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