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