]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sys/netinet6/in6.c
MFC r277951:
[FreeBSD/stable/9.git] / sys / netinet6 / in6.c
1 /*-
2  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the project nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *      $KAME: in6.c,v 1.259 2002/01/21 11:37:50 keiichi Exp $
30  */
31
32 /*-
33  * Copyright (c) 1982, 1986, 1991, 1993
34  *      The Regents of the University of California.  All rights reserved.
35  *
36  * Redistribution and use in source and binary forms, with or without
37  * modification, are permitted provided that the following conditions
38  * are met:
39  * 1. Redistributions of source code must retain the above copyright
40  *    notice, this list of conditions and the following disclaimer.
41  * 2. Redistributions in binary form must reproduce the above copyright
42  *    notice, this list of conditions and the following disclaimer in the
43  *    documentation and/or other materials provided with the distribution.
44  * 4. Neither the name of the University nor the names of its contributors
45  *    may be used to endorse or promote products derived from this software
46  *    without specific prior written permission.
47  *
48  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58  * SUCH DAMAGE.
59  *
60  *      @(#)in.c        8.2 (Berkeley) 11/15/93
61  */
62
63 #include <sys/cdefs.h>
64 __FBSDID("$FreeBSD$");
65
66 #include "opt_compat.h"
67 #include "opt_inet.h"
68 #include "opt_inet6.h"
69
70 #include <sys/param.h>
71 #include <sys/errno.h>
72 #include <sys/jail.h>
73 #include <sys/malloc.h>
74 #include <sys/socket.h>
75 #include <sys/socketvar.h>
76 #include <sys/sockio.h>
77 #include <sys/systm.h>
78 #include <sys/priv.h>
79 #include <sys/proc.h>
80 #include <sys/time.h>
81 #include <sys/kernel.h>
82 #include <sys/syslog.h>
83
84 #include <net/if.h>
85 #include <net/if_var.h>
86 #include <net/if_types.h>
87 #include <net/route.h>
88 #include <net/if_dl.h>
89 #include <net/vnet.h>
90
91 #include <netinet/in.h>
92 #include <netinet/in_var.h>
93 #include <net/if_llatbl.h>
94 #include <netinet/if_ether.h>
95 #include <netinet/in_systm.h>
96 #include <netinet/ip.h>
97 #include <netinet/in_pcb.h>
98
99 #include <netinet/ip6.h>
100 #include <netinet6/ip6_var.h>
101 #include <netinet6/nd6.h>
102 #include <netinet6/mld6_var.h>
103 #include <netinet6/ip6_mroute.h>
104 #include <netinet6/in6_ifattach.h>
105 #include <netinet6/scope6_var.h>
106 #include <netinet6/in6_pcb.h>
107
108 VNET_DECLARE(int, icmp6_nodeinfo_oldmcprefix);
109 #define V_icmp6_nodeinfo_oldmcprefix    VNET(icmp6_nodeinfo_oldmcprefix)
110
111 /*
112  * Definitions of some costant IP6 addresses.
113  */
114 const struct in6_addr in6addr_any = IN6ADDR_ANY_INIT;
115 const struct in6_addr in6addr_loopback = IN6ADDR_LOOPBACK_INIT;
116 const struct in6_addr in6addr_nodelocal_allnodes =
117         IN6ADDR_NODELOCAL_ALLNODES_INIT;
118 const struct in6_addr in6addr_linklocal_allnodes =
119         IN6ADDR_LINKLOCAL_ALLNODES_INIT;
120 const struct in6_addr in6addr_linklocal_allrouters =
121         IN6ADDR_LINKLOCAL_ALLROUTERS_INIT;
122 const struct in6_addr in6addr_linklocal_allv2routers =
123         IN6ADDR_LINKLOCAL_ALLV2ROUTERS_INIT;
124
125 const struct in6_addr in6mask0 = IN6MASK0;
126 const struct in6_addr in6mask32 = IN6MASK32;
127 const struct in6_addr in6mask64 = IN6MASK64;
128 const struct in6_addr in6mask96 = IN6MASK96;
129 const struct in6_addr in6mask128 = IN6MASK128;
130
131 const struct sockaddr_in6 sa6_any =
132         { sizeof(sa6_any), AF_INET6, 0, 0, IN6ADDR_ANY_INIT, 0 };
133
134 static int in6_lifaddr_ioctl(struct socket *, u_long, caddr_t,
135         struct ifnet *, struct thread *);
136 static int in6_ifinit(struct ifnet *, struct in6_ifaddr *,
137         struct sockaddr_in6 *, int);
138 static void in6_unlink_ifa(struct in6_ifaddr *, struct ifnet *);
139
140 int     (*faithprefix_p)(struct in6_addr *);
141
142 #define ifa2ia6(ifa)    ((struct in6_ifaddr *)(ifa))
143 #define ia62ifa(ia6)    (&((ia6)->ia_ifa))
144
145 void
146 in6_ifaddloop(struct ifaddr *ifa)
147 {
148         struct sockaddr_dl gateway;
149         struct sockaddr_in6 mask, addr;
150         struct rtentry rt;
151         struct in6_ifaddr *ia;
152         struct ifnet *ifp;
153         struct llentry *ln;
154
155         ia = ifa2ia6(ifa);
156         ifp = ifa->ifa_ifp;
157         IF_AFDATA_LOCK(ifp);
158         ifa->ifa_rtrequest = nd6_rtrequest;
159         ln = lla_lookup(LLTABLE6(ifp), (LLE_CREATE | LLE_IFADDR |
160             LLE_EXCLUSIVE), (struct sockaddr *)&ia->ia_addr);
161         IF_AFDATA_UNLOCK(ifp);
162         if (ln != NULL) {
163                 ln->la_expire = 0;  /* for IPv6 this means permanent */
164                 ln->ln_state = ND6_LLINFO_REACHABLE;
165                 /*
166                  * initialize for rtmsg generation
167                  */
168                 bzero(&gateway, sizeof(gateway));
169                 gateway.sdl_len = sizeof(gateway);
170                 gateway.sdl_family = AF_LINK;
171                 gateway.sdl_nlen = 0;
172                 gateway.sdl_alen = 6;
173                 memcpy(gateway.sdl_data, &ln->ll_addr.mac_aligned,
174                     sizeof(ln->ll_addr));
175                 LLE_WUNLOCK(ln);
176         }
177
178         bzero(&rt, sizeof(rt));
179         rt.rt_gateway = (struct sockaddr *)&gateway;
180         memcpy(&mask, &ia->ia_prefixmask, sizeof(ia->ia_prefixmask));
181         memcpy(&addr, &ia->ia_addr, sizeof(ia->ia_addr));
182         rt_mask(&rt) = (struct sockaddr *)&mask;
183         rt_key(&rt) = (struct sockaddr *)&addr;
184         rt.rt_flags = RTF_UP | RTF_HOST | RTF_STATIC;
185         /* Announce arrival of local address to all FIBs. */
186         rt_newaddrmsg(RTM_ADD, ifa, 0, &rt);
187 }
188
189 void
190 in6_ifremloop(struct ifaddr *ifa)
191 {
192         struct sockaddr_dl gateway;
193         struct sockaddr_in6 mask, addr;
194         struct rtentry rt0;
195         struct in6_ifaddr *ia;
196         struct ifnet *ifp;
197
198         ia = ifa2ia6(ifa);
199         ifp = ifa->ifa_ifp;
200         memcpy(&addr, &ia->ia_addr, sizeof(ia->ia_addr));
201         memcpy(&mask, &ia->ia_prefixmask, sizeof(ia->ia_prefixmask));
202         lltable_prefix_free(AF_INET6, (struct sockaddr *)&addr,
203                     (struct sockaddr *)&mask, LLE_STATIC);
204
205         /*
206          * initialize for rtmsg generation
207          */
208         bzero(&gateway, sizeof(gateway));
209         gateway.sdl_len = sizeof(gateway);
210         gateway.sdl_family = AF_LINK;
211         gateway.sdl_nlen = 0;
212         gateway.sdl_alen = ifp->if_addrlen;
213         bzero(&rt0, sizeof(rt0));
214         rt0.rt_gateway = (struct sockaddr *)&gateway;
215         rt_mask(&rt0) = (struct sockaddr *)&mask;
216         rt_key(&rt0) = (struct sockaddr *)&addr;
217         rt0.rt_flags = RTF_HOST | RTF_STATIC;
218         /* Announce removal of local address to all FIBs. */
219         rt_newaddrmsg(RTM_DELETE, ifa, 0, &rt0);
220 }
221
222 int
223 in6_mask2len(struct in6_addr *mask, u_char *lim0)
224 {
225         int x = 0, y;
226         u_char *lim = lim0, *p;
227
228         /* ignore the scope_id part */
229         if (lim0 == NULL || lim0 - (u_char *)mask > sizeof(*mask))
230                 lim = (u_char *)mask + sizeof(*mask);
231         for (p = (u_char *)mask; p < lim; x++, p++) {
232                 if (*p != 0xff)
233                         break;
234         }
235         y = 0;
236         if (p < lim) {
237                 for (y = 0; y < 8; y++) {
238                         if ((*p & (0x80 >> y)) == 0)
239                                 break;
240                 }
241         }
242
243         /*
244          * when the limit pointer is given, do a stricter check on the
245          * remaining bits.
246          */
247         if (p < lim) {
248                 if (y != 0 && (*p & (0x00ff >> y)) != 0)
249                         return (-1);
250                 for (p = p + 1; p < lim; p++)
251                         if (*p != 0)
252                                 return (-1);
253         }
254
255         return x * 8 + y;
256 }
257
258 #ifdef COMPAT_FREEBSD32
259 struct in6_ndifreq32 {
260         char ifname[IFNAMSIZ];
261         uint32_t ifindex;
262 };
263 #define SIOCGDEFIFACE32_IN6     _IOWR('i', 86, struct in6_ndifreq32)
264 #endif
265
266 int
267 in6_control(struct socket *so, u_long cmd, caddr_t data,
268     struct ifnet *ifp, struct thread *td)
269 {
270         struct  in6_ifreq *ifr = (struct in6_ifreq *)data;
271         struct  in6_ifaddr *ia = NULL;
272         struct  in6_aliasreq *ifra = (struct in6_aliasreq *)data;
273         struct sockaddr_in6 *sa6;
274         int error;
275
276         switch (cmd) {
277         case SIOCGETSGCNT_IN6:
278         case SIOCGETMIFCNT_IN6:
279                 /*
280                  * XXX mrt_ioctl has a 3rd, unused, FIB argument in route.c.
281                  * We cannot see how that would be needed, so do not adjust the
282                  * KPI blindly; more likely should clean up the IPv4 variant.
283                  */
284                 return (mrt6_ioctl ? mrt6_ioctl(cmd, data) : EOPNOTSUPP);
285         }
286
287         switch (cmd) {
288         case SIOCAADDRCTL_POLICY:
289         case SIOCDADDRCTL_POLICY:
290                 if (td != NULL) {
291                         error = priv_check(td, PRIV_NETINET_ADDRCTRL6);
292                         if (error)
293                                 return (error);
294                 }
295                 return (in6_src_ioctl(cmd, data));
296         }
297
298         if (ifp == NULL)
299                 return (EOPNOTSUPP);
300
301         switch (cmd) {
302         case SIOCSNDFLUSH_IN6:
303         case SIOCSPFXFLUSH_IN6:
304         case SIOCSRTRFLUSH_IN6:
305         case SIOCSDEFIFACE_IN6:
306         case SIOCSIFINFO_FLAGS:
307         case SIOCSIFINFO_IN6:
308                 if (td != NULL) {
309                         error = priv_check(td, PRIV_NETINET_ND6);
310                         if (error)
311                                 return (error);
312                 }
313                 /* FALLTHROUGH */
314         case OSIOCGIFINFO_IN6:
315         case SIOCGIFINFO_IN6:
316         case SIOCGDRLST_IN6:
317         case SIOCGPRLST_IN6:
318         case SIOCGNBRINFO_IN6:
319         case SIOCGDEFIFACE_IN6:
320                 return (nd6_ioctl(cmd, data, ifp));
321
322 #ifdef COMPAT_FREEBSD32
323         case SIOCGDEFIFACE32_IN6:
324                 {
325                         struct in6_ndifreq ndif;
326                         struct in6_ndifreq32 *ndif32;
327
328                         error = nd6_ioctl(SIOCGDEFIFACE_IN6, (caddr_t)&ndif,
329                             ifp);
330                         if (error)
331                                 return (error);
332                         ndif32 = (struct in6_ndifreq32 *)data;
333                         ndif32->ifindex = ndif.ifindex;
334                         return (0);
335                 }
336 #endif
337         }
338
339         switch (cmd) {
340         case SIOCSIFPREFIX_IN6:
341         case SIOCDIFPREFIX_IN6:
342         case SIOCAIFPREFIX_IN6:
343         case SIOCCIFPREFIX_IN6:
344         case SIOCSGIFPREFIX_IN6:
345         case SIOCGIFPREFIX_IN6:
346                 log(LOG_NOTICE,
347                     "prefix ioctls are now invalidated. "
348                     "please use ifconfig.\n");
349                 return (EOPNOTSUPP);
350         }
351
352         switch (cmd) {
353         case SIOCSSCOPE6:
354                 if (td != NULL) {
355                         error = priv_check(td, PRIV_NETINET_SCOPE6);
356                         if (error)
357                                 return (error);
358                 }
359                 /* FALLTHROUGH */
360         case SIOCGSCOPE6:
361         case SIOCGSCOPE6DEF:
362                 return (scope6_ioctl(cmd, data, ifp));
363         }
364
365         switch (cmd) {
366         case SIOCALIFADDR:
367                 if (td != NULL) {
368                         error = priv_check(td, PRIV_NET_ADDIFADDR);
369                         if (error)
370                                 return (error);
371                 }
372                 return in6_lifaddr_ioctl(so, cmd, data, ifp, td);
373
374         case SIOCDLIFADDR:
375                 if (td != NULL) {
376                         error = priv_check(td, PRIV_NET_DELIFADDR);
377                         if (error)
378                                 return (error);
379                 }
380                 /* FALLTHROUGH */
381         case SIOCGLIFADDR:
382                 return in6_lifaddr_ioctl(so, cmd, data, ifp, td);
383         }
384
385         /*
386          * Find address for this interface, if it exists.
387          *
388          * In netinet code, we have checked ifra_addr in SIOCSIF*ADDR operation
389          * only, and used the first interface address as the target of other
390          * operations (without checking ifra_addr).  This was because netinet
391          * code/API assumed at most 1 interface address per interface.
392          * Since IPv6 allows a node to assign multiple addresses
393          * on a single interface, we almost always look and check the
394          * presence of ifra_addr, and reject invalid ones here.
395          * It also decreases duplicated code among SIOC*_IN6 operations.
396          */
397         switch (cmd) {
398         case SIOCAIFADDR_IN6:
399         case SIOCSIFPHYADDR_IN6:
400                 sa6 = &ifra->ifra_addr;
401                 break;
402         case SIOCSIFADDR_IN6:
403         case SIOCGIFADDR_IN6:
404         case SIOCSIFDSTADDR_IN6:
405         case SIOCSIFNETMASK_IN6:
406         case SIOCGIFDSTADDR_IN6:
407         case SIOCGIFNETMASK_IN6:
408         case SIOCDIFADDR_IN6:
409         case SIOCGIFPSRCADDR_IN6:
410         case SIOCGIFPDSTADDR_IN6:
411         case SIOCGIFAFLAG_IN6:
412         case SIOCSNDFLUSH_IN6:
413         case SIOCSPFXFLUSH_IN6:
414         case SIOCSRTRFLUSH_IN6:
415         case SIOCGIFALIFETIME_IN6:
416         case SIOCSIFALIFETIME_IN6:
417         case SIOCGIFSTAT_IN6:
418         case SIOCGIFSTAT_ICMP6:
419                 sa6 = &ifr->ifr_addr;
420                 break;
421         case SIOCSIFADDR:
422         case SIOCSIFBRDADDR:
423         case SIOCSIFDSTADDR:
424         case SIOCSIFNETMASK:
425                 /*
426                  * Although we should pass any non-INET6 ioctl requests
427                  * down to driver, we filter some legacy INET requests.
428                  * Drivers trust SIOCSIFADDR et al to come from an already
429                  * privileged layer, and do not perform any credentials
430                  * checks or input validation.
431                  */
432                 return (EINVAL);
433         default:
434                 sa6 = NULL;
435                 break;
436         }
437         if (sa6 && sa6->sin6_family == AF_INET6) {
438                 if (sa6->sin6_scope_id != 0)
439                         error = sa6_embedscope(sa6, 0);
440                 else
441                         error = in6_setscope(&sa6->sin6_addr, ifp, NULL);
442                 if (error != 0)
443                         return (error);
444                 if (td != NULL && (error = prison_check_ip6(td->td_ucred,
445                     &sa6->sin6_addr)) != 0)
446                         return (error);
447                 ia = in6ifa_ifpwithaddr(ifp, &sa6->sin6_addr);
448         } else
449                 ia = NULL;
450
451         switch (cmd) {
452         case SIOCSIFADDR_IN6:
453         case SIOCSIFDSTADDR_IN6:
454         case SIOCSIFNETMASK_IN6:
455                 /*
456                  * Since IPv6 allows a node to assign multiple addresses
457                  * on a single interface, SIOCSIFxxx ioctls are deprecated.
458                  */
459                 /* we decided to obsolete this command (20000704) */
460                 error = EINVAL;
461                 goto out;
462
463         case SIOCDIFADDR_IN6:
464                 /*
465                  * for IPv4, we look for existing in_ifaddr here to allow
466                  * "ifconfig if0 delete" to remove the first IPv4 address on
467                  * the interface.  For IPv6, as the spec allows multiple
468                  * interface address from the day one, we consider "remove the
469                  * first one" semantics to be not preferable.
470                  */
471                 if (ia == NULL) {
472                         error = EADDRNOTAVAIL;
473                         goto out;
474                 }
475                 /* FALLTHROUGH */
476         case SIOCAIFADDR_IN6:
477                 /*
478                  * We always require users to specify a valid IPv6 address for
479                  * the corresponding operation.
480                  */
481                 if (ifra->ifra_addr.sin6_family != AF_INET6 ||
482                     ifra->ifra_addr.sin6_len != sizeof(struct sockaddr_in6)) {
483                         error = EAFNOSUPPORT;
484                         goto out;
485                 }
486
487                 if (td != NULL) {
488                         error = priv_check(td, (cmd == SIOCDIFADDR_IN6) ?
489                             PRIV_NET_DELIFADDR : PRIV_NET_ADDIFADDR);
490                         if (error)
491                                 goto out;
492                 }
493                 /* FALLTHROUGH */
494         case SIOCGIFSTAT_IN6:
495         case SIOCGIFSTAT_ICMP6:
496                 if (ifp->if_afdata[AF_INET6] == NULL) {
497                         error = EPFNOSUPPORT;
498                         goto out;
499                 }
500                 break;
501
502         case SIOCGIFADDR_IN6:
503                 /* This interface is basically deprecated. use SIOCGIFCONF. */
504                 /* FALLTHROUGH */
505         case SIOCGIFAFLAG_IN6:
506         case SIOCGIFNETMASK_IN6:
507         case SIOCGIFDSTADDR_IN6:
508         case SIOCGIFALIFETIME_IN6:
509                 /* must think again about its semantics */
510                 if (ia == NULL) {
511                         error = EADDRNOTAVAIL;
512                         goto out;
513                 }
514                 break;
515
516         case SIOCSIFALIFETIME_IN6:
517             {
518                 struct in6_addrlifetime *lt;
519
520                 if (td != NULL) {
521                         error = priv_check(td, PRIV_NETINET_ALIFETIME6);
522                         if (error)
523                                 goto out;
524                 }
525                 if (ia == NULL) {
526                         error = EADDRNOTAVAIL;
527                         goto out;
528                 }
529                 /* sanity for overflow - beware unsigned */
530                 lt = &ifr->ifr_ifru.ifru_lifetime;
531                 if (lt->ia6t_vltime != ND6_INFINITE_LIFETIME &&
532                     lt->ia6t_vltime + time_second < time_second) {
533                         error = EINVAL;
534                         goto out;
535                 }
536                 if (lt->ia6t_pltime != ND6_INFINITE_LIFETIME &&
537                     lt->ia6t_pltime + time_second < time_second) {
538                         error = EINVAL;
539                         goto out;
540                 }
541                 break;
542             }
543         }
544
545         switch (cmd) {
546         case SIOCGIFADDR_IN6:
547                 ifr->ifr_addr = ia->ia_addr;
548                 if ((error = sa6_recoverscope(&ifr->ifr_addr)) != 0)
549                         goto out;
550                 break;
551
552         case SIOCGIFDSTADDR_IN6:
553                 if ((ifp->if_flags & IFF_POINTOPOINT) == 0) {
554                         error = EINVAL;
555                         goto out;
556                 }
557                 /*
558                  * XXX: should we check if ifa_dstaddr is NULL and return
559                  * an error?
560                  */
561                 ifr->ifr_dstaddr = ia->ia_dstaddr;
562                 if ((error = sa6_recoverscope(&ifr->ifr_dstaddr)) != 0)
563                         goto out;
564                 break;
565
566         case SIOCGIFNETMASK_IN6:
567                 ifr->ifr_addr = ia->ia_prefixmask;
568                 break;
569
570         case SIOCGIFAFLAG_IN6:
571                 ifr->ifr_ifru.ifru_flags6 = ia->ia6_flags;
572                 break;
573
574         case SIOCGIFSTAT_IN6:
575                 bzero(&ifr->ifr_ifru.ifru_stat,
576                     sizeof(ifr->ifr_ifru.ifru_stat));
577                 ifr->ifr_ifru.ifru_stat =
578                     *((struct in6_ifextra *)ifp->if_afdata[AF_INET6])->in6_ifstat;
579                 break;
580
581         case SIOCGIFSTAT_ICMP6:
582                 bzero(&ifr->ifr_ifru.ifru_icmp6stat,
583                     sizeof(ifr->ifr_ifru.ifru_icmp6stat));
584                 ifr->ifr_ifru.ifru_icmp6stat =
585                     *((struct in6_ifextra *)ifp->if_afdata[AF_INET6])->icmp6_ifstat;
586                 break;
587
588         case SIOCGIFALIFETIME_IN6:
589                 ifr->ifr_ifru.ifru_lifetime = ia->ia6_lifetime;
590                 if (ia->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
591                         time_t maxexpire;
592                         struct in6_addrlifetime *retlt =
593                             &ifr->ifr_ifru.ifru_lifetime;
594
595                         /*
596                          * XXX: adjust expiration time assuming time_t is
597                          * signed.
598                          */
599                         maxexpire = (-1) &
600                             ~((time_t)1 << ((sizeof(maxexpire) * 8) - 1));
601                         if (ia->ia6_lifetime.ia6t_vltime <
602                             maxexpire - ia->ia6_updatetime) {
603                                 retlt->ia6t_expire = ia->ia6_updatetime +
604                                     ia->ia6_lifetime.ia6t_vltime;
605                         } else
606                                 retlt->ia6t_expire = maxexpire;
607                 }
608                 if (ia->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
609                         time_t maxexpire;
610                         struct in6_addrlifetime *retlt =
611                             &ifr->ifr_ifru.ifru_lifetime;
612
613                         /*
614                          * XXX: adjust expiration time assuming time_t is
615                          * signed.
616                          */
617                         maxexpire = (-1) &
618                             ~((time_t)1 << ((sizeof(maxexpire) * 8) - 1));
619                         if (ia->ia6_lifetime.ia6t_pltime <
620                             maxexpire - ia->ia6_updatetime) {
621                                 retlt->ia6t_preferred = ia->ia6_updatetime +
622                                     ia->ia6_lifetime.ia6t_pltime;
623                         } else
624                                 retlt->ia6t_preferred = maxexpire;
625                 }
626                 break;
627
628         case SIOCSIFALIFETIME_IN6:
629                 ia->ia6_lifetime = ifr->ifr_ifru.ifru_lifetime;
630                 /* for sanity */
631                 if (ia->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
632                         ia->ia6_lifetime.ia6t_expire =
633                                 time_second + ia->ia6_lifetime.ia6t_vltime;
634                 } else
635                         ia->ia6_lifetime.ia6t_expire = 0;
636                 if (ia->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
637                         ia->ia6_lifetime.ia6t_preferred =
638                                 time_second + ia->ia6_lifetime.ia6t_pltime;
639                 } else
640                         ia->ia6_lifetime.ia6t_preferred = 0;
641                 break;
642
643         case SIOCAIFADDR_IN6:
644         {
645                 int i;
646                 struct nd_prefixctl pr0;
647                 struct nd_prefix *pr;
648
649                 /*
650                  * first, make or update the interface address structure,
651                  * and link it to the list.
652                  */
653                 if ((error = in6_update_ifa(ifp, ifra, ia, 0)) != 0)
654                         goto out;
655                 if (ia != NULL)
656                         ifa_free(&ia->ia_ifa);
657                 if ((ia = in6ifa_ifpwithaddr(ifp, &ifra->ifra_addr.sin6_addr))
658                     == NULL) {
659                         /*
660                          * this can happen when the user specify the 0 valid
661                          * lifetime.
662                          */
663                         break;
664                 }
665
666                 /*
667                  * then, make the prefix on-link on the interface.
668                  * XXX: we'd rather create the prefix before the address, but
669                  * we need at least one address to install the corresponding
670                  * interface route, so we configure the address first.
671                  */
672
673                 /*
674                  * convert mask to prefix length (prefixmask has already
675                  * been validated in in6_update_ifa().
676                  */
677                 bzero(&pr0, sizeof(pr0));
678                 pr0.ndpr_ifp = ifp;
679                 pr0.ndpr_plen = in6_mask2len(&ifra->ifra_prefixmask.sin6_addr,
680                     NULL);
681                 if (pr0.ndpr_plen == 128) {
682                         break;  /* we don't need to install a host route. */
683                 }
684                 pr0.ndpr_prefix = ifra->ifra_addr;
685                 /* apply the mask for safety. */
686                 for (i = 0; i < 4; i++) {
687                         pr0.ndpr_prefix.sin6_addr.s6_addr32[i] &=
688                             ifra->ifra_prefixmask.sin6_addr.s6_addr32[i];
689                 }
690                 /*
691                  * XXX: since we don't have an API to set prefix (not address)
692                  * lifetimes, we just use the same lifetimes as addresses.
693                  * The (temporarily) installed lifetimes can be overridden by
694                  * later advertised RAs (when accept_rtadv is non 0), which is
695                  * an intended behavior.
696                  */
697                 pr0.ndpr_raf_onlink = 1; /* should be configurable? */
698                 pr0.ndpr_raf_auto =
699                     ((ifra->ifra_flags & IN6_IFF_AUTOCONF) != 0);
700                 pr0.ndpr_vltime = ifra->ifra_lifetime.ia6t_vltime;
701                 pr0.ndpr_pltime = ifra->ifra_lifetime.ia6t_pltime;
702
703                 /* add the prefix if not yet. */
704                 if ((pr = nd6_prefix_lookup(&pr0)) == NULL) {
705                         /*
706                          * nd6_prelist_add will install the corresponding
707                          * interface route.
708                          */
709                         if ((error = nd6_prelist_add(&pr0, NULL, &pr)) != 0)
710                                 goto out;
711                         if (pr == NULL) {
712                                 log(LOG_ERR, "nd6_prelist_add succeeded but "
713                                     "no prefix\n");
714                                 error = EINVAL;
715                                 goto out;
716                         }
717                 }
718
719                 /* relate the address to the prefix */
720                 if (ia->ia6_ndpr == NULL) {
721                         ia->ia6_ndpr = pr;
722                         pr->ndpr_refcnt++;
723
724                         /*
725                          * If this is the first autoconf address from the
726                          * prefix, create a temporary address as well
727                          * (when required).
728                          */
729                         if ((ia->ia6_flags & IN6_IFF_AUTOCONF) &&
730                             V_ip6_use_tempaddr && pr->ndpr_refcnt == 1) {
731                                 int e;
732                                 if ((e = in6_tmpifadd(ia, 1, 0)) != 0) {
733                                         log(LOG_NOTICE, "in6_control: failed "
734                                             "to create a temporary address, "
735                                             "errno=%d\n", e);
736                                 }
737                         }
738                 }
739
740                 /*
741                  * this might affect the status of autoconfigured addresses,
742                  * that is, this address might make other addresses detached.
743                  */
744                 pfxlist_onlink_check();
745                 if (error == 0 && ia) {
746                         if (ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED) {
747                                 /*
748                                  * Try to clear the flag when a new
749                                  * IPv6 address is added onto an
750                                  * IFDISABLED interface and it
751                                  * succeeds.
752                                  */
753                                 struct in6_ndireq nd;
754
755                                 memset(&nd, 0, sizeof(nd));
756                                 nd.ndi.flags = ND_IFINFO(ifp)->flags;
757                                 nd.ndi.flags &= ~ND6_IFF_IFDISABLED;
758                                 if (nd6_ioctl(SIOCSIFINFO_FLAGS,
759                                     (caddr_t)&nd, ifp) < 0)
760                                         log(LOG_NOTICE, "SIOCAIFADDR_IN6: "
761                                             "SIOCSIFINFO_FLAGS for -ifdisabled "
762                                             "failed.");
763                                 /*
764                                  * Ignore failure of clearing the flag
765                                  * intentionally.  The failure means
766                                  * address duplication was detected.
767                                  */
768                         }
769                         EVENTHANDLER_INVOKE(ifaddr_event, ifp);
770                 }
771                 break;
772         }
773
774         case SIOCDIFADDR_IN6:
775         {
776                 struct nd_prefix *pr;
777
778                 /*
779                  * If the address being deleted is the only one that owns
780                  * the corresponding prefix, expire the prefix as well.
781                  * XXX: theoretically, we don't have to worry about such
782                  * relationship, since we separate the address management
783                  * and the prefix management.  We do this, however, to provide
784                  * as much backward compatibility as possible in terms of
785                  * the ioctl operation.
786                  * Note that in6_purgeaddr() will decrement ndpr_refcnt.
787                  */
788                 pr = ia->ia6_ndpr;
789                 in6_purgeaddr(&ia->ia_ifa);
790                 if (pr && pr->ndpr_refcnt == 0)
791                         prelist_remove(pr);
792                 EVENTHANDLER_INVOKE(ifaddr_event, ifp);
793                 break;
794         }
795
796         default:
797                 if (ifp->if_ioctl == NULL) {
798                         error = EOPNOTSUPP;
799                         goto out;
800                 }
801                 error = (*ifp->if_ioctl)(ifp, cmd, data);
802                 goto out;
803         }
804
805         error = 0;
806 out:
807         if (ia != NULL)
808                 ifa_free(&ia->ia_ifa);
809         return (error);
810 }
811
812
813 /*
814  * Join necessary multicast groups.  Factored out from in6_update_ifa().
815  * This entire work should only be done once, for the default FIB.
816  */
817 static int
818 in6_update_ifa_join_mc(struct ifnet *ifp, struct in6_aliasreq *ifra,
819     struct in6_ifaddr *ia, int flags, struct in6_multi **in6m_sol)
820 {
821         char ip6buf[INET6_ADDRSTRLEN];
822         struct sockaddr_in6 mltaddr, mltmask;
823         struct in6_addr llsol;
824         struct in6_multi_mship *imm;
825         struct rtentry *rt;
826         int delay, error;
827
828         KASSERT(in6m_sol != NULL, ("%s: in6m_sol is NULL", __func__));
829
830         /* Join solicited multicast addr for new host id. */
831         bzero(&llsol, sizeof(struct in6_addr));
832         llsol.s6_addr32[0] = IPV6_ADDR_INT32_MLL;
833         llsol.s6_addr32[1] = 0;
834         llsol.s6_addr32[2] = htonl(1);
835         llsol.s6_addr32[3] = ifra->ifra_addr.sin6_addr.s6_addr32[3];
836         llsol.s6_addr8[12] = 0xff;
837         if ((error = in6_setscope(&llsol, ifp, NULL)) != 0) {
838                 /* XXX: should not happen */
839                 log(LOG_ERR, "%s: in6_setscope failed\n", __func__);
840                 goto cleanup;
841         }
842         delay = 0;
843         if ((flags & IN6_IFAUPDATE_DADDELAY)) {
844                 /*
845                  * We need a random delay for DAD on the address being
846                  * configured.  It also means delaying transmission of the
847                  * corresponding MLD report to avoid report collision.
848                  * [RFC 4861, Section 6.3.7]
849                  */
850                 delay = arc4random() % (MAX_RTR_SOLICITATION_DELAY * hz);
851         }
852         imm = in6_joingroup(ifp, &llsol, &error, delay);
853         if (imm == NULL) {
854                 nd6log((LOG_WARNING, "%s: addmulti failed for %s on %s "
855                     "(errno=%d)\n", __func__, ip6_sprintf(ip6buf, &llsol),
856                     if_name(ifp), error));
857                 goto cleanup;
858         }
859         LIST_INSERT_HEAD(&ia->ia6_memberships, imm, i6mm_chain);
860         *in6m_sol = imm->i6mm_maddr;
861
862         bzero(&mltmask, sizeof(mltmask));
863         mltmask.sin6_len = sizeof(struct sockaddr_in6);
864         mltmask.sin6_family = AF_INET6;
865         mltmask.sin6_addr = in6mask32;
866 #define MLTMASK_LEN  4  /* mltmask's masklen (=32bit=4octet) */
867
868         /*
869          * Join link-local all-nodes address.
870          */
871         bzero(&mltaddr, sizeof(mltaddr));
872         mltaddr.sin6_len = sizeof(struct sockaddr_in6);
873         mltaddr.sin6_family = AF_INET6;
874         mltaddr.sin6_addr = in6addr_linklocal_allnodes;
875         if ((error = in6_setscope(&mltaddr.sin6_addr, ifp, NULL)) != 0)
876                 goto cleanup; /* XXX: should not fail */
877
878         /*
879          * XXX: do we really need this automatic routes?  We should probably
880          * reconsider this stuff.  Most applications actually do not need the
881          * routes, since they usually specify the outgoing interface.
882          */
883         rt = in6_rtalloc1((struct sockaddr *)&mltaddr, 0, 0UL, RT_DEFAULT_FIB);
884         if (rt != NULL) {
885                 /* XXX: only works in !SCOPEDROUTING case. */
886                 if (memcmp(&mltaddr.sin6_addr,
887                     &((struct sockaddr_in6 *)rt_key(rt))->sin6_addr,
888                     MLTMASK_LEN)) {
889                         RTFREE_LOCKED(rt);
890                         rt = NULL;
891                 }
892         }
893         if (rt == NULL) {
894                 error = in6_rtrequest(RTM_ADD, (struct sockaddr *)&mltaddr,
895                     (struct sockaddr *)&ia->ia_addr,
896                     (struct sockaddr *)&mltmask, RTF_UP,
897                     (struct rtentry **)0, RT_DEFAULT_FIB);
898                 if (error)
899                         goto cleanup;
900         } else
901                 RTFREE_LOCKED(rt);
902
903         imm = in6_joingroup(ifp, &mltaddr.sin6_addr, &error, 0);
904         if (imm == NULL) {
905                 nd6log((LOG_WARNING, "%s: addmulti failed for %s on %s "
906                     "(errno=%d)\n", __func__, ip6_sprintf(ip6buf,
907                     &mltaddr.sin6_addr), if_name(ifp), error));
908                 goto cleanup;
909         }
910         LIST_INSERT_HEAD(&ia->ia6_memberships, imm, i6mm_chain);
911
912         /*
913          * Join node information group address.
914          */
915         delay = 0;
916         if ((flags & IN6_IFAUPDATE_DADDELAY)) {
917                 /*
918                  * The spec does not say anything about delay for this group,
919                  * but the same logic should apply.
920                  */
921                 delay = arc4random() % (MAX_RTR_SOLICITATION_DELAY * hz);
922         }
923         if (in6_nigroup(ifp, NULL, -1, &mltaddr.sin6_addr) == 0) {
924                 /* XXX jinmei */
925                 imm = in6_joingroup(ifp, &mltaddr.sin6_addr, &error, delay);
926                 if (imm == NULL)
927                         nd6log((LOG_WARNING, "%s: addmulti failed for %s on %s "
928                             "(errno=%d)\n", __func__, ip6_sprintf(ip6buf,
929                             &mltaddr.sin6_addr), if_name(ifp), error));
930                         /* XXX not very fatal, go on... */
931                 else
932                         LIST_INSERT_HEAD(&ia->ia6_memberships, imm, i6mm_chain);
933         }
934         if (V_icmp6_nodeinfo_oldmcprefix && 
935              in6_nigroup_oldmcprefix(ifp, NULL, -1, &mltaddr.sin6_addr) == 0) {
936                 imm = in6_joingroup(ifp, &mltaddr.sin6_addr, &error, delay);
937                 if (imm == NULL)
938                         nd6log((LOG_WARNING, "%s: addmulti failed for %s on %s "
939                             "(errno=%d)\n", __func__, ip6_sprintf(ip6buf,
940                             &mltaddr.sin6_addr), if_name(ifp), error));
941                         /* XXX not very fatal, go on... */
942                 else
943                         LIST_INSERT_HEAD(&ia->ia6_memberships, imm, i6mm_chain);
944         }
945
946         /*
947          * Join interface-local all-nodes address.
948          * (ff01::1%ifN, and ff01::%ifN/32)
949          */
950         mltaddr.sin6_addr = in6addr_nodelocal_allnodes;
951         if ((error = in6_setscope(&mltaddr.sin6_addr, ifp, NULL)) != 0)
952                 goto cleanup; /* XXX: should not fail */
953         /* XXX: again, do we really need the route? */
954         rt = in6_rtalloc1((struct sockaddr *)&mltaddr, 0, 0UL, RT_DEFAULT_FIB);
955         if (rt != NULL) {
956                 if (memcmp(&mltaddr.sin6_addr,
957                     &((struct sockaddr_in6 *)rt_key(rt))->sin6_addr,
958                     MLTMASK_LEN)) {
959                         RTFREE_LOCKED(rt);
960                         rt = NULL;
961                 }
962         }
963         if (rt == NULL) {
964                 error = in6_rtrequest(RTM_ADD, (struct sockaddr *)&mltaddr,
965                     (struct sockaddr *)&ia->ia_addr,
966                     (struct sockaddr *)&mltmask, RTF_UP,
967                     (struct rtentry **)0, RT_DEFAULT_FIB);
968                 if (error)
969                         goto cleanup;
970         } else
971                 RTFREE_LOCKED(rt);
972
973         imm = in6_joingroup(ifp, &mltaddr.sin6_addr, &error, 0);
974         if (imm == NULL) {
975                 nd6log((LOG_WARNING, "%s: addmulti failed for %s on %s "
976                     "(errno=%d)\n", __func__, ip6_sprintf(ip6buf,
977                     &mltaddr.sin6_addr), if_name(ifp), error));
978                 goto cleanup;
979         }
980         LIST_INSERT_HEAD(&ia->ia6_memberships, imm, i6mm_chain);
981 #undef  MLTMASK_LEN
982
983 cleanup:
984         return (error);
985 }
986
987 /*
988  * Update parameters of an IPv6 interface address.
989  * If necessary, a new entry is created and linked into address chains.
990  * This function is separated from in6_control().
991  * XXX: should this be performed under splnet()?
992  */
993 int
994 in6_update_ifa(struct ifnet *ifp, struct in6_aliasreq *ifra,
995     struct in6_ifaddr *ia, int flags)
996 {
997         int error = 0, hostIsNew = 0, plen = -1;
998         struct sockaddr_in6 dst6;
999         struct in6_addrlifetime *lt;
1000         struct in6_multi *in6m_sol;
1001         int delay;
1002         char ip6buf[INET6_ADDRSTRLEN];
1003
1004         /* Validate parameters */
1005         if (ifp == NULL || ifra == NULL) /* this maybe redundant */
1006                 return (EINVAL);
1007
1008         /*
1009          * The destination address for a p2p link must have a family
1010          * of AF_UNSPEC or AF_INET6.
1011          */
1012         if ((ifp->if_flags & IFF_POINTOPOINT) != 0 &&
1013             ifra->ifra_dstaddr.sin6_family != AF_INET6 &&
1014             ifra->ifra_dstaddr.sin6_family != AF_UNSPEC)
1015                 return (EAFNOSUPPORT);
1016         /*
1017          * validate ifra_prefixmask.  don't check sin6_family, netmask
1018          * does not carry fields other than sin6_len.
1019          */
1020         if (ifra->ifra_prefixmask.sin6_len > sizeof(struct sockaddr_in6))
1021                 return (EINVAL);
1022         /*
1023          * Because the IPv6 address architecture is classless, we require
1024          * users to specify a (non 0) prefix length (mask) for a new address.
1025          * We also require the prefix (when specified) mask is valid, and thus
1026          * reject a non-consecutive mask.
1027          */
1028         if (ia == NULL && ifra->ifra_prefixmask.sin6_len == 0)
1029                 return (EINVAL);
1030         if (ifra->ifra_prefixmask.sin6_len != 0) {
1031                 plen = in6_mask2len(&ifra->ifra_prefixmask.sin6_addr,
1032                     (u_char *)&ifra->ifra_prefixmask +
1033                     ifra->ifra_prefixmask.sin6_len);
1034                 if (plen <= 0)
1035                         return (EINVAL);
1036         } else {
1037                 /*
1038                  * In this case, ia must not be NULL.  We just use its prefix
1039                  * length.
1040                  */
1041                 plen = in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL);
1042         }
1043         /*
1044          * If the destination address on a p2p interface is specified,
1045          * and the address is a scoped one, validate/set the scope
1046          * zone identifier.
1047          */
1048         dst6 = ifra->ifra_dstaddr;
1049         if ((ifp->if_flags & (IFF_POINTOPOINT|IFF_LOOPBACK)) != 0 &&
1050             (dst6.sin6_family == AF_INET6)) {
1051                 struct in6_addr in6_tmp;
1052                 u_int32_t zoneid;
1053
1054                 in6_tmp = dst6.sin6_addr;
1055                 if (in6_setscope(&in6_tmp, ifp, &zoneid))
1056                         return (EINVAL); /* XXX: should be impossible */
1057
1058                 if (dst6.sin6_scope_id != 0) {
1059                         if (dst6.sin6_scope_id != zoneid)
1060                                 return (EINVAL);
1061                 } else          /* user omit to specify the ID. */
1062                         dst6.sin6_scope_id = zoneid;
1063
1064                 /* convert into the internal form */
1065                 if (sa6_embedscope(&dst6, 0))
1066                         return (EINVAL); /* XXX: should be impossible */
1067         }
1068         /*
1069          * The destination address can be specified only for a p2p or a
1070          * loopback interface.  If specified, the corresponding prefix length
1071          * must be 128.
1072          */
1073         if (ifra->ifra_dstaddr.sin6_family == AF_INET6) {
1074                 if ((ifp->if_flags & (IFF_POINTOPOINT|IFF_LOOPBACK)) == 0) {
1075                         /* XXX: noisy message */
1076                         nd6log((LOG_INFO, "in6_update_ifa: a destination can "
1077                             "be specified for a p2p or a loopback IF only\n"));
1078                         return (EINVAL);
1079                 }
1080                 if (plen != 128) {
1081                         nd6log((LOG_INFO, "in6_update_ifa: prefixlen should "
1082                             "be 128 when dstaddr is specified\n"));
1083                         return (EINVAL);
1084                 }
1085         }
1086         /* lifetime consistency check */
1087         lt = &ifra->ifra_lifetime;
1088         if (lt->ia6t_pltime > lt->ia6t_vltime)
1089                 return (EINVAL);
1090         if (lt->ia6t_vltime == 0) {
1091                 /*
1092                  * the following log might be noisy, but this is a typical
1093                  * configuration mistake or a tool's bug.
1094                  */
1095                 nd6log((LOG_INFO,
1096                     "in6_update_ifa: valid lifetime is 0 for %s\n",
1097                     ip6_sprintf(ip6buf, &ifra->ifra_addr.sin6_addr)));
1098
1099                 if (ia == NULL)
1100                         return (0); /* there's nothing to do */
1101         }
1102
1103         /*
1104          * If this is a new address, allocate a new ifaddr and link it
1105          * into chains.
1106          */
1107         if (ia == NULL) {
1108                 hostIsNew = 1;
1109                 /*
1110                  * When in6_update_ifa() is called in a process of a received
1111                  * RA, it is called under an interrupt context.  So, we should
1112                  * call malloc with M_NOWAIT.
1113                  */
1114                 ia = (struct in6_ifaddr *) malloc(sizeof(*ia), M_IFADDR,
1115                     M_NOWAIT);
1116                 if (ia == NULL)
1117                         return (ENOBUFS);
1118                 bzero((caddr_t)ia, sizeof(*ia));
1119                 ifa_init(&ia->ia_ifa);
1120                 LIST_INIT(&ia->ia6_memberships);
1121                 /* Initialize the address and masks, and put time stamp */
1122                 ia->ia_ifa.ifa_addr = (struct sockaddr *)&ia->ia_addr;
1123                 ia->ia_addr.sin6_family = AF_INET6;
1124                 ia->ia_addr.sin6_len = sizeof(ia->ia_addr);
1125                 ia->ia6_createtime = time_second;
1126                 if ((ifp->if_flags & (IFF_POINTOPOINT | IFF_LOOPBACK)) != 0) {
1127                         /*
1128                          * XXX: some functions expect that ifa_dstaddr is not
1129                          * NULL for p2p interfaces.
1130                          */
1131                         ia->ia_ifa.ifa_dstaddr =
1132                             (struct sockaddr *)&ia->ia_dstaddr;
1133                 } else {
1134                         ia->ia_ifa.ifa_dstaddr = NULL;
1135                 }
1136                 ia->ia_ifa.ifa_netmask = (struct sockaddr *)&ia->ia_prefixmask;
1137                 ia->ia_ifp = ifp;
1138                 ifa_ref(&ia->ia_ifa);                   /* if_addrhead */
1139                 IF_ADDR_WLOCK(ifp);
1140                 TAILQ_INSERT_TAIL(&ifp->if_addrhead, &ia->ia_ifa, ifa_link);
1141                 IF_ADDR_WUNLOCK(ifp);
1142
1143                 ifa_ref(&ia->ia_ifa);                   /* in6_ifaddrhead */
1144                 IN6_IFADDR_WLOCK();
1145                 TAILQ_INSERT_TAIL(&V_in6_ifaddrhead, ia, ia_link);
1146                 IN6_IFADDR_WUNLOCK();
1147         }
1148
1149         /* update timestamp */
1150         ia->ia6_updatetime = time_second;
1151
1152         /* set prefix mask */
1153         if (ifra->ifra_prefixmask.sin6_len) {
1154                 /*
1155                  * We prohibit changing the prefix length of an existing
1156                  * address, because
1157                  * + such an operation should be rare in IPv6, and
1158                  * + the operation would confuse prefix management.
1159                  */
1160                 if (ia->ia_prefixmask.sin6_len &&
1161                     in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL) != plen) {
1162                         nd6log((LOG_INFO, "in6_update_ifa: the prefix length of an"
1163                             " existing (%s) address should not be changed\n",
1164                             ip6_sprintf(ip6buf, &ia->ia_addr.sin6_addr)));
1165                         error = EINVAL;
1166                         goto unlink;
1167                 }
1168                 ia->ia_prefixmask = ifra->ifra_prefixmask;
1169         }
1170
1171         /*
1172          * If a new destination address is specified, scrub the old one and
1173          * install the new destination.  Note that the interface must be
1174          * p2p or loopback (see the check above.)
1175          */
1176         if (dst6.sin6_family == AF_INET6 &&
1177             !IN6_ARE_ADDR_EQUAL(&dst6.sin6_addr, &ia->ia_dstaddr.sin6_addr)) {
1178                 int e;
1179
1180                 if ((ia->ia_flags & IFA_ROUTE) != 0 &&
1181                     (e = rtinit(&(ia->ia_ifa), (int)RTM_DELETE, RTF_HOST)) != 0) {
1182                         nd6log((LOG_ERR, "in6_update_ifa: failed to remove "
1183                             "a route to the old destination: %s\n",
1184                             ip6_sprintf(ip6buf, &ia->ia_addr.sin6_addr)));
1185                         /* proceed anyway... */
1186                 } else
1187                         ia->ia_flags &= ~IFA_ROUTE;
1188                 ia->ia_dstaddr = dst6;
1189         }
1190
1191         /*
1192          * Set lifetimes.  We do not refer to ia6t_expire and ia6t_preferred
1193          * to see if the address is deprecated or invalidated, but initialize
1194          * these members for applications.
1195          */
1196         ia->ia6_lifetime = ifra->ifra_lifetime;
1197         if (ia->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
1198                 ia->ia6_lifetime.ia6t_expire =
1199                     time_second + ia->ia6_lifetime.ia6t_vltime;
1200         } else
1201                 ia->ia6_lifetime.ia6t_expire = 0;
1202         if (ia->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
1203                 ia->ia6_lifetime.ia6t_preferred =
1204                     time_second + ia->ia6_lifetime.ia6t_pltime;
1205         } else
1206                 ia->ia6_lifetime.ia6t_preferred = 0;
1207
1208         /* reset the interface and routing table appropriately. */
1209         if ((error = in6_ifinit(ifp, ia, &ifra->ifra_addr, hostIsNew)) != 0)
1210                 goto unlink;
1211
1212         /*
1213          * configure address flags.
1214          */
1215         ia->ia6_flags = ifra->ifra_flags;
1216         /*
1217          * backward compatibility - if IN6_IFF_DEPRECATED is set from the
1218          * userland, make it deprecated.
1219          */
1220         if ((ifra->ifra_flags & IN6_IFF_DEPRECATED) != 0) {
1221                 ia->ia6_lifetime.ia6t_pltime = 0;
1222                 ia->ia6_lifetime.ia6t_preferred = time_second;
1223         }
1224         /*
1225          * Make the address tentative before joining multicast addresses,
1226          * so that corresponding MLD responses would not have a tentative
1227          * source address.
1228          */
1229         ia->ia6_flags &= ~IN6_IFF_DUPLICATED;   /* safety */
1230         if (hostIsNew && in6if_do_dad(ifp))
1231                 ia->ia6_flags |= IN6_IFF_TENTATIVE;
1232
1233         /* DAD should be performed after ND6_IFF_IFDISABLED is cleared. */
1234         if (ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED)
1235                 ia->ia6_flags |= IN6_IFF_TENTATIVE;
1236
1237         /*
1238          * We are done if we have simply modified an existing address.
1239          */
1240         if (!hostIsNew)
1241                 return (error);
1242
1243         /*
1244          * Beyond this point, we should call in6_purgeaddr upon an error,
1245          * not just go to unlink.
1246          */
1247
1248         /* Join necessary multicast groups. */
1249         in6m_sol = NULL;
1250         if ((ifp->if_flags & IFF_MULTICAST) != 0) {
1251                 error = in6_update_ifa_join_mc(ifp, ifra, ia, flags, &in6m_sol);
1252                 if (error)
1253                         goto cleanup;
1254         }
1255
1256         /*
1257          * Perform DAD, if needed.
1258          * XXX It may be of use, if we can administratively disable DAD.
1259          */
1260         if (in6if_do_dad(ifp) && ((ifra->ifra_flags & IN6_IFF_NODAD) == 0) &&
1261             (ia->ia6_flags & IN6_IFF_TENTATIVE))
1262         {
1263                 int mindelay, maxdelay;
1264
1265                 delay = 0;
1266                 if ((flags & IN6_IFAUPDATE_DADDELAY)) {
1267                         /*
1268                          * We need to impose a delay before sending an NS
1269                          * for DAD.  Check if we also needed a delay for the
1270                          * corresponding MLD message.  If we did, the delay
1271                          * should be larger than the MLD delay (this could be
1272                          * relaxed a bit, but this simple logic is at least
1273                          * safe).
1274                          * XXX: Break data hiding guidelines and look at
1275                          * state for the solicited multicast group.
1276                          */
1277                         mindelay = 0;
1278                         if (in6m_sol != NULL &&
1279                             in6m_sol->in6m_state == MLD_REPORTING_MEMBER) {
1280                                 mindelay = in6m_sol->in6m_timer;
1281                         }
1282                         maxdelay = MAX_RTR_SOLICITATION_DELAY * hz;
1283                         if (maxdelay - mindelay == 0)
1284                                 delay = 0;
1285                         else {
1286                                 delay =
1287                                     (arc4random() % (maxdelay - mindelay)) +
1288                                     mindelay;
1289                         }
1290                 }
1291                 nd6_dad_start((struct ifaddr *)ia, delay);
1292         }
1293
1294         KASSERT(hostIsNew, ("in6_update_ifa: !hostIsNew"));
1295         ifa_free(&ia->ia_ifa);
1296         return (error);
1297
1298   unlink:
1299         /*
1300          * XXX: if a change of an existing address failed, keep the entry
1301          * anyway.
1302          */
1303         if (hostIsNew) {
1304                 in6_unlink_ifa(ia, ifp);
1305                 ifa_free(&ia->ia_ifa);
1306         }
1307         return (error);
1308
1309   cleanup:
1310         KASSERT(hostIsNew, ("in6_update_ifa: cleanup: !hostIsNew"));
1311         ifa_free(&ia->ia_ifa);
1312         in6_purgeaddr(&ia->ia_ifa);
1313         return error;
1314 }
1315
1316 /*
1317  * Leave multicast groups.  Factored out from in6_purgeaddr().
1318  * This entire work should only be done once, for the default FIB.
1319  */
1320 static int
1321 in6_purgeaddr_mc(struct ifnet *ifp, struct in6_ifaddr *ia, struct ifaddr *ifa0)
1322 {
1323         struct sockaddr_in6 mltaddr, mltmask;
1324         struct in6_multi_mship *imm;
1325         struct rtentry *rt;
1326         struct sockaddr_in6 sin6;
1327         int error;
1328
1329         /*
1330          * Leave from multicast groups we have joined for the interface.
1331          */
1332         while ((imm = LIST_FIRST(&ia->ia6_memberships)) != NULL) {
1333                 LIST_REMOVE(imm, i6mm_chain);
1334                 in6_leavegroup(imm);
1335         }
1336
1337         /*
1338          * Remove the link-local all-nodes address.
1339          */
1340         bzero(&mltmask, sizeof(mltmask));
1341         mltmask.sin6_len = sizeof(struct sockaddr_in6);
1342         mltmask.sin6_family = AF_INET6;
1343         mltmask.sin6_addr = in6mask32;
1344
1345         bzero(&mltaddr, sizeof(mltaddr));
1346         mltaddr.sin6_len = sizeof(struct sockaddr_in6);
1347         mltaddr.sin6_family = AF_INET6;
1348         mltaddr.sin6_addr = in6addr_linklocal_allnodes;
1349
1350         if ((error = in6_setscope(&mltaddr.sin6_addr, ifp, NULL)) != 0)
1351                 return (error);
1352
1353         /*
1354          * As for the mltaddr above, proactively prepare the sin6 to avoid
1355          * rtentry un- and re-locking.
1356          */
1357         if (ifa0 != NULL) {
1358                 bzero(&sin6, sizeof(sin6));
1359                 sin6.sin6_len = sizeof(sin6);
1360                 sin6.sin6_family = AF_INET6;
1361                 memcpy(&sin6.sin6_addr, &satosin6(ifa0->ifa_addr)->sin6_addr,
1362                     sizeof(sin6.sin6_addr));
1363                 error = in6_setscope(&sin6.sin6_addr, ifa0->ifa_ifp, NULL);
1364                 if (error != 0)
1365                         return (error);
1366         }
1367
1368         rt = in6_rtalloc1((struct sockaddr *)&mltaddr, 0, 0UL, RT_DEFAULT_FIB);
1369         if (rt != NULL && rt->rt_gateway != NULL &&
1370             (memcmp(&satosin6(rt->rt_gateway)->sin6_addr,
1371                     &ia->ia_addr.sin6_addr,
1372                     sizeof(ia->ia_addr.sin6_addr)) == 0)) {
1373                 /*
1374                  * If no more IPv6 address exists on this interface then
1375                  * remove the multicast address route.
1376                  */
1377                 if (ifa0 == NULL) {
1378                         memcpy(&mltaddr.sin6_addr,
1379                             &satosin6(rt_key(rt))->sin6_addr,
1380                             sizeof(mltaddr.sin6_addr));
1381                         RTFREE_LOCKED(rt);
1382                         error = in6_rtrequest(RTM_DELETE,
1383                             (struct sockaddr *)&mltaddr,
1384                             (struct sockaddr *)&ia->ia_addr,
1385                             (struct sockaddr *)&mltmask, RTF_UP,
1386                             (struct rtentry **)0, RT_DEFAULT_FIB);
1387                         if (error)
1388                                 log(LOG_INFO, "%s: link-local all-nodes "
1389                                     "multicast address deletion error\n",
1390                                     __func__);
1391                 } else {
1392                         /*
1393                          * Replace the gateway of the route.
1394                          */
1395                         memcpy(rt->rt_gateway, &sin6, sizeof(sin6));
1396                         RTFREE_LOCKED(rt);
1397                 }
1398         } else {
1399                 if (rt != NULL)
1400                         RTFREE_LOCKED(rt);
1401         }
1402
1403         /*
1404          * Remove the node-local all-nodes address.
1405          */
1406         mltaddr.sin6_addr = in6addr_nodelocal_allnodes;
1407         if ((error = in6_setscope(&mltaddr.sin6_addr, ifp, NULL)) != 0)
1408                 return (error);
1409
1410         rt = in6_rtalloc1((struct sockaddr *)&mltaddr, 0, 0UL, RT_DEFAULT_FIB);
1411         if (rt != NULL && rt->rt_gateway != NULL &&
1412             (memcmp(&satosin6(rt->rt_gateway)->sin6_addr,
1413                     &ia->ia_addr.sin6_addr,
1414                     sizeof(ia->ia_addr.sin6_addr)) == 0)) {
1415                 /*
1416                  * If no more IPv6 address exists on this interface then
1417                  * remove the multicast address route.
1418                  */
1419                 if (ifa0 == NULL) {
1420                         memcpy(&mltaddr.sin6_addr,
1421                             &satosin6(rt_key(rt))->sin6_addr,
1422                             sizeof(mltaddr.sin6_addr));
1423
1424                         RTFREE_LOCKED(rt);
1425                         error = in6_rtrequest(RTM_DELETE,
1426                             (struct sockaddr *)&mltaddr,
1427                             (struct sockaddr *)&ia->ia_addr,
1428                             (struct sockaddr *)&mltmask, RTF_UP,
1429                             (struct rtentry **)0, RT_DEFAULT_FIB);
1430                         if (error)
1431                                 log(LOG_INFO, "%s: node-local all-nodes"
1432                                     "multicast address deletion error\n",
1433                                     __func__);
1434                 } else {
1435                         /*
1436                          * Replace the gateway of the route.
1437                          */
1438                         memcpy(rt->rt_gateway, &sin6, sizeof(sin6));
1439                         RTFREE_LOCKED(rt);
1440                 }
1441         } else {
1442                 if (rt != NULL)
1443                         RTFREE_LOCKED(rt);
1444         }
1445
1446         return (0);
1447 }
1448
1449 void
1450 in6_purgeaddr(struct ifaddr *ifa)
1451 {
1452         struct ifnet *ifp = ifa->ifa_ifp;
1453         struct in6_ifaddr *ia = (struct in6_ifaddr *) ifa;
1454         int plen, error;
1455         struct ifaddr *ifa0;
1456
1457         /*
1458          * find another IPv6 address as the gateway for the
1459          * link-local and node-local all-nodes multicast
1460          * address routes
1461          */
1462         IF_ADDR_RLOCK(ifp);
1463         TAILQ_FOREACH(ifa0, &ifp->if_addrhead, ifa_link) {
1464                 if ((ifa0->ifa_addr->sa_family != AF_INET6) ||
1465                     memcmp(&satosin6(ifa0->ifa_addr)->sin6_addr,
1466                     &ia->ia_addr.sin6_addr, sizeof(struct in6_addr)) == 0)
1467                         continue;
1468                 else
1469                         break;
1470         }
1471         if (ifa0 != NULL)
1472                 ifa_ref(ifa0);
1473         IF_ADDR_RUNLOCK(ifp);
1474
1475         /*
1476          * Remove the loopback route to the interface address.
1477          * The check for the current setting of "nd6_useloopback"
1478          * is not needed.
1479          */
1480         if (ia->ia_flags & IFA_RTSELF) {
1481                 error = ifa_del_loopback_route((struct ifaddr *)ia,
1482                     (struct sockaddr *)&ia->ia_addr);
1483                 if (error == 0)
1484                         ia->ia_flags &= ~IFA_RTSELF;
1485         }
1486
1487         /* stop DAD processing */
1488         nd6_dad_stop(ifa);
1489
1490         /* Remove local address entry from lltable. */
1491         in6_ifremloop(ifa);
1492
1493         /* Leave multicast groups. */
1494         error = in6_purgeaddr_mc(ifp, ia, ifa0);
1495
1496         if (ifa0 != NULL)
1497                 ifa_free(ifa0);
1498
1499         plen = in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL); /* XXX */
1500         if ((ia->ia_flags & IFA_ROUTE) && plen == 128) {
1501                 error = rtinit(&(ia->ia_ifa), RTM_DELETE, ia->ia_flags |
1502                     (ia->ia_dstaddr.sin6_family == AF_INET6) ? RTF_HOST : 0);
1503                 if (error != 0)
1504                         log(LOG_INFO, "%s: err=%d, destination address delete "
1505                             "failed\n", __func__, error);
1506                 ia->ia_flags &= ~IFA_ROUTE;
1507         }
1508
1509         in6_unlink_ifa(ia, ifp);
1510 }
1511
1512 static void
1513 in6_unlink_ifa(struct in6_ifaddr *ia, struct ifnet *ifp)
1514 {
1515         int     s = splnet();
1516
1517         IF_ADDR_WLOCK(ifp);
1518         TAILQ_REMOVE(&ifp->if_addrhead, &ia->ia_ifa, ifa_link);
1519         IF_ADDR_WUNLOCK(ifp);
1520         ifa_free(&ia->ia_ifa);                  /* if_addrhead */
1521
1522         /*
1523          * Defer the release of what might be the last reference to the
1524          * in6_ifaddr so that it can't be freed before the remainder of the
1525          * cleanup.
1526          */
1527         IN6_IFADDR_WLOCK();
1528         TAILQ_REMOVE(&V_in6_ifaddrhead, ia, ia_link);
1529         IN6_IFADDR_WUNLOCK();
1530
1531         /*
1532          * Release the reference to the base prefix.  There should be a
1533          * positive reference.
1534          */
1535         if (ia->ia6_ndpr == NULL) {
1536                 nd6log((LOG_NOTICE,
1537                     "in6_unlink_ifa: autoconf'ed address "
1538                     "%p has no prefix\n", ia));
1539         } else {
1540                 ia->ia6_ndpr->ndpr_refcnt--;
1541                 ia->ia6_ndpr = NULL;
1542         }
1543
1544         /*
1545          * Also, if the address being removed is autoconf'ed, call
1546          * pfxlist_onlink_check() since the release might affect the status of
1547          * other (detached) addresses.
1548          */
1549         if ((ia->ia6_flags & IN6_IFF_AUTOCONF)) {
1550                 pfxlist_onlink_check();
1551         }
1552         ifa_free(&ia->ia_ifa);                  /* in6_ifaddrhead */
1553         splx(s);
1554 }
1555
1556 void
1557 in6_purgeif(struct ifnet *ifp)
1558 {
1559         struct ifaddr *ifa, *nifa;
1560
1561         TAILQ_FOREACH_SAFE(ifa, &ifp->if_addrhead, ifa_link, nifa) {
1562                 if (ifa->ifa_addr->sa_family != AF_INET6)
1563                         continue;
1564                 in6_purgeaddr(ifa);
1565         }
1566
1567         in6_ifdetach(ifp);
1568 }
1569
1570 /*
1571  * SIOC[GAD]LIFADDR.
1572  *      SIOCGLIFADDR: get first address. (?)
1573  *      SIOCGLIFADDR with IFLR_PREFIX:
1574  *              get first address that matches the specified prefix.
1575  *      SIOCALIFADDR: add the specified address.
1576  *      SIOCALIFADDR with IFLR_PREFIX:
1577  *              add the specified prefix, filling hostid part from
1578  *              the first link-local address.  prefixlen must be <= 64.
1579  *      SIOCDLIFADDR: delete the specified address.
1580  *      SIOCDLIFADDR with IFLR_PREFIX:
1581  *              delete the first address that matches the specified prefix.
1582  * return values:
1583  *      EINVAL on invalid parameters
1584  *      EADDRNOTAVAIL on prefix match failed/specified address not found
1585  *      other values may be returned from in6_ioctl()
1586  *
1587  * NOTE: SIOCALIFADDR(with IFLR_PREFIX set) allows prefixlen less than 64.
1588  * this is to accomodate address naming scheme other than RFC2374,
1589  * in the future.
1590  * RFC2373 defines interface id to be 64bit, but it allows non-RFC2374
1591  * address encoding scheme. (see figure on page 8)
1592  */
1593 static int
1594 in6_lifaddr_ioctl(struct socket *so, u_long cmd, caddr_t data,
1595     struct ifnet *ifp, struct thread *td)
1596 {
1597         struct if_laddrreq *iflr = (struct if_laddrreq *)data;
1598         struct ifaddr *ifa;
1599         struct sockaddr *sa;
1600
1601         /* sanity checks */
1602         if (!data || !ifp) {
1603                 panic("invalid argument to in6_lifaddr_ioctl");
1604                 /* NOTREACHED */
1605         }
1606
1607         switch (cmd) {
1608         case SIOCGLIFADDR:
1609                 /* address must be specified on GET with IFLR_PREFIX */
1610                 if ((iflr->flags & IFLR_PREFIX) == 0)
1611                         break;
1612                 /* FALLTHROUGH */
1613         case SIOCALIFADDR:
1614         case SIOCDLIFADDR:
1615                 /* address must be specified on ADD and DELETE */
1616                 sa = (struct sockaddr *)&iflr->addr;
1617                 if (sa->sa_family != AF_INET6)
1618                         return EINVAL;
1619                 if (sa->sa_len != sizeof(struct sockaddr_in6))
1620                         return EINVAL;
1621                 /* XXX need improvement */
1622                 sa = (struct sockaddr *)&iflr->dstaddr;
1623                 if (sa->sa_family && sa->sa_family != AF_INET6)
1624                         return EINVAL;
1625                 if (sa->sa_len && sa->sa_len != sizeof(struct sockaddr_in6))
1626                         return EINVAL;
1627                 break;
1628         default: /* shouldn't happen */
1629 #if 0
1630                 panic("invalid cmd to in6_lifaddr_ioctl");
1631                 /* NOTREACHED */
1632 #else
1633                 return EOPNOTSUPP;
1634 #endif
1635         }
1636         if (sizeof(struct in6_addr) * 8 < iflr->prefixlen)
1637                 return EINVAL;
1638
1639         switch (cmd) {
1640         case SIOCALIFADDR:
1641             {
1642                 struct in6_aliasreq ifra;
1643                 struct in6_addr *hostid = NULL;
1644                 int prefixlen;
1645
1646                 ifa = NULL;
1647                 if ((iflr->flags & IFLR_PREFIX) != 0) {
1648                         struct sockaddr_in6 *sin6;
1649
1650                         /*
1651                          * hostid is to fill in the hostid part of the
1652                          * address.  hostid points to the first link-local
1653                          * address attached to the interface.
1654                          */
1655                         ifa = (struct ifaddr *)in6ifa_ifpforlinklocal(ifp, 0);
1656                         if (!ifa)
1657                                 return EADDRNOTAVAIL;
1658                         hostid = IFA_IN6(ifa);
1659
1660                         /* prefixlen must be <= 64. */
1661                         if (64 < iflr->prefixlen) {
1662                                 if (ifa != NULL)
1663                                         ifa_free(ifa);
1664                                 return EINVAL;
1665                         }
1666                         prefixlen = iflr->prefixlen;
1667
1668                         /* hostid part must be zero. */
1669                         sin6 = (struct sockaddr_in6 *)&iflr->addr;
1670                         if (sin6->sin6_addr.s6_addr32[2] != 0 ||
1671                             sin6->sin6_addr.s6_addr32[3] != 0) {
1672                                 if (ifa != NULL)
1673                                         ifa_free(ifa);
1674                                 return EINVAL;
1675                         }
1676                 } else
1677                         prefixlen = iflr->prefixlen;
1678
1679                 /* copy args to in6_aliasreq, perform ioctl(SIOCAIFADDR_IN6). */
1680                 bzero(&ifra, sizeof(ifra));
1681                 bcopy(iflr->iflr_name, ifra.ifra_name, sizeof(ifra.ifra_name));
1682
1683                 bcopy(&iflr->addr, &ifra.ifra_addr,
1684                     ((struct sockaddr *)&iflr->addr)->sa_len);
1685                 if (hostid) {
1686                         /* fill in hostid part */
1687                         ifra.ifra_addr.sin6_addr.s6_addr32[2] =
1688                             hostid->s6_addr32[2];
1689                         ifra.ifra_addr.sin6_addr.s6_addr32[3] =
1690                             hostid->s6_addr32[3];
1691                 }
1692
1693                 if (((struct sockaddr *)&iflr->dstaddr)->sa_family) { /* XXX */
1694                         bcopy(&iflr->dstaddr, &ifra.ifra_dstaddr,
1695                             ((struct sockaddr *)&iflr->dstaddr)->sa_len);
1696                         if (hostid) {
1697                                 ifra.ifra_dstaddr.sin6_addr.s6_addr32[2] =
1698                                     hostid->s6_addr32[2];
1699                                 ifra.ifra_dstaddr.sin6_addr.s6_addr32[3] =
1700                                     hostid->s6_addr32[3];
1701                         }
1702                 }
1703                 if (ifa != NULL)
1704                         ifa_free(ifa);
1705
1706                 ifra.ifra_prefixmask.sin6_len = sizeof(struct sockaddr_in6);
1707                 in6_prefixlen2mask(&ifra.ifra_prefixmask.sin6_addr, prefixlen);
1708
1709                 ifra.ifra_flags = iflr->flags & ~IFLR_PREFIX;
1710                 return in6_control(so, SIOCAIFADDR_IN6, (caddr_t)&ifra, ifp, td);
1711             }
1712         case SIOCGLIFADDR:
1713         case SIOCDLIFADDR:
1714             {
1715                 struct in6_ifaddr *ia;
1716                 struct in6_addr mask, candidate, match;
1717                 struct sockaddr_in6 *sin6;
1718                 int cmp;
1719
1720                 bzero(&mask, sizeof(mask));
1721                 if (iflr->flags & IFLR_PREFIX) {
1722                         /* lookup a prefix rather than address. */
1723                         in6_prefixlen2mask(&mask, iflr->prefixlen);
1724
1725                         sin6 = (struct sockaddr_in6 *)&iflr->addr;
1726                         bcopy(&sin6->sin6_addr, &match, sizeof(match));
1727                         match.s6_addr32[0] &= mask.s6_addr32[0];
1728                         match.s6_addr32[1] &= mask.s6_addr32[1];
1729                         match.s6_addr32[2] &= mask.s6_addr32[2];
1730                         match.s6_addr32[3] &= mask.s6_addr32[3];
1731
1732                         /* if you set extra bits, that's wrong */
1733                         if (bcmp(&match, &sin6->sin6_addr, sizeof(match)))
1734                                 return EINVAL;
1735
1736                         cmp = 1;
1737                 } else {
1738                         if (cmd == SIOCGLIFADDR) {
1739                                 /* on getting an address, take the 1st match */
1740                                 cmp = 0;        /* XXX */
1741                         } else {
1742                                 /* on deleting an address, do exact match */
1743                                 in6_prefixlen2mask(&mask, 128);
1744                                 sin6 = (struct sockaddr_in6 *)&iflr->addr;
1745                                 bcopy(&sin6->sin6_addr, &match, sizeof(match));
1746
1747                                 cmp = 1;
1748                         }
1749                 }
1750
1751                 IF_ADDR_RLOCK(ifp);
1752                 TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1753                         if (ifa->ifa_addr->sa_family != AF_INET6)
1754                                 continue;
1755                         if (!cmp)
1756                                 break;
1757
1758                         /*
1759                          * XXX: this is adhoc, but is necessary to allow
1760                          * a user to specify fe80::/64 (not /10) for a
1761                          * link-local address.
1762                          */
1763                         bcopy(IFA_IN6(ifa), &candidate, sizeof(candidate));
1764                         in6_clearscope(&candidate);
1765                         candidate.s6_addr32[0] &= mask.s6_addr32[0];
1766                         candidate.s6_addr32[1] &= mask.s6_addr32[1];
1767                         candidate.s6_addr32[2] &= mask.s6_addr32[2];
1768                         candidate.s6_addr32[3] &= mask.s6_addr32[3];
1769                         if (IN6_ARE_ADDR_EQUAL(&candidate, &match))
1770                                 break;
1771                 }
1772                 if (ifa != NULL)
1773                         ifa_ref(ifa);
1774                 IF_ADDR_RUNLOCK(ifp);
1775                 if (!ifa)
1776                         return EADDRNOTAVAIL;
1777                 ia = ifa2ia6(ifa);
1778
1779                 if (cmd == SIOCGLIFADDR) {
1780                         int error;
1781
1782                         /* fill in the if_laddrreq structure */
1783                         bcopy(&ia->ia_addr, &iflr->addr, ia->ia_addr.sin6_len);
1784                         error = sa6_recoverscope(
1785                             (struct sockaddr_in6 *)&iflr->addr);
1786                         if (error != 0) {
1787                                 ifa_free(ifa);
1788                                 return (error);
1789                         }
1790
1791                         if ((ifp->if_flags & IFF_POINTOPOINT) != 0) {
1792                                 bcopy(&ia->ia_dstaddr, &iflr->dstaddr,
1793                                     ia->ia_dstaddr.sin6_len);
1794                                 error = sa6_recoverscope(
1795                                     (struct sockaddr_in6 *)&iflr->dstaddr);
1796                                 if (error != 0) {
1797                                         ifa_free(ifa);
1798                                         return (error);
1799                                 }
1800                         } else
1801                                 bzero(&iflr->dstaddr, sizeof(iflr->dstaddr));
1802
1803                         iflr->prefixlen =
1804                             in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL);
1805
1806                         iflr->flags = ia->ia6_flags;    /* XXX */
1807                         ifa_free(ifa);
1808
1809                         return 0;
1810                 } else {
1811                         struct in6_aliasreq ifra;
1812
1813                         /* fill in6_aliasreq and do ioctl(SIOCDIFADDR_IN6) */
1814                         bzero(&ifra, sizeof(ifra));
1815                         bcopy(iflr->iflr_name, ifra.ifra_name,
1816                             sizeof(ifra.ifra_name));
1817
1818                         bcopy(&ia->ia_addr, &ifra.ifra_addr,
1819                             ia->ia_addr.sin6_len);
1820                         if ((ifp->if_flags & IFF_POINTOPOINT) != 0) {
1821                                 bcopy(&ia->ia_dstaddr, &ifra.ifra_dstaddr,
1822                                     ia->ia_dstaddr.sin6_len);
1823                         } else {
1824                                 bzero(&ifra.ifra_dstaddr,
1825                                     sizeof(ifra.ifra_dstaddr));
1826                         }
1827                         bcopy(&ia->ia_prefixmask, &ifra.ifra_dstaddr,
1828                             ia->ia_prefixmask.sin6_len);
1829
1830                         ifra.ifra_flags = ia->ia6_flags;
1831                         ifa_free(ifa);
1832                         return in6_control(so, SIOCDIFADDR_IN6, (caddr_t)&ifra,
1833                             ifp, td);
1834                 }
1835             }
1836         }
1837
1838         return EOPNOTSUPP;      /* just for safety */
1839 }
1840
1841 /*
1842  * Initialize an interface's IPv6 address and routing table entry.
1843  */
1844 static int
1845 in6_ifinit(struct ifnet *ifp, struct in6_ifaddr *ia,
1846     struct sockaddr_in6 *sin6, int newhost)
1847 {
1848         int     error = 0, plen, ifacount = 0;
1849         int     s = splimp();
1850         struct ifaddr *ifa;
1851
1852         /*
1853          * Give the interface a chance to initialize
1854          * if this is its first address,
1855          * and to validate the address if necessary.
1856          */
1857         IF_ADDR_RLOCK(ifp);
1858         TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1859                 if (ifa->ifa_addr->sa_family != AF_INET6)
1860                         continue;
1861                 ifacount++;
1862         }
1863         IF_ADDR_RUNLOCK(ifp);
1864
1865         ia->ia_addr = *sin6;
1866
1867         if (ifacount <= 1 && ifp->if_ioctl) {
1868                 error = (*ifp->if_ioctl)(ifp, SIOCSIFADDR, (caddr_t)ia);
1869                 if (error) {
1870                         splx(s);
1871                         return (error);
1872                 }
1873         }
1874         splx(s);
1875
1876         ia->ia_ifa.ifa_metric = ifp->if_metric;
1877
1878         /* we could do in(6)_socktrim here, but just omit it at this moment. */
1879
1880         /*
1881          * Special case:
1882          * If a new destination address is specified for a point-to-point
1883          * interface, install a route to the destination as an interface
1884          * direct route.
1885          * XXX: the logic below rejects assigning multiple addresses on a p2p
1886          * interface that share the same destination.
1887          */
1888         plen = in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL); /* XXX */
1889         if (!(ia->ia_flags & IFA_ROUTE) && plen == 128 &&
1890             ia->ia_dstaddr.sin6_family == AF_INET6) {
1891                 int rtflags = RTF_UP | RTF_HOST;
1892                 error = rtinit(&ia->ia_ifa, RTM_ADD, ia->ia_flags | rtflags);
1893                 if (error)
1894                         return (error);
1895                 ia->ia_flags |= IFA_ROUTE;
1896                 /*
1897                  * Handle the case for ::1 .
1898                  */
1899                 if (ifp->if_flags & IFF_LOOPBACK)
1900                         ia->ia_flags |= IFA_RTSELF;
1901         }
1902
1903         /*
1904          * add a loopback route to self
1905          */
1906         if (!(ia->ia_flags & IFA_RTSELF) && V_nd6_useloopback) {
1907                 error = ifa_add_loopback_route((struct ifaddr *)ia,
1908                     (struct sockaddr *)&ia->ia_addr);
1909                 if (error == 0)
1910                         ia->ia_flags |= IFA_RTSELF;
1911         }
1912
1913         /* Add local address to lltable, if necessary (ex. on p2p link). */
1914         if (newhost)
1915                 in6_ifaddloop(&(ia->ia_ifa));
1916
1917         return (error);
1918 }
1919
1920 /*
1921  * Find an IPv6 interface link-local address specific to an interface.
1922  * ifaddr is returned referenced.
1923  */
1924 struct in6_ifaddr *
1925 in6ifa_ifpforlinklocal(struct ifnet *ifp, int ignoreflags)
1926 {
1927         struct ifaddr *ifa;
1928
1929         IF_ADDR_RLOCK(ifp);
1930         TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1931                 if (ifa->ifa_addr->sa_family != AF_INET6)
1932                         continue;
1933                 if (IN6_IS_ADDR_LINKLOCAL(IFA_IN6(ifa))) {
1934                         if ((((struct in6_ifaddr *)ifa)->ia6_flags &
1935                             ignoreflags) != 0)
1936                                 continue;
1937                         ifa_ref(ifa);
1938                         break;
1939                 }
1940         }
1941         IF_ADDR_RUNLOCK(ifp);
1942
1943         return ((struct in6_ifaddr *)ifa);
1944 }
1945
1946
1947 /*
1948  * find the internet address corresponding to a given interface and address.
1949  * ifaddr is returned referenced.
1950  */
1951 struct in6_ifaddr *
1952 in6ifa_ifpwithaddr(struct ifnet *ifp, struct in6_addr *addr)
1953 {
1954         struct ifaddr *ifa;
1955
1956         IF_ADDR_RLOCK(ifp);
1957         TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1958                 if (ifa->ifa_addr->sa_family != AF_INET6)
1959                         continue;
1960                 if (IN6_ARE_ADDR_EQUAL(addr, IFA_IN6(ifa))) {
1961                         ifa_ref(ifa);
1962                         break;
1963                 }
1964         }
1965         IF_ADDR_RUNLOCK(ifp);
1966
1967         return ((struct in6_ifaddr *)ifa);
1968 }
1969
1970 /*
1971  * Find a link-local scoped address on ifp and return it if any.
1972  */
1973 struct in6_ifaddr *
1974 in6ifa_llaonifp(struct ifnet *ifp)
1975 {
1976         struct sockaddr_in6 *sin6;
1977         struct ifaddr *ifa;
1978
1979         if (ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED)
1980                 return (NULL);
1981         if_addr_rlock(ifp);
1982         TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1983                 if (ifa->ifa_addr->sa_family != AF_INET6)
1984                         continue;
1985                 sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
1986                 if (IN6_IS_SCOPE_LINKLOCAL(&sin6->sin6_addr) ||
1987                     IN6_IS_ADDR_MC_INTFACELOCAL(&sin6->sin6_addr) ||
1988                     IN6_IS_ADDR_MC_NODELOCAL(&sin6->sin6_addr))
1989                         break;
1990         }
1991         if_addr_runlock(ifp);
1992
1993         return ((struct in6_ifaddr *)ifa);
1994 }
1995
1996 /*
1997  * Convert IP6 address to printable (loggable) representation. Caller
1998  * has to make sure that ip6buf is at least INET6_ADDRSTRLEN long.
1999  */
2000 static char digits[] = "0123456789abcdef";
2001 char *
2002 ip6_sprintf(char *ip6buf, const struct in6_addr *addr)
2003 {
2004         int i, cnt = 0, maxcnt = 0, idx = 0, index = 0;
2005         char *cp;
2006         const u_int16_t *a = (const u_int16_t *)addr;
2007         const u_int8_t *d;
2008         int dcolon = 0, zero = 0;
2009
2010         cp = ip6buf;
2011
2012         for (i = 0; i < 8; i++) {
2013                 if (*(a + i) == 0) {
2014                         cnt++;
2015                         if (cnt == 1)
2016                                 idx = i;
2017                 }
2018                 else if (maxcnt < cnt) {
2019                         maxcnt = cnt;
2020                         index = idx;
2021                         cnt = 0;
2022                 }
2023         }
2024         if (maxcnt < cnt) {
2025                 maxcnt = cnt;
2026                 index = idx;
2027         }
2028
2029         for (i = 0; i < 8; i++) {
2030                 if (dcolon == 1) {
2031                         if (*a == 0) {
2032                                 if (i == 7)
2033                                         *cp++ = ':';
2034                                 a++;
2035                                 continue;
2036                         } else
2037                                 dcolon = 2;
2038                 }
2039                 if (*a == 0) {
2040                         if (dcolon == 0 && *(a + 1) == 0 && i == index) {
2041                                 if (i == 0)
2042                                         *cp++ = ':';
2043                                 *cp++ = ':';
2044                                 dcolon = 1;
2045                         } else {
2046                                 *cp++ = '0';
2047                                 *cp++ = ':';
2048                         }
2049                         a++;
2050                         continue;
2051                 }
2052                 d = (const u_char *)a;
2053                 /* Try to eliminate leading zeros in printout like in :0001. */
2054                 zero = 1;
2055                 *cp = digits[*d >> 4];
2056                 if (*cp != '0') {
2057                         zero = 0;
2058                         cp++;
2059                 }
2060                 *cp = digits[*d++ & 0xf];
2061                 if (zero == 0 || (*cp != '0')) {
2062                         zero = 0;
2063                         cp++;
2064                 }
2065                 *cp = digits[*d >> 4];
2066                 if (zero == 0 || (*cp != '0')) {
2067                         zero = 0;
2068                         cp++;
2069                 }
2070                 *cp++ = digits[*d & 0xf];
2071                 *cp++ = ':';
2072                 a++;
2073         }
2074         *--cp = '\0';
2075         return (ip6buf);
2076 }
2077
2078 int
2079 in6_localaddr(struct in6_addr *in6)
2080 {
2081         struct in6_ifaddr *ia;
2082
2083         if (IN6_IS_ADDR_LOOPBACK(in6) || IN6_IS_ADDR_LINKLOCAL(in6))
2084                 return 1;
2085
2086         IN6_IFADDR_RLOCK();
2087         TAILQ_FOREACH(ia, &V_in6_ifaddrhead, ia_link) {
2088                 if (IN6_ARE_MASKED_ADDR_EQUAL(in6, &ia->ia_addr.sin6_addr,
2089                     &ia->ia_prefixmask.sin6_addr)) {
2090                         IN6_IFADDR_RUNLOCK();
2091                         return 1;
2092                 }
2093         }
2094         IN6_IFADDR_RUNLOCK();
2095
2096         return (0);
2097 }
2098
2099 /*
2100  * Return 1 if an internet address is for the local host and configured
2101  * on one of its interfaces.
2102  */
2103 int
2104 in6_localip(struct in6_addr *in6)
2105 {
2106         struct in6_ifaddr *ia;
2107
2108         IN6_IFADDR_RLOCK();
2109         TAILQ_FOREACH(ia, &V_in6_ifaddrhead, ia_link) {
2110                 if (IN6_ARE_ADDR_EQUAL(in6, &ia->ia_addr.sin6_addr)) {
2111                         IN6_IFADDR_RUNLOCK();
2112                         return (1);
2113                 }
2114         }
2115         IN6_IFADDR_RUNLOCK();
2116         return (0);
2117 }
2118
2119
2120 int
2121 in6_is_addr_deprecated(struct sockaddr_in6 *sa6)
2122 {
2123         struct in6_ifaddr *ia;
2124
2125         IN6_IFADDR_RLOCK();
2126         TAILQ_FOREACH(ia, &V_in6_ifaddrhead, ia_link) {
2127                 if (IN6_ARE_ADDR_EQUAL(&ia->ia_addr.sin6_addr,
2128                     &sa6->sin6_addr) &&
2129                     (ia->ia6_flags & IN6_IFF_DEPRECATED) != 0) {
2130                         IN6_IFADDR_RUNLOCK();
2131                         return (1); /* true */
2132                 }
2133
2134                 /* XXX: do we still have to go thru the rest of the list? */
2135         }
2136         IN6_IFADDR_RUNLOCK();
2137
2138         return (0);             /* false */
2139 }
2140
2141 /*
2142  * return length of part which dst and src are equal
2143  * hard coding...
2144  */
2145 int
2146 in6_matchlen(struct in6_addr *src, struct in6_addr *dst)
2147 {
2148         int match = 0;
2149         u_char *s = (u_char *)src, *d = (u_char *)dst;
2150         u_char *lim = s + 16, r;
2151
2152         while (s < lim)
2153                 if ((r = (*d++ ^ *s++)) != 0) {
2154                         while (r < 128) {
2155                                 match++;
2156                                 r <<= 1;
2157                         }
2158                         break;
2159                 } else
2160                         match += 8;
2161         return match;
2162 }
2163
2164 /* XXX: to be scope conscious */
2165 int
2166 in6_are_prefix_equal(struct in6_addr *p1, struct in6_addr *p2, int len)
2167 {
2168         int bytelen, bitlen;
2169
2170         /* sanity check */
2171         if (0 > len || len > 128) {
2172                 log(LOG_ERR, "in6_are_prefix_equal: invalid prefix length(%d)\n",
2173                     len);
2174                 return (0);
2175         }
2176
2177         bytelen = len / 8;
2178         bitlen = len % 8;
2179
2180         if (bcmp(&p1->s6_addr, &p2->s6_addr, bytelen))
2181                 return (0);
2182         if (bitlen != 0 &&
2183             p1->s6_addr[bytelen] >> (8 - bitlen) !=
2184             p2->s6_addr[bytelen] >> (8 - bitlen))
2185                 return (0);
2186
2187         return (1);
2188 }
2189
2190 void
2191 in6_prefixlen2mask(struct in6_addr *maskp, int len)
2192 {
2193         u_char maskarray[8] = {0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff};
2194         int bytelen, bitlen, i;
2195
2196         /* sanity check */
2197         if (0 > len || len > 128) {
2198                 log(LOG_ERR, "in6_prefixlen2mask: invalid prefix length(%d)\n",
2199                     len);
2200                 return;
2201         }
2202
2203         bzero(maskp, sizeof(*maskp));
2204         bytelen = len / 8;
2205         bitlen = len % 8;
2206         for (i = 0; i < bytelen; i++)
2207                 maskp->s6_addr[i] = 0xff;
2208         if (bitlen)
2209                 maskp->s6_addr[bytelen] = maskarray[bitlen - 1];
2210 }
2211
2212 /*
2213  * return the best address out of the same scope. if no address was
2214  * found, return the first valid address from designated IF.
2215  */
2216 struct in6_ifaddr *
2217 in6_ifawithifp(struct ifnet *ifp, struct in6_addr *dst)
2218 {
2219         int dst_scope = in6_addrscope(dst), blen = -1, tlen;
2220         struct ifaddr *ifa;
2221         struct in6_ifaddr *besta = 0;
2222         struct in6_ifaddr *dep[2];      /* last-resort: deprecated */
2223
2224         dep[0] = dep[1] = NULL;
2225
2226         /*
2227          * We first look for addresses in the same scope.
2228          * If there is one, return it.
2229          * If two or more, return one which matches the dst longest.
2230          * If none, return one of global addresses assigned other ifs.
2231          */
2232         IF_ADDR_RLOCK(ifp);
2233         TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
2234                 if (ifa->ifa_addr->sa_family != AF_INET6)
2235                         continue;
2236                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_ANYCAST)
2237                         continue; /* XXX: is there any case to allow anycast? */
2238                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_NOTREADY)
2239                         continue; /* don't use this interface */
2240                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DETACHED)
2241                         continue;
2242                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DEPRECATED) {
2243                         if (V_ip6_use_deprecated)
2244                                 dep[0] = (struct in6_ifaddr *)ifa;
2245                         continue;
2246                 }
2247
2248                 if (dst_scope == in6_addrscope(IFA_IN6(ifa))) {
2249                         /*
2250                          * call in6_matchlen() as few as possible
2251                          */
2252                         if (besta) {
2253                                 if (blen == -1)
2254                                         blen = in6_matchlen(&besta->ia_addr.sin6_addr, dst);
2255                                 tlen = in6_matchlen(IFA_IN6(ifa), dst);
2256                                 if (tlen > blen) {
2257                                         blen = tlen;
2258                                         besta = (struct in6_ifaddr *)ifa;
2259                                 }
2260                         } else
2261                                 besta = (struct in6_ifaddr *)ifa;
2262                 }
2263         }
2264         if (besta) {
2265                 ifa_ref(&besta->ia_ifa);
2266                 IF_ADDR_RUNLOCK(ifp);
2267                 return (besta);
2268         }
2269
2270         TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
2271                 if (ifa->ifa_addr->sa_family != AF_INET6)
2272                         continue;
2273                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_ANYCAST)
2274                         continue; /* XXX: is there any case to allow anycast? */
2275                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_NOTREADY)
2276                         continue; /* don't use this interface */
2277                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DETACHED)
2278                         continue;
2279                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DEPRECATED) {
2280                         if (V_ip6_use_deprecated)
2281                                 dep[1] = (struct in6_ifaddr *)ifa;
2282                         continue;
2283                 }
2284
2285                 if (ifa != NULL)
2286                         ifa_ref(ifa);
2287                 IF_ADDR_RUNLOCK(ifp);
2288                 return (struct in6_ifaddr *)ifa;
2289         }
2290
2291         /* use the last-resort values, that are, deprecated addresses */
2292         if (dep[0]) {
2293                 ifa_ref((struct ifaddr *)dep[0]);
2294                 IF_ADDR_RUNLOCK(ifp);
2295                 return dep[0];
2296         }
2297         if (dep[1]) {
2298                 ifa_ref((struct ifaddr *)dep[1]);
2299                 IF_ADDR_RUNLOCK(ifp);
2300                 return dep[1];
2301         }
2302
2303         IF_ADDR_RUNLOCK(ifp);
2304         return NULL;
2305 }
2306
2307 /*
2308  * perform DAD when interface becomes IFF_UP.
2309  */
2310 void
2311 in6_if_up(struct ifnet *ifp)
2312 {
2313         struct ifaddr *ifa;
2314         struct in6_ifaddr *ia;
2315
2316         IF_ADDR_RLOCK(ifp);
2317         TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
2318                 if (ifa->ifa_addr->sa_family != AF_INET6)
2319                         continue;
2320                 ia = (struct in6_ifaddr *)ifa;
2321                 if (ia->ia6_flags & IN6_IFF_TENTATIVE) {
2322                         /*
2323                          * The TENTATIVE flag was likely set by hand
2324                          * beforehand, implicitly indicating the need for DAD.
2325                          * We may be able to skip the random delay in this
2326                          * case, but we impose delays just in case.
2327                          */
2328                         nd6_dad_start(ifa,
2329                             arc4random() % (MAX_RTR_SOLICITATION_DELAY * hz));
2330                 }
2331         }
2332         IF_ADDR_RUNLOCK(ifp);
2333
2334         /*
2335          * special cases, like 6to4, are handled in in6_ifattach
2336          */
2337         in6_ifattach(ifp, NULL);
2338 }
2339
2340 int
2341 in6if_do_dad(struct ifnet *ifp)
2342 {
2343         if ((ifp->if_flags & IFF_LOOPBACK) != 0)
2344                 return (0);
2345
2346         if (ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED)
2347                 return (0);
2348
2349         switch (ifp->if_type) {
2350 #ifdef IFT_DUMMY
2351         case IFT_DUMMY:
2352 #endif
2353         case IFT_FAITH:
2354                 /*
2355                  * These interfaces do not have the IFF_LOOPBACK flag,
2356                  * but loop packets back.  We do not have to do DAD on such
2357                  * interfaces.  We should even omit it, because loop-backed
2358                  * NS would confuse the DAD procedure.
2359                  */
2360                 return (0);
2361         default:
2362                 /*
2363                  * Our DAD routine requires the interface up and running.
2364                  * However, some interfaces can be up before the RUNNING
2365                  * status.  Additionaly, users may try to assign addresses
2366                  * before the interface becomes up (or running).
2367                  * We simply skip DAD in such a case as a work around.
2368                  * XXX: we should rather mark "tentative" on such addresses,
2369                  * and do DAD after the interface becomes ready.
2370                  */
2371                 if (!((ifp->if_flags & IFF_UP) &&
2372                     (ifp->if_drv_flags & IFF_DRV_RUNNING)))
2373                         return (0);
2374
2375                 return (1);
2376         }
2377 }
2378
2379 /*
2380  * Calculate max IPv6 MTU through all the interfaces and store it
2381  * to in6_maxmtu.
2382  */
2383 void
2384 in6_setmaxmtu(void)
2385 {
2386         unsigned long maxmtu = 0;
2387         struct ifnet *ifp;
2388
2389         IFNET_RLOCK_NOSLEEP();
2390         TAILQ_FOREACH(ifp, &V_ifnet, if_list) {
2391                 /* this function can be called during ifnet initialization */
2392                 if (!ifp->if_afdata[AF_INET6])
2393                         continue;
2394                 if ((ifp->if_flags & IFF_LOOPBACK) == 0 &&
2395                     IN6_LINKMTU(ifp) > maxmtu)
2396                         maxmtu = IN6_LINKMTU(ifp);
2397         }
2398         IFNET_RUNLOCK_NOSLEEP();
2399         if (maxmtu)     /* update only when maxmtu is positive */
2400                 V_in6_maxmtu = maxmtu;
2401 }
2402
2403 /*
2404  * Provide the length of interface identifiers to be used for the link attached
2405  * to the given interface.  The length should be defined in "IPv6 over
2406  * xxx-link" document.  Note that address architecture might also define
2407  * the length for a particular set of address prefixes, regardless of the
2408  * link type.  As clarified in rfc2462bis, those two definitions should be
2409  * consistent, and those really are as of August 2004.
2410  */
2411 int
2412 in6_if2idlen(struct ifnet *ifp)
2413 {
2414         switch (ifp->if_type) {
2415         case IFT_ETHER:         /* RFC2464 */
2416 #ifdef IFT_PROPVIRTUAL
2417         case IFT_PROPVIRTUAL:   /* XXX: no RFC. treat it as ether */
2418 #endif
2419 #ifdef IFT_L2VLAN
2420         case IFT_L2VLAN:        /* ditto */
2421 #endif
2422 #ifdef IFT_IEEE80211
2423         case IFT_IEEE80211:     /* ditto */
2424 #endif
2425 #ifdef IFT_MIP
2426         case IFT_MIP:   /* ditto */
2427 #endif
2428         case IFT_INFINIBAND:
2429                 return (64);
2430         case IFT_FDDI:          /* RFC2467 */
2431                 return (64);
2432         case IFT_ISO88025:      /* RFC2470 (IPv6 over Token Ring) */
2433                 return (64);
2434         case IFT_PPP:           /* RFC2472 */
2435                 return (64);
2436         case IFT_ARCNET:        /* RFC2497 */
2437                 return (64);
2438         case IFT_FRELAY:        /* RFC2590 */
2439                 return (64);
2440         case IFT_IEEE1394:      /* RFC3146 */
2441                 return (64);
2442         case IFT_GIF:
2443                 return (64);    /* draft-ietf-v6ops-mech-v2-07 */
2444         case IFT_LOOP:
2445                 return (64);    /* XXX: is this really correct? */
2446         default:
2447                 /*
2448                  * Unknown link type:
2449                  * It might be controversial to use the today's common constant
2450                  * of 64 for these cases unconditionally.  For full compliance,
2451                  * we should return an error in this case.  On the other hand,
2452                  * if we simply miss the standard for the link type or a new
2453                  * standard is defined for a new link type, the IFID length
2454                  * is very likely to be the common constant.  As a compromise,
2455                  * we always use the constant, but make an explicit notice
2456                  * indicating the "unknown" case.
2457                  */
2458                 printf("in6_if2idlen: unknown link type (%d)\n", ifp->if_type);
2459                 return (64);
2460         }
2461 }
2462
2463 #include <sys/sysctl.h>
2464
2465 struct in6_llentry {
2466         struct llentry          base;
2467         struct sockaddr_in6     l3_addr6;
2468 };
2469
2470 /*
2471  * Deletes an address from the address table.
2472  * This function is called by the timer functions
2473  * such as arptimer() and nd6_llinfo_timer(), and
2474  * the caller does the locking.
2475  */
2476 static void
2477 in6_lltable_free(struct lltable *llt, struct llentry *lle)
2478 {
2479         LLE_WUNLOCK(lle);
2480         LLE_LOCK_DESTROY(lle);
2481         free(lle, M_LLTABLE);
2482 }
2483
2484 static struct llentry *
2485 in6_lltable_new(const struct sockaddr *l3addr, u_int flags)
2486 {
2487         struct in6_llentry *lle;
2488
2489         lle = malloc(sizeof(struct in6_llentry), M_LLTABLE, M_NOWAIT | M_ZERO);
2490         if (lle == NULL)                /* NB: caller generates msg */
2491                 return NULL;
2492
2493         lle->l3_addr6 = *(const struct sockaddr_in6 *)l3addr;
2494         lle->base.lle_refcnt = 1;
2495         lle->base.lle_free = in6_lltable_free;
2496         LLE_LOCK_INIT(&lle->base);
2497         callout_init_rw(&lle->base.ln_timer_ch, &lle->base.lle_lock,
2498             CALLOUT_RETURNUNLOCKED);
2499
2500         return (&lle->base);
2501 }
2502
2503 static void
2504 in6_lltable_prefix_free(struct lltable *llt, const struct sockaddr *prefix,
2505     const struct sockaddr *mask, u_int flags)
2506 {
2507         const struct sockaddr_in6 *pfx = (const struct sockaddr_in6 *)prefix;
2508         const struct sockaddr_in6 *msk = (const struct sockaddr_in6 *)mask;
2509         struct llentry *lle, *next;
2510         int i;
2511
2512         /*
2513          * (flags & LLE_STATIC) means deleting all entries
2514          * including static ND6 entries.
2515          */
2516         IF_AFDATA_WLOCK(llt->llt_ifp);
2517         for (i = 0; i < LLTBL_HASHTBL_SIZE; i++) {
2518                 LIST_FOREACH_SAFE(lle, &llt->lle_head[i], lle_next, next) {
2519                         if (IN6_ARE_MASKED_ADDR_EQUAL(
2520                             &satosin6(L3_ADDR(lle))->sin6_addr,
2521                             &pfx->sin6_addr, &msk->sin6_addr) &&
2522                             ((flags & LLE_STATIC) ||
2523                             !(lle->la_flags & LLE_STATIC))) {
2524                                 LLE_WLOCK(lle);
2525                                 if (callout_stop(&lle->la_timer))
2526                                         LLE_REMREF(lle);
2527                                 llentry_free(lle);
2528                         }
2529                 }
2530         }
2531         IF_AFDATA_WUNLOCK(llt->llt_ifp);
2532 }
2533
2534 static int
2535 in6_lltable_rtcheck(struct ifnet *ifp,
2536                     u_int flags,
2537                     const struct sockaddr *l3addr)
2538 {
2539         struct rtentry *rt;
2540         char ip6buf[INET6_ADDRSTRLEN];
2541
2542         KASSERT(l3addr->sa_family == AF_INET6,
2543             ("sin_family %d", l3addr->sa_family));
2544
2545         /* Our local addresses are always only installed on the default FIB. */
2546         /* XXX rtalloc1 should take a const param */
2547         rt = in6_rtalloc1(__DECONST(struct sockaddr *, l3addr), 0, 0,
2548             RT_DEFAULT_FIB);
2549         if (rt == NULL || (rt->rt_flags & RTF_GATEWAY) || rt->rt_ifp != ifp) {
2550                 struct ifaddr *ifa;
2551                 /*
2552                  * Create an ND6 cache for an IPv6 neighbor
2553                  * that is not covered by our own prefix.
2554                  */
2555                 /* XXX ifaof_ifpforaddr should take a const param */
2556                 ifa = ifaof_ifpforaddr(__DECONST(struct sockaddr *, l3addr), ifp);
2557                 if (ifa != NULL) {
2558                         ifa_free(ifa);
2559                         if (rt != NULL)
2560                                 RTFREE_LOCKED(rt);
2561                         return 0;
2562                 }
2563                 log(LOG_INFO, "IPv6 address: \"%s\" is not on the network\n",
2564                     ip6_sprintf(ip6buf, &((const struct sockaddr_in6 *)l3addr)->sin6_addr));
2565                 if (rt != NULL)
2566                         RTFREE_LOCKED(rt);
2567                 return EINVAL;
2568         }
2569         RTFREE_LOCKED(rt);
2570         return 0;
2571 }
2572
2573 static struct llentry *
2574 in6_lltable_lookup(struct lltable *llt, u_int flags,
2575         const struct sockaddr *l3addr)
2576 {
2577         const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)l3addr;
2578         struct ifnet *ifp = llt->llt_ifp;
2579         struct llentry *lle;
2580         struct llentries *lleh;
2581         u_int hashkey;
2582
2583         IF_AFDATA_LOCK_ASSERT(ifp);
2584         KASSERT(l3addr->sa_family == AF_INET6,
2585             ("sin_family %d", l3addr->sa_family));
2586
2587         hashkey = sin6->sin6_addr.s6_addr32[3];
2588         lleh = &llt->lle_head[LLATBL_HASH(hashkey, LLTBL_HASHMASK)];
2589         LIST_FOREACH(lle, lleh, lle_next) {
2590                 struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)L3_ADDR(lle);
2591                 if (lle->la_flags & LLE_DELETED)
2592                         continue;
2593                 if (bcmp(&sa6->sin6_addr, &sin6->sin6_addr,
2594                     sizeof(struct in6_addr)) == 0)
2595                         break;
2596         }
2597
2598         if (lle == NULL) {
2599                 if (!(flags & LLE_CREATE))
2600                         return (NULL);
2601                 IF_AFDATA_WLOCK_ASSERT(ifp);
2602                 /*
2603                  * A route that covers the given address must have
2604                  * been installed 1st because we are doing a resolution,
2605                  * verify this.
2606                  */
2607                 if (!(flags & LLE_IFADDR) &&
2608                     in6_lltable_rtcheck(ifp, flags, l3addr) != 0)
2609                         return NULL;
2610
2611                 lle = in6_lltable_new(l3addr, flags);
2612                 if (lle == NULL) {
2613                         log(LOG_INFO, "lla_lookup: new lle malloc failed\n");
2614                         return NULL;
2615                 }
2616                 lle->la_flags = flags & ~LLE_CREATE;
2617                 if ((flags & (LLE_CREATE | LLE_IFADDR)) == (LLE_CREATE | LLE_IFADDR)) {
2618                         bcopy(IF_LLADDR(ifp), &lle->ll_addr, ifp->if_addrlen);
2619                         lle->la_flags |= (LLE_VALID | LLE_STATIC);
2620                 }
2621
2622                 lle->lle_tbl  = llt;
2623                 lle->lle_head = lleh;
2624                 lle->la_flags |= LLE_LINKED;
2625                 LIST_INSERT_HEAD(lleh, lle, lle_next);
2626         } else if (flags & LLE_DELETE) {
2627                 if (!(lle->la_flags & LLE_IFADDR) || (flags & LLE_IFADDR)) {
2628                         LLE_WLOCK(lle);
2629                         lle->la_flags |= LLE_DELETED;
2630 #ifdef DIAGNOSTIC
2631                         log(LOG_INFO, "ifaddr cache = %p is deleted\n", lle);
2632 #endif
2633                         if ((lle->la_flags &
2634                             (LLE_STATIC | LLE_IFADDR)) == LLE_STATIC)
2635                                 llentry_free(lle);
2636                         else
2637                                 LLE_WUNLOCK(lle);
2638                 }
2639                 lle = (void *)-1;
2640         }
2641         if (LLE_IS_VALID(lle)) {
2642                 if (flags & LLE_EXCLUSIVE)
2643                         LLE_WLOCK(lle);
2644                 else
2645                         LLE_RLOCK(lle);
2646         }
2647         return (lle);
2648 }
2649
2650 static int
2651 in6_lltable_dump(struct lltable *llt, struct sysctl_req *wr)
2652 {
2653         struct ifnet *ifp = llt->llt_ifp;
2654         struct llentry *lle;
2655         /* XXX stack use */
2656         struct {
2657                 struct rt_msghdr        rtm;
2658                 struct sockaddr_in6     sin6;
2659                 /*
2660                  * ndp.c assumes that sdl is word aligned
2661                  */
2662 #ifdef __LP64__
2663                 uint32_t                pad;
2664 #endif
2665                 struct sockaddr_dl      sdl;
2666         } ndpc;
2667         int i, error;
2668
2669         if (ifp->if_flags & IFF_LOOPBACK)
2670                 return 0;
2671
2672         LLTABLE_LOCK_ASSERT();
2673
2674         error = 0;
2675         for (i = 0; i < LLTBL_HASHTBL_SIZE; i++) {
2676                 LIST_FOREACH(lle, &llt->lle_head[i], lle_next) {
2677                         struct sockaddr_dl *sdl;
2678
2679                         /* skip deleted or invalid entries */
2680                         if ((lle->la_flags & (LLE_DELETED|LLE_VALID)) != LLE_VALID)
2681                                 continue;
2682                         /* Skip if jailed and not a valid IP of the prison. */
2683                         if (prison_if(wr->td->td_ucred, L3_ADDR(lle)) != 0)
2684                                 continue;
2685                         /*
2686                          * produce a msg made of:
2687                          *  struct rt_msghdr;
2688                          *  struct sockaddr_in6 (IPv6)
2689                          *  struct sockaddr_dl;
2690                          */
2691                         bzero(&ndpc, sizeof(ndpc));
2692                         ndpc.rtm.rtm_msglen = sizeof(ndpc);
2693                         ndpc.rtm.rtm_version = RTM_VERSION;
2694                         ndpc.rtm.rtm_type = RTM_GET;
2695                         ndpc.rtm.rtm_flags = RTF_UP;
2696                         ndpc.rtm.rtm_addrs = RTA_DST | RTA_GATEWAY;
2697                         ndpc.sin6.sin6_family = AF_INET6;
2698                         ndpc.sin6.sin6_len = sizeof(ndpc.sin6);
2699                         bcopy(L3_ADDR(lle), &ndpc.sin6, L3_ADDR_LEN(lle));
2700
2701                         /* publish */
2702                         if (lle->la_flags & LLE_PUB)
2703                                 ndpc.rtm.rtm_flags |= RTF_ANNOUNCE;
2704
2705                         sdl = &ndpc.sdl;
2706                         sdl->sdl_family = AF_LINK;
2707                         sdl->sdl_len = sizeof(*sdl);
2708                         sdl->sdl_alen = ifp->if_addrlen;
2709                         sdl->sdl_index = ifp->if_index;
2710                         sdl->sdl_type = ifp->if_type;
2711                         bcopy(&lle->ll_addr, LLADDR(sdl), ifp->if_addrlen);
2712                         ndpc.rtm.rtm_rmx.rmx_expire =
2713                             lle->la_flags & LLE_STATIC ? 0 : lle->la_expire;
2714                         ndpc.rtm.rtm_flags |= (RTF_HOST | RTF_LLDATA);
2715                         if (lle->la_flags & LLE_STATIC)
2716                                 ndpc.rtm.rtm_flags |= RTF_STATIC;
2717                         ndpc.rtm.rtm_index = ifp->if_index;
2718                         error = SYSCTL_OUT(wr, &ndpc, sizeof(ndpc));
2719                         if (error)
2720                                 break;
2721                 }
2722         }
2723         return error;
2724 }
2725
2726 void *
2727 in6_domifattach(struct ifnet *ifp)
2728 {
2729         struct in6_ifextra *ext;
2730
2731         ext = (struct in6_ifextra *)malloc(sizeof(*ext), M_IFADDR, M_WAITOK);
2732         bzero(ext, sizeof(*ext));
2733
2734         ext->in6_ifstat = (struct in6_ifstat *)malloc(sizeof(struct in6_ifstat),
2735             M_IFADDR, M_WAITOK);
2736         bzero(ext->in6_ifstat, sizeof(*ext->in6_ifstat));
2737
2738         ext->icmp6_ifstat =
2739             (struct icmp6_ifstat *)malloc(sizeof(struct icmp6_ifstat),
2740             M_IFADDR, M_WAITOK);
2741         bzero(ext->icmp6_ifstat, sizeof(*ext->icmp6_ifstat));
2742
2743         ext->nd_ifinfo = nd6_ifattach(ifp);
2744         ext->scope6_id = scope6_ifattach(ifp);
2745         ext->lltable = lltable_init(ifp, AF_INET6);
2746         if (ext->lltable != NULL) {
2747                 ext->lltable->llt_prefix_free = in6_lltable_prefix_free;
2748                 ext->lltable->llt_lookup = in6_lltable_lookup;
2749                 ext->lltable->llt_dump = in6_lltable_dump;
2750         }
2751
2752         ext->mld_ifinfo = mld_domifattach(ifp);
2753
2754         return ext;
2755 }
2756
2757 void
2758 in6_domifdetach(struct ifnet *ifp, void *aux)
2759 {
2760         struct in6_ifextra *ext = (struct in6_ifextra *)aux;
2761
2762         mld_domifdetach(ifp);
2763         scope6_ifdetach(ext->scope6_id);
2764         nd6_ifdetach(ext->nd_ifinfo);
2765         lltable_free(ext->lltable);
2766         free(ext->in6_ifstat, M_IFADDR);
2767         free(ext->icmp6_ifstat, M_IFADDR);
2768         free(ext, M_IFADDR);
2769 }
2770
2771 /*
2772  * Convert sockaddr_in6 to sockaddr_in.  Original sockaddr_in6 must be
2773  * v4 mapped addr or v4 compat addr
2774  */
2775 void
2776 in6_sin6_2_sin(struct sockaddr_in *sin, struct sockaddr_in6 *sin6)
2777 {
2778
2779         bzero(sin, sizeof(*sin));
2780         sin->sin_len = sizeof(struct sockaddr_in);
2781         sin->sin_family = AF_INET;
2782         sin->sin_port = sin6->sin6_port;
2783         sin->sin_addr.s_addr = sin6->sin6_addr.s6_addr32[3];
2784 }
2785
2786 /* Convert sockaddr_in to sockaddr_in6 in v4 mapped addr format. */
2787 void
2788 in6_sin_2_v4mapsin6(struct sockaddr_in *sin, struct sockaddr_in6 *sin6)
2789 {
2790         bzero(sin6, sizeof(*sin6));
2791         sin6->sin6_len = sizeof(struct sockaddr_in6);
2792         sin6->sin6_family = AF_INET6;
2793         sin6->sin6_port = sin->sin_port;
2794         sin6->sin6_addr.s6_addr32[0] = 0;
2795         sin6->sin6_addr.s6_addr32[1] = 0;
2796         sin6->sin6_addr.s6_addr32[2] = IPV6_ADDR_INT32_SMP;
2797         sin6->sin6_addr.s6_addr32[3] = sin->sin_addr.s_addr;
2798 }
2799
2800 /* Convert sockaddr_in6 into sockaddr_in. */
2801 void
2802 in6_sin6_2_sin_in_sock(struct sockaddr *nam)
2803 {
2804         struct sockaddr_in *sin_p;
2805         struct sockaddr_in6 sin6;
2806
2807         /*
2808          * Save original sockaddr_in6 addr and convert it
2809          * to sockaddr_in.
2810          */
2811         sin6 = *(struct sockaddr_in6 *)nam;
2812         sin_p = (struct sockaddr_in *)nam;
2813         in6_sin6_2_sin(sin_p, &sin6);
2814 }
2815
2816 /* Convert sockaddr_in into sockaddr_in6 in v4 mapped addr format. */
2817 void
2818 in6_sin_2_v4mapsin6_in_sock(struct sockaddr **nam)
2819 {
2820         struct sockaddr_in *sin_p;
2821         struct sockaddr_in6 *sin6_p;
2822
2823         sin6_p = malloc(sizeof *sin6_p, M_SONAME, M_WAITOK);
2824         sin_p = (struct sockaddr_in *)*nam;
2825         in6_sin_2_v4mapsin6(sin_p, sin6_p);
2826         free(*nam, M_SONAME);
2827         *nam = (struct sockaddr *)sin6_p;
2828 }