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