Home | History | Annotate | Line # | Download | only in net
getaddrinfo.c revision 1.21
      1 /*	$NetBSD: getaddrinfo.c,v 1.21 2000/01/23 01:37:19 mycroft 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  * "#ifdef FAITH" part is local hack for supporting IPv4-v6 translator.
     34  *
     35  * Issues to be discussed:
     36  * - Thread safe-ness must be checked.
     37  * - Return values.  There are nonstandard return values defined and used
     38  *   in the source code.  This is because RFC2553 is silent about which error
     39  *   code must be returned for which situation.
     40  * Note:
     41  * - We use getipnodebyname() just for thread-safeness.  There's no intent
     42  *   to let it do PF_UNSPEC (actually we never pass PF_UNSPEC to
     43  *   getipnodebyname().
     44  * - The code filters out AFs that are not supported by the kernel,
     45  *   when resolving FQDNs and globbing NULL hostname.  Is it the right
     46  *   thing to do?  What is the relationship with post-RFC2553 AI_ADDRCONFIG
     47  *   in ai_flags?
     48  */
     49 
     50 #include <sys/types.h>
     51 #include <sys/param.h>
     52 #include <sys/socket.h>
     53 #include <net/if.h>
     54 #include <netinet/in.h>
     55 #include <arpa/inet.h>
     56 #include <arpa/nameser.h>
     57 #include <netdb.h>
     58 #include <resolv.h>
     59 #include <string.h>
     60 #include <stdlib.h>
     61 #include <stddef.h>
     62 #include <ctype.h>
     63 #include <unistd.h>
     64 #include <stdio.h>
     65 #include <errno.h>
     66 
     67 #define SUCCESS 0
     68 #define ANY 0
     69 #define YES 1
     70 #define NO  0
     71 
     72 #ifdef FAITH
     73 static int translate = NO;
     74 static struct in6_addr faith_prefix = IN6ADDR_ANY_INIT;
     75 #endif
     76 
     77 static const char in_addrany[] = { 0, 0, 0, 0 };
     78 static const char in6_addrany[] = {
     79 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
     80 };
     81 static const char in_loopback[] = { 127, 0, 0, 1 };
     82 static const char in6_loopback[] = {
     83 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
     84 };
     85 
     86 struct sockinet {
     87 	u_char	si_len;
     88 	u_char	si_family;
     89 	u_short	si_port;
     90 	u_int32_t si_scope_id;
     91 };
     92 
     93 static const struct afd {
     94 	int a_af;
     95 	int a_addrlen;
     96 	int a_socklen;
     97 	int a_off;
     98 	const char *a_addrany;
     99 	const char *a_loopback;
    100 	int a_scoped;
    101 } afdl [] = {
    102 #ifdef INET6
    103 	{PF_INET6, sizeof(struct in6_addr),
    104 	 sizeof(struct sockaddr_in6),
    105 	 offsetof(struct sockaddr_in6, sin6_addr),
    106 	 in6_addrany, in6_loopback, 1},
    107 #endif
    108 	{PF_INET, sizeof(struct in_addr),
    109 	 sizeof(struct sockaddr_in),
    110 	 offsetof(struct sockaddr_in, sin_addr),
    111 	 in_addrany, in_loopback, 0},
    112 	{0, 0, 0, 0, NULL, NULL, 0},
    113 };
    114 
    115 struct explore {
    116 	int e_af;
    117 	int e_socktype;
    118 	int e_protocol;
    119 	const char *e_protostr;
    120 	int e_wild;
    121 #define WILD_AF(ex)		((ex)->e_wild & 0x01)
    122 #define WILD_SOCKTYPE(ex)	((ex)->e_wild & 0x02)
    123 #define WILD_PROTOCOL(ex)	((ex)->e_wild & 0x04)
    124 };
    125 
    126 static const struct explore explore[] = {
    127 #if 0
    128 	{ PF_LOCAL, 0, ANY, ANY, NULL, 0x01 },
    129 #endif
    130 #ifdef INET6
    131 	{ PF_INET6, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
    132 	{ PF_INET6, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
    133 	{ PF_INET6, SOCK_RAW, ANY, NULL, 0x05 },
    134 #endif
    135 	{ PF_INET, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
    136 	{ PF_INET, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
    137 	{ PF_INET, SOCK_RAW, ANY, NULL, 0x05 },
    138 	{ -1, 0, 0, NULL, 0 },
    139 };
    140 
    141 #ifdef INET6
    142 #define PTON_MAX	16
    143 #else
    144 #define PTON_MAX	4
    145 #endif
    146 
    147 
    148 static int str_isnumber __P((const char *));
    149 static int explore_fqdn __P((const struct addrinfo *, const char *,
    150 	const char *, struct addrinfo **));
    151 static int explore_null __P((const struct addrinfo *,
    152 	const char *, struct addrinfo **));
    153 static int explore_numeric __P((const struct addrinfo *, const char *,
    154 	const char *, struct addrinfo **));
    155 static int explore_numeric_scope __P((const struct addrinfo *, const char *,
    156 	const char *, struct addrinfo **));
    157 static int get_name __P((const char *, const struct afd *, struct addrinfo **,
    158 	char *, const struct addrinfo *, const char *));
    159 static int get_canonname __P((const struct addrinfo *,
    160 	struct addrinfo *, const char *));
    161 static struct addrinfo *get_ai __P((const struct addrinfo *,
    162 	const struct afd *, const char *));
    163 static int get_portmatch __P((const struct addrinfo *, const char *));
    164 static int get_port __P((struct addrinfo *, const char *, int));
    165 static const struct afd *find_afd __P((int));
    166 
    167 static char *ai_errlist[] = {
    168 	"Success",
    169 	"Address family for hostname not supported",	/* EAI_ADDRFAMILY */
    170 	"Temporary failure in name resolution",		/* EAI_AGAIN      */
    171 	"Invalid value for ai_flags",		       	/* EAI_BADFLAGS   */
    172 	"Non-recoverable failure in name resolution", 	/* EAI_FAIL       */
    173 	"ai_family not supported",			/* EAI_FAMILY     */
    174 	"Memory allocation failure", 			/* EAI_MEMORY     */
    175 	"No address associated with hostname", 		/* EAI_NODATA     */
    176 	"hostname nor servname provided, or not known",	/* EAI_NONAME     */
    177 	"servname not supported for ai_socktype",	/* EAI_SERVICE    */
    178 	"ai_socktype not supported", 			/* EAI_SOCKTYPE   */
    179 	"System error returned in errno", 		/* EAI_SYSTEM     */
    180 	"Invalid value for hints",			/* EAI_BADHINTS	  */
    181 	"Resolved protocol is unknown",			/* EAI_PROTOCOL   */
    182 	"Unknown error", 				/* EAI_MAX        */
    183 };
    184 
    185 /* XXX macros that make external reference is BAD. */
    186 
    187 #define GET_AI(ai, afd, addr) \
    188 do { \
    189 	/* external reference: pai, error, and label free */ \
    190 	(ai) = get_ai(pai, (afd), (addr)); \
    191 	if ((ai) == NULL) { \
    192 		error = EAI_MEMORY; \
    193 		goto free; \
    194 	} \
    195 } while (/*CONSTCOND*/0)
    196 
    197 #define GET_PORT(ai, serv) \
    198 do { \
    199 	/* external reference: error and label free */ \
    200 	error = get_port((ai), (serv), 0); \
    201 	if (error != 0) \
    202 		goto free; \
    203 } while (/*CONSTCOND*/0)
    204 
    205 #define GET_CANONNAME(ai, str) \
    206 do { \
    207 	/* external reference: pai, error and label free */ \
    208 	error = get_canonname(pai, (ai), (str)); \
    209 	if (error != 0) \
    210 		goto free; \
    211 } while (/*CONSTCOND*/0)
    212 
    213 #define ERR(err) \
    214 do { \
    215 	/* external reference: error, and label bad */ \
    216 	error = (err); \
    217 	goto bad; \
    218 } while (/*CONSTCOND*/0)
    219 
    220 #define MATCH_FAMILY(x, y, w) \
    221 	((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC || (y) == PF_UNSPEC)))
    222 #define MATCH(x, y, w) \
    223 	((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY)))
    224 
    225 char *
    226 gai_strerror(ecode)
    227 	int ecode;
    228 {
    229 	if (ecode < 0 || ecode > EAI_MAX)
    230 		ecode = EAI_MAX;
    231 	return ai_errlist[ecode];
    232 }
    233 
    234 void
    235 freeaddrinfo(ai)
    236 	struct addrinfo *ai;
    237 {
    238 	struct addrinfo *next;
    239 
    240 	do {
    241 		next = ai->ai_next;
    242 		if (ai->ai_canonname)
    243 			free(ai->ai_canonname);
    244 		/* no need to free(ai->ai_addr) */
    245 		free(ai);
    246 	} while ((ai = next) != NULL);
    247 }
    248 
    249 static int
    250 str_isnumber(p)
    251 	const char *p;
    252 {
    253 	const char *q = (const char *)p;
    254 	while (*q) {
    255 		if (!isdigit(*q))
    256 			return NO;
    257 		q++;
    258 	}
    259 	return YES;
    260 }
    261 
    262 int
    263 getaddrinfo(hostname, servname, hints, res)
    264 	const char *hostname, *servname;
    265 	const struct addrinfo *hints;
    266 	struct addrinfo **res;
    267 {
    268 	struct addrinfo sentinel;
    269 	struct addrinfo *cur;
    270 	int error = 0;
    271 	struct addrinfo ai;
    272 	struct addrinfo ai0;
    273 	struct addrinfo *pai;
    274 	const struct afd *afd;
    275 	const struct explore *ex;
    276 
    277 #ifdef FAITH
    278 	static int firsttime = 1;
    279 
    280 	if (firsttime) {
    281 		/* translator hack */
    282 		char *q = getenv("GAI");
    283 		if (q && inet_pton(AF_INET6, q, &faith_prefix) == 1)
    284 			translate = YES;
    285 		firsttime = 0;
    286 	}
    287 #endif
    288 
    289 	sentinel.ai_next = NULL;
    290 	cur = &sentinel;
    291 	pai = &ai;
    292 	pai->ai_flags = 0;
    293 	pai->ai_family = PF_UNSPEC;
    294 	pai->ai_socktype = ANY;
    295 	pai->ai_protocol = ANY;
    296 	pai->ai_addrlen = 0;
    297 	pai->ai_canonname = NULL;
    298 	pai->ai_addr = NULL;
    299 	pai->ai_next = NULL;
    300 
    301 	if (hostname == NULL && servname == NULL)
    302 		return EAI_NONAME;
    303 	if (hints) {
    304 		/* error check for hints */
    305 		if (hints->ai_addrlen || hints->ai_canonname ||
    306 		    hints->ai_addr || hints->ai_next)
    307 			ERR(EAI_BADHINTS); /* xxx */
    308 		if (hints->ai_flags & ~AI_MASK)
    309 			ERR(EAI_BADFLAGS);
    310 		switch (hints->ai_family) {
    311 		case PF_UNSPEC:
    312 		case PF_INET:
    313 #ifdef INET6
    314 		case PF_INET6:
    315 #endif
    316 			break;
    317 		default:
    318 			ERR(EAI_FAMILY);
    319 		}
    320 		memcpy(pai, hints, sizeof(*pai));
    321 
    322 		/*
    323 		 * if both socktype/protocol are specified, check if they
    324 		 * are meaningful combination.
    325 		 */
    326 		if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
    327 			for (ex = explore; ex->e_af >= 0; ex++) {
    328 				if (pai->ai_family != ex->e_af)
    329 					continue;
    330 				if (ex->e_socktype == ANY)
    331 					continue;
    332 				if (ex->e_protocol == ANY)
    333 					continue;
    334 				if (pai->ai_socktype == ex->e_socktype
    335 				 && pai->ai_protocol != ex->e_protocol) {
    336 					ERR(EAI_BADHINTS);
    337 				}
    338 			}
    339 		}
    340 	}
    341 
    342 	/*
    343 	 * check for special cases.  (1) numeric servname is disallowed if
    344 	 * socktype/protocol are left unspecified. (2) servname is disallowed
    345 	 * for raw and other inet{,6} sockets.
    346 	 */
    347 	if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
    348 	 || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)) {
    349 		ai0 = *pai;
    350 
    351 		if (pai->ai_family == PF_UNSPEC)
    352 			pai->ai_family = PF_INET6;
    353 		error = get_portmatch(pai, servname);
    354 		if (error)
    355 			ERR(error);
    356 
    357 		*pai = ai0;
    358 	}
    359 
    360 	ai0 = *pai;
    361 
    362 	/* NULL hostname, or numeric hostname */
    363 	for (ex = explore; ex->e_af >= 0; ex++) {
    364 		*pai = ai0;
    365 
    366 		if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
    367 			continue;
    368 		if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex)))
    369 			continue;
    370 		if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex)))
    371 			continue;
    372 
    373 		if (pai->ai_family == PF_UNSPEC)
    374 			pai->ai_family = ex->e_af;
    375 		if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
    376 			pai->ai_socktype = ex->e_socktype;
    377 		if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
    378 			pai->ai_protocol = ex->e_protocol;
    379 
    380 		if (hostname == NULL)
    381 			error = explore_null(pai, servname, &cur->ai_next);
    382 		else
    383 			error = explore_numeric_scope(pai, hostname, servname, &cur->ai_next);
    384 
    385 		if (error)
    386 			goto free;
    387 
    388 		while (cur && cur->ai_next)
    389 			cur = cur->ai_next;
    390 	}
    391 
    392 	/*
    393 	 * XXX
    394 	 * If numreic representation of AF1 can be interpreted as FQDN
    395 	 * representation of AF2, we need to think again about the code below.
    396 	 */
    397 	if (sentinel.ai_next)
    398 		goto good;
    399 
    400 	if (pai->ai_flags & AI_NUMERICHOST)
    401 		ERR(EAI_NONAME);
    402 	if (hostname == NULL)
    403 		ERR(EAI_NONAME);
    404 
    405 	/*
    406 	 * hostname as alphabetical name.
    407 	 * we would like to prefer AF_INET6 than AF_INET, so we'll make a
    408 	 * outer loop by AFs.
    409 	 */
    410 	for (afd = afdl; afd->a_af; afd++) {
    411 		*pai = ai0;
    412 
    413 		if (!MATCH_FAMILY(pai->ai_family, afd->a_af, 1))
    414 			continue;
    415 
    416 		for (ex = explore; ex->e_af >= 0; ex++) {
    417 			*pai = ai0;
    418 
    419 			if (pai->ai_family == PF_UNSPEC)
    420 				pai->ai_family = afd->a_af;
    421 
    422 			if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
    423 				continue;
    424 			if (!MATCH(pai->ai_socktype, ex->e_socktype,
    425 					WILD_SOCKTYPE(ex))) {
    426 				continue;
    427 			}
    428 			if (!MATCH(pai->ai_protocol, ex->e_protocol,
    429 					WILD_PROTOCOL(ex))) {
    430 				continue;
    431 			}
    432 
    433 			if (pai->ai_family == PF_UNSPEC)
    434 				pai->ai_family = ex->e_af;
    435 			if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
    436 				pai->ai_socktype = ex->e_socktype;
    437 			if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
    438 				pai->ai_protocol = ex->e_protocol;
    439 
    440 			error = explore_fqdn(pai, hostname, servname,
    441 				&cur->ai_next);
    442 
    443 			while (cur && cur->ai_next)
    444 				cur = cur->ai_next;
    445 		}
    446 	}
    447 
    448 	/* XXX */
    449 	if (sentinel.ai_next)
    450 		error = 0;
    451 
    452 	if (error)
    453 		goto free;
    454 	if (error == 0) {
    455 		if (sentinel.ai_next) {
    456  good:
    457 			*res = sentinel.ai_next;
    458 			return SUCCESS;
    459 		} else
    460 			error = EAI_FAIL;
    461 	}
    462  free:
    463  bad:
    464 	if (sentinel.ai_next)
    465 		freeaddrinfo(sentinel.ai_next);
    466 	*res = NULL;
    467 	return error;
    468 }
    469 
    470 /*
    471  * FQDN hostname, DNS lookup
    472  */
    473 static int
    474 explore_fqdn(pai, hostname, servname, res)
    475 	const struct addrinfo *pai;
    476 	const char *hostname;
    477 	const char *servname;
    478 	struct addrinfo **res;
    479 {
    480 #if 0
    481 	int s;
    482 #endif
    483 	struct hostent *hp;
    484 	int h_error;
    485 	int af;
    486 	char **aplist = NULL, *apbuf = NULL;
    487 	char *ap;
    488 	struct addrinfo sentinel, *cur;
    489 	int i;
    490 #ifndef USE_GETIPNODEBY
    491 	int naddrs;
    492 #endif
    493 	const struct afd *afd;
    494 	int error;
    495 
    496 	*res = NULL;
    497 	sentinel.ai_next = NULL;
    498 	cur = &sentinel;
    499 
    500 #if 0
    501 	/*
    502 	 * filter out AFs that are not supported by the kernel
    503 	 * XXX errno?
    504 	 */
    505 	s = socket(pai->ai_family, SOCK_DGRAM, 0);
    506 	if (s < 0) {
    507 		if (errno != EMFILE)
    508 			return 0;
    509 	} else
    510 		close(s);
    511 #endif
    512 
    513 	/*
    514 	 * if the servname does not match socktype/protocol, ignore it.
    515 	 */
    516 	if (get_portmatch(pai, servname) != 0)
    517 		return 0;
    518 
    519 	afd = find_afd(pai->ai_family);
    520 
    521 	/*
    522 	 * post-RFC2553: should look at (pai->ai_flags & AI_ADDRCONFIG)
    523 	 * rather than hardcoding it.  we may need to add AI_ADDRCONFIG
    524 	 * handling code by ourselves in case we don't have getipnodebyname().
    525 	 */
    526 #ifdef USE_GETIPNODEBY
    527 	hp = getipnodebyname(hostname, pai->ai_family, AI_ADDRCONFIG, &h_error);
    528 #else
    529 	hp = gethostbyname2(hostname, pai->ai_family);
    530 	h_error = h_errno;
    531 #endif
    532 
    533 	if (hp == NULL) {
    534 		switch (h_error) {
    535 		case HOST_NOT_FOUND:
    536 		case NO_DATA:
    537 			error = EAI_NODATA;
    538 			break;
    539 		case TRY_AGAIN:
    540 			error = EAI_AGAIN;
    541 			break;
    542 		case NO_RECOVERY:
    543 		case NETDB_INTERNAL:
    544 		default:
    545 			error = EAI_FAIL;
    546 			break;
    547 		}
    548 	} else if ((hp->h_name == NULL) || (hp->h_name[0] == 0)
    549 			|| (hp->h_addr_list[0] == NULL)) {
    550 #ifdef USE_GETIPNODEBY
    551 		freehostent(hp);
    552 #endif
    553 		hp = NULL;
    554 		error = EAI_FAIL;
    555 	}
    556 
    557 	if (hp == NULL)
    558 		goto free;
    559 
    560 #ifdef USE_GETIPNODEBY
    561 	aplist = hp->h_addr_list;
    562 #else
    563 	/*
    564 	 * hp will be overwritten if we use gethostbyname2().
    565 	 * always deep copy for simplification.
    566 	 */
    567 	for (naddrs = 0; hp->h_addr_list[naddrs] != NULL; naddrs++)
    568 		;
    569 	naddrs++;
    570 	aplist = (char **)malloc(sizeof(aplist[0]) * naddrs);
    571 	apbuf = (char *)malloc((size_t)hp->h_length * naddrs);
    572 	if (aplist == NULL || apbuf == NULL) {
    573 		error = EAI_MEMORY;
    574 		goto free;
    575 	}
    576 	memset(aplist, 0, sizeof(aplist[0]) * naddrs);
    577 	for (i = 0; i < naddrs; i++) {
    578 		if (hp->h_addr_list[i] == NULL) {
    579 			aplist[i] = NULL;
    580 			continue;
    581 		}
    582 		memcpy(&apbuf[i * hp->h_length], hp->h_addr_list[i],
    583 			(size_t)hp->h_length);
    584 		aplist[i] = &apbuf[i * hp->h_length];
    585 	}
    586 #endif
    587 
    588 	for (i = 0; aplist[i] != NULL; i++) {
    589 		af = hp->h_addrtype;
    590 		ap = aplist[i];
    591 		if (af == AF_INET6
    592 		 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)ap)) {
    593 			af = AF_INET;
    594 			ap = ap + sizeof(struct in6_addr)
    595 				- sizeof(struct in_addr);
    596 		}
    597 
    598 		if (af != pai->ai_family)
    599 			continue;
    600 
    601 		if ((pai->ai_flags & AI_CANONNAME) == 0) {
    602 			GET_AI(cur->ai_next, afd, ap);
    603 			GET_PORT(cur->ai_next, servname);
    604 		} else {
    605 			/*
    606 			 * if AI_CANONNAME and if reverse lookup
    607 			 * fail, return ai anyway to pacify
    608 			 * calling application.
    609 			 *
    610 			 * XXX getaddrinfo() is a name->address
    611 			 * translation function, and it looks
    612 			 * strange that we do addr->name
    613 			 * translation here.
    614 			 */
    615 			get_name(ap, afd, &cur->ai_next,
    616 				ap, pai, servname);
    617 		}
    618 
    619 		while (cur && cur->ai_next)
    620 			cur = cur->ai_next;
    621 	}
    622 
    623 	*res = sentinel.ai_next;
    624 	return 0;
    625 
    626 free:
    627 #ifdef USE_GETIPNODEBY
    628 	if (hp)
    629 		freehostent(hp);
    630 #endif
    631 	if (aplist)
    632 		free(aplist);
    633 	if (apbuf)
    634 		free(apbuf);
    635 	if (sentinel.ai_next)
    636 		freeaddrinfo(sentinel.ai_next);
    637 	return error;
    638 }
    639 
    640 /*
    641  * hostname == NULL.
    642  * passive socket -> anyaddr (0.0.0.0 or ::)
    643  * non-passive socket -> localhost (127.0.0.1 or ::1)
    644  */
    645 static int
    646 explore_null(pai, servname, res)
    647 	const struct addrinfo *pai;
    648 	const char *servname;
    649 	struct addrinfo **res;
    650 {
    651 	int s;
    652 	const struct afd *afd;
    653 	struct addrinfo *cur;
    654 	struct addrinfo sentinel;
    655 	int error;
    656 
    657 	*res = NULL;
    658 	sentinel.ai_next = NULL;
    659 	cur = &sentinel;
    660 
    661 	/*
    662 	 * filter out AFs that are not supported by the kernel
    663 	 * XXX errno?
    664 	 */
    665 	s = socket(pai->ai_family, SOCK_DGRAM, 0);
    666 	if (s < 0) {
    667 		if (errno != EMFILE)
    668 			return 0;
    669 	} else
    670 		close(s);
    671 
    672 	/*
    673 	 * if the servname does not match socktype/protocol, ignore it.
    674 	 */
    675 	if (get_portmatch(pai, servname) != 0)
    676 		return 0;
    677 
    678 	afd = find_afd(pai->ai_family);
    679 
    680 	if (pai->ai_flags & AI_PASSIVE) {
    681 		GET_AI(cur->ai_next, afd, afd->a_addrany);
    682 		/* xxx meaningless?
    683 		 * GET_CANONNAME(cur->ai_next, "anyaddr");
    684 		 */
    685 		GET_PORT(cur->ai_next, servname);
    686 	} else {
    687 		GET_AI(cur->ai_next, afd, afd->a_loopback);
    688 		/* xxx meaningless?
    689 		 * GET_CANONNAME(cur->ai_next, "localhost");
    690 		 */
    691 		GET_PORT(cur->ai_next, servname);
    692 	}
    693 	cur = cur->ai_next;
    694 
    695 	*res = sentinel.ai_next;
    696 	return 0;
    697 
    698 free:
    699 	if (sentinel.ai_next)
    700 		freeaddrinfo(sentinel.ai_next);
    701 	return error;
    702 }
    703 
    704 /*
    705  * numeric hostname
    706  */
    707 static int
    708 explore_numeric(pai, hostname, servname, res)
    709 	const struct addrinfo *pai;
    710 	const char *hostname;
    711 	const char *servname;
    712 	struct addrinfo **res;
    713 {
    714 	const struct afd *afd;
    715 	struct addrinfo *cur;
    716 	struct addrinfo sentinel;
    717 	int error;
    718 	char pton[PTON_MAX];
    719 	int flags;
    720 
    721 	*res = NULL;
    722 	sentinel.ai_next = NULL;
    723 	cur = &sentinel;
    724 
    725 	/*
    726 	 * if the servname does not match socktype/protocol, ignore it.
    727 	 */
    728 	if (get_portmatch(pai, servname) != 0)
    729 		return 0;
    730 
    731 	afd = find_afd(pai->ai_family);
    732 	flags = pai->ai_flags;
    733 
    734 	if (inet_pton(afd->a_af, hostname, pton) == 1) {
    735 		u_int32_t v4a;
    736 #ifdef INET6
    737 		u_char pfx;
    738 #endif
    739 
    740 		switch (afd->a_af) {
    741 		case AF_INET:
    742 			v4a = (u_int32_t)ntohl(((struct in_addr *)pton)->s_addr);
    743 			if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a))
    744 				flags &= ~AI_CANONNAME;
    745 			v4a >>= IN_CLASSA_NSHIFT;
    746 			if (v4a == 0 || v4a == IN_LOOPBACKNET)
    747 				flags &= ~AI_CANONNAME;
    748 			break;
    749 #ifdef INET6
    750 		case AF_INET6:
    751 			pfx = ((struct in6_addr *)pton)->s6_addr[0];
    752 			if (pfx == 0 || pfx == 0xfe || pfx == 0xff)
    753 				flags &= ~AI_CANONNAME;
    754 			break;
    755 #endif
    756 		}
    757 
    758 		if (pai->ai_family == afd->a_af ||
    759 		    pai->ai_family == PF_UNSPEC /*?*/) {
    760 			if ((flags & AI_CANONNAME) == 0) {
    761 				GET_AI(cur->ai_next, afd, pton);
    762 				GET_PORT(cur->ai_next, servname);
    763 			} else {
    764 				/*
    765 				 * if AI_CANONNAME and if reverse lookup
    766 				 * fail, return ai anyway to pacify
    767 				 * calling application.
    768 				 *
    769 				 * XXX getaddrinfo() is a name->address
    770 				 * translation function, and it looks
    771 				 * strange that we do addr->name
    772 				 * translation here.
    773 				 */
    774 				get_name(pton, afd, &cur->ai_next,
    775 					pton, pai, servname);
    776 			}
    777 			while (cur && cur->ai_next)
    778 				cur = cur->ai_next;
    779 		} else
    780 			ERR(EAI_FAMILY);	/*xxx*/
    781 	}
    782 
    783 	*res = sentinel.ai_next;
    784 	return 0;
    785 
    786 free:
    787 bad:
    788 	if (sentinel.ai_next)
    789 		freeaddrinfo(sentinel.ai_next);
    790 	return error;
    791 }
    792 
    793 /*
    794  * numeric hostname with scope
    795  */
    796 static int
    797 explore_numeric_scope(pai, hostname, servname, res)
    798 	const struct addrinfo *pai;
    799 	const char *hostname;
    800 	const char *servname;
    801 	struct addrinfo **res;
    802 {
    803 #ifndef SCOPE_DELIMITER
    804 	return explore_numeric(pai, hostname, servname, res);
    805 #else
    806 	const struct afd *afd;
    807 	struct addrinfo *cur;
    808 	int error;
    809 	char *cp, *hostname2 = NULL;
    810 	int scope;
    811 	struct sockaddr_in6 *sin6;
    812 
    813 	/*
    814 	 * if the servname does not match socktype/protocol, ignore it.
    815 	 */
    816 	if (get_portmatch(pai, servname) != 0)
    817 		return 0;
    818 
    819 	afd = find_afd(pai->ai_family);
    820 	if (!afd->a_scoped)
    821 		return explore_numeric(pai, hostname, servname, res);
    822 
    823 	cp = strchr(hostname, SCOPE_DELIMITER);
    824 	if (cp == NULL)
    825 		return explore_numeric(pai, hostname, servname, res);
    826 
    827 	/*
    828 	 * Handle special case of <scoped_address><delimiter><scope id>
    829 	 */
    830 	hostname2 = strdup(hostname);
    831 	if (hostname2 == NULL)
    832 		return EAI_MEMORY;
    833 	/* terminate at the delimiter */
    834 	hostname2[cp - hostname] = '\0';
    835 
    836 	cp++;
    837 	switch (pai->ai_family) {
    838 #ifdef INET6
    839 	case AF_INET6:
    840 		scope = if_nametoindex(cp);
    841 		if (scope == 0) {
    842 			free(hostname2);
    843 			return (EAI_NONAME);
    844 		}
    845 		break;
    846 #endif
    847 	}
    848 
    849 	error = explore_numeric(pai, hostname2, servname, res);
    850 	if (error == 0) {
    851 		for (cur = *res; cur; cur = cur->ai_next) {
    852 			if (cur->ai_family != AF_INET6)
    853 				continue;
    854 			sin6 = (struct sockaddr_in6 *)cur->ai_addr;
    855 			if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr) ||
    856 			    IN6_IS_ADDR_MC_LINKLOCAL(&sin6->sin6_addr))
    857 				sin6->sin6_scope_id = scope;
    858 		}
    859 	}
    860 
    861 	free(hostname2);
    862 
    863 	return error;
    864 #endif
    865 }
    866 
    867 static int
    868 get_name(addr, afd, res, numaddr, pai, servname)
    869 	const char *addr;
    870 	const struct afd *afd;
    871 	struct addrinfo **res;
    872 	char *numaddr;
    873 	const struct addrinfo *pai;
    874 	const char *servname;
    875 {
    876 	struct hostent *hp = NULL;
    877 	struct addrinfo *cur = NULL;
    878 	int error = 0;
    879 	char *ap = NULL, *cn = NULL;
    880 #ifdef USE_GETIPNODEBY
    881 	int h_error;
    882 
    883 	hp = getipnodebyaddr(addr, afd->a_addrlen, afd->a_af, &h_error);
    884 #else
    885 	hp = gethostbyaddr(addr, afd->a_addrlen, afd->a_af);
    886 #endif
    887 	if (hp && hp->h_name && hp->h_name[0] && hp->h_addr_list[0]) {
    888 #ifdef USE_GETIPNODEBY
    889 		GET_AI(cur, afd, hp->h_addr_list[0]);
    890 		GET_PORT(cur, servname);
    891 		GET_CANONNAME(cur, hp->h_name);
    892 #else
    893 		/* hp will be damaged if we use gethostbyaddr() */
    894 		if ((ap = (char *)malloc((size_t)hp->h_length)) == NULL) {
    895 			error = EAI_MEMORY;
    896 			goto free;
    897 		}
    898 		memcpy(ap, hp->h_addr_list[0], (size_t)hp->h_length);
    899 		if ((cn = strdup(hp->h_name)) == NULL) {
    900 			error = EAI_MEMORY;
    901 			goto free;
    902 		}
    903 
    904 		GET_AI(cur, afd, ap);
    905 		GET_PORT(cur, servname);
    906 		GET_CANONNAME(cur, cn);
    907 		free(ap); ap = NULL;
    908 		free(cn); cn = NULL;
    909 #endif
    910 	} else {
    911 		GET_AI(cur, afd, numaddr);
    912 		GET_PORT(cur, servname);
    913 	}
    914 
    915 #ifdef USE_GETIPNODEBY
    916 	if (hp)
    917 		freehostent(hp);
    918 #endif
    919 	*res = cur;
    920 	return SUCCESS;
    921  free:
    922 	if (cur)
    923 		freeaddrinfo(cur);
    924 	if (ap)
    925 		free(ap);
    926 	if (cn)
    927 		free(cn);
    928 #ifdef USE_GETIPNODEBY
    929 	if (hp)
    930 		freehostent(hp);
    931 #endif
    932 	*res = NULL;
    933 	return error;
    934 }
    935 
    936 static int
    937 get_canonname(pai, ai, str)
    938 	const struct addrinfo *pai;
    939 	struct addrinfo *ai;
    940 	const char *str;
    941 {
    942 	if ((pai->ai_flags & AI_CANONNAME) != 0) {
    943 		ai->ai_canonname = (char *)malloc(strlen(str) + 1);
    944 		if (ai->ai_canonname == NULL)
    945 			return EAI_MEMORY;
    946 		strcpy(ai->ai_canonname, str);
    947 	}
    948 	return 0;
    949 }
    950 
    951 static struct addrinfo *
    952 get_ai(pai, afd, addr)
    953 	const struct addrinfo *pai;
    954 	const struct afd *afd;
    955 	const char *addr;
    956 {
    957 	char *p;
    958 	struct addrinfo *ai;
    959 
    960 	ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
    961 		+ (afd->a_socklen));
    962 	if (ai == NULL)
    963 		return NULL;
    964 
    965 	memcpy(ai, pai, sizeof(struct addrinfo));
    966 	ai->ai_addr = (struct sockaddr *)(ai + 1);
    967 	memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
    968 	ai->ai_addr->sa_len = afd->a_socklen;
    969 	ai->ai_addrlen = afd->a_socklen;
    970 	ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
    971 	p = (char *)(ai->ai_addr);
    972 	memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
    973 	return ai;
    974 }
    975 
    976 static int
    977 get_portmatch(ai, servname)
    978 	const struct addrinfo *ai;
    979 	const char *servname;
    980 {
    981 
    982 	/* get_port does not touch first argument. when matchonly == 1. */
    983 	return get_port((struct addrinfo *)ai, servname, 1);
    984 }
    985 
    986 static int
    987 get_port(ai, servname, matchonly)
    988 	struct addrinfo *ai;
    989 	const char *servname;
    990 	int matchonly;
    991 {
    992 	const char *proto;
    993 	struct servent *sp;
    994 	int port;
    995 	int allownumeric;
    996 
    997 	if (servname == NULL)
    998 		return 0;
    999 	if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
   1000 		return 0;
   1001 
   1002 	switch (ai->ai_socktype) {
   1003 	case SOCK_RAW:
   1004 		return EAI_SERVICE;
   1005 	case SOCK_DGRAM:
   1006 	case SOCK_STREAM:
   1007 		allownumeric = 1;
   1008 		break;
   1009 	case ANY:
   1010 		allownumeric = 0;
   1011 		break;
   1012 	default:
   1013 		return EAI_SOCKTYPE;
   1014 	}
   1015 
   1016 	if (str_isnumber(servname)) {
   1017 		if (!allownumeric)
   1018 			return EAI_SERVICE;
   1019 		port = htons(atoi(servname));
   1020 		if (port < 0 || port > 65535)
   1021 			return EAI_SERVICE;
   1022 	} else {
   1023 		switch (ai->ai_socktype) {
   1024 		case SOCK_DGRAM:
   1025 			proto = "udp";
   1026 			break;
   1027 		case SOCK_STREAM:
   1028 			proto = "tcp";
   1029 			break;
   1030 		default:
   1031 			proto = NULL;
   1032 			break;
   1033 		}
   1034 
   1035 		if ((sp = getservbyname(servname, proto)) == NULL)
   1036 			return EAI_SERVICE;
   1037 		port = sp->s_port;
   1038 	}
   1039 
   1040 	if (!matchonly) {
   1041 		switch (ai->ai_family) {
   1042 		case AF_INET:
   1043 			((struct sockaddr_in *)ai->ai_addr)->sin_port = port;
   1044 			break;
   1045 #ifdef INET6
   1046 		case AF_INET6:
   1047 			((struct sockaddr_in6 *)ai->ai_addr)->sin6_port = port;
   1048 			break;
   1049 #endif
   1050 		}
   1051 	}
   1052 
   1053 	return 0;
   1054 }
   1055 
   1056 static const struct afd *
   1057 find_afd(af)
   1058 	int af;
   1059 {
   1060 	const struct afd *afd;
   1061 
   1062 	if (af == PF_UNSPEC)
   1063 		return NULL;
   1064 	for (afd = afdl; afd->a_af; afd++) {
   1065 		if (afd->a_af == af)
   1066 			return afd;
   1067 	}
   1068 	return NULL;
   1069 }
   1070