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