Home | History | Annotate | Line # | Download | only in net
getaddrinfo.c revision 1.33
      1 /*	$NetBSD: getaddrinfo.c,v 1.33 2000/02/20 17:07:01 itojun Exp $	*/
      2 
      3 /*
      4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     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.
     18  *
     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
     29  * SUCH DAMAGE.
     30  */
     31 
     32 /*
     33  * Issues to be discussed:
     34  * - Thread safe-ness must be checked.
     35  * - Return values.  There are nonstandard return values defined and used
     36  *   in the source code.  This is because RFC2553 is silent about which error
     37  *   code must be returned for which situation.
     38  * - IPv4 classful (shortened) form.  RFC2553 is silent about it.  XNET 5.2
     39  *   says to use inet_aton() to convert IPv4 numeric to binary (alows
     40  *   classful form as a result).
     41  *   current code - disallow classful form for IPv4 (due to use of inet_pton).
     42  * - freeaddrinfo(NULL).  RFC2553 is silent about it.  XNET 5.2 says it is
     43  *   invalid.
     44  *   current code - SEGV on freeaddrinfo(NULL)
     45  * Note:
     46  * - We use getipnodebyname() just for thread-safeness.  There's no intent
     47  *   to let it do PF_UNSPEC (actually we never pass PF_UNSPEC to
     48  *   getipnodebyname().
     49  * - The code filters out AFs that are not supported by the kernel,
     50  *   when globbing NULL hostname (to loopback, or wildcard).  Is it the right
     51  *   thing to do?  What is the relationship with post-RFC2553 AI_ADDRCONFIG
     52  *   in ai_flags?
     53  * - (post-2553) semantics of AI_ADDRCONFIG itself is too vague.
     54  *   (1) what should we do against numeric hostname (2) what should we do
     55  *   against NULL hostname (3) what is AI_ADDRCONFIG itself.  AF not ready?
     56  *   non-loopback address configured?  global address configured?
     57  * - To avoid search order issue, we have a big amount of code duplicate
     58  *   from gethnamaddr.c and some other places.  The issues that there's no
     59  *   lower layer function to lookup "IPv4 or IPv6" record.  Calling
     60  *   gethostbyname2 from getaddrinfo will end up in wrong search order, as
     61  *   follows:
     62  *	- The code makes use of following calls when asked to resolver with
     63  *	  ai_family  = PF_UNSPEC:
     64  *		getipnodebyname(host, AF_INET6);
     65  *		getipnodebyname(host, AF_INET);
     66  *	  This will result in the following queries if the node is configure to
     67  *	  prefer /etc/hosts than DNS:
     68  *		lookup /etc/hosts for IPv6 address
     69  *		lookup DNS for IPv6 address
     70  *		lookup /etc/hosts for IPv4 address
     71  *		lookup DNS for IPv4 address
     72  *	  which may not meet people's requirement.
     73  *	  The right thing to happen is to have underlying layer which does
     74  *	  PF_UNSPEC lookup (lookup both) and return chain of addrinfos.
     75  *	  This would result in a bit of code duplicate with _dns_ghbyname() and
     76  *	  friends.
     77  */
     78 
     79 #include <sys/types.h>
     80 #include <sys/param.h>
     81 #include <sys/socket.h>
     82 #include <net/if.h>
     83 #include <netinet/in.h>
     84 #include <arpa/inet.h>
     85 #include <arpa/nameser.h>
     86 #include <netdb.h>
     87 #include <resolv.h>
     88 #include <string.h>
     89 #include <stdlib.h>
     90 #include <stddef.h>
     91 #include <ctype.h>
     92 #include <unistd.h>
     93 #include <stdio.h>
     94 #include <errno.h>
     95 
     96 #include <syslog.h>
     97 #include <stdarg.h>
     98 #include <nsswitch.h>
     99 
    100 #ifdef YP
    101 #include <rpc/rpc.h>
    102 #include <rpcsvc/yp_prot.h>
    103 #include <rpcsvc/ypclnt.h>
    104 #endif
    105 
    106 #define SUCCESS 0
    107 #define ANY 0
    108 #define YES 1
    109 #define NO  0
    110 
    111 static const char in_addrany[] = { 0, 0, 0, 0 };
    112 static const char in6_addrany[] = {
    113 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    114 };
    115 static const char in_loopback[] = { 127, 0, 0, 1 };
    116 static const char in6_loopback[] = {
    117 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
    118 };
    119 
    120 struct sockinet {
    121 	u_char	si_len;
    122 	u_char	si_family;
    123 	u_short	si_port;
    124 	u_int32_t si_scope_id;
    125 };
    126 
    127 static const struct afd {
    128 	int a_af;
    129 	int a_addrlen;
    130 	int a_socklen;
    131 	int a_off;
    132 	const char *a_addrany;
    133 	const char *a_loopback;
    134 	int a_scoped;
    135 } afdl [] = {
    136 #ifdef INET6
    137 	{PF_INET6, sizeof(struct in6_addr),
    138 	 sizeof(struct sockaddr_in6),
    139 	 offsetof(struct sockaddr_in6, sin6_addr),
    140 	 in6_addrany, in6_loopback, 1},
    141 #endif
    142 	{PF_INET, sizeof(struct in_addr),
    143 	 sizeof(struct sockaddr_in),
    144 	 offsetof(struct sockaddr_in, sin_addr),
    145 	 in_addrany, in_loopback, 0},
    146 	{0, 0, 0, 0, NULL, NULL, 0},
    147 };
    148 
    149 struct explore {
    150 	int e_af;
    151 	int e_socktype;
    152 	int e_protocol;
    153 	const char *e_protostr;
    154 	int e_wild;
    155 #define WILD_AF(ex)		((ex)->e_wild & 0x01)
    156 #define WILD_SOCKTYPE(ex)	((ex)->e_wild & 0x02)
    157 #define WILD_PROTOCOL(ex)	((ex)->e_wild & 0x04)
    158 };
    159 
    160 static const struct explore explore[] = {
    161 #if 0
    162 	{ PF_LOCAL, 0, ANY, ANY, NULL, 0x01 },
    163 #endif
    164 #ifdef INET6
    165 	{ PF_INET6, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
    166 	{ PF_INET6, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
    167 	{ PF_INET6, SOCK_RAW, ANY, NULL, 0x05 },
    168 #endif
    169 	{ PF_INET, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
    170 	{ PF_INET, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
    171 	{ PF_INET, SOCK_RAW, ANY, NULL, 0x05 },
    172 	{ PF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
    173 	{ PF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
    174 	{ PF_UNSPEC, SOCK_RAW, ANY, NULL, 0x05 },
    175 	{ -1, 0, 0, NULL, 0 },
    176 };
    177 
    178 #ifdef INET6
    179 #define PTON_MAX	16
    180 #else
    181 #define PTON_MAX	4
    182 #endif
    183 
    184 static const ns_src default_dns_files[] = {
    185 	{ NSSRC_FILES, 	NS_SUCCESS },
    186 	{ NSSRC_DNS, 	NS_SUCCESS },
    187 	{ 0 }
    188 };
    189 
    190 #if PACKETSZ > 1024
    191 #define MAXPACKET	PACKETSZ
    192 #else
    193 #define MAXPACKET	1024
    194 #endif
    195 
    196 typedef union {
    197 	HEADER hdr;
    198 	u_char buf[MAXPACKET];
    199 } querybuf;
    200 
    201 struct res_target {
    202 	struct res_target *next;
    203 	const char *name;	/* domain name */
    204 	int class, type;	/* class and type of query */
    205 	u_char *answer;		/* buffer to put answer */
    206 	int anslen;		/* size of answer buffer */
    207 	int n;			/* result length */
    208 };
    209 
    210 static int str_isnumber __P((const char *));
    211 static int explore_fqdn __P((const struct addrinfo *, const char *,
    212 	const char *, struct addrinfo **));
    213 static int explore_null __P((const struct addrinfo *,
    214 	const char *, struct addrinfo **));
    215 static int explore_numeric __P((const struct addrinfo *, const char *,
    216 	const char *, struct addrinfo **));
    217 static int explore_numeric_scope __P((const struct addrinfo *, const char *,
    218 	const char *, struct addrinfo **));
    219 static int get_canonname __P((const struct addrinfo *,
    220 	struct addrinfo *, const char *));
    221 static struct addrinfo *get_ai __P((const struct addrinfo *,
    222 	const struct afd *, const char *));
    223 static int get_portmatch __P((const struct addrinfo *, const char *));
    224 static int get_port __P((struct addrinfo *, const char *, int));
    225 static const struct afd *find_afd __P((int));
    226 static int addrconfig __P((const struct addrinfo *));
    227 #ifdef INET6
    228 static int ip6_str2scopeid __P((char *, struct sockaddr_in6 *));
    229 #endif
    230 
    231 static struct addrinfo *getanswer __P((const querybuf *, int, const char *, int,
    232 	const struct addrinfo *));
    233 static int _dns_getaddrinfo __P((void *, void *, va_list));
    234 static void _sethtent __P((void));
    235 static void _endhtent __P((void));
    236 static struct addrinfo *_gethtent __P((const char *, const struct addrinfo *));
    237 static int _files_getaddrinfo __P((void *, void *, va_list));
    238 #ifdef YP
    239 static struct addrinfo *_yphostent __P((char *, const struct addrinfo *));
    240 static int _yp_getaddrinfo __P((void *, void *, va_list));
    241 #endif
    242 
    243 static int res_queryN __P((const char *, struct res_target *));
    244 static int res_searchN __P((const char *, struct res_target *));
    245 static int res_querydomainN __P((const char *, const char *,
    246 	struct res_target *));
    247 
    248 static char *ai_errlist[] = {
    249 	"Success",
    250 	"Address family for hostname not supported",	/* EAI_ADDRFAMILY */
    251 	"Temporary failure in name resolution",		/* EAI_AGAIN      */
    252 	"Invalid value for ai_flags",		       	/* EAI_BADFLAGS   */
    253 	"Non-recoverable failure in name resolution", 	/* EAI_FAIL       */
    254 	"ai_family not supported",			/* EAI_FAMILY     */
    255 	"Memory allocation failure", 			/* EAI_MEMORY     */
    256 	"No address associated with hostname", 		/* EAI_NODATA     */
    257 	"hostname nor servname provided, or not known",	/* EAI_NONAME     */
    258 	"servname not supported for ai_socktype",	/* EAI_SERVICE    */
    259 	"ai_socktype not supported", 			/* EAI_SOCKTYPE   */
    260 	"System error returned in errno", 		/* EAI_SYSTEM     */
    261 	"Invalid value for hints",			/* EAI_BADHINTS	  */
    262 	"Resolved protocol is unknown",			/* EAI_PROTOCOL   */
    263 	"Unknown error", 				/* EAI_MAX        */
    264 };
    265 
    266 /* XXX macros that make external reference is BAD. */
    267 
    268 #define GET_AI(ai, afd, addr) \
    269 do { \
    270 	/* external reference: pai, error, and label free */ \
    271 	(ai) = get_ai(pai, (afd), (addr)); \
    272 	if ((ai) == NULL) { \
    273 		error = EAI_MEMORY; \
    274 		goto free; \
    275 	} \
    276 } while (/*CONSTCOND*/0)
    277 
    278 #define GET_PORT(ai, serv) \
    279 do { \
    280 	/* external reference: error and label free */ \
    281 	error = get_port((ai), (serv), 0); \
    282 	if (error != 0) \
    283 		goto free; \
    284 } while (/*CONSTCOND*/0)
    285 
    286 #define GET_CANONNAME(ai, str) \
    287 do { \
    288 	/* external reference: pai, error and label free */ \
    289 	error = get_canonname(pai, (ai), (str)); \
    290 	if (error != 0) \
    291 		goto free; \
    292 } while (/*CONSTCOND*/0)
    293 
    294 #define ERR(err) \
    295 do { \
    296 	/* external reference: error, and label bad */ \
    297 	error = (err); \
    298 	goto bad; \
    299 } while (/*CONSTCOND*/0)
    300 
    301 #define MATCH_FAMILY(x, y, w) \
    302 	((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC || (y) == PF_UNSPEC)))
    303 #define MATCH(x, y, w) \
    304 	((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY)))
    305 
    306 char *
    307 gai_strerror(ecode)
    308 	int ecode;
    309 {
    310 	if (ecode < 0 || ecode > EAI_MAX)
    311 		ecode = EAI_MAX;
    312 	return ai_errlist[ecode];
    313 }
    314 
    315 void
    316 freeaddrinfo(ai)
    317 	struct addrinfo *ai;
    318 {
    319 	struct addrinfo *next;
    320 
    321 	do {
    322 		next = ai->ai_next;
    323 		if (ai->ai_canonname)
    324 			free(ai->ai_canonname);
    325 		/* no need to free(ai->ai_addr) */
    326 		free(ai);
    327 		ai = next;
    328 	} while (ai);
    329 }
    330 
    331 static int
    332 str_isnumber(p)
    333 	const char *p;
    334 {
    335 	const char *q = (const char *)p;
    336 	while (*q) {
    337 		if (!isdigit(*q))
    338 			return NO;
    339 		q++;
    340 	}
    341 	return YES;
    342 }
    343 
    344 int
    345 getaddrinfo(hostname, servname, hints, res)
    346 	const char *hostname, *servname;
    347 	const struct addrinfo *hints;
    348 	struct addrinfo **res;
    349 {
    350 	struct addrinfo sentinel;
    351 	struct addrinfo *cur;
    352 	int error = 0;
    353 	struct addrinfo ai;
    354 	struct addrinfo ai0;
    355 	struct addrinfo *pai;
    356 	const struct explore *ex;
    357 
    358 	memset(&sentinel, 0, sizeof(sentinel));
    359 	cur = &sentinel;
    360 	pai = &ai;
    361 	pai->ai_flags = 0;
    362 	pai->ai_family = PF_UNSPEC;
    363 	pai->ai_socktype = ANY;
    364 	pai->ai_protocol = ANY;
    365 	pai->ai_addrlen = 0;
    366 	pai->ai_canonname = NULL;
    367 	pai->ai_addr = NULL;
    368 	pai->ai_next = NULL;
    369 
    370 	if (hostname == NULL && servname == NULL)
    371 		return EAI_NONAME;
    372 	if (hints) {
    373 		/* error check for hints */
    374 		if (hints->ai_addrlen || hints->ai_canonname ||
    375 		    hints->ai_addr || hints->ai_next)
    376 			ERR(EAI_BADHINTS); /* xxx */
    377 		if (hints->ai_flags & ~AI_MASK)
    378 			ERR(EAI_BADFLAGS);
    379 		switch (hints->ai_family) {
    380 		case PF_UNSPEC:
    381 		case PF_INET:
    382 #ifdef INET6
    383 		case PF_INET6:
    384 #endif
    385 			break;
    386 		default:
    387 			ERR(EAI_FAMILY);
    388 		}
    389 		memcpy(pai, hints, sizeof(*pai));
    390 
    391 		/*
    392 		 * if both socktype/protocol are specified, check if they
    393 		 * are meaningful combination.
    394 		 */
    395 		if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
    396 			for (ex = explore; ex->e_af >= 0; ex++) {
    397 				if (pai->ai_family != ex->e_af)
    398 					continue;
    399 				if (ex->e_socktype == ANY)
    400 					continue;
    401 				if (ex->e_protocol == ANY)
    402 					continue;
    403 				if (pai->ai_socktype == ex->e_socktype
    404 				 && pai->ai_protocol != ex->e_protocol) {
    405 					ERR(EAI_BADHINTS);
    406 				}
    407 			}
    408 		}
    409 	}
    410 
    411 	/*
    412 	 * check for special cases.  (1) numeric servname is disallowed if
    413 	 * socktype/protocol are left unspecified. (2) servname is disallowed
    414 	 * for raw and other inet{,6} sockets.
    415 	 */
    416 	if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
    417 #ifdef PF_INET6
    418 	 || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
    419 #endif
    420 	    ) {
    421 		ai0 = *pai;	/* backup *pai */
    422 
    423 		if (pai->ai_family == PF_UNSPEC) {
    424 #ifdef PF_INET6
    425 			pai->ai_family = PF_INET6;
    426 #else
    427 			pai->ai_family = PF_INET;
    428 #endif
    429 		}
    430 		error = get_portmatch(pai, servname);
    431 		if (error)
    432 			ERR(error);
    433 
    434 		*pai = ai0;
    435 	}
    436 
    437 	ai0 = *pai;
    438 
    439 	/* NULL hostname, or numeric hostname */
    440 	for (ex = explore; ex->e_af >= 0; ex++) {
    441 		*pai = ai0;
    442 
    443 		/* PF_UNSPEC entries are prepared for DNS queries only */
    444 		if (ex->e_af == PF_UNSPEC)
    445 			continue;
    446 
    447 		if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
    448 			continue;
    449 		if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex)))
    450 			continue;
    451 		if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex)))
    452 			continue;
    453 
    454 		if (pai->ai_family == PF_UNSPEC)
    455 			pai->ai_family = ex->e_af;
    456 		if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
    457 			pai->ai_socktype = ex->e_socktype;
    458 		if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
    459 			pai->ai_protocol = ex->e_protocol;
    460 
    461 		if (hostname == NULL)
    462 			error = explore_null(pai, servname, &cur->ai_next);
    463 		else
    464 			error = explore_numeric_scope(pai, hostname, servname, &cur->ai_next);
    465 
    466 		if (error)
    467 			goto free;
    468 
    469 		while (cur && cur->ai_next)
    470 			cur = cur->ai_next;
    471 	}
    472 
    473 	/*
    474 	 * XXX
    475 	 * If numreic representation of AF1 can be interpreted as FQDN
    476 	 * representation of AF2, we need to think again about the code below.
    477 	 */
    478 	if (sentinel.ai_next)
    479 		goto good;
    480 
    481 	if (pai->ai_flags & AI_NUMERICHOST)
    482 		ERR(EAI_NONAME);
    483 	if (hostname == NULL)
    484 		ERR(EAI_NONAME);
    485 
    486 	/*
    487 	 * hostname as alphabetical name.
    488 	 * we would like to prefer AF_INET6 than AF_INET, so we'll make a
    489 	 * outer loop by AFs.
    490 	 */
    491 	for (ex = explore; ex->e_af >= 0; ex++) {
    492 		*pai = ai0;
    493 
    494 		/* require exact match for family field */
    495 		if (pai->ai_family != ex->e_af)
    496 			continue;
    497 
    498 		if (!MATCH(pai->ai_socktype, ex->e_socktype,
    499 				WILD_SOCKTYPE(ex))) {
    500 			continue;
    501 		}
    502 		if (!MATCH(pai->ai_protocol, ex->e_protocol,
    503 				WILD_PROTOCOL(ex))) {
    504 			continue;
    505 		}
    506 
    507 		if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
    508 			pai->ai_socktype = ex->e_socktype;
    509 		if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
    510 			pai->ai_protocol = ex->e_protocol;
    511 
    512 		error = explore_fqdn(pai, hostname, servname,
    513 			&cur->ai_next);
    514 
    515 		while (cur && cur->ai_next)
    516 			cur = cur->ai_next;
    517 	}
    518 
    519 	/* XXX */
    520 	if (sentinel.ai_next)
    521 		error = 0;
    522 
    523 	if (error)
    524 		goto free;
    525 	if (error == 0) {
    526 		if (sentinel.ai_next) {
    527  good:
    528 			*res = sentinel.ai_next;
    529 			return SUCCESS;
    530 		} else
    531 			error = EAI_FAIL;
    532 	}
    533  free:
    534  bad:
    535 	if (sentinel.ai_next)
    536 		freeaddrinfo(sentinel.ai_next);
    537 	*res = NULL;
    538 	return error;
    539 }
    540 
    541 /*
    542  * FQDN hostname, DNS lookup
    543  */
    544 static int
    545 explore_fqdn(pai, hostname, servname, res)
    546 	const struct addrinfo *pai;
    547 	const char *hostname;
    548 	const char *servname;
    549 	struct addrinfo **res;
    550 {
    551 	struct addrinfo *result;
    552 	struct addrinfo *cur;
    553 	int error = 0;
    554 	static const ns_dtab dtab[] = {
    555 		NS_FILES_CB(_files_getaddrinfo, NULL)
    556 		{ NSSRC_DNS, _dns_getaddrinfo, NULL },	/* force -DHESIOD */
    557 		NS_NIS_CB(_yp_getaddrinfo, NULL)
    558 		{ 0 }
    559 	};
    560 
    561 	result = NULL;
    562 
    563 	/*
    564 	 * If AI_ADDRCONFIG is specified, check if we are expected to
    565 	 * return the address family or not.
    566 	 */
    567 	if ((pai->ai_flags & AI_ADDRCONFIG) != 0 && !addrconfig(pai))
    568 		return 0;
    569 
    570 	/*
    571 	 * if the servname does not match socktype/protocol, ignore it.
    572 	 */
    573 	if (get_portmatch(pai, servname) != 0)
    574 		return 0;
    575 
    576 	switch (nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
    577 			default_dns_files, hostname, pai)) {
    578 	case NS_TRYAGAIN:
    579 		error = EAI_AGAIN;
    580 		goto free;
    581 	case NS_UNAVAIL:
    582 		error = EAI_FAIL;
    583 		goto free;
    584 	case NS_NOTFOUND:
    585 		error = EAI_NODATA;
    586 		goto free;
    587 	case NS_SUCCESS:
    588 		error = 0;
    589 		for (cur = result; cur; cur = cur->ai_next) {
    590 			GET_PORT(cur, servname);
    591 			/* canonname should be filled already */
    592 		}
    593 		break;
    594 	}
    595 
    596 	*res = result;
    597 
    598 	return 0;
    599 
    600 free:
    601 	return error;
    602 }
    603 
    604 /*
    605  * hostname == NULL.
    606  * passive socket -> anyaddr (0.0.0.0 or ::)
    607  * non-passive socket -> localhost (127.0.0.1 or ::1)
    608  */
    609 static int
    610 explore_null(pai, servname, res)
    611 	const struct addrinfo *pai;
    612 	const char *servname;
    613 	struct addrinfo **res;
    614 {
    615 	int s;
    616 	const struct afd *afd;
    617 	struct addrinfo *cur;
    618 	struct addrinfo sentinel;
    619 	int error;
    620 
    621 	*res = NULL;
    622 	sentinel.ai_next = NULL;
    623 	cur = &sentinel;
    624 
    625 	/*
    626 	 * filter out AFs that are not supported by the kernel
    627 	 * XXX errno?
    628 	 */
    629 	s = socket(pai->ai_family, SOCK_DGRAM, 0);
    630 	if (s < 0) {
    631 		if (errno != EMFILE)
    632 			return 0;
    633 	} else
    634 		close(s);
    635 
    636 	/*
    637 	 * if the servname does not match socktype/protocol, ignore it.
    638 	 */
    639 	if (get_portmatch(pai, servname) != 0)
    640 		return 0;
    641 
    642 	afd = find_afd(pai->ai_family);
    643 
    644 	if (pai->ai_flags & AI_PASSIVE) {
    645 		GET_AI(cur->ai_next, afd, afd->a_addrany);
    646 		/* xxx meaningless?
    647 		 * GET_CANONNAME(cur->ai_next, "anyaddr");
    648 		 */
    649 		GET_PORT(cur->ai_next, servname);
    650 	} else {
    651 		GET_AI(cur->ai_next, afd, afd->a_loopback);
    652 		/* xxx meaningless?
    653 		 * GET_CANONNAME(cur->ai_next, "localhost");
    654 		 */
    655 		GET_PORT(cur->ai_next, servname);
    656 	}
    657 	cur = cur->ai_next;
    658 
    659 	*res = sentinel.ai_next;
    660 	return 0;
    661 
    662 free:
    663 	if (sentinel.ai_next)
    664 		freeaddrinfo(sentinel.ai_next);
    665 	return error;
    666 }
    667 
    668 /*
    669  * numeric hostname
    670  */
    671 static int
    672 explore_numeric(pai, hostname, servname, res)
    673 	const struct addrinfo *pai;
    674 	const char *hostname;
    675 	const char *servname;
    676 	struct addrinfo **res;
    677 {
    678 	const struct afd *afd;
    679 	struct addrinfo *cur;
    680 	struct addrinfo sentinel;
    681 	int error;
    682 	char pton[PTON_MAX];
    683 	int flags;
    684 
    685 	*res = NULL;
    686 	sentinel.ai_next = NULL;
    687 	cur = &sentinel;
    688 
    689 	/*
    690 	 * if the servname does not match socktype/protocol, ignore it.
    691 	 */
    692 	if (get_portmatch(pai, servname) != 0)
    693 		return 0;
    694 
    695 	afd = find_afd(pai->ai_family);
    696 	flags = pai->ai_flags;
    697 
    698 	switch (afd->a_af) {
    699 #if 0 /*X/Open spec*/
    700 	case AF_INET:
    701 		if (inet_aton(hostname, (struct in_addr *)pton) == 1) {
    702 			if (pai->ai_family == afd->a_af ||
    703 			    pai->ai_family == PF_UNSPEC /*?*/) {
    704 				GET_AI(cur->ai_next, afd, pton);
    705 				GET_PORT(cur->ai_next, servname);
    706 				while (cur && cur->ai_next)
    707 					cur = cur->ai_next;
    708 			} else
    709 				ERR(EAI_FAMILY);	/*xxx*/
    710 		}
    711 		break;
    712 #endif
    713 	default:
    714 		if (inet_pton(afd->a_af, hostname, pton) == 1) {
    715 			if (pai->ai_family == afd->a_af ||
    716 			    pai->ai_family == PF_UNSPEC /*?*/) {
    717 				GET_AI(cur->ai_next, afd, pton);
    718 				GET_PORT(cur->ai_next, servname);
    719 				while (cur && cur->ai_next)
    720 					cur = cur->ai_next;
    721 			} else
    722 				ERR(EAI_FAMILY);	/*xxx*/
    723 		}
    724 		break;
    725 	}
    726 
    727 	*res = sentinel.ai_next;
    728 	return 0;
    729 
    730 free:
    731 bad:
    732 	if (sentinel.ai_next)
    733 		freeaddrinfo(sentinel.ai_next);
    734 	return error;
    735 }
    736 
    737 /*
    738  * numeric hostname with scope
    739  */
    740 static int
    741 explore_numeric_scope(pai, hostname, servname, res)
    742 	const struct addrinfo *pai;
    743 	const char *hostname;
    744 	const char *servname;
    745 	struct addrinfo **res;
    746 {
    747 #if !defined(SCOPE_DELIMITER) || !defined(INET6)
    748 	return explore_numeric(pai, hostname, servname, res);
    749 #else
    750 	const struct afd *afd;
    751 	struct addrinfo *cur;
    752 	int error;
    753 	char *cp, *hostname2 = NULL, *scope, *addr;
    754 	struct sockaddr_in6 *sin6;
    755 
    756 	/*
    757 	 * if the servname does not match socktype/protocol, ignore it.
    758 	 */
    759 	if (get_portmatch(pai, servname) != 0)
    760 		return 0;
    761 
    762 	afd = find_afd(pai->ai_family);
    763 	if (!afd->a_scoped)
    764 		return explore_numeric(pai, hostname, servname, res);
    765 
    766 	cp = strchr(hostname, SCOPE_DELIMITER);
    767 	if (cp == NULL)
    768 		return explore_numeric(pai, hostname, servname, res);
    769 
    770 #if 0
    771 	/*
    772 	 * Handle special case of <scope id><delimiter><scoped_address>
    773 	 */
    774 	hostname2 = strdup(hostname);
    775 	if (hostname2 == NULL)
    776 		return EAI_MEMORY;
    777 	/* terminate at the delimiter */
    778 	hostname2[cp - hostname] = '\0';
    779 	scope = hostname2;
    780 	addr = cp + 1;
    781 #else
    782 	/*
    783 	 * Handle special case of <scoped_address><delimiter><scope id>
    784 	 */
    785 	hostname2 = strdup(hostname);
    786 	if (hostname2 == NULL)
    787 		return EAI_MEMORY;
    788 	/* terminate at the delimiter */
    789 	hostname2[cp - hostname] = '\0';
    790 	addr = hostname2;
    791 	scope = cp + 1;
    792 #endif
    793 
    794 	error = explore_numeric(pai, addr, servname, res);
    795 	if (error == 0) {
    796 		int scopeid;
    797 
    798 		for (cur = *res; cur; cur = cur->ai_next) {
    799 			if (cur->ai_family != AF_INET6)
    800 				continue;
    801 			sin6 = (struct sockaddr_in6 *)cur->ai_addr;
    802 			if ((scopeid = ip6_str2scopeid(scope, sin6)) == -1) {
    803 				free(hostname2);
    804 				return(EAI_NONAME); /* XXX: is return OK? */
    805 			}
    806 			sin6->sin6_scope_id = scopeid;
    807 		}
    808 	}
    809 
    810 	free(hostname2);
    811 
    812 	return error;
    813 #endif
    814 }
    815 
    816 static int
    817 get_canonname(pai, ai, str)
    818 	const struct addrinfo *pai;
    819 	struct addrinfo *ai;
    820 	const char *str;
    821 {
    822 	if ((pai->ai_flags & AI_CANONNAME) != 0) {
    823 		ai->ai_canonname = (char *)malloc(strlen(str) + 1);
    824 		if (ai->ai_canonname == NULL)
    825 			return EAI_MEMORY;
    826 		strcpy(ai->ai_canonname, str);
    827 	}
    828 	return 0;
    829 }
    830 
    831 static struct addrinfo *
    832 get_ai(pai, afd, addr)
    833 	const struct addrinfo *pai;
    834 	const struct afd *afd;
    835 	const char *addr;
    836 {
    837 	char *p;
    838 	struct addrinfo *ai;
    839 
    840 	ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
    841 		+ (afd->a_socklen));
    842 	if (ai == NULL)
    843 		return NULL;
    844 
    845 	memcpy(ai, pai, sizeof(struct addrinfo));
    846 	ai->ai_addr = (struct sockaddr *)(ai + 1);
    847 	memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
    848 	ai->ai_addr->sa_len = afd->a_socklen;
    849 	ai->ai_addrlen = afd->a_socklen;
    850 	ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
    851 	p = (char *)(ai->ai_addr);
    852 	memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
    853 	return ai;
    854 }
    855 
    856 static int
    857 get_portmatch(ai, servname)
    858 	const struct addrinfo *ai;
    859 	const char *servname;
    860 {
    861 
    862 	/* get_port does not touch first argument. when matchonly == 1. */
    863 	return get_port((struct addrinfo *)ai, servname, 1);
    864 }
    865 
    866 static int
    867 get_port(ai, servname, matchonly)
    868 	struct addrinfo *ai;
    869 	const char *servname;
    870 	int matchonly;
    871 {
    872 	const char *proto;
    873 	struct servent *sp;
    874 	int port;
    875 	int allownumeric;
    876 
    877 	if (servname == NULL)
    878 		return 0;
    879 	switch (ai->ai_family) {
    880 	case AF_INET:
    881 #ifdef AF_INET6
    882 	case AF_INET6:
    883 #endif
    884 		break;
    885 	default:
    886 		return 0;
    887 	}
    888 
    889 	switch (ai->ai_socktype) {
    890 	case SOCK_RAW:
    891 		return EAI_SERVICE;
    892 	case SOCK_DGRAM:
    893 	case SOCK_STREAM:
    894 		allownumeric = 1;
    895 		break;
    896 	case ANY:
    897 		allownumeric = 0;
    898 		break;
    899 	default:
    900 		return EAI_SOCKTYPE;
    901 	}
    902 
    903 	if (str_isnumber(servname)) {
    904 		if (!allownumeric)
    905 			return EAI_SERVICE;
    906 		port = htons(atoi(servname));
    907 		if (port < 0 || port > 65535)
    908 			return EAI_SERVICE;
    909 	} else {
    910 		switch (ai->ai_socktype) {
    911 		case SOCK_DGRAM:
    912 			proto = "udp";
    913 			break;
    914 		case SOCK_STREAM:
    915 			proto = "tcp";
    916 			break;
    917 		default:
    918 			proto = NULL;
    919 			break;
    920 		}
    921 
    922 		if ((sp = getservbyname(servname, proto)) == NULL)
    923 			return EAI_SERVICE;
    924 		port = sp->s_port;
    925 	}
    926 
    927 	if (!matchonly) {
    928 		switch (ai->ai_family) {
    929 		case AF_INET:
    930 			((struct sockaddr_in *)ai->ai_addr)->sin_port = port;
    931 			break;
    932 #ifdef INET6
    933 		case AF_INET6:
    934 			((struct sockaddr_in6 *)ai->ai_addr)->sin6_port = port;
    935 			break;
    936 #endif
    937 		}
    938 	}
    939 
    940 	return 0;
    941 }
    942 
    943 static const struct afd *
    944 find_afd(af)
    945 	int af;
    946 {
    947 	const struct afd *afd;
    948 
    949 	if (af == PF_UNSPEC)
    950 		return NULL;
    951 	for (afd = afdl; afd->a_af; afd++) {
    952 		if (afd->a_af == af)
    953 			return afd;
    954 	}
    955 	return NULL;
    956 }
    957 
    958 /*
    959  * post-2553: AI_ADDRCONFIG check.  if we use getipnodeby* as backend, backend
    960  * will take care of it.
    961  * the semantics of AI_ADDRCONFIG is not defined well.  we are not sure
    962  * if the code is right or not.
    963  */
    964 static int
    965 addrconfig(pai)
    966 	const struct addrinfo *pai;
    967 {
    968 	int s;
    969 
    970 	/* XXX errno */
    971 	s = socket(pai->ai_family, SOCK_DGRAM, 0);
    972 	if (s < 0)
    973 		return 0;
    974 	close(s);
    975 	return 1;
    976 }
    977 
    978 #ifdef INET6
    979 /* convert a string to a scope identifier. XXX: IPv6 specific */
    980 static int
    981 ip6_str2scopeid(scope, sin6)
    982 	char *scope;
    983 	struct sockaddr_in6 *sin6;
    984 {
    985 	int scopeid;
    986 	struct in6_addr *a6 = &sin6->sin6_addr;
    987 	char *ep;
    988 
    989 	if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
    990 		/*
    991 		 * We currently assume a one-to-one mapping between links
    992 		 * and interfaces, so we simply use interface indices for
    993 		 * like-local scopes.
    994 		 */
    995 		scopeid = if_nametoindex(scope);
    996 		if (scopeid == 0)
    997 			goto trynumeric;
    998 		return(scopeid);
    999 	}
   1000 
   1001 	/* still unclear about literal, allow numeric only - placeholder */
   1002 	if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
   1003 		goto trynumeric;
   1004 	if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
   1005 		goto trynumeric;
   1006 	else
   1007 		goto trynumeric;	/* global */
   1008 
   1009 	/* try to convert to a numeric id as a last resort */
   1010   trynumeric:
   1011 	scopeid = (int)strtoul(scope, &ep, 10);
   1012 	if (*ep == '\0')
   1013 		return scopeid;
   1014 	else
   1015 		return -1;
   1016 }
   1017 #endif
   1018 
   1019 /* code duplicate with gethnamaddr.c */
   1020 
   1021 static const char AskedForGot[] =
   1022 	"gethostby*.getanswer: asked for \"%s\", got \"%s\"";
   1023 static FILE *hostf = NULL;
   1024 
   1025 static struct addrinfo *
   1026 getanswer(answer, anslen, qname, qtype, pai)
   1027 	const querybuf *answer;
   1028 	int anslen;
   1029 	const char *qname;
   1030 	int qtype;
   1031 	const struct addrinfo *pai;
   1032 {
   1033 	struct addrinfo sentinel, *cur;
   1034 	struct addrinfo ai;
   1035 	const struct afd *afd;
   1036 	char *canonname;
   1037 	const HEADER *hp;
   1038 	const u_char *cp;
   1039 	int n;
   1040 	const u_char *eom;
   1041 	char *bp;
   1042 	int type, class, buflen, ancount, qdcount;
   1043 	int haveanswer, had_error;
   1044 	char tbuf[MAXDNAME];
   1045 	const char *tname;
   1046 	int (*name_ok) __P((const char *));
   1047 	char hostbuf[8*1024];
   1048 
   1049 	memset(&sentinel, 0, sizeof(sentinel));
   1050 	cur = &sentinel;
   1051 
   1052 	tname = qname;
   1053 	canonname = NULL;
   1054 	eom = answer->buf + anslen;
   1055 	switch (qtype) {
   1056 	case T_A:
   1057 	case T_AAAA:
   1058 	case T_ANY:	/*use T_ANY only for T_A/T_AAAA lookup*/
   1059 		name_ok = res_hnok;
   1060 		break;
   1061 	default:
   1062 		return (NULL);	/* XXX should be abort(); */
   1063 	}
   1064 	/*
   1065 	 * find first satisfactory answer
   1066 	 */
   1067 	hp = &answer->hdr;
   1068 	ancount = ntohs(hp->ancount);
   1069 	qdcount = ntohs(hp->qdcount);
   1070 	bp = hostbuf;
   1071 	buflen = sizeof hostbuf;
   1072 	cp = answer->buf + HFIXEDSZ;
   1073 	if (qdcount != 1) {
   1074 		h_errno = NO_RECOVERY;
   1075 		return (NULL);
   1076 	}
   1077 	n = dn_expand(answer->buf, eom, cp, bp, buflen);
   1078 	if ((n < 0) || !(*name_ok)(bp)) {
   1079 		h_errno = NO_RECOVERY;
   1080 		return (NULL);
   1081 	}
   1082 	cp += n + QFIXEDSZ;
   1083 	if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
   1084 		/* res_send() has already verified that the query name is the
   1085 		 * same as the one we sent; this just gets the expanded name
   1086 		 * (i.e., with the succeeding search-domain tacked on).
   1087 		 */
   1088 		n = strlen(bp) + 1;		/* for the \0 */
   1089 		if (n >= MAXHOSTNAMELEN) {
   1090 			h_errno = NO_RECOVERY;
   1091 			return (NULL);
   1092 		}
   1093 		canonname = bp;
   1094 		bp += n;
   1095 		buflen -= n;
   1096 		/* The qname can be abbreviated, but h_name is now absolute. */
   1097 		qname = canonname;
   1098 	}
   1099 	haveanswer = 0;
   1100 	had_error = 0;
   1101 	while (ancount-- > 0 && cp < eom && !had_error) {
   1102 		n = dn_expand(answer->buf, eom, cp, bp, buflen);
   1103 		if ((n < 0) || !(*name_ok)(bp)) {
   1104 			had_error++;
   1105 			continue;
   1106 		}
   1107 		cp += n;			/* name */
   1108 		type = _getshort(cp);
   1109  		cp += INT16SZ;			/* type */
   1110 		class = _getshort(cp);
   1111  		cp += INT16SZ + INT32SZ;	/* class, TTL */
   1112 		n = _getshort(cp);
   1113 		cp += INT16SZ;			/* len */
   1114 		if (class != C_IN) {
   1115 			/* XXX - debug? syslog? */
   1116 			cp += n;
   1117 			continue;		/* XXX - had_error++ ? */
   1118 		}
   1119 		if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
   1120 		    type == T_CNAME) {
   1121 			n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
   1122 			if ((n < 0) || !(*name_ok)(tbuf)) {
   1123 				had_error++;
   1124 				continue;
   1125 			}
   1126 			cp += n;
   1127 			/* Get canonical name. */
   1128 			n = strlen(tbuf) + 1;	/* for the \0 */
   1129 			if (n > buflen || n >= MAXHOSTNAMELEN) {
   1130 				had_error++;
   1131 				continue;
   1132 			}
   1133 			strcpy(bp, tbuf);
   1134 			canonname = bp;
   1135 			bp += n;
   1136 			buflen -= n;
   1137 			continue;
   1138 		}
   1139 		if (qtype == T_ANY) {
   1140 			if (!(type == T_A || type == T_AAAA)) {
   1141 				cp += n;
   1142 				continue;
   1143 			}
   1144 		} else if (type != qtype) {
   1145 			if (type != T_KEY && type != T_SIG)
   1146 				syslog(LOG_NOTICE|LOG_AUTH,
   1147 	       "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
   1148 				       qname, p_class(C_IN), p_type(qtype),
   1149 				       p_type(type));
   1150 			cp += n;
   1151 			continue;		/* XXX - had_error++ ? */
   1152 		}
   1153 		switch (type) {
   1154 		case T_A:
   1155 		case T_AAAA:
   1156 			if (strcasecmp(canonname, bp) != 0) {
   1157 				syslog(LOG_NOTICE|LOG_AUTH,
   1158 				       AskedForGot, canonname, bp);
   1159 				cp += n;
   1160 				continue;	/* XXX - had_error++ ? */
   1161 			}
   1162 			if (type == T_A && n != INADDRSZ) {
   1163 				cp += n;
   1164 				continue;
   1165 			}
   1166 			if (type == T_AAAA && n != IN6ADDRSZ) {
   1167 				cp += n;
   1168 				continue;
   1169 			}
   1170 			if (!haveanswer) {
   1171 				int nn;
   1172 
   1173 				canonname = bp;
   1174 				nn = strlen(bp) + 1;	/* for the \0 */
   1175 				bp += nn;
   1176 				buflen -= nn;
   1177 			}
   1178 
   1179 			/* don't overwrite pai */
   1180 			ai = *pai;
   1181 			ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
   1182 			afd = find_afd(ai.ai_family);
   1183 			if (afd == NULL) {
   1184 				cp += n;
   1185 				continue;
   1186 			}
   1187 			cur->ai_next = get_ai(&ai, afd, cp);
   1188 			if (cur->ai_next == NULL)
   1189 				had_error++;
   1190 			while (cur && cur->ai_next)
   1191 				cur = cur->ai_next;
   1192 			cp += n;
   1193 			break;
   1194 		default:
   1195 			abort();
   1196 		}
   1197 		if (!had_error)
   1198 			haveanswer++;
   1199 	}
   1200 	if (haveanswer) {
   1201 		if (!canonname)
   1202 			(void)get_canonname(pai, sentinel.ai_next, qname);
   1203 		else
   1204 			(void)get_canonname(pai, sentinel.ai_next, canonname);
   1205 		h_errno = NETDB_SUCCESS;
   1206 		return sentinel.ai_next;
   1207 	}
   1208 
   1209 	h_errno = NO_RECOVERY;
   1210 	return NULL;
   1211 }
   1212 
   1213 /*ARGSUSED*/
   1214 static int
   1215 _dns_getaddrinfo(rv, cb_data, ap)
   1216 	void	*rv;
   1217 	void	*cb_data;
   1218 	va_list	 ap;
   1219 {
   1220 	struct addrinfo *ai;
   1221 	querybuf buf, buf2;
   1222 	const char *name;
   1223 	const struct addrinfo *pai;
   1224 	struct addrinfo sentinel, *cur;
   1225 	struct res_target q, q2;
   1226 	int ancount;
   1227 
   1228 	name = va_arg(ap, char *);
   1229 	pai = va_arg(ap, const struct addrinfo *);
   1230 
   1231 	memset(&q, 0, sizeof(q2));
   1232 	memset(&q2, 0, sizeof(q2));
   1233 	memset(&sentinel, 0, sizeof(sentinel));
   1234 	cur = &sentinel;
   1235 
   1236 	switch (pai->ai_family) {
   1237 	case AF_UNSPEC:
   1238 		/* prefer IPv6 */
   1239 		q.class = C_IN;
   1240 		q.type = T_AAAA;
   1241 		q.answer = buf.buf;
   1242 		q.anslen = sizeof(buf);
   1243 		q.next = &q2;
   1244 		q2.class = C_IN;
   1245 		q2.type = T_A;
   1246 		q2.answer = buf2.buf;
   1247 		q2.anslen = sizeof(buf2);
   1248 		break;
   1249 	case AF_INET:
   1250 		q.class = C_IN;
   1251 		q.type = T_A;
   1252 		q.answer = buf.buf;
   1253 		q.anslen = sizeof(buf);
   1254 		break;
   1255 	case AF_INET6:
   1256 		q.class = C_IN;
   1257 		q.type = T_AAAA;
   1258 		q.answer = buf.buf;
   1259 		q.anslen = sizeof(buf);
   1260 		break;
   1261 	default:
   1262 		return NS_UNAVAIL;
   1263 	}
   1264 	if ((ancount = res_searchN(name, &q)) < 0)
   1265 		return NS_NOTFOUND;
   1266 	ai = getanswer(&buf, q.n, q.name, q.type, pai);
   1267 	if (ai) {
   1268 		cur->ai_next = ai;
   1269 		while (cur && cur->ai_next)
   1270 			cur = cur->ai_next;
   1271 	}
   1272 	if (q.next) {
   1273 		ai = getanswer(&buf2, q2.n, q2.name, q2.type, pai);
   1274 		if (ai)
   1275 			cur->ai_next = ai;
   1276 	}
   1277 	if (sentinel.ai_next == NULL)
   1278 		switch (h_errno) {
   1279 		case HOST_NOT_FOUND:
   1280 			return NS_NOTFOUND;
   1281 		case TRY_AGAIN:
   1282 			return NS_TRYAGAIN;
   1283 		default:
   1284 			return NS_UNAVAIL;
   1285 		}
   1286 	*((struct addrinfo **)rv) = sentinel.ai_next;
   1287 	return NS_SUCCESS;
   1288 }
   1289 
   1290 static void
   1291 _sethtent()
   1292 {
   1293 	if (!hostf)
   1294 		hostf = fopen(_PATH_HOSTS, "r" );
   1295 	else
   1296 		rewind(hostf);
   1297 }
   1298 
   1299 static void
   1300 _endhtent()
   1301 {
   1302 	if (hostf) {
   1303 		(void) fclose(hostf);
   1304 		hostf = NULL;
   1305 	}
   1306 }
   1307 
   1308 static struct addrinfo *
   1309 _gethtent(name, pai)
   1310 	const char *name;
   1311 	const struct addrinfo *pai;
   1312 {
   1313 	char *p;
   1314 	char *cp, *tname;
   1315 	struct addrinfo hints, *res0, *res;
   1316 	int error;
   1317 	const char *addr;
   1318 	char hostbuf[8*1024];
   1319 
   1320 	if (!hostf && !(hostf = fopen(_PATH_HOSTS, "r" )))
   1321 		return (NULL);
   1322  again:
   1323 	if (!(p = fgets(hostbuf, sizeof hostbuf, hostf)))
   1324 		return (NULL);
   1325 	if (*p == '#')
   1326 		goto again;
   1327 	if (!(cp = strpbrk(p, "#\n")))
   1328 		goto again;
   1329 	*cp = '\0';
   1330 	if (!(cp = strpbrk(p, " \t")))
   1331 		goto again;
   1332 	*cp++ = '\0';
   1333 	addr = p;
   1334 	/* if this is not something we're looking for, skip it. */
   1335 	while (cp && *cp) {
   1336 		if (*cp == ' ' || *cp == '\t') {
   1337 			cp++;
   1338 			continue;
   1339 		}
   1340 		tname = cp;
   1341 		if ((cp = strpbrk(cp, " \t")) != NULL)
   1342 			*cp++ = '\0';
   1343 		if (strcasecmp(name, tname) == 0)
   1344 			goto found;
   1345 	}
   1346 	goto again;
   1347 
   1348 found:
   1349 	hints = *pai;
   1350 	hints.ai_flags = AI_NUMERICHOST;
   1351 	error = getaddrinfo(addr, NULL, &hints, &res0);
   1352 	if (error)
   1353 		goto again;
   1354 	for (res = res0; res; res = res->ai_next) {
   1355 		/* cover it up */
   1356 		res->ai_flags = pai->ai_flags;
   1357 
   1358 		if (pai->ai_flags & AI_CANONNAME) {
   1359 			if (get_canonname(pai, res, name) != 0) {
   1360 				freeaddrinfo(res0);
   1361 				goto again;
   1362 			}
   1363 		}
   1364 	}
   1365 	return res0;
   1366 }
   1367 
   1368 /*ARGSUSED*/
   1369 static int
   1370 _files_getaddrinfo(rv, cb_data, ap)
   1371 	void	*rv;
   1372 	void	*cb_data;
   1373 	va_list	 ap;
   1374 {
   1375 	const char *name;
   1376 	const struct addrinfo *pai;
   1377 	struct addrinfo sentinel, *cur;
   1378 	struct addrinfo *p;
   1379 
   1380 	name = va_arg(ap, char *);
   1381 	pai = va_arg(ap, struct addrinfo *);
   1382 
   1383 	memset(&sentinel, 0, sizeof(sentinel));
   1384 	cur = &sentinel;
   1385 
   1386 	_sethtent();
   1387 	while ((p = _gethtent(name, pai)) != NULL) {
   1388 		cur->ai_next = p;
   1389 		while (cur && cur->ai_next)
   1390 			cur = cur->ai_next;
   1391 	}
   1392 	_endhtent();
   1393 
   1394 	*((struct addrinfo **)rv) = sentinel.ai_next;
   1395 	if (sentinel.ai_next == NULL)
   1396 		return NS_NOTFOUND;
   1397 	return NS_SUCCESS;
   1398 }
   1399 
   1400 #ifdef YP
   1401 static char *__ypdomain;
   1402 
   1403 /*ARGSUSED*/
   1404 static struct addrinfo *
   1405 _yphostent(line, pai)
   1406 	char *line;
   1407 	const struct addrinfo *pai;
   1408 {
   1409 	struct addrinfo sentinel, *cur;
   1410 	struct addrinfo hints, *res, *res0;
   1411 	int error;
   1412 	char *p = line;
   1413 	const char *addr, *canonname;
   1414 	char *nextline;
   1415 	char *cp;
   1416 	int more;
   1417 
   1418 	addr = canonname = NULL;
   1419 
   1420 nextline:
   1421 	more = 0;
   1422 
   1423 	/* terminate line */
   1424 	cp = strchr(p, '\n');
   1425 	if (cp) {
   1426 		*cp++ = '\0';
   1427 		nextline = cp;
   1428 	} else
   1429 		nextline = NULL;
   1430 
   1431 	cp = strpbrk(p, " \t");
   1432 	if (cp == NULL) {
   1433 		if (canonname == NULL)
   1434 			return (NULL);
   1435 		else
   1436 			goto done;
   1437 	}
   1438 	*cp++ = '\0';
   1439 
   1440 	addr = p;
   1441 
   1442 	while (cp && *cp) {
   1443 		if (*cp == ' ' || *cp == '\t') {
   1444 			cp++;
   1445 			continue;
   1446 		}
   1447 		if (!canonname)
   1448 			canonname = cp;
   1449 		if ((cp = strpbrk(cp, " \t")) != NULL)
   1450 			*cp++ = '\0';
   1451 	}
   1452 
   1453 	hints = *pai;
   1454 	hints.ai_flags = AI_NUMERICHOST;
   1455 	error = getaddrinfo(addr, NULL, &hints, &res0);
   1456 	if (error == 0) {
   1457 		for (res = res0; res; res = res->ai_next) {
   1458 			/* cover it up */
   1459 			res->ai_flags = pai->ai_flags;
   1460 
   1461 			if (pai->ai_flags & AI_CANONNAME)
   1462 				(void)get_canonname(pai, res, canonname);
   1463 		}
   1464 	}
   1465 	if (res0) {
   1466 		cur->ai_next = res0;
   1467 		while (cur && cur->ai_next)
   1468 			cur = cur->ai_next;
   1469 	}
   1470 
   1471 	if (nextline) {
   1472 		p = nextline;
   1473 		goto nextline;
   1474 	}
   1475 
   1476 done:
   1477 	return sentinel.ai_next;
   1478 }
   1479 
   1480 /*ARGSUSED*/
   1481 static int
   1482 _yp_getaddrinfo(rv, cb_data, ap)
   1483 	void	*rv;
   1484 	void	*cb_data;
   1485 	va_list	 ap;
   1486 {
   1487 	struct addrinfo sentinel, *cur;
   1488 	struct addrinfo *ai = NULL;
   1489 	static char *__ypcurrent;
   1490 	int __ypcurrentlen, r;
   1491 	const char *name;
   1492 	const struct addrinfo *pai;
   1493 
   1494 	name = va_arg(ap, char *);
   1495 	pai = va_arg(ap, const struct addrinfo *);
   1496 
   1497 	memset(&sentinel, 0, sizeof(sentinel));
   1498 	cur = &sentinel;
   1499 
   1500 	if (!__ypdomain) {
   1501 		if (_yp_check(&__ypdomain) == 0)
   1502 			return NS_UNAVAIL;
   1503 	}
   1504 	if (__ypcurrent)
   1505 		free(__ypcurrent);
   1506 	__ypcurrent = NULL;
   1507 
   1508 	/* hosts.byname is only for IPv4 (Solaris8) */
   1509 	if (pai->ai_family == PF_UNSPEC || pai->ai_family == PF_INET) {
   1510 		r = yp_match(__ypdomain, "hosts.byname", name,
   1511 			(int)strlen(name), &__ypcurrent, &__ypcurrentlen);
   1512 		if (r == 0) {
   1513 			struct addrinfo ai4;
   1514 
   1515 			ai4 = *pai;
   1516 			ai4.ai_family = AF_INET;
   1517 			ai = _yphostent(__ypcurrent, &ai4);
   1518 			if (ai) {
   1519 				cur->ai_next = ai;
   1520 				while (cur && cur->ai_next)
   1521 					cur = cur->ai_next;
   1522 			}
   1523 		}
   1524 	}
   1525 
   1526 	/* ipnodes.byname can hold both IPv4/v6 */
   1527 	r = yp_match(__ypdomain, "ipnodes.byname", name,
   1528 		(int)strlen(name), &__ypcurrent, &__ypcurrentlen);
   1529 	if (r == 0) {
   1530 		ai = _yphostent(__ypcurrent, pai);
   1531 		if (ai) {
   1532 			cur->ai_next = ai;
   1533 			while (cur && cur->ai_next)
   1534 				cur = cur->ai_next;
   1535 		}
   1536 	}
   1537 
   1538 	if (sentinel.ai_next == NULL) {
   1539 		h_errno = HOST_NOT_FOUND;
   1540 		return NS_NOTFOUND;
   1541 	}
   1542 	*((struct addrinfo **)rv) = sentinel.ai_next;
   1543 	return NS_SUCCESS;
   1544 }
   1545 #endif
   1546 
   1547 /* resolver logic */
   1548 
   1549 extern const char *__hostalias __P((const char *));
   1550 extern int h_errno;
   1551 
   1552 /*
   1553  * Formulate a normal query, send, and await answer.
   1554  * Returned answer is placed in supplied buffer "answer".
   1555  * Perform preliminary check of answer, returning success only
   1556  * if no error is indicated and the answer count is nonzero.
   1557  * Return the size of the response on success, -1 on error.
   1558  * Error number is left in h_errno.
   1559  *
   1560  * Caller must parse answer and determine whether it answers the question.
   1561  */
   1562 static int
   1563 res_queryN(name, target)
   1564 	const char *name;	/* domain name */
   1565 	struct res_target *target;
   1566 {
   1567 	u_char buf[MAXPACKET];
   1568 	HEADER *hp;
   1569 	int n;
   1570 	struct res_target *t;
   1571 	int rcode;
   1572 	int ancount;
   1573 
   1574 	rcode = NOERROR;
   1575 	ancount = 0;
   1576 
   1577 	if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
   1578 		h_errno = NETDB_INTERNAL;
   1579 		return (-1);
   1580 	}
   1581 
   1582 	for (t = target; t; t = t->next) {
   1583 		int class, type;
   1584 		u_char *answer;
   1585 		int anslen;
   1586 
   1587 		hp = (HEADER *)(void *)t->answer;
   1588 		hp->rcode = NOERROR;	/* default */
   1589 
   1590 		/* make it easier... */
   1591 		class = t->class;
   1592 		type = t->type;
   1593 		answer = t->answer;
   1594 		anslen = t->anslen;
   1595 #ifdef DEBUG
   1596 		if (_res.options & RES_DEBUG)
   1597 			printf(";; res_query(%s, %d, %d)\n", name, class, type);
   1598 #endif
   1599 
   1600 		n = res_mkquery(QUERY, name, class, type, NULL, 0, NULL,
   1601 		    buf, sizeof(buf));
   1602 		if (n <= 0) {
   1603 #ifdef DEBUG
   1604 			if (_res.options & RES_DEBUG)
   1605 				printf(";; res_query: mkquery failed\n");
   1606 #endif
   1607 			h_errno = NO_RECOVERY;
   1608 			return (n);
   1609 		}
   1610 		n = res_send(buf, n, answer, anslen);
   1611 		if (n < 0) {
   1612 #ifdef DEBUG
   1613 			if (_res.options & RES_DEBUG)
   1614 				printf(";; res_query: send error\n");
   1615 #endif
   1616 			h_errno = TRY_AGAIN;
   1617 			return (n);
   1618 		}
   1619 
   1620 		if (hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
   1621 			rcode = hp->rcode;	/* record most recent error */
   1622 #ifdef DEBUG
   1623 			if (_res.options & RES_DEBUG)
   1624 				printf(";; rcode = %d, ancount=%d\n", hp->rcode,
   1625 				    ntohs(hp->ancount));
   1626 #endif
   1627 			continue;
   1628 		}
   1629 
   1630 		ancount += ntohs(hp->ancount);
   1631 
   1632 		t->n = n;
   1633 	}
   1634 
   1635 	if (ancount == 0) {
   1636 		switch (rcode) {
   1637 		case NXDOMAIN:
   1638 			h_errno = HOST_NOT_FOUND;
   1639 			break;
   1640 		case SERVFAIL:
   1641 			h_errno = TRY_AGAIN;
   1642 			break;
   1643 		case NOERROR:
   1644 			h_errno = NO_DATA;
   1645 			break;
   1646 		case FORMERR:
   1647 		case NOTIMP:
   1648 		case REFUSED:
   1649 		default:
   1650 			h_errno = NO_RECOVERY;
   1651 			break;
   1652 		}
   1653 		return (-1);
   1654 	}
   1655 	return (ancount);
   1656 }
   1657 
   1658 /*
   1659  * Formulate a normal query, send, and retrieve answer in supplied buffer.
   1660  * Return the size of the response on success, -1 on error.
   1661  * If enabled, implement search rules until answer or unrecoverable failure
   1662  * is detected.  Error code, if any, is left in h_errno.
   1663  */
   1664 static int
   1665 res_searchN(name, target)
   1666 	const char *name;	/* domain name */
   1667 	struct res_target *target;
   1668 {
   1669 	const char *cp, * const *domain;
   1670 	HEADER *hp = (HEADER *)(void *)target->answer;	/*XXX*/
   1671 	u_int dots;
   1672 	int trailing_dot, ret, saved_herrno;
   1673 	int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
   1674 
   1675 	if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
   1676 		h_errno = NETDB_INTERNAL;
   1677 		return (-1);
   1678 	}
   1679 
   1680 	errno = 0;
   1681 	h_errno = HOST_NOT_FOUND;	/* default, if we never query */
   1682 	dots = 0;
   1683 	for (cp = name; *cp; cp++)
   1684 		dots += (*cp == '.');
   1685 	trailing_dot = 0;
   1686 	if (cp > name && *--cp == '.')
   1687 		trailing_dot++;
   1688 
   1689 	/*
   1690 	 * if there aren't any dots, it could be a user-level alias
   1691 	 */
   1692 	if (!dots && (cp = __hostalias(name)) != NULL)
   1693 		return (res_queryN(cp, target));
   1694 
   1695 	/*
   1696 	 * If there are dots in the name already, let's just give it a try
   1697 	 * 'as is'.  The threshold can be set with the "ndots" option.
   1698 	 */
   1699 	saved_herrno = -1;
   1700 	if (dots >= _res.ndots) {
   1701 		ret = res_querydomainN(name, NULL, target);
   1702 		if (ret > 0)
   1703 			return (ret);
   1704 		saved_herrno = h_errno;
   1705 		tried_as_is++;
   1706 	}
   1707 
   1708 	/*
   1709 	 * We do at least one level of search if
   1710 	 *	- there is no dot and RES_DEFNAME is set, or
   1711 	 *	- there is at least one dot, there is no trailing dot,
   1712 	 *	  and RES_DNSRCH is set.
   1713 	 */
   1714 	if ((!dots && (_res.options & RES_DEFNAMES)) ||
   1715 	    (dots && !trailing_dot && (_res.options & RES_DNSRCH))) {
   1716 		int done = 0;
   1717 
   1718 		for (domain = (const char * const *)_res.dnsrch;
   1719 		   *domain && !done;
   1720 		   domain++) {
   1721 
   1722 			ret = res_querydomainN(name, *domain, target);
   1723 			if (ret > 0)
   1724 				return (ret);
   1725 
   1726 			/*
   1727 			 * If no server present, give up.
   1728 			 * If name isn't found in this domain,
   1729 			 * keep trying higher domains in the search list
   1730 			 * (if that's enabled).
   1731 			 * On a NO_DATA error, keep trying, otherwise
   1732 			 * a wildcard entry of another type could keep us
   1733 			 * from finding this entry higher in the domain.
   1734 			 * If we get some other error (negative answer or
   1735 			 * server failure), then stop searching up,
   1736 			 * but try the input name below in case it's
   1737 			 * fully-qualified.
   1738 			 */
   1739 			if (errno == ECONNREFUSED) {
   1740 				h_errno = TRY_AGAIN;
   1741 				return (-1);
   1742 			}
   1743 
   1744 			switch (h_errno) {
   1745 			case NO_DATA:
   1746 				got_nodata++;
   1747 				/* FALLTHROUGH */
   1748 			case HOST_NOT_FOUND:
   1749 				/* keep trying */
   1750 				break;
   1751 			case TRY_AGAIN:
   1752 				if (hp->rcode == SERVFAIL) {
   1753 					/* try next search element, if any */
   1754 					got_servfail++;
   1755 					break;
   1756 				}
   1757 				/* FALLTHROUGH */
   1758 			default:
   1759 				/* anything else implies that we're done */
   1760 				done++;
   1761 			}
   1762 			/*
   1763 			 * if we got here for some reason other than DNSRCH,
   1764 			 * we only wanted one iteration of the loop, so stop.
   1765 			 */
   1766 			if (!(_res.options & RES_DNSRCH))
   1767 			        done++;
   1768 		}
   1769 	}
   1770 
   1771 	/*
   1772 	 * if we have not already tried the name "as is", do that now.
   1773 	 * note that we do this regardless of how many dots were in the
   1774 	 * name or whether it ends with a dot.
   1775 	 */
   1776 	if (!tried_as_is) {
   1777 		ret = res_querydomainN(name, NULL, target);
   1778 		if (ret > 0)
   1779 			return (ret);
   1780 	}
   1781 
   1782 	/*
   1783 	 * if we got here, we didn't satisfy the search.
   1784 	 * if we did an initial full query, return that query's h_errno
   1785 	 * (note that we wouldn't be here if that query had succeeded).
   1786 	 * else if we ever got a nodata, send that back as the reason.
   1787 	 * else send back meaningless h_errno, that being the one from
   1788 	 * the last DNSRCH we did.
   1789 	 */
   1790 	if (saved_herrno != -1)
   1791 		h_errno = saved_herrno;
   1792 	else if (got_nodata)
   1793 		h_errno = NO_DATA;
   1794 	else if (got_servfail)
   1795 		h_errno = TRY_AGAIN;
   1796 	return (-1);
   1797 }
   1798 
   1799 /*
   1800  * Perform a call on res_query on the concatenation of name and domain,
   1801  * removing a trailing dot from name if domain is NULL.
   1802  */
   1803 static int
   1804 res_querydomainN(name, domain, target)
   1805 	const char *name, *domain;
   1806 	struct res_target *target;
   1807 {
   1808 	char nbuf[MAXDNAME];
   1809 	const char *longname = nbuf;
   1810 	size_t n, d;
   1811 
   1812 	if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
   1813 		h_errno = NETDB_INTERNAL;
   1814 		return (-1);
   1815 	}
   1816 #ifdef DEBUG
   1817 	if (_res.options & RES_DEBUG)
   1818 		printf(";; res_querydomain(%s, %s)\n",
   1819 			name, domain?domain:"<Nil>");
   1820 #endif
   1821 	if (domain == NULL) {
   1822 		/*
   1823 		 * Check for trailing '.';
   1824 		 * copy without '.' if present.
   1825 		 */
   1826 		n = strlen(name);
   1827 		if (n >= MAXDNAME) {
   1828 			h_errno = NO_RECOVERY;
   1829 			return (-1);
   1830 		}
   1831 		if (n-- != 0 && name[n] == '.') {
   1832 			strncpy(nbuf, name, n);
   1833 			nbuf[n] = '\0';
   1834 		} else
   1835 			longname = name;
   1836 	} else {
   1837 		n = strlen(name);
   1838 		d = strlen(domain);
   1839 		if (n + d + 1 >= MAXDNAME) {
   1840 			h_errno = NO_RECOVERY;
   1841 			return (-1);
   1842 		}
   1843 		sprintf(nbuf, "%s.%s", name, domain);
   1844 	}
   1845 	return (res_queryN(longname, target));
   1846 }
   1847