icmp6: Fix possible mbuf leakage
[dragonfly.git] / sys / netinet6 / nd6_nbr.c
1 /*      $FreeBSD: src/sys/netinet6/nd6_nbr.c,v 1.4.2.6 2003/01/23 21:06:47 sam Exp $    */
2 /*      $KAME: nd6_nbr.c,v 1.86 2002/01/21 02:33:04 jinmei Exp $        */
3
4 /*
5  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the project nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32
33 #include "opt_inet.h"
34 #include "opt_inet6.h"
35 #include "opt_ipsec.h"
36 #include "opt_carp.h"
37
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/malloc.h>
41 #include <sys/mbuf.h>
42 #include <sys/socket.h>
43 #include <sys/sockio.h>
44 #include <sys/time.h>
45 #include <sys/kernel.h>
46 #include <sys/errno.h>
47 #include <sys/syslog.h>
48 #include <sys/queue.h>
49 #include <sys/callout.h>
50 #include <sys/mutex.h>
51
52 #include <sys/thread2.h>
53 #include <sys/mutex2.h>
54
55 #include <net/if.h>
56 #include <net/if_types.h>
57 #include <net/if_dl.h>
58 #include <net/route.h>
59 #include <net/netisr2.h>
60 #include <net/netmsg2.h>
61
62 #include <netinet/in.h>
63 #include <netinet/in_var.h>
64 #include <netinet6/in6_var.h>
65 #include <netinet/ip6.h>
66 #include <netinet6/ip6_var.h>
67 #include <netinet6/nd6.h>
68 #include <netinet/icmp6.h>
69
70 #ifdef IPSEC
71 #include <netinet6/ipsec.h>
72 #ifdef INET6
73 #include <netinet6/ipsec6.h>
74 #endif
75 #endif
76
77 #include <net/net_osdep.h>
78
79 #ifdef CARP
80 #include <netinet/ip_carp.h>
81 #endif
82
83
84 #define SDL(s) ((struct sockaddr_dl *)s)
85
86 struct dadq;
87 static struct dadq *nd6_dad_find(struct ifaddr *);
88 static void nd6_dad_starttimer(struct dadq *, int);
89 static void nd6_dad_stoptimer(struct dadq *);
90 static void nd6_dad_timer(void *);
91 static void nd6_dad_timer_handler(netmsg_t);
92 static void nd6_dad_ns_output(struct dadq *);
93 static void nd6_dad_ns_input(struct ifaddr *);
94 static void nd6_dad_na_input(struct ifaddr *);
95 static struct dadq *nd6_dad_create(struct ifaddr *);
96 static void nd6_dad_destroy(struct dadq *);
97 static void nd6_dad_duplicated(struct ifaddr *);
98
99 static int dad_ignore_ns = 0;   /* ignore NS in DAD - specwise incorrect*/
100 static int dad_maxtry = 15;     /* max # of *tries* to transmit DAD packet */
101
102 /*
103  * Input an Neighbor Solicitation Message.
104  *
105  * Based on RFC 2461
106  * Based on RFC 2462 (duplicated address detection)
107  */
108 void
109 nd6_ns_input(struct mbuf *m, int off, int icmp6len)
110 {
111         struct ifnet *ifp = m->m_pkthdr.rcvif;
112         struct ifnet *cmpifp;
113         struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
114         struct nd_neighbor_solicit *nd_ns;
115         struct in6_addr saddr6 = ip6->ip6_src;
116         struct in6_addr daddr6 = ip6->ip6_dst;
117         struct in6_addr taddr6;
118         struct in6_addr myaddr6;
119         char *lladdr = NULL;
120         struct ifaddr *ifa = NULL;
121         int lladdrlen = 0;
122         int anycast = 0, proxy = 0, tentative = 0;
123         int tlladdr;
124         union nd_opts ndopts;
125         struct sockaddr_dl *proxydl = NULL;
126
127         /*
128          * Collapse interfaces to the bridge for comparison and
129          * mac (llinfo) purposes.
130          */
131         cmpifp = ifp;
132         if (ifp->if_bridge)
133                 cmpifp = ifp->if_bridge;
134
135 #ifndef PULLDOWN_TEST
136         IP6_EXTHDR_CHECK(m, off, icmp6len,);
137         nd_ns = (struct nd_neighbor_solicit *)((caddr_t)ip6 + off);
138 #else
139         IP6_EXTHDR_GET(nd_ns, struct nd_neighbor_solicit *, m, off, icmp6len);
140         if (nd_ns == NULL) {
141                 icmp6stat.icp6s_tooshort++;
142                 return;
143         }
144 #endif
145         ip6 = mtod(m, struct ip6_hdr *); /* adjust pointer for safety */
146         taddr6 = nd_ns->nd_ns_target;
147
148         if (ip6->ip6_hlim != 255) {
149                 nd6log((LOG_ERR,
150                     "nd6_ns_input: invalid hlim (%d) from %s to %s on %s\n",
151                     ip6->ip6_hlim, ip6_sprintf(&ip6->ip6_src),
152                     ip6_sprintf(&ip6->ip6_dst), if_name(ifp)));
153                 goto bad;
154         }
155
156         if (IN6_IS_ADDR_UNSPECIFIED(&saddr6)) {
157                 /* dst has to be solicited node multicast address. */
158                 if (daddr6.s6_addr16[0] == IPV6_ADDR_INT16_MLL
159                     /* don't check ifindex portion */
160                     && daddr6.s6_addr32[1] == 0
161                     && daddr6.s6_addr32[2] == IPV6_ADDR_INT32_ONE
162                     && daddr6.s6_addr8[12] == 0xff) {
163                         ; /* good */
164                 } else {
165                         nd6log((LOG_INFO, "nd6_ns_input: bad DAD packet "
166                                 "(wrong ip6 dst)\n"));
167                         goto bad;
168                 }
169         } else if (!nd6_onlink_ns_rfc4861) {
170                 /*
171                  * Make sure the source address is from a neighbor's address.
172                  *
173                  * XXX probably only need to check cmpifp.
174                  */
175                 if (in6ifa_ifplocaladdr(cmpifp, &saddr6) == NULL &&
176                     in6ifa_ifplocaladdr(ifp, &saddr6) == NULL) {
177                         nd6log((LOG_INFO, "nd6_ns_input: "
178                             "NS packet from non-neighbor\n"));
179                         goto bad;
180                 }
181         }
182
183         if (IN6_IS_ADDR_MULTICAST(&taddr6)) {
184                 nd6log((LOG_INFO, "nd6_ns_input: bad NS target (multicast)\n"));
185                 goto bad;
186         }
187
188         if (IN6_IS_SCOPE_LINKLOCAL(&taddr6))
189                 taddr6.s6_addr16[1] = htons(ifp->if_index);
190
191         icmp6len -= sizeof(*nd_ns);
192         nd6_option_init(nd_ns + 1, icmp6len, &ndopts);
193         if (nd6_options(&ndopts) < 0) {
194                 nd6log((LOG_INFO,
195                     "nd6_ns_input: invalid ND option, ignored\n"));
196                 /* nd6_options have incremented stats */
197                 goto freeit;
198         }
199
200         if (ndopts.nd_opts_src_lladdr) {
201                 lladdr = (char *)(ndopts.nd_opts_src_lladdr + 1);
202                 lladdrlen = ndopts.nd_opts_src_lladdr->nd_opt_len << 3;
203         }
204
205         if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src) && lladdr) {
206                 nd6log((LOG_INFO, "nd6_ns_input: bad DAD packet "
207                     "(link-layer address option)\n"));
208                 goto bad;
209         }
210
211         /*
212          * Attaching target link-layer address to the NA?
213          * (RFC 2461 7.2.4)
214          *
215          * NS IP dst is unicast/anycast                 MUST NOT add
216          * NS IP dst is solicited-node multicast        MUST add
217          *
218          * In implementation, we add target link-layer address by default.
219          * We do not add one in MUST NOT cases.
220          */
221 #if 0 /* too much! */
222         ifa = (struct ifaddr *)in6ifa_ifpwithaddr(ifp, &daddr6);
223         if (ifa && (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_ANYCAST))
224                 tlladdr = 0;
225         else
226 #endif
227         if (!IN6_IS_ADDR_MULTICAST(&daddr6))
228                 tlladdr = 0;
229         else
230                 tlladdr = 1;
231
232         /*
233          * Target address (taddr6) must be either:
234          * (1) Valid unicast/anycast address for my receiving interface.
235          * (2) Unicast or anycast address for which I'm offering proxy
236          *     service.
237          * (3) "tentative" address on which DAD is being performed.
238          */
239         /* (1) and (3) check. */
240 #ifdef CARP
241         if (ifp->if_carp)
242                 ifa = carp_iamatch6(ifp->if_carp, &taddr6);
243         if (!ifa)
244                 ifa = (struct ifaddr *)in6ifa_ifpwithaddr(ifp, &taddr6);
245 #else
246         ifa = (struct ifaddr *)in6ifa_ifpwithaddr(ifp, &taddr6);
247 #endif
248
249         /*
250          * (2) Check proxying.  Requires ip6_forwarding to be turned on.
251          *
252          *     If the packet is anycast the target route must be on a
253          *     different interface because the anycast will get anything
254          *     on the current interface.
255          *
256          *     If the packet is unicast the target route may be on the
257          *     same interface.  If the gateway is a (typically manually
258          *     configured) link address we can directly offer it.
259          *     XXX for now we don't do this but instead offer ours and
260          *     presumably relay.
261          *
262          *     WARNING! Since this is a subnet proxy the interface proxying
263          *     the ND6 must be in promiscuous mode or it will not see the
264          *     solicited multicast requests for various hosts being proxied.
265          *
266          *     WARNING! Since this is a subnet proxy we have to treat bridge
267          *     interfaces as being the bridge itself so we do not proxy-nd6
268          *     between bridge interfaces (which are effectively switched).
269          *
270          *     (In the specific-host-proxy case via RTF_ANNOUNCE, which is
271          *     a bitch to configure, a specific multicast route is already
272          *     added for that host <-- NOT RECOMMENDED).
273          */
274         if (!ifa && ip6_forwarding) {
275                 struct rtentry *rt;
276                 struct sockaddr_in6 tsin6;
277                 struct ifnet *rtifp;
278
279                 bzero(&tsin6, sizeof tsin6);
280                 tsin6.sin6_len = sizeof(struct sockaddr_in6);
281                 tsin6.sin6_family = AF_INET6;
282                 tsin6.sin6_addr = taddr6;
283
284                 rt = rtpurelookup((struct sockaddr *)&tsin6);
285                 rtifp = rt ? rt->rt_ifp : NULL;
286                 if (rtifp && rtifp->if_bridge)
287                         rtifp = rtifp->if_bridge;
288
289                 if (rt != NULL &&
290                     (cmpifp != rtifp ||
291                      (cmpifp == rtifp && (m->m_flags & M_MCAST) == 0))
292                 ) {
293                         ifa = (struct ifaddr *)in6ifa_ifpforlinklocal(cmpifp,
294                                 IN6_IFF_NOTREADY|IN6_IFF_ANYCAST);
295                         nd6log((LOG_INFO,
296                                "nd6_ns_input: nd6 proxy %s(%s)<-%s ifa %p\n",
297                                if_name(cmpifp), if_name(ifp),
298                                if_name(rtifp), ifa));
299                         if (ifa) {
300                                 proxy = 1;
301                                 /*
302                                  * Manual link address on same interface
303                                  * w/announce flag will proxy-arp using
304                                  * target mac, else our mac is used.
305                                  */
306                                 if (cmpifp == rtifp &&
307                                     (rt->rt_flags & RTF_ANNOUNCE) &&
308                                     rt->rt_gateway->sa_family == AF_LINK) {
309                                         proxydl = SDL(rt->rt_gateway);
310                                 }
311                         }
312                 }
313                 if (rt != NULL)
314                         --rt->rt_refcnt;
315         }
316         if (ifa == NULL) {
317                 /*
318                  * We've got an NS packet, and we don't have that adddress
319                  * assigned for us.  We MUST silently ignore it.
320                  * See RFC2461 7.2.3.
321                  */
322                 goto freeit;
323         }
324         myaddr6 = *IFA_IN6(ifa);
325         anycast = ((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_ANYCAST;
326         tentative = ((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_TENTATIVE;
327         if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DUPLICATED)
328                 goto freeit;
329
330         if (lladdr && ((cmpifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
331                 nd6log((LOG_INFO,
332                     "nd6_ns_input: lladdrlen mismatch for %s "
333                     "(if %d, NS packet %d)\n",
334                     ip6_sprintf(&taddr6), cmpifp->if_addrlen, lladdrlen - 2));
335                 goto bad;
336         }
337
338         if (IN6_ARE_ADDR_EQUAL(&myaddr6, &saddr6)) {
339                 nd6log((LOG_INFO,
340                         "nd6_ns_input: duplicate IP6 address %s\n",
341                         ip6_sprintf(&saddr6)));
342                 goto freeit;
343         }
344
345         /*
346          * We have neighbor solicitation packet, with target address equals to
347          * one of my tentative address.
348          *
349          * src addr     how to process?
350          * ---          ---
351          * multicast    of course, invalid (rejected in ip6_input)
352          * unicast      somebody is doing address resolution -> ignore
353          * unspec       dup address detection
354          *
355          * The processing is defined in RFC 2462.
356          */
357         if (tentative) {
358                 /*
359                  * If source address is unspecified address, it is for
360                  * duplicated address detection.
361                  *
362                  * If not, the packet is for addess resolution;
363                  * silently ignore it.
364                  */
365                 if (IN6_IS_ADDR_UNSPECIFIED(&saddr6))
366                         nd6_dad_ns_input(ifa);
367
368                 goto freeit;
369         }
370
371         /*
372          * If the source address is unspecified address, entries must not
373          * be created or updated.
374          * It looks that sender is performing DAD.  Output NA toward
375          * all-node multicast address, to tell the sender that I'm using
376          * the address.
377          * S bit ("solicited") must be zero.
378          */
379         if (IN6_IS_ADDR_UNSPECIFIED(&saddr6)) {
380                 saddr6 = kin6addr_linklocal_allnodes;
381                 saddr6.s6_addr16[1] = htons(cmpifp->if_index);
382                 nd6_na_output(cmpifp, &saddr6, &taddr6,
383                               ((anycast || proxy || !tlladdr)
384                                       ? 0 : ND_NA_FLAG_OVERRIDE)
385                                 | (ip6_forwarding ? ND_NA_FLAG_ROUTER : 0),
386                               tlladdr, (struct sockaddr *)proxydl);
387                 goto freeit;
388         }
389
390         nd6_cache_lladdr(cmpifp, &saddr6, lladdr,
391                          lladdrlen, ND_NEIGHBOR_SOLICIT, 0);
392
393         nd6_na_output(ifp, &saddr6, &taddr6,
394                       ((anycast || proxy || !tlladdr) ? 0 : ND_NA_FLAG_OVERRIDE)
395                         | (ip6_forwarding ? ND_NA_FLAG_ROUTER : 0)
396                         | ND_NA_FLAG_SOLICITED,
397                       tlladdr, (struct sockaddr *)proxydl);
398 freeit:
399         m_freem(m);
400         return;
401
402 bad:
403         nd6log((LOG_ERR, "nd6_ns_input: src=%s\n", ip6_sprintf(&saddr6)));
404         nd6log((LOG_ERR, "nd6_ns_input: dst=%s\n", ip6_sprintf(&daddr6)));
405         nd6log((LOG_ERR, "nd6_ns_input: tgt=%s\n", ip6_sprintf(&taddr6)));
406         icmp6stat.icp6s_badns++;
407         m_freem(m);
408 }
409
410 /*
411  * Output an Neighbor Solicitation Message. Caller specifies:
412  *      - ICMP6 header source IP6 address
413  *      - ND6 header target IP6 address
414  *      - ND6 header source datalink address
415  *
416  * Based on RFC 2461
417  * Based on RFC 2462 (duplicated address detection)
418  */
419 void
420 nd6_ns_output(struct ifnet *ifp, const struct in6_addr *daddr6,
421               const struct in6_addr *taddr6,
422               struct llinfo_nd6 *ln,    /* for source address determination */
423               int dad)                  /* duplicated address detection */
424 {
425         struct mbuf *m;
426         struct ip6_hdr *ip6;
427         struct nd_neighbor_solicit *nd_ns;
428         struct in6_ifaddr *ia = NULL;
429         struct ip6_moptions im6o;
430         int icmp6len;
431         int maxlen;
432         caddr_t mac;
433         struct ifnet *outif = NULL;
434
435         if (IN6_IS_ADDR_MULTICAST(taddr6))
436                 return;
437
438         /* estimate the size of message */
439         maxlen = sizeof(*ip6) + sizeof(*nd_ns);
440         maxlen += (sizeof(struct nd_opt_hdr) + ifp->if_addrlen + 7) & ~7;
441         if (max_linkhdr + maxlen >= MCLBYTES) {
442 #ifdef DIAGNOSTIC
443                 kprintf("nd6_ns_output: max_linkhdr + maxlen >= MCLBYTES "
444                     "(%d + %d > %d)\n", max_linkhdr, maxlen, MCLBYTES);
445 #endif
446                 return;
447         }
448
449         m = m_getb(max_linkhdr + maxlen, M_NOWAIT, MT_DATA, M_PKTHDR);
450         if (m == NULL)
451                 return;
452
453         if (daddr6 == NULL || IN6_IS_ADDR_MULTICAST(daddr6)) {
454                 m->m_flags |= M_MCAST;
455                 im6o.im6o_multicast_ifp = ifp;
456                 im6o.im6o_multicast_hlim = 255;
457                 im6o.im6o_multicast_loop = 0;
458         }
459
460         icmp6len = sizeof(*nd_ns);
461         m->m_pkthdr.len = m->m_len = sizeof(*ip6) + icmp6len;
462         m->m_data += max_linkhdr;       /* or MH_ALIGN() equivalent? */
463
464         /* fill neighbor solicitation packet */
465         ip6 = mtod(m, struct ip6_hdr *);
466         ip6->ip6_flow = 0;
467         ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
468         ip6->ip6_vfc |= IPV6_VERSION;
469         /* ip6->ip6_plen will be set later */
470         ip6->ip6_nxt = IPPROTO_ICMPV6;
471         ip6->ip6_hlim = 255;
472         if (daddr6)
473                 ip6->ip6_dst = *daddr6;
474         else {
475                 ip6->ip6_dst.s6_addr16[0] = IPV6_ADDR_INT16_MLL;
476                 ip6->ip6_dst.s6_addr16[1] = htons(ifp->if_index);
477                 ip6->ip6_dst.s6_addr32[1] = 0;
478                 ip6->ip6_dst.s6_addr32[2] = IPV6_ADDR_INT32_ONE;
479                 ip6->ip6_dst.s6_addr32[3] = taddr6->s6_addr32[3];
480                 ip6->ip6_dst.s6_addr8[12] = 0xff;
481         }
482         if (!dad) {
483 #if 0   /* KAME way, exact address scope match */
484                 /*
485                  * Select a source whose scope is the same as that of the dest.
486                  * Typically, the dest is link-local solicitation multicast
487                  * (i.e. neighbor discovery) or link-local/global unicast
488                  * (i.e. neighbor un-reachability detection).
489                  */
490                 ia = in6_ifawithifp(ifp, &ip6->ip6_dst);
491                 if (ia == NULL) {
492                         m_freem(m);
493                         return;
494                 }
495                 ip6->ip6_src = ia->ia_addr.sin6_addr;
496 #else   /* spec-wise correct */
497                 /*
498                  * RFC2461 7.2.2:
499                  * "If the source address of the packet prompting the
500                  * solicitation is the same as one of the addresses assigned
501                  * to the outgoing interface, that address SHOULD be placed
502                  * in the IP Source Address of the outgoing solicitation.
503                  * Otherwise, any one of the addresses assigned to the
504                  * interface should be used."
505                  *
506                  * We use the source address for the prompting packet
507                  * (saddr6), if:
508                  * - saddr6 is given from the caller (by giving "ln"), and
509                  * - saddr6 belongs to the outgoing interface.
510                  * Otherwise, we perform a scope-wise match.
511                  */
512                 struct ip6_hdr *hip6;           /* hold ip6 */
513                 struct in6_addr *saddr6;
514
515                 if (ln && ln->ln_hold) {
516                         hip6 = mtod(ln->ln_hold, struct ip6_hdr *);
517                         /* XXX pullup? */
518                         if (sizeof(*hip6) < ln->ln_hold->m_len)
519                                 saddr6 = &hip6->ip6_src;
520                         else
521                                 saddr6 = NULL;
522                 } else
523                         saddr6 = NULL;
524                 if (saddr6 && in6ifa_ifpwithaddr(ifp, saddr6))
525                         bcopy(saddr6, &ip6->ip6_src, sizeof(*saddr6));
526                 else {
527                         ia = in6_ifawithifp(ifp, &ip6->ip6_dst);
528                         if (ia == NULL) {
529                                 m_freem(m);
530                                 return;
531                         }
532                         ip6->ip6_src = ia->ia_addr.sin6_addr;
533                 }
534 #endif
535         } else {
536                 /*
537                  * Source address for DAD packet must always be IPv6
538                  * unspecified address. (0::0)
539                  */
540                 bzero(&ip6->ip6_src, sizeof(ip6->ip6_src));
541         }
542         nd_ns = (struct nd_neighbor_solicit *)(ip6 + 1);
543         nd_ns->nd_ns_type = ND_NEIGHBOR_SOLICIT;
544         nd_ns->nd_ns_code = 0;
545         nd_ns->nd_ns_reserved = 0;
546         nd_ns->nd_ns_target = *taddr6;
547
548         if (IN6_IS_SCOPE_LINKLOCAL(&nd_ns->nd_ns_target))
549                 nd_ns->nd_ns_target.s6_addr16[1] = 0;
550
551         /*
552          * Add source link-layer address option.
553          *
554          *                              spec            implementation
555          *                              ---             ---
556          * DAD packet                   MUST NOT        do not add the option
557          * there's no link layer address:
558          *                              impossible      do not add the option
559          * there's link layer address:
560          *      Multicast NS            MUST add one    add the option
561          *      Unicast NS              SHOULD add one  add the option
562          */
563         if (!dad && (mac = nd6_ifptomac(ifp))) {
564                 int optlen = sizeof(struct nd_opt_hdr) + ifp->if_addrlen;
565                 struct nd_opt_hdr *nd_opt = (struct nd_opt_hdr *)(nd_ns + 1);
566                 /* 8 byte alignments... */
567                 optlen = (optlen + 7) & ~7;
568
569                 m->m_pkthdr.len += optlen;
570                 m->m_len += optlen;
571                 icmp6len += optlen;
572                 bzero((caddr_t)nd_opt, optlen);
573                 nd_opt->nd_opt_type = ND_OPT_SOURCE_LINKADDR;
574                 nd_opt->nd_opt_len = optlen >> 3;
575                 bcopy(mac, (caddr_t)(nd_opt + 1), ifp->if_addrlen);
576         }
577
578         ip6->ip6_plen = htons((u_short)icmp6len);
579         nd_ns->nd_ns_cksum = 0;
580         nd_ns->nd_ns_cksum
581                 = in6_cksum(m, IPPROTO_ICMPV6, sizeof(*ip6), icmp6len);
582
583         ip6_output(m, NULL, NULL, dad ? IPV6_DADOUTPUT : 0, &im6o, &outif, NULL);
584         if (outif) {
585                 icmp6_ifstat_inc(outif, ifs6_out_msg);
586                 icmp6_ifstat_inc(outif, ifs6_out_neighborsolicit);
587         }
588         icmp6stat.icp6s_outhist[ND_NEIGHBOR_SOLICIT]++;
589 }
590
591 /*
592  * Neighbor advertisement input handling.
593  *
594  * Based on RFC 2461
595  * Based on RFC 2462 (duplicated address detection)
596  *
597  * the following items are not implemented yet:
598  * - proxy advertisement delay rule (RFC2461 7.2.8, last paragraph, SHOULD)
599  * - anycast advertisement delay rule (RFC2461 7.2.7, SHOULD)
600  */
601 void
602 nd6_na_input(struct mbuf *m, int off, int icmp6len)
603 {
604         struct ifnet *ifp = m->m_pkthdr.rcvif;
605         struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
606         struct nd_neighbor_advert *nd_na;
607         struct in6_addr saddr6 = ip6->ip6_src;
608         struct in6_addr daddr6 = ip6->ip6_dst;
609         struct in6_addr taddr6;
610         int flags;
611         int is_router;
612         int is_solicited;
613         int is_override;
614         char *lladdr = NULL;
615         int lladdrlen = 0;
616         struct ifaddr *ifa;
617         struct llinfo_nd6 *ln;
618         struct rtentry *rt;
619         struct sockaddr_dl *sdl;
620         union nd_opts ndopts;
621
622         if (ip6->ip6_hlim != 255) {
623                 nd6log((LOG_ERR,
624                     "nd6_na_input: invalid hlim (%d) from %s to %s on %s\n",
625                     ip6->ip6_hlim, ip6_sprintf(&ip6->ip6_src),
626                     ip6_sprintf(&ip6->ip6_dst), if_name(ifp)));
627                 goto bad;
628         }
629
630 #ifndef PULLDOWN_TEST
631         IP6_EXTHDR_CHECK(m, off, icmp6len,);
632         nd_na = (struct nd_neighbor_advert *)((caddr_t)ip6 + off);
633 #else
634         IP6_EXTHDR_GET(nd_na, struct nd_neighbor_advert *, m, off, icmp6len);
635         if (nd_na == NULL) {
636                 icmp6stat.icp6s_tooshort++;
637                 return;
638         }
639 #endif
640         taddr6 = nd_na->nd_na_target;
641         flags = nd_na->nd_na_flags_reserved;
642         is_router = ((flags & ND_NA_FLAG_ROUTER) != 0);
643         is_solicited = ((flags & ND_NA_FLAG_SOLICITED) != 0);
644         is_override = ((flags & ND_NA_FLAG_OVERRIDE) != 0);
645
646         if (IN6_IS_SCOPE_LINKLOCAL(&taddr6))
647                 taddr6.s6_addr16[1] = htons(ifp->if_index);
648
649         if (IN6_IS_ADDR_MULTICAST(&taddr6)) {
650                 nd6log((LOG_ERR,
651                     "nd6_na_input: invalid target address %s\n",
652                     ip6_sprintf(&taddr6)));
653                 goto bad;
654         }
655         if (IN6_IS_ADDR_MULTICAST(&daddr6))
656                 if (is_solicited) {
657                         nd6log((LOG_ERR,
658                             "nd6_na_input: a solicited adv is multicasted\n"));
659                         goto bad;
660                 }
661
662         icmp6len -= sizeof(*nd_na);
663         nd6_option_init(nd_na + 1, icmp6len, &ndopts);
664         if (nd6_options(&ndopts) < 0) {
665                 nd6log((LOG_INFO,
666                     "nd6_na_input: invalid ND option, ignored\n"));
667                 /* nd6_options have incremented stats */
668                 goto freeit;
669         }
670
671         if (ndopts.nd_opts_tgt_lladdr) {
672                 lladdr = (char *)(ndopts.nd_opts_tgt_lladdr + 1);
673                 lladdrlen = ndopts.nd_opts_tgt_lladdr->nd_opt_len << 3;
674         }
675
676         ifa = (struct ifaddr *)in6ifa_ifpwithaddr(ifp, &taddr6);
677
678         /*
679          * Target address matches one of my interface address.
680          *
681          * If my address is tentative, this means that there's somebody
682          * already using the same address as mine.  This indicates DAD failure.
683          * This is defined in RFC 2462.
684          *
685          * Otherwise, process as defined in RFC 2461.
686          */
687         if (ifa
688          && (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_TENTATIVE)) {
689                 nd6_dad_na_input(ifa);
690                 goto freeit;
691         }
692
693         /* Just for safety, maybe unnecessary. */
694         if (ifa) {
695                 log(LOG_ERR,
696                     "nd6_na_input: duplicate IP6 address %s\n",
697                     ip6_sprintf(&taddr6));
698                 goto freeit;
699         }
700
701         /*
702          * Make sure the source address is from a neighbor's address.
703          */
704         if (in6ifa_ifplocaladdr(ifp, &saddr6) == NULL) {
705                 nd6log((LOG_INFO, "nd6_na_input: "
706                     "NA packet from non-neighbor\n"));
707                 goto bad;
708         }
709
710         if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
711                 nd6log((LOG_INFO,
712                     "nd6_na_input: lladdrlen mismatch for %s "
713                     "(if %d, NA packet %d)\n",
714                         ip6_sprintf(&taddr6), ifp->if_addrlen, lladdrlen - 2));
715                 goto bad;
716         }
717
718         /*
719          * If no neighbor cache entry is found, NA SHOULD silently be discarded.
720          */
721         rt = nd6_lookup(&taddr6, 0, ifp);
722         if ((rt == NULL) ||
723            ((ln = (struct llinfo_nd6 *)rt->rt_llinfo) == NULL) ||
724            ((sdl = SDL(rt->rt_gateway)) == NULL))
725                 goto freeit;
726
727         if (ln->ln_state == ND6_LLINFO_INCOMPLETE) {
728                 /*
729                  * If the link-layer has address, and no lladdr option came,
730                  * discard the packet.
731                  */
732                 if (ifp->if_addrlen && !lladdr)
733                         goto freeit;
734
735                 /*
736                  * Record link-layer address, and update the state.
737                  */
738                 sdl->sdl_alen = ifp->if_addrlen;
739                 bcopy(lladdr, LLADDR(sdl), ifp->if_addrlen);
740                 if (is_solicited) {
741                         ln->ln_state = ND6_LLINFO_REACHABLE;
742                         ln->ln_byhint = 0;
743                         if (ln->ln_expire)
744                                 ln->ln_expire = time_uptime +
745                                     ND_IFINFO(rt->rt_ifp)->reachable;
746                 } else {
747                         ln->ln_state = ND6_LLINFO_STALE;
748                         ln->ln_expire = time_uptime + nd6_gctimer;
749                 }
750                 if ((ln->ln_router = is_router) != 0) {
751                         /*
752                          * This means a router's state has changed from
753                          * non-reachable to probably reachable, and might
754                          * affect the status of associated prefixes..
755                          */
756                         pfxlist_onlink_check();
757                 }
758         } else {
759                 int llchange;
760
761                 /*
762                  * Check if the link-layer address has changed or not.
763                  */
764                 if (!lladdr)
765                         llchange = 0;
766                 else {
767                         if (sdl->sdl_alen) {
768                                 if (bcmp(lladdr, LLADDR(sdl), ifp->if_addrlen))
769                                         llchange = 1;
770                                 else
771                                         llchange = 0;
772                         } else
773                                 llchange = 1;
774                 }
775
776                 /*
777                  * This is VERY complex.  Look at it with care.
778                  *
779                  * override solicit lladdr llchange     action
780                  *                                      (L: record lladdr)
781                  *
782                  *      0       0       n       --      (2c)
783                  *      0       0       y       n       (2b) L
784                  *      0       0       y       y       (1)    REACHABLE->STALE
785                  *      0       1       n       --      (2c)   *->REACHABLE
786                  *      0       1       y       n       (2b) L *->REACHABLE
787                  *      0       1       y       y       (1)    REACHABLE->STALE
788                  *      1       0       n       --      (2a)
789                  *      1       0       y       n       (2a) L
790                  *      1       0       y       y       (2a) L *->STALE
791                  *      1       1       n       --      (2a)   *->REACHABLE
792                  *      1       1       y       n       (2a) L *->REACHABLE
793                  *      1       1       y       y       (2a) L *->REACHABLE
794                  */
795                 if (!is_override && (lladdr && llchange)) {        /* (1) */
796                         /*
797                          * If state is REACHABLE, make it STALE.
798                          * no other updates should be done.
799                          */
800                         if (ln->ln_state == ND6_LLINFO_REACHABLE) {
801                                 ln->ln_state = ND6_LLINFO_STALE;
802                                 ln->ln_expire = time_uptime + nd6_gctimer;
803                         }
804                         goto freeit;
805                 } else if (is_override                             /* (2a) */
806                         || (!is_override && (lladdr && !llchange)) /* (2b) */
807                         || !lladdr) {                              /* (2c) */
808                         /*
809                          * Update link-local address, if any.
810                          */
811                         if (lladdr) {
812                                 sdl->sdl_alen = ifp->if_addrlen;
813                                 bcopy(lladdr, LLADDR(sdl), ifp->if_addrlen);
814                         }
815
816                         /*
817                          * If solicited, make the state REACHABLE.
818                          * If not solicited and the link-layer address was
819                          * changed, make it STALE.
820                          */
821                         if (is_solicited) {
822                                 ln->ln_state = ND6_LLINFO_REACHABLE;
823                                 ln->ln_byhint = 0;
824                                 if (ln->ln_expire) {
825                                         ln->ln_expire = time_uptime +
826                                             ND_IFINFO(ifp)->reachable;
827                                 }
828                         } else {
829                                 if (lladdr && llchange) {
830                                         ln->ln_state = ND6_LLINFO_STALE;
831                                         ln->ln_expire = time_uptime + nd6_gctimer;
832                                 }
833                         }
834                 }
835
836                 if (ln->ln_router && !is_router) {
837                         /*
838                          * The peer dropped the router flag.
839                          * Remove the sender from the Default Router List and
840                          * update the Destination Cache entries.
841                          */
842                         struct nd_defrouter *dr;
843                         struct in6_addr *in6;
844
845                         in6 = &((struct sockaddr_in6 *)rt_key(rt))->sin6_addr;
846
847                         /*
848                          * Lock to protect the default router list.
849                          * XXX: this might be unnecessary, since this function
850                          * is only called under the network software interrupt
851                          * context.  However, we keep it just for safety.
852                          */
853                         mtx_lock(&nd6_mtx);
854                         dr = defrouter_lookup(in6, rt->rt_ifp);
855                         if (dr)
856                                 defrtrlist_del(dr);
857                         mtx_unlock(&nd6_mtx);
858
859                         if (dr == NULL && !ip6_forwarding && ip6_accept_rtadv) {
860                                 /*
861                                  * Even if the neighbor is not in the default
862                                  * router list, the neighbor may be used
863                                  * as a next hop for some destinations
864                                  * (e.g. redirect case). So we must
865                                  * call rt6_flush explicitly.
866                                  */
867                                 rt6_flush(&ip6->ip6_src, rt->rt_ifp);
868                         }
869                 }
870                 ln->ln_router = is_router;
871         }
872         rt->rt_flags &= ~RTF_REJECT;
873         ln->ln_asked = 0;
874         if (ln->ln_hold) {
875                 /*
876                  * we assume ifp is not a loopback here, so just set the 2nd
877                  * argument as the 1st one.
878                  */
879                 nd6_output(ifp, ifp, ln->ln_hold,
880                            (struct sockaddr_in6 *)rt_key(rt), rt);
881                 ln->ln_hold = 0;
882         }
883
884 freeit:
885         m_freem(m);
886         return;
887
888 bad:
889         icmp6stat.icp6s_badna++;
890         m_freem(m);
891 }
892
893 /*
894  * Neighbor advertisement output handling.
895  *
896  * Based on RFC 2461
897  *
898  * the following items are not implemented yet:
899  * - proxy advertisement delay rule (RFC2461 7.2.8, last paragraph, SHOULD)
900  * - anycast advertisement delay rule (RFC2461 7.2.7, SHOULD)
901  */
902 void
903 nd6_na_output(struct ifnet *ifp, const struct in6_addr *daddr6,
904               const struct in6_addr *taddr6, u_long flags,
905               int tlladdr,      /* 1 if include target link-layer address */
906               struct sockaddr *sdl0)    /* sockaddr_dl (= proxy NA) or NULL */
907 {
908         struct mbuf *m;
909         struct ip6_hdr *ip6;
910         struct nd_neighbor_advert *nd_na;
911         struct in6_ifaddr *ia = NULL;
912         struct ip6_moptions im6o;
913         int icmp6len;
914         int maxlen;
915         caddr_t mac;
916         struct ifnet *outif = NULL;
917
918         /* estimate the size of message */
919         maxlen = sizeof(*ip6) + sizeof(*nd_na);
920         maxlen += (sizeof(struct nd_opt_hdr) + ifp->if_addrlen + 7) & ~7;
921         if (max_linkhdr + maxlen >= MCLBYTES) {
922 #ifdef DIAGNOSTIC
923                 kprintf("nd6_na_output: max_linkhdr + maxlen >= MCLBYTES "
924                     "(%d + %d > %d)\n", max_linkhdr, maxlen, MCLBYTES);
925 #endif
926                 return;
927         }
928
929         m = m_getb(max_linkhdr + maxlen, M_NOWAIT, MT_DATA, M_PKTHDR);
930         if (m == NULL)
931                 return;
932
933         if (IN6_IS_ADDR_MULTICAST(daddr6)) {
934                 m->m_flags |= M_MCAST;
935                 im6o.im6o_multicast_ifp = ifp;
936                 im6o.im6o_multicast_hlim = 255;
937                 im6o.im6o_multicast_loop = 0;
938         }
939
940         icmp6len = sizeof(*nd_na);
941         m->m_pkthdr.len = m->m_len = sizeof(struct ip6_hdr) + icmp6len;
942         m->m_data += max_linkhdr;       /* or MH_ALIGN() equivalent? */
943
944         /* fill neighbor advertisement packet */
945         ip6 = mtod(m, struct ip6_hdr *);
946         ip6->ip6_flow = 0;
947         ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
948         ip6->ip6_vfc |= IPV6_VERSION;
949         ip6->ip6_nxt = IPPROTO_ICMPV6;
950         ip6->ip6_hlim = 255;
951         if (IN6_IS_ADDR_UNSPECIFIED(daddr6)) {
952                 /* reply to DAD */
953                 ip6->ip6_dst.s6_addr16[0] = IPV6_ADDR_INT16_MLL;
954                 ip6->ip6_dst.s6_addr16[1] = htons(ifp->if_index);
955                 ip6->ip6_dst.s6_addr32[1] = 0;
956                 ip6->ip6_dst.s6_addr32[2] = 0;
957                 ip6->ip6_dst.s6_addr32[3] = IPV6_ADDR_INT32_ONE;
958                 flags &= ~ND_NA_FLAG_SOLICITED;
959         } else
960                 ip6->ip6_dst = *daddr6;
961
962         /*
963          * Select a source whose scope is the same as that of the dest.
964          */
965         ia = in6_ifawithifp(ifp, &ip6->ip6_dst);
966         if (ia == NULL) {
967                 m_freem(m);
968                 return;
969         }
970         ip6->ip6_src = ia->ia_addr.sin6_addr;
971         nd_na = (struct nd_neighbor_advert *)(ip6 + 1);
972         nd_na->nd_na_type = ND_NEIGHBOR_ADVERT;
973         nd_na->nd_na_code = 0;
974         nd_na->nd_na_target = *taddr6;
975         if (IN6_IS_SCOPE_LINKLOCAL(&nd_na->nd_na_target))
976                 nd_na->nd_na_target.s6_addr16[1] = 0;
977
978         /*
979          * "tlladdr" indicates NS's condition for adding tlladdr or not.
980          * see nd6_ns_input() for details.
981          * Basically, if NS packet is sent to unicast/anycast addr,
982          * target lladdr option SHOULD NOT be included.
983          */
984         mac = NULL;
985         if (tlladdr) {
986                 /*
987                  * sdl0 != NULL indicates proxy NA.  If we do proxy, use
988                  * lladdr in sdl0.  If we are not proxying (sending NA for
989                  * my address) use lladdr configured for the interface.
990                  */
991                 if (sdl0 == NULL) {
992 #ifdef CARP
993                         if (ifp->if_carp)
994                                 mac = carp_macmatch6(ifp->if_carp, m, taddr6);
995                         if (mac == NULL)
996                                 mac = nd6_ifptomac(ifp);
997 #else
998                         mac = nd6_ifptomac(ifp);
999 #endif
1000                 } else if (sdl0->sa_family == AF_LINK) {
1001                         struct sockaddr_dl *sdl;
1002                         sdl = (struct sockaddr_dl *)sdl0;
1003                         if (sdl->sdl_alen == ifp->if_addrlen)
1004                                 mac = LLADDR(sdl);
1005                 }
1006         }
1007         if (mac != NULL) {
1008                 int optlen = sizeof(struct nd_opt_hdr) + ifp->if_addrlen;
1009                 struct nd_opt_hdr *nd_opt = (struct nd_opt_hdr *)(nd_na + 1);
1010
1011                 /* roundup to 8 bytes alignment! */
1012                 optlen = (optlen + 7) & ~7;
1013
1014                 m->m_pkthdr.len += optlen;
1015                 m->m_len += optlen;
1016                 icmp6len += optlen;
1017                 bzero((caddr_t)nd_opt, optlen);
1018                 nd_opt->nd_opt_type = ND_OPT_TARGET_LINKADDR;
1019                 nd_opt->nd_opt_len = optlen >> 3;
1020                 bcopy(mac, (caddr_t)(nd_opt + 1), ifp->if_addrlen);
1021         } else
1022                 flags &= ~ND_NA_FLAG_OVERRIDE;
1023
1024         ip6->ip6_plen = htons((u_short)icmp6len);
1025         nd_na->nd_na_flags_reserved = flags;
1026         nd_na->nd_na_cksum = 0;
1027         nd_na->nd_na_cksum =
1028                 in6_cksum(m, IPPROTO_ICMPV6, sizeof(struct ip6_hdr), icmp6len);
1029
1030         ip6_output(m, NULL, NULL, 0, &im6o, &outif, NULL);
1031         if (outif) {
1032                 icmp6_ifstat_inc(outif, ifs6_out_msg);
1033                 icmp6_ifstat_inc(outif, ifs6_out_neighboradvert);
1034         }
1035         icmp6stat.icp6s_outhist[ND_NEIGHBOR_ADVERT]++;
1036 }
1037
1038 caddr_t
1039 nd6_ifptomac(struct ifnet *ifp)
1040 {
1041         switch (ifp->if_type) {
1042         case IFT_ETHER:
1043         case IFT_IEEE1394:
1044 #ifdef IFT_L2VLAN
1045         case IFT_L2VLAN:
1046 #endif
1047 #ifdef IFT_IEEE80211
1048         case IFT_IEEE80211:
1049 #endif
1050 #ifdef IFT_CARP
1051         case IFT_CARP:
1052 #endif
1053                 return ((caddr_t)(ifp + 1));
1054                 break;
1055         default:
1056                 return NULL;
1057         }
1058 }
1059
1060 struct netmsg_dad {
1061         struct netmsg_base      base;
1062         struct dadq             *dadq;
1063 };
1064
1065 struct dadq {
1066         TAILQ_ENTRY(dadq) dad_list;
1067         struct ifaddr *dad_ifa;
1068         int dad_count;          /* max NS to send */
1069         int dad_ns_tcount;      /* # of trials to send NS */
1070         int dad_ns_ocount;      /* NS sent so far */
1071         int dad_ns_icount;
1072         int dad_na_icount;
1073         struct callout dad_timer_ch;
1074         struct netmsg_dad dad_nmsg;
1075 };
1076 TAILQ_HEAD(dadq_head, dadq);
1077
1078 static struct dadq_head dadq = TAILQ_HEAD_INITIALIZER(dadq);
1079
1080 static struct dadq *
1081 nd6_dad_find(struct ifaddr *ifa)
1082 {
1083         struct dadq *dp;
1084
1085         ASSERT_IN_NETISR(0);
1086
1087         TAILQ_FOREACH(dp, &dadq, dad_list) {
1088                 if (dp->dad_ifa == ifa)
1089                         return dp;
1090         }
1091         return NULL;
1092 }
1093
1094 static void
1095 nd6_dad_starttimer(struct dadq *dp, int ticks)
1096 {
1097         ASSERT_IN_NETISR(0);
1098         callout_reset(&dp->dad_timer_ch, ticks, nd6_dad_timer, dp);
1099 }
1100
1101 static void
1102 nd6_dad_stoptimer(struct dadq *dp)
1103 {
1104         ASSERT_IN_NETISR(0);
1105         callout_stop(&dp->dad_timer_ch);
1106 }
1107
1108 /*
1109  * Start Duplicated Address Detection (DAD) for specified interface address.
1110  */
1111 void
1112 nd6_dad_start(struct ifaddr *ifa,
1113               int *tick)        /* minimum delay ticks for IFF_UP event */
1114 {
1115         struct in6_ifaddr *ia = (struct in6_ifaddr *)ifa;
1116         struct dadq *dp;
1117
1118         ASSERT_IN_NETISR(0);
1119
1120         /*
1121          * If we don't need DAD, don't do it.
1122          * There are several cases:
1123          * - DAD is disabled (ip6_dad_count == 0)
1124          * - the interface address is anycast
1125          */
1126         if (!(ia->ia6_flags & IN6_IFF_TENTATIVE)) {
1127                 log(LOG_DEBUG,
1128                         "nd6_dad_start: called with non-tentative address "
1129                         "%s(%s)\n",
1130                         ip6_sprintf(&ia->ia_addr.sin6_addr),
1131                         ifa->ifa_ifp ? if_name(ifa->ifa_ifp) : "???");
1132                 return;
1133         }
1134         if (ia->ia6_flags & IN6_IFF_ANYCAST) {
1135                 ia->ia6_flags &= ~IN6_IFF_TENTATIVE;
1136                 return;
1137         }
1138         if (!ip6_dad_count) {
1139                 ia->ia6_flags &= ~IN6_IFF_TENTATIVE;
1140                 return;
1141         }
1142         if (!ifa->ifa_ifp)
1143                 panic("nd6_dad_start: ifa->ifa_ifp == NULL");
1144         if (!(ifa->ifa_ifp->if_flags & IFF_UP))
1145                 return;
1146         if (nd6_dad_find(ifa) != NULL) {
1147                 /* DAD already in progress */
1148                 return;
1149         }
1150
1151         dp = nd6_dad_create(ifa);
1152         nd6log((LOG_DEBUG, "%s: starting DAD for %s\n", if_name(ifa->ifa_ifp),
1153             ip6_sprintf(&ia->ia_addr.sin6_addr)));
1154
1155         /*
1156          * Send NS packet for DAD, dp->dad_count times.
1157          * Note that we must delay the first transmission, if this is the
1158          * first packet to be sent from the interface after interface
1159          * (re)initialization.
1160          */
1161         if (tick == NULL) {
1162                 nd6_dad_ns_output(dp);
1163                 nd6_dad_starttimer(dp,
1164                     ND_IFINFO(ifa->ifa_ifp)->retrans * hz / 1000);
1165         } else {
1166                 int ntick;
1167
1168                 if (*tick == 0)
1169                         ntick = krandom() % (MAX_RTR_SOLICITATION_DELAY * hz);
1170                 else
1171                         ntick = *tick + krandom() % (hz / 2);
1172                 *tick = ntick;
1173                 nd6_dad_starttimer(dp, ntick);
1174         }
1175 }
1176
1177 /*
1178  * Terminate DAD unconditionally.  Used for address removals.
1179  */
1180 void
1181 nd6_dad_stop(struct ifaddr *ifa)
1182 {
1183         struct dadq *dp;
1184
1185         ASSERT_IN_NETISR(0);
1186
1187         dp = nd6_dad_find(ifa);
1188         if (!dp) {
1189                 /* DAD wasn't started yet */
1190                 return;
1191         }
1192         nd6_dad_destroy(dp);
1193 }
1194
1195 static struct dadq *
1196 nd6_dad_create(struct ifaddr *ifa)
1197 {
1198         struct netmsg_dad *dm;
1199         struct dadq *dp;
1200
1201         ASSERT_IN_NETISR(0);
1202
1203         dp = kmalloc(sizeof(*dp), M_IP6NDP, M_INTWAIT | M_ZERO);
1204         callout_init_mp(&dp->dad_timer_ch);
1205
1206         dm = &dp->dad_nmsg;
1207         netmsg_init(&dm->base, NULL, &netisr_adone_rport,
1208             MSGF_DROPABLE | MSGF_PRIORITY, nd6_dad_timer_handler);
1209         dm->dadq = dp;
1210
1211         dp->dad_ifa = ifa;
1212         IFAREF(ifa);    /* just for safety */
1213
1214         /* Send NS packet for DAD, ip6_dad_count times. */
1215         dp->dad_count = ip6_dad_count;
1216
1217         TAILQ_INSERT_TAIL(&dadq, dp, dad_list);
1218
1219         return dp;
1220 }
1221
1222 static void
1223 nd6_dad_destroy(struct dadq *dp)
1224 {
1225         struct lwkt_msg *lmsg = &dp->dad_nmsg.base.lmsg;
1226
1227         ASSERT_IN_NETISR(0);
1228
1229         TAILQ_REMOVE(&dadq, dp, dad_list);
1230
1231         nd6_dad_stoptimer(dp);
1232
1233         crit_enter();
1234         if ((lmsg->ms_flags & MSGF_DONE) == 0)
1235                 lwkt_dropmsg(lmsg);
1236         crit_exit();
1237
1238         IFAFREE(dp->dad_ifa);
1239         kfree(dp, M_IP6NDP);
1240 }
1241
1242 static void
1243 nd6_dad_timer(void *xdp)
1244 {
1245         struct dadq *dp = xdp;
1246         struct lwkt_msg *lmsg = &dp->dad_nmsg.base.lmsg;
1247
1248         KASSERT(mycpuid == 0, ("dad timer not on cpu0"));
1249
1250         crit_enter();
1251         if (lmsg->ms_flags & MSGF_DONE)
1252                 lwkt_sendmsg_oncpu(netisr_cpuport(0), lmsg);
1253         crit_exit();
1254 }
1255
1256 static void
1257 nd6_dad_timer_handler(netmsg_t msg)
1258 {
1259         struct netmsg_dad *dm = (struct netmsg_dad *)msg;
1260         struct dadq *dp = dm->dadq;
1261         struct ifaddr *ifa = dp->dad_ifa;
1262         struct in6_ifaddr *ia = (struct in6_ifaddr *)ifa;
1263
1264         ASSERT_IN_NETISR(0);
1265
1266         /* Reply ASAP */
1267         crit_enter();
1268         lwkt_replymsg(&dm->base.lmsg, 0);
1269         crit_exit();
1270
1271         if (ia->ia6_flags & IN6_IFF_DUPLICATED) {
1272                 log(LOG_ERR, "nd6_dad_timer: called with duplicated address "
1273                         "%s(%s)\n",
1274                         ip6_sprintf(&ia->ia_addr.sin6_addr),
1275                         ifa->ifa_ifp ? if_name(ifa->ifa_ifp) : "???");
1276                 goto destroy;
1277         }
1278         if (!(ia->ia6_flags & IN6_IFF_TENTATIVE)) {
1279                 log(LOG_ERR, "nd6_dad_timer: called with non-tentative address "
1280                         "%s(%s)\n",
1281                         ip6_sprintf(&ia->ia_addr.sin6_addr),
1282                         ifa->ifa_ifp ? if_name(ifa->ifa_ifp) : "???");
1283                 goto destroy;
1284         }
1285
1286         /* Timed out with IFF_{RUNNING,UP} check */
1287         if (dp->dad_ns_tcount > dad_maxtry) {
1288                 nd6log((LOG_INFO, "%s: could not run DAD, driver problem?\n",
1289                         if_name(ifa->ifa_ifp)));
1290                 goto destroy;
1291         }
1292
1293         /* Need more checks? */
1294         if (dp->dad_ns_ocount < dp->dad_count) {
1295                 /*
1296                  * We have more NS to go.  Send NS packet for DAD.
1297                  */
1298                 nd6_dad_ns_output(dp);
1299                 nd6_dad_starttimer(dp,
1300                         ND_IFINFO(ifa->ifa_ifp)->retrans * hz / 1000);
1301         } else {
1302                 /*
1303                  * We have transmitted sufficient number of DAD packets.
1304                  * See what we've got.
1305                  */
1306                 int duplicate;
1307
1308                 duplicate = 0;
1309
1310                 if (dp->dad_na_icount) {
1311                         /*
1312                          * the check is in nd6_dad_na_input(),
1313                          * but just in case
1314                          */
1315                         duplicate++;
1316                 }
1317
1318                 if (dp->dad_ns_icount) {
1319 #if 0 /* heuristics */
1320                         /*
1321                          * if
1322                          * - we have sent many(?) DAD NS, and
1323                          * - the number of NS we sent equals to the
1324                          *   number of NS we've got, and
1325                          * - we've got no NA
1326                          * we may have a faulty network card/driver which
1327                          * loops back multicasts to myself.
1328                          */
1329                         if (3 < dp->dad_count
1330                          && dp->dad_ns_icount == dp->dad_count
1331                          && dp->dad_na_icount == 0) {
1332                                 log(LOG_INFO, "DAD questionable for %s(%s): "
1333                                         "network card loops back multicast?\n",
1334                                         ip6_sprintf(&ia->ia_addr.sin6_addr),
1335                                         if_name(ifa->ifa_ifp));
1336                                 /* XXX consider it a duplicate or not? */
1337                                 /* duplicate++; */
1338                         } else {
1339                                 /* We've seen NS, means DAD has failed. */
1340                                 duplicate++;
1341                         }
1342 #else
1343                         /* We've seen NS, means DAD has failed. */
1344                         duplicate++;
1345 #endif
1346                 }
1347
1348                 if (duplicate) {
1349                         /* dp will be freed in nd6_dad_duplicated() */
1350                         dp = NULL;
1351                         nd6_dad_duplicated(ifa);
1352                 } else {
1353                         /*
1354                          * We are done with DAD.  No NA came, no NS came.
1355                          * duplicated address found.
1356                          */
1357                         ia->ia6_flags &= ~IN6_IFF_TENTATIVE;
1358                         nd6log((LOG_DEBUG,
1359                             "%s: DAD complete for %s - no duplicates found\n",
1360                             if_name(ifa->ifa_ifp),
1361                             ip6_sprintf(&ia->ia_addr.sin6_addr)));
1362                         goto destroy;
1363                 }
1364         }
1365         return;
1366 destroy:
1367         nd6_dad_destroy(dp);
1368 }
1369
1370 static void
1371 nd6_dad_duplicated(struct ifaddr *ifa)
1372 {
1373         struct in6_ifaddr *ia = (struct in6_ifaddr *)ifa;
1374         struct dadq *dp;
1375
1376         ASSERT_IN_NETISR(0);
1377
1378         dp = nd6_dad_find(ifa);
1379         if (dp == NULL) {
1380                 log(LOG_ERR, "nd6_dad_duplicated: DAD structure not found\n");
1381                 return;
1382         }
1383
1384         /*
1385          * We are done with DAD, with duplicated address found. (failure)
1386          */
1387         log(LOG_ERR, "%s: DAD detected duplicate IPv6 address %s: "
1388             "NS in/out=%d/%d, NA in=%d\n",
1389             if_name(ifa->ifa_ifp), ip6_sprintf(&ia->ia_addr.sin6_addr),
1390             dp->dad_ns_icount, dp->dad_ns_ocount, dp->dad_na_icount);
1391
1392         ia->ia6_flags &= ~IN6_IFF_TENTATIVE;
1393         ia->ia6_flags |= IN6_IFF_DUPLICATED;
1394
1395         log(LOG_ERR, "%s: DAD complete for %s - duplicate found\n",
1396             if_name(ifa->ifa_ifp), ip6_sprintf(&ia->ia_addr.sin6_addr));
1397         log(LOG_ERR, "%s: manual intervention required\n",
1398             if_name(ifa->ifa_ifp));
1399
1400         nd6_dad_destroy(dp);
1401 }
1402
1403 static void
1404 nd6_dad_ns_output(struct dadq *dp)
1405 {
1406         struct in6_ifaddr *ia = (struct in6_ifaddr *)dp->dad_ifa;
1407         struct ifnet *ifp = dp->dad_ifa->ifa_ifp;
1408
1409         ASSERT_IN_NETISR(0);
1410
1411         dp->dad_ns_tcount++;
1412         if (!(ifp->if_flags & IFF_UP)) {
1413 #if 0
1414                 kprintf("%s: interface down?\n", if_name(ifp));
1415 #endif
1416                 return;
1417         }
1418         if (!(ifp->if_flags & IFF_RUNNING)) {
1419 #if 0
1420                 kprintf("%s: interface not running?\n", if_name(ifp));
1421 #endif
1422                 return;
1423         }
1424
1425         dp->dad_ns_ocount++;
1426         nd6_ns_output(ifp, NULL, &ia->ia_addr.sin6_addr, NULL, 1);
1427 }
1428
1429 static void
1430 nd6_dad_ns_input(struct ifaddr *ifa)
1431 {
1432         struct in6_ifaddr *ia;
1433         const struct in6_addr *taddr6;
1434         struct dadq *dp;
1435         int duplicate;
1436
1437         ASSERT_IN_NETISR(0);
1438
1439         if (!ifa)
1440                 panic("ifa == NULL in nd6_dad_ns_input");
1441
1442         ia = (struct in6_ifaddr *)ifa;
1443         taddr6 = &ia->ia_addr.sin6_addr;
1444         duplicate = 0;
1445         dp = nd6_dad_find(ifa);
1446
1447         /* Quickhack - completely ignore DAD NS packets */
1448         if (dad_ignore_ns) {
1449                 nd6log((LOG_INFO,
1450                     "nd6_dad_ns_input: ignoring DAD NS packet for "
1451                     "address %s(%s)\n", ip6_sprintf(taddr6),
1452                     if_name(ifa->ifa_ifp)));
1453                 return;
1454         }
1455
1456         /*
1457          * if I'm yet to start DAD, someone else started using this address
1458          * first.  I have a duplicate and you win.
1459          */
1460         if (!dp || dp->dad_ns_ocount == 0)
1461                 duplicate++;
1462
1463         /* XXX more checks for loopback situation - see nd6_dad_timer too */
1464
1465         if (duplicate) {
1466                 dp = NULL;      /* will be freed in nd6_dad_duplicated() */
1467                 nd6_dad_duplicated(ifa);
1468         } else {
1469                 /*
1470                  * not sure if I got a duplicate.
1471                  * increment ns count and see what happens.
1472                  */
1473                 if (dp)
1474                         dp->dad_ns_icount++;
1475         }
1476 }
1477
1478 static void
1479 nd6_dad_na_input(struct ifaddr *ifa)
1480 {
1481         struct dadq *dp;
1482
1483         ASSERT_IN_NETISR(0);
1484
1485         if (!ifa)
1486                 panic("ifa == NULL in nd6_dad_na_input");
1487
1488         dp = nd6_dad_find(ifa);
1489         if (dp)
1490                 dp->dad_na_icount++;
1491
1492         /* remove the address. */
1493         nd6_dad_duplicated(ifa);
1494 }