Home | History | Annotate | Line # | Download | only in net
getaddrinfo.c revision 1.22
      1 /*	$NetBSD: getaddrinfo.c,v 1.22 2000/01/23 04:03:21 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  * "#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 globbing NULL hostname (to loopback, or wildcard).  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 		/* call to get_portmatch() can conterminate *pai */
    350 		ai0 = *pai;
    351 
    352 		if (pai->ai_family == PF_UNSPEC)
    353 			pai->ai_family = PF_INET6;
    354 		error = get_portmatch(pai, servname);
    355 		if (error)
    356 			ERR(error);
    357 
    358 		*pai = ai0;
    359 	}
    360 
    361 	ai0 = *pai;
    362 
    363 	/* NULL hostname, or numeric hostname */
    364 	for (ex = explore; ex->e_af >= 0; ex++) {
    365 		*pai = ai0;
    366 
    367 		if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
    368 			continue;
    369 		if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex)))
    370 			continue;
    371 		if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex)))
    372 			continue;
    373 
    374 		if (pai->ai_family == PF_UNSPEC)
    375 			pai->ai_family = ex->e_af;
    376 		if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
    377 			pai->ai_socktype = ex->e_socktype;
    378 		if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
    379 			pai->ai_protocol = ex->e_protocol;
    380 
    381 		if (hostname == NULL)
    382 			error = explore_null(pai, servname, &cur->ai_next);
    383 		else
    384 			error = explore_numeric_scope(pai, hostname, servname, &cur->ai_next);
    385 
    386 		if (error)
    387 			goto free;
    388 
    389 		while (cur && cur->ai_next)
    390 			cur = cur->ai_next;
    391 	}
    392 
    393 	/*
    394 	 * XXX
    395 	 * If numreic representation of AF1 can be interpreted as FQDN
    396 	 * representation of AF2, we need to think again about the code below.
    397 	 */
    398 	if (sentinel.ai_next)
    399 		goto good;
    400 
    401 	if (pai->ai_flags & AI_NUMERICHOST)
    402 		ERR(EAI_NONAME);
    403 	if (hostname == NULL)
    404 		ERR(EAI_NONAME);
    405 
    406 	/*
    407 	 * hostname as alphabetical name.
    408 	 * we would like to prefer AF_INET6 than AF_INET, so we'll make a
    409 	 * outer loop by AFs.
    410 	 */
    411 	for (afd = afdl; afd->a_af; afd++) {
    412 		*pai = ai0;
    413 
    414 		if (!MATCH_FAMILY(pai->ai_family, afd->a_af, 1))
    415 			continue;
    416 
    417 		for (ex = explore; ex->e_af >= 0; ex++) {
    418 			*pai = ai0;
    419 
    420 			if (pai->ai_family == PF_UNSPEC)
    421 				pai->ai_family = afd->a_af;
    422 
    423 			if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
    424 				continue;
    425 			if (!MATCH(pai->ai_socktype, ex->e_socktype,
    426 					WILD_SOCKTYPE(ex))) {
    427 				continue;
    428 			}
    429 			if (!MATCH(pai->ai_protocol, ex->e_protocol,
    430 					WILD_PROTOCOL(ex))) {
    431 				continue;
    432 			}
    433 
    434 			if (pai->ai_family == PF_UNSPEC)
    435 				pai->ai_family = ex->e_af;
    436 			if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
    437 				pai->ai_socktype = ex->e_socktype;
    438 			if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
    439 				pai->ai_protocol = ex->e_protocol;
    440 
    441 			error = explore_fqdn(pai, hostname, servname,
    442 				&cur->ai_next);
    443 
    444 			while (cur && cur->ai_next)
    445 				cur = cur->ai_next;
    446 		}
    447 	}
    448 
    449 	/* XXX */
    450 	if (sentinel.ai_next)
    451 		error = 0;
    452 
    453 	if (error)
    454 		goto free;
    455 	if (error == 0) {
    456 		if (sentinel.ai_next) {
    457  good:
    458 			*res = sentinel.ai_next;
    459 			return SUCCESS;
    460 		} else
    461 			error = EAI_FAIL;
    462 	}
    463  free:
    464  bad:
    465 	if (sentinel.ai_next)
    466 		freeaddrinfo(sentinel.ai_next);
    467 	*res = NULL;
    468 	return error;
    469 }
    470 
    471 /*
    472  * FQDN hostname, DNS lookup
    473  */
    474 static int
    475 explore_fqdn(pai, hostname, servname, res)
    476 	const struct addrinfo *pai;
    477 	const char *hostname;
    478 	const char *servname;
    479 	struct addrinfo **res;
    480 {
    481 	struct hostent *hp;
    482 	int h_error;
    483 	int af;
    484 	char **aplist = NULL, *apbuf = NULL;
    485 	char *ap;
    486 	struct addrinfo sentinel, *cur;
    487 	int i;
    488 #ifndef USE_GETIPNODEBY
    489 	int naddrs;
    490 #endif
    491 	const struct afd *afd;
    492 	int error;
    493 
    494 	*res = NULL;
    495 	sentinel.ai_next = NULL;
    496 	cur = &sentinel;
    497 
    498 	/*
    499 	 * Do not filter unsupported AFs here.  We need to honor content of
    500 	 * databases (/etc/hosts, DNS and others).  Otherwise we cannot
    501 	 * replace gethostbyname() by getaddrinfo().
    502 	 */
    503 
    504 	/*
    505 	 * if the servname does not match socktype/protocol, ignore it.
    506 	 */
    507 	if (get_portmatch(pai, servname) != 0)
    508 		return 0;
    509 
    510 	afd = find_afd(pai->ai_family);
    511 
    512 	/*
    513 	 * post-RFC2553: should look at (pai->ai_flags & AI_ADDRCONFIG)
    514 	 * rather than hardcoding it.  we may need to add AI_ADDRCONFIG
    515 	 * handling code by ourselves in case we don't have getipnodebyname().
    516 	 */
    517 #ifdef USE_GETIPNODEBY
    518 	hp = getipnodebyname(hostname, pai->ai_family, AI_ADDRCONFIG, &h_error);
    519 #else
    520 	hp = gethostbyname2(hostname, pai->ai_family);
    521 	h_error = h_errno;
    522 #endif
    523 
    524 	if (hp == NULL) {
    525 		switch (h_error) {
    526 		case HOST_NOT_FOUND:
    527 		case NO_DATA:
    528 			error = EAI_NODATA;
    529 			break;
    530 		case TRY_AGAIN:
    531 			error = EAI_AGAIN;
    532 			break;
    533 		case NO_RECOVERY:
    534 		case NETDB_INTERNAL:
    535 		default:
    536 			error = EAI_FAIL;
    537 			break;
    538 		}
    539 	} else if ((hp->h_name == NULL) || (hp->h_name[0] == 0)
    540 			|| (hp->h_addr_list[0] == NULL)) {
    541 #ifdef USE_GETIPNODEBY
    542 		freehostent(hp);
    543 #endif
    544 		hp = NULL;
    545 		error = EAI_FAIL;
    546 	}
    547 
    548 	if (hp == NULL)
    549 		goto free;
    550 
    551 #ifdef USE_GETIPNODEBY
    552 	aplist = hp->h_addr_list;
    553 #else
    554 	/*
    555 	 * hp will be overwritten if we use gethostbyname2().
    556 	 * always deep copy for simplification.
    557 	 */
    558 	for (naddrs = 0; hp->h_addr_list[naddrs] != NULL; naddrs++)
    559 		;
    560 	naddrs++;
    561 	aplist = (char **)malloc(sizeof(aplist[0]) * naddrs);
    562 	apbuf = (char *)malloc((size_t)hp->h_length * naddrs);
    563 	if (aplist == NULL || apbuf == NULL) {
    564 		error = EAI_MEMORY;
    565 		goto free;
    566 	}
    567 	memset(aplist, 0, sizeof(aplist[0]) * naddrs);
    568 	for (i = 0; i < naddrs; i++) {
    569 		if (hp->h_addr_list[i] == NULL) {
    570 			aplist[i] = NULL;
    571 			continue;
    572 		}
    573 		memcpy(&apbuf[i * hp->h_length], hp->h_addr_list[i],
    574 			(size_t)hp->h_length);
    575 		aplist[i] = &apbuf[i * hp->h_length];
    576 	}
    577 #endif
    578 
    579 	for (i = 0; aplist[i] != NULL; i++) {
    580 		af = hp->h_addrtype;
    581 		ap = aplist[i];
    582 		if (af == AF_INET6
    583 		 && IN6_IS_ADDR_V4MAPPED((struct in6_addr *)ap)) {
    584 			af = AF_INET;
    585 			ap = ap + sizeof(struct in6_addr)
    586 				- sizeof(struct in_addr);
    587 		}
    588 
    589 		if (af != pai->ai_family)
    590 			continue;
    591 
    592 		if ((pai->ai_flags & AI_CANONNAME) == 0) {
    593 			GET_AI(cur->ai_next, afd, ap);
    594 			GET_PORT(cur->ai_next, servname);
    595 		} else {
    596 			/*
    597 			 * if AI_CANONNAME and if reverse lookup
    598 			 * fail, return ai anyway to pacify
    599 			 * calling application.
    600 			 *
    601 			 * XXX getaddrinfo() is a name->address
    602 			 * translation function, and it looks
    603 			 * strange that we do addr->name
    604 			 * translation here.
    605 			 */
    606 			get_name(ap, afd, &cur->ai_next,
    607 				ap, pai, servname);
    608 		}
    609 
    610 		while (cur && cur->ai_next)
    611 			cur = cur->ai_next;
    612 	}
    613 
    614 	*res = sentinel.ai_next;
    615 	return 0;
    616 
    617 free:
    618 #ifdef USE_GETIPNODEBY
    619 	if (hp)
    620 		freehostent(hp);
    621 #endif
    622 	if (aplist)
    623 		free(aplist);
    624 	if (apbuf)
    625 		free(apbuf);
    626 	if (sentinel.ai_next)
    627 		freeaddrinfo(sentinel.ai_next);
    628 	return error;
    629 }
    630 
    631 /*
    632  * hostname == NULL.
    633  * passive socket -> anyaddr (0.0.0.0 or ::)
    634  * non-passive socket -> localhost (127.0.0.1 or ::1)
    635  */
    636 static int
    637 explore_null(pai, servname, res)
    638 	const struct addrinfo *pai;
    639 	const char *servname;
    640 	struct addrinfo **res;
    641 {
    642 	int s;
    643 	const struct afd *afd;
    644 	struct addrinfo *cur;
    645 	struct addrinfo sentinel;
    646 	int error;
    647 
    648 	*res = NULL;
    649 	sentinel.ai_next = NULL;
    650 	cur = &sentinel;
    651 
    652 	/*
    653 	 * filter out AFs that are not supported by the kernel
    654 	 * XXX errno?
    655 	 */
    656 	s = socket(pai->ai_family, SOCK_DGRAM, 0);
    657 	if (s < 0) {
    658 		if (errno != EMFILE)
    659 			return 0;
    660 	} else
    661 		close(s);
    662 
    663 	/*
    664 	 * if the servname does not match socktype/protocol, ignore it.
    665 	 */
    666 	if (get_portmatch(pai, servname) != 0)
    667 		return 0;
    668 
    669 	afd = find_afd(pai->ai_family);
    670 
    671 	if (pai->ai_flags & AI_PASSIVE) {
    672 		GET_AI(cur->ai_next, afd, afd->a_addrany);
    673 		/* xxx meaningless?
    674 		 * GET_CANONNAME(cur->ai_next, "anyaddr");
    675 		 */
    676 		GET_PORT(cur->ai_next, servname);
    677 	} else {
    678 		GET_AI(cur->ai_next, afd, afd->a_loopback);
    679 		/* xxx meaningless?
    680 		 * GET_CANONNAME(cur->ai_next, "localhost");
    681 		 */
    682 		GET_PORT(cur->ai_next, servname);
    683 	}
    684 	cur = cur->ai_next;
    685 
    686 	*res = sentinel.ai_next;
    687 	return 0;
    688 
    689 free:
    690 	if (sentinel.ai_next)
    691 		freeaddrinfo(sentinel.ai_next);
    692 	return error;
    693 }
    694 
    695 /*
    696  * numeric hostname
    697  */
    698 static int
    699 explore_numeric(pai, hostname, servname, res)
    700 	const struct addrinfo *pai;
    701 	const char *hostname;
    702 	const char *servname;
    703 	struct addrinfo **res;
    704 {
    705 	const struct afd *afd;
    706 	struct addrinfo *cur;
    707 	struct addrinfo sentinel;
    708 	int error;
    709 	char pton[PTON_MAX];
    710 	int flags;
    711 
    712 	*res = NULL;
    713 	sentinel.ai_next = NULL;
    714 	cur = &sentinel;
    715 
    716 	/*
    717 	 * if the servname does not match socktype/protocol, ignore it.
    718 	 */
    719 	if (get_portmatch(pai, servname) != 0)
    720 		return 0;
    721 
    722 	afd = find_afd(pai->ai_family);
    723 	flags = pai->ai_flags;
    724 
    725 	if (inet_pton(afd->a_af, hostname, pton) == 1) {
    726 		u_int32_t v4a;
    727 #ifdef INET6
    728 		u_char pfx;
    729 #endif
    730 
    731 		switch (afd->a_af) {
    732 		case AF_INET:
    733 			v4a = (u_int32_t)ntohl(((struct in_addr *)pton)->s_addr);
    734 			if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a))
    735 				flags &= ~AI_CANONNAME;
    736 			v4a >>= IN_CLASSA_NSHIFT;
    737 			if (v4a == 0 || v4a == IN_LOOPBACKNET)
    738 				flags &= ~AI_CANONNAME;
    739 			break;
    740 #ifdef INET6
    741 		case AF_INET6:
    742 			pfx = ((struct in6_addr *)pton)->s6_addr[0];
    743 			if (pfx == 0 || pfx == 0xfe || pfx == 0xff)
    744 				flags &= ~AI_CANONNAME;
    745 			break;
    746 #endif
    747 		}
    748 
    749 		if (pai->ai_family == afd->a_af ||
    750 		    pai->ai_family == PF_UNSPEC /*?*/) {
    751 			if ((flags & AI_CANONNAME) == 0) {
    752 				GET_AI(cur->ai_next, afd, pton);
    753 				GET_PORT(cur->ai_next, servname);
    754 			} else {
    755 				/*
    756 				 * if AI_CANONNAME and if reverse lookup
    757 				 * fail, return ai anyway to pacify
    758 				 * calling application.
    759 				 *
    760 				 * XXX getaddrinfo() is a name->address
    761 				 * translation function, and it looks
    762 				 * strange that we do addr->name
    763 				 * translation here.
    764 				 */
    765 				get_name(pton, afd, &cur->ai_next,
    766 					pton, pai, servname);
    767 			}
    768 			while (cur && cur->ai_next)
    769 				cur = cur->ai_next;
    770 		} else
    771 			ERR(EAI_FAMILY);	/*xxx*/
    772 	}
    773 
    774 	*res = sentinel.ai_next;
    775 	return 0;
    776 
    777 free:
    778 bad:
    779 	if (sentinel.ai_next)
    780 		freeaddrinfo(sentinel.ai_next);
    781 	return error;
    782 }
    783 
    784 /*
    785  * numeric hostname with scope
    786  */
    787 static int
    788 explore_numeric_scope(pai, hostname, servname, res)
    789 	const struct addrinfo *pai;
    790 	const char *hostname;
    791 	const char *servname;
    792 	struct addrinfo **res;
    793 {
    794 #ifndef SCOPE_DELIMITER
    795 	return explore_numeric(pai, hostname, servname, res);
    796 #else
    797 	const struct afd *afd;
    798 	struct addrinfo *cur;
    799 	int error;
    800 	char *cp, *hostname2 = NULL;
    801 	int scope;
    802 	struct sockaddr_in6 *sin6;
    803 
    804 	/*
    805 	 * if the servname does not match socktype/protocol, ignore it.
    806 	 */
    807 	if (get_portmatch(pai, servname) != 0)
    808 		return 0;
    809 
    810 	afd = find_afd(pai->ai_family);
    811 	if (!afd->a_scoped)
    812 		return explore_numeric(pai, hostname, servname, res);
    813 
    814 	cp = strchr(hostname, SCOPE_DELIMITER);
    815 	if (cp == NULL)
    816 		return explore_numeric(pai, hostname, servname, res);
    817 
    818 	/*
    819 	 * Handle special case of <scoped_address><delimiter><scope id>
    820 	 */
    821 	hostname2 = strdup(hostname);
    822 	if (hostname2 == NULL)
    823 		return EAI_MEMORY;
    824 	/* terminate at the delimiter */
    825 	hostname2[cp - hostname] = '\0';
    826 
    827 	cp++;
    828 	switch (pai->ai_family) {
    829 #ifdef INET6
    830 	case AF_INET6:
    831 		scope = if_nametoindex(cp);
    832 		if (scope == 0) {
    833 			free(hostname2);
    834 			return (EAI_NONAME);
    835 		}
    836 		break;
    837 #endif
    838 	}
    839 
    840 	error = explore_numeric(pai, hostname2, servname, res);
    841 	if (error == 0) {
    842 		for (cur = *res; cur; cur = cur->ai_next) {
    843 			if (cur->ai_family != AF_INET6)
    844 				continue;
    845 			sin6 = (struct sockaddr_in6 *)cur->ai_addr;
    846 			if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr) ||
    847 			    IN6_IS_ADDR_MC_LINKLOCAL(&sin6->sin6_addr))
    848 				sin6->sin6_scope_id = scope;
    849 		}
    850 	}
    851 
    852 	free(hostname2);
    853 
    854 	return error;
    855 #endif
    856 }
    857 
    858 static int
    859 get_name(addr, afd, res, numaddr, pai, servname)
    860 	const char *addr;
    861 	const struct afd *afd;
    862 	struct addrinfo **res;
    863 	char *numaddr;
    864 	const struct addrinfo *pai;
    865 	const char *servname;
    866 {
    867 	struct hostent *hp = NULL;
    868 	struct addrinfo *cur = NULL;
    869 	int error = 0;
    870 	char *ap = NULL, *cn = NULL;
    871 #ifdef USE_GETIPNODEBY
    872 	int h_error;
    873 
    874 	hp = getipnodebyaddr(addr, afd->a_addrlen, afd->a_af, &h_error);
    875 #else
    876 	hp = gethostbyaddr(addr, afd->a_addrlen, afd->a_af);
    877 #endif
    878 	if (hp && hp->h_name && hp->h_name[0] && hp->h_addr_list[0]) {
    879 #ifdef USE_GETIPNODEBY
    880 		GET_AI(cur, afd, hp->h_addr_list[0]);
    881 		GET_PORT(cur, servname);
    882 		GET_CANONNAME(cur, hp->h_name);
    883 #else
    884 		/* hp will be damaged if we use gethostbyaddr() */
    885 		if ((ap = (char *)malloc((size_t)hp->h_length)) == NULL) {
    886 			error = EAI_MEMORY;
    887 			goto free;
    888 		}
    889 		memcpy(ap, hp->h_addr_list[0], (size_t)hp->h_length);
    890 		if ((cn = strdup(hp->h_name)) == NULL) {
    891 			error = EAI_MEMORY;
    892 			goto free;
    893 		}
    894 
    895 		GET_AI(cur, afd, ap);
    896 		GET_PORT(cur, servname);
    897 		GET_CANONNAME(cur, cn);
    898 		free(ap); ap = NULL;
    899 		free(cn); cn = NULL;
    900 #endif
    901 	} else {
    902 		GET_AI(cur, afd, numaddr);
    903 		GET_PORT(cur, servname);
    904 	}
    905 
    906 #ifdef USE_GETIPNODEBY
    907 	if (hp)
    908 		freehostent(hp);
    909 #endif
    910 	*res = cur;
    911 	return SUCCESS;
    912  free:
    913 	if (cur)
    914 		freeaddrinfo(cur);
    915 	if (ap)
    916 		free(ap);
    917 	if (cn)
    918 		free(cn);
    919 #ifdef USE_GETIPNODEBY
    920 	if (hp)
    921 		freehostent(hp);
    922 #endif
    923 	*res = NULL;
    924 	return error;
    925 }
    926 
    927 static int
    928 get_canonname(pai, ai, str)
    929 	const struct addrinfo *pai;
    930 	struct addrinfo *ai;
    931 	const char *str;
    932 {
    933 	if ((pai->ai_flags & AI_CANONNAME) != 0) {
    934 		ai->ai_canonname = (char *)malloc(strlen(str) + 1);
    935 		if (ai->ai_canonname == NULL)
    936 			return EAI_MEMORY;
    937 		strcpy(ai->ai_canonname, str);
    938 	}
    939 	return 0;
    940 }
    941 
    942 static struct addrinfo *
    943 get_ai(pai, afd, addr)
    944 	const struct addrinfo *pai;
    945 	const struct afd *afd;
    946 	const char *addr;
    947 {
    948 	char *p;
    949 	struct addrinfo *ai;
    950 
    951 	ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
    952 		+ (afd->a_socklen));
    953 	if (ai == NULL)
    954 		return NULL;
    955 
    956 	memcpy(ai, pai, sizeof(struct addrinfo));
    957 	ai->ai_addr = (struct sockaddr *)(ai + 1);
    958 	memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
    959 	ai->ai_addr->sa_len = afd->a_socklen;
    960 	ai->ai_addrlen = afd->a_socklen;
    961 	ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
    962 	p = (char *)(ai->ai_addr);
    963 	memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
    964 	return ai;
    965 }
    966 
    967 static int
    968 get_portmatch(ai, servname)
    969 	const struct addrinfo *ai;
    970 	const char *servname;
    971 {
    972 
    973 	/* get_port does not touch first argument. when matchonly == 1. */
    974 	return get_port((struct addrinfo *)ai, servname, 1);
    975 }
    976 
    977 static int
    978 get_port(ai, servname, matchonly)
    979 	struct addrinfo *ai;
    980 	const char *servname;
    981 	int matchonly;
    982 {
    983 	const char *proto;
    984 	struct servent *sp;
    985 	int port;
    986 	int allownumeric;
    987 
    988 	if (servname == NULL)
    989 		return 0;
    990 	if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
    991 		return 0;
    992 
    993 	switch (ai->ai_socktype) {
    994 	case SOCK_RAW:
    995 		return EAI_SERVICE;
    996 	case SOCK_DGRAM:
    997 	case SOCK_STREAM:
    998 		allownumeric = 1;
    999 		break;
   1000 	case ANY:
   1001 		allownumeric = 0;
   1002 		break;
   1003 	default:
   1004 		return EAI_SOCKTYPE;
   1005 	}
   1006 
   1007 	if (str_isnumber(servname)) {
   1008 		if (!allownumeric)
   1009 			return EAI_SERVICE;
   1010 		port = htons(atoi(servname));
   1011 		if (port < 0 || port > 65535)
   1012 			return EAI_SERVICE;
   1013 	} else {
   1014 		switch (ai->ai_socktype) {
   1015 		case SOCK_DGRAM:
   1016 			proto = "udp";
   1017 			break;
   1018 		case SOCK_STREAM:
   1019 			proto = "tcp";
   1020 			break;
   1021 		default:
   1022 			proto = NULL;
   1023 			break;
   1024 		}
   1025 
   1026 		if ((sp = getservbyname(servname, proto)) == NULL)
   1027 			return EAI_SERVICE;
   1028 		port = sp->s_port;
   1029 	}
   1030 
   1031 	if (!matchonly) {
   1032 		switch (ai->ai_family) {
   1033 		case AF_INET:
   1034 			((struct sockaddr_in *)ai->ai_addr)->sin_port = port;
   1035 			break;
   1036 #ifdef INET6
   1037 		case AF_INET6:
   1038 			((struct sockaddr_in6 *)ai->ai_addr)->sin6_port = port;
   1039 			break;
   1040 #endif
   1041 		}
   1042 	}
   1043 
   1044 	return 0;
   1045 }
   1046 
   1047 static const struct afd *
   1048 find_afd(af)
   1049 	int af;
   1050 {
   1051 	const struct afd *afd;
   1052 
   1053 	if (af == PF_UNSPEC)
   1054 		return NULL;
   1055 	for (afd = afdl; afd->a_af; afd++) {
   1056 		if (afd->a_af == af)
   1057 			return afd;
   1058 	}
   1059 	return NULL;
   1060 }
   1061