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 __FBSDID("$FreeBSD$");
88 #include "namespace.h"
89 #include <sys/types.h>
90 #include <sys/param.h>
91 #include <sys/socket.h>
93 #include <netinet/in.h>
94 #include <arpa/inet.h>
95 #include <arpa/nameser.h>
97 #include <rpcsvc/yp_prot.h>
98 #include <rpcsvc/ypclnt.h>
114 #include <nsswitch.h>
115 #include "un-namespace.h"
117 #if defined(__KAME__) && defined(INET6)
126 static const char in_addrany[] = { 0, 0, 0, 0 };
127 static const char in6_addrany[] = {
128 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
130 static const char in_loopback[] = { 127, 0, 0, 1 };
131 static const char in6_loopback[] = {
132 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
135 static const struct afd {
140 const char *a_addrany;
141 const char *a_loopback;
146 {PF_INET6, sizeof(struct in6_addr),
147 sizeof(struct sockaddr_in6),
148 offsetof(struct sockaddr_in6, sin6_addr),
149 in6_addrany, in6_loopback, 1},
154 {PF_INET, sizeof(struct in_addr),
155 sizeof(struct sockaddr_in),
156 offsetof(struct sockaddr_in, sin_addr),
157 in_addrany, in_loopback, 0},
158 {0, 0, 0, 0, NULL, NULL, 0},
165 const char *e_protostr;
167 #define WILD_AF(ex) ((ex)->e_wild & 0x01)
168 #define WILD_SOCKTYPE(ex) ((ex)->e_wild & 0x02)
169 #define WILD_PROTOCOL(ex) ((ex)->e_wild & 0x04)
172 static const struct explore explore[] = {
174 { PF_LOCAL, 0, ANY, ANY, NULL, 0x01 },
177 { PF_INET6, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
178 { PF_INET6, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
179 { PF_INET6, SOCK_RAW, ANY, NULL, 0x05 },
181 { PF_INET, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
182 { PF_INET, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
183 { PF_INET, SOCK_RAW, ANY, NULL, 0x05 },
184 { PF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
185 { PF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
186 { PF_UNSPEC, SOCK_RAW, ANY, NULL, 0x05 },
187 { -1, 0, 0, NULL, 0 },
196 static const ns_src default_dns_files[] = {
197 { NSSRC_FILES, NS_SUCCESS },
198 { NSSRC_DNS, NS_SUCCESS },
203 #define MAXPACKET PACKETSZ
205 #define MAXPACKET 1024
210 u_char buf[MAXPACKET];
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 static int str_isnumber(const char *);
223 static int explore_fqdn(const struct addrinfo *, const char *,
224 const char *, struct addrinfo **);
225 static int explore_null(const struct addrinfo *,
226 const char *, struct addrinfo **);
227 static int explore_numeric(const struct addrinfo *, const char *,
228 const char *, struct addrinfo **);
229 static int explore_numeric_scope(const struct addrinfo *, const char *,
230 const char *, struct addrinfo **);
231 static int get_canonname(const struct addrinfo *,
232 struct addrinfo *, const char *);
233 static struct addrinfo *get_ai(const struct addrinfo *,
234 const struct afd *, const char *);
235 static int get_portmatch(const struct addrinfo *, const char *);
236 static int get_port(struct addrinfo *, const char *, int);
237 static const struct afd *find_afd(int);
238 static int addrconfig(struct addrinfo *);
240 static int ip6_str2scopeid(char *, struct sockaddr_in6 *);
243 static struct addrinfo *getanswer(const querybuf *, int, const char *, int,
244 const struct addrinfo *);
245 static int _dns_getaddrinfo(void *, void *, va_list);
246 static void _sethtent(void);
247 static void _endhtent(void);
248 static struct addrinfo *_gethtent(const char *, const struct addrinfo *);
249 static int _files_getaddrinfo(void *, void *, va_list);
251 static struct addrinfo *_yphostent(char *, const struct addrinfo *);
252 static int _yp_getaddrinfo(void *, void *, va_list);
253 extern int _yp_check(char **);
256 static int res_queryN(const char *, struct res_target *);
257 static int res_searchN(const char *, struct res_target *);
258 static int res_querydomainN(const char *, const char *,
259 struct res_target *);
261 static char *ai_errlist[] = {
263 "Address family for hostname not supported", /* EAI_ADDRFAMILY */
264 "Temporary failure in name resolution", /* EAI_AGAIN */
265 "Invalid value for ai_flags", /* EAI_BADFLAGS */
266 "Non-recoverable failure in name resolution", /* EAI_FAIL */
267 "ai_family not supported", /* EAI_FAMILY */
268 "Memory allocation failure", /* EAI_MEMORY */
269 "No address associated with hostname", /* EAI_NODATA */
270 "hostname nor servname provided, or not known", /* EAI_NONAME */
271 "servname not supported for ai_socktype", /* EAI_SERVICE */
272 "ai_socktype not supported", /* EAI_SOCKTYPE */
273 "System error returned in errno", /* EAI_SYSTEM */
274 "Invalid value for hints", /* EAI_BADHINTS */
275 "Resolved protocol is unknown", /* EAI_PROTOCOL */
276 "Unknown error", /* EAI_MAX */
279 /* XXX macros that make external reference is BAD. */
281 #define GET_AI(ai, afd, addr) \
283 /* external reference: pai, error, and label free */ \
284 (ai) = get_ai(pai, (afd), (addr)); \
285 if ((ai) == NULL) { \
286 error = EAI_MEMORY; \
289 } while (/*CONSTCOND*/0)
291 #define GET_PORT(ai, serv) \
293 /* external reference: error and label free */ \
294 error = get_port((ai), (serv), 0); \
297 } while (/*CONSTCOND*/0)
299 #define GET_CANONNAME(ai, str) \
301 /* external reference: pai, error and label free */ \
302 error = get_canonname(pai, (ai), (str)); \
305 } while (/*CONSTCOND*/0)
309 /* external reference: error, and label bad */ \
313 } while (/*CONSTCOND*/0)
315 #define MATCH_FAMILY(x, y, w) \
316 ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC || (y) == PF_UNSPEC)))
317 #define MATCH(x, y, w) \
318 ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY)))
324 if (ecode < 0 || ecode > EAI_MAX)
326 return ai_errlist[ecode];
333 struct addrinfo *next;
337 if (ai->ai_canonname)
338 free(ai->ai_canonname);
339 /* no need to free(ai->ai_addr) */
354 (void)strtoul(p, &ep, 10);
355 if (ep && *ep == '\0')
362 getaddrinfo(hostname, servname, hints, res)
363 const char *hostname, *servname;
364 const struct addrinfo *hints;
365 struct addrinfo **res;
367 struct addrinfo sentinel;
368 struct addrinfo *cur;
372 struct addrinfo *pai;
373 const struct explore *ex;
375 memset(&sentinel, 0, sizeof(sentinel));
379 pai->ai_family = PF_UNSPEC;
380 pai->ai_socktype = ANY;
381 pai->ai_protocol = ANY;
383 pai->ai_canonname = NULL;
387 if (hostname == NULL && servname == NULL)
390 /* error check for hints */
391 if (hints->ai_addrlen || hints->ai_canonname ||
392 hints->ai_addr || hints->ai_next)
393 ERR(EAI_BADHINTS); /* xxx */
394 if (hints->ai_flags & ~AI_MASK)
396 switch (hints->ai_family) {
406 memcpy(pai, hints, sizeof(*pai));
409 * if both socktype/protocol are specified, check if they
410 * are meaningful combination.
412 if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
413 for (ex = explore; ex->e_af >= 0; ex++) {
414 if (pai->ai_family != ex->e_af)
416 if (ex->e_socktype == ANY)
418 if (ex->e_protocol == ANY)
420 if (pai->ai_socktype == ex->e_socktype
421 && pai->ai_protocol != ex->e_protocol) {
429 * post-2553: AI_ALL and AI_V4MAPPED are effective only against
430 * AF_INET6 query. They needs to be ignored if specified in other
433 switch (pai->ai_flags & (AI_ALL | AI_V4MAPPED)) {
435 case AI_ALL | AI_V4MAPPED:
436 if (pai->ai_family != AF_INET6)
437 pai->ai_flags &= ~(AI_ALL | AI_V4MAPPED);
444 pai->ai_flags &= ~(AI_ALL | AI_V4MAPPED);
450 * check for special cases. (1) numeric servname is disallowed if
451 * socktype/protocol are left unspecified. (2) servname is disallowed
452 * for raw and other inet{,6} sockets.
454 if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
456 || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
459 ai0 = *pai; /* backup *pai */
461 if (pai->ai_family == PF_UNSPEC) {
463 pai->ai_family = PF_INET6;
465 pai->ai_family = PF_INET;
468 error = get_portmatch(pai, servname);
477 /* NULL hostname, or numeric hostname */
478 for (ex = explore; ex->e_af >= 0; ex++) {
481 /* PF_UNSPEC entries are prepared for DNS queries only */
482 if (ex->e_af == PF_UNSPEC)
485 if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
487 if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex)))
489 if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex)))
492 if (pai->ai_family == PF_UNSPEC)
493 pai->ai_family = ex->e_af;
494 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
495 pai->ai_socktype = ex->e_socktype;
496 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
497 pai->ai_protocol = ex->e_protocol;
499 if (hostname == NULL)
500 error = explore_null(pai, servname, &cur->ai_next);
502 error = explore_numeric_scope(pai, hostname, servname, &cur->ai_next);
507 while (cur && cur->ai_next)
513 * If numreic representation of AF1 can be interpreted as FQDN
514 * representation of AF2, we need to think again about the code below.
516 if (sentinel.ai_next)
519 if (pai->ai_flags & AI_NUMERICHOST)
521 if (hostname == NULL)
524 if ((pai->ai_flags & AI_ADDRCONFIG) != 0 && !addrconfig(&ai0))
528 * hostname as alphabetical name.
529 * we would like to prefer AF_INET6 than AF_INET, so we'll make a
532 for (ex = explore; ex->e_af >= 0; ex++) {
535 /* require exact match for family field */
536 if (pai->ai_family != ex->e_af)
539 if (!MATCH(pai->ai_socktype, ex->e_socktype,
540 WILD_SOCKTYPE(ex))) {
543 if (!MATCH(pai->ai_protocol, ex->e_protocol,
544 WILD_PROTOCOL(ex))) {
548 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
549 pai->ai_socktype = ex->e_socktype;
550 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
551 pai->ai_protocol = ex->e_protocol;
553 error = explore_fqdn(pai, hostname, servname,
556 while (cur && cur->ai_next)
561 if (sentinel.ai_next)
567 if (sentinel.ai_next) {
569 *res = sentinel.ai_next;
576 if (sentinel.ai_next)
577 freeaddrinfo(sentinel.ai_next);
583 * FQDN hostname, DNS lookup
586 explore_fqdn(pai, hostname, servname, res)
587 const struct addrinfo *pai;
588 const char *hostname;
589 const char *servname;
590 struct addrinfo **res;
592 struct addrinfo *result;
593 struct addrinfo *cur;
595 static const ns_dtab dtab[] = {
596 NS_FILES_CB(_files_getaddrinfo, NULL)
597 { NSSRC_DNS, _dns_getaddrinfo, NULL }, /* force -DHESIOD */
598 NS_NIS_CB(_yp_getaddrinfo, NULL)
605 * if the servname does not match socktype/protocol, ignore it.
607 if (get_portmatch(pai, servname) != 0)
610 switch (nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
611 default_dns_files, hostname, pai)) {
623 for (cur = result; cur; cur = cur->ai_next) {
624 GET_PORT(cur, servname);
625 /* canonname should be filled already */
636 freeaddrinfo(result);
642 * passive socket -> anyaddr (0.0.0.0 or ::)
643 * non-passive socket -> localhost (127.0.0.1 or ::1)
646 explore_null(pai, servname, res)
647 const struct addrinfo *pai;
648 const char *servname;
649 struct addrinfo **res;
652 const struct afd *afd;
653 struct addrinfo *cur;
654 struct addrinfo sentinel;
658 sentinel.ai_next = NULL;
662 * filter out AFs that are not supported by the kernel
665 s = _socket(pai->ai_family, SOCK_DGRAM, 0);
673 * if the servname does not match socktype/protocol, ignore it.
675 if (get_portmatch(pai, servname) != 0)
678 afd = find_afd(pai->ai_family);
682 if (pai->ai_flags & AI_PASSIVE) {
683 GET_AI(cur->ai_next, afd, afd->a_addrany);
685 * GET_CANONNAME(cur->ai_next, "anyaddr");
687 GET_PORT(cur->ai_next, servname);
689 GET_AI(cur->ai_next, afd, afd->a_loopback);
691 * GET_CANONNAME(cur->ai_next, "localhost");
693 GET_PORT(cur->ai_next, servname);
697 *res = sentinel.ai_next;
701 if (sentinel.ai_next)
702 freeaddrinfo(sentinel.ai_next);
710 explore_numeric(pai, hostname, servname, res)
711 const struct addrinfo *pai;
712 const char *hostname;
713 const char *servname;
714 struct addrinfo **res;
716 const struct afd *afd;
717 struct addrinfo *cur;
718 struct addrinfo sentinel;
723 sentinel.ai_next = NULL;
727 * if the servname does not match socktype/protocol, ignore it.
729 if (get_portmatch(pai, servname) != 0)
732 afd = find_afd(pai->ai_family);
737 #if 1 /*X/Open spec*/
739 if (inet_aton(hostname, (struct in_addr *)pton) == 1) {
740 if (pai->ai_family == afd->a_af ||
741 pai->ai_family == PF_UNSPEC /*?*/) {
742 GET_AI(cur->ai_next, afd, pton);
743 GET_PORT(cur->ai_next, servname);
744 while (cur && cur->ai_next)
747 ERR(EAI_FAMILY); /*xxx*/
752 if (inet_pton(afd->a_af, hostname, pton) == 1) {
753 if (pai->ai_family == afd->a_af ||
754 pai->ai_family == PF_UNSPEC /*?*/) {
755 GET_AI(cur->ai_next, afd, pton);
756 GET_PORT(cur->ai_next, servname);
757 while (cur && cur->ai_next)
760 ERR(EAI_FAMILY); /*xxx*/
765 *res = sentinel.ai_next;
770 if (sentinel.ai_next)
771 freeaddrinfo(sentinel.ai_next);
776 * numeric hostname with scope
779 explore_numeric_scope(pai, hostname, servname, res)
780 const struct addrinfo *pai;
781 const char *hostname;
782 const char *servname;
783 struct addrinfo **res;
785 #if !defined(SCOPE_DELIMITER) || !defined(INET6)
786 return explore_numeric(pai, hostname, servname, res);
788 const struct afd *afd;
789 struct addrinfo *cur;
791 char *cp, *hostname2 = NULL, *scope, *addr;
792 struct sockaddr_in6 *sin6;
795 * if the servname does not match socktype/protocol, ignore it.
797 if (get_portmatch(pai, servname) != 0)
800 afd = find_afd(pai->ai_family);
805 return explore_numeric(pai, hostname, servname, res);
807 cp = strchr(hostname, SCOPE_DELIMITER);
809 return explore_numeric(pai, hostname, servname, res);
812 * Handle special case of <scoped_address><delimiter><scope id>
814 hostname2 = strdup(hostname);
815 if (hostname2 == NULL)
817 /* terminate at the delimiter */
818 hostname2[cp - hostname] = '\0';
822 error = explore_numeric(pai, addr, servname, res);
826 for (cur = *res; cur; cur = cur->ai_next) {
827 if (cur->ai_family != AF_INET6)
829 sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
830 if ((scopeid = ip6_str2scopeid(scope, sin6)) == -1) {
832 return(EAI_NODATA); /* XXX: is return OK? */
834 sin6->sin6_scope_id = scopeid;
845 get_canonname(pai, ai, str)
846 const struct addrinfo *pai;
850 if ((pai->ai_flags & AI_CANONNAME) != 0) {
851 ai->ai_canonname = (char *)malloc(strlen(str) + 1);
852 if (ai->ai_canonname == NULL)
854 strcpy(ai->ai_canonname, str);
859 static struct addrinfo *
860 get_ai(pai, afd, addr)
861 const struct addrinfo *pai;
862 const struct afd *afd;
868 struct in6_addr faith_prefix;
875 * Transfrom an IPv4 addr into a special IPv6 addr format for
876 * IPv6->IPv4 translation gateway. (only TCP is supported now)
878 * +-----------------------------------+------------+
879 * | faith prefix part (12 bytes) | embedded |
880 * | | IPv4 addr part (4 bytes)
881 * +-----------------------------------+------------+
883 * faith prefix part is specified as ascii IPv6 addr format
884 * in environmental variable GAI.
885 * For FAITH to work correctly, routing to faith prefix must be
886 * setup toward a machine where a FAITH daemon operates.
887 * Also, the machine must enable some mechanizm
888 * (e.g. faith interface hack) to divert those packet with
889 * faith prefixed destination addr to user-land FAITH daemon.
891 fp_str = getenv("GAI");
892 if (fp_str && inet_pton(AF_INET6, fp_str, &faith_prefix) == 1 &&
893 afd->a_af == AF_INET && pai->ai_socktype == SOCK_STREAM) {
897 memcpy(&v4a, addr, sizeof v4a);
898 v4a_top = v4a >> IN_CLASSA_NSHIFT;
899 if (!IN_MULTICAST(v4a) && !IN_EXPERIMENTAL(v4a) &&
900 v4a_top != 0 && v4a != IN_LOOPBACKNET) {
901 afd = &afdl[N_INET6];
902 memcpy(&faith_prefix.s6_addr[12], addr,
903 sizeof(struct in_addr));
909 ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
914 memcpy(ai, pai, sizeof(struct addrinfo));
915 ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
916 memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
917 ai->ai_addr->sa_len = afd->a_socklen;
918 ai->ai_addrlen = afd->a_socklen;
919 ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
920 p = (char *)(void *)(ai->ai_addr);
923 memcpy(p + afd->a_off, &faith_prefix, (size_t)afd->a_addrlen);
926 memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
931 get_portmatch(ai, servname)
932 const struct addrinfo *ai;
933 const char *servname;
936 /* get_port does not touch first argument. when matchonly == 1. */
937 /* LINTED const cast */
938 return get_port((struct addrinfo *)ai, servname, 1);
942 get_port(ai, servname, matchonly)
944 const char *servname;
952 if (servname == NULL)
954 switch (ai->ai_family) {
964 switch (ai->ai_socktype) {
978 if (str_isnumber(servname)) {
981 port = htons(atoi(servname));
982 if (port < 0 || port > 65535)
985 switch (ai->ai_socktype) {
997 if ((sp = getservbyname(servname, proto)) == NULL)
1003 switch (ai->ai_family) {
1005 ((struct sockaddr_in *)(void *)
1006 ai->ai_addr)->sin_port = port;
1010 ((struct sockaddr_in6 *)(void *)
1011 ai->ai_addr)->sin6_port = port;
1020 static const struct afd *
1024 const struct afd *afd;
1026 if (af == PF_UNSPEC)
1028 for (afd = afdl; afd->a_af; afd++) {
1029 if (afd->a_af == af)
1036 * post-2553: AI_ADDRCONFIG check. if we use getipnodeby* as backend, backend
1037 * will take care of it.
1038 * the semantics of AI_ADDRCONFIG is not defined well. we are not sure
1039 * if the code is right or not.
1041 * XXX PF_UNSPEC -> PF_INET6 + PF_INET mapping needs to be in sync with
1046 struct addrinfo *pai;
1052 * Note that implementation dependent test for address
1053 * configuration should be done everytime called
1054 * (or apropriate interval),
1055 * because addresses will be dynamically assigned or deleted.
1057 af = pai->ai_family;
1058 if (af == AF_UNSPEC) {
1059 if ((s = _socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
1063 if ((s = _socket(AF_INET, SOCK_DGRAM, 0)) < 0)
1069 if (af != AF_UNSPEC) {
1070 if ((s = _socket(af, SOCK_DGRAM, 0)) < 0)
1074 pai->ai_family = af;
1079 /* convert a string to a scope identifier. XXX: IPv6 specific */
1081 ip6_str2scopeid(scope, sin6)
1083 struct sockaddr_in6 *sin6;
1086 struct in6_addr *a6 = &sin6->sin6_addr;
1089 /* empty scopeid portion is invalid */
1093 if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
1095 * We currently assume a one-to-one mapping between links
1096 * and interfaces, so we simply use interface indices for
1097 * like-local scopes.
1099 scopeid = if_nametoindex(scope);
1105 /* still unclear about literal, allow numeric only - placeholder */
1106 if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
1108 if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
1111 goto trynumeric; /* global */
1113 /* try to convert to a numeric id as a last resort */
1115 scopeid = (int)strtoul(scope, &ep, 10);
1124 static const char AskedForGot[] =
1125 "gethostby*.getanswer: asked for \"%s\", got \"%s\"";
1127 static FILE *hostf = NULL;
1129 static struct addrinfo *
1130 getanswer(answer, anslen, qname, qtype, pai)
1131 const querybuf *answer;
1135 const struct addrinfo *pai;
1137 struct addrinfo sentinel, *cur;
1139 const struct afd *afd;
1146 int type, class, buflen, ancount, qdcount;
1147 int haveanswer, had_error;
1148 char tbuf[MAXDNAME];
1149 int (*name_ok)(const char *);
1150 char hostbuf[8*1024];
1152 memset(&sentinel, 0, sizeof(sentinel));
1156 eom = answer->buf + anslen;
1160 case T_ANY: /*use T_ANY only for T_A/T_AAAA lookup*/
1164 return (NULL); /* XXX should be abort(); */
1167 * find first satisfactory answer
1170 ancount = ntohs(hp->ancount);
1171 qdcount = ntohs(hp->qdcount);
1173 buflen = sizeof hostbuf;
1174 cp = answer->buf + HFIXEDSZ;
1176 h_errno = NO_RECOVERY;
1179 n = dn_expand(answer->buf, eom, cp, bp, buflen);
1180 if ((n < 0) || !(*name_ok)(bp)) {
1181 h_errno = NO_RECOVERY;
1185 if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
1186 /* res_send() has already verified that the query name is the
1187 * same as the one we sent; this just gets the expanded name
1188 * (i.e., with the succeeding search-domain tacked on).
1190 n = strlen(bp) + 1; /* for the \0 */
1191 if (n >= MAXHOSTNAMELEN) {
1192 h_errno = NO_RECOVERY;
1198 /* The qname can be abbreviated, but h_name is now absolute. */
1203 while (ancount-- > 0 && cp < eom && !had_error) {
1204 n = dn_expand(answer->buf, eom, cp, bp, buflen);
1205 if ((n < 0) || !(*name_ok)(bp)) {
1210 type = _getshort(cp);
1211 cp += INT16SZ; /* type */
1212 class = _getshort(cp);
1213 cp += INT16SZ + INT32SZ; /* class, TTL */
1215 cp += INT16SZ; /* len */
1216 if (class != C_IN) {
1217 /* XXX - debug? syslog? */
1219 continue; /* XXX - had_error++ ? */
1221 if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
1223 n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
1224 if ((n < 0) || !(*name_ok)(tbuf)) {
1229 /* Get canonical name. */
1230 n = strlen(tbuf) + 1; /* for the \0 */
1231 if (n > buflen || n >= MAXHOSTNAMELEN) {
1241 if (qtype == T_ANY) {
1242 if (!(type == T_A || type == T_AAAA)) {
1246 } else if (type != qtype) {
1248 if (type != T_KEY && type != T_SIG)
1249 syslog(LOG_NOTICE|LOG_AUTH,
1250 "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
1251 qname, p_class(C_IN), p_type(qtype),
1255 continue; /* XXX - had_error++ ? */
1260 if (strcasecmp(canonname, bp) != 0) {
1262 syslog(LOG_NOTICE|LOG_AUTH,
1263 AskedForGot, canonname, bp);
1266 continue; /* XXX - had_error++ ? */
1268 if (type == T_A && n != INADDRSZ) {
1272 if (type == T_AAAA && n != IN6ADDRSZ) {
1276 #ifdef FILTER_V4MAPPED
1277 if (type == T_AAAA) {
1278 struct in6_addr in6;
1279 memcpy(&in6, cp, sizeof(in6));
1280 if (IN6_IS_ADDR_V4MAPPED(&in6)) {
1290 nn = strlen(bp) + 1; /* for the \0 */
1295 /* don't overwrite pai */
1297 ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
1298 afd = find_afd(ai.ai_family);
1303 cur->ai_next = get_ai(&ai, afd, (const char *)cp);
1304 if (cur->ai_next == NULL)
1306 while (cur && cur->ai_next)
1318 (void)get_canonname(pai, sentinel.ai_next, qname);
1320 (void)get_canonname(pai, sentinel.ai_next, canonname);
1321 h_errno = NETDB_SUCCESS;
1322 return sentinel.ai_next;
1325 h_errno = NO_RECOVERY;
1331 _dns_getaddrinfo(rv, cb_data, ap)
1336 struct addrinfo *ai;
1339 const struct addrinfo *pai;
1340 struct addrinfo sentinel, *cur;
1341 struct res_target q, q2;
1343 name = va_arg(ap, char *);
1344 pai = va_arg(ap, const struct addrinfo *);
1346 memset(&q, 0, sizeof(q2));
1347 memset(&q2, 0, sizeof(q2));
1348 memset(&sentinel, 0, sizeof(sentinel));
1351 switch (pai->ai_family) {
1357 q.anslen = sizeof(buf);
1361 q2.answer = buf2.buf;
1362 q2.anslen = sizeof(buf2);
1368 q.anslen = sizeof(buf);
1374 q.anslen = sizeof(buf);
1379 if (res_searchN(name, &q) < 0)
1381 ai = getanswer(&buf, q.n, q.name, q.qtype, pai);
1384 while (cur && cur->ai_next)
1388 ai = getanswer(&buf2, q2.n, q2.name, q2.qtype, pai);
1392 if (sentinel.ai_next == NULL)
1394 case HOST_NOT_FOUND:
1401 *((struct addrinfo **)rv) = sentinel.ai_next;
1409 hostf = fopen(_PATH_HOSTS, "r" );
1418 (void) fclose(hostf);
1423 static struct addrinfo *
1424 _gethtent(name, pai)
1426 const struct addrinfo *pai;
1429 char *cp, *tname, *cname;
1430 struct addrinfo hints, *res0, *res;
1433 char hostbuf[8*1024];
1435 if (!hostf && !(hostf = fopen(_PATH_HOSTS, "r" )))
1438 if (!(p = fgets(hostbuf, sizeof hostbuf, hostf)))
1442 if (!(cp = strpbrk(p, "#\n")))
1445 if (!(cp = strpbrk(p, " \t")))
1450 /* if this is not something we're looking for, skip it. */
1452 if (*cp == ' ' || *cp == '\t') {
1459 if ((cp = strpbrk(cp, " \t")) != NULL)
1461 if (strcasecmp(name, tname) == 0)
1468 hints.ai_flags = AI_NUMERICHOST;
1469 error = getaddrinfo(addr, NULL, &hints, &res0);
1472 #ifdef FILTER_V4MAPPED
1473 /* XXX should check all items in the chain */
1474 if (res0->ai_family == AF_INET6 &&
1475 IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)res0->ai_addr)->sin6_addr)) {
1480 for (res = res0; res; res = res->ai_next) {
1482 res->ai_flags = pai->ai_flags;
1484 if (pai->ai_flags & AI_CANONNAME) {
1485 if (get_canonname(pai, res, cname) != 0) {
1496 _files_getaddrinfo(rv, cb_data, ap)
1502 const struct addrinfo *pai;
1503 struct addrinfo sentinel, *cur;
1506 name = va_arg(ap, char *);
1507 pai = va_arg(ap, struct addrinfo *);
1509 memset(&sentinel, 0, sizeof(sentinel));
1513 while ((p = _gethtent(name, pai)) != NULL) {
1515 while (cur && cur->ai_next)
1520 *((struct addrinfo **)rv) = sentinel.ai_next;
1521 if (sentinel.ai_next == NULL)
1527 static char *__ypdomain;
1530 static struct addrinfo *
1531 _yphostent(line, pai)
1533 const struct addrinfo *pai;
1535 struct addrinfo sentinel, *cur;
1536 struct addrinfo hints, *res, *res0;
1539 const char *addr, *canonname;
1543 addr = canonname = NULL;
1545 memset(&sentinel, 0, sizeof(sentinel));
1549 /* terminate line */
1550 cp = strchr(p, '\n');
1557 cp = strpbrk(p, " \t");
1559 if (canonname == NULL)
1569 if (*cp == ' ' || *cp == '\t') {
1575 if ((cp = strpbrk(cp, " \t")) != NULL)
1580 hints.ai_flags = AI_NUMERICHOST;
1581 error = getaddrinfo(addr, NULL, &hints, &res0);
1583 for (res = res0; res; res = res->ai_next) {
1585 res->ai_flags = pai->ai_flags;
1587 if (pai->ai_flags & AI_CANONNAME)
1588 (void)get_canonname(pai, res, canonname);
1593 cur->ai_next = res0;
1594 while (cur && cur->ai_next)
1604 return sentinel.ai_next;
1609 _yp_getaddrinfo(rv, cb_data, ap)
1614 struct addrinfo sentinel, *cur;
1615 struct addrinfo *ai = NULL;
1616 static char *__ypcurrent;
1617 int __ypcurrentlen, r;
1619 const struct addrinfo *pai;
1621 name = va_arg(ap, char *);
1622 pai = va_arg(ap, const struct addrinfo *);
1624 memset(&sentinel, 0, sizeof(sentinel));
1628 if (_yp_check(&__ypdomain) == 0)
1635 /* hosts.byname is only for IPv4 (Solaris8) */
1636 if (pai->ai_family == PF_UNSPEC || pai->ai_family == PF_INET) {
1637 r = yp_match(__ypdomain, "hosts.byname", name,
1638 (int)strlen(name), &__ypcurrent, &__ypcurrentlen);
1640 struct addrinfo ai4;
1643 ai4.ai_family = AF_INET;
1644 ai = _yphostent(__ypcurrent, &ai4);
1647 while (cur && cur->ai_next)
1653 /* ipnodes.byname can hold both IPv4/v6 */
1654 r = yp_match(__ypdomain, "ipnodes.byname", name,
1655 (int)strlen(name), &__ypcurrent, &__ypcurrentlen);
1657 ai = _yphostent(__ypcurrent, pai);
1660 while (cur && cur->ai_next)
1665 if (sentinel.ai_next == NULL) {
1666 h_errno = HOST_NOT_FOUND;
1669 *((struct addrinfo **)rv) = sentinel.ai_next;
1674 /* resolver logic */
1676 extern const char *__hostalias(const char *);
1680 * Formulate a normal query, send, and await answer.
1681 * Returned answer is placed in supplied buffer "answer".
1682 * Perform preliminary check of answer, returning success only
1683 * if no error is indicated and the answer count is nonzero.
1684 * Return the size of the response on success, -1 on error.
1685 * Error number is left in h_errno.
1687 * Caller must parse answer and determine whether it answers the question.
1690 res_queryN(name, target)
1691 const char *name; /* domain name */
1692 struct res_target *target;
1694 u_char buf[MAXPACKET];
1697 struct res_target *t;
1704 if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
1705 h_errno = NETDB_INTERNAL;
1709 for (t = target; t; t = t->next) {
1714 hp = (HEADER *)(void *)t->answer;
1715 hp->rcode = NOERROR; /* default */
1717 /* make it easier... */
1723 if (_res.options & RES_DEBUG)
1724 printf(";; res_query(%s, %d, %d)\n", name, class, type);
1727 n = res_mkquery(QUERY, name, class, type, NULL, 0, NULL,
1729 if (n > 0 && (_res.options & RES_USE_EDNS0) != 0)
1730 n = res_opt(n, buf, sizeof(buf), anslen);
1733 if (_res.options & RES_DEBUG)
1734 printf(";; res_query: mkquery failed\n");
1736 h_errno = NO_RECOVERY;
1739 n = res_send(buf, n, answer, anslen);
1743 if (_res.options & RES_DEBUG)
1744 printf(";; res_query: send error\n");
1746 h_errno = TRY_AGAIN;
1751 if (n < 0 || hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
1752 rcode = hp->rcode; /* record most recent error */
1754 if (_res.options & RES_DEBUG)
1755 printf(";; rcode = %d, ancount=%d\n", hp->rcode,
1756 ntohs(hp->ancount));
1761 ancount += ntohs(hp->ancount);
1769 h_errno = HOST_NOT_FOUND;
1772 h_errno = TRY_AGAIN;
1781 h_errno = NO_RECOVERY;
1790 * Formulate a normal query, send, and retrieve answer in supplied buffer.
1791 * Return the size of the response on success, -1 on error.
1792 * If enabled, implement search rules until answer or unrecoverable failure
1793 * is detected. Error code, if any, is left in h_errno.
1796 res_searchN(name, target)
1797 const char *name; /* domain name */
1798 struct res_target *target;
1800 const char *cp, * const *domain;
1801 HEADER *hp = (HEADER *)(void *)target->answer; /*XXX*/
1803 int trailing_dot, ret, saved_herrno;
1804 int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
1806 if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
1807 h_errno = NETDB_INTERNAL;
1812 h_errno = HOST_NOT_FOUND; /* default, if we never query */
1814 for (cp = name; *cp; cp++)
1815 dots += (*cp == '.');
1817 if (cp > name && *--cp == '.')
1821 * if there aren't any dots, it could be a user-level alias
1823 if (!dots && (cp = __hostalias(name)) != NULL)
1824 return (res_queryN(cp, target));
1827 * If there are dots in the name already, let's just give it a try
1828 * 'as is'. The threshold can be set with the "ndots" option.
1831 if (dots >= _res.ndots) {
1832 ret = res_querydomainN(name, NULL, target);
1835 saved_herrno = h_errno;
1840 * We do at least one level of search if
1841 * - there is no dot and RES_DEFNAME is set, or
1842 * - there is at least one dot, there is no trailing dot,
1843 * and RES_DNSRCH is set.
1845 if ((!dots && (_res.options & RES_DEFNAMES)) ||
1846 (dots && !trailing_dot && (_res.options & RES_DNSRCH))) {
1849 for (domain = (const char * const *)_res.dnsrch;
1853 ret = res_querydomainN(name, *domain, target);
1858 * If no server present, give up.
1859 * If name isn't found in this domain,
1860 * keep trying higher domains in the search list
1861 * (if that's enabled).
1862 * On a NO_DATA error, keep trying, otherwise
1863 * a wildcard entry of another type could keep us
1864 * from finding this entry higher in the domain.
1865 * If we get some other error (negative answer or
1866 * server failure), then stop searching up,
1867 * but try the input name below in case it's
1870 if (errno == ECONNREFUSED) {
1871 h_errno = TRY_AGAIN;
1879 case HOST_NOT_FOUND:
1883 if (hp->rcode == SERVFAIL) {
1884 /* try next search element, if any */
1890 /* anything else implies that we're done */
1894 * if we got here for some reason other than DNSRCH,
1895 * we only wanted one iteration of the loop, so stop.
1897 if (!(_res.options & RES_DNSRCH))
1903 * if we have not already tried the name "as is", do that now.
1904 * note that we do this regardless of how many dots were in the
1905 * name or whether it ends with a dot.
1907 if (!tried_as_is && (dots || !(_res.options & RES_NOTLDQUERY))) {
1908 ret = res_querydomainN(name, NULL, target);
1914 * if we got here, we didn't satisfy the search.
1915 * if we did an initial full query, return that query's h_errno
1916 * (note that we wouldn't be here if that query had succeeded).
1917 * else if we ever got a nodata, send that back as the reason.
1918 * else send back meaningless h_errno, that being the one from
1919 * the last DNSRCH we did.
1921 if (saved_herrno != -1)
1922 h_errno = saved_herrno;
1923 else if (got_nodata)
1925 else if (got_servfail)
1926 h_errno = TRY_AGAIN;
1931 * Perform a call on res_query on the concatenation of name and domain,
1932 * removing a trailing dot from name if domain is NULL.
1935 res_querydomainN(name, domain, target)
1936 const char *name, *domain;
1937 struct res_target *target;
1939 char nbuf[MAXDNAME];
1940 const char *longname = nbuf;
1943 if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
1944 h_errno = NETDB_INTERNAL;
1948 if (_res.options & RES_DEBUG)
1949 printf(";; res_querydomain(%s, %s)\n",
1950 name, domain?domain:"<Nil>");
1952 if (domain == NULL) {
1954 * Check for trailing '.';
1955 * copy without '.' if present.
1958 if (n >= MAXDNAME) {
1959 h_errno = NO_RECOVERY;
1962 if (n > 0 && name[--n] == '.') {
1963 strncpy(nbuf, name, n);
1970 if (n + d + 1 >= MAXDNAME) {
1971 h_errno = NO_RECOVERY;
1974 sprintf(nbuf, "%s.%s", name, domain);
1976 return (res_queryN(longname, target));