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