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