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 * - Thread safe-ness must be checked.
37 * - Return values. There are nonstandard return values defined and used
38 * in the source code. This is because RFC2553 is silent about which error
39 * code must be returned for which situation.
40 * - freeaddrinfo(NULL). RFC2553 is silent about it. XNET 5.2 says it is
42 * current code - SEGV on freeaddrinfo(NULL)
44 * - We use getipnodebyname() just for thread-safeness. There's no intent
45 * to let it do PF_UNSPEC (actually we never pass PF_UNSPEC to
47 * - The code filters out AFs that are not supported by the kernel,
48 * when globbing NULL hostname (to loopback, or wildcard). Is it the right
49 * thing to do? What is the relationship with post-RFC2553 AI_ADDRCONFIG
51 * - (post-2553) semantics of AI_ADDRCONFIG itself is too vague.
52 * (1) what should we do against numeric hostname (2) what should we do
53 * against NULL hostname (3) what is AI_ADDRCONFIG itself. AF not ready?
54 * non-loopback address configured? global address configured?
55 * - To avoid search order issue, we have a big amount of code duplicate
56 * from gethnamaddr.c and some other places. The issues that there's no
57 * lower layer function to lookup "IPv4 or IPv6" record. Calling
58 * gethostbyname2 from getaddrinfo will end up in wrong search order, as
60 * - The code makes use of following calls when asked to resolver with
61 * ai_family = PF_UNSPEC:
62 * getipnodebyname(host, AF_INET6);
63 * getipnodebyname(host, AF_INET);
64 * This will result in the following queries if the node is configure to
65 * prefer /etc/hosts than DNS:
66 * lookup /etc/hosts for IPv6 address
67 * lookup DNS for IPv6 address
68 * lookup /etc/hosts for IPv4 address
69 * lookup DNS for IPv4 address
70 * which may not meet people's requirement.
71 * The right thing to happen is to have underlying layer which does
72 * PF_UNSPEC lookup (lookup both) and return chain of addrinfos.
73 * This would result in a bit of code duplicate with _dns_ghbyname() and
77 * diffs with other KAME platforms:
78 * - other KAME platforms already nuked FAITH ($GAI), but as FreeBSD
79 * 4.0-RELEASE supplies it, we still have the code here.
80 * - AI_ADDRCONFIG support is supplied
81 * - some of FreeBSD style (#define tabify and others)
82 * - classful IPv4 numeric (127.1) is allowed.
85 #include <sys/cdefs.h>
86 #include <machine/endian.h>
88 #include "namespace.h"
89 #include <sys/types.h>
90 #include <sys/types.h>
91 #include <sys/param.h>
92 #include <sys/socket.h>
94 #include <netinet/in.h>
95 #include <arpa/inet.h>
96 #include <arpa/nameser.h>
98 #include <rpcsvc/yp_prot.h>
99 #include <rpcsvc/ypclnt.h>
115 #include <nsswitch.h>
116 #include "un-namespace.h"
118 #if defined(__KAME__) && defined(INET6)
127 static const char in_addrany[] = { 0, 0, 0, 0 };
128 static const char in6_addrany[] = {
129 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
131 static const char in_loopback[] = { 127, 0, 0, 1 };
132 static const char in6_loopback[] = {
133 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
136 static const struct afd {
141 const char *a_addrany;
142 const char *a_loopback;
147 {PF_INET6, sizeof(struct in6_addr),
148 sizeof(struct sockaddr_in6),
149 offsetof(struct sockaddr_in6, sin6_addr),
150 in6_addrany, in6_loopback, 1},
155 {PF_INET, sizeof(struct in_addr),
156 sizeof(struct sockaddr_in),
157 offsetof(struct sockaddr_in, sin_addr),
158 in_addrany, in_loopback, 0},
159 {0, 0, 0, 0, NULL, NULL, 0},
166 const char *e_protostr;
168 #define WILD_AF(ex) ((ex)->e_wild & 0x01)
169 #define WILD_SOCKTYPE(ex) ((ex)->e_wild & 0x02)
170 #define WILD_PROTOCOL(ex) ((ex)->e_wild & 0x04)
173 static const struct explore explore[] = {
175 { PF_LOCAL, 0, ANY, ANY, NULL, 0x01 },
178 { PF_INET6, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
179 { PF_INET6, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
180 { PF_INET6, SOCK_RAW, ANY, NULL, 0x05 },
182 { PF_INET, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
183 { PF_INET, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
184 { PF_INET, SOCK_RAW, ANY, NULL, 0x05 },
185 { PF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
186 { PF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
187 { PF_UNSPEC, SOCK_RAW, ANY, NULL, 0x05 },
188 { -1, 0, 0, NULL, 0 },
197 static const ns_src default_dns_files[] = {
198 { NSSRC_FILES, NS_SUCCESS },
199 { NSSRC_DNS, NS_SUCCESS },
204 #define MAXPACKET PACKETSZ
206 #define MAXPACKET 1024
211 u_char buf[MAXPACKET];
215 struct res_target *next;
216 const char *name; /* domain name */
217 int qclass, qtype; /* class and type of query */
218 u_char *answer; /* buffer to put answer */
219 int anslen; /* size of answer buffer */
220 int n; /* result length */
223 static int str_isnumber(const char *);
224 static int explore_fqdn(const struct addrinfo *, const char *,
225 const char *, struct addrinfo **);
226 static int explore_null(const struct addrinfo *,
227 const char *, struct addrinfo **);
228 static int explore_numeric(const struct addrinfo *, const char *,
229 const char *, struct addrinfo **);
230 static int explore_numeric_scope(const struct addrinfo *, const char *,
231 const char *, struct addrinfo **);
232 static int get_canonname(const struct addrinfo *,
233 struct addrinfo *, const char *);
234 static struct addrinfo *get_ai(const struct addrinfo *,
235 const struct afd *, const char *);
236 static int get_portmatch(const struct addrinfo *, const char *);
237 static int get_port(struct addrinfo *, const char *, int);
238 static const struct afd *find_afd(int);
239 static int addrconfig(struct addrinfo *);
241 static int ip6_str2scopeid(char *, struct sockaddr_in6 *);
244 static struct addrinfo *getanswer(const querybuf *, int, const char *, int,
245 const struct addrinfo *);
246 static int _dns_getaddrinfo(void *, void *, va_list);
247 static void _sethtent(void);
248 static void _endhtent(void);
249 static struct addrinfo *_gethtent(const char *, const struct addrinfo *);
250 static int _files_getaddrinfo(void *, void *, va_list);
252 static struct addrinfo *_yphostent(char *, const struct addrinfo *);
253 static int _yp_getaddrinfo(void *, void *, va_list);
254 extern int _yp_check(char **);
257 u_int16_t _getshort(const u_char *src);
259 static int res_queryN(const char *, struct res_target *);
260 static int res_searchN(const char *, struct res_target *);
261 static int res_querydomainN(const char *, const char *,
262 struct res_target *);
264 static char *ai_errlist[] = {
266 "Address family for hostname not supported", /* EAI_ADDRFAMILY */
267 "Temporary failure in name resolution", /* EAI_AGAIN */
268 "Invalid value for ai_flags", /* EAI_BADFLAGS */
269 "Non-recoverable failure in name resolution", /* EAI_FAIL */
270 "ai_family not supported", /* EAI_FAMILY */
271 "Memory allocation failure", /* EAI_MEMORY */
272 "No address associated with hostname", /* EAI_NODATA */
273 "hostname nor servname provided, or not known", /* EAI_NONAME */
274 "servname not supported for ai_socktype", /* EAI_SERVICE */
275 "ai_socktype not supported", /* EAI_SOCKTYPE */
276 "System error returned in errno", /* EAI_SYSTEM */
277 "Invalid value for hints", /* EAI_BADHINTS */
278 "Resolved protocol is unknown", /* EAI_PROTOCOL */
279 "Unknown error", /* EAI_MAX */
282 /* XXX macros that make external reference is BAD. */
284 #define GET_AI(ai, afd, addr) \
286 /* external reference: pai, error, and label free */ \
287 (ai) = get_ai(pai, (afd), (addr)); \
288 if ((ai) == NULL) { \
289 error = EAI_MEMORY; \
292 } while (/*CONSTCOND*/0)
294 #define GET_PORT(ai, serv) \
296 /* external reference: error and label free */ \
297 error = get_port((ai), (serv), 0); \
300 } while (/*CONSTCOND*/0)
302 #define GET_CANONNAME(ai, str) \
304 /* external reference: pai, error and label free */ \
305 error = get_canonname(pai, (ai), (str)); \
308 } while (/*CONSTCOND*/0)
312 /* external reference: error, and label bad */ \
316 } while (/*CONSTCOND*/0)
318 #define MATCH_FAMILY(x, y, w) \
319 ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC || (y) == PF_UNSPEC)))
320 #define MATCH(x, y, w) \
321 ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY)))
327 if (ecode < 0 || ecode > EAI_MAX)
329 return ai_errlist[ecode];
336 struct addrinfo *next;
340 if (ai->ai_canonname)
341 free(ai->ai_canonname);
342 /* no need to free(ai->ai_addr) */
357 (void)strtoul(p, &ep, 10);
358 if (ep && *ep == '\0')
365 getaddrinfo(hostname, servname, hints, res)
366 const char *hostname, *servname;
367 const struct addrinfo *hints;
368 struct addrinfo **res;
370 struct addrinfo sentinel;
371 struct addrinfo *cur;
375 struct addrinfo *pai;
376 const struct explore *ex;
378 memset(&sentinel, 0, sizeof(sentinel));
382 pai->ai_family = PF_UNSPEC;
383 pai->ai_socktype = ANY;
384 pai->ai_protocol = ANY;
386 pai->ai_canonname = NULL;
390 if (hostname == NULL && servname == NULL)
393 /* error check for hints */
394 if (hints->ai_addrlen || hints->ai_canonname ||
395 hints->ai_addr || hints->ai_next)
396 ERR(EAI_BADHINTS); /* xxx */
397 if (hints->ai_flags & ~AI_MASK)
399 switch (hints->ai_family) {
409 memcpy(pai, hints, sizeof(*pai));
412 * if both socktype/protocol are specified, check if they
413 * are meaningful combination.
415 if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
416 for (ex = explore; ex->e_af >= 0; ex++) {
417 if (pai->ai_family != ex->e_af)
419 if (ex->e_socktype == ANY)
421 if (ex->e_protocol == ANY)
423 if (pai->ai_socktype == ex->e_socktype
424 && pai->ai_protocol != ex->e_protocol) {
432 * post-2553: AI_ALL and AI_V4MAPPED are effective only against
433 * AF_INET6 query. They needs to be ignored if specified in other
436 switch (pai->ai_flags & (AI_ALL | AI_V4MAPPED)) {
438 case AI_ALL | AI_V4MAPPED:
439 if (pai->ai_family != AF_INET6)
440 pai->ai_flags &= ~(AI_ALL | AI_V4MAPPED);
447 pai->ai_flags &= ~(AI_ALL | AI_V4MAPPED);
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);
480 /* NULL hostname, or numeric hostname */
481 for (ex = explore; ex->e_af >= 0; ex++) {
484 /* PF_UNSPEC entries are prepared for DNS queries only */
485 if (ex->e_af == PF_UNSPEC)
488 if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
490 if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex)))
492 if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex)))
495 if (pai->ai_family == PF_UNSPEC)
496 pai->ai_family = ex->e_af;
497 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
498 pai->ai_socktype = ex->e_socktype;
499 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
500 pai->ai_protocol = ex->e_protocol;
502 if (hostname == NULL)
503 error = explore_null(pai, servname, &cur->ai_next);
505 error = explore_numeric_scope(pai, hostname, servname, &cur->ai_next);
510 while (cur && cur->ai_next)
516 * If numreic representation of AF1 can be interpreted as FQDN
517 * representation of AF2, we need to think again about the code below.
519 if (sentinel.ai_next)
522 if (pai->ai_flags & AI_NUMERICHOST)
524 if (hostname == NULL)
527 if ((pai->ai_flags & AI_ADDRCONFIG) != 0 && !addrconfig(&ai0))
531 * hostname as alphabetical name.
532 * we would like to prefer AF_INET6 than AF_INET, so we'll make a
535 for (ex = explore; ex->e_af >= 0; ex++) {
538 /* require exact match for family field */
539 if (pai->ai_family != ex->e_af)
542 if (!MATCH(pai->ai_socktype, ex->e_socktype,
543 WILD_SOCKTYPE(ex))) {
546 if (!MATCH(pai->ai_protocol, ex->e_protocol,
547 WILD_PROTOCOL(ex))) {
551 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
552 pai->ai_socktype = ex->e_socktype;
553 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
554 pai->ai_protocol = ex->e_protocol;
556 error = explore_fqdn(pai, hostname, servname,
559 while (cur && cur->ai_next)
564 if (sentinel.ai_next)
570 if (sentinel.ai_next) {
572 *res = sentinel.ai_next;
579 if (sentinel.ai_next)
580 freeaddrinfo(sentinel.ai_next);
586 * FQDN hostname, DNS lookup
589 explore_fqdn(pai, hostname, servname, res)
590 const struct addrinfo *pai;
591 const char *hostname;
592 const char *servname;
593 struct addrinfo **res;
595 struct addrinfo *result;
596 struct addrinfo *cur;
598 static const ns_dtab dtab[] = {
599 NS_FILES_CB(_files_getaddrinfo, NULL)
600 { NSSRC_DNS, _dns_getaddrinfo, NULL }, /* force -DHESIOD */
601 NS_NIS_CB(_yp_getaddrinfo, NULL)
608 * if the servname does not match socktype/protocol, ignore it.
610 if (get_portmatch(pai, servname) != 0)
613 switch (nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
614 default_dns_files, hostname, pai)) {
626 for (cur = result; cur; cur = cur->ai_next) {
627 GET_PORT(cur, servname);
628 /* canonname should be filled already */
639 freeaddrinfo(result);
645 * passive socket -> anyaddr (0.0.0.0 or ::)
646 * non-passive socket -> localhost (127.0.0.1 or ::1)
649 explore_null(pai, servname, res)
650 const struct addrinfo *pai;
651 const char *servname;
652 struct addrinfo **res;
655 const struct afd *afd;
656 struct addrinfo *cur;
657 struct addrinfo sentinel;
661 sentinel.ai_next = NULL;
665 * filter out AFs that are not supported by the kernel
668 s = socket(pai->ai_family, SOCK_DGRAM, 0);
676 * if the servname does not match socktype/protocol, ignore it.
678 if (get_portmatch(pai, servname) != 0)
681 afd = find_afd(pai->ai_family);
685 if (pai->ai_flags & AI_PASSIVE) {
686 GET_AI(cur->ai_next, afd, afd->a_addrany);
688 * GET_CANONNAME(cur->ai_next, "anyaddr");
690 GET_PORT(cur->ai_next, servname);
692 GET_AI(cur->ai_next, afd, afd->a_loopback);
694 * GET_CANONNAME(cur->ai_next, "localhost");
696 GET_PORT(cur->ai_next, servname);
700 *res = sentinel.ai_next;
704 if (sentinel.ai_next)
705 freeaddrinfo(sentinel.ai_next);
713 explore_numeric(pai, hostname, servname, res)
714 const struct addrinfo *pai;
715 const char *hostname;
716 const char *servname;
717 struct addrinfo **res;
719 const struct afd *afd;
720 struct addrinfo *cur;
721 struct addrinfo sentinel;
726 sentinel.ai_next = NULL;
730 * if the servname does not match socktype/protocol, ignore it.
732 if (get_portmatch(pai, servname) != 0)
735 afd = find_afd(pai->ai_family);
740 #if 1 /*X/Open spec*/
742 if (inet_aton(hostname, (struct in_addr *)pton) == 1) {
743 if (pai->ai_family == afd->a_af ||
744 pai->ai_family == PF_UNSPEC /*?*/) {
745 GET_AI(cur->ai_next, afd, pton);
746 GET_PORT(cur->ai_next, servname);
747 while (cur && cur->ai_next)
750 ERR(EAI_FAMILY); /*xxx*/
755 if (inet_pton(afd->a_af, hostname, pton) == 1) {
756 if (pai->ai_family == afd->a_af ||
757 pai->ai_family == PF_UNSPEC /*?*/) {
758 GET_AI(cur->ai_next, afd, pton);
759 GET_PORT(cur->ai_next, servname);
760 while (cur && cur->ai_next)
763 ERR(EAI_FAMILY); /*xxx*/
768 *res = sentinel.ai_next;
773 if (sentinel.ai_next)
774 freeaddrinfo(sentinel.ai_next);
779 * numeric hostname with scope
782 explore_numeric_scope(pai, hostname, servname, res)
783 const struct addrinfo *pai;
784 const char *hostname;
785 const char *servname;
786 struct addrinfo **res;
788 #if !defined(SCOPE_DELIMITER) || !defined(INET6)
789 return explore_numeric(pai, hostname, servname, res);
791 const struct afd *afd;
792 struct addrinfo *cur;
794 char *cp, *hostname2 = NULL, *scope, *addr;
795 struct sockaddr_in6 *sin6;
798 * if the servname does not match socktype/protocol, ignore it.
800 if (get_portmatch(pai, servname) != 0)
803 afd = find_afd(pai->ai_family);
808 return explore_numeric(pai, hostname, servname, res);
810 cp = strchr(hostname, SCOPE_DELIMITER);
812 return explore_numeric(pai, hostname, servname, res);
815 * Handle special case of <scoped_address><delimiter><scope id>
817 hostname2 = strdup(hostname);
818 if (hostname2 == NULL)
820 /* terminate at the delimiter */
821 hostname2[cp - hostname] = '\0';
825 error = explore_numeric(pai, addr, servname, res);
829 for (cur = *res; cur; cur = cur->ai_next) {
830 if (cur->ai_family != AF_INET6)
832 sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
833 if ((scopeid = ip6_str2scopeid(scope, sin6)) == -1) {
835 return(EAI_NODATA); /* XXX: is return OK? */
837 sin6->sin6_scope_id = scopeid;
848 get_canonname(pai, ai, str)
849 const struct addrinfo *pai;
853 if ((pai->ai_flags & AI_CANONNAME) != 0) {
854 ai->ai_canonname = (char *)malloc(strlen(str) + 1);
855 if (ai->ai_canonname == NULL)
857 strcpy(ai->ai_canonname, str);
862 static struct addrinfo *
863 get_ai(pai, afd, addr)
864 const struct addrinfo *pai;
865 const struct afd *afd;
871 struct in6_addr faith_prefix;
878 * Transfrom an IPv4 addr into a special IPv6 addr format for
879 * IPv6->IPv4 translation gateway. (only TCP is supported now)
881 * +-----------------------------------+------------+
882 * | faith prefix part (12 bytes) | embedded |
883 * | | IPv4 addr part (4 bytes)
884 * +-----------------------------------+------------+
886 * faith prefix part is specified as ascii IPv6 addr format
887 * in environmental variable GAI.
888 * For FAITH to work correctly, routing to faith prefix must be
889 * setup toward a machine where a FAITH daemon operates.
890 * Also, the machine must enable some mechanizm
891 * (e.g. faith interface hack) to divert those packet with
892 * faith prefixed destination addr to user-land FAITH daemon.
894 fp_str = getenv("GAI");
895 if (fp_str && inet_pton(AF_INET6, fp_str, &faith_prefix) == 1 &&
896 afd->a_af == AF_INET && pai->ai_socktype == SOCK_STREAM) {
900 memcpy(&v4a, addr, sizeof v4a);
901 v4a_top = v4a >> IN_CLASSA_NSHIFT;
902 if (!IN_MULTICAST(v4a) && !IN_EXPERIMENTAL(v4a) &&
903 v4a_top != 0 && v4a != IN_LOOPBACKNET) {
904 afd = &afdl[N_INET6];
905 memcpy(&faith_prefix.s6_addr[12], addr,
906 sizeof(struct in_addr));
912 ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
917 memcpy(ai, pai, sizeof(struct addrinfo));
918 ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
919 memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
920 ai->ai_addrlen = afd->a_socklen;
921 ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
922 p = (char *)(void *)(ai->ai_addr);
925 memcpy(p + afd->a_off, &faith_prefix, (size_t)afd->a_addrlen);
928 memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
933 get_portmatch(ai, servname)
934 const struct addrinfo *ai;
935 const char *servname;
938 /* get_port does not touch first argument. when matchonly == 1. */
939 /* LINTED const cast */
940 return get_port((struct addrinfo *)ai, servname, 1);
944 get_port(ai, servname, matchonly)
946 const char *servname;
954 if (servname == NULL)
956 switch (ai->ai_family) {
966 switch (ai->ai_socktype) {
980 if (str_isnumber(servname)) {
983 port = htons(atoi(servname));
984 if (port < 0 || port > 65535)
987 switch (ai->ai_socktype) {
999 if ((sp = getservbyname(servname, proto)) == NULL)
1005 switch (ai->ai_family) {
1007 ((struct sockaddr_in *)(void *)
1008 ai->ai_addr)->sin_port = port;
1012 ((struct sockaddr_in6 *)(void *)
1013 ai->ai_addr)->sin6_port = port;
1022 static const struct afd *
1026 const struct afd *afd;
1028 if (af == PF_UNSPEC)
1030 for (afd = afdl; afd->a_af; afd++) {
1031 if (afd->a_af == af)
1038 * post-2553: AI_ADDRCONFIG check. if we use getipnodeby* as backend, backend
1039 * will take care of it.
1040 * the semantics of AI_ADDRCONFIG is not defined well. we are not sure
1041 * if the code is right or not.
1043 * XXX PF_UNSPEC -> PF_INET6 + PF_INET mapping needs to be in sync with
1048 struct addrinfo *pai;
1054 * Note that implementation dependent test for address
1055 * configuration should be done everytime called
1056 * (or apropriate interval),
1057 * because addresses will be dynamically assigned or deleted.
1059 af = pai->ai_family;
1060 if (af == AF_UNSPEC) {
1061 if ((s = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
1065 if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
1071 if (af != AF_UNSPEC) {
1072 if ((s = socket(af, SOCK_DGRAM, 0)) < 0)
1076 pai->ai_family = af;
1081 /* convert a string to a scope identifier. XXX: IPv6 specific */
1083 ip6_str2scopeid(scope, sin6)
1085 struct sockaddr_in6 *sin6;
1088 struct in6_addr *a6 = &sin6->sin6_addr;
1091 /* empty scopeid portion is invalid */
1095 if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
1097 * We currently assume a one-to-one mapping between links
1098 * and interfaces, so we simply use interface indices for
1099 * like-local scopes.
1101 scopeid = if_nametoindex(scope);
1107 /* still unclear about literal, allow numeric only - placeholder */
1108 if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
1110 if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
1113 goto trynumeric; /* global */
1115 /* try to convert to a numeric id as a last resort */
1117 scopeid = (int)strtoul(scope, &ep, 10);
1126 static const char AskedForGot[] =
1127 "gethostby*.getanswer: asked for \"%s\", got \"%s\"";
1129 static FILE *hostf = NULL;
1131 static struct addrinfo *
1132 getanswer(answer, anslen, qname, qtype, pai)
1133 const querybuf *answer;
1137 const struct addrinfo *pai;
1139 struct addrinfo sentinel, *cur;
1141 const struct afd *afd;
1148 int type, class, buflen, ancount, qdcount;
1149 int haveanswer, had_error;
1150 char tbuf[MAXDNAME];
1151 int (*name_ok)(const char *);
1152 char hostbuf[8*1024];
1154 memset(&sentinel, 0, sizeof(sentinel));
1158 eom = answer->buf + anslen;
1162 case T_ANY: /*use T_ANY only for T_A/T_AAAA lookup*/
1166 return (NULL); /* XXX should be abort(); */
1169 * find first satisfactory answer
1172 ancount = ntohs(hp->ancount);
1173 qdcount = ntohs(hp->qdcount);
1175 buflen = sizeof hostbuf;
1176 cp = answer->buf + HFIXEDSZ;
1178 h_errno = NO_RECOVERY;
1181 n = dn_expand(answer->buf, eom, cp, bp, buflen);
1182 if ((n < 0) || !(*name_ok)(bp)) {
1183 h_errno = NO_RECOVERY;
1187 if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
1188 /* res_send() has already verified that the query name is the
1189 * same as the one we sent; this just gets the expanded name
1190 * (i.e., with the succeeding search-domain tacked on).
1192 n = strlen(bp) + 1; /* for the \0 */
1193 if (n >= MAXHOSTNAMELEN) {
1194 h_errno = NO_RECOVERY;
1200 /* The qname can be abbreviated, but h_name is now absolute. */
1205 while (ancount-- > 0 && cp < eom && !had_error) {
1206 n = dn_expand(answer->buf, eom, cp, bp, buflen);
1207 if ((n < 0) || !(*name_ok)(bp)) {
1212 type = _getshort(cp);
1213 cp += INT16SZ; /* type */
1214 class = _getshort(cp);
1215 cp += INT16SZ + INT32SZ; /* class, TTL */
1217 cp += INT16SZ; /* len */
1218 if (class != C_IN) {
1219 /* XXX - debug? syslog? */
1221 continue; /* XXX - had_error++ ? */
1223 if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
1225 n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
1226 if ((n < 0) || !(*name_ok)(tbuf)) {
1231 /* Get canonical name. */
1232 n = strlen(tbuf) + 1; /* for the \0 */
1233 if (n > buflen || n >= MAXHOSTNAMELEN) {
1243 if (qtype == T_ANY) {
1244 if (!(type == T_A || type == T_AAAA)) {
1248 } else if (type != qtype) {
1250 if (type != T_KEY && type != T_SIG)
1251 syslog(LOG_NOTICE|LOG_AUTH,
1252 "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
1253 qname, p_class(C_IN), p_type(qtype),
1257 continue; /* XXX - had_error++ ? */
1262 if (strcasecmp(canonname, bp) != 0) {
1264 syslog(LOG_NOTICE|LOG_AUTH,
1265 AskedForGot, canonname, bp);
1268 continue; /* XXX - had_error++ ? */
1270 if (type == T_A && n != INADDRSZ) {
1274 if (type == T_AAAA && n != IN6ADDRSZ) {
1278 #ifdef FILTER_V4MAPPED
1279 if (type == T_AAAA) {
1280 struct in6_addr in6;
1281 memcpy(&in6, cp, sizeof(in6));
1282 if (IN6_IS_ADDR_V4MAPPED(&in6)) {
1292 nn = strlen(bp) + 1; /* for the \0 */
1297 /* don't overwrite pai */
1299 ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
1300 afd = find_afd(ai.ai_family);
1305 cur->ai_next = get_ai(&ai, afd, (const char *)cp);
1306 if (cur->ai_next == NULL)
1308 while (cur && cur->ai_next)
1320 (void)get_canonname(pai, sentinel.ai_next, qname);
1322 (void)get_canonname(pai, sentinel.ai_next, canonname);
1323 h_errno = NETDB_SUCCESS;
1324 return sentinel.ai_next;
1327 h_errno = NO_RECOVERY;
1333 _dns_getaddrinfo(rv, cb_data, ap)
1338 struct addrinfo *ai;
1341 const struct addrinfo *pai;
1342 struct addrinfo sentinel, *cur;
1343 struct res_target q, q2;
1345 name = va_arg(ap, char *);
1346 pai = va_arg(ap, const struct addrinfo *);
1348 memset(&q, 0, sizeof(q2));
1349 memset(&q2, 0, sizeof(q2));
1350 memset(&sentinel, 0, sizeof(sentinel));
1353 switch (pai->ai_family) {
1359 q.anslen = sizeof(buf);
1363 q2.answer = buf2.buf;
1364 q2.anslen = sizeof(buf2);
1370 q.anslen = sizeof(buf);
1376 q.anslen = sizeof(buf);
1381 if (res_searchN(name, &q) < 0)
1383 ai = getanswer(&buf, q.n, q.name, q.qtype, pai);
1386 while (cur && cur->ai_next)
1390 ai = getanswer(&buf2, q2.n, q2.name, q2.qtype, pai);
1394 if (sentinel.ai_next == NULL)
1396 case HOST_NOT_FOUND:
1403 *((struct addrinfo **)rv) = sentinel.ai_next;
1411 hostf = fopen(_PATH_HOSTS, "r" );
1420 (void) fclose(hostf);
1425 static struct addrinfo *
1426 _gethtent(name, pai)
1428 const struct addrinfo *pai;
1431 char *cp, *tname, *cname;
1432 struct addrinfo hints, *res0, *res;
1435 char hostbuf[8*1024];
1437 if (!hostf && !(hostf = fopen(_PATH_HOSTS, "r" )))
1440 if (!(p = fgets(hostbuf, sizeof hostbuf, hostf)))
1444 if (!(cp = strpbrk(p, "#\n")))
1447 if (!(cp = strpbrk(p, " \t")))
1452 /* if this is not something we're looking for, skip it. */
1454 if (*cp == ' ' || *cp == '\t') {
1461 if ((cp = strpbrk(cp, " \t")) != NULL)
1463 if (strcasecmp(name, tname) == 0)
1470 hints.ai_flags = AI_NUMERICHOST;
1471 error = getaddrinfo(addr, NULL, &hints, &res0);
1474 #ifdef FILTER_V4MAPPED
1475 /* XXX should check all items in the chain */
1476 if (res0->ai_family == AF_INET6 &&
1477 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)res0->ai_addr)->sin6_addr)) {
1482 for (res = res0; res; res = res->ai_next) {
1484 res->ai_flags = pai->ai_flags;
1486 if (pai->ai_flags & AI_CANONNAME) {
1487 if (get_canonname(pai, res, cname) != 0) {
1498 _files_getaddrinfo(rv, cb_data, ap)
1504 const struct addrinfo *pai;
1505 struct addrinfo sentinel, *cur;
1508 name = va_arg(ap, char *);
1509 pai = va_arg(ap, struct addrinfo *);
1511 memset(&sentinel, 0, sizeof(sentinel));
1515 while ((p = _gethtent(name, pai)) != NULL) {
1517 while (cur && cur->ai_next)
1522 *((struct addrinfo **)rv) = sentinel.ai_next;
1523 if (sentinel.ai_next == NULL)
1529 static char *__ypdomain;
1532 static struct addrinfo *
1533 _yphostent(line, pai)
1535 const struct addrinfo *pai;
1537 struct addrinfo sentinel, *cur;
1538 struct addrinfo hints, *res, *res0;
1541 const char *addr, *canonname;
1545 addr = canonname = NULL;
1547 memset(&sentinel, 0, sizeof(sentinel));
1551 /* terminate line */
1552 cp = strchr(p, '\n');
1559 cp = strpbrk(p, " \t");
1561 if (canonname == NULL)
1571 if (*cp == ' ' || *cp == '\t') {
1577 if ((cp = strpbrk(cp, " \t")) != NULL)
1582 hints.ai_flags = AI_NUMERICHOST;
1583 error = getaddrinfo(addr, NULL, &hints, &res0);
1585 for (res = res0; res; res = res->ai_next) {
1587 res->ai_flags = pai->ai_flags;
1589 if (pai->ai_flags & AI_CANONNAME)
1590 (void)get_canonname(pai, res, canonname);
1595 cur->ai_next = res0;
1596 while (cur && cur->ai_next)
1606 return sentinel.ai_next;
1611 _yp_getaddrinfo(rv, cb_data, ap)
1616 struct addrinfo sentinel, *cur;
1617 struct addrinfo *ai = NULL;
1618 static char *__ypcurrent;
1619 int __ypcurrentlen, r;
1621 const struct addrinfo *pai;
1623 name = va_arg(ap, char *);
1624 pai = va_arg(ap, const struct addrinfo *);
1626 memset(&sentinel, 0, sizeof(sentinel));
1630 if (_yp_check(&__ypdomain) == 0)
1637 /* hosts.byname is only for IPv4 (Solaris8) */
1638 if (pai->ai_family == PF_UNSPEC || pai->ai_family == PF_INET) {
1639 r = yp_match(__ypdomain, "hosts.byname", name,
1640 (int)strlen(name), &__ypcurrent, &__ypcurrentlen);
1642 struct addrinfo ai4;
1645 ai4.ai_family = AF_INET;
1646 ai = _yphostent(__ypcurrent, &ai4);
1649 while (cur && cur->ai_next)
1655 /* ipnodes.byname can hold both IPv4/v6 */
1656 r = yp_match(__ypdomain, "ipnodes.byname", name,
1657 (int)strlen(name), &__ypcurrent, &__ypcurrentlen);
1659 ai = _yphostent(__ypcurrent, pai);
1662 while (cur && cur->ai_next)
1667 if (sentinel.ai_next == NULL) {
1668 h_errno = HOST_NOT_FOUND;
1671 *((struct addrinfo **)rv) = sentinel.ai_next;
1676 /* resolver logic */
1678 extern const char *__hostalias(const char *);
1682 * Formulate a normal query, send, and await answer.
1683 * Returned answer is placed in supplied buffer "answer".
1684 * Perform preliminary check of answer, returning success only
1685 * if no error is indicated and the answer count is nonzero.
1686 * Return the size of the response on success, -1 on error.
1687 * Error number is left in h_errno.
1689 * Caller must parse answer and determine whether it answers the question.
1692 res_queryN(name, target)
1693 const char *name; /* domain name */
1694 struct res_target *target;
1696 u_char buf[MAXPACKET];
1699 struct res_target *t;
1706 if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
1707 h_errno = NETDB_INTERNAL;
1711 for (t = target; t; t = t->next) {
1716 hp = (HEADER *)(void *)t->answer;
1717 hp->rcode = NOERROR; /* default */
1719 /* make it easier... */
1725 if (_res.options & RES_DEBUG)
1726 printf(";; res_query(%s, %d, %d)\n", name, class, type);
1729 n = res_mkquery(QUERY, name, class, type, NULL, 0, NULL,
1731 if (n > 0 && (_res.options & RES_USE_EDNS0) != 0)
1732 n = res_opt(n, buf, sizeof(buf), anslen);
1735 if (_res.options & RES_DEBUG)
1736 printf(";; res_query: mkquery failed\n");
1738 h_errno = NO_RECOVERY;
1741 n = res_send(buf, n, answer, anslen);
1745 if (_res.options & RES_DEBUG)
1746 printf(";; res_query: send error\n");
1748 h_errno = TRY_AGAIN;
1753 if (n < 0 || hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
1754 rcode = hp->rcode; /* record most recent error */
1756 if (_res.options & RES_DEBUG)
1757 printf(";; rcode = %d, ancount=%d\n", hp->rcode,
1758 ntohs(hp->ancount));
1763 ancount += ntohs(hp->ancount);
1771 h_errno = HOST_NOT_FOUND;
1774 h_errno = TRY_AGAIN;
1783 h_errno = NO_RECOVERY;
1792 * Formulate a normal query, send, and retrieve answer in supplied buffer.
1793 * Return the size of the response on success, -1 on error.
1794 * If enabled, implement search rules until answer or unrecoverable failure
1795 * is detected. Error code, if any, is left in h_errno.
1798 res_searchN(name, target)
1799 const char *name; /* domain name */
1800 struct res_target *target;
1802 const char *cp, * const *domain;
1803 HEADER *hp = (HEADER *)(void *)target->answer; /*XXX*/
1805 int trailing_dot, ret, saved_herrno;
1806 int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
1808 if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
1809 h_errno = NETDB_INTERNAL;
1814 h_errno = HOST_NOT_FOUND; /* default, if we never query */
1816 for (cp = name; *cp; cp++)
1817 dots += (*cp == '.');
1819 if (cp > name && *--cp == '.')
1823 * if there aren't any dots, it could be a user-level alias
1825 if (!dots && (cp = __hostalias(name)) != NULL)
1826 return (res_queryN(cp, target));
1829 * If there are dots in the name already, let's just give it a try
1830 * 'as is'. The threshold can be set with the "ndots" option.
1833 if (dots >= _res.ndots) {
1834 ret = res_querydomainN(name, NULL, target);
1837 saved_herrno = h_errno;
1842 * We do at least one level of search if
1843 * - there is no dot and RES_DEFNAME is set, or
1844 * - there is at least one dot, there is no trailing dot,
1845 * and RES_DNSRCH is set.
1847 if ((!dots && (_res.options & RES_DEFNAMES)) ||
1848 (dots && !trailing_dot && (_res.options & RES_DNSRCH))) {
1851 for (domain = (const char * const *)_res.dnsrch;
1855 ret = res_querydomainN(name, *domain, target);
1860 * If no server present, give up.
1861 * If name isn't found in this domain,
1862 * keep trying higher domains in the search list
1863 * (if that's enabled).
1864 * On a NO_DATA error, keep trying, otherwise
1865 * a wildcard entry of another type could keep us
1866 * from finding this entry higher in the domain.
1867 * If we get some other error (negative answer or
1868 * server failure), then stop searching up,
1869 * but try the input name below in case it's
1872 if (errno == ECONNREFUSED) {
1873 h_errno = TRY_AGAIN;
1881 case HOST_NOT_FOUND:
1885 if (hp->rcode == SERVFAIL) {
1886 /* try next search element, if any */
1892 /* anything else implies that we're done */
1896 * if we got here for some reason other than DNSRCH,
1897 * we only wanted one iteration of the loop, so stop.
1899 if (!(_res.options & RES_DNSRCH))
1905 * if we have not already tried the name "as is", do that now.
1906 * note that we do this regardless of how many dots were in the
1907 * name or whether it ends with a dot.
1909 if (!tried_as_is && (dots || !(_res.options & RES_NOTLDQUERY))) {
1910 ret = res_querydomainN(name, NULL, target);
1916 * if we got here, we didn't satisfy the search.
1917 * if we did an initial full query, return that query's h_errno
1918 * (note that we wouldn't be here if that query had succeeded).
1919 * else if we ever got a nodata, send that back as the reason.
1920 * else send back meaningless h_errno, that being the one from
1921 * the last DNSRCH we did.
1923 if (saved_herrno != -1)
1924 h_errno = saved_herrno;
1925 else if (got_nodata)
1927 else if (got_servfail)
1928 h_errno = TRY_AGAIN;
1933 * Perform a call on res_query on the concatenation of name and domain,
1934 * removing a trailing dot from name if domain is NULL.
1937 res_querydomainN(name, domain, target)
1938 const char *name, *domain;
1939 struct res_target *target;
1941 char nbuf[MAXDNAME];
1942 const char *longname = nbuf;
1945 if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
1946 h_errno = NETDB_INTERNAL;
1950 if (_res.options & RES_DEBUG)
1951 printf(";; res_querydomain(%s, %s)\n",
1952 name, domain?domain:"<Nil>");
1954 if (domain == NULL) {
1956 * Check for trailing '.';
1957 * copy without '.' if present.
1960 if (n >= MAXDNAME) {
1961 h_errno = NO_RECOVERY;
1964 if (n > 0 && name[--n] == '.') {
1965 strncpy(nbuf, name, n);
1972 if (n + d + 1 >= MAXDNAME) {
1973 h_errno = NO_RECOVERY;
1976 sprintf(nbuf, "%s.%s", name, domain);
1978 return (res_queryN(longname, target));