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