Explicitly set a compiler instead of defaulting to CCVER.
[dragonfly.git] / sys / netinet6 / in6_src.c
1 /*      $FreeBSD: src/sys/netinet6/in6_src.c,v 1.1.2.3 2002/02/26 18:02:06 ume Exp $    */
2 /*      $DragonFly: src/sys/netinet6/in6_src.c,v 1.13 2006/12/29 18:02:56 victor Exp $  */
3 /*      $KAME: in6_src.c,v 1.37 2001/03/29 05:34:31 itojun 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_pcb.c    8.2 (Berkeley) 1/4/94
67  */
68
69 #include "opt_inet.h"
70 #include "opt_inet6.h"
71
72 #include <sys/param.h>
73 #include <sys/systm.h>
74 #include <sys/jail.h>
75 #include <sys/kernel.h>
76 #include <sys/malloc.h>
77 #include <sys/mbuf.h>
78 #include <sys/protosw.h>
79 #include <sys/socket.h>
80 #include <sys/socketvar.h>
81 #include <sys/sockio.h>
82 #include <sys/sysctl.h>
83 #include <sys/errno.h>
84 #include <sys/time.h>
85 #include <sys/proc.h>
86
87 #include <net/if.h>
88 #include <net/route.h>
89
90 #include <netinet/in.h>
91 #include <netinet/in_var.h>
92 #include <netinet/in_systm.h>
93 #include <netinet/ip.h>
94 #include <netinet/in_pcb.h>
95 #include <netinet6/in6_var.h>
96 #include <netinet/ip6.h>
97 #include <netinet6/in6_pcb.h>
98 #include <netinet6/ip6_var.h>
99 #include <netinet6/nd6.h>
100 #ifdef ENABLE_DEFAULT_SCOPE
101 #include <netinet6/scope6_var.h>
102 #endif
103
104 #include <net/net_osdep.h>
105
106 #include "use_loop.h"
107
108 #define ADDR_LABEL_NOTAPP (-1)
109 struct in6_addrpolicy defaultaddrpolicy;
110
111 static void     init_policy_queue(void);
112 static int      add_addrsel_policyent(struct in6_addrpolicy *);
113 static int      delete_addrsel_policyent(struct in6_addrpolicy *);
114 static int      walk_addrsel_policy(int (*)(struct in6_addrpolicy *, void *),
115                                     void *);
116 static int      dump_addrsel_policyent(struct in6_addrpolicy *, void *);
117
118
119 /*
120  * Return an IPv6 address, which is the most appropriate for a given
121  * destination and user specified options.
122  * If necessary, this function lookups the routing table and returns
123  * an entry to the caller for later use.
124  */
125 struct in6_addr *
126 in6_selectsrc(struct sockaddr_in6 *dstsock, struct ip6_pktopts *opts,
127               struct ip6_moptions *mopts, struct route_in6 *ro,
128               struct in6_addr *laddr, int *errorp, struct thread *td)
129 {
130         struct sockaddr_in6 jsin6;
131         struct ucred *cred = NULL;
132         struct in6_addr *dst;
133         struct in6_ifaddr *ia6 = 0;
134         struct in6_pktinfo *pi = NULL;
135         int jailed = 0;
136
137         if (td && td->td_proc && td->td_proc->p_ucred)
138                 cred = td->td_proc->p_ucred;
139         if (cred && cred->cr_prison)
140                 jailed = 1;
141         jsin6.sin6_family = AF_INET6;
142         dst = &dstsock->sin6_addr;
143         *errorp = 0;
144
145         /*
146          * If the source address is explicitly specified by the caller,
147          * use it.
148          */
149         if (opts && (pi = opts->ip6po_pktinfo) &&
150             !IN6_IS_ADDR_UNSPECIFIED(&pi->ipi6_addr)) {
151                 jsin6.sin6_addr = pi->ipi6_addr;
152                 if (jailed && !jailed_ip(cred->cr_prison,
153                     (struct sockaddr *)&jsin6)) {
154                         return(0);
155                 } else {
156                         return (&pi->ipi6_addr);
157                 }
158         }
159
160         /*
161          * If the source address is not specified but the socket(if any)
162          * is already bound, use the bound address.
163          */
164         if (laddr && !IN6_IS_ADDR_UNSPECIFIED(laddr)) {
165                 jsin6.sin6_addr = *laddr;
166                 if (jailed && !jailed_ip(cred->cr_prison,
167                     (struct sockaddr *)&jsin6)) {
168                         return(0);
169                 } else {
170                         return (laddr);
171                 }
172         }
173
174         /*
175          * If the caller doesn't specify the source address but
176          * the outgoing interface, use an address associated with
177          * the interface.
178          */
179         if (pi && pi->ipi6_ifindex) {
180                 /* XXX boundary check is assumed to be already done. */
181                 ia6 = in6_ifawithscope(ifindex2ifnet[pi->ipi6_ifindex],
182                                        dst);
183
184                 if (ia6 && jailed) {
185                         jsin6.sin6_addr = (&ia6->ia_addr)->sin6_addr;
186                         if (!jailed_ip(cred->cr_prison,
187                                 (struct sockaddr *)&jsin6))
188                                 ia6 = 0;
189                 }
190
191                 if (ia6 == 0) {
192                         *errorp = EADDRNOTAVAIL;
193                         return (0);
194                 }
195                 return (&satosin6(&ia6->ia_addr)->sin6_addr);
196         }
197
198         /*
199          * If the destination address is a link-local unicast address or
200          * a multicast address, and if the outgoing interface is specified
201          * by the sin6_scope_id filed, use an address associated with the
202          * interface.
203          * XXX: We're now trying to define more specific semantics of
204          *      sin6_scope_id field, so this part will be rewritten in
205          *      the near future.
206          */
207         if ((IN6_IS_ADDR_LINKLOCAL(dst) || IN6_IS_ADDR_MULTICAST(dst)) &&
208             dstsock->sin6_scope_id) {
209                 /*
210                  * I'm not sure if boundary check for scope_id is done
211                  * somewhere...
212                  */
213                 if (dstsock->sin6_scope_id < 0 ||
214                     if_index < dstsock->sin6_scope_id) {
215                         *errorp = ENXIO; /* XXX: better error? */
216                         return (0);
217                 }
218                 ia6 = in6_ifawithscope(ifindex2ifnet[dstsock->sin6_scope_id],
219                                        dst);
220
221                 if (ia6 && jailed) {
222                         jsin6.sin6_addr = (&ia6->ia_addr)->sin6_addr;
223                         if (!jailed_ip(cred->cr_prison,
224                                 (struct sockaddr *)&jsin6))
225                                 ia6 = 0;
226                 }
227
228                 if (ia6 == 0) {
229                         *errorp = EADDRNOTAVAIL;
230                         return (0);
231                 }
232                 return (&satosin6(&ia6->ia_addr)->sin6_addr);
233         }
234
235         /*
236          * If the destination address is a multicast address and
237          * the outgoing interface for the address is specified
238          * by the caller, use an address associated with the interface.
239          * There is a sanity check here; if the destination has node-local
240          * scope, the outgoing interfacde should be a loopback address.
241          * Even if the outgoing interface is not specified, we also
242          * choose a loopback interface as the outgoing interface.
243          */
244         if (!jailed && IN6_IS_ADDR_MULTICAST(dst)) {
245                 struct ifnet *ifp = mopts ? mopts->im6o_multicast_ifp : NULL;
246
247                 if (ifp == NULL && IN6_IS_ADDR_MC_NODELOCAL(dst)) {
248                         ifp = &loif[0];
249                 }
250
251                 if (ifp) {
252                         ia6 = in6_ifawithscope(ifp, dst);
253                         if (ia6 == 0) {
254                                 *errorp = EADDRNOTAVAIL;
255                                 return (0);
256                         }
257                         return (&satosin6(&ia6->ia_addr)->sin6_addr);
258                 }
259         }
260
261         /*
262          * If the next hop address for the packet is specified
263          * by caller, use an address associated with the route
264          * to the next hop.
265          */
266         {
267                 struct sockaddr_in6 *sin6_next;
268                 struct rtentry *rt;
269
270                 if (opts && opts->ip6po_nexthop) {
271                         sin6_next = satosin6(opts->ip6po_nexthop);
272                         rt = nd6_lookup(&sin6_next->sin6_addr, 1, NULL);
273                         if (rt) {
274                                 ia6 = in6_ifawithscope(rt->rt_ifp, dst);
275                                 if (ia6 == 0)
276                                         ia6 = ifatoia6(rt->rt_ifa);
277                         }
278                         if (ia6 && jailed) {
279                                 jsin6.sin6_addr = (&ia6->ia_addr)->sin6_addr;
280                                 if (!jailed_ip(cred->cr_prison,
281                                         (struct sockaddr *)&jsin6))
282                                         ia6 = 0;
283                         }
284
285                         if (ia6 == 0) {
286                                 *errorp = EADDRNOTAVAIL;
287                                 return (0);
288                         }
289                         return (&satosin6(&ia6->ia_addr)->sin6_addr);
290                 }
291         }
292
293         /*
294          * If route is known or can be allocated now,
295          * our src addr is taken from the i/f, else punt.
296          */
297         if (ro) {
298                 if (ro->ro_rt &&
299                     (!(ro->ro_rt->rt_flags & RTF_UP) ||
300                      satosin6(&ro->ro_dst)->sin6_family != AF_INET6 ||
301                      !IN6_ARE_ADDR_EQUAL(&satosin6(&ro->ro_dst)->sin6_addr,
302                                          dst))) {
303                         RTFREE(ro->ro_rt);
304                         ro->ro_rt = NULL;
305                 }
306                 if (ro->ro_rt == NULL || ro->ro_rt->rt_ifp == NULL) {
307                         struct sockaddr_in6 *sa6;
308
309                         /* No route yet, so try to acquire one */
310                         bzero(&ro->ro_dst, sizeof(struct sockaddr_in6));
311                         sa6 = &ro->ro_dst;
312                         sa6->sin6_family = AF_INET6;
313                         sa6->sin6_len = sizeof(struct sockaddr_in6);
314                         sa6->sin6_addr = *dst;
315                         sa6->sin6_scope_id = dstsock->sin6_scope_id;
316                         if (!jailed && IN6_IS_ADDR_MULTICAST(dst)) {
317                                 ro->ro_rt =
318                                   rtpurelookup((struct sockaddr *)&ro->ro_dst);
319                         } else {
320                                 rtalloc((struct route *)ro);
321                         }
322                 }
323
324                 /*
325                  * in_pcbconnect() checks out IFF_LOOPBACK to skip using
326                  * the address. But we don't know why it does so.
327                  * It is necessary to ensure the scope even for lo0
328                  * so doesn't check out IFF_LOOPBACK.
329                  */
330
331                 if (ro->ro_rt) {
332                         ia6 = in6_ifawithscope(ro->ro_rt->rt_ifa->ifa_ifp, dst);
333                         if (ia6 && jailed) {
334                                 jsin6.sin6_addr = (&ia6->ia_addr)->sin6_addr;
335                                 if (!jailed_ip(cred->cr_prison,
336                                         (struct sockaddr *)&jsin6))
337                                         ia6 = 0;
338                         }
339
340                         if (ia6 == 0) /* xxx scope error ?*/
341                                 ia6 = ifatoia6(ro->ro_rt->rt_ifa);
342
343                         if (ia6 && jailed) {
344                                 jsin6.sin6_addr = (&ia6->ia_addr)->sin6_addr;
345                                 if (!jailed_ip(cred->cr_prison,
346                                         (struct sockaddr *)&jsin6))
347                                         ia6 = 0;
348                         }
349                 }
350 #if 0
351                 /*
352                  * xxx The followings are necessary? (kazu)
353                  * I don't think so.
354                  * It's for SO_DONTROUTE option in IPv4.(jinmei)
355                  */
356                 if (ia6 == 0) {
357                         struct sockaddr_in6 sin6 = {sizeof(sin6), AF_INET6, 0};
358
359                         sin6->sin6_addr = *dst;
360
361                         ia6 = ifatoia6(ifa_ifwithdstaddr(sin6tosa(&sin6)));
362                         if (ia6 == 0)
363                                 ia6 = ifatoia6(ifa_ifwithnet(sin6tosa(&sin6)));
364                         if (ia6 == 0)
365                                 return (0);
366                         return (&satosin6(&ia6->ia_addr)->sin6_addr);
367                 }
368 #endif /* 0 */
369                 if (ia6 == 0) {
370                         *errorp = EHOSTUNREACH; /* no route */
371                         return (0);
372                 }
373                 return (&satosin6(&ia6->ia_addr)->sin6_addr);
374         }
375
376         *errorp = EADDRNOTAVAIL;
377         return (0);
378 }
379
380 /*
381  * Default hop limit selection. The precedence is as follows:
382  * 1. Hoplimit value specified via ioctl.
383  * 2. (If the outgoing interface is detected) the current
384  *     hop limit of the interface specified by router advertisement.
385  * 3. The system default hoplimit.
386 */
387 int
388 in6_selecthlim(struct in6pcb *in6p, struct ifnet *ifp)
389 {
390         if (in6p && in6p->in6p_hops >= 0)
391                 return (in6p->in6p_hops);
392         else if (ifp)
393                 return (ND_IFINFO(ifp)->chlim);
394         else
395                 return (ip6_defhlim);
396 }
397
398 /*
399  * XXX: this is borrowed from in6_pcbbind(). If possible, we should
400  * share this function by all *bsd*...
401  */
402 int
403 in6_pcbsetport(struct in6_addr *laddr, struct inpcb *inp, struct thread *td)
404 {
405         struct socket *so = inp->inp_socket;
406         u_int16_t lport = 0, first, last, *lastport;
407         int count, error = 0, wild = 0;
408         struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
409         struct ucred *cred = NULL;
410
411         /* XXX: this is redundant when called from in6_pcbbind */
412         if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) == 0)
413                 wild = INPLOOKUP_WILDCARD;
414         if (td->td_proc && td->td_proc->p_ucred)
415                 cred = td->td_proc->p_ucred;
416
417         inp->inp_flags |= INP_ANONPORT;
418
419         if (inp->inp_flags & INP_HIGHPORT) {
420                 first = ipport_hifirstauto;     /* sysctl */
421                 last  = ipport_hilastauto;
422                 lastport = &pcbinfo->lasthi;
423         } else if (inp->inp_flags & INP_LOWPORT) {
424                 if ((error = suser(td)) != 0)
425                         return error;
426                 first = ipport_lowfirstauto;    /* 1023 */
427                 last  = ipport_lowlastauto;     /* 600 */
428                 lastport = &pcbinfo->lastlow;
429         } else {
430                 first = ipport_firstauto;       /* sysctl */
431                 last  = ipport_lastauto;
432                 lastport = &pcbinfo->lastport;
433         }
434         /*
435          * Simple check to ensure all ports are not used up causing
436          * a deadlock here.
437          *
438          * We split the two cases (up and down) so that the direction
439          * is not being tested on each round of the loop.
440          */
441         if (first > last) {
442                 /*
443                  * counting down
444                  */
445                 count = first - last;
446
447                 do {
448                         if (count-- < 0) {      /* completely used? */
449                                 /*
450                                  * Undo any address bind that may have
451                                  * occurred above.
452                                  */
453                                 inp->in6p_laddr = kin6addr_any;
454                                 return (EAGAIN);
455                         }
456                         --*lastport;
457                         if (*lastport > first || *lastport < last)
458                                 *lastport = first;
459                         lport = htons(*lastport);
460                 } while (in6_pcblookup_local(pcbinfo, &inp->in6p_laddr,
461                          lport, wild, cred));
462         } else {
463                 /*
464                  * counting up
465                  */
466                 count = last - first;
467
468                 do {
469                         if (count-- < 0) {      /* completely used? */
470                                 /*
471                                  * Undo any address bind that may have
472                                  * occurred above.
473                                  */
474                                 inp->in6p_laddr = kin6addr_any;
475                                 return (EAGAIN);
476                         }
477                         ++*lastport;
478                         if (*lastport < first || *lastport > last)
479                                 *lastport = first;
480                         lport = htons(*lastport);
481                 } while (in6_pcblookup_local(pcbinfo, &inp->in6p_laddr,
482                          lport, wild, cred));
483         }
484
485         inp->inp_lport = lport;
486         if (in_pcbinsporthash(inp) != 0) {
487                 inp->in6p_laddr = kin6addr_any;
488                 inp->inp_lport = 0;
489                 return (EAGAIN);
490         }
491
492         return (0);
493 }
494
495 /*
496  * generate kernel-internal form (scopeid embedded into s6_addr16[1]).
497  * If the address scope of is link-local, embed the interface index in the
498  * address.  The routine determines our precedence
499  * between advanced API scope/interface specification and basic API
500  * specification.
501  *
502  * this function should be nuked in the future, when we get rid of
503  * embedded scopeid thing.
504  *
505  * XXX actually, it is over-specification to return ifp against sin6_scope_id.
506  * there can be multiple interfaces that belong to a particular scope zone
507  * (in specification, we have 1:N mapping between a scope zone and interfaces).
508  * we may want to change the function to return something other than ifp.
509  */
510 int
511 in6_embedscope(struct in6_addr *in6,
512                const struct sockaddr_in6 *sin6,
513 #ifdef HAVE_NRL_INPCB
514                struct inpcb *in6p,
515 #define in6p_outputopts inp_outputopts6
516 #define in6p_moptions   inp_moptions6
517 #else
518                struct in6pcb *in6p,
519 #endif
520                struct ifnet **ifpp)
521 {
522         struct ifnet *ifp = NULL;
523         u_int32_t scopeid;
524
525         *in6 = sin6->sin6_addr;
526         scopeid = sin6->sin6_scope_id;
527         if (ifpp)
528                 *ifpp = NULL;
529
530         /*
531          * don't try to read sin6->sin6_addr beyond here, since the caller may
532          * ask us to overwrite existing sockaddr_in6
533          */
534
535 #ifdef ENABLE_DEFAULT_SCOPE
536         if (scopeid == 0)
537                 scopeid = scope6_addr2default(in6);
538 #endif
539
540         if (IN6_IS_SCOPE_LINKLOCAL(in6)) {
541                 struct in6_pktinfo *pi;
542
543                 /*
544                  * KAME assumption: link id == interface id
545                  */
546
547                 if (in6p && in6p->in6p_outputopts &&
548                     (pi = in6p->in6p_outputopts->ip6po_pktinfo) &&
549                     pi->ipi6_ifindex) {
550                         ifp = ifindex2ifnet[pi->ipi6_ifindex];
551                         in6->s6_addr16[1] = htons(pi->ipi6_ifindex);
552                 } else if (in6p && IN6_IS_ADDR_MULTICAST(in6) &&
553                            in6p->in6p_moptions &&
554                            in6p->in6p_moptions->im6o_multicast_ifp) {
555                         ifp = in6p->in6p_moptions->im6o_multicast_ifp;
556                         in6->s6_addr16[1] = htons(ifp->if_index);
557                 } else if (scopeid) {
558                         /* boundary check */
559                         if (scopeid < 0 || if_index < scopeid)
560                                 return ENXIO;  /* XXX EINVAL? */
561                         ifp = ifindex2ifnet[scopeid];
562                         /*XXX assignment to 16bit from 32bit variable */
563                         in6->s6_addr16[1] = htons(scopeid & 0xffff);
564                 }
565
566                 if (ifpp)
567                         *ifpp = ifp;
568         }
569
570         return 0;
571 }
572 #ifdef HAVE_NRL_INPCB
573 #undef in6p_outputopts
574 #undef in6p_moptions
575 #endif
576
577 /*
578  * generate standard sockaddr_in6 from embedded form.
579  * touches sin6_addr and sin6_scope_id only.
580  *
581  * this function should be nuked in the future, when we get rid of
582  * embedded scopeid thing.
583  */
584 int
585 in6_recoverscope(struct sockaddr_in6 *sin6, const struct in6_addr *in6,
586                  struct ifnet *ifp)
587 {
588         u_int32_t scopeid;
589
590         sin6->sin6_addr = *in6;
591
592         /*
593          * don't try to read *in6 beyond here, since the caller may
594          * ask us to overwrite existing sockaddr_in6
595          */
596
597         sin6->sin6_scope_id = 0;
598         if (IN6_IS_SCOPE_LINKLOCAL(in6)) {
599                 /*
600                  * KAME assumption: link id == interface id
601                  */
602                 scopeid = ntohs(sin6->sin6_addr.s6_addr16[1]);
603                 if (scopeid) {
604                         /* sanity check */
605                         if (scopeid < 0 || if_index < scopeid)
606                                 return ENXIO;
607                         if (ifp && ifp->if_index != scopeid)
608                                 return ENXIO;
609                         sin6->sin6_addr.s6_addr16[1] = 0;
610                         sin6->sin6_scope_id = scopeid;
611                 }
612         }
613
614         return 0;
615 }
616
617 /*
618  * just clear the embedded scope identifer.
619  * XXX: currently used for bsdi4 only as a supplement function.
620  */
621 void
622 in6_clearscope(struct in6_addr *addr)
623 {
624         if (IN6_IS_SCOPE_LINKLOCAL(addr))
625                 addr->s6_addr16[1] = 0;
626 }
627
628 void
629 addrsel_policy_init(void)
630 {
631
632         init_policy_queue();
633
634         /* initialize the "last resort" policy */
635         bzero(&defaultaddrpolicy, sizeof(defaultaddrpolicy));
636         defaultaddrpolicy.label = ADDR_LABEL_NOTAPP;
637 }
638
639 /*
640  * Subroutines to manage the address selection policy table via sysctl.
641  */
642 struct walkarg {
643         struct sysctl_req *w_req;
644 };
645
646 static int in6_src_sysctl(SYSCTL_HANDLER_ARGS);
647 SYSCTL_DECL(_net_inet6_ip6);
648 SYSCTL_NODE(_net_inet6_ip6, IPV6CTL_ADDRCTLPOLICY, addrctlpolicy,
649         CTLFLAG_RD, in6_src_sysctl, "");
650
651 static int
652 in6_src_sysctl(SYSCTL_HANDLER_ARGS)
653 {
654         struct walkarg w;
655
656         if (req->newptr)
657                 return EPERM;
658
659         bzero(&w, sizeof(w));
660         w.w_req = req;
661
662         return (walk_addrsel_policy(dump_addrsel_policyent, &w));
663 }
664
665 int
666 in6_src_ioctl(u_long cmd, caddr_t data)
667 {
668         int i;
669         struct in6_addrpolicy ent0;
670
671         if (cmd != SIOCAADDRCTL_POLICY && cmd != SIOCDADDRCTL_POLICY)
672                 return (EOPNOTSUPP); /* check for safety */
673
674         ent0 = *(struct in6_addrpolicy *)data;
675
676         if (ent0.label == ADDR_LABEL_NOTAPP)
677                 return (EINVAL);
678         /* check if the prefix mask is consecutive. */
679         if (in6_mask2len(&ent0.addrmask.sin6_addr, NULL) < 0)
680                 return (EINVAL);
681         /* clear trailing garbages (if any) of the prefix address. */
682         for (i = 0; i < 4; i++) {
683                 ent0.addr.sin6_addr.s6_addr32[i] &=
684                         ent0.addrmask.sin6_addr.s6_addr32[i];
685         }
686         ent0.use = 0;
687
688         switch (cmd) {
689         case SIOCAADDRCTL_POLICY:
690                 return (add_addrsel_policyent(&ent0));
691         case SIOCDADDRCTL_POLICY:
692                 return (delete_addrsel_policyent(&ent0));
693         }
694
695         return (0);             /* XXX: compromise compilers */
696 }
697
698 /*
699  * The followings are implementation of the policy table using a
700  * simple tail queue.
701  * XXX such details should be hidden.
702  * XXX implementation using binary tree should be more efficient.
703  */
704 struct addrsel_policyent {
705         TAILQ_ENTRY(addrsel_policyent) ape_entry;
706         struct in6_addrpolicy ape_policy;
707 };
708
709 TAILQ_HEAD(addrsel_policyhead, addrsel_policyent);
710
711 struct addrsel_policyhead addrsel_policytab;
712
713 static void
714 init_policy_queue(void)
715 {
716         TAILQ_INIT(&addrsel_policytab);
717 }
718
719 static int
720 add_addrsel_policyent(struct in6_addrpolicy *newpolicy)
721 {
722         struct addrsel_policyent *new, *pol;
723
724         /* duplication check */
725         for (pol = TAILQ_FIRST(&addrsel_policytab); pol;
726              pol = TAILQ_NEXT(pol, ape_entry)) {
727                 if (SA6_ARE_ADDR_EQUAL(&newpolicy->addr,
728                                        &pol->ape_policy.addr) &&
729                     SA6_ARE_ADDR_EQUAL(&newpolicy->addrmask,
730                                        &pol->ape_policy.addrmask)) {
731                         return (EEXIST);        /* or override it? */
732                 }
733         }
734
735         new = kmalloc(sizeof(*new), M_IFADDR, M_WAITOK | M_ZERO);
736
737         /* XXX: should validate entry */
738         new->ape_policy = *newpolicy;
739
740         TAILQ_INSERT_TAIL(&addrsel_policytab, new, ape_entry);
741
742         return (0);
743 }
744
745 static int
746 delete_addrsel_policyent(struct in6_addrpolicy *key)
747 {
748         struct addrsel_policyent *pol;
749
750         /* search for the entry in the table */
751         for (pol = TAILQ_FIRST(&addrsel_policytab); pol;
752              pol = TAILQ_NEXT(pol, ape_entry)) {
753                 if (SA6_ARE_ADDR_EQUAL(&key->addr, &pol->ape_policy.addr) &&
754                     SA6_ARE_ADDR_EQUAL(&key->addrmask,
755                                        &pol->ape_policy.addrmask)) {
756                         break;
757                 }
758         }
759         if (pol == NULL)
760                 return (ESRCH);
761
762         TAILQ_REMOVE(&addrsel_policytab, pol, ape_entry);
763         kfree(pol, M_IFADDR);
764
765         return (0);
766 }
767
768 static int
769 walk_addrsel_policy(int(*callback)(struct in6_addrpolicy *, void *), void *w)
770 {
771         struct addrsel_policyent *pol;
772         int error = 0;
773
774         for (pol = TAILQ_FIRST(&addrsel_policytab); pol;
775              pol = TAILQ_NEXT(pol, ape_entry)) {
776                 if ((error = (*callback)(&pol->ape_policy, w)) != 0)
777                         return (error);
778         }
779
780         return (error);
781 }
782
783 static int
784 dump_addrsel_policyent(struct in6_addrpolicy *pol, void *arg)
785 {
786         int error = 0;
787         struct walkarg *w = arg;
788
789         error = SYSCTL_OUT(w->w_req, pol, sizeof(*pol));
790
791         return (error);
792 }