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