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