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