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