blob: 7e36c20b8f7b79a10db29cb110dc7adcaacb4a41 [file] [log] [blame]
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001/* $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
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -070080#include <fcntl.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080081#include <sys/cdefs.h>
82#include <sys/types.h>
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -070083#include <sys/stat.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080084#include <sys/param.h>
85#include <sys/socket.h>
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -070086#include <sys/un.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080087#include <net/if.h>
88#include <netinet/in.h>
89#include <arpa/inet.h>
Calin Juravle569fb982014-03-04 15:01:29 +000090#include <arpa/nameser.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080091#include <assert.h>
92#include <ctype.h>
93#include <errno.h>
94#include <netdb.h>
Sreeram Ramachandran57a26272014-05-19 10:21:39 -070095#include "NetdClientDispatch.h"
Szymon Jakubczakea9bf672014-02-14 17:07:23 -050096#include "resolv_cache.h"
97#include "resolv_netid.h"
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080098#include "resolv_private.h"
Robert Greenwalt1d8d9a32013-08-02 15:24:45 -070099#include <stdbool.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800100#include <stddef.h>
101#include <stdio.h>
102#include <stdlib.h>
103#include <string.h>
Carl Shapiro2cc2b2b2011-03-21 20:01:03 -0700104#include <strings.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800105#include <unistd.h>
106
107#include <syslog.h>
108#include <stdarg.h>
109#include "nsswitch.h"
110
Brad Fitzpatrick78585642010-10-28 13:22:20 -0700111#ifdef ANDROID_CHANGES
112#include <sys/system_properties.h>
113#endif /* ANDROID_CHANGES */
114
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -0700115typedef union sockaddr_union {
116 struct sockaddr generic;
117 struct sockaddr_in in;
118 struct sockaddr_in6 in6;
119} sockaddr_union;
120
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800121#define SUCCESS 0
122#define ANY 0
123#define YES 1
124#define NO 0
125
126static const char in_addrany[] = { 0, 0, 0, 0 };
127static const char in_loopback[] = { 127, 0, 0, 1 };
128#ifdef INET6
129static const char in6_addrany[] = {
130 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
131};
132static const char in6_loopback[] = {
133 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
134};
135#endif
136
Selim Gurun06e18312012-02-27 15:58:54 -0800137// This should be synchronized to ResponseCode.h
138static const int DnsProxyQueryResult = 222;
139
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800140static const struct afd {
141 int a_af;
142 int a_addrlen;
143 int a_socklen;
144 int a_off;
145 const char *a_addrany;
146 const char *a_loopback;
147 int a_scoped;
148} afdl [] = {
149#ifdef INET6
150 {PF_INET6, sizeof(struct in6_addr),
151 sizeof(struct sockaddr_in6),
152 offsetof(struct sockaddr_in6, sin6_addr),
153 in6_addrany, in6_loopback, 1},
154#endif
155 {PF_INET, sizeof(struct in_addr),
156 sizeof(struct sockaddr_in),
157 offsetof(struct sockaddr_in, sin_addr),
158 in_addrany, in_loopback, 0},
159 {0, 0, 0, 0, NULL, NULL, 0},
160};
161
162struct explore {
163 int e_af;
164 int e_socktype;
165 int e_protocol;
166 const char *e_protostr;
167 int e_wild;
168#define WILD_AF(ex) ((ex)->e_wild & 0x01)
169#define WILD_SOCKTYPE(ex) ((ex)->e_wild & 0x02)
170#define WILD_PROTOCOL(ex) ((ex)->e_wild & 0x04)
171};
172
173static const struct explore explore[] = {
174#if 0
175 { PF_LOCAL, 0, ANY, ANY, NULL, 0x01 },
176#endif
177#ifdef INET6
178 { PF_INET6, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
179 { PF_INET6, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
180 { PF_INET6, SOCK_RAW, ANY, NULL, 0x05 },
181#endif
182 { PF_INET, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
183 { PF_INET, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
184 { PF_INET, SOCK_RAW, ANY, NULL, 0x05 },
185 { PF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
186 { PF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
187 { PF_UNSPEC, SOCK_RAW, ANY, NULL, 0x05 },
188 { -1, 0, 0, NULL, 0 },
189};
190
191#ifdef INET6
192#define PTON_MAX 16
193#else
194#define PTON_MAX 4
195#endif
196
197static const ns_src default_dns_files[] = {
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700198 { NSSRC_FILES, NS_SUCCESS },
199 { NSSRC_DNS, NS_SUCCESS },
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800200 { 0, 0 }
201};
202
203#define MAXPACKET (64*1024)
204
205typedef union {
206 HEADER hdr;
207 u_char buf[MAXPACKET];
208} querybuf;
209
210struct res_target {
211 struct res_target *next;
212 const char *name; /* domain name */
213 int qclass, qtype; /* class and type of query */
214 u_char *answer; /* buffer to put answer */
215 int anslen; /* size of answer buffer */
216 int n; /* result length */
217};
218
219static int str2number(const char *);
220static int explore_fqdn(const struct addrinfo *, const char *,
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500221 const char *, struct addrinfo **, unsigned netid, unsigned mark);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800222static int explore_null(const struct addrinfo *,
223 const char *, struct addrinfo **);
224static int explore_numeric(const struct addrinfo *, const char *,
225 const char *, struct addrinfo **, const char *);
226static int explore_numeric_scope(const struct addrinfo *, const char *,
227 const char *, struct addrinfo **);
228static int get_canonname(const struct addrinfo *,
229 struct addrinfo *, const char *);
230static struct addrinfo *get_ai(const struct addrinfo *,
231 const struct afd *, const char *);
232static int get_portmatch(const struct addrinfo *, const char *);
233static int get_port(const struct addrinfo *, const char *, int);
234static const struct afd *find_afd(int);
235#ifdef INET6
236static int ip6_str2scopeid(char *, struct sockaddr_in6 *, u_int32_t *);
237#endif
238
239static struct addrinfo *getanswer(const querybuf *, int, const char *, int,
240 const struct addrinfo *);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800241static int _dns_getaddrinfo(void *, void *, va_list);
242static void _sethtent(FILE **);
243static void _endhtent(FILE **);
244static struct addrinfo *_gethtent(FILE **, const char *,
245 const struct addrinfo *);
246static int _files_getaddrinfo(void *, void *, va_list);
247
248static int res_queryN(const char *, struct res_target *, res_state);
249static int res_searchN(const char *, struct res_target *, res_state);
250static int res_querydomainN(const char *, const char *,
251 struct res_target *, res_state);
252
253static const char * const ai_errlist[] = {
254 "Success",
255 "Address family for hostname not supported", /* EAI_ADDRFAMILY */
256 "Temporary failure in name resolution", /* EAI_AGAIN */
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700257 "Invalid value for ai_flags", /* EAI_BADFLAGS */
258 "Non-recoverable failure in name resolution", /* EAI_FAIL */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800259 "ai_family not supported", /* EAI_FAMILY */
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700260 "Memory allocation failure", /* EAI_MEMORY */
261 "No address associated with hostname", /* EAI_NODATA */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800262 "hostname nor servname provided, or not known", /* EAI_NONAME */
263 "servname not supported for ai_socktype", /* EAI_SERVICE */
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700264 "ai_socktype not supported", /* EAI_SOCKTYPE */
265 "System error returned in errno", /* EAI_SYSTEM */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800266 "Invalid value for hints", /* EAI_BADHINTS */
267 "Resolved protocol is unknown", /* EAI_PROTOCOL */
268 "Argument buffer overflow", /* EAI_OVERFLOW */
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700269 "Unknown error", /* EAI_MAX */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800270};
271
272/* XXX macros that make external reference is BAD. */
273
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700274#define GET_AI(ai, afd, addr) \
275do { \
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 } \
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800282} while (/*CONSTCOND*/0)
283
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700284#define GET_PORT(ai, serv) \
285do { \
286 /* external reference: error and label free */ \
287 error = get_port((ai), (serv), 0); \
288 if (error != 0) \
289 goto free; \
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800290} while (/*CONSTCOND*/0)
291
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700292#define GET_CANONNAME(ai, str) \
293do { \
294 /* external reference: pai, error and label free */ \
295 error = get_canonname(pai, (ai), (str)); \
296 if (error != 0) \
297 goto free; \
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800298} while (/*CONSTCOND*/0)
299
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700300#define ERR(err) \
301do { \
302 /* external reference: error, and label bad */ \
303 error = (err); \
304 goto bad; \
305 /*NOTREACHED*/ \
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800306} while (/*CONSTCOND*/0)
307
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700308#define MATCH_FAMILY(x, y, w) \
309 ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC || \
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800310 (y) == PF_UNSPEC)))
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700311#define MATCH(x, y, w) \
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800312 ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY)))
313
314const char *
315gai_strerror(int ecode)
316{
317 if (ecode < 0 || ecode > EAI_MAX)
318 ecode = EAI_MAX;
319 return ai_errlist[ecode];
320}
321
322void
323freeaddrinfo(struct addrinfo *ai)
324{
325 struct addrinfo *next;
326
327 assert(ai != NULL);
328
329 do {
330 next = ai->ai_next;
331 if (ai->ai_canonname)
332 free(ai->ai_canonname);
333 /* no need to free(ai->ai_addr) */
334 free(ai);
335 ai = next;
336 } while (ai);
337}
338
339static int
340str2number(const char *p)
341{
342 char *ep;
343 unsigned long v;
344
345 assert(p != NULL);
346
347 if (*p == '\0')
348 return -1;
349 ep = NULL;
350 errno = 0;
351 v = strtoul(p, &ep, 10);
352 if (errno == 0 && ep && *ep == '\0' && v <= UINT_MAX)
353 return v;
354 else
355 return -1;
356}
357
Lorenzo Colittiba96e302011-01-14 12:26:05 -0800358/*
359 * Connect a UDP socket to a given unicast address. This will cause no network
360 * traffic, but will fail fast if the system has no or limited reachability to
361 * the destination (e.g., no IPv4 address, no IPv6 default route, ...).
362 */
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -0700363static int
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500364_test_connect(int pf, struct sockaddr *addr, size_t addrlen, unsigned mark) {
Nick Kralevich1781ed72014-06-29 20:46:17 -0700365 int s = socket(pf, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -0700366 if (s < 0)
367 return 0;
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500368 if (mark != MARK_UNSET && setsockopt(s, SOL_SOCKET, SO_MARK, &mark, sizeof(mark)) < 0)
369 return 0;
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -0700370 int ret;
371 do {
Paul Jensen31ad0372014-05-29 16:28:30 -0400372 ret = __connect(s, addr, addrlen);
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -0700373 } while (ret < 0 && errno == EINTR);
Lorenzo Colittiba96e302011-01-14 12:26:05 -0800374 int success = (ret == 0);
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -0700375 do {
376 ret = close(s);
377 } while (ret < 0 && errno == EINTR);
Lorenzo Colittiba96e302011-01-14 12:26:05 -0800378 return success;
379}
380
381/*
382 * The following functions determine whether IPv4 or IPv6 connectivity is
383 * available in order to implement AI_ADDRCONFIG.
384 *
385 * Strictly speaking, AI_ADDRCONFIG should not look at whether connectivity is
386 * available, but whether addresses of the specified family are "configured
387 * on the local system". However, bionic doesn't currently support getifaddrs,
388 * so checking for connectivity is the next best thing.
389 */
390static int
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500391_have_ipv6(unsigned mark) {
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700392 static const struct sockaddr_in6 sin6_test = {
393 .sin6_family = AF_INET6,
394 .sin6_addr.s6_addr = { // 2000::
395 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
396 };
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500397 sockaddr_union addr = { .in6 = sin6_test };
398 return _test_connect(PF_INET6, &addr.generic, sizeof(addr.in6), mark);
Lorenzo Colittiba96e302011-01-14 12:26:05 -0800399}
400
401static int
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500402_have_ipv4(unsigned mark) {
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700403 static const struct sockaddr_in sin_test = {
404 .sin_family = AF_INET,
405 .sin_addr.s_addr = __constant_htonl(0x08080808L) // 8.8.8.8
406 };
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500407 sockaddr_union addr = { .in = sin_test };
408 return _test_connect(PF_INET, &addr.generic, sizeof(addr.in), mark);
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -0700409}
410
Mattias Falkc63e5902011-08-23 14:34:14 +0200411// Returns 0 on success, else returns on error.
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700412static int
413android_getaddrinfo_proxy(
414 const char *hostname, const char *servname,
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500415 const struct addrinfo *hints, struct addrinfo **res, unsigned netid)
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700416{
417 int sock;
418 const int one = 1;
419 struct sockaddr_un proxy_addr;
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700420 FILE* proxy = NULL;
421 int success = 0;
422
423 // Clear this at start, as we use its non-NULLness later (in the
424 // error path) to decide if we have to free up any memory we
425 // allocated in the process (before failing).
426 *res = NULL;
427
Mattias Falkc63e5902011-08-23 14:34:14 +0200428 // Bogus things we can't serialize. Don't use the proxy. These will fail - let them.
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700429 if ((hostname != NULL &&
430 strcspn(hostname, " \n\r\t^'\"") != strlen(hostname)) ||
431 (servname != NULL &&
432 strcspn(servname, " \n\r\t^'\"") != strlen(servname))) {
Mattias Falkc63e5902011-08-23 14:34:14 +0200433 return EAI_NODATA;
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700434 }
435
Nick Kralevich1781ed72014-06-29 20:46:17 -0700436 sock = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700437 if (sock < 0) {
Mattias Falkc63e5902011-08-23 14:34:14 +0200438 return EAI_NODATA;
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700439 }
440
441 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
442 memset(&proxy_addr, 0, sizeof(proxy_addr));
443 proxy_addr.sun_family = AF_UNIX;
444 strlcpy(proxy_addr.sun_path, "/dev/socket/dnsproxyd",
445 sizeof(proxy_addr.sun_path));
446 if (TEMP_FAILURE_RETRY(connect(sock,
447 (const struct sockaddr*) &proxy_addr,
448 sizeof(proxy_addr))) != 0) {
449 close(sock);
Mattias Falkc63e5902011-08-23 14:34:14 +0200450 return EAI_NODATA;
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700451 }
452
Paul Jensen559c7842014-05-15 14:43:07 -0400453 netid = __netdClientDispatch.netIdForResolv(netid);
454
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700455 // Send the request.
456 proxy = fdopen(sock, "r+");
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500457 if (fprintf(proxy, "getaddrinfo %s %s %d %d %d %d %u",
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700458 hostname == NULL ? "^" : hostname,
459 servname == NULL ? "^" : servname,
460 hints == NULL ? -1 : hints->ai_flags,
461 hints == NULL ? -1 : hints->ai_family,
462 hints == NULL ? -1 : hints->ai_socktype,
Mattias Falkc63e5902011-08-23 14:34:14 +0200463 hints == NULL ? -1 : hints->ai_protocol,
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500464 netid) < 0) {
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700465 goto exit;
466 }
467 // literal NULL byte at end, required by FrameworkListener
468 if (fputc(0, proxy) == EOF ||
469 fflush(proxy) != 0) {
470 goto exit;
471 }
472
Robert Greenwaltc59ba452012-03-09 11:34:27 -0800473 char buf[4];
Selim Gurun06e18312012-02-27 15:58:54 -0800474 // read result code for gethostbyaddr
475 if (fread(buf, 1, sizeof(buf), proxy) != sizeof(buf)) {
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700476 goto exit;
477 }
478
Selim Gurun06e18312012-02-27 15:58:54 -0800479 int result_code = (int)strtol(buf, NULL, 10);
480 // verify the code itself
481 if (result_code != DnsProxyQueryResult ) {
Mattias Falkc63e5902011-08-23 14:34:14 +0200482 fread(buf, 1, sizeof(buf), proxy);
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700483 goto exit;
484 }
485
486 struct addrinfo* ai = NULL;
487 struct addrinfo** nextres = res;
488 while (1) {
489 uint32_t addrinfo_len;
490 if (fread(&addrinfo_len, sizeof(addrinfo_len),
491 1, proxy) != 1) {
492 break;
493 }
494 addrinfo_len = ntohl(addrinfo_len);
495 if (addrinfo_len == 0) {
496 success = 1;
497 break;
498 }
499
500 if (addrinfo_len < sizeof(struct addrinfo)) {
501 break;
502 }
503 struct addrinfo* ai = calloc(1, addrinfo_len +
504 sizeof(struct sockaddr_storage));
505 if (ai == NULL) {
506 break;
507 }
508
509 if (fread(ai, addrinfo_len, 1, proxy) != 1) {
510 // Error; fall through.
511 break;
512 }
513
514 // Zero out the pointer fields we copied which aren't
515 // valid in this address space.
516 ai->ai_addr = NULL;
517 ai->ai_canonname = NULL;
518 ai->ai_next = NULL;
519
520 // struct sockaddr
521 uint32_t addr_len;
522 if (fread(&addr_len, sizeof(addr_len), 1, proxy) != 1) {
523 break;
524 }
525 addr_len = ntohl(addr_len);
526 if (addr_len != 0) {
527 if (addr_len > sizeof(struct sockaddr_storage)) {
528 // Bogus; too big.
529 break;
530 }
531 struct sockaddr* addr = (struct sockaddr*)(ai + 1);
532 if (fread(addr, addr_len, 1, proxy) != 1) {
533 break;
534 }
535 ai->ai_addr = addr;
536 }
537
538 // cannonname
539 uint32_t name_len;
540 if (fread(&name_len, sizeof(name_len), 1, proxy) != 1) {
541 break;
542 }
Mattias Falk0ee092f2011-02-15 08:44:20 +0100543 name_len = ntohl(name_len);
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700544 if (name_len != 0) {
545 ai->ai_canonname = (char*) malloc(name_len);
546 if (fread(ai->ai_canonname, name_len, 1, proxy) != 1) {
547 break;
548 }
549 if (ai->ai_canonname[name_len - 1] != '\0') {
550 // The proxy should be returning this
551 // NULL-terminated.
552 break;
553 }
554 }
555
556 *nextres = ai;
557 nextres = &ai->ai_next;
558 ai = NULL;
559 }
560
561 if (ai != NULL) {
562 // Clean up partially-built addrinfo that we never ended up
563 // attaching to the response.
564 freeaddrinfo(ai);
565 }
566exit:
567 if (proxy != NULL) {
568 fclose(proxy);
569 }
570
571 if (success) {
572 return 0;
573 }
574
Mattias Falkc63e5902011-08-23 14:34:14 +0200575 // Proxy failed;
576 // clean up memory we might've allocated.
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700577 if (*res) {
578 freeaddrinfo(*res);
579 *res = NULL;
580 }
Mattias Falkc63e5902011-08-23 14:34:14 +0200581 return EAI_NODATA;
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700582}
583
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800584int
585getaddrinfo(const char *hostname, const char *servname,
586 const struct addrinfo *hints, struct addrinfo **res)
587{
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500588 return android_getaddrinfofornet(hostname, servname, hints, NETID_UNSET, MARK_UNSET, res);
Mattias Falkc63e5902011-08-23 14:34:14 +0200589}
590
591int
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500592android_getaddrinfofornet(const char *hostname, const char *servname,
593 const struct addrinfo *hints, unsigned netid, unsigned mark, struct addrinfo **res)
Mattias Falkc63e5902011-08-23 14:34:14 +0200594{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800595 struct addrinfo sentinel;
596 struct addrinfo *cur;
597 int error = 0;
598 struct addrinfo ai;
599 struct addrinfo ai0;
600 struct addrinfo *pai;
601 const struct explore *ex;
Mattias Falkc63e5902011-08-23 14:34:14 +0200602 const char* cache_mode = getenv("ANDROID_DNS_MODE");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800603
604 /* hostname is allowed to be NULL */
605 /* servname is allowed to be NULL */
606 /* hints is allowed to be NULL */
607 assert(res != NULL);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800608 memset(&sentinel, 0, sizeof(sentinel));
609 cur = &sentinel;
610 pai = &ai;
611 pai->ai_flags = 0;
612 pai->ai_family = PF_UNSPEC;
613 pai->ai_socktype = ANY;
614 pai->ai_protocol = ANY;
615 pai->ai_addrlen = 0;
616 pai->ai_canonname = NULL;
617 pai->ai_addr = NULL;
618 pai->ai_next = NULL;
619
620 if (hostname == NULL && servname == NULL)
621 return EAI_NONAME;
622 if (hints) {
623 /* error check for hints */
624 if (hints->ai_addrlen || hints->ai_canonname ||
625 hints->ai_addr || hints->ai_next)
626 ERR(EAI_BADHINTS); /* xxx */
627 if (hints->ai_flags & ~AI_MASK)
628 ERR(EAI_BADFLAGS);
629 switch (hints->ai_family) {
630 case PF_UNSPEC:
631 case PF_INET:
632#ifdef INET6
633 case PF_INET6:
634#endif
635 break;
636 default:
637 ERR(EAI_FAMILY);
638 }
639 memcpy(pai, hints, sizeof(*pai));
640
641 /*
642 * if both socktype/protocol are specified, check if they
643 * are meaningful combination.
644 */
645 if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
646 for (ex = explore; ex->e_af >= 0; ex++) {
647 if (pai->ai_family != ex->e_af)
648 continue;
649 if (ex->e_socktype == ANY)
650 continue;
651 if (ex->e_protocol == ANY)
652 continue;
653 if (pai->ai_socktype == ex->e_socktype
654 && pai->ai_protocol != ex->e_protocol) {
655 ERR(EAI_BADHINTS);
656 }
657 }
658 }
659 }
660
661 /*
662 * check for special cases. (1) numeric servname is disallowed if
663 * socktype/protocol are left unspecified. (2) servname is disallowed
664 * for raw and other inet{,6} sockets.
665 */
666 if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
667#ifdef PF_INET6
668 || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
669#endif
670 ) {
671 ai0 = *pai; /* backup *pai */
672
673 if (pai->ai_family == PF_UNSPEC) {
674#ifdef PF_INET6
675 pai->ai_family = PF_INET6;
676#else
677 pai->ai_family = PF_INET;
678#endif
679 }
680 error = get_portmatch(pai, servname);
681 if (error)
682 ERR(error);
683
684 *pai = ai0;
685 }
686
687 ai0 = *pai;
688
689 /* NULL hostname, or numeric hostname */
690 for (ex = explore; ex->e_af >= 0; ex++) {
691 *pai = ai0;
692
693 /* PF_UNSPEC entries are prepared for DNS queries only */
694 if (ex->e_af == PF_UNSPEC)
695 continue;
696
697 if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
698 continue;
699 if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex)))
700 continue;
701 if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex)))
702 continue;
703
704 if (pai->ai_family == PF_UNSPEC)
705 pai->ai_family = ex->e_af;
706 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
707 pai->ai_socktype = ex->e_socktype;
708 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
709 pai->ai_protocol = ex->e_protocol;
710
711 if (hostname == NULL)
712 error = explore_null(pai, servname, &cur->ai_next);
713 else
714 error = explore_numeric_scope(pai, hostname, servname,
715 &cur->ai_next);
716
717 if (error)
718 goto free;
719
720 while (cur->ai_next)
721 cur = cur->ai_next;
722 }
723
724 /*
725 * XXX
726 * If numeric representation of AF1 can be interpreted as FQDN
727 * representation of AF2, we need to think again about the code below.
728 */
729 if (sentinel.ai_next)
730 goto good;
731
732 if (hostname == NULL)
733 ERR(EAI_NODATA);
734 if (pai->ai_flags & AI_NUMERICHOST)
735 ERR(EAI_NONAME);
736
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700737 /*
738 * BEGIN ANDROID CHANGES; proxying to the cache
739 */
Mattias Falkc63e5902011-08-23 14:34:14 +0200740 if (cache_mode == NULL || strcmp(cache_mode, "local") != 0) {
741 // we're not the proxy - pass the request to them
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500742 return android_getaddrinfo_proxy(hostname, servname, hints, res, netid);
Mattias Falkc63e5902011-08-23 14:34:14 +0200743 }
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700744
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800745 /*
746 * hostname as alphabetical name.
747 * we would like to prefer AF_INET6 than AF_INET, so we'll make a
748 * outer loop by AFs.
749 */
750 for (ex = explore; ex->e_af >= 0; ex++) {
751 *pai = ai0;
752
753 /* require exact match for family field */
754 if (pai->ai_family != ex->e_af)
755 continue;
756
757 if (!MATCH(pai->ai_socktype, ex->e_socktype,
758 WILD_SOCKTYPE(ex))) {
759 continue;
760 }
761 if (!MATCH(pai->ai_protocol, ex->e_protocol,
762 WILD_PROTOCOL(ex))) {
763 continue;
764 }
765
766 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
767 pai->ai_socktype = ex->e_socktype;
768 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
769 pai->ai_protocol = ex->e_protocol;
770
771 error = explore_fqdn(pai, hostname, servname,
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500772 &cur->ai_next, netid, mark);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800773
774 while (cur && cur->ai_next)
775 cur = cur->ai_next;
776 }
777
778 /* XXX */
779 if (sentinel.ai_next)
780 error = 0;
781
782 if (error)
783 goto free;
784 if (error == 0) {
785 if (sentinel.ai_next) {
786 good:
787 *res = sentinel.ai_next;
788 return SUCCESS;
789 } else
790 error = EAI_FAIL;
791 }
792 free:
793 bad:
794 if (sentinel.ai_next)
795 freeaddrinfo(sentinel.ai_next);
796 *res = NULL;
797 return error;
798}
799
800/*
801 * FQDN hostname, DNS lookup
802 */
803static int
804explore_fqdn(const struct addrinfo *pai, const char *hostname,
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500805 const char *servname, struct addrinfo **res, unsigned netid, unsigned mark)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800806{
807 struct addrinfo *result;
808 struct addrinfo *cur;
809 int error = 0;
810 static const ns_dtab dtab[] = {
811 NS_FILES_CB(_files_getaddrinfo, NULL)
812 { NSSRC_DNS, _dns_getaddrinfo, NULL }, /* force -DHESIOD */
813 NS_NIS_CB(_yp_getaddrinfo, NULL)
814 { 0, 0, 0 }
815 };
816
817 assert(pai != NULL);
818 /* hostname may be NULL */
819 /* servname may be NULL */
820 assert(res != NULL);
821
822 result = NULL;
823
824 /*
825 * if the servname does not match socktype/protocol, ignore it.
826 */
827 if (get_portmatch(pai, servname) != 0)
828 return 0;
829
830 switch (nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500831 default_dns_files, hostname, pai, netid, mark)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800832 case NS_TRYAGAIN:
833 error = EAI_AGAIN;
834 goto free;
835 case NS_UNAVAIL:
836 error = EAI_FAIL;
837 goto free;
838 case NS_NOTFOUND:
839 error = EAI_NODATA;
840 goto free;
841 case NS_SUCCESS:
842 error = 0;
843 for (cur = result; cur; cur = cur->ai_next) {
844 GET_PORT(cur, servname);
845 /* canonname should be filled already */
846 }
847 break;
848 }
849
850 *res = result;
851
852 return 0;
853
854free:
855 if (result)
856 freeaddrinfo(result);
857 return error;
858}
859
860/*
861 * hostname == NULL.
862 * passive socket -> anyaddr (0.0.0.0 or ::)
863 * non-passive socket -> localhost (127.0.0.1 or ::1)
864 */
865static int
866explore_null(const struct addrinfo *pai, const char *servname,
867 struct addrinfo **res)
868{
869 int s;
870 const struct afd *afd;
871 struct addrinfo *cur;
872 struct addrinfo sentinel;
873 int error;
874
875 assert(pai != NULL);
876 /* servname may be NULL */
877 assert(res != NULL);
878
879 *res = NULL;
880 sentinel.ai_next = NULL;
881 cur = &sentinel;
882
883 /*
884 * filter out AFs that are not supported by the kernel
885 * XXX errno?
886 */
Nick Kralevich1781ed72014-06-29 20:46:17 -0700887 s = socket(pai->ai_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800888 if (s < 0) {
889 if (errno != EMFILE)
890 return 0;
891 } else
892 close(s);
893
894 /*
895 * if the servname does not match socktype/protocol, ignore it.
896 */
897 if (get_portmatch(pai, servname) != 0)
898 return 0;
899
900 afd = find_afd(pai->ai_family);
901 if (afd == NULL)
902 return 0;
903
904 if (pai->ai_flags & AI_PASSIVE) {
905 GET_AI(cur->ai_next, afd, afd->a_addrany);
906 /* xxx meaningless?
907 * GET_CANONNAME(cur->ai_next, "anyaddr");
908 */
909 GET_PORT(cur->ai_next, servname);
910 } else {
911 GET_AI(cur->ai_next, afd, afd->a_loopback);
912 /* xxx meaningless?
913 * GET_CANONNAME(cur->ai_next, "localhost");
914 */
915 GET_PORT(cur->ai_next, servname);
916 }
917 cur = cur->ai_next;
918
919 *res = sentinel.ai_next;
920 return 0;
921
922free:
923 if (sentinel.ai_next)
924 freeaddrinfo(sentinel.ai_next);
925 return error;
926}
927
928/*
929 * numeric hostname
930 */
931static int
932explore_numeric(const struct addrinfo *pai, const char *hostname,
933 const char *servname, struct addrinfo **res, const char *canonname)
934{
935 const struct afd *afd;
936 struct addrinfo *cur;
937 struct addrinfo sentinel;
938 int error;
939 char pton[PTON_MAX];
940
941 assert(pai != NULL);
942 /* hostname may be NULL */
943 /* servname may be NULL */
944 assert(res != NULL);
945
946 *res = NULL;
947 sentinel.ai_next = NULL;
948 cur = &sentinel;
949
950 /*
951 * if the servname does not match socktype/protocol, ignore it.
952 */
953 if (get_portmatch(pai, servname) != 0)
954 return 0;
955
956 afd = find_afd(pai->ai_family);
957 if (afd == NULL)
958 return 0;
959
960 switch (afd->a_af) {
961#if 0 /*X/Open spec*/
962 case AF_INET:
963 if (inet_aton(hostname, (struct in_addr *)pton) == 1) {
964 if (pai->ai_family == afd->a_af ||
965 pai->ai_family == PF_UNSPEC /*?*/) {
966 GET_AI(cur->ai_next, afd, pton);
967 GET_PORT(cur->ai_next, servname);
968 if ((pai->ai_flags & AI_CANONNAME)) {
969 /*
970 * Set the numeric address itself as
971 * the canonical name, based on a
972 * clarification in rfc2553bis-03.
973 */
974 GET_CANONNAME(cur->ai_next, canonname);
975 }
976 while (cur && cur->ai_next)
977 cur = cur->ai_next;
978 } else
979 ERR(EAI_FAMILY); /*xxx*/
980 }
981 break;
982#endif
983 default:
984 if (inet_pton(afd->a_af, hostname, pton) == 1) {
985 if (pai->ai_family == afd->a_af ||
986 pai->ai_family == PF_UNSPEC /*?*/) {
987 GET_AI(cur->ai_next, afd, pton);
988 GET_PORT(cur->ai_next, servname);
989 if ((pai->ai_flags & AI_CANONNAME)) {
990 /*
991 * Set the numeric address itself as
992 * the canonical name, based on a
993 * clarification in rfc2553bis-03.
994 */
995 GET_CANONNAME(cur->ai_next, canonname);
996 }
997 while (cur->ai_next)
998 cur = cur->ai_next;
999 } else
1000 ERR(EAI_FAMILY); /*xxx*/
1001 }
1002 break;
1003 }
1004
1005 *res = sentinel.ai_next;
1006 return 0;
1007
1008free:
1009bad:
1010 if (sentinel.ai_next)
1011 freeaddrinfo(sentinel.ai_next);
1012 return error;
1013}
1014
1015/*
1016 * numeric hostname with scope
1017 */
1018static int
1019explore_numeric_scope(const struct addrinfo *pai, const char *hostname,
1020 const char *servname, struct addrinfo **res)
1021{
1022#if !defined(SCOPE_DELIMITER) || !defined(INET6)
1023 return explore_numeric(pai, hostname, servname, res, hostname);
1024#else
1025 const struct afd *afd;
1026 struct addrinfo *cur;
1027 int error;
1028 char *cp, *hostname2 = NULL, *scope, *addr;
1029 struct sockaddr_in6 *sin6;
1030
1031 assert(pai != NULL);
1032 /* hostname may be NULL */
1033 /* servname may be NULL */
1034 assert(res != NULL);
1035
1036 /*
1037 * if the servname does not match socktype/protocol, ignore it.
1038 */
1039 if (get_portmatch(pai, servname) != 0)
1040 return 0;
1041
1042 afd = find_afd(pai->ai_family);
1043 if (afd == NULL)
1044 return 0;
1045
1046 if (!afd->a_scoped)
1047 return explore_numeric(pai, hostname, servname, res, hostname);
1048
1049 cp = strchr(hostname, SCOPE_DELIMITER);
1050 if (cp == NULL)
1051 return explore_numeric(pai, hostname, servname, res, hostname);
1052
1053 /*
1054 * Handle special case of <scoped_address><delimiter><scope id>
1055 */
1056 hostname2 = strdup(hostname);
1057 if (hostname2 == NULL)
1058 return EAI_MEMORY;
1059 /* terminate at the delimiter */
1060 hostname2[cp - hostname] = '\0';
1061 addr = hostname2;
1062 scope = cp + 1;
1063
1064 error = explore_numeric(pai, addr, servname, res, hostname);
1065 if (error == 0) {
1066 u_int32_t scopeid;
1067
1068 for (cur = *res; cur; cur = cur->ai_next) {
1069 if (cur->ai_family != AF_INET6)
1070 continue;
1071 sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
1072 if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) {
1073 free(hostname2);
1074 return(EAI_NODATA); /* XXX: is return OK? */
1075 }
1076 sin6->sin6_scope_id = scopeid;
1077 }
1078 }
1079
1080 free(hostname2);
1081
1082 return error;
1083#endif
1084}
1085
1086static int
1087get_canonname(const struct addrinfo *pai, struct addrinfo *ai, const char *str)
1088{
1089
1090 assert(pai != NULL);
1091 assert(ai != NULL);
1092 assert(str != NULL);
1093
1094 if ((pai->ai_flags & AI_CANONNAME) != 0) {
1095 ai->ai_canonname = strdup(str);
1096 if (ai->ai_canonname == NULL)
1097 return EAI_MEMORY;
1098 }
1099 return 0;
1100}
1101
1102static struct addrinfo *
1103get_ai(const struct addrinfo *pai, const struct afd *afd, const char *addr)
1104{
1105 char *p;
1106 struct addrinfo *ai;
1107
1108 assert(pai != NULL);
1109 assert(afd != NULL);
1110 assert(addr != NULL);
1111
1112 ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
1113 + (afd->a_socklen));
1114 if (ai == NULL)
1115 return NULL;
1116
1117 memcpy(ai, pai, sizeof(struct addrinfo));
1118 ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
1119 memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
1120
1121#ifdef HAVE_SA_LEN
1122 ai->ai_addr->sa_len = afd->a_socklen;
1123#endif
1124
1125 ai->ai_addrlen = afd->a_socklen;
1126#if defined (__alpha__) || (defined(__i386__) && defined(_LP64)) || defined(__sparc64__)
1127 ai->__ai_pad0 = 0;
1128#endif
1129 ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
1130 p = (char *)(void *)(ai->ai_addr);
1131 memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
1132 return ai;
1133}
1134
1135static int
1136get_portmatch(const struct addrinfo *ai, const char *servname)
1137{
1138
1139 assert(ai != NULL);
1140 /* servname may be NULL */
1141
1142 return get_port(ai, servname, 1);
1143}
1144
1145static int
1146get_port(const struct addrinfo *ai, const char *servname, int matchonly)
1147{
1148 const char *proto;
1149 struct servent *sp;
1150 int port;
1151 int allownumeric;
1152
1153 assert(ai != NULL);
1154 /* servname may be NULL */
1155
1156 if (servname == NULL)
1157 return 0;
1158 switch (ai->ai_family) {
1159 case AF_INET:
1160#ifdef AF_INET6
1161 case AF_INET6:
1162#endif
1163 break;
1164 default:
1165 return 0;
1166 }
1167
1168 switch (ai->ai_socktype) {
1169 case SOCK_RAW:
1170 return EAI_SERVICE;
1171 case SOCK_DGRAM:
1172 case SOCK_STREAM:
1173 allownumeric = 1;
1174 break;
1175 case ANY:
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001176#if 1 /* ANDROID-SPECIFIC CHANGE TO MATCH GLIBC */
David 'Digit' Turner5e563702009-05-05 15:50:24 +02001177 allownumeric = 1;
1178#else
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001179 allownumeric = 0;
David 'Digit' Turner5e563702009-05-05 15:50:24 +02001180#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001181 break;
1182 default:
1183 return EAI_SOCKTYPE;
1184 }
1185
1186 port = str2number(servname);
1187 if (port >= 0) {
1188 if (!allownumeric)
1189 return EAI_SERVICE;
1190 if (port < 0 || port > 65535)
1191 return EAI_SERVICE;
1192 port = htons(port);
1193 } else {
1194 if (ai->ai_flags & AI_NUMERICSERV)
1195 return EAI_NONAME;
1196
1197 switch (ai->ai_socktype) {
1198 case SOCK_DGRAM:
1199 proto = "udp";
1200 break;
1201 case SOCK_STREAM:
1202 proto = "tcp";
1203 break;
1204 default:
1205 proto = NULL;
1206 break;
1207 }
1208
1209 if ((sp = getservbyname(servname, proto)) == NULL)
1210 return EAI_SERVICE;
1211 port = sp->s_port;
1212 }
1213
1214 if (!matchonly) {
1215 switch (ai->ai_family) {
1216 case AF_INET:
1217 ((struct sockaddr_in *)(void *)
1218 ai->ai_addr)->sin_port = port;
1219 break;
1220#ifdef INET6
1221 case AF_INET6:
1222 ((struct sockaddr_in6 *)(void *)
1223 ai->ai_addr)->sin6_port = port;
1224 break;
1225#endif
1226 }
1227 }
1228
1229 return 0;
1230}
1231
1232static const struct afd *
1233find_afd(int af)
1234{
1235 const struct afd *afd;
1236
1237 if (af == PF_UNSPEC)
1238 return NULL;
1239 for (afd = afdl; afd->a_af; afd++) {
1240 if (afd->a_af == af)
1241 return afd;
1242 }
1243 return NULL;
1244}
1245
1246#ifdef INET6
1247/* convert a string to a scope identifier. XXX: IPv6 specific */
1248static int
1249ip6_str2scopeid(char *scope, struct sockaddr_in6 *sin6, u_int32_t *scopeid)
1250{
1251 u_long lscopeid;
1252 struct in6_addr *a6;
1253 char *ep;
1254
1255 assert(scope != NULL);
1256 assert(sin6 != NULL);
1257 assert(scopeid != NULL);
1258
1259 a6 = &sin6->sin6_addr;
1260
1261 /* empty scopeid portion is invalid */
1262 if (*scope == '\0')
1263 return -1;
1264
1265 if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
1266 /*
1267 * We currently assume a one-to-one mapping between links
1268 * and interfaces, so we simply use interface indices for
1269 * like-local scopes.
1270 */
1271 *scopeid = if_nametoindex(scope);
1272 if (*scopeid == 0)
1273 goto trynumeric;
1274 return 0;
1275 }
1276
1277 /* still unclear about literal, allow numeric only - placeholder */
1278 if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
1279 goto trynumeric;
1280 if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
1281 goto trynumeric;
1282 else
1283 goto trynumeric; /* global */
1284
1285 /* try to convert to a numeric id as a last resort */
1286 trynumeric:
1287 errno = 0;
1288 lscopeid = strtoul(scope, &ep, 10);
1289 *scopeid = (u_int32_t)(lscopeid & 0xffffffffUL);
1290 if (errno == 0 && ep && *ep == '\0' && *scopeid == lscopeid)
1291 return 0;
1292 else
1293 return -1;
1294}
1295#endif
1296
1297/* code duplicate with gethnamaddr.c */
1298
1299static const char AskedForGot[] =
1300 "gethostby*.getanswer: asked for \"%s\", got \"%s\"";
1301
Elliott Hughes0e441f02016-11-14 13:56:32 -08001302#define BOUNDED_INCR(x) \
1303 do { \
1304 BOUNDS_CHECK(cp, x); \
1305 cp += (x); \
1306 } while (/*CONSTCOND*/0)
1307
1308#define BOUNDS_CHECK(ptr, count) \
1309 do { \
1310 if (eom - (ptr) < (count)) { h_errno = NO_RECOVERY; return NULL; } \
1311 } while (/*CONSTCOND*/0)
1312
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001313static struct addrinfo *
1314getanswer(const querybuf *answer, int anslen, const char *qname, int qtype,
1315 const struct addrinfo *pai)
1316{
1317 struct addrinfo sentinel, *cur;
1318 struct addrinfo ai;
1319 const struct afd *afd;
1320 char *canonname;
1321 const HEADER *hp;
1322 const u_char *cp;
1323 int n;
1324 const u_char *eom;
1325 char *bp, *ep;
1326 int type, class, ancount, qdcount;
1327 int haveanswer, had_error;
1328 char tbuf[MAXDNAME];
1329 int (*name_ok) (const char *);
1330 char hostbuf[8*1024];
1331
1332 assert(answer != NULL);
1333 assert(qname != NULL);
1334 assert(pai != NULL);
1335
1336 memset(&sentinel, 0, sizeof(sentinel));
1337 cur = &sentinel;
1338
1339 canonname = NULL;
1340 eom = answer->buf + anslen;
1341 switch (qtype) {
1342 case T_A:
1343 case T_AAAA:
1344 case T_ANY: /*use T_ANY only for T_A/T_AAAA lookup*/
1345 name_ok = res_hnok;
1346 break;
1347 default:
1348 return NULL; /* XXX should be abort(); */
1349 }
1350 /*
1351 * find first satisfactory answer
1352 */
1353 hp = &answer->hdr;
1354 ancount = ntohs(hp->ancount);
1355 qdcount = ntohs(hp->qdcount);
1356 bp = hostbuf;
1357 ep = hostbuf + sizeof hostbuf;
Elliott Hughes0e441f02016-11-14 13:56:32 -08001358 cp = answer->buf;
1359 BOUNDED_INCR(HFIXEDSZ);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001360 if (qdcount != 1) {
1361 h_errno = NO_RECOVERY;
1362 return (NULL);
1363 }
1364 n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1365 if ((n < 0) || !(*name_ok)(bp)) {
1366 h_errno = NO_RECOVERY;
1367 return (NULL);
1368 }
Elliott Hughes0e441f02016-11-14 13:56:32 -08001369 BOUNDED_INCR(n + QFIXEDSZ);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001370 if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
1371 /* res_send() has already verified that the query name is the
1372 * same as the one we sent; this just gets the expanded name
1373 * (i.e., with the succeeding search-domain tacked on).
1374 */
1375 n = strlen(bp) + 1; /* for the \0 */
1376 if (n >= MAXHOSTNAMELEN) {
1377 h_errno = NO_RECOVERY;
1378 return (NULL);
1379 }
1380 canonname = bp;
1381 bp += n;
1382 /* The qname can be abbreviated, but h_name is now absolute. */
1383 qname = canonname;
1384 }
1385 haveanswer = 0;
1386 had_error = 0;
1387 while (ancount-- > 0 && cp < eom && !had_error) {
1388 n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1389 if ((n < 0) || !(*name_ok)(bp)) {
1390 had_error++;
1391 continue;
1392 }
1393 cp += n; /* name */
Elliott Hughes0e441f02016-11-14 13:56:32 -08001394 BOUNDS_CHECK(cp, 3 * INT16SZ + INT32SZ);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001395 type = _getshort(cp);
Lorenzo Colittib82532d2011-09-28 19:28:32 -07001396 cp += INT16SZ; /* type */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001397 class = _getshort(cp);
Lorenzo Colittib82532d2011-09-28 19:28:32 -07001398 cp += INT16SZ + INT32SZ; /* class, TTL */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001399 n = _getshort(cp);
1400 cp += INT16SZ; /* len */
Elliott Hughes0e441f02016-11-14 13:56:32 -08001401 BOUNDS_CHECK(cp, n);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001402 if (class != C_IN) {
1403 /* XXX - debug? syslog? */
1404 cp += n;
1405 continue; /* XXX - had_error++ ? */
1406 }
1407 if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
1408 type == T_CNAME) {
1409 n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
1410 if ((n < 0) || !(*name_ok)(tbuf)) {
1411 had_error++;
1412 continue;
1413 }
1414 cp += n;
1415 /* Get canonical name. */
1416 n = strlen(tbuf) + 1; /* for the \0 */
1417 if (n > ep - bp || n >= MAXHOSTNAMELEN) {
1418 had_error++;
1419 continue;
1420 }
1421 strlcpy(bp, tbuf, (size_t)(ep - bp));
1422 canonname = bp;
1423 bp += n;
1424 continue;
1425 }
1426 if (qtype == T_ANY) {
1427 if (!(type == T_A || type == T_AAAA)) {
1428 cp += n;
1429 continue;
1430 }
1431 } else if (type != qtype) {
1432 if (type != T_KEY && type != T_SIG)
1433 syslog(LOG_NOTICE|LOG_AUTH,
1434 "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
1435 qname, p_class(C_IN), p_type(qtype),
1436 p_type(type));
1437 cp += n;
1438 continue; /* XXX - had_error++ ? */
1439 }
1440 switch (type) {
1441 case T_A:
1442 case T_AAAA:
1443 if (strcasecmp(canonname, bp) != 0) {
1444 syslog(LOG_NOTICE|LOG_AUTH,
1445 AskedForGot, canonname, bp);
1446 cp += n;
1447 continue; /* XXX - had_error++ ? */
1448 }
1449 if (type == T_A && n != INADDRSZ) {
1450 cp += n;
1451 continue;
1452 }
1453 if (type == T_AAAA && n != IN6ADDRSZ) {
1454 cp += n;
1455 continue;
1456 }
1457 if (type == T_AAAA) {
1458 struct in6_addr in6;
1459 memcpy(&in6, cp, IN6ADDRSZ);
1460 if (IN6_IS_ADDR_V4MAPPED(&in6)) {
1461 cp += n;
1462 continue;
1463 }
1464 }
1465 if (!haveanswer) {
1466 int nn;
1467
1468 canonname = bp;
1469 nn = strlen(bp) + 1; /* for the \0 */
1470 bp += nn;
1471 }
1472
1473 /* don't overwrite pai */
1474 ai = *pai;
1475 ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
1476 afd = find_afd(ai.ai_family);
1477 if (afd == NULL) {
1478 cp += n;
1479 continue;
1480 }
1481 cur->ai_next = get_ai(&ai, afd, (const char *)cp);
1482 if (cur->ai_next == NULL)
1483 had_error++;
1484 while (cur && cur->ai_next)
1485 cur = cur->ai_next;
1486 cp += n;
1487 break;
1488 default:
1489 abort();
1490 }
1491 if (!had_error)
1492 haveanswer++;
1493 }
1494 if (haveanswer) {
1495 if (!canonname)
1496 (void)get_canonname(pai, sentinel.ai_next, qname);
1497 else
1498 (void)get_canonname(pai, sentinel.ai_next, canonname);
1499 h_errno = NETDB_SUCCESS;
1500 return sentinel.ai_next;
1501 }
1502
1503 h_errno = NO_RECOVERY;
1504 return NULL;
1505}
1506
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001507struct addrinfo_sort_elem {
1508 struct addrinfo *ai;
1509 int has_src_addr;
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001510 sockaddr_union src_addr;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001511 int original_order;
1512};
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001513
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001514/*ARGSUSED*/
1515static int
1516_get_scope(const struct sockaddr *addr)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001517{
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001518 if (addr->sa_family == AF_INET6) {
1519 const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)addr;
1520 if (IN6_IS_ADDR_MULTICAST(&addr6->sin6_addr)) {
1521 return IPV6_ADDR_MC_SCOPE(&addr6->sin6_addr);
1522 } else if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr) ||
1523 IN6_IS_ADDR_LINKLOCAL(&addr6->sin6_addr)) {
1524 /*
1525 * RFC 4291 section 2.5.3 says loopback is to be treated as having
1526 * link-local scope.
1527 */
1528 return IPV6_ADDR_SCOPE_LINKLOCAL;
1529 } else if (IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr)) {
1530 return IPV6_ADDR_SCOPE_SITELOCAL;
1531 } else {
1532 return IPV6_ADDR_SCOPE_GLOBAL;
1533 }
1534 } else if (addr->sa_family == AF_INET) {
1535 const struct sockaddr_in *addr4 = (const struct sockaddr_in *)addr;
1536 unsigned long int na = ntohl(addr4->sin_addr.s_addr);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001537
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001538 if (IN_LOOPBACK(na) || /* 127.0.0.0/8 */
1539 (na & 0xffff0000) == 0xa9fe0000) { /* 169.254.0.0/16 */
1540 return IPV6_ADDR_SCOPE_LINKLOCAL;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001541 } else {
Steinar H. Gundersond1624ad2010-12-20 11:15:33 +01001542 /*
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001543 * RFC 6724 section 3.2. Other IPv4 addresses, including private addresses
1544 * and shared addresses (100.64.0.0/10), are assigned global scope.
Steinar H. Gundersond1624ad2010-12-20 11:15:33 +01001545 */
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001546 return IPV6_ADDR_SCOPE_GLOBAL;
1547 }
1548 } else {
1549 /*
1550 * This should never happen.
1551 * Return a scope with low priority as a last resort.
1552 */
1553 return IPV6_ADDR_SCOPE_NODELOCAL;
1554 }
1555}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001556
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001557/* These macros are modelled after the ones in <netinet/in6.h>. */
1558
1559/* RFC 4380, section 2.6 */
1560#define IN6_IS_ADDR_TEREDO(a) \
1561 ((*(const uint32_t *)(const void *)(&(a)->s6_addr[0]) == ntohl(0x20010000)))
1562
1563/* RFC 3056, section 2. */
1564#define IN6_IS_ADDR_6TO4(a) \
1565 (((a)->s6_addr[0] == 0x20) && ((a)->s6_addr[1] == 0x02))
1566
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001567/* 6bone testing address area (3ffe::/16), deprecated in RFC 3701. */
1568#define IN6_IS_ADDR_6BONE(a) \
1569 (((a)->s6_addr[0] == 0x3f) && ((a)->s6_addr[1] == 0xfe))
1570
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001571/*
1572 * Get the label for a given IPv4/IPv6 address.
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001573 * RFC 6724, section 2.1.
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001574 */
1575
1576/*ARGSUSED*/
1577static int
1578_get_label(const struct sockaddr *addr)
1579{
1580 if (addr->sa_family == AF_INET) {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001581 return 4;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001582 } else if (addr->sa_family == AF_INET6) {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001583 const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *) addr;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001584 if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr)) {
1585 return 0;
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001586 } else if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001587 return 4;
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001588 } else if (IN6_IS_ADDR_6TO4(&addr6->sin6_addr)) {
1589 return 2;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001590 } else if (IN6_IS_ADDR_TEREDO(&addr6->sin6_addr)) {
1591 return 5;
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001592 } else if (IN6_IS_ADDR_ULA(&addr6->sin6_addr)) {
1593 return 13;
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001594 } else if (IN6_IS_ADDR_V4COMPAT(&addr6->sin6_addr)) {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001595 return 3;
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001596 } else if (IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr)) {
1597 return 11;
1598 } else if (IN6_IS_ADDR_6BONE(&addr6->sin6_addr)) {
1599 return 12;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001600 } else {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001601 /* All other IPv6 addresses, including global unicast addresses. */
1602 return 1;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001603 }
1604 } else {
1605 /*
1606 * This should never happen.
1607 * Return a semi-random label as a last resort.
1608 */
1609 return 1;
1610 }
1611}
1612
1613/*
1614 * Get the precedence for a given IPv4/IPv6 address.
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001615 * RFC 6724, section 2.1.
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001616 */
1617
1618/*ARGSUSED*/
1619static int
1620_get_precedence(const struct sockaddr *addr)
1621{
1622 if (addr->sa_family == AF_INET) {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001623 return 35;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001624 } else if (addr->sa_family == AF_INET6) {
1625 const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)addr;
1626 if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr)) {
1627 return 50;
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001628 } else if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001629 return 35;
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001630 } else if (IN6_IS_ADDR_6TO4(&addr6->sin6_addr)) {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001631 return 30;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001632 } else if (IN6_IS_ADDR_TEREDO(&addr6->sin6_addr)) {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001633 return 5;
1634 } else if (IN6_IS_ADDR_ULA(&addr6->sin6_addr)) {
1635 return 3;
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001636 } else if (IN6_IS_ADDR_V4COMPAT(&addr6->sin6_addr) ||
Lorenzo Colittib82532d2011-09-28 19:28:32 -07001637 IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr) ||
1638 IN6_IS_ADDR_6BONE(&addr6->sin6_addr)) {
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001639 return 1;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001640 } else {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001641 /* All other IPv6 addresses, including global unicast addresses. */
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001642 return 40;
1643 }
1644 } else {
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001645 return 1;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001646 }
1647}
1648
1649/*
1650 * Find number of matching initial bits between the two addresses a1 and a2.
1651 */
1652
1653/*ARGSUSED*/
1654static int
1655_common_prefix_len(const struct in6_addr *a1, const struct in6_addr *a2)
1656{
1657 const char *p1 = (const char *)a1;
1658 const char *p2 = (const char *)a2;
1659 unsigned i;
1660
1661 for (i = 0; i < sizeof(*a1); ++i) {
1662 int x, j;
1663
1664 if (p1[i] == p2[i]) {
1665 continue;
1666 }
1667 x = p1[i] ^ p2[i];
1668 for (j = 0; j < CHAR_BIT; ++j) {
1669 if (x & (1 << (CHAR_BIT - 1))) {
1670 return i * CHAR_BIT + j;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001671 }
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001672 x <<= 1;
1673 }
1674 }
1675 return sizeof(*a1) * CHAR_BIT;
1676}
1677
1678/*
1679 * Compare two source/destination address pairs.
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001680 * RFC 6724, section 6.
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001681 */
1682
1683/*ARGSUSED*/
1684static int
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001685_rfc6724_compare(const void *ptr1, const void* ptr2)
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001686{
1687 const struct addrinfo_sort_elem *a1 = (const struct addrinfo_sort_elem *)ptr1;
1688 const struct addrinfo_sort_elem *a2 = (const struct addrinfo_sort_elem *)ptr2;
1689 int scope_src1, scope_dst1, scope_match1;
1690 int scope_src2, scope_dst2, scope_match2;
1691 int label_src1, label_dst1, label_match1;
1692 int label_src2, label_dst2, label_match2;
1693 int precedence1, precedence2;
1694 int prefixlen1, prefixlen2;
1695
1696 /* Rule 1: Avoid unusable destinations. */
1697 if (a1->has_src_addr != a2->has_src_addr) {
1698 return a2->has_src_addr - a1->has_src_addr;
1699 }
1700
1701 /* Rule 2: Prefer matching scope. */
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001702 scope_src1 = _get_scope(&a1->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001703 scope_dst1 = _get_scope(a1->ai->ai_addr);
1704 scope_match1 = (scope_src1 == scope_dst1);
1705
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001706 scope_src2 = _get_scope(&a2->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001707 scope_dst2 = _get_scope(a2->ai->ai_addr);
1708 scope_match2 = (scope_src2 == scope_dst2);
1709
1710 if (scope_match1 != scope_match2) {
1711 return scope_match2 - scope_match1;
1712 }
1713
1714 /*
1715 * Rule 3: Avoid deprecated addresses.
1716 * TODO(sesse): We don't currently have a good way of finding this.
1717 */
1718
1719 /*
1720 * Rule 4: Prefer home addresses.
1721 * TODO(sesse): We don't currently have a good way of finding this.
1722 */
1723
1724 /* Rule 5: Prefer matching label. */
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001725 label_src1 = _get_label(&a1->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001726 label_dst1 = _get_label(a1->ai->ai_addr);
1727 label_match1 = (label_src1 == label_dst1);
1728
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001729 label_src2 = _get_label(&a2->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001730 label_dst2 = _get_label(a2->ai->ai_addr);
1731 label_match2 = (label_src2 == label_dst2);
1732
1733 if (label_match1 != label_match2) {
1734 return label_match2 - label_match1;
1735 }
1736
1737 /* Rule 6: Prefer higher precedence. */
1738 precedence1 = _get_precedence(a1->ai->ai_addr);
1739 precedence2 = _get_precedence(a2->ai->ai_addr);
1740 if (precedence1 != precedence2) {
1741 return precedence2 - precedence1;
1742 }
1743
1744 /*
1745 * Rule 7: Prefer native transport.
1746 * TODO(sesse): We don't currently have a good way of finding this.
1747 */
1748
1749 /* Rule 8: Prefer smaller scope. */
1750 if (scope_dst1 != scope_dst2) {
1751 return scope_dst1 - scope_dst2;
1752 }
1753
1754 /*
1755 * Rule 9: Use longest matching prefix.
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001756 * We implement this for IPv6 only, as the rules in RFC 6724 don't seem
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001757 * to work very well directly applied to IPv4. (glibc uses information from
1758 * the routing table for a custom IPv4 implementation here.)
1759 */
1760 if (a1->has_src_addr && a1->ai->ai_addr->sa_family == AF_INET6 &&
1761 a2->has_src_addr && a2->ai->ai_addr->sa_family == AF_INET6) {
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001762 const struct sockaddr_in6 *a1_src = &a1->src_addr.in6;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001763 const struct sockaddr_in6 *a1_dst = (const struct sockaddr_in6 *)a1->ai->ai_addr;
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001764 const struct sockaddr_in6 *a2_src = &a2->src_addr.in6;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001765 const struct sockaddr_in6 *a2_dst = (const struct sockaddr_in6 *)a2->ai->ai_addr;
1766 prefixlen1 = _common_prefix_len(&a1_src->sin6_addr, &a1_dst->sin6_addr);
Kenny Root7e0bfb52010-03-24 18:06:20 -07001767 prefixlen2 = _common_prefix_len(&a2_src->sin6_addr, &a2_dst->sin6_addr);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001768 if (prefixlen1 != prefixlen2) {
1769 return prefixlen2 - prefixlen1;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001770 }
1771 }
1772
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001773 /*
1774 * Rule 10: Leave the order unchanged.
1775 * We need this since qsort() is not necessarily stable.
1776 */
1777 return a1->original_order - a2->original_order;
1778}
1779
1780/*
1781 * Find the source address that will be used if trying to connect to the given
1782 * address. src_addr must be large enough to hold a struct sockaddr_in6.
1783 *
1784 * Returns 1 if a source address was found, 0 if the address is unreachable,
1785 * and -1 if a fatal error occurred. If 0 or 1, the contents of src_addr are
1786 * undefined.
1787 */
1788
1789/*ARGSUSED*/
1790static int
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001791_find_src_addr(const struct sockaddr *addr, struct sockaddr *src_addr, unsigned mark)
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001792{
1793 int sock;
1794 int ret;
1795 socklen_t len;
1796
1797 switch (addr->sa_family) {
1798 case AF_INET:
1799 len = sizeof(struct sockaddr_in);
1800 break;
1801 case AF_INET6:
1802 len = sizeof(struct sockaddr_in6);
1803 break;
1804 default:
1805 /* No known usable source address for non-INET families. */
1806 return 0;
1807 }
1808
Nick Kralevich1781ed72014-06-29 20:46:17 -07001809 sock = socket(addr->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001810 if (sock == -1) {
1811 if (errno == EAFNOSUPPORT) {
1812 return 0;
1813 } else {
1814 return -1;
1815 }
1816 }
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001817 if (mark != MARK_UNSET && setsockopt(sock, SOL_SOCKET, SO_MARK, &mark, sizeof(mark)) < 0)
1818 return 0;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001819 do {
Paul Jensen31ad0372014-05-29 16:28:30 -04001820 ret = __connect(sock, addr, len);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001821 } while (ret == -1 && errno == EINTR);
1822
1823 if (ret == -1) {
1824 close(sock);
1825 return 0;
1826 }
1827
1828 if (getsockname(sock, src_addr, &len) == -1) {
1829 close(sock);
1830 return -1;
1831 }
1832 close(sock);
1833 return 1;
1834}
1835
1836/*
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001837 * Sort the linked list starting at sentinel->ai_next in RFC6724 order.
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001838 * Will leave the list unchanged if an error occurs.
1839 */
1840
1841/*ARGSUSED*/
1842static void
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001843_rfc6724_sort(struct addrinfo *list_sentinel, unsigned mark)
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001844{
1845 struct addrinfo *cur;
1846 int nelem = 0, i;
1847 struct addrinfo_sort_elem *elems;
1848
1849 cur = list_sentinel->ai_next;
1850 while (cur) {
1851 ++nelem;
1852 cur = cur->ai_next;
1853 }
1854
1855 elems = (struct addrinfo_sort_elem *)malloc(nelem * sizeof(struct addrinfo_sort_elem));
1856 if (elems == NULL) {
1857 goto error;
1858 }
1859
1860 /*
1861 * Convert the linked list to an array that also contains the candidate
1862 * source address for each destination address.
1863 */
1864 for (i = 0, cur = list_sentinel->ai_next; i < nelem; ++i, cur = cur->ai_next) {
1865 int has_src_addr;
1866 assert(cur != NULL);
1867 elems[i].ai = cur;
1868 elems[i].original_order = i;
1869
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001870 has_src_addr = _find_src_addr(cur->ai_addr, &elems[i].src_addr.generic, mark);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001871 if (has_src_addr == -1) {
1872 goto error;
1873 }
1874 elems[i].has_src_addr = has_src_addr;
1875 }
1876
1877 /* Sort the addresses, and rearrange the linked list so it matches the sorted order. */
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001878 qsort((void *)elems, nelem, sizeof(struct addrinfo_sort_elem), _rfc6724_compare);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001879
1880 list_sentinel->ai_next = elems[0].ai;
1881 for (i = 0; i < nelem - 1; ++i) {
1882 elems[i].ai->ai_next = elems[i + 1].ai;
1883 }
1884 elems[nelem - 1].ai->ai_next = NULL;
1885
1886error:
1887 free(elems);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001888}
1889
1890/*ARGSUSED*/
1891static int
1892_dns_getaddrinfo(void *rv, void *cb_data, va_list ap)
1893{
1894 struct addrinfo *ai;
1895 querybuf *buf, *buf2;
1896 const char *name;
1897 const struct addrinfo *pai;
1898 struct addrinfo sentinel, *cur;
1899 struct res_target q, q2;
1900 res_state res;
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001901 unsigned netid, mark;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001902
1903 name = va_arg(ap, char *);
1904 pai = va_arg(ap, const struct addrinfo *);
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001905 netid = va_arg(ap, unsigned);
1906 mark = va_arg(ap, unsigned);
David 'Digit' Turner5e563702009-05-05 15:50:24 +02001907 //fprintf(stderr, "_dns_getaddrinfo() name = '%s'\n", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001908
1909 memset(&q, 0, sizeof(q));
1910 memset(&q2, 0, sizeof(q2));
1911 memset(&sentinel, 0, sizeof(sentinel));
1912 cur = &sentinel;
1913
1914 buf = malloc(sizeof(*buf));
1915 if (buf == NULL) {
1916 h_errno = NETDB_INTERNAL;
1917 return NS_NOTFOUND;
1918 }
1919 buf2 = malloc(sizeof(*buf2));
1920 if (buf2 == NULL) {
1921 free(buf);
1922 h_errno = NETDB_INTERNAL;
1923 return NS_NOTFOUND;
1924 }
1925
1926 switch (pai->ai_family) {
1927 case AF_UNSPEC:
1928 /* prefer IPv6 */
1929 q.name = name;
1930 q.qclass = C_IN;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001931 q.answer = buf->buf;
1932 q.anslen = sizeof(buf->buf);
Lorenzo Colittiba96e302011-01-14 12:26:05 -08001933 int query_ipv6 = 1, query_ipv4 = 1;
1934 if (pai->ai_flags & AI_ADDRCONFIG) {
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001935 query_ipv6 = _have_ipv6(mark);
1936 query_ipv4 = _have_ipv4(mark);
Lorenzo Colittiba96e302011-01-14 12:26:05 -08001937 }
1938 if (query_ipv6) {
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -07001939 q.qtype = T_AAAA;
Lorenzo Colittiba96e302011-01-14 12:26:05 -08001940 if (query_ipv4) {
1941 q.next = &q2;
1942 q2.name = name;
1943 q2.qclass = C_IN;
1944 q2.qtype = T_A;
1945 q2.answer = buf2->buf;
1946 q2.anslen = sizeof(buf2->buf);
1947 }
1948 } else if (query_ipv4) {
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -07001949 q.qtype = T_A;
Lorenzo Colittiba96e302011-01-14 12:26:05 -08001950 } else {
1951 free(buf);
1952 free(buf2);
1953 return NS_NOTFOUND;
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -07001954 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001955 break;
1956 case AF_INET:
1957 q.name = name;
1958 q.qclass = C_IN;
1959 q.qtype = T_A;
1960 q.answer = buf->buf;
1961 q.anslen = sizeof(buf->buf);
1962 break;
1963 case AF_INET6:
1964 q.name = name;
1965 q.qclass = C_IN;
1966 q.qtype = T_AAAA;
1967 q.answer = buf->buf;
1968 q.anslen = sizeof(buf->buf);
1969 break;
1970 default:
1971 free(buf);
1972 free(buf2);
1973 return NS_UNAVAIL;
1974 }
1975
1976 res = __res_get_state();
1977 if (res == NULL) {
1978 free(buf);
1979 free(buf2);
1980 return NS_NOTFOUND;
1981 }
1982
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001983 /* this just sets our netid val in the thread private data so we don't have to
Mattias Falkc63e5902011-08-23 14:34:14 +02001984 * modify the api's all the way down to res_send.c's res_nsend. We could
1985 * fully populate the thread private data here, but if we get down there
1986 * and have a cache hit that would be wasted, so we do the rest there on miss
1987 */
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001988 res_setnetid(res, netid);
Chad Brubakerc39214e2013-06-20 10:36:56 -07001989 res_setmark(res, mark);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001990 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
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05002021 _rfc6724_sort(&sentinel, netid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002022
2023 __res_put_state(res);
2024
2025 *((struct addrinfo **)rv) = sentinel.ai_next;
2026 return NS_SUCCESS;
2027}
2028
2029static void
2030_sethtent(FILE **hostf)
2031{
2032
2033 if (!*hostf)
2034 *hostf = fopen(_PATH_HOSTS, "r" );
2035 else
2036 rewind(*hostf);
2037}
2038
2039static void
2040_endhtent(FILE **hostf)
2041{
2042
2043 if (*hostf) {
2044 (void) fclose(*hostf);
2045 *hostf = NULL;
2046 }
2047}
2048
2049static struct addrinfo *
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, "r" )))
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
2095found:
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*/
2116static int
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 */
2158static int
2159res_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
2180 hp = (HEADER *)(void *)t->answer;
2181 hp->rcode = NOERROR; /* default */
2182
2183 /* make it easier... */
2184 class = t->qclass;
2185 type = t->qtype;
2186 answer = t->answer;
2187 anslen = t->anslen;
2188#ifdef DEBUG
2189 if (res->options & RES_DEBUG)
2190 printf(";; res_nquery(%s, %d, %d)\n", name, class, type);
2191#endif
2192
2193 n = res_nmkquery(res, QUERY, name, class, type, NULL, 0, NULL,
2194 buf, sizeof(buf));
2195#ifdef RES_USE_EDNS0
2196 if (n > 0 && (res->options & RES_USE_EDNS0) != 0)
2197 n = res_nopt(res, n, buf, sizeof(buf), anslen);
2198#endif
2199 if (n <= 0) {
2200#ifdef DEBUG
2201 if (res->options & RES_DEBUG)
2202 printf(";; res_nquery: mkquery failed\n");
2203#endif
2204 h_errno = NO_RECOVERY;
2205 return n;
2206 }
2207 n = res_nsend(res, buf, n, answer, anslen);
2208#if 0
2209 if (n < 0) {
2210#ifdef DEBUG
2211 if (res->options & RES_DEBUG)
2212 printf(";; res_query: send error\n");
2213#endif
2214 h_errno = TRY_AGAIN;
2215 return n;
2216 }
2217#endif
2218
2219 if (n < 0 || hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
2220 rcode = hp->rcode; /* record most recent error */
2221#ifdef DEBUG
2222 if (res->options & RES_DEBUG)
2223 printf(";; rcode = %u, ancount=%u\n", hp->rcode,
2224 ntohs(hp->ancount));
2225#endif
2226 continue;
2227 }
2228
2229 ancount += ntohs(hp->ancount);
2230
2231 t->n = n;
2232 }
2233
2234 if (ancount == 0) {
2235 switch (rcode) {
2236 case NXDOMAIN:
2237 h_errno = HOST_NOT_FOUND;
2238 break;
2239 case SERVFAIL:
2240 h_errno = TRY_AGAIN;
2241 break;
2242 case NOERROR:
2243 h_errno = NO_DATA;
2244 break;
2245 case FORMERR:
2246 case NOTIMP:
2247 case REFUSED:
2248 default:
2249 h_errno = NO_RECOVERY;
2250 break;
2251 }
2252 return -1;
2253 }
2254 return ancount;
2255}
2256
2257/*
2258 * Formulate a normal query, send, and retrieve answer in supplied buffer.
2259 * Return the size of the response on success, -1 on error.
2260 * If enabled, implement search rules until answer or unrecoverable failure
2261 * is detected. Error code, if any, is left in h_errno.
2262 */
2263static int
2264res_searchN(const char *name, struct res_target *target, res_state res)
2265{
2266 const char *cp, * const *domain;
2267 HEADER *hp;
2268 u_int dots;
2269 int trailing_dot, ret, saved_herrno;
2270 int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
2271
2272 assert(name != NULL);
2273 assert(target != NULL);
2274
2275 hp = (HEADER *)(void *)target->answer; /*XXX*/
2276
2277 errno = 0;
2278 h_errno = HOST_NOT_FOUND; /* default, if we never query */
2279 dots = 0;
2280 for (cp = name; *cp; cp++)
2281 dots += (*cp == '.');
2282 trailing_dot = 0;
2283 if (cp > name && *--cp == '.')
2284 trailing_dot++;
2285
2286
David 'Digit' Turner5e563702009-05-05 15:50:24 +02002287 //fprintf(stderr, "res_searchN() name = '%s'\n", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002288
2289 /*
2290 * if there aren't any dots, it could be a user-level alias
2291 */
2292 if (!dots && (cp = __hostalias(name)) != NULL) {
2293 ret = res_queryN(cp, target, res);
2294 return ret;
2295 }
2296
2297 /*
2298 * If there are dots in the name already, let's just give it a try
2299 * 'as is'. The threshold can be set with the "ndots" option.
2300 */
2301 saved_herrno = -1;
2302 if (dots >= res->ndots) {
2303 ret = res_querydomainN(name, NULL, target, res);
2304 if (ret > 0)
2305 return (ret);
2306 saved_herrno = h_errno;
2307 tried_as_is++;
2308 }
2309
2310 /*
2311 * We do at least one level of search if
2312 * - there is no dot and RES_DEFNAME is set, or
2313 * - there is at least one dot, there is no trailing dot,
2314 * and RES_DNSRCH is set.
2315 */
2316 if ((!dots && (res->options & RES_DEFNAMES)) ||
2317 (dots && !trailing_dot && (res->options & RES_DNSRCH))) {
2318 int done = 0;
2319
Robert Greenwalte0805a92013-07-31 16:53:46 -07002320 /* Unfortunately we need to set stuff up before
2321 * the domain stuff is tried. Will have a better
2322 * fix after thread pools are used.
2323 */
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05002324 _resolv_populate_res_for_net(res);
Robert Greenwalte0805a92013-07-31 16:53:46 -07002325
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002326 for (domain = (const char * const *)res->dnsrch;
2327 *domain && !done;
2328 domain++) {
2329
2330 ret = res_querydomainN(name, *domain, target, res);
2331 if (ret > 0)
2332 return ret;
2333
2334 /*
2335 * If no server present, give up.
2336 * If name isn't found in this domain,
2337 * keep trying higher domains in the search list
2338 * (if that's enabled).
2339 * On a NO_DATA error, keep trying, otherwise
2340 * a wildcard entry of another type could keep us
2341 * from finding this entry higher in the domain.
2342 * If we get some other error (negative answer or
2343 * server failure), then stop searching up,
2344 * but try the input name below in case it's
2345 * fully-qualified.
2346 */
2347 if (errno == ECONNREFUSED) {
2348 h_errno = TRY_AGAIN;
2349 return -1;
2350 }
2351
2352 switch (h_errno) {
2353 case NO_DATA:
2354 got_nodata++;
2355 /* FALLTHROUGH */
2356 case HOST_NOT_FOUND:
2357 /* keep trying */
2358 break;
2359 case TRY_AGAIN:
2360 if (hp->rcode == SERVFAIL) {
2361 /* try next search element, if any */
2362 got_servfail++;
2363 break;
2364 }
2365 /* FALLTHROUGH */
2366 default:
2367 /* anything else implies that we're done */
2368 done++;
2369 }
2370 /*
2371 * if we got here for some reason other than DNSRCH,
2372 * we only wanted one iteration of the loop, so stop.
2373 */
2374 if (!(res->options & RES_DNSRCH))
Lorenzo Colittib82532d2011-09-28 19:28:32 -07002375 done++;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002376 }
2377 }
2378
2379 /*
2380 * if we have not already tried the name "as is", do that now.
2381 * note that we do this regardless of how many dots were in the
2382 * name or whether it ends with a dot.
2383 */
2384 if (!tried_as_is) {
2385 ret = res_querydomainN(name, NULL, target, res);
2386 if (ret > 0)
2387 return ret;
2388 }
2389
2390 /*
2391 * if we got here, we didn't satisfy the search.
2392 * if we did an initial full query, return that query's h_errno
2393 * (note that we wouldn't be here if that query had succeeded).
2394 * else if we ever got a nodata, send that back as the reason.
2395 * else send back meaningless h_errno, that being the one from
2396 * the last DNSRCH we did.
2397 */
2398 if (saved_herrno != -1)
2399 h_errno = saved_herrno;
2400 else if (got_nodata)
2401 h_errno = NO_DATA;
2402 else if (got_servfail)
2403 h_errno = TRY_AGAIN;
2404 return -1;
2405}
2406
2407/*
2408 * Perform a call on res_query on the concatenation of name and domain,
2409 * removing a trailing dot from name if domain is NULL.
2410 */
2411static int
2412res_querydomainN(const char *name, const char *domain,
2413 struct res_target *target, res_state res)
2414{
2415 char nbuf[MAXDNAME];
2416 const char *longname = nbuf;
2417 size_t n, d;
2418
2419 assert(name != NULL);
2420 /* XXX: target may be NULL??? */
2421
2422#ifdef DEBUG
2423 if (res->options & RES_DEBUG)
2424 printf(";; res_querydomain(%s, %s)\n",
2425 name, domain?domain:"<Nil>");
2426#endif
2427 if (domain == NULL) {
2428 /*
2429 * Check for trailing '.';
2430 * copy without '.' if present.
2431 */
2432 n = strlen(name);
2433 if (n + 1 > sizeof(nbuf)) {
2434 h_errno = NO_RECOVERY;
2435 return -1;
2436 }
2437 if (n > 0 && name[--n] == '.') {
2438 strncpy(nbuf, name, n);
2439 nbuf[n] = '\0';
2440 } else
2441 longname = name;
2442 } else {
2443 n = strlen(name);
2444 d = strlen(domain);
2445 if (n + 1 + d + 1 > sizeof(nbuf)) {
2446 h_errno = NO_RECOVERY;
2447 return -1;
2448 }
2449 snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
2450 }
2451 return res_queryN(longname, target, res);
2452}