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