xref: /dragonfly/lib/libc/net/name6.c (revision 3f7b72606e8fadb0b2e9e32302c89298c107534b)
1 /*        $KAME: name6.c,v 1.25 2000/06/26 16:44:40 itojun Exp $      */
2 
3 /*
4  * Copyright (C) 1995, 1996, 1997, 1998, and 1999 WIDE Project.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the project nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 /*
32  * ++Copyright++ 1985, 1988, 1993
33  * -
34  * Copyright (c) 1985, 1988, 1993
35  *    The Regents of the University of California.  All rights reserved.
36  *
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions
39  * are met:
40  * 1. Redistributions of source code must retain the above copyright
41  *    notice, this list of conditions and the following disclaimer.
42  * 2. Redistributions in binary form must reproduce the above copyright
43  *    notice, this list of conditions and the following disclaimer in the
44  *    documentation and/or other materials provided with the distribution.
45  * 3. Neither the name of the University nor the names of its contributors
46  *    may be used to endorse or promote products derived from this software
47  *    without specific prior written permission.
48  *
49  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
50  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
51  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
52  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
53  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
54  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
55  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
56  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
57  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
58  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
59  * SUCH DAMAGE.
60  * -
61  * Portions Copyright (c) 1993 by Digital Equipment Corporation.
62  *
63  * Permission to use, copy, modify, and distribute this software for any
64  * purpose with or without fee is hereby granted, provided that the above
65  * copyright notice and this permission notice appear in all copies, and that
66  * the name of Digital Equipment Corporation not be used in advertising or
67  * publicity pertaining to distribution of the document or software without
68  * specific, written prior permission.
69  *
70  * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
71  * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
72  * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
73  * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
74  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
75  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
76  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
77  * SOFTWARE.
78  * -
79  * --Copyright--
80  *
81  * $FreeBSD: src/lib/libc/net/name6.c,v 1.62 2007/07/31 16:09:41 bushman Exp $
82  */
83 
84 /*
85  *        Atsushi Onoe <onoe@sm.sony.co.jp>
86  */
87 
88 #include "namespace.h"
89 #include <sys/param.h>
90 #include <sys/socket.h>
91 #include <sys/time.h>
92 #include <sys/queue.h>
93 #include <netinet/in.h>
94 #ifdef INET6
95 #include <net/if.h>
96 #include <net/if_var.h>
97 #include <sys/sysctl.h>
98 #include <sys/ioctl.h>
99 #include <netinet6/in6_var.h> /* XXX */
100 #endif
101 
102 #include <arpa/inet.h>
103 #include <arpa/nameser.h>
104 
105 #include <errno.h>
106 #include <netdb.h>
107 #include <resolv.h>
108 #include <stdio.h>
109 #include <stdlib.h>
110 #include <string.h>
111 #include <stdarg.h>
112 #include <nsswitch.h>
113 #include <unistd.h>
114 #include "un-namespace.h"
115 #include "netdb_private.h"
116 #include "res_private.h"
117 
118 #ifndef MAXALIASES
119 #define   MAXALIASES          10
120 #endif
121 #ifndef   MAXADDRS
122 #define   MAXADDRS  20
123 #endif
124 #ifndef MAXDNAME
125 #define   MAXDNAME  1025
126 #endif
127 
128 #ifdef INET6
129 #define   ADDRLEN(af)         ((af) == AF_INET6 ? sizeof(struct in6_addr) : \
130                                                       sizeof(struct in_addr))
131 #else
132 #define   ADDRLEN(af)         sizeof(struct in_addr)
133 #endif
134 
135 #define   MAPADDR(ab, ina) \
136 do {                                                                                      \
137           memcpy(&(ab)->map_inaddr, ina, sizeof(struct in_addr));               \
138           memset((ab)->map_zero, 0, sizeof((ab)->map_zero));                    \
139           memset((ab)->map_one, 0xff, sizeof((ab)->map_one));                   \
140 } while (0)
141 #define   MAPADDRENABLED(flags) \
142           (((flags) & AI_V4MAPPED) || \
143            (((flags) & AI_V4MAPPED_CFG)))
144 
145 union inx_addr {
146           struct in_addr      in_addr;
147 #ifdef INET6
148           struct in6_addr     in6_addr;
149 #endif
150           struct {
151                     u_char    mau_zero[10];
152                     u_char    mau_one[2];
153                     struct in_addr mau_inaddr;
154           }                   map_addr_un;
155 #define   map_zero  map_addr_un.mau_zero
156 #define   map_one             map_addr_un.mau_one
157 #define   map_inaddr          map_addr_un.mau_inaddr
158 };
159 
160 struct policyqueue {
161           TAILQ_ENTRY(policyqueue) pc_entry;
162 #ifdef INET6
163           struct in6_addrpolicy pc_policy;
164 #endif
165 };
166 TAILQ_HEAD(policyhead, policyqueue);
167 
168 #define AIO_SRCFLAG_DEPRECATED          0x1
169 
170 struct hp_order {
171           union {
172                     struct sockaddr_storage aiou_ss;
173                     struct sockaddr aiou_sa;
174           } aio_src_un;
175 #define aio_srcsa aio_src_un.aiou_sa
176           u_int32_t aio_srcflag;
177           int aio_srcscope;
178           int aio_dstscope;
179           struct policyqueue *aio_srcpolicy;
180           struct policyqueue *aio_dstpolicy;
181           union {
182                     struct sockaddr_storage aiou_ss;
183                     struct sockaddr aiou_sa;
184           } aio_un;
185 #define aio_sa aio_un.aiou_sa
186           int aio_matchlen;
187           char *aio_h_addr;
188 };
189 
190 static struct hostent         *_hpcopy(struct hostent *, int *);
191 static struct hostent         *_hpaddr(int, const char *, void *, int *);
192 #ifdef INET6
193 static struct hostent         *_hpmerge(struct hostent *, struct hostent *, int *);
194 static struct hostent         *_hpmapv6(struct hostent *, int *);
195 #endif
196 static struct hostent         *_hpsort(struct hostent *, res_state);
197 
198 static struct hostent         *_hpreorder(struct hostent *);
199 static int                     get_addrselectpolicy(struct policyhead *);
200 static void                    free_addrselectpolicy(struct policyhead *);
201 static struct policyqueue *match_addrselectpolicy(struct sockaddr *,
202                                                               struct policyhead *);
203 static void                    set_source(struct hp_order *, struct policyhead *);
204 static int                     matchlen(struct sockaddr *, struct sockaddr *);
205 static int                     comp_dst(const void *, const void *);
206 static int                     gai_addr2scopetype(struct sockaddr *);
207 
208 /*
209  * Functions defined in RFC2553
210  *        getipnodebyname, getipnodebyaddr, freehostent
211  */
212 
213 struct hostent *
getipnodebyname(const char * name,int af,int flags,int * errp)214 getipnodebyname(const char *name, int af, int flags, int *errp)
215 {
216           struct hostent *hp;
217           union inx_addr addrbuf;
218           res_state statp;
219           u_long options;
220 
221           switch (af) {
222           case AF_INET:
223 #ifdef INET6
224           case AF_INET6:
225 #endif
226                     break;
227           default:
228                     *errp = NO_RECOVERY;
229                     return NULL;
230           }
231 
232           if (flags & AI_ADDRCONFIG) {
233                     int s;
234 
235                     if ((s = _socket(af, SOCK_DGRAM, 0)) < 0)
236                               return NULL;
237                     /*
238                      * TODO:
239                      * Note that implementation dependent test for address
240                      * configuration should be done everytime called
241                      * (or apropriate interval),
242                      * because addresses will be dynamically assigned or deleted.
243                      */
244                     _close(s);
245           }
246 
247 #ifdef INET6
248           /* special case for literal address */
249           if (inet_pton(AF_INET6, name, &addrbuf) == 1) {
250                     if (af != AF_INET6) {
251                               *errp = HOST_NOT_FOUND;
252                               return NULL;
253                     }
254                     return _hpaddr(af, name, &addrbuf, errp);
255           }
256 #endif
257           if (inet_aton(name, (struct in_addr *)&addrbuf) == 1) {
258                     if (af != AF_INET) {
259                               if (MAPADDRENABLED(flags)) {
260                                         MAPADDR(&addrbuf, &addrbuf.in_addr);
261                               } else {
262                                         *errp = HOST_NOT_FOUND;
263                                         return NULL;
264                               }
265                     }
266                     return _hpaddr(af, name, &addrbuf, errp);
267           }
268 
269 
270           statp = __res_state();
271           if ((statp->options & RES_INIT) == 0) {
272                     if (res_ninit(statp) < 0) {
273                               *errp = NETDB_INTERNAL;
274                               return NULL;
275                     }
276           }
277 
278           options = statp->options;
279           statp->options &= ~RES_USE_INET6;
280 
281           hp = gethostbyname2(name, af);
282           hp = _hpcopy(hp, errp);
283 
284 #ifdef INET6
285           if (af == AF_INET6 && ((flags & AI_ALL) || hp == NULL) &&
286               MAPADDRENABLED(flags)) {
287                     struct hostent *hp2 = gethostbyname2(name, AF_INET);
288                     if (hp == NULL)
289                               if (hp2 == NULL)
290                                         *errp = statp->res_h_errno;
291                               else
292                                         hp = _hpmapv6(hp2, errp);
293                     else {
294                               if (hp2 && strcmp(hp->h_name, hp2->h_name) == 0) {
295                                         struct hostent *hpb = hp;
296                                         hp = _hpmerge(hpb, hp2, errp);
297                                         freehostent(hpb);
298                               }
299                     }
300           }
301 #endif
302 
303           if (hp == NULL)
304                     *errp = statp->res_h_errno;
305 
306           statp->options = options;
307           return _hpreorder(_hpsort(hp, statp));
308 }
309 
310 struct hostent *
getipnodebyaddr(const void * src,size_t len,int af,int * errp)311 getipnodebyaddr(const void *src, size_t len, int af, int *errp)
312 {
313           struct hostent *hp;
314           res_state statp;
315           u_long options;
316 
317 #ifdef INET6
318           struct in6_addr addrbuf;
319 #else
320           struct in_addr addrbuf;
321 #endif
322 
323           switch (af) {
324           case AF_INET:
325                     if (len != sizeof(struct in_addr)) {
326                               *errp = NO_RECOVERY;
327                               return NULL;
328                     }
329                     if (rounddown2((long)src, sizeof(struct in_addr))) {
330                               memcpy(&addrbuf, src, len);
331                               src = &addrbuf;
332                     }
333                     if (((struct in_addr *)src)->s_addr == 0)
334                               return NULL;
335                     break;
336 #ifdef INET6
337           case AF_INET6:
338                     if (len != sizeof(struct in6_addr)) {
339                               *errp = NO_RECOVERY;
340                               return NULL;
341                     }
342                     if (rounddown2((long)src, sizeof(struct in6_addr) / 2)) {   /*XXX*/
343                               memcpy(&addrbuf, src, len);
344                               src = &addrbuf;
345                     }
346                     if (IN6_IS_ADDR_UNSPECIFIED((struct in6_addr *)src))
347                               return NULL;
348                     if (IN6_IS_ADDR_V4MAPPED((struct in6_addr *)src)
349                     ||  IN6_IS_ADDR_V4COMPAT((struct in6_addr *)src)) {
350                               src = (char *)src +
351                                   (sizeof(struct in6_addr) - sizeof(struct in_addr));
352                               af = AF_INET;
353                               len = sizeof(struct in_addr);
354                     }
355                     break;
356 #endif
357           default:
358                     *errp = NO_RECOVERY;
359                     return NULL;
360           }
361 
362           statp = __res_state();
363           if ((statp->options & RES_INIT) == 0) {
364                     if (res_ninit(statp) < 0) {
365                               RES_SET_H_ERRNO(statp, NETDB_INTERNAL);
366                               return NULL;
367                     }
368           }
369 
370           options = statp->options;
371           statp->options &= ~RES_USE_INET6;
372 
373           hp = gethostbyaddr(src, len, af);
374           if (hp == NULL)
375                     *errp = statp->res_h_errno;
376 
377           statp->options = options;
378           return (_hpcopy(hp, errp));
379 }
380 
381 void
freehostent(struct hostent * ptr)382 freehostent(struct hostent *ptr)
383 {
384           free(ptr);
385 }
386 
387 /*
388  * Private utility functions
389  */
390 
391 /*
392  * _hpcopy: allocate and copy hostent structure
393  */
394 static struct hostent *
_hpcopy(struct hostent * hp,int * errp)395 _hpcopy(struct hostent *hp, int *errp)
396 {
397           struct hostent *nhp;
398           char *cp, **pp;
399           int size, addrsize;
400           int nalias = 0, naddr = 0;
401           int al_off;
402           int i;
403 
404           if (hp == NULL)
405                     return hp;
406 
407           /* count size to be allocated */
408           size = sizeof(struct hostent);
409           if (hp->h_name != NULL)
410                     size += strlen(hp->h_name) + 1;
411           if ((pp = hp->h_aliases) != NULL) {
412                     for (i = 0; *pp != NULL; i++, pp++) {
413                               if (**pp != '\0') {
414                                         size += strlen(*pp) + 1;
415                                         nalias++;
416                               }
417                     }
418           }
419           /* adjust alignment */
420           size = ALIGN(size);
421           al_off = size;
422           size += sizeof(char *) * (nalias + 1);
423           addrsize = ALIGN(hp->h_length);
424           if ((pp = hp->h_addr_list) != NULL) {
425                     while (*pp++ != NULL)
426                               naddr++;
427           }
428           size += addrsize * naddr;
429           size += sizeof(char *) * (naddr + 1);
430 
431           /* copy */
432           if ((nhp = (struct hostent *)malloc(size)) == NULL) {
433                     *errp = TRY_AGAIN;
434                     return NULL;
435           }
436           cp = (char *)&nhp[1];
437           if (hp->h_name != NULL) {
438                     nhp->h_name = cp;
439                     strcpy(cp, hp->h_name);
440                     cp += strlen(cp) + 1;
441           } else
442                     nhp->h_name = NULL;
443           nhp->h_aliases = (char **)((char *)nhp + al_off);
444           if ((pp = hp->h_aliases) != NULL) {
445                     for (i = 0; *pp != NULL; pp++) {
446                               if (**pp != '\0') {
447                                         nhp->h_aliases[i++] = cp;
448                                         strcpy(cp, *pp);
449                                         cp += strlen(cp) + 1;
450                               }
451                     }
452           }
453           nhp->h_aliases[nalias] = NULL;
454           cp = (char *)&nhp->h_aliases[nalias + 1];
455           nhp->h_addrtype = hp->h_addrtype;
456           nhp->h_length = hp->h_length;
457           nhp->h_addr_list = (char **)cp;
458           if ((pp = hp->h_addr_list) != NULL) {
459                     cp = (char *)&nhp->h_addr_list[naddr + 1];
460                     for (i = 0; *pp != NULL; pp++) {
461                               nhp->h_addr_list[i++] = cp;
462                               memcpy(cp, *pp, hp->h_length);
463                               cp += addrsize;
464                     }
465           }
466           nhp->h_addr_list[naddr] = NULL;
467           return nhp;
468 }
469 
470 /*
471  * _hpaddr: construct hostent structure with one address
472  */
473 static struct hostent *
_hpaddr(int af,const char * name,void * addr,int * errp)474 _hpaddr(int af, const char *name, void *addr, int *errp)
475 {
476           struct hostent *hp, hpbuf;
477           char *addrs[2];
478 
479           hp = &hpbuf;
480           hp->h_name = (char *)name;
481           hp->h_aliases = NULL;
482           hp->h_addrtype = af;
483           hp->h_length = ADDRLEN(af);
484           hp->h_addr_list = addrs;
485           addrs[0] = (char *)addr;
486           addrs[1] = NULL;
487           return (_hpcopy(hp, errp));
488 }
489 
490 #ifdef INET6
491 /*
492  * _hpmerge: merge 2 hostent structure, arguments will be freed
493  */
494 static struct hostent *
_hpmerge(struct hostent * hp1,struct hostent * hp2,int * errp)495 _hpmerge(struct hostent *hp1, struct hostent *hp2, int *errp)
496 {
497           int i, j;
498           int naddr, nalias;
499           char **pp;
500           struct hostent *hp, hpbuf;
501           char *aliases[MAXALIASES + 1], *addrs[MAXADDRS + 1];
502           union inx_addr addrbuf[MAXADDRS];
503 
504           if (hp1 == NULL)
505                     return _hpcopy(hp2, errp);
506           if (hp2 == NULL)
507                     return _hpcopy(hp1, errp);
508 
509 #define   HP(i)     (i == 1 ? hp1 : hp2)
510           hp = &hpbuf;
511           hp->h_name = (hp1->h_name != NULL ? hp1->h_name : hp2->h_name);
512           hp->h_aliases = aliases;
513           nalias = 0;
514           for (i = 1; i <= 2; i++) {
515                     if ((pp = HP(i)->h_aliases) == NULL)
516                               continue;
517                     for (; nalias < MAXALIASES && *pp != NULL; pp++) {
518                               /* check duplicates */
519                               for (j = 0; j < nalias; j++)
520                                         if (strcasecmp(*pp, aliases[j]) == 0)
521                                                   break;
522                               if (j == nalias)
523                                         aliases[nalias++] = *pp;
524                     }
525           }
526           aliases[nalias] = NULL;
527           if (hp1->h_length != hp2->h_length) {
528                     hp->h_addrtype = AF_INET6;
529                     hp->h_length = sizeof(struct in6_addr);
530           } else {
531                     hp->h_addrtype = hp1->h_addrtype;
532                     hp->h_length = hp1->h_length;
533           }
534 
535           hp->h_addr_list = addrs;
536           naddr = 0;
537           for (i = 1; i <= 2; i++) {
538                     if ((pp = HP(i)->h_addr_list) == NULL)
539                               continue;
540                     if (HP(i)->h_length == hp->h_length) {
541                               while (naddr < MAXADDRS && *pp != NULL)
542                                         addrs[naddr++] = *pp++;
543                     } else {
544                               /* copy IPv4 addr as mapped IPv6 addr */
545                               while (naddr < MAXADDRS && *pp != NULL) {
546                                         MAPADDR(&addrbuf[naddr], *pp++);
547                                         addrs[naddr] = (char *)&addrbuf[naddr];
548                                         naddr++;
549                               }
550                     }
551           }
552           addrs[naddr] = NULL;
553           return (_hpcopy(hp, errp));
554 }
555 #endif
556 
557 /*
558  * _hpmapv6: convert IPv4 hostent into IPv4-mapped IPv6 addresses
559  */
560 #ifdef INET6
561 static struct hostent *
_hpmapv6(struct hostent * hp,int * errp)562 _hpmapv6(struct hostent *hp, int *errp)
563 {
564           struct hostent hp6;
565 
566           if (hp == NULL)
567                     return NULL;
568           if (hp->h_addrtype == AF_INET6)
569                     return _hpcopy(hp, errp);
570 
571           memset(&hp6, 0, sizeof(struct hostent));
572           hp6.h_addrtype = AF_INET6;
573           hp6.h_length = sizeof(struct in6_addr);
574           return _hpmerge(&hp6, hp, errp);
575 }
576 #endif
577 
578 /*
579  * _hpsort: sort address by sortlist
580  */
581 static struct hostent *
_hpsort(struct hostent * hp,res_state statp)582 _hpsort(struct hostent *hp, res_state statp)
583 {
584           int i, j, n;
585           u_char *ap, *sp, *mp, **pp;
586           char t;
587           char order[MAXADDRS];
588           int nsort = statp->nsort;
589 
590           if (hp == NULL || hp->h_addr_list[1] == NULL || nsort == 0)
591                     return hp;
592           for (i = 0; (ap = (u_char *)hp->h_addr_list[i]); i++) {
593                     for (j = 0; j < nsort; j++) {
594 #ifdef INET6
595                               if (statp->_u._ext.ext->sort_list[j].af !=
596                                   hp->h_addrtype)
597                                         continue;
598                               sp = (u_char *)&statp->_u._ext.ext->sort_list[j].addr;
599                               mp = (u_char *)&statp->_u._ext.ext->sort_list[j].mask;
600 #else
601                               sp = (u_char *)&statp->sort_list[j].addr;
602                               mp = (u_char *)&statp->sort_list[j].mask;
603 #endif
604                               for (n = 0; n < hp->h_length; n++) {
605                                         if ((ap[n] & mp[n]) != sp[n])
606                                                   break;
607                               }
608                               if (n == hp->h_length)
609                                         break;
610                     }
611                     order[i] = j;
612           }
613           n = i;
614           pp = (u_char **)hp->h_addr_list;
615           for (i = 0; i < n - 1; i++) {
616                     for (j = i + 1; j < n; j++) {
617                               if (order[i] > order[j]) {
618                                         ap = pp[i];
619                                         pp[i] = pp[j];
620                                         pp[j] = ap;
621                                         t = order[i];
622                                         order[i] = order[j];
623                                         order[j] = t;
624                               }
625                     }
626           }
627           return hp;
628 }
629 
630 /*
631  * _hpreorder: sort address by default address selection
632  */
633 static struct hostent *
_hpreorder(struct hostent * hp)634 _hpreorder(struct hostent *hp)
635 {
636           struct hp_order *aio;
637           int i, n;
638           char *ap;
639           struct sockaddr *sa;
640           struct policyhead policyhead;
641 
642           if (hp == NULL)
643                     return hp;
644 
645           switch (hp->h_addrtype) {
646           case AF_INET:
647 #ifdef INET6
648           case AF_INET6:
649 #endif
650                     break;
651           default:
652                     free_addrselectpolicy(&policyhead);
653                     return hp;
654           }
655 
656           /* count the number of addrinfo elements for sorting. */
657           for (n = 0; hp->h_addr_list[n] != NULL; n++)
658                     ;
659 
660           /*
661            * If the number is small enough, we can skip the reordering process.
662            */
663           if (n <= 1)
664                     return hp;
665 
666           /* allocate a temporary array for sort and initialization of it. */
667           if ((aio = malloc(sizeof(*aio) * n)) == NULL)
668                     return hp;          /* give up reordering */
669           memset(aio, 0, sizeof(*aio) * n);
670 
671           /* retrieve address selection policy from the kernel */
672           TAILQ_INIT(&policyhead);
673           if (!get_addrselectpolicy(&policyhead)) {
674                     /* no policy is installed into kernel, we don't sort. */
675                     free(aio);
676                     return hp;
677           }
678 
679           for (i = 0; i < n; i++) {
680                     ap = hp->h_addr_list[i];
681                     aio[i].aio_h_addr = ap;
682                     sa = &aio[i].aio_sa;
683                     switch (hp->h_addrtype) {
684                     case AF_INET:
685                               sa->sa_family = AF_INET;
686                               sa->sa_len = sizeof(struct sockaddr_in);
687                               memcpy(&((struct sockaddr_in *)sa)->sin_addr, ap,
688                                   sizeof(struct in_addr));
689                               break;
690 #ifdef INET6
691                     case AF_INET6:
692                               if (IN6_IS_ADDR_V4MAPPED((struct in6_addr *)ap)) {
693                                         sa->sa_family = AF_INET;
694                                         sa->sa_len = sizeof(struct sockaddr_in);
695                                         memcpy(&((struct sockaddr_in *)sa)->sin_addr,
696                                             &ap[12], sizeof(struct in_addr));
697                               } else {
698                                         sa->sa_family = AF_INET6;
699                                         sa->sa_len = sizeof(struct sockaddr_in6);
700                                         memcpy(&((struct sockaddr_in6 *)sa)->sin6_addr,
701                                             ap, sizeof(struct in6_addr));
702                               }
703                               break;
704 #endif
705                     }
706                     aio[i].aio_dstscope = gai_addr2scopetype(sa);
707                     aio[i].aio_dstpolicy = match_addrselectpolicy(sa, &policyhead);
708                     set_source(&aio[i], &policyhead);
709           }
710 
711           /* perform sorting. */
712           qsort(aio, n, sizeof(*aio), comp_dst);
713 
714           /* reorder the h_addr_list. */
715           for (i = 0; i < n; i++)
716                     hp->h_addr_list[i] = aio[i].aio_h_addr;
717 
718           /* cleanup and return */
719           free(aio);
720           free_addrselectpolicy(&policyhead);
721           return hp;
722 }
723 
724 static int
get_addrselectpolicy(struct policyhead * head)725 get_addrselectpolicy(struct policyhead *head)
726 {
727 #ifdef INET6
728           int mib[] = { CTL_NET, PF_INET6, IPPROTO_IPV6, IPV6CTL_ADDRCTLPOLICY };
729           size_t l;
730           char *buf;
731           struct in6_addrpolicy *pol, *ep;
732 
733           if (sysctl(mib, NELEM(mib), NULL, &l, NULL, 0) < 0)
734                     return (0);
735           if ((buf = malloc(l)) == NULL)
736                     return (0);
737           if (sysctl(mib, NELEM(mib), buf, &l, NULL, 0) < 0) {
738                     free(buf);
739                     return (0);
740           }
741 
742           ep = (struct in6_addrpolicy *)(buf + l);
743           for (pol = (struct in6_addrpolicy *)buf; pol + 1 <= ep; pol++) {
744                     struct policyqueue *new;
745 
746                     if ((new = malloc(sizeof(*new))) == NULL) {
747                               free_addrselectpolicy(head); /* make the list empty */
748                               break;
749                     }
750                     new->pc_policy = *pol;
751                     TAILQ_INSERT_TAIL(head, new, pc_entry);
752           }
753 
754           free(buf);
755           return (1);
756 #else
757           return (0);
758 #endif
759 }
760 
761 static void
free_addrselectpolicy(struct policyhead * head)762 free_addrselectpolicy(struct policyhead *head)
763 {
764           struct policyqueue *ent, *nent;
765 
766           for (ent = TAILQ_FIRST(head); ent; ent = nent) {
767                     nent = TAILQ_NEXT(ent, pc_entry);
768                     TAILQ_REMOVE(head, ent, pc_entry);
769                     free(ent);
770           }
771 }
772 
773 static struct policyqueue *
match_addrselectpolicy(struct sockaddr * addr,struct policyhead * head)774 match_addrselectpolicy(struct sockaddr *addr, struct policyhead *head)
775 {
776 #ifdef INET6
777           struct policyqueue *ent, *bestent = NULL;
778           struct in6_addrpolicy *pol;
779           int matchlen, bestmatchlen = -1;
780           u_char *mp, *ep, *k, *p, m;
781           struct sockaddr_in6 key;
782 
783           switch(addr->sa_family) {
784           case AF_INET6:
785                     key = *(struct sockaddr_in6 *)addr;
786                     break;
787           case AF_INET:
788                     /* convert the address into IPv4-mapped IPv6 address. */
789                     memset(&key, 0, sizeof(key));
790                     key.sin6_family = AF_INET6;
791                     key.sin6_len = sizeof(key);
792                     key.sin6_addr.s6_addr[10] = 0xff;
793                     key.sin6_addr.s6_addr[11] = 0xff;
794                     memcpy(&key.sin6_addr.s6_addr[12],
795                            &((struct sockaddr_in *)addr)->sin_addr, 4);
796                     break;
797           default:
798                     return(NULL);
799           }
800 
801           for (ent = TAILQ_FIRST(head); ent; ent = TAILQ_NEXT(ent, pc_entry)) {
802                     pol = &ent->pc_policy;
803                     matchlen = 0;
804 
805                     mp = (u_char *)&pol->addrmask.sin6_addr;
806                     ep = mp + 16;       /* XXX: scope field? */
807                     k = (u_char *)&key.sin6_addr;
808                     p = (u_char *)&pol->addr.sin6_addr;
809                     for (; mp < ep && *mp; mp++, k++, p++) {
810                               m = *mp;
811                               if ((*k & m) != *p)
812                                         goto next; /* not match */
813                               if (m == 0xff) /* short cut for a typical case */
814                                         matchlen += 8;
815                               else {
816                                         while (m >= 0x80) {
817                                                   matchlen++;
818                                                   m <<= 1;
819                                         }
820                               }
821                     }
822 
823                     /* matched.  check if this is better than the current best. */
824                     if (matchlen > bestmatchlen) {
825                               bestent = ent;
826                               bestmatchlen = matchlen;
827                     }
828 
829             next:
830                     continue;
831           }
832 
833           return(bestent);
834 #else
835           return(NULL);
836 #endif
837 
838 }
839 
840 static void
set_source(struct hp_order * aio,struct policyhead * ph)841 set_source(struct hp_order *aio, struct policyhead *ph)
842 {
843           struct sockaddr_storage ss = aio->aio_un.aiou_ss;
844           socklen_t srclen;
845           int s;
846 
847           /* set unspec ("no source is available"), just in case */
848           aio->aio_srcsa.sa_family = AF_UNSPEC;
849           aio->aio_srcscope = -1;
850 
851           switch(ss.ss_family) {
852           case AF_INET:
853                     ((struct sockaddr_in *)&ss)->sin_port = htons(1);
854                     break;
855 #ifdef INET6
856           case AF_INET6:
857                     ((struct sockaddr_in6 *)&ss)->sin6_port = htons(1);
858                     break;
859 #endif
860           default:            /* ignore unsupported AFs explicitly */
861                     return;
862           }
863 
864           /* open a socket to get the source address for the given dst */
865           if ((s = _socket(ss.ss_family, SOCK_DGRAM, IPPROTO_UDP)) < 0)
866                     return;             /* give up */
867           if (_connect(s, (struct sockaddr *)&ss, ss.ss_len) < 0)
868                     goto cleanup;
869           srclen = ss.ss_len;
870           if (_getsockname(s, &aio->aio_srcsa, &srclen) < 0) {
871                     aio->aio_srcsa.sa_family = AF_UNSPEC;
872                     goto cleanup;
873           }
874           aio->aio_srcscope = gai_addr2scopetype(&aio->aio_srcsa);
875           aio->aio_srcpolicy = match_addrselectpolicy(&aio->aio_srcsa, ph);
876           aio->aio_matchlen = matchlen(&aio->aio_srcsa, (struct sockaddr *)&ss);
877 #ifdef INET6
878           if (ss.ss_family == AF_INET6) {
879                     struct in6_ifreq ifr6;
880                     u_int32_t flags6;
881 
882                     /* XXX: interface name should not be hardcoded */
883                     strncpy(ifr6.ifr_name, "lo0", sizeof(ifr6.ifr_name));
884                     memset(&ifr6, 0, sizeof(ifr6));
885                     memcpy(&ifr6.ifr_addr, &ss, ss.ss_len);
886                     if (_ioctl(s, SIOCGIFAFLAG_IN6, &ifr6) == 0) {
887                               flags6 = ifr6.ifr_ifru.ifru_flags6;
888                               if ((flags6 & IN6_IFF_DEPRECATED))
889                                         aio->aio_srcflag |= AIO_SRCFLAG_DEPRECATED;
890                     }
891           }
892 #endif
893 
894   cleanup:
895           _close(s);
896           return;
897 }
898 
899 static int
matchlen(struct sockaddr * src,struct sockaddr * dst)900 matchlen(struct sockaddr *src, struct sockaddr *dst)
901 {
902           int match = 0;
903           u_char *s, *d;
904           u_char *lim, r;
905           int addrlen;
906 
907           switch (src->sa_family) {
908 #ifdef INET6
909           case AF_INET6:
910                     s = (u_char *)&((struct sockaddr_in6 *)src)->sin6_addr;
911                     d = (u_char *)&((struct sockaddr_in6 *)dst)->sin6_addr;
912                     addrlen = sizeof(struct in6_addr);
913                     lim = s + addrlen;
914                     break;
915 #endif
916           case AF_INET:
917                     s = (u_char *)&((struct sockaddr_in *)src)->sin_addr;
918                     d = (u_char *)&((struct sockaddr_in *)dst)->sin_addr;
919                     addrlen = sizeof(struct in_addr);
920                     lim = s + addrlen;
921                     break;
922           default:
923                     return(0);
924           }
925 
926           while (s < lim)
927                     if ((r = (*d++ ^ *s++)) != 0) {
928                               while (r < addrlen * 8) {
929                                         match++;
930                                         r <<= 1;
931                               }
932                               break;
933                     } else
934                               match += 8;
935           return(match);
936 }
937 
938 static int
comp_dst(const void * arg1,const void * arg2)939 comp_dst(const void *arg1, const void *arg2)
940 {
941           const struct hp_order *dst1 = arg1, *dst2 = arg2;
942 
943           /*
944            * Rule 1: Avoid unusable destinations.
945            * XXX: we currently do not consider if an appropriate route exists.
946            */
947           if (dst1->aio_srcsa.sa_family != AF_UNSPEC &&
948               dst2->aio_srcsa.sa_family == AF_UNSPEC) {
949                     return(-1);
950           }
951           if (dst1->aio_srcsa.sa_family == AF_UNSPEC &&
952               dst2->aio_srcsa.sa_family != AF_UNSPEC) {
953                     return(1);
954           }
955 
956           /* Rule 2: Prefer matching scope. */
957           if (dst1->aio_dstscope == dst1->aio_srcscope &&
958               dst2->aio_dstscope != dst2->aio_srcscope) {
959                     return(-1);
960           }
961           if (dst1->aio_dstscope != dst1->aio_srcscope &&
962               dst2->aio_dstscope == dst2->aio_srcscope) {
963                     return(1);
964           }
965 
966           /* Rule 3: Avoid deprecated addresses. */
967           if (dst1->aio_srcsa.sa_family != AF_UNSPEC &&
968               dst2->aio_srcsa.sa_family != AF_UNSPEC) {
969                     if (!(dst1->aio_srcflag & AIO_SRCFLAG_DEPRECATED) &&
970                         (dst2->aio_srcflag & AIO_SRCFLAG_DEPRECATED)) {
971                               return(-1);
972                     }
973                     if ((dst1->aio_srcflag & AIO_SRCFLAG_DEPRECATED) &&
974                         !(dst2->aio_srcflag & AIO_SRCFLAG_DEPRECATED)) {
975                               return(1);
976                     }
977           }
978 
979           /* Rule 4: Prefer home addresses. */
980           /* XXX: not implemented yet */
981 
982           /* Rule 5: Prefer matching label. */
983 #ifdef INET6
984           if (dst1->aio_srcpolicy && dst1->aio_dstpolicy &&
985               dst1->aio_srcpolicy->pc_policy.label ==
986               dst1->aio_dstpolicy->pc_policy.label &&
987               (dst2->aio_srcpolicy == NULL || dst2->aio_dstpolicy == NULL ||
988                dst2->aio_srcpolicy->pc_policy.label !=
989                dst2->aio_dstpolicy->pc_policy.label)) {
990                     return(-1);
991           }
992           if (dst2->aio_srcpolicy && dst2->aio_dstpolicy &&
993               dst2->aio_srcpolicy->pc_policy.label ==
994               dst2->aio_dstpolicy->pc_policy.label &&
995               (dst1->aio_srcpolicy == NULL || dst1->aio_dstpolicy == NULL ||
996                dst1->aio_srcpolicy->pc_policy.label !=
997                dst1->aio_dstpolicy->pc_policy.label)) {
998                     return(1);
999           }
1000 #endif
1001 
1002           /* Rule 6: Prefer higher precedence. */
1003 #ifdef INET6
1004           if (dst1->aio_dstpolicy &&
1005               (dst2->aio_dstpolicy == NULL ||
1006                dst1->aio_dstpolicy->pc_policy.preced >
1007                dst2->aio_dstpolicy->pc_policy.preced)) {
1008                     return(-1);
1009           }
1010           if (dst2->aio_dstpolicy &&
1011               (dst1->aio_dstpolicy == NULL ||
1012                dst2->aio_dstpolicy->pc_policy.preced >
1013                dst1->aio_dstpolicy->pc_policy.preced)) {
1014                     return(1);
1015           }
1016 #endif
1017 
1018           /* Rule 7: Prefer native transport. */
1019           /* XXX: not implemented yet */
1020 
1021           /* Rule 8: Prefer smaller scope. */
1022           if (dst1->aio_dstscope >= 0 &&
1023               dst1->aio_dstscope < dst2->aio_dstscope) {
1024                     return(-1);
1025           }
1026           if (dst2->aio_dstscope >= 0 &&
1027               dst2->aio_dstscope < dst1->aio_dstscope) {
1028                     return(1);
1029           }
1030 
1031           /*
1032            * Rule 9: Use longest matching prefix.
1033            * We compare the match length in a same AF only.
1034            */
1035           if (dst1->aio_sa.sa_family == dst2->aio_sa.sa_family) {
1036                     if (dst1->aio_matchlen > dst2->aio_matchlen) {
1037                               return(-1);
1038                     }
1039                     if (dst1->aio_matchlen < dst2->aio_matchlen) {
1040                               return(1);
1041                     }
1042           }
1043 
1044           /* Rule 10: Otherwise, leave the order unchanged. */
1045           return(-1);
1046 }
1047 
1048 /*
1049  * Copy from scope.c.
1050  * XXX: we should standardize the functions and link them as standard
1051  * library.
1052  */
1053 static int
gai_addr2scopetype(struct sockaddr * sa)1054 gai_addr2scopetype(struct sockaddr *sa)
1055 {
1056 #ifdef INET6
1057           struct sockaddr_in6 *sa6;
1058 #endif
1059           struct sockaddr_in *sa4;
1060 
1061           switch(sa->sa_family) {
1062 #ifdef INET6
1063           case AF_INET6:
1064                     sa6 = (struct sockaddr_in6 *)sa;
1065                     if (IN6_IS_ADDR_MULTICAST(&sa6->sin6_addr)) {
1066                               /* just use the scope field of the multicast address */
1067                               return(sa6->sin6_addr.s6_addr[2] & 0x0f);
1068                     }
1069                     /*
1070                      * Unicast addresses: map scope type to corresponding scope
1071                      * value defined for multcast addresses.
1072                      * XXX: hardcoded scope type values are bad...
1073                      */
1074                     if (IN6_IS_ADDR_LOOPBACK(&sa6->sin6_addr))
1075                               return(1); /* node local scope */
1076                     if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr))
1077                               return(2); /* link-local scope */
1078                     if (IN6_IS_ADDR_SITELOCAL(&sa6->sin6_addr))
1079                               return(5); /* site-local scope */
1080                     return(14);         /* global scope */
1081                     break;
1082 #endif
1083           case AF_INET:
1084                     /*
1085                      * IPv4 pseudo scoping according to RFC 3484.
1086                      */
1087                     sa4 = (struct sockaddr_in *)sa;
1088                     /* IPv4 autoconfiguration addresses have link-local scope. */
1089                     if (((u_char *)&sa4->sin_addr)[0] == 169 &&
1090                         ((u_char *)&sa4->sin_addr)[1] == 254)
1091                               return(2);
1092                     /* Private addresses have site-local scope. */
1093                     if (((u_char *)&sa4->sin_addr)[0] == 10 ||
1094                         (((u_char *)&sa4->sin_addr)[0] == 172 &&
1095                          (((u_char *)&sa4->sin_addr)[1] & 0xf0) == 16) ||
1096                         (((u_char *)&sa4->sin_addr)[0] == 192 &&
1097                          ((u_char *)&sa4->sin_addr)[1] == 168))
1098                               return(14);         /* XXX: It should be 5 unless NAT */
1099                     /* Loopback addresses have link-local scope. */
1100                     if (((u_char *)&sa4->sin_addr)[0] == 127)
1101                               return(2);
1102                     return(14);
1103                     break;
1104           default:
1105                     errno = EAFNOSUPPORT; /* is this a good error? */
1106                     return(-1);
1107           }
1108 }
1109