1 /* $KAME: getaddrinfo.c,v 1.15 2000/07/09 04:37:24 itojun Exp $ */
4 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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
33 * "#ifdef FAITH" part is local hack for supporting IPv4-v6 translator.
35 * Issues to be discussed:
36 * - Return values. There are nonstandard return values defined and used
37 * in the source code. This is because RFC2553 is silent about which error
38 * code must be returned for which situation.
39 * - freeaddrinfo(NULL). RFC2553 is silent about it. XNET 5.2 says it is
40 * invalid. current code - SEGV on freeaddrinfo(NULL)
43 * - The code filters out AFs that are not supported by the kernel,
44 * when globbing NULL hostname (to loopback, or wildcard). Is it the right
45 * thing to do? What is the relationship with post-RFC2553 AI_ADDRCONFIG
47 * - (post-2553) semantics of AI_ADDRCONFIG itself is too vague.
48 * (1) what should we do against numeric hostname (2) what should we do
49 * against NULL hostname (3) what is AI_ADDRCONFIG itself. AF not ready?
50 * non-loopback address configured? global address configured?
52 * OS specific notes for freebsd4:
53 * - FreeBSD supported $GAI. The code does not.
56 #include <sys/cdefs.h>
57 __FBSDID("$FreeBSD$");
59 #include "namespace.h"
60 #include <sys/types.h>
61 #include <sys/param.h>
62 #include <sys/socket.h>
64 #include <netinet/in.h>
65 #include <net/if_types.h>
67 #include <sys/queue.h>
69 #include <net/if_var.h>
70 #include <sys/sysctl.h>
71 #include <sys/ioctl.h>
72 #include <netinet6/in6_var.h>
73 #include <netinet6/nd6.h>
75 #include <arpa/inet.h>
76 #include <arpa/nameser.h>
78 #include <rpcsvc/yp_prot.h>
79 #include <rpcsvc/ypclnt.h>
90 #include "res_config.h"
98 #include "un-namespace.h"
99 #include "libc_private.h"
104 #if defined(__KAME__) && defined(INET6)
112 static const char in_addrany[] = { 0, 0, 0, 0 };
113 static const char in_loopback[] = { 127, 0, 0, 1 };
115 static const char in6_addrany[] = {
116 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
118 static const char in6_loopback[] = {
119 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
124 TAILQ_ENTRY(policyqueue) pc_entry;
126 struct in6_addrpolicy pc_policy;
129 TAILQ_HEAD(policyhead, policyqueue);
131 static const struct afd {
136 const char *a_addrany;
137 const char *a_loopback;
142 {PF_INET6, sizeof(struct in6_addr),
143 sizeof(struct sockaddr_in6),
144 offsetof(struct sockaddr_in6, sin6_addr),
145 in6_addrany, in6_loopback, 1},
150 {PF_INET, sizeof(struct in_addr),
151 sizeof(struct sockaddr_in),
152 offsetof(struct sockaddr_in, sin_addr),
153 in_addrany, in_loopback, 0},
154 {0, 0, 0, 0, NULL, NULL, 0},
161 const char *e_protostr;
163 #define WILD_AF(ex) ((ex)->e_wild & 0x01)
164 #define WILD_SOCKTYPE(ex) ((ex)->e_wild & 0x02)
165 #define WILD_PROTOCOL(ex) ((ex)->e_wild & 0x04)
168 static const struct explore explore[] = {
170 { PF_LOCAL, ANY, ANY, NULL, 0x01 },
173 { PF_INET6, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
174 { PF_INET6, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
175 { PF_INET6, SOCK_STREAM, IPPROTO_SCTP, "sctp", 0x03 },
176 { PF_INET6, SOCK_SEQPACKET, IPPROTO_SCTP, "sctp", 0x07 },
177 { PF_INET6, SOCK_RAW, ANY, NULL, 0x05 },
179 { PF_INET, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
180 { PF_INET, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
181 { PF_INET, SOCK_STREAM, IPPROTO_SCTP, "sctp", 0x03 },
182 { PF_INET, SOCK_SEQPACKET, IPPROTO_SCTP, "sctp", 0x07 },
183 { PF_INET, SOCK_RAW, ANY, NULL, 0x05 },
184 { -1, 0, 0, NULL, 0 },
193 #define AIO_SRCFLAG_DEPRECATED 0x1
197 struct sockaddr_storage aiou_ss;
198 struct sockaddr aiou_sa;
200 #define aio_srcsa aio_src_un.aiou_sa
201 u_int32_t aio_srcflag;
204 struct policyqueue *aio_srcpolicy;
205 struct policyqueue *aio_dstpolicy;
206 struct addrinfo *aio_ai;
210 static const ns_src default_dns_files[] = {
211 { NSSRC_FILES, NS_SUCCESS },
212 { NSSRC_DNS, NS_SUCCESS },
217 struct res_target *next;
218 const char *name; /* domain name */
219 int qclass, qtype; /* class and type of query */
220 u_char *answer; /* buffer to put answer */
221 int anslen; /* size of answer buffer */
222 int n; /* result length */
225 #define MAXPACKET (64*1024)
229 u_char buf[MAXPACKET];
232 static int str2number(const char *, int *);
233 static int explore_copy(const struct addrinfo *, const struct addrinfo *,
235 static int explore_null(const struct addrinfo *,
236 const char *, struct addrinfo **);
237 static int explore_numeric(const struct addrinfo *, const char *,
238 const char *, struct addrinfo **, const char *);
239 static int explore_numeric_scope(const struct addrinfo *, const char *,
240 const char *, struct addrinfo **);
241 static int get_canonname(const struct addrinfo *,
242 struct addrinfo *, const char *);
243 static struct addrinfo *get_ai(const struct addrinfo *,
244 const struct afd *, const char *);
245 static struct addrinfo *copy_ai(const struct addrinfo *);
246 static int get_portmatch(const struct addrinfo *, const char *);
247 static int get_port(struct addrinfo *, const char *, int);
248 static const struct afd *find_afd(int);
249 static int addrconfig(struct addrinfo *);
251 static int is_ifdisabled(char *);
253 static void set_source(struct ai_order *, struct policyhead *);
254 static int comp_dst(const void *, const void *);
256 static int ip6_str2scopeid(char *, struct sockaddr_in6 *, u_int32_t *);
258 static int gai_addr2scopetype(struct sockaddr *);
260 static int explore_fqdn(const struct addrinfo *, const char *,
261 const char *, struct addrinfo **);
263 static int reorder(struct addrinfo *);
264 static int get_addrselectpolicy(struct policyhead *);
265 static void free_addrselectpolicy(struct policyhead *);
266 static struct policyqueue *match_addrselectpolicy(struct sockaddr *,
267 struct policyhead *);
268 static int matchlen(struct sockaddr *, struct sockaddr *);
270 static struct addrinfo *getanswer(const querybuf *, int, const char *, int,
271 const struct addrinfo *, res_state);
272 #if defined(RESOLVSORT)
273 static int addr4sort(struct addrinfo *, res_state);
275 static int _dns_getaddrinfo(void *, void *, va_list);
276 static void _sethtent(FILE **);
277 static void _endhtent(FILE **);
278 static struct addrinfo *_gethtent(FILE **, const char *,
279 const struct addrinfo *);
280 static int _files_getaddrinfo(void *, void *, va_list);
282 static struct addrinfo *_yphostent(char *, const struct addrinfo *);
283 static int _yp_getaddrinfo(void *, void *, va_list);
286 static int addrinfo_id_func(char *, size_t *, va_list, void *);
287 static int addrinfo_marshal_func(char *, size_t *, void *, va_list, void *);
288 static int addrinfo_unmarshal_func(char *, size_t, void *, va_list, void *);
291 static int res_queryN(const char *, struct res_target *, res_state);
292 static int res_searchN(const char *, struct res_target *, res_state);
293 static int res_querydomainN(const char *, const char *,
294 struct res_target *, res_state);
296 /* XXX macros that make external reference is BAD. */
298 #define GET_AI(ai, afd, addr) \
300 /* external reference: pai, error, and label free */ \
301 (ai) = get_ai(pai, (afd), (addr)); \
302 if ((ai) == NULL) { \
303 error = EAI_MEMORY; \
306 } while (/*CONSTCOND*/0)
308 #define GET_PORT(ai, serv) \
310 /* external reference: error and label free */ \
311 error = get_port((ai), (serv), 0); \
314 } while (/*CONSTCOND*/0)
316 #define GET_CANONNAME(ai, str) \
318 /* external reference: pai, error and label free */ \
319 error = get_canonname(pai, (ai), (str)); \
322 } while (/*CONSTCOND*/0)
326 /* external reference: error, and label bad */ \
330 } while (/*CONSTCOND*/0)
332 #define MATCH_FAMILY(x, y, w) \
333 ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC || (y) == PF_UNSPEC)))
334 #define MATCH(x, y, w) \
335 ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY)))
338 freeaddrinfo(struct addrinfo *ai)
340 struct addrinfo *next;
344 if (ai->ai_canonname)
345 free(ai->ai_canonname);
346 /* no need to free(ai->ai_addr) */
353 str2number(const char *p, int *portp)
362 v = strtoul(p, &ep, 10);
363 if (errno == 0 && ep && *ep == '\0' && v <= UINT_MAX) {
371 getaddrinfo(const char *hostname, const char *servname,
372 const struct addrinfo *hints, struct addrinfo **res)
374 struct addrinfo sentinel;
375 struct addrinfo *cur;
377 struct addrinfo ai, ai0, *afai;
378 struct addrinfo *pai;
379 const struct afd *afd;
380 const struct explore *ex;
381 struct addrinfo *afailist[sizeof(afdl)/sizeof(afdl[0])];
382 struct addrinfo *afai_unspec;
386 /* ensure we return NULL on errors */
389 memset(&ai, 0, sizeof(ai));
391 memset(afailist, 0, sizeof(afailist));
394 memset(&sentinel, 0, sizeof(sentinel));
398 pai->ai_family = PF_UNSPEC;
399 pai->ai_socktype = ANY;
400 pai->ai_protocol = ANY;
402 pai->ai_canonname = NULL;
406 if (hostname == NULL && servname == NULL)
409 /* error check for hints */
410 if (hints->ai_addrlen || hints->ai_canonname ||
411 hints->ai_addr || hints->ai_next)
412 ERR(EAI_BADHINTS); /* xxx */
413 if (hints->ai_flags & ~AI_MASK)
415 switch (hints->ai_family) {
425 memcpy(pai, hints, sizeof(*pai));
428 * if both socktype/protocol are specified, check if they
429 * are meaningful combination.
431 if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
432 for (ex = explore; ex->e_af >= 0; ex++) {
433 if (!MATCH_FAMILY(pai->ai_family, ex->e_af,
436 if (!MATCH(pai->ai_socktype, ex->e_socktype,
439 if (!MATCH(pai->ai_protocol, ex->e_protocol,
453 * check for special cases. (1) numeric servname is disallowed if
454 * socktype/protocol are left unspecified. (2) servname is disallowed
455 * for raw and other inet{,6} sockets.
457 if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
459 || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
462 ai0 = *pai; /* backup *pai */
464 if (pai->ai_family == PF_UNSPEC) {
466 pai->ai_family = PF_INET6;
468 pai->ai_family = PF_INET;
471 error = get_portmatch(pai, servname);
481 * NULL hostname, or numeric hostname.
482 * If numeric representation of AF1 can be interpreted as FQDN
483 * representation of AF2, we need to think again about the code below.
486 for (afd = afdl; afd->a_af; afd++) {
489 if (!MATCH_FAMILY(pai->ai_family, afd->a_af, 1))
492 if (pai->ai_family == PF_UNSPEC)
493 pai->ai_family = afd->a_af;
495 if (hostname == NULL) {
496 error = explore_null(pai, servname,
497 &afailist[afd - afdl]);
500 * Errors from explore_null should be unexpected and
501 * be caught to avoid returning an incomplete result.
506 error = explore_numeric_scope(pai, hostname, servname,
507 &afailist[afd - afdl]);
510 * explore_numeric_scope returns an error for address
511 * families that do not match that of hostname.
512 * Thus we should not catch the error at this moment.
516 if (!error && afailist[afd - afdl])
524 if (hostname == NULL)
525 ERR(EAI_NONAME); /* used to be EAI_NODATA */
526 if (pai->ai_flags & AI_NUMERICHOST)
529 if ((pai->ai_flags & AI_ADDRCONFIG) != 0 && !addrconfig(&ai0))
533 * hostname as alphabetical name.
536 error = explore_fqdn(pai, hostname, servname, &afai_unspec);
539 for (ex = explore; ex->e_af >= 0; ex++) {
542 if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
544 if (!MATCH(pai->ai_socktype, ex->e_socktype,
547 if (!MATCH(pai->ai_protocol, ex->e_protocol,
551 if (pai->ai_family == PF_UNSPEC)
552 pai->ai_family = ex->e_af;
553 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
554 pai->ai_socktype = ex->e_socktype;
555 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
556 pai->ai_protocol = ex->e_protocol;
559 * if the servname does not match socktype/protocol, ignore it.
561 if (get_portmatch(pai, servname) != 0)
567 if ((afd = find_afd(pai->ai_family)) == NULL)
569 /* XXX assumes that afd points inside afdl[] */
570 afai = afailist[afd - afdl];
575 error = explore_copy(pai, afai, &cur->ai_next);
579 while (cur && cur->ai_next)
584 * ensure we return either:
585 * - error == 0, non-NULL *res
586 * - error != 0, NULL *res
589 if (sentinel.ai_next) {
591 * If the returned entry is for an active connection,
592 * and the given name is not numeric, reorder the
593 * list, so that the application would try the list
594 * in the most efficient order. Since the head entry
595 * of the original list may contain ai_canonname and
596 * that entry may be moved elsewhere in the new list,
597 * we keep the pointer and will restore it in the new
598 * head entry. (Note that RFC3493 requires the head
599 * entry store it when requested by the caller).
601 if (hints == NULL || !(hints->ai_flags & AI_PASSIVE)) {
606 sentinel.ai_next->ai_canonname;
607 sentinel.ai_next->ai_canonname = NULL;
608 (void)reorder(&sentinel);
609 if (sentinel.ai_next->ai_canonname ==
611 sentinel.ai_next->ai_canonname
613 } else if (canonname != NULL)
617 *res = sentinel.ai_next;
624 freeaddrinfo(afai_unspec);
625 for (afd = afdl; afd->a_af; afd++) {
626 if (afailist[afd - afdl])
627 freeaddrinfo(afailist[afd - afdl]);
630 if (sentinel.ai_next)
631 freeaddrinfo(sentinel.ai_next);
637 reorder(struct addrinfo *sentinel)
639 struct addrinfo *ai, **aip;
640 struct ai_order *aio;
642 struct policyhead policyhead;
644 /* count the number of addrinfo elements for sorting. */
645 for (n = 0, ai = sentinel->ai_next; ai != NULL; ai = ai->ai_next, n++)
649 * If the number is small enough, we can skip the reordering process.
654 /* allocate a temporary array for sort and initialization of it. */
655 if ((aio = malloc(sizeof(*aio) * n)) == NULL)
656 return(n); /* give up reordering */
657 memset(aio, 0, sizeof(*aio) * n);
659 /* retrieve address selection policy from the kernel */
660 TAILQ_INIT(&policyhead);
661 if (!get_addrselectpolicy(&policyhead)) {
662 /* no policy is installed into kernel, we don't sort. */
667 for (i = 0, ai = sentinel->ai_next; i < n; ai = ai->ai_next, i++) {
669 aio[i].aio_dstscope = gai_addr2scopetype(ai->ai_addr);
670 aio[i].aio_dstpolicy = match_addrselectpolicy(ai->ai_addr,
672 set_source(&aio[i], &policyhead);
675 /* perform sorting. */
676 qsort(aio, n, sizeof(*aio), comp_dst);
678 /* reorder the addrinfo chain. */
679 for (i = 0, aip = &sentinel->ai_next; i < n; i++) {
680 *aip = aio[i].aio_ai;
681 aip = &aio[i].aio_ai->ai_next;
685 /* cleanup and return */
687 free_addrselectpolicy(&policyhead);
692 get_addrselectpolicy(struct policyhead *head)
695 int mib[] = { CTL_NET, PF_INET6, IPPROTO_IPV6, IPV6CTL_ADDRCTLPOLICY };
698 struct in6_addrpolicy *pol, *ep;
700 if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), NULL, &l, NULL, 0) < 0)
704 if ((buf = malloc(l)) == NULL)
706 if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), buf, &l, NULL, 0) < 0) {
711 ep = (struct in6_addrpolicy *)(buf + l);
712 for (pol = (struct in6_addrpolicy *)buf; pol + 1 <= ep; pol++) {
713 struct policyqueue *new;
715 if ((new = malloc(sizeof(*new))) == NULL) {
716 free_addrselectpolicy(head); /* make the list empty */
719 new->pc_policy = *pol;
720 TAILQ_INSERT_TAIL(head, new, pc_entry);
731 free_addrselectpolicy(struct policyhead *head)
733 struct policyqueue *ent, *nent;
735 for (ent = TAILQ_FIRST(head); ent; ent = nent) {
736 nent = TAILQ_NEXT(ent, pc_entry);
737 TAILQ_REMOVE(head, ent, pc_entry);
742 static struct policyqueue *
743 match_addrselectpolicy(struct sockaddr *addr, struct policyhead *head)
746 struct policyqueue *ent, *bestent = NULL;
747 struct in6_addrpolicy *pol;
748 int matchlen, bestmatchlen = -1;
749 u_char *mp, *ep, *k, *p, m;
750 struct sockaddr_in6 key;
752 switch(addr->sa_family) {
754 key = *(struct sockaddr_in6 *)addr;
757 /* convert the address into IPv4-mapped IPv6 address. */
758 memset(&key, 0, sizeof(key));
759 key.sin6_family = AF_INET6;
760 key.sin6_len = sizeof(key);
761 key.sin6_addr.s6_addr[10] = 0xff;
762 key.sin6_addr.s6_addr[11] = 0xff;
763 memcpy(&key.sin6_addr.s6_addr[12],
764 &((struct sockaddr_in *)addr)->sin_addr, 4);
770 for (ent = TAILQ_FIRST(head); ent; ent = TAILQ_NEXT(ent, pc_entry)) {
771 pol = &ent->pc_policy;
774 mp = (u_char *)&pol->addrmask.sin6_addr;
775 ep = mp + 16; /* XXX: scope field? */
776 k = (u_char *)&key.sin6_addr;
777 p = (u_char *)&pol->addr.sin6_addr;
778 for (; mp < ep && *mp; mp++, k++, p++) {
781 goto next; /* not match */
782 if (m == 0xff) /* short cut for a typical case */
792 /* matched. check if this is better than the current best. */
793 if (matchlen > bestmatchlen) {
795 bestmatchlen = matchlen;
810 set_source(struct ai_order *aio, struct policyhead *ph)
812 struct addrinfo ai = *aio->aio_ai;
813 struct sockaddr_storage ss;
817 /* set unspec ("no source is available"), just in case */
818 aio->aio_srcsa.sa_family = AF_UNSPEC;
819 aio->aio_srcscope = -1;
821 switch(ai.ai_family) {
827 default: /* ignore unsupported AFs explicitly */
831 /* XXX: make a dummy addrinfo to call connect() */
832 ai.ai_socktype = SOCK_DGRAM;
833 ai.ai_protocol = IPPROTO_UDP; /* is UDP too specific? */
835 memset(&ss, 0, sizeof(ss));
836 memcpy(&ss, ai.ai_addr, ai.ai_addrlen);
837 ai.ai_addr = (struct sockaddr *)&ss;
838 get_port(&ai, "1", 0);
840 /* open a socket to get the source address for the given dst */
841 if ((s = _socket(ai.ai_family, ai.ai_socktype, ai.ai_protocol)) < 0)
842 return; /* give up */
843 if (_connect(s, ai.ai_addr, ai.ai_addrlen) < 0)
845 srclen = ai.ai_addrlen;
846 if (_getsockname(s, &aio->aio_srcsa, &srclen) < 0) {
847 aio->aio_srcsa.sa_family = AF_UNSPEC;
850 aio->aio_srcscope = gai_addr2scopetype(&aio->aio_srcsa);
851 aio->aio_srcpolicy = match_addrselectpolicy(&aio->aio_srcsa, ph);
852 aio->aio_matchlen = matchlen(&aio->aio_srcsa, aio->aio_ai->ai_addr);
854 if (ai.ai_family == AF_INET6) {
855 struct in6_ifreq ifr6;
858 memset(&ifr6, 0, sizeof(ifr6));
859 memcpy(&ifr6.ifr_addr, ai.ai_addr, ai.ai_addrlen);
860 if (_ioctl(s, SIOCGIFAFLAG_IN6, &ifr6) == 0) {
861 flags6 = ifr6.ifr_ifru.ifru_flags6;
862 if ((flags6 & IN6_IFF_DEPRECATED))
863 aio->aio_srcflag |= AIO_SRCFLAG_DEPRECATED;
874 matchlen(struct sockaddr *src, struct sockaddr *dst)
881 switch (src->sa_family) {
884 s = (u_char *)&((struct sockaddr_in6 *)src)->sin6_addr;
885 d = (u_char *)&((struct sockaddr_in6 *)dst)->sin6_addr;
886 addrlen = sizeof(struct in6_addr);
891 s = (u_char *)&((struct sockaddr_in *)src)->sin_addr;
892 d = (u_char *)&((struct sockaddr_in *)dst)->sin_addr;
893 addrlen = sizeof(struct in_addr);
901 if ((r = (*d++ ^ *s++)) != 0) {
902 while (r < addrlen * 8) {
913 comp_dst(const void *arg1, const void *arg2)
915 const struct ai_order *dst1 = arg1, *dst2 = arg2;
918 * Rule 1: Avoid unusable destinations.
919 * XXX: we currently do not consider if an appropriate route exists.
921 if (dst1->aio_srcsa.sa_family != AF_UNSPEC &&
922 dst2->aio_srcsa.sa_family == AF_UNSPEC) {
925 if (dst1->aio_srcsa.sa_family == AF_UNSPEC &&
926 dst2->aio_srcsa.sa_family != AF_UNSPEC) {
930 /* Rule 2: Prefer matching scope. */
931 if (dst1->aio_dstscope == dst1->aio_srcscope &&
932 dst2->aio_dstscope != dst2->aio_srcscope) {
935 if (dst1->aio_dstscope != dst1->aio_srcscope &&
936 dst2->aio_dstscope == dst2->aio_srcscope) {
940 /* Rule 3: Avoid deprecated addresses. */
941 if (dst1->aio_srcsa.sa_family != AF_UNSPEC &&
942 dst2->aio_srcsa.sa_family != AF_UNSPEC) {
943 if (!(dst1->aio_srcflag & AIO_SRCFLAG_DEPRECATED) &&
944 (dst2->aio_srcflag & AIO_SRCFLAG_DEPRECATED)) {
947 if ((dst1->aio_srcflag & AIO_SRCFLAG_DEPRECATED) &&
948 !(dst2->aio_srcflag & AIO_SRCFLAG_DEPRECATED)) {
953 /* Rule 4: Prefer home addresses. */
954 /* XXX: not implemented yet */
956 /* Rule 5: Prefer matching label. */
958 if (dst1->aio_srcpolicy && dst1->aio_dstpolicy &&
959 dst1->aio_srcpolicy->pc_policy.label ==
960 dst1->aio_dstpolicy->pc_policy.label &&
961 (dst2->aio_srcpolicy == NULL || dst2->aio_dstpolicy == NULL ||
962 dst2->aio_srcpolicy->pc_policy.label !=
963 dst2->aio_dstpolicy->pc_policy.label)) {
966 if (dst2->aio_srcpolicy && dst2->aio_dstpolicy &&
967 dst2->aio_srcpolicy->pc_policy.label ==
968 dst2->aio_dstpolicy->pc_policy.label &&
969 (dst1->aio_srcpolicy == NULL || dst1->aio_dstpolicy == NULL ||
970 dst1->aio_srcpolicy->pc_policy.label !=
971 dst1->aio_dstpolicy->pc_policy.label)) {
976 /* Rule 6: Prefer higher precedence. */
978 if (dst1->aio_dstpolicy &&
979 (dst2->aio_dstpolicy == NULL ||
980 dst1->aio_dstpolicy->pc_policy.preced >
981 dst2->aio_dstpolicy->pc_policy.preced)) {
984 if (dst2->aio_dstpolicy &&
985 (dst1->aio_dstpolicy == NULL ||
986 dst2->aio_dstpolicy->pc_policy.preced >
987 dst1->aio_dstpolicy->pc_policy.preced)) {
992 /* Rule 7: Prefer native transport. */
993 /* XXX: not implemented yet */
995 /* Rule 8: Prefer smaller scope. */
996 if (dst1->aio_dstscope >= 0 &&
997 dst1->aio_dstscope < dst2->aio_dstscope) {
1000 if (dst2->aio_dstscope >= 0 &&
1001 dst2->aio_dstscope < dst1->aio_dstscope) {
1006 * Rule 9: Use longest matching prefix.
1007 * We compare the match length in a same AF only.
1009 if (dst1->aio_ai->ai_addr->sa_family ==
1010 dst2->aio_ai->ai_addr->sa_family) {
1011 if (dst1->aio_matchlen > dst2->aio_matchlen) {
1014 if (dst1->aio_matchlen < dst2->aio_matchlen) {
1019 /* Rule 10: Otherwise, leave the order unchanged. */
1024 * Copy from scope.c.
1025 * XXX: we should standardize the functions and link them as standard
1029 gai_addr2scopetype(struct sockaddr *sa)
1032 struct sockaddr_in6 *sa6;
1034 struct sockaddr_in *sa4;
1036 switch(sa->sa_family) {
1039 sa6 = (struct sockaddr_in6 *)sa;
1040 if (IN6_IS_ADDR_MULTICAST(&sa6->sin6_addr)) {
1041 /* just use the scope field of the multicast address */
1042 return(sa6->sin6_addr.s6_addr[2] & 0x0f);
1045 * Unicast addresses: map scope type to corresponding scope
1046 * value defined for multcast addresses.
1047 * XXX: hardcoded scope type values are bad...
1049 if (IN6_IS_ADDR_LOOPBACK(&sa6->sin6_addr))
1050 return(1); /* node local scope */
1051 if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr))
1052 return(2); /* link-local scope */
1053 if (IN6_IS_ADDR_SITELOCAL(&sa6->sin6_addr))
1054 return(5); /* site-local scope */
1055 return(14); /* global scope */
1060 * IPv4 pseudo scoping according to RFC 3484.
1062 sa4 = (struct sockaddr_in *)sa;
1063 /* IPv4 autoconfiguration addresses have link-local scope. */
1064 if (((u_char *)&sa4->sin_addr)[0] == 169 &&
1065 ((u_char *)&sa4->sin_addr)[1] == 254)
1067 /* Private addresses have site-local scope. */
1068 if (((u_char *)&sa4->sin_addr)[0] == 10 ||
1069 (((u_char *)&sa4->sin_addr)[0] == 172 &&
1070 (((u_char *)&sa4->sin_addr)[1] & 0xf0) == 16) ||
1071 (((u_char *)&sa4->sin_addr)[0] == 192 &&
1072 ((u_char *)&sa4->sin_addr)[1] == 168))
1073 return(14); /* XXX: It should be 5 unless NAT */
1074 /* Loopback addresses have link-local scope. */
1075 if (((u_char *)&sa4->sin_addr)[0] == 127)
1080 errno = EAFNOSUPPORT; /* is this a good error? */
1086 explore_copy(const struct addrinfo *pai, const struct addrinfo *src0,
1087 struct addrinfo **res)
1090 struct addrinfo sentinel, *cur;
1091 const struct addrinfo *src;
1094 sentinel.ai_next = NULL;
1097 for (src = src0; src != NULL; src = src->ai_next) {
1098 if (src->ai_family != pai->ai_family)
1101 cur->ai_next = copy_ai(src);
1102 if (!cur->ai_next) {
1107 cur->ai_next->ai_socktype = pai->ai_socktype;
1108 cur->ai_next->ai_protocol = pai->ai_protocol;
1112 *res = sentinel.ai_next;
1116 freeaddrinfo(sentinel.ai_next);
1122 * passive socket -> anyaddr (0.0.0.0 or ::)
1123 * non-passive socket -> localhost (127.0.0.1 or ::1)
1126 explore_null(const struct addrinfo *pai, const char *servname,
1127 struct addrinfo **res)
1130 const struct afd *afd;
1131 struct addrinfo *ai;
1138 * filter out AFs that are not supported by the kernel
1141 s = _socket(pai->ai_family, SOCK_DGRAM, 0);
1143 if (errno != EMFILE)
1148 afd = find_afd(pai->ai_family);
1152 if (pai->ai_flags & AI_PASSIVE) {
1153 GET_AI(ai, afd, afd->a_addrany);
1154 GET_PORT(ai, servname);
1156 GET_AI(ai, afd, afd->a_loopback);
1157 GET_PORT(ai, servname);
1173 explore_numeric(const struct addrinfo *pai, const char *hostname,
1174 const char *servname, struct addrinfo **res, const char *canonname)
1176 const struct afd *afd;
1177 struct addrinfo *ai;
1179 char pton[PTON_MAX];
1184 afd = find_afd(pai->ai_family);
1188 switch (afd->a_af) {
1191 * RFC3493 requires getaddrinfo() to accept AF_INET formats
1192 * that are accepted by inet_addr() and its family. The
1193 * accepted forms includes the "classful" one, which inet_pton
1194 * does not accept. So we need to separate the case for
1197 if (inet_aton(hostname, (struct in_addr *)pton) != 1)
1201 if (inet_pton(afd->a_af, hostname, pton) != 1)
1206 if (pai->ai_family == afd->a_af) {
1207 GET_AI(ai, afd, pton);
1208 GET_PORT(ai, servname);
1209 if ((pai->ai_flags & AI_CANONNAME)) {
1211 * Set the numeric address itself as the canonical
1212 * name, based on a clarification in RFC3493.
1214 GET_CANONNAME(ai, canonname);
1218 * XXX: This should not happen since we already matched the AF
1235 * numeric hostname with scope
1238 explore_numeric_scope(const struct addrinfo *pai, const char *hostname,
1239 const char *servname, struct addrinfo **res)
1241 #if !defined(SCOPE_DELIMITER) || !defined(INET6)
1242 return explore_numeric(pai, hostname, servname, res, hostname);
1244 const struct afd *afd;
1245 struct addrinfo *cur;
1247 char *cp, *hostname2 = NULL, *scope, *addr;
1248 struct sockaddr_in6 *sin6;
1250 afd = find_afd(pai->ai_family);
1255 return explore_numeric(pai, hostname, servname, res, hostname);
1257 cp = strchr(hostname, SCOPE_DELIMITER);
1259 return explore_numeric(pai, hostname, servname, res, hostname);
1262 * Handle special case of <scoped_address><delimiter><scope id>
1264 hostname2 = strdup(hostname);
1265 if (hostname2 == NULL)
1267 /* terminate at the delimiter */
1268 hostname2[cp - hostname] = '\0';
1272 error = explore_numeric(pai, addr, servname, res, hostname);
1276 for (cur = *res; cur; cur = cur->ai_next) {
1277 if (cur->ai_family != AF_INET6)
1279 sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
1280 if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) {
1284 return(EAI_NONAME); /* XXX: is return OK? */
1286 sin6->sin6_scope_id = scopeid;
1292 if (error && *res) {
1301 get_canonname(const struct addrinfo *pai, struct addrinfo *ai, const char *str)
1303 if ((pai->ai_flags & AI_CANONNAME) != 0) {
1304 ai->ai_canonname = strdup(str);
1305 if (ai->ai_canonname == NULL)
1311 static struct addrinfo *
1312 get_ai(const struct addrinfo *pai, const struct afd *afd, const char *addr)
1315 struct addrinfo *ai;
1317 struct in6_addr faith_prefix;
1324 * Transfrom an IPv4 addr into a special IPv6 addr format for
1325 * IPv6->IPv4 translation gateway. (only TCP is supported now)
1327 * +-----------------------------------+------------+
1328 * | faith prefix part (12 bytes) | embedded |
1329 * | | IPv4 addr part (4 bytes)
1330 * +-----------------------------------+------------+
1332 * faith prefix part is specified as ascii IPv6 addr format
1333 * in environmental variable GAI.
1334 * For FAITH to work correctly, routing to faith prefix must be
1335 * setup toward a machine where a FAITH daemon operates.
1336 * Also, the machine must enable some mechanizm
1337 * (e.g. faith interface hack) to divert those packet with
1338 * faith prefixed destination addr to user-land FAITH daemon.
1340 fp_str = getenv("GAI");
1341 if (fp_str && inet_pton(AF_INET6, fp_str, &faith_prefix) == 1 &&
1342 afd->a_af == AF_INET && pai->ai_socktype == SOCK_STREAM) {
1346 memcpy(&v4a, addr, sizeof v4a);
1347 v4a_top = v4a >> IN_CLASSA_NSHIFT;
1348 if (!IN_MULTICAST(v4a) && !IN_EXPERIMENTAL(v4a) &&
1349 v4a_top != 0 && v4a != IN_LOOPBACKNET) {
1350 afd = &afdl[N_INET6];
1351 memcpy(&faith_prefix.s6_addr[12], addr,
1352 sizeof(struct in_addr));
1358 ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
1359 + (afd->a_socklen));
1363 memcpy(ai, pai, sizeof(struct addrinfo));
1364 ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
1365 memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
1366 ai->ai_addr->sa_len = afd->a_socklen;
1367 ai->ai_addrlen = afd->a_socklen;
1368 ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
1369 p = (char *)(void *)(ai->ai_addr);
1372 memcpy(p + afd->a_off, &faith_prefix, (size_t)afd->a_addrlen);
1375 memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
1379 /* XXX need to malloc() the same way we do from other functions! */
1380 static struct addrinfo *
1381 copy_ai(const struct addrinfo *pai)
1383 struct addrinfo *ai;
1386 l = sizeof(*ai) + pai->ai_addrlen;
1387 if ((ai = (struct addrinfo *)malloc(l)) == NULL)
1390 memcpy(ai, pai, sizeof(*ai));
1391 ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
1392 memcpy(ai->ai_addr, pai->ai_addr, pai->ai_addrlen);
1394 if (pai->ai_canonname) {
1395 l = strlen(pai->ai_canonname) + 1;
1396 if ((ai->ai_canonname = malloc(l)) == NULL) {
1400 strlcpy(ai->ai_canonname, pai->ai_canonname, l);
1402 /* just to make sure */
1403 ai->ai_canonname = NULL;
1412 get_portmatch(const struct addrinfo *ai, const char *servname)
1415 /* get_port does not touch first argument when matchonly == 1. */
1416 /* LINTED const cast */
1417 return get_port((struct addrinfo *)ai, servname, 1);
1421 get_port(struct addrinfo *ai, const char *servname, int matchonly)
1428 if (servname == NULL)
1430 switch (ai->ai_family) {
1440 switch (ai->ai_socktype) {
1445 case SOCK_SEQPACKET:
1449 switch (ai->ai_family) {
1462 return EAI_SOCKTYPE;
1465 error = str2number(servname, &port);
1469 if (port < 0 || port > 65535)
1473 if (ai->ai_flags & AI_NUMERICSERV)
1476 switch (ai->ai_protocol) {
1491 if ((sp = getservbyname(servname, proto)) == NULL)
1497 switch (ai->ai_family) {
1499 ((struct sockaddr_in *)(void *)
1500 ai->ai_addr)->sin_port = port;
1504 ((struct sockaddr_in6 *)(void *)
1505 ai->ai_addr)->sin6_port = port;
1514 static const struct afd *
1517 const struct afd *afd;
1519 if (af == PF_UNSPEC)
1521 for (afd = afdl; afd->a_af; afd++) {
1522 if (afd->a_af == af)
1529 * post-2553: AI_ADDRCONFIG check. Determines which address families are
1530 * configured on the local system and correlates with pai->ai_family value.
1531 * If an address family is not configured on the system, it will not be
1532 * queried for. For this purpose, loopback addresses are not considered
1533 * configured addresses.
1535 * XXX PF_UNSPEC -> PF_INET6 + PF_INET mapping needs to be in sync with
1539 addrconfig(struct addrinfo *pai)
1541 struct ifaddrs *ifaddrs, *ifa;
1542 int seen_inet = 0, seen_inet6 = 0;
1544 if (getifaddrs(&ifaddrs) != 0)
1547 for (ifa = ifaddrs; ifa != NULL; ifa = ifa->ifa_next) {
1548 if (ifa->ifa_addr == NULL || (ifa->ifa_flags & IFF_UP) == 0)
1550 if ((ifa->ifa_flags & IFT_LOOP) != 0)
1552 switch (ifa->ifa_addr->sa_family) {
1558 if (!seen_inet6 && !is_ifdisabled(ifa->ifa_name))
1564 freeifaddrs(ifaddrs);
1566 switch(pai->ai_family) {
1572 if (seen_inet == seen_inet6)
1574 pai->ai_family = seen_inet ? AF_INET : AF_INET6;
1582 is_ifdisabled(char *name)
1584 struct in6_ndireq nd;
1587 if ((fd = _socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
1589 memset(&nd, 0, sizeof(nd));
1590 strlcpy(nd.ifname, name, sizeof(nd.ifname));
1591 if (_ioctl(fd, SIOCGIFINFO_IN6, &nd) < 0) {
1596 return ((nd.ndi.flags & ND6_IFF_IFDISABLED) != 0);
1599 /* convert a string to a scope identifier. XXX: IPv6 specific */
1601 ip6_str2scopeid(char *scope, struct sockaddr_in6 *sin6, u_int32_t *scopeid)
1604 struct in6_addr *a6;
1607 a6 = &sin6->sin6_addr;
1609 /* empty scopeid portion is invalid */
1613 if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6) ||
1614 IN6_IS_ADDR_MC_NODELOCAL(a6)) {
1616 * We currently assume a one-to-one mapping between links
1617 * and interfaces, so we simply use interface indices for
1618 * like-local scopes.
1620 *scopeid = if_nametoindex(scope);
1626 /* still unclear about literal, allow numeric only - placeholder */
1627 if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
1629 if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
1632 goto trynumeric; /* global */
1634 /* try to convert to a numeric id as a last resort */
1637 lscopeid = strtoul(scope, &ep, 10);
1638 *scopeid = (u_int32_t)(lscopeid & 0xffffffffUL);
1639 if (errno == 0 && ep && *ep == '\0' && *scopeid == lscopeid)
1649 addrinfo_id_func(char *buffer, size_t *buffer_size, va_list ap,
1655 const int op_id = 0; /* identifies the getaddrinfo for the cache */
1657 struct addrinfo *hints;
1660 int ai_flags, ai_family, ai_socktype, ai_protocol;
1661 size_t desired_size, size;
1663 statp = __res_state();
1664 res_options = statp->options & (RES_RECURSE | RES_DEFNAMES |
1665 RES_DNSRCH | RES_NOALIASES | RES_USE_INET6);
1667 hostname = va_arg(ap, char *);
1668 hints = va_arg(ap, struct addrinfo *);
1670 desired_size = sizeof(res_options) + sizeof(int) + sizeof(int) * 4;
1671 if (hostname != NULL) {
1672 size = strlen(hostname);
1673 desired_size += size + 1;
1677 if (desired_size > *buffer_size) {
1678 *buffer_size = desired_size;
1683 ai_flags = ai_family = ai_socktype = ai_protocol = 0;
1685 ai_flags = hints->ai_flags;
1686 ai_family = hints->ai_family;
1687 ai_socktype = hints->ai_socktype;
1688 ai_protocol = hints->ai_protocol;
1692 memcpy(p, &res_options, sizeof(res_options));
1693 p += sizeof(res_options);
1695 memcpy(p, &op_id, sizeof(int));
1698 memcpy(p, &ai_flags, sizeof(int));
1701 memcpy(p, &ai_family, sizeof(int));
1704 memcpy(p, &ai_socktype, sizeof(int));
1707 memcpy(p, &ai_protocol, sizeof(int));
1710 if (hostname != NULL)
1711 memcpy(p, hostname, size);
1713 *buffer_size = desired_size;
1714 return (NS_SUCCESS);
1718 addrinfo_marshal_func(char *buffer, size_t *buffer_size, void *retval,
1719 va_list ap, void *cache_mdata)
1721 struct addrinfo *ai, *cai;
1723 size_t desired_size, size, ai_size;
1725 ai = *((struct addrinfo **)retval);
1727 desired_size = sizeof(size_t);
1729 for (cai = ai; cai != NULL; cai = cai->ai_next) {
1730 desired_size += sizeof(struct addrinfo) + cai->ai_addrlen;
1731 if (cai->ai_canonname != NULL)
1732 desired_size += sizeof(size_t) +
1733 strlen(cai->ai_canonname);
1737 if (desired_size > *buffer_size) {
1738 /* this assignment is here for future use */
1740 *buffer_size = desired_size;
1744 memset(buffer, 0, desired_size);
1747 memcpy(p, &ai_size, sizeof(size_t));
1748 p += sizeof(size_t);
1749 for (cai = ai; cai != NULL; cai = cai->ai_next) {
1750 memcpy(p, cai, sizeof(struct addrinfo));
1751 p += sizeof(struct addrinfo);
1753 memcpy(p, cai->ai_addr, cai->ai_addrlen);
1754 p += cai->ai_addrlen;
1756 if (cai->ai_canonname != NULL) {
1757 size = strlen(cai->ai_canonname);
1758 memcpy(p, &size, sizeof(size_t));
1759 p += sizeof(size_t);
1761 memcpy(p, cai->ai_canonname, size);
1766 return (NS_SUCCESS);
1770 addrinfo_unmarshal_func(char *buffer, size_t buffer_size, void *retval,
1771 va_list ap, void *cache_mdata)
1773 struct addrinfo new_ai, *result, *sentinel, *lasts;
1776 size_t ai_size, ai_i, size;
1779 memcpy(&ai_size, p, sizeof(size_t));
1780 p += sizeof(size_t);
1784 for (ai_i = 0; ai_i < ai_size; ++ai_i) {
1785 memcpy(&new_ai, p, sizeof(struct addrinfo));
1786 p += sizeof(struct addrinfo);
1787 size = new_ai.ai_addrlen + sizeof(struct addrinfo) +
1790 sentinel = (struct addrinfo *)malloc(size);
1791 memset(sentinel, 0, size);
1793 memcpy(sentinel, &new_ai, sizeof(struct addrinfo));
1794 sentinel->ai_addr = (struct sockaddr *)_ALIGN((char *)sentinel +
1795 sizeof(struct addrinfo));
1797 memcpy(sentinel->ai_addr, p, new_ai.ai_addrlen);
1798 p += new_ai.ai_addrlen;
1800 if (new_ai.ai_canonname != NULL) {
1801 memcpy(&size, p, sizeof(size_t));
1802 p += sizeof(size_t);
1804 sentinel->ai_canonname = (char *)malloc(size + 1);
1805 memset(sentinel->ai_canonname, 0, size + 1);
1807 memcpy(sentinel->ai_canonname, p, size);
1811 if (result == NULL) {
1815 lasts->ai_next = sentinel;
1820 *((struct addrinfo **)retval) = result;
1821 return (NS_SUCCESS);
1823 #endif /* NS_CACHING */
1826 * FQDN hostname, DNS lookup
1829 explore_fqdn(const struct addrinfo *pai, const char *hostname,
1830 const char *servname, struct addrinfo **res)
1832 struct addrinfo *result;
1833 struct addrinfo *cur;
1837 static const nss_cache_info cache_info =
1838 NS_COMMON_CACHE_INFO_INITIALIZER(
1839 hosts, NULL, addrinfo_id_func, addrinfo_marshal_func,
1840 addrinfo_unmarshal_func);
1842 static const ns_dtab dtab[] = {
1843 NS_FILES_CB(_files_getaddrinfo, NULL)
1844 { NSSRC_DNS, _dns_getaddrinfo, NULL }, /* force -DHESIOD */
1845 NS_NIS_CB(_yp_getaddrinfo, NULL)
1847 NS_CACHE_CB(&cache_info)
1855 * if the servname does not match socktype/protocol, ignore it.
1857 if (get_portmatch(pai, servname) != 0)
1860 switch (_nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
1861 default_dns_files, hostname, pai)) {
1873 for (cur = result; cur; cur = cur->ai_next) {
1874 GET_PORT(cur, servname);
1875 /* canonname should be filled already */
1886 freeaddrinfo(result);
1891 static const char AskedForGot[] =
1892 "gethostby*.getanswer: asked for \"%s\", got \"%s\"";
1895 static struct addrinfo *
1896 getanswer(const querybuf *answer, int anslen, const char *qname, int qtype,
1897 const struct addrinfo *pai, res_state res)
1899 struct addrinfo sentinel, *cur;
1901 const struct afd *afd;
1908 int type, class, ancount, qdcount;
1909 int haveanswer, had_error;
1910 char tbuf[MAXDNAME];
1911 int (*name_ok)(const char *);
1912 char hostbuf[8*1024];
1914 memset(&sentinel, 0, sizeof(sentinel));
1918 eom = answer->buf + anslen;
1922 case T_ANY: /*use T_ANY only for T_A/T_AAAA lookup*/
1926 return (NULL); /* XXX should be abort(); */
1929 * find first satisfactory answer
1932 ancount = ntohs(hp->ancount);
1933 qdcount = ntohs(hp->qdcount);
1935 ep = hostbuf + sizeof hostbuf;
1936 cp = answer->buf + HFIXEDSZ;
1938 RES_SET_H_ERRNO(res, NO_RECOVERY);
1941 n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1942 if ((n < 0) || !(*name_ok)(bp)) {
1943 RES_SET_H_ERRNO(res, NO_RECOVERY);
1947 if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
1948 /* res_send() has already verified that the query name is the
1949 * same as the one we sent; this just gets the expanded name
1950 * (i.e., with the succeeding search-domain tacked on).
1952 n = strlen(bp) + 1; /* for the \0 */
1953 if (n >= MAXHOSTNAMELEN) {
1954 RES_SET_H_ERRNO(res, NO_RECOVERY);
1959 /* The qname can be abbreviated, but h_name is now absolute. */
1964 while (ancount-- > 0 && cp < eom && !had_error) {
1965 n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1966 if ((n < 0) || !(*name_ok)(bp)) {
1971 type = _getshort(cp);
1972 cp += INT16SZ; /* type */
1973 class = _getshort(cp);
1974 cp += INT16SZ + INT32SZ; /* class, TTL */
1976 cp += INT16SZ; /* len */
1977 if (class != C_IN) {
1978 /* XXX - debug? syslog? */
1980 continue; /* XXX - had_error++ ? */
1982 if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
1984 n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
1985 if ((n < 0) || !(*name_ok)(tbuf)) {
1990 /* Get canonical name. */
1991 n = strlen(tbuf) + 1; /* for the \0 */
1992 if (n > ep - bp || n >= MAXHOSTNAMELEN) {
1996 strlcpy(bp, tbuf, ep - bp);
2001 if (qtype == T_ANY) {
2002 if (!(type == T_A || type == T_AAAA)) {
2006 } else if (type != qtype) {
2008 if (type != T_KEY && type != T_SIG &&
2010 syslog(LOG_NOTICE|LOG_AUTH,
2011 "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
2012 qname, p_class(C_IN), p_type(qtype),
2016 continue; /* XXX - had_error++ ? */
2021 if (strcasecmp(canonname, bp) != 0) {
2023 syslog(LOG_NOTICE|LOG_AUTH,
2024 AskedForGot, canonname, bp);
2027 continue; /* XXX - had_error++ ? */
2029 if (type == T_A && n != INADDRSZ) {
2033 if (type == T_AAAA && n != IN6ADDRSZ) {
2037 #ifdef FILTER_V4MAPPED
2038 if (type == T_AAAA) {
2039 struct in6_addr in6;
2040 memcpy(&in6, cp, sizeof(in6));
2041 if (IN6_IS_ADDR_V4MAPPED(&in6)) {
2051 nn = strlen(bp) + 1; /* for the \0 */
2055 /* don't overwrite pai */
2057 ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
2058 afd = find_afd(ai.ai_family);
2063 cur->ai_next = get_ai(&ai, afd, (const char *)cp);
2064 if (cur->ai_next == NULL)
2066 while (cur && cur->ai_next)
2077 #if defined(RESOLVSORT)
2079 * We support only IPv4 address for backward
2080 * compatibility against gethostbyname(3).
2082 if (res->nsort && qtype == T_A) {
2083 if (addr4sort(&sentinel, res) < 0) {
2084 freeaddrinfo(sentinel.ai_next);
2085 RES_SET_H_ERRNO(res, NO_RECOVERY);
2089 #endif /*RESOLVSORT*/
2091 (void)get_canonname(pai, sentinel.ai_next, qname);
2093 (void)get_canonname(pai, sentinel.ai_next, canonname);
2094 RES_SET_H_ERRNO(res, NETDB_SUCCESS);
2095 return sentinel.ai_next;
2098 RES_SET_H_ERRNO(res, NO_RECOVERY);
2104 struct addrinfo *ai;
2109 addr4sort(struct addrinfo *sentinel, res_state res)
2111 struct addrinfo *ai;
2112 struct addr_ptr *addrs, addr;
2113 struct sockaddr_in *sin;
2120 for (ai = sentinel->ai_next; ai; ai = ai->ai_next)
2123 return 0; /* We don't need sorting. */
2124 if ((addrs = malloc(sizeof(struct addr_ptr) * naddrs)) == NULL)
2127 for (ai = sentinel->ai_next; ai; ai = ai->ai_next) {
2128 sin = (struct sockaddr_in *)ai->ai_addr;
2129 for (j = 0; (unsigned)j < res->nsort; j++) {
2130 if (res->sort_list[j].addr.s_addr ==
2131 (sin->sin_addr.s_addr & res->sort_list[j].mask))
2136 if (needsort == 0 && i > 0 && j < addrs[i - 1].aval)
2145 while (needsort < naddrs) {
2146 for (j = needsort - 1; j >= 0; j--) {
2147 if (addrs[j].aval > addrs[j+1].aval) {
2149 addrs[j] = addrs[j + 1];
2150 addrs[j + 1] = addr;
2158 for (i = 0; i < naddrs; ++i) {
2159 ai->ai_next = addrs[i].ai;
2166 #endif /*RESOLVSORT*/
2170 _dns_getaddrinfo(void *rv, void *cb_data, va_list ap)
2172 struct addrinfo *ai;
2173 querybuf *buf, *buf2;
2174 const char *hostname;
2175 const struct addrinfo *pai;
2176 struct addrinfo sentinel, *cur;
2177 struct res_target q, q2;
2180 hostname = va_arg(ap, char *);
2181 pai = va_arg(ap, const struct addrinfo *);
2183 memset(&q, 0, sizeof(q));
2184 memset(&q2, 0, sizeof(q2));
2185 memset(&sentinel, 0, sizeof(sentinel));
2188 buf = malloc(sizeof(*buf));
2190 RES_SET_H_ERRNO(res, NETDB_INTERNAL);
2193 buf2 = malloc(sizeof(*buf2));
2196 RES_SET_H_ERRNO(res, NETDB_INTERNAL);
2200 switch (pai->ai_family) {
2205 q.answer = buf->buf;
2206 q.anslen = sizeof(buf->buf);
2211 q2.answer = buf2->buf;
2212 q2.anslen = sizeof(buf2->buf);
2218 q.answer = buf->buf;
2219 q.anslen = sizeof(buf->buf);
2225 q.answer = buf->buf;
2226 q.anslen = sizeof(buf->buf);
2234 res = __res_state();
2235 if ((res->options & RES_INIT) == 0 && res_ninit(res) == -1) {
2236 RES_SET_H_ERRNO(res, NETDB_INTERNAL);
2242 if (res_searchN(hostname, &q, res) < 0) {
2249 ai = getanswer(buf2, q2.n, q2.name, q2.qtype, pai, res);
2252 while (cur && cur->ai_next)
2256 ai = getanswer(buf, q.n, q.name, q.qtype, pai, res);
2261 if (sentinel.ai_next == NULL)
2262 switch (res->res_h_errno) {
2263 case HOST_NOT_FOUND:
2270 *((struct addrinfo **)rv) = sentinel.ai_next;
2275 _sethtent(FILE **hostf)
2278 *hostf = fopen(_PATH_HOSTS, "r");
2284 _endhtent(FILE **hostf)
2287 (void) fclose(*hostf);
2292 static struct addrinfo *
2293 _gethtent(FILE **hostf, const char *name, const struct addrinfo *pai)
2296 char *cp, *tname, *cname;
2297 struct addrinfo hints, *res0, *res;
2300 char hostbuf[8*1024];
2302 if (!*hostf && !(*hostf = fopen(_PATH_HOSTS, "r")))
2305 if (!(p = fgets(hostbuf, sizeof hostbuf, *hostf)))
2309 cp = strpbrk(p, "#\n");
2312 if (!(cp = strpbrk(p, " \t")))
2317 /* if this is not something we're looking for, skip it. */
2319 if (*cp == ' ' || *cp == '\t') {
2326 if ((cp = strpbrk(cp, " \t")) != NULL)
2328 if (strcasecmp(name, tname) == 0)
2334 /* we should not glob socktype/protocol here */
2335 memset(&hints, 0, sizeof(hints));
2336 hints.ai_family = pai->ai_family;
2337 hints.ai_socktype = SOCK_DGRAM;
2338 hints.ai_protocol = 0;
2339 hints.ai_flags = AI_NUMERICHOST;
2340 error = getaddrinfo(addr, "0", &hints, &res0);
2343 #ifdef FILTER_V4MAPPED
2344 /* XXX should check all items in the chain */
2345 if (res0->ai_family == AF_INET6 &&
2346 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)res0->ai_addr)->sin6_addr)) {
2351 for (res = res0; res; res = res->ai_next) {
2353 res->ai_flags = pai->ai_flags;
2354 res->ai_socktype = pai->ai_socktype;
2355 res->ai_protocol = pai->ai_protocol;
2357 if (pai->ai_flags & AI_CANONNAME) {
2358 if (get_canonname(pai, res, cname) != 0) {
2369 _files_getaddrinfo(void *rv, void *cb_data, va_list ap)
2372 const struct addrinfo *pai;
2373 struct addrinfo sentinel, *cur;
2377 name = va_arg(ap, char *);
2378 pai = va_arg(ap, struct addrinfo *);
2380 memset(&sentinel, 0, sizeof(sentinel));
2384 while ((p = _gethtent(&hostf, name, pai)) != NULL) {
2386 while (cur && cur->ai_next)
2391 *((struct addrinfo **)rv) = sentinel.ai_next;
2392 if (sentinel.ai_next == NULL)
2399 static struct addrinfo *
2400 _yphostent(char *line, const struct addrinfo *pai)
2402 struct addrinfo sentinel, *cur;
2403 struct addrinfo hints, *res, *res0;
2406 const char *addr, *canonname;
2410 addr = canonname = NULL;
2412 memset(&sentinel, 0, sizeof(sentinel));
2416 /* terminate line */
2417 cp = strchr(p, '\n');
2424 cp = strpbrk(p, " \t");
2426 if (canonname == NULL)
2436 if (*cp == ' ' || *cp == '\t') {
2442 if ((cp = strpbrk(cp, " \t")) != NULL)
2447 hints.ai_flags = AI_NUMERICHOST;
2448 error = getaddrinfo(addr, NULL, &hints, &res0);
2450 for (res = res0; res; res = res->ai_next) {
2452 res->ai_flags = pai->ai_flags;
2454 if (pai->ai_flags & AI_CANONNAME)
2455 (void)get_canonname(pai, res, canonname);
2460 cur->ai_next = res0;
2461 while (cur && cur->ai_next)
2471 return sentinel.ai_next;
2476 _yp_getaddrinfo(void *rv, void *cb_data, va_list ap)
2478 struct addrinfo sentinel, *cur;
2479 struct addrinfo *ai = NULL;
2483 const struct addrinfo *pai;
2486 if (_yp_check(&ypdomain) == 0)
2489 name = va_arg(ap, char *);
2490 pai = va_arg(ap, const struct addrinfo *);
2492 memset(&sentinel, 0, sizeof(sentinel));
2495 /* hosts.byname is only for IPv4 (Solaris8) */
2496 if (pai->ai_family == PF_UNSPEC || pai->ai_family == PF_INET) {
2497 r = yp_match(ypdomain, "hosts.byname", name,
2498 (int)strlen(name), &ypbuf, &ypbuflen);
2500 struct addrinfo ai4;
2503 ai4.ai_family = AF_INET;
2504 ai = _yphostent(ypbuf, &ai4);
2507 while (cur && cur->ai_next)
2514 /* ipnodes.byname can hold both IPv4/v6 */
2515 r = yp_match(ypdomain, "ipnodes.byname", name,
2516 (int)strlen(name), &ypbuf, &ypbuflen);
2518 ai = _yphostent(ypbuf, pai);
2524 if (sentinel.ai_next == NULL) {
2525 RES_SET_H_ERRNO(__res_state(), HOST_NOT_FOUND);
2528 *((struct addrinfo **)rv) = sentinel.ai_next;
2533 /* resolver logic */
2536 * Formulate a normal query, send, and await answer.
2537 * Returned answer is placed in supplied buffer "answer".
2538 * Perform preliminary check of answer, returning success only
2539 * if no error is indicated and the answer count is nonzero.
2540 * Return the size of the response on success, -1 on error.
2541 * Error number is left in h_errno.
2543 * Caller must parse answer and determine whether it answers the question.
2546 res_queryN(const char *name, struct res_target *target, res_state res)
2552 struct res_target *t;
2559 buf = malloc(MAXPACKET);
2561 RES_SET_H_ERRNO(res, NETDB_INTERNAL);
2565 for (t = target; t; t = t->next) {
2570 hp = (HEADER *)(void *)t->answer;
2572 /* make it easier... */
2578 oflags = res->_flags;
2581 hp->rcode = NOERROR; /* default */
2584 if (res->options & RES_DEBUG)
2585 printf(";; res_query(%s, %d, %d)\n", name, class, type);
2588 n = res_nmkquery(res, QUERY, name, class, type, NULL, 0, NULL,
2590 if (n > 0 && (res->_flags & RES_F_EDNS0ERR) == 0 &&
2591 (res->options & (RES_USE_EDNS0|RES_USE_DNSSEC)) != 0U)
2592 n = res_nopt(res, n, buf, MAXPACKET, anslen);
2595 if (res->options & RES_DEBUG)
2596 printf(";; res_query: mkquery failed\n");
2599 RES_SET_H_ERRNO(res, NO_RECOVERY);
2602 n = res_nsend(res, buf, n, answer, anslen);
2605 * if the query choked with EDNS0, retry
2608 if ((res->options & (RES_USE_EDNS0|RES_USE_DNSSEC))
2610 ((oflags ^ res->_flags) & RES_F_EDNS0ERR) != 0) {
2611 res->_flags |= RES_F_EDNS0ERR;
2612 if (res->options & RES_DEBUG)
2613 printf(";; res_nquery: retry without EDNS0\n");
2616 rcode = hp->rcode; /* record most recent error */
2618 if (res->options & RES_DEBUG)
2619 printf(";; res_query: send error\n");
2625 hp->rcode = FORMERR; /* XXX not very informative */
2626 if (hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
2627 rcode = hp->rcode; /* record most recent error */
2629 if (res->options & RES_DEBUG)
2630 printf(";; rcode = %u, ancount=%u\n", hp->rcode,
2631 ntohs(hp->ancount));
2636 ancount += ntohs(hp->ancount);
2646 RES_SET_H_ERRNO(res, HOST_NOT_FOUND);
2649 RES_SET_H_ERRNO(res, TRY_AGAIN);
2652 RES_SET_H_ERRNO(res, NO_DATA);
2658 RES_SET_H_ERRNO(res, NO_RECOVERY);
2667 * Formulate a normal query, send, and retrieve answer in supplied buffer.
2668 * Return the size of the response on success, -1 on error.
2669 * If enabled, implement search rules until answer or unrecoverable failure
2670 * is detected. Error code, if any, is left in h_errno.
2673 res_searchN(const char *name, struct res_target *target, res_state res)
2675 const char *cp, * const *domain;
2676 HEADER *hp = (HEADER *)(void *)target->answer; /*XXX*/
2678 int trailing_dot, ret, saved_herrno;
2679 int got_nodata = 0, got_servfail = 0, root_on_list = 0;
2680 int tried_as_is = 0;
2682 char abuf[MAXDNAME];
2685 RES_SET_H_ERRNO(res, HOST_NOT_FOUND); /* default, if we never query */
2687 for (cp = name; *cp; cp++)
2688 dots += (*cp == '.');
2690 if (cp > name && *--cp == '.')
2694 * if there aren't any dots, it could be a user-level alias
2697 (cp = res_hostalias(res, name, abuf, sizeof(abuf))) != NULL)
2698 return (res_queryN(cp, target, res));
2701 * If there are enough dots in the name, let's just give it a
2702 * try 'as is'. The threshold can be set with the "ndots" option.
2703 * Also, query 'as is', if there is a trailing dot in the name.
2706 if (dots >= res->ndots || trailing_dot) {
2707 ret = res_querydomainN(name, NULL, target, res);
2708 if (ret > 0 || trailing_dot)
2710 if (errno == ECONNREFUSED) {
2711 RES_SET_H_ERRNO(res, TRY_AGAIN);
2714 switch (res->res_h_errno) {
2716 case HOST_NOT_FOUND:
2719 if (hp->rcode == SERVFAIL)
2725 saved_herrno = res->res_h_errno;
2730 * We do at least one level of search if
2731 * - there is no dot and RES_DEFNAME is set, or
2732 * - there is at least one dot, there is no trailing dot,
2733 * and RES_DNSRCH is set.
2735 if ((!dots && (res->options & RES_DEFNAMES)) ||
2736 (dots && !trailing_dot && (res->options & RES_DNSRCH))) {
2739 for (domain = (const char * const *)res->dnsrch;
2744 if (domain[0][0] == '\0' ||
2745 (domain[0][0] == '.' && domain[0][1] == '\0'))
2748 if (root_on_list && tried_as_is)
2751 ret = res_querydomainN(name, *domain, target, res);
2756 * If no server present, give up.
2757 * If name isn't found in this domain,
2758 * keep trying higher domains in the search list
2759 * (if that's enabled).
2760 * On a NO_DATA error, keep trying, otherwise
2761 * a wildcard entry of another type could keep us
2762 * from finding this entry higher in the domain.
2763 * If we get some other error (negative answer or
2764 * server failure), then stop searching up,
2765 * but try the input name below in case it's
2768 if (errno == ECONNREFUSED) {
2769 RES_SET_H_ERRNO(res, TRY_AGAIN);
2773 switch (res->res_h_errno) {
2777 case HOST_NOT_FOUND:
2782 if (hp->rcode == SERVFAIL) {
2783 /* try next search element, if any */
2788 /* anything else implies that we're done */
2792 * if we got here for some reason other than DNSRCH,
2793 * we only wanted one iteration of the loop, so stop.
2795 if (!(res->options & RES_DNSRCH))
2800 switch (res->res_h_errno) {
2802 case HOST_NOT_FOUND:
2805 if (hp->rcode == SERVFAIL)
2813 * If the query has not already been tried as is then try it
2814 * unless RES_NOTLDQUERY is set and there were no dots.
2816 if ((dots || !searched || !(res->options & RES_NOTLDQUERY)) &&
2817 !(tried_as_is || root_on_list)) {
2818 ret = res_querydomainN(name, NULL, target, res);
2824 * if we got here, we didn't satisfy the search.
2825 * if we did an initial full query, return that query's h_errno
2826 * (note that we wouldn't be here if that query had succeeded).
2827 * else if we ever got a nodata, send that back as the reason.
2828 * else send back meaningless h_errno, that being the one from
2829 * the last DNSRCH we did.
2832 if (saved_herrno != -1)
2833 RES_SET_H_ERRNO(res, saved_herrno);
2834 else if (got_nodata)
2835 RES_SET_H_ERRNO(res, NO_DATA);
2836 else if (got_servfail)
2837 RES_SET_H_ERRNO(res, TRY_AGAIN);
2842 * Perform a call on res_query on the concatenation of name and domain,
2843 * removing a trailing dot from name if domain is NULL.
2846 res_querydomainN(const char *name, const char *domain,
2847 struct res_target *target, res_state res)
2849 char nbuf[MAXDNAME];
2850 const char *longname = nbuf;
2854 if (res->options & RES_DEBUG)
2855 printf(";; res_querydomain(%s, %s)\n",
2856 name, domain?domain:"<Nil>");
2858 if (domain == NULL) {
2860 * Check for trailing '.';
2861 * copy without '.' if present.
2864 if (n >= MAXDNAME) {
2865 RES_SET_H_ERRNO(res, NO_RECOVERY);
2868 if (n > 0 && name[--n] == '.') {
2869 strncpy(nbuf, name, n);
2876 if (n + d + 1 >= MAXDNAME) {
2877 RES_SET_H_ERRNO(res, NO_RECOVERY);
2880 snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
2882 return (res_queryN(longname, target, res));