1 /* $FreeBSD: src/lib/libc/net/getaddrinfo.c,v 1.9.2.14 2002/11/08 17:49:31 ume Exp $ */
2 /* $DragonFly: src/lib/libc/net/getaddrinfo.c,v 1.7 2008/05/22 06:50:14 hasso Exp $ */
3 /* $KAME: getaddrinfo.c,v 1.15 2000/07/09 04:37:24 itojun Exp $ */
6 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the project nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * "#ifdef FAITH" part is local hack for supporting IPv4-v6 translator.
37 * Issues to be discussed:
38 * - Thread safe-ness must be checked.
39 * - Return values. There are nonstandard return values defined and used
40 * in the source code. This is because RFC2553 is silent about which error
41 * code must be returned for which situation.
42 * - freeaddrinfo(NULL). RFC2553 is silent about it. XNET 5.2 says it is
43 * invalid. current code - SEGV on freeaddrinfo(NULL)
46 * - The code filters out AFs that are not supported by the kernel,
47 * when globbing NULL hostname (to loopback, or wildcard). Is it the right
48 * thing to do? What is the relationship with post-RFC2553 AI_ADDRCONFIG
50 * - (post-2553) semantics of AI_ADDRCONFIG itself is too vague.
51 * (1) what should we do against numeric hostname (2) what should we do
52 * against NULL hostname (3) what is AI_ADDRCONFIG itself. AF not ready?
53 * non-loopback address configured? global address configured?
55 * OS specific notes for netbsd/openbsd/freebsd4/bsdi4:
56 * - To avoid search order issue, we have a big amount of code duplicate
57 * from gethnamaddr.c and some other places. The issues that there's no
58 * lower layer function to lookup "IPv4 or IPv6" record. Calling
59 * gethostbyname2 from getaddrinfo will end up in wrong search order, as
62 * OS specific notes for freebsd4:
63 * - FreeBSD supported $GAI. The code does not.
64 * - FreeBSD allowed classful IPv4 numeric (127.1), the code does not.
67 #include "namespace.h"
68 #include <sys/types.h>
69 #include <sys/param.h>
70 #include <sys/socket.h>
72 #include <netinet/in.h>
73 #include <arpa/inet.h>
74 #include <arpa/nameser.h>
84 #include "un-namespace.h"
86 #include "res_config.h"
92 #if defined(__KAME__) && defined(INET6)
101 static const char in_addrany[] = { 0, 0, 0, 0 };
102 static const char in_loopback[] = { 127, 0, 0, 1 };
104 static const char in6_addrany[] = {
105 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
107 static const char in6_loopback[] = {
108 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
112 static const struct afd {
117 const char *a_addrany;
118 const char *a_loopback;
123 {PF_INET6, sizeof(struct in6_addr),
124 sizeof(struct sockaddr_in6),
125 offsetof(struct sockaddr_in6, sin6_addr),
126 in6_addrany, in6_loopback, 1},
131 {PF_INET, sizeof(struct in_addr),
132 sizeof(struct sockaddr_in),
133 offsetof(struct sockaddr_in, sin_addr),
134 in_addrany, in_loopback, 0},
135 {0, 0, 0, 0, NULL, NULL, 0},
142 const char *e_protostr;
144 #define WILD_AF(ex) ((ex)->e_wild & 0x01)
145 #define WILD_SOCKTYPE(ex) ((ex)->e_wild & 0x02)
146 #define WILD_PROTOCOL(ex) ((ex)->e_wild & 0x04)
149 static const struct explore explore[] = {
151 { PF_LOCAL, 0, ANY, ANY, NULL, 0x01 },
154 { PF_INET6, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
155 { PF_INET6, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
156 { PF_INET6, SOCK_RAW, ANY, NULL, 0x05 },
158 { PF_INET, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
159 { PF_INET, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
160 { PF_INET, SOCK_RAW, ANY, NULL, 0x05 },
161 { PF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
162 { PF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
163 { PF_UNSPEC, SOCK_RAW, ANY, NULL, 0x05 },
164 { -1, 0, 0, NULL, 0 },
173 #define MAXPACKET (64*1024)
177 u_char buf[MAXPACKET];
181 struct res_target *next;
182 const char *name; /* domain name */
183 int qclass, qtype; /* class and type of query */
184 u_char *answer; /* buffer to put answer */
185 int anslen; /* size of answer buffer */
186 int n; /* result length */
189 static int str2number (const char *);
190 static int explore_fqdn (const struct addrinfo *, const char *,
191 const char *, struct addrinfo **);
192 static int explore_null (const struct addrinfo *,
193 const char *, struct addrinfo **);
194 static int explore_numeric (const struct addrinfo *, const char *,
195 const char *, struct addrinfo **);
196 static int explore_numeric_scope (const struct addrinfo *, const char *,
197 const char *, struct addrinfo **);
198 static int get_canonname (const struct addrinfo *,
199 struct addrinfo *, const char *);
200 static struct addrinfo *get_ai (const struct addrinfo *,
201 const struct afd *, const char *);
202 static int get_portmatch (const struct addrinfo *, const char *);
203 static int get_port (struct addrinfo *, const char *, int);
204 static const struct afd *find_afd (int);
205 static int addrconfig (struct addrinfo *);
207 static int ip6_str2scopeid (char *, struct sockaddr_in6 *, u_int32_t *);
210 static struct addrinfo *getanswer (const querybuf *, int, const char *,
211 int, const struct addrinfo *);
212 static int _dns_getaddrinfo (const struct addrinfo *, const char *,
214 static struct addrinfo *_gethtent (FILE *fp, const char *,
215 const struct addrinfo *);
216 static int _files_getaddrinfo (const struct addrinfo *, const char *,
219 static int _nis_getaddrinfo (const struct addrinfo *, const char *,
223 static int res_queryN (const char *, struct res_target *);
224 static int res_searchN (const char *, struct res_target *);
225 static int res_querydomainN (const char *, const char *,
226 struct res_target *);
228 static char *ai_errlist[] = {
230 "Address family for hostname not supported", /* EAI_ADDRFAMILY */
231 "Temporary failure in name resolution", /* EAI_AGAIN */
232 "Invalid value for ai_flags", /* EAI_BADFLAGS */
233 "Non-recoverable failure in name resolution", /* EAI_FAIL */
234 "ai_family not supported", /* EAI_FAMILY */
235 "Memory allocation failure", /* EAI_MEMORY */
236 "No address associated with hostname", /* EAI_NODATA */
237 "hostname nor servname provided, or not known", /* EAI_NONAME */
238 "servname not supported for ai_socktype", /* EAI_SERVICE */
239 "ai_socktype not supported", /* EAI_SOCKTYPE */
240 "System error returned in errno", /* EAI_SYSTEM */
241 "Invalid value for hints", /* EAI_BADHINTS */
242 "Resolved protocol is unknown", /* EAI_PROTOCOL */
243 "Unknown error", /* EAI_MAX */
247 * Select order host function.
249 #define MAXHOSTCONF 4
252 # define HOSTCONF "/etc/host.conf"
253 #endif /* !HOSTCONF */
256 int (*byname)(const struct addrinfo *, const char *,
261 static struct _hostconf _hostconf[MAXHOSTCONF] = {
269 static int _hostconf_init_done;
270 static void _hostconf_init(void);
272 /* Make getaddrinfo() thread-safe in libc for use with kernel threads. */
273 #include "libc_private.h"
274 #include "spinlock.h"
276 * XXX: Our res_*() is not thread-safe. So, we share lock between
277 * getaddrinfo() and getipnodeby*(). Still, we cannot use
278 * getaddrinfo() and getipnodeby*() in conjunction with other
279 * functions which call res_*().
281 spinlock_t __getaddrinfo_thread_lock = _SPINLOCK_INITIALIZER;
282 #define THREAD_LOCK() \
283 if (__isthreaded) _SPINLOCK(&__getaddrinfo_thread_lock);
284 #define THREAD_UNLOCK() \
285 if (__isthreaded) _SPINUNLOCK(&__getaddrinfo_thread_lock);
287 /* XXX macros that make external reference is BAD. */
289 #define GET_AI(ai, afd, addr) \
291 /* external reference: pai, error, and label free */ \
292 (ai) = get_ai(pai, (afd), (addr)); \
293 if ((ai) == NULL) { \
294 error = EAI_MEMORY; \
297 } while (/*CONSTCOND*/0)
299 #define GET_PORT(ai, serv) \
301 /* external reference: error and label free */ \
302 error = get_port((ai), (serv), 0); \
305 } while (/*CONSTCOND*/0)
307 #define GET_CANONNAME(ai, str) \
309 /* external reference: pai, error and label free */ \
310 error = get_canonname(pai, (ai), (str)); \
313 } while (/*CONSTCOND*/0)
317 /* external reference: error, and label bad */ \
321 } while (/*CONSTCOND*/0)
323 #define MATCH_FAMILY(x, y, w) \
324 ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC || (y) == PF_UNSPEC)))
325 #define MATCH(x, y, w) \
326 ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY)))
329 gai_strerror(int ecode)
331 if (ecode < 0 || ecode > EAI_MAX)
333 return ai_errlist[ecode];
337 freeaddrinfo(struct addrinfo *ai)
339 struct addrinfo *next;
343 if (ai->ai_canonname)
344 free(ai->ai_canonname);
345 /* no need to free(ai->ai_addr) */
352 str2number(const char *p)
361 v = strtoul(p, &ep, 10);
362 if (errno == 0 && ep && *ep == '\0' && v <= UINT_MAX)
369 getaddrinfo(const char *hostname, const char *servname,
370 const struct addrinfo *hints, struct addrinfo **res)
372 struct addrinfo sentinel;
373 struct addrinfo *cur;
377 struct addrinfo *pai;
378 const struct explore *ex;
380 memset(&sentinel, 0, sizeof(sentinel));
384 pai->ai_family = PF_UNSPEC;
385 pai->ai_socktype = ANY;
386 pai->ai_protocol = ANY;
388 pai->ai_canonname = NULL;
392 if (hostname == NULL && servname == NULL)
395 /* error check for hints */
396 if (hints->ai_addrlen || hints->ai_canonname ||
397 hints->ai_addr || hints->ai_next)
398 ERR(EAI_BADHINTS); /* xxx */
399 if (hints->ai_flags & ~AI_MASK)
401 switch (hints->ai_family) {
411 memcpy(pai, hints, sizeof(*pai));
414 * if both socktype/protocol are specified, check if they
415 * are meaningful combination.
417 if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
418 for (ex = explore; ex->e_af >= 0; ex++) {
419 if (pai->ai_family != ex->e_af)
421 if (ex->e_socktype == ANY)
423 if (ex->e_protocol == ANY)
425 if (pai->ai_socktype == ex->e_socktype &&
426 pai->ai_protocol != ex->e_protocol) {
434 * post-2553: AI_ALL and AI_V4MAPPED are effective only against
435 * AF_INET6 query. They need to be ignored if specified in other
438 switch (pai->ai_flags & (AI_ALL | AI_V4MAPPED)) {
440 case AI_ALL | AI_V4MAPPED:
441 if (pai->ai_family != AF_INET6)
442 pai->ai_flags &= ~(AI_ALL | AI_V4MAPPED);
449 pai->ai_flags &= ~(AI_ALL | AI_V4MAPPED);
455 * check for special cases. (1) numeric servname is disallowed if
456 * socktype/protocol are left unspecified. (2) servname is disallowed
457 * for raw and other inet{,6} sockets.
459 if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
461 || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
464 ai0 = *pai; /* backup *pai */
466 if (pai->ai_family == PF_UNSPEC) {
468 pai->ai_family = PF_INET6;
470 pai->ai_family = PF_INET;
473 error = get_portmatch(pai, servname);
482 /* NULL hostname, or numeric hostname */
483 for (ex = explore; ex->e_af >= 0; ex++) {
486 /* PF_UNSPEC entries are prepared for DNS queries only */
487 if (ex->e_af == PF_UNSPEC)
490 if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
492 if (!MATCH(pai->ai_socktype, ex->e_socktype,
495 if (!MATCH(pai->ai_protocol, ex->e_protocol,
499 if (pai->ai_family == PF_UNSPEC)
500 pai->ai_family = ex->e_af;
501 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
502 pai->ai_socktype = ex->e_socktype;
503 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
504 pai->ai_protocol = ex->e_protocol;
506 if (hostname == NULL)
507 error = explore_null(pai, servname, &cur->ai_next);
509 error = explore_numeric_scope(pai, hostname, servname,
515 while (cur && cur->ai_next)
521 * If numreic representation of AF1 can be interpreted as FQDN
522 * representation of AF2, we need to think again about the code below.
524 if (sentinel.ai_next)
527 if (pai->ai_flags & AI_NUMERICHOST)
529 if (hostname == NULL)
532 if ((pai->ai_flags & AI_ADDRCONFIG) != 0 && !addrconfig(&ai0))
536 * hostname as alphabetical name.
537 * we would like to prefer AF_INET6 than AF_INET, so we'll make a
540 for (ex = explore; ex->e_af >= 0; ex++) {
543 /* require exact match for family field */
544 if (pai->ai_family != ex->e_af)
547 if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex))) {
550 if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex))) {
554 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
555 pai->ai_socktype = ex->e_socktype;
556 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
557 pai->ai_protocol = ex->e_protocol;
559 error = explore_fqdn(pai, hostname, servname, &cur->ai_next);
561 while (cur && cur->ai_next)
566 if (sentinel.ai_next)
572 if (sentinel.ai_next) {
574 *res = sentinel.ai_next;
581 if (sentinel.ai_next)
582 freeaddrinfo(sentinel.ai_next);
592 static const char sep[] = "# \t\n";
595 for (p = *pp; (c = *p) != '\0'; p++) {
596 for (sp = sep; *sp != '\0'; sp++) {
601 p[1] = '\0'; /* ignore rest of line */
613 if (ret == NULL || *ret == '\0')
619 * Initialize hostconf structure.
630 _hostconf_init_done = 1;
633 if ((fp = fopen(p, "r")) == NULL)
635 while (n < MAXHOSTCONF && fgets(buf, sizeof(buf), fp)) {
637 if ((p = _hgetword(&line)) == NULL)
640 if (strcmp(p, "hosts") == 0
641 || strcmp(p, "local") == 0
642 || strcmp(p, "file") == 0
643 || strcmp(p, "files") == 0)
644 _hostconf[n++].byname = _files_getaddrinfo;
645 else if (strcmp(p, "dns") == 0
646 || strcmp(p, "bind") == 0)
647 _hostconf[n++].byname = _dns_getaddrinfo;
649 else if (strcmp(p, "nis") == 0)
650 _hostconf[n++].byname = _nis_getaddrinfo;
652 } while ((p = _hgetword(&line)) != NULL);
656 /* no keyword found. do not change default configuration */
659 for (; n < MAXHOSTCONF; n++)
660 _hostconf[n].byname = NULL;
664 * FQDN hostname, DNS lookup
667 explore_fqdn(const struct addrinfo *pai, const char *hostname,
668 const char *servname, struct addrinfo **res)
670 struct addrinfo *result;
671 struct addrinfo *cur;
680 * if the servname does not match socktype/protocol, ignore it.
682 if (get_portmatch(pai, servname) != 0) {
687 if (!_hostconf_init_done)
690 for (i = 0; i < MAXHOSTCONF; i++) {
691 if (!_hostconf[i].byname)
693 error = (*_hostconf[i].byname)(pai, hostname, &result);
696 for (cur = result; cur; cur = cur->ai_next) {
697 GET_PORT(cur, servname);
698 /* canonname should be filled already */
708 freeaddrinfo(result);
714 * passive socket -> anyaddr (0.0.0.0 or ::)
715 * non-passive socket -> localhost (127.0.0.1 or ::1)
718 explore_null(const struct addrinfo *pai, const char *servname,
719 struct addrinfo **res)
722 const struct afd *afd;
723 struct addrinfo *cur;
724 struct addrinfo sentinel;
728 sentinel.ai_next = NULL;
732 * filter out AFs that are not supported by the kernel
735 s = _socket(pai->ai_family, SOCK_DGRAM, 0);
743 * if the servname does not match socktype/protocol, ignore it.
745 if (get_portmatch(pai, servname) != 0)
748 afd = find_afd(pai->ai_family);
752 if (pai->ai_flags & AI_PASSIVE) {
753 GET_AI(cur->ai_next, afd, afd->a_addrany);
755 * GET_CANONNAME(cur->ai_next, "anyaddr");
757 GET_PORT(cur->ai_next, servname);
759 GET_AI(cur->ai_next, afd, afd->a_loopback);
761 * GET_CANONNAME(cur->ai_next, "localhost");
763 GET_PORT(cur->ai_next, servname);
767 *res = sentinel.ai_next;
771 if (sentinel.ai_next)
772 freeaddrinfo(sentinel.ai_next);
780 explore_numeric(const struct addrinfo *pai, const char *hostname,
781 const char *servname, struct addrinfo **res)
783 const struct afd *afd;
784 struct addrinfo *cur;
785 struct addrinfo sentinel;
790 sentinel.ai_next = NULL;
794 * if the servname does not match socktype/protocol, ignore it.
796 if (get_portmatch(pai, servname) != 0)
799 afd = find_afd(pai->ai_family);
804 #if 1 /*X/Open spec*/
806 if (inet_aton(hostname, (struct in_addr *)pton) == 1) {
807 if (pai->ai_family == afd->a_af ||
808 pai->ai_family == PF_UNSPEC /*?*/) {
809 GET_AI(cur->ai_next, afd, pton);
810 GET_PORT(cur->ai_next, servname);
811 while (cur && cur->ai_next)
814 ERR(EAI_FAMILY); /*xxx*/
819 if (inet_pton(afd->a_af, hostname, pton) == 1) {
820 if (pai->ai_family == afd->a_af ||
821 pai->ai_family == PF_UNSPEC /*?*/) {
822 GET_AI(cur->ai_next, afd, pton);
823 GET_PORT(cur->ai_next, servname);
824 while (cur && cur->ai_next)
827 ERR(EAI_FAMILY); /* XXX */
832 *res = sentinel.ai_next;
837 if (sentinel.ai_next)
838 freeaddrinfo(sentinel.ai_next);
843 * numeric hostname with scope
846 explore_numeric_scope(const struct addrinfo *pai, const char *hostname,
847 const char *servname, struct addrinfo **res)
849 #if !defined(SCOPE_DELIMITER) || !defined(INET6)
850 return explore_numeric(pai, hostname, servname, res);
852 const struct afd *afd;
853 struct addrinfo *cur;
855 char *cp, *hostname2 = NULL, *scope, *addr;
856 struct sockaddr_in6 *sin6;
859 * if the servname does not match socktype/protocol, ignore it.
861 if (get_portmatch(pai, servname) != 0)
864 afd = find_afd(pai->ai_family);
868 return explore_numeric(pai, hostname, servname, res);
870 cp = strchr(hostname, SCOPE_DELIMITER);
872 return explore_numeric(pai, hostname, servname, res);
875 * Handle special case of <scoped_address><delimiter><scope id>
877 hostname2 = strdup(hostname);
878 if (hostname2 == NULL)
880 /* terminate at the delimiter */
881 hostname2[cp - hostname] = '\0';
885 error = explore_numeric(pai, addr, servname, res);
889 for (cur = *res; cur; cur = cur->ai_next) {
890 if (cur->ai_family != AF_INET6)
892 sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
893 if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) {
895 return(EAI_NODATA); /* XXX: is return OK? */
897 sin6->sin6_scope_id = scopeid;
908 get_canonname(const struct addrinfo *pai, struct addrinfo *ai, const char *str)
910 if ((pai->ai_flags & AI_CANONNAME) != 0) {
911 ai->ai_canonname = (char *)malloc(strlen(str) + 1);
912 if (ai->ai_canonname == NULL)
914 strlcpy(ai->ai_canonname, str, strlen(str) + 1);
919 static struct addrinfo *
920 get_ai(const struct addrinfo *pai, const struct afd *afd, const char *addr)
925 struct in6_addr faith_prefix;
932 * Transfrom an IPv4 addr into a special IPv6 addr format for
933 * IPv6->IPv4 translation gateway. (only TCP is supported now)
935 * +-----------------------------------+------------+
936 * | faith prefix part (12 bytes) | embedded |
937 * | | IPv4 addr part (4 bytes)
938 * +-----------------------------------+------------+
940 * faith prefix part is specified as ascii IPv6 addr format
941 * in environmental variable GAI.
942 * For FAITH to work correctly, routing to faith prefix must be
943 * setup toward a machine where a FAITH daemon operates.
944 * Also, the machine must enable some mechanizm
945 * (e.g. faith interface hack) to divert those packet with
946 * faith prefixed destination addr to user-land FAITH daemon.
948 fp_str = getenv("GAI");
949 if (fp_str && inet_pton(AF_INET6, fp_str, &faith_prefix) == 1 &&
950 afd->a_af == AF_INET && pai->ai_socktype == SOCK_STREAM) {
954 memcpy(&v4a, addr, sizeof v4a);
955 v4a_top = v4a >> IN_CLASSA_NSHIFT;
956 if (!IN_MULTICAST(v4a) && !IN_EXPERIMENTAL(v4a) &&
957 v4a_top != 0 && v4a != IN_LOOPBACKNET) {
958 afd = &afdl[N_INET6];
959 memcpy(&faith_prefix.s6_addr[12], addr,
960 sizeof(struct in_addr));
966 ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
971 memcpy(ai, pai, sizeof(struct addrinfo));
972 ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
973 memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
974 ai->ai_addr->sa_len = afd->a_socklen;
975 ai->ai_addrlen = afd->a_socklen;
976 ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
977 p = (char *)(ai->ai_addr);
980 memcpy(p + afd->a_off, &faith_prefix, afd->a_addrlen);
983 memcpy(p + afd->a_off, addr, afd->a_addrlen);
989 get_portmatch(const struct addrinfo *ai, const char *servname)
992 /* get_port does not touch first argument. when matchonly == 1. */
993 /* LINTED const cast */
994 return get_port((struct addrinfo *)ai, servname, 1);
998 get_port(struct addrinfo *ai, const char *servname, int matchonly)
1005 if (servname == NULL)
1007 switch (ai->ai_family) {
1017 switch (ai->ai_socktype) {
1028 return EAI_SOCKTYPE;
1031 port = str2number(servname);
1035 if (port < 0 || port > 65535)
1039 if (ai->ai_flags & AI_NUMERICSERV)
1041 switch (ai->ai_socktype) {
1053 if ((sp = getservbyname(servname, proto)) == NULL)
1059 switch (ai->ai_family) {
1061 ((struct sockaddr_in *)(void *)
1062 ai->ai_addr)->sin_port = port;
1066 ((struct sockaddr_in6 *)(void *)
1067 ai->ai_addr)->sin6_port = port;
1076 static const struct afd *
1079 const struct afd *afd;
1081 if (af == PF_UNSPEC)
1083 for (afd = afdl; afd->a_af; afd++) {
1084 if (afd->a_af == af)
1091 * post-2553: AI_ADDRCONFIG check. if we use getipnodeby* as backend, backend
1092 * will take care of it.
1093 * the semantics of AI_ADDRCONFIG is not defined well. we are not sure
1094 * if the code is right or not.
1096 * XXX PF_UNSPEC -> PF_INET6 + PF_INET mapping needs to be in sync with
1100 addrconfig(struct addrinfo *pai)
1106 * Note that implementation dependent test for address
1107 * configuration should be done everytime called
1108 * (or apropriate interval),
1109 * because addresses will be dynamically assigned or deleted.
1111 af = pai->ai_family;
1112 if (af == AF_UNSPEC) {
1113 if ((s = _socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
1117 if ((s = _socket(AF_INET, SOCK_DGRAM, 0)) < 0)
1124 if (af != AF_UNSPEC) {
1125 if ((s = _socket(af, SOCK_DGRAM, 0)) < 0)
1129 pai->ai_family = af;
1134 /* convert a string to a scope identifier. XXX: IPv6 specific */
1136 ip6_str2scopeid(char *scope, struct sockaddr_in6 *sin6, u_int32_t *scopeid)
1139 struct in6_addr *a6;
1142 a6 = &sin6->sin6_addr;
1144 /* empty scopeid portion is invalid */
1148 if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
1150 * We currently assume a one-to-one mapping between links
1151 * and interfaces, so we simply use interface indices for
1152 * like-local scopes.
1154 *scopeid = if_nametoindex(scope);
1160 /* still unclear about literal, allow numeric only - placeholder */
1161 if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
1163 if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
1166 goto trynumeric; /* global */
1168 /* try to convert to a numeric id as a last resort */
1171 lscopeid = strtoul(scope, &ep, 10);
1172 *scopeid = (u_int32_t)(lscopeid & 0xffffffffUL);
1173 if (errno == 0 && ep && *ep == '\0' && *scopeid == lscopeid)
1182 struct addrinfo *ai;
1187 addr4sort(struct addrinfo *sentinel)
1189 struct addrinfo *ai;
1190 struct addr_ptr *addrs, addr;
1191 struct sockaddr_in *sin;
1198 for (ai = sentinel->ai_next; ai; ai = ai->ai_next)
1201 return 0; /* We don't need sorting. */
1202 if ((addrs = malloc(sizeof(struct addr_ptr) * naddrs)) == NULL)
1205 for (ai = sentinel->ai_next; ai; ai = ai->ai_next) {
1206 sin = (struct sockaddr_in *)ai->ai_addr;
1207 for (j = 0; (unsigned)j < _res.nsort; j++) {
1208 if (_res.sort_list[j].addr.s_addr ==
1209 (sin->sin_addr.s_addr & _res.sort_list[j].mask))
1214 if (needsort == 0 && i > 0 && j < addrs[i - 1].aval)
1223 while (needsort < naddrs) {
1224 for (j = needsort - 1; j >= 0; j--) {
1225 if (addrs[j].aval > addrs[j+1].aval) {
1227 addrs[j] = addrs[j + 1];
1228 addrs[j + 1] = addr;
1236 for (i = 0; i < naddrs; ++i) {
1237 ai->ai_next = addrs[i].ai;
1244 #endif /*RESOLVSORT*/
1247 static const char AskedForGot[] =
1248 "gethostby*.getanswer: asked for \"%s\", got \"%s\"";
1251 static struct addrinfo *
1252 getanswer(const querybuf *answer, int anslen, const char *qname, int qtype,
1253 const struct addrinfo *pai)
1255 struct addrinfo sentinel, *cur;
1257 const struct afd *afd;
1264 int type, class, ancount, qdcount;
1265 int haveanswer, had_error;
1266 char tbuf[MAXDNAME];
1267 int (*name_ok) (const char *);
1268 char hostbuf[8*1024];
1270 memset(&sentinel, 0, sizeof(sentinel));
1274 eom = answer->buf + anslen;
1278 case T_ANY: /*use T_ANY only for T_A/T_AAAA lookup*/
1282 return (NULL); /* XXX should be abort(); */
1285 * find first satisfactory answer
1288 ancount = ntohs(hp->ancount);
1289 qdcount = ntohs(hp->qdcount);
1291 ep = hostbuf + sizeof hostbuf;
1292 cp = answer->buf + HFIXEDSZ;
1294 h_errno = NO_RECOVERY;
1297 n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1298 if ((n < 0) || !(*name_ok)(bp)) {
1299 h_errno = NO_RECOVERY;
1303 if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
1304 /* res_send() has already verified that the query name is the
1305 * same as the one we sent; this just gets the expanded name
1306 * (i.e., with the succeeding search-domain tacked on).
1308 n = strlen(bp) + 1; /* for the \0 */
1309 if (n >= MAXHOSTNAMELEN) {
1310 h_errno = NO_RECOVERY;
1315 /* The qname can be abbreviated, but h_name is now absolute. */
1320 while (ancount-- > 0 && cp < eom && !had_error) {
1321 n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1322 if ((n < 0) || !(*name_ok)(bp)) {
1327 type = _getshort(cp);
1328 cp += INT16SZ; /* type */
1329 class = _getshort(cp);
1330 cp += INT16SZ + INT32SZ; /* class, TTL */
1332 cp += INT16SZ; /* len */
1333 if (class != C_IN) {
1334 /* XXX - debug? syslog? */
1336 continue; /* XXX - had_error++ ? */
1338 if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
1340 n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
1341 if ((n < 0) || !(*name_ok)(tbuf)) {
1346 /* Get canonical name. */
1347 n = strlen(tbuf) + 1; /* for the \0 */
1348 if (n > ep - bp || n >= MAXHOSTNAMELEN) {
1352 strlcpy(bp, tbuf, ep - bp);
1357 if (qtype == T_ANY) {
1358 if (!(type == T_A || type == T_AAAA)) {
1362 } else if (type != qtype) {
1364 if (type != T_KEY && type != T_SIG)
1365 syslog(LOG_NOTICE|LOG_AUTH,
1366 "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
1367 qname, p_class(C_IN), p_type(qtype),
1371 continue; /* XXX - had_error++ ? */
1376 if (strcasecmp(canonname, bp) != 0) {
1378 syslog(LOG_NOTICE|LOG_AUTH,
1379 AskedForGot, canonname, bp);
1382 continue; /* XXX - had_error++ ? */
1384 if (type == T_A && n != INADDRSZ) {
1388 if (type == T_AAAA && n != IN6ADDRSZ) {
1392 #ifdef FILTER_V4MAPPED
1393 if (type == T_AAAA) {
1394 struct in6_addr in6;
1395 memcpy(&in6, cp, sizeof(in6));
1396 if (IN6_IS_ADDR_V4MAPPED(&in6)) {
1406 nn = strlen(bp) + 1; /* for the \0 */
1410 /* don't overwrite pai */
1412 ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
1413 afd = find_afd(ai.ai_family);
1418 cur->ai_next = get_ai(&ai, afd, (const char *)cp);
1419 if (cur->ai_next == NULL)
1421 while (cur && cur->ai_next)
1432 #if defined(RESOLVSORT)
1434 * We support only IPv4 address for backward
1435 * compatibility against gethostbyname(3).
1437 if (_res.nsort && qtype == T_A) {
1438 if (addr4sort(&sentinel) < 0) {
1439 freeaddrinfo(sentinel.ai_next);
1440 h_errno = NO_RECOVERY;
1444 #endif /*RESOLVSORT*/
1446 get_canonname(pai, sentinel.ai_next, qname);
1448 get_canonname(pai, sentinel.ai_next, canonname);
1449 h_errno = NETDB_SUCCESS;
1450 return sentinel.ai_next;
1453 h_errno = NO_RECOVERY;
1459 _dns_getaddrinfo(const struct addrinfo *pai, const char *hostname,
1460 struct addrinfo **res)
1462 struct addrinfo *ai;
1463 querybuf *buf, *buf2;
1465 struct addrinfo sentinel, *cur;
1466 struct res_target q, q2;
1468 memset(&q, 0, sizeof(q2));
1469 memset(&q2, 0, sizeof(q2));
1470 memset(&sentinel, 0, sizeof(sentinel));
1473 buf = malloc(sizeof(*buf));
1475 h_errno = NETDB_INTERNAL;
1478 buf2 = malloc(sizeof(*buf2));
1481 h_errno = NETDB_INTERNAL;
1485 switch (pai->ai_family) {
1490 q.answer = buf->buf;
1491 q.anslen = sizeof(buf->buf);
1496 q2.answer = buf2->buf;
1497 q2.anslen = sizeof(buf2->buf);
1503 q.answer = buf->buf;
1504 q.anslen = sizeof(buf->buf);
1510 q.answer = buf->buf;
1511 q.anslen = sizeof(buf->buf);
1518 if (res_searchN(hostname, &q) < 0) {
1525 ai = getanswer(buf2, q2.n, q2.name, q2.qtype, pai);
1528 while (cur && cur->ai_next)
1533 ai = getanswer(buf, q.n, q.name, q.qtype, pai);
1538 if (sentinel.ai_next == NULL)
1540 case HOST_NOT_FOUND:
1547 *res = sentinel.ai_next;
1551 static struct addrinfo *
1552 _gethtent(FILE *hostf, const char *name, const struct addrinfo *pai)
1555 char *cp, *tname, *cname;
1556 struct addrinfo hints, *res0, *res;
1559 char hostbuf[8*1024];
1562 if (!(p = fgets(hostbuf, sizeof hostbuf, hostf)))
1566 if (!(cp = strpbrk(p, "#\n")))
1569 if (!(cp = strpbrk(p, " \t")))
1574 /* if this is not something we're looking for, skip it. */
1576 if (*cp == ' ' || *cp == '\t') {
1583 if ((cp = strpbrk(cp, " \t")) != NULL)
1585 if (strcasecmp(name, tname) == 0)
1591 /* we should not glob socktype/protocol here */
1592 memset(&hints, 0, sizeof(hints));
1593 hints.ai_family = pai->ai_family;
1594 hints.ai_socktype = SOCK_DGRAM;
1595 hints.ai_protocol = 0;
1596 hints.ai_flags = AI_NUMERICHOST;
1597 error = getaddrinfo(addr, "0", &hints, &res0);
1600 #ifdef FILTER_V4MAPPED
1601 /* XXX should check all items in the chain */
1602 if (res0->ai_family == AF_INET6 &&
1603 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)res0->ai_addr)->sin6_addr)) {
1608 for (res = res0; res; res = res->ai_next) {
1610 res->ai_flags = pai->ai_flags;
1611 res->ai_socktype = pai->ai_socktype;
1612 res->ai_protocol = pai->ai_protocol;
1614 if (pai->ai_flags & AI_CANONNAME) {
1615 if (get_canonname(pai, res, cname) != 0) {
1626 _files_getaddrinfo(const struct addrinfo *pai, const char *hostname,
1627 struct addrinfo **res)
1630 struct addrinfo sentinel, *cur;
1633 sentinel.ai_next = NULL;
1636 if ((hostf = fopen(_PATH_HOSTS, "r")) == NULL)
1638 while ((p = _gethtent(hostf, hostname, pai)) != NULL) {
1640 while (cur && cur->ai_next)
1645 if (!sentinel.ai_next)
1648 *res = sentinel.ai_next;
1655 _nis_getaddrinfo(const struct addrinfo *pai, const char *hostname,
1656 struct addrinfo **res)
1660 struct addrinfo sentinel, *cur;
1662 const struct afd *afd;
1665 sentinel.ai_next = NULL;
1668 af = (pai->ai_family == AF_UNSPEC) ? AF_INET : pai->ai_family;
1670 return (EAI_ADDRFAMILY);
1672 if ((hp = _gethostbynisname(hostname, af)) == NULL) {
1674 /* XXX: should be filled in */
1679 } else if (hp->h_name == NULL ||
1680 hp->h_name[0] == 0 || hp->h_addr_list[0] == NULL) {
1688 for (i = 0; hp->h_addr_list[i] != NULL; i++) {
1689 if (hp->h_addrtype != af)
1692 afd = find_afd(hp->h_addrtype);
1696 GET_AI(cur->ai_next, afd, hp->h_addr_list[i]);
1697 if ((pai->ai_flags & AI_CANONNAME) != 0) {
1699 * RFC2553 says that ai_canonname will be set only for
1700 * the first element. we do it for all the elements,
1701 * just for convenience.
1703 GET_CANONNAME(cur->ai_next, hp->h_name);
1706 while (cur && cur->ai_next)
1710 *res = sentinel.ai_next;
1714 if (sentinel.ai_next)
1715 freeaddrinfo(sentinel.ai_next);
1720 /* resolver logic */
1722 extern const char *__hostalias (const char *);
1726 * Formulate a normal query, send, and await answer.
1727 * Returned answer is placed in supplied buffer "answer".
1728 * Perform preliminary check of answer, returning success only
1729 * if no error is indicated and the answer count is nonzero.
1730 * Return the size of the response on success, -1 on error.
1731 * Error number is left in h_errno.
1733 * Caller must parse answer and determine whether it answers the question.
1736 res_queryN(const char *name, /* domain name */
1737 struct res_target *target)
1742 struct res_target *t;
1749 if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
1750 h_errno = NETDB_INTERNAL;
1754 buf = malloc(MAXPACKET);
1756 h_errno = NETDB_INTERNAL;
1760 for (t = target; t; t = t->next) {
1765 hp = (HEADER *)(void *)t->answer;
1766 hp->rcode = NOERROR; /* default */
1768 /* make it easier... */
1774 if (_res.options & RES_DEBUG)
1775 printf(";; res_query(%s, %d, %d)\n", name, class, type);
1778 n = res_mkquery(QUERY, name, class, type, NULL, 0, NULL,
1780 if (n > 0 && (_res.options & RES_USE_EDNS0) != 0)
1781 n = res_opt(n, buf, MAXPACKET, anslen);
1784 if (_res.options & RES_DEBUG)
1785 printf(";; res_query: mkquery failed\n");
1788 h_errno = NO_RECOVERY;
1791 n = res_send(buf, n, answer, anslen);
1795 if (_res.options & RES_DEBUG)
1796 printf(";; res_query: send error\n");
1799 h_errno = TRY_AGAIN;
1804 if (n < 0 || n > anslen)
1805 hp->rcode = FORMERR; /* XXX not very informative */
1806 if (hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
1807 rcode = hp->rcode; /* record most recent error */
1809 if (_res.options & RES_DEBUG)
1810 printf(";; rcode = %u, ancount=%u\n", hp->rcode,
1811 ntohs(hp->ancount));
1816 ancount += ntohs(hp->ancount);
1826 h_errno = HOST_NOT_FOUND;
1829 h_errno = TRY_AGAIN;
1838 h_errno = NO_RECOVERY;
1847 * Formulate a normal query, send, and retrieve answer in supplied buffer.
1848 * Return the size of the response on success, -1 on error.
1849 * If enabled, implement search rules until answer or unrecoverable failure
1850 * is detected. Error code, if any, is left in h_errno.
1853 res_searchN(const char *name, /* domain name */
1854 struct res_target *target)
1856 const char *cp, * const *domain;
1857 HEADER *hp = (HEADER *)(void *)target->answer; /*XXX*/
1859 int trailing_dot, ret, saved_herrno;
1860 int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
1862 if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
1863 h_errno = NETDB_INTERNAL;
1868 h_errno = HOST_NOT_FOUND; /* default, if we never query */
1870 for (cp = name; *cp; cp++)
1871 dots += (*cp == '.');
1873 if (cp > name && *--cp == '.')
1877 * if there aren't any dots, it could be a user-level alias
1879 if (!dots && (cp = __hostalias(name)) != NULL)
1880 return (res_queryN(cp, target));
1883 * If there are dots in the name already, let's just give it a try
1884 * 'as is'. The threshold can be set with the "ndots" option.
1887 if (dots >= _res.ndots) {
1888 ret = res_querydomainN(name, NULL, target);
1891 saved_herrno = h_errno;
1896 * We do at least one level of search if
1897 * - there is no dot and RES_DEFNAME is set, or
1898 * - there is at least one dot, there is no trailing dot,
1899 * and RES_DNSRCH is set.
1901 if ((!dots && (_res.options & RES_DEFNAMES)) ||
1902 (dots && !trailing_dot && (_res.options & RES_DNSRCH))) {
1905 for (domain = (const char * const *)_res.dnsrch;
1909 ret = res_querydomainN(name, *domain, target);
1914 * If no server present, give up.
1915 * If name isn't found in this domain,
1916 * keep trying higher domains in the search list
1917 * (if that's enabled).
1918 * On a NO_DATA error, keep trying, otherwise
1919 * a wildcard entry of another type could keep us
1920 * from finding this entry higher in the domain.
1921 * If we get some other error (negative answer or
1922 * server failure), then stop searching up,
1923 * but try the input name below in case it's
1926 if (errno == ECONNREFUSED) {
1927 h_errno = TRY_AGAIN;
1935 case HOST_NOT_FOUND:
1939 if (hp->rcode == SERVFAIL) {
1940 /* try next search element, if any */
1946 /* anything else implies that we're done */
1950 * if we got here for some reason other than DNSRCH,
1951 * we only wanted one iteration of the loop, so stop.
1953 if (!(_res.options & RES_DNSRCH))
1959 * if we have not already tried the name "as is", do that now.
1960 * note that we do this regardless of how many dots were in the
1961 * name or whether it ends with a dot.
1963 if (!tried_as_is && (dots || !(_res.options & RES_NOTLDQUERY))) {
1964 ret = res_querydomainN(name, NULL, target);
1970 * if we got here, we didn't satisfy the search.
1971 * if we did an initial full query, return that query's h_errno
1972 * (note that we wouldn't be here if that query had succeeded).
1973 * else if we ever got a nodata, send that back as the reason.
1974 * else send back meaningless h_errno, that being the one from
1975 * the last DNSRCH we did.
1977 if (saved_herrno != -1)
1978 h_errno = saved_herrno;
1979 else if (got_nodata)
1981 else if (got_servfail)
1982 h_errno = TRY_AGAIN;
1987 * Perform a call on res_query on the concatenation of name and domain,
1988 * removing a trailing dot from name if domain is NULL.
1991 res_querydomainN(const char *name, const char *domain,
1992 struct res_target *target)
1994 char nbuf[MAXDNAME];
1995 const char *longname = nbuf;
1998 if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
1999 h_errno = NETDB_INTERNAL;
2003 if (_res.options & RES_DEBUG)
2004 printf(";; res_querydomain(%s, %s)\n",
2005 name, domain?domain:"<Nil>");
2007 if (domain == NULL) {
2009 * Check for trailing '.';
2010 * copy without '.' if present.
2013 if (n >= MAXDNAME) {
2014 h_errno = NO_RECOVERY;
2017 if (n > 0 && name[--n] == '.') {
2018 strncpy(nbuf, name, n);
2025 if (n + d + 1 >= MAXDNAME) {
2026 h_errno = NO_RECOVERY;
2029 snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
2031 return (res_queryN(longname, target));