1 /*        $NetBSD: nd6.c,v 1.283 2025/03/31 05:55:43 ozaki-r Exp $    */
2 /*        $KAME: nd6.c,v 1.279 2002/06/08 11:16:51 itojun Exp $       */
3 
4 /*
5  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the project nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #include <sys/cdefs.h>
34 __KERNEL_RCSID(0, "$NetBSD: nd6.c,v 1.283 2025/03/31 05:55:43 ozaki-r Exp $");
35 
36 #ifdef _KERNEL_OPT
37 #include "opt_compat_netbsd.h"
38 #include "opt_net_mpsafe.h"
39 #endif
40 
41 #include "bridge.h"
42 #include "carp.h"
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/callout.h>
47 #include <sys/kmem.h>
48 #include <sys/mbuf.h>
49 #include <sys/socket.h>
50 #include <sys/socketvar.h>
51 #include <sys/sockio.h>
52 #include <sys/time.h>
53 #include <sys/kernel.h>
54 #include <sys/errno.h>
55 #include <sys/ioctl.h>
56 #include <sys/syslog.h>
57 #include <sys/queue.h>
58 #include <sys/cprng.h>
59 #include <sys/workqueue.h>
60 #include <sys/compat_stub.h>
61 
62 #include <net/if.h>
63 #include <net/if_dl.h>
64 #include <net/if_llatbl.h>
65 #include <net/if_types.h>
66 #include <net/nd.h>
67 #include <net/route.h>
68 #include <net/if_ether.h>
69 #include <net/if_arc.h>
70 
71 #include <netinet/in.h>
72 #include <netinet6/in6_var.h>
73 #include <netinet/ip6.h>
74 #include <netinet6/ip6_var.h>
75 #include <netinet6/scope6_var.h>
76 #include <netinet6/nd6.h>
77 #include <netinet6/in6_ifattach.h>
78 #include <netinet/icmp6.h>
79 #include <netinet6/icmp6_private.h>
80 
81 #include <compat/netinet6/in6_var.h>
82 #include <compat/netinet6/nd6.h>
83 
84 #define ND6_SLOWTIMER_INTERVAL (60 * 60) /* 1 hour */
85 #define ND6_RECALC_REACHTM_INTERVAL (60 * 120) /* 2 hours */
86 
87 /* timer values */
88 int       nd6_prune = 1;      /* walk list every 1 seconds */
89 int       nd6_useloopback = 1;          /* use loopback interface for local traffic */
90 
91 /* preventing too many loops in ND option parsing */
92 int nd6_maxndopt = 10;        /* max # of ND options allowed */
93 
94 #ifdef ND6_DEBUG
95 int nd6_debug = 1;
96 #else
97 int nd6_debug = 0;
98 #endif
99 
100 krwlock_t nd6_lock __cacheline_aligned;
101 
102 int nd6_recalc_reachtm_interval = ND6_RECALC_REACHTM_INTERVAL;
103 
104 static void nd6_slowtimo(void *);
105 static void nd6_free(struct llentry *, int);
106 static bool nd6_nud_enabled(struct ifnet *);
107 static unsigned int nd6_llinfo_reachable(struct ifnet *);
108 static unsigned int nd6_llinfo_retrans(struct ifnet *);
109 static union l3addr *nd6_llinfo_holdsrc(struct llentry *, union l3addr *);
110 static void nd6_llinfo_output(struct ifnet *, const union l3addr *,
111     const union l3addr *, const uint8_t *, const union l3addr *);
112 static void nd6_llinfo_missed(struct ifnet *, const union l3addr *,
113     int16_t, struct mbuf *);
114 static void nd6_timer(void *);
115 static void nd6_timer_work(struct work *, void *);
116 static struct nd_opt_hdr *nd6_option(union nd_opts *);
117 
118 static callout_t nd6_slowtimo_ch;
119 static callout_t nd6_timer_ch;
120 static struct workqueue       *nd6_timer_wq;
121 static struct work  nd6_timer_wk;
122 
123 struct nd_domain nd6_nd_domain = {
124           .nd_family = AF_INET6,
125           .nd_delay = 5,                /* delay first probe time 5 second */
126           .nd_mmaxtries = 3,  /* maximum unicast query */
127           .nd_umaxtries = 3,  /* maximum multicast query */
128           .nd_retransmultiple = BACKOFF_MULTIPLE,
129           .nd_maxretrans = MAX_RETRANS_TIMER,
130           .nd_maxnudhint = 0, /* max # of subsequent upper layer hints */
131           .nd_maxqueuelen = 1,          /* max # of packets in unresolved ND entries */
132           .nd_nud_enabled = nd6_nud_enabled,
133           .nd_reachable = nd6_llinfo_reachable,
134           .nd_retrans = nd6_llinfo_retrans,
135           .nd_holdsrc = nd6_llinfo_holdsrc,
136           .nd_output = nd6_llinfo_output,
137           .nd_missed = nd6_llinfo_missed,
138           .nd_free = nd6_free,
139 };
140 
141 MALLOC_DEFINE(M_IP6NDP, "NDP", "IPv6 Neighbour Discovery");
142 
143 void
nd6_init(void)144 nd6_init(void)
145 {
146           int error;
147 
148           nd_attach_domain(&nd6_nd_domain);
149           nd6_nbr_init();
150 
151           rw_init(&nd6_lock);
152 
153           callout_init(&nd6_slowtimo_ch, CALLOUT_MPSAFE);
154           callout_init(&nd6_timer_ch, CALLOUT_MPSAFE);
155 
156           error = workqueue_create(&nd6_timer_wq, "nd6_timer",
157               nd6_timer_work, NULL, PRI_SOFTNET, IPL_SOFTNET, WQ_MPSAFE);
158           if (error)
159                     panic("%s: workqueue_create failed (%d)\n", __func__, error);
160 
161           /* start timer */
162           callout_reset(&nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL * hz,
163               nd6_slowtimo, NULL);
164           callout_reset(&nd6_timer_ch, hz, nd6_timer, NULL);
165 }
166 
167 struct nd_kifinfo *
nd6_ifattach(struct ifnet * ifp)168 nd6_ifattach(struct ifnet *ifp)
169 {
170           struct nd_kifinfo *nd;
171 
172           nd = kmem_zalloc(sizeof(*nd), KM_SLEEP);
173 
174           nd->chlim = IPV6_DEFHLIM;
175           nd->basereachable = REACHABLE_TIME;
176           nd->reachable = ND_COMPUTE_RTIME(nd->basereachable);
177           nd->retrans = RETRANS_TIMER;
178 
179           nd->flags = ND6_IFF_PERFORMNUD;
180 
181           /* A loopback interface always has ND6_IFF_AUTO_LINKLOCAL.
182            * A bridge interface should not have ND6_IFF_AUTO_LINKLOCAL
183            * because one of its members should. */
184           if ((ip6_auto_linklocal && ifp->if_type != IFT_BRIDGE) ||
185               (ifp->if_flags & IFF_LOOPBACK))
186                     nd->flags |= ND6_IFF_AUTO_LINKLOCAL;
187 
188           return nd;
189 }
190 
191 void
nd6_ifdetach(struct ifnet * ifp,struct in6_ifextra * ext)192 nd6_ifdetach(struct ifnet *ifp, struct in6_ifextra *ext)
193 {
194 
195           /* Ensure all IPv6 addresses are purged before calling nd6_purge */
196           if_purgeaddrs(ifp, AF_INET6, in6_purgeaddr);
197           nd6_purge(ifp, ext);
198           kmem_free(ext->nd_ifinfo, sizeof(struct nd_kifinfo));
199 }
200 
201 void
nd6_option_init(void * opt,int icmp6len,union nd_opts * ndopts)202 nd6_option_init(void *opt, int icmp6len, union nd_opts *ndopts)
203 {
204 
205           memset(ndopts, 0, sizeof(*ndopts));
206           ndopts->nd_opts_search = (struct nd_opt_hdr *)opt;
207           ndopts->nd_opts_last
208                     = (struct nd_opt_hdr *)(((u_char *)opt) + icmp6len);
209 
210           if (icmp6len == 0) {
211                     ndopts->nd_opts_done = 1;
212                     ndopts->nd_opts_search = NULL;
213           }
214 }
215 
216 /*
217  * Take one ND option.
218  */
219 static struct nd_opt_hdr *
nd6_option(union nd_opts * ndopts)220 nd6_option(union nd_opts *ndopts)
221 {
222           struct nd_opt_hdr *nd_opt;
223           int olen;
224 
225           KASSERT(ndopts != NULL);
226           KASSERT(ndopts->nd_opts_last != NULL);
227 
228           if (ndopts->nd_opts_search == NULL)
229                     return NULL;
230           if (ndopts->nd_opts_done)
231                     return NULL;
232 
233           nd_opt = ndopts->nd_opts_search;
234 
235           /* make sure nd_opt_len is inside the buffer */
236           if ((void *)&nd_opt->nd_opt_len >= (void *)ndopts->nd_opts_last) {
237                     memset(ndopts, 0, sizeof(*ndopts));
238                     return NULL;
239           }
240 
241           olen = nd_opt->nd_opt_len << 3;
242           if (olen == 0) {
243                     /*
244                      * Message validation requires that all included
245                      * options have a length that is greater than zero.
246                      */
247                     memset(ndopts, 0, sizeof(*ndopts));
248                     return NULL;
249           }
250 
251           ndopts->nd_opts_search = (struct nd_opt_hdr *)((char *)nd_opt + olen);
252           if (ndopts->nd_opts_search > ndopts->nd_opts_last) {
253                     /* option overruns the end of buffer, invalid */
254                     memset(ndopts, 0, sizeof(*ndopts));
255                     return NULL;
256           } else if (ndopts->nd_opts_search == ndopts->nd_opts_last) {
257                     /* reached the end of options chain */
258                     ndopts->nd_opts_done = 1;
259                     ndopts->nd_opts_search = NULL;
260           }
261           return nd_opt;
262 }
263 
264 /*
265  * Parse multiple ND options.
266  * This function is much easier to use, for ND routines that do not need
267  * multiple options of the same type.
268  */
269 int
nd6_options(union nd_opts * ndopts)270 nd6_options(union nd_opts *ndopts)
271 {
272           struct nd_opt_hdr *nd_opt;
273           int i = 0;
274 
275           KASSERT(ndopts != NULL);
276           KASSERT(ndopts->nd_opts_last != NULL);
277 
278           if (ndopts->nd_opts_search == NULL)
279                     return 0;
280 
281           while (1) {
282                     nd_opt = nd6_option(ndopts);
283                     if (nd_opt == NULL && ndopts->nd_opts_last == NULL) {
284                               /*
285                                * Message validation requires that all included
286                                * options have a length that is greater than zero.
287                                */
288                               ICMP6_STATINC(ICMP6_STAT_ND_BADOPT);
289                               memset(ndopts, 0, sizeof(*ndopts));
290                               return -1;
291                     }
292 
293                     if (nd_opt == NULL)
294                               goto skip1;
295 
296                     switch (nd_opt->nd_opt_type) {
297                     case ND_OPT_SOURCE_LINKADDR:
298                     case ND_OPT_TARGET_LINKADDR:
299                     case ND_OPT_MTU:
300                     case ND_OPT_REDIRECTED_HEADER:
301                     case ND_OPT_NONCE:
302                               if (ndopts->nd_opt_array[nd_opt->nd_opt_type]) {
303                                         nd6log(LOG_INFO,
304                                             "duplicated ND6 option found (type=%d)\n",
305                                             nd_opt->nd_opt_type);
306                                         /* XXX bark? */
307                               } else {
308                                         ndopts->nd_opt_array[nd_opt->nd_opt_type]
309                                                   = nd_opt;
310                               }
311                               break;
312                     case ND_OPT_PREFIX_INFORMATION:
313                               if (ndopts->nd_opt_array[nd_opt->nd_opt_type] == 0) {
314                                         ndopts->nd_opt_array[nd_opt->nd_opt_type]
315                                                   = nd_opt;
316                               }
317                               ndopts->nd_opts_pi_end =
318                                         (struct nd_opt_prefix_info *)nd_opt;
319                               break;
320                     default:
321                               /*
322                                * Unknown options must be silently ignored,
323                                * to accommodate future extension to the protocol.
324                                */
325                               nd6log(LOG_DEBUG,
326                                   "nd6_options: unsupported option %d - "
327                                   "option ignored\n", nd_opt->nd_opt_type);
328                     }
329 
330 skip1:
331                     i++;
332                     if (i > nd6_maxndopt) {
333                               ICMP6_STATINC(ICMP6_STAT_ND_TOOMANYOPT);
334                               nd6log(LOG_INFO, "too many loop in nd opt\n");
335                               break;
336                     }
337 
338                     if (ndopts->nd_opts_done)
339                               break;
340           }
341 
342           return 0;
343 }
344 
345 /*
346  * Gets source address of the first packet in hold queue
347  * and stores it in @src.
348  * Returns pointer to @src (if hold queue is not empty) or NULL.
349  */
350 static struct in6_addr *
nd6_llinfo_get_holdsrc(struct llentry * ln,struct in6_addr * src)351 nd6_llinfo_get_holdsrc(struct llentry *ln, struct in6_addr *src)
352 {
353           struct ip6_hdr *hip6;
354 
355           if (ln == NULL || ln->ln_hold == NULL)
356                     return NULL;
357 
358           /*
359            * assuming every packet in ln_hold has the same IP header
360            */
361           hip6 = mtod(ln->ln_hold, struct ip6_hdr *);
362           /* XXX pullup? */
363           if (sizeof(*hip6) < ln->ln_hold->m_len)
364                     *src = hip6->ip6_src;
365           else
366                     src = NULL;
367 
368           return src;
369 }
370 
371 static union l3addr *
nd6_llinfo_holdsrc(struct llentry * ln,union l3addr * src)372 nd6_llinfo_holdsrc(struct llentry *ln, union l3addr *src)
373 {
374 
375           if (nd6_llinfo_get_holdsrc(ln, &src->addr6) == NULL)
376                     return NULL;
377           return src;
378 }
379 
380 static void
nd6_llinfo_output(struct ifnet * ifp,const union l3addr * daddr,const union l3addr * taddr,__unused const uint8_t * tlladdr,const union l3addr * hsrc)381 nd6_llinfo_output(struct ifnet *ifp, const union l3addr *daddr,
382     const union l3addr *taddr, __unused const uint8_t *tlladdr,
383     const union l3addr *hsrc)
384 {
385 
386           nd6_ns_output(ifp,
387               daddr != NULL ? &daddr->addr6 : NULL,
388               taddr != NULL ? &taddr->addr6 : NULL,
389               hsrc != NULL ? &hsrc->addr6 : NULL, NULL);
390 }
391 
392 static bool
nd6_nud_enabled(struct ifnet * ifp)393 nd6_nud_enabled(struct ifnet *ifp)
394 {
395           struct nd_kifinfo *ndi = ND_IFINFO(ifp);
396 
397           return ndi->flags & ND6_IFF_PERFORMNUD;
398 }
399 
400 static unsigned int
nd6_llinfo_reachable(struct ifnet * ifp)401 nd6_llinfo_reachable(struct ifnet *ifp)
402 {
403           struct nd_kifinfo *ndi = ND_IFINFO(ifp);
404 
405           return ndi->reachable;
406 }
407 
408 static unsigned int
nd6_llinfo_retrans(struct ifnet * ifp)409 nd6_llinfo_retrans(struct ifnet *ifp)
410 {
411           struct nd_kifinfo *ndi = ND_IFINFO(ifp);
412 
413           return ndi->retrans;
414 }
415 
416 static void
nd6_llinfo_missed(struct ifnet * ifp,const union l3addr * taddr,int16_t type,struct mbuf * m)417 nd6_llinfo_missed(struct ifnet *ifp, const union l3addr *taddr,
418     int16_t type, struct mbuf *m)
419 {
420           struct in6_addr mdaddr6 = zeroin6_addr;
421           struct sockaddr_in6 dsin6, tsin6;
422           struct sockaddr *sa;
423 
424           if (m != NULL) {
425                     if (type == ND_LLINFO_PROBE) {
426                               struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
427 
428                               /* XXX pullup? */
429                               if (sizeof(*ip6) < m->m_len)
430                                         mdaddr6 = ip6->ip6_src;
431                               m_freem(m);
432                     } else
433                               icmp6_error2(m, ICMP6_DST_UNREACH,
434                                   ICMP6_DST_UNREACH_ADDR, 0, ifp, &mdaddr6);
435           }
436           if (!IN6_IS_ADDR_UNSPECIFIED(&mdaddr6)) {
437                     sockaddr_in6_init(&dsin6, &mdaddr6, 0, 0, 0);
438                     sa = sin6tosa(&dsin6);
439           } else
440                     sa = NULL;
441 
442           sockaddr_in6_init(&tsin6, &taddr->addr6, 0, 0, 0);
443           rt_clonedmsg(RTM_MISS, sa, sin6tosa(&tsin6), NULL, ifp);
444 }
445 
446 /*
447  * ND6 timer routine to expire default route list and prefix list
448  */
449 static void
nd6_timer_work(struct work * wk,void * arg)450 nd6_timer_work(struct work *wk, void *arg)
451 {
452           struct in6_ifaddr *ia6, *nia6;
453           int s, bound;
454           struct psref psref;
455 
456           callout_reset(&nd6_timer_ch, nd6_prune * hz,
457               nd6_timer, NULL);
458 
459           SOFTNET_KERNEL_LOCK_UNLESS_NET_MPSAFE();
460 
461           /* expire interface addresses */
462           bound = curlwp_bind();
463           s = pserialize_read_enter();
464           for (ia6 = IN6_ADDRLIST_READER_FIRST(); ia6; ia6 = nia6) {
465                     nia6 = IN6_ADDRLIST_READER_NEXT(ia6);
466 
467                     ia6_acquire(ia6, &psref);
468                     pserialize_read_exit(s);
469 
470                     /* check address lifetime */
471                     if (IFA6_IS_INVALID(ia6)) {
472                               struct ifnet *ifp;
473 
474                               ifp = ia6->ia_ifa.ifa_ifp;
475                               IFNET_LOCK(ifp);
476                               /*
477                                * Need to take the lock first to prevent if_detach
478                                * from running in6_purgeaddr concurrently.
479                                */
480                               if (!if_is_deactivated(ifp)) {
481                                         ia6_release(ia6, &psref);
482                                         in6_purgeaddr(&ia6->ia_ifa);
483                               } else {
484                                         /*
485                                          * ifp is being destroyed, ia6 will be destroyed
486                                          * by if_detach.
487                                          */
488                                         ia6_release(ia6, &psref);
489                               }
490                               ia6 = NULL;
491                               IFNET_UNLOCK(ifp);
492                     } else if (IFA6_IS_DEPRECATED(ia6)) {
493                               int oldflags = ia6->ia6_flags;
494 
495                               if ((oldflags & IN6_IFF_DEPRECATED) == 0) {
496                                         ia6->ia6_flags |= IN6_IFF_DEPRECATED;
497                                         rt_addrmsg(RTM_NEWADDR, (struct ifaddr *)ia6);
498                               }
499                     } else {
500                               /*
501                                * A new RA might have made a deprecated address
502                                * preferred.
503                                */
504                               if (ia6->ia6_flags & IN6_IFF_DEPRECATED) {
505                                         ia6->ia6_flags &= ~IN6_IFF_DEPRECATED;
506                                         rt_addrmsg(RTM_NEWADDR, (struct ifaddr *)ia6);
507                               }
508                     }
509                     s = pserialize_read_enter();
510                     ia6_release(ia6, &psref);
511           }
512           pserialize_read_exit(s);
513           curlwp_bindx(bound);
514 
515           SOFTNET_KERNEL_UNLOCK_UNLESS_NET_MPSAFE();
516 }
517 
518 static void
nd6_timer(void * ignored_arg)519 nd6_timer(void *ignored_arg)
520 {
521 
522           workqueue_enqueue(nd6_timer_wq, &nd6_timer_wk, NULL);
523 }
524 
525 /*
526  * Nuke neighbor cache/prefix/default router management table, right before
527  * ifp goes away.
528  */
529 void
nd6_purge(struct ifnet * ifp,struct in6_ifextra * ext)530 nd6_purge(struct ifnet *ifp, struct in6_ifextra *ext)
531 {
532 
533           /*
534            * During detach, the ND info might be already removed, but
535            * then is explitly passed as argument.
536            * Otherwise get it from ifp->if_afdata.
537            */
538           if (ext == NULL)
539                     ext = ifp->if_afdata[AF_INET6];
540           if (ext == NULL)
541                     return;
542 
543           /*
544            * We may not need to nuke the neighbor cache entries here
545            * because the neighbor cache is kept in if_afdata[AF_INET6].
546            * nd6_purge() is invoked by in6_ifdetach() which is called
547            * from if_detach() where everything gets purged. However
548            * in6_ifdetach is directly called from vlan(4), so we still
549            * need to purge entries here.
550            */
551           if (ext->lltable != NULL)
552                     lltable_purge_entries(ext->lltable);
553 }
554 
555 struct llentry *
nd6_lookup(const struct in6_addr * addr6,const struct ifnet * ifp,bool wlock)556 nd6_lookup(const struct in6_addr *addr6, const struct ifnet *ifp, bool wlock)
557 {
558           struct sockaddr_in6 sin6;
559           struct llentry *ln;
560 
561           sockaddr_in6_init(&sin6, addr6, 0, 0, 0);
562 
563           IF_AFDATA_RLOCK(ifp);
564           ln = lla_lookup(LLTABLE6(ifp), wlock ? LLE_EXCLUSIVE : 0,
565               sin6tosa(&sin6));
566           IF_AFDATA_RUNLOCK(ifp);
567 
568           return ln;
569 }
570 
571 struct llentry *
nd6_create(const struct in6_addr * addr6,const struct ifnet * ifp)572 nd6_create(const struct in6_addr *addr6, const struct ifnet *ifp)
573 {
574           struct sockaddr_in6 sin6;
575           struct llentry *ln;
576           struct rtentry *rt;
577 
578           sockaddr_in6_init(&sin6, addr6, 0, 0, 0);
579           rt = rtalloc1(sin6tosa(&sin6), 0);
580 
581           IF_AFDATA_WLOCK(ifp);
582           ln = lla_create(LLTABLE6(ifp), LLE_EXCLUSIVE, sin6tosa(&sin6), rt);
583           IF_AFDATA_WUNLOCK(ifp);
584 
585           if (rt != NULL)
586                     rt_unref(rt);
587           if (ln != NULL)
588                     ln->ln_state = ND_LLINFO_NOSTATE;
589 
590           return ln;
591 }
592 
593 /*
594  * Test whether a given IPv6 address is a neighbor or not, ignoring
595  * the actual neighbor cache.  The neighbor cache is ignored in order
596  * to not reenter the routing code from within itself.
597  */
598 static int
nd6_is_new_addr_neighbor(const struct sockaddr_in6 * addr,struct ifnet * ifp)599 nd6_is_new_addr_neighbor(const struct sockaddr_in6 *addr, struct ifnet *ifp)
600 {
601           struct ifaddr *dstaddr;
602           int s;
603 
604           /*
605            * A link-local address is always a neighbor.
606            * XXX: a link does not necessarily specify a single interface.
607            */
608           if (IN6_IS_ADDR_LINKLOCAL(&addr->sin6_addr)) {
609                     struct sockaddr_in6 sin6_copy;
610                     u_int32_t zone;
611 
612                     /*
613                      * We need sin6_copy since sa6_recoverscope() may modify the
614                      * content (XXX).
615                      */
616                     sin6_copy = *addr;
617                     if (sa6_recoverscope(&sin6_copy))
618                               return 0; /* XXX: should be impossible */
619                     if (in6_setscope(&sin6_copy.sin6_addr, ifp, &zone))
620                               return 0;
621                     if (sin6_copy.sin6_scope_id == zone)
622                               return 1;
623                     else
624                               return 0;
625           }
626 
627           /*
628            * If the address is assigned on the node of the other side of
629            * a p2p interface, the address should be a neighbor.
630            */
631           s = pserialize_read_enter();
632           dstaddr = ifa_ifwithdstaddr(sin6tocsa(addr));
633           if (dstaddr != NULL) {
634                     if (dstaddr->ifa_ifp == ifp) {
635                               pserialize_read_exit(s);
636                               return 1;
637                     }
638           }
639           pserialize_read_exit(s);
640 
641           return 0;
642 }
643 
644 /*
645  * Detect if a given IPv6 address identifies a neighbor on a given link.
646  * XXX: should take care of the destination of a p2p link?
647  */
648 int
nd6_is_addr_neighbor(const struct sockaddr_in6 * addr,struct ifnet * ifp)649 nd6_is_addr_neighbor(const struct sockaddr_in6 *addr, struct ifnet *ifp)
650 {
651           struct llentry *ln;
652           struct rtentry *rt;
653 
654           /*
655            * A link-local address is always a neighbor.
656            * XXX: a link does not necessarily specify a single interface.
657            */
658           if (IN6_IS_ADDR_LINKLOCAL(&addr->sin6_addr)) {
659                     struct sockaddr_in6 sin6_copy;
660                     u_int32_t zone;
661 
662                     /*
663                      * We need sin6_copy since sa6_recoverscope() may modify the
664                      * content (XXX).
665                      */
666                     sin6_copy = *addr;
667                     if (sa6_recoverscope(&sin6_copy))
668                               return 0; /* XXX: should be impossible */
669                     if (in6_setscope(&sin6_copy.sin6_addr, ifp, &zone))
670                               return 0;
671                     if (sin6_copy.sin6_scope_id == zone)
672                               return 1;
673                     else
674                               return 0;
675           }
676 
677           if (nd6_is_new_addr_neighbor(addr, ifp))
678                     return 1;
679 
680           /*
681            * Even if the address matches none of our addresses, it might be
682            * in the neighbor cache or a connected route.
683            */
684           ln = nd6_lookup(&addr->sin6_addr, ifp, false);
685           if (ln != NULL) {
686                     LLE_RUNLOCK(ln);
687                     return 1;
688           }
689 
690           rt = rtalloc1(sin6tocsa(addr), 0);
691           if (rt == NULL)
692                     return 0;
693 
694           if ((rt->rt_flags & RTF_CONNECTED) && (rt->rt_ifp == ifp
695 #if NBRIDGE > 0
696               || rt->rt_ifp->if_bridge == ifp->if_bridge
697 #endif
698 #if NCARP > 0
699               || (ifp->if_type == IFT_CARP && rt->rt_ifp == ifp->if_carpdev) ||
700               (rt->rt_ifp->if_type == IFT_CARP && rt->rt_ifp->if_carpdev == ifp)||
701               (ifp->if_type == IFT_CARP && rt->rt_ifp->if_type == IFT_CARP &&
702               rt->rt_ifp->if_carpdev == ifp->if_carpdev)
703 #endif
704               )) {
705                     rt_unref(rt);
706                     return 1;
707           }
708           rt_unref(rt);
709 
710           return 0;
711 }
712 
713 /*
714  * Free an nd6 llinfo entry.
715  * Since the function would cause significant changes in the kernel, DO NOT
716  * make it global, unless you have a strong reason for the change, and are sure
717  * that the change is safe.
718  */
719 static void
nd6_free(struct llentry * ln,int gc)720 nd6_free(struct llentry *ln, int gc)
721 {
722           struct ifnet *ifp;
723 
724           KASSERT(ln != NULL);
725           LLE_WLOCK_ASSERT(ln);
726 
727           /*
728            * If the reason for the deletion is just garbage collection,
729            * and the neighbor is an active router, do not delete it.
730            * Instead, reset the GC timer using the router's lifetime.
731            * XXX: the check for ln_state should be redundant,
732            *      but we intentionally keep it just in case.
733            */
734           if (!ip6_forwarding && ln->ln_router &&
735               ln->ln_state == ND_LLINFO_STALE && gc)
736           {
737                     nd_set_timer(ln, ND_TIMER_EXPIRE);
738                     LLE_WUNLOCK(ln);
739                     return;
740           }
741 
742           ifp = ln->lle_tbl->llt_ifp;
743 
744           if (ln->la_flags & LLE_VALID || gc) {
745                     struct sockaddr_in6 sin6;
746                     const char *lladdr;
747 
748                     sockaddr_in6_init(&sin6, &ln->r_l3addr.addr6, 0, 0, 0);
749                     lladdr = ln->la_flags & LLE_VALID ?
750                         (const char *)&ln->ll_addr : NULL;
751                     rt_clonedmsg(RTM_DELETE, NULL, sin6tosa(&sin6), lladdr, ifp);
752           }
753 
754           /*
755            * Save to unlock. We still hold an extra reference and will not
756            * free(9) in llentry_free() if someone else holds one as well.
757            */
758           LLE_WUNLOCK(ln);
759           IF_AFDATA_LOCK(ifp);
760           LLE_WLOCK(ln);
761 
762           lltable_free_entry(LLTABLE6(ifp), ln);
763 
764           IF_AFDATA_UNLOCK(ifp);
765 }
766 
767 /*
768  * Upper-layer reachability hint for Neighbor Unreachability Detection.
769  *
770  * XXX cost-effective methods?
771  */
772 void
nd6_nud_hint(struct rtentry * rt)773 nd6_nud_hint(struct rtentry *rt)
774 {
775           struct llentry *ln;
776           struct ifnet *ifp;
777 
778           if (rt == NULL)
779                     return;
780 
781           ifp = rt->rt_ifp;
782           ln = nd6_lookup(&(satocsin6(rt_getkey(rt)))->sin6_addr, ifp, true);
783           nd_nud_hint(ln);
784 }
785 
786 struct gc_args {
787           int gc_entries;
788           const struct in6_addr *skip_in6;
789 };
790 
791 static int
nd6_purge_entry(struct lltable * llt,struct llentry * ln,void * farg)792 nd6_purge_entry(struct lltable *llt, struct llentry *ln, void *farg)
793 {
794           struct gc_args *args = farg;
795           int *n = &args->gc_entries;
796           const struct in6_addr *skip_in6 = args->skip_in6;
797 
798           if (*n <= 0)
799                     return 0;
800 
801           if (ND_IS_LLINFO_PERMANENT(ln))
802                     return 0;
803 
804           if (IN6_ARE_ADDR_EQUAL(&ln->r_l3addr.addr6, skip_in6))
805                     return 0;
806 
807           LLE_WLOCK(ln);
808           if (ln->ln_state > ND_LLINFO_INCOMPLETE)
809                     ln->ln_state = ND_LLINFO_STALE;
810           else
811                     ln->ln_state = ND_LLINFO_PURGE;
812           nd_set_timer(ln, ND_TIMER_IMMEDIATE);
813           LLE_WUNLOCK(ln);
814 
815           (*n)--;
816           return 0;
817 }
818 
819 static void
nd6_gc_neighbors(struct lltable * llt,const struct in6_addr * in6)820 nd6_gc_neighbors(struct lltable *llt, const struct in6_addr *in6)
821 {
822 
823           if (ip6_neighborgcthresh >= 0 &&
824               lltable_get_entry_count(llt) >= ip6_neighborgcthresh) {
825                     struct gc_args gc_args = {10, in6};
826                     /*
827                      * XXX entries that are "less recently used" should be
828                      * freed first.
829                      */
830                     lltable_foreach_lle(llt, nd6_purge_entry, &gc_args);
831           }
832 }
833 
834 void
nd6_rtrequest(int req,struct rtentry * rt,const struct rt_addrinfo * info)835 nd6_rtrequest(int req, struct rtentry *rt, const struct rt_addrinfo *info)
836 {
837           struct sockaddr *gate = rt->rt_gateway;
838           struct ifnet *ifp = rt->rt_ifp;
839           uint8_t namelen = strlen(ifp->if_xname), addrlen = ifp->if_addrlen;
840           struct ifaddr *ifa;
841 
842           RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
843 
844           if (req == RTM_LLINFO_UPD) {
845                     int rc;
846                     struct in6_addr *in6;
847                     struct in6_addr in6_all;
848                     int anycast;
849 
850                     if ((ifa = info->rti_ifa) == NULL)
851                               return;
852 
853                     in6 = &ifatoia6(ifa)->ia_addr.sin6_addr;
854                     anycast = ifatoia6(ifa)->ia6_flags & IN6_IFF_ANYCAST;
855 
856                     in6_all = in6addr_linklocal_allnodes;
857                     if ((rc = in6_setscope(&in6_all, ifa->ifa_ifp, NULL)) != 0) {
858                               log(LOG_ERR, "%s: failed to set scope %s "
859                                   "(errno=%d)\n", __func__, if_name(ifp), rc);
860                               return;
861                     }
862 
863                     /* XXX don't set Override for proxy addresses */
864                     nd6_na_output(ifa->ifa_ifp, &in6_all, in6,
865                         (anycast ? 0 : ND_NA_FLAG_OVERRIDE)
866 #if 0
867                         | (ip6_forwarding ? ND_NA_FLAG_ROUTER : 0)
868 #endif
869                         , 1, NULL);
870                     return;
871           }
872 
873           if ((rt->rt_flags & RTF_GATEWAY) != 0) {
874                     if (req != RTM_ADD)
875                               return;
876                     /*
877                      * linklayers with particular MTU limitation.
878                      */
879                     switch(ifp->if_type) {
880 #if NARCNET > 0
881                     case IFT_ARCNET:
882                               if (rt->rt_rmx.rmx_mtu > ARC_PHDS_MAXMTU) /* RFC2497 */
883                                         rt->rt_rmx.rmx_mtu = ARC_PHDS_MAXMTU;
884                               break;
885 #endif
886                     }
887                     return;
888           }
889 
890           if (nd6_need_cache(ifp) == 0 && (rt->rt_flags & RTF_HOST) == 0) {
891                     RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
892                     /*
893                      * This is probably an interface direct route for a link
894                      * which does not need neighbor caches (e.g. fe80::%lo0/64).
895                      * We do not need special treatment below for such a route.
896                      * Moreover, the RTF_LLINFO flag which would be set below
897                      * would annoy the ndp(8) command.
898                      */
899                     return;
900           }
901 
902           switch (req) {
903           case RTM_ADD: {
904                     struct psref psref;
905 
906                     RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
907                     /*
908                      * There is no backward compatibility :)
909                      *
910                      * if ((rt->rt_flags & RTF_HOST) == 0 &&
911                      *     SIN(rt_mask(rt))->sin_addr.s_addr != 0xffffffff)
912                      *           rt->rt_flags |= RTF_CLONING;
913                      */
914                     /* XXX should move to route.c? */
915                     if (rt->rt_flags & (RTF_CONNECTED | RTF_LOCAL)) {
916                               union {
917                                         struct sockaddr sa;
918                                         struct sockaddr_dl sdl;
919                                         struct sockaddr_storage ss;
920                               } u;
921                               /*
922                                * Case 1: This route should come from a route to
923                                * interface (RTF_CLONING case) or the route should be
924                                * treated as on-link but is currently not
925                                * (RTF_LLINFO && ln == NULL case).
926                                */
927                               if (sockaddr_dl_init(&u.sdl, sizeof(u.ss),
928                                   ifp->if_index, ifp->if_type,
929                                   NULL, namelen, NULL, addrlen) == NULL) {
930                                         printf("%s.%d: sockaddr_dl_init(, %zu, ) "
931                                             "failed on %s\n", __func__, __LINE__,
932                                             sizeof(u.ss), if_name(ifp));
933                               }
934                               rt_setgate(rt, &u.sa);
935                               gate = rt->rt_gateway;
936                               RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
937                               if (gate == NULL) {
938                                         log(LOG_ERR,
939                                             "%s: rt_setgate failed on %s\n", __func__,
940                                             if_name(ifp));
941                                         break;
942                               }
943 
944                               RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
945                               if ((rt->rt_flags & RTF_CONNECTED) != 0)
946                                         break;
947                     }
948                     RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
949                     /*
950                      * In IPv4 code, we try to annonuce new RTF_ANNOUNCE entry here.
951                      * We don't do that here since llinfo is not ready yet.
952                      *
953                      * There are also couple of other things to be discussed:
954                      * - unsolicited NA code needs improvement beforehand
955                      * - RFC2461 says we MAY send multicast unsolicited NA
956                      *   (7.2.6 paragraph 4), however, it also says that we
957                      *   SHOULD provide a mechanism to prevent multicast NA storm.
958                      *   we don't have anything like it right now.
959                      *   note that the mechanism needs a mutual agreement
960                      *   between proxies, which means that we need to implement
961                      *   a new protocol, or a new kludge.
962                      * - from RFC2461 6.2.4, host MUST NOT send an unsolicited NA.
963                      *   we need to check ip6forwarding before sending it.
964                      *   (or should we allow proxy ND configuration only for
965                      *   routers?  there's no mention about proxy ND from hosts)
966                      */
967 #if 0
968                     /* XXX it does not work */
969                     if (rt->rt_flags & RTF_ANNOUNCE)
970                               nd6_na_output(ifp,
971                                     &satocsin6(rt_getkey(rt))->sin6_addr,
972                                     &satocsin6(rt_getkey(rt))->sin6_addr,
973                                     ip6_forwarding ? ND_NA_FLAG_ROUTER : 0,
974                                     1, NULL);
975 #endif
976 
977                     if ((ifp->if_flags & (IFF_POINTOPOINT | IFF_LOOPBACK)) == 0) {
978                               RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
979                               /*
980                                * Address resolution isn't necessary for a point to
981                                * point link, so we can skip this test for a p2p link.
982                                */
983                               if (gate->sa_family != AF_LINK ||
984                                   gate->sa_len <
985                                   sockaddr_dl_measure(namelen, addrlen)) {
986                                         log(LOG_DEBUG,
987                                             "nd6_rtrequest: bad gateway value: %s\n",
988                                             if_name(ifp));
989                                         break;
990                               }
991                               satosdl(gate)->sdl_type = ifp->if_type;
992                               satosdl(gate)->sdl_index = ifp->if_index;
993                               RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
994                     }
995                     RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
996 
997                     /*
998                      * When called from rt_ifa_addlocal, we cannot depend on that
999                      * the address (rt_getkey(rt)) exits in the address list of the
1000                      * interface. So check RTF_LOCAL instead.
1001                      */
1002                     if (rt->rt_flags & RTF_LOCAL) {
1003                               if (nd6_useloopback)
1004                                         rt->rt_ifp = lo0ifp;          /* XXX */
1005                               break;
1006                     }
1007 
1008                     /*
1009                      * check if rt_getkey(rt) is an address assigned
1010                      * to the interface.
1011                      */
1012                     ifa = (struct ifaddr *)in6ifa_ifpwithaddr_psref(ifp,
1013                         &satocsin6(rt_getkey(rt))->sin6_addr, &psref);
1014                     if (ifa != NULL) {
1015                               if (nd6_useloopback) {
1016                                         rt->rt_ifp = lo0ifp;          /* XXX */
1017                                         /*
1018                                          * Make sure rt_ifa be equal to the ifaddr
1019                                          * corresponding to the address.
1020                                          * We need this because when we refer
1021                                          * rt_ifa->ia6_flags in ip6_input, we assume
1022                                          * that the rt_ifa points to the address instead
1023                                          * of the loopback address.
1024                                          */
1025                                         if (!ISSET(info->rti_flags, RTF_DONTCHANGEIFA)
1026                                             && ifa != rt->rt_ifa)
1027                                                   rt_replace_ifa(rt, ifa);
1028                               }
1029                     } else if (rt->rt_flags & RTF_ANNOUNCE) {
1030                               /* join solicited node multicast for proxy ND */
1031                               if (ifp->if_flags & IFF_MULTICAST) {
1032                                         struct in6_addr llsol;
1033                                         int error;
1034 
1035                                         llsol = satocsin6(rt_getkey(rt))->sin6_addr;
1036                                         llsol.s6_addr32[0] = htonl(0xff020000);
1037                                         llsol.s6_addr32[1] = 0;
1038                                         llsol.s6_addr32[2] = htonl(1);
1039                                         llsol.s6_addr8[12] = 0xff;
1040                                         if (in6_setscope(&llsol, ifp, NULL))
1041                                                   goto out;
1042                                         if (!in6_addmulti(&llsol, ifp, &error, 0)) {
1043                                                   char ip6buf[INET6_ADDRSTRLEN];
1044                                                   nd6log(LOG_ERR, "%s: failed to join "
1045                                                       "%s (errno=%d)\n", if_name(ifp),
1046                                                       IN6_PRINT(ip6buf, &llsol), error);
1047                                         }
1048                               }
1049                     }
1050           out:
1051                     ifa_release(ifa, &psref);
1052                     /*
1053                      * If we have too many cache entries, initiate immediate
1054                      * purging for some entries.
1055                      */
1056                     if (rt->rt_ifp != NULL)
1057                               nd6_gc_neighbors(LLTABLE6(rt->rt_ifp), NULL);
1058                     break;
1059               }
1060 
1061           case RTM_DELETE:
1062                     /* leave from solicited node multicast for proxy ND */
1063                     if ((rt->rt_flags & RTF_ANNOUNCE) != 0 &&
1064                         (ifp->if_flags & IFF_MULTICAST) != 0) {
1065                               struct in6_addr llsol;
1066 
1067                               llsol = satocsin6(rt_getkey(rt))->sin6_addr;
1068                               llsol.s6_addr32[0] = htonl(0xff020000);
1069                               llsol.s6_addr32[1] = 0;
1070                               llsol.s6_addr32[2] = htonl(1);
1071                               llsol.s6_addr8[12] = 0xff;
1072                               if (in6_setscope(&llsol, ifp, NULL) == 0)
1073                                         in6_lookup_and_delete_multi(&llsol, ifp);
1074                     }
1075                     break;
1076           }
1077 }
1078 
1079 static void
nd6_setifflags(struct ifnet * ifp,uint32_t flags)1080 nd6_setifflags(struct ifnet *ifp, uint32_t flags)
1081 {
1082           struct nd_kifinfo *ndi = ND_IFINFO(ifp);
1083           struct ifaddr *ifa;
1084           struct in6_ifaddr *ia;
1085           int s;
1086 
1087           if (ndi->flags & ND6_IFF_IFDISABLED && !(flags & ND6_IFF_IFDISABLED)) {
1088                     /*
1089                      * If the interface is marked as ND6_IFF_IFDISABLED and
1090                      * has a link-local address with IN6_IFF_DUPLICATED,
1091                      * do not clear ND6_IFF_IFDISABLED.
1092                      * See RFC 4862, section 5.4.5.
1093                      */
1094                     bool duplicated_linklocal = false;
1095 
1096                     s = pserialize_read_enter();
1097                     IFADDR_READER_FOREACH(ifa, ifp) {
1098                               if (ifa->ifa_addr->sa_family != AF_INET6)
1099                                         continue;
1100                               ia = (struct in6_ifaddr *)ifa;
1101                               if ((ia->ia6_flags & IN6_IFF_DUPLICATED) &&
1102                                   IN6_IS_ADDR_LINKLOCAL(IA6_IN6(ia)))
1103                               {
1104                                         duplicated_linklocal = true;
1105                                         break;
1106                               }
1107                     }
1108                     pserialize_read_exit(s);
1109 
1110                     if (duplicated_linklocal) {
1111                               flags |= ND6_IFF_IFDISABLED;
1112                               log(LOG_ERR, "%s: Cannot enable an interface"
1113                                   " with a link-local address marked"
1114                                   " duplicate.\n", if_name(ifp));
1115                     } else {
1116                               ndi->flags &= ~ND6_IFF_IFDISABLED;
1117                               if (ifp->if_flags & IFF_UP)
1118                                         in6_if_up(ifp);
1119                     }
1120           } else if (!(ndi->flags & ND6_IFF_IFDISABLED) &&
1121               (flags & ND6_IFF_IFDISABLED))
1122           {
1123                     struct psref psref;
1124                     int bound = curlwp_bind();
1125 
1126                     /* Mark all IPv6 addresses as tentative. */
1127 
1128                     ndi->flags |= ND6_IFF_IFDISABLED;
1129                     s = pserialize_read_enter();
1130                     IFADDR_READER_FOREACH(ifa, ifp) {
1131                               if (ifa->ifa_addr->sa_family != AF_INET6)
1132                                         continue;
1133                               ifa_acquire(ifa, &psref);
1134                               pserialize_read_exit(s);
1135 
1136                               nd6_dad_stop(ifa);
1137 
1138                               ia = (struct in6_ifaddr *)ifa;
1139                               ia->ia6_flags |= IN6_IFF_TENTATIVE;
1140 
1141                               s = pserialize_read_enter();
1142                               ifa_release(ifa, &psref);
1143                     }
1144                     pserialize_read_exit(s);
1145                     curlwp_bindx(bound);
1146           }
1147 
1148           if (flags & ND6_IFF_AUTO_LINKLOCAL) {
1149                     if (!(ndi->flags & ND6_IFF_AUTO_LINKLOCAL)) {
1150                               /* auto_linklocal 0->1 transition */
1151 
1152                               ndi->flags |= ND6_IFF_AUTO_LINKLOCAL;
1153                               in6_ifattach(ifp, NULL);
1154                     } else if (!(flags & ND6_IFF_IFDISABLED) &&
1155                         ifp->if_flags & IFF_UP)
1156                     {
1157                               /*
1158                                * When the IF already has
1159                                * ND6_IFF_AUTO_LINKLOCAL, no link-local
1160                                * address is assigned, and IFF_UP, try to
1161                                * assign one.
1162                                */
1163                               bool haslinklocal = 0;
1164 
1165                               s = pserialize_read_enter();
1166                               IFADDR_READER_FOREACH(ifa, ifp) {
1167                                         if (ifa->ifa_addr->sa_family !=AF_INET6)
1168                                                   continue;
1169                                         ia = (struct in6_ifaddr *)ifa;
1170                                         if (IN6_IS_ADDR_LINKLOCAL(IA6_IN6(ia))){
1171                                                   haslinklocal = true;
1172                                                   break;
1173                                         }
1174                               }
1175                               pserialize_read_exit(s);
1176                               if (!haslinklocal)
1177                                         in6_ifattach(ifp, NULL);
1178                     }
1179           }
1180 
1181           ndi->flags = flags;
1182 }
1183 
1184 int
nd6_ioctl(u_long cmd,void * data,struct ifnet * ifp)1185 nd6_ioctl(u_long cmd, void *data, struct ifnet *ifp)
1186 {
1187 #ifdef OSIOCGIFINFO_IN6_90
1188           struct in6_ndireq90 *ondi = (struct in6_ndireq90 *)data;
1189           struct in6_ndifreq90 *ndif = (struct in6_ndifreq90 *)data;
1190 #define OND         ondi->ndi
1191 #endif
1192           struct in6_ndireq *ndi = (struct in6_ndireq *)data;
1193           struct in6_nbrinfo *nbi = (struct in6_nbrinfo *)data;
1194           struct nd_kifinfo *ifndi = ND_IFINFO(ifp);
1195           int error = 0;
1196 #define ND     ndi->ndi
1197 
1198           switch (cmd) {
1199 #ifdef OSIOCSRTRFLUSH_IN6
1200           case OSIOCGDRLST_IN6:                   /* FALLTHROUGH */
1201           case OSIOCGPRLST_IN6:                   /* FALLTHROUGH */
1202           case OSIOCSNDFLUSH_IN6:                 /* FALLTHROUGH */
1203           case OSIOCSPFXFLUSH_IN6:      /* FALLTHROUGH */
1204           case OSIOCSRTRFLUSH_IN6:      /* FALLTHROUGH */
1205                     break;
1206           case OSIOCGDEFIFACE_IN6:
1207                     ndif->ifindex = 0;
1208                     break;
1209           case OSIOCSDEFIFACE_IN6:
1210                     error = ENOTSUP;
1211                     break;
1212 #endif
1213 #ifdef OSIOCGIFINFO_IN6
1214           case OSIOCGIFINFO_IN6:                  /* FALLTHROUGH */
1215 #endif
1216 #ifdef OSIOCGIFINFO_IN6_90
1217           case OSIOCGIFINFO_IN6_90:
1218                     memset(&OND, 0, sizeof(OND));
1219                     OND.initialized = 1;
1220                     OND.chlim = ifndi->chlim;
1221                     OND.basereachable = ifndi->basereachable;
1222                     OND.retrans = ifndi->retrans;
1223                     OND.flags = ifndi->flags;
1224                     break;
1225           case OSIOCSIFINFO_IN6_90:
1226                     /* Allow userland to set Neighbor Unreachability Detection
1227                      * timers. */
1228                     if (OND.chlim != 0)
1229                               ifndi->chlim = OND.chlim;
1230                     if (OND.basereachable != 0 &&
1231                         OND.basereachable != ifndi->basereachable)
1232                     {
1233                               ifndi->basereachable = OND.basereachable;
1234                               ifndi->reachable = ND_COMPUTE_RTIME(OND.basereachable);
1235                     }
1236                     if (OND.retrans != 0)
1237                               ifndi->retrans = OND.retrans;
1238                     /* Retain the old behaviour .... */
1239                     /* FALLTHROUGH */
1240           case OSIOCSIFINFO_FLAGS_90:
1241                     nd6_setifflags(ifp, OND.flags);
1242                     break;
1243 #undef OND
1244 #endif
1245           case SIOCGIFINFO_IN6:
1246                     ND.chlim = ifndi->chlim;
1247                     ND.basereachable = ifndi->basereachable;
1248                     ND.retrans = ifndi->retrans;
1249                     ND.flags = ifndi->flags;
1250                     break;
1251           case SIOCSIFINFO_IN6:
1252                     /* Allow userland to set Neighbor Unreachability Detection
1253                      * timers. */
1254                     if (ND.chlim != 0)
1255                               ifndi->chlim = ND.chlim;
1256                     if (ND.basereachable != 0 &&
1257                         ND.basereachable != ifndi->basereachable)
1258                     {
1259                               ifndi->basereachable = ND.basereachable;
1260                               ifndi->reachable = ND_COMPUTE_RTIME(ND.basereachable);
1261                     }
1262                     if (ND.retrans != 0)
1263                               ifndi->retrans = ND.retrans;
1264                     break;
1265           case SIOCSIFINFO_FLAGS:
1266                     nd6_setifflags(ifp, ND.flags);
1267                     break;
1268 #undef ND
1269           case SIOCGNBRINFO_IN6:
1270           {
1271                     struct llentry *ln;
1272                     struct in6_addr nb_addr = nbi->addr; /* make local for safety */
1273 
1274                     if ((error = in6_setscope(&nb_addr, ifp, NULL)) != 0)
1275                               return error;
1276 
1277                     ln = nd6_lookup(&nb_addr, ifp, false);
1278                     if (ln == NULL) {
1279                               error = EINVAL;
1280                               break;
1281                     }
1282                     nbi->state = ln->ln_state;
1283                     nbi->asked = ln->ln_asked;
1284                     nbi->isrouter = ln->ln_router;
1285                     nbi->expire = ln->ln_expire ?
1286                         time_mono_to_wall(ln->ln_expire) : 0;
1287                     LLE_RUNLOCK(ln);
1288 
1289                     break;
1290           }
1291           }
1292           return error;
1293 }
1294 
1295 void
nd6_llinfo_release_pkts(struct llentry * ln,struct ifnet * ifp)1296 nd6_llinfo_release_pkts(struct llentry *ln, struct ifnet *ifp)
1297 {
1298           struct mbuf *m_hold, *m_hold_next;
1299           struct sockaddr_in6 sin6;
1300 
1301           LLE_WLOCK_ASSERT(ln);
1302 
1303           sockaddr_in6_init(&sin6, &ln->r_l3addr.addr6, 0, 0, 0);
1304 
1305           m_hold = ln->la_hold, ln->la_hold = NULL, ln->la_numheld = 0;
1306 
1307           LLE_ADDREF(ln);
1308           LLE_WUNLOCK(ln);
1309           for (; m_hold != NULL; m_hold = m_hold_next) {
1310                     m_hold_next = m_hold->m_nextpkt;
1311                     m_hold->m_nextpkt = NULL;
1312 
1313                     /*
1314                      * we assume ifp is not a p2p here, so
1315                      * just set the 2nd argument as the
1316                      * 1st one.
1317                      */
1318                     ip6_if_output(ifp, ifp, m_hold, &sin6, NULL);
1319           }
1320           LLE_WLOCK(ln);
1321           LLE_REMREF(ln);
1322 }
1323 
1324 /*
1325  * Create neighbor cache entry and cache link-layer address,
1326  * on reception of inbound ND6 packets.  (RS/RA/NS/redirect)
1327  */
1328 void
nd6_cache_lladdr(struct ifnet * ifp,struct in6_addr * from,char * lladdr,int lladdrlen,int type,int code)1329 nd6_cache_lladdr(
1330     struct ifnet *ifp,
1331     struct in6_addr *from,
1332     char *lladdr,
1333     int lladdrlen,
1334     int type,       /* ICMP6 type */
1335     int code        /* type dependent information */
1336 )
1337 {
1338           struct llentry *ln = NULL;
1339           int is_newentry;
1340           int do_update;
1341           int olladdr;
1342           int llchange;
1343           int newstate = 0;
1344 
1345           KASSERT(ifp != NULL);
1346           KASSERT(from != NULL);
1347 
1348           /* nothing must be updated for unspecified address */
1349           if (IN6_IS_ADDR_UNSPECIFIED(from))
1350                     return;
1351 
1352           /*
1353            * Validation about ifp->if_addrlen and lladdrlen must be done in
1354            * the caller.
1355            *
1356            * XXX If the link does not have link-layer adderss, what should
1357            * we do? (ifp->if_addrlen == 0)
1358            * Spec says nothing in sections for RA, RS and NA.  There's small
1359            * description on it in NS section (RFC 2461 7.2.3).
1360            */
1361 
1362           ln = nd6_lookup(from, ifp, true);
1363           if (ln == NULL) {
1364 #if 0
1365                     /* nothing must be done if there's no lladdr */
1366                     if (!lladdr || !lladdrlen)
1367                               return NULL;
1368 #endif
1369 
1370                     ln = nd6_create(from, ifp);
1371                     is_newentry = 1;
1372           } else {
1373                     /* do nothing if static ndp is set */
1374                     if (ln->la_flags & LLE_STATIC) {
1375                               LLE_WUNLOCK(ln);
1376                               return;
1377                     }
1378                     is_newentry = 0;
1379           }
1380 
1381           if (ln == NULL)
1382                     return;
1383 
1384           olladdr = (ln->la_flags & LLE_VALID) ? 1 : 0;
1385           if (olladdr && lladdr) {
1386                     llchange = memcmp(lladdr, &ln->ll_addr, ifp->if_addrlen);
1387           } else
1388                     llchange = 0;
1389 
1390           /*
1391            * newentry olladdr  lladdr  llchange   (*=record)
1392            *        0         n         n         --        (1)
1393            *        0         y         n         --        (2)
1394            *        0         n         y         --        (3) * STALE
1395            *        0         y         y         n         (4) *
1396            *        0         y         y         y         (5) * STALE
1397            *        1         --        n         --        (6)   NOSTATE(= PASSIVE)
1398            *        1         --        y         --        (7) * STALE
1399            */
1400 
1401           if (lladdr) {                 /* (3-5) and (7) */
1402                     /*
1403                      * Record source link-layer address
1404                      * XXX is it dependent to ifp->if_type?
1405                      */
1406                     memcpy(&ln->ll_addr, lladdr, ifp->if_addrlen);
1407                     ln->la_flags |= LLE_VALID;
1408           }
1409 
1410           if (!is_newentry) {
1411                     if ((!olladdr && lladdr) ||             /* (3) */
1412                         (olladdr && lladdr && llchange)) {  /* (5) */
1413                               do_update = 1;
1414                               newstate = ND_LLINFO_STALE;
1415                     } else                                            /* (1-2,4) */
1416                               do_update = 0;
1417           } else {
1418                     do_update = 1;
1419                     if (lladdr == NULL)                     /* (6) */
1420                               newstate = ND_LLINFO_NOSTATE;
1421                     else                                              /* (7) */
1422                               newstate = ND_LLINFO_STALE;
1423           }
1424 
1425           if (do_update) {
1426                     /*
1427                      * Update the state of the neighbor cache.
1428                      */
1429                     ln->ln_state = newstate;
1430 
1431                     if (ln->ln_state == ND_LLINFO_STALE) {
1432                               /*
1433                                * XXX: since nd6_output() below will cause
1434                                * state tansition to DELAY and reset the timer,
1435                                * we must set the timer now, although it is actually
1436                                * meaningless.
1437                                */
1438                               nd_set_timer(ln, ND_TIMER_GC);
1439 
1440                               nd6_llinfo_release_pkts(ln, ifp);
1441                     } else if (ln->ln_state == ND_LLINFO_INCOMPLETE) {
1442                               /* probe right away */
1443                               nd_set_timer(ln, ND_TIMER_IMMEDIATE);
1444                     }
1445           }
1446 
1447           /*
1448            * ICMP6 type dependent behavior.
1449            *
1450            * NS: clear IsRouter if new entry
1451            * RS: clear IsRouter
1452            * RA: set IsRouter if there's lladdr
1453            * redir: clear IsRouter if new entry
1454            *
1455            * RA case, (1):
1456            * The spec says that we must set IsRouter in the following cases:
1457            * - If lladdr exist, set IsRouter.  This means (1-5).
1458            * - If it is old entry (!newentry), set IsRouter.  This means (7).
1459            * So, based on the spec, in (1-5) and (7) cases we must set IsRouter.
1460            * A question arises for (1) case.  (1) case has no lladdr in the
1461            * neighbor cache, this is similar to (6).
1462            * This case is rare but we figured that we MUST NOT set IsRouter.
1463            *
1464            * newentry olladdr  lladdr  llchange       NS  RS  RA      redir
1465            *                                                                    D R
1466            *        0         n         n         --        (1)       c   ?     s
1467            *        0         y         n         --        (2)       c   s     s
1468            *        0         n         y         --        (3)       c   s     s
1469            *        0         y         y         n         (4)       c   s     s
1470            *        0         y         y         y         (5)       c   s     s
1471            *        1         --        n         --        (6) c     c         c s
1472            *        1         --        y         --        (7) c     c   s     c s
1473            *
1474            *                                                (c=clear s=set)
1475            */
1476           switch (type & 0xff) {
1477           case ND_NEIGHBOR_SOLICIT:
1478                     /*
1479                      * New entry must have is_router flag cleared.
1480                      */
1481                     if (is_newentry)    /* (6-7) */
1482                               ln->ln_router = 0;
1483                     break;
1484           case ND_REDIRECT:
1485                     /*
1486                      * If the icmp is a redirect to a better router, always set the
1487                      * is_router flag.  Otherwise, if the entry is newly created,
1488                      * clear the flag.  [RFC 2461, sec 8.3]
1489                      */
1490                     if (code == ND_REDIRECT_ROUTER)
1491                               ln->ln_router = 1;
1492                     else if (is_newentry) /* (6-7) */
1493                               ln->ln_router = 0;
1494                     break;
1495           case ND_ROUTER_SOLICIT:
1496                     /*
1497                      * is_router flag must always be cleared.
1498                      */
1499                     ln->ln_router = 0;
1500                     break;
1501           case ND_ROUTER_ADVERT:
1502                     /*
1503                      * Mark an entry with lladdr as a router.
1504                      */
1505                     if ((!is_newentry && (olladdr || lladdr)) ||      /* (2-5) */
1506                         (is_newentry && lladdr)) {                              /* (7) */
1507                               ln->ln_router = 1;
1508                     }
1509                     break;
1510           }
1511 
1512           if (do_update && lladdr != NULL) {
1513                     struct sockaddr_in6 sin6;
1514 
1515                     sockaddr_in6_init(&sin6, from, 0, 0, 0);
1516                     rt_clonedmsg(is_newentry ? RTM_ADD : RTM_CHANGE,
1517                         NULL, sin6tosa(&sin6), lladdr, ifp);
1518           }
1519 
1520           if (ln != NULL)
1521                     LLE_WUNLOCK(ln);
1522 
1523           /*
1524            * If we have too many cache entries, initiate immediate
1525            * purging for some entries.
1526            */
1527           if (is_newentry)
1528                     nd6_gc_neighbors(LLTABLE6(ifp), &ln->r_l3addr.addr6);
1529 }
1530 
1531 static void
nd6_slowtimo(void * ignored_arg)1532 nd6_slowtimo(void *ignored_arg)
1533 {
1534           struct nd_kifinfo *ndi;
1535           struct ifnet *ifp;
1536           struct psref psref;
1537           int s;
1538 
1539           SOFTNET_KERNEL_LOCK_UNLESS_NET_MPSAFE();
1540           callout_reset(&nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL * hz,
1541               nd6_slowtimo, NULL);
1542 
1543           s = pserialize_read_enter();
1544           IFNET_READER_FOREACH(ifp) {
1545                     ndi = ND_IFINFO(ifp);
1546                     if (ndi->basereachable && /* already initialized */
1547                         (ndi->recalctm -= ND6_SLOWTIMER_INTERVAL) <= 0) {
1548                               if_acquire(ifp, &psref);
1549                               pserialize_read_exit(s);
1550                               /*
1551                                * Since reachable time rarely changes by router
1552                                * advertisements, we SHOULD insure that a new random
1553                                * value gets recomputed at least once every few hours.
1554                                * (RFC 2461, 6.3.4)
1555                                */
1556                               ndi->recalctm = nd6_recalc_reachtm_interval;
1557                               ndi->reachable = ND_COMPUTE_RTIME(ndi->basereachable);
1558                               s = pserialize_read_enter();
1559                               if_release(ifp, &psref);
1560                     }
1561           }
1562           pserialize_read_exit(s);
1563 
1564           SOFTNET_KERNEL_UNLOCK_UNLESS_NET_MPSAFE();
1565 }
1566 
1567 /*
1568  * Return 0 if a neighbor cache is found. Return EWOULDBLOCK if a cache is not
1569  * found and trying to resolve a neighbor; in this case the mbuf is queued in
1570  * the list. Otherwise return errno after freeing the mbuf.
1571  */
1572 int
nd6_resolve(struct ifnet * ifp,const struct rtentry * rt,struct mbuf * m,const struct sockaddr * _dst,uint8_t * lldst,size_t dstsize)1573 nd6_resolve(struct ifnet *ifp, const struct rtentry *rt, struct mbuf *m,
1574     const struct sockaddr *_dst, uint8_t *lldst, size_t dstsize)
1575 {
1576           struct llentry *ln = NULL;
1577           bool created = false;
1578           const struct sockaddr_in6 *dst = satocsin6(_dst);
1579           int error;
1580           struct nd_kifinfo *ndi = ND_IFINFO(ifp);
1581 
1582           /* discard the packet if IPv6 operation is disabled on the interface */
1583           if (ndi->flags & ND6_IFF_IFDISABLED) {
1584                     m_freem(m);
1585                     return ENETDOWN; /* better error? */
1586           }
1587 
1588           /*
1589            * Address resolution or Neighbor Unreachability Detection
1590            * for the next hop.
1591            * At this point, the destination of the packet must be a unicast
1592            * or an anycast address(i.e. not a multicast).
1593            */
1594 
1595           /* Look up the neighbor cache for the nexthop */
1596           ln = nd6_lookup(&dst->sin6_addr, ifp, false);
1597 
1598           if (ln != NULL && (ln->la_flags & LLE_VALID) != 0 &&
1599               /* Only STALE needs to go the slow path to change its state. */
1600               (ln->ln_state == ND_LLINFO_REACHABLE ||
1601                ln->ln_state == ND_LLINFO_DELAY ||
1602                ln->ln_state == ND_LLINFO_PROBE)) {
1603                     /* Fast path */
1604                     memcpy(lldst, &ln->ll_addr, MIN(dstsize, ifp->if_addrlen));
1605                     LLE_RUNLOCK(ln);
1606                     return 0;
1607           }
1608           if (ln != NULL)
1609                     LLE_RUNLOCK(ln);
1610 
1611           /* Slow path */
1612           ln = nd6_lookup(&dst->sin6_addr, ifp, true);
1613           if (ln == NULL && nd6_is_addr_neighbor(dst, ifp))  {
1614                     /*
1615                      * Since nd6_is_addr_neighbor() internally calls nd6_lookup(),
1616                      * the condition below is not very efficient.  But we believe
1617                      * it is tolerable, because this should be a rare case.
1618                      */
1619                     ln = nd6_create(&dst->sin6_addr, ifp);
1620                     if (ln == NULL) {
1621                               char ip6buf[INET6_ADDRSTRLEN];
1622                               log(LOG_DEBUG,
1623                                   "%s: can't allocate llinfo for %s "
1624                                   "(ln=%p, rt=%p)\n", __func__,
1625                                   IN6_PRINT(ip6buf, &dst->sin6_addr), ln, rt);
1626                               m_freem(m);
1627                               return ENOBUFS;
1628                     }
1629                     created = true;
1630           }
1631 
1632           if (ln == NULL) {
1633                     m_freem(m);
1634                     return ENETDOWN; /* better error? */
1635           }
1636 
1637           error = nd_resolve(ln, rt, m, lldst, dstsize);
1638 
1639           if (created)
1640                     nd6_gc_neighbors(LLTABLE6(ifp), &dst->sin6_addr);
1641 
1642           return error;
1643 }
1644 
1645 int
nd6_need_cache(struct ifnet * ifp)1646 nd6_need_cache(struct ifnet *ifp)
1647 {
1648           /*
1649            * XXX: we currently do not make neighbor cache on any interface
1650            * other than ARCnet, Ethernet, and GIF.
1651            *
1652            * RFC2893 says:
1653            * - unidirectional tunnels needs no ND
1654            */
1655           switch (ifp->if_type) {
1656           case IFT_ARCNET:
1657           case IFT_ETHER:
1658           case IFT_IEEE1394:
1659           case IFT_CARP:
1660           case IFT_GIF:                 /* XXX need more cases? */
1661           case IFT_IPSEC:
1662           case IFT_PPP:
1663           case IFT_TUNNEL:
1664                     return 1;
1665           default:
1666                     return 0;
1667           }
1668 }
1669 
1670 int
nd6_sysctl(int name,void * oldp,size_t * oldlenp,void * newp,size_t newlen)1671 nd6_sysctl(
1672     int name,
1673     void *oldp,     /* syscall arg, need copyout */
1674     size_t *oldlenp,
1675     void *newp,     /* syscall arg, need copyin */
1676     size_t newlen
1677 )
1678 {
1679           int error;
1680 
1681           if (newp)
1682                     return EPERM;
1683 
1684           switch (name) {
1685 
1686 /* call the nd6 compat_90 hook to validate the nd6-related names */
1687           case OICMPV6CTL_ND6_DRLIST: /* FALLTHROUGH */
1688           case OICMPV6CTL_ND6_PRLIST:
1689                     MODULE_HOOK_CALL(net_inet6_nd_90_hook, (name), ENOPROTOOPT,
1690                         error);
1691                     if (error == 0)
1692                               *oldlenp = 0;
1693                     return error;
1694 
1695           case ICMPV6CTL_ND6_MAXQLEN:
1696                     return 0;
1697           default:
1698                     return ENOPROTOOPT;
1699           }
1700 }
1701