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