]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet6/nd6.c
add -n option to suppress clearing the build tree and add -DNO_CLEAN
[FreeBSD/FreeBSD.git] / sys / netinet6 / nd6.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.c,v 1.144 2001/05/24 07:44:00 itojun Exp $
30  */
31
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34
35 #include "opt_inet.h"
36 #include "opt_inet6.h"
37 #include "opt_mac.h"
38
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/callout.h>
42 #include <sys/malloc.h>
43 #include <sys/mbuf.h>
44 #include <sys/socket.h>
45 #include <sys/sockio.h>
46 #include <sys/time.h>
47 #include <sys/kernel.h>
48 #include <sys/protosw.h>
49 #include <sys/errno.h>
50 #include <sys/syslog.h>
51 #include <sys/queue.h>
52 #include <sys/sysctl.h>
53
54 #include <net/if.h>
55 #include <net/if_arc.h>
56 #include <net/if_dl.h>
57 #include <net/if_types.h>
58 #include <net/iso88025.h>
59 #include <net/fddi.h>
60 #include <net/route.h>
61
62 #include <netinet/in.h>
63 #include <netinet/if_ether.h>
64 #include <netinet6/in6_var.h>
65 #include <netinet/ip6.h>
66 #include <netinet6/ip6_var.h>
67 #include <netinet6/scope6_var.h>
68 #include <netinet6/nd6.h>
69 #include <netinet/icmp6.h>
70
71 #include <sys/limits.h>
72 #include <sys/vimage.h>
73
74 #include <security/mac/mac_framework.h>
75
76 #define ND6_SLOWTIMER_INTERVAL (60 * 60) /* 1 hour */
77 #define ND6_RECALC_REACHTM_INTERVAL (60 * 120) /* 2 hours */
78
79 #define SIN6(s) ((struct sockaddr_in6 *)s)
80 #define SDL(s) ((struct sockaddr_dl *)s)
81
82 /* timer values */
83 int     nd6_prune       = 1;    /* walk list every 1 seconds */
84 int     nd6_delay       = 5;    /* delay first probe time 5 second */
85 int     nd6_umaxtries   = 3;    /* maximum unicast query */
86 int     nd6_mmaxtries   = 3;    /* maximum multicast query */
87 int     nd6_useloopback = 1;    /* use loopback interface for local traffic */
88 int     nd6_gctimer     = (60 * 60 * 24); /* 1 day: garbage collection timer */
89
90 /* preventing too many loops in ND option parsing */
91 int nd6_maxndopt = 10;  /* max # of ND options allowed */
92
93 int nd6_maxnudhint = 0; /* max # of subsequent upper layer hints */
94 int nd6_maxqueuelen = 1; /* max # of packets cached in unresolved ND entries */
95
96 #ifdef ND6_DEBUG
97 int nd6_debug = 1;
98 #else
99 int nd6_debug = 0;
100 #endif
101
102 /* for debugging? */
103 static int nd6_inuse, nd6_allocated;
104
105 struct llinfo_nd6 llinfo_nd6 = {&llinfo_nd6, &llinfo_nd6};
106 struct nd_drhead nd_defrouter;
107 struct nd_prhead nd_prefix = { 0 };
108
109 int nd6_recalc_reachtm_interval = ND6_RECALC_REACHTM_INTERVAL;
110 static struct sockaddr_in6 all1_sa;
111
112 static int nd6_is_new_addr_neighbor __P((struct sockaddr_in6 *,
113         struct ifnet *));
114 static void nd6_setmtu0(struct ifnet *, struct nd_ifinfo *);
115 static void nd6_slowtimo(void *);
116 static int regen_tmpaddr(struct in6_ifaddr *);
117 static struct llinfo_nd6 *nd6_free(struct rtentry *, int);
118 static void nd6_llinfo_timer(void *);
119 static void clear_llinfo_pqueue(struct llinfo_nd6 *);
120
121 struct callout nd6_slowtimo_ch;
122 struct callout nd6_timer_ch;
123 extern struct callout in6_tmpaddrtimer_ch;
124
125 void
126 nd6_init(void)
127 {
128         INIT_VNET_INET6(curvnet);
129         static int nd6_init_done = 0;
130         int i;
131
132         if (nd6_init_done) {
133                 log(LOG_NOTICE, "nd6_init called more than once(ignored)\n");
134                 return;
135         }
136
137         all1_sa.sin6_family = AF_INET6;
138         all1_sa.sin6_len = sizeof(struct sockaddr_in6);
139         for (i = 0; i < sizeof(all1_sa.sin6_addr); i++)
140                 all1_sa.sin6_addr.s6_addr[i] = 0xff;
141
142         /* initialization of the default router list */
143         TAILQ_INIT(&V_nd_defrouter);
144         /* start timer */
145         callout_init(&V_nd6_slowtimo_ch, 0);
146         callout_reset(&V_nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL * hz,
147             nd6_slowtimo, NULL);
148
149         nd6_init_done = 1;
150
151 }
152
153 struct nd_ifinfo *
154 nd6_ifattach(struct ifnet *ifp)
155 {
156         struct nd_ifinfo *nd;
157
158         nd = (struct nd_ifinfo *)malloc(sizeof(*nd), M_IP6NDP, M_WAITOK);
159         bzero(nd, sizeof(*nd));
160
161         nd->initialized = 1;
162
163         nd->chlim = IPV6_DEFHLIM;
164         nd->basereachable = REACHABLE_TIME;
165         nd->reachable = ND_COMPUTE_RTIME(nd->basereachable);
166         nd->retrans = RETRANS_TIMER;
167         /*
168          * Note that the default value of ip6_accept_rtadv is 0, which means
169          * we won't accept RAs by default even if we set ND6_IFF_ACCEPT_RTADV
170          * here.
171          */
172         nd->flags = (ND6_IFF_PERFORMNUD | ND6_IFF_ACCEPT_RTADV);
173
174         /* XXX: we cannot call nd6_setmtu since ifp is not fully initialized */
175         nd6_setmtu0(ifp, nd);
176
177         return nd;
178 }
179
180 void
181 nd6_ifdetach(struct nd_ifinfo *nd)
182 {
183
184         free(nd, M_IP6NDP);
185 }
186
187 /*
188  * Reset ND level link MTU. This function is called when the physical MTU
189  * changes, which means we might have to adjust the ND level MTU.
190  */
191 void
192 nd6_setmtu(struct ifnet *ifp)
193 {
194
195         nd6_setmtu0(ifp, ND_IFINFO(ifp));
196 }
197
198 /* XXX todo: do not maintain copy of ifp->if_mtu in ndi->maxmtu */
199 void
200 nd6_setmtu0(struct ifnet *ifp, struct nd_ifinfo *ndi)
201 {
202         INIT_VNET_INET6(ifp->if_vnet);
203         u_int32_t omaxmtu;
204
205         omaxmtu = ndi->maxmtu;
206
207         switch (ifp->if_type) {
208         case IFT_ARCNET:
209                 ndi->maxmtu = MIN(ARC_PHDS_MAXMTU, ifp->if_mtu); /* RFC2497 */
210                 break;
211         case IFT_FDDI:
212                 ndi->maxmtu = MIN(FDDIIPMTU, ifp->if_mtu); /* RFC2467 */
213                 break;
214         case IFT_ISO88025:
215                  ndi->maxmtu = MIN(ISO88025_MAX_MTU, ifp->if_mtu);
216                  break;
217         default:
218                 ndi->maxmtu = ifp->if_mtu;
219                 break;
220         }
221
222         /*
223          * Decreasing the interface MTU under IPV6 minimum MTU may cause
224          * undesirable situation.  We thus notify the operator of the change
225          * explicitly.  The check for omaxmtu is necessary to restrict the
226          * log to the case of changing the MTU, not initializing it.
227          */
228         if (omaxmtu >= IPV6_MMTU && ndi->maxmtu < IPV6_MMTU) {
229                 log(LOG_NOTICE, "nd6_setmtu0: "
230                     "new link MTU on %s (%lu) is too small for IPv6\n",
231                     if_name(ifp), (unsigned long)ndi->maxmtu);
232         }
233
234         if (ndi->maxmtu > V_in6_maxmtu)
235                 in6_setmaxmtu(); /* check all interfaces just in case */
236
237 #undef MIN
238 }
239
240 void
241 nd6_option_init(void *opt, int icmp6len, union nd_opts *ndopts)
242 {
243
244         bzero(ndopts, sizeof(*ndopts));
245         ndopts->nd_opts_search = (struct nd_opt_hdr *)opt;
246         ndopts->nd_opts_last
247                 = (struct nd_opt_hdr *)(((u_char *)opt) + icmp6len);
248
249         if (icmp6len == 0) {
250                 ndopts->nd_opts_done = 1;
251                 ndopts->nd_opts_search = NULL;
252         }
253 }
254
255 /*
256  * Take one ND option.
257  */
258 struct nd_opt_hdr *
259 nd6_option(union nd_opts *ndopts)
260 {
261         struct nd_opt_hdr *nd_opt;
262         int olen;
263
264         if (ndopts == NULL)
265                 panic("ndopts == NULL in nd6_option");
266         if (ndopts->nd_opts_last == NULL)
267                 panic("uninitialized ndopts in nd6_option");
268         if (ndopts->nd_opts_search == NULL)
269                 return NULL;
270         if (ndopts->nd_opts_done)
271                 return NULL;
272
273         nd_opt = ndopts->nd_opts_search;
274
275         /* make sure nd_opt_len is inside the buffer */
276         if ((caddr_t)&nd_opt->nd_opt_len >= (caddr_t)ndopts->nd_opts_last) {
277                 bzero(ndopts, sizeof(*ndopts));
278                 return NULL;
279         }
280
281         olen = nd_opt->nd_opt_len << 3;
282         if (olen == 0) {
283                 /*
284                  * Message validation requires that all included
285                  * options have a length that is greater than zero.
286                  */
287                 bzero(ndopts, sizeof(*ndopts));
288                 return NULL;
289         }
290
291         ndopts->nd_opts_search = (struct nd_opt_hdr *)((caddr_t)nd_opt + olen);
292         if (ndopts->nd_opts_search > ndopts->nd_opts_last) {
293                 /* option overruns the end of buffer, invalid */
294                 bzero(ndopts, sizeof(*ndopts));
295                 return NULL;
296         } else if (ndopts->nd_opts_search == ndopts->nd_opts_last) {
297                 /* reached the end of options chain */
298                 ndopts->nd_opts_done = 1;
299                 ndopts->nd_opts_search = NULL;
300         }
301         return nd_opt;
302 }
303
304 /*
305  * Parse multiple ND options.
306  * This function is much easier to use, for ND routines that do not need
307  * multiple options of the same type.
308  */
309 int
310 nd6_options(union nd_opts *ndopts)
311 {
312         INIT_VNET_INET6(curvnet);
313         struct nd_opt_hdr *nd_opt;
314         int i = 0;
315
316         if (ndopts == NULL)
317                 panic("ndopts == NULL in nd6_options");
318         if (ndopts->nd_opts_last == NULL)
319                 panic("uninitialized ndopts in nd6_options");
320         if (ndopts->nd_opts_search == NULL)
321                 return 0;
322
323         while (1) {
324                 nd_opt = nd6_option(ndopts);
325                 if (nd_opt == NULL && ndopts->nd_opts_last == NULL) {
326                         /*
327                          * Message validation requires that all included
328                          * options have a length that is greater than zero.
329                          */
330                         V_icmp6stat.icp6s_nd_badopt++;
331                         bzero(ndopts, sizeof(*ndopts));
332                         return -1;
333                 }
334
335                 if (nd_opt == NULL)
336                         goto skip1;
337
338                 switch (nd_opt->nd_opt_type) {
339                 case ND_OPT_SOURCE_LINKADDR:
340                 case ND_OPT_TARGET_LINKADDR:
341                 case ND_OPT_MTU:
342                 case ND_OPT_REDIRECTED_HEADER:
343                         if (ndopts->nd_opt_array[nd_opt->nd_opt_type]) {
344                                 nd6log((LOG_INFO,
345                                     "duplicated ND6 option found (type=%d)\n",
346                                     nd_opt->nd_opt_type));
347                                 /* XXX bark? */
348                         } else {
349                                 ndopts->nd_opt_array[nd_opt->nd_opt_type]
350                                         = nd_opt;
351                         }
352                         break;
353                 case ND_OPT_PREFIX_INFORMATION:
354                         if (ndopts->nd_opt_array[nd_opt->nd_opt_type] == 0) {
355                                 ndopts->nd_opt_array[nd_opt->nd_opt_type]
356                                         = nd_opt;
357                         }
358                         ndopts->nd_opts_pi_end =
359                                 (struct nd_opt_prefix_info *)nd_opt;
360                         break;
361                 default:
362                         /*
363                          * Unknown options must be silently ignored,
364                          * to accomodate future extension to the protocol.
365                          */
366                         nd6log((LOG_DEBUG,
367                             "nd6_options: unsupported option %d - "
368                             "option ignored\n", nd_opt->nd_opt_type));
369                 }
370
371 skip1:
372                 i++;
373                 if (i > V_nd6_maxndopt) {
374                         V_icmp6stat.icp6s_nd_toomanyopt++;
375                         nd6log((LOG_INFO, "too many loop in nd opt\n"));
376                         break;
377                 }
378
379                 if (ndopts->nd_opts_done)
380                         break;
381         }
382
383         return 0;
384 }
385
386 /*
387  * ND6 timer routine to handle ND6 entries
388  */
389 void
390 nd6_llinfo_settimer(struct llinfo_nd6 *ln, long tick)
391 {
392         if (tick < 0) {
393                 ln->ln_expire = 0;
394                 ln->ln_ntick = 0;
395                 callout_stop(&ln->ln_timer_ch);
396         } else {
397                 ln->ln_expire = time_second + tick / hz;
398                 if (tick > INT_MAX) {
399                         ln->ln_ntick = tick - INT_MAX;
400                         callout_reset(&ln->ln_timer_ch, INT_MAX,
401                             nd6_llinfo_timer, ln);
402                 } else {
403                         ln->ln_ntick = 0;
404                         callout_reset(&ln->ln_timer_ch, tick,
405                             nd6_llinfo_timer, ln);
406                 }
407         }
408 }
409
410 static void
411 nd6_llinfo_timer(void *arg)
412 {
413         struct llinfo_nd6 *ln;
414         struct rtentry *rt;
415         struct in6_addr *dst;
416         struct ifnet *ifp;
417         struct nd_ifinfo *ndi = NULL;
418
419         ln = (struct llinfo_nd6 *)arg;
420
421         if (ln->ln_ntick > 0) {
422                 if (ln->ln_ntick > INT_MAX) {
423                         ln->ln_ntick -= INT_MAX;
424                         nd6_llinfo_settimer(ln, INT_MAX);
425                 } else {
426                         ln->ln_ntick = 0;
427                         nd6_llinfo_settimer(ln, ln->ln_ntick);
428                 }
429                 return;
430         }
431
432         if ((rt = ln->ln_rt) == NULL)
433                 panic("ln->ln_rt == NULL");
434         if ((ifp = rt->rt_ifp) == NULL)
435                 panic("ln->ln_rt->rt_ifp == NULL");
436         ndi = ND_IFINFO(ifp);
437
438         CURVNET_SET(ifp->if_vnet);
439         INIT_VNET_INET6(curvnet);
440
441         /* sanity check */
442         if (rt->rt_llinfo && (struct llinfo_nd6 *)rt->rt_llinfo != ln)
443                 panic("rt_llinfo(%p) is not equal to ln(%p)",
444                       rt->rt_llinfo, ln);
445         if (rt_key(rt) == NULL)
446                 panic("rt key is NULL in nd6_timer(ln=%p)", ln);
447
448         dst = &((struct sockaddr_in6 *)rt_key(rt))->sin6_addr;
449
450         switch (ln->ln_state) {
451         case ND6_LLINFO_INCOMPLETE:
452                 if (ln->ln_asked < V_nd6_mmaxtries) {
453                         ln->ln_asked++;
454                         nd6_llinfo_settimer(ln, (long)ndi->retrans * hz / 1000);
455                         nd6_ns_output(ifp, NULL, dst, ln, 0);
456                 } else {
457                         struct mbuf *m = ln->ln_hold;
458                         if (m) {
459                                 struct mbuf *m0;
460
461                                 /*
462                                  * assuming every packet in ln_hold has the
463                                  * same IP header
464                                  */
465                                 m0 = m->m_nextpkt;
466                                 m->m_nextpkt = NULL;
467                                 icmp6_error2(m, ICMP6_DST_UNREACH,
468                                     ICMP6_DST_UNREACH_ADDR, 0, rt->rt_ifp);
469
470                                 ln->ln_hold = m0;
471                                 clear_llinfo_pqueue(ln);
472                         }
473                         if (rt && rt->rt_llinfo)
474                                 (void)nd6_free(rt, 0);
475                         ln = NULL;
476                 }
477                 break;
478         case ND6_LLINFO_REACHABLE:
479                 if (!ND6_LLINFO_PERMANENT(ln)) {
480                         ln->ln_state = ND6_LLINFO_STALE;
481                         nd6_llinfo_settimer(ln, (long)V_nd6_gctimer * hz);
482                 }
483                 break;
484
485         case ND6_LLINFO_STALE:
486                 /* Garbage Collection(RFC 2461 5.3) */
487                 if (!ND6_LLINFO_PERMANENT(ln)) {
488                         if (rt && rt->rt_llinfo)
489                                 (void)nd6_free(rt, 1);
490                         ln = NULL;
491                 }
492                 break;
493
494         case ND6_LLINFO_DELAY:
495                 if (ndi && (ndi->flags & ND6_IFF_PERFORMNUD) != 0) {
496                         /* We need NUD */
497                         ln->ln_asked = 1;
498                         ln->ln_state = ND6_LLINFO_PROBE;
499                         nd6_llinfo_settimer(ln, (long)ndi->retrans * hz / 1000);
500                         nd6_ns_output(ifp, dst, dst, ln, 0);
501                 } else {
502                         ln->ln_state = ND6_LLINFO_STALE; /* XXX */
503                         nd6_llinfo_settimer(ln, (long)V_nd6_gctimer * hz);
504                 }
505                 break;
506         case ND6_LLINFO_PROBE:
507                 if (ln->ln_asked < V_nd6_umaxtries) {
508                         ln->ln_asked++;
509                         nd6_llinfo_settimer(ln, (long)ndi->retrans * hz / 1000);
510                         nd6_ns_output(ifp, dst, dst, ln, 0);
511                 } else if (rt->rt_ifa != NULL &&
512                     rt->rt_ifa->ifa_addr->sa_family == AF_INET6 &&
513                     (((struct in6_ifaddr *)rt->rt_ifa)->ia_flags & IFA_ROUTE)) {
514                         /*
515                          * This is an unreachable neighbor whose address is
516                          * specified as the destination of a p2p interface
517                          * (see in6_ifinit()).  We should not free the entry
518                          * since this is sort of a "static" entry generated
519                          * via interface address configuration.
520                          */
521                         ln->ln_asked = 0;
522                         ln->ln_expire = 0; /* make it permanent */
523                         ln->ln_state = ND6_LLINFO_STALE;
524                 } else {
525                         if (rt && rt->rt_llinfo)
526                                 (void)nd6_free(rt, 0);
527                         ln = NULL;
528                 }
529                 break;
530         }
531         CURVNET_RESTORE();
532 }
533
534
535 /*
536  * ND6 timer routine to expire default route list and prefix list
537  */
538 void
539 nd6_timer(void *arg)
540 {
541         CURVNET_SET_QUIET((struct vnet *) arg);
542         INIT_VNET_INET6((struct vnet *) arg);
543         int s;
544         struct nd_defrouter *dr;
545         struct nd_prefix *pr;
546         struct in6_ifaddr *ia6, *nia6;
547         struct in6_addrlifetime *lt6;
548
549         callout_reset(&V_nd6_timer_ch, V_nd6_prune * hz,
550             nd6_timer, NULL);
551
552         /* expire default router list */
553         s = splnet();
554         dr = TAILQ_FIRST(&V_nd_defrouter);
555         while (dr) {
556                 if (dr->expire && dr->expire < time_second) {
557                         struct nd_defrouter *t;
558                         t = TAILQ_NEXT(dr, dr_entry);
559                         defrtrlist_del(dr);
560                         dr = t;
561                 } else {
562                         dr = TAILQ_NEXT(dr, dr_entry);
563                 }
564         }
565
566         /*
567          * expire interface addresses.
568          * in the past the loop was inside prefix expiry processing.
569          * However, from a stricter speci-confrmance standpoint, we should
570          * rather separate address lifetimes and prefix lifetimes.
571          */
572   addrloop:
573         for (ia6 = V_in6_ifaddr; ia6; ia6 = nia6) {
574                 nia6 = ia6->ia_next;
575                 /* check address lifetime */
576                 lt6 = &ia6->ia6_lifetime;
577                 if (IFA6_IS_INVALID(ia6)) {
578                         int regen = 0;
579
580                         /*
581                          * If the expiring address is temporary, try
582                          * regenerating a new one.  This would be useful when
583                          * we suspended a laptop PC, then turned it on after a
584                          * period that could invalidate all temporary
585                          * addresses.  Although we may have to restart the
586                          * loop (see below), it must be after purging the
587                          * address.  Otherwise, we'd see an infinite loop of
588                          * regeneration.
589                          */
590                         if (V_ip6_use_tempaddr &&
591                             (ia6->ia6_flags & IN6_IFF_TEMPORARY) != 0) {
592                                 if (regen_tmpaddr(ia6) == 0)
593                                         regen = 1;
594                         }
595
596                         in6_purgeaddr(&ia6->ia_ifa);
597
598                         if (regen)
599                                 goto addrloop; /* XXX: see below */
600                 } else if (IFA6_IS_DEPRECATED(ia6)) {
601                         int oldflags = ia6->ia6_flags;
602
603                         ia6->ia6_flags |= IN6_IFF_DEPRECATED;
604
605                         /*
606                          * If a temporary address has just become deprecated,
607                          * regenerate a new one if possible.
608                          */
609                         if (V_ip6_use_tempaddr &&
610                             (ia6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
611                             (oldflags & IN6_IFF_DEPRECATED) == 0) {
612
613                                 if (regen_tmpaddr(ia6) == 0) {
614                                         /*
615                                          * A new temporary address is
616                                          * generated.
617                                          * XXX: this means the address chain
618                                          * has changed while we are still in
619                                          * the loop.  Although the change
620                                          * would not cause disaster (because
621                                          * it's not a deletion, but an
622                                          * addition,) we'd rather restart the
623                                          * loop just for safety.  Or does this
624                                          * significantly reduce performance??
625                                          */
626                                         goto addrloop;
627                                 }
628                         }
629                 } else {
630                         /*
631                          * A new RA might have made a deprecated address
632                          * preferred.
633                          */
634                         ia6->ia6_flags &= ~IN6_IFF_DEPRECATED;
635                 }
636         }
637
638         /* expire prefix list */
639         pr = V_nd_prefix.lh_first;
640         while (pr) {
641                 /*
642                  * check prefix lifetime.
643                  * since pltime is just for autoconf, pltime processing for
644                  * prefix is not necessary.
645                  */
646                 if (pr->ndpr_vltime != ND6_INFINITE_LIFETIME &&
647                     time_second - pr->ndpr_lastupdate > pr->ndpr_vltime) {
648                         struct nd_prefix *t;
649                         t = pr->ndpr_next;
650
651                         /*
652                          * address expiration and prefix expiration are
653                          * separate.  NEVER perform in6_purgeaddr here.
654                          */
655
656                         prelist_remove(pr);
657                         pr = t;
658                 } else
659                         pr = pr->ndpr_next;
660         }
661         splx(s);
662         CURVNET_RESTORE();
663 }
664
665 /*
666  * ia6 - deprecated/invalidated temporary address
667  */
668 static int
669 regen_tmpaddr(struct in6_ifaddr *ia6)
670 {
671         struct ifaddr *ifa;
672         struct ifnet *ifp;
673         struct in6_ifaddr *public_ifa6 = NULL;
674
675         ifp = ia6->ia_ifa.ifa_ifp;
676         for (ifa = ifp->if_addrlist.tqh_first; ifa;
677              ifa = ifa->ifa_list.tqe_next) {
678                 struct in6_ifaddr *it6;
679
680                 if (ifa->ifa_addr->sa_family != AF_INET6)
681                         continue;
682
683                 it6 = (struct in6_ifaddr *)ifa;
684
685                 /* ignore no autoconf addresses. */
686                 if ((it6->ia6_flags & IN6_IFF_AUTOCONF) == 0)
687                         continue;
688
689                 /* ignore autoconf addresses with different prefixes. */
690                 if (it6->ia6_ndpr == NULL || it6->ia6_ndpr != ia6->ia6_ndpr)
691                         continue;
692
693                 /*
694                  * Now we are looking at an autoconf address with the same
695                  * prefix as ours.  If the address is temporary and is still
696                  * preferred, do not create another one.  It would be rare, but
697                  * could happen, for example, when we resume a laptop PC after
698                  * a long period.
699                  */
700                 if ((it6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
701                     !IFA6_IS_DEPRECATED(it6)) {
702                         public_ifa6 = NULL;
703                         break;
704                 }
705
706                 /*
707                  * This is a public autoconf address that has the same prefix
708                  * as ours.  If it is preferred, keep it.  We can't break the
709                  * loop here, because there may be a still-preferred temporary
710                  * address with the prefix.
711                  */
712                 if (!IFA6_IS_DEPRECATED(it6))
713                     public_ifa6 = it6;
714         }
715
716         if (public_ifa6 != NULL) {
717                 int e;
718
719                 if ((e = in6_tmpifadd(public_ifa6, 0, 0)) != 0) {
720                         log(LOG_NOTICE, "regen_tmpaddr: failed to create a new"
721                             " tmp addr,errno=%d\n", e);
722                         return (-1);
723                 }
724                 return (0);
725         }
726
727         return (-1);
728 }
729
730 /*
731  * Nuke neighbor cache/prefix/default router management table, right before
732  * ifp goes away.
733  */
734 void
735 nd6_purge(struct ifnet *ifp)
736 {
737         INIT_VNET_INET6(ifp->if_vnet);
738         struct llinfo_nd6 *ln, *nln;
739         struct nd_defrouter *dr, *ndr;
740         struct nd_prefix *pr, *npr;
741
742         /*
743          * Nuke default router list entries toward ifp.
744          * We defer removal of default router list entries that is installed
745          * in the routing table, in order to keep additional side effects as
746          * small as possible.
747          */
748         for (dr = TAILQ_FIRST(&V_nd_defrouter); dr; dr = ndr) {
749                 ndr = TAILQ_NEXT(dr, dr_entry);
750                 if (dr->installed)
751                         continue;
752
753                 if (dr->ifp == ifp)
754                         defrtrlist_del(dr);
755         }
756
757         for (dr = TAILQ_FIRST(&V_nd_defrouter); dr; dr = ndr) {
758                 ndr = TAILQ_NEXT(dr, dr_entry);
759                 if (!dr->installed)
760                         continue;
761
762                 if (dr->ifp == ifp)
763                         defrtrlist_del(dr);
764         }
765
766         /* Nuke prefix list entries toward ifp */
767         for (pr = V_nd_prefix.lh_first; pr; pr = npr) {
768                 npr = pr->ndpr_next;
769                 if (pr->ndpr_ifp == ifp) {
770                         /*
771                          * Because if_detach() does *not* release prefixes
772                          * while purging addresses the reference count will
773                          * still be above zero. We therefore reset it to
774                          * make sure that the prefix really gets purged.
775                          */
776                         pr->ndpr_refcnt = 0;
777
778                         /*
779                          * Previously, pr->ndpr_addr is removed as well,
780                          * but I strongly believe we don't have to do it.
781                          * nd6_purge() is only called from in6_ifdetach(),
782                          * which removes all the associated interface addresses
783                          * by itself.
784                          * (jinmei@kame.net 20010129)
785                          */
786                         prelist_remove(pr);
787                 }
788         }
789
790         /* cancel default outgoing interface setting */
791         if (V_nd6_defifindex == ifp->if_index)
792                 nd6_setdefaultiface(0);
793
794         if (!V_ip6_forwarding && V_ip6_accept_rtadv) { /* XXX: too restrictive? */
795                 /* refresh default router list */
796                 defrouter_select();
797         }
798
799         /*
800          * Nuke neighbor cache entries for the ifp.
801          * Note that rt->rt_ifp may not be the same as ifp,
802          * due to KAME goto ours hack.  See RTM_RESOLVE case in
803          * nd6_rtrequest(), and ip6_input().
804          */
805         ln = V_llinfo_nd6.ln_next;
806         while (ln && ln != &V_llinfo_nd6) {
807                 struct rtentry *rt;
808                 struct sockaddr_dl *sdl;
809
810                 nln = ln->ln_next;
811                 rt = ln->ln_rt;
812                 if (rt && rt->rt_gateway &&
813                     rt->rt_gateway->sa_family == AF_LINK) {
814                         sdl = (struct sockaddr_dl *)rt->rt_gateway;
815                         if (sdl->sdl_index == ifp->if_index)
816                                 nln = nd6_free(rt, 0);
817                 }
818                 ln = nln;
819         }
820 }
821
822 struct rtentry *
823 nd6_lookup(struct in6_addr *addr6, int create, struct ifnet *ifp)
824 {
825         INIT_VNET_INET6(curvnet);
826         struct rtentry *rt;
827         struct sockaddr_in6 sin6;
828         char ip6buf[INET6_ADDRSTRLEN];
829
830         bzero(&sin6, sizeof(sin6));
831         sin6.sin6_len = sizeof(struct sockaddr_in6);
832         sin6.sin6_family = AF_INET6;
833         sin6.sin6_addr = *addr6;
834         rt = rtalloc1((struct sockaddr *)&sin6, create, 0UL);
835         if (rt) {
836                 if ((rt->rt_flags & RTF_LLINFO) == 0 && create) {
837                         /*
838                          * This is the case for the default route.
839                          * If we want to create a neighbor cache for the
840                          * address, we should free the route for the
841                          * destination and allocate an interface route.
842                          */
843                         RTFREE_LOCKED(rt);
844                         rt = NULL;
845                 }
846         }
847         if (rt == NULL) {
848                 if (create && ifp) {
849                         int e;
850
851                         /*
852                          * If no route is available and create is set,
853                          * we allocate a host route for the destination
854                          * and treat it like an interface route.
855                          * This hack is necessary for a neighbor which can't
856                          * be covered by our own prefix.
857                          */
858                         struct ifaddr *ifa =
859                             ifaof_ifpforaddr((struct sockaddr *)&sin6, ifp);
860                         if (ifa == NULL)
861                                 return (NULL);
862
863                         /*
864                          * Create a new route.  RTF_LLINFO is necessary
865                          * to create a Neighbor Cache entry for the
866                          * destination in nd6_rtrequest which will be
867                          * called in rtrequest via ifa->ifa_rtrequest.
868                          */
869                         if ((e = rtrequest(RTM_ADD, (struct sockaddr *)&sin6,
870                             ifa->ifa_addr, (struct sockaddr *)&all1_sa,
871                             (ifa->ifa_flags | RTF_HOST | RTF_LLINFO) &
872                             ~RTF_CLONING, &rt)) != 0) {
873                                 log(LOG_ERR,
874                                     "nd6_lookup: failed to add route for a "
875                                     "neighbor(%s), errno=%d\n",
876                                     ip6_sprintf(ip6buf, addr6), e);
877                         }
878                         if (rt == NULL)
879                                 return (NULL);
880                         RT_LOCK(rt);
881                         if (rt->rt_llinfo) {
882                                 struct llinfo_nd6 *ln =
883                                     (struct llinfo_nd6 *)rt->rt_llinfo;
884                                 ln->ln_state = ND6_LLINFO_NOSTATE;
885                         }
886                 } else
887                         return (NULL);
888         }
889         RT_LOCK_ASSERT(rt);
890         RT_REMREF(rt);
891         /*
892          * Validation for the entry.
893          * Note that the check for rt_llinfo is necessary because a cloned
894          * route from a parent route that has the L flag (e.g. the default
895          * route to a p2p interface) may have the flag, too, while the
896          * destination is not actually a neighbor.
897          * XXX: we can't use rt->rt_ifp to check for the interface, since
898          *      it might be the loopback interface if the entry is for our
899          *      own address on a non-loopback interface. Instead, we should
900          *      use rt->rt_ifa->ifa_ifp, which would specify the REAL
901          *      interface.
902          * Note also that ifa_ifp and ifp may differ when we connect two
903          * interfaces to a same link, install a link prefix to an interface,
904          * and try to install a neighbor cache on an interface that does not
905          * have a route to the prefix.
906          */
907         if ((rt->rt_flags & RTF_GATEWAY) || (rt->rt_flags & RTF_LLINFO) == 0 ||
908             rt->rt_gateway->sa_family != AF_LINK || rt->rt_llinfo == NULL ||
909             (ifp && rt->rt_ifa->ifa_ifp != ifp)) {
910                 if (create) {
911                         nd6log((LOG_DEBUG,
912                             "nd6_lookup: failed to lookup %s (if = %s)\n",
913                             ip6_sprintf(ip6buf, addr6),
914                             ifp ? if_name(ifp) : "unspec"));
915                 }
916                 RT_UNLOCK(rt);
917                 return (NULL);
918         }
919         RT_UNLOCK(rt);          /* XXX not ready to return rt locked */
920         return (rt);
921 }
922
923 /*
924  * Test whether a given IPv6 address is a neighbor or not, ignoring
925  * the actual neighbor cache.  The neighbor cache is ignored in order
926  * to not reenter the routing code from within itself.
927  */
928 static int
929 nd6_is_new_addr_neighbor(struct sockaddr_in6 *addr, struct ifnet *ifp)
930 {
931         INIT_VNET_INET6(ifp->if_vnet);
932         struct nd_prefix *pr;
933         struct ifaddr *dstaddr;
934
935         /*
936          * A link-local address is always a neighbor.
937          * XXX: a link does not necessarily specify a single interface.
938          */
939         if (IN6_IS_ADDR_LINKLOCAL(&addr->sin6_addr)) {
940                 struct sockaddr_in6 sin6_copy;
941                 u_int32_t zone;
942
943                 /*
944                  * We need sin6_copy since sa6_recoverscope() may modify the
945                  * content (XXX).
946                  */
947                 sin6_copy = *addr;
948                 if (sa6_recoverscope(&sin6_copy))
949                         return (0); /* XXX: should be impossible */
950                 if (in6_setscope(&sin6_copy.sin6_addr, ifp, &zone))
951                         return (0);
952                 if (sin6_copy.sin6_scope_id == zone)
953                         return (1);
954                 else
955                         return (0);
956         }
957
958         /*
959          * If the address matches one of our addresses,
960          * it should be a neighbor.
961          * If the address matches one of our on-link prefixes, it should be a
962          * neighbor.
963          */
964         for (pr = V_nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
965                 if (pr->ndpr_ifp != ifp)
966                         continue;
967
968                 if (!(pr->ndpr_stateflags & NDPRF_ONLINK))
969                         continue;
970
971                 if (IN6_ARE_MASKED_ADDR_EQUAL(&pr->ndpr_prefix.sin6_addr,
972                     &addr->sin6_addr, &pr->ndpr_mask))
973                         return (1);
974         }
975
976         /*
977          * If the address is assigned on the node of the other side of
978          * a p2p interface, the address should be a neighbor.
979          */
980         dstaddr = ifa_ifwithdstaddr((struct sockaddr *)addr);
981         if ((dstaddr != NULL) && (dstaddr->ifa_ifp == ifp))
982                 return (1);
983
984         /*
985          * If the default router list is empty, all addresses are regarded
986          * as on-link, and thus, as a neighbor.
987          * XXX: we restrict the condition to hosts, because routers usually do
988          * not have the "default router list".
989          */
990         if (!V_ip6_forwarding && TAILQ_FIRST(&V_nd_defrouter) == NULL &&
991             V_nd6_defifindex == ifp->if_index) {
992                 return (1);
993         }
994
995         return (0);
996 }
997
998
999 /*
1000  * Detect if a given IPv6 address identifies a neighbor on a given link.
1001  * XXX: should take care of the destination of a p2p link?
1002  */
1003 int
1004 nd6_is_addr_neighbor(struct sockaddr_in6 *addr, struct ifnet *ifp)
1005 {
1006
1007         if (nd6_is_new_addr_neighbor(addr, ifp))
1008                 return (1);
1009
1010         /*
1011          * Even if the address matches none of our addresses, it might be
1012          * in the neighbor cache.
1013          */
1014         if (nd6_lookup(&addr->sin6_addr, 0, ifp) != NULL)
1015                 return (1);
1016
1017         return (0);
1018 }
1019
1020 /*
1021  * Free an nd6 llinfo entry.
1022  * Since the function would cause significant changes in the kernel, DO NOT
1023  * make it global, unless you have a strong reason for the change, and are sure
1024  * that the change is safe.
1025  */
1026 static struct llinfo_nd6 *
1027 nd6_free(struct rtentry *rt, int gc)
1028 {
1029         INIT_VNET_INET6(curvnet);
1030         struct llinfo_nd6 *ln = (struct llinfo_nd6 *)rt->rt_llinfo, *next;
1031         struct in6_addr in6 = ((struct sockaddr_in6 *)rt_key(rt))->sin6_addr;
1032         struct nd_defrouter *dr;
1033
1034         /*
1035          * we used to have pfctlinput(PRC_HOSTDEAD) here.
1036          * even though it is not harmful, it was not really necessary.
1037          */
1038
1039         /* cancel timer */
1040         nd6_llinfo_settimer(ln, -1);
1041
1042         if (!V_ip6_forwarding) {
1043                 int s;
1044                 s = splnet();
1045                 dr = defrouter_lookup(&((struct sockaddr_in6 *)rt_key(rt))->sin6_addr,
1046                     rt->rt_ifp);
1047
1048                 if (dr != NULL && dr->expire &&
1049                     ln->ln_state == ND6_LLINFO_STALE && gc) {
1050                         /*
1051                          * If the reason for the deletion is just garbage
1052                          * collection, and the neighbor is an active default
1053                          * router, do not delete it.  Instead, reset the GC
1054                          * timer using the router's lifetime.
1055                          * Simply deleting the entry would affect default
1056                          * router selection, which is not necessarily a good
1057                          * thing, especially when we're using router preference
1058                          * values.
1059                          * XXX: the check for ln_state would be redundant,
1060                          *      but we intentionally keep it just in case.
1061                          */
1062                         if (dr->expire > time_second)
1063                                 nd6_llinfo_settimer(ln,
1064                                     (dr->expire - time_second) * hz);
1065                         else
1066                                 nd6_llinfo_settimer(ln, (long)V_nd6_gctimer * hz);
1067                         splx(s);
1068                         return (ln->ln_next);
1069                 }
1070
1071                 if (ln->ln_router || dr) {
1072                         /*
1073                          * rt6_flush must be called whether or not the neighbor
1074                          * is in the Default Router List.
1075                          * See a corresponding comment in nd6_na_input().
1076                          */
1077                         rt6_flush(&in6, rt->rt_ifp);
1078                 }
1079
1080                 if (dr) {
1081                         /*
1082                          * Unreachablity of a router might affect the default
1083                          * router selection and on-link detection of advertised
1084                          * prefixes.
1085                          */
1086
1087                         /*
1088                          * Temporarily fake the state to choose a new default
1089                          * router and to perform on-link determination of
1090                          * prefixes correctly.
1091                          * Below the state will be set correctly,
1092                          * or the entry itself will be deleted.
1093                          */
1094                         ln->ln_state = ND6_LLINFO_INCOMPLETE;
1095
1096                         /*
1097                          * Since defrouter_select() does not affect the
1098                          * on-link determination and MIP6 needs the check
1099                          * before the default router selection, we perform
1100                          * the check now.
1101                          */
1102                         pfxlist_onlink_check();
1103
1104                         /*
1105                          * refresh default router list
1106                          */
1107                         defrouter_select();
1108                 }
1109                 splx(s);
1110         }
1111
1112         /*
1113          * Before deleting the entry, remember the next entry as the
1114          * return value.  We need this because pfxlist_onlink_check() above
1115          * might have freed other entries (particularly the old next entry) as
1116          * a side effect (XXX).
1117          */
1118         next = ln->ln_next;
1119
1120         /*
1121          * Detach the route from the routing tree and the list of neighbor
1122          * caches, and disable the route entry not to be used in already
1123          * cached routes.
1124          */
1125         rtrequest(RTM_DELETE, rt_key(rt), (struct sockaddr *)0,
1126             rt_mask(rt), 0, (struct rtentry **)0);
1127
1128         return (next);
1129 }
1130
1131 /*
1132  * Upper-layer reachability hint for Neighbor Unreachability Detection.
1133  *
1134  * XXX cost-effective methods?
1135  */
1136 void
1137 nd6_nud_hint(struct rtentry *rt, struct in6_addr *dst6, int force)
1138 {
1139         INIT_VNET_INET6(curvnet);
1140         struct llinfo_nd6 *ln;
1141
1142         /*
1143          * If the caller specified "rt", use that.  Otherwise, resolve the
1144          * routing table by supplied "dst6".
1145          */
1146         if (rt == NULL) {
1147                 if (dst6 == NULL)
1148                         return;
1149                 if ((rt = nd6_lookup(dst6, 0, NULL)) == NULL)
1150                         return;
1151         }
1152
1153         if ((rt->rt_flags & RTF_GATEWAY) != 0 ||
1154             (rt->rt_flags & RTF_LLINFO) == 0 ||
1155             rt->rt_llinfo == NULL || rt->rt_gateway == NULL ||
1156             rt->rt_gateway->sa_family != AF_LINK) {
1157                 /* This is not a host route. */
1158                 return;
1159         }
1160
1161         ln = (struct llinfo_nd6 *)rt->rt_llinfo;
1162         if (ln->ln_state < ND6_LLINFO_REACHABLE)
1163                 return;
1164
1165         /*
1166          * if we get upper-layer reachability confirmation many times,
1167          * it is possible we have false information.
1168          */
1169         if (!force) {
1170                 ln->ln_byhint++;
1171                 if (ln->ln_byhint > V_nd6_maxnudhint)
1172                         return;
1173         }
1174
1175         ln->ln_state = ND6_LLINFO_REACHABLE;
1176         if (!ND6_LLINFO_PERMANENT(ln)) {
1177                 nd6_llinfo_settimer(ln,
1178                     (long)ND_IFINFO(rt->rt_ifp)->reachable * hz);
1179         }
1180 }
1181
1182 /*
1183  * info - XXX unused
1184  */
1185 void
1186 nd6_rtrequest(int req, struct rtentry *rt, struct rt_addrinfo *info)
1187 {
1188         struct sockaddr *gate = rt->rt_gateway;
1189         struct llinfo_nd6 *ln = (struct llinfo_nd6 *)rt->rt_llinfo;
1190         static struct sockaddr_dl null_sdl = {sizeof(null_sdl), AF_LINK};
1191         struct ifnet *ifp = rt->rt_ifp;
1192         struct ifaddr *ifa;
1193         INIT_VNET_NET(ifp->if_vnet);
1194         INIT_VNET_INET6(ifp->if_vnet);
1195
1196         RT_LOCK_ASSERT(rt);
1197
1198         if ((rt->rt_flags & RTF_GATEWAY) != 0)
1199                 return;
1200
1201         if (nd6_need_cache(ifp) == 0 && (rt->rt_flags & RTF_HOST) == 0) {
1202                 /*
1203                  * This is probably an interface direct route for a link
1204                  * which does not need neighbor caches (e.g. fe80::%lo0/64).
1205                  * We do not need special treatment below for such a route.
1206                  * Moreover, the RTF_LLINFO flag which would be set below
1207                  * would annoy the ndp(8) command.
1208                  */
1209                 return;
1210         }
1211
1212         if (req == RTM_RESOLVE &&
1213             (nd6_need_cache(ifp) == 0 || /* stf case */
1214              !nd6_is_new_addr_neighbor((struct sockaddr_in6 *)rt_key(rt),
1215              ifp))) {
1216                 /*
1217                  * FreeBSD and BSD/OS often make a cloned host route based
1218                  * on a less-specific route (e.g. the default route).
1219                  * If the less specific route does not have a "gateway"
1220                  * (this is the case when the route just goes to a p2p or an
1221                  * stf interface), we'll mistakenly make a neighbor cache for
1222                  * the host route, and will see strange neighbor solicitation
1223                  * for the corresponding destination.  In order to avoid the
1224                  * confusion, we check if the destination of the route is
1225                  * a neighbor in terms of neighbor discovery, and stop the
1226                  * process if not.  Additionally, we remove the LLINFO flag
1227                  * so that ndp(8) will not try to get the neighbor information
1228                  * of the destination.
1229                  */
1230                 rt->rt_flags &= ~RTF_LLINFO;
1231                 return;
1232         }
1233
1234         switch (req) {
1235         case RTM_ADD:
1236                 /*
1237                  * There is no backward compatibility :)
1238                  *
1239                  * if ((rt->rt_flags & RTF_HOST) == 0 &&
1240                  *     SIN(rt_mask(rt))->sin_addr.s_addr != 0xffffffff)
1241                  *         rt->rt_flags |= RTF_CLONING;
1242                  */
1243                 if ((rt->rt_flags & RTF_CLONING) ||
1244                     ((rt->rt_flags & RTF_LLINFO) && ln == NULL)) {
1245                         /*
1246                          * Case 1: This route should come from a route to
1247                          * interface (RTF_CLONING case) or the route should be
1248                          * treated as on-link but is currently not
1249                          * (RTF_LLINFO && ln == NULL case).
1250                          */
1251                         rt_setgate(rt, rt_key(rt),
1252                                    (struct sockaddr *)&null_sdl);
1253                         gate = rt->rt_gateway;
1254                         SDL(gate)->sdl_type = ifp->if_type;
1255                         SDL(gate)->sdl_index = ifp->if_index;
1256                         if (ln)
1257                                 nd6_llinfo_settimer(ln, 0);
1258                         if ((rt->rt_flags & RTF_CLONING) != 0)
1259                                 break;
1260                 }
1261                 /*
1262                  * In IPv4 code, we try to annonuce new RTF_ANNOUNCE entry here.
1263                  * We don't do that here since llinfo is not ready yet.
1264                  *
1265                  * There are also couple of other things to be discussed:
1266                  * - unsolicited NA code needs improvement beforehand
1267                  * - RFC2461 says we MAY send multicast unsolicited NA
1268                  *   (7.2.6 paragraph 4), however, it also says that we
1269                  *   SHOULD provide a mechanism to prevent multicast NA storm.
1270                  *   we don't have anything like it right now.
1271                  *   note that the mechanism needs a mutual agreement
1272                  *   between proxies, which means that we need to implement
1273                  *   a new protocol, or a new kludge.
1274                  * - from RFC2461 6.2.4, host MUST NOT send an unsolicited NA.
1275                  *   we need to check ip6forwarding before sending it.
1276                  *   (or should we allow proxy ND configuration only for
1277                  *   routers?  there's no mention about proxy ND from hosts)
1278                  */
1279                 /* FALLTHROUGH */
1280         case RTM_RESOLVE:
1281                 if ((ifp->if_flags & (IFF_POINTOPOINT | IFF_LOOPBACK)) == 0) {
1282                         /*
1283                          * Address resolution isn't necessary for a point to
1284                          * point link, so we can skip this test for a p2p link.
1285                          */
1286                         if (gate->sa_family != AF_LINK ||
1287                             gate->sa_len < sizeof(null_sdl)) {
1288                                 log(LOG_DEBUG,
1289                                     "nd6_rtrequest: bad gateway value: %s\n",
1290                                     if_name(ifp));
1291                                 break;
1292                         }
1293                         SDL(gate)->sdl_type = ifp->if_type;
1294                         SDL(gate)->sdl_index = ifp->if_index;
1295                 }
1296                 if (ln != NULL)
1297                         break;  /* This happens on a route change */
1298                 /*
1299                  * Case 2: This route may come from cloning, or a manual route
1300                  * add with a LL address.
1301                  */
1302                 R_Malloc(ln, struct llinfo_nd6 *, sizeof(*ln));
1303                 rt->rt_llinfo = (caddr_t)ln;
1304                 if (ln == NULL) {
1305                         log(LOG_DEBUG, "nd6_rtrequest: malloc failed\n");
1306                         break;
1307                 }
1308                 V_nd6_inuse++;
1309                 V_nd6_allocated++;
1310                 bzero(ln, sizeof(*ln));
1311                 RT_ADDREF(rt);
1312                 ln->ln_rt = rt;
1313                 callout_init(&ln->ln_timer_ch, 0);
1314
1315                 /* this is required for "ndp" command. - shin */
1316                 if (req == RTM_ADD) {
1317                         /*
1318                          * gate should have some valid AF_LINK entry,
1319                          * and ln->ln_expire should have some lifetime
1320                          * which is specified by ndp command.
1321                          */
1322                         ln->ln_state = ND6_LLINFO_REACHABLE;
1323                         ln->ln_byhint = 0;
1324                 } else {
1325                         /*
1326                          * When req == RTM_RESOLVE, rt is created and
1327                          * initialized in rtrequest(), so rt_expire is 0.
1328                          */
1329                         ln->ln_state = ND6_LLINFO_NOSTATE;
1330                         nd6_llinfo_settimer(ln, 0);
1331                 }
1332                 rt->rt_flags |= RTF_LLINFO;
1333                 ln->ln_next = V_llinfo_nd6.ln_next;
1334                 V_llinfo_nd6.ln_next = ln;
1335                 ln->ln_prev = &V_llinfo_nd6;
1336                 ln->ln_next->ln_prev = ln;
1337
1338                 /*
1339                  * check if rt_key(rt) is one of my address assigned
1340                  * to the interface.
1341                  */
1342                 ifa = (struct ifaddr *)in6ifa_ifpwithaddr(rt->rt_ifp,
1343                     &SIN6(rt_key(rt))->sin6_addr);
1344                 if (ifa) {
1345                         caddr_t macp = nd6_ifptomac(ifp);
1346                         nd6_llinfo_settimer(ln, -1);
1347                         ln->ln_state = ND6_LLINFO_REACHABLE;
1348                         ln->ln_byhint = 0;
1349                         if (macp) {
1350                                 bcopy(macp, LLADDR(SDL(gate)), ifp->if_addrlen);
1351                                 SDL(gate)->sdl_alen = ifp->if_addrlen;
1352                         }
1353                         if (V_nd6_useloopback) {
1354                                 rt->rt_ifp = &V_loif[0];        /* XXX */
1355                                 /*
1356                                  * Make sure rt_ifa be equal to the ifaddr
1357                                  * corresponding to the address.
1358                                  * We need this because when we refer
1359                                  * rt_ifa->ia6_flags in ip6_input, we assume
1360                                  * that the rt_ifa points to the address instead
1361                                  * of the loopback address.
1362                                  */
1363                                 if (ifa != rt->rt_ifa) {
1364                                         IFAFREE(rt->rt_ifa);
1365                                         IFAREF(ifa);
1366                                         rt->rt_ifa = ifa;
1367                                 }
1368                         }
1369                 } else if (rt->rt_flags & RTF_ANNOUNCE) {
1370                         nd6_llinfo_settimer(ln, -1);
1371                         ln->ln_state = ND6_LLINFO_REACHABLE;
1372                         ln->ln_byhint = 0;
1373
1374                         /* join solicited node multicast for proxy ND */
1375                         if (ifp->if_flags & IFF_MULTICAST) {
1376                                 struct in6_addr llsol;
1377                                 int error;
1378
1379                                 llsol = SIN6(rt_key(rt))->sin6_addr;
1380                                 llsol.s6_addr32[0] = IPV6_ADDR_INT32_MLL;
1381                                 llsol.s6_addr32[1] = 0;
1382                                 llsol.s6_addr32[2] = htonl(1);
1383                                 llsol.s6_addr8[12] = 0xff;
1384                                 if (in6_setscope(&llsol, ifp, NULL))
1385                                         break;
1386                                 if (in6_addmulti(&llsol, ifp,
1387                                     &error, 0) == NULL) {
1388                                         char ip6buf[INET6_ADDRSTRLEN];
1389                                         nd6log((LOG_ERR, "%s: failed to join "
1390                                             "%s (errno=%d)\n", if_name(ifp),
1391                                             ip6_sprintf(ip6buf, &llsol),
1392                                             error));
1393                                 }
1394                         }
1395                 }
1396                 break;
1397
1398         case RTM_DELETE:
1399                 if (ln == NULL)
1400                         break;
1401                 /* leave from solicited node multicast for proxy ND */
1402                 if ((rt->rt_flags & RTF_ANNOUNCE) != 0 &&
1403                     (ifp->if_flags & IFF_MULTICAST) != 0) {
1404                         struct in6_addr llsol;
1405                         struct in6_multi *in6m;
1406
1407                         llsol = SIN6(rt_key(rt))->sin6_addr;
1408                         llsol.s6_addr32[0] = IPV6_ADDR_INT32_MLL;
1409                         llsol.s6_addr32[1] = 0;
1410                         llsol.s6_addr32[2] = htonl(1);
1411                         llsol.s6_addr8[12] = 0xff;
1412                         if (in6_setscope(&llsol, ifp, NULL) == 0) {
1413                                 IN6_LOOKUP_MULTI(llsol, ifp, in6m);
1414                                 if (in6m)
1415                                         in6_delmulti(in6m);
1416                         } else
1417                                 ; /* XXX: should not happen. bark here? */
1418                 }
1419                 V_nd6_inuse--;
1420                 ln->ln_next->ln_prev = ln->ln_prev;
1421                 ln->ln_prev->ln_next = ln->ln_next;
1422                 ln->ln_prev = NULL;
1423                 nd6_llinfo_settimer(ln, -1);
1424                 RT_REMREF(rt);
1425                 rt->rt_llinfo = 0;
1426                 rt->rt_flags &= ~RTF_LLINFO;
1427                 clear_llinfo_pqueue(ln);
1428                 Free((caddr_t)ln);
1429         }
1430 }
1431
1432 int
1433 nd6_ioctl(u_long cmd, caddr_t data, struct ifnet *ifp)
1434 {
1435         INIT_VNET_INET6(ifp->if_vnet);
1436         struct in6_drlist *drl = (struct in6_drlist *)data;
1437         struct in6_oprlist *oprl = (struct in6_oprlist *)data;
1438         struct in6_ndireq *ndi = (struct in6_ndireq *)data;
1439         struct in6_nbrinfo *nbi = (struct in6_nbrinfo *)data;
1440         struct in6_ndifreq *ndif = (struct in6_ndifreq *)data;
1441         struct nd_defrouter *dr;
1442         struct nd_prefix *pr;
1443         struct rtentry *rt;
1444         int i = 0, error = 0;
1445         int s;
1446
1447         switch (cmd) {
1448         case SIOCGDRLST_IN6:
1449                 /*
1450                  * obsolete API, use sysctl under net.inet6.icmp6
1451                  */
1452                 bzero(drl, sizeof(*drl));
1453                 s = splnet();
1454                 dr = TAILQ_FIRST(&V_nd_defrouter);
1455                 while (dr && i < DRLSTSIZ) {
1456                         drl->defrouter[i].rtaddr = dr->rtaddr;
1457                         in6_clearscope(&drl->defrouter[i].rtaddr);
1458
1459                         drl->defrouter[i].flags = dr->flags;
1460                         drl->defrouter[i].rtlifetime = dr->rtlifetime;
1461                         drl->defrouter[i].expire = dr->expire;
1462                         drl->defrouter[i].if_index = dr->ifp->if_index;
1463                         i++;
1464                         dr = TAILQ_NEXT(dr, dr_entry);
1465                 }
1466                 splx(s);
1467                 break;
1468         case SIOCGPRLST_IN6:
1469                 /*
1470                  * obsolete API, use sysctl under net.inet6.icmp6
1471                  *
1472                  * XXX the structure in6_prlist was changed in backward-
1473                  * incompatible manner.  in6_oprlist is used for SIOCGPRLST_IN6,
1474                  * in6_prlist is used for nd6_sysctl() - fill_prlist().
1475                  */
1476                 /*
1477                  * XXX meaning of fields, especialy "raflags", is very
1478                  * differnet between RA prefix list and RR/static prefix list.
1479                  * how about separating ioctls into two?
1480                  */
1481                 bzero(oprl, sizeof(*oprl));
1482                 s = splnet();
1483                 pr = V_nd_prefix.lh_first;
1484                 while (pr && i < PRLSTSIZ) {
1485                         struct nd_pfxrouter *pfr;
1486                         int j;
1487
1488                         oprl->prefix[i].prefix = pr->ndpr_prefix.sin6_addr;
1489                         oprl->prefix[i].raflags = pr->ndpr_raf;
1490                         oprl->prefix[i].prefixlen = pr->ndpr_plen;
1491                         oprl->prefix[i].vltime = pr->ndpr_vltime;
1492                         oprl->prefix[i].pltime = pr->ndpr_pltime;
1493                         oprl->prefix[i].if_index = pr->ndpr_ifp->if_index;
1494                         if (pr->ndpr_vltime == ND6_INFINITE_LIFETIME)
1495                                 oprl->prefix[i].expire = 0;
1496                         else {
1497                                 time_t maxexpire;
1498
1499                                 /* XXX: we assume time_t is signed. */
1500                                 maxexpire = (-1) &
1501                                     ~((time_t)1 <<
1502                                     ((sizeof(maxexpire) * 8) - 1));
1503                                 if (pr->ndpr_vltime <
1504                                     maxexpire - pr->ndpr_lastupdate) {
1505                                         oprl->prefix[i].expire =
1506                                             pr->ndpr_lastupdate +
1507                                             pr->ndpr_vltime;
1508                                 } else
1509                                         oprl->prefix[i].expire = maxexpire;
1510                         }
1511
1512                         pfr = pr->ndpr_advrtrs.lh_first;
1513                         j = 0;
1514                         while (pfr) {
1515                                 if (j < DRLSTSIZ) {
1516 #define RTRADDR oprl->prefix[i].advrtr[j]
1517                                         RTRADDR = pfr->router->rtaddr;
1518                                         in6_clearscope(&RTRADDR);
1519 #undef RTRADDR
1520                                 }
1521                                 j++;
1522                                 pfr = pfr->pfr_next;
1523                         }
1524                         oprl->prefix[i].advrtrs = j;
1525                         oprl->prefix[i].origin = PR_ORIG_RA;
1526
1527                         i++;
1528                         pr = pr->ndpr_next;
1529                 }
1530                 splx(s);
1531
1532                 break;
1533         case OSIOCGIFINFO_IN6:
1534 #define ND      ndi->ndi
1535                 /* XXX: old ndp(8) assumes a positive value for linkmtu. */
1536                 bzero(&ND, sizeof(ND));
1537                 ND.linkmtu = IN6_LINKMTU(ifp);
1538                 ND.maxmtu = ND_IFINFO(ifp)->maxmtu;
1539                 ND.basereachable = ND_IFINFO(ifp)->basereachable;
1540                 ND.reachable = ND_IFINFO(ifp)->reachable;
1541                 ND.retrans = ND_IFINFO(ifp)->retrans;
1542                 ND.flags = ND_IFINFO(ifp)->flags;
1543                 ND.recalctm = ND_IFINFO(ifp)->recalctm;
1544                 ND.chlim = ND_IFINFO(ifp)->chlim;
1545                 break;
1546         case SIOCGIFINFO_IN6:
1547                 ND = *ND_IFINFO(ifp);
1548                 break;
1549         case SIOCSIFINFO_IN6:
1550                 /*
1551                  * used to change host variables from userland.
1552                  * intented for a use on router to reflect RA configurations.
1553                  */
1554                 /* 0 means 'unspecified' */
1555                 if (ND.linkmtu != 0) {
1556                         if (ND.linkmtu < IPV6_MMTU ||
1557                             ND.linkmtu > IN6_LINKMTU(ifp)) {
1558                                 error = EINVAL;
1559                                 break;
1560                         }
1561                         ND_IFINFO(ifp)->linkmtu = ND.linkmtu;
1562                 }
1563
1564                 if (ND.basereachable != 0) {
1565                         int obasereachable = ND_IFINFO(ifp)->basereachable;
1566
1567                         ND_IFINFO(ifp)->basereachable = ND.basereachable;
1568                         if (ND.basereachable != obasereachable)
1569                                 ND_IFINFO(ifp)->reachable =
1570                                     ND_COMPUTE_RTIME(ND.basereachable);
1571                 }
1572                 if (ND.retrans != 0)
1573                         ND_IFINFO(ifp)->retrans = ND.retrans;
1574                 if (ND.chlim != 0)
1575                         ND_IFINFO(ifp)->chlim = ND.chlim;
1576                 /* FALLTHROUGH */
1577         case SIOCSIFINFO_FLAGS:
1578                 ND_IFINFO(ifp)->flags = ND.flags;
1579                 break;
1580 #undef ND
1581         case SIOCSNDFLUSH_IN6:  /* XXX: the ioctl name is confusing... */
1582                 /* sync kernel routing table with the default router list */
1583                 defrouter_reset();
1584                 defrouter_select();
1585                 break;
1586         case SIOCSPFXFLUSH_IN6:
1587         {
1588                 /* flush all the prefix advertised by routers */
1589                 struct nd_prefix *pr, *next;
1590
1591                 s = splnet();
1592                 for (pr = V_nd_prefix.lh_first; pr; pr = next) {
1593                         struct in6_ifaddr *ia, *ia_next;
1594
1595                         next = pr->ndpr_next;
1596
1597                         if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
1598                                 continue; /* XXX */
1599
1600                         /* do we really have to remove addresses as well? */
1601                         for (ia = V_in6_ifaddr; ia; ia = ia_next) {
1602                                 /* ia might be removed.  keep the next ptr. */
1603                                 ia_next = ia->ia_next;
1604
1605                                 if ((ia->ia6_flags & IN6_IFF_AUTOCONF) == 0)
1606                                         continue;
1607
1608                                 if (ia->ia6_ndpr == pr)
1609                                         in6_purgeaddr(&ia->ia_ifa);
1610                         }
1611                         prelist_remove(pr);
1612                 }
1613                 splx(s);
1614                 break;
1615         }
1616         case SIOCSRTRFLUSH_IN6:
1617         {
1618                 /* flush all the default routers */
1619                 struct nd_defrouter *dr, *next;
1620
1621                 s = splnet();
1622                 defrouter_reset();
1623                 for (dr = TAILQ_FIRST(&V_nd_defrouter); dr; dr = next) {
1624                         next = TAILQ_NEXT(dr, dr_entry);
1625                         defrtrlist_del(dr);
1626                 }
1627                 defrouter_select();
1628                 splx(s);
1629                 break;
1630         }
1631         case SIOCGNBRINFO_IN6:
1632         {
1633                 struct llinfo_nd6 *ln;
1634                 struct in6_addr nb_addr = nbi->addr; /* make local for safety */
1635
1636                 if ((error = in6_setscope(&nb_addr, ifp, NULL)) != 0)
1637                         return (error);
1638
1639                 s = splnet();
1640                 if ((rt = nd6_lookup(&nb_addr, 0, ifp)) == NULL) {
1641                         error = EINVAL;
1642                         splx(s);
1643                         break;
1644                 }
1645                 ln = (struct llinfo_nd6 *)rt->rt_llinfo;
1646                 nbi->state = ln->ln_state;
1647                 nbi->asked = ln->ln_asked;
1648                 nbi->isrouter = ln->ln_router;
1649                 nbi->expire = ln->ln_expire;
1650                 splx(s);
1651
1652                 break;
1653         }
1654         case SIOCGDEFIFACE_IN6: /* XXX: should be implemented as a sysctl? */
1655                 ndif->ifindex = V_nd6_defifindex;
1656                 break;
1657         case SIOCSDEFIFACE_IN6: /* XXX: should be implemented as a sysctl? */
1658                 return (nd6_setdefaultiface(ndif->ifindex));
1659         }
1660         return (error);
1661 }
1662
1663 /*
1664  * Create neighbor cache entry and cache link-layer address,
1665  * on reception of inbound ND6 packets.  (RS/RA/NS/redirect)
1666  *
1667  * type - ICMP6 type
1668  * code - type dependent information
1669  */
1670 struct rtentry *
1671 nd6_cache_lladdr(struct ifnet *ifp, struct in6_addr *from, char *lladdr,
1672     int lladdrlen, int type, int code)
1673 {
1674         INIT_VNET_INET6(curvnet);
1675         struct rtentry *rt = NULL;
1676         struct llinfo_nd6 *ln = NULL;
1677         int is_newentry;
1678         struct sockaddr_dl *sdl = NULL;
1679         int do_update;
1680         int olladdr;
1681         int llchange;
1682         int newstate = 0;
1683
1684         if (ifp == NULL)
1685                 panic("ifp == NULL in nd6_cache_lladdr");
1686         if (from == NULL)
1687                 panic("from == NULL in nd6_cache_lladdr");
1688
1689         /* nothing must be updated for unspecified address */
1690         if (IN6_IS_ADDR_UNSPECIFIED(from))
1691                 return NULL;
1692
1693         /*
1694          * Validation about ifp->if_addrlen and lladdrlen must be done in
1695          * the caller.
1696          *
1697          * XXX If the link does not have link-layer adderss, what should
1698          * we do? (ifp->if_addrlen == 0)
1699          * Spec says nothing in sections for RA, RS and NA.  There's small
1700          * description on it in NS section (RFC 2461 7.2.3).
1701          */
1702
1703         rt = nd6_lookup(from, 0, ifp);
1704         if (rt == NULL) {
1705                 rt = nd6_lookup(from, 1, ifp);
1706                 is_newentry = 1;
1707         } else {
1708                 /* do nothing if static ndp is set */
1709                 if (rt->rt_flags & RTF_STATIC)
1710                         return NULL;
1711                 is_newentry = 0;
1712         }
1713
1714         if (rt == NULL)
1715                 return NULL;
1716         if ((rt->rt_flags & (RTF_GATEWAY | RTF_LLINFO)) != RTF_LLINFO) {
1717 fail:
1718                 (void)nd6_free(rt, 0);
1719                 return NULL;
1720         }
1721         ln = (struct llinfo_nd6 *)rt->rt_llinfo;
1722         if (ln == NULL)
1723                 goto fail;
1724         if (rt->rt_gateway == NULL)
1725                 goto fail;
1726         if (rt->rt_gateway->sa_family != AF_LINK)
1727                 goto fail;
1728         sdl = SDL(rt->rt_gateway);
1729
1730         olladdr = (sdl->sdl_alen) ? 1 : 0;
1731         if (olladdr && lladdr) {
1732                 if (bcmp(lladdr, LLADDR(sdl), ifp->if_addrlen))
1733                         llchange = 1;
1734                 else
1735                         llchange = 0;
1736         } else
1737                 llchange = 0;
1738
1739         /*
1740          * newentry olladdr  lladdr  llchange   (*=record)
1741          *      0       n       n       --      (1)
1742          *      0       y       n       --      (2)
1743          *      0       n       y       --      (3) * STALE
1744          *      0       y       y       n       (4) *
1745          *      0       y       y       y       (5) * STALE
1746          *      1       --      n       --      (6)   NOSTATE(= PASSIVE)
1747          *      1       --      y       --      (7) * STALE
1748          */
1749
1750         if (lladdr) {           /* (3-5) and (7) */
1751                 /*
1752                  * Record source link-layer address
1753                  * XXX is it dependent to ifp->if_type?
1754                  */
1755                 sdl->sdl_alen = ifp->if_addrlen;
1756                 bcopy(lladdr, LLADDR(sdl), ifp->if_addrlen);
1757         }
1758
1759         if (!is_newentry) {
1760                 if ((!olladdr && lladdr != NULL) ||     /* (3) */
1761                     (olladdr && lladdr != NULL && llchange)) {  /* (5) */
1762                         do_update = 1;
1763                         newstate = ND6_LLINFO_STALE;
1764                 } else                                  /* (1-2,4) */
1765                         do_update = 0;
1766         } else {
1767                 do_update = 1;
1768                 if (lladdr == NULL)                     /* (6) */
1769                         newstate = ND6_LLINFO_NOSTATE;
1770                 else                                    /* (7) */
1771                         newstate = ND6_LLINFO_STALE;
1772         }
1773
1774         if (do_update) {
1775                 /*
1776                  * Update the state of the neighbor cache.
1777                  */
1778                 ln->ln_state = newstate;
1779
1780                 if (ln->ln_state == ND6_LLINFO_STALE) {
1781                         /*
1782                          * XXX: since nd6_output() below will cause
1783                          * state tansition to DELAY and reset the timer,
1784                          * we must set the timer now, although it is actually
1785                          * meaningless.
1786                          */
1787                         nd6_llinfo_settimer(ln, (long)V_nd6_gctimer * hz);
1788
1789                         if (ln->ln_hold) {
1790                                 struct mbuf *m_hold, *m_hold_next;
1791
1792                                 /*
1793                                  * reset the ln_hold in advance, to explicitly
1794                                  * prevent a ln_hold lookup in nd6_output()
1795                                  * (wouldn't happen, though...)
1796                                  */
1797                                 for (m_hold = ln->ln_hold, ln->ln_hold = NULL;
1798                                     m_hold; m_hold = m_hold_next) {
1799                                         m_hold_next = m_hold->m_nextpkt;
1800                                         m_hold->m_nextpkt = NULL;
1801
1802                                         /*
1803                                          * we assume ifp is not a p2p here, so
1804                                          * just set the 2nd argument as the
1805                                          * 1st one.
1806                                          */
1807                                         nd6_output(ifp, ifp, m_hold,
1808                                              (struct sockaddr_in6 *)rt_key(rt),
1809                                              rt);
1810                                 }
1811                         }
1812                 } else if (ln->ln_state == ND6_LLINFO_INCOMPLETE) {
1813                         /* probe right away */
1814                         nd6_llinfo_settimer((void *)ln, 0);
1815                 }
1816         }
1817
1818         /*
1819          * ICMP6 type dependent behavior.
1820          *
1821          * NS: clear IsRouter if new entry
1822          * RS: clear IsRouter
1823          * RA: set IsRouter if there's lladdr
1824          * redir: clear IsRouter if new entry
1825          *
1826          * RA case, (1):
1827          * The spec says that we must set IsRouter in the following cases:
1828          * - If lladdr exist, set IsRouter.  This means (1-5).
1829          * - If it is old entry (!newentry), set IsRouter.  This means (7).
1830          * So, based on the spec, in (1-5) and (7) cases we must set IsRouter.
1831          * A quetion arises for (1) case.  (1) case has no lladdr in the
1832          * neighbor cache, this is similar to (6).
1833          * This case is rare but we figured that we MUST NOT set IsRouter.
1834          *
1835          * newentry olladdr  lladdr  llchange       NS  RS  RA  redir
1836          *                                                      D R
1837          *      0       n       n       --      (1)     c   ?     s
1838          *      0       y       n       --      (2)     c   s     s
1839          *      0       n       y       --      (3)     c   s     s
1840          *      0       y       y       n       (4)     c   s     s
1841          *      0       y       y       y       (5)     c   s     s
1842          *      1       --      n       --      (6) c   c       c s
1843          *      1       --      y       --      (7) c   c   s   c s
1844          *
1845          *                                      (c=clear s=set)
1846          */
1847         switch (type & 0xff) {
1848         case ND_NEIGHBOR_SOLICIT:
1849                 /*
1850                  * New entry must have is_router flag cleared.
1851                  */
1852                 if (is_newentry)        /* (6-7) */
1853                         ln->ln_router = 0;
1854                 break;
1855         case ND_REDIRECT:
1856                 /*
1857                  * If the icmp is a redirect to a better router, always set the
1858                  * is_router flag.  Otherwise, if the entry is newly created,
1859                  * clear the flag.  [RFC 2461, sec 8.3]
1860                  */
1861                 if (code == ND_REDIRECT_ROUTER)
1862                         ln->ln_router = 1;
1863                 else if (is_newentry) /* (6-7) */
1864                         ln->ln_router = 0;
1865                 break;
1866         case ND_ROUTER_SOLICIT:
1867                 /*
1868                  * is_router flag must always be cleared.
1869                  */
1870                 ln->ln_router = 0;
1871                 break;
1872         case ND_ROUTER_ADVERT:
1873                 /*
1874                  * Mark an entry with lladdr as a router.
1875                  */
1876                 if ((!is_newentry && (olladdr || lladdr)) ||    /* (2-5) */
1877                     (is_newentry && lladdr)) {                  /* (7) */
1878                         ln->ln_router = 1;
1879                 }
1880                 break;
1881         }
1882
1883         /*
1884          * When the link-layer address of a router changes, select the
1885          * best router again.  In particular, when the neighbor entry is newly
1886          * created, it might affect the selection policy.
1887          * Question: can we restrict the first condition to the "is_newentry"
1888          * case?
1889          * XXX: when we hear an RA from a new router with the link-layer
1890          * address option, defrouter_select() is called twice, since
1891          * defrtrlist_update called the function as well.  However, I believe
1892          * we can compromise the overhead, since it only happens the first
1893          * time.
1894          * XXX: although defrouter_select() should not have a bad effect
1895          * for those are not autoconfigured hosts, we explicitly avoid such
1896          * cases for safety.
1897          */
1898         if (do_update && ln->ln_router && !V_ip6_forwarding && V_ip6_accept_rtadv)
1899                 defrouter_select();
1900
1901         return rt;
1902 }
1903
1904 static void
1905 nd6_slowtimo(void *arg)
1906 {
1907         CURVNET_SET((struct vnet *) arg);
1908         INIT_VNET_NET((struct vnet *) arg);
1909         INIT_VNET_INET6((struct vnet *) arg);
1910         struct nd_ifinfo *nd6if;
1911         struct ifnet *ifp;
1912
1913         callout_reset(&V_nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL * hz,
1914             nd6_slowtimo, NULL);
1915         IFNET_RLOCK();
1916         for (ifp = TAILQ_FIRST(&V_ifnet); ifp;
1917             ifp = TAILQ_NEXT(ifp, if_list)) {
1918                 nd6if = ND_IFINFO(ifp);
1919                 if (nd6if->basereachable && /* already initialized */
1920                     (nd6if->recalctm -= ND6_SLOWTIMER_INTERVAL) <= 0) {
1921                         /*
1922                          * Since reachable time rarely changes by router
1923                          * advertisements, we SHOULD insure that a new random
1924                          * value gets recomputed at least once every few hours.
1925                          * (RFC 2461, 6.3.4)
1926                          */
1927                         nd6if->recalctm = V_nd6_recalc_reachtm_interval;
1928                         nd6if->reachable = ND_COMPUTE_RTIME(nd6if->basereachable);
1929                 }
1930         }
1931         IFNET_RUNLOCK();
1932         CURVNET_RESTORE();
1933 }
1934
1935 #define senderr(e) { error = (e); goto bad;}
1936 int
1937 nd6_output(struct ifnet *ifp, struct ifnet *origifp, struct mbuf *m0,
1938     struct sockaddr_in6 *dst, struct rtentry *rt0)
1939 {
1940         INIT_VNET_INET6(curvnet);
1941         struct mbuf *m = m0;
1942         struct rtentry *rt = rt0;
1943         struct sockaddr_in6 *gw6 = NULL;
1944         struct llinfo_nd6 *ln = NULL;
1945         int error = 0;
1946
1947         if (IN6_IS_ADDR_MULTICAST(&dst->sin6_addr))
1948                 goto sendpkt;
1949
1950         if (nd6_need_cache(ifp) == 0)
1951                 goto sendpkt;
1952
1953         /*
1954          * next hop determination.  This routine is derived from ether_output.
1955          */
1956         /* NB: the locking here is tortuous... */
1957         if (rt != NULL)
1958                 RT_LOCK(rt);
1959 again:
1960         if (rt != NULL) {
1961                 if ((rt->rt_flags & RTF_UP) == 0) {
1962                         RT_UNLOCK(rt);
1963                         rt0 = rt = rtalloc1((struct sockaddr *)dst, 1, 0UL);
1964                         if (rt != NULL) {
1965                                 RT_REMREF(rt);
1966                                 if (rt->rt_ifp != ifp)
1967                                         /*
1968                                          * XXX maybe we should update ifp too,
1969                                          * but the original code didn't and I
1970                                          * don't know what is correct here.
1971                                          */
1972                                         goto again;
1973                         } else
1974                                 senderr(EHOSTUNREACH);
1975                 }
1976
1977                 if (rt->rt_flags & RTF_GATEWAY) {
1978                         gw6 = (struct sockaddr_in6 *)rt->rt_gateway;
1979
1980                         /*
1981                          * We skip link-layer address resolution and NUD
1982                          * if the gateway is not a neighbor from ND point
1983                          * of view, regardless of the value of nd_ifinfo.flags.
1984                          * The second condition is a bit tricky; we skip
1985                          * if the gateway is our own address, which is
1986                          * sometimes used to install a route to a p2p link.
1987                          */
1988                         if (!nd6_is_addr_neighbor(gw6, ifp) ||
1989                             in6ifa_ifpwithaddr(ifp, &gw6->sin6_addr)) {
1990                                 RT_UNLOCK(rt);
1991                                 /*
1992                                  * We allow this kind of tricky route only
1993                                  * when the outgoing interface is p2p.
1994                                  * XXX: we may need a more generic rule here.
1995                                  */
1996                                 if ((ifp->if_flags & IFF_POINTOPOINT) == 0)
1997                                         senderr(EHOSTUNREACH);
1998
1999                                 goto sendpkt;
2000                         }
2001
2002                         if (rt->rt_gwroute == NULL)
2003                                 goto lookup;
2004                         rt = rt->rt_gwroute;
2005                         RT_LOCK(rt);            /* NB: gwroute */
2006                         if ((rt->rt_flags & RTF_UP) == 0) {
2007                                 RTFREE_LOCKED(rt);      /* unlock gwroute */
2008                                 rt = rt0;
2009                                 rt0->rt_gwroute = NULL;
2010                         lookup:
2011                                 RT_UNLOCK(rt0);
2012                                 rt = rtalloc1(rt->rt_gateway, 1, 0UL);
2013                                 if (rt == rt0) {
2014                                         RT_REMREF(rt0);
2015                                         RT_UNLOCK(rt0);
2016                                         senderr(EHOSTUNREACH);
2017                                 }
2018                                 RT_LOCK(rt0);
2019                                 if (rt0->rt_gwroute != NULL)
2020                                         RTFREE(rt0->rt_gwroute);
2021                                 rt0->rt_gwroute = rt;
2022                                 if (rt == NULL) {
2023                                         RT_UNLOCK(rt0);
2024                                         senderr(EHOSTUNREACH);
2025                                 }
2026                         }
2027                         RT_UNLOCK(rt0);
2028                 }
2029                 RT_UNLOCK(rt);
2030         }
2031
2032         /*
2033          * Address resolution or Neighbor Unreachability Detection
2034          * for the next hop.
2035          * At this point, the destination of the packet must be a unicast
2036          * or an anycast address(i.e. not a multicast).
2037          */
2038
2039         /* Look up the neighbor cache for the nexthop */
2040         if (rt && (rt->rt_flags & RTF_LLINFO) != 0)
2041                 ln = (struct llinfo_nd6 *)rt->rt_llinfo;
2042         else {
2043                 /*
2044                  * Since nd6_is_addr_neighbor() internally calls nd6_lookup(),
2045                  * the condition below is not very efficient.  But we believe
2046                  * it is tolerable, because this should be a rare case.
2047                  */
2048                 if (nd6_is_addr_neighbor(dst, ifp) &&
2049                     (rt = nd6_lookup(&dst->sin6_addr, 1, ifp)) != NULL)
2050                         ln = (struct llinfo_nd6 *)rt->rt_llinfo;
2051         }
2052         if (ln == NULL || rt == NULL) {
2053                 if ((ifp->if_flags & IFF_POINTOPOINT) == 0 &&
2054                     !(ND_IFINFO(ifp)->flags & ND6_IFF_PERFORMNUD)) {
2055                         char ip6buf[INET6_ADDRSTRLEN];
2056                         log(LOG_DEBUG,
2057                             "nd6_output: can't allocate llinfo for %s "
2058                             "(ln=%p, rt=%p)\n",
2059                             ip6_sprintf(ip6buf, &dst->sin6_addr), ln, rt);
2060                         senderr(EIO);   /* XXX: good error? */
2061                 }
2062
2063                 goto sendpkt;   /* send anyway */
2064         }
2065
2066         /* We don't have to do link-layer address resolution on a p2p link. */
2067         if ((ifp->if_flags & IFF_POINTOPOINT) != 0 &&
2068             ln->ln_state < ND6_LLINFO_REACHABLE) {
2069                 ln->ln_state = ND6_LLINFO_STALE;
2070                 nd6_llinfo_settimer(ln, (long)V_nd6_gctimer * hz);
2071         }
2072
2073         /*
2074          * The first time we send a packet to a neighbor whose entry is
2075          * STALE, we have to change the state to DELAY and a sets a timer to
2076          * expire in DELAY_FIRST_PROBE_TIME seconds to ensure do
2077          * neighbor unreachability detection on expiration.
2078          * (RFC 2461 7.3.3)
2079          */
2080         if (ln->ln_state == ND6_LLINFO_STALE) {
2081                 ln->ln_asked = 0;
2082                 ln->ln_state = ND6_LLINFO_DELAY;
2083                 nd6_llinfo_settimer(ln, (long)V_nd6_delay * hz);
2084         }
2085
2086         /*
2087          * If the neighbor cache entry has a state other than INCOMPLETE
2088          * (i.e. its link-layer address is already resolved), just
2089          * send the packet.
2090          */
2091         if (ln->ln_state > ND6_LLINFO_INCOMPLETE)
2092                 goto sendpkt;
2093
2094         /*
2095          * There is a neighbor cache entry, but no ethernet address
2096          * response yet.  Append this latest packet to the end of the
2097          * packet queue in the mbuf, unless the number of the packet
2098          * does not exceed nd6_maxqueuelen.  When it exceeds nd6_maxqueuelen,
2099          * the oldest packet in the queue will be removed.
2100          */
2101         if (ln->ln_state == ND6_LLINFO_NOSTATE)
2102                 ln->ln_state = ND6_LLINFO_INCOMPLETE;
2103         if (ln->ln_hold) {
2104                 struct mbuf *m_hold;
2105                 int i;
2106
2107                 i = 0;
2108                 for (m_hold = ln->ln_hold; m_hold; m_hold = m_hold->m_nextpkt) {
2109                         i++;
2110                         if (m_hold->m_nextpkt == NULL) {
2111                                 m_hold->m_nextpkt = m;
2112                                 break;
2113                         }
2114                 }
2115                 while (i >= V_nd6_maxqueuelen) {
2116                         m_hold = ln->ln_hold;
2117                         ln->ln_hold = ln->ln_hold->m_nextpkt;
2118                         m_freem(m_hold);
2119                         i--;
2120                 }
2121         } else {
2122                 ln->ln_hold = m;
2123         }
2124
2125         /*
2126          * If there has been no NS for the neighbor after entering the
2127          * INCOMPLETE state, send the first solicitation.
2128          */
2129         if (!ND6_LLINFO_PERMANENT(ln) && ln->ln_asked == 0) {
2130                 ln->ln_asked++;
2131                 nd6_llinfo_settimer(ln,
2132                     (long)ND_IFINFO(ifp)->retrans * hz / 1000);
2133                 nd6_ns_output(ifp, NULL, &dst->sin6_addr, ln, 0);
2134         }
2135         return (0);
2136
2137   sendpkt:
2138         /* discard the packet if IPv6 operation is disabled on the interface */
2139         if ((ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED)) {
2140                 error = ENETDOWN; /* better error? */
2141                 goto bad;
2142         }
2143
2144 #ifdef MAC
2145         mac_netinet6_nd6_send(ifp, m);
2146 #endif
2147         if ((ifp->if_flags & IFF_LOOPBACK) != 0) {
2148                 return ((*ifp->if_output)(origifp, m, (struct sockaddr *)dst,
2149                     rt));
2150         }
2151         return ((*ifp->if_output)(ifp, m, (struct sockaddr *)dst, rt));
2152
2153   bad:
2154         if (m)
2155                 m_freem(m);
2156         return (error);
2157 }
2158 #undef senderr
2159
2160 int
2161 nd6_need_cache(struct ifnet *ifp)
2162 {
2163         /*
2164          * XXX: we currently do not make neighbor cache on any interface
2165          * other than ARCnet, Ethernet, FDDI and GIF.
2166          *
2167          * RFC2893 says:
2168          * - unidirectional tunnels needs no ND
2169          */
2170         switch (ifp->if_type) {
2171         case IFT_ARCNET:
2172         case IFT_ETHER:
2173         case IFT_FDDI:
2174         case IFT_IEEE1394:
2175 #ifdef IFT_L2VLAN
2176         case IFT_L2VLAN:
2177 #endif
2178 #ifdef IFT_IEEE80211
2179         case IFT_IEEE80211:
2180 #endif
2181 #ifdef IFT_CARP
2182         case IFT_CARP:
2183 #endif
2184         case IFT_GIF:           /* XXX need more cases? */
2185         case IFT_PPP:
2186         case IFT_TUNNEL:
2187         case IFT_BRIDGE:
2188         case IFT_PROPVIRTUAL:
2189                 return (1);
2190         default:
2191                 return (0);
2192         }
2193 }
2194
2195 int
2196 nd6_storelladdr(struct ifnet *ifp, struct rtentry *rt0, struct mbuf *m,
2197     struct sockaddr *dst, u_char *desten)
2198 {
2199         struct sockaddr_dl *sdl;
2200         struct rtentry *rt;
2201         int error;
2202
2203         if (m->m_flags & M_MCAST) {
2204                 int i;
2205
2206                 switch (ifp->if_type) {
2207                 case IFT_ETHER:
2208                 case IFT_FDDI:
2209 #ifdef IFT_L2VLAN
2210                 case IFT_L2VLAN:
2211 #endif
2212 #ifdef IFT_IEEE80211
2213                 case IFT_IEEE80211:
2214 #endif
2215                 case IFT_BRIDGE:
2216                 case IFT_ISO88025:
2217                         ETHER_MAP_IPV6_MULTICAST(&SIN6(dst)->sin6_addr,
2218                                                  desten);
2219                         return (0);
2220                 case IFT_IEEE1394:
2221                         /*
2222                          * netbsd can use if_broadcastaddr, but we don't do so
2223                          * to reduce # of ifdef.
2224                          */
2225                         for (i = 0; i < ifp->if_addrlen; i++)
2226                                 desten[i] = ~0;
2227                         return (0);
2228                 case IFT_ARCNET:
2229                         *desten = 0;
2230                         return (0);
2231                 default:
2232                         m_freem(m);
2233                         return (EAFNOSUPPORT);
2234                 }
2235         }
2236
2237         if (rt0 == NULL) {
2238                 /* this could happen, if we could not allocate memory */
2239                 m_freem(m);
2240                 return (ENOMEM);
2241         }
2242
2243         error = rt_check(&rt, &rt0, dst);
2244         if (error) {
2245                 m_freem(m);
2246                 return (error);
2247         }
2248         RT_UNLOCK(rt);
2249
2250         if (rt->rt_gateway->sa_family != AF_LINK) {
2251                 printf("nd6_storelladdr: something odd happens\n");
2252                 m_freem(m);
2253                 return (EINVAL);
2254         }
2255         sdl = SDL(rt->rt_gateway);
2256         if (sdl->sdl_alen == 0) {
2257                 /* this should be impossible, but we bark here for debugging */
2258                 printf("nd6_storelladdr: sdl_alen == 0\n");
2259                 m_freem(m);
2260                 return (EINVAL);
2261         }
2262
2263         bcopy(LLADDR(sdl), desten, sdl->sdl_alen);
2264         return (0);
2265 }
2266
2267 static void
2268 clear_llinfo_pqueue(struct llinfo_nd6 *ln)
2269 {
2270         struct mbuf *m_hold, *m_hold_next;
2271
2272         for (m_hold = ln->ln_hold; m_hold; m_hold = m_hold_next) {
2273                 m_hold_next = m_hold->m_nextpkt;
2274                 m_hold->m_nextpkt = NULL;
2275                 m_freem(m_hold);
2276         }
2277
2278         ln->ln_hold = NULL;
2279         return;
2280 }
2281
2282 static int nd6_sysctl_drlist(SYSCTL_HANDLER_ARGS);
2283 static int nd6_sysctl_prlist(SYSCTL_HANDLER_ARGS);
2284 #ifdef SYSCTL_DECL
2285 SYSCTL_DECL(_net_inet6_icmp6);
2286 #endif
2287 SYSCTL_NODE(_net_inet6_icmp6, ICMPV6CTL_ND6_DRLIST, nd6_drlist,
2288         CTLFLAG_RD, nd6_sysctl_drlist, "");
2289 SYSCTL_NODE(_net_inet6_icmp6, ICMPV6CTL_ND6_PRLIST, nd6_prlist,
2290         CTLFLAG_RD, nd6_sysctl_prlist, "");
2291 SYSCTL_V_INT(V_NET, vnet_inet6, _net_inet6_icmp6, ICMPV6CTL_ND6_MAXQLEN,
2292         nd6_maxqueuelen, CTLFLAG_RW, nd6_maxqueuelen, 1, "");
2293
2294 static int
2295 nd6_sysctl_drlist(SYSCTL_HANDLER_ARGS)
2296 {
2297         INIT_VNET_INET6(curvnet);
2298         int error;
2299         char buf[1024] __aligned(4);
2300         struct in6_defrouter *d, *de;
2301         struct nd_defrouter *dr;
2302
2303         if (req->newptr)
2304                 return EPERM;
2305         error = 0;
2306
2307         for (dr = TAILQ_FIRST(&V_nd_defrouter); dr;
2308              dr = TAILQ_NEXT(dr, dr_entry)) {
2309                 d = (struct in6_defrouter *)buf;
2310                 de = (struct in6_defrouter *)(buf + sizeof(buf));
2311
2312                 if (d + 1 <= de) {
2313                         bzero(d, sizeof(*d));
2314                         d->rtaddr.sin6_family = AF_INET6;
2315                         d->rtaddr.sin6_len = sizeof(d->rtaddr);
2316                         d->rtaddr.sin6_addr = dr->rtaddr;
2317                         error = sa6_recoverscope(&d->rtaddr);
2318                         if (error != 0)
2319                                 return (error);
2320                         d->flags = dr->flags;
2321                         d->rtlifetime = dr->rtlifetime;
2322                         d->expire = dr->expire;
2323                         d->if_index = dr->ifp->if_index;
2324                 } else
2325                         panic("buffer too short");
2326
2327                 error = SYSCTL_OUT(req, buf, sizeof(*d));
2328                 if (error)
2329                         break;
2330         }
2331
2332         return (error);
2333 }
2334
2335 static int
2336 nd6_sysctl_prlist(SYSCTL_HANDLER_ARGS)
2337 {
2338         INIT_VNET_INET6(curvnet);
2339         int error;
2340         char buf[1024] __aligned(4);
2341         struct in6_prefix *p, *pe;
2342         struct nd_prefix *pr;
2343         char ip6buf[INET6_ADDRSTRLEN];
2344
2345         if (req->newptr)
2346                 return EPERM;
2347         error = 0;
2348
2349         for (pr = V_nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
2350                 u_short advrtrs;
2351                 size_t advance;
2352                 struct sockaddr_in6 *sin6, *s6;
2353                 struct nd_pfxrouter *pfr;
2354
2355                 p = (struct in6_prefix *)buf;
2356                 pe = (struct in6_prefix *)(buf + sizeof(buf));
2357
2358                 if (p + 1 <= pe) {
2359                         bzero(p, sizeof(*p));
2360                         sin6 = (struct sockaddr_in6 *)(p + 1);
2361
2362                         p->prefix = pr->ndpr_prefix;
2363                         if (sa6_recoverscope(&p->prefix)) {
2364                                 log(LOG_ERR,
2365                                     "scope error in prefix list (%s)\n",
2366                                     ip6_sprintf(ip6buf, &p->prefix.sin6_addr));
2367                                 /* XXX: press on... */
2368                         }
2369                         p->raflags = pr->ndpr_raf;
2370                         p->prefixlen = pr->ndpr_plen;
2371                         p->vltime = pr->ndpr_vltime;
2372                         p->pltime = pr->ndpr_pltime;
2373                         p->if_index = pr->ndpr_ifp->if_index;
2374                         if (pr->ndpr_vltime == ND6_INFINITE_LIFETIME)
2375                                 p->expire = 0;
2376                         else {
2377                                 time_t maxexpire;
2378
2379                                 /* XXX: we assume time_t is signed. */
2380                                 maxexpire = (-1) &
2381                                     ~((time_t)1 <<
2382                                     ((sizeof(maxexpire) * 8) - 1));
2383                                 if (pr->ndpr_vltime <
2384                                     maxexpire - pr->ndpr_lastupdate) {
2385                                     p->expire = pr->ndpr_lastupdate +
2386                                         pr->ndpr_vltime;
2387                                 } else
2388                                         p->expire = maxexpire;
2389                         }
2390                         p->refcnt = pr->ndpr_refcnt;
2391                         p->flags = pr->ndpr_stateflags;
2392                         p->origin = PR_ORIG_RA;
2393                         advrtrs = 0;
2394                         for (pfr = pr->ndpr_advrtrs.lh_first; pfr;
2395                              pfr = pfr->pfr_next) {
2396                                 if ((void *)&sin6[advrtrs + 1] > (void *)pe) {
2397                                         advrtrs++;
2398                                         continue;
2399                                 }
2400                                 s6 = &sin6[advrtrs];
2401                                 bzero(s6, sizeof(*s6));
2402                                 s6->sin6_family = AF_INET6;
2403                                 s6->sin6_len = sizeof(*sin6);
2404                                 s6->sin6_addr = pfr->router->rtaddr;
2405                                 if (sa6_recoverscope(s6)) {
2406                                         log(LOG_ERR,
2407                                             "scope error in "
2408                                             "prefix list (%s)\n",
2409                                             ip6_sprintf(ip6buf,
2410                                                     &pfr->router->rtaddr));
2411                                 }
2412                                 advrtrs++;
2413                         }
2414                         p->advrtrs = advrtrs;
2415                 } else
2416                         panic("buffer too short");
2417
2418                 advance = sizeof(*p) + sizeof(*sin6) * advrtrs;
2419                 error = SYSCTL_OUT(req, buf, advance);
2420                 if (error)
2421                         break;
2422         }
2423
2424         return (error);
2425 }