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 <sys/queue.h>
67 #include <net/if_var.h>
68 #include <sys/sysctl.h>
69 #include <sys/ioctl.h>
70 #include <netinet6/in6_var.h> /* XXX */
72 #include <arpa/inet.h>
73 #include <arpa/nameser.h>
75 #include <rpcsvc/yp_prot.h>
76 #include <rpcsvc/ypclnt.h>
87 #include "res_config.h"
95 #include "un-namespace.h"
96 #include "libc_private.h"
101 #if defined(__KAME__) && defined(INET6)
109 static const char in_addrany[] = { 0, 0, 0, 0 };
110 static const char in_loopback[] = { 127, 0, 0, 1 };
112 static const char in6_addrany[] = {
113 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
115 static const char in6_loopback[] = {
116 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
121 TAILQ_ENTRY(policyqueue) pc_entry;
123 struct in6_addrpolicy pc_policy;
126 TAILQ_HEAD(policyhead, policyqueue);
128 static const struct afd {
133 const char *a_addrany;
134 const char *a_loopback;
139 {PF_INET6, sizeof(struct in6_addr),
140 sizeof(struct sockaddr_in6),
141 offsetof(struct sockaddr_in6, sin6_addr),
142 in6_addrany, in6_loopback, 1},
147 {PF_INET, sizeof(struct in_addr),
148 sizeof(struct sockaddr_in),
149 offsetof(struct sockaddr_in, sin_addr),
150 in_addrany, in_loopback, 0},
151 {0, 0, 0, 0, NULL, NULL, 0},
158 const char *e_protostr;
160 #define WILD_AF(ex) ((ex)->e_wild & 0x01)
161 #define WILD_SOCKTYPE(ex) ((ex)->e_wild & 0x02)
162 #define WILD_PROTOCOL(ex) ((ex)->e_wild & 0x04)
165 static const struct explore explore[] = {
167 { PF_LOCAL, ANY, ANY, NULL, 0x01 },
170 { PF_INET6, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
171 { PF_INET6, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
172 { PF_INET6, SOCK_STREAM, IPPROTO_SCTP, "sctp", 0x03 },
173 { PF_INET6, SOCK_SEQPACKET, IPPROTO_SCTP, "sctp", 0x07 },
174 { PF_INET6, SOCK_RAW, ANY, NULL, 0x05 },
176 { PF_INET, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
177 { PF_INET, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
178 { PF_INET, SOCK_STREAM, IPPROTO_SCTP, "sctp", 0x03 },
179 { PF_INET, SOCK_SEQPACKET, IPPROTO_SCTP, "sctp", 0x07 },
180 { PF_INET, SOCK_RAW, ANY, NULL, 0x05 },
181 { -1, 0, 0, NULL, 0 },
190 #define AIO_SRCFLAG_DEPRECATED 0x1
194 struct sockaddr_storage aiou_ss;
195 struct sockaddr aiou_sa;
197 #define aio_srcsa aio_src_un.aiou_sa
198 u_int32_t aio_srcflag;
201 struct policyqueue *aio_srcpolicy;
202 struct policyqueue *aio_dstpolicy;
203 struct addrinfo *aio_ai;
207 static const ns_src default_dns_files[] = {
208 { NSSRC_FILES, NS_SUCCESS },
209 { NSSRC_DNS, NS_SUCCESS },
214 struct res_target *next;
215 const char *name; /* domain name */
216 int qclass, qtype; /* class and type of query */
217 u_char *answer; /* buffer to put answer */
218 int anslen; /* size of answer buffer */
219 int n; /* result length */
222 #define MAXPACKET (64*1024)
226 u_char buf[MAXPACKET];
229 static int str2number(const char *, int *);
230 static int explore_copy(const struct addrinfo *, const struct addrinfo *,
232 static int explore_null(const struct addrinfo *,
233 const char *, struct addrinfo **);
234 static int explore_numeric(const struct addrinfo *, const char *,
235 const char *, struct addrinfo **, const char *);
236 static int explore_numeric_scope(const struct addrinfo *, const char *,
237 const char *, struct addrinfo **);
238 static int get_canonname(const struct addrinfo *,
239 struct addrinfo *, const char *);
240 static struct addrinfo *get_ai(const struct addrinfo *,
241 const struct afd *, const char *);
242 static struct addrinfo *copy_ai(const struct addrinfo *);
243 static int get_portmatch(const struct addrinfo *, const char *);
244 static int get_port(struct addrinfo *, const char *, int);
245 static const struct afd *find_afd(int);
246 static int addrconfig(struct addrinfo *);
247 static void set_source(struct ai_order *, struct policyhead *);
248 static int comp_dst(const void *, const void *);
250 static int ip6_str2scopeid(char *, struct sockaddr_in6 *, u_int32_t *);
252 static int gai_addr2scopetype(struct sockaddr *);
254 static int explore_fqdn(const struct addrinfo *, const char *,
255 const char *, struct addrinfo **);
257 static int reorder(struct addrinfo *);
258 static int get_addrselectpolicy(struct policyhead *);
259 static void free_addrselectpolicy(struct policyhead *);
260 static struct policyqueue *match_addrselectpolicy(struct sockaddr *,
261 struct policyhead *);
262 static int matchlen(struct sockaddr *, struct sockaddr *);
264 static struct addrinfo *getanswer(const querybuf *, int, const char *, int,
265 const struct addrinfo *, res_state);
266 #if defined(RESOLVSORT)
267 static int addr4sort(struct addrinfo *, res_state);
269 static int _dns_getaddrinfo(void *, void *, va_list);
270 static void _sethtent(FILE **);
271 static void _endhtent(FILE **);
272 static struct addrinfo *_gethtent(FILE **, const char *,
273 const struct addrinfo *);
274 static int _files_getaddrinfo(void *, void *, va_list);
276 static struct addrinfo *_yphostent(char *, const struct addrinfo *);
277 static int _yp_getaddrinfo(void *, void *, va_list);
280 static int addrinfo_id_func(char *, size_t *, va_list, void *);
281 static int addrinfo_marshal_func(char *, size_t *, void *, va_list, void *);
282 static int addrinfo_unmarshal_func(char *, size_t, void *, va_list, void *);
285 static int res_queryN(const char *, struct res_target *, res_state);
286 static int res_searchN(const char *, struct res_target *, res_state);
287 static int res_querydomainN(const char *, const char *,
288 struct res_target *, res_state);
290 /* XXX macros that make external reference is BAD. */
292 #define GET_AI(ai, afd, addr) \
294 /* external reference: pai, error, and label free */ \
295 (ai) = get_ai(pai, (afd), (addr)); \
296 if ((ai) == NULL) { \
297 error = EAI_MEMORY; \
300 } while (/*CONSTCOND*/0)
302 #define GET_PORT(ai, serv) \
304 /* external reference: error and label free */ \
305 error = get_port((ai), (serv), 0); \
308 } while (/*CONSTCOND*/0)
310 #define GET_CANONNAME(ai, str) \
312 /* external reference: pai, error and label free */ \
313 error = get_canonname(pai, (ai), (str)); \
316 } while (/*CONSTCOND*/0)
320 /* external reference: error, and label bad */ \
324 } while (/*CONSTCOND*/0)
326 #define MATCH_FAMILY(x, y, w) \
327 ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC || (y) == PF_UNSPEC)))
328 #define MATCH(x, y, w) \
329 ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY)))
332 freeaddrinfo(struct addrinfo *ai)
334 struct addrinfo *next;
338 if (ai->ai_canonname)
339 free(ai->ai_canonname);
340 /* no need to free(ai->ai_addr) */
347 str2number(const char *p, int *portp)
356 v = strtoul(p, &ep, 10);
357 if (errno == 0 && ep && *ep == '\0' && v <= UINT_MAX) {
365 getaddrinfo(const char *hostname, const char *servname,
366 const struct addrinfo *hints, struct addrinfo **res)
368 struct addrinfo sentinel;
369 struct addrinfo *cur;
371 struct addrinfo ai, ai0, *afai;
372 struct addrinfo *pai;
373 const struct afd *afd;
374 const struct explore *ex;
375 struct addrinfo *afailist[sizeof(afdl)/sizeof(afdl[0])];
376 struct addrinfo *afai_unspec;
380 /* ensure we return NULL on errors */
383 memset(&ai, 0, sizeof(ai));
385 memset(afailist, 0, sizeof(afailist));
388 memset(&sentinel, 0, sizeof(sentinel));
392 pai->ai_family = PF_UNSPEC;
393 pai->ai_socktype = ANY;
394 pai->ai_protocol = ANY;
396 pai->ai_canonname = NULL;
400 if (hostname == NULL && servname == NULL)
403 /* error check for hints */
404 if (hints->ai_addrlen || hints->ai_canonname ||
405 hints->ai_addr || hints->ai_next)
406 ERR(EAI_BADHINTS); /* xxx */
407 if (hints->ai_flags & ~AI_MASK)
409 switch (hints->ai_family) {
419 memcpy(pai, hints, sizeof(*pai));
422 * if both socktype/protocol are specified, check if they
423 * are meaningful combination.
425 if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
426 for (ex = explore; ex->e_af >= 0; ex++) {
427 if (!MATCH_FAMILY(pai->ai_family, ex->e_af,
430 if (!MATCH(pai->ai_socktype, ex->e_socktype,
433 if (!MATCH(pai->ai_protocol, ex->e_protocol,
447 * check for special cases. (1) numeric servname is disallowed if
448 * socktype/protocol are left unspecified. (2) servname is disallowed
449 * for raw and other inet{,6} sockets.
451 if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
453 || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
456 ai0 = *pai; /* backup *pai */
458 if (pai->ai_family == PF_UNSPEC) {
460 pai->ai_family = PF_INET6;
462 pai->ai_family = PF_INET;
465 error = get_portmatch(pai, servname);
475 * NULL hostname, or numeric hostname.
476 * If numeric representation of AF1 can be interpreted as FQDN
477 * representation of AF2, we need to think again about the code below.
480 for (afd = afdl; afd->a_af; afd++) {
483 if (!MATCH_FAMILY(pai->ai_family, afd->a_af, 1))
486 if (pai->ai_family == PF_UNSPEC)
487 pai->ai_family = afd->a_af;
489 if (hostname == NULL) {
490 error = explore_null(pai, servname,
491 &afailist[afd - afdl]);
494 * Errors from explore_null should be unexpected and
495 * be caught to avoid returning an incomplete result.
500 error = explore_numeric_scope(pai, hostname, servname,
501 &afailist[afd - afdl]);
504 * explore_numeric_scope returns an error for address
505 * families that do not match that of hostname.
506 * Thus we should not catch the error at this moment.
510 if (!error && afailist[afd - afdl])
518 if (hostname == NULL)
519 ERR(EAI_NONAME); /* used to be EAI_NODATA */
520 if (pai->ai_flags & AI_NUMERICHOST)
523 if ((pai->ai_flags & AI_ADDRCONFIG) != 0 && !addrconfig(&ai0))
527 * hostname as alphabetical name.
530 error = explore_fqdn(pai, hostname, servname, &afai_unspec);
533 for (ex = explore; ex->e_af >= 0; ex++) {
536 if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
538 if (!MATCH(pai->ai_socktype, ex->e_socktype,
541 if (!MATCH(pai->ai_protocol, ex->e_protocol,
545 if (pai->ai_family == PF_UNSPEC)
546 pai->ai_family = ex->e_af;
547 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
548 pai->ai_socktype = ex->e_socktype;
549 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
550 pai->ai_protocol = ex->e_protocol;
553 * if the servname does not match socktype/protocol, ignore it.
555 if (get_portmatch(pai, servname) != 0)
561 if ((afd = find_afd(pai->ai_family)) == NULL)
563 /* XXX assumes that afd points inside afdl[] */
564 afai = afailist[afd - afdl];
569 error = explore_copy(pai, afai, &cur->ai_next);
573 while (cur && cur->ai_next)
578 * ensure we return either:
579 * - error == 0, non-NULL *res
580 * - error != 0, NULL *res
583 if (sentinel.ai_next) {
585 * If the returned entry is for an active connection,
586 * and the given name is not numeric, reorder the
587 * list, so that the application would try the list
588 * in the most efficient order. Since the head entry
589 * of the original list may contain ai_canonname and
590 * that entry may be moved elsewhere in the new list,
591 * we keep the pointer and will restore it in the new
592 * head entry. (Note that RFC3493 requires the head
593 * entry store it when requested by the caller).
595 if (hints == NULL || !(hints->ai_flags & AI_PASSIVE)) {
600 sentinel.ai_next->ai_canonname;
601 sentinel.ai_next->ai_canonname = NULL;
602 (void)reorder(&sentinel);
603 if (sentinel.ai_next->ai_canonname ==
605 sentinel.ai_next->ai_canonname
607 } else if (canonname != NULL)
611 *res = sentinel.ai_next;
618 freeaddrinfo(afai_unspec);
619 for (afd = afdl; afd->a_af; afd++) {
620 if (afailist[afd - afdl])
621 freeaddrinfo(afailist[afd - afdl]);
624 if (sentinel.ai_next)
625 freeaddrinfo(sentinel.ai_next);
631 reorder(struct addrinfo *sentinel)
633 struct addrinfo *ai, **aip;
634 struct ai_order *aio;
636 struct policyhead policyhead;
638 /* count the number of addrinfo elements for sorting. */
639 for (n = 0, ai = sentinel->ai_next; ai != NULL; ai = ai->ai_next, n++)
643 * If the number is small enough, we can skip the reordering process.
648 /* allocate a temporary array for sort and initialization of it. */
649 if ((aio = malloc(sizeof(*aio) * n)) == NULL)
650 return(n); /* give up reordering */
651 memset(aio, 0, sizeof(*aio) * n);
653 /* retrieve address selection policy from the kernel */
654 TAILQ_INIT(&policyhead);
655 if (!get_addrselectpolicy(&policyhead)) {
656 /* no policy is installed into kernel, we don't sort. */
661 for (i = 0, ai = sentinel->ai_next; i < n; ai = ai->ai_next, i++) {
663 aio[i].aio_dstscope = gai_addr2scopetype(ai->ai_addr);
664 aio[i].aio_dstpolicy = match_addrselectpolicy(ai->ai_addr,
666 set_source(&aio[i], &policyhead);
669 /* perform sorting. */
670 qsort(aio, n, sizeof(*aio), comp_dst);
672 /* reorder the addrinfo chain. */
673 for (i = 0, aip = &sentinel->ai_next; i < n; i++) {
674 *aip = aio[i].aio_ai;
675 aip = &aio[i].aio_ai->ai_next;
679 /* cleanup and return */
681 free_addrselectpolicy(&policyhead);
686 get_addrselectpolicy(struct policyhead *head)
689 int mib[] = { CTL_NET, PF_INET6, IPPROTO_IPV6, IPV6CTL_ADDRCTLPOLICY };
692 struct in6_addrpolicy *pol, *ep;
694 if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), NULL, &l, NULL, 0) < 0)
698 if ((buf = malloc(l)) == NULL)
700 if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), buf, &l, NULL, 0) < 0) {
705 ep = (struct in6_addrpolicy *)(buf + l);
706 for (pol = (struct in6_addrpolicy *)buf; pol + 1 <= ep; pol++) {
707 struct policyqueue *new;
709 if ((new = malloc(sizeof(*new))) == NULL) {
710 free_addrselectpolicy(head); /* make the list empty */
713 new->pc_policy = *pol;
714 TAILQ_INSERT_TAIL(head, new, pc_entry);
725 free_addrselectpolicy(struct policyhead *head)
727 struct policyqueue *ent, *nent;
729 for (ent = TAILQ_FIRST(head); ent; ent = nent) {
730 nent = TAILQ_NEXT(ent, pc_entry);
731 TAILQ_REMOVE(head, ent, pc_entry);
736 static struct policyqueue *
737 match_addrselectpolicy(struct sockaddr *addr, struct policyhead *head)
740 struct policyqueue *ent, *bestent = NULL;
741 struct in6_addrpolicy *pol;
742 int matchlen, bestmatchlen = -1;
743 u_char *mp, *ep, *k, *p, m;
744 struct sockaddr_in6 key;
746 switch(addr->sa_family) {
748 key = *(struct sockaddr_in6 *)addr;
751 /* convert the address into IPv4-mapped IPv6 address. */
752 memset(&key, 0, sizeof(key));
753 key.sin6_family = AF_INET6;
754 key.sin6_len = sizeof(key);
755 key.sin6_addr.s6_addr[10] = 0xff;
756 key.sin6_addr.s6_addr[11] = 0xff;
757 memcpy(&key.sin6_addr.s6_addr[12],
758 &((struct sockaddr_in *)addr)->sin_addr, 4);
764 for (ent = TAILQ_FIRST(head); ent; ent = TAILQ_NEXT(ent, pc_entry)) {
765 pol = &ent->pc_policy;
768 mp = (u_char *)&pol->addrmask.sin6_addr;
769 ep = mp + 16; /* XXX: scope field? */
770 k = (u_char *)&key.sin6_addr;
771 p = (u_char *)&pol->addr.sin6_addr;
772 for (; mp < ep && *mp; mp++, k++, p++) {
775 goto next; /* not match */
776 if (m == 0xff) /* short cut for a typical case */
786 /* matched. check if this is better than the current best. */
787 if (matchlen > bestmatchlen) {
789 bestmatchlen = matchlen;
804 set_source(struct ai_order *aio, struct policyhead *ph)
806 struct addrinfo ai = *aio->aio_ai;
807 struct sockaddr_storage ss;
811 /* set unspec ("no source is available"), just in case */
812 aio->aio_srcsa.sa_family = AF_UNSPEC;
813 aio->aio_srcscope = -1;
815 switch(ai.ai_family) {
821 default: /* ignore unsupported AFs explicitly */
825 /* XXX: make a dummy addrinfo to call connect() */
826 ai.ai_socktype = SOCK_DGRAM;
827 ai.ai_protocol = IPPROTO_UDP; /* is UDP too specific? */
829 memset(&ss, 0, sizeof(ss));
830 memcpy(&ss, ai.ai_addr, ai.ai_addrlen);
831 ai.ai_addr = (struct sockaddr *)&ss;
832 get_port(&ai, "1", 0);
834 /* open a socket to get the source address for the given dst */
835 if ((s = _socket(ai.ai_family, ai.ai_socktype, ai.ai_protocol)) < 0)
836 return; /* give up */
837 if (_connect(s, ai.ai_addr, ai.ai_addrlen) < 0)
839 srclen = ai.ai_addrlen;
840 if (_getsockname(s, &aio->aio_srcsa, &srclen) < 0) {
841 aio->aio_srcsa.sa_family = AF_UNSPEC;
844 aio->aio_srcscope = gai_addr2scopetype(&aio->aio_srcsa);
845 aio->aio_srcpolicy = match_addrselectpolicy(&aio->aio_srcsa, ph);
846 aio->aio_matchlen = matchlen(&aio->aio_srcsa, aio->aio_ai->ai_addr);
848 if (ai.ai_family == AF_INET6) {
849 struct in6_ifreq ifr6;
852 memset(&ifr6, 0, sizeof(ifr6));
853 memcpy(&ifr6.ifr_addr, ai.ai_addr, ai.ai_addrlen);
854 if (_ioctl(s, SIOCGIFAFLAG_IN6, &ifr6) == 0) {
855 flags6 = ifr6.ifr_ifru.ifru_flags6;
856 if ((flags6 & IN6_IFF_DEPRECATED))
857 aio->aio_srcflag |= AIO_SRCFLAG_DEPRECATED;
868 matchlen(struct sockaddr *src, struct sockaddr *dst)
875 switch (src->sa_family) {
878 s = (u_char *)&((struct sockaddr_in6 *)src)->sin6_addr;
879 d = (u_char *)&((struct sockaddr_in6 *)dst)->sin6_addr;
880 addrlen = sizeof(struct in6_addr);
885 s = (u_char *)&((struct sockaddr_in *)src)->sin_addr;
886 d = (u_char *)&((struct sockaddr_in *)dst)->sin_addr;
887 addrlen = sizeof(struct in_addr);
895 if ((r = (*d++ ^ *s++)) != 0) {
896 while (r < addrlen * 8) {
907 comp_dst(const void *arg1, const void *arg2)
909 const struct ai_order *dst1 = arg1, *dst2 = arg2;
912 * Rule 1: Avoid unusable destinations.
913 * XXX: we currently do not consider if an appropriate route exists.
915 if (dst1->aio_srcsa.sa_family != AF_UNSPEC &&
916 dst2->aio_srcsa.sa_family == AF_UNSPEC) {
919 if (dst1->aio_srcsa.sa_family == AF_UNSPEC &&
920 dst2->aio_srcsa.sa_family != AF_UNSPEC) {
924 /* Rule 2: Prefer matching scope. */
925 if (dst1->aio_dstscope == dst1->aio_srcscope &&
926 dst2->aio_dstscope != dst2->aio_srcscope) {
929 if (dst1->aio_dstscope != dst1->aio_srcscope &&
930 dst2->aio_dstscope == dst2->aio_srcscope) {
934 /* Rule 3: Avoid deprecated addresses. */
935 if (dst1->aio_srcsa.sa_family != AF_UNSPEC &&
936 dst2->aio_srcsa.sa_family != AF_UNSPEC) {
937 if (!(dst1->aio_srcflag & AIO_SRCFLAG_DEPRECATED) &&
938 (dst2->aio_srcflag & AIO_SRCFLAG_DEPRECATED)) {
941 if ((dst1->aio_srcflag & AIO_SRCFLAG_DEPRECATED) &&
942 !(dst2->aio_srcflag & AIO_SRCFLAG_DEPRECATED)) {
947 /* Rule 4: Prefer home addresses. */
948 /* XXX: not implemented yet */
950 /* Rule 5: Prefer matching label. */
952 if (dst1->aio_srcpolicy && dst1->aio_dstpolicy &&
953 dst1->aio_srcpolicy->pc_policy.label ==
954 dst1->aio_dstpolicy->pc_policy.label &&
955 (dst2->aio_srcpolicy == NULL || dst2->aio_dstpolicy == NULL ||
956 dst2->aio_srcpolicy->pc_policy.label !=
957 dst2->aio_dstpolicy->pc_policy.label)) {
960 if (dst2->aio_srcpolicy && dst2->aio_dstpolicy &&
961 dst2->aio_srcpolicy->pc_policy.label ==
962 dst2->aio_dstpolicy->pc_policy.label &&
963 (dst1->aio_srcpolicy == NULL || dst1->aio_dstpolicy == NULL ||
964 dst1->aio_srcpolicy->pc_policy.label !=
965 dst1->aio_dstpolicy->pc_policy.label)) {
970 /* Rule 6: Prefer higher precedence. */
972 if (dst1->aio_dstpolicy &&
973 (dst2->aio_dstpolicy == NULL ||
974 dst1->aio_dstpolicy->pc_policy.preced >
975 dst2->aio_dstpolicy->pc_policy.preced)) {
978 if (dst2->aio_dstpolicy &&
979 (dst1->aio_dstpolicy == NULL ||
980 dst2->aio_dstpolicy->pc_policy.preced >
981 dst1->aio_dstpolicy->pc_policy.preced)) {
986 /* Rule 7: Prefer native transport. */
987 /* XXX: not implemented yet */
989 /* Rule 8: Prefer smaller scope. */
990 if (dst1->aio_dstscope >= 0 &&
991 dst1->aio_dstscope < dst2->aio_dstscope) {
994 if (dst2->aio_dstscope >= 0 &&
995 dst2->aio_dstscope < dst1->aio_dstscope) {
1000 * Rule 9: Use longest matching prefix.
1001 * We compare the match length in a same AF only.
1003 if (dst1->aio_ai->ai_addr->sa_family ==
1004 dst2->aio_ai->ai_addr->sa_family) {
1005 if (dst1->aio_matchlen > dst2->aio_matchlen) {
1008 if (dst1->aio_matchlen < dst2->aio_matchlen) {
1013 /* Rule 10: Otherwise, leave the order unchanged. */
1018 * Copy from scope.c.
1019 * XXX: we should standardize the functions and link them as standard
1023 gai_addr2scopetype(struct sockaddr *sa)
1026 struct sockaddr_in6 *sa6;
1028 struct sockaddr_in *sa4;
1030 switch(sa->sa_family) {
1033 sa6 = (struct sockaddr_in6 *)sa;
1034 if (IN6_IS_ADDR_MULTICAST(&sa6->sin6_addr)) {
1035 /* just use the scope field of the multicast address */
1036 return(sa6->sin6_addr.s6_addr[2] & 0x0f);
1039 * Unicast addresses: map scope type to corresponding scope
1040 * value defined for multcast addresses.
1041 * XXX: hardcoded scope type values are bad...
1043 if (IN6_IS_ADDR_LOOPBACK(&sa6->sin6_addr))
1044 return(1); /* node local scope */
1045 if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr))
1046 return(2); /* link-local scope */
1047 if (IN6_IS_ADDR_SITELOCAL(&sa6->sin6_addr))
1048 return(5); /* site-local scope */
1049 return(14); /* global scope */
1054 * IPv4 pseudo scoping according to RFC 3484.
1056 sa4 = (struct sockaddr_in *)sa;
1057 /* IPv4 autoconfiguration addresses have link-local scope. */
1058 if (((u_char *)&sa4->sin_addr)[0] == 169 &&
1059 ((u_char *)&sa4->sin_addr)[1] == 254)
1061 /* Private addresses have site-local scope. */
1062 if (((u_char *)&sa4->sin_addr)[0] == 10 ||
1063 (((u_char *)&sa4->sin_addr)[0] == 172 &&
1064 (((u_char *)&sa4->sin_addr)[1] & 0xf0) == 16) ||
1065 (((u_char *)&sa4->sin_addr)[0] == 192 &&
1066 ((u_char *)&sa4->sin_addr)[1] == 168))
1067 return(14); /* XXX: It should be 5 unless NAT */
1068 /* Loopback addresses have link-local scope. */
1069 if (((u_char *)&sa4->sin_addr)[0] == 127)
1074 errno = EAFNOSUPPORT; /* is this a good error? */
1080 explore_copy(const struct addrinfo *pai, const struct addrinfo *src0,
1081 struct addrinfo **res)
1084 struct addrinfo sentinel, *cur;
1085 const struct addrinfo *src;
1088 sentinel.ai_next = NULL;
1091 for (src = src0; src != NULL; src = src->ai_next) {
1092 if (src->ai_family != pai->ai_family)
1095 cur->ai_next = copy_ai(src);
1096 if (!cur->ai_next) {
1101 cur->ai_next->ai_socktype = pai->ai_socktype;
1102 cur->ai_next->ai_protocol = pai->ai_protocol;
1106 *res = sentinel.ai_next;
1110 freeaddrinfo(sentinel.ai_next);
1116 * passive socket -> anyaddr (0.0.0.0 or ::)
1117 * non-passive socket -> localhost (127.0.0.1 or ::1)
1120 explore_null(const struct addrinfo *pai, const char *servname,
1121 struct addrinfo **res)
1124 const struct afd *afd;
1125 struct addrinfo *ai;
1132 * filter out AFs that are not supported by the kernel
1135 s = _socket(pai->ai_family, SOCK_DGRAM, 0);
1137 if (errno != EMFILE)
1142 afd = find_afd(pai->ai_family);
1146 if (pai->ai_flags & AI_PASSIVE) {
1147 GET_AI(ai, afd, afd->a_addrany);
1148 GET_PORT(ai, servname);
1150 GET_AI(ai, afd, afd->a_loopback);
1151 GET_PORT(ai, servname);
1167 explore_numeric(const struct addrinfo *pai, const char *hostname,
1168 const char *servname, struct addrinfo **res, const char *canonname)
1170 const struct afd *afd;
1171 struct addrinfo *ai;
1173 char pton[PTON_MAX];
1178 afd = find_afd(pai->ai_family);
1182 switch (afd->a_af) {
1185 * RFC3493 requires getaddrinfo() to accept AF_INET formats
1186 * that are accepted by inet_addr() and its family. The
1187 * accepted forms includes the "classful" one, which inet_pton
1188 * does not accept. So we need to separate the case for
1191 if (inet_aton(hostname, (struct in_addr *)pton) != 1)
1195 if (inet_pton(afd->a_af, hostname, pton) != 1)
1200 if (pai->ai_family == afd->a_af) {
1201 GET_AI(ai, afd, pton);
1202 GET_PORT(ai, servname);
1203 if ((pai->ai_flags & AI_CANONNAME)) {
1205 * Set the numeric address itself as the canonical
1206 * name, based on a clarification in RFC3493.
1208 GET_CANONNAME(ai, canonname);
1212 * XXX: This should not happen since we already matched the AF
1229 * numeric hostname with scope
1232 explore_numeric_scope(const struct addrinfo *pai, const char *hostname,
1233 const char *servname, struct addrinfo **res)
1235 #if !defined(SCOPE_DELIMITER) || !defined(INET6)
1236 return explore_numeric(pai, hostname, servname, res, hostname);
1238 const struct afd *afd;
1239 struct addrinfo *cur;
1241 char *cp, *hostname2 = NULL, *scope, *addr;
1242 struct sockaddr_in6 *sin6;
1244 afd = find_afd(pai->ai_family);
1249 return explore_numeric(pai, hostname, servname, res, hostname);
1251 cp = strchr(hostname, SCOPE_DELIMITER);
1253 return explore_numeric(pai, hostname, servname, res, hostname);
1256 * Handle special case of <scoped_address><delimiter><scope id>
1258 hostname2 = strdup(hostname);
1259 if (hostname2 == NULL)
1261 /* terminate at the delimiter */
1262 hostname2[cp - hostname] = '\0';
1266 error = explore_numeric(pai, addr, servname, res, hostname);
1270 for (cur = *res; cur; cur = cur->ai_next) {
1271 if (cur->ai_family != AF_INET6)
1273 sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
1274 if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) {
1278 return(EAI_NONAME); /* XXX: is return OK? */
1280 sin6->sin6_scope_id = scopeid;
1286 if (error && *res) {
1295 get_canonname(const struct addrinfo *pai, struct addrinfo *ai, const char *str)
1297 if ((pai->ai_flags & AI_CANONNAME) != 0) {
1298 ai->ai_canonname = strdup(str);
1299 if (ai->ai_canonname == NULL)
1305 static struct addrinfo *
1306 get_ai(const struct addrinfo *pai, const struct afd *afd, const char *addr)
1309 struct addrinfo *ai;
1311 struct in6_addr faith_prefix;
1318 * Transfrom an IPv4 addr into a special IPv6 addr format for
1319 * IPv6->IPv4 translation gateway. (only TCP is supported now)
1321 * +-----------------------------------+------------+
1322 * | faith prefix part (12 bytes) | embedded |
1323 * | | IPv4 addr part (4 bytes)
1324 * +-----------------------------------+------------+
1326 * faith prefix part is specified as ascii IPv6 addr format
1327 * in environmental variable GAI.
1328 * For FAITH to work correctly, routing to faith prefix must be
1329 * setup toward a machine where a FAITH daemon operates.
1330 * Also, the machine must enable some mechanizm
1331 * (e.g. faith interface hack) to divert those packet with
1332 * faith prefixed destination addr to user-land FAITH daemon.
1334 fp_str = getenv("GAI");
1335 if (fp_str && inet_pton(AF_INET6, fp_str, &faith_prefix) == 1 &&
1336 afd->a_af == AF_INET && pai->ai_socktype == SOCK_STREAM) {
1340 memcpy(&v4a, addr, sizeof v4a);
1341 v4a_top = v4a >> IN_CLASSA_NSHIFT;
1342 if (!IN_MULTICAST(v4a) && !IN_EXPERIMENTAL(v4a) &&
1343 v4a_top != 0 && v4a != IN_LOOPBACKNET) {
1344 afd = &afdl[N_INET6];
1345 memcpy(&faith_prefix.s6_addr[12], addr,
1346 sizeof(struct in_addr));
1352 ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
1353 + (afd->a_socklen));
1357 memcpy(ai, pai, sizeof(struct addrinfo));
1358 ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
1359 memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
1360 ai->ai_addr->sa_len = afd->a_socklen;
1361 ai->ai_addrlen = afd->a_socklen;
1362 ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
1363 p = (char *)(void *)(ai->ai_addr);
1366 memcpy(p + afd->a_off, &faith_prefix, (size_t)afd->a_addrlen);
1369 memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
1373 /* XXX need to malloc() the same way we do from other functions! */
1374 static struct addrinfo *
1375 copy_ai(const struct addrinfo *pai)
1377 struct addrinfo *ai;
1380 l = sizeof(*ai) + pai->ai_addrlen;
1381 if ((ai = (struct addrinfo *)malloc(l)) == NULL)
1384 memcpy(ai, pai, sizeof(*ai));
1385 ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
1386 memcpy(ai->ai_addr, pai->ai_addr, pai->ai_addrlen);
1388 if (pai->ai_canonname) {
1389 l = strlen(pai->ai_canonname) + 1;
1390 if ((ai->ai_canonname = malloc(l)) == NULL) {
1394 strlcpy(ai->ai_canonname, pai->ai_canonname, l);
1396 /* just to make sure */
1397 ai->ai_canonname = NULL;
1406 get_portmatch(const struct addrinfo *ai, const char *servname)
1409 /* get_port does not touch first argument when matchonly == 1. */
1410 /* LINTED const cast */
1411 return get_port((struct addrinfo *)ai, servname, 1);
1415 get_port(struct addrinfo *ai, const char *servname, int matchonly)
1422 if (servname == NULL)
1424 switch (ai->ai_family) {
1434 switch (ai->ai_socktype) {
1439 case SOCK_SEQPACKET:
1443 switch (ai->ai_family) {
1456 return EAI_SOCKTYPE;
1459 error = str2number(servname, &port);
1463 if (port < 0 || port > 65535)
1467 if (ai->ai_flags & AI_NUMERICSERV)
1470 switch (ai->ai_protocol) {
1485 if ((sp = getservbyname(servname, proto)) == NULL)
1491 switch (ai->ai_family) {
1493 ((struct sockaddr_in *)(void *)
1494 ai->ai_addr)->sin_port = port;
1498 ((struct sockaddr_in6 *)(void *)
1499 ai->ai_addr)->sin6_port = port;
1508 static const struct afd *
1511 const struct afd *afd;
1513 if (af == PF_UNSPEC)
1515 for (afd = afdl; afd->a_af; afd++) {
1516 if (afd->a_af == af)
1523 * post-2553: AI_ADDRCONFIG check. if we use getipnodeby* as backend, backend
1524 * will take care of it.
1525 * the semantics of AI_ADDRCONFIG is not defined well. we are not sure
1526 * if the code is right or not.
1528 * XXX PF_UNSPEC -> PF_INET6 + PF_INET mapping needs to be in sync with
1532 addrconfig(struct addrinfo *pai)
1538 * Note that implementation dependent test for address
1539 * configuration should be done everytime called
1540 * (or apropriate interval),
1541 * because addresses will be dynamically assigned or deleted.
1543 af = pai->ai_family;
1544 if (af == AF_UNSPEC) {
1545 if ((s = _socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
1549 if ((s = _socket(AF_INET, SOCK_DGRAM, 0)) < 0)
1555 if (af != AF_UNSPEC) {
1556 if ((s = _socket(af, SOCK_DGRAM, 0)) < 0)
1560 pai->ai_family = af;
1565 /* convert a string to a scope identifier. XXX: IPv6 specific */
1567 ip6_str2scopeid(char *scope, struct sockaddr_in6 *sin6, u_int32_t *scopeid)
1570 struct in6_addr *a6;
1573 a6 = &sin6->sin6_addr;
1575 /* empty scopeid portion is invalid */
1579 if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6) ||
1580 IN6_IS_ADDR_MC_NODELOCAL(a6)) {
1582 * We currently assume a one-to-one mapping between links
1583 * and interfaces, so we simply use interface indices for
1584 * like-local scopes.
1586 *scopeid = if_nametoindex(scope);
1592 /* still unclear about literal, allow numeric only - placeholder */
1593 if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
1595 if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
1598 goto trynumeric; /* global */
1600 /* try to convert to a numeric id as a last resort */
1603 lscopeid = strtoul(scope, &ep, 10);
1604 *scopeid = (u_int32_t)(lscopeid & 0xffffffffUL);
1605 if (errno == 0 && ep && *ep == '\0' && *scopeid == lscopeid)
1615 addrinfo_id_func(char *buffer, size_t *buffer_size, va_list ap,
1621 const int op_id = 0; /* identifies the getaddrinfo for the cache */
1623 struct addrinfo *hints;
1626 int ai_flags, ai_family, ai_socktype, ai_protocol;
1627 size_t desired_size, size;
1629 statp = __res_state();
1630 res_options = statp->options & (RES_RECURSE | RES_DEFNAMES |
1631 RES_DNSRCH | RES_NOALIASES | RES_USE_INET6);
1633 hostname = va_arg(ap, char *);
1634 hints = va_arg(ap, struct addrinfo *);
1636 desired_size = sizeof(res_options) + sizeof(int) + sizeof(int) * 4;
1637 if (hostname != NULL) {
1638 size = strlen(hostname);
1639 desired_size += size + 1;
1643 if (desired_size > *buffer_size) {
1644 *buffer_size = desired_size;
1649 ai_flags = ai_family = ai_socktype = ai_protocol = 0;
1651 ai_flags = hints->ai_flags;
1652 ai_family = hints->ai_family;
1653 ai_socktype = hints->ai_socktype;
1654 ai_protocol = hints->ai_protocol;
1658 memcpy(p, &res_options, sizeof(res_options));
1659 p += sizeof(res_options);
1661 memcpy(p, &op_id, sizeof(int));
1664 memcpy(p, &ai_flags, sizeof(int));
1667 memcpy(p, &ai_family, sizeof(int));
1670 memcpy(p, &ai_socktype, sizeof(int));
1673 memcpy(p, &ai_protocol, sizeof(int));
1676 if (hostname != NULL)
1677 memcpy(p, hostname, size);
1679 *buffer_size = desired_size;
1680 return (NS_SUCCESS);
1684 addrinfo_marshal_func(char *buffer, size_t *buffer_size, void *retval,
1685 va_list ap, void *cache_mdata)
1687 struct addrinfo *ai, *cai;
1689 size_t desired_size, size, ai_size;
1691 ai = *((struct addrinfo **)retval);
1693 desired_size = sizeof(size_t);
1695 for (cai = ai; cai != NULL; cai = cai->ai_next) {
1696 desired_size += sizeof(struct addrinfo) + cai->ai_addrlen;
1697 if (cai->ai_canonname != NULL)
1698 desired_size += sizeof(size_t) +
1699 strlen(cai->ai_canonname);
1703 if (desired_size > *buffer_size) {
1704 /* this assignment is here for future use */
1706 *buffer_size = desired_size;
1710 memset(buffer, 0, desired_size);
1713 memcpy(p, &ai_size, sizeof(size_t));
1714 p += sizeof(size_t);
1715 for (cai = ai; cai != NULL; cai = cai->ai_next) {
1716 memcpy(p, cai, sizeof(struct addrinfo));
1717 p += sizeof(struct addrinfo);
1719 memcpy(p, cai->ai_addr, cai->ai_addrlen);
1720 p += cai->ai_addrlen;
1722 if (cai->ai_canonname != NULL) {
1723 size = strlen(cai->ai_canonname);
1724 memcpy(p, &size, sizeof(size_t));
1725 p += sizeof(size_t);
1727 memcpy(p, cai->ai_canonname, size);
1732 return (NS_SUCCESS);
1736 addrinfo_unmarshal_func(char *buffer, size_t buffer_size, void *retval,
1737 va_list ap, void *cache_mdata)
1739 struct addrinfo new_ai, *result, *sentinel, *lasts;
1742 size_t ai_size, ai_i, size;
1745 memcpy(&ai_size, p, sizeof(size_t));
1746 p += sizeof(size_t);
1750 for (ai_i = 0; ai_i < ai_size; ++ai_i) {
1751 memcpy(&new_ai, p, sizeof(struct addrinfo));
1752 p += sizeof(struct addrinfo);
1753 size = new_ai.ai_addrlen + sizeof(struct addrinfo) +
1756 sentinel = (struct addrinfo *)malloc(size);
1757 memset(sentinel, 0, size);
1759 memcpy(sentinel, &new_ai, sizeof(struct addrinfo));
1760 sentinel->ai_addr = (struct sockaddr *)_ALIGN((char *)sentinel +
1761 sizeof(struct addrinfo));
1763 memcpy(sentinel->ai_addr, p, new_ai.ai_addrlen);
1764 p += new_ai.ai_addrlen;
1766 if (new_ai.ai_canonname != NULL) {
1767 memcpy(&size, p, sizeof(size_t));
1768 p += sizeof(size_t);
1770 sentinel->ai_canonname = (char *)malloc(size + 1);
1771 memset(sentinel->ai_canonname, 0, size + 1);
1773 memcpy(sentinel->ai_canonname, p, size);
1777 if (result == NULL) {
1781 lasts->ai_next = sentinel;
1786 *((struct addrinfo **)retval) = result;
1787 return (NS_SUCCESS);
1789 #endif /* NS_CACHING */
1792 * FQDN hostname, DNS lookup
1795 explore_fqdn(const struct addrinfo *pai, const char *hostname,
1796 const char *servname, struct addrinfo **res)
1798 struct addrinfo *result;
1799 struct addrinfo *cur;
1803 static const nss_cache_info cache_info =
1804 NS_COMMON_CACHE_INFO_INITIALIZER(
1805 hosts, NULL, addrinfo_id_func, addrinfo_marshal_func,
1806 addrinfo_unmarshal_func);
1808 static const ns_dtab dtab[] = {
1809 NS_FILES_CB(_files_getaddrinfo, NULL)
1810 { NSSRC_DNS, _dns_getaddrinfo, NULL }, /* force -DHESIOD */
1811 NS_NIS_CB(_yp_getaddrinfo, NULL)
1813 NS_CACHE_CB(&cache_info)
1821 * if the servname does not match socktype/protocol, ignore it.
1823 if (get_portmatch(pai, servname) != 0)
1826 switch (_nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
1827 default_dns_files, hostname, pai)) {
1839 for (cur = result; cur; cur = cur->ai_next) {
1840 GET_PORT(cur, servname);
1841 /* canonname should be filled already */
1852 freeaddrinfo(result);
1857 static const char AskedForGot[] =
1858 "gethostby*.getanswer: asked for \"%s\", got \"%s\"";
1861 static struct addrinfo *
1862 getanswer(const querybuf *answer, int anslen, const char *qname, int qtype,
1863 const struct addrinfo *pai, res_state res)
1865 struct addrinfo sentinel, *cur;
1867 const struct afd *afd;
1874 int type, class, ancount, qdcount;
1875 int haveanswer, had_error;
1876 char tbuf[MAXDNAME];
1877 int (*name_ok)(const char *);
1878 char hostbuf[8*1024];
1880 memset(&sentinel, 0, sizeof(sentinel));
1884 eom = answer->buf + anslen;
1888 case T_ANY: /*use T_ANY only for T_A/T_AAAA lookup*/
1892 return (NULL); /* XXX should be abort(); */
1895 * find first satisfactory answer
1898 ancount = ntohs(hp->ancount);
1899 qdcount = ntohs(hp->qdcount);
1901 ep = hostbuf + sizeof hostbuf;
1902 cp = answer->buf + HFIXEDSZ;
1904 RES_SET_H_ERRNO(res, NO_RECOVERY);
1907 n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1908 if ((n < 0) || !(*name_ok)(bp)) {
1909 RES_SET_H_ERRNO(res, NO_RECOVERY);
1913 if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
1914 /* res_send() has already verified that the query name is the
1915 * same as the one we sent; this just gets the expanded name
1916 * (i.e., with the succeeding search-domain tacked on).
1918 n = strlen(bp) + 1; /* for the \0 */
1919 if (n >= MAXHOSTNAMELEN) {
1920 RES_SET_H_ERRNO(res, NO_RECOVERY);
1925 /* The qname can be abbreviated, but h_name is now absolute. */
1930 while (ancount-- > 0 && cp < eom && !had_error) {
1931 n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1932 if ((n < 0) || !(*name_ok)(bp)) {
1937 type = _getshort(cp);
1938 cp += INT16SZ; /* type */
1939 class = _getshort(cp);
1940 cp += INT16SZ + INT32SZ; /* class, TTL */
1942 cp += INT16SZ; /* len */
1943 if (class != C_IN) {
1944 /* XXX - debug? syslog? */
1946 continue; /* XXX - had_error++ ? */
1948 if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
1950 n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
1951 if ((n < 0) || !(*name_ok)(tbuf)) {
1956 /* Get canonical name. */
1957 n = strlen(tbuf) + 1; /* for the \0 */
1958 if (n > ep - bp || n >= MAXHOSTNAMELEN) {
1962 strlcpy(bp, tbuf, ep - bp);
1967 if (qtype == T_ANY) {
1968 if (!(type == T_A || type == T_AAAA)) {
1972 } else if (type != qtype) {
1974 if (type != T_KEY && type != T_SIG &&
1976 syslog(LOG_NOTICE|LOG_AUTH,
1977 "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
1978 qname, p_class(C_IN), p_type(qtype),
1982 continue; /* XXX - had_error++ ? */
1987 if (strcasecmp(canonname, bp) != 0) {
1989 syslog(LOG_NOTICE|LOG_AUTH,
1990 AskedForGot, canonname, bp);
1993 continue; /* XXX - had_error++ ? */
1995 if (type == T_A && n != INADDRSZ) {
1999 if (type == T_AAAA && n != IN6ADDRSZ) {
2003 #ifdef FILTER_V4MAPPED
2004 if (type == T_AAAA) {
2005 struct in6_addr in6;
2006 memcpy(&in6, cp, sizeof(in6));
2007 if (IN6_IS_ADDR_V4MAPPED(&in6)) {
2017 nn = strlen(bp) + 1; /* for the \0 */
2021 /* don't overwrite pai */
2023 ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
2024 afd = find_afd(ai.ai_family);
2029 cur->ai_next = get_ai(&ai, afd, (const char *)cp);
2030 if (cur->ai_next == NULL)
2032 while (cur && cur->ai_next)
2043 #if defined(RESOLVSORT)
2045 * We support only IPv4 address for backward
2046 * compatibility against gethostbyname(3).
2048 if (res->nsort && qtype == T_A) {
2049 if (addr4sort(&sentinel, res) < 0) {
2050 freeaddrinfo(sentinel.ai_next);
2051 RES_SET_H_ERRNO(res, NO_RECOVERY);
2055 #endif /*RESOLVSORT*/
2057 (void)get_canonname(pai, sentinel.ai_next, qname);
2059 (void)get_canonname(pai, sentinel.ai_next, canonname);
2060 RES_SET_H_ERRNO(res, NETDB_SUCCESS);
2061 return sentinel.ai_next;
2064 RES_SET_H_ERRNO(res, NO_RECOVERY);
2070 struct addrinfo *ai;
2075 addr4sort(struct addrinfo *sentinel, res_state res)
2077 struct addrinfo *ai;
2078 struct addr_ptr *addrs, addr;
2079 struct sockaddr_in *sin;
2086 for (ai = sentinel->ai_next; ai; ai = ai->ai_next)
2089 return 0; /* We don't need sorting. */
2090 if ((addrs = malloc(sizeof(struct addr_ptr) * naddrs)) == NULL)
2093 for (ai = sentinel->ai_next; ai; ai = ai->ai_next) {
2094 sin = (struct sockaddr_in *)ai->ai_addr;
2095 for (j = 0; (unsigned)j < res->nsort; j++) {
2096 if (res->sort_list[j].addr.s_addr ==
2097 (sin->sin_addr.s_addr & res->sort_list[j].mask))
2102 if (needsort == 0 && i > 0 && j < addrs[i - 1].aval)
2111 while (needsort < naddrs) {
2112 for (j = needsort - 1; j >= 0; j--) {
2113 if (addrs[j].aval > addrs[j+1].aval) {
2115 addrs[j] = addrs[j + 1];
2116 addrs[j + 1] = addr;
2124 for (i = 0; i < naddrs; ++i) {
2125 ai->ai_next = addrs[i].ai;
2132 #endif /*RESOLVSORT*/
2136 _dns_getaddrinfo(void *rv, void *cb_data, va_list ap)
2138 struct addrinfo *ai;
2139 querybuf *buf, *buf2;
2140 const char *hostname;
2141 const struct addrinfo *pai;
2142 struct addrinfo sentinel, *cur;
2143 struct res_target q, q2;
2146 hostname = va_arg(ap, char *);
2147 pai = va_arg(ap, const struct addrinfo *);
2149 memset(&q, 0, sizeof(q));
2150 memset(&q2, 0, sizeof(q2));
2151 memset(&sentinel, 0, sizeof(sentinel));
2154 buf = malloc(sizeof(*buf));
2156 RES_SET_H_ERRNO(res, NETDB_INTERNAL);
2159 buf2 = malloc(sizeof(*buf2));
2162 RES_SET_H_ERRNO(res, NETDB_INTERNAL);
2166 switch (pai->ai_family) {
2171 q.answer = buf->buf;
2172 q.anslen = sizeof(buf->buf);
2177 q2.answer = buf2->buf;
2178 q2.anslen = sizeof(buf2->buf);
2184 q.answer = buf->buf;
2185 q.anslen = sizeof(buf->buf);
2191 q.answer = buf->buf;
2192 q.anslen = sizeof(buf->buf);
2200 res = __res_state();
2201 if ((res->options & RES_INIT) == 0 && res_ninit(res) == -1) {
2202 RES_SET_H_ERRNO(res, NETDB_INTERNAL);
2208 if (res_searchN(hostname, &q, res) < 0) {
2215 ai = getanswer(buf2, q2.n, q2.name, q2.qtype, pai, res);
2218 while (cur && cur->ai_next)
2222 ai = getanswer(buf, q.n, q.name, q.qtype, pai, res);
2227 if (sentinel.ai_next == NULL)
2228 switch (res->res_h_errno) {
2229 case HOST_NOT_FOUND:
2236 *((struct addrinfo **)rv) = sentinel.ai_next;
2241 _sethtent(FILE **hostf)
2244 *hostf = fopen(_PATH_HOSTS, "r");
2250 _endhtent(FILE **hostf)
2253 (void) fclose(*hostf);
2258 static struct addrinfo *
2259 _gethtent(FILE **hostf, const char *name, const struct addrinfo *pai)
2262 char *cp, *tname, *cname;
2263 struct addrinfo hints, *res0, *res;
2266 char hostbuf[8*1024];
2268 if (!*hostf && !(*hostf = fopen(_PATH_HOSTS, "r")))
2271 if (!(p = fgets(hostbuf, sizeof hostbuf, *hostf)))
2275 cp = strpbrk(p, "#\n");
2278 if (!(cp = strpbrk(p, " \t")))
2283 /* if this is not something we're looking for, skip it. */
2285 if (*cp == ' ' || *cp == '\t') {
2292 if ((cp = strpbrk(cp, " \t")) != NULL)
2294 if (strcasecmp(name, tname) == 0)
2300 /* we should not glob socktype/protocol here */
2301 memset(&hints, 0, sizeof(hints));
2302 hints.ai_family = pai->ai_family;
2303 hints.ai_socktype = SOCK_DGRAM;
2304 hints.ai_protocol = 0;
2305 hints.ai_flags = AI_NUMERICHOST;
2306 error = getaddrinfo(addr, "0", &hints, &res0);
2309 #ifdef FILTER_V4MAPPED
2310 /* XXX should check all items in the chain */
2311 if (res0->ai_family == AF_INET6 &&
2312 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)res0->ai_addr)->sin6_addr)) {
2317 for (res = res0; res; res = res->ai_next) {
2319 res->ai_flags = pai->ai_flags;
2320 res->ai_socktype = pai->ai_socktype;
2321 res->ai_protocol = pai->ai_protocol;
2323 if (pai->ai_flags & AI_CANONNAME) {
2324 if (get_canonname(pai, res, cname) != 0) {
2335 _files_getaddrinfo(void *rv, void *cb_data, va_list ap)
2338 const struct addrinfo *pai;
2339 struct addrinfo sentinel, *cur;
2343 name = va_arg(ap, char *);
2344 pai = va_arg(ap, struct addrinfo *);
2346 memset(&sentinel, 0, sizeof(sentinel));
2350 while ((p = _gethtent(&hostf, name, pai)) != NULL) {
2352 while (cur && cur->ai_next)
2357 *((struct addrinfo **)rv) = sentinel.ai_next;
2358 if (sentinel.ai_next == NULL)
2365 static struct addrinfo *
2366 _yphostent(char *line, const struct addrinfo *pai)
2368 struct addrinfo sentinel, *cur;
2369 struct addrinfo hints, *res, *res0;
2372 const char *addr, *canonname;
2376 addr = canonname = NULL;
2378 memset(&sentinel, 0, sizeof(sentinel));
2382 /* terminate line */
2383 cp = strchr(p, '\n');
2390 cp = strpbrk(p, " \t");
2392 if (canonname == NULL)
2402 if (*cp == ' ' || *cp == '\t') {
2408 if ((cp = strpbrk(cp, " \t")) != NULL)
2413 hints.ai_flags = AI_NUMERICHOST;
2414 error = getaddrinfo(addr, NULL, &hints, &res0);
2416 for (res = res0; res; res = res->ai_next) {
2418 res->ai_flags = pai->ai_flags;
2420 if (pai->ai_flags & AI_CANONNAME)
2421 (void)get_canonname(pai, res, canonname);
2426 cur->ai_next = res0;
2427 while (cur && cur->ai_next)
2437 return sentinel.ai_next;
2442 _yp_getaddrinfo(void *rv, void *cb_data, va_list ap)
2444 struct addrinfo sentinel, *cur;
2445 struct addrinfo *ai = NULL;
2449 const struct addrinfo *pai;
2452 if (_yp_check(&ypdomain) == 0)
2455 name = va_arg(ap, char *);
2456 pai = va_arg(ap, const struct addrinfo *);
2458 memset(&sentinel, 0, sizeof(sentinel));
2461 /* hosts.byname is only for IPv4 (Solaris8) */
2462 if (pai->ai_family == PF_UNSPEC || pai->ai_family == PF_INET) {
2463 r = yp_match(ypdomain, "hosts.byname", name,
2464 (int)strlen(name), &ypbuf, &ypbuflen);
2466 struct addrinfo ai4;
2469 ai4.ai_family = AF_INET;
2470 ai = _yphostent(ypbuf, &ai4);
2473 while (cur && cur->ai_next)
2480 /* ipnodes.byname can hold both IPv4/v6 */
2481 r = yp_match(ypdomain, "ipnodes.byname", name,
2482 (int)strlen(name), &ypbuf, &ypbuflen);
2484 ai = _yphostent(ypbuf, pai);
2490 if (sentinel.ai_next == NULL) {
2491 RES_SET_H_ERRNO(__res_state(), HOST_NOT_FOUND);
2494 *((struct addrinfo **)rv) = sentinel.ai_next;
2499 /* resolver logic */
2502 * Formulate a normal query, send, and await answer.
2503 * Returned answer is placed in supplied buffer "answer".
2504 * Perform preliminary check of answer, returning success only
2505 * if no error is indicated and the answer count is nonzero.
2506 * Return the size of the response on success, -1 on error.
2507 * Error number is left in h_errno.
2509 * Caller must parse answer and determine whether it answers the question.
2512 res_queryN(const char *name, struct res_target *target, res_state res)
2518 struct res_target *t;
2525 buf = malloc(MAXPACKET);
2527 RES_SET_H_ERRNO(res, NETDB_INTERNAL);
2531 for (t = target; t; t = t->next) {
2536 hp = (HEADER *)(void *)t->answer;
2538 /* make it easier... */
2544 oflags = res->_flags;
2547 hp->rcode = NOERROR; /* default */
2550 if (res->options & RES_DEBUG)
2551 printf(";; res_query(%s, %d, %d)\n", name, class, type);
2554 n = res_nmkquery(res, QUERY, name, class, type, NULL, 0, NULL,
2556 if (n > 0 && (res->_flags & RES_F_EDNS0ERR) == 0 &&
2557 (res->options & (RES_USE_EDNS0|RES_USE_DNSSEC)) != 0U)
2558 n = res_nopt(res, n, buf, MAXPACKET, anslen);
2561 if (res->options & RES_DEBUG)
2562 printf(";; res_query: mkquery failed\n");
2565 RES_SET_H_ERRNO(res, NO_RECOVERY);
2568 n = res_nsend(res, buf, n, answer, anslen);
2571 * if the query choked with EDNS0, retry
2574 if ((res->options & (RES_USE_EDNS0|RES_USE_DNSSEC))
2576 ((oflags ^ res->_flags) & RES_F_EDNS0ERR) != 0) {
2577 res->_flags |= RES_F_EDNS0ERR;
2578 if (res->options & RES_DEBUG)
2579 printf(";; res_nquery: retry without EDNS0\n");
2582 rcode = hp->rcode; /* record most recent error */
2584 if (res->options & RES_DEBUG)
2585 printf(";; res_query: send error\n");
2591 hp->rcode = FORMERR; /* XXX not very informative */
2592 if (hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
2593 rcode = hp->rcode; /* record most recent error */
2595 if (res->options & RES_DEBUG)
2596 printf(";; rcode = %u, ancount=%u\n", hp->rcode,
2597 ntohs(hp->ancount));
2602 ancount += ntohs(hp->ancount);
2612 RES_SET_H_ERRNO(res, HOST_NOT_FOUND);
2615 RES_SET_H_ERRNO(res, TRY_AGAIN);
2618 RES_SET_H_ERRNO(res, NO_DATA);
2624 RES_SET_H_ERRNO(res, NO_RECOVERY);
2633 * Formulate a normal query, send, and retrieve answer in supplied buffer.
2634 * Return the size of the response on success, -1 on error.
2635 * If enabled, implement search rules until answer or unrecoverable failure
2636 * is detected. Error code, if any, is left in h_errno.
2639 res_searchN(const char *name, struct res_target *target, res_state res)
2641 const char *cp, * const *domain;
2642 HEADER *hp = (HEADER *)(void *)target->answer; /*XXX*/
2644 int trailing_dot, ret, saved_herrno;
2645 int got_nodata = 0, got_servfail = 0, root_on_list = 0;
2646 int tried_as_is = 0;
2648 char abuf[MAXDNAME];
2651 RES_SET_H_ERRNO(res, HOST_NOT_FOUND); /* default, if we never query */
2653 for (cp = name; *cp; cp++)
2654 dots += (*cp == '.');
2656 if (cp > name && *--cp == '.')
2660 * if there aren't any dots, it could be a user-level alias
2663 (cp = res_hostalias(res, name, abuf, sizeof(abuf))) != NULL)
2664 return (res_queryN(cp, target, res));
2667 * If there are enough dots in the name, let's just give it a
2668 * try 'as is'. The threshold can be set with the "ndots" option.
2669 * Also, query 'as is', if there is a trailing dot in the name.
2672 if (dots >= res->ndots || trailing_dot) {
2673 ret = res_querydomainN(name, NULL, target, res);
2674 if (ret > 0 || trailing_dot)
2676 if (errno == ECONNREFUSED) {
2677 RES_SET_H_ERRNO(res, TRY_AGAIN);
2680 switch (res->res_h_errno) {
2682 case HOST_NOT_FOUND:
2685 if (hp->rcode == SERVFAIL)
2691 saved_herrno = res->res_h_errno;
2696 * We do at least one level of search if
2697 * - there is no dot and RES_DEFNAME is set, or
2698 * - there is at least one dot, there is no trailing dot,
2699 * and RES_DNSRCH is set.
2701 if ((!dots && (res->options & RES_DEFNAMES)) ||
2702 (dots && !trailing_dot && (res->options & RES_DNSRCH))) {
2705 for (domain = (const char * const *)res->dnsrch;
2710 if (domain[0][0] == '\0' ||
2711 (domain[0][0] == '.' && domain[0][1] == '\0'))
2714 if (root_on_list && tried_as_is)
2717 ret = res_querydomainN(name, *domain, target, res);
2722 * If no server present, give up.
2723 * If name isn't found in this domain,
2724 * keep trying higher domains in the search list
2725 * (if that's enabled).
2726 * On a NO_DATA error, keep trying, otherwise
2727 * a wildcard entry of another type could keep us
2728 * from finding this entry higher in the domain.
2729 * If we get some other error (negative answer or
2730 * server failure), then stop searching up,
2731 * but try the input name below in case it's
2734 if (errno == ECONNREFUSED) {
2735 RES_SET_H_ERRNO(res, TRY_AGAIN);
2739 switch (res->res_h_errno) {
2743 case HOST_NOT_FOUND:
2748 if (hp->rcode == SERVFAIL) {
2749 /* try next search element, if any */
2754 /* anything else implies that we're done */
2758 * if we got here for some reason other than DNSRCH,
2759 * we only wanted one iteration of the loop, so stop.
2761 if (!(res->options & RES_DNSRCH))
2766 switch (res->res_h_errno) {
2768 case HOST_NOT_FOUND:
2771 if (hp->rcode == SERVFAIL)
2779 * If the query has not already been tried as is then try it
2780 * unless RES_NOTLDQUERY is set and there were no dots.
2782 if ((dots || !searched || !(res->options & RES_NOTLDQUERY)) &&
2783 !(tried_as_is || root_on_list)) {
2784 ret = res_querydomainN(name, NULL, target, res);
2790 * if we got here, we didn't satisfy the search.
2791 * if we did an initial full query, return that query's h_errno
2792 * (note that we wouldn't be here if that query had succeeded).
2793 * else if we ever got a nodata, send that back as the reason.
2794 * else send back meaningless h_errno, that being the one from
2795 * the last DNSRCH we did.
2798 if (saved_herrno != -1)
2799 RES_SET_H_ERRNO(res, saved_herrno);
2800 else if (got_nodata)
2801 RES_SET_H_ERRNO(res, NO_DATA);
2802 else if (got_servfail)
2803 RES_SET_H_ERRNO(res, TRY_AGAIN);
2808 * Perform a call on res_query on the concatenation of name and domain,
2809 * removing a trailing dot from name if domain is NULL.
2812 res_querydomainN(const char *name, const char *domain,
2813 struct res_target *target, res_state res)
2815 char nbuf[MAXDNAME];
2816 const char *longname = nbuf;
2820 if (res->options & RES_DEBUG)
2821 printf(";; res_querydomain(%s, %s)\n",
2822 name, domain?domain:"<Nil>");
2824 if (domain == NULL) {
2826 * Check for trailing '.';
2827 * copy without '.' if present.
2830 if (n >= MAXDNAME) {
2831 RES_SET_H_ERRNO(res, NO_RECOVERY);
2834 if (n > 0 && name[--n] == '.') {
2835 strncpy(nbuf, name, n);
2842 if (n + d + 1 >= MAXDNAME) {
2843 RES_SET_H_ERRNO(res, NO_RECOVERY);
2846 snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
2848 return (res_queryN(longname, target, res));