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