Merge from vendor branch GROFF:
[dragonfly.git] / sys / netinet6 / in6.c
1 /*      $FreeBSD: src/sys/netinet6/in6.c,v 1.7.2.9 2002/04/28 05:40:26 suz Exp $        */
2 /*      $DragonFly: src/sys/netinet6/in6.c,v 1.15 2005/07/26 20:48:41 dillon Exp $      */
3 /*      $KAME: in6.c,v 1.259 2002/01/21 11:37:50 keiichi Exp $  */
4
5 /*
6  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the project nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 /*
35  * Copyright (c) 1982, 1986, 1991, 1993
36  *      The Regents of the University of California.  All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. All advertising materials mentioning features or use of this software
47  *    must display the following acknowledgement:
48  *      This product includes software developed by the University of
49  *      California, Berkeley and its contributors.
50  * 4. Neither the name of the University nor the names of its contributors
51  *    may be used to endorse or promote products derived from this software
52  *    without specific prior written permission.
53  *
54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64  * SUCH DAMAGE.
65  *
66  *      @(#)in.c        8.2 (Berkeley) 11/15/93
67  */
68
69 #include "opt_inet.h"
70 #include "opt_inet6.h"
71
72 #include <sys/param.h>
73 #include <sys/errno.h>
74 #include <sys/malloc.h>
75 #include <sys/socket.h>
76 #include <sys/socketvar.h>
77 #include <sys/sockio.h>
78 #include <sys/systm.h>
79 #include <sys/proc.h>
80 #include <sys/time.h>
81 #include <sys/kernel.h>
82 #include <sys/syslog.h>
83 #include <sys/thread2.h>
84
85 #include <net/if.h>
86 #include <net/if_types.h>
87 #include <net/route.h>
88 #include <net/if_dl.h>
89
90 #include <netinet/in.h>
91 #include <netinet/in_var.h>
92 #include <netinet/if_ether.h>
93 #include <netinet/in_systm.h>
94 #include <netinet/ip.h>
95 #include <netinet/in_pcb.h>
96
97 #include <netinet/ip6.h>
98 #include <netinet6/ip6_var.h>
99 #include <netinet6/nd6.h>
100 #include <netinet6/mld6_var.h>
101 #include <netinet6/ip6_mroute.h>
102 #include <netinet6/in6_ifattach.h>
103 #include <netinet6/scope6_var.h>
104 #include <netinet6/in6_pcb.h>
105
106 #include <net/net_osdep.h>
107
108 MALLOC_DEFINE(M_IPMADDR, "in6_multi", "internet multicast address");
109
110 /*
111  * Definitions of some costant IP6 addresses.
112  */
113 const struct in6_addr in6addr_any = IN6ADDR_ANY_INIT;
114 const struct in6_addr in6addr_loopback = IN6ADDR_LOOPBACK_INIT;
115 const struct in6_addr in6addr_nodelocal_allnodes =
116         IN6ADDR_NODELOCAL_ALLNODES_INIT;
117 const struct in6_addr in6addr_linklocal_allnodes =
118         IN6ADDR_LINKLOCAL_ALLNODES_INIT;
119 const struct in6_addr in6addr_linklocal_allrouters =
120         IN6ADDR_LINKLOCAL_ALLROUTERS_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 = {sizeof(sa6_any), AF_INET6,
129                                      0, 0, IN6ADDR_ANY_INIT, 0};
130
131 static int in6_lifaddr_ioctl (struct socket *, u_long, caddr_t,
132         struct ifnet *, struct thread *);
133 static int in6_ifinit (struct ifnet *, struct in6_ifaddr *,
134                            struct sockaddr_in6 *, int);
135 static void in6_unlink_ifa (struct in6_ifaddr *, struct ifnet *);
136
137 struct in6_multihead in6_multihead;     /* XXX BSS initialization */
138
139 int     (*faithprefix_p)(struct in6_addr *);
140
141 /*
142  * Subroutine for in6_ifaddloop() and in6_ifremloop().
143  * This routine does actual work.
144  */
145 static void
146 in6_ifloop_request(int cmd, struct ifaddr *ifa)
147 {
148         struct sockaddr_in6 all1_sa;
149         struct rtentry *nrt = NULL;
150         int e;
151         
152         bzero(&all1_sa, sizeof(all1_sa));
153         all1_sa.sin6_family = AF_INET6;
154         all1_sa.sin6_len = sizeof(struct sockaddr_in6);
155         all1_sa.sin6_addr = in6mask128;
156
157         /*
158          * We specify the address itself as the gateway, and set the
159          * RTF_LLINFO flag, so that the corresponding host route would have
160          * the flag, and thus applications that assume traditional behavior
161          * would be happy.  Note that we assume the caller of the function
162          * (probably implicitly) set nd6_rtrequest() to ifa->ifa_rtrequest,
163          * which changes the outgoing interface to the loopback interface.
164          */
165         e = rtrequest(cmd, ifa->ifa_addr, ifa->ifa_addr,
166                       (struct sockaddr *)&all1_sa,
167                       RTF_UP|RTF_HOST|RTF_LLINFO, &nrt);
168         if (e != 0) {
169                 log(LOG_ERR, "in6_ifloop_request: "
170                     "%s operation failed for %s (errno=%d)\n",
171                     cmd == RTM_ADD ? "ADD" : "DELETE",
172                     ip6_sprintf(&((struct in6_ifaddr *)ifa)->ia_addr.sin6_addr),
173                     e);
174         }
175
176         /*
177          * Make sure rt_ifa be equal to IFA, the second argument of the
178          * function.
179          * We need this because when we refer to rt_ifa->ia6_flags in
180          * ip6_input, we assume that the rt_ifa points to the address instead
181          * of the loopback address.
182          */
183         if (cmd == RTM_ADD && nrt && ifa != nrt->rt_ifa) {
184                 IFAFREE(nrt->rt_ifa);
185                 IFAREF(ifa);
186                 nrt->rt_ifa = ifa;
187         }
188
189         /*
190          * Report the addition/removal of the address to the routing socket.
191          * XXX: since we called rtinit for a p2p interface with a destination,
192          *      we end up reporting twice in such a case.  Should we rather
193          *      omit the second report?
194          */
195         if (nrt) {
196                 rt_newaddrmsg(cmd, ifa, e, nrt);
197                 if (cmd == RTM_DELETE) {
198                         if (nrt->rt_refcnt <= 0) {
199                                 /* XXX: we should free the entry ourselves. */
200                                 nrt->rt_refcnt++;
201                                 rtfree(nrt);
202                         }
203                 } else {
204                         /* the cmd must be RTM_ADD here */
205                         nrt->rt_refcnt--;
206                 }
207         }
208 }
209
210 /*
211  * Add ownaddr as loopback rtentry.  We previously add the route only if
212  * necessary (ex. on a p2p link).  However, since we now manage addresses
213  * separately from prefixes, we should always add the route.  We can't
214  * rely on the cloning mechanism from the corresponding interface route
215  * any more.
216  */
217 static void
218 in6_ifaddloop(struct ifaddr *ifa)
219 {
220         struct rtentry *rt;
221
222         /* If there is no loopback entry, allocate one. */
223         rt = rtpurelookup(ifa->ifa_addr);
224         if (rt == NULL || !(rt->rt_flags & RTF_HOST) ||
225             !(rt->rt_ifp->if_flags & IFF_LOOPBACK))
226                 in6_ifloop_request(RTM_ADD, ifa);
227         if (rt != NULL)
228                 rt->rt_refcnt--;
229 }
230
231 /*
232  * Remove loopback rtentry of ownaddr generated by in6_ifaddloop(),
233  * if it exists.
234  */
235 static void
236 in6_ifremloop(struct ifaddr *ifa)
237 {
238         struct in6_ifaddr *ia;
239         struct rtentry *rt;
240         int ia_count = 0;
241
242         /*
243          * Some of BSD variants do not remove cloned routes
244          * from an interface direct route, when removing the direct route
245          * (see comments in net/net_osdep.h).  Even for variants that do remove
246          * cloned routes, they could fail to remove the cloned routes when
247          * we handle multple addresses that share a common prefix.
248          * So, we should remove the route corresponding to the deleted address
249          * regardless of the result of in6_is_ifloop_auto().
250          */
251
252         /*
253          * Delete the entry only if exact one ifa exists.  More than one ifa
254          * can exist if we assign a same single address to multiple
255          * (probably p2p) interfaces.
256          * XXX: we should avoid such a configuration in IPv6...
257          */
258         for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
259                 if (IN6_ARE_ADDR_EQUAL(IFA_IN6(ifa), &ia->ia_addr.sin6_addr)) {
260                         ia_count++;
261                         if (ia_count > 1)
262                                 break;
263                 }
264         }
265
266         if (ia_count == 1) {
267                 /*
268                  * Before deleting, check if a corresponding loopbacked host
269                  * route surely exists.  With this check, we can avoid to
270                  * delete an interface direct route whose destination is same
271                  * as the address being removed.  This can happen when remofing
272                  * a subnet-router anycast address on an interface attahced
273                  * to a shared medium.
274                  */
275                 rt = rtpurelookup(ifa->ifa_addr);
276                 if (rt != NULL && (rt->rt_flags & RTF_HOST) &&
277                     (rt->rt_ifp->if_flags & IFF_LOOPBACK)) {
278                         rt->rt_refcnt--;
279                         in6_ifloop_request(RTM_DELETE, ifa);
280                 }
281         }
282 }
283
284 int
285 in6_ifindex2scopeid(int idx)
286 {
287         struct ifnet *ifp;
288         struct ifaddr *ifa;
289         struct sockaddr_in6 *sin6;
290
291         if (idx < 0 || if_index < idx)
292                 return -1;
293         ifp = ifindex2ifnet[idx];
294
295         TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list)
296         {
297                 if (ifa->ifa_addr->sa_family != AF_INET6)
298                         continue;
299                 sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
300                 if (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr))
301                         return sin6->sin6_scope_id & 0xffff;
302         }
303
304         return -1;
305 }
306
307 int
308 in6_mask2len(struct in6_addr *mask, u_char *lim0)
309 {
310         int x = 0, y;
311         u_char *lim = lim0, *p;
312
313         if (lim0 == NULL ||
314             lim0 - (u_char *)mask > sizeof(*mask)) /* ignore the scope_id part */
315                 lim = (u_char *)mask + sizeof(*mask);
316         for (p = (u_char *)mask; p < lim; x++, p++) {
317                 if (*p != 0xff)
318                         break;
319         }
320         y = 0;
321         if (p < lim) {
322                 for (y = 0; y < 8; y++) {
323                         if ((*p & (0x80 >> y)) == 0)
324                                 break;
325                 }
326         }
327
328         /*
329          * when the limit pointer is given, do a stricter check on the
330          * remaining bits.
331          */
332         if (p < lim) {
333                 if (y != 0 && (*p & (0x00ff >> y)) != 0)
334                         return(-1);
335                 for (p = p + 1; p < lim; p++)
336                         if (*p != 0)
337                                 return(-1);
338         }
339         
340         return x * 8 + y;
341 }
342
343 void
344 in6_len2mask(struct in6_addr *mask, int len)
345 {
346         int i;
347
348         bzero(mask, sizeof(*mask));
349         for (i = 0; i < len / 8; i++)
350                 mask->s6_addr8[i] = 0xff;
351         if (len % 8)
352                 mask->s6_addr8[i] = (0xff00 >> (len % 8)) & 0xff;
353 }
354
355 #define ifa2ia6(ifa)    ((struct in6_ifaddr *)(ifa))
356 #define ia62ifa(ia6)    (&((ia6)->ia_ifa))
357
358 int
359 in6_control(struct socket *so, u_long cmd, caddr_t data,
360             struct ifnet *ifp, struct thread *td)
361 {
362         struct  in6_ifreq *ifr = (struct in6_ifreq *)data;
363         struct  in6_ifaddr *ia = NULL;
364         struct  in6_aliasreq *ifra = (struct in6_aliasreq *)data;
365         int privileged;
366
367         privileged = 0;
368         if (suser(td) == 0)
369                 privileged++;
370
371         switch (cmd) {
372         case SIOCGETSGCNT_IN6:
373         case SIOCGETMIFCNT_IN6:
374                 return (mrt6_ioctl(cmd, data));
375         }
376
377         if (ifp == NULL)
378                 return(EOPNOTSUPP);
379
380         switch (cmd) {
381         case SIOCSNDFLUSH_IN6:
382         case SIOCSPFXFLUSH_IN6:
383         case SIOCSRTRFLUSH_IN6:
384         case SIOCSDEFIFACE_IN6:
385         case SIOCSIFINFO_FLAGS:
386                 if (!privileged)
387                         return(EPERM);
388                 /* fall through */
389         case OSIOCGIFINFO_IN6:
390         case SIOCGIFINFO_IN6:
391         case SIOCGDRLST_IN6:
392         case SIOCGPRLST_IN6:
393         case SIOCGNBRINFO_IN6:
394         case SIOCGDEFIFACE_IN6:
395                 return(nd6_ioctl(cmd, data, ifp));
396         }
397
398         switch (cmd) {
399         case SIOCSIFPREFIX_IN6:
400         case SIOCDIFPREFIX_IN6:
401         case SIOCAIFPREFIX_IN6:
402         case SIOCCIFPREFIX_IN6:
403         case SIOCSGIFPREFIX_IN6:
404         case SIOCGIFPREFIX_IN6:
405                 log(LOG_NOTICE,
406                     "prefix ioctls are now invalidated. "
407                     "please use ifconfig.\n");
408                 return(EOPNOTSUPP);
409         }
410
411         switch (cmd) {
412         case SIOCSSCOPE6:
413                 if (!privileged)
414                         return(EPERM);
415                 return(scope6_set(ifp,
416                         (struct scope6_id *)ifr->ifr_ifru.ifru_scope_id));
417                 break;
418         case SIOCGSCOPE6:
419                 return(scope6_get(ifp,
420                         (struct scope6_id *)ifr->ifr_ifru.ifru_scope_id));
421                 break;
422         case SIOCGSCOPE6DEF:
423                 return(scope6_get_default((struct scope6_id *)
424                         ifr->ifr_ifru.ifru_scope_id));
425                 break;
426         }
427
428         switch (cmd) {
429         case SIOCALIFADDR:
430         case SIOCDLIFADDR:
431                 if (!privileged)
432                         return(EPERM);
433                 /* fall through */
434         case SIOCGLIFADDR:
435                 return in6_lifaddr_ioctl(so, cmd, data, ifp, td);
436         }
437
438         /*
439          * Find address for this interface, if it exists.
440          */
441         if (ifra->ifra_addr.sin6_family == AF_INET6) { /* XXX */
442                 struct sockaddr_in6 *sa6 =
443                         (struct sockaddr_in6 *)&ifra->ifra_addr;
444
445                 if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr)) {
446                         if (sa6->sin6_addr.s6_addr16[1] == 0) {
447                                 /* link ID is not embedded by the user */
448                                 sa6->sin6_addr.s6_addr16[1] =
449                                         htons(ifp->if_index);
450                         } else if (sa6->sin6_addr.s6_addr16[1] !=
451                                     htons(ifp->if_index)) {
452                                 return(EINVAL); /* link ID contradicts */
453                         }
454                         if (sa6->sin6_scope_id) {
455                                 if (sa6->sin6_scope_id !=
456                                     (u_int32_t)ifp->if_index)
457                                         return(EINVAL);
458                                 sa6->sin6_scope_id = 0; /* XXX: good way? */
459                         }
460                 }
461                 ia = in6ifa_ifpwithaddr(ifp, &ifra->ifra_addr.sin6_addr);
462         }
463
464         switch (cmd) {
465         case SIOCSIFADDR_IN6:
466         case SIOCSIFDSTADDR_IN6:
467         case SIOCSIFNETMASK_IN6:
468                 /*
469                  * Since IPv6 allows a node to assign multiple addresses
470                  * on a single interface, SIOCSIFxxx ioctls are not suitable
471                  * and should be unused.
472                  */
473                 /* we decided to obsolete this command (20000704) */
474                 return(EINVAL);
475
476         case SIOCDIFADDR_IN6:
477                 /*
478                  * for IPv4, we look for existing in_ifaddr here to allow
479                  * "ifconfig if0 delete" to remove first IPv4 address on the
480                  * interface.  For IPv6, as the spec allow multiple interface
481                  * address from the day one, we consider "remove the first one"
482                  * semantics to be not preferable.
483                  */
484                 if (ia == NULL)
485                         return(EADDRNOTAVAIL);
486                 /* FALLTHROUGH */
487         case SIOCAIFADDR_IN6:
488                 /*
489                  * We always require users to specify a valid IPv6 address for
490                  * the corresponding operation.
491                  */
492                 if (ifra->ifra_addr.sin6_family != AF_INET6 ||
493                     ifra->ifra_addr.sin6_len != sizeof(struct sockaddr_in6))
494                         return(EAFNOSUPPORT);
495                 if (!privileged)
496                         return(EPERM);
497
498                 break;
499
500         case SIOCGIFADDR_IN6:
501                 /* This interface is basically deprecated. use SIOCGIFCONF. */
502                 /* fall through */
503         case SIOCGIFAFLAG_IN6:
504         case SIOCGIFNETMASK_IN6:
505         case SIOCGIFDSTADDR_IN6:
506         case SIOCGIFALIFETIME_IN6:
507                 /* must think again about its semantics */
508                 if (ia == NULL)
509                         return(EADDRNOTAVAIL);
510                 break;
511         case SIOCSIFALIFETIME_IN6:
512             {
513                 struct in6_addrlifetime *lt;
514
515                 if (!privileged)
516                         return(EPERM);
517                 if (ia == NULL)
518                         return(EADDRNOTAVAIL);
519                 /* sanity for overflow - beware unsigned */
520                 lt = &ifr->ifr_ifru.ifru_lifetime;
521                 if (lt->ia6t_vltime != ND6_INFINITE_LIFETIME
522                  && lt->ia6t_vltime + time_second < time_second) {
523                         return EINVAL;
524                 }
525                 if (lt->ia6t_pltime != ND6_INFINITE_LIFETIME
526                  && lt->ia6t_pltime + time_second < time_second) {
527                         return EINVAL;
528                 }
529                 break;
530             }
531         }
532
533         switch (cmd) {
534
535         case SIOCGIFADDR_IN6:
536                 ifr->ifr_addr = ia->ia_addr;
537                 break;
538
539         case SIOCGIFDSTADDR_IN6:
540                 if ((ifp->if_flags & IFF_POINTOPOINT) == 0)
541                         return(EINVAL);
542                 /*
543                  * XXX: should we check if ifa_dstaddr is NULL and return
544                  * an error?
545                  */
546                 ifr->ifr_dstaddr = ia->ia_dstaddr;
547                 break;
548
549         case SIOCGIFNETMASK_IN6:
550                 ifr->ifr_addr = ia->ia_prefixmask;
551                 break;
552
553         case SIOCGIFAFLAG_IN6:
554                 ifr->ifr_ifru.ifru_flags6 = ia->ia6_flags;
555                 break;
556
557         case SIOCGIFSTAT_IN6:
558                 if (ifp == NULL)
559                         return EINVAL;
560                 bzero(&ifr->ifr_ifru.ifru_stat,
561                         sizeof(ifr->ifr_ifru.ifru_stat));
562                 ifr->ifr_ifru.ifru_stat =
563                         *((struct in6_ifextra *)ifp->if_afdata[AF_INET6])->in6_ifstat;
564                 break;
565
566         case SIOCGIFSTAT_ICMP6:
567                 bzero(&ifr->ifr_ifru.ifru_stat,
568                         sizeof(ifr->ifr_ifru.ifru_icmp6stat));
569                 ifr->ifr_ifru.ifru_icmp6stat =
570                         *((struct in6_ifextra *)ifp->if_afdata[AF_INET6])->icmp6_ifstat;
571                 break;
572
573         case SIOCGIFALIFETIME_IN6:
574                 ifr->ifr_ifru.ifru_lifetime = ia->ia6_lifetime;
575                 break;
576
577         case SIOCSIFALIFETIME_IN6:
578                 ia->ia6_lifetime = ifr->ifr_ifru.ifru_lifetime;
579                 /* for sanity */
580                 if (ia->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
581                         ia->ia6_lifetime.ia6t_expire =
582                                 time_second + ia->ia6_lifetime.ia6t_vltime;
583                 } else
584                         ia->ia6_lifetime.ia6t_expire = 0;
585                 if (ia->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
586                         ia->ia6_lifetime.ia6t_preferred =
587                                 time_second + ia->ia6_lifetime.ia6t_pltime;
588                 } else
589                         ia->ia6_lifetime.ia6t_preferred = 0;
590                 break;
591
592         case SIOCAIFADDR_IN6:
593         {
594                 int i, error = 0;
595                 struct nd_prefix pr0, *pr;
596
597                 /*
598                  * first, make or update the interface address structure,
599                  * and link it to the list.
600                  */
601                 if ((error = in6_update_ifa(ifp, ifra, ia)) != 0)
602                         return(error);
603
604                 /*
605                  * then, make the prefix on-link on the interface.
606                  * XXX: we'd rather create the prefix before the address, but
607                  * we need at least one address to install the corresponding
608                  * interface route, so we configure the address first.
609                  */
610
611                 /*
612                  * convert mask to prefix length (prefixmask has already
613                  * been validated in in6_update_ifa().
614                  */
615                 bzero(&pr0, sizeof(pr0));
616                 pr0.ndpr_ifp = ifp;
617                 pr0.ndpr_plen = in6_mask2len(&ifra->ifra_prefixmask.sin6_addr,
618                                              NULL);
619                 if (pr0.ndpr_plen == 128)
620                         break;  /* we don't need to install a host route. */
621                 pr0.ndpr_prefix = ifra->ifra_addr;
622                 pr0.ndpr_mask = ifra->ifra_prefixmask.sin6_addr;
623                 /* apply the mask for safety. */
624                 for (i = 0; i < 4; i++) {
625                         pr0.ndpr_prefix.sin6_addr.s6_addr32[i] &=
626                                 ifra->ifra_prefixmask.sin6_addr.s6_addr32[i];
627                 }
628                 /*
629                  * XXX: since we don't have an API to set prefix (not address)
630                  * lifetimes, we just use the same lifetimes as addresses.
631                  * The (temporarily) installed lifetimes can be overridden by
632                  * later advertised RAs (when accept_rtadv is non 0), which is
633                  * an intended behavior.
634                  */
635                 pr0.ndpr_raf_onlink = 1; /* should be configurable? */
636                 pr0.ndpr_raf_auto =
637                         ((ifra->ifra_flags & IN6_IFF_AUTOCONF) != 0);
638                 pr0.ndpr_vltime = ifra->ifra_lifetime.ia6t_vltime;
639                 pr0.ndpr_pltime = ifra->ifra_lifetime.ia6t_pltime;
640
641                 /* add the prefix if there's one. */
642                 if ((pr = nd6_prefix_lookup(&pr0)) == NULL) {
643                         /*
644                          * nd6_prelist_add will install the corresponding
645                          * interface route.
646                          */
647                         if ((error = nd6_prelist_add(&pr0, NULL, &pr)) != 0)
648                                 return(error);
649                         if (pr == NULL) {
650                                 log(LOG_ERR, "nd6_prelist_add succedded but "
651                                     "no prefix\n");
652                                 return(EINVAL); /* XXX panic here? */
653                         }
654                 }
655                 if ((ia = in6ifa_ifpwithaddr(ifp, &ifra->ifra_addr.sin6_addr))
656                     == NULL) {
657                         /* XXX: this should not happen! */
658                         log(LOG_ERR, "in6_control: addition succeeded, but"
659                             " no ifaddr\n");
660                 } else {
661                         if ((ia->ia6_flags & IN6_IFF_AUTOCONF) != 0 &&
662                             ia->ia6_ndpr == NULL) { /* new autoconfed addr */
663                                 ia->ia6_ndpr = pr;
664                                 pr->ndpr_refcnt++;
665
666                                 /*
667                                  * If this is the first autoconf address from
668                                  * the prefix, create a temporary address
669                                  * as well (when specified).
670                                  */
671                                 if (ip6_use_tempaddr &&
672                                     pr->ndpr_refcnt == 1) {
673                                         int e;
674                                         if ((e = in6_tmpifadd(ia, 1)) != 0) {
675                                                 log(LOG_NOTICE, "in6_control: "
676                                                     "failed to create a "
677                                                     "temporary address, "
678                                                     "errno=%d\n",
679                                                     e);
680                                         }
681                                 }
682                         }
683
684                         /*
685                          * this might affect the status of autoconfigured
686                          * addresses, that is, this address might make
687                          * other addresses detached.
688                          */
689                         pfxlist_onlink_check();
690                 }
691                 if (error == 0 && ia)
692                         EVENTHANDLER_INVOKE(ifaddr_event, ifp);
693                 break;
694         }
695
696         case SIOCDIFADDR_IN6:
697         {
698                 int i = 0;
699                 struct nd_prefix pr0, *pr;
700
701                 /*
702                  * If the address being deleted is the only one that owns
703                  * the corresponding prefix, expire the prefix as well.
704                  * XXX: theoretically, we don't have to warry about such
705                  * relationship, since we separate the address management
706                  * and the prefix management.  We do this, however, to provide
707                  * as much backward compatibility as possible in terms of
708                  * the ioctl operation.
709                  */
710                 bzero(&pr0, sizeof(pr0));
711                 pr0.ndpr_ifp = ifp;
712                 pr0.ndpr_plen = in6_mask2len(&ia->ia_prefixmask.sin6_addr,
713                                              NULL);
714                 if (pr0.ndpr_plen == 128)
715                         goto purgeaddr;
716                 pr0.ndpr_prefix = ia->ia_addr;
717                 pr0.ndpr_mask = ia->ia_prefixmask.sin6_addr;
718                 for (i = 0; i < 4; i++) {
719                         pr0.ndpr_prefix.sin6_addr.s6_addr32[i] &=
720                                 ia->ia_prefixmask.sin6_addr.s6_addr32[i];
721                 }
722                 /*
723                  * The logic of the following condition is a bit complicated.
724                  * We expire the prefix when
725                  * 1. the address obeys autoconfiguration and it is the
726                  *    only owner of the associated prefix, or
727                  * 2. the address does not obey autoconf and there is no
728                  *    other owner of the prefix.
729                  */
730                 if ((pr = nd6_prefix_lookup(&pr0)) != NULL &&
731                     (((ia->ia6_flags & IN6_IFF_AUTOCONF) != 0 &&
732                       pr->ndpr_refcnt == 1) ||
733                      ((ia->ia6_flags & IN6_IFF_AUTOCONF) == 0 &&
734                       pr->ndpr_refcnt == 0))) {
735                         pr->ndpr_expire = 1; /* XXX: just for expiration */
736                 }
737
738           purgeaddr:
739                 in6_purgeaddr(&ia->ia_ifa);
740                 EVENTHANDLER_INVOKE(ifaddr_event, ifp);
741                 break;
742         }
743
744         default:
745                 if (ifp == NULL || ifp->if_ioctl == 0)
746                         return(EOPNOTSUPP);
747                 return((*ifp->if_ioctl)(ifp, cmd, data, td->td_proc->p_ucred));
748         }
749
750         return(0);
751 }
752
753 /*
754  * Update parameters of an IPv6 interface address.
755  * If necessary, a new entry is created and linked into address chains.
756  * This function is separated from in6_control().
757  * XXX: should this be performed under splnet()?
758  */
759 int
760 in6_update_ifa(struct ifnet *ifp, struct in6_aliasreq *ifra,
761                struct in6_ifaddr *ia)
762 {
763         int error = 0, hostIsNew = 0, plen = -1;
764         struct in6_ifaddr *oia;
765         struct sockaddr_in6 dst6;
766         struct in6_addrlifetime *lt;
767
768         /* Validate parameters */
769         if (ifp == NULL || ifra == NULL) /* this maybe redundant */
770                 return(EINVAL);
771
772         /*
773          * The destination address for a p2p link must have a family
774          * of AF_UNSPEC or AF_INET6.
775          */
776         if ((ifp->if_flags & IFF_POINTOPOINT) != 0 &&
777             ifra->ifra_dstaddr.sin6_family != AF_INET6 &&
778             ifra->ifra_dstaddr.sin6_family != AF_UNSPEC)
779                 return(EAFNOSUPPORT);
780         /*
781          * validate ifra_prefixmask.  don't check sin6_family, netmask
782          * does not carry fields other than sin6_len.
783          */
784         if (ifra->ifra_prefixmask.sin6_len > sizeof(struct sockaddr_in6))
785                 return(EINVAL);
786         /*
787          * Because the IPv6 address architecture is classless, we require
788          * users to specify a (non 0) prefix length (mask) for a new address.
789          * We also require the prefix (when specified) mask is valid, and thus
790          * reject a non-consecutive mask.
791          */
792         if (ia == NULL && ifra->ifra_prefixmask.sin6_len == 0)
793                 return(EINVAL);
794         if (ifra->ifra_prefixmask.sin6_len != 0) {
795                 plen = in6_mask2len(&ifra->ifra_prefixmask.sin6_addr,
796                                     (u_char *)&ifra->ifra_prefixmask +
797                                     ifra->ifra_prefixmask.sin6_len);
798                 if (plen <= 0)
799                         return(EINVAL);
800         }
801         else {
802                 /*
803                  * In this case, ia must not be NULL.  We just use its prefix
804                  * length.
805                  */
806                 plen = in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL);
807         }
808         /*
809          * If the destination address on a p2p interface is specified,
810          * and the address is a scoped one, validate/set the scope
811          * zone identifier.
812          */
813         dst6 = ifra->ifra_dstaddr;
814         if ((ifp->if_flags & (IFF_POINTOPOINT|IFF_LOOPBACK)) &&
815             (dst6.sin6_family == AF_INET6)) {
816                 int scopeid;
817
818                 if ((error = in6_recoverscope(&dst6,
819                                               &ifra->ifra_dstaddr.sin6_addr,
820                                               ifp)) != 0)
821                         return(error);
822                 scopeid = in6_addr2scopeid(ifp, &dst6.sin6_addr);
823                 if (dst6.sin6_scope_id == 0) /* user omit to specify the ID. */
824                         dst6.sin6_scope_id = scopeid;
825                 else if (dst6.sin6_scope_id != scopeid)
826                         return(EINVAL); /* scope ID mismatch. */
827                 if ((error = in6_embedscope(&dst6.sin6_addr, &dst6, NULL, NULL))
828                     != 0)
829                         return(error);
830                 dst6.sin6_scope_id = 0; /* XXX */
831         }
832         /*
833          * The destination address can be specified only for a p2p or a
834          * loopback interface.  If specified, the corresponding prefix length
835          * must be 128.
836          */
837         if (ifra->ifra_dstaddr.sin6_family == AF_INET6) {
838                 if ((ifp->if_flags & (IFF_POINTOPOINT|IFF_LOOPBACK)) == 0) {
839                         /* XXX: noisy message */
840                         log(LOG_INFO, "in6_update_ifa: a destination can be "
841                             "specified for a p2p or a loopback IF only\n");
842                         return(EINVAL);
843                 }
844                 if (plen != 128) {
845                         /*
846                          * The following message seems noisy, but we dare to
847                          * add it for diagnosis.
848                          */
849                         log(LOG_INFO, "in6_update_ifa: prefixlen must be 128 "
850                             "when dstaddr is specified\n");
851                         return(EINVAL);
852                 }
853         }
854         /* lifetime consistency check */
855         lt = &ifra->ifra_lifetime;
856         if (lt->ia6t_vltime != ND6_INFINITE_LIFETIME
857             && lt->ia6t_vltime + time_second < time_second) {
858                 return EINVAL;
859         }
860         if (lt->ia6t_vltime == 0) {
861                 /*
862                  * the following log might be noisy, but this is a typical
863                  * configuration mistake or a tool's bug.
864                  */
865                 log(LOG_INFO,
866                     "in6_update_ifa: valid lifetime is 0 for %s\n",
867                     ip6_sprintf(&ifra->ifra_addr.sin6_addr));
868         }
869         if (lt->ia6t_pltime != ND6_INFINITE_LIFETIME
870             && lt->ia6t_pltime + time_second < time_second) {
871                 return EINVAL;
872         }
873
874         /*
875          * If this is a new address, allocate a new ifaddr and link it
876          * into chains.
877          */
878         if (ia == NULL) {
879                 hostIsNew = 1;
880                 /*
881                  * When in6_update_ifa() is called in a process of a received
882                  * RA, it is called under splnet().  So, we should call malloc
883                  * with M_NOWAIT.
884                  */
885                 ia = (struct in6_ifaddr *)
886                         malloc(sizeof(*ia), M_IFADDR, M_NOWAIT);
887                 if (ia == NULL)
888                         return (ENOBUFS);
889                 bzero((caddr_t)ia, sizeof(*ia));
890                 /* Initialize the address and masks */
891                 ia->ia_ifa.ifa_addr = (struct sockaddr *)&ia->ia_addr;
892                 ia->ia_addr.sin6_family = AF_INET6;
893                 ia->ia_addr.sin6_len = sizeof(ia->ia_addr);
894                 if ((ifp->if_flags & (IFF_POINTOPOINT | IFF_LOOPBACK)) != 0) {
895                         /*
896                          * XXX: some functions expect that ifa_dstaddr is not
897                          * NULL for p2p interfaces.
898                          */
899                         ia->ia_ifa.ifa_dstaddr
900                                 = (struct sockaddr *)&ia->ia_dstaddr;
901                 } else {
902                         ia->ia_ifa.ifa_dstaddr = NULL;
903                 }
904                 ia->ia_ifa.ifa_netmask
905                         = (struct sockaddr *)&ia->ia_prefixmask;
906
907                 ia->ia_ifp = ifp;
908                 if ((oia = in6_ifaddr) != NULL) {
909                         for ( ; oia->ia_next; oia = oia->ia_next)
910                                 continue;
911                         oia->ia_next = ia;
912                 } else
913                         in6_ifaddr = ia;
914
915                 TAILQ_INSERT_TAIL(&ifp->if_addrlist, &ia->ia_ifa,
916                                   ifa_list);
917         }
918
919         /* set prefix mask */
920         if (ifra->ifra_prefixmask.sin6_len) {
921                 /*
922                  * We prohibit changing the prefix length of an existing
923                  * address, because
924                  * + such an operation should be rare in IPv6, and
925                  * + the operation would confuse prefix management.
926                  */
927                 if (ia->ia_prefixmask.sin6_len &&
928                     in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL) != plen) {
929                         log(LOG_INFO, "in6_update_ifa: the prefix length of an"
930                             " existing (%s) address should not be changed\n",
931                             ip6_sprintf(&ia->ia_addr.sin6_addr));
932                         error = EINVAL;
933                         goto unlink;
934                 }
935                 ia->ia_prefixmask = ifra->ifra_prefixmask;
936         }
937
938         /*
939          * If a new destination address is specified, scrub the old one and
940          * install the new destination.  Note that the interface must be
941          * p2p or loopback (see the check above.) 
942          */
943         if (dst6.sin6_family == AF_INET6 &&
944             !IN6_ARE_ADDR_EQUAL(&dst6.sin6_addr,
945                                 &ia->ia_dstaddr.sin6_addr)) {
946                 int e;
947
948                 if ((ia->ia_flags & IFA_ROUTE) != 0 &&
949                     (e = rtinit(&(ia->ia_ifa), (int)RTM_DELETE, RTF_HOST))
950                     != 0) {
951                         log(LOG_ERR, "in6_update_ifa: failed to remove "
952                             "a route to the old destination: %s\n",
953                             ip6_sprintf(&ia->ia_addr.sin6_addr));
954                         /* proceed anyway... */
955                 }
956                 else
957                         ia->ia_flags &= ~IFA_ROUTE;
958                 ia->ia_dstaddr = dst6;
959         }
960
961         /* reset the interface and routing table appropriately. */
962         if ((error = in6_ifinit(ifp, ia, &ifra->ifra_addr, hostIsNew)) != 0)
963                 goto unlink;
964
965         /*
966          * Beyond this point, we should call in6_purgeaddr upon an error,
967          * not just go to unlink. 
968          */
969
970 #if 0                           /* disable this mechanism for now */
971         /* update prefix list */
972         if (hostIsNew &&
973             (ifra->ifra_flags & IN6_IFF_NOPFX) == 0) { /* XXX */
974                 int iilen;
975
976                 iilen = (sizeof(ia->ia_prefixmask.sin6_addr) << 3) - plen;
977                 if ((error = in6_prefix_add_ifid(iilen, ia)) != 0) {
978                         in6_purgeaddr((struct ifaddr *)ia);
979                         return(error);
980                 }
981         }
982 #endif
983
984         if ((ifp->if_flags & IFF_MULTICAST) != 0) {
985                 struct sockaddr_in6 mltaddr, mltmask;
986                 struct in6_multi *in6m;
987
988                 if (hostIsNew) {
989                         /*
990                          * join solicited multicast addr for new host id
991                          */
992                         struct in6_addr llsol;
993                         bzero(&llsol, sizeof(struct in6_addr));
994                         llsol.s6_addr16[0] = htons(0xff02);
995                         llsol.s6_addr16[1] = htons(ifp->if_index);
996                         llsol.s6_addr32[1] = 0;
997                         llsol.s6_addr32[2] = htonl(1);
998                         llsol.s6_addr32[3] =
999                                 ifra->ifra_addr.sin6_addr.s6_addr32[3];
1000                         llsol.s6_addr8[12] = 0xff;
1001                         (void)in6_addmulti(&llsol, ifp, &error);
1002                         if (error != 0) {
1003                                 log(LOG_WARNING,
1004                                     "in6_update_ifa: addmulti failed for "
1005                                     "%s on %s (errno=%d)\n",
1006                                     ip6_sprintf(&llsol), if_name(ifp),
1007                                     error);
1008                                 in6_purgeaddr((struct ifaddr *)ia);
1009                                 return(error);
1010                         }
1011                 }
1012
1013                 bzero(&mltmask, sizeof(mltmask));
1014                 mltmask.sin6_len = sizeof(struct sockaddr_in6);
1015                 mltmask.sin6_family = AF_INET6;
1016                 mltmask.sin6_addr = in6mask32;
1017
1018                 /*
1019                  * join link-local all-nodes address
1020                  */
1021                 bzero(&mltaddr, sizeof(mltaddr));
1022                 mltaddr.sin6_len = sizeof(struct sockaddr_in6);
1023                 mltaddr.sin6_family = AF_INET6;
1024                 mltaddr.sin6_addr = in6addr_linklocal_allnodes;
1025                 mltaddr.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
1026
1027                 IN6_LOOKUP_MULTI(mltaddr.sin6_addr, ifp, in6m);
1028                 if (in6m == NULL) {
1029                         rtrequest(RTM_ADD,
1030                                   (struct sockaddr *)&mltaddr,
1031                                   (struct sockaddr *)&ia->ia_addr,
1032                                   (struct sockaddr *)&mltmask,
1033                                   RTF_UP|RTF_CLONING,  /* xxx */
1034                                   (struct rtentry **)0);
1035                         (void)in6_addmulti(&mltaddr.sin6_addr, ifp, &error);
1036                         if (error != 0) {
1037                                 log(LOG_WARNING,
1038                                     "in6_update_ifa: addmulti failed for "
1039                                     "%s on %s (errno=%d)\n",
1040                                     ip6_sprintf(&mltaddr.sin6_addr), 
1041                                     if_name(ifp), error);
1042                         }
1043                 }
1044
1045                 /*
1046                  * join node information group address
1047                  */
1048 #define hostnamelen     strlen(hostname)
1049                 if (in6_nigroup(ifp, hostname, hostnamelen, &mltaddr.sin6_addr)
1050                     == 0) {
1051                         IN6_LOOKUP_MULTI(mltaddr.sin6_addr, ifp, in6m);
1052                         if (in6m == NULL && ia != NULL) {
1053                                 (void)in6_addmulti(&mltaddr.sin6_addr,
1054                                     ifp, &error);
1055                                 if (error != 0) {
1056                                         log(LOG_WARNING, "in6_update_ifa: "
1057                                             "addmulti failed for "
1058                                             "%s on %s (errno=%d)\n",
1059                                             ip6_sprintf(&mltaddr.sin6_addr), 
1060                                             if_name(ifp), error);
1061                                 }
1062                         }
1063                 }
1064 #undef hostnamelen
1065
1066                 /*
1067                  * join node-local all-nodes address, on loopback.
1068                  * XXX: since "node-local" is obsoleted by interface-local,
1069                  *      we have to join the group on every interface with
1070                  *      some interface-boundary restriction.
1071                  */
1072                 if (ifp->if_flags & IFF_LOOPBACK) {
1073                         struct in6_ifaddr *ia_loop;
1074
1075                         struct in6_addr loop6 = in6addr_loopback;
1076                         ia_loop = in6ifa_ifpwithaddr(ifp, &loop6);
1077
1078                         mltaddr.sin6_addr = in6addr_nodelocal_allnodes;
1079
1080                         IN6_LOOKUP_MULTI(mltaddr.sin6_addr, ifp, in6m);
1081                         if (in6m == NULL && ia_loop != NULL) {
1082                                 rtrequest(RTM_ADD,
1083                                           (struct sockaddr *)&mltaddr,
1084                                           (struct sockaddr *)&ia_loop->ia_addr,
1085                                           (struct sockaddr *)&mltmask,
1086                                           RTF_UP,
1087                                           (struct rtentry **)0);
1088                                 (void)in6_addmulti(&mltaddr.sin6_addr, ifp,
1089                                                    &error);
1090                                 if (error != 0) {
1091                                         log(LOG_WARNING, "in6_update_ifa: "
1092                                             "addmulti failed for %s on %s "
1093                                             "(errno=%d)\n",
1094                                             ip6_sprintf(&mltaddr.sin6_addr), 
1095                                             if_name(ifp), error);
1096                                 }
1097                         }
1098                 }
1099         }
1100
1101         ia->ia6_flags = ifra->ifra_flags;
1102         ia->ia6_flags &= ~IN6_IFF_DUPLICATED;   /*safety*/
1103         ia->ia6_flags &= ~IN6_IFF_NODAD;        /* Mobile IPv6 */
1104
1105         ia->ia6_lifetime = ifra->ifra_lifetime;
1106         /* for sanity */
1107         if (ia->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
1108                 ia->ia6_lifetime.ia6t_expire =
1109                         time_second + ia->ia6_lifetime.ia6t_vltime;
1110         } else
1111                 ia->ia6_lifetime.ia6t_expire = 0;
1112         if (ia->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
1113                 ia->ia6_lifetime.ia6t_preferred =
1114                         time_second + ia->ia6_lifetime.ia6t_pltime;
1115         } else
1116                 ia->ia6_lifetime.ia6t_preferred = 0;
1117
1118         /*
1119          * Perform DAD, if needed.
1120          * XXX It may be of use, if we can administratively
1121          * disable DAD.
1122          */
1123         if (in6if_do_dad(ifp) && (ifra->ifra_flags & IN6_IFF_NODAD) == 0) {
1124                 ia->ia6_flags |= IN6_IFF_TENTATIVE;
1125                 nd6_dad_start((struct ifaddr *)ia, NULL);
1126         }
1127
1128         return(error);
1129
1130   unlink:
1131         /*
1132          * XXX: if a change of an existing address failed, keep the entry
1133          * anyway.
1134          */
1135         if (hostIsNew)
1136                 in6_unlink_ifa(ia, ifp);
1137         return(error);
1138 }
1139
1140 void
1141 in6_purgeaddr(struct ifaddr *ifa)
1142 {
1143         struct ifnet *ifp = ifa->ifa_ifp;
1144         struct in6_ifaddr *ia = (struct in6_ifaddr *) ifa;
1145
1146         /* stop DAD processing */
1147         nd6_dad_stop(ifa);
1148
1149         /*
1150          * delete route to the destination of the address being purged.
1151          * The interface must be p2p or loopback in this case.
1152          */
1153         if ((ia->ia_flags & IFA_ROUTE) != 0 && ia->ia_dstaddr.sin6_len != 0) {
1154                 int e;
1155
1156                 if ((e = rtinit(&(ia->ia_ifa), (int)RTM_DELETE, RTF_HOST))
1157                     != 0) {
1158                         log(LOG_ERR, "in6_purgeaddr: failed to remove "
1159                             "a route to the p2p destination: %s on %s, "
1160                             "errno=%d\n",
1161                             ip6_sprintf(&ia->ia_addr.sin6_addr), if_name(ifp),
1162                             e);
1163                         /* proceed anyway... */
1164                 }
1165                 else
1166                         ia->ia_flags &= ~IFA_ROUTE;
1167         }
1168
1169         /* Remove ownaddr's loopback rtentry, if it exists. */
1170         in6_ifremloop(&(ia->ia_ifa));
1171
1172         if (ifp->if_flags & IFF_MULTICAST) {
1173                 /*
1174                  * delete solicited multicast addr for deleting host id
1175                  */
1176                 struct in6_multi *in6m;
1177                 struct in6_addr llsol;
1178                 bzero(&llsol, sizeof(struct in6_addr));
1179                 llsol.s6_addr16[0] = htons(0xff02);
1180                 llsol.s6_addr16[1] = htons(ifp->if_index);
1181                 llsol.s6_addr32[1] = 0;
1182                 llsol.s6_addr32[2] = htonl(1);
1183                 llsol.s6_addr32[3] =
1184                         ia->ia_addr.sin6_addr.s6_addr32[3];
1185                 llsol.s6_addr8[12] = 0xff;
1186
1187                 IN6_LOOKUP_MULTI(llsol, ifp, in6m);
1188                 if (in6m)
1189                         in6_delmulti(in6m);
1190         }
1191
1192         in6_unlink_ifa(ia, ifp);
1193 }
1194
1195 static void
1196 in6_unlink_ifa(struct in6_ifaddr *ia, struct ifnet *ifp)
1197 {
1198         int plen, iilen;
1199         struct in6_ifaddr *oia;
1200
1201         crit_enter();
1202
1203         TAILQ_REMOVE(&ifp->if_addrlist, &ia->ia_ifa, ifa_list);
1204
1205         oia = ia;
1206         if (oia == (ia = in6_ifaddr))
1207                 in6_ifaddr = ia->ia_next;
1208         else {
1209                 while (ia->ia_next && (ia->ia_next != oia))
1210                         ia = ia->ia_next;
1211                 if (ia->ia_next)
1212                         ia->ia_next = oia->ia_next;
1213                 else {
1214                         /* search failed */
1215                         printf("Couldn't unlink in6_ifaddr from in6_ifaddr\n");
1216                 }
1217         }
1218
1219         if (oia->ia6_ifpr) {    /* check for safety */
1220                 plen = in6_mask2len(&oia->ia_prefixmask.sin6_addr, NULL);
1221                 iilen = (sizeof(oia->ia_prefixmask.sin6_addr) << 3) - plen;
1222                 in6_prefix_remove_ifid(iilen, oia);
1223         }
1224
1225         /*
1226          * When an autoconfigured address is being removed, release the
1227          * reference to the base prefix.  Also, since the release might
1228          * affect the status of other (detached) addresses, call
1229          * pfxlist_onlink_check().
1230          */
1231         if ((oia->ia6_flags & IN6_IFF_AUTOCONF) != 0) {
1232                 if (oia->ia6_ndpr == NULL) {
1233                         log(LOG_NOTICE, "in6_unlink_ifa: autoconf'ed address "
1234                             "%p has no prefix\n", oia);
1235                 } else {
1236                         oia->ia6_ndpr->ndpr_refcnt--;
1237                         oia->ia6_flags &= ~IN6_IFF_AUTOCONF;
1238                         oia->ia6_ndpr = NULL;
1239                 }
1240
1241                 pfxlist_onlink_check();
1242         }
1243
1244         /*
1245          * release another refcnt for the link from in6_ifaddr.
1246          * Note that we should decrement the refcnt at least once for all *BSD.
1247          */
1248         IFAFREE(&oia->ia_ifa);
1249
1250         crit_exit();
1251 }
1252
1253 void
1254 in6_purgeif(struct ifnet *ifp)
1255 {
1256         struct ifaddr *ifa, *nifa;
1257
1258         for (ifa = TAILQ_FIRST(&ifp->if_addrlist); ifa != NULL; ifa = nifa)
1259         {
1260                 nifa = TAILQ_NEXT(ifa, ifa_list);
1261                 if (ifa->ifa_addr->sa_family != AF_INET6)
1262                         continue;
1263                 in6_purgeaddr(ifa);
1264         }
1265
1266         in6_ifdetach(ifp);
1267 }
1268
1269 /*
1270  * SIOC[GAD]LIFADDR.
1271  *      SIOCGLIFADDR: get first address. (?)
1272  *      SIOCGLIFADDR with IFLR_PREFIX:
1273  *              get first address that matches the specified prefix.
1274  *      SIOCALIFADDR: add the specified address.
1275  *      SIOCALIFADDR with IFLR_PREFIX:
1276  *              add the specified prefix, filling hostid part from
1277  *              the first link-local address.  prefixlen must be <= 64.
1278  *      SIOCDLIFADDR: delete the specified address.
1279  *      SIOCDLIFADDR with IFLR_PREFIX:
1280  *              delete the first address that matches the specified prefix.
1281  * return values:
1282  *      EINVAL on invalid parameters
1283  *      EADDRNOTAVAIL on prefix match failed/specified address not found
1284  *      other values may be returned from in6_ioctl()
1285  *
1286  * NOTE: SIOCALIFADDR(with IFLR_PREFIX set) allows prefixlen less than 64.
1287  * this is to accomodate address naming scheme other than RFC2374,
1288  * in the future.
1289  * RFC2373 defines interface id to be 64bit, but it allows non-RFC2374
1290  * address encoding scheme. (see figure on page 8)
1291  */
1292 static int
1293 in6_lifaddr_ioctl(struct socket *so, u_long cmd, caddr_t data,
1294                   struct ifnet *ifp, struct thread *td)
1295 {
1296         struct if_laddrreq *iflr = (struct if_laddrreq *)data;
1297         struct ifaddr *ifa;
1298         struct sockaddr *sa;
1299
1300         /* sanity checks */
1301         if (!data || !ifp) {
1302                 panic("invalid argument to in6_lifaddr_ioctl");
1303                 /*NOTRECHED*/
1304         }
1305
1306         switch (cmd) {
1307         case SIOCGLIFADDR:
1308                 /* address must be specified on GET with IFLR_PREFIX */
1309                 if ((iflr->flags & IFLR_PREFIX) == 0)
1310                         break;
1311                 /* FALLTHROUGH */
1312         case SIOCALIFADDR:
1313         case SIOCDLIFADDR:
1314                 /* address must be specified on ADD and DELETE */
1315                 sa = (struct sockaddr *)&iflr->addr;
1316                 if (sa->sa_family != AF_INET6)
1317                         return EINVAL;
1318                 if (sa->sa_len != sizeof(struct sockaddr_in6))
1319                         return EINVAL;
1320                 /* XXX need improvement */
1321                 sa = (struct sockaddr *)&iflr->dstaddr;
1322                 if (sa->sa_family && sa->sa_family != AF_INET6)
1323                         return EINVAL;
1324                 if (sa->sa_len && sa->sa_len != sizeof(struct sockaddr_in6))
1325                         return EINVAL;
1326                 break;
1327         default: /* shouldn't happen */
1328 #if 0
1329                 panic("invalid cmd to in6_lifaddr_ioctl");
1330                 /* NOTREACHED */
1331 #else
1332                 return EOPNOTSUPP;
1333 #endif
1334         }
1335         if (sizeof(struct in6_addr) * 8 < iflr->prefixlen)
1336                 return EINVAL;
1337
1338         switch (cmd) {
1339         case SIOCALIFADDR:
1340             {
1341                 struct in6_aliasreq ifra;
1342                 struct in6_addr *hostid = NULL;
1343                 int prefixlen;
1344
1345                 if ((iflr->flags & IFLR_PREFIX) != 0) {
1346                         struct sockaddr_in6 *sin6;
1347
1348                         /*
1349                          * hostid is to fill in the hostid part of the
1350                          * address.  hostid points to the first link-local
1351                          * address attached to the interface.
1352                          */
1353                         ifa = (struct ifaddr *)in6ifa_ifpforlinklocal(ifp, 0);
1354                         if (!ifa)
1355                                 return EADDRNOTAVAIL;
1356                         hostid = IFA_IN6(ifa);
1357
1358                         /* prefixlen must be <= 64. */
1359                         if (64 < iflr->prefixlen)
1360                                 return EINVAL;
1361                         prefixlen = iflr->prefixlen;
1362
1363                         /* hostid part must be zero. */
1364                         sin6 = (struct sockaddr_in6 *)&iflr->addr;
1365                         if (sin6->sin6_addr.s6_addr32[2] != 0
1366                          || sin6->sin6_addr.s6_addr32[3] != 0) {
1367                                 return EINVAL;
1368                         }
1369                 } else
1370                         prefixlen = iflr->prefixlen;
1371
1372                 /* copy args to in6_aliasreq, perform ioctl(SIOCAIFADDR_IN6). */
1373                 bzero(&ifra, sizeof(ifra));
1374                 bcopy(iflr->iflr_name, ifra.ifra_name,
1375                         sizeof(ifra.ifra_name));
1376
1377                 bcopy(&iflr->addr, &ifra.ifra_addr,
1378                         ((struct sockaddr *)&iflr->addr)->sa_len);
1379                 if (hostid) {
1380                         /* fill in hostid part */
1381                         ifra.ifra_addr.sin6_addr.s6_addr32[2] =
1382                                 hostid->s6_addr32[2];
1383                         ifra.ifra_addr.sin6_addr.s6_addr32[3] =
1384                                 hostid->s6_addr32[3];
1385                 }
1386
1387                 if (((struct sockaddr *)&iflr->dstaddr)->sa_family) {   /*XXX*/
1388                         bcopy(&iflr->dstaddr, &ifra.ifra_dstaddr,
1389                                 ((struct sockaddr *)&iflr->dstaddr)->sa_len);
1390                         if (hostid) {
1391                                 ifra.ifra_dstaddr.sin6_addr.s6_addr32[2] =
1392                                         hostid->s6_addr32[2];
1393                                 ifra.ifra_dstaddr.sin6_addr.s6_addr32[3] =
1394                                         hostid->s6_addr32[3];
1395                         }
1396                 }
1397
1398                 ifra.ifra_prefixmask.sin6_len = sizeof(struct sockaddr_in6);
1399                 in6_len2mask(&ifra.ifra_prefixmask.sin6_addr, prefixlen);
1400
1401                 ifra.ifra_flags = iflr->flags & ~IFLR_PREFIX;
1402                 return in6_control(so, SIOCAIFADDR_IN6, (caddr_t)&ifra, ifp, td);
1403             }
1404         case SIOCGLIFADDR:
1405         case SIOCDLIFADDR:
1406             {
1407                 struct in6_ifaddr *ia;
1408                 struct in6_addr mask, candidate, match;
1409                 struct sockaddr_in6 *sin6;
1410                 int cmp;
1411
1412                 bzero(&mask, sizeof(mask));
1413                 if (iflr->flags & IFLR_PREFIX) {
1414                         /* lookup a prefix rather than address. */
1415                         in6_len2mask(&mask, iflr->prefixlen);
1416
1417                         sin6 = (struct sockaddr_in6 *)&iflr->addr;
1418                         bcopy(&sin6->sin6_addr, &match, sizeof(match));
1419                         match.s6_addr32[0] &= mask.s6_addr32[0];
1420                         match.s6_addr32[1] &= mask.s6_addr32[1];
1421                         match.s6_addr32[2] &= mask.s6_addr32[2];
1422                         match.s6_addr32[3] &= mask.s6_addr32[3];
1423
1424                         /* if you set extra bits, that's wrong */
1425                         if (bcmp(&match, &sin6->sin6_addr, sizeof(match)))
1426                                 return EINVAL;
1427
1428                         cmp = 1;
1429                 } else {
1430                         if (cmd == SIOCGLIFADDR) {
1431                                 /* on getting an address, take the 1st match */
1432                                 cmp = 0;        /* XXX */
1433                         } else {
1434                                 /* on deleting an address, do exact match */
1435                                 in6_len2mask(&mask, 128);
1436                                 sin6 = (struct sockaddr_in6 *)&iflr->addr;
1437                                 bcopy(&sin6->sin6_addr, &match, sizeof(match));
1438
1439                                 cmp = 1;
1440                         }
1441                 }
1442
1443                 TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list)
1444                 {
1445                         if (ifa->ifa_addr->sa_family != AF_INET6)
1446                                 continue;
1447                         if (!cmp)
1448                                 break;
1449
1450                         bcopy(IFA_IN6(ifa), &candidate, sizeof(candidate));
1451                         /*
1452                          * XXX: this is adhoc, but is necessary to allow
1453                          * a user to specify fe80::/64 (not /10) for a
1454                          * link-local address.
1455                          */
1456                         if (IN6_IS_ADDR_LINKLOCAL(&candidate))
1457                                 candidate.s6_addr16[1] = 0;
1458                         candidate.s6_addr32[0] &= mask.s6_addr32[0];
1459                         candidate.s6_addr32[1] &= mask.s6_addr32[1];
1460                         candidate.s6_addr32[2] &= mask.s6_addr32[2];
1461                         candidate.s6_addr32[3] &= mask.s6_addr32[3];
1462                         if (IN6_ARE_ADDR_EQUAL(&candidate, &match))
1463                                 break;
1464                 }
1465                 if (!ifa)
1466                         return EADDRNOTAVAIL;
1467                 ia = ifa2ia6(ifa);
1468
1469                 if (cmd == SIOCGLIFADDR) {
1470                         struct sockaddr_in6 *s6;
1471
1472                         /* fill in the if_laddrreq structure */
1473                         bcopy(&ia->ia_addr, &iflr->addr, ia->ia_addr.sin6_len);
1474                         s6 = (struct sockaddr_in6 *)&iflr->addr;
1475                         if (IN6_IS_ADDR_LINKLOCAL(&s6->sin6_addr)) {
1476                                 s6->sin6_addr.s6_addr16[1] = 0;
1477                                 s6->sin6_scope_id =
1478                                         in6_addr2scopeid(ifp, &s6->sin6_addr);
1479                         }
1480                         if ((ifp->if_flags & IFF_POINTOPOINT) != 0) {
1481                                 bcopy(&ia->ia_dstaddr, &iflr->dstaddr,
1482                                         ia->ia_dstaddr.sin6_len);
1483                                 s6 = (struct sockaddr_in6 *)&iflr->dstaddr;
1484                                 if (IN6_IS_ADDR_LINKLOCAL(&s6->sin6_addr)) {
1485                                         s6->sin6_addr.s6_addr16[1] = 0;
1486                                         s6->sin6_scope_id =
1487                                                 in6_addr2scopeid(ifp,
1488                                                                  &s6->sin6_addr);
1489                                 }
1490                         } else
1491                                 bzero(&iflr->dstaddr, sizeof(iflr->dstaddr));
1492
1493                         iflr->prefixlen =
1494                                 in6_mask2len(&ia->ia_prefixmask.sin6_addr,
1495                                              NULL);
1496
1497                         iflr->flags = ia->ia6_flags;    /* XXX */
1498
1499                         return 0;
1500                 } else {
1501                         struct in6_aliasreq ifra;
1502
1503                         /* fill in6_aliasreq and do ioctl(SIOCDIFADDR_IN6) */
1504                         bzero(&ifra, sizeof(ifra));
1505                         bcopy(iflr->iflr_name, ifra.ifra_name,
1506                                 sizeof(ifra.ifra_name));
1507
1508                         bcopy(&ia->ia_addr, &ifra.ifra_addr,
1509                                 ia->ia_addr.sin6_len);
1510                         if ((ifp->if_flags & IFF_POINTOPOINT) != 0) {
1511                                 bcopy(&ia->ia_dstaddr, &ifra.ifra_dstaddr,
1512                                         ia->ia_dstaddr.sin6_len);
1513                         } else {
1514                                 bzero(&ifra.ifra_dstaddr,
1515                                     sizeof(ifra.ifra_dstaddr));
1516                         }
1517                         bcopy(&ia->ia_prefixmask, &ifra.ifra_dstaddr,
1518                                 ia->ia_prefixmask.sin6_len);
1519
1520                         ifra.ifra_flags = ia->ia6_flags;
1521                         return in6_control(so, SIOCDIFADDR_IN6, (caddr_t)&ifra,
1522                                 ifp, td);
1523                 }
1524             }
1525         }
1526
1527         return EOPNOTSUPP;      /* just for safety */
1528 }
1529
1530 /*
1531  * Initialize an interface's intetnet6 address
1532  * and routing table entry.
1533  */
1534 static int
1535 in6_ifinit(struct ifnet *ifp, struct in6_ifaddr *ia, struct sockaddr_in6 *sin6,
1536            int newhost)
1537 {
1538         int     error = 0, plen, ifacount = 0;
1539         struct ifaddr *ifa;
1540
1541         crit_enter();
1542
1543         /*
1544          * Give the interface a chance to initialize
1545          * if this is its first address,
1546          * and to validate the address if necessary.
1547          */
1548         TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list)
1549         {
1550                 if (ifa->ifa_addr == NULL)
1551                         continue;       /* just for safety */
1552                 if (ifa->ifa_addr->sa_family != AF_INET6)
1553                         continue;
1554                 ifacount++;
1555         }
1556
1557         ia->ia_addr = *sin6;
1558
1559         if (ifacount <= 1 && ifp->if_ioctl &&
1560             (error = (*ifp->if_ioctl)(ifp, SIOCSIFADDR, (caddr_t)ia,
1561                                       (struct ucred *)NULL))) {
1562                 crit_exit();
1563                 return(error);
1564         }
1565         crit_exit();
1566
1567         ia->ia_ifa.ifa_metric = ifp->if_metric;
1568
1569         /* we could do in(6)_socktrim here, but just omit it at this moment. */
1570
1571         /*
1572          * Special case:
1573          * If the destination address is specified for a point-to-point
1574          * interface, install a route to the destination as an interface
1575          * direct route.
1576          */
1577         plen = in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL); /* XXX */
1578         if (plen == 128 && ia->ia_dstaddr.sin6_family == AF_INET6) {
1579                 if ((error = rtinit(&(ia->ia_ifa), (int)RTM_ADD,
1580                                     RTF_UP | RTF_HOST)) != 0)
1581                         return(error);
1582                 ia->ia_flags |= IFA_ROUTE;
1583         }
1584         if (plen < 128) {
1585                 /*
1586                  * The RTF_CLONING flag is necessary for in6_is_ifloop_auto().
1587                  */
1588                 ia->ia_ifa.ifa_flags |= RTF_CLONING;
1589         }
1590
1591         /* Add ownaddr as loopback rtentry, if necessary (ex. on p2p link). */
1592         if (newhost) {
1593                 /* set the rtrequest function to create llinfo */
1594                 ia->ia_ifa.ifa_rtrequest = nd6_rtrequest;
1595                 in6_ifaddloop(&(ia->ia_ifa));
1596         }
1597
1598         return(error);
1599 }
1600
1601 /*
1602  * Add an address to the list of IP6 multicast addresses for a
1603  * given interface.
1604  */
1605 struct  in6_multi *
1606 in6_addmulti(struct in6_addr *maddr6, struct ifnet *ifp, int *errorp)
1607 {
1608         struct  in6_multi *in6m;
1609         struct sockaddr_in6 sin6;
1610         struct ifmultiaddr *ifma;
1611
1612         *errorp = 0;
1613
1614         crit_enter();
1615
1616         /*
1617          * Call generic routine to add membership or increment
1618          * refcount.  It wants addresses in the form of a sockaddr,
1619          * so we build one here (being careful to zero the unused bytes).
1620          */
1621         bzero(&sin6, sizeof sin6);
1622         sin6.sin6_family = AF_INET6;
1623         sin6.sin6_len = sizeof sin6;
1624         sin6.sin6_addr = *maddr6;
1625         *errorp = if_addmulti(ifp, (struct sockaddr *)&sin6, &ifma);
1626         if (*errorp) {
1627                 crit_exit();
1628                 return 0;
1629         }
1630
1631         /*
1632          * If ifma->ifma_protospec is null, then if_addmulti() created
1633          * a new record.  Otherwise, we are done.
1634          */
1635         if (ifma->ifma_protospec != 0) {
1636                 crit_exit();
1637                 return ifma->ifma_protospec;
1638         }
1639
1640         /* XXX - if_addmulti uses M_WAITOK.  Can this really be called
1641            at interrupt time?  If so, need to fix if_addmulti. XXX */
1642         in6m = (struct in6_multi *)malloc(sizeof(*in6m), M_IPMADDR, M_NOWAIT);
1643         if (in6m == NULL) {
1644                 crit_exit();
1645                 return (NULL);
1646         }
1647
1648         bzero(in6m, sizeof *in6m);
1649         in6m->in6m_addr = *maddr6;
1650         in6m->in6m_ifp = ifp;
1651         in6m->in6m_ifma = ifma;
1652         ifma->ifma_protospec = in6m;
1653         LIST_INSERT_HEAD(&in6_multihead, in6m, in6m_entry);
1654
1655         /*
1656          * Let MLD6 know that we have joined a new IP6 multicast
1657          * group.
1658          */
1659         mld6_start_listening(in6m);
1660         crit_exit();
1661         return(in6m);
1662 }
1663
1664 /*
1665  * Delete a multicast address record.
1666  */
1667 void
1668 in6_delmulti(struct in6_multi *in6m)
1669 {
1670         struct ifmultiaddr *ifma = in6m->in6m_ifma;
1671
1672         crit_enter();
1673
1674         if (ifma->ifma_refcount == 1) {
1675                 /*
1676                  * No remaining claims to this record; let MLD6 know
1677                  * that we are leaving the multicast group.
1678                  */
1679                 mld6_stop_listening(in6m);
1680                 ifma->ifma_protospec = 0;
1681                 LIST_REMOVE(in6m, in6m_entry);
1682                 free(in6m, M_IPMADDR);
1683         }
1684         /* XXX - should be separate API for when we have an ifma? */
1685         if_delmulti(ifma->ifma_ifp, ifma->ifma_addr);
1686         crit_exit();
1687 }
1688
1689 /*
1690  * Find an IPv6 interface link-local address specific to an interface.
1691  */
1692 struct in6_ifaddr *
1693 in6ifa_ifpforlinklocal(struct ifnet *ifp, int ignoreflags)
1694 {
1695         struct ifaddr *ifa;
1696
1697         TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list)
1698         {
1699                 if (ifa->ifa_addr == NULL)
1700                         continue;       /* just for safety */
1701                 if (ifa->ifa_addr->sa_family != AF_INET6)
1702                         continue;
1703                 if (IN6_IS_ADDR_LINKLOCAL(IFA_IN6(ifa))) {
1704                         if ((((struct in6_ifaddr *)ifa)->ia6_flags &
1705                              ignoreflags) != 0)
1706                                 continue;
1707                         break;
1708                 }
1709         }
1710
1711         return((struct in6_ifaddr *)ifa);
1712 }
1713
1714
1715 /*
1716  * find the internet address corresponding to a given interface and address.
1717  */
1718 struct in6_ifaddr *
1719 in6ifa_ifpwithaddr(struct ifnet *ifp, struct in6_addr *addr)
1720 {
1721         struct ifaddr *ifa;
1722
1723         TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list)
1724         {
1725                 if (ifa->ifa_addr == NULL)
1726                         continue;       /* just for safety */
1727                 if (ifa->ifa_addr->sa_family != AF_INET6)
1728                         continue;
1729                 if (IN6_ARE_ADDR_EQUAL(addr, IFA_IN6(ifa)))
1730                         break;
1731         }
1732
1733         return((struct in6_ifaddr *)ifa);
1734 }
1735
1736 /*
1737  * Convert IP6 address to printable (loggable) representation.
1738  */
1739 static char digits[] = "0123456789abcdef";
1740 static int ip6round = 0;
1741 char *
1742 ip6_sprintf(const struct in6_addr *addr)
1743 {
1744         static char ip6buf[8][48];
1745         int i;
1746         char *cp;
1747         const u_short *a = (const u_short *)addr;
1748         const u_char *d;
1749         int dcolon = 0;
1750
1751         ip6round = (ip6round + 1) & 7;
1752         cp = ip6buf[ip6round];
1753
1754         for (i = 0; i < 8; i++) {
1755                 if (dcolon == 1) {
1756                         if (*a == 0) {
1757                                 if (i == 7)
1758                                         *cp++ = ':';
1759                                 a++;
1760                                 continue;
1761                         } else
1762                                 dcolon = 2;
1763                 }
1764                 if (*a == 0) {
1765                         if (dcolon == 0 && *(a + 1) == 0) {
1766                                 if (i == 0)
1767                                         *cp++ = ':';
1768                                 *cp++ = ':';
1769                                 dcolon = 1;
1770                         } else {
1771                                 *cp++ = '0';
1772                                 *cp++ = ':';
1773                         }
1774                         a++;
1775                         continue;
1776                 }
1777                 d = (const u_char *)a;
1778                 *cp++ = digits[*d >> 4];
1779                 *cp++ = digits[*d++ & 0xf];
1780                 *cp++ = digits[*d >> 4];
1781                 *cp++ = digits[*d & 0xf];
1782                 *cp++ = ':';
1783                 a++;
1784         }
1785         *--cp = 0;
1786         return(ip6buf[ip6round]);
1787 }
1788
1789 int
1790 in6_localaddr(struct in6_addr *in6)
1791 {
1792         struct in6_ifaddr *ia;
1793
1794         if (IN6_IS_ADDR_LOOPBACK(in6) || IN6_IS_ADDR_LINKLOCAL(in6))
1795                 return 1;
1796
1797         for (ia = in6_ifaddr; ia; ia = ia->ia_next)
1798                 if (IN6_ARE_MASKED_ADDR_EQUAL(in6, &ia->ia_addr.sin6_addr,
1799                                               &ia->ia_prefixmask.sin6_addr))
1800                         return 1;
1801
1802         return (0);
1803 }
1804
1805 int
1806 in6_is_addr_deprecated(struct sockaddr_in6 *sa6)
1807 {
1808         struct in6_ifaddr *ia;
1809
1810         for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
1811                 if (IN6_ARE_ADDR_EQUAL(&ia->ia_addr.sin6_addr,
1812                                        &sa6->sin6_addr) &&
1813                     (ia->ia6_flags & IN6_IFF_DEPRECATED) != 0)
1814                         return(1); /* true */
1815
1816                 /* XXX: do we still have to go thru the rest of the list? */
1817         }
1818
1819         return(0);              /* false */
1820 }
1821
1822 /*
1823  * return length of part which dst and src are equal
1824  * hard coding...
1825  */
1826 int
1827 in6_matchlen(struct in6_addr *src, struct in6_addr *dst)
1828 {
1829         int match = 0;
1830         u_char *s = (u_char *)src, *d = (u_char *)dst;
1831         u_char *lim = s + 16, r;
1832
1833         while (s < lim)
1834                 if ((r = (*d++ ^ *s++)) != 0) {
1835                         while (r < 128) {
1836                                 match++;
1837                                 r <<= 1;
1838                         }
1839                         break;
1840                 } else
1841                         match += 8;
1842         return match;
1843 }
1844
1845 /* XXX: to be scope conscious */
1846 int
1847 in6_are_prefix_equal(struct in6_addr *p1, struct in6_addr *p2, int len)
1848 {
1849         int bytelen, bitlen;
1850
1851         /* sanity check */
1852         if (0 > len || len > 128) {
1853                 log(LOG_ERR, "in6_are_prefix_equal: invalid prefix length(%d)\n",
1854                     len);
1855                 return(0);
1856         }
1857
1858         bytelen = len / 8;
1859         bitlen = len % 8;
1860
1861         if (bcmp(&p1->s6_addr, &p2->s6_addr, bytelen))
1862                 return(0);
1863         if (p1->s6_addr[bytelen] >> (8 - bitlen) !=
1864             p2->s6_addr[bytelen] >> (8 - bitlen))
1865                 return(0);
1866
1867         return(1);
1868 }
1869
1870 void
1871 in6_prefixlen2mask(struct in6_addr *maskp, int len)
1872 {
1873         u_char maskarray[8] = {0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff};
1874         int bytelen, bitlen, i;
1875
1876         /* sanity check */
1877         if (0 > len || len > 128) {
1878                 log(LOG_ERR, "in6_prefixlen2mask: invalid prefix length(%d)\n",
1879                     len);
1880                 return;
1881         }
1882
1883         bzero(maskp, sizeof(*maskp));
1884         bytelen = len / 8;
1885         bitlen = len % 8;
1886         for (i = 0; i < bytelen; i++)
1887                 maskp->s6_addr[i] = 0xff;
1888         if (bitlen)
1889                 maskp->s6_addr[bytelen] = maskarray[bitlen - 1];
1890 }
1891
1892 /*
1893  * return the best address out of the same scope
1894  */
1895 struct in6_ifaddr *
1896 in6_ifawithscope(struct ifnet *oifp, struct in6_addr *dst)
1897 {
1898         int dst_scope = in6_addrscope(dst), src_scope, best_scope = 0;
1899         int blen = -1;
1900         struct ifaddr *ifa;
1901         struct ifnet *ifp;
1902         struct in6_ifaddr *ifa_best = NULL;
1903         
1904         if (oifp == NULL) {
1905 #if 0
1906                 printf("in6_ifawithscope: output interface is not specified\n");
1907 #endif
1908                 return(NULL);
1909         }
1910
1911         /*
1912          * We search for all addresses on all interfaces from the beginning.
1913          * Comparing an interface with the outgoing interface will be done
1914          * only at the final stage of tiebreaking.
1915          */
1916         for (ifp = TAILQ_FIRST(&ifnet); ifp; ifp = TAILQ_NEXT(ifp, if_list))
1917         {
1918                 /*
1919                  * We can never take an address that breaks the scope zone
1920                  * of the destination.
1921                  */
1922                 if (in6_addr2scopeid(ifp, dst) != in6_addr2scopeid(oifp, dst))
1923                         continue;
1924
1925                 TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list)
1926                 {
1927                         int tlen = -1, dscopecmp, bscopecmp, matchcmp;
1928
1929                         if (ifa->ifa_addr->sa_family != AF_INET6)
1930                                 continue;
1931
1932                         src_scope = in6_addrscope(IFA_IN6(ifa));
1933
1934                         /*
1935                          * Don't use an address before completing DAD
1936                          * nor a duplicated address.
1937                          */
1938                         if (((struct in6_ifaddr *)ifa)->ia6_flags &
1939                             IN6_IFF_NOTREADY)
1940                                 continue;
1941
1942                         /* XXX: is there any case to allow anycasts? */
1943                         if (((struct in6_ifaddr *)ifa)->ia6_flags &
1944                             IN6_IFF_ANYCAST)
1945                                 continue;
1946
1947                         if (((struct in6_ifaddr *)ifa)->ia6_flags &
1948                             IN6_IFF_DETACHED)
1949                                 continue;
1950
1951                         /*
1952                          * If this is the first address we find,
1953                          * keep it anyway.
1954                          */
1955                         if (ifa_best == NULL)
1956                                 goto replace;
1957
1958                         /*
1959                          * ifa_best is never NULL beyond this line except
1960                          * within the block labeled "replace".
1961                          */
1962
1963                         /*
1964                          * If ifa_best has a smaller scope than dst and
1965                          * the current address has a larger one than
1966                          * (or equal to) dst, always replace ifa_best.
1967                          * Also, if the current address has a smaller scope
1968                          * than dst, ignore it unless ifa_best also has a
1969                          * smaller scope.
1970                          * Consequently, after the two if-clause below,
1971                          * the followings must be satisfied:
1972                          * (scope(src) < scope(dst) &&
1973                          *  scope(best) < scope(dst))
1974                          *  OR
1975                          * (scope(best) >= scope(dst) &&
1976                          *  scope(src) >= scope(dst))
1977                          */
1978                         if (IN6_ARE_SCOPE_CMP(best_scope, dst_scope) < 0 &&
1979                             IN6_ARE_SCOPE_CMP(src_scope, dst_scope) >= 0)
1980                                 goto replace; /* (A) */
1981                         if (IN6_ARE_SCOPE_CMP(src_scope, dst_scope) < 0 &&
1982                             IN6_ARE_SCOPE_CMP(best_scope, dst_scope) >= 0)
1983                                 continue; /* (B) */
1984
1985                         /*
1986                          * A deprecated address SHOULD NOT be used in new
1987                          * communications if an alternate (non-deprecated)
1988                          * address is available and has sufficient scope.
1989                          * RFC 2462, Section 5.5.4.
1990                          */
1991                         if (((struct in6_ifaddr *)ifa)->ia6_flags &
1992                             IN6_IFF_DEPRECATED) {
1993                                 /*
1994                                  * Ignore any deprecated addresses if
1995                                  * specified by configuration.
1996                                  */
1997                                 if (!ip6_use_deprecated)
1998                                         continue;
1999
2000                                 /*
2001                                  * If we have already found a non-deprecated
2002                                  * candidate, just ignore deprecated addresses.
2003                                  */
2004                                 if ((ifa_best->ia6_flags & IN6_IFF_DEPRECATED)
2005                                     == 0)
2006                                         continue;
2007                         }
2008
2009                         /*
2010                          * A non-deprecated address is always preferred
2011                          * to a deprecated one regardless of scopes and
2012                          * address matching (Note invariants ensured by the
2013                          * conditions (A) and (B) above.)
2014                          */
2015                         if ((ifa_best->ia6_flags & IN6_IFF_DEPRECATED) &&
2016                             (((struct in6_ifaddr *)ifa)->ia6_flags &
2017                              IN6_IFF_DEPRECATED) == 0)
2018                                 goto replace;
2019
2020                         /*
2021                          * When we use temporary addresses described in
2022                          * RFC 3041, we prefer temporary addresses to
2023                          * public autoconf addresses.  Again, note the
2024                          * invariants from (A) and (B).  Also note that we
2025                          * don't have any preference between static addresses
2026                          * and autoconf addresses (despite of whether or not
2027                          * the latter is temporary or public.)
2028                          */
2029                         if (ip6_use_tempaddr) {
2030                                 struct in6_ifaddr *ifat;
2031
2032                                 ifat = (struct in6_ifaddr *)ifa;
2033                                 if ((ifa_best->ia6_flags &
2034                                      (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY))
2035                                      == IN6_IFF_AUTOCONF &&
2036                                     (ifat->ia6_flags &
2037                                      (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY))
2038                                      == (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY)) {
2039                                         goto replace;
2040                                 }
2041                                 if ((ifa_best->ia6_flags &
2042                                      (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY))
2043                                     == (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY) &&
2044                                     (ifat->ia6_flags &
2045                                      (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY))
2046                                      == IN6_IFF_AUTOCONF) {
2047                                         continue;
2048                                 }
2049                         }
2050
2051                         /*
2052                          * At this point, we have two cases:
2053                          * 1. we are looking at a non-deprecated address,
2054                          *    and ifa_best is also non-deprecated.
2055                          * 2. we are looking at a deprecated address,
2056                          *    and ifa_best is also deprecated.
2057                          * Also, we do not have to consider a case where
2058                          * the scope of if_best is larger(smaller) than dst and
2059                          * the scope of the current address is smaller(larger)
2060                          * than dst. Such a case has already been covered.
2061                          * Tiebreaking is done according to the following
2062                          * items:
2063                          * - the scope comparison between the address and
2064                          *   dst (dscopecmp)
2065                          * - the scope comparison between the address and
2066                          *   ifa_best (bscopecmp)
2067                          * - if the address match dst longer than ifa_best
2068                          *   (matchcmp)
2069                          * - if the address is on the outgoing I/F (outI/F)
2070                          *
2071                          * Roughly speaking, the selection policy is
2072                          * - the most important item is scope. The same scope
2073                          *   is best. Then search for a larger scope.
2074                          *   Smaller scopes are the last resort.
2075                          * - A deprecated address is chosen only when we have
2076                          *   no address that has an enough scope, but is
2077                          *   prefered to any addresses of smaller scopes
2078                          *   (this must be already done above.)
2079                          * - addresses on the outgoing I/F are preferred to
2080                          *   ones on other interfaces if none of above
2081                          *   tiebreaks.  In the table below, the column "bI"
2082                          *   means if the best_ifa is on the outgoing
2083                          *   interface, and the column "sI" means if the ifa
2084                          *   is on the outgoing interface.
2085                          * - If there is no other reasons to choose one,
2086                          *   longest address match against dst is considered.
2087                          *
2088                          * The precise decision table is as follows:
2089                          * dscopecmp bscopecmp    match  bI oI | replace?
2090                          *       N/A     equal      N/A   Y  N |   No (1)
2091                          *       N/A     equal      N/A   N  Y |  Yes (2)
2092                          *       N/A     equal   larger    N/A |  Yes (3)
2093                          *       N/A     equal  !larger    N/A |   No (4)
2094                          *    larger    larger      N/A    N/A |   No (5)
2095                          *    larger   smaller      N/A    N/A |  Yes (6)
2096                          *   smaller    larger      N/A    N/A |  Yes (7)
2097                          *   smaller   smaller      N/A    N/A |   No (8)
2098                          *     equal   smaller      N/A    N/A |  Yes (9)
2099                          *     equal    larger       (already done at A above)
2100                          */
2101                         dscopecmp = IN6_ARE_SCOPE_CMP(src_scope, dst_scope);
2102                         bscopecmp = IN6_ARE_SCOPE_CMP(src_scope, best_scope);
2103
2104                         if (bscopecmp == 0) {
2105                                 struct ifnet *bifp = ifa_best->ia_ifp;
2106
2107                                 if (bifp == oifp && ifp != oifp) /* (1) */
2108                                         continue;
2109                                 if (bifp != oifp && ifp == oifp) /* (2) */
2110                                         goto replace;
2111
2112                                 /*
2113                                  * Both bifp and ifp are on the outgoing
2114                                  * interface, or both two are on a different
2115                                  * interface from the outgoing I/F.
2116                                  * now we need address matching against dst
2117                                  * for tiebreaking.
2118                                  */
2119                                 tlen = in6_matchlen(IFA_IN6(ifa), dst);
2120                                 matchcmp = tlen - blen;
2121                                 if (matchcmp > 0) /* (3) */
2122                                         goto replace;
2123                                 continue; /* (4) */
2124                         }
2125                         if (dscopecmp > 0) {
2126                                 if (bscopecmp > 0) /* (5) */
2127                                         continue;
2128                                 goto replace; /* (6) */
2129                         }
2130                         if (dscopecmp < 0) {
2131                                 if (bscopecmp > 0) /* (7) */
2132                                         goto replace;
2133                                 continue; /* (8) */
2134                         }
2135
2136                         /* now dscopecmp must be 0 */
2137                         if (bscopecmp < 0)
2138                                 goto replace; /* (9) */
2139
2140                   replace:
2141                         ifa_best = (struct in6_ifaddr *)ifa;
2142                         blen = tlen >= 0 ? tlen :
2143                                 in6_matchlen(IFA_IN6(ifa), dst);
2144                         best_scope = in6_addrscope(&ifa_best->ia_addr.sin6_addr);
2145                 }
2146         }
2147
2148         /* count statistics for future improvements */
2149         if (ifa_best == NULL)
2150                 ip6stat.ip6s_sources_none++;
2151         else {
2152                 if (oifp == ifa_best->ia_ifp)
2153                         ip6stat.ip6s_sources_sameif[best_scope]++;
2154                 else
2155                         ip6stat.ip6s_sources_otherif[best_scope]++;
2156
2157                 if (best_scope == dst_scope)
2158                         ip6stat.ip6s_sources_samescope[best_scope]++;
2159                 else
2160                         ip6stat.ip6s_sources_otherscope[best_scope]++;
2161
2162                 if ((ifa_best->ia6_flags & IN6_IFF_DEPRECATED) != 0)
2163                         ip6stat.ip6s_sources_deprecated[best_scope]++;
2164         }
2165
2166         return(ifa_best);
2167 }
2168
2169 /*
2170  * return the best address out of the same scope. if no address was
2171  * found, return the first valid address from designated IF.
2172  */
2173 struct in6_ifaddr *
2174 in6_ifawithifp(struct ifnet *ifp, struct in6_addr *dst)
2175 {
2176         int dst_scope = in6_addrscope(dst), blen = -1, tlen;
2177         struct ifaddr *ifa;
2178         struct in6_ifaddr *besta = 0;
2179         struct in6_ifaddr *dep[2];      /* last-resort: deprecated */
2180
2181         dep[0] = dep[1] = NULL;
2182
2183         /*
2184          * We first look for addresses in the same scope.
2185          * If there is one, return it.
2186          * If two or more, return one which matches the dst longest.
2187          * If none, return one of global addresses assigned other ifs.
2188          */
2189         TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list)
2190         {
2191                 if (ifa->ifa_addr->sa_family != AF_INET6)
2192                         continue;
2193                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_ANYCAST)
2194                         continue; /* XXX: is there any case to allow anycast? */
2195                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_NOTREADY)
2196                         continue; /* don't use this interface */
2197                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DETACHED)
2198                         continue;
2199                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DEPRECATED) {
2200                         if (ip6_use_deprecated)
2201                                 dep[0] = (struct in6_ifaddr *)ifa;
2202                         continue;
2203                 }
2204
2205                 if (dst_scope == in6_addrscope(IFA_IN6(ifa))) {
2206                         /*
2207                          * call in6_matchlen() as few as possible
2208                          */
2209                         if (besta) {
2210                                 if (blen == -1)
2211                                         blen = in6_matchlen(&besta->ia_addr.sin6_addr, dst);
2212                                 tlen = in6_matchlen(IFA_IN6(ifa), dst);
2213                                 if (tlen > blen) {
2214                                         blen = tlen;
2215                                         besta = (struct in6_ifaddr *)ifa;
2216                                 }
2217                         } else
2218                                 besta = (struct in6_ifaddr *)ifa;
2219                 }
2220         }
2221         if (besta)
2222                 return(besta);
2223
2224         TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list)
2225         {
2226                 if (ifa->ifa_addr->sa_family != AF_INET6)
2227                         continue;
2228                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_ANYCAST)
2229                         continue; /* XXX: is there any case to allow anycast? */
2230                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_NOTREADY)
2231                         continue; /* don't use this interface */
2232                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DETACHED)
2233                         continue;
2234                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DEPRECATED) {
2235                         if (ip6_use_deprecated)
2236                                 dep[1] = (struct in6_ifaddr *)ifa;
2237                         continue;
2238                 }
2239
2240                 return (struct in6_ifaddr *)ifa;
2241         }
2242
2243         /* use the last-resort values, that are, deprecated addresses */
2244         if (dep[0])
2245                 return dep[0];
2246         if (dep[1])
2247                 return dep[1];
2248
2249         return NULL;
2250 }
2251
2252 /*
2253  * perform DAD when interface becomes IFF_UP.
2254  */
2255 void
2256 in6_if_up(struct ifnet *ifp)
2257 {
2258         struct ifaddr *ifa;
2259         struct in6_ifaddr *ia;
2260         int dad_delay;          /* delay ticks before DAD output */
2261
2262         /*
2263          * special cases, like 6to4, are handled in in6_ifattach
2264          */
2265         in6_ifattach(ifp, NULL);
2266
2267         dad_delay = 0;
2268         TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list)
2269         {
2270                 if (ifa->ifa_addr->sa_family != AF_INET6)
2271                         continue;
2272                 ia = (struct in6_ifaddr *)ifa;
2273                 if (ia->ia6_flags & IN6_IFF_TENTATIVE)
2274                         nd6_dad_start(ifa, &dad_delay);
2275         }
2276 }
2277
2278 int
2279 in6if_do_dad(struct ifnet *ifp)
2280 {
2281         if ((ifp->if_flags & IFF_LOOPBACK) != 0)
2282                 return(0);
2283
2284         switch (ifp->if_type) {
2285 #ifdef IFT_DUMMY
2286         case IFT_DUMMY:
2287 #endif
2288         case IFT_FAITH:
2289                 /*
2290                  * These interfaces do not have the IFF_LOOPBACK flag,
2291                  * but loop packets back.  We do not have to do DAD on such
2292                  * interfaces.  We should even omit it, because loop-backed
2293                  * NS would confuse the DAD procedure.
2294                  */
2295                 return(0);
2296         default:
2297                 /*
2298                  * Our DAD routine requires the interface up and running.
2299                  * However, some interfaces can be up before the RUNNING
2300                  * status.  Additionaly, users may try to assign addresses
2301                  * before the interface becomes up (or running).
2302                  * We simply skip DAD in such a case as a work around.
2303                  * XXX: we should rather mark "tentative" on such addresses,
2304                  * and do DAD after the interface becomes ready.
2305                  */
2306                 if ((ifp->if_flags & (IFF_UP|IFF_RUNNING)) !=
2307                     (IFF_UP|IFF_RUNNING))
2308                         return(0);
2309
2310                 return(1);
2311         }
2312 }
2313
2314 /*
2315  * Calculate max IPv6 MTU through all the interfaces and store it
2316  * to in6_maxmtu.
2317  */
2318 void
2319 in6_setmaxmtu(void)
2320 {
2321         unsigned long maxmtu = 0;
2322         struct ifnet *ifp;
2323
2324         for (ifp = TAILQ_FIRST(&ifnet); ifp; ifp = TAILQ_NEXT(ifp, if_list))
2325         {
2326                 if ((ifp->if_flags & IFF_LOOPBACK) == 0 &&
2327                     ND_IFINFO(ifp)->linkmtu > maxmtu)
2328                         maxmtu =  ND_IFINFO(ifp)->linkmtu;
2329         }
2330         if (maxmtu)     /* update only when maxmtu is positive */
2331                 in6_maxmtu = maxmtu;
2332 }
2333
2334 void *
2335 in6_domifattach(struct ifnet *ifp)
2336 {
2337         struct in6_ifextra *ext;
2338
2339         ext = (struct in6_ifextra *)malloc(sizeof(*ext), M_IFADDR, M_WAITOK);
2340         bzero(ext, sizeof(*ext));
2341
2342         ext->in6_ifstat = (struct in6_ifstat *)malloc(sizeof(struct in6_ifstat),
2343                 M_IFADDR, M_WAITOK);
2344         bzero(ext->in6_ifstat, sizeof(*ext->in6_ifstat));
2345
2346         ext->icmp6_ifstat =
2347                 (struct icmp6_ifstat *)malloc(sizeof(struct icmp6_ifstat),
2348                         M_IFADDR, M_WAITOK);
2349         bzero(ext->icmp6_ifstat, sizeof(*ext->icmp6_ifstat));
2350
2351         ext->nd_ifinfo = nd6_ifattach(ifp);
2352         ext->scope6_id = scope6_ifattach(ifp);
2353         return ext;
2354 }
2355
2356 void
2357 in6_domifdetach(struct ifnet *ifp, void *aux)
2358 {
2359         struct in6_ifextra *ext = (struct in6_ifextra *)aux;
2360         scope6_ifdetach(ext->scope6_id);
2361         nd6_ifdetach(ext->nd_ifinfo);
2362         free(ext->in6_ifstat, M_IFADDR);
2363         free(ext->icmp6_ifstat, M_IFADDR);
2364         free(ext, M_IFADDR);
2365 }
2366
2367 /*
2368  * Convert sockaddr_in6 to sockaddr_in.  Original sockaddr_in6 must be
2369  * v4 mapped addr or v4 compat addr
2370  */
2371 void
2372 in6_sin6_2_sin(struct sockaddr_in *sin, struct sockaddr_in6 *sin6)
2373 {
2374         bzero(sin, sizeof(*sin));
2375         sin->sin_len = sizeof(struct sockaddr_in);
2376         sin->sin_family = AF_INET;
2377         sin->sin_port = sin6->sin6_port;
2378         sin->sin_addr.s_addr = sin6->sin6_addr.s6_addr32[3];    
2379 }
2380
2381 /* Convert sockaddr_in to sockaddr_in6 in v4 mapped addr format. */
2382 void
2383 in6_sin_2_v4mapsin6(struct sockaddr_in *sin, struct sockaddr_in6 *sin6)
2384 {
2385         bzero(sin6, sizeof(*sin6));
2386         sin6->sin6_len = sizeof(struct sockaddr_in6);
2387         sin6->sin6_family = AF_INET6;
2388         sin6->sin6_port = sin->sin_port;
2389         sin6->sin6_addr.s6_addr32[0] = 0;
2390         sin6->sin6_addr.s6_addr32[1] = 0;
2391         sin6->sin6_addr.s6_addr32[2] = IPV6_ADDR_INT32_SMP;
2392         sin6->sin6_addr.s6_addr32[3] = sin->sin_addr.s_addr;
2393 }
2394
2395 /* Convert sockaddr_in6 into sockaddr_in. */
2396 void
2397 in6_sin6_2_sin_in_sock(struct sockaddr *nam)
2398 {
2399         struct sockaddr_in *sin_p;
2400         struct sockaddr_in6 sin6;
2401
2402         /*
2403          * Save original sockaddr_in6 addr and convert it
2404          * to sockaddr_in.
2405          */
2406         sin6 = *(struct sockaddr_in6 *)nam;
2407         sin_p = (struct sockaddr_in *)nam;
2408         in6_sin6_2_sin(sin_p, &sin6);
2409 }
2410
2411 /* Convert sockaddr_in into sockaddr_in6 in v4 mapped addr format. */
2412 void
2413 in6_sin_2_v4mapsin6_in_sock(struct sockaddr **nam)
2414 {
2415         struct sockaddr_in *sin_p;
2416         struct sockaddr_in6 *sin6_p;
2417
2418         MALLOC(sin6_p, struct sockaddr_in6 *, sizeof *sin6_p, M_SONAME,
2419                M_WAITOK);
2420         sin_p = (struct sockaddr_in *)*nam;
2421         in6_sin_2_v4mapsin6(sin_p, sin6_p);
2422         FREE(*nam, M_SONAME);
2423         *nam = (struct sockaddr *)sin6_p;
2424 }