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