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