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