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