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