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