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