inet6: Cosmetic clean up
[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, "nd6_ns_input: lladdrlen mismatch for %s "
332                     "(if %d, NS packet %d)\n",
333                     ip6_sprintf(&taddr6), cmpifp->if_addrlen, lladdrlen - 2));
334                 goto bad;
335         }
336
337         if (IN6_ARE_ADDR_EQUAL(&myaddr6, &saddr6)) {
338                 nd6log((LOG_INFO, "nd6_ns_input: duplicate IP6 address %s\n",
339                     ip6_sprintf(&saddr6)));
340                 goto freeit;
341         }
342
343         /*
344          * We have neighbor solicitation packet, with target address equals to
345          * one of my tentative address.
346          *
347          * src addr     how to process?
348          * ---          ---
349          * multicast    of course, invalid (rejected in ip6_input)
350          * unicast      somebody is doing address resolution -> ignore
351          * unspec       dup address detection
352          *
353          * The processing is defined in RFC 2462.
354          */
355         if (tentative) {
356                 /*
357                  * If source address is unspecified address, it is for
358                  * duplicated address detection.
359                  *
360                  * If not, the packet is for addess resolution;
361                  * silently ignore it.
362                  */
363                 if (IN6_IS_ADDR_UNSPECIFIED(&saddr6))
364                         nd6_dad_ns_input(ifa);
365
366                 goto freeit;
367         }
368
369         /*
370          * If the source address is unspecified address, entries must not
371          * be created or updated.
372          * It looks that sender is performing DAD.  Output NA toward
373          * all-node multicast address, to tell the sender that I'm using
374          * the address.
375          * S bit ("solicited") must be zero.
376          */
377         if (IN6_IS_ADDR_UNSPECIFIED(&saddr6)) {
378                 saddr6 = kin6addr_linklocal_allnodes;
379                 saddr6.s6_addr16[1] = htons(cmpifp->if_index);
380                 nd6_na_output(cmpifp, &saddr6, &taddr6,
381                     ((anycast || proxy || !tlladdr) ? 0 : ND_NA_FLAG_OVERRIDE) |
382                     (ip6_forwarding ? ND_NA_FLAG_ROUTER : 0),
383                     tlladdr, (struct sockaddr *)proxydl);
384                 goto freeit;
385         }
386
387         nd6_cache_lladdr(cmpifp, &saddr6, lladdr, lladdrlen,
388             ND_NEIGHBOR_SOLICIT, 0);
389
390         nd6_na_output(ifp, &saddr6, &taddr6,
391             ((anycast || proxy || !tlladdr) ? 0 : ND_NA_FLAG_OVERRIDE) |
392             (ip6_forwarding ? ND_NA_FLAG_ROUTER : 0) | ND_NA_FLAG_SOLICITED,
393             tlladdr, (struct sockaddr *)proxydl);
394 freeit:
395         m_freem(m);
396         return;
397
398 bad:
399         nd6log((LOG_ERR, "nd6_ns_input: src=%s\n", ip6_sprintf(&saddr6)));
400         nd6log((LOG_ERR, "nd6_ns_input: dst=%s\n", ip6_sprintf(&daddr6)));
401         nd6log((LOG_ERR, "nd6_ns_input: tgt=%s\n", ip6_sprintf(&taddr6)));
402         icmp6stat.icp6s_badns++;
403         m_freem(m);
404 }
405
406 /*
407  * Output an Neighbor Solicitation Message. Caller specifies:
408  *      - ICMP6 header source IP6 address
409  *      - ND6 header target IP6 address
410  *      - ND6 header source datalink address
411  *
412  * Based on RFC 2461
413  * Based on RFC 2462 (duplicated address detection)
414  */
415 void
416 nd6_ns_output(struct ifnet *ifp, const struct in6_addr *daddr6,
417               const struct in6_addr *taddr6,
418               struct llinfo_nd6 *ln,    /* for source address determination */
419               int dad)                  /* duplicated address detection */
420 {
421         struct mbuf *m;
422         struct ip6_hdr *ip6;
423         struct nd_neighbor_solicit *nd_ns;
424         struct in6_ifaddr *ia = NULL;
425         struct ip6_moptions im6o;
426         int icmp6len;
427         int maxlen;
428         caddr_t mac;
429         struct ifnet *outif = NULL;
430
431         if (IN6_IS_ADDR_MULTICAST(taddr6))
432                 return;
433
434         /* estimate the size of message */
435         maxlen = sizeof(*ip6) + sizeof(*nd_ns);
436         maxlen += (sizeof(struct nd_opt_hdr) + ifp->if_addrlen + 7) & ~7;
437         if (max_linkhdr + maxlen >= MCLBYTES) {
438 #ifdef DIAGNOSTIC
439                 kprintf("nd6_ns_output: max_linkhdr + maxlen >= MCLBYTES "
440                     "(%d + %d > %d)\n", max_linkhdr, maxlen, MCLBYTES);
441 #endif
442                 return;
443         }
444
445         m = m_getb(max_linkhdr + maxlen, M_NOWAIT, MT_DATA, M_PKTHDR);
446         if (m == NULL)
447                 return;
448
449         if (daddr6 == NULL || IN6_IS_ADDR_MULTICAST(daddr6)) {
450                 m->m_flags |= M_MCAST;
451                 im6o.im6o_multicast_ifp = ifp;
452                 im6o.im6o_multicast_hlim = 255;
453                 im6o.im6o_multicast_loop = 0;
454         }
455
456         icmp6len = sizeof(*nd_ns);
457         m->m_pkthdr.len = m->m_len = sizeof(*ip6) + icmp6len;
458         m->m_data += max_linkhdr;       /* or MH_ALIGN() equivalent? */
459
460         /* fill neighbor solicitation packet */
461         ip6 = mtod(m, struct ip6_hdr *);
462         ip6->ip6_flow = 0;
463         ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
464         ip6->ip6_vfc |= IPV6_VERSION;
465         /* ip6->ip6_plen will be set later */
466         ip6->ip6_nxt = IPPROTO_ICMPV6;
467         ip6->ip6_hlim = 255;
468         if (daddr6)
469                 ip6->ip6_dst = *daddr6;
470         else {
471                 ip6->ip6_dst.s6_addr16[0] = IPV6_ADDR_INT16_MLL;
472                 ip6->ip6_dst.s6_addr16[1] = htons(ifp->if_index);
473                 ip6->ip6_dst.s6_addr32[1] = 0;
474                 ip6->ip6_dst.s6_addr32[2] = IPV6_ADDR_INT32_ONE;
475                 ip6->ip6_dst.s6_addr32[3] = taddr6->s6_addr32[3];
476                 ip6->ip6_dst.s6_addr8[12] = 0xff;
477         }
478         if (!dad) {
479                 /*
480                  * RFC2461 7.2.2:
481                  * "If the source address of the packet prompting the
482                  * solicitation is the same as one of the addresses assigned
483                  * to the outgoing interface, that address SHOULD be placed
484                  * in the IP Source Address of the outgoing solicitation.
485                  * Otherwise, any one of the addresses assigned to the
486                  * interface should be used."
487                  *
488                  * We use the source address for the prompting packet
489                  * (saddr6), if:
490                  * - saddr6 is given from the caller (by giving "ln"), and
491                  * - saddr6 belongs to the outgoing interface.
492                  * Otherwise, we perform a scope-wise match.
493                  */
494                 struct ip6_hdr *hip6;           /* hold ip6 */
495                 struct in6_addr *saddr6;
496
497                 if (ln && ln->ln_hold) {
498                         hip6 = mtod(ln->ln_hold, struct ip6_hdr *);
499                         /* XXX pullup? */
500                         if (sizeof(*hip6) < ln->ln_hold->m_len)
501                                 saddr6 = &hip6->ip6_src;
502                         else
503                                 saddr6 = NULL;
504                 } else
505                         saddr6 = NULL;
506                 if (saddr6 && in6ifa_ifpwithaddr(ifp, saddr6))
507                         bcopy(saddr6, &ip6->ip6_src, sizeof(*saddr6));
508                 else {
509                         ia = in6_ifawithifp(ifp, &ip6->ip6_dst);
510                         if (ia == NULL) {
511                                 m_freem(m);
512                                 return;
513                         }
514                         ip6->ip6_src = ia->ia_addr.sin6_addr;
515                 }
516         } else {
517                 /*
518                  * Source address for DAD packet must always be IPv6
519                  * unspecified address. (0::0)
520                  */
521                 bzero(&ip6->ip6_src, sizeof(ip6->ip6_src));
522         }
523         nd_ns = (struct nd_neighbor_solicit *)(ip6 + 1);
524         nd_ns->nd_ns_type = ND_NEIGHBOR_SOLICIT;
525         nd_ns->nd_ns_code = 0;
526         nd_ns->nd_ns_reserved = 0;
527         nd_ns->nd_ns_target = *taddr6;
528
529         if (IN6_IS_SCOPE_LINKLOCAL(&nd_ns->nd_ns_target))
530                 nd_ns->nd_ns_target.s6_addr16[1] = 0;
531
532         /*
533          * Add source link-layer address option.
534          *
535          *                              spec            implementation
536          *                              ---             ---
537          * DAD packet                   MUST NOT        do not add the option
538          * there's no link layer address:
539          *                              impossible      do not add the option
540          * there's link layer address:
541          *      Multicast NS            MUST add one    add the option
542          *      Unicast NS              SHOULD add one  add the option
543          */
544         if (!dad && (mac = nd6_ifptomac(ifp))) {
545                 int optlen = sizeof(struct nd_opt_hdr) + ifp->if_addrlen;
546                 struct nd_opt_hdr *nd_opt = (struct nd_opt_hdr *)(nd_ns + 1);
547                 /* 8 byte alignments... */
548                 optlen = (optlen + 7) & ~7;
549
550                 m->m_pkthdr.len += optlen;
551                 m->m_len += optlen;
552                 icmp6len += optlen;
553                 bzero((caddr_t)nd_opt, optlen);
554                 nd_opt->nd_opt_type = ND_OPT_SOURCE_LINKADDR;
555                 nd_opt->nd_opt_len = optlen >> 3;
556                 bcopy(mac, (caddr_t)(nd_opt + 1), ifp->if_addrlen);
557         }
558
559         ip6->ip6_plen = htons((u_short)icmp6len);
560         nd_ns->nd_ns_cksum = 0;
561         nd_ns->nd_ns_cksum =
562             in6_cksum(m, IPPROTO_ICMPV6, sizeof(*ip6), icmp6len);
563
564         ip6_output(m, NULL, NULL, dad ? IPV6_DADOUTPUT : 0, &im6o, &outif, NULL);
565         if (outif) {
566                 icmp6_ifstat_inc(outif, ifs6_out_msg);
567                 icmp6_ifstat_inc(outif, ifs6_out_neighborsolicit);
568         }
569         icmp6stat.icp6s_outhist[ND_NEIGHBOR_SOLICIT]++;
570 }
571
572 /*
573  * Neighbor advertisement input handling.
574  *
575  * Based on RFC 2461
576  * Based on RFC 2462 (duplicated address detection)
577  *
578  * the following items are not implemented yet:
579  * - proxy advertisement delay rule (RFC2461 7.2.8, last paragraph, SHOULD)
580  * - anycast advertisement delay rule (RFC2461 7.2.7, SHOULD)
581  */
582 void
583 nd6_na_input(struct mbuf *m, int off, int icmp6len)
584 {
585         struct ifnet *ifp = m->m_pkthdr.rcvif;
586         struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
587         struct nd_neighbor_advert *nd_na;
588         struct in6_addr saddr6 = ip6->ip6_src;
589         struct in6_addr daddr6 = ip6->ip6_dst;
590         struct in6_addr taddr6;
591         int flags;
592         int is_router;
593         int is_solicited;
594         int is_override;
595         char *lladdr = NULL;
596         int lladdrlen = 0;
597         struct ifaddr *ifa;
598         struct llinfo_nd6 *ln;
599         struct rtentry *rt;
600         struct sockaddr_dl *sdl;
601         union nd_opts ndopts;
602
603         if (ip6->ip6_hlim != 255) {
604                 nd6log((LOG_ERR,
605                     "nd6_na_input: invalid hlim (%d) from %s to %s on %s\n",
606                     ip6->ip6_hlim, ip6_sprintf(&ip6->ip6_src),
607                     ip6_sprintf(&ip6->ip6_dst), if_name(ifp)));
608                 goto bad;
609         }
610
611 #ifndef PULLDOWN_TEST
612         IP6_EXTHDR_CHECK(m, off, icmp6len,);
613         nd_na = (struct nd_neighbor_advert *)((caddr_t)ip6 + off);
614 #else
615         IP6_EXTHDR_GET(nd_na, struct nd_neighbor_advert *, m, off, icmp6len);
616         if (nd_na == NULL) {
617                 icmp6stat.icp6s_tooshort++;
618                 return;
619         }
620 #endif
621         taddr6 = nd_na->nd_na_target;
622         flags = nd_na->nd_na_flags_reserved;
623         is_router = ((flags & ND_NA_FLAG_ROUTER) != 0);
624         is_solicited = ((flags & ND_NA_FLAG_SOLICITED) != 0);
625         is_override = ((flags & ND_NA_FLAG_OVERRIDE) != 0);
626
627         if (IN6_IS_SCOPE_LINKLOCAL(&taddr6))
628                 taddr6.s6_addr16[1] = htons(ifp->if_index);
629
630         if (IN6_IS_ADDR_MULTICAST(&taddr6)) {
631                 nd6log((LOG_ERR,
632                     "nd6_na_input: invalid target address %s\n",
633                     ip6_sprintf(&taddr6)));
634                 goto bad;
635         }
636         if (IN6_IS_ADDR_MULTICAST(&daddr6))
637                 if (is_solicited) {
638                         nd6log((LOG_ERR,
639                             "nd6_na_input: a solicited adv is multicasted\n"));
640                         goto bad;
641                 }
642
643         icmp6len -= sizeof(*nd_na);
644         nd6_option_init(nd_na + 1, icmp6len, &ndopts);
645         if (nd6_options(&ndopts) < 0) {
646                 nd6log((LOG_INFO,
647                     "nd6_na_input: invalid ND option, ignored\n"));
648                 /* nd6_options have incremented stats */
649                 goto freeit;
650         }
651
652         if (ndopts.nd_opts_tgt_lladdr) {
653                 lladdr = (char *)(ndopts.nd_opts_tgt_lladdr + 1);
654                 lladdrlen = ndopts.nd_opts_tgt_lladdr->nd_opt_len << 3;
655         }
656
657         ifa = (struct ifaddr *)in6ifa_ifpwithaddr(ifp, &taddr6);
658
659         /*
660          * Target address matches one of my interface address.
661          *
662          * If my address is tentative, this means that there's somebody
663          * already using the same address as mine.  This indicates DAD failure.
664          * This is defined in RFC 2462.
665          *
666          * Otherwise, process as defined in RFC 2461.
667          */
668         if (ifa
669          && (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_TENTATIVE)) {
670                 nd6_dad_na_input(ifa);
671                 goto freeit;
672         }
673
674         /* Just for safety, maybe unnecessary. */
675         if (ifa) {
676                 log(LOG_ERR,
677                     "nd6_na_input: duplicate IP6 address %s\n",
678                     ip6_sprintf(&taddr6));
679                 goto freeit;
680         }
681
682         /*
683          * Make sure the source address is from a neighbor's address.
684          */
685         if (in6ifa_ifplocaladdr(ifp, &saddr6) == NULL) {
686                 nd6log((LOG_INFO, "nd6_na_input: "
687                     "NA packet from non-neighbor\n"));
688                 goto bad;
689         }
690
691         if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
692                 nd6log((LOG_INFO, "nd6_na_input: lladdrlen mismatch for %s "
693                     "(if %d, NA packet %d)\n", ip6_sprintf(&taddr6),
694                     ifp->if_addrlen, lladdrlen - 2));
695                 goto bad;
696         }
697
698         /*
699          * If no neighbor cache entry is found, NA SHOULD silently be discarded.
700          */
701         rt = nd6_lookup(&taddr6, 0, ifp);
702         if ((rt == NULL) ||
703            ((ln = (struct llinfo_nd6 *)rt->rt_llinfo) == NULL) ||
704            ((sdl = SDL(rt->rt_gateway)) == NULL))
705                 goto freeit;
706
707         if (ln->ln_state == ND6_LLINFO_INCOMPLETE) {
708                 /*
709                  * If the link-layer has address, and no lladdr option came,
710                  * discard the packet.
711                  */
712                 if (ifp->if_addrlen && !lladdr)
713                         goto freeit;
714
715                 /*
716                  * Record link-layer address, and update the state.
717                  */
718                 sdl->sdl_alen = ifp->if_addrlen;
719                 bcopy(lladdr, LLADDR(sdl), ifp->if_addrlen);
720                 if (is_solicited) {
721                         ln->ln_state = ND6_LLINFO_REACHABLE;
722                         ln->ln_byhint = 0;
723                         if (ln->ln_expire) {
724                                 ln->ln_expire = time_uptime +
725                                     ND_IFINFO(rt->rt_ifp)->reachable;
726                         }
727                 } else {
728                         ln->ln_state = ND6_LLINFO_STALE;
729                         ln->ln_expire = time_uptime + nd6_gctimer;
730                 }
731                 if ((ln->ln_router = is_router) != 0) {
732                         /*
733                          * This means a router's state has changed from
734                          * non-reachable to probably reachable, and might
735                          * affect the status of associated prefixes..
736                          */
737                         pfxlist_onlink_check();
738                 }
739         } else {
740                 int llchange;
741
742                 /*
743                  * Check if the link-layer address has changed or not.
744                  */
745                 if (!lladdr)
746                         llchange = 0;
747                 else {
748                         if (sdl->sdl_alen) {
749                                 if (bcmp(lladdr, LLADDR(sdl), ifp->if_addrlen))
750                                         llchange = 1;
751                                 else
752                                         llchange = 0;
753                         } else
754                                 llchange = 1;
755                 }
756
757                 /*
758                  * This is VERY complex.  Look at it with care.
759                  *
760                  * override solicit lladdr llchange     action
761                  *                                      (L: record lladdr)
762                  *
763                  *      0       0       n       --      (2c)
764                  *      0       0       y       n       (2b) L
765                  *      0       0       y       y       (1)    REACHABLE->STALE
766                  *      0       1       n       --      (2c)   *->REACHABLE
767                  *      0       1       y       n       (2b) L *->REACHABLE
768                  *      0       1       y       y       (1)    REACHABLE->STALE
769                  *      1       0       n       --      (2a)
770                  *      1       0       y       n       (2a) L
771                  *      1       0       y       y       (2a) L *->STALE
772                  *      1       1       n       --      (2a)   *->REACHABLE
773                  *      1       1       y       n       (2a) L *->REACHABLE
774                  *      1       1       y       y       (2a) L *->REACHABLE
775                  */
776                 if (!is_override && (lladdr && llchange)) {        /* (1) */
777                         /*
778                          * If state is REACHABLE, make it STALE.
779                          * no other updates should be done.
780                          */
781                         if (ln->ln_state == ND6_LLINFO_REACHABLE) {
782                                 ln->ln_state = ND6_LLINFO_STALE;
783                                 ln->ln_expire = time_uptime + nd6_gctimer;
784                         }
785                         goto freeit;
786                 } else if (is_override                             /* (2a) */
787                         || (!is_override && (lladdr && !llchange)) /* (2b) */
788                         || !lladdr) {                              /* (2c) */
789                         /*
790                          * Update link-local address, if any.
791                          */
792                         if (lladdr) {
793                                 sdl->sdl_alen = ifp->if_addrlen;
794                                 bcopy(lladdr, LLADDR(sdl), ifp->if_addrlen);
795                         }
796
797                         /*
798                          * If solicited, make the state REACHABLE.
799                          * If not solicited and the link-layer address was
800                          * changed, make it STALE.
801                          */
802                         if (is_solicited) {
803                                 ln->ln_state = ND6_LLINFO_REACHABLE;
804                                 ln->ln_byhint = 0;
805                                 if (ln->ln_expire) {
806                                         ln->ln_expire = time_uptime +
807                                             ND_IFINFO(ifp)->reachable;
808                                 }
809                         } else {
810                                 if (lladdr && llchange) {
811                                         ln->ln_state = ND6_LLINFO_STALE;
812                                         ln->ln_expire = time_uptime + nd6_gctimer;
813                                 }
814                         }
815                 }
816
817                 if (ln->ln_router && !is_router) {
818                         /*
819                          * The peer dropped the router flag.
820                          * Remove the sender from the Default Router List and
821                          * update the Destination Cache entries.
822                          */
823                         struct nd_defrouter *dr;
824                         struct in6_addr *in6;
825
826                         in6 = &((struct sockaddr_in6 *)rt_key(rt))->sin6_addr;
827
828                         /*
829                          * Lock to protect the default router list.
830                          * XXX: this might be unnecessary, since this function
831                          * is only called under the network software interrupt
832                          * context.  However, we keep it just for safety.
833                          */
834                         mtx_lock(&nd6_mtx);
835                         dr = defrouter_lookup(in6, rt->rt_ifp);
836                         if (dr)
837                                 defrtrlist_del(dr);
838                         mtx_unlock(&nd6_mtx);
839
840                         if (dr == NULL && !ip6_forwarding && ip6_accept_rtadv) {
841                                 /*
842                                  * Even if the neighbor is not in the default
843                                  * router list, the neighbor may be used
844                                  * as a next hop for some destinations
845                                  * (e.g. redirect case). So we must
846                                  * call rt6_flush explicitly.
847                                  */
848                                 rt6_flush(&ip6->ip6_src, rt->rt_ifp);
849                         }
850                 }
851                 ln->ln_router = is_router;
852         }
853         rt->rt_flags &= ~RTF_REJECT;
854         ln->ln_asked = 0;
855         if (ln->ln_hold) {
856                 /*
857                  * we assume ifp is not a loopback here, so just set the 2nd
858                  * argument as the 1st one.
859                  */
860                 nd6_output(ifp, ifp, ln->ln_hold,
861                            (struct sockaddr_in6 *)rt_key(rt), rt);
862                 ln->ln_hold = NULL;
863         }
864
865 freeit:
866         m_freem(m);
867         return;
868
869 bad:
870         icmp6stat.icp6s_badna++;
871         m_freem(m);
872 }
873
874 /*
875  * Neighbor advertisement output handling.
876  *
877  * Based on RFC 2461
878  *
879  * the following items are not implemented yet:
880  * - proxy advertisement delay rule (RFC2461 7.2.8, last paragraph, SHOULD)
881  * - anycast advertisement delay rule (RFC2461 7.2.7, SHOULD)
882  */
883 void
884 nd6_na_output(struct ifnet *ifp, const struct in6_addr *daddr6,
885               const struct in6_addr *taddr6, u_long flags,
886               int tlladdr,      /* 1 if include target link-layer address */
887               struct sockaddr *sdl0)    /* sockaddr_dl (= proxy NA) or NULL */
888 {
889         struct mbuf *m;
890         struct ip6_hdr *ip6;
891         struct nd_neighbor_advert *nd_na;
892         struct in6_ifaddr *ia = NULL;
893         struct ip6_moptions im6o;
894         int icmp6len;
895         int maxlen;
896         caddr_t mac;
897         struct ifnet *outif = NULL;
898
899         /* estimate the size of message */
900         maxlen = sizeof(*ip6) + sizeof(*nd_na);
901         maxlen += (sizeof(struct nd_opt_hdr) + ifp->if_addrlen + 7) & ~7;
902         if (max_linkhdr + maxlen >= MCLBYTES) {
903 #ifdef DIAGNOSTIC
904                 kprintf("nd6_na_output: max_linkhdr + maxlen >= MCLBYTES "
905                     "(%d + %d > %d)\n", max_linkhdr, maxlen, MCLBYTES);
906 #endif
907                 return;
908         }
909
910         m = m_getb(max_linkhdr + maxlen, M_NOWAIT, MT_DATA, M_PKTHDR);
911         if (m == NULL)
912                 return;
913
914         if (IN6_IS_ADDR_MULTICAST(daddr6)) {
915                 m->m_flags |= M_MCAST;
916                 im6o.im6o_multicast_ifp = ifp;
917                 im6o.im6o_multicast_hlim = 255;
918                 im6o.im6o_multicast_loop = 0;
919         }
920
921         icmp6len = sizeof(*nd_na);
922         m->m_pkthdr.len = m->m_len = sizeof(struct ip6_hdr) + icmp6len;
923         m->m_data += max_linkhdr;       /* or MH_ALIGN() equivalent? */
924
925         /* fill neighbor advertisement packet */
926         ip6 = mtod(m, struct ip6_hdr *);
927         ip6->ip6_flow = 0;
928         ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
929         ip6->ip6_vfc |= IPV6_VERSION;
930         ip6->ip6_nxt = IPPROTO_ICMPV6;
931         ip6->ip6_hlim = 255;
932         if (IN6_IS_ADDR_UNSPECIFIED(daddr6)) {
933                 /* reply to DAD */
934                 ip6->ip6_dst.s6_addr16[0] = IPV6_ADDR_INT16_MLL;
935                 ip6->ip6_dst.s6_addr16[1] = htons(ifp->if_index);
936                 ip6->ip6_dst.s6_addr32[1] = 0;
937                 ip6->ip6_dst.s6_addr32[2] = 0;
938                 ip6->ip6_dst.s6_addr32[3] = IPV6_ADDR_INT32_ONE;
939                 flags &= ~ND_NA_FLAG_SOLICITED;
940         } else
941                 ip6->ip6_dst = *daddr6;
942
943         /*
944          * Select a source whose scope is the same as that of the dest.
945          */
946         ia = in6_ifawithifp(ifp, &ip6->ip6_dst);
947         if (ia == NULL) {
948                 m_freem(m);
949                 return;
950         }
951         ip6->ip6_src = ia->ia_addr.sin6_addr;
952         nd_na = (struct nd_neighbor_advert *)(ip6 + 1);
953         nd_na->nd_na_type = ND_NEIGHBOR_ADVERT;
954         nd_na->nd_na_code = 0;
955         nd_na->nd_na_target = *taddr6;
956         if (IN6_IS_SCOPE_LINKLOCAL(&nd_na->nd_na_target))
957                 nd_na->nd_na_target.s6_addr16[1] = 0;
958
959         /*
960          * "tlladdr" indicates NS's condition for adding tlladdr or not.
961          * see nd6_ns_input() for details.
962          * Basically, if NS packet is sent to unicast/anycast addr,
963          * target lladdr option SHOULD NOT be included.
964          */
965         mac = NULL;
966         if (tlladdr) {
967                 /*
968                  * sdl0 != NULL indicates proxy NA.  If we do proxy, use
969                  * lladdr in sdl0.  If we are not proxying (sending NA for
970                  * my address) use lladdr configured for the interface.
971                  */
972                 if (sdl0 == NULL) {
973 #ifdef CARP
974                         if (ifp->if_carp)
975                                 mac = carp_macmatch6(ifp->if_carp, m, taddr6);
976                         if (mac == NULL)
977                                 mac = nd6_ifptomac(ifp);
978 #else
979                         mac = nd6_ifptomac(ifp);
980 #endif
981                 } else if (sdl0->sa_family == AF_LINK) {
982                         struct sockaddr_dl *sdl;
983                         sdl = (struct sockaddr_dl *)sdl0;
984                         if (sdl->sdl_alen == ifp->if_addrlen)
985                                 mac = LLADDR(sdl);
986                 }
987         }
988         if (mac != NULL) {
989                 int optlen = sizeof(struct nd_opt_hdr) + ifp->if_addrlen;
990                 struct nd_opt_hdr *nd_opt = (struct nd_opt_hdr *)(nd_na + 1);
991
992                 /* roundup to 8 bytes alignment! */
993                 optlen = (optlen + 7) & ~7;
994
995                 m->m_pkthdr.len += optlen;
996                 m->m_len += optlen;
997                 icmp6len += optlen;
998                 bzero((caddr_t)nd_opt, optlen);
999                 nd_opt->nd_opt_type = ND_OPT_TARGET_LINKADDR;
1000                 nd_opt->nd_opt_len = optlen >> 3;
1001                 bcopy(mac, (caddr_t)(nd_opt + 1), ifp->if_addrlen);
1002         } else
1003                 flags &= ~ND_NA_FLAG_OVERRIDE;
1004
1005         ip6->ip6_plen = htons((u_short)icmp6len);
1006         nd_na->nd_na_flags_reserved = flags;
1007         nd_na->nd_na_cksum = 0;
1008         nd_na->nd_na_cksum =
1009             in6_cksum(m, IPPROTO_ICMPV6, sizeof(struct ip6_hdr), icmp6len);
1010
1011         ip6_output(m, NULL, NULL, 0, &im6o, &outif, NULL);
1012         if (outif) {
1013                 icmp6_ifstat_inc(outif, ifs6_out_msg);
1014                 icmp6_ifstat_inc(outif, ifs6_out_neighboradvert);
1015         }
1016         icmp6stat.icp6s_outhist[ND_NEIGHBOR_ADVERT]++;
1017 }
1018
1019 caddr_t
1020 nd6_ifptomac(struct ifnet *ifp)
1021 {
1022         switch (ifp->if_type) {
1023         case IFT_ETHER:
1024         case IFT_IEEE1394:
1025 #ifdef IFT_L2VLAN
1026         case IFT_L2VLAN:
1027 #endif
1028 #ifdef IFT_IEEE80211
1029         case IFT_IEEE80211:
1030 #endif
1031 #ifdef IFT_CARP
1032         case IFT_CARP:
1033 #endif
1034                 return ((caddr_t)(ifp + 1));
1035         default:
1036                 return NULL;
1037         }
1038 }
1039
1040 struct netmsg_dad {
1041         struct netmsg_base      base;
1042         struct dadq             *dadq;
1043 };
1044
1045 struct dadq {
1046         TAILQ_ENTRY(dadq) dad_list;
1047         struct ifaddr *dad_ifa;
1048         int dad_count;          /* max NS to send */
1049         int dad_ns_tcount;      /* # of trials to send NS */
1050         int dad_ns_ocount;      /* NS sent so far */
1051         int dad_ns_icount;
1052         int dad_na_icount;
1053         struct callout dad_timer_ch;
1054         struct netmsg_dad dad_nmsg;
1055 };
1056 TAILQ_HEAD(dadq_head, dadq);
1057
1058 static struct dadq_head dadq = TAILQ_HEAD_INITIALIZER(dadq);
1059
1060 static struct dadq *
1061 nd6_dad_find(struct ifaddr *ifa)
1062 {
1063         struct dadq *dp;
1064
1065         ASSERT_IN_NETISR(0);
1066
1067         TAILQ_FOREACH(dp, &dadq, dad_list) {
1068                 if (dp->dad_ifa == ifa)
1069                         return dp;
1070         }
1071         return NULL;
1072 }
1073
1074 static void
1075 nd6_dad_starttimer(struct dadq *dp, int ticks)
1076 {
1077         ASSERT_IN_NETISR(0);
1078         callout_reset(&dp->dad_timer_ch, ticks, nd6_dad_timer, dp);
1079 }
1080
1081 static void
1082 nd6_dad_stoptimer(struct dadq *dp)
1083 {
1084         ASSERT_IN_NETISR(0);
1085         callout_stop(&dp->dad_timer_ch);
1086 }
1087
1088 /*
1089  * Start Duplicated Address Detection (DAD) for specified interface address.
1090  */
1091 void
1092 nd6_dad_start(struct ifaddr *ifa,
1093               int *tick)        /* minimum delay ticks for IFF_UP event */
1094 {
1095         struct in6_ifaddr *ia = (struct in6_ifaddr *)ifa;
1096         struct dadq *dp;
1097
1098         ASSERT_IN_NETISR(0);
1099
1100         /*
1101          * If we don't need DAD, don't do it.
1102          * There are several cases:
1103          * - DAD is disabled (ip6_dad_count == 0)
1104          * - the interface address is anycast
1105          */
1106         if (!(ia->ia6_flags & IN6_IFF_TENTATIVE)) {
1107                 log(LOG_DEBUG,
1108                         "nd6_dad_start: called with non-tentative address "
1109                         "%s(%s)\n",
1110                         ip6_sprintf(&ia->ia_addr.sin6_addr),
1111                         ifa->ifa_ifp ? if_name(ifa->ifa_ifp) : "???");
1112                 return;
1113         }
1114         if (ia->ia6_flags & IN6_IFF_ANYCAST) {
1115                 ia->ia6_flags &= ~IN6_IFF_TENTATIVE;
1116                 return;
1117         }
1118         if (!ip6_dad_count) {
1119                 ia->ia6_flags &= ~IN6_IFF_TENTATIVE;
1120                 return;
1121         }
1122         if (!ifa->ifa_ifp)
1123                 panic("nd6_dad_start: ifa->ifa_ifp == NULL");
1124         if (!(ifa->ifa_ifp->if_flags & IFF_UP))
1125                 return;
1126         if (nd6_dad_find(ifa) != NULL) {
1127                 /* DAD already in progress */
1128                 return;
1129         }
1130
1131         dp = nd6_dad_create(ifa);
1132         nd6log((LOG_DEBUG, "%s: starting DAD for %s\n", if_name(ifa->ifa_ifp),
1133             ip6_sprintf(&ia->ia_addr.sin6_addr)));
1134
1135         /*
1136          * Send NS packet for DAD, dp->dad_count times.
1137          * Note that we must delay the first transmission, if this is the
1138          * first packet to be sent from the interface after interface
1139          * (re)initialization.
1140          */
1141         if (tick == NULL) {
1142                 nd6_dad_ns_output(dp);
1143                 nd6_dad_starttimer(dp,
1144                     ND_IFINFO(ifa->ifa_ifp)->retrans * hz / 1000);
1145         } else {
1146                 int ntick;
1147
1148                 if (*tick == 0)
1149                         ntick = krandom() % (MAX_RTR_SOLICITATION_DELAY * hz);
1150                 else
1151                         ntick = *tick + krandom() % (hz / 2);
1152                 *tick = ntick;
1153                 nd6_dad_starttimer(dp, ntick);
1154         }
1155 }
1156
1157 /*
1158  * Terminate DAD unconditionally.  Used for address removals.
1159  */
1160 void
1161 nd6_dad_stop(struct ifaddr *ifa)
1162 {
1163         struct dadq *dp;
1164
1165         ASSERT_IN_NETISR(0);
1166
1167         dp = nd6_dad_find(ifa);
1168         if (!dp) {
1169                 /* DAD wasn't started yet */
1170                 return;
1171         }
1172         nd6_dad_destroy(dp);
1173 }
1174
1175 static struct dadq *
1176 nd6_dad_create(struct ifaddr *ifa)
1177 {
1178         struct netmsg_dad *dm;
1179         struct dadq *dp;
1180
1181         ASSERT_IN_NETISR(0);
1182
1183         dp = kmalloc(sizeof(*dp), M_IP6NDP, M_INTWAIT | M_ZERO);
1184         callout_init_mp(&dp->dad_timer_ch);
1185
1186         dm = &dp->dad_nmsg;
1187         netmsg_init(&dm->base, NULL, &netisr_adone_rport,
1188             MSGF_DROPABLE | MSGF_PRIORITY, nd6_dad_timer_handler);
1189         dm->dadq = dp;
1190
1191         dp->dad_ifa = ifa;
1192         IFAREF(ifa);    /* just for safety */
1193
1194         /* Send NS packet for DAD, ip6_dad_count times. */
1195         dp->dad_count = ip6_dad_count;
1196
1197         TAILQ_INSERT_TAIL(&dadq, dp, dad_list);
1198
1199         return dp;
1200 }
1201
1202 static void
1203 nd6_dad_destroy(struct dadq *dp)
1204 {
1205         struct lwkt_msg *lmsg = &dp->dad_nmsg.base.lmsg;
1206
1207         ASSERT_IN_NETISR(0);
1208
1209         TAILQ_REMOVE(&dadq, dp, dad_list);
1210
1211         nd6_dad_stoptimer(dp);
1212
1213         crit_enter();
1214         if ((lmsg->ms_flags & MSGF_DONE) == 0)
1215                 lwkt_dropmsg(lmsg);
1216         crit_exit();
1217
1218         IFAFREE(dp->dad_ifa);
1219         kfree(dp, M_IP6NDP);
1220 }
1221
1222 static void
1223 nd6_dad_timer(void *xdp)
1224 {
1225         struct dadq *dp = xdp;
1226         struct lwkt_msg *lmsg = &dp->dad_nmsg.base.lmsg;
1227
1228         KASSERT(mycpuid == 0, ("dad timer not on cpu0"));
1229
1230         crit_enter();
1231         if (lmsg->ms_flags & MSGF_DONE)
1232                 lwkt_sendmsg_oncpu(netisr_cpuport(0), lmsg);
1233         crit_exit();
1234 }
1235
1236 static void
1237 nd6_dad_timer_handler(netmsg_t msg)
1238 {
1239         struct netmsg_dad *dm = (struct netmsg_dad *)msg;
1240         struct dadq *dp = dm->dadq;
1241         struct ifaddr *ifa = dp->dad_ifa;
1242         struct in6_ifaddr *ia = (struct in6_ifaddr *)ifa;
1243
1244         ASSERT_IN_NETISR(0);
1245
1246         /* Reply ASAP */
1247         crit_enter();
1248         lwkt_replymsg(&dm->base.lmsg, 0);
1249         crit_exit();
1250
1251         if (ia->ia6_flags & IN6_IFF_DUPLICATED) {
1252                 log(LOG_ERR, "nd6_dad_timer: called with duplicated address "
1253                         "%s(%s)\n",
1254                         ip6_sprintf(&ia->ia_addr.sin6_addr),
1255                         ifa->ifa_ifp ? if_name(ifa->ifa_ifp) : "???");
1256                 goto destroy;
1257         }
1258         if (!(ia->ia6_flags & IN6_IFF_TENTATIVE)) {
1259                 log(LOG_ERR, "nd6_dad_timer: called with non-tentative address "
1260                         "%s(%s)\n",
1261                         ip6_sprintf(&ia->ia_addr.sin6_addr),
1262                         ifa->ifa_ifp ? if_name(ifa->ifa_ifp) : "???");
1263                 goto destroy;
1264         }
1265
1266         /* Timed out with IFF_{RUNNING,UP} check */
1267         if (dp->dad_ns_tcount > dad_maxtry) {
1268                 nd6log((LOG_INFO, "%s: could not run DAD, driver problem?\n",
1269                     if_name(ifa->ifa_ifp)));
1270                 goto destroy;
1271         }
1272
1273         /* Need more checks? */
1274         if (dp->dad_ns_ocount < dp->dad_count) {
1275                 /*
1276                  * We have more NS to go.  Send NS packet for DAD.
1277                  */
1278                 nd6_dad_ns_output(dp);
1279                 nd6_dad_starttimer(dp,
1280                     ND_IFINFO(ifa->ifa_ifp)->retrans * hz / 1000);
1281         } else {
1282                 /*
1283                  * We have transmitted sufficient number of DAD packets.
1284                  * See what we've got.
1285                  */
1286                 int duplicate;
1287
1288                 duplicate = 0;
1289
1290                 if (dp->dad_na_icount) {
1291                         /*
1292                          * the check is in nd6_dad_na_input(),
1293                          * but just in case
1294                          */
1295                         duplicate++;
1296                 }
1297
1298                 if (dp->dad_ns_icount) {
1299 #if 0 /* heuristics */
1300                         /*
1301                          * if
1302                          * - we have sent many(?) DAD NS, and
1303                          * - the number of NS we sent equals to the
1304                          *   number of NS we've got, and
1305                          * - we've got no NA
1306                          * we may have a faulty network card/driver which
1307                          * loops back multicasts to myself.
1308                          */
1309                         if (3 < dp->dad_count
1310                          && dp->dad_ns_icount == dp->dad_count
1311                          && dp->dad_na_icount == 0) {
1312                                 log(LOG_INFO, "DAD questionable for %s(%s): "
1313                                     "network card loops back multicast?\n",
1314                                     ip6_sprintf(&ia->ia_addr.sin6_addr),
1315                                     if_name(ifa->ifa_ifp));
1316                                 /* XXX consider it a duplicate or not? */
1317                                 /* duplicate++; */
1318                         } else {
1319                                 /* We've seen NS, means DAD has failed. */
1320                                 duplicate++;
1321                         }
1322 #else
1323                         /* We've seen NS, means DAD has failed. */
1324                         duplicate++;
1325 #endif
1326                 }
1327
1328                 if (duplicate) {
1329                         /* dp will be freed in nd6_dad_duplicated() */
1330                         dp = NULL;
1331                         nd6_dad_duplicated(ifa);
1332                 } else {
1333                         /*
1334                          * We are done with DAD.  No NA came, no NS came.
1335                          * duplicated address found.
1336                          */
1337                         ia->ia6_flags &= ~IN6_IFF_TENTATIVE;
1338                         nd6log((LOG_DEBUG,
1339                             "%s: DAD complete for %s - no duplicates found\n",
1340                             if_name(ifa->ifa_ifp),
1341                             ip6_sprintf(&ia->ia_addr.sin6_addr)));
1342                         goto destroy;
1343                 }
1344         }
1345         return;
1346 destroy:
1347         nd6_dad_destroy(dp);
1348 }
1349
1350 static void
1351 nd6_dad_duplicated(struct ifaddr *ifa)
1352 {
1353         struct in6_ifaddr *ia = (struct in6_ifaddr *)ifa;
1354         struct dadq *dp;
1355
1356         ASSERT_IN_NETISR(0);
1357
1358         dp = nd6_dad_find(ifa);
1359         if (dp == NULL) {
1360                 log(LOG_ERR, "nd6_dad_duplicated: DAD structure not found\n");
1361                 return;
1362         }
1363
1364         /*
1365          * We are done with DAD, with duplicated address found. (failure)
1366          */
1367         log(LOG_ERR, "%s: DAD detected duplicate IPv6 address %s: "
1368             "NS in/out=%d/%d, NA in=%d\n",
1369             if_name(ifa->ifa_ifp), ip6_sprintf(&ia->ia_addr.sin6_addr),
1370             dp->dad_ns_icount, dp->dad_ns_ocount, dp->dad_na_icount);
1371
1372         ia->ia6_flags &= ~IN6_IFF_TENTATIVE;
1373         ia->ia6_flags |= IN6_IFF_DUPLICATED;
1374
1375         log(LOG_ERR, "%s: DAD complete for %s - duplicate found\n",
1376             if_name(ifa->ifa_ifp), ip6_sprintf(&ia->ia_addr.sin6_addr));
1377         log(LOG_ERR, "%s: manual intervention required\n",
1378             if_name(ifa->ifa_ifp));
1379
1380         nd6_dad_destroy(dp);
1381 }
1382
1383 static void
1384 nd6_dad_ns_output(struct dadq *dp)
1385 {
1386         struct in6_ifaddr *ia = (struct in6_ifaddr *)dp->dad_ifa;
1387         struct ifnet *ifp = dp->dad_ifa->ifa_ifp;
1388
1389         ASSERT_IN_NETISR(0);
1390
1391         dp->dad_ns_tcount++;
1392         if (!(ifp->if_flags & IFF_UP)) {
1393 #if 0
1394                 kprintf("%s: interface down?\n", if_name(ifp));
1395 #endif
1396                 return;
1397         }
1398         if (!(ifp->if_flags & IFF_RUNNING)) {
1399 #if 0
1400                 kprintf("%s: interface not running?\n", if_name(ifp));
1401 #endif
1402                 return;
1403         }
1404
1405         dp->dad_ns_ocount++;
1406         nd6_ns_output(ifp, NULL, &ia->ia_addr.sin6_addr, NULL, 1);
1407 }
1408
1409 static void
1410 nd6_dad_ns_input(struct ifaddr *ifa)
1411 {
1412         struct in6_ifaddr *ia;
1413         const struct in6_addr *taddr6;
1414         struct dadq *dp;
1415         int duplicate;
1416
1417         ASSERT_IN_NETISR(0);
1418
1419         if (!ifa)
1420                 panic("ifa == NULL in nd6_dad_ns_input");
1421
1422         ia = (struct in6_ifaddr *)ifa;
1423         taddr6 = &ia->ia_addr.sin6_addr;
1424         duplicate = 0;
1425         dp = nd6_dad_find(ifa);
1426
1427         /* Quickhack - completely ignore DAD NS packets */
1428         if (dad_ignore_ns) {
1429                 nd6log((LOG_INFO,
1430                     "nd6_dad_ns_input: ignoring DAD NS packet for "
1431                     "address %s(%s)\n", ip6_sprintf(taddr6),
1432                     if_name(ifa->ifa_ifp)));
1433                 return;
1434         }
1435
1436         /*
1437          * if I'm yet to start DAD, someone else started using this address
1438          * first.  I have a duplicate and you win.
1439          */
1440         if (!dp || dp->dad_ns_ocount == 0)
1441                 duplicate++;
1442
1443         /* XXX more checks for loopback situation - see nd6_dad_timer too */
1444
1445         if (duplicate) {
1446                 dp = NULL;      /* will be freed in nd6_dad_duplicated() */
1447                 nd6_dad_duplicated(ifa);
1448         } else {
1449                 /*
1450                  * not sure if I got a duplicate.
1451                  * increment ns count and see what happens.
1452                  */
1453                 if (dp)
1454                         dp->dad_ns_icount++;
1455         }
1456 }
1457
1458 static void
1459 nd6_dad_na_input(struct ifaddr *ifa)
1460 {
1461         struct dadq *dp;
1462
1463         ASSERT_IN_NETISR(0);
1464
1465         if (!ifa)
1466                 panic("ifa == NULL in nd6_dad_na_input");
1467
1468         dp = nd6_dad_find(ifa);
1469         if (dp)
1470                 dp->dad_na_icount++;
1471
1472         /* remove the address. */
1473         nd6_dad_duplicated(ifa);
1474 }