• 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 typedef union sockaddr_union {
104     struct sockaddr     generic;
105     struct sockaddr_in  in;
106     struct sockaddr_in6 in6;
107 } sockaddr_union;
108 
109 #define SUCCESS 0
110 #define ANY 0
111 #define YES 1
112 #define NO  0
113 
114 static const char in_addrany[] = { 0, 0, 0, 0 };
115 static const char in_loopback[] = { 127, 0, 0, 1 };
116 #ifdef INET6
117 static const char in6_addrany[] = {
118 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
119 };
120 static const char in6_loopback[] = {
121 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
122 };
123 #endif
124 
125 static const struct afd {
126 	int a_af;
127 	int a_addrlen;
128 	int a_socklen;
129 	int a_off;
130 	const char *a_addrany;
131 	const char *a_loopback;
132 	int a_scoped;
133 } afdl [] = {
134 #ifdef INET6
135 	{PF_INET6, sizeof(struct in6_addr),
136 	 sizeof(struct sockaddr_in6),
137 	 offsetof(struct sockaddr_in6, sin6_addr),
138 	 in6_addrany, in6_loopback, 1},
139 #endif
140 	{PF_INET, sizeof(struct in_addr),
141 	 sizeof(struct sockaddr_in),
142 	 offsetof(struct sockaddr_in, sin_addr),
143 	 in_addrany, in_loopback, 0},
144 	{0, 0, 0, 0, NULL, NULL, 0},
145 };
146 
147 struct explore {
148 	int e_af;
149 	int e_socktype;
150 	int e_protocol;
151 	const char *e_protostr;
152 	int e_wild;
153 #define WILD_AF(ex)		((ex)->e_wild & 0x01)
154 #define WILD_SOCKTYPE(ex)	((ex)->e_wild & 0x02)
155 #define WILD_PROTOCOL(ex)	((ex)->e_wild & 0x04)
156 };
157 
158 static const struct explore explore[] = {
159 #if 0
160 	{ PF_LOCAL, 0, ANY, ANY, NULL, 0x01 },
161 #endif
162 #ifdef INET6
163 	{ PF_INET6, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
164 	{ PF_INET6, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
165 	{ PF_INET6, SOCK_RAW, ANY, NULL, 0x05 },
166 #endif
167 	{ PF_INET, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
168 	{ PF_INET, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
169 	{ PF_INET, SOCK_RAW, ANY, NULL, 0x05 },
170 	{ PF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
171 	{ PF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
172 	{ PF_UNSPEC, SOCK_RAW, ANY, NULL, 0x05 },
173 	{ -1, 0, 0, NULL, 0 },
174 };
175 
176 #ifdef INET6
177 #define PTON_MAX	16
178 #else
179 #define PTON_MAX	4
180 #endif
181 
182 static const ns_src default_dns_files[] = {
183 	{ NSSRC_FILES, 	NS_SUCCESS },
184 	{ NSSRC_DNS, 	NS_SUCCESS },
185 	{ 0, 0 }
186 };
187 
188 #define MAXPACKET	(64*1024)
189 
190 typedef union {
191 	HEADER hdr;
192 	u_char buf[MAXPACKET];
193 } querybuf;
194 
195 struct res_target {
196 	struct res_target *next;
197 	const char *name;	/* domain name */
198 	int qclass, qtype;	/* class and type of query */
199 	u_char *answer;		/* buffer to put answer */
200 	int anslen;		/* size of answer buffer */
201 	int n;			/* result length */
202 };
203 
204 static int str2number(const char *);
205 static int explore_fqdn(const struct addrinfo *, const char *,
206 	const char *, struct addrinfo **);
207 static int explore_null(const struct addrinfo *,
208 	const char *, struct addrinfo **);
209 static int explore_numeric(const struct addrinfo *, const char *,
210 	const char *, struct addrinfo **, const char *);
211 static int explore_numeric_scope(const struct addrinfo *, const char *,
212 	const char *, struct addrinfo **);
213 static int get_canonname(const struct addrinfo *,
214 	struct addrinfo *, const char *);
215 static struct addrinfo *get_ai(const struct addrinfo *,
216 	const struct afd *, const char *);
217 static int get_portmatch(const struct addrinfo *, const char *);
218 static int get_port(const struct addrinfo *, const char *, int);
219 static const struct afd *find_afd(int);
220 #ifdef INET6
221 static int ip6_str2scopeid(char *, struct sockaddr_in6 *, u_int32_t *);
222 #endif
223 
224 static struct addrinfo *getanswer(const querybuf *, int, const char *, int,
225 	const struct addrinfo *);
226 static int _dns_getaddrinfo(void *, void *, va_list);
227 static void _sethtent(FILE **);
228 static void _endhtent(FILE **);
229 static struct addrinfo *_gethtent(FILE **, const char *,
230     const struct addrinfo *);
231 static int _files_getaddrinfo(void *, void *, va_list);
232 
233 static int res_queryN(const char *, struct res_target *, res_state);
234 static int res_searchN(const char *, struct res_target *, res_state);
235 static int res_querydomainN(const char *, const char *,
236 	struct res_target *, res_state);
237 
238 static const char * const ai_errlist[] = {
239 	"Success",
240 	"Address family for hostname not supported",	/* EAI_ADDRFAMILY */
241 	"Temporary failure in name resolution",		/* EAI_AGAIN      */
242 	"Invalid value for ai_flags",		       	/* EAI_BADFLAGS   */
243 	"Non-recoverable failure in name resolution", 	/* EAI_FAIL       */
244 	"ai_family not supported",			/* EAI_FAMILY     */
245 	"Memory allocation failure", 			/* EAI_MEMORY     */
246 	"No address associated with hostname", 		/* EAI_NODATA     */
247 	"hostname nor servname provided, or not known",	/* EAI_NONAME     */
248 	"servname not supported for ai_socktype",	/* EAI_SERVICE    */
249 	"ai_socktype not supported", 			/* EAI_SOCKTYPE   */
250 	"System error returned in errno", 		/* EAI_SYSTEM     */
251 	"Invalid value for hints",			/* EAI_BADHINTS	  */
252 	"Resolved protocol is unknown",			/* EAI_PROTOCOL   */
253 	"Argument buffer overflow",			/* EAI_OVERFLOW   */
254 	"Unknown error", 				/* EAI_MAX        */
255 };
256 
257 /* XXX macros that make external reference is BAD. */
258 
259 #define GET_AI(ai, afd, addr) 					\
260 do { 								\
261 	/* external reference: pai, error, and label free */ 	\
262 	(ai) = get_ai(pai, (afd), (addr)); 			\
263 	if ((ai) == NULL) { 					\
264 		error = EAI_MEMORY; 				\
265 		goto free; 					\
266 	} 							\
267 } while (/*CONSTCOND*/0)
268 
269 #define GET_PORT(ai, serv) 					\
270 do { 								\
271 	/* external reference: error and label free */ 		\
272 	error = get_port((ai), (serv), 0); 			\
273 	if (error != 0) 					\
274 		goto free; 					\
275 } while (/*CONSTCOND*/0)
276 
277 #define GET_CANONNAME(ai, str) 					\
278 do { 								\
279 	/* external reference: pai, error and label free */ 	\
280 	error = get_canonname(pai, (ai), (str)); 		\
281 	if (error != 0) 					\
282 		goto free; 					\
283 } while (/*CONSTCOND*/0)
284 
285 #define ERR(err) 						\
286 do { 								\
287 	/* external reference: error, and label bad */ 		\
288 	error = (err); 						\
289 	goto bad; 						\
290 	/*NOTREACHED*/ 						\
291 } while (/*CONSTCOND*/0)
292 
293 #define MATCH_FAMILY(x, y, w) 						\
294 	((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC || 	\
295 	    (y) == PF_UNSPEC)))
296 #define MATCH(x, y, w) 							\
297 	((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY)))
298 
299 const char *
gai_strerror(int ecode)300 gai_strerror(int ecode)
301 {
302 	if (ecode < 0 || ecode > EAI_MAX)
303 		ecode = EAI_MAX;
304 	return ai_errlist[ecode];
305 }
306 
307 void
freeaddrinfo(struct addrinfo * ai)308 freeaddrinfo(struct addrinfo *ai)
309 {
310 	struct addrinfo *next;
311 
312 	assert(ai != NULL);
313 
314 	do {
315 		next = ai->ai_next;
316 		if (ai->ai_canonname)
317 			free(ai->ai_canonname);
318 		/* no need to free(ai->ai_addr) */
319 		free(ai);
320 		ai = next;
321 	} while (ai);
322 }
323 
324 static int
str2number(const char * p)325 str2number(const char *p)
326 {
327 	char *ep;
328 	unsigned long v;
329 
330 	assert(p != NULL);
331 
332 	if (*p == '\0')
333 		return -1;
334 	ep = NULL;
335 	errno = 0;
336 	v = strtoul(p, &ep, 10);
337 	if (errno == 0 && ep && *ep == '\0' && v <= UINT_MAX)
338 		return v;
339 	else
340 		return -1;
341 }
342 
343 /*
344  * Connect a UDP socket to a given unicast address. This will cause no network
345  * traffic, but will fail fast if the system has no or limited reachability to
346  * the destination (e.g., no IPv4 address, no IPv6 default route, ...).
347  */
348 static int
_test_connect(int pf,struct sockaddr * addr,size_t addrlen)349 _test_connect(int pf, struct sockaddr *addr, size_t addrlen) {
350 	int s = socket(pf, SOCK_DGRAM, IPPROTO_UDP);
351 	if (s < 0)
352 		return 0;
353 	int ret;
354 	do {
355 		ret = connect(s, addr, addrlen);
356 	} while (ret < 0 && errno == EINTR);
357 	int success = (ret == 0);
358 	do {
359 		ret = close(s);
360 	} while (ret < 0 && errno == EINTR);
361 	return success;
362 }
363 
364 /*
365  * The following functions determine whether IPv4 or IPv6 connectivity is
366  * available in order to implement AI_ADDRCONFIG.
367  *
368  * Strictly speaking, AI_ADDRCONFIG should not look at whether connectivity is
369  * available, but whether addresses of the specified family are "configured
370  * on the local system". However, bionic doesn't currently support getifaddrs,
371  * so checking for connectivity is the next best thing.
372  */
373 static int
_have_ipv6()374 _have_ipv6() {
375 	static const struct sockaddr_in6 sin6_test = {
376 		.sin6_family = AF_INET6,
377 		.sin6_addr.s6_addr = {  // 2000::
378 			0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
379 		};
380         sockaddr_union addr = { .in6 = sin6_test };
381 	return _test_connect(PF_INET6, &addr.generic, sizeof(addr.in6));
382 }
383 
384 static int
_have_ipv4()385 _have_ipv4() {
386 	static const struct sockaddr_in sin_test = {
387 		.sin_family = AF_INET,
388 		.sin_addr.s_addr = __constant_htonl(0x08080808L)  // 8.8.8.8
389 	};
390         sockaddr_union addr = { .in = sin_test };
391         return _test_connect(PF_INET, &addr.generic, sizeof(addr.in));
392 }
393 
394 int
getaddrinfo(const char * hostname,const char * servname,const struct addrinfo * hints,struct addrinfo ** res)395 getaddrinfo(const char *hostname, const char *servname,
396     const struct addrinfo *hints, struct addrinfo **res)
397 {
398 	struct addrinfo sentinel;
399 	struct addrinfo *cur;
400 	int error = 0;
401 	struct addrinfo ai;
402 	struct addrinfo ai0;
403 	struct addrinfo *pai;
404 	const struct explore *ex;
405 
406 	/* hostname is allowed to be NULL */
407 	/* servname is allowed to be NULL */
408 	/* hints is allowed to be NULL */
409 	assert(res != NULL);
410 
411 	memset(&sentinel, 0, sizeof(sentinel));
412 	cur = &sentinel;
413 	pai = &ai;
414 	pai->ai_flags = 0;
415 	pai->ai_family = PF_UNSPEC;
416 	pai->ai_socktype = ANY;
417 	pai->ai_protocol = ANY;
418 	pai->ai_addrlen = 0;
419 	pai->ai_canonname = NULL;
420 	pai->ai_addr = NULL;
421 	pai->ai_next = NULL;
422 
423 	if (hostname == NULL && servname == NULL)
424 		return EAI_NONAME;
425 	if (hints) {
426 		/* error check for hints */
427 		if (hints->ai_addrlen || hints->ai_canonname ||
428 		    hints->ai_addr || hints->ai_next)
429 			ERR(EAI_BADHINTS); /* xxx */
430 		if (hints->ai_flags & ~AI_MASK)
431 			ERR(EAI_BADFLAGS);
432 		switch (hints->ai_family) {
433 		case PF_UNSPEC:
434 		case PF_INET:
435 #ifdef INET6
436 		case PF_INET6:
437 #endif
438 			break;
439 		default:
440 			ERR(EAI_FAMILY);
441 		}
442 		memcpy(pai, hints, sizeof(*pai));
443 
444 		/*
445 		 * if both socktype/protocol are specified, check if they
446 		 * are meaningful combination.
447 		 */
448 		if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
449 			for (ex = explore; ex->e_af >= 0; ex++) {
450 				if (pai->ai_family != ex->e_af)
451 					continue;
452 				if (ex->e_socktype == ANY)
453 					continue;
454 				if (ex->e_protocol == ANY)
455 					continue;
456 				if (pai->ai_socktype == ex->e_socktype
457 				 && pai->ai_protocol != ex->e_protocol) {
458 					ERR(EAI_BADHINTS);
459 				}
460 			}
461 		}
462 	}
463 
464 	/*
465 	 * check for special cases.  (1) numeric servname is disallowed if
466 	 * socktype/protocol are left unspecified. (2) servname is disallowed
467 	 * for raw and other inet{,6} sockets.
468 	 */
469 	if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
470 #ifdef PF_INET6
471 	 || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
472 #endif
473 	    ) {
474 		ai0 = *pai;	/* backup *pai */
475 
476 		if (pai->ai_family == PF_UNSPEC) {
477 #ifdef PF_INET6
478 			pai->ai_family = PF_INET6;
479 #else
480 			pai->ai_family = PF_INET;
481 #endif
482 		}
483 		error = get_portmatch(pai, servname);
484 		if (error)
485 			ERR(error);
486 
487 		*pai = ai0;
488 	}
489 
490 	ai0 = *pai;
491 
492 	/* NULL hostname, or numeric hostname */
493 	for (ex = explore; ex->e_af >= 0; ex++) {
494 		*pai = ai0;
495 
496 		/* PF_UNSPEC entries are prepared for DNS queries only */
497 		if (ex->e_af == PF_UNSPEC)
498 			continue;
499 
500 		if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
501 			continue;
502 		if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex)))
503 			continue;
504 		if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex)))
505 			continue;
506 
507 		if (pai->ai_family == PF_UNSPEC)
508 			pai->ai_family = ex->e_af;
509 		if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
510 			pai->ai_socktype = ex->e_socktype;
511 		if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
512 			pai->ai_protocol = ex->e_protocol;
513 
514 		if (hostname == NULL)
515 			error = explore_null(pai, servname, &cur->ai_next);
516 		else
517 			error = explore_numeric_scope(pai, hostname, servname,
518 			    &cur->ai_next);
519 
520 		if (error)
521 			goto free;
522 
523 		while (cur->ai_next)
524 			cur = cur->ai_next;
525 	}
526 
527 	/*
528 	 * XXX
529 	 * If numeric representation of AF1 can be interpreted as FQDN
530 	 * representation of AF2, we need to think again about the code below.
531 	 */
532 	if (sentinel.ai_next)
533 		goto good;
534 
535 	if (hostname == NULL)
536 		ERR(EAI_NODATA);
537 	if (pai->ai_flags & AI_NUMERICHOST)
538 		ERR(EAI_NONAME);
539 
540 	/*
541 	 * hostname as alphabetical name.
542 	 * we would like to prefer AF_INET6 than AF_INET, so we'll make a
543 	 * outer loop by AFs.
544 	 */
545 	for (ex = explore; ex->e_af >= 0; ex++) {
546 		*pai = ai0;
547 
548 		/* require exact match for family field */
549 		if (pai->ai_family != ex->e_af)
550 			continue;
551 
552 		if (!MATCH(pai->ai_socktype, ex->e_socktype,
553 				WILD_SOCKTYPE(ex))) {
554 			continue;
555 		}
556 		if (!MATCH(pai->ai_protocol, ex->e_protocol,
557 				WILD_PROTOCOL(ex))) {
558 			continue;
559 		}
560 
561 		if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
562 			pai->ai_socktype = ex->e_socktype;
563 		if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
564 			pai->ai_protocol = ex->e_protocol;
565 
566 		error = explore_fqdn(pai, hostname, servname,
567 			&cur->ai_next);
568 
569 		while (cur && cur->ai_next)
570 			cur = cur->ai_next;
571 	}
572 
573 	/* XXX */
574 	if (sentinel.ai_next)
575 		error = 0;
576 
577 	if (error)
578 		goto free;
579 	if (error == 0) {
580 		if (sentinel.ai_next) {
581  good:
582 			*res = sentinel.ai_next;
583 			return SUCCESS;
584 		} else
585 			error = EAI_FAIL;
586 	}
587  free:
588  bad:
589 	if (sentinel.ai_next)
590 		freeaddrinfo(sentinel.ai_next);
591 	*res = NULL;
592 	return error;
593 }
594 
595 /*
596  * FQDN hostname, DNS lookup
597  */
598 static int
explore_fqdn(const struct addrinfo * pai,const char * hostname,const char * servname,struct addrinfo ** res)599 explore_fqdn(const struct addrinfo *pai, const char *hostname,
600     const char *servname, struct addrinfo **res)
601 {
602 	struct addrinfo *result;
603 	struct addrinfo *cur;
604 	int error = 0;
605 	static const ns_dtab dtab[] = {
606 		NS_FILES_CB(_files_getaddrinfo, NULL)
607 		{ NSSRC_DNS, _dns_getaddrinfo, NULL },	/* force -DHESIOD */
608 		NS_NIS_CB(_yp_getaddrinfo, NULL)
609 		{ 0, 0, 0 }
610 	};
611 
612 	assert(pai != NULL);
613 	/* hostname may be NULL */
614 	/* servname may be NULL */
615 	assert(res != NULL);
616 
617 	result = NULL;
618 
619 	/*
620 	 * if the servname does not match socktype/protocol, ignore it.
621 	 */
622 	if (get_portmatch(pai, servname) != 0)
623 		return 0;
624 
625 	switch (nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
626 			default_dns_files, hostname, pai)) {
627 	case NS_TRYAGAIN:
628 		error = EAI_AGAIN;
629 		goto free;
630 	case NS_UNAVAIL:
631 		error = EAI_FAIL;
632 		goto free;
633 	case NS_NOTFOUND:
634 		error = EAI_NODATA;
635 		goto free;
636 	case NS_SUCCESS:
637 		error = 0;
638 		for (cur = result; cur; cur = cur->ai_next) {
639 			GET_PORT(cur, servname);
640 			/* canonname should be filled already */
641 		}
642 		break;
643 	}
644 
645 	*res = result;
646 
647 	return 0;
648 
649 free:
650 	if (result)
651 		freeaddrinfo(result);
652 	return error;
653 }
654 
655 /*
656  * hostname == NULL.
657  * passive socket -> anyaddr (0.0.0.0 or ::)
658  * non-passive socket -> localhost (127.0.0.1 or ::1)
659  */
660 static int
explore_null(const struct addrinfo * pai,const char * servname,struct addrinfo ** res)661 explore_null(const struct addrinfo *pai, const char *servname,
662     struct addrinfo **res)
663 {
664 	int s;
665 	const struct afd *afd;
666 	struct addrinfo *cur;
667 	struct addrinfo sentinel;
668 	int error;
669 
670 	assert(pai != NULL);
671 	/* servname may be NULL */
672 	assert(res != NULL);
673 
674 	*res = NULL;
675 	sentinel.ai_next = NULL;
676 	cur = &sentinel;
677 
678 	/*
679 	 * filter out AFs that are not supported by the kernel
680 	 * XXX errno?
681 	 */
682 	s = socket(pai->ai_family, SOCK_DGRAM, 0);
683 	if (s < 0) {
684 		if (errno != EMFILE)
685 			return 0;
686 	} else
687 		close(s);
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 	if (pai->ai_flags & AI_PASSIVE) {
700 		GET_AI(cur->ai_next, afd, afd->a_addrany);
701 		/* xxx meaningless?
702 		 * GET_CANONNAME(cur->ai_next, "anyaddr");
703 		 */
704 		GET_PORT(cur->ai_next, servname);
705 	} else {
706 		GET_AI(cur->ai_next, afd, afd->a_loopback);
707 		/* xxx meaningless?
708 		 * GET_CANONNAME(cur->ai_next, "localhost");
709 		 */
710 		GET_PORT(cur->ai_next, servname);
711 	}
712 	cur = cur->ai_next;
713 
714 	*res = sentinel.ai_next;
715 	return 0;
716 
717 free:
718 	if (sentinel.ai_next)
719 		freeaddrinfo(sentinel.ai_next);
720 	return error;
721 }
722 
723 /*
724  * numeric hostname
725  */
726 static int
explore_numeric(const struct addrinfo * pai,const char * hostname,const char * servname,struct addrinfo ** res,const char * canonname)727 explore_numeric(const struct addrinfo *pai, const char *hostname,
728     const char *servname, struct addrinfo **res, const char *canonname)
729 {
730 	const struct afd *afd;
731 	struct addrinfo *cur;
732 	struct addrinfo sentinel;
733 	int error;
734 	char pton[PTON_MAX];
735 
736 	assert(pai != NULL);
737 	/* hostname may be NULL */
738 	/* servname may be NULL */
739 	assert(res != NULL);
740 
741 	*res = NULL;
742 	sentinel.ai_next = NULL;
743 	cur = &sentinel;
744 
745 	/*
746 	 * if the servname does not match socktype/protocol, ignore it.
747 	 */
748 	if (get_portmatch(pai, servname) != 0)
749 		return 0;
750 
751 	afd = find_afd(pai->ai_family);
752 	if (afd == NULL)
753 		return 0;
754 
755 	switch (afd->a_af) {
756 #if 0 /*X/Open spec*/
757 	case AF_INET:
758 		if (inet_aton(hostname, (struct in_addr *)pton) == 1) {
759 			if (pai->ai_family == afd->a_af ||
760 			    pai->ai_family == PF_UNSPEC /*?*/) {
761 				GET_AI(cur->ai_next, afd, pton);
762 				GET_PORT(cur->ai_next, servname);
763 				if ((pai->ai_flags & AI_CANONNAME)) {
764 					/*
765 					 * Set the numeric address itself as
766 					 * the canonical name, based on a
767 					 * clarification in rfc2553bis-03.
768 					 */
769 					GET_CANONNAME(cur->ai_next, canonname);
770 				}
771 				while (cur && cur->ai_next)
772 					cur = cur->ai_next;
773 			} else
774 				ERR(EAI_FAMILY);	/*xxx*/
775 		}
776 		break;
777 #endif
778 	default:
779 		if (inet_pton(afd->a_af, hostname, pton) == 1) {
780 			if (pai->ai_family == afd->a_af ||
781 			    pai->ai_family == PF_UNSPEC /*?*/) {
782 				GET_AI(cur->ai_next, afd, pton);
783 				GET_PORT(cur->ai_next, servname);
784 				if ((pai->ai_flags & AI_CANONNAME)) {
785 					/*
786 					 * Set the numeric address itself as
787 					 * the canonical name, based on a
788 					 * clarification in rfc2553bis-03.
789 					 */
790 					GET_CANONNAME(cur->ai_next, canonname);
791 				}
792 				while (cur->ai_next)
793 					cur = cur->ai_next;
794 			} else
795 				ERR(EAI_FAMILY);	/*xxx*/
796 		}
797 		break;
798 	}
799 
800 	*res = sentinel.ai_next;
801 	return 0;
802 
803 free:
804 bad:
805 	if (sentinel.ai_next)
806 		freeaddrinfo(sentinel.ai_next);
807 	return error;
808 }
809 
810 /*
811  * numeric hostname with scope
812  */
813 static int
explore_numeric_scope(const struct addrinfo * pai,const char * hostname,const char * servname,struct addrinfo ** res)814 explore_numeric_scope(const struct addrinfo *pai, const char *hostname,
815     const char *servname, struct addrinfo **res)
816 {
817 #if !defined(SCOPE_DELIMITER) || !defined(INET6)
818 	return explore_numeric(pai, hostname, servname, res, hostname);
819 #else
820 	const struct afd *afd;
821 	struct addrinfo *cur;
822 	int error;
823 	char *cp, *hostname2 = NULL, *scope, *addr;
824 	struct sockaddr_in6 *sin6;
825 
826 	assert(pai != NULL);
827 	/* hostname may be NULL */
828 	/* servname may be NULL */
829 	assert(res != NULL);
830 
831 	/*
832 	 * if the servname does not match socktype/protocol, ignore it.
833 	 */
834 	if (get_portmatch(pai, servname) != 0)
835 		return 0;
836 
837 	afd = find_afd(pai->ai_family);
838 	if (afd == NULL)
839 		return 0;
840 
841 	if (!afd->a_scoped)
842 		return explore_numeric(pai, hostname, servname, res, hostname);
843 
844 	cp = strchr(hostname, SCOPE_DELIMITER);
845 	if (cp == NULL)
846 		return explore_numeric(pai, hostname, servname, res, hostname);
847 
848 	/*
849 	 * Handle special case of <scoped_address><delimiter><scope id>
850 	 */
851 	hostname2 = strdup(hostname);
852 	if (hostname2 == NULL)
853 		return EAI_MEMORY;
854 	/* terminate at the delimiter */
855 	hostname2[cp - hostname] = '\0';
856 	addr = hostname2;
857 	scope = cp + 1;
858 
859 	error = explore_numeric(pai, addr, servname, res, hostname);
860 	if (error == 0) {
861 		u_int32_t scopeid;
862 
863 		for (cur = *res; cur; cur = cur->ai_next) {
864 			if (cur->ai_family != AF_INET6)
865 				continue;
866 			sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
867 			if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) {
868 				free(hostname2);
869 				return(EAI_NODATA); /* XXX: is return OK? */
870 			}
871 			sin6->sin6_scope_id = scopeid;
872 		}
873 	}
874 
875 	free(hostname2);
876 
877 	return error;
878 #endif
879 }
880 
881 static int
get_canonname(const struct addrinfo * pai,struct addrinfo * ai,const char * str)882 get_canonname(const struct addrinfo *pai, struct addrinfo *ai, const char *str)
883 {
884 
885 	assert(pai != NULL);
886 	assert(ai != NULL);
887 	assert(str != NULL);
888 
889 	if ((pai->ai_flags & AI_CANONNAME) != 0) {
890 		ai->ai_canonname = strdup(str);
891 		if (ai->ai_canonname == NULL)
892 			return EAI_MEMORY;
893 	}
894 	return 0;
895 }
896 
897 static struct addrinfo *
get_ai(const struct addrinfo * pai,const struct afd * afd,const char * addr)898 get_ai(const struct addrinfo *pai, const struct afd *afd, const char *addr)
899 {
900 	char *p;
901 	struct addrinfo *ai;
902 
903 	assert(pai != NULL);
904 	assert(afd != NULL);
905 	assert(addr != NULL);
906 
907 	ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
908 		+ (afd->a_socklen));
909 	if (ai == NULL)
910 		return NULL;
911 
912 	memcpy(ai, pai, sizeof(struct addrinfo));
913 	ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
914 	memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
915 
916 #ifdef HAVE_SA_LEN
917 	ai->ai_addr->sa_len = afd->a_socklen;
918 #endif
919 
920 	ai->ai_addrlen = afd->a_socklen;
921 #if defined (__alpha__) || (defined(__i386__) && defined(_LP64)) || defined(__sparc64__)
922 	ai->__ai_pad0 = 0;
923 #endif
924 	ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
925 	p = (char *)(void *)(ai->ai_addr);
926 	memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
927 	return ai;
928 }
929 
930 static int
get_portmatch(const struct addrinfo * ai,const char * servname)931 get_portmatch(const struct addrinfo *ai, const char *servname)
932 {
933 
934 	assert(ai != NULL);
935 	/* servname may be NULL */
936 
937 	return get_port(ai, servname, 1);
938 }
939 
940 static int
get_port(const struct addrinfo * ai,const char * servname,int matchonly)941 get_port(const struct addrinfo *ai, const char *servname, int matchonly)
942 {
943 	const char *proto;
944 	struct servent *sp;
945 	int port;
946 	int allownumeric;
947 
948 	assert(ai != NULL);
949 	/* servname may be NULL */
950 
951 	if (servname == NULL)
952 		return 0;
953 	switch (ai->ai_family) {
954 	case AF_INET:
955 #ifdef AF_INET6
956 	case AF_INET6:
957 #endif
958 		break;
959 	default:
960 		return 0;
961 	}
962 
963 	switch (ai->ai_socktype) {
964 	case SOCK_RAW:
965 		return EAI_SERVICE;
966 	case SOCK_DGRAM:
967 	case SOCK_STREAM:
968 		allownumeric = 1;
969 		break;
970 	case ANY:
971 #if 1  /* ANDROID-SPECIFIC CHANGE TO MATCH GLIBC */
972 		allownumeric = 1;
973 #else
974 		allownumeric = 0;
975 #endif
976 		break;
977 	default:
978 		return EAI_SOCKTYPE;
979 	}
980 
981 	port = str2number(servname);
982 	if (port >= 0) {
983 		if (!allownumeric)
984 			return EAI_SERVICE;
985 		if (port < 0 || port > 65535)
986 			return EAI_SERVICE;
987 		port = htons(port);
988 	} else {
989 		if (ai->ai_flags & AI_NUMERICSERV)
990 			return EAI_NONAME;
991 
992 		switch (ai->ai_socktype) {
993 		case SOCK_DGRAM:
994 			proto = "udp";
995 			break;
996 		case SOCK_STREAM:
997 			proto = "tcp";
998 			break;
999 		default:
1000 			proto = NULL;
1001 			break;
1002 		}
1003 
1004 		if ((sp = getservbyname(servname, proto)) == NULL)
1005 			return EAI_SERVICE;
1006 		port = sp->s_port;
1007 	}
1008 
1009 	if (!matchonly) {
1010 		switch (ai->ai_family) {
1011 		case AF_INET:
1012 			((struct sockaddr_in *)(void *)
1013 			    ai->ai_addr)->sin_port = port;
1014 			break;
1015 #ifdef INET6
1016 		case AF_INET6:
1017 			((struct sockaddr_in6 *)(void *)
1018 			    ai->ai_addr)->sin6_port = port;
1019 			break;
1020 #endif
1021 		}
1022 	}
1023 
1024 	return 0;
1025 }
1026 
1027 static const struct afd *
find_afd(int af)1028 find_afd(int af)
1029 {
1030 	const struct afd *afd;
1031 
1032 	if (af == PF_UNSPEC)
1033 		return NULL;
1034 	for (afd = afdl; afd->a_af; afd++) {
1035 		if (afd->a_af == af)
1036 			return afd;
1037 	}
1038 	return NULL;
1039 }
1040 
1041 #ifdef INET6
1042 /* convert a string to a scope identifier. XXX: IPv6 specific */
1043 static int
ip6_str2scopeid(char * scope,struct sockaddr_in6 * sin6,u_int32_t * scopeid)1044 ip6_str2scopeid(char *scope, struct sockaddr_in6 *sin6, u_int32_t *scopeid)
1045 {
1046 	u_long lscopeid;
1047 	struct in6_addr *a6;
1048 	char *ep;
1049 
1050 	assert(scope != NULL);
1051 	assert(sin6 != NULL);
1052 	assert(scopeid != NULL);
1053 
1054 	a6 = &sin6->sin6_addr;
1055 
1056 	/* empty scopeid portion is invalid */
1057 	if (*scope == '\0')
1058 		return -1;
1059 
1060 	if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
1061 		/*
1062 		 * We currently assume a one-to-one mapping between links
1063 		 * and interfaces, so we simply use interface indices for
1064 		 * like-local scopes.
1065 		 */
1066 		*scopeid = if_nametoindex(scope);
1067 		if (*scopeid == 0)
1068 			goto trynumeric;
1069 		return 0;
1070 	}
1071 
1072 	/* still unclear about literal, allow numeric only - placeholder */
1073 	if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
1074 		goto trynumeric;
1075 	if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
1076 		goto trynumeric;
1077 	else
1078 		goto trynumeric;	/* global */
1079 
1080 	/* try to convert to a numeric id as a last resort */
1081   trynumeric:
1082 	errno = 0;
1083 	lscopeid = strtoul(scope, &ep, 10);
1084 	*scopeid = (u_int32_t)(lscopeid & 0xffffffffUL);
1085 	if (errno == 0 && ep && *ep == '\0' && *scopeid == lscopeid)
1086 		return 0;
1087 	else
1088 		return -1;
1089 }
1090 #endif
1091 
1092 /* code duplicate with gethnamaddr.c */
1093 
1094 static const char AskedForGot[] =
1095 	"gethostby*.getanswer: asked for \"%s\", got \"%s\"";
1096 
1097 static struct addrinfo *
getanswer(const querybuf * answer,int anslen,const char * qname,int qtype,const struct addrinfo * pai)1098 getanswer(const querybuf *answer, int anslen, const char *qname, int qtype,
1099     const struct addrinfo *pai)
1100 {
1101 	struct addrinfo sentinel, *cur;
1102 	struct addrinfo ai;
1103 	const struct afd *afd;
1104 	char *canonname;
1105 	const HEADER *hp;
1106 	const u_char *cp;
1107 	int n;
1108 	const u_char *eom;
1109 	char *bp, *ep;
1110 	int type, class, ancount, qdcount;
1111 	int haveanswer, had_error;
1112 	char tbuf[MAXDNAME];
1113 	int (*name_ok) (const char *);
1114 	char hostbuf[8*1024];
1115 
1116 	assert(answer != NULL);
1117 	assert(qname != NULL);
1118 	assert(pai != NULL);
1119 
1120 	memset(&sentinel, 0, sizeof(sentinel));
1121 	cur = &sentinel;
1122 
1123 	canonname = NULL;
1124 	eom = answer->buf + anslen;
1125 	switch (qtype) {
1126 	case T_A:
1127 	case T_AAAA:
1128 	case T_ANY:	/*use T_ANY only for T_A/T_AAAA lookup*/
1129 		name_ok = res_hnok;
1130 		break;
1131 	default:
1132 		return NULL;	/* XXX should be abort(); */
1133 	}
1134 	/*
1135 	 * find first satisfactory answer
1136 	 */
1137 	hp = &answer->hdr;
1138 	ancount = ntohs(hp->ancount);
1139 	qdcount = ntohs(hp->qdcount);
1140 	bp = hostbuf;
1141 	ep = hostbuf + sizeof hostbuf;
1142 	cp = answer->buf + HFIXEDSZ;
1143 	if (qdcount != 1) {
1144 		h_errno = NO_RECOVERY;
1145 		return (NULL);
1146 	}
1147 	n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1148 	if ((n < 0) || !(*name_ok)(bp)) {
1149 		h_errno = NO_RECOVERY;
1150 		return (NULL);
1151 	}
1152 	cp += n + QFIXEDSZ;
1153 	if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
1154 		/* res_send() has already verified that the query name is the
1155 		 * same as the one we sent; this just gets the expanded name
1156 		 * (i.e., with the succeeding search-domain tacked on).
1157 		 */
1158 		n = strlen(bp) + 1;		/* for the \0 */
1159 		if (n >= MAXHOSTNAMELEN) {
1160 			h_errno = NO_RECOVERY;
1161 			return (NULL);
1162 		}
1163 		canonname = bp;
1164 		bp += n;
1165 		/* The qname can be abbreviated, but h_name is now absolute. */
1166 		qname = canonname;
1167 	}
1168 	haveanswer = 0;
1169 	had_error = 0;
1170 	while (ancount-- > 0 && cp < eom && !had_error) {
1171 		n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1172 		if ((n < 0) || !(*name_ok)(bp)) {
1173 			had_error++;
1174 			continue;
1175 		}
1176 		cp += n;			/* name */
1177 		type = _getshort(cp);
1178  		cp += INT16SZ;			/* type */
1179 		class = _getshort(cp);
1180  		cp += INT16SZ + INT32SZ;	/* class, TTL */
1181 		n = _getshort(cp);
1182 		cp += INT16SZ;			/* len */
1183 		if (class != C_IN) {
1184 			/* XXX - debug? syslog? */
1185 			cp += n;
1186 			continue;		/* XXX - had_error++ ? */
1187 		}
1188 		if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
1189 		    type == T_CNAME) {
1190 			n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
1191 			if ((n < 0) || !(*name_ok)(tbuf)) {
1192 				had_error++;
1193 				continue;
1194 			}
1195 			cp += n;
1196 			/* Get canonical name. */
1197 			n = strlen(tbuf) + 1;	/* for the \0 */
1198 			if (n > ep - bp || n >= MAXHOSTNAMELEN) {
1199 				had_error++;
1200 				continue;
1201 			}
1202 			strlcpy(bp, tbuf, (size_t)(ep - bp));
1203 			canonname = bp;
1204 			bp += n;
1205 			continue;
1206 		}
1207 		if (qtype == T_ANY) {
1208 			if (!(type == T_A || type == T_AAAA)) {
1209 				cp += n;
1210 				continue;
1211 			}
1212 		} else if (type != qtype) {
1213 			if (type != T_KEY && type != T_SIG)
1214 				syslog(LOG_NOTICE|LOG_AUTH,
1215 	       "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
1216 				       qname, p_class(C_IN), p_type(qtype),
1217 				       p_type(type));
1218 			cp += n;
1219 			continue;		/* XXX - had_error++ ? */
1220 		}
1221 		switch (type) {
1222 		case T_A:
1223 		case T_AAAA:
1224 			if (strcasecmp(canonname, bp) != 0) {
1225 				syslog(LOG_NOTICE|LOG_AUTH,
1226 				       AskedForGot, canonname, bp);
1227 				cp += n;
1228 				continue;	/* XXX - had_error++ ? */
1229 			}
1230 			if (type == T_A && n != INADDRSZ) {
1231 				cp += n;
1232 				continue;
1233 			}
1234 			if (type == T_AAAA && n != IN6ADDRSZ) {
1235 				cp += n;
1236 				continue;
1237 			}
1238 			if (type == T_AAAA) {
1239 				struct in6_addr in6;
1240 				memcpy(&in6, cp, IN6ADDRSZ);
1241 				if (IN6_IS_ADDR_V4MAPPED(&in6)) {
1242 					cp += n;
1243 					continue;
1244 				}
1245 			}
1246 			if (!haveanswer) {
1247 				int nn;
1248 
1249 				canonname = bp;
1250 				nn = strlen(bp) + 1;	/* for the \0 */
1251 				bp += nn;
1252 			}
1253 
1254 			/* don't overwrite pai */
1255 			ai = *pai;
1256 			ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
1257 			afd = find_afd(ai.ai_family);
1258 			if (afd == NULL) {
1259 				cp += n;
1260 				continue;
1261 			}
1262 			cur->ai_next = get_ai(&ai, afd, (const char *)cp);
1263 			if (cur->ai_next == NULL)
1264 				had_error++;
1265 			while (cur && cur->ai_next)
1266 				cur = cur->ai_next;
1267 			cp += n;
1268 			break;
1269 		default:
1270 			abort();
1271 		}
1272 		if (!had_error)
1273 			haveanswer++;
1274 	}
1275 	if (haveanswer) {
1276 		if (!canonname)
1277 			(void)get_canonname(pai, sentinel.ai_next, qname);
1278 		else
1279 			(void)get_canonname(pai, sentinel.ai_next, canonname);
1280 		h_errno = NETDB_SUCCESS;
1281 		return sentinel.ai_next;
1282 	}
1283 
1284 	h_errno = NO_RECOVERY;
1285 	return NULL;
1286 }
1287 
1288 struct addrinfo_sort_elem {
1289 	struct addrinfo *ai;
1290 	int has_src_addr;
1291 	sockaddr_union src_addr;
1292 	int original_order;
1293 };
1294 
1295 /*ARGSUSED*/
1296 static int
_get_scope(const struct sockaddr * addr)1297 _get_scope(const struct sockaddr *addr)
1298 {
1299 	if (addr->sa_family == AF_INET6) {
1300 		const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)addr;
1301 		if (IN6_IS_ADDR_MULTICAST(&addr6->sin6_addr)) {
1302 			return IPV6_ADDR_MC_SCOPE(&addr6->sin6_addr);
1303 		} else if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr) ||
1304 			   IN6_IS_ADDR_LINKLOCAL(&addr6->sin6_addr)) {
1305 			/*
1306 			 * RFC 4291 section 2.5.3 says loopback is to be treated as having
1307 			 * link-local scope.
1308 			 */
1309 			return IPV6_ADDR_SCOPE_LINKLOCAL;
1310 		} else if (IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr)) {
1311 			return IPV6_ADDR_SCOPE_SITELOCAL;
1312 		} else {
1313 			return IPV6_ADDR_SCOPE_GLOBAL;
1314 		}
1315 	} else if (addr->sa_family == AF_INET) {
1316 		const struct sockaddr_in *addr4 = (const struct sockaddr_in *)addr;
1317 		unsigned long int na = ntohl(addr4->sin_addr.s_addr);
1318 
1319 		if (IN_LOOPBACK(na) ||                          /* 127.0.0.0/8 */
1320 		    (na & 0xffff0000) == 0xa9fe0000) {          /* 169.254.0.0/16 */
1321 			return IPV6_ADDR_SCOPE_LINKLOCAL;
1322 		} else {
1323 			/*
1324 			 * According to draft-ietf-6man-rfc3484-revise-01 section 2.3,
1325 			 * it is best not to treat the private IPv4 ranges
1326 			 * (10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16) as being
1327 			 * in a special scope, so we don't.
1328 			 */
1329 			return IPV6_ADDR_SCOPE_GLOBAL;
1330 		}
1331 	} else {
1332 		/*
1333 		 * This should never happen.
1334 		 * Return a scope with low priority as a last resort.
1335 		 */
1336 		return IPV6_ADDR_SCOPE_NODELOCAL;
1337 	}
1338 }
1339 
1340 /* These macros are modelled after the ones in <netinet/in6.h>. */
1341 
1342 /* RFC 4380, section 2.6 */
1343 #define IN6_IS_ADDR_TEREDO(a)	 \
1344 	((*(const uint32_t *)(const void *)(&(a)->s6_addr[0]) == ntohl(0x20010000)))
1345 
1346 /* RFC 3056, section 2. */
1347 #define IN6_IS_ADDR_6TO4(a)	 \
1348 	(((a)->s6_addr[0] == 0x20) && ((a)->s6_addr[1] == 0x02))
1349 
1350 /* 6bone testing address area (3ffe::/16), deprecated in RFC 3701. */
1351 #define IN6_IS_ADDR_6BONE(a)      \
1352 	(((a)->s6_addr[0] == 0x3f) && ((a)->s6_addr[1] == 0xfe))
1353 
1354 /*
1355  * Get the label for a given IPv4/IPv6 address.
1356  * RFC 3484, section 2.1, plus changes from draft-ietf-6man-rfc3484-revise-01.
1357  */
1358 
1359 /*ARGSUSED*/
1360 static int
_get_label(const struct sockaddr * addr)1361 _get_label(const struct sockaddr *addr)
1362 {
1363 	if (addr->sa_family == AF_INET) {
1364 		return 3;
1365 	} else if (addr->sa_family == AF_INET6) {
1366 		const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)addr;
1367 		if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr)) {
1368 			return 0;
1369 		} else if (IN6_IS_ADDR_ULA(&addr6->sin6_addr)) {
1370 			return 1;
1371 		} else if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
1372 			return 3;
1373 		} else if (IN6_IS_ADDR_6TO4(&addr6->sin6_addr)) {
1374 			return 4;
1375 		} else if (IN6_IS_ADDR_TEREDO(&addr6->sin6_addr)) {
1376 			return 5;
1377 		} else if (IN6_IS_ADDR_V4COMPAT(&addr6->sin6_addr)) {
1378 			return 10;
1379 		} else if (IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr)) {
1380 			return 11;
1381 		} else if (IN6_IS_ADDR_6BONE(&addr6->sin6_addr)) {
1382 			return 12;
1383 		} else {
1384 			return 2;
1385 		}
1386 	} else {
1387 		/*
1388 		 * This should never happen.
1389 		 * Return a semi-random label as a last resort.
1390 		 */
1391 		return 1;
1392 	}
1393 }
1394 
1395 /*
1396  * Get the precedence for a given IPv4/IPv6 address.
1397  * RFC 3484, section 2.1, plus changes from draft-ietf-6man-rfc3484-revise-01.
1398  */
1399 
1400 /*ARGSUSED*/
1401 static int
_get_precedence(const struct sockaddr * addr)1402 _get_precedence(const struct sockaddr *addr)
1403 {
1404 	if (addr->sa_family == AF_INET) {
1405 		return 30;
1406 	} else if (addr->sa_family == AF_INET6) {
1407 		const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)addr;
1408 		if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr)) {
1409 			return 60;
1410 		} else if (IN6_IS_ADDR_ULA(&addr6->sin6_addr)) {
1411 			return 50;
1412 		} else if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
1413 			return 30;
1414 		} else if (IN6_IS_ADDR_6TO4(&addr6->sin6_addr)) {
1415 			return 20;
1416 		} else if (IN6_IS_ADDR_TEREDO(&addr6->sin6_addr)) {
1417 			return 10;
1418 		} else if (IN6_IS_ADDR_V4COMPAT(&addr6->sin6_addr) ||
1419 		           IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr) ||
1420 		           IN6_IS_ADDR_6BONE(&addr6->sin6_addr)) {
1421 			return 1;
1422 		} else {
1423 			return 40;
1424 		}
1425 	} else {
1426 		return 1;
1427 	}
1428 }
1429 
1430 /*
1431  * Find number of matching initial bits between the two addresses a1 and a2.
1432  */
1433 
1434 /*ARGSUSED*/
1435 static int
_common_prefix_len(const struct in6_addr * a1,const struct in6_addr * a2)1436 _common_prefix_len(const struct in6_addr *a1, const struct in6_addr *a2)
1437 {
1438 	const char *p1 = (const char *)a1;
1439 	const char *p2 = (const char *)a2;
1440 	unsigned i;
1441 
1442 	for (i = 0; i < sizeof(*a1); ++i) {
1443 		int x, j;
1444 
1445 		if (p1[i] == p2[i]) {
1446 			continue;
1447 		}
1448 		x = p1[i] ^ p2[i];
1449 		for (j = 0; j < CHAR_BIT; ++j) {
1450 			if (x & (1 << (CHAR_BIT - 1))) {
1451 				return i * CHAR_BIT + j;
1452 			}
1453 			x <<= 1;
1454 		}
1455 	}
1456 	return sizeof(*a1) * CHAR_BIT;
1457 }
1458 
1459 /*
1460  * Compare two source/destination address pairs.
1461  * RFC 3484, section 6.
1462  */
1463 
1464 /*ARGSUSED*/
1465 static int
_rfc3484_compare(const void * ptr1,const void * ptr2)1466 _rfc3484_compare(const void *ptr1, const void* ptr2)
1467 {
1468 	const struct addrinfo_sort_elem *a1 = (const struct addrinfo_sort_elem *)ptr1;
1469 	const struct addrinfo_sort_elem *a2 = (const struct addrinfo_sort_elem *)ptr2;
1470 	int scope_src1, scope_dst1, scope_match1;
1471 	int scope_src2, scope_dst2, scope_match2;
1472 	int label_src1, label_dst1, label_match1;
1473 	int label_src2, label_dst2, label_match2;
1474 	int precedence1, precedence2;
1475 	int prefixlen1, prefixlen2;
1476 
1477 	/* Rule 1: Avoid unusable destinations. */
1478 	if (a1->has_src_addr != a2->has_src_addr) {
1479 		return a2->has_src_addr - a1->has_src_addr;
1480 	}
1481 
1482 	/* Rule 2: Prefer matching scope. */
1483 	scope_src1 = _get_scope(&a1->src_addr.generic);
1484 	scope_dst1 = _get_scope(a1->ai->ai_addr);
1485 	scope_match1 = (scope_src1 == scope_dst1);
1486 
1487 	scope_src2 = _get_scope(&a2->src_addr.generic);
1488 	scope_dst2 = _get_scope(a2->ai->ai_addr);
1489 	scope_match2 = (scope_src2 == scope_dst2);
1490 
1491 	if (scope_match1 != scope_match2) {
1492 		return scope_match2 - scope_match1;
1493 	}
1494 
1495 	/*
1496 	 * Rule 3: Avoid deprecated addresses.
1497 	 * TODO(sesse): We don't currently have a good way of finding this.
1498 	 */
1499 
1500 	/*
1501 	 * Rule 4: Prefer home addresses.
1502 	 * TODO(sesse): We don't currently have a good way of finding this.
1503 	 */
1504 
1505 	/* Rule 5: Prefer matching label. */
1506 	label_src1 = _get_label(&a1->src_addr.generic);
1507 	label_dst1 = _get_label(a1->ai->ai_addr);
1508 	label_match1 = (label_src1 == label_dst1);
1509 
1510 	label_src2 = _get_label(&a2->src_addr.generic);
1511 	label_dst2 = _get_label(a2->ai->ai_addr);
1512 	label_match2 = (label_src2 == label_dst2);
1513 
1514 	if (label_match1 != label_match2) {
1515 		return label_match2 - label_match1;
1516 	}
1517 
1518 	/* Rule 6: Prefer higher precedence. */
1519 	precedence1 = _get_precedence(a1->ai->ai_addr);
1520 	precedence2 = _get_precedence(a2->ai->ai_addr);
1521 	if (precedence1 != precedence2) {
1522 		return precedence2 - precedence1;
1523 	}
1524 
1525 	/*
1526 	 * Rule 7: Prefer native transport.
1527 	 * TODO(sesse): We don't currently have a good way of finding this.
1528 	 */
1529 
1530 	/* Rule 8: Prefer smaller scope. */
1531 	if (scope_dst1 != scope_dst2) {
1532 		return scope_dst1 - scope_dst2;
1533 	}
1534 
1535 	/*
1536 	 * Rule 9: Use longest matching prefix.
1537          * We implement this for IPv6 only, as the rules in RFC 3484 don't seem
1538          * to work very well directly applied to IPv4. (glibc uses information from
1539          * the routing table for a custom IPv4 implementation here.)
1540 	 */
1541 	if (a1->has_src_addr && a1->ai->ai_addr->sa_family == AF_INET6 &&
1542 	    a2->has_src_addr && a2->ai->ai_addr->sa_family == AF_INET6) {
1543 		const struct sockaddr_in6 *a1_src = &a1->src_addr.in6;
1544 		const struct sockaddr_in6 *a1_dst = (const struct sockaddr_in6 *)a1->ai->ai_addr;
1545 		const struct sockaddr_in6 *a2_src = &a2->src_addr.in6;
1546 		const struct sockaddr_in6 *a2_dst = (const struct sockaddr_in6 *)a2->ai->ai_addr;
1547 		prefixlen1 = _common_prefix_len(&a1_src->sin6_addr, &a1_dst->sin6_addr);
1548 		prefixlen2 = _common_prefix_len(&a2_src->sin6_addr, &a2_dst->sin6_addr);
1549 		if (prefixlen1 != prefixlen2) {
1550 			return prefixlen2 - prefixlen1;
1551 		}
1552 	}
1553 
1554 	/*
1555 	 * Rule 10: Leave the order unchanged.
1556 	 * We need this since qsort() is not necessarily stable.
1557 	 */
1558 	return a1->original_order - a2->original_order;
1559 }
1560 
1561 /*
1562  * Find the source address that will be used if trying to connect to the given
1563  * address. src_addr must be large enough to hold a struct sockaddr_in6.
1564  *
1565  * Returns 1 if a source address was found, 0 if the address is unreachable,
1566  * and -1 if a fatal error occurred. If 0 or 1, the contents of src_addr are
1567  * undefined.
1568  */
1569 
1570 /*ARGSUSED*/
1571 static int
_find_src_addr(const struct sockaddr * addr,struct sockaddr * src_addr)1572 _find_src_addr(const struct sockaddr *addr, struct sockaddr *src_addr)
1573 {
1574 	int sock;
1575 	int ret;
1576 	socklen_t len;
1577 
1578 	switch (addr->sa_family) {
1579 	case AF_INET:
1580 		len = sizeof(struct sockaddr_in);
1581 		break;
1582 	case AF_INET6:
1583 		len = sizeof(struct sockaddr_in6);
1584 		break;
1585 	default:
1586 		/* No known usable source address for non-INET families. */
1587 		return 0;
1588 	}
1589 
1590 	sock = socket(addr->sa_family, SOCK_DGRAM, IPPROTO_UDP);
1591 	if (sock == -1) {
1592 		if (errno == EAFNOSUPPORT) {
1593 			return 0;
1594 		} else {
1595 			return -1;
1596 		}
1597 	}
1598 
1599 	do {
1600 		ret = connect(sock, addr, len);
1601 	} while (ret == -1 && errno == EINTR);
1602 
1603 	if (ret == -1) {
1604 		close(sock);
1605 		return 0;
1606 	}
1607 
1608 	if (getsockname(sock, src_addr, &len) == -1) {
1609 		close(sock);
1610 		return -1;
1611 	}
1612 	close(sock);
1613 	return 1;
1614 }
1615 
1616 /*
1617  * Sort the linked list starting at sentinel->ai_next in RFC3484 order.
1618  * Will leave the list unchanged if an error occurs.
1619  */
1620 
1621 /*ARGSUSED*/
1622 static void
_rfc3484_sort(struct addrinfo * list_sentinel)1623 _rfc3484_sort(struct addrinfo *list_sentinel)
1624 {
1625 	struct addrinfo *cur;
1626 	int nelem = 0, i;
1627 	struct addrinfo_sort_elem *elems;
1628 
1629 	cur = list_sentinel->ai_next;
1630 	while (cur) {
1631 		++nelem;
1632 		cur = cur->ai_next;
1633 	}
1634 
1635 	elems = (struct addrinfo_sort_elem *)malloc(nelem * sizeof(struct addrinfo_sort_elem));
1636 	if (elems == NULL) {
1637 		goto error;
1638 	}
1639 
1640 	/*
1641 	 * Convert the linked list to an array that also contains the candidate
1642 	 * source address for each destination address.
1643 	 */
1644 	for (i = 0, cur = list_sentinel->ai_next; i < nelem; ++i, cur = cur->ai_next) {
1645 		int has_src_addr;
1646 		assert(cur != NULL);
1647 		elems[i].ai = cur;
1648 		elems[i].original_order = i;
1649 
1650 		has_src_addr = _find_src_addr(cur->ai_addr, &elems[i].src_addr.generic);
1651 		if (has_src_addr == -1) {
1652 			goto error;
1653 		}
1654 		elems[i].has_src_addr = has_src_addr;
1655 	}
1656 
1657 	/* Sort the addresses, and rearrange the linked list so it matches the sorted order. */
1658 	qsort((void *)elems, nelem, sizeof(struct addrinfo_sort_elem), _rfc3484_compare);
1659 
1660 	list_sentinel->ai_next = elems[0].ai;
1661 	for (i = 0; i < nelem - 1; ++i) {
1662 		elems[i].ai->ai_next = elems[i + 1].ai;
1663 	}
1664 	elems[nelem - 1].ai->ai_next = NULL;
1665 
1666 error:
1667 	free(elems);
1668 }
1669 
1670 /*ARGSUSED*/
1671 static int
_dns_getaddrinfo(void * rv,void * cb_data,va_list ap)1672 _dns_getaddrinfo(void *rv, void	*cb_data, va_list ap)
1673 {
1674 	struct addrinfo *ai;
1675 	querybuf *buf, *buf2;
1676 	const char *name;
1677 	const struct addrinfo *pai;
1678 	struct addrinfo sentinel, *cur;
1679 	struct res_target q, q2;
1680 	res_state res;
1681 
1682 	name = va_arg(ap, char *);
1683 	pai = va_arg(ap, const struct addrinfo *);
1684 	//fprintf(stderr, "_dns_getaddrinfo() name = '%s'\n", name);
1685 
1686 	memset(&q, 0, sizeof(q));
1687 	memset(&q2, 0, sizeof(q2));
1688 	memset(&sentinel, 0, sizeof(sentinel));
1689 	cur = &sentinel;
1690 
1691 	buf = malloc(sizeof(*buf));
1692 	if (buf == NULL) {
1693 		h_errno = NETDB_INTERNAL;
1694 		return NS_NOTFOUND;
1695 	}
1696 	buf2 = malloc(sizeof(*buf2));
1697 	if (buf2 == NULL) {
1698 		free(buf);
1699 		h_errno = NETDB_INTERNAL;
1700 		return NS_NOTFOUND;
1701 	}
1702 
1703 	switch (pai->ai_family) {
1704 	case AF_UNSPEC:
1705 		/* prefer IPv6 */
1706 		q.name = name;
1707 		q.qclass = C_IN;
1708 		q.answer = buf->buf;
1709 		q.anslen = sizeof(buf->buf);
1710 		int query_ipv6 = 1, query_ipv4 = 1;
1711 		if (pai->ai_flags & AI_ADDRCONFIG) {
1712 			query_ipv6 = _have_ipv6();
1713 			query_ipv4 = _have_ipv4();
1714 		}
1715 		if (query_ipv6) {
1716 			q.qtype = T_AAAA;
1717 			if (query_ipv4) {
1718 				q.next = &q2;
1719 				q2.name = name;
1720 				q2.qclass = C_IN;
1721 				q2.qtype = T_A;
1722 				q2.answer = buf2->buf;
1723 				q2.anslen = sizeof(buf2->buf);
1724 			}
1725 		} else if (query_ipv4) {
1726 			q.qtype = T_A;
1727 		} else {
1728 			free(buf);
1729 			free(buf2);
1730 			return NS_NOTFOUND;
1731 		}
1732 		break;
1733 	case AF_INET:
1734 		q.name = name;
1735 		q.qclass = C_IN;
1736 		q.qtype = T_A;
1737 		q.answer = buf->buf;
1738 		q.anslen = sizeof(buf->buf);
1739 		break;
1740 	case AF_INET6:
1741 		q.name = name;
1742 		q.qclass = C_IN;
1743 		q.qtype = T_AAAA;
1744 		q.answer = buf->buf;
1745 		q.anslen = sizeof(buf->buf);
1746 		break;
1747 	default:
1748 		free(buf);
1749 		free(buf2);
1750 		return NS_UNAVAIL;
1751 	}
1752 
1753 	res = __res_get_state();
1754 	if (res == NULL) {
1755 		free(buf);
1756 		free(buf2);
1757 		return NS_NOTFOUND;
1758 	}
1759 
1760 	if (res_searchN(name, &q, res) < 0) {
1761 		__res_put_state(res);
1762 		free(buf);
1763 		free(buf2);
1764 		return NS_NOTFOUND;
1765 	}
1766 	ai = getanswer(buf, q.n, q.name, q.qtype, pai);
1767 	if (ai) {
1768 		cur->ai_next = ai;
1769 		while (cur && cur->ai_next)
1770 			cur = cur->ai_next;
1771 	}
1772 	if (q.next) {
1773 		ai = getanswer(buf2, q2.n, q2.name, q2.qtype, pai);
1774 		if (ai)
1775 			cur->ai_next = ai;
1776 	}
1777 	free(buf);
1778 	free(buf2);
1779 	if (sentinel.ai_next == NULL) {
1780 		__res_put_state(res);
1781 		switch (h_errno) {
1782 		case HOST_NOT_FOUND:
1783 			return NS_NOTFOUND;
1784 		case TRY_AGAIN:
1785 			return NS_TRYAGAIN;
1786 		default:
1787 			return NS_UNAVAIL;
1788 		}
1789 	}
1790 
1791 	_rfc3484_sort(&sentinel);
1792 
1793 	__res_put_state(res);
1794 
1795 	*((struct addrinfo **)rv) = sentinel.ai_next;
1796 	return NS_SUCCESS;
1797 }
1798 
1799 static void
_sethtent(FILE ** hostf)1800 _sethtent(FILE **hostf)
1801 {
1802 
1803 	if (!*hostf)
1804 		*hostf = fopen(_PATH_HOSTS, "r" );
1805 	else
1806 		rewind(*hostf);
1807 }
1808 
1809 static void
_endhtent(FILE ** hostf)1810 _endhtent(FILE **hostf)
1811 {
1812 
1813 	if (*hostf) {
1814 		(void) fclose(*hostf);
1815 		*hostf = NULL;
1816 	}
1817 }
1818 
1819 static struct addrinfo *
_gethtent(FILE ** hostf,const char * name,const struct addrinfo * pai)1820 _gethtent(FILE **hostf, const char *name, const struct addrinfo *pai)
1821 {
1822 	char *p;
1823 	char *cp, *tname, *cname;
1824 	struct addrinfo hints, *res0, *res;
1825 	int error;
1826 	const char *addr;
1827 	char hostbuf[8*1024];
1828 
1829 //	fprintf(stderr, "_gethtent() name = '%s'\n", name);
1830 	assert(name != NULL);
1831 	assert(pai != NULL);
1832 
1833 	if (!*hostf && !(*hostf = fopen(_PATH_HOSTS, "r" )))
1834 		return (NULL);
1835  again:
1836 	if (!(p = fgets(hostbuf, sizeof hostbuf, *hostf)))
1837 		return (NULL);
1838 	if (*p == '#')
1839 		goto again;
1840 	if (!(cp = strpbrk(p, "#\n")))
1841 		goto again;
1842 	*cp = '\0';
1843 	if (!(cp = strpbrk(p, " \t")))
1844 		goto again;
1845 	*cp++ = '\0';
1846 	addr = p;
1847 	/* if this is not something we're looking for, skip it. */
1848 	cname = NULL;
1849 	while (cp && *cp) {
1850 		if (*cp == ' ' || *cp == '\t') {
1851 			cp++;
1852 			continue;
1853 		}
1854 		if (!cname)
1855 			cname = cp;
1856 		tname = cp;
1857 		if ((cp = strpbrk(cp, " \t")) != NULL)
1858 			*cp++ = '\0';
1859 //		fprintf(stderr, "\ttname = '%s'", tname);
1860 		if (strcasecmp(name, tname) == 0)
1861 			goto found;
1862 	}
1863 	goto again;
1864 
1865 found:
1866 	hints = *pai;
1867 	hints.ai_flags = AI_NUMERICHOST;
1868 	error = getaddrinfo(addr, NULL, &hints, &res0);
1869 	if (error)
1870 		goto again;
1871 	for (res = res0; res; res = res->ai_next) {
1872 		/* cover it up */
1873 		res->ai_flags = pai->ai_flags;
1874 
1875 		if (pai->ai_flags & AI_CANONNAME) {
1876 			if (get_canonname(pai, res, cname) != 0) {
1877 				freeaddrinfo(res0);
1878 				goto again;
1879 			}
1880 		}
1881 	}
1882 	return res0;
1883 }
1884 
1885 /*ARGSUSED*/
1886 static int
_files_getaddrinfo(void * rv,void * cb_data,va_list ap)1887 _files_getaddrinfo(void *rv, void *cb_data, va_list ap)
1888 {
1889 	const char *name;
1890 	const struct addrinfo *pai;
1891 	struct addrinfo sentinel, *cur;
1892 	struct addrinfo *p;
1893 	FILE *hostf = NULL;
1894 
1895 	name = va_arg(ap, char *);
1896 	pai = va_arg(ap, struct addrinfo *);
1897 
1898 //	fprintf(stderr, "_files_getaddrinfo() name = '%s'\n", name);
1899 	memset(&sentinel, 0, sizeof(sentinel));
1900 	cur = &sentinel;
1901 
1902 	_sethtent(&hostf);
1903 	while ((p = _gethtent(&hostf, name, pai)) != NULL) {
1904 		cur->ai_next = p;
1905 		while (cur && cur->ai_next)
1906 			cur = cur->ai_next;
1907 	}
1908 	_endhtent(&hostf);
1909 
1910 	*((struct addrinfo **)rv) = sentinel.ai_next;
1911 	if (sentinel.ai_next == NULL)
1912 		return NS_NOTFOUND;
1913 	return NS_SUCCESS;
1914 }
1915 
1916 /* resolver logic */
1917 
1918 /*
1919  * Formulate a normal query, send, and await answer.
1920  * Returned answer is placed in supplied buffer "answer".
1921  * Perform preliminary check of answer, returning success only
1922  * if no error is indicated and the answer count is nonzero.
1923  * Return the size of the response on success, -1 on error.
1924  * Error number is left in h_errno.
1925  *
1926  * Caller must parse answer and determine whether it answers the question.
1927  */
1928 static int
res_queryN(const char * name,struct res_target * target,res_state res)1929 res_queryN(const char *name, /* domain name */ struct res_target *target,
1930     res_state res)
1931 {
1932 	u_char buf[MAXPACKET];
1933 	HEADER *hp;
1934 	int n;
1935 	struct res_target *t;
1936 	int rcode;
1937 	int ancount;
1938 
1939 	assert(name != NULL);
1940 	/* XXX: target may be NULL??? */
1941 
1942 	rcode = NOERROR;
1943 	ancount = 0;
1944 
1945 	for (t = target; t; t = t->next) {
1946 		int class, type;
1947 		u_char *answer;
1948 		int anslen;
1949 
1950 		hp = (HEADER *)(void *)t->answer;
1951 		hp->rcode = NOERROR;	/* default */
1952 
1953 		/* make it easier... */
1954 		class = t->qclass;
1955 		type = t->qtype;
1956 		answer = t->answer;
1957 		anslen = t->anslen;
1958 #ifdef DEBUG
1959 		if (res->options & RES_DEBUG)
1960 			printf(";; res_nquery(%s, %d, %d)\n", name, class, type);
1961 #endif
1962 
1963 		n = res_nmkquery(res, QUERY, name, class, type, NULL, 0, NULL,
1964 		    buf, sizeof(buf));
1965 #ifdef RES_USE_EDNS0
1966 		if (n > 0 && (res->options & RES_USE_EDNS0) != 0)
1967 			n = res_nopt(res, n, buf, sizeof(buf), anslen);
1968 #endif
1969 		if (n <= 0) {
1970 #ifdef DEBUG
1971 			if (res->options & RES_DEBUG)
1972 				printf(";; res_nquery: mkquery failed\n");
1973 #endif
1974 			h_errno = NO_RECOVERY;
1975 			return n;
1976 		}
1977 		n = res_nsend(res, buf, n, answer, anslen);
1978 #if 0
1979 		if (n < 0) {
1980 #ifdef DEBUG
1981 			if (res->options & RES_DEBUG)
1982 				printf(";; res_query: send error\n");
1983 #endif
1984 			h_errno = TRY_AGAIN;
1985 			return n;
1986 		}
1987 #endif
1988 
1989 		if (n < 0 || hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
1990 			rcode = hp->rcode;	/* record most recent error */
1991 #ifdef DEBUG
1992 			if (res->options & RES_DEBUG)
1993 				printf(";; rcode = %u, ancount=%u\n", hp->rcode,
1994 				    ntohs(hp->ancount));
1995 #endif
1996 			continue;
1997 		}
1998 
1999 		ancount += ntohs(hp->ancount);
2000 
2001 		t->n = n;
2002 	}
2003 
2004 	if (ancount == 0) {
2005 		switch (rcode) {
2006 		case NXDOMAIN:
2007 			h_errno = HOST_NOT_FOUND;
2008 			break;
2009 		case SERVFAIL:
2010 			h_errno = TRY_AGAIN;
2011 			break;
2012 		case NOERROR:
2013 			h_errno = NO_DATA;
2014 			break;
2015 		case FORMERR:
2016 		case NOTIMP:
2017 		case REFUSED:
2018 		default:
2019 			h_errno = NO_RECOVERY;
2020 			break;
2021 		}
2022 		return -1;
2023 	}
2024 	return ancount;
2025 }
2026 
2027 /*
2028  * Formulate a normal query, send, and retrieve answer in supplied buffer.
2029  * Return the size of the response on success, -1 on error.
2030  * If enabled, implement search rules until answer or unrecoverable failure
2031  * is detected.  Error code, if any, is left in h_errno.
2032  */
2033 static int
res_searchN(const char * name,struct res_target * target,res_state res)2034 res_searchN(const char *name, struct res_target *target, res_state res)
2035 {
2036 	const char *cp, * const *domain;
2037 	HEADER *hp;
2038 	u_int dots;
2039 	int trailing_dot, ret, saved_herrno;
2040 	int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
2041 
2042 	assert(name != NULL);
2043 	assert(target != NULL);
2044 
2045 	hp = (HEADER *)(void *)target->answer;	/*XXX*/
2046 
2047 	errno = 0;
2048 	h_errno = HOST_NOT_FOUND;	/* default, if we never query */
2049 	dots = 0;
2050 	for (cp = name; *cp; cp++)
2051 		dots += (*cp == '.');
2052 	trailing_dot = 0;
2053 	if (cp > name && *--cp == '.')
2054 		trailing_dot++;
2055 
2056 
2057         //fprintf(stderr, "res_searchN() name = '%s'\n", name);
2058 
2059 	/*
2060 	 * if there aren't any dots, it could be a user-level alias
2061 	 */
2062 	if (!dots && (cp = __hostalias(name)) != NULL) {
2063 		ret = res_queryN(cp, target, res);
2064 		return ret;
2065 	}
2066 
2067 	/*
2068 	 * If there are dots in the name already, let's just give it a try
2069 	 * 'as is'.  The threshold can be set with the "ndots" option.
2070 	 */
2071 	saved_herrno = -1;
2072 	if (dots >= res->ndots) {
2073 		ret = res_querydomainN(name, NULL, target, res);
2074 		if (ret > 0)
2075 			return (ret);
2076 		saved_herrno = h_errno;
2077 		tried_as_is++;
2078 	}
2079 
2080 	/*
2081 	 * We do at least one level of search if
2082 	 *	- there is no dot and RES_DEFNAME is set, or
2083 	 *	- there is at least one dot, there is no trailing dot,
2084 	 *	  and RES_DNSRCH is set.
2085 	 */
2086 	if ((!dots && (res->options & RES_DEFNAMES)) ||
2087 	    (dots && !trailing_dot && (res->options & RES_DNSRCH))) {
2088 		int done = 0;
2089 
2090 		for (domain = (const char * const *)res->dnsrch;
2091 		   *domain && !done;
2092 		   domain++) {
2093 
2094 			ret = res_querydomainN(name, *domain, target, res);
2095 			if (ret > 0)
2096 				return ret;
2097 
2098 			/*
2099 			 * If no server present, give up.
2100 			 * If name isn't found in this domain,
2101 			 * keep trying higher domains in the search list
2102 			 * (if that's enabled).
2103 			 * On a NO_DATA error, keep trying, otherwise
2104 			 * a wildcard entry of another type could keep us
2105 			 * from finding this entry higher in the domain.
2106 			 * If we get some other error (negative answer or
2107 			 * server failure), then stop searching up,
2108 			 * but try the input name below in case it's
2109 			 * fully-qualified.
2110 			 */
2111 			if (errno == ECONNREFUSED) {
2112 				h_errno = TRY_AGAIN;
2113 				return -1;
2114 			}
2115 
2116 			switch (h_errno) {
2117 			case NO_DATA:
2118 				got_nodata++;
2119 				/* FALLTHROUGH */
2120 			case HOST_NOT_FOUND:
2121 				/* keep trying */
2122 				break;
2123 			case TRY_AGAIN:
2124 				if (hp->rcode == SERVFAIL) {
2125 					/* try next search element, if any */
2126 					got_servfail++;
2127 					break;
2128 				}
2129 				/* FALLTHROUGH */
2130 			default:
2131 				/* anything else implies that we're done */
2132 				done++;
2133 			}
2134 			/*
2135 			 * if we got here for some reason other than DNSRCH,
2136 			 * we only wanted one iteration of the loop, so stop.
2137 			 */
2138 			if (!(res->options & RES_DNSRCH))
2139 			        done++;
2140 		}
2141 	}
2142 
2143 	/*
2144 	 * if we have not already tried the name "as is", do that now.
2145 	 * note that we do this regardless of how many dots were in the
2146 	 * name or whether it ends with a dot.
2147 	 */
2148 	if (!tried_as_is) {
2149 		ret = res_querydomainN(name, NULL, target, res);
2150 		if (ret > 0)
2151 			return ret;
2152 	}
2153 
2154 	/*
2155 	 * if we got here, we didn't satisfy the search.
2156 	 * if we did an initial full query, return that query's h_errno
2157 	 * (note that we wouldn't be here if that query had succeeded).
2158 	 * else if we ever got a nodata, send that back as the reason.
2159 	 * else send back meaningless h_errno, that being the one from
2160 	 * the last DNSRCH we did.
2161 	 */
2162 	if (saved_herrno != -1)
2163 		h_errno = saved_herrno;
2164 	else if (got_nodata)
2165 		h_errno = NO_DATA;
2166 	else if (got_servfail)
2167 		h_errno = TRY_AGAIN;
2168 	return -1;
2169 }
2170 
2171 /*
2172  * Perform a call on res_query on the concatenation of name and domain,
2173  * removing a trailing dot from name if domain is NULL.
2174  */
2175 static int
res_querydomainN(const char * name,const char * domain,struct res_target * target,res_state res)2176 res_querydomainN(const char *name, const char *domain,
2177     struct res_target *target, res_state res)
2178 {
2179 	char nbuf[MAXDNAME];
2180 	const char *longname = nbuf;
2181 	size_t n, d;
2182 
2183 	assert(name != NULL);
2184 	/* XXX: target may be NULL??? */
2185 
2186 #ifdef DEBUG
2187 	if (res->options & RES_DEBUG)
2188 		printf(";; res_querydomain(%s, %s)\n",
2189 			name, domain?domain:"<Nil>");
2190 #endif
2191 	if (domain == NULL) {
2192 		/*
2193 		 * Check for trailing '.';
2194 		 * copy without '.' if present.
2195 		 */
2196 		n = strlen(name);
2197 		if (n + 1 > sizeof(nbuf)) {
2198 			h_errno = NO_RECOVERY;
2199 			return -1;
2200 		}
2201 		if (n > 0 && name[--n] == '.') {
2202 			strncpy(nbuf, name, n);
2203 			nbuf[n] = '\0';
2204 		} else
2205 			longname = name;
2206 	} else {
2207 		n = strlen(name);
2208 		d = strlen(domain);
2209 		if (n + 1 + d + 1 > sizeof(nbuf)) {
2210 			h_errno = NO_RECOVERY;
2211 			return -1;
2212 		}
2213 		snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
2214 	}
2215 	return res_queryN(longname, target, res);
2216 }
2217