blob: 1ebd222fe3a798d600d1b79efd686bcefb782c50 [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
Elliott Hughes55293c12014-11-12 17:00:30 -0800411bool readBE32(FILE* fp, int32_t* result) {
412 int32_t tmp;
413 if (fread(&tmp, sizeof(tmp), 1, fp) != 1) {
414 return false;
415 }
416 *result = ntohl(tmp);
417 return true;
418}
419
Mattias Falkc63e5902011-08-23 14:34:14 +0200420// Returns 0 on success, else returns on error.
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700421static int
422android_getaddrinfo_proxy(
423 const char *hostname, const char *servname,
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500424 const struct addrinfo *hints, struct addrinfo **res, unsigned netid)
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700425{
426 int sock;
427 const int one = 1;
428 struct sockaddr_un proxy_addr;
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700429 FILE* proxy = NULL;
430 int success = 0;
431
432 // Clear this at start, as we use its non-NULLness later (in the
433 // error path) to decide if we have to free up any memory we
434 // allocated in the process (before failing).
435 *res = NULL;
436
Mattias Falkc63e5902011-08-23 14:34:14 +0200437 // Bogus things we can't serialize. Don't use the proxy. These will fail - let them.
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700438 if ((hostname != NULL &&
439 strcspn(hostname, " \n\r\t^'\"") != strlen(hostname)) ||
440 (servname != NULL &&
441 strcspn(servname, " \n\r\t^'\"") != strlen(servname))) {
Mattias Falkc63e5902011-08-23 14:34:14 +0200442 return EAI_NODATA;
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700443 }
444
Nick Kralevich1781ed72014-06-29 20:46:17 -0700445 sock = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700446 if (sock < 0) {
Mattias Falkc63e5902011-08-23 14:34:14 +0200447 return EAI_NODATA;
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700448 }
449
450 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
451 memset(&proxy_addr, 0, sizeof(proxy_addr));
452 proxy_addr.sun_family = AF_UNIX;
453 strlcpy(proxy_addr.sun_path, "/dev/socket/dnsproxyd",
454 sizeof(proxy_addr.sun_path));
455 if (TEMP_FAILURE_RETRY(connect(sock,
456 (const struct sockaddr*) &proxy_addr,
457 sizeof(proxy_addr))) != 0) {
458 close(sock);
Mattias Falkc63e5902011-08-23 14:34:14 +0200459 return EAI_NODATA;
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700460 }
461
Paul Jensen559c7842014-05-15 14:43:07 -0400462 netid = __netdClientDispatch.netIdForResolv(netid);
463
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700464 // Send the request.
465 proxy = fdopen(sock, "r+");
Robert Alm3638a832014-11-25 13:28:11 +0100466 if (proxy == NULL) {
467 // Failed to map sock to FILE*. Check errno for the cause.
468 // @sonymobile.com saw failures in automated testing, but
469 // couldn't reproduce it for debugging.
470 // Fail with EAI_SYSTEM and let callers handle the failure.
471 close(sock);
472 return EAI_SYSTEM;
473 }
474
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500475 if (fprintf(proxy, "getaddrinfo %s %s %d %d %d %d %u",
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700476 hostname == NULL ? "^" : hostname,
477 servname == NULL ? "^" : servname,
478 hints == NULL ? -1 : hints->ai_flags,
479 hints == NULL ? -1 : hints->ai_family,
480 hints == NULL ? -1 : hints->ai_socktype,
Mattias Falkc63e5902011-08-23 14:34:14 +0200481 hints == NULL ? -1 : hints->ai_protocol,
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500482 netid) < 0) {
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700483 goto exit;
484 }
485 // literal NULL byte at end, required by FrameworkListener
486 if (fputc(0, proxy) == EOF ||
487 fflush(proxy) != 0) {
488 goto exit;
489 }
490
Robert Greenwaltc59ba452012-03-09 11:34:27 -0800491 char buf[4];
Selim Gurun06e18312012-02-27 15:58:54 -0800492 // read result code for gethostbyaddr
493 if (fread(buf, 1, sizeof(buf), proxy) != sizeof(buf)) {
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700494 goto exit;
495 }
496
Selim Gurun06e18312012-02-27 15:58:54 -0800497 int result_code = (int)strtol(buf, NULL, 10);
498 // verify the code itself
499 if (result_code != DnsProxyQueryResult ) {
Mattias Falkc63e5902011-08-23 14:34:14 +0200500 fread(buf, 1, sizeof(buf), proxy);
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700501 goto exit;
502 }
503
504 struct addrinfo* ai = NULL;
505 struct addrinfo** nextres = res;
506 while (1) {
Elliott Hughes55293c12014-11-12 17:00:30 -0800507 int32_t have_more;
508 if (!readBE32(proxy, &have_more)) {
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700509 break;
510 }
Elliott Hughes55293c12014-11-12 17:00:30 -0800511 if (have_more == 0) {
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700512 success = 1;
513 break;
514 }
515
Elliott Hughes55293c12014-11-12 17:00:30 -0800516 struct addrinfo* ai = calloc(1, sizeof(struct addrinfo) + sizeof(struct sockaddr_storage));
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700517 if (ai == NULL) {
518 break;
519 }
Elliott Hughes55293c12014-11-12 17:00:30 -0800520 ai->ai_addr = (struct sockaddr*)(ai + 1);
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700521
Elliott Hughes55293c12014-11-12 17:00:30 -0800522 // struct addrinfo {
523 // int ai_flags; /* AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST */
524 // int ai_family; /* PF_xxx */
525 // int ai_socktype; /* SOCK_xxx */
526 // int ai_protocol; /* 0 or IPPROTO_xxx for IPv4 and IPv6 */
527 // socklen_t ai_addrlen; /* length of ai_addr */
528 // char *ai_canonname; /* canonical name for hostname */
529 // struct sockaddr *ai_addr; /* binary address */
530 // struct addrinfo *ai_next; /* next structure in linked list */
531 // };
532
533 // Read the struct piece by piece because we might be a 32-bit process
534 // talking to a 64-bit netd.
535 int32_t addr_len;
536 bool success =
537 readBE32(proxy, &ai->ai_flags) &&
538 readBE32(proxy, &ai->ai_family) &&
539 readBE32(proxy, &ai->ai_socktype) &&
540 readBE32(proxy, &ai->ai_protocol) &&
541 readBE32(proxy, &addr_len);
542 if (!success) {
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700543 break;
544 }
545
Elliott Hughes55293c12014-11-12 17:00:30 -0800546 // Set ai_addrlen and read the ai_addr data.
547 ai->ai_addrlen = addr_len;
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700548 if (addr_len != 0) {
Elliott Hughes55293c12014-11-12 17:00:30 -0800549 if ((size_t) addr_len > sizeof(struct sockaddr_storage)) {
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700550 // Bogus; too big.
551 break;
552 }
Elliott Hughes55293c12014-11-12 17:00:30 -0800553 if (fread(ai->ai_addr, addr_len, 1, proxy) != 1) {
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700554 break;
555 }
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700556 }
557
Elliott Hughes55293c12014-11-12 17:00:30 -0800558 // The string for ai_cannonname.
559 int32_t name_len;
560 if (!readBE32(proxy, &name_len)) {
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700561 break;
562 }
563 if (name_len != 0) {
564 ai->ai_canonname = (char*) malloc(name_len);
565 if (fread(ai->ai_canonname, name_len, 1, proxy) != 1) {
566 break;
567 }
568 if (ai->ai_canonname[name_len - 1] != '\0') {
569 // The proxy should be returning this
570 // NULL-terminated.
571 break;
572 }
573 }
574
575 *nextres = ai;
576 nextres = &ai->ai_next;
577 ai = NULL;
578 }
579
580 if (ai != NULL) {
581 // Clean up partially-built addrinfo that we never ended up
582 // attaching to the response.
583 freeaddrinfo(ai);
584 }
585exit:
586 if (proxy != NULL) {
587 fclose(proxy);
588 }
589
590 if (success) {
591 return 0;
592 }
593
Mattias Falkc63e5902011-08-23 14:34:14 +0200594 // Proxy failed;
595 // clean up memory we might've allocated.
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700596 if (*res) {
597 freeaddrinfo(*res);
598 *res = NULL;
599 }
Mattias Falkc63e5902011-08-23 14:34:14 +0200600 return EAI_NODATA;
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700601}
602
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800603int
604getaddrinfo(const char *hostname, const char *servname,
605 const struct addrinfo *hints, struct addrinfo **res)
606{
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500607 return android_getaddrinfofornet(hostname, servname, hints, NETID_UNSET, MARK_UNSET, res);
Mattias Falkc63e5902011-08-23 14:34:14 +0200608}
609
610int
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500611android_getaddrinfofornet(const char *hostname, const char *servname,
612 const struct addrinfo *hints, unsigned netid, unsigned mark, struct addrinfo **res)
Mattias Falkc63e5902011-08-23 14:34:14 +0200613{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800614 struct addrinfo sentinel;
615 struct addrinfo *cur;
616 int error = 0;
617 struct addrinfo ai;
618 struct addrinfo ai0;
619 struct addrinfo *pai;
620 const struct explore *ex;
Mattias Falkc63e5902011-08-23 14:34:14 +0200621 const char* cache_mode = getenv("ANDROID_DNS_MODE");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800622
623 /* hostname is allowed to be NULL */
624 /* servname is allowed to be NULL */
625 /* hints is allowed to be NULL */
626 assert(res != NULL);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800627 memset(&sentinel, 0, sizeof(sentinel));
628 cur = &sentinel;
629 pai = &ai;
630 pai->ai_flags = 0;
631 pai->ai_family = PF_UNSPEC;
632 pai->ai_socktype = ANY;
633 pai->ai_protocol = ANY;
634 pai->ai_addrlen = 0;
635 pai->ai_canonname = NULL;
636 pai->ai_addr = NULL;
637 pai->ai_next = NULL;
638
639 if (hostname == NULL && servname == NULL)
640 return EAI_NONAME;
641 if (hints) {
642 /* error check for hints */
643 if (hints->ai_addrlen || hints->ai_canonname ||
644 hints->ai_addr || hints->ai_next)
645 ERR(EAI_BADHINTS); /* xxx */
646 if (hints->ai_flags & ~AI_MASK)
647 ERR(EAI_BADFLAGS);
648 switch (hints->ai_family) {
649 case PF_UNSPEC:
650 case PF_INET:
651#ifdef INET6
652 case PF_INET6:
653#endif
654 break;
655 default:
656 ERR(EAI_FAMILY);
657 }
658 memcpy(pai, hints, sizeof(*pai));
659
660 /*
661 * if both socktype/protocol are specified, check if they
662 * are meaningful combination.
663 */
664 if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
665 for (ex = explore; ex->e_af >= 0; ex++) {
666 if (pai->ai_family != ex->e_af)
667 continue;
668 if (ex->e_socktype == ANY)
669 continue;
670 if (ex->e_protocol == ANY)
671 continue;
672 if (pai->ai_socktype == ex->e_socktype
673 && pai->ai_protocol != ex->e_protocol) {
674 ERR(EAI_BADHINTS);
675 }
676 }
677 }
678 }
679
680 /*
681 * check for special cases. (1) numeric servname is disallowed if
682 * socktype/protocol are left unspecified. (2) servname is disallowed
683 * for raw and other inet{,6} sockets.
684 */
685 if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
686#ifdef PF_INET6
687 || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
688#endif
689 ) {
690 ai0 = *pai; /* backup *pai */
691
692 if (pai->ai_family == PF_UNSPEC) {
693#ifdef PF_INET6
694 pai->ai_family = PF_INET6;
695#else
696 pai->ai_family = PF_INET;
697#endif
698 }
699 error = get_portmatch(pai, servname);
700 if (error)
701 ERR(error);
702
703 *pai = ai0;
704 }
705
706 ai0 = *pai;
707
708 /* NULL hostname, or numeric hostname */
709 for (ex = explore; ex->e_af >= 0; ex++) {
710 *pai = ai0;
711
712 /* PF_UNSPEC entries are prepared for DNS queries only */
713 if (ex->e_af == PF_UNSPEC)
714 continue;
715
716 if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
717 continue;
718 if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex)))
719 continue;
720 if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex)))
721 continue;
722
723 if (pai->ai_family == PF_UNSPEC)
724 pai->ai_family = ex->e_af;
725 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
726 pai->ai_socktype = ex->e_socktype;
727 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
728 pai->ai_protocol = ex->e_protocol;
729
730 if (hostname == NULL)
731 error = explore_null(pai, servname, &cur->ai_next);
732 else
733 error = explore_numeric_scope(pai, hostname, servname,
734 &cur->ai_next);
735
736 if (error)
737 goto free;
738
739 while (cur->ai_next)
740 cur = cur->ai_next;
741 }
742
743 /*
744 * XXX
745 * If numeric representation of AF1 can be interpreted as FQDN
746 * representation of AF2, we need to think again about the code below.
747 */
748 if (sentinel.ai_next)
749 goto good;
750
751 if (hostname == NULL)
752 ERR(EAI_NODATA);
753 if (pai->ai_flags & AI_NUMERICHOST)
754 ERR(EAI_NONAME);
755
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700756 /*
757 * BEGIN ANDROID CHANGES; proxying to the cache
758 */
Mattias Falkc63e5902011-08-23 14:34:14 +0200759 if (cache_mode == NULL || strcmp(cache_mode, "local") != 0) {
760 // we're not the proxy - pass the request to them
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500761 return android_getaddrinfo_proxy(hostname, servname, hints, res, netid);
Mattias Falkc63e5902011-08-23 14:34:14 +0200762 }
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700763
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800764 /*
765 * hostname as alphabetical name.
766 * we would like to prefer AF_INET6 than AF_INET, so we'll make a
767 * outer loop by AFs.
768 */
769 for (ex = explore; ex->e_af >= 0; ex++) {
770 *pai = ai0;
771
772 /* require exact match for family field */
773 if (pai->ai_family != ex->e_af)
774 continue;
775
776 if (!MATCH(pai->ai_socktype, ex->e_socktype,
777 WILD_SOCKTYPE(ex))) {
778 continue;
779 }
780 if (!MATCH(pai->ai_protocol, ex->e_protocol,
781 WILD_PROTOCOL(ex))) {
782 continue;
783 }
784
785 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
786 pai->ai_socktype = ex->e_socktype;
787 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
788 pai->ai_protocol = ex->e_protocol;
789
790 error = explore_fqdn(pai, hostname, servname,
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500791 &cur->ai_next, netid, mark);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800792
793 while (cur && cur->ai_next)
794 cur = cur->ai_next;
795 }
796
797 /* XXX */
798 if (sentinel.ai_next)
799 error = 0;
800
801 if (error)
802 goto free;
803 if (error == 0) {
804 if (sentinel.ai_next) {
805 good:
806 *res = sentinel.ai_next;
807 return SUCCESS;
808 } else
809 error = EAI_FAIL;
810 }
811 free:
812 bad:
813 if (sentinel.ai_next)
814 freeaddrinfo(sentinel.ai_next);
815 *res = NULL;
816 return error;
817}
818
819/*
820 * FQDN hostname, DNS lookup
821 */
822static int
823explore_fqdn(const struct addrinfo *pai, const char *hostname,
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500824 const char *servname, struct addrinfo **res, unsigned netid, unsigned mark)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800825{
826 struct addrinfo *result;
827 struct addrinfo *cur;
828 int error = 0;
829 static const ns_dtab dtab[] = {
830 NS_FILES_CB(_files_getaddrinfo, NULL)
831 { NSSRC_DNS, _dns_getaddrinfo, NULL }, /* force -DHESIOD */
832 NS_NIS_CB(_yp_getaddrinfo, NULL)
833 { 0, 0, 0 }
834 };
835
836 assert(pai != NULL);
837 /* hostname may be NULL */
838 /* servname may be NULL */
839 assert(res != NULL);
840
841 result = NULL;
842
843 /*
844 * if the servname does not match socktype/protocol, ignore it.
845 */
846 if (get_portmatch(pai, servname) != 0)
847 return 0;
848
849 switch (nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500850 default_dns_files, hostname, pai, netid, mark)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800851 case NS_TRYAGAIN:
852 error = EAI_AGAIN;
853 goto free;
854 case NS_UNAVAIL:
855 error = EAI_FAIL;
856 goto free;
857 case NS_NOTFOUND:
858 error = EAI_NODATA;
859 goto free;
860 case NS_SUCCESS:
861 error = 0;
862 for (cur = result; cur; cur = cur->ai_next) {
863 GET_PORT(cur, servname);
864 /* canonname should be filled already */
865 }
866 break;
867 }
868
869 *res = result;
870
871 return 0;
872
873free:
874 if (result)
875 freeaddrinfo(result);
876 return error;
877}
878
879/*
880 * hostname == NULL.
881 * passive socket -> anyaddr (0.0.0.0 or ::)
882 * non-passive socket -> localhost (127.0.0.1 or ::1)
883 */
884static int
885explore_null(const struct addrinfo *pai, const char *servname,
886 struct addrinfo **res)
887{
888 int s;
889 const struct afd *afd;
890 struct addrinfo *cur;
891 struct addrinfo sentinel;
892 int error;
893
894 assert(pai != NULL);
895 /* servname may be NULL */
896 assert(res != NULL);
897
898 *res = NULL;
899 sentinel.ai_next = NULL;
900 cur = &sentinel;
901
902 /*
903 * filter out AFs that are not supported by the kernel
904 * XXX errno?
905 */
Nick Kralevich1781ed72014-06-29 20:46:17 -0700906 s = socket(pai->ai_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800907 if (s < 0) {
908 if (errno != EMFILE)
909 return 0;
910 } else
911 close(s);
912
913 /*
914 * if the servname does not match socktype/protocol, ignore it.
915 */
916 if (get_portmatch(pai, servname) != 0)
917 return 0;
918
919 afd = find_afd(pai->ai_family);
920 if (afd == NULL)
921 return 0;
922
923 if (pai->ai_flags & AI_PASSIVE) {
924 GET_AI(cur->ai_next, afd, afd->a_addrany);
925 /* xxx meaningless?
926 * GET_CANONNAME(cur->ai_next, "anyaddr");
927 */
928 GET_PORT(cur->ai_next, servname);
929 } else {
930 GET_AI(cur->ai_next, afd, afd->a_loopback);
931 /* xxx meaningless?
932 * GET_CANONNAME(cur->ai_next, "localhost");
933 */
934 GET_PORT(cur->ai_next, servname);
935 }
936 cur = cur->ai_next;
937
938 *res = sentinel.ai_next;
939 return 0;
940
941free:
942 if (sentinel.ai_next)
943 freeaddrinfo(sentinel.ai_next);
944 return error;
945}
946
947/*
948 * numeric hostname
949 */
950static int
951explore_numeric(const struct addrinfo *pai, const char *hostname,
952 const char *servname, struct addrinfo **res, const char *canonname)
953{
954 const struct afd *afd;
955 struct addrinfo *cur;
956 struct addrinfo sentinel;
957 int error;
958 char pton[PTON_MAX];
959
960 assert(pai != NULL);
961 /* hostname may be NULL */
962 /* servname may be NULL */
963 assert(res != NULL);
964
965 *res = NULL;
966 sentinel.ai_next = NULL;
967 cur = &sentinel;
968
969 /*
970 * if the servname does not match socktype/protocol, ignore it.
971 */
972 if (get_portmatch(pai, servname) != 0)
973 return 0;
974
975 afd = find_afd(pai->ai_family);
976 if (afd == NULL)
977 return 0;
978
979 switch (afd->a_af) {
980#if 0 /*X/Open spec*/
981 case AF_INET:
982 if (inet_aton(hostname, (struct in_addr *)pton) == 1) {
983 if (pai->ai_family == afd->a_af ||
984 pai->ai_family == PF_UNSPEC /*?*/) {
985 GET_AI(cur->ai_next, afd, pton);
986 GET_PORT(cur->ai_next, servname);
987 if ((pai->ai_flags & AI_CANONNAME)) {
988 /*
989 * Set the numeric address itself as
990 * the canonical name, based on a
991 * clarification in rfc2553bis-03.
992 */
993 GET_CANONNAME(cur->ai_next, canonname);
994 }
995 while (cur && cur->ai_next)
996 cur = cur->ai_next;
997 } else
998 ERR(EAI_FAMILY); /*xxx*/
999 }
1000 break;
1001#endif
1002 default:
1003 if (inet_pton(afd->a_af, hostname, pton) == 1) {
1004 if (pai->ai_family == afd->a_af ||
1005 pai->ai_family == PF_UNSPEC /*?*/) {
1006 GET_AI(cur->ai_next, afd, pton);
1007 GET_PORT(cur->ai_next, servname);
1008 if ((pai->ai_flags & AI_CANONNAME)) {
1009 /*
1010 * Set the numeric address itself as
1011 * the canonical name, based on a
1012 * clarification in rfc2553bis-03.
1013 */
1014 GET_CANONNAME(cur->ai_next, canonname);
1015 }
1016 while (cur->ai_next)
1017 cur = cur->ai_next;
1018 } else
1019 ERR(EAI_FAMILY); /*xxx*/
1020 }
1021 break;
1022 }
1023
1024 *res = sentinel.ai_next;
1025 return 0;
1026
1027free:
1028bad:
1029 if (sentinel.ai_next)
1030 freeaddrinfo(sentinel.ai_next);
1031 return error;
1032}
1033
1034/*
1035 * numeric hostname with scope
1036 */
1037static int
1038explore_numeric_scope(const struct addrinfo *pai, const char *hostname,
1039 const char *servname, struct addrinfo **res)
1040{
1041#if !defined(SCOPE_DELIMITER) || !defined(INET6)
1042 return explore_numeric(pai, hostname, servname, res, hostname);
1043#else
1044 const struct afd *afd;
1045 struct addrinfo *cur;
1046 int error;
1047 char *cp, *hostname2 = NULL, *scope, *addr;
1048 struct sockaddr_in6 *sin6;
1049
1050 assert(pai != NULL);
1051 /* hostname may be NULL */
1052 /* servname may be NULL */
1053 assert(res != NULL);
1054
1055 /*
1056 * if the servname does not match socktype/protocol, ignore it.
1057 */
1058 if (get_portmatch(pai, servname) != 0)
1059 return 0;
1060
1061 afd = find_afd(pai->ai_family);
1062 if (afd == NULL)
1063 return 0;
1064
1065 if (!afd->a_scoped)
1066 return explore_numeric(pai, hostname, servname, res, hostname);
1067
1068 cp = strchr(hostname, SCOPE_DELIMITER);
1069 if (cp == NULL)
1070 return explore_numeric(pai, hostname, servname, res, hostname);
1071
1072 /*
1073 * Handle special case of <scoped_address><delimiter><scope id>
1074 */
1075 hostname2 = strdup(hostname);
1076 if (hostname2 == NULL)
1077 return EAI_MEMORY;
1078 /* terminate at the delimiter */
1079 hostname2[cp - hostname] = '\0';
1080 addr = hostname2;
1081 scope = cp + 1;
1082
1083 error = explore_numeric(pai, addr, servname, res, hostname);
1084 if (error == 0) {
1085 u_int32_t scopeid;
1086
1087 for (cur = *res; cur; cur = cur->ai_next) {
1088 if (cur->ai_family != AF_INET6)
1089 continue;
1090 sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
1091 if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) {
1092 free(hostname2);
1093 return(EAI_NODATA); /* XXX: is return OK? */
1094 }
1095 sin6->sin6_scope_id = scopeid;
1096 }
1097 }
1098
1099 free(hostname2);
1100
1101 return error;
1102#endif
1103}
1104
1105static int
1106get_canonname(const struct addrinfo *pai, struct addrinfo *ai, const char *str)
1107{
1108
1109 assert(pai != NULL);
1110 assert(ai != NULL);
1111 assert(str != NULL);
1112
1113 if ((pai->ai_flags & AI_CANONNAME) != 0) {
1114 ai->ai_canonname = strdup(str);
1115 if (ai->ai_canonname == NULL)
1116 return EAI_MEMORY;
1117 }
1118 return 0;
1119}
1120
1121static struct addrinfo *
1122get_ai(const struct addrinfo *pai, const struct afd *afd, const char *addr)
1123{
1124 char *p;
1125 struct addrinfo *ai;
1126
1127 assert(pai != NULL);
1128 assert(afd != NULL);
1129 assert(addr != NULL);
1130
1131 ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
1132 + (afd->a_socklen));
1133 if (ai == NULL)
1134 return NULL;
1135
1136 memcpy(ai, pai, sizeof(struct addrinfo));
1137 ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
1138 memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
1139
1140#ifdef HAVE_SA_LEN
1141 ai->ai_addr->sa_len = afd->a_socklen;
1142#endif
1143
1144 ai->ai_addrlen = afd->a_socklen;
1145#if defined (__alpha__) || (defined(__i386__) && defined(_LP64)) || defined(__sparc64__)
1146 ai->__ai_pad0 = 0;
1147#endif
1148 ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
1149 p = (char *)(void *)(ai->ai_addr);
1150 memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
1151 return ai;
1152}
1153
1154static int
1155get_portmatch(const struct addrinfo *ai, const char *servname)
1156{
1157
1158 assert(ai != NULL);
1159 /* servname may be NULL */
1160
1161 return get_port(ai, servname, 1);
1162}
1163
1164static int
1165get_port(const struct addrinfo *ai, const char *servname, int matchonly)
1166{
1167 const char *proto;
1168 struct servent *sp;
1169 int port;
1170 int allownumeric;
1171
1172 assert(ai != NULL);
1173 /* servname may be NULL */
1174
1175 if (servname == NULL)
1176 return 0;
1177 switch (ai->ai_family) {
1178 case AF_INET:
1179#ifdef AF_INET6
1180 case AF_INET6:
1181#endif
1182 break;
1183 default:
1184 return 0;
1185 }
1186
1187 switch (ai->ai_socktype) {
1188 case SOCK_RAW:
1189 return EAI_SERVICE;
1190 case SOCK_DGRAM:
1191 case SOCK_STREAM:
1192 allownumeric = 1;
1193 break;
1194 case ANY:
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001195#if 1 /* ANDROID-SPECIFIC CHANGE TO MATCH GLIBC */
David 'Digit' Turner5e563702009-05-05 15:50:24 +02001196 allownumeric = 1;
1197#else
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001198 allownumeric = 0;
David 'Digit' Turner5e563702009-05-05 15:50:24 +02001199#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001200 break;
1201 default:
1202 return EAI_SOCKTYPE;
1203 }
1204
1205 port = str2number(servname);
1206 if (port >= 0) {
1207 if (!allownumeric)
1208 return EAI_SERVICE;
1209 if (port < 0 || port > 65535)
1210 return EAI_SERVICE;
1211 port = htons(port);
1212 } else {
1213 if (ai->ai_flags & AI_NUMERICSERV)
1214 return EAI_NONAME;
1215
1216 switch (ai->ai_socktype) {
1217 case SOCK_DGRAM:
1218 proto = "udp";
1219 break;
1220 case SOCK_STREAM:
1221 proto = "tcp";
1222 break;
1223 default:
1224 proto = NULL;
1225 break;
1226 }
1227
1228 if ((sp = getservbyname(servname, proto)) == NULL)
1229 return EAI_SERVICE;
1230 port = sp->s_port;
1231 }
1232
1233 if (!matchonly) {
1234 switch (ai->ai_family) {
1235 case AF_INET:
1236 ((struct sockaddr_in *)(void *)
1237 ai->ai_addr)->sin_port = port;
1238 break;
1239#ifdef INET6
1240 case AF_INET6:
1241 ((struct sockaddr_in6 *)(void *)
1242 ai->ai_addr)->sin6_port = port;
1243 break;
1244#endif
1245 }
1246 }
1247
1248 return 0;
1249}
1250
1251static const struct afd *
1252find_afd(int af)
1253{
1254 const struct afd *afd;
1255
1256 if (af == PF_UNSPEC)
1257 return NULL;
1258 for (afd = afdl; afd->a_af; afd++) {
1259 if (afd->a_af == af)
1260 return afd;
1261 }
1262 return NULL;
1263}
1264
1265#ifdef INET6
1266/* convert a string to a scope identifier. XXX: IPv6 specific */
1267static int
1268ip6_str2scopeid(char *scope, struct sockaddr_in6 *sin6, u_int32_t *scopeid)
1269{
1270 u_long lscopeid;
1271 struct in6_addr *a6;
1272 char *ep;
1273
1274 assert(scope != NULL);
1275 assert(sin6 != NULL);
1276 assert(scopeid != NULL);
1277
1278 a6 = &sin6->sin6_addr;
1279
1280 /* empty scopeid portion is invalid */
1281 if (*scope == '\0')
1282 return -1;
1283
1284 if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
1285 /*
1286 * We currently assume a one-to-one mapping between links
1287 * and interfaces, so we simply use interface indices for
1288 * like-local scopes.
1289 */
1290 *scopeid = if_nametoindex(scope);
1291 if (*scopeid == 0)
1292 goto trynumeric;
1293 return 0;
1294 }
1295
1296 /* still unclear about literal, allow numeric only - placeholder */
1297 if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
1298 goto trynumeric;
1299 if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
1300 goto trynumeric;
1301 else
1302 goto trynumeric; /* global */
1303
1304 /* try to convert to a numeric id as a last resort */
1305 trynumeric:
1306 errno = 0;
1307 lscopeid = strtoul(scope, &ep, 10);
1308 *scopeid = (u_int32_t)(lscopeid & 0xffffffffUL);
1309 if (errno == 0 && ep && *ep == '\0' && *scopeid == lscopeid)
1310 return 0;
1311 else
1312 return -1;
1313}
1314#endif
1315
1316/* code duplicate with gethnamaddr.c */
1317
1318static const char AskedForGot[] =
1319 "gethostby*.getanswer: asked for \"%s\", got \"%s\"";
1320
1321static struct addrinfo *
1322getanswer(const querybuf *answer, int anslen, const char *qname, int qtype,
1323 const struct addrinfo *pai)
1324{
1325 struct addrinfo sentinel, *cur;
1326 struct addrinfo ai;
1327 const struct afd *afd;
1328 char *canonname;
1329 const HEADER *hp;
1330 const u_char *cp;
1331 int n;
1332 const u_char *eom;
1333 char *bp, *ep;
1334 int type, class, ancount, qdcount;
1335 int haveanswer, had_error;
1336 char tbuf[MAXDNAME];
1337 int (*name_ok) (const char *);
1338 char hostbuf[8*1024];
1339
1340 assert(answer != NULL);
1341 assert(qname != NULL);
1342 assert(pai != NULL);
1343
1344 memset(&sentinel, 0, sizeof(sentinel));
1345 cur = &sentinel;
1346
1347 canonname = NULL;
1348 eom = answer->buf + anslen;
1349 switch (qtype) {
1350 case T_A:
1351 case T_AAAA:
1352 case T_ANY: /*use T_ANY only for T_A/T_AAAA lookup*/
1353 name_ok = res_hnok;
1354 break;
1355 default:
1356 return NULL; /* XXX should be abort(); */
1357 }
1358 /*
1359 * find first satisfactory answer
1360 */
1361 hp = &answer->hdr;
1362 ancount = ntohs(hp->ancount);
1363 qdcount = ntohs(hp->qdcount);
1364 bp = hostbuf;
1365 ep = hostbuf + sizeof hostbuf;
1366 cp = answer->buf + HFIXEDSZ;
1367 if (qdcount != 1) {
1368 h_errno = NO_RECOVERY;
1369 return (NULL);
1370 }
1371 n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1372 if ((n < 0) || !(*name_ok)(bp)) {
1373 h_errno = NO_RECOVERY;
1374 return (NULL);
1375 }
1376 cp += n + QFIXEDSZ;
1377 if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
1378 /* res_send() has already verified that the query name is the
1379 * same as the one we sent; this just gets the expanded name
1380 * (i.e., with the succeeding search-domain tacked on).
1381 */
1382 n = strlen(bp) + 1; /* for the \0 */
1383 if (n >= MAXHOSTNAMELEN) {
1384 h_errno = NO_RECOVERY;
1385 return (NULL);
1386 }
1387 canonname = bp;
1388 bp += n;
1389 /* The qname can be abbreviated, but h_name is now absolute. */
1390 qname = canonname;
1391 }
1392 haveanswer = 0;
1393 had_error = 0;
1394 while (ancount-- > 0 && cp < eom && !had_error) {
1395 n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1396 if ((n < 0) || !(*name_ok)(bp)) {
1397 had_error++;
1398 continue;
1399 }
1400 cp += n; /* name */
1401 type = _getshort(cp);
Lorenzo Colittib82532d2011-09-28 19:28:32 -07001402 cp += INT16SZ; /* type */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001403 class = _getshort(cp);
Lorenzo Colittib82532d2011-09-28 19:28:32 -07001404 cp += INT16SZ + INT32SZ; /* class, TTL */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001405 n = _getshort(cp);
1406 cp += INT16SZ; /* len */
1407 if (class != C_IN) {
1408 /* XXX - debug? syslog? */
1409 cp += n;
1410 continue; /* XXX - had_error++ ? */
1411 }
1412 if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
1413 type == T_CNAME) {
1414 n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
1415 if ((n < 0) || !(*name_ok)(tbuf)) {
1416 had_error++;
1417 continue;
1418 }
1419 cp += n;
1420 /* Get canonical name. */
1421 n = strlen(tbuf) + 1; /* for the \0 */
1422 if (n > ep - bp || n >= MAXHOSTNAMELEN) {
1423 had_error++;
1424 continue;
1425 }
1426 strlcpy(bp, tbuf, (size_t)(ep - bp));
1427 canonname = bp;
1428 bp += n;
1429 continue;
1430 }
1431 if (qtype == T_ANY) {
1432 if (!(type == T_A || type == T_AAAA)) {
1433 cp += n;
1434 continue;
1435 }
1436 } else if (type != qtype) {
1437 if (type != T_KEY && type != T_SIG)
1438 syslog(LOG_NOTICE|LOG_AUTH,
1439 "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
1440 qname, p_class(C_IN), p_type(qtype),
1441 p_type(type));
1442 cp += n;
1443 continue; /* XXX - had_error++ ? */
1444 }
1445 switch (type) {
1446 case T_A:
1447 case T_AAAA:
1448 if (strcasecmp(canonname, bp) != 0) {
1449 syslog(LOG_NOTICE|LOG_AUTH,
1450 AskedForGot, canonname, bp);
1451 cp += n;
1452 continue; /* XXX - had_error++ ? */
1453 }
1454 if (type == T_A && n != INADDRSZ) {
1455 cp += n;
1456 continue;
1457 }
1458 if (type == T_AAAA && n != IN6ADDRSZ) {
1459 cp += n;
1460 continue;
1461 }
1462 if (type == T_AAAA) {
1463 struct in6_addr in6;
1464 memcpy(&in6, cp, IN6ADDRSZ);
1465 if (IN6_IS_ADDR_V4MAPPED(&in6)) {
1466 cp += n;
1467 continue;
1468 }
1469 }
1470 if (!haveanswer) {
1471 int nn;
1472
1473 canonname = bp;
1474 nn = strlen(bp) + 1; /* for the \0 */
1475 bp += nn;
1476 }
1477
1478 /* don't overwrite pai */
1479 ai = *pai;
1480 ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
1481 afd = find_afd(ai.ai_family);
1482 if (afd == NULL) {
1483 cp += n;
1484 continue;
1485 }
1486 cur->ai_next = get_ai(&ai, afd, (const char *)cp);
1487 if (cur->ai_next == NULL)
1488 had_error++;
1489 while (cur && cur->ai_next)
1490 cur = cur->ai_next;
1491 cp += n;
1492 break;
1493 default:
1494 abort();
1495 }
1496 if (!had_error)
1497 haveanswer++;
1498 }
1499 if (haveanswer) {
1500 if (!canonname)
1501 (void)get_canonname(pai, sentinel.ai_next, qname);
1502 else
1503 (void)get_canonname(pai, sentinel.ai_next, canonname);
1504 h_errno = NETDB_SUCCESS;
1505 return sentinel.ai_next;
1506 }
1507
1508 h_errno = NO_RECOVERY;
1509 return NULL;
1510}
1511
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001512struct addrinfo_sort_elem {
1513 struct addrinfo *ai;
1514 int has_src_addr;
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001515 sockaddr_union src_addr;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001516 int original_order;
1517};
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001518
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001519/*ARGSUSED*/
1520static int
1521_get_scope(const struct sockaddr *addr)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001522{
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001523 if (addr->sa_family == AF_INET6) {
1524 const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)addr;
1525 if (IN6_IS_ADDR_MULTICAST(&addr6->sin6_addr)) {
1526 return IPV6_ADDR_MC_SCOPE(&addr6->sin6_addr);
1527 } else if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr) ||
1528 IN6_IS_ADDR_LINKLOCAL(&addr6->sin6_addr)) {
1529 /*
1530 * RFC 4291 section 2.5.3 says loopback is to be treated as having
1531 * link-local scope.
1532 */
1533 return IPV6_ADDR_SCOPE_LINKLOCAL;
1534 } else if (IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr)) {
1535 return IPV6_ADDR_SCOPE_SITELOCAL;
1536 } else {
1537 return IPV6_ADDR_SCOPE_GLOBAL;
1538 }
1539 } else if (addr->sa_family == AF_INET) {
1540 const struct sockaddr_in *addr4 = (const struct sockaddr_in *)addr;
1541 unsigned long int na = ntohl(addr4->sin_addr.s_addr);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001542
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001543 if (IN_LOOPBACK(na) || /* 127.0.0.0/8 */
1544 (na & 0xffff0000) == 0xa9fe0000) { /* 169.254.0.0/16 */
1545 return IPV6_ADDR_SCOPE_LINKLOCAL;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001546 } else {
Steinar H. Gundersond1624ad2010-12-20 11:15:33 +01001547 /*
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001548 * RFC 6724 section 3.2. Other IPv4 addresses, including private addresses
1549 * and shared addresses (100.64.0.0/10), are assigned global scope.
Steinar H. Gundersond1624ad2010-12-20 11:15:33 +01001550 */
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001551 return IPV6_ADDR_SCOPE_GLOBAL;
1552 }
1553 } else {
1554 /*
1555 * This should never happen.
1556 * Return a scope with low priority as a last resort.
1557 */
1558 return IPV6_ADDR_SCOPE_NODELOCAL;
1559 }
1560}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001561
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001562/* These macros are modelled after the ones in <netinet/in6.h>. */
1563
1564/* RFC 4380, section 2.6 */
1565#define IN6_IS_ADDR_TEREDO(a) \
1566 ((*(const uint32_t *)(const void *)(&(a)->s6_addr[0]) == ntohl(0x20010000)))
1567
1568/* RFC 3056, section 2. */
1569#define IN6_IS_ADDR_6TO4(a) \
1570 (((a)->s6_addr[0] == 0x20) && ((a)->s6_addr[1] == 0x02))
1571
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001572/* 6bone testing address area (3ffe::/16), deprecated in RFC 3701. */
1573#define IN6_IS_ADDR_6BONE(a) \
1574 (((a)->s6_addr[0] == 0x3f) && ((a)->s6_addr[1] == 0xfe))
1575
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001576/*
1577 * Get the label for a given IPv4/IPv6 address.
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001578 * RFC 6724, section 2.1.
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001579 */
1580
1581/*ARGSUSED*/
1582static int
1583_get_label(const struct sockaddr *addr)
1584{
1585 if (addr->sa_family == AF_INET) {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001586 return 4;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001587 } else if (addr->sa_family == AF_INET6) {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001588 const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *) addr;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001589 if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr)) {
1590 return 0;
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001591 } else if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001592 return 4;
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001593 } else if (IN6_IS_ADDR_6TO4(&addr6->sin6_addr)) {
1594 return 2;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001595 } else if (IN6_IS_ADDR_TEREDO(&addr6->sin6_addr)) {
1596 return 5;
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001597 } else if (IN6_IS_ADDR_ULA(&addr6->sin6_addr)) {
1598 return 13;
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001599 } else if (IN6_IS_ADDR_V4COMPAT(&addr6->sin6_addr)) {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001600 return 3;
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001601 } else if (IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr)) {
1602 return 11;
1603 } else if (IN6_IS_ADDR_6BONE(&addr6->sin6_addr)) {
1604 return 12;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001605 } else {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001606 /* All other IPv6 addresses, including global unicast addresses. */
1607 return 1;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001608 }
1609 } else {
1610 /*
1611 * This should never happen.
1612 * Return a semi-random label as a last resort.
1613 */
1614 return 1;
1615 }
1616}
1617
1618/*
1619 * Get the precedence for a given IPv4/IPv6 address.
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001620 * RFC 6724, section 2.1.
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001621 */
1622
1623/*ARGSUSED*/
1624static int
1625_get_precedence(const struct sockaddr *addr)
1626{
1627 if (addr->sa_family == AF_INET) {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001628 return 35;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001629 } else if (addr->sa_family == AF_INET6) {
1630 const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)addr;
1631 if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr)) {
1632 return 50;
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001633 } else if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001634 return 35;
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001635 } else if (IN6_IS_ADDR_6TO4(&addr6->sin6_addr)) {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001636 return 30;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001637 } else if (IN6_IS_ADDR_TEREDO(&addr6->sin6_addr)) {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001638 return 5;
1639 } else if (IN6_IS_ADDR_ULA(&addr6->sin6_addr)) {
1640 return 3;
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001641 } else if (IN6_IS_ADDR_V4COMPAT(&addr6->sin6_addr) ||
Lorenzo Colittib82532d2011-09-28 19:28:32 -07001642 IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr) ||
1643 IN6_IS_ADDR_6BONE(&addr6->sin6_addr)) {
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001644 return 1;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001645 } else {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001646 /* All other IPv6 addresses, including global unicast addresses. */
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001647 return 40;
1648 }
1649 } else {
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001650 return 1;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001651 }
1652}
1653
1654/*
1655 * Find number of matching initial bits between the two addresses a1 and a2.
1656 */
1657
1658/*ARGSUSED*/
1659static int
1660_common_prefix_len(const struct in6_addr *a1, const struct in6_addr *a2)
1661{
1662 const char *p1 = (const char *)a1;
1663 const char *p2 = (const char *)a2;
1664 unsigned i;
1665
1666 for (i = 0; i < sizeof(*a1); ++i) {
1667 int x, j;
1668
1669 if (p1[i] == p2[i]) {
1670 continue;
1671 }
1672 x = p1[i] ^ p2[i];
1673 for (j = 0; j < CHAR_BIT; ++j) {
1674 if (x & (1 << (CHAR_BIT - 1))) {
1675 return i * CHAR_BIT + j;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001676 }
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001677 x <<= 1;
1678 }
1679 }
1680 return sizeof(*a1) * CHAR_BIT;
1681}
1682
1683/*
1684 * Compare two source/destination address pairs.
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001685 * RFC 6724, section 6.
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001686 */
1687
1688/*ARGSUSED*/
1689static int
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001690_rfc6724_compare(const void *ptr1, const void* ptr2)
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001691{
1692 const struct addrinfo_sort_elem *a1 = (const struct addrinfo_sort_elem *)ptr1;
1693 const struct addrinfo_sort_elem *a2 = (const struct addrinfo_sort_elem *)ptr2;
1694 int scope_src1, scope_dst1, scope_match1;
1695 int scope_src2, scope_dst2, scope_match2;
1696 int label_src1, label_dst1, label_match1;
1697 int label_src2, label_dst2, label_match2;
1698 int precedence1, precedence2;
1699 int prefixlen1, prefixlen2;
1700
1701 /* Rule 1: Avoid unusable destinations. */
1702 if (a1->has_src_addr != a2->has_src_addr) {
1703 return a2->has_src_addr - a1->has_src_addr;
1704 }
1705
1706 /* Rule 2: Prefer matching scope. */
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001707 scope_src1 = _get_scope(&a1->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001708 scope_dst1 = _get_scope(a1->ai->ai_addr);
1709 scope_match1 = (scope_src1 == scope_dst1);
1710
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001711 scope_src2 = _get_scope(&a2->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001712 scope_dst2 = _get_scope(a2->ai->ai_addr);
1713 scope_match2 = (scope_src2 == scope_dst2);
1714
1715 if (scope_match1 != scope_match2) {
1716 return scope_match2 - scope_match1;
1717 }
1718
1719 /*
1720 * Rule 3: Avoid deprecated addresses.
1721 * TODO(sesse): We don't currently have a good way of finding this.
1722 */
1723
1724 /*
1725 * Rule 4: Prefer home addresses.
1726 * TODO(sesse): We don't currently have a good way of finding this.
1727 */
1728
1729 /* Rule 5: Prefer matching label. */
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001730 label_src1 = _get_label(&a1->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001731 label_dst1 = _get_label(a1->ai->ai_addr);
1732 label_match1 = (label_src1 == label_dst1);
1733
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001734 label_src2 = _get_label(&a2->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001735 label_dst2 = _get_label(a2->ai->ai_addr);
1736 label_match2 = (label_src2 == label_dst2);
1737
1738 if (label_match1 != label_match2) {
1739 return label_match2 - label_match1;
1740 }
1741
1742 /* Rule 6: Prefer higher precedence. */
1743 precedence1 = _get_precedence(a1->ai->ai_addr);
1744 precedence2 = _get_precedence(a2->ai->ai_addr);
1745 if (precedence1 != precedence2) {
1746 return precedence2 - precedence1;
1747 }
1748
1749 /*
1750 * Rule 7: Prefer native transport.
1751 * TODO(sesse): We don't currently have a good way of finding this.
1752 */
1753
1754 /* Rule 8: Prefer smaller scope. */
1755 if (scope_dst1 != scope_dst2) {
1756 return scope_dst1 - scope_dst2;
1757 }
1758
1759 /*
1760 * Rule 9: Use longest matching prefix.
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001761 * We implement this for IPv6 only, as the rules in RFC 6724 don't seem
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001762 * to work very well directly applied to IPv4. (glibc uses information from
1763 * the routing table for a custom IPv4 implementation here.)
1764 */
1765 if (a1->has_src_addr && a1->ai->ai_addr->sa_family == AF_INET6 &&
1766 a2->has_src_addr && a2->ai->ai_addr->sa_family == AF_INET6) {
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001767 const struct sockaddr_in6 *a1_src = &a1->src_addr.in6;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001768 const struct sockaddr_in6 *a1_dst = (const struct sockaddr_in6 *)a1->ai->ai_addr;
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001769 const struct sockaddr_in6 *a2_src = &a2->src_addr.in6;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001770 const struct sockaddr_in6 *a2_dst = (const struct sockaddr_in6 *)a2->ai->ai_addr;
1771 prefixlen1 = _common_prefix_len(&a1_src->sin6_addr, &a1_dst->sin6_addr);
Kenny Root7e0bfb52010-03-24 18:06:20 -07001772 prefixlen2 = _common_prefix_len(&a2_src->sin6_addr, &a2_dst->sin6_addr);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001773 if (prefixlen1 != prefixlen2) {
1774 return prefixlen2 - prefixlen1;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001775 }
1776 }
1777
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001778 /*
1779 * Rule 10: Leave the order unchanged.
1780 * We need this since qsort() is not necessarily stable.
1781 */
1782 return a1->original_order - a2->original_order;
1783}
1784
1785/*
1786 * Find the source address that will be used if trying to connect to the given
1787 * address. src_addr must be large enough to hold a struct sockaddr_in6.
1788 *
1789 * Returns 1 if a source address was found, 0 if the address is unreachable,
1790 * and -1 if a fatal error occurred. If 0 or 1, the contents of src_addr are
1791 * undefined.
1792 */
1793
1794/*ARGSUSED*/
1795static int
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001796_find_src_addr(const struct sockaddr *addr, struct sockaddr *src_addr, unsigned mark)
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001797{
1798 int sock;
1799 int ret;
1800 socklen_t len;
1801
1802 switch (addr->sa_family) {
1803 case AF_INET:
1804 len = sizeof(struct sockaddr_in);
1805 break;
1806 case AF_INET6:
1807 len = sizeof(struct sockaddr_in6);
1808 break;
1809 default:
1810 /* No known usable source address for non-INET families. */
1811 return 0;
1812 }
1813
Nick Kralevich1781ed72014-06-29 20:46:17 -07001814 sock = socket(addr->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001815 if (sock == -1) {
1816 if (errno == EAFNOSUPPORT) {
1817 return 0;
1818 } else {
1819 return -1;
1820 }
1821 }
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001822 if (mark != MARK_UNSET && setsockopt(sock, SOL_SOCKET, SO_MARK, &mark, sizeof(mark)) < 0)
1823 return 0;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001824 do {
Paul Jensen31ad0372014-05-29 16:28:30 -04001825 ret = __connect(sock, addr, len);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001826 } while (ret == -1 && errno == EINTR);
1827
1828 if (ret == -1) {
1829 close(sock);
1830 return 0;
1831 }
1832
1833 if (getsockname(sock, src_addr, &len) == -1) {
1834 close(sock);
1835 return -1;
1836 }
1837 close(sock);
1838 return 1;
1839}
1840
1841/*
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001842 * Sort the linked list starting at sentinel->ai_next in RFC6724 order.
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001843 * Will leave the list unchanged if an error occurs.
1844 */
1845
1846/*ARGSUSED*/
1847static void
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001848_rfc6724_sort(struct addrinfo *list_sentinel, unsigned mark)
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001849{
1850 struct addrinfo *cur;
1851 int nelem = 0, i;
1852 struct addrinfo_sort_elem *elems;
1853
1854 cur = list_sentinel->ai_next;
1855 while (cur) {
1856 ++nelem;
1857 cur = cur->ai_next;
1858 }
1859
1860 elems = (struct addrinfo_sort_elem *)malloc(nelem * sizeof(struct addrinfo_sort_elem));
1861 if (elems == NULL) {
1862 goto error;
1863 }
1864
1865 /*
1866 * Convert the linked list to an array that also contains the candidate
1867 * source address for each destination address.
1868 */
1869 for (i = 0, cur = list_sentinel->ai_next; i < nelem; ++i, cur = cur->ai_next) {
1870 int has_src_addr;
1871 assert(cur != NULL);
1872 elems[i].ai = cur;
1873 elems[i].original_order = i;
1874
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001875 has_src_addr = _find_src_addr(cur->ai_addr, &elems[i].src_addr.generic, mark);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001876 if (has_src_addr == -1) {
1877 goto error;
1878 }
1879 elems[i].has_src_addr = has_src_addr;
1880 }
1881
1882 /* Sort the addresses, and rearrange the linked list so it matches the sorted order. */
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001883 qsort((void *)elems, nelem, sizeof(struct addrinfo_sort_elem), _rfc6724_compare);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001884
1885 list_sentinel->ai_next = elems[0].ai;
1886 for (i = 0; i < nelem - 1; ++i) {
1887 elems[i].ai->ai_next = elems[i + 1].ai;
1888 }
1889 elems[nelem - 1].ai->ai_next = NULL;
1890
1891error:
1892 free(elems);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001893}
1894
1895/*ARGSUSED*/
1896static int
1897_dns_getaddrinfo(void *rv, void *cb_data, va_list ap)
1898{
1899 struct addrinfo *ai;
1900 querybuf *buf, *buf2;
1901 const char *name;
1902 const struct addrinfo *pai;
1903 struct addrinfo sentinel, *cur;
1904 struct res_target q, q2;
1905 res_state res;
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001906 unsigned netid, mark;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001907
1908 name = va_arg(ap, char *);
1909 pai = va_arg(ap, const struct addrinfo *);
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001910 netid = va_arg(ap, unsigned);
1911 mark = va_arg(ap, unsigned);
David 'Digit' Turner5e563702009-05-05 15:50:24 +02001912 //fprintf(stderr, "_dns_getaddrinfo() name = '%s'\n", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001913
1914 memset(&q, 0, sizeof(q));
1915 memset(&q2, 0, sizeof(q2));
1916 memset(&sentinel, 0, sizeof(sentinel));
1917 cur = &sentinel;
1918
1919 buf = malloc(sizeof(*buf));
1920 if (buf == NULL) {
1921 h_errno = NETDB_INTERNAL;
1922 return NS_NOTFOUND;
1923 }
1924 buf2 = malloc(sizeof(*buf2));
1925 if (buf2 == NULL) {
1926 free(buf);
1927 h_errno = NETDB_INTERNAL;
1928 return NS_NOTFOUND;
1929 }
1930
1931 switch (pai->ai_family) {
1932 case AF_UNSPEC:
1933 /* prefer IPv6 */
1934 q.name = name;
1935 q.qclass = C_IN;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001936 q.answer = buf->buf;
1937 q.anslen = sizeof(buf->buf);
Lorenzo Colittiba96e302011-01-14 12:26:05 -08001938 int query_ipv6 = 1, query_ipv4 = 1;
1939 if (pai->ai_flags & AI_ADDRCONFIG) {
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001940 query_ipv6 = _have_ipv6(mark);
1941 query_ipv4 = _have_ipv4(mark);
Lorenzo Colittiba96e302011-01-14 12:26:05 -08001942 }
1943 if (query_ipv6) {
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -07001944 q.qtype = T_AAAA;
Lorenzo Colittiba96e302011-01-14 12:26:05 -08001945 if (query_ipv4) {
1946 q.next = &q2;
1947 q2.name = name;
1948 q2.qclass = C_IN;
1949 q2.qtype = T_A;
1950 q2.answer = buf2->buf;
1951 q2.anslen = sizeof(buf2->buf);
1952 }
1953 } else if (query_ipv4) {
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -07001954 q.qtype = T_A;
Lorenzo Colittiba96e302011-01-14 12:26:05 -08001955 } else {
1956 free(buf);
1957 free(buf2);
1958 return NS_NOTFOUND;
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -07001959 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001960 break;
1961 case AF_INET:
1962 q.name = name;
1963 q.qclass = C_IN;
1964 q.qtype = T_A;
1965 q.answer = buf->buf;
1966 q.anslen = sizeof(buf->buf);
1967 break;
1968 case AF_INET6:
1969 q.name = name;
1970 q.qclass = C_IN;
1971 q.qtype = T_AAAA;
1972 q.answer = buf->buf;
1973 q.anslen = sizeof(buf->buf);
1974 break;
1975 default:
1976 free(buf);
1977 free(buf2);
1978 return NS_UNAVAIL;
1979 }
1980
1981 res = __res_get_state();
1982 if (res == NULL) {
1983 free(buf);
1984 free(buf2);
1985 return NS_NOTFOUND;
1986 }
1987
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001988 /* this just sets our netid val in the thread private data so we don't have to
Mattias Falkc63e5902011-08-23 14:34:14 +02001989 * modify the api's all the way down to res_send.c's res_nsend. We could
1990 * fully populate the thread private data here, but if we get down there
1991 * and have a cache hit that would be wasted, so we do the rest there on miss
1992 */
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001993 res_setnetid(res, netid);
Chad Brubakerc39214e2013-06-20 10:36:56 -07001994 res_setmark(res, mark);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001995 if (res_searchN(name, &q, res) < 0) {
1996 __res_put_state(res);
1997 free(buf);
1998 free(buf2);
1999 return NS_NOTFOUND;
2000 }
2001 ai = getanswer(buf, q.n, q.name, q.qtype, pai);
2002 if (ai) {
2003 cur->ai_next = ai;
2004 while (cur && cur->ai_next)
2005 cur = cur->ai_next;
2006 }
2007 if (q.next) {
2008 ai = getanswer(buf2, q2.n, q2.name, q2.qtype, pai);
2009 if (ai)
2010 cur->ai_next = ai;
2011 }
2012 free(buf);
2013 free(buf2);
2014 if (sentinel.ai_next == NULL) {
2015 __res_put_state(res);
2016 switch (h_errno) {
2017 case HOST_NOT_FOUND:
2018 return NS_NOTFOUND;
2019 case TRY_AGAIN:
2020 return NS_TRYAGAIN;
2021 default:
2022 return NS_UNAVAIL;
2023 }
2024 }
2025
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05002026 _rfc6724_sort(&sentinel, netid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002027
2028 __res_put_state(res);
2029
2030 *((struct addrinfo **)rv) = sentinel.ai_next;
2031 return NS_SUCCESS;
2032}
2033
2034static void
2035_sethtent(FILE **hostf)
2036{
2037
2038 if (!*hostf)
Elliott Hughesc674edb2014-08-26 15:56:54 -07002039 *hostf = fopen(_PATH_HOSTS, "re");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002040 else
2041 rewind(*hostf);
2042}
2043
2044static void
2045_endhtent(FILE **hostf)
2046{
2047
2048 if (*hostf) {
2049 (void) fclose(*hostf);
2050 *hostf = NULL;
2051 }
2052}
2053
2054static struct addrinfo *
2055_gethtent(FILE **hostf, const char *name, const struct addrinfo *pai)
2056{
2057 char *p;
2058 char *cp, *tname, *cname;
2059 struct addrinfo hints, *res0, *res;
2060 int error;
2061 const char *addr;
2062 char hostbuf[8*1024];
2063
2064// fprintf(stderr, "_gethtent() name = '%s'\n", name);
2065 assert(name != NULL);
2066 assert(pai != NULL);
2067
Elliott Hughesc674edb2014-08-26 15:56:54 -07002068 if (!*hostf && !(*hostf = fopen(_PATH_HOSTS, "re")))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002069 return (NULL);
2070 again:
2071 if (!(p = fgets(hostbuf, sizeof hostbuf, *hostf)))
2072 return (NULL);
2073 if (*p == '#')
2074 goto again;
2075 if (!(cp = strpbrk(p, "#\n")))
2076 goto again;
2077 *cp = '\0';
2078 if (!(cp = strpbrk(p, " \t")))
2079 goto again;
2080 *cp++ = '\0';
2081 addr = p;
2082 /* if this is not something we're looking for, skip it. */
2083 cname = NULL;
2084 while (cp && *cp) {
2085 if (*cp == ' ' || *cp == '\t') {
2086 cp++;
2087 continue;
2088 }
2089 if (!cname)
2090 cname = cp;
2091 tname = cp;
2092 if ((cp = strpbrk(cp, " \t")) != NULL)
2093 *cp++ = '\0';
2094// fprintf(stderr, "\ttname = '%s'", tname);
2095 if (strcasecmp(name, tname) == 0)
2096 goto found;
2097 }
2098 goto again;
2099
2100found:
2101 hints = *pai;
2102 hints.ai_flags = AI_NUMERICHOST;
2103 error = getaddrinfo(addr, NULL, &hints, &res0);
2104 if (error)
2105 goto again;
2106 for (res = res0; res; res = res->ai_next) {
2107 /* cover it up */
2108 res->ai_flags = pai->ai_flags;
2109
2110 if (pai->ai_flags & AI_CANONNAME) {
2111 if (get_canonname(pai, res, cname) != 0) {
2112 freeaddrinfo(res0);
2113 goto again;
2114 }
2115 }
2116 }
2117 return res0;
2118}
2119
2120/*ARGSUSED*/
2121static int
2122_files_getaddrinfo(void *rv, void *cb_data, va_list ap)
2123{
2124 const char *name;
2125 const struct addrinfo *pai;
2126 struct addrinfo sentinel, *cur;
2127 struct addrinfo *p;
2128 FILE *hostf = NULL;
2129
2130 name = va_arg(ap, char *);
2131 pai = va_arg(ap, struct addrinfo *);
2132
2133// fprintf(stderr, "_files_getaddrinfo() name = '%s'\n", name);
2134 memset(&sentinel, 0, sizeof(sentinel));
2135 cur = &sentinel;
2136
2137 _sethtent(&hostf);
2138 while ((p = _gethtent(&hostf, name, pai)) != NULL) {
2139 cur->ai_next = p;
2140 while (cur && cur->ai_next)
2141 cur = cur->ai_next;
2142 }
2143 _endhtent(&hostf);
2144
2145 *((struct addrinfo **)rv) = sentinel.ai_next;
2146 if (sentinel.ai_next == NULL)
2147 return NS_NOTFOUND;
2148 return NS_SUCCESS;
2149}
2150
2151/* resolver logic */
2152
2153/*
2154 * Formulate a normal query, send, and await answer.
2155 * Returned answer is placed in supplied buffer "answer".
2156 * Perform preliminary check of answer, returning success only
2157 * if no error is indicated and the answer count is nonzero.
2158 * Return the size of the response on success, -1 on error.
2159 * Error number is left in h_errno.
2160 *
2161 * Caller must parse answer and determine whether it answers the question.
2162 */
2163static int
2164res_queryN(const char *name, /* domain name */ struct res_target *target,
2165 res_state res)
2166{
2167 u_char buf[MAXPACKET];
2168 HEADER *hp;
2169 int n;
2170 struct res_target *t;
2171 int rcode;
2172 int ancount;
2173
2174 assert(name != NULL);
2175 /* XXX: target may be NULL??? */
2176
2177 rcode = NOERROR;
2178 ancount = 0;
2179
2180 for (t = target; t; t = t->next) {
2181 int class, type;
2182 u_char *answer;
2183 int anslen;
2184
2185 hp = (HEADER *)(void *)t->answer;
2186 hp->rcode = NOERROR; /* default */
2187
2188 /* make it easier... */
2189 class = t->qclass;
2190 type = t->qtype;
2191 answer = t->answer;
2192 anslen = t->anslen;
2193#ifdef DEBUG
2194 if (res->options & RES_DEBUG)
2195 printf(";; res_nquery(%s, %d, %d)\n", name, class, type);
2196#endif
2197
2198 n = res_nmkquery(res, QUERY, name, class, type, NULL, 0, NULL,
2199 buf, sizeof(buf));
2200#ifdef RES_USE_EDNS0
2201 if (n > 0 && (res->options & RES_USE_EDNS0) != 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 DEBUG
2227 if (res->options & RES_DEBUG)
2228 printf(";; rcode = %u, ancount=%u\n", hp->rcode,
2229 ntohs(hp->ancount));
2230#endif
2231 continue;
2232 }
2233
2234 ancount += ntohs(hp->ancount);
2235
2236 t->n = n;
2237 }
2238
2239 if (ancount == 0) {
2240 switch (rcode) {
2241 case NXDOMAIN:
2242 h_errno = HOST_NOT_FOUND;
2243 break;
2244 case SERVFAIL:
2245 h_errno = TRY_AGAIN;
2246 break;
2247 case NOERROR:
2248 h_errno = NO_DATA;
2249 break;
2250 case FORMERR:
2251 case NOTIMP:
2252 case REFUSED:
2253 default:
2254 h_errno = NO_RECOVERY;
2255 break;
2256 }
2257 return -1;
2258 }
2259 return ancount;
2260}
2261
2262/*
2263 * Formulate a normal query, send, and retrieve answer in supplied buffer.
2264 * Return the size of the response on success, -1 on error.
2265 * If enabled, implement search rules until answer or unrecoverable failure
2266 * is detected. Error code, if any, is left in h_errno.
2267 */
2268static int
2269res_searchN(const char *name, struct res_target *target, res_state res)
2270{
2271 const char *cp, * const *domain;
2272 HEADER *hp;
2273 u_int dots;
2274 int trailing_dot, ret, saved_herrno;
2275 int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
2276
2277 assert(name != NULL);
2278 assert(target != NULL);
2279
2280 hp = (HEADER *)(void *)target->answer; /*XXX*/
2281
2282 errno = 0;
2283 h_errno = HOST_NOT_FOUND; /* default, if we never query */
2284 dots = 0;
2285 for (cp = name; *cp; cp++)
2286 dots += (*cp == '.');
2287 trailing_dot = 0;
2288 if (cp > name && *--cp == '.')
2289 trailing_dot++;
2290
2291
David 'Digit' Turner5e563702009-05-05 15:50:24 +02002292 //fprintf(stderr, "res_searchN() name = '%s'\n", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002293
2294 /*
2295 * if there aren't any dots, it could be a user-level alias
2296 */
2297 if (!dots && (cp = __hostalias(name)) != NULL) {
2298 ret = res_queryN(cp, target, res);
2299 return ret;
2300 }
2301
2302 /*
2303 * If there are dots in the name already, let's just give it a try
2304 * 'as is'. The threshold can be set with the "ndots" option.
2305 */
2306 saved_herrno = -1;
2307 if (dots >= res->ndots) {
2308 ret = res_querydomainN(name, NULL, target, res);
2309 if (ret > 0)
2310 return (ret);
2311 saved_herrno = h_errno;
2312 tried_as_is++;
2313 }
2314
2315 /*
2316 * We do at least one level of search if
2317 * - there is no dot and RES_DEFNAME is set, or
2318 * - there is at least one dot, there is no trailing dot,
2319 * and RES_DNSRCH is set.
2320 */
2321 if ((!dots && (res->options & RES_DEFNAMES)) ||
2322 (dots && !trailing_dot && (res->options & RES_DNSRCH))) {
2323 int done = 0;
2324
Robert Greenwalte0805a92013-07-31 16:53:46 -07002325 /* Unfortunately we need to set stuff up before
2326 * the domain stuff is tried. Will have a better
2327 * fix after thread pools are used.
2328 */
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05002329 _resolv_populate_res_for_net(res);
Robert Greenwalte0805a92013-07-31 16:53:46 -07002330
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002331 for (domain = (const char * const *)res->dnsrch;
2332 *domain && !done;
2333 domain++) {
2334
2335 ret = res_querydomainN(name, *domain, target, res);
2336 if (ret > 0)
2337 return ret;
2338
2339 /*
2340 * If no server present, give up.
2341 * If name isn't found in this domain,
2342 * keep trying higher domains in the search list
2343 * (if that's enabled).
2344 * On a NO_DATA error, keep trying, otherwise
2345 * a wildcard entry of another type could keep us
2346 * from finding this entry higher in the domain.
2347 * If we get some other error (negative answer or
2348 * server failure), then stop searching up,
2349 * but try the input name below in case it's
2350 * fully-qualified.
2351 */
2352 if (errno == ECONNREFUSED) {
2353 h_errno = TRY_AGAIN;
2354 return -1;
2355 }
2356
2357 switch (h_errno) {
2358 case NO_DATA:
2359 got_nodata++;
2360 /* FALLTHROUGH */
2361 case HOST_NOT_FOUND:
2362 /* keep trying */
2363 break;
2364 case TRY_AGAIN:
2365 if (hp->rcode == SERVFAIL) {
2366 /* try next search element, if any */
2367 got_servfail++;
2368 break;
2369 }
2370 /* FALLTHROUGH */
2371 default:
2372 /* anything else implies that we're done */
2373 done++;
2374 }
2375 /*
2376 * if we got here for some reason other than DNSRCH,
2377 * we only wanted one iteration of the loop, so stop.
2378 */
2379 if (!(res->options & RES_DNSRCH))
Lorenzo Colittib82532d2011-09-28 19:28:32 -07002380 done++;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002381 }
2382 }
2383
2384 /*
2385 * if we have not already tried the name "as is", do that now.
2386 * note that we do this regardless of how many dots were in the
2387 * name or whether it ends with a dot.
2388 */
2389 if (!tried_as_is) {
2390 ret = res_querydomainN(name, NULL, target, res);
2391 if (ret > 0)
2392 return ret;
2393 }
2394
2395 /*
2396 * if we got here, we didn't satisfy the search.
2397 * if we did an initial full query, return that query's h_errno
2398 * (note that we wouldn't be here if that query had succeeded).
2399 * else if we ever got a nodata, send that back as the reason.
2400 * else send back meaningless h_errno, that being the one from
2401 * the last DNSRCH we did.
2402 */
2403 if (saved_herrno != -1)
2404 h_errno = saved_herrno;
2405 else if (got_nodata)
2406 h_errno = NO_DATA;
2407 else if (got_servfail)
2408 h_errno = TRY_AGAIN;
2409 return -1;
2410}
2411
2412/*
2413 * Perform a call on res_query on the concatenation of name and domain,
2414 * removing a trailing dot from name if domain is NULL.
2415 */
2416static int
2417res_querydomainN(const char *name, const char *domain,
2418 struct res_target *target, res_state res)
2419{
2420 char nbuf[MAXDNAME];
2421 const char *longname = nbuf;
2422 size_t n, d;
2423
2424 assert(name != NULL);
2425 /* XXX: target may be NULL??? */
2426
2427#ifdef DEBUG
2428 if (res->options & RES_DEBUG)
2429 printf(";; res_querydomain(%s, %s)\n",
2430 name, domain?domain:"<Nil>");
2431#endif
2432 if (domain == NULL) {
2433 /*
2434 * Check for trailing '.';
2435 * copy without '.' if present.
2436 */
2437 n = strlen(name);
2438 if (n + 1 > sizeof(nbuf)) {
2439 h_errno = NO_RECOVERY;
2440 return -1;
2441 }
2442 if (n > 0 && name[--n] == '.') {
2443 strncpy(nbuf, name, n);
2444 nbuf[n] = '\0';
2445 } else
2446 longname = name;
2447 } else {
2448 n = strlen(name);
2449 d = strlen(domain);
2450 if (n + 1 + d + 1 > sizeof(nbuf)) {
2451 h_errno = NO_RECOVERY;
2452 return -1;
2453 }
2454 snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
2455 }
2456 return res_queryN(longname, target, res);
2457}