Merge branch 'master' into net80211-update
[dragonfly.git] / sys / netinet6 / in6.c
1 /*      $FreeBSD: src/sys/netinet6/in6.c,v 1.7.2.9 2002/04/28 05:40:26 suz Exp $        */
2 /*      $DragonFly: src/sys/netinet6/in6.c,v 1.30 2008/10/03 07:59:20 hasso Exp $       */
3 /*      $KAME: in6.c,v 1.259 2002/01/21 11:37:50 keiichi Exp $  */
4
5 /*
6  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the project nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 /*
35  * Copyright (c) 1982, 1986, 1991, 1993
36  *      The Regents of the University of California.  All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. All advertising materials mentioning features or use of this software
47  *    must display the following acknowledgement:
48  *      This product includes software developed by the University of
49  *      California, Berkeley and its contributors.
50  * 4. Neither the name of the University nor the names of its contributors
51  *    may be used to endorse or promote products derived from this software
52  *    without specific prior written permission.
53  *
54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64  * SUCH DAMAGE.
65  *
66  *      @(#)in.c        8.2 (Berkeley) 11/15/93
67  */
68
69 #include "opt_inet.h"
70 #include "opt_inet6.h"
71
72 #include <sys/param.h>
73 #include <sys/errno.h>
74 #include <sys/malloc.h>
75 #include <sys/socket.h>
76 #include <sys/socketvar.h>
77 #include <sys/sockio.h>
78 #include <sys/systm.h>
79 #include <sys/proc.h>
80 #include <sys/priv.h>
81 #include <sys/time.h>
82 #include <sys/kernel.h>
83 #include <sys/syslog.h>
84 #include <sys/thread2.h>
85
86 #include <net/if.h>
87 #include <net/if_types.h>
88 #include <net/route.h>
89 #include <net/if_dl.h>
90
91 #include <netinet/in.h>
92 #include <netinet/in_var.h>
93 #include <netinet/if_ether.h>
94 #include <netinet/in_systm.h>
95 #include <netinet/ip.h>
96 #include <netinet/in_pcb.h>
97
98 #include <netinet/ip6.h>
99 #include <netinet6/ip6_var.h>
100 #include <netinet6/nd6.h>
101 #include <netinet6/mld6_var.h>
102 #include <netinet6/ip6_mroute.h>
103 #include <netinet6/in6_ifattach.h>
104 #include <netinet6/scope6_var.h>
105 #include <netinet6/in6_pcb.h>
106 #include <netinet6/in6_var.h>
107
108 #include <net/net_osdep.h>
109
110 /*
111  * Definitions of some costant IP6 addresses.
112  */
113 const struct in6_addr kin6addr_any = IN6ADDR_ANY_INIT;
114 const struct in6_addr kin6addr_loopback = IN6ADDR_LOOPBACK_INIT;
115 const struct in6_addr kin6addr_nodelocal_allnodes =
116         IN6ADDR_NODELOCAL_ALLNODES_INIT;
117 const struct in6_addr kin6addr_linklocal_allnodes =
118         IN6ADDR_LINKLOCAL_ALLNODES_INIT;
119 const struct in6_addr kin6addr_linklocal_allrouters =
120         IN6ADDR_LINKLOCAL_ALLROUTERS_INIT;
121
122 const struct in6_addr in6mask0 = IN6MASK0;
123 const struct in6_addr in6mask32 = IN6MASK32;
124 const struct in6_addr in6mask64 = IN6MASK64;
125 const struct in6_addr in6mask96 = IN6MASK96;
126 const struct in6_addr in6mask128 = IN6MASK128;
127
128 const struct sockaddr_in6 sa6_any = {sizeof(sa6_any), AF_INET6,
129                                      0, 0, IN6ADDR_ANY_INIT, 0};
130
131 static int in6_lifaddr_ioctl (struct socket *, u_long, caddr_t,
132         struct ifnet *, struct thread *);
133 static int in6_ifinit (struct ifnet *, struct in6_ifaddr *,
134                            struct sockaddr_in6 *, int);
135 static void in6_unlink_ifa (struct in6_ifaddr *, struct ifnet *);
136 static void in6_ifloop_request_callback(int, int, struct rt_addrinfo *, struct rtentry *, void *);
137
138 struct in6_multihead in6_multihead;     /* XXX BSS initialization */
139
140 int     (*faithprefix_p)(struct in6_addr *);
141
142 /*
143  * Subroutine for in6_ifaddloop() and in6_ifremloop().
144  * This routine does actual work.
145  */
146 static void
147 in6_ifloop_request(int cmd, struct ifaddr *ifa)
148 {
149         struct sockaddr_in6 all1_sa;
150         struct rt_addrinfo rtinfo;
151         int error;
152
153         bzero(&all1_sa, sizeof(all1_sa));
154         all1_sa.sin6_family = AF_INET6;
155         all1_sa.sin6_len = sizeof(struct sockaddr_in6);
156         all1_sa.sin6_addr = in6mask128;
157
158         /*
159          * We specify the address itself as the gateway, and set the
160          * RTF_LLINFO flag, so that the corresponding host route would have
161          * the flag, and thus applications that assume traditional behavior
162          * would be happy.  Note that we assume the caller of the function
163          * (probably implicitly) set nd6_rtrequest() to ifa->ifa_rtrequest,
164          * which changes the outgoing interface to the loopback interface.
165          */
166         bzero(&rtinfo, sizeof(struct rt_addrinfo));
167         rtinfo.rti_info[RTAX_DST] = ifa->ifa_addr;
168         rtinfo.rti_info[RTAX_GATEWAY] = ifa->ifa_addr;
169         rtinfo.rti_info[RTAX_NETMASK] = (struct sockaddr *)&all1_sa;
170         rtinfo.rti_flags = RTF_UP|RTF_HOST|RTF_LLINFO;
171
172         error = rtrequest1_global(cmd, &rtinfo,
173                                   in6_ifloop_request_callback, ifa);
174         if (error != 0) {
175                 log(LOG_ERR, "in6_ifloop_request: "
176                     "%s operation failed for %s (errno=%d)\n",
177                     cmd == RTM_ADD ? "ADD" : "DELETE",
178                     ip6_sprintf(&((struct in6_ifaddr *)ifa)->ia_addr.sin6_addr),
179                     error);
180         }
181 }
182
183 static void
184 in6_ifloop_request_callback(int cmd, int error, struct rt_addrinfo *rtinfo,
185                             struct rtentry *rt, void *arg)
186 {
187         struct ifaddr *ifa = arg;
188
189         if (error)
190                 goto done;
191
192         /*
193          * Make sure rt_ifa be equal to IFA, the second argument of the
194          * function.
195          * We need this because when we refer to rt_ifa->ia6_flags in
196          * ip6_input, we assume that the rt_ifa points to the address instead
197          * of the loopback address.
198          */
199         if (cmd == RTM_ADD && rt && ifa != rt->rt_ifa) {
200                 ++rt->rt_refcnt;
201                 IFAFREE(rt->rt_ifa);
202                 IFAREF(ifa);
203                 rt->rt_ifa = ifa;
204                 --rt->rt_refcnt;
205         }
206
207         /*
208          * Report the addition/removal of the address to the routing socket.
209          * XXX: since we called rtinit for a p2p interface with a destination,
210          *      we end up reporting twice in such a case.  Should we rather
211          *      omit the second report?
212          */
213         if (rt) {
214                 if (mycpuid == 0)
215                         rt_newaddrmsg(cmd, ifa, error, rt);
216                 if (cmd == RTM_DELETE) {
217                         if (rt->rt_refcnt == 0) {
218                                 ++rt->rt_refcnt;
219                                 rtfree(rt);
220                         }
221                 }
222         }
223 done:
224         /* no way to return any new error */
225         ;
226 }
227
228 /*
229  * Add ownaddr as loopback rtentry.  We previously add the route only if
230  * necessary (ex. on a p2p link).  However, since we now manage addresses
231  * separately from prefixes, we should always add the route.  We can't
232  * rely on the cloning mechanism from the corresponding interface route
233  * any more.
234  */
235 void
236 in6_ifaddloop(struct ifaddr *ifa)
237 {
238         struct rtentry *rt;
239
240         /* If there is no loopback entry, allocate one. */
241         rt = rtpurelookup(ifa->ifa_addr);
242         if (rt == NULL || !(rt->rt_flags & RTF_HOST) ||
243             !(rt->rt_ifp->if_flags & IFF_LOOPBACK))
244                 in6_ifloop_request(RTM_ADD, ifa);
245         if (rt != NULL)
246                 rt->rt_refcnt--;
247 }
248
249 /*
250  * Remove loopback rtentry of ownaddr generated by in6_ifaddloop(),
251  * if it exists.
252  */
253 void
254 in6_ifremloop(struct ifaddr *ifa)
255 {
256         struct in6_ifaddr *ia;
257         struct rtentry *rt;
258         int ia_count = 0;
259
260         /*
261          * Some of BSD variants do not remove cloned routes
262          * from an interface direct route, when removing the direct route
263          * (see comments in net/net_osdep.h).  Even for variants that do remove
264          * cloned routes, they could fail to remove the cloned routes when
265          * we handle multple addresses that share a common prefix.
266          * So, we should remove the route corresponding to the deleted address
267          * regardless of the result of in6_is_ifloop_auto().
268          */
269
270         /*
271          * Delete the entry only if exact one ifa exists.  More than one ifa
272          * can exist if we assign a same single address to multiple
273          * (probably p2p) interfaces.
274          * XXX: we should avoid such a configuration in IPv6...
275          */
276         for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
277                 if (IN6_ARE_ADDR_EQUAL(IFA_IN6(ifa), &ia->ia_addr.sin6_addr)) {
278                         ia_count++;
279                         if (ia_count > 1)
280                                 break;
281                 }
282         }
283
284         if (ia_count == 1) {
285                 /*
286                  * Before deleting, check if a corresponding loopbacked host
287                  * route surely exists.  With this check, we can avoid to
288                  * delete an interface direct route whose destination is same
289                  * as the address being removed.  This can happen when remofing
290                  * a subnet-router anycast address on an interface attahced
291                  * to a shared medium.
292                  */
293                 rt = rtpurelookup(ifa->ifa_addr);
294                 if (rt != NULL && (rt->rt_flags & RTF_HOST) &&
295                     (rt->rt_ifp->if_flags & IFF_LOOPBACK)) {
296                         rt->rt_refcnt--;
297                         in6_ifloop_request(RTM_DELETE, ifa);
298                 }
299         }
300 }
301
302 int
303 in6_ifindex2scopeid(int idx)
304 {
305         struct ifnet *ifp;
306         struct sockaddr_in6 *sin6;
307         struct ifaddr_container *ifac;
308
309         if (idx < 0 || if_index < idx)
310                 return -1;
311         ifp = ifindex2ifnet[idx];
312
313         TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link)
314         {
315                 struct ifaddr *ifa = ifac->ifa;
316
317                 if (ifa->ifa_addr->sa_family != AF_INET6)
318                         continue;
319                 sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
320                 if (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr))
321                         return sin6->sin6_scope_id & 0xffff;
322         }
323
324         return -1;
325 }
326
327 int
328 in6_mask2len(struct in6_addr *mask, u_char *lim0)
329 {
330         int x = 0, y;
331         u_char *lim = lim0, *p;
332
333         if (lim0 == NULL ||
334             lim0 - (u_char *)mask > sizeof(*mask)) /* ignore the scope_id part */
335                 lim = (u_char *)mask + sizeof(*mask);
336         for (p = (u_char *)mask; p < lim; x++, p++) {
337                 if (*p != 0xff)
338                         break;
339         }
340         y = 0;
341         if (p < lim) {
342                 for (y = 0; y < 8; y++) {
343                         if ((*p & (0x80 >> y)) == 0)
344                                 break;
345                 }
346         }
347
348         /*
349          * when the limit pointer is given, do a stricter check on the
350          * remaining bits.
351          */
352         if (p < lim) {
353                 if (y != 0 && (*p & (0x00ff >> y)) != 0)
354                         return (-1);
355                 for (p = p + 1; p < lim; p++)
356                         if (*p != 0)
357                                 return (-1);
358         }
359
360         return x * 8 + y;
361 }
362
363 void
364 in6_len2mask(struct in6_addr *mask, int len)
365 {
366         int i;
367
368         bzero(mask, sizeof(*mask));
369         for (i = 0; i < len / 8; i++)
370                 mask->s6_addr8[i] = 0xff;
371         if (len % 8)
372                 mask->s6_addr8[i] = (0xff00 >> (len % 8)) & 0xff;
373 }
374
375 #define ifa2ia6(ifa)    ((struct in6_ifaddr *)(ifa))
376 #define ia62ifa(ia6)    (&((ia6)->ia_ifa))
377
378 int
379 in6_control(struct socket *so, u_long cmd, caddr_t data,
380             struct ifnet *ifp, struct thread *td)
381 {
382         struct  in6_ifreq *ifr = (struct in6_ifreq *)data;
383         struct  in6_ifaddr *ia = NULL;
384         struct  in6_aliasreq *ifra = (struct in6_aliasreq *)data;
385         int privileged;
386         int error;
387
388         privileged = 0;
389         if (priv_check(td, PRIV_ROOT) == 0)
390                 privileged++;
391
392         switch (cmd) {
393         case SIOCGETSGCNT_IN6:
394         case SIOCGETMIFCNT_IN6:
395                 return (mrt6_ioctl(cmd, data));
396         }
397
398         switch(cmd) {
399         case SIOCAADDRCTL_POLICY:
400         case SIOCDADDRCTL_POLICY:
401                 if (!privileged)
402                         return (EPERM);
403                 return (in6_src_ioctl(cmd, data));
404         }
405
406         if (ifp == NULL)
407                 return (EOPNOTSUPP);
408
409         switch (cmd) {
410         case SIOCSNDFLUSH_IN6:
411         case SIOCSPFXFLUSH_IN6:
412         case SIOCSRTRFLUSH_IN6:
413         case SIOCSDEFIFACE_IN6:
414         case SIOCSIFINFO_FLAGS:
415                 if (!privileged)
416                         return (EPERM);
417                 /* fall through */
418         case OSIOCGIFINFO_IN6:
419         case SIOCGIFINFO_IN6:
420         case SIOCGDRLST_IN6:
421         case SIOCGPRLST_IN6:
422         case SIOCGNBRINFO_IN6:
423         case SIOCGDEFIFACE_IN6:
424                 return (nd6_ioctl(cmd, data, ifp));
425         }
426
427         switch (cmd) {
428         case SIOCSIFPREFIX_IN6:
429         case SIOCDIFPREFIX_IN6:
430         case SIOCAIFPREFIX_IN6:
431         case SIOCCIFPREFIX_IN6:
432         case SIOCSGIFPREFIX_IN6:
433         case SIOCGIFPREFIX_IN6:
434                 log(LOG_NOTICE,
435                     "prefix ioctls are now invalidated. "
436                     "please use ifconfig.\n");
437                 return (EOPNOTSUPP);
438         }
439
440         switch (cmd) {
441         case SIOCSSCOPE6:
442                 if (!privileged)
443                         return (EPERM);
444                 return (scope6_set(ifp,
445                         (struct scope6_id *)ifr->ifr_ifru.ifru_scope_id));
446                 break;
447         case SIOCGSCOPE6:
448                 return (scope6_get(ifp,
449                         (struct scope6_id *)ifr->ifr_ifru.ifru_scope_id));
450                 break;
451         case SIOCGSCOPE6DEF:
452                 return (scope6_get_default((struct scope6_id *)
453                         ifr->ifr_ifru.ifru_scope_id));
454                 break;
455         }
456
457         switch (cmd) {
458         case SIOCALIFADDR:
459         case SIOCDLIFADDR:
460                 if (!privileged)
461                         return (EPERM);
462                 /* fall through */
463         case SIOCGLIFADDR:
464                 return in6_lifaddr_ioctl(so, cmd, data, ifp, td);
465         }
466
467         /*
468          * Find address for this interface, if it exists.
469          */
470         if (ifra->ifra_addr.sin6_family == AF_INET6) { /* XXX */
471                 struct sockaddr_in6 *sa6 =
472                         (struct sockaddr_in6 *)&ifra->ifra_addr;
473
474                 if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr)) {
475                         if (sa6->sin6_addr.s6_addr16[1] == 0) {
476                                 /* link ID is not embedded by the user */
477                                 sa6->sin6_addr.s6_addr16[1] =
478                                         htons(ifp->if_index);
479                         } else if (sa6->sin6_addr.s6_addr16[1] !=
480                                     htons(ifp->if_index)) {
481                                 return (EINVAL);        /* link ID contradicts */
482                         }
483                         if (sa6->sin6_scope_id) {
484                                 if (sa6->sin6_scope_id !=
485                                     (u_int32_t)ifp->if_index)
486                                         return (EINVAL);
487                                 sa6->sin6_scope_id = 0; /* XXX: good way? */
488                         }
489                 }
490                 ia = in6ifa_ifpwithaddr(ifp, &ifra->ifra_addr.sin6_addr);
491         }
492
493         switch (cmd) {
494         case SIOCSIFADDR_IN6:
495         case SIOCSIFDSTADDR_IN6:
496         case SIOCSIFNETMASK_IN6:
497                 /*
498                  * Since IPv6 allows a node to assign multiple addresses
499                  * on a single interface, SIOCSIFxxx ioctls are not suitable
500                  * and should be unused.
501                  */
502                 /* we decided to obsolete this command (20000704) */
503                 return (EINVAL);
504
505         case SIOCDIFADDR_IN6:
506                 /*
507                  * for IPv4, we look for existing in_ifaddr here to allow
508                  * "ifconfig if0 delete" to remove first IPv4 address on the
509                  * interface.  For IPv6, as the spec allow multiple interface
510                  * address from the day one, we consider "remove the first one"
511                  * semantics to be not preferable.
512                  */
513                 if (ia == NULL)
514                         return (EADDRNOTAVAIL);
515                 /* FALLTHROUGH */
516         case SIOCAIFADDR_IN6:
517                 /*
518                  * We always require users to specify a valid IPv6 address for
519                  * the corresponding operation.
520                  */
521                 if (ifra->ifra_addr.sin6_family != AF_INET6 ||
522                     ifra->ifra_addr.sin6_len != sizeof(struct sockaddr_in6))
523                         return (EAFNOSUPPORT);
524                 if (!privileged)
525                         return (EPERM);
526
527                 break;
528
529         case SIOCGIFADDR_IN6:
530                 /* This interface is basically deprecated. use SIOCGIFCONF. */
531                 /* fall through */
532         case SIOCGIFAFLAG_IN6:
533         case SIOCGIFNETMASK_IN6:
534         case SIOCGIFDSTADDR_IN6:
535         case SIOCGIFALIFETIME_IN6:
536                 /* must think again about its semantics */
537                 if (ia == NULL)
538                         return (EADDRNOTAVAIL);
539                 break;
540         case SIOCSIFALIFETIME_IN6:
541             {
542                 struct in6_addrlifetime *lt;
543
544                 if (!privileged)
545                         return (EPERM);
546                 if (ia == NULL)
547                         return (EADDRNOTAVAIL);
548                 /* sanity for overflow - beware unsigned */
549                 lt = &ifr->ifr_ifru.ifru_lifetime;
550                 if (lt->ia6t_vltime != ND6_INFINITE_LIFETIME
551                  && lt->ia6t_vltime + time_second < time_second) {
552                         return EINVAL;
553                 }
554                 if (lt->ia6t_pltime != ND6_INFINITE_LIFETIME
555                  && lt->ia6t_pltime + time_second < time_second) {
556                         return EINVAL;
557                 }
558                 break;
559             }
560         }
561
562         switch (cmd) {
563
564         case SIOCGIFADDR_IN6:
565                 ifr->ifr_addr = ia->ia_addr;
566                 break;
567
568         case SIOCGIFDSTADDR_IN6:
569                 if (!(ifp->if_flags & IFF_POINTOPOINT))
570                         return (EINVAL);
571                 /*
572                  * XXX: should we check if ifa_dstaddr is NULL and return
573                  * an error?
574                  */
575                 ifr->ifr_dstaddr = ia->ia_dstaddr;
576                 break;
577
578         case SIOCGIFNETMASK_IN6:
579                 ifr->ifr_addr = ia->ia_prefixmask;
580                 break;
581
582         case SIOCGIFAFLAG_IN6:
583                 ifr->ifr_ifru.ifru_flags6 = ia->ia6_flags;
584                 break;
585
586         case SIOCGIFSTAT_IN6:
587                 if (ifp == NULL)
588                         return EINVAL;
589                 bzero(&ifr->ifr_ifru.ifru_stat,
590                         sizeof(ifr->ifr_ifru.ifru_stat));
591                 ifr->ifr_ifru.ifru_stat =
592                         *((struct in6_ifextra *)ifp->if_afdata[AF_INET6])->in6_ifstat;
593                 break;
594
595         case SIOCGIFSTAT_ICMP6:
596                 bzero(&ifr->ifr_ifru.ifru_stat,
597                         sizeof(ifr->ifr_ifru.ifru_icmp6stat));
598                 ifr->ifr_ifru.ifru_icmp6stat =
599                         *((struct in6_ifextra *)ifp->if_afdata[AF_INET6])->icmp6_ifstat;
600                 break;
601
602         case SIOCGIFALIFETIME_IN6:
603                 ifr->ifr_ifru.ifru_lifetime = ia->ia6_lifetime;
604                 break;
605
606         case SIOCSIFALIFETIME_IN6:
607                 ia->ia6_lifetime = ifr->ifr_ifru.ifru_lifetime;
608                 /* for sanity */
609                 if (ia->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
610                         ia->ia6_lifetime.ia6t_expire =
611                                 time_second + ia->ia6_lifetime.ia6t_vltime;
612                 } else
613                         ia->ia6_lifetime.ia6t_expire = 0;
614                 if (ia->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
615                         ia->ia6_lifetime.ia6t_preferred =
616                                 time_second + ia->ia6_lifetime.ia6t_pltime;
617                 } else
618                         ia->ia6_lifetime.ia6t_preferred = 0;
619                 break;
620
621         case SIOCAIFADDR_IN6:
622         {
623                 int i, error = 0, iaIsNew;
624                 struct nd_prefix pr0, *pr;
625
626                 if (ia != NULL)
627                         iaIsNew = 0;
628                 else
629                         iaIsNew = 1;
630
631                 /*
632                  * first, make or update the interface address structure,
633                  * and link it to the list.
634                  */
635                 if ((error = in6_update_ifa(ifp, ifra, ia)) != 0)
636                         return (error);
637
638                 /*
639                  * then, make the prefix on-link on the interface.
640                  * XXX: we'd rather create the prefix before the address, but
641                  * we need at least one address to install the corresponding
642                  * interface route, so we configure the address first.
643                  */
644
645                 /*
646                  * convert mask to prefix length (prefixmask has already
647                  * been validated in in6_update_ifa().
648                  */
649                 bzero(&pr0, sizeof(pr0));
650                 pr0.ndpr_ifp = ifp;
651                 pr0.ndpr_plen = in6_mask2len(&ifra->ifra_prefixmask.sin6_addr,
652                                              NULL);
653                 if (pr0.ndpr_plen == 128)
654                         break;  /* we don't need to install a host route. */
655                 pr0.ndpr_prefix = ifra->ifra_addr;
656                 pr0.ndpr_mask = ifra->ifra_prefixmask.sin6_addr;
657                 /* apply the mask for safety. */
658                 for (i = 0; i < 4; i++) {
659                         pr0.ndpr_prefix.sin6_addr.s6_addr32[i] &=
660                                 ifra->ifra_prefixmask.sin6_addr.s6_addr32[i];
661                 }
662                 /*
663                  * XXX: since we don't have an API to set prefix (not address)
664                  * lifetimes, we just use the same lifetimes as addresses.
665                  * The (temporarily) installed lifetimes can be overridden by
666                  * later advertised RAs (when accept_rtadv is non 0), which is
667                  * an intended behavior.
668                  */
669                 pr0.ndpr_raf_onlink = 1; /* should be configurable? */
670                 pr0.ndpr_raf_auto =
671                         ((ifra->ifra_flags & IN6_IFF_AUTOCONF) != 0);
672                 pr0.ndpr_vltime = ifra->ifra_lifetime.ia6t_vltime;
673                 pr0.ndpr_pltime = ifra->ifra_lifetime.ia6t_pltime;
674
675                 /* add the prefix if there's one. */
676                 if ((pr = nd6_prefix_lookup(&pr0)) == NULL) {
677                         /*
678                          * nd6_prelist_add will install the corresponding
679                          * interface route.
680                          */
681                         if ((error = nd6_prelist_add(&pr0, NULL, &pr)) != 0)
682                                 return (error);
683                         if (pr == NULL) {
684                                 log(LOG_ERR, "nd6_prelist_add succeeded but "
685                                     "no prefix\n");
686                                 return (EINVAL); /* XXX panic here? */
687                         }
688                 }
689                 if ((ia = in6ifa_ifpwithaddr(ifp, &ifra->ifra_addr.sin6_addr))
690                     == NULL) {
691                         /* XXX: this should not happen! */
692                         log(LOG_ERR, "in6_control: addition succeeded, but"
693                             " no ifaddr\n");
694                 } else {
695                         if ((ia->ia6_flags & IN6_IFF_AUTOCONF) &&
696                             ia->ia6_ndpr == NULL) { /* new autoconfed addr */
697                                 ia->ia6_ndpr = pr;
698                                 pr->ndpr_refcnt++;
699
700                                 /*
701                                  * If this is the first autoconf address from
702                                  * the prefix, create a temporary address
703                                  * as well (when specified).
704                                  */
705                                 if (ip6_use_tempaddr &&
706                                     pr->ndpr_refcnt == 1) {
707                                         int e;
708                                         if ((e = in6_tmpifadd(ia, 1)) != 0) {
709                                                 log(LOG_NOTICE, "in6_control: "
710                                                     "failed to create a "
711                                                     "temporary address, "
712                                                     "errno=%d\n",
713                                                     e);
714                                         }
715                                 }
716                         }
717
718                         /*
719                          * this might affect the status of autoconfigured
720                          * addresses, that is, this address might make
721                          * other addresses detached.
722                          */
723                         pfxlist_onlink_check();
724                 }
725                 if (error == 0 && ia) {
726                         EVENTHANDLER_INVOKE(ifaddr_event, ifp,
727                         iaIsNew ? IFADDR_EVENT_ADD : IFADDR_EVENT_CHANGE,
728                         &ia->ia_ifa);
729                 }
730                 break;
731         }
732
733         case SIOCDIFADDR_IN6:
734         {
735                 int i = 0;
736                 struct nd_prefix pr0, *pr;
737
738                 /*
739                  * If the address being deleted is the only one that owns
740                  * the corresponding prefix, expire the prefix as well.
741                  * XXX: theoretically, we don't have to warry about such
742                  * relationship, since we separate the address management
743                  * and the prefix management.  We do this, however, to provide
744                  * as much backward compatibility as possible in terms of
745                  * the ioctl operation.
746                  */
747                 bzero(&pr0, sizeof(pr0));
748                 pr0.ndpr_ifp = ifp;
749                 pr0.ndpr_plen = in6_mask2len(&ia->ia_prefixmask.sin6_addr,
750                                              NULL);
751                 if (pr0.ndpr_plen == 128)
752                         goto purgeaddr;
753                 pr0.ndpr_prefix = ia->ia_addr;
754                 pr0.ndpr_mask = ia->ia_prefixmask.sin6_addr;
755                 for (i = 0; i < 4; i++) {
756                         pr0.ndpr_prefix.sin6_addr.s6_addr32[i] &=
757                                 ia->ia_prefixmask.sin6_addr.s6_addr32[i];
758                 }
759                 /*
760                  * The logic of the following condition is a bit complicated.
761                  * We expire the prefix when
762                  * 1. the address obeys autoconfiguration and it is the
763                  *    only owner of the associated prefix, or
764                  * 2. the address does not obey autoconf and there is no
765                  *    other owner of the prefix.
766                  */
767                 if ((pr = nd6_prefix_lookup(&pr0)) != NULL &&
768                     (((ia->ia6_flags & IN6_IFF_AUTOCONF) &&
769                        pr->ndpr_refcnt == 1) ||
770                      (!(ia->ia6_flags & IN6_IFF_AUTOCONF) &&
771                       pr->ndpr_refcnt == 0))) {
772                         pr->ndpr_expire = 1; /* XXX: just for expiration */
773                 }
774
775 purgeaddr:
776                 EVENTHANDLER_INVOKE(ifaddr_event, ifp, IFADDR_EVENT_DELETE,
777                                     &ia->ia_ifa);
778                 in6_purgeaddr(&ia->ia_ifa);
779                 break;
780         }
781
782         default:
783                 if (ifp == NULL || ifp->if_ioctl == 0)
784                         return (EOPNOTSUPP);
785                 ifnet_serialize_all(ifp);
786                 error = ifp->if_ioctl(ifp, cmd, data, td->td_proc->p_ucred);
787                 ifnet_deserialize_all(ifp);
788                 return (error);
789         }
790
791         return (0);
792 }
793
794 /*
795  * Update parameters of an IPv6 interface address.
796  * If necessary, a new entry is created and linked into address chains.
797  * This function is separated from in6_control().
798  * XXX: should this be performed under splnet()?
799  */
800 int
801 in6_update_ifa(struct ifnet *ifp, struct in6_aliasreq *ifra,
802                struct in6_ifaddr *ia)
803 {
804         int error = 0, hostIsNew = 0, plen = -1;
805         struct in6_ifaddr *oia;
806         struct sockaddr_in6 dst6;
807         struct in6_addrlifetime *lt;
808
809         /* Validate parameters */
810         if (ifp == NULL || ifra == NULL) /* this maybe redundant */
811                 return (EINVAL);
812
813         /*
814          * The destination address for a p2p link must have a family
815          * of AF_UNSPEC or AF_INET6.
816          */
817         if ((ifp->if_flags & IFF_POINTOPOINT) &&
818             ifra->ifra_dstaddr.sin6_family != AF_INET6 &&
819             ifra->ifra_dstaddr.sin6_family != AF_UNSPEC)
820                 return (EAFNOSUPPORT);
821         /*
822          * validate ifra_prefixmask.  don't check sin6_family, netmask
823          * does not carry fields other than sin6_len.
824          */
825         if (ifra->ifra_prefixmask.sin6_len > sizeof(struct sockaddr_in6))
826                 return (EINVAL);
827         /*
828          * Because the IPv6 address architecture is classless, we require
829          * users to specify a (non 0) prefix length (mask) for a new address.
830          * We also require the prefix (when specified) mask is valid, and thus
831          * reject a non-consecutive mask.
832          */
833         if (ia == NULL && ifra->ifra_prefixmask.sin6_len == 0)
834                 return (EINVAL);
835         if (ifra->ifra_prefixmask.sin6_len != 0) {
836                 plen = in6_mask2len(&ifra->ifra_prefixmask.sin6_addr,
837                                     (u_char *)&ifra->ifra_prefixmask +
838                                     ifra->ifra_prefixmask.sin6_len);
839                 if (plen <= 0)
840                         return (EINVAL);
841         }
842         else {
843                 /*
844                  * In this case, ia must not be NULL.  We just use its prefix
845                  * length.
846                  */
847                 plen = in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL);
848         }
849         /*
850          * If the destination address on a p2p interface is specified,
851          * and the address is a scoped one, validate/set the scope
852          * zone identifier.
853          */
854         dst6 = ifra->ifra_dstaddr;
855         if ((ifp->if_flags & (IFF_POINTOPOINT|IFF_LOOPBACK)) &&
856             (dst6.sin6_family == AF_INET6)) {
857                 int scopeid;
858
859                 if ((error = in6_recoverscope(&dst6,
860                                               &ifra->ifra_dstaddr.sin6_addr,
861                                               ifp)) != 0)
862                         return (error);
863                 scopeid = in6_addr2scopeid(ifp, &dst6.sin6_addr);
864                 if (dst6.sin6_scope_id == 0) /* user omit to specify the ID. */
865                         dst6.sin6_scope_id = scopeid;
866                 else if (dst6.sin6_scope_id != scopeid)
867                         return (EINVAL); /* scope ID mismatch. */
868                 if ((error = in6_embedscope(&dst6.sin6_addr, &dst6, NULL, NULL))
869                     != 0)
870                         return (error);
871                 dst6.sin6_scope_id = 0; /* XXX */
872         }
873         /*
874          * The destination address can be specified only for a p2p or a
875          * loopback interface.  If specified, the corresponding prefix length
876          * must be 128.
877          */
878         if (ifra->ifra_dstaddr.sin6_family == AF_INET6) {
879                 if ((ifp->if_flags & (IFF_POINTOPOINT | IFF_LOOPBACK)) == 0) {
880                         /* XXX: noisy message */
881                         log(LOG_INFO, "in6_update_ifa: a destination can be "
882                             "specified for a p2p or a loopback IF only\n");
883                         return (EINVAL);
884                 }
885                 if (plen != 128) {
886                         /*
887                          * The following message seems noisy, but we dare to
888                          * add it for diagnosis.
889                          */
890                         log(LOG_INFO, "in6_update_ifa: prefixlen must be 128 "
891                             "when dstaddr is specified\n");
892                         return (EINVAL);
893                 }
894         }
895         /* lifetime consistency check */
896         lt = &ifra->ifra_lifetime;
897         if (lt->ia6t_vltime != ND6_INFINITE_LIFETIME
898             && lt->ia6t_vltime + time_second < time_second) {
899                 return EINVAL;
900         }
901         if (lt->ia6t_vltime == 0) {
902                 /*
903                  * the following log might be noisy, but this is a typical
904                  * configuration mistake or a tool's bug.
905                  */
906                 log(LOG_INFO,
907                     "in6_update_ifa: valid lifetime is 0 for %s\n",
908                     ip6_sprintf(&ifra->ifra_addr.sin6_addr));
909         }
910         if (lt->ia6t_pltime != ND6_INFINITE_LIFETIME
911             && lt->ia6t_pltime + time_second < time_second) {
912                 return EINVAL;
913         }
914
915         /*
916          * If this is a new address, allocate a new ifaddr and link it
917          * into chains.
918          */
919         if (ia == NULL) {
920                 hostIsNew = 1;
921                 /*
922                  * When in6_update_ifa() is called in a process of a received
923                  * RA, it is called under splnet().  So, we should call malloc
924                  * with M_NOWAIT.
925                  */
926                 ia = ifa_create(sizeof(*ia), M_NOWAIT);
927                 if (ia == NULL)
928                         return (ENOBUFS);
929                 /* Initialize the address and masks */
930                 ia->ia_ifa.ifa_addr = (struct sockaddr *)&ia->ia_addr;
931                 ia->ia_addr.sin6_family = AF_INET6;
932                 ia->ia_addr.sin6_len = sizeof(ia->ia_addr);
933                 if ((ifp->if_flags & (IFF_POINTOPOINT | IFF_LOOPBACK)) != 0) {
934                         /*
935                          * XXX: some functions expect that ifa_dstaddr is not
936                          * NULL for p2p interfaces.
937                          */
938                         ia->ia_ifa.ifa_dstaddr
939                                 = (struct sockaddr *)&ia->ia_dstaddr;
940                 } else {
941                         ia->ia_ifa.ifa_dstaddr = NULL;
942                 }
943                 ia->ia_ifa.ifa_netmask
944                         = (struct sockaddr *)&ia->ia_prefixmask;
945
946                 ia->ia_ifp = ifp;
947                 if ((oia = in6_ifaddr) != NULL) {
948                         for ( ; oia->ia_next; oia = oia->ia_next)
949                                 continue;
950                         oia->ia_next = ia;
951                 } else
952                         in6_ifaddr = ia;
953
954                 ifa_iflink(&ia->ia_ifa, ifp, 1);
955         }
956
957         /* set prefix mask */
958         if (ifra->ifra_prefixmask.sin6_len) {
959                 /*
960                  * We prohibit changing the prefix length of an existing
961                  * address, because
962                  * + such an operation should be rare in IPv6, and
963                  * + the operation would confuse prefix management.
964                  */
965                 if (ia->ia_prefixmask.sin6_len &&
966                     in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL) != plen) {
967                         log(LOG_INFO, "in6_update_ifa: the prefix length of an"
968                             " existing (%s) address should not be changed\n",
969                             ip6_sprintf(&ia->ia_addr.sin6_addr));
970                         error = EINVAL;
971                         goto unlink;
972                 }
973                 ia->ia_prefixmask = ifra->ifra_prefixmask;
974         }
975
976         /*
977          * If a new destination address is specified, scrub the old one and
978          * install the new destination.  Note that the interface must be
979          * p2p or loopback (see the check above.)
980          */
981         if (dst6.sin6_family == AF_INET6 &&
982             !IN6_ARE_ADDR_EQUAL(&dst6.sin6_addr,
983                                 &ia->ia_dstaddr.sin6_addr)) {
984                 int e;
985
986                 if ((ia->ia_flags & IFA_ROUTE) &&
987                     (e = rtinit(&(ia->ia_ifa), (int)RTM_DELETE, RTF_HOST))
988                     != 0) {
989                         log(LOG_ERR, "in6_update_ifa: failed to remove "
990                             "a route to the old destination: %s\n",
991                             ip6_sprintf(&ia->ia_addr.sin6_addr));
992                         /* proceed anyway... */
993                 }
994                 else
995                         ia->ia_flags &= ~IFA_ROUTE;
996                 ia->ia_dstaddr = dst6;
997         }
998
999         /* reset the interface and routing table appropriately. */
1000         if ((error = in6_ifinit(ifp, ia, &ifra->ifra_addr, hostIsNew)) != 0)
1001                 goto unlink;
1002
1003         /*
1004          * Beyond this point, we should call in6_purgeaddr upon an error,
1005          * not just go to unlink.
1006          */
1007
1008 #if 0                           /* disable this mechanism for now */
1009         /* update prefix list */
1010         if (hostIsNew &&
1011             (ifra->ifra_flags & IN6_IFF_NOPFX) == 0) { /* XXX */
1012                 int iilen;
1013
1014                 iilen = (sizeof(ia->ia_prefixmask.sin6_addr) << 3) - plen;
1015                 if ((error = in6_prefix_add_ifid(iilen, ia)) != 0) {
1016                         in6_purgeaddr((struct ifaddr *)ia);
1017                         return (error);
1018                 }
1019         }
1020 #endif
1021
1022         if (ifp->if_flags & IFF_MULTICAST) {
1023                 struct sockaddr_in6 mltaddr, mltmask;
1024                 struct in6_multi *in6m;
1025
1026                 if (hostIsNew) {
1027                         /*
1028                          * join solicited multicast addr for new host id
1029                          */
1030                         struct in6_addr llsol;
1031                         bzero(&llsol, sizeof(struct in6_addr));
1032                         llsol.s6_addr16[0] = htons(0xff02);
1033                         llsol.s6_addr16[1] = htons(ifp->if_index);
1034                         llsol.s6_addr32[1] = 0;
1035                         llsol.s6_addr32[2] = htonl(1);
1036                         llsol.s6_addr32[3] =
1037                                 ifra->ifra_addr.sin6_addr.s6_addr32[3];
1038                         llsol.s6_addr8[12] = 0xff;
1039                         in6_addmulti(&llsol, ifp, &error);
1040                         if (error != 0) {
1041                                 log(LOG_WARNING,
1042                                     "in6_update_ifa: addmulti failed for "
1043                                     "%s on %s (errno=%d)\n",
1044                                     ip6_sprintf(&llsol), if_name(ifp),
1045                                     error);
1046                                 in6_purgeaddr((struct ifaddr *)ia);
1047                                 return (error);
1048                         }
1049                 }
1050
1051                 bzero(&mltmask, sizeof(mltmask));
1052                 mltmask.sin6_len = sizeof(struct sockaddr_in6);
1053                 mltmask.sin6_family = AF_INET6;
1054                 mltmask.sin6_addr = in6mask32;
1055
1056                 /*
1057                  * join link-local all-nodes address
1058                  */
1059                 bzero(&mltaddr, sizeof(mltaddr));
1060                 mltaddr.sin6_len = sizeof(struct sockaddr_in6);
1061                 mltaddr.sin6_family = AF_INET6;
1062                 mltaddr.sin6_addr = kin6addr_linklocal_allnodes;
1063                 mltaddr.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
1064
1065                 IN6_LOOKUP_MULTI(mltaddr.sin6_addr, ifp, in6m);
1066                 if (in6m == NULL) {
1067                         rtrequest_global(RTM_ADD,
1068                                   (struct sockaddr *)&mltaddr,
1069                                   (struct sockaddr *)&ia->ia_addr,
1070                                   (struct sockaddr *)&mltmask,
1071                                   RTF_UP|RTF_CLONING);  /* xxx */
1072                         in6_addmulti(&mltaddr.sin6_addr, ifp, &error);
1073                         if (error != 0) {
1074                                 log(LOG_WARNING,
1075                                     "in6_update_ifa: addmulti failed for "
1076                                     "%s on %s (errno=%d)\n",
1077                                     ip6_sprintf(&mltaddr.sin6_addr),
1078                                     if_name(ifp), error);
1079                         }
1080                 }
1081
1082                 /*
1083                  * join node information group address
1084                  */
1085 #define hostnamelen     strlen(hostname)
1086                 if (in6_nigroup(ifp, hostname, hostnamelen, &mltaddr.sin6_addr)
1087                     == 0) {
1088                         IN6_LOOKUP_MULTI(mltaddr.sin6_addr, ifp, in6m);
1089                         if (in6m == NULL && ia != NULL) {
1090                                 in6_addmulti(&mltaddr.sin6_addr, ifp, &error);
1091                                 if (error != 0) {
1092                                         log(LOG_WARNING, "in6_update_ifa: "
1093                                             "addmulti failed for "
1094                                             "%s on %s (errno=%d)\n",
1095                                             ip6_sprintf(&mltaddr.sin6_addr),
1096                                             if_name(ifp), error);
1097                                 }
1098                         }
1099                 }
1100 #undef hostnamelen
1101
1102                 /*
1103                  * join node-local all-nodes address, on loopback.
1104                  * XXX: since "node-local" is obsoleted by interface-local,
1105                  *      we have to join the group on every interface with
1106                  *      some interface-boundary restriction.
1107                  */
1108                 if (ifp->if_flags & IFF_LOOPBACK) {
1109                         struct in6_ifaddr *ia_loop;
1110
1111                         struct in6_addr loop6 = kin6addr_loopback;
1112                         ia_loop = in6ifa_ifpwithaddr(ifp, &loop6);
1113
1114                         mltaddr.sin6_addr = kin6addr_nodelocal_allnodes;
1115
1116                         IN6_LOOKUP_MULTI(mltaddr.sin6_addr, ifp, in6m);
1117                         if (in6m == NULL && ia_loop != NULL) {
1118                                 rtrequest_global(RTM_ADD,
1119                                           (struct sockaddr *)&mltaddr,
1120                                           (struct sockaddr *)&ia_loop->ia_addr,
1121                                           (struct sockaddr *)&mltmask,
1122                                           RTF_UP);
1123                                 in6_addmulti(&mltaddr.sin6_addr, ifp, &error);
1124                                 if (error != 0) {
1125                                         log(LOG_WARNING, "in6_update_ifa: "
1126                                             "addmulti failed for %s on %s "
1127                                             "(errno=%d)\n",
1128                                             ip6_sprintf(&mltaddr.sin6_addr),
1129                                             if_name(ifp), error);
1130                                 }
1131                         }
1132                 }
1133         }
1134
1135         ia->ia6_flags = ifra->ifra_flags;
1136         ia->ia6_flags &= ~IN6_IFF_DUPLICATED;   /*safety*/
1137         ia->ia6_flags &= ~IN6_IFF_NODAD;        /* Mobile IPv6 */
1138
1139         ia->ia6_lifetime = ifra->ifra_lifetime;
1140         /* for sanity */
1141         if (ia->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
1142                 ia->ia6_lifetime.ia6t_expire =
1143                         time_second + ia->ia6_lifetime.ia6t_vltime;
1144         } else
1145                 ia->ia6_lifetime.ia6t_expire = 0;
1146         if (ia->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
1147                 ia->ia6_lifetime.ia6t_preferred =
1148                         time_second + ia->ia6_lifetime.ia6t_pltime;
1149         } else
1150                 ia->ia6_lifetime.ia6t_preferred = 0;
1151
1152         /*
1153          * Perform DAD, if needed.
1154          * XXX It may be of use, if we can administratively
1155          * disable DAD.
1156          */
1157         if (in6if_do_dad(ifp) && !(ifra->ifra_flags & IN6_IFF_NODAD)) {
1158                 ia->ia6_flags |= IN6_IFF_TENTATIVE;
1159                 nd6_dad_start((struct ifaddr *)ia, NULL);
1160         }
1161
1162         return (error);
1163
1164 unlink:
1165         /*
1166          * XXX: if a change of an existing address failed, keep the entry
1167          * anyway.
1168          */
1169         if (hostIsNew)
1170                 in6_unlink_ifa(ia, ifp);
1171         return (error);
1172 }
1173
1174 void
1175 in6_purgeaddr(struct ifaddr *ifa)
1176 {
1177         struct ifnet *ifp = ifa->ifa_ifp;
1178         struct in6_ifaddr *ia = (struct in6_ifaddr *) ifa;
1179
1180         /* stop DAD processing */
1181         nd6_dad_stop(ifa);
1182
1183         /*
1184          * delete route to the destination of the address being purged.
1185          * The interface must be p2p or loopback in this case.
1186          */
1187         if ((ia->ia_flags & IFA_ROUTE) && ia->ia_dstaddr.sin6_len != 0) {
1188                 int e;
1189
1190                 if ((e = rtinit(&(ia->ia_ifa), (int)RTM_DELETE, RTF_HOST))
1191                     != 0) {
1192                         log(LOG_ERR, "in6_purgeaddr: failed to remove "
1193                             "a route to the p2p destination: %s on %s, "
1194                             "errno=%d\n",
1195                             ip6_sprintf(&ia->ia_addr.sin6_addr), if_name(ifp),
1196                             e);
1197                         /* proceed anyway... */
1198                 }
1199                 else
1200                         ia->ia_flags &= ~IFA_ROUTE;
1201         }
1202
1203         /* Remove ownaddr's loopback rtentry, if it exists. */
1204         in6_ifremloop(&(ia->ia_ifa));
1205
1206         if (ifp->if_flags & IFF_MULTICAST) {
1207                 /*
1208                  * delete solicited multicast addr for deleting host id
1209                  */
1210                 struct in6_multi *in6m;
1211                 struct in6_addr llsol;
1212                 bzero(&llsol, sizeof(struct in6_addr));
1213                 llsol.s6_addr16[0] = htons(0xff02);
1214                 llsol.s6_addr16[1] = htons(ifp->if_index);
1215                 llsol.s6_addr32[1] = 0;
1216                 llsol.s6_addr32[2] = htonl(1);
1217                 llsol.s6_addr32[3] =
1218                         ia->ia_addr.sin6_addr.s6_addr32[3];
1219                 llsol.s6_addr8[12] = 0xff;
1220
1221                 IN6_LOOKUP_MULTI(llsol, ifp, in6m);
1222                 if (in6m)
1223                         in6_delmulti(in6m);
1224         }
1225
1226         in6_unlink_ifa(ia, ifp);
1227 }
1228
1229 static void
1230 in6_unlink_ifa(struct in6_ifaddr *ia, struct ifnet *ifp)
1231 {
1232         int plen, iilen;
1233         struct in6_ifaddr *oia;
1234
1235         crit_enter();
1236
1237         ifa_ifunlink(&ia->ia_ifa, ifp);
1238
1239         oia = ia;
1240         if (oia == (ia = in6_ifaddr))
1241                 in6_ifaddr = ia->ia_next;
1242         else {
1243                 while (ia->ia_next && (ia->ia_next != oia))
1244                         ia = ia->ia_next;
1245                 if (ia->ia_next)
1246                         ia->ia_next = oia->ia_next;
1247                 else {
1248                         /* search failed */
1249                         kprintf("Couldn't unlink in6_ifaddr from in6_ifaddr\n");
1250                 }
1251         }
1252
1253         if (oia->ia6_ifpr) {    /* check for safety */
1254                 plen = in6_mask2len(&oia->ia_prefixmask.sin6_addr, NULL);
1255                 iilen = (sizeof(oia->ia_prefixmask.sin6_addr) << 3) - plen;
1256                 in6_prefix_remove_ifid(iilen, oia);
1257         }
1258
1259         /*
1260          * When an autoconfigured address is being removed, release the
1261          * reference to the base prefix.  Also, since the release might
1262          * affect the status of other (detached) addresses, call
1263          * pfxlist_onlink_check().
1264          */
1265         if (oia->ia6_flags & IN6_IFF_AUTOCONF) {
1266                 if (oia->ia6_ndpr == NULL) {
1267                         log(LOG_NOTICE, "in6_unlink_ifa: autoconf'ed address "
1268                             "%p has no prefix\n", oia);
1269                 } else {
1270                         oia->ia6_ndpr->ndpr_refcnt--;
1271                         oia->ia6_flags &= ~IN6_IFF_AUTOCONF;
1272                         oia->ia6_ndpr = NULL;
1273                 }
1274
1275                 pfxlist_onlink_check();
1276         }
1277
1278         /*
1279          * release another refcnt for the link from in6_ifaddr.
1280          * Note that we should decrement the refcnt at least once for all *BSD.
1281          */
1282         ifa_destroy(&oia->ia_ifa);
1283
1284         crit_exit();
1285 }
1286
1287 void
1288 in6_purgeif(struct ifnet *ifp)
1289 {
1290         struct ifaddr_container *ifac, *next;
1291
1292         TAILQ_FOREACH_MUTABLE(ifac, &ifp->if_addrheads[mycpuid],
1293                               ifa_link, next) {
1294                 if (ifac->ifa->ifa_addr->sa_family != AF_INET6)
1295                         continue;
1296                 in6_purgeaddr(ifac->ifa);
1297         }
1298
1299         in6_ifdetach(ifp);
1300 }
1301
1302 /*
1303  * SIOC[GAD]LIFADDR.
1304  *      SIOCGLIFADDR: get first address. (?)
1305  *      SIOCGLIFADDR with IFLR_PREFIX:
1306  *              get first address that matches the specified prefix.
1307  *      SIOCALIFADDR: add the specified address.
1308  *      SIOCALIFADDR with IFLR_PREFIX:
1309  *              add the specified prefix, filling hostid part from
1310  *              the first link-local address.  prefixlen must be <= 64.
1311  *      SIOCDLIFADDR: delete the specified address.
1312  *      SIOCDLIFADDR with IFLR_PREFIX:
1313  *              delete the first address that matches the specified prefix.
1314  * return values:
1315  *      EINVAL on invalid parameters
1316  *      EADDRNOTAVAIL on prefix match failed/specified address not found
1317  *      other values may be returned from in6_ioctl()
1318  *
1319  * NOTE: SIOCALIFADDR(with IFLR_PREFIX set) allows prefixlen less than 64.
1320  * this is to accomodate address naming scheme other than RFC2374,
1321  * in the future.
1322  * RFC2373 defines interface id to be 64bit, but it allows non-RFC2374
1323  * address encoding scheme. (see figure on page 8)
1324  */
1325 static int
1326 in6_lifaddr_ioctl(struct socket *so, u_long cmd, caddr_t data,
1327                   struct ifnet *ifp, struct thread *td)
1328 {
1329         struct if_laddrreq *iflr = (struct if_laddrreq *)data;
1330         struct sockaddr *sa;
1331
1332         /* sanity checks */
1333         if (!data || !ifp) {
1334                 panic("invalid argument to in6_lifaddr_ioctl");
1335                 /*NOTRECHED*/
1336         }
1337
1338         switch (cmd) {
1339         case SIOCGLIFADDR:
1340                 /* address must be specified on GET with IFLR_PREFIX */
1341                 if (!(iflr->flags & IFLR_PREFIX))
1342                         break;
1343                 /* FALLTHROUGH */
1344         case SIOCALIFADDR:
1345         case SIOCDLIFADDR:
1346                 /* address must be specified on ADD and DELETE */
1347                 sa = (struct sockaddr *)&iflr->addr;
1348                 if (sa->sa_family != AF_INET6)
1349                         return EINVAL;
1350                 if (sa->sa_len != sizeof(struct sockaddr_in6))
1351                         return EINVAL;
1352                 /* XXX need improvement */
1353                 sa = (struct sockaddr *)&iflr->dstaddr;
1354                 if (sa->sa_family && sa->sa_family != AF_INET6)
1355                         return EINVAL;
1356                 if (sa->sa_len && sa->sa_len != sizeof(struct sockaddr_in6))
1357                         return EINVAL;
1358                 break;
1359         default: /* shouldn't happen */
1360 #if 0
1361                 panic("invalid cmd to in6_lifaddr_ioctl");
1362                 /* NOTREACHED */
1363 #else
1364                 return EOPNOTSUPP;
1365 #endif
1366         }
1367         if (sizeof(struct in6_addr) * 8 < iflr->prefixlen)
1368                 return EINVAL;
1369
1370         switch (cmd) {
1371         case SIOCALIFADDR:
1372             {
1373                 struct in6_aliasreq ifra;
1374                 struct in6_addr *hostid = NULL;
1375                 int prefixlen;
1376
1377                 if (iflr->flags & IFLR_PREFIX) {
1378                         struct ifaddr *ifa;
1379                         struct sockaddr_in6 *sin6;
1380
1381                         /*
1382                          * hostid is to fill in the hostid part of the
1383                          * address.  hostid points to the first link-local
1384                          * address attached to the interface.
1385                          */
1386                         ifa = (struct ifaddr *)in6ifa_ifpforlinklocal(ifp, 0);
1387                         if (!ifa)
1388                                 return EADDRNOTAVAIL;
1389                         hostid = IFA_IN6(ifa);
1390
1391                         /* prefixlen must be <= 64. */
1392                         if (64 < iflr->prefixlen)
1393                                 return EINVAL;
1394                         prefixlen = iflr->prefixlen;
1395
1396                         /* hostid part must be zero. */
1397                         sin6 = (struct sockaddr_in6 *)&iflr->addr;
1398                         if (sin6->sin6_addr.s6_addr32[2] != 0
1399                          || sin6->sin6_addr.s6_addr32[3] != 0) {
1400                                 return EINVAL;
1401                         }
1402                 } else
1403                         prefixlen = iflr->prefixlen;
1404
1405                 /* copy args to in6_aliasreq, perform ioctl(SIOCAIFADDR_IN6). */
1406                 bzero(&ifra, sizeof(ifra));
1407                 bcopy(iflr->iflr_name, ifra.ifra_name,
1408                         sizeof(ifra.ifra_name));
1409
1410                 bcopy(&iflr->addr, &ifra.ifra_addr,
1411                         ((struct sockaddr *)&iflr->addr)->sa_len);
1412                 if (hostid) {
1413                         /* fill in hostid part */
1414                         ifra.ifra_addr.sin6_addr.s6_addr32[2] =
1415                                 hostid->s6_addr32[2];
1416                         ifra.ifra_addr.sin6_addr.s6_addr32[3] =
1417                                 hostid->s6_addr32[3];
1418                 }
1419
1420                 if (((struct sockaddr *)&iflr->dstaddr)->sa_family) {   /*XXX*/
1421                         bcopy(&iflr->dstaddr, &ifra.ifra_dstaddr,
1422                                 ((struct sockaddr *)&iflr->dstaddr)->sa_len);
1423                         if (hostid) {
1424                                 ifra.ifra_dstaddr.sin6_addr.s6_addr32[2] =
1425                                         hostid->s6_addr32[2];
1426                                 ifra.ifra_dstaddr.sin6_addr.s6_addr32[3] =
1427                                         hostid->s6_addr32[3];
1428                         }
1429                 }
1430
1431                 ifra.ifra_prefixmask.sin6_len = sizeof(struct sockaddr_in6);
1432                 in6_len2mask(&ifra.ifra_prefixmask.sin6_addr, prefixlen);
1433
1434                 ifra.ifra_flags = iflr->flags & ~IFLR_PREFIX;
1435                 return in6_control(so, SIOCAIFADDR_IN6, (caddr_t)&ifra, ifp, td);
1436             }
1437         case SIOCGLIFADDR:
1438         case SIOCDLIFADDR:
1439             {
1440                 struct ifaddr_container *ifac;
1441                 struct in6_ifaddr *ia;
1442                 struct in6_addr mask, candidate, match;
1443                 struct sockaddr_in6 *sin6;
1444                 int cmp;
1445
1446                 bzero(&mask, sizeof(mask));
1447                 if (iflr->flags & IFLR_PREFIX) {
1448                         /* lookup a prefix rather than address. */
1449                         in6_len2mask(&mask, iflr->prefixlen);
1450
1451                         sin6 = (struct sockaddr_in6 *)&iflr->addr;
1452                         bcopy(&sin6->sin6_addr, &match, sizeof(match));
1453                         match.s6_addr32[0] &= mask.s6_addr32[0];
1454                         match.s6_addr32[1] &= mask.s6_addr32[1];
1455                         match.s6_addr32[2] &= mask.s6_addr32[2];
1456                         match.s6_addr32[3] &= mask.s6_addr32[3];
1457
1458                         /* if you set extra bits, that's wrong */
1459                         if (bcmp(&match, &sin6->sin6_addr, sizeof(match)))
1460                                 return EINVAL;
1461
1462                         cmp = 1;
1463                 } else {
1464                         if (cmd == SIOCGLIFADDR) {
1465                                 /* on getting an address, take the 1st match */
1466                                 cmp = 0;        /* XXX */
1467                         } else {
1468                                 /* on deleting an address, do exact match */
1469                                 in6_len2mask(&mask, 128);
1470                                 sin6 = (struct sockaddr_in6 *)&iflr->addr;
1471                                 bcopy(&sin6->sin6_addr, &match, sizeof(match));
1472
1473                                 cmp = 1;
1474                         }
1475                 }
1476
1477                 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1478                         struct ifaddr *ifa = ifac->ifa;
1479
1480                         if (ifa->ifa_addr->sa_family != AF_INET6)
1481                                 continue;
1482                         if (!cmp)
1483                                 break;
1484
1485                         bcopy(IFA_IN6(ifa), &candidate, sizeof(candidate));
1486                         /*
1487                          * XXX: this is adhoc, but is necessary to allow
1488                          * a user to specify fe80::/64 (not /10) for a
1489                          * link-local address.
1490                          */
1491                         if (IN6_IS_ADDR_LINKLOCAL(&candidate))
1492                                 candidate.s6_addr16[1] = 0;
1493                         candidate.s6_addr32[0] &= mask.s6_addr32[0];
1494                         candidate.s6_addr32[1] &= mask.s6_addr32[1];
1495                         candidate.s6_addr32[2] &= mask.s6_addr32[2];
1496                         candidate.s6_addr32[3] &= mask.s6_addr32[3];
1497                         if (IN6_ARE_ADDR_EQUAL(&candidate, &match))
1498                                 break;
1499                 }
1500                 if (ifac == NULL)
1501                         return EADDRNOTAVAIL;
1502                 ia = ifa2ia6(ifac->ifa);
1503
1504                 if (cmd == SIOCGLIFADDR) {
1505                         struct sockaddr_in6 *s6;
1506
1507                         /* fill in the if_laddrreq structure */
1508                         bcopy(&ia->ia_addr, &iflr->addr, ia->ia_addr.sin6_len);
1509                         s6 = (struct sockaddr_in6 *)&iflr->addr;
1510                         if (IN6_IS_ADDR_LINKLOCAL(&s6->sin6_addr)) {
1511                                 s6->sin6_addr.s6_addr16[1] = 0;
1512                                 s6->sin6_scope_id =
1513                                         in6_addr2scopeid(ifp, &s6->sin6_addr);
1514                         }
1515                         if (ifp->if_flags & IFF_POINTOPOINT) {
1516                                 bcopy(&ia->ia_dstaddr, &iflr->dstaddr,
1517                                         ia->ia_dstaddr.sin6_len);
1518                                 s6 = (struct sockaddr_in6 *)&iflr->dstaddr;
1519                                 if (IN6_IS_ADDR_LINKLOCAL(&s6->sin6_addr)) {
1520                                         s6->sin6_addr.s6_addr16[1] = 0;
1521                                         s6->sin6_scope_id =
1522                                                 in6_addr2scopeid(ifp,
1523                                                                  &s6->sin6_addr);
1524                                 }
1525                         } else
1526                                 bzero(&iflr->dstaddr, sizeof(iflr->dstaddr));
1527
1528                         iflr->prefixlen =
1529                                 in6_mask2len(&ia->ia_prefixmask.sin6_addr,
1530                                              NULL);
1531
1532                         iflr->flags = ia->ia6_flags;    /* XXX */
1533
1534                         return 0;
1535                 } else {
1536                         struct in6_aliasreq ifra;
1537
1538                         /* fill in6_aliasreq and do ioctl(SIOCDIFADDR_IN6) */
1539                         bzero(&ifra, sizeof(ifra));
1540                         bcopy(iflr->iflr_name, ifra.ifra_name,
1541                               sizeof(ifra.ifra_name));
1542
1543                         bcopy(&ia->ia_addr, &ifra.ifra_addr,
1544                               ia->ia_addr.sin6_len);
1545                         if (ifp->if_flags & IFF_POINTOPOINT)
1546                                 bcopy(&ia->ia_dstaddr, &ifra.ifra_dstaddr,
1547                                       ia->ia_dstaddr.sin6_len);
1548                         else
1549                                 bzero(&ifra.ifra_dstaddr,
1550                                       sizeof(ifra.ifra_dstaddr));
1551                         bcopy(&ia->ia_prefixmask, &ifra.ifra_dstaddr,
1552                               ia->ia_prefixmask.sin6_len);
1553
1554                         ifra.ifra_flags = ia->ia6_flags;
1555                         return in6_control(so, SIOCDIFADDR_IN6, (caddr_t)&ifra,
1556                                 ifp, td);
1557                 }
1558             }
1559         }
1560
1561         return EOPNOTSUPP;      /* just for safety */
1562 }
1563
1564 /*
1565  * Initialize an interface's intetnet6 address
1566  * and routing table entry.
1567  */
1568 static int
1569 in6_ifinit(struct ifnet *ifp, struct in6_ifaddr *ia, struct sockaddr_in6 *sin6,
1570            int newhost)
1571 {
1572         int     error = 0, plen, ifacount = 0;
1573         struct ifaddr_container *ifac;
1574
1575         /*
1576          * Give the interface a chance to initialize
1577          * if this is its first address,
1578          * and to validate the address if necessary.
1579          */
1580         TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1581                 if (ifac->ifa->ifa_addr == NULL)
1582                         continue;       /* just for safety */
1583                 if (ifac->ifa->ifa_addr->sa_family != AF_INET6)
1584                         continue;
1585                 ifacount++;
1586         }
1587
1588         ifnet_serialize_all(ifp);
1589
1590         ia->ia_addr = *sin6;
1591
1592         if (ifacount <= 1 && ifp->if_ioctl &&
1593             (error = ifp->if_ioctl(ifp, SIOCSIFADDR, (caddr_t)ia, NULL))) {
1594                 ifnet_deserialize_all(ifp);
1595                 return (error);
1596         }
1597
1598         ifnet_deserialize_all(ifp);
1599
1600         ia->ia_ifa.ifa_metric = ifp->if_metric;
1601
1602         /* we could do in(6)_socktrim here, but just omit it at this moment. */
1603
1604         /*
1605          * Special case:
1606          * If the destination address is specified for a point-to-point
1607          * interface, install a route to the destination as an interface
1608          * direct route.
1609          */
1610         plen = in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL); /* XXX */
1611         if (plen == 128 && ia->ia_dstaddr.sin6_family == AF_INET6) {
1612                 if ((error = rtinit(&(ia->ia_ifa), (int)RTM_ADD,
1613                                     RTF_UP | RTF_HOST)) != 0)
1614                         return (error);
1615                 ia->ia_flags |= IFA_ROUTE;
1616         }
1617         if (plen < 128) {
1618                 /*
1619                  * The RTF_CLONING flag is necessary for in6_is_ifloop_auto().
1620                  */
1621                 ia->ia_ifa.ifa_flags |= RTF_CLONING;
1622         }
1623
1624         /* Add ownaddr as loopback rtentry, if necessary (ex. on p2p link). */
1625         if (newhost) {
1626                 /* set the rtrequest function to create llinfo */
1627                 ia->ia_ifa.ifa_rtrequest = nd6_rtrequest;
1628                 in6_ifaddloop(&(ia->ia_ifa));
1629         }
1630
1631         return (error);
1632 }
1633
1634 struct in6_multi_mship *
1635 in6_joingroup(struct ifnet *ifp, struct in6_addr *addr, int *errorp)
1636 {
1637        struct in6_multi_mship *imm;
1638
1639        imm = kmalloc(sizeof(*imm), M_IPMADDR, M_NOWAIT);
1640        if (!imm) {
1641                *errorp = ENOBUFS;
1642                return NULL;
1643        }
1644        imm->i6mm_maddr = in6_addmulti(addr, ifp, errorp);
1645        if (!imm->i6mm_maddr) {
1646                /* *errorp is alrady set */
1647                kfree(imm, M_IPMADDR);
1648                return NULL;
1649        }
1650        return imm;
1651 }
1652
1653 int
1654 in6_leavegroup(struct in6_multi_mship *imm)
1655 {
1656
1657        if (imm->i6mm_maddr)
1658                in6_delmulti(imm->i6mm_maddr);
1659        kfree(imm,  M_IPMADDR);
1660        return 0;
1661 }
1662
1663 /*
1664  * Add an address to the list of IP6 multicast addresses for a
1665  * given interface.
1666  */
1667 struct  in6_multi *
1668 in6_addmulti(struct in6_addr *maddr6, struct ifnet *ifp, int *errorp)
1669 {
1670         struct  in6_multi *in6m;
1671         struct sockaddr_in6 sin6;
1672         struct ifmultiaddr *ifma;
1673
1674         *errorp = 0;
1675
1676         crit_enter();
1677
1678         /*
1679          * Call generic routine to add membership or increment
1680          * refcount.  It wants addresses in the form of a sockaddr,
1681          * so we build one here (being careful to zero the unused bytes).
1682          */
1683         bzero(&sin6, sizeof sin6);
1684         sin6.sin6_family = AF_INET6;
1685         sin6.sin6_len = sizeof sin6;
1686         sin6.sin6_addr = *maddr6;
1687         *errorp = if_addmulti(ifp, (struct sockaddr *)&sin6, &ifma);
1688         if (*errorp) {
1689                 crit_exit();
1690                 return 0;
1691         }
1692
1693         /*
1694          * If ifma->ifma_protospec is null, then if_addmulti() created
1695          * a new record.  Otherwise, we are done.
1696          */
1697         if (ifma->ifma_protospec != 0) {
1698                 crit_exit();
1699                 return ifma->ifma_protospec;
1700         }
1701
1702         /* XXX - if_addmulti uses M_WAITOK.  Can this really be called
1703            at interrupt time?  If so, need to fix if_addmulti. XXX */
1704         in6m = (struct in6_multi *)kmalloc(sizeof(*in6m), M_IPMADDR, M_NOWAIT);
1705         if (in6m == NULL) {
1706                 crit_exit();
1707                 return (NULL);
1708         }
1709
1710         bzero(in6m, sizeof *in6m);
1711         in6m->in6m_addr = *maddr6;
1712         in6m->in6m_ifp = ifp;
1713         in6m->in6m_ifma = ifma;
1714         ifma->ifma_protospec = in6m;
1715         LIST_INSERT_HEAD(&in6_multihead, in6m, in6m_entry);
1716
1717         /*
1718          * Let MLD6 know that we have joined a new IP6 multicast
1719          * group.
1720          */
1721         mld6_start_listening(in6m);
1722         crit_exit();
1723         return (in6m);
1724 }
1725
1726 /*
1727  * Delete a multicast address record.
1728  */
1729 void
1730 in6_delmulti(struct in6_multi *in6m)
1731 {
1732         struct ifmultiaddr *ifma = in6m->in6m_ifma;
1733
1734         crit_enter();
1735
1736         if (ifma->ifma_refcount == 1) {
1737                 /*
1738                  * No remaining claims to this record; let MLD6 know
1739                  * that we are leaving the multicast group.
1740                  */
1741                 mld6_stop_listening(in6m);
1742                 ifma->ifma_protospec = 0;
1743                 LIST_REMOVE(in6m, in6m_entry);
1744                 kfree(in6m, M_IPMADDR);
1745         }
1746         /* XXX - should be separate API for when we have an ifma? */
1747         if_delmulti(ifma->ifma_ifp, ifma->ifma_addr);
1748         crit_exit();
1749 }
1750
1751 /*
1752  * Find an IPv6 interface link-local address specific to an interface.
1753  */
1754 struct in6_ifaddr *
1755 in6ifa_ifpforlinklocal(struct ifnet *ifp, int ignoreflags)
1756 {
1757         struct ifaddr_container *ifac;
1758
1759         TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1760                 struct ifaddr *ifa = ifac->ifa;
1761
1762                 if (ifa->ifa_addr == NULL)
1763                         continue;       /* just for safety */
1764                 if (ifa->ifa_addr->sa_family != AF_INET6)
1765                         continue;
1766                 if (IN6_IS_ADDR_LINKLOCAL(IFA_IN6(ifa))) {
1767                         if ((((struct in6_ifaddr *)ifa)->ia6_flags &
1768                              ignoreflags) != 0)
1769                                 continue;
1770                         break;
1771                 }
1772         }
1773         if (ifac != NULL)
1774                 return ((struct in6_ifaddr *)(ifac->ifa));
1775         else
1776                 return (NULL);
1777 }
1778
1779
1780 /*
1781  * find the internet address corresponding to a given interface and address.
1782  */
1783 struct in6_ifaddr *
1784 in6ifa_ifpwithaddr(struct ifnet *ifp, struct in6_addr *addr)
1785 {
1786         struct ifaddr_container *ifac;
1787
1788         TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1789                 struct ifaddr *ifa = ifac->ifa;
1790
1791                 if (ifa->ifa_addr == NULL)
1792                         continue;       /* just for safety */
1793                 if (ifa->ifa_addr->sa_family != AF_INET6)
1794                         continue;
1795                 if (IN6_ARE_ADDR_EQUAL(addr, IFA_IN6(ifa)))
1796                         break;
1797         }
1798         if (ifac != NULL)
1799                 return ((struct in6_ifaddr *)(ifac->ifa));
1800         else
1801                 return (NULL);
1802 }
1803
1804 /*
1805  * find the internet address on a given interface corresponding to a neighbor's
1806  * address.
1807  */
1808 struct in6_ifaddr *
1809 in6ifa_ifplocaladdr(const struct ifnet *ifp, const struct in6_addr *addr)
1810 {
1811         struct ifaddr *ifa;
1812         struct in6_ifaddr *ia;
1813         struct ifaddr_container *ifac;
1814
1815         TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1816                 ifa = ifac->ifa;
1817
1818                 if (ifa->ifa_addr == NULL)
1819                         continue;       /* just for safety */
1820                 if (ifa->ifa_addr->sa_family != AF_INET6)
1821                         continue;
1822                 ia = (struct in6_ifaddr *)ifa;
1823                 if (IN6_ARE_MASKED_ADDR_EQUAL(addr,
1824                                 &ia->ia_addr.sin6_addr,
1825                                 &ia->ia_prefixmask.sin6_addr))
1826                         return ia;
1827         }
1828
1829         return NULL;
1830 }
1831
1832 /*
1833  * Convert IP6 address to printable (loggable) representation.
1834  */
1835 static char digits[] = "0123456789abcdef";
1836 static int ip6round = 0;
1837 char *
1838 ip6_sprintf(const struct in6_addr *addr)
1839 {
1840         static char ip6buf[8][48];
1841         int i;
1842         char *cp;
1843         const u_short *a = (const u_short *)addr;
1844         const u_char *d;
1845         int dcolon = 0;
1846
1847         ip6round = (ip6round + 1) & 7;
1848         cp = ip6buf[ip6round];
1849
1850         for (i = 0; i < 8; i++) {
1851                 if (dcolon == 1) {
1852                         if (*a == 0) {
1853                                 if (i == 7)
1854                                         *cp++ = ':';
1855                                 a++;
1856                                 continue;
1857                         } else
1858                                 dcolon = 2;
1859                 }
1860                 if (*a == 0) {
1861                         if (dcolon == 0 && *(a + 1) == 0) {
1862                                 if (i == 0)
1863                                         *cp++ = ':';
1864                                 *cp++ = ':';
1865                                 dcolon = 1;
1866                         } else {
1867                                 *cp++ = '0';
1868                                 *cp++ = ':';
1869                         }
1870                         a++;
1871                         continue;
1872                 }
1873                 d = (const u_char *)a;
1874                 *cp++ = digits[*d >> 4];
1875                 *cp++ = digits[*d++ & 0xf];
1876                 *cp++ = digits[*d >> 4];
1877                 *cp++ = digits[*d & 0xf];
1878                 *cp++ = ':';
1879                 a++;
1880         }
1881         *--cp = 0;
1882         return (ip6buf[ip6round]);
1883 }
1884
1885 int
1886 in6_localaddr(struct in6_addr *in6)
1887 {
1888         struct in6_ifaddr *ia;
1889
1890         if (IN6_IS_ADDR_LOOPBACK(in6) || IN6_IS_ADDR_LINKLOCAL(in6))
1891                 return 1;
1892
1893         for (ia = in6_ifaddr; ia; ia = ia->ia_next)
1894                 if (IN6_ARE_MASKED_ADDR_EQUAL(in6, &ia->ia_addr.sin6_addr,
1895                                               &ia->ia_prefixmask.sin6_addr))
1896                         return 1;
1897
1898         return (0);
1899 }
1900
1901 int
1902 in6_is_addr_deprecated(struct sockaddr_in6 *sa6)
1903 {
1904         struct in6_ifaddr *ia;
1905
1906         for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
1907                 if (IN6_ARE_ADDR_EQUAL(&ia->ia_addr.sin6_addr,
1908                                        &sa6->sin6_addr) &&
1909                     (ia->ia6_flags & IN6_IFF_DEPRECATED))
1910                         return (1); /* true */
1911
1912                 /* XXX: do we still have to go thru the rest of the list? */
1913         }
1914
1915         return (0);             /* false */
1916 }
1917
1918 /*
1919  * return length of part which dst and src are equal
1920  * hard coding...
1921  */
1922 int
1923 in6_matchlen(struct in6_addr *src, struct in6_addr *dst)
1924 {
1925         int match = 0;
1926         u_char *s = (u_char *)src, *d = (u_char *)dst;
1927         u_char *lim = s + 16, r;
1928
1929         while (s < lim)
1930                 if ((r = (*d++ ^ *s++)) != 0) {
1931                         while (r < 128) {
1932                                 match++;
1933                                 r <<= 1;
1934                         }
1935                         break;
1936                 } else
1937                         match += 8;
1938         return match;
1939 }
1940
1941 /* XXX: to be scope conscious */
1942 int
1943 in6_are_prefix_equal(struct in6_addr *p1, struct in6_addr *p2, int len)
1944 {
1945         int bytelen, bitlen;
1946
1947         /* sanity check */
1948         if (0 > len || len > 128) {
1949                 log(LOG_ERR, "in6_are_prefix_equal: invalid prefix length(%d)\n",
1950                     len);
1951                 return (0);
1952         }
1953
1954         bytelen = len / 8;
1955         bitlen = len % 8;
1956
1957         if (bcmp(&p1->s6_addr, &p2->s6_addr, bytelen))
1958                 return (0);
1959         if (p1->s6_addr[bytelen] >> (8 - bitlen) !=
1960             p2->s6_addr[bytelen] >> (8 - bitlen))
1961                 return (0);
1962
1963         return (1);
1964 }
1965
1966 void
1967 in6_prefixlen2mask(struct in6_addr *maskp, int len)
1968 {
1969         u_char maskarray[8] = {0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff};
1970         int bytelen, bitlen, i;
1971
1972         /* sanity check */
1973         if (0 > len || len > 128) {
1974                 log(LOG_ERR, "in6_prefixlen2mask: invalid prefix length(%d)\n",
1975                     len);
1976                 return;
1977         }
1978
1979         bzero(maskp, sizeof(*maskp));
1980         bytelen = len / 8;
1981         bitlen = len % 8;
1982         for (i = 0; i < bytelen; i++)
1983                 maskp->s6_addr[i] = 0xff;
1984         if (bitlen)
1985                 maskp->s6_addr[bytelen] = maskarray[bitlen - 1];
1986 }
1987
1988 /*
1989  * return the best address out of the same scope
1990  */
1991 struct in6_ifaddr *
1992 in6_ifawithscope(struct ifnet *oifp, struct in6_addr *dst)
1993 {
1994         int dst_scope = in6_addrscope(dst), src_scope, best_scope = 0;
1995         int blen = -1;
1996         struct ifnet *ifp;
1997         struct in6_ifaddr *ifa_best = NULL;
1998
1999         if (oifp == NULL) {
2000 #if 0
2001                 kprintf("in6_ifawithscope: output interface is not specified\n");
2002 #endif
2003                 return (NULL);
2004         }
2005
2006         /*
2007          * We search for all addresses on all interfaces from the beginning.
2008          * Comparing an interface with the outgoing interface will be done
2009          * only at the final stage of tiebreaking.
2010          */
2011         for (ifp = TAILQ_FIRST(&ifnet); ifp; ifp = TAILQ_NEXT(ifp, if_list))
2012         {
2013                 struct ifaddr_container *ifac;
2014
2015                 /*
2016                  * We can never take an address that breaks the scope zone
2017                  * of the destination.
2018                  */
2019                 if (in6_addr2scopeid(ifp, dst) != in6_addr2scopeid(oifp, dst))
2020                         continue;
2021
2022                 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
2023                         int tlen = -1, dscopecmp, bscopecmp, matchcmp;
2024                         struct ifaddr *ifa = ifac->ifa;
2025
2026                         if (ifa->ifa_addr->sa_family != AF_INET6)
2027                                 continue;
2028
2029                         src_scope = in6_addrscope(IFA_IN6(ifa));
2030
2031                         /*
2032                          * Don't use an address before completing DAD
2033                          * nor a duplicated address.
2034                          */
2035                         if (((struct in6_ifaddr *)ifa)->ia6_flags &
2036                             IN6_IFF_NOTREADY)
2037                                 continue;
2038
2039                         /* XXX: is there any case to allow anycasts? */
2040                         if (((struct in6_ifaddr *)ifa)->ia6_flags &
2041                             IN6_IFF_ANYCAST)
2042                                 continue;
2043
2044                         if (((struct in6_ifaddr *)ifa)->ia6_flags &
2045                             IN6_IFF_DETACHED)
2046                                 continue;
2047
2048                         /*
2049                          * If this is the first address we find,
2050                          * keep it anyway.
2051                          */
2052                         if (ifa_best == NULL)
2053                                 goto replace;
2054
2055                         /*
2056                          * ifa_best is never NULL beyond this line except
2057                          * within the block labeled "replace".
2058                          */
2059
2060                         /*
2061                          * If ifa_best has a smaller scope than dst and
2062                          * the current address has a larger one than
2063                          * (or equal to) dst, always replace ifa_best.
2064                          * Also, if the current address has a smaller scope
2065                          * than dst, ignore it unless ifa_best also has a
2066                          * smaller scope.
2067                          * Consequently, after the two if-clause below,
2068                          * the followings must be satisfied:
2069                          * (scope(src) < scope(dst) &&
2070                          *  scope(best) < scope(dst))
2071                          *  OR
2072                          * (scope(best) >= scope(dst) &&
2073                          *  scope(src) >= scope(dst))
2074                          */
2075                         if (IN6_ARE_SCOPE_CMP(best_scope, dst_scope) < 0 &&
2076                             IN6_ARE_SCOPE_CMP(src_scope, dst_scope) >= 0)
2077                                 goto replace; /* (A) */
2078                         if (IN6_ARE_SCOPE_CMP(src_scope, dst_scope) < 0 &&
2079                             IN6_ARE_SCOPE_CMP(best_scope, dst_scope) >= 0)
2080                                 continue; /* (B) */
2081
2082                         /*
2083                          * A deprecated address SHOULD NOT be used in new
2084                          * communications if an alternate (non-deprecated)
2085                          * address is available and has sufficient scope.
2086                          * RFC 2462, Section 5.5.4.
2087                          */
2088                         if (((struct in6_ifaddr *)ifa)->ia6_flags &
2089                             IN6_IFF_DEPRECATED) {
2090                                 /*
2091                                  * Ignore any deprecated addresses if
2092                                  * specified by configuration.
2093                                  */
2094                                 if (!ip6_use_deprecated)
2095                                         continue;
2096
2097                                 /*
2098                                  * If we have already found a non-deprecated
2099                                  * candidate, just ignore deprecated addresses.
2100                                  */
2101                                 if (!(ifa_best->ia6_flags & IN6_IFF_DEPRECATED))
2102                                         continue;
2103                         }
2104
2105                         /*
2106                          * A non-deprecated address is always preferred
2107                          * to a deprecated one regardless of scopes and
2108                          * address matching (Note invariants ensured by the
2109                          * conditions (A) and (B) above.)
2110                          */
2111                         if ((ifa_best->ia6_flags & IN6_IFF_DEPRECATED) &&
2112                             !(((struct in6_ifaddr *)ifa)->ia6_flags &
2113                              IN6_IFF_DEPRECATED))
2114                                 goto replace;
2115
2116                         /*
2117                          * When we use temporary addresses described in
2118                          * RFC 3041, we prefer temporary addresses to
2119                          * public autoconf addresses.  Again, note the
2120                          * invariants from (A) and (B).  Also note that we
2121                          * don't have any preference between static addresses
2122                          * and autoconf addresses (despite of whether or not
2123                          * the latter is temporary or public.)
2124                          */
2125                         if (ip6_use_tempaddr) {
2126                                 struct in6_ifaddr *ifat;
2127
2128                                 ifat = (struct in6_ifaddr *)ifa;
2129                                 if ((ifa_best->ia6_flags &
2130                                      (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY))
2131                                      == IN6_IFF_AUTOCONF &&
2132                                     (ifat->ia6_flags &
2133                                      (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY))
2134                                      == (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY)) {
2135                                         goto replace;
2136                                 }
2137                                 if ((ifa_best->ia6_flags &
2138                                      (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY))
2139                                     == (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY) &&
2140                                     (ifat->ia6_flags &
2141                                      (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY))
2142                                      == IN6_IFF_AUTOCONF) {
2143                                         continue;
2144                                 }
2145                         }
2146
2147                         /*
2148                          * At this point, we have two cases:
2149                          * 1. we are looking at a non-deprecated address,
2150                          *    and ifa_best is also non-deprecated.
2151                          * 2. we are looking at a deprecated address,
2152                          *    and ifa_best is also deprecated.
2153                          * Also, we do not have to consider a case where
2154                          * the scope of if_best is larger(smaller) than dst and
2155                          * the scope of the current address is smaller(larger)
2156                          * than dst. Such a case has already been covered.
2157                          * Tiebreaking is done according to the following
2158                          * items:
2159                          * - the scope comparison between the address and
2160                          *   dst (dscopecmp)
2161                          * - the scope comparison between the address and
2162                          *   ifa_best (bscopecmp)
2163                          * - if the address match dst longer than ifa_best
2164                          *   (matchcmp)
2165                          * - if the address is on the outgoing I/F (outI/F)
2166                          *
2167                          * Roughly speaking, the selection policy is
2168                          * - the most important item is scope. The same scope
2169                          *   is best. Then search for a larger scope.
2170                          *   Smaller scopes are the last resort.
2171                          * - A deprecated address is chosen only when we have
2172                          *   no address that has an enough scope, but is
2173                          *   prefered to any addresses of smaller scopes
2174                          *   (this must be already done above.)
2175                          * - addresses on the outgoing I/F are preferred to
2176                          *   ones on other interfaces if none of above
2177                          *   tiebreaks.  In the table below, the column "bI"
2178                          *   means if the best_ifa is on the outgoing
2179                          *   interface, and the column "sI" means if the ifa
2180                          *   is on the outgoing interface.
2181                          * - If there is no other reasons to choose one,
2182                          *   longest address match against dst is considered.
2183                          *
2184                          * The precise decision table is as follows:
2185                          * dscopecmp bscopecmp    match  bI oI | replace?
2186                          *       N/A     equal      N/A   Y  N |   No (1)
2187                          *       N/A     equal      N/A   N  Y |  Yes (2)
2188                          *       N/A     equal   larger    N/A |  Yes (3)
2189                          *       N/A     equal  !larger    N/A |   No (4)
2190                          *    larger    larger      N/A    N/A |   No (5)
2191                          *    larger   smaller      N/A    N/A |  Yes (6)
2192                          *   smaller    larger      N/A    N/A |  Yes (7)
2193                          *   smaller   smaller      N/A    N/A |   No (8)
2194                          *     equal   smaller      N/A    N/A |  Yes (9)
2195                          *     equal    larger       (already done at A above)
2196                          */
2197                         dscopecmp = IN6_ARE_SCOPE_CMP(src_scope, dst_scope);
2198                         bscopecmp = IN6_ARE_SCOPE_CMP(src_scope, best_scope);
2199
2200                         if (bscopecmp == 0) {
2201                                 struct ifnet *bifp = ifa_best->ia_ifp;
2202
2203                                 if (bifp == oifp && ifp != oifp) /* (1) */
2204                                         continue;
2205                                 if (bifp != oifp && ifp == oifp) /* (2) */
2206                                         goto replace;
2207
2208                                 /*
2209                                  * Both bifp and ifp are on the outgoing
2210                                  * interface, or both two are on a different
2211                                  * interface from the outgoing I/F.
2212                                  * now we need address matching against dst
2213                                  * for tiebreaking.
2214                                  */
2215                                 tlen = in6_matchlen(IFA_IN6(ifa), dst);
2216                                 matchcmp = tlen - blen;
2217                                 if (matchcmp > 0) /* (3) */
2218                                         goto replace;
2219                                 continue; /* (4) */
2220                         }
2221                         if (dscopecmp > 0) {
2222                                 if (bscopecmp > 0) /* (5) */
2223                                         continue;
2224                                 goto replace; /* (6) */
2225                         }
2226                         if (dscopecmp < 0) {
2227                                 if (bscopecmp > 0) /* (7) */
2228                                         goto replace;
2229                                 continue; /* (8) */
2230                         }
2231
2232                         /* now dscopecmp must be 0 */
2233                         if (bscopecmp < 0)
2234                                 goto replace; /* (9) */
2235
2236                   replace:
2237                         ifa_best = (struct in6_ifaddr *)ifa;
2238                         blen = tlen >= 0 ? tlen :
2239                                 in6_matchlen(IFA_IN6(ifa), dst);
2240                         best_scope = in6_addrscope(&ifa_best->ia_addr.sin6_addr);
2241                 }
2242         }
2243
2244         /* count statistics for future improvements */
2245         if (ifa_best == NULL)
2246                 ip6stat.ip6s_sources_none++;
2247         else {
2248                 if (oifp == ifa_best->ia_ifp)
2249                         ip6stat.ip6s_sources_sameif[best_scope]++;
2250                 else
2251                         ip6stat.ip6s_sources_otherif[best_scope]++;
2252
2253                 if (best_scope == dst_scope)
2254                         ip6stat.ip6s_sources_samescope[best_scope]++;
2255                 else
2256                         ip6stat.ip6s_sources_otherscope[best_scope]++;
2257
2258                 if (ifa_best->ia6_flags & IN6_IFF_DEPRECATED)
2259                         ip6stat.ip6s_sources_deprecated[best_scope]++;
2260         }
2261
2262         return (ifa_best);
2263 }
2264
2265 /*
2266  * return the best address out of the same scope. if no address was
2267  * found, return the first valid address from designated IF.
2268  */
2269 struct in6_ifaddr *
2270 in6_ifawithifp(struct ifnet *ifp, struct in6_addr *dst)
2271 {
2272         int dst_scope = in6_addrscope(dst), blen = -1, tlen;
2273         struct ifaddr_container *ifac;
2274         struct in6_ifaddr *besta = 0;
2275         struct in6_ifaddr *dep[2];      /* last-resort: deprecated */
2276
2277         dep[0] = dep[1] = NULL;
2278
2279         /*
2280          * We first look for addresses in the same scope.
2281          * If there is one, return it.
2282          * If two or more, return one which matches the dst longest.
2283          * If none, return one of global addresses assigned other ifs.
2284          */
2285         TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
2286                 struct ifaddr *ifa = ifac->ifa;
2287
2288                 if (ifa->ifa_addr->sa_family != AF_INET6)
2289                         continue;
2290                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_ANYCAST)
2291                         continue; /* XXX: is there any case to allow anycast? */
2292                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_NOTREADY)
2293                         continue; /* don't use this interface */
2294                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DETACHED)
2295                         continue;
2296                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DEPRECATED) {
2297                         if (ip6_use_deprecated)
2298                                 dep[0] = (struct in6_ifaddr *)ifa;
2299                         continue;
2300                 }
2301
2302                 if (dst_scope == in6_addrscope(IFA_IN6(ifa))) {
2303                         /*
2304                          * call in6_matchlen() as few as possible
2305                          */
2306                         if (besta) {
2307                                 if (blen == -1)
2308                                         blen = in6_matchlen(&besta->ia_addr.sin6_addr, dst);
2309                                 tlen = in6_matchlen(IFA_IN6(ifa), dst);
2310                                 if (tlen > blen) {
2311                                         blen = tlen;
2312                                         besta = (struct in6_ifaddr *)ifa;
2313                                 }
2314                         } else
2315                                 besta = (struct in6_ifaddr *)ifa;
2316                 }
2317         }
2318         if (besta)
2319                 return (besta);
2320
2321         TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
2322                 struct ifaddr *ifa = ifac->ifa;
2323
2324                 if (ifa->ifa_addr->sa_family != AF_INET6)
2325                         continue;
2326                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_ANYCAST)
2327                         continue; /* XXX: is there any case to allow anycast? */
2328                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_NOTREADY)
2329                         continue; /* don't use this interface */
2330                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DETACHED)
2331                         continue;
2332                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DEPRECATED) {
2333                         if (ip6_use_deprecated)
2334                                 dep[1] = (struct in6_ifaddr *)ifa;
2335                         continue;
2336                 }
2337
2338                 return (struct in6_ifaddr *)ifa;
2339         }
2340
2341         /* use the last-resort values, that are, deprecated addresses */
2342         if (dep[0])
2343                 return dep[0];
2344         if (dep[1])
2345                 return dep[1];
2346
2347         return NULL;
2348 }
2349
2350 /*
2351  * perform DAD when interface becomes IFF_UP.
2352  */
2353 void
2354 in6_if_up(struct ifnet *ifp)
2355 {
2356         struct ifaddr_container *ifac;
2357         struct in6_ifaddr *ia;
2358         int dad_delay;          /* delay ticks before DAD output */
2359
2360         /*
2361          * special cases, like 6to4, are handled in in6_ifattach
2362          */
2363         in6_ifattach(ifp, NULL);
2364
2365         dad_delay = 0;
2366         TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
2367                 struct ifaddr *ifa = ifac->ifa;
2368
2369                 if (ifa->ifa_addr->sa_family != AF_INET6)
2370                         continue;
2371                 ia = (struct in6_ifaddr *)ifa;
2372                 if (ia->ia6_flags & IN6_IFF_TENTATIVE)
2373                         nd6_dad_start(ifa, &dad_delay);
2374         }
2375 }
2376
2377 int
2378 in6if_do_dad(struct ifnet *ifp)
2379 {
2380         if (ifp->if_flags & IFF_LOOPBACK)
2381                 return (0);
2382
2383         switch (ifp->if_type) {
2384 #ifdef IFT_DUMMY
2385         case IFT_DUMMY:
2386 #endif
2387         case IFT_FAITH:
2388                 /*
2389                  * These interfaces do not have the IFF_LOOPBACK flag,
2390                  * but loop packets back.  We do not have to do DAD on such
2391                  * interfaces.  We should even omit it, because loop-backed
2392                  * NS would confuse the DAD procedure.
2393                  */
2394                 return (0);
2395         default:
2396                 /*
2397                  * Our DAD routine requires the interface up and running.
2398                  * However, some interfaces can be up before the RUNNING
2399                  * status.  Additionaly, users may try to assign addresses
2400                  * before the interface becomes up (or running).
2401                  * We simply skip DAD in such a case as a work around.
2402                  * XXX: we should rather mark "tentative" on such addresses,
2403                  * and do DAD after the interface becomes ready.
2404                  */
2405                 if ((ifp->if_flags & (IFF_UP|IFF_RUNNING)) !=
2406                     (IFF_UP|IFF_RUNNING))
2407                         return (0);
2408
2409                 return (1);
2410         }
2411 }
2412
2413 /*
2414  * Calculate max IPv6 MTU through all the interfaces and store it
2415  * to in6_maxmtu.
2416  */
2417 void
2418 in6_setmaxmtu(void)
2419 {
2420         unsigned long maxmtu = 0;
2421         struct ifnet *ifp;
2422
2423         for (ifp = TAILQ_FIRST(&ifnet); ifp; ifp = TAILQ_NEXT(ifp, if_list))
2424         {
2425                 /* this function can be called during ifnet initialization */
2426                 if (!ifp->if_afdata[AF_INET6])
2427                         continue;
2428                 if (!(ifp->if_flags & IFF_LOOPBACK) &&
2429                     ND_IFINFO(ifp)->linkmtu > maxmtu)
2430                         maxmtu =  ND_IFINFO(ifp)->linkmtu;
2431         }
2432         if (maxmtu)     /* update only when maxmtu is positive */
2433                 in6_maxmtu = maxmtu;
2434 }
2435
2436 void *
2437 in6_domifattach(struct ifnet *ifp)
2438 {
2439         struct in6_ifextra *ext;
2440
2441         ext = (struct in6_ifextra *)kmalloc(sizeof(*ext), M_IFADDR, M_WAITOK);
2442         bzero(ext, sizeof(*ext));
2443
2444         ext->in6_ifstat = (struct in6_ifstat *)kmalloc(sizeof(struct in6_ifstat),
2445                 M_IFADDR, M_WAITOK);
2446         bzero(ext->in6_ifstat, sizeof(*ext->in6_ifstat));
2447
2448         ext->icmp6_ifstat =
2449                 (struct icmp6_ifstat *)kmalloc(sizeof(struct icmp6_ifstat),
2450                         M_IFADDR, M_WAITOK);
2451         bzero(ext->icmp6_ifstat, sizeof(*ext->icmp6_ifstat));
2452
2453         ext->nd_ifinfo = nd6_ifattach(ifp);
2454         ext->scope6_id = scope6_ifattach(ifp);
2455         return ext;
2456 }
2457
2458 void
2459 in6_domifdetach(struct ifnet *ifp, void *aux)
2460 {
2461         struct in6_ifextra *ext = (struct in6_ifextra *)aux;
2462         scope6_ifdetach(ext->scope6_id);
2463         nd6_ifdetach(ext->nd_ifinfo);
2464         kfree(ext->in6_ifstat, M_IFADDR);
2465         kfree(ext->icmp6_ifstat, M_IFADDR);
2466         kfree(ext, M_IFADDR);
2467 }
2468
2469 /*
2470  * Convert sockaddr_in6 to sockaddr_in.  Original sockaddr_in6 must be
2471  * v4 mapped addr or v4 compat addr
2472  */
2473 void
2474 in6_sin6_2_sin(struct sockaddr_in *sin, struct sockaddr_in6 *sin6)
2475 {
2476         bzero(sin, sizeof(*sin));
2477         sin->sin_len = sizeof(struct sockaddr_in);
2478         sin->sin_family = AF_INET;
2479         sin->sin_port = sin6->sin6_port;
2480         sin->sin_addr.s_addr = sin6->sin6_addr.s6_addr32[3];
2481 }
2482
2483 /* Convert sockaddr_in to sockaddr_in6 in v4 mapped addr format. */
2484 void
2485 in6_sin_2_v4mapsin6(struct sockaddr_in *sin, struct sockaddr_in6 *sin6)
2486 {
2487         bzero(sin6, sizeof(*sin6));
2488         sin6->sin6_len = sizeof(struct sockaddr_in6);
2489         sin6->sin6_family = AF_INET6;
2490         sin6->sin6_port = sin->sin_port;
2491         sin6->sin6_addr.s6_addr32[0] = 0;
2492         sin6->sin6_addr.s6_addr32[1] = 0;
2493         sin6->sin6_addr.s6_addr32[2] = IPV6_ADDR_INT32_SMP;
2494         sin6->sin6_addr.s6_addr32[3] = sin->sin_addr.s_addr;
2495 }
2496
2497 /* Convert sockaddr_in6 into sockaddr_in. */
2498 void
2499 in6_sin6_2_sin_in_sock(struct sockaddr *nam)
2500 {
2501         struct sockaddr_in *sin_p;
2502         struct sockaddr_in6 sin6;
2503
2504         /*
2505          * Save original sockaddr_in6 addr and convert it
2506          * to sockaddr_in.
2507          */
2508         sin6 = *(struct sockaddr_in6 *)nam;
2509         sin_p = (struct sockaddr_in *)nam;
2510         in6_sin6_2_sin(sin_p, &sin6);
2511 }
2512
2513 /* Convert sockaddr_in into sockaddr_in6 in v4 mapped addr format. */
2514 void
2515 in6_sin_2_v4mapsin6_in_sock(struct sockaddr **nam)
2516 {
2517         struct sockaddr_in *sin_p;
2518         struct sockaddr_in6 *sin6_p;
2519
2520         MALLOC(sin6_p, struct sockaddr_in6 *, sizeof *sin6_p, M_SONAME,
2521                M_WAITOK);
2522         sin_p = (struct sockaddr_in *)*nam;
2523         in6_sin_2_v4mapsin6(sin_p, sin6_p);
2524         FREE(*nam, M_SONAME);
2525         *nam = (struct sockaddr *)sin6_p;
2526 }