blob: cc94b21e2712088a7e19980a8c97d9dfe3a2e418 [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"
Victor Khimenko59568472018-03-14 17:41:22 +0100110#include "private/bionic_defs.h"
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800111
Tom Marshall2af99722016-06-17 16:38:12 -0700112#include "hosts_cache.h"
113
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -0700114typedef union sockaddr_union {
115 struct sockaddr generic;
116 struct sockaddr_in in;
117 struct sockaddr_in6 in6;
118} sockaddr_union;
119
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800120#define SUCCESS 0
121#define ANY 0
122#define YES 1
123#define NO 0
124
125static const char in_addrany[] = { 0, 0, 0, 0 };
126static const char in_loopback[] = { 127, 0, 0, 1 };
127#ifdef INET6
128static const char in6_addrany[] = {
129 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
130};
131static const char in6_loopback[] = {
132 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
133};
134#endif
135
Dan Willemsen7ec52b12016-11-28 17:02:25 -0800136#if defined(__ANDROID__)
Selim Gurun06e18312012-02-27 15:58:54 -0800137// This should be synchronized to ResponseCode.h
138static const int DnsProxyQueryResult = 222;
Dan Willemsen7ec52b12016-11-28 17:02:25 -0800139#endif
Selim Gurun06e18312012-02-27 15:58:54 -0800140
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800141static const struct afd {
142 int a_af;
143 int a_addrlen;
144 int a_socklen;
145 int a_off;
146 const char *a_addrany;
147 const char *a_loopback;
148 int a_scoped;
149} afdl [] = {
150#ifdef INET6
151 {PF_INET6, sizeof(struct in6_addr),
152 sizeof(struct sockaddr_in6),
153 offsetof(struct sockaddr_in6, sin6_addr),
154 in6_addrany, in6_loopback, 1},
155#endif
156 {PF_INET, sizeof(struct in_addr),
157 sizeof(struct sockaddr_in),
158 offsetof(struct sockaddr_in, sin_addr),
159 in_addrany, in_loopback, 0},
160 {0, 0, 0, 0, NULL, NULL, 0},
161};
162
163struct explore {
164 int e_af;
165 int e_socktype;
166 int e_protocol;
167 const char *e_protostr;
168 int e_wild;
169#define WILD_AF(ex) ((ex)->e_wild & 0x01)
170#define WILD_SOCKTYPE(ex) ((ex)->e_wild & 0x02)
171#define WILD_PROTOCOL(ex) ((ex)->e_wild & 0x04)
172};
173
174static const struct explore explore[] = {
175#if 0
176 { PF_LOCAL, 0, ANY, ANY, NULL, 0x01 },
177#endif
178#ifdef INET6
179 { PF_INET6, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
180 { PF_INET6, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
181 { PF_INET6, SOCK_RAW, ANY, NULL, 0x05 },
182#endif
183 { PF_INET, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
184 { PF_INET, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
185 { PF_INET, SOCK_RAW, ANY, NULL, 0x05 },
186 { PF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
187 { PF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
188 { PF_UNSPEC, SOCK_RAW, ANY, NULL, 0x05 },
189 { -1, 0, 0, NULL, 0 },
190};
191
192#ifdef INET6
193#define PTON_MAX 16
194#else
195#define PTON_MAX 4
196#endif
197
198static const ns_src default_dns_files[] = {
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700199 { NSSRC_FILES, NS_SUCCESS },
200 { NSSRC_DNS, NS_SUCCESS },
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800201 { 0, 0 }
202};
203
Ben Schwartz47fb0e82018-01-31 13:35:03 -0500204#define MAXPACKET (8*1024)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800205
206typedef union {
207 HEADER hdr;
208 u_char buf[MAXPACKET];
209} querybuf;
210
211struct res_target {
212 struct res_target *next;
213 const char *name; /* domain name */
214 int qclass, qtype; /* class and type of query */
215 u_char *answer; /* buffer to put answer */
216 int anslen; /* size of answer buffer */
217 int n; /* result length */
218};
219
220static int str2number(const char *);
221static int explore_fqdn(const struct addrinfo *, const char *,
Erik Kline01e37c92015-06-25 14:27:34 +0900222 const char *, struct addrinfo **, const struct android_net_context *);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800223static int explore_null(const struct addrinfo *,
224 const char *, struct addrinfo **);
225static int explore_numeric(const struct addrinfo *, const char *,
226 const char *, struct addrinfo **, const char *);
227static int explore_numeric_scope(const struct addrinfo *, const char *,
228 const char *, struct addrinfo **);
229static int get_canonname(const struct addrinfo *,
230 struct addrinfo *, const char *);
231static struct addrinfo *get_ai(const struct addrinfo *,
232 const struct afd *, const char *);
233static int get_portmatch(const struct addrinfo *, const char *);
234static int get_port(const struct addrinfo *, const char *, int);
235static const struct afd *find_afd(int);
236#ifdef INET6
237static int ip6_str2scopeid(char *, struct sockaddr_in6 *, u_int32_t *);
238#endif
239
240static struct addrinfo *getanswer(const querybuf *, int, const char *, int,
241 const struct addrinfo *);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800242static int _dns_getaddrinfo(void *, void *, va_list);
243static void _sethtent(FILE **);
244static void _endhtent(FILE **);
245static struct addrinfo *_gethtent(FILE **, const char *,
246 const struct addrinfo *);
247static int _files_getaddrinfo(void *, void *, va_list);
Erik Kline01e37c92015-06-25 14:27:34 +0900248static int _find_src_addr(const struct sockaddr *, struct sockaddr *, unsigned , uid_t);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800249
250static int res_queryN(const char *, struct res_target *, res_state);
251static int res_searchN(const char *, struct res_target *, res_state);
252static int res_querydomainN(const char *, const char *,
253 struct res_target *, res_state);
254
255static const char * const ai_errlist[] = {
256 "Success",
257 "Address family for hostname not supported", /* EAI_ADDRFAMILY */
258 "Temporary failure in name resolution", /* EAI_AGAIN */
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700259 "Invalid value for ai_flags", /* EAI_BADFLAGS */
260 "Non-recoverable failure in name resolution", /* EAI_FAIL */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800261 "ai_family not supported", /* EAI_FAMILY */
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700262 "Memory allocation failure", /* EAI_MEMORY */
263 "No address associated with hostname", /* EAI_NODATA */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800264 "hostname nor servname provided, or not known", /* EAI_NONAME */
265 "servname not supported for ai_socktype", /* EAI_SERVICE */
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700266 "ai_socktype not supported", /* EAI_SOCKTYPE */
267 "System error returned in errno", /* EAI_SYSTEM */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800268 "Invalid value for hints", /* EAI_BADHINTS */
269 "Resolved protocol is unknown", /* EAI_PROTOCOL */
270 "Argument buffer overflow", /* EAI_OVERFLOW */
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700271 "Unknown error", /* EAI_MAX */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800272};
273
274/* XXX macros that make external reference is BAD. */
275
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700276#define GET_AI(ai, afd, addr) \
277do { \
278 /* external reference: pai, error, and label free */ \
279 (ai) = get_ai(pai, (afd), (addr)); \
280 if ((ai) == NULL) { \
281 error = EAI_MEMORY; \
282 goto free; \
283 } \
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800284} while (/*CONSTCOND*/0)
285
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700286#define GET_PORT(ai, serv) \
287do { \
288 /* external reference: error and label free */ \
289 error = get_port((ai), (serv), 0); \
290 if (error != 0) \
291 goto free; \
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800292} while (/*CONSTCOND*/0)
293
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700294#define GET_CANONNAME(ai, str) \
295do { \
296 /* external reference: pai, error and label free */ \
297 error = get_canonname(pai, (ai), (str)); \
298 if (error != 0) \
299 goto free; \
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800300} while (/*CONSTCOND*/0)
301
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700302#define ERR(err) \
303do { \
304 /* external reference: error, and label bad */ \
305 error = (err); \
306 goto bad; \
307 /*NOTREACHED*/ \
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800308} while (/*CONSTCOND*/0)
309
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700310#define MATCH_FAMILY(x, y, w) \
311 ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC || \
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800312 (y) == PF_UNSPEC)))
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700313#define MATCH(x, y, w) \
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800314 ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY)))
315
Victor Khimenko59568472018-03-14 17:41:22 +0100316__BIONIC_WEAK_FOR_NATIVE_BRIDGE
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800317const char *
318gai_strerror(int ecode)
319{
320 if (ecode < 0 || ecode > EAI_MAX)
321 ecode = EAI_MAX;
322 return ai_errlist[ecode];
323}
324
Victor Khimenko59568472018-03-14 17:41:22 +0100325__BIONIC_WEAK_FOR_NATIVE_BRIDGE
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800326void
327freeaddrinfo(struct addrinfo *ai)
328{
329 struct addrinfo *next;
330
Elliott Hughesa9209d72016-09-16 18:16:47 -0700331#if defined(__BIONIC__)
Elliott Hughesc62a4b52015-01-08 17:28:46 -0800332 if (ai == NULL) return;
333#else
334 _DIAGASSERT(ai != NULL);
335#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800336
337 do {
338 next = ai->ai_next;
339 if (ai->ai_canonname)
340 free(ai->ai_canonname);
341 /* no need to free(ai->ai_addr) */
342 free(ai);
343 ai = next;
344 } while (ai);
345}
346
347static int
348str2number(const char *p)
349{
350 char *ep;
351 unsigned long v;
352
353 assert(p != NULL);
354
355 if (*p == '\0')
356 return -1;
357 ep = NULL;
358 errno = 0;
359 v = strtoul(p, &ep, 10);
360 if (errno == 0 && ep && *ep == '\0' && v <= UINT_MAX)
361 return v;
362 else
363 return -1;
364}
365
Lorenzo Colittiba96e302011-01-14 12:26:05 -0800366/*
Lorenzo Colittiba96e302011-01-14 12:26:05 -0800367 * The following functions determine whether IPv4 or IPv6 connectivity is
368 * available in order to implement AI_ADDRCONFIG.
369 *
370 * Strictly speaking, AI_ADDRCONFIG should not look at whether connectivity is
371 * available, but whether addresses of the specified family are "configured
372 * on the local system". However, bionic doesn't currently support getifaddrs,
373 * so checking for connectivity is the next best thing.
374 */
375static int
Erik Kline01e37c92015-06-25 14:27:34 +0900376_have_ipv6(unsigned mark, uid_t uid) {
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700377 static const struct sockaddr_in6 sin6_test = {
378 .sin6_family = AF_INET6,
379 .sin6_addr.s6_addr = { // 2000::
380 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
381 };
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500382 sockaddr_union addr = { .in6 = sin6_test };
Erik Kline01e37c92015-06-25 14:27:34 +0900383 return _find_src_addr(&addr.generic, NULL, mark, uid) == 1;
Lorenzo Colittiba96e302011-01-14 12:26:05 -0800384}
385
386static int
Erik Kline01e37c92015-06-25 14:27:34 +0900387_have_ipv4(unsigned mark, uid_t uid) {
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700388 static const struct sockaddr_in sin_test = {
389 .sin_family = AF_INET,
390 .sin_addr.s_addr = __constant_htonl(0x08080808L) // 8.8.8.8
391 };
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500392 sockaddr_union addr = { .in = sin_test };
Erik Kline01e37c92015-06-25 14:27:34 +0900393 return _find_src_addr(&addr.generic, NULL, mark, uid) == 1;
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -0700394}
395
Elliott Hughes55293c12014-11-12 17:00:30 -0800396bool readBE32(FILE* fp, int32_t* result) {
397 int32_t tmp;
398 if (fread(&tmp, sizeof(tmp), 1, fp) != 1) {
399 return false;
400 }
401 *result = ntohl(tmp);
402 return true;
403}
404
Dan Willemsen7ec52b12016-11-28 17:02:25 -0800405#if defined(__ANDROID__)
Mattias Falkc63e5902011-08-23 14:34:14 +0200406// Returns 0 on success, else returns on error.
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700407static int
408android_getaddrinfo_proxy(
409 const char *hostname, const char *servname,
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500410 const struct addrinfo *hints, struct addrinfo **res, unsigned netid)
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700411{
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700412 int success = 0;
413
414 // Clear this at start, as we use its non-NULLness later (in the
415 // error path) to decide if we have to free up any memory we
416 // allocated in the process (before failing).
417 *res = NULL;
418
Mattias Falkc63e5902011-08-23 14:34:14 +0200419 // Bogus things we can't serialize. Don't use the proxy. These will fail - let them.
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700420 if ((hostname != NULL &&
421 strcspn(hostname, " \n\r\t^'\"") != strlen(hostname)) ||
422 (servname != NULL &&
423 strcspn(servname, " \n\r\t^'\"") != strlen(servname))) {
Mattias Falkc63e5902011-08-23 14:34:14 +0200424 return EAI_NODATA;
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700425 }
426
Luke Huange3ed8922018-11-19 16:59:08 +0800427 FILE* proxy = fdopen(__netdClientDispatch.dnsOpenProxy(), "r+");
Elliott Hughes9773fa32014-12-10 14:56:46 -0800428 if (proxy == NULL) {
429 return EAI_SYSTEM;
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700430 }
Paul Jensen559c7842014-05-15 14:43:07 -0400431 netid = __netdClientDispatch.netIdForResolv(netid);
432
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700433 // Send the request.
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500434 if (fprintf(proxy, "getaddrinfo %s %s %d %d %d %d %u",
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700435 hostname == NULL ? "^" : hostname,
436 servname == NULL ? "^" : servname,
437 hints == NULL ? -1 : hints->ai_flags,
438 hints == NULL ? -1 : hints->ai_family,
439 hints == NULL ? -1 : hints->ai_socktype,
Mattias Falkc63e5902011-08-23 14:34:14 +0200440 hints == NULL ? -1 : hints->ai_protocol,
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500441 netid) < 0) {
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700442 goto exit;
443 }
444 // literal NULL byte at end, required by FrameworkListener
445 if (fputc(0, proxy) == EOF ||
446 fflush(proxy) != 0) {
447 goto exit;
448 }
449
Robert Greenwaltc59ba452012-03-09 11:34:27 -0800450 char buf[4];
Selim Gurun06e18312012-02-27 15:58:54 -0800451 // read result code for gethostbyaddr
452 if (fread(buf, 1, sizeof(buf), proxy) != sizeof(buf)) {
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700453 goto exit;
454 }
455
Selim Gurun06e18312012-02-27 15:58:54 -0800456 int result_code = (int)strtol(buf, NULL, 10);
457 // verify the code itself
Erik Kline01e37c92015-06-25 14:27:34 +0900458 if (result_code != DnsProxyQueryResult) {
Mattias Falkc63e5902011-08-23 14:34:14 +0200459 fread(buf, 1, sizeof(buf), proxy);
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700460 goto exit;
461 }
462
463 struct addrinfo* ai = NULL;
464 struct addrinfo** nextres = res;
465 while (1) {
Elliott Hughes55293c12014-11-12 17:00:30 -0800466 int32_t have_more;
467 if (!readBE32(proxy, &have_more)) {
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700468 break;
469 }
Elliott Hughes55293c12014-11-12 17:00:30 -0800470 if (have_more == 0) {
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700471 success = 1;
472 break;
473 }
474
Elliott Hughese6418c82019-11-05 12:42:14 -0800475 ai = calloc(1, sizeof(struct addrinfo) + sizeof(struct sockaddr_storage));
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700476 if (ai == NULL) {
477 break;
478 }
Elliott Hughes55293c12014-11-12 17:00:30 -0800479 ai->ai_addr = (struct sockaddr*)(ai + 1);
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700480
Elliott Hughes55293c12014-11-12 17:00:30 -0800481 // struct addrinfo {
482 // int ai_flags; /* AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST */
483 // int ai_family; /* PF_xxx */
484 // int ai_socktype; /* SOCK_xxx */
485 // int ai_protocol; /* 0 or IPPROTO_xxx for IPv4 and IPv6 */
486 // socklen_t ai_addrlen; /* length of ai_addr */
487 // char *ai_canonname; /* canonical name for hostname */
488 // struct sockaddr *ai_addr; /* binary address */
489 // struct addrinfo *ai_next; /* next structure in linked list */
490 // };
491
492 // Read the struct piece by piece because we might be a 32-bit process
493 // talking to a 64-bit netd.
494 int32_t addr_len;
495 bool success =
496 readBE32(proxy, &ai->ai_flags) &&
497 readBE32(proxy, &ai->ai_family) &&
498 readBE32(proxy, &ai->ai_socktype) &&
499 readBE32(proxy, &ai->ai_protocol) &&
500 readBE32(proxy, &addr_len);
501 if (!success) {
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700502 break;
503 }
504
Elliott Hughes55293c12014-11-12 17:00:30 -0800505 // Set ai_addrlen and read the ai_addr data.
506 ai->ai_addrlen = addr_len;
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700507 if (addr_len != 0) {
Elliott Hughes55293c12014-11-12 17:00:30 -0800508 if ((size_t) addr_len > sizeof(struct sockaddr_storage)) {
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700509 // Bogus; too big.
510 break;
511 }
Elliott Hughes55293c12014-11-12 17:00:30 -0800512 if (fread(ai->ai_addr, addr_len, 1, proxy) != 1) {
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700513 break;
514 }
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700515 }
516
Elliott Hughes55293c12014-11-12 17:00:30 -0800517 // The string for ai_cannonname.
518 int32_t name_len;
519 if (!readBE32(proxy, &name_len)) {
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700520 break;
521 }
522 if (name_len != 0) {
523 ai->ai_canonname = (char*) malloc(name_len);
524 if (fread(ai->ai_canonname, name_len, 1, proxy) != 1) {
525 break;
526 }
527 if (ai->ai_canonname[name_len - 1] != '\0') {
528 // The proxy should be returning this
529 // NULL-terminated.
530 break;
531 }
532 }
533
534 *nextres = ai;
535 nextres = &ai->ai_next;
536 ai = NULL;
537 }
538
539 if (ai != NULL) {
540 // Clean up partially-built addrinfo that we never ended up
541 // attaching to the response.
542 freeaddrinfo(ai);
543 }
544exit:
545 if (proxy != NULL) {
546 fclose(proxy);
547 }
548
549 if (success) {
550 return 0;
551 }
552
Mattias Falkc63e5902011-08-23 14:34:14 +0200553 // Proxy failed;
554 // clean up memory we might've allocated.
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700555 if (*res) {
556 freeaddrinfo(*res);
557 *res = NULL;
558 }
Mattias Falkc63e5902011-08-23 14:34:14 +0200559 return EAI_NODATA;
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700560}
Dan Willemsen7ec52b12016-11-28 17:02:25 -0800561#endif
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700562
Victor Khimenko59568472018-03-14 17:41:22 +0100563__BIONIC_WEAK_FOR_NATIVE_BRIDGE
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800564int
565getaddrinfo(const char *hostname, const char *servname,
566 const struct addrinfo *hints, struct addrinfo **res)
567{
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500568 return android_getaddrinfofornet(hostname, servname, hints, NETID_UNSET, MARK_UNSET, res);
Mattias Falkc63e5902011-08-23 14:34:14 +0200569}
570
Victor Khimenko59568472018-03-14 17:41:22 +0100571__BIONIC_WEAK_FOR_NATIVE_BRIDGE
Mattias Falkc63e5902011-08-23 14:34:14 +0200572int
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500573android_getaddrinfofornet(const char *hostname, const char *servname,
574 const struct addrinfo *hints, unsigned netid, unsigned mark, struct addrinfo **res)
Mattias Falkc63e5902011-08-23 14:34:14 +0200575{
Erik Kline01e37c92015-06-25 14:27:34 +0900576 struct android_net_context netcontext = {
577 .app_netid = netid,
578 .app_mark = mark,
579 .dns_netid = netid,
580 .dns_mark = mark,
581 .uid = NET_CONTEXT_INVALID_UID,
582 };
583 return android_getaddrinfofornetcontext(hostname, servname, hints, &netcontext, res);
584}
585
Victor Khimenko59568472018-03-14 17:41:22 +0100586__BIONIC_WEAK_FOR_NATIVE_BRIDGE
Erik Kline01e37c92015-06-25 14:27:34 +0900587int
588android_getaddrinfofornetcontext(const char *hostname, const char *servname,
589 const struct addrinfo *hints, const struct android_net_context *netcontext,
590 struct addrinfo **res)
591{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800592 struct addrinfo sentinel;
593 struct addrinfo *cur;
594 int error = 0;
595 struct addrinfo ai;
596 struct addrinfo ai0;
597 struct addrinfo *pai;
598 const struct explore *ex;
599
600 /* hostname is allowed to be NULL */
601 /* servname is allowed to be NULL */
602 /* hints is allowed to be NULL */
603 assert(res != NULL);
Erik Kline01e37c92015-06-25 14:27:34 +0900604 assert(netcontext != NULL);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800605 memset(&sentinel, 0, sizeof(sentinel));
606 cur = &sentinel;
607 pai = &ai;
608 pai->ai_flags = 0;
609 pai->ai_family = PF_UNSPEC;
610 pai->ai_socktype = ANY;
611 pai->ai_protocol = ANY;
612 pai->ai_addrlen = 0;
613 pai->ai_canonname = NULL;
614 pai->ai_addr = NULL;
615 pai->ai_next = NULL;
616
617 if (hostname == NULL && servname == NULL)
618 return EAI_NONAME;
619 if (hints) {
620 /* error check for hints */
621 if (hints->ai_addrlen || hints->ai_canonname ||
622 hints->ai_addr || hints->ai_next)
623 ERR(EAI_BADHINTS); /* xxx */
624 if (hints->ai_flags & ~AI_MASK)
625 ERR(EAI_BADFLAGS);
626 switch (hints->ai_family) {
627 case PF_UNSPEC:
628 case PF_INET:
629#ifdef INET6
630 case PF_INET6:
631#endif
632 break;
633 default:
634 ERR(EAI_FAMILY);
635 }
636 memcpy(pai, hints, sizeof(*pai));
637
638 /*
639 * if both socktype/protocol are specified, check if they
640 * are meaningful combination.
641 */
642 if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
643 for (ex = explore; ex->e_af >= 0; ex++) {
644 if (pai->ai_family != ex->e_af)
645 continue;
646 if (ex->e_socktype == ANY)
647 continue;
648 if (ex->e_protocol == ANY)
649 continue;
650 if (pai->ai_socktype == ex->e_socktype
651 && pai->ai_protocol != ex->e_protocol) {
652 ERR(EAI_BADHINTS);
653 }
654 }
655 }
656 }
657
658 /*
659 * check for special cases. (1) numeric servname is disallowed if
660 * socktype/protocol are left unspecified. (2) servname is disallowed
661 * for raw and other inet{,6} sockets.
662 */
663 if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
664#ifdef PF_INET6
665 || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
666#endif
667 ) {
668 ai0 = *pai; /* backup *pai */
669
670 if (pai->ai_family == PF_UNSPEC) {
671#ifdef PF_INET6
672 pai->ai_family = PF_INET6;
673#else
674 pai->ai_family = PF_INET;
675#endif
676 }
677 error = get_portmatch(pai, servname);
678 if (error)
679 ERR(error);
680
681 *pai = ai0;
682 }
683
684 ai0 = *pai;
685
686 /* NULL hostname, or numeric hostname */
687 for (ex = explore; ex->e_af >= 0; ex++) {
688 *pai = ai0;
689
690 /* PF_UNSPEC entries are prepared for DNS queries only */
691 if (ex->e_af == PF_UNSPEC)
692 continue;
693
694 if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
695 continue;
696 if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex)))
697 continue;
698 if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex)))
699 continue;
700
701 if (pai->ai_family == PF_UNSPEC)
702 pai->ai_family = ex->e_af;
703 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
704 pai->ai_socktype = ex->e_socktype;
705 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
706 pai->ai_protocol = ex->e_protocol;
707
708 if (hostname == NULL)
709 error = explore_null(pai, servname, &cur->ai_next);
710 else
711 error = explore_numeric_scope(pai, hostname, servname,
712 &cur->ai_next);
713
714 if (error)
715 goto free;
716
717 while (cur->ai_next)
718 cur = cur->ai_next;
719 }
720
721 /*
722 * XXX
723 * If numeric representation of AF1 can be interpreted as FQDN
724 * representation of AF2, we need to think again about the code below.
725 */
726 if (sentinel.ai_next)
727 goto good;
728
729 if (hostname == NULL)
730 ERR(EAI_NODATA);
731 if (pai->ai_flags & AI_NUMERICHOST)
732 ERR(EAI_NONAME);
733
Elliott Hughes9773fa32014-12-10 14:56:46 -0800734#if defined(__ANDROID__)
Erik Kline01e37c92015-06-25 14:27:34 +0900735 int gai_error = android_getaddrinfo_proxy(
736 hostname, servname, hints, res, netcontext->app_netid);
Elliott Hughes9773fa32014-12-10 14:56:46 -0800737 if (gai_error != EAI_SYSTEM) {
738 return gai_error;
Mattias Falkc63e5902011-08-23 14:34:14 +0200739 }
Elliott Hughes9773fa32014-12-10 14:56:46 -0800740#endif
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700741
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800742 /*
743 * hostname as alphabetical name.
744 * we would like to prefer AF_INET6 than AF_INET, so we'll make a
745 * outer loop by AFs.
746 */
747 for (ex = explore; ex->e_af >= 0; ex++) {
748 *pai = ai0;
749
750 /* require exact match for family field */
751 if (pai->ai_family != ex->e_af)
752 continue;
753
754 if (!MATCH(pai->ai_socktype, ex->e_socktype,
755 WILD_SOCKTYPE(ex))) {
756 continue;
757 }
758 if (!MATCH(pai->ai_protocol, ex->e_protocol,
759 WILD_PROTOCOL(ex))) {
760 continue;
761 }
762
763 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
764 pai->ai_socktype = ex->e_socktype;
765 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
766 pai->ai_protocol = ex->e_protocol;
767
Erik Kline01e37c92015-06-25 14:27:34 +0900768 error = explore_fqdn(
769 pai, hostname, servname, &cur->ai_next, netcontext);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800770
771 while (cur && cur->ai_next)
772 cur = cur->ai_next;
773 }
774
775 /* XXX */
776 if (sentinel.ai_next)
777 error = 0;
778
779 if (error)
780 goto free;
781 if (error == 0) {
782 if (sentinel.ai_next) {
783 good:
784 *res = sentinel.ai_next;
785 return SUCCESS;
786 } else
787 error = EAI_FAIL;
788 }
789 free:
790 bad:
791 if (sentinel.ai_next)
792 freeaddrinfo(sentinel.ai_next);
793 *res = NULL;
794 return error;
795}
796
797/*
798 * FQDN hostname, DNS lookup
799 */
800static int
801explore_fqdn(const struct addrinfo *pai, const char *hostname,
Erik Kline01e37c92015-06-25 14:27:34 +0900802 const char *servname, struct addrinfo **res,
803 const struct android_net_context *netcontext)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800804{
805 struct addrinfo *result;
806 struct addrinfo *cur;
807 int error = 0;
808 static const ns_dtab dtab[] = {
809 NS_FILES_CB(_files_getaddrinfo, NULL)
810 { NSSRC_DNS, _dns_getaddrinfo, NULL }, /* force -DHESIOD */
811 NS_NIS_CB(_yp_getaddrinfo, NULL)
812 { 0, 0, 0 }
813 };
814
815 assert(pai != NULL);
816 /* hostname may be NULL */
817 /* servname may be NULL */
818 assert(res != NULL);
819
820 result = NULL;
821
822 /*
823 * if the servname does not match socktype/protocol, ignore it.
824 */
825 if (get_portmatch(pai, servname) != 0)
826 return 0;
827
828 switch (nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
Erik Kline01e37c92015-06-25 14:27:34 +0900829 default_dns_files, hostname, pai, netcontext)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800830 case NS_TRYAGAIN:
831 error = EAI_AGAIN;
832 goto free;
833 case NS_UNAVAIL:
834 error = EAI_FAIL;
835 goto free;
836 case NS_NOTFOUND:
837 error = EAI_NODATA;
838 goto free;
839 case NS_SUCCESS:
840 error = 0;
841 for (cur = result; cur; cur = cur->ai_next) {
842 GET_PORT(cur, servname);
843 /* canonname should be filled already */
844 }
845 break;
846 }
847
848 *res = result;
849
850 return 0;
851
852free:
853 if (result)
854 freeaddrinfo(result);
855 return error;
856}
857
858/*
859 * hostname == NULL.
860 * passive socket -> anyaddr (0.0.0.0 or ::)
861 * non-passive socket -> localhost (127.0.0.1 or ::1)
862 */
863static int
864explore_null(const struct addrinfo *pai, const char *servname,
865 struct addrinfo **res)
866{
867 int s;
868 const struct afd *afd;
869 struct addrinfo *cur;
870 struct addrinfo sentinel;
871 int error;
872
873 assert(pai != NULL);
874 /* servname may be NULL */
875 assert(res != NULL);
876
877 *res = NULL;
878 sentinel.ai_next = NULL;
879 cur = &sentinel;
880
881 /*
882 * filter out AFs that are not supported by the kernel
883 * XXX errno?
884 */
Nick Kralevich1781ed72014-06-29 20:46:17 -0700885 s = socket(pai->ai_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800886 if (s < 0) {
887 if (errno != EMFILE)
888 return 0;
889 } else
890 close(s);
891
892 /*
893 * if the servname does not match socktype/protocol, ignore it.
894 */
895 if (get_portmatch(pai, servname) != 0)
896 return 0;
897
898 afd = find_afd(pai->ai_family);
899 if (afd == NULL)
900 return 0;
901
902 if (pai->ai_flags & AI_PASSIVE) {
903 GET_AI(cur->ai_next, afd, afd->a_addrany);
904 /* xxx meaningless?
905 * GET_CANONNAME(cur->ai_next, "anyaddr");
906 */
907 GET_PORT(cur->ai_next, servname);
908 } else {
909 GET_AI(cur->ai_next, afd, afd->a_loopback);
910 /* xxx meaningless?
911 * GET_CANONNAME(cur->ai_next, "localhost");
912 */
913 GET_PORT(cur->ai_next, servname);
914 }
915 cur = cur->ai_next;
916
917 *res = sentinel.ai_next;
918 return 0;
919
920free:
921 if (sentinel.ai_next)
922 freeaddrinfo(sentinel.ai_next);
923 return error;
924}
925
926/*
927 * numeric hostname
928 */
929static int
930explore_numeric(const struct addrinfo *pai, const char *hostname,
931 const char *servname, struct addrinfo **res, const char *canonname)
932{
933 const struct afd *afd;
934 struct addrinfo *cur;
935 struct addrinfo sentinel;
936 int error;
937 char pton[PTON_MAX];
938
939 assert(pai != NULL);
940 /* hostname may be NULL */
941 /* servname may be NULL */
942 assert(res != NULL);
943
944 *res = NULL;
945 sentinel.ai_next = NULL;
946 cur = &sentinel;
947
948 /*
949 * if the servname does not match socktype/protocol, ignore it.
950 */
951 if (get_portmatch(pai, servname) != 0)
952 return 0;
953
954 afd = find_afd(pai->ai_family);
955 if (afd == NULL)
956 return 0;
957
958 switch (afd->a_af) {
959#if 0 /*X/Open spec*/
960 case AF_INET:
961 if (inet_aton(hostname, (struct in_addr *)pton) == 1) {
962 if (pai->ai_family == afd->a_af ||
963 pai->ai_family == PF_UNSPEC /*?*/) {
964 GET_AI(cur->ai_next, afd, pton);
965 GET_PORT(cur->ai_next, servname);
966 if ((pai->ai_flags & AI_CANONNAME)) {
967 /*
968 * Set the numeric address itself as
969 * the canonical name, based on a
970 * clarification in rfc2553bis-03.
971 */
972 GET_CANONNAME(cur->ai_next, canonname);
973 }
974 while (cur && cur->ai_next)
975 cur = cur->ai_next;
976 } else
977 ERR(EAI_FAMILY); /*xxx*/
978 }
979 break;
980#endif
981 default:
982 if (inet_pton(afd->a_af, hostname, 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->ai_next)
996 cur = cur->ai_next;
997 } else
998 ERR(EAI_FAMILY); /*xxx*/
999 }
1000 break;
1001 }
1002
1003 *res = sentinel.ai_next;
1004 return 0;
1005
1006free:
1007bad:
1008 if (sentinel.ai_next)
1009 freeaddrinfo(sentinel.ai_next);
1010 return error;
1011}
1012
1013/*
1014 * numeric hostname with scope
1015 */
1016static int
1017explore_numeric_scope(const struct addrinfo *pai, const char *hostname,
1018 const char *servname, struct addrinfo **res)
1019{
1020#if !defined(SCOPE_DELIMITER) || !defined(INET6)
1021 return explore_numeric(pai, hostname, servname, res, hostname);
1022#else
1023 const struct afd *afd;
1024 struct addrinfo *cur;
1025 int error;
1026 char *cp, *hostname2 = NULL, *scope, *addr;
1027 struct sockaddr_in6 *sin6;
1028
1029 assert(pai != NULL);
1030 /* hostname may be NULL */
1031 /* servname may be NULL */
1032 assert(res != NULL);
1033
1034 /*
1035 * if the servname does not match socktype/protocol, ignore it.
1036 */
1037 if (get_portmatch(pai, servname) != 0)
1038 return 0;
1039
1040 afd = find_afd(pai->ai_family);
1041 if (afd == NULL)
1042 return 0;
1043
1044 if (!afd->a_scoped)
1045 return explore_numeric(pai, hostname, servname, res, hostname);
1046
1047 cp = strchr(hostname, SCOPE_DELIMITER);
1048 if (cp == NULL)
1049 return explore_numeric(pai, hostname, servname, res, hostname);
1050
1051 /*
1052 * Handle special case of <scoped_address><delimiter><scope id>
1053 */
1054 hostname2 = strdup(hostname);
1055 if (hostname2 == NULL)
1056 return EAI_MEMORY;
1057 /* terminate at the delimiter */
1058 hostname2[cp - hostname] = '\0';
1059 addr = hostname2;
1060 scope = cp + 1;
1061
1062 error = explore_numeric(pai, addr, servname, res, hostname);
1063 if (error == 0) {
1064 u_int32_t scopeid;
1065
1066 for (cur = *res; cur; cur = cur->ai_next) {
1067 if (cur->ai_family != AF_INET6)
1068 continue;
1069 sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
1070 if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) {
1071 free(hostname2);
1072 return(EAI_NODATA); /* XXX: is return OK? */
1073 }
1074 sin6->sin6_scope_id = scopeid;
1075 }
1076 }
1077
1078 free(hostname2);
1079
1080 return error;
1081#endif
1082}
1083
1084static int
1085get_canonname(const struct addrinfo *pai, struct addrinfo *ai, const char *str)
1086{
1087
1088 assert(pai != NULL);
1089 assert(ai != NULL);
1090 assert(str != NULL);
1091
1092 if ((pai->ai_flags & AI_CANONNAME) != 0) {
1093 ai->ai_canonname = strdup(str);
1094 if (ai->ai_canonname == NULL)
1095 return EAI_MEMORY;
1096 }
1097 return 0;
1098}
1099
1100static struct addrinfo *
1101get_ai(const struct addrinfo *pai, const struct afd *afd, const char *addr)
1102{
1103 char *p;
1104 struct addrinfo *ai;
1105
1106 assert(pai != NULL);
1107 assert(afd != NULL);
1108 assert(addr != NULL);
1109
1110 ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
1111 + (afd->a_socklen));
1112 if (ai == NULL)
1113 return NULL;
1114
1115 memcpy(ai, pai, sizeof(struct addrinfo));
1116 ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
1117 memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
1118
1119#ifdef HAVE_SA_LEN
1120 ai->ai_addr->sa_len = afd->a_socklen;
1121#endif
1122
1123 ai->ai_addrlen = afd->a_socklen;
1124#if defined (__alpha__) || (defined(__i386__) && defined(_LP64)) || defined(__sparc64__)
1125 ai->__ai_pad0 = 0;
1126#endif
1127 ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
1128 p = (char *)(void *)(ai->ai_addr);
1129 memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
1130 return ai;
1131}
1132
1133static int
1134get_portmatch(const struct addrinfo *ai, const char *servname)
1135{
1136
1137 assert(ai != NULL);
1138 /* servname may be NULL */
1139
1140 return get_port(ai, servname, 1);
1141}
1142
1143static int
1144get_port(const struct addrinfo *ai, const char *servname, int matchonly)
1145{
1146 const char *proto;
1147 struct servent *sp;
1148 int port;
1149 int allownumeric;
1150
1151 assert(ai != NULL);
1152 /* servname may be NULL */
1153
1154 if (servname == NULL)
1155 return 0;
1156 switch (ai->ai_family) {
1157 case AF_INET:
1158#ifdef AF_INET6
1159 case AF_INET6:
1160#endif
1161 break;
1162 default:
1163 return 0;
1164 }
1165
1166 switch (ai->ai_socktype) {
1167 case SOCK_RAW:
1168 return EAI_SERVICE;
1169 case SOCK_DGRAM:
1170 case SOCK_STREAM:
1171 allownumeric = 1;
1172 break;
1173 case ANY:
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001174#if 1 /* ANDROID-SPECIFIC CHANGE TO MATCH GLIBC */
David 'Digit' Turner5e563702009-05-05 15:50:24 +02001175 allownumeric = 1;
1176#else
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001177 allownumeric = 0;
David 'Digit' Turner5e563702009-05-05 15:50:24 +02001178#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001179 break;
1180 default:
1181 return EAI_SOCKTYPE;
1182 }
1183
1184 port = str2number(servname);
1185 if (port >= 0) {
1186 if (!allownumeric)
1187 return EAI_SERVICE;
1188 if (port < 0 || port > 65535)
1189 return EAI_SERVICE;
1190 port = htons(port);
1191 } else {
1192 if (ai->ai_flags & AI_NUMERICSERV)
1193 return EAI_NONAME;
1194
1195 switch (ai->ai_socktype) {
1196 case SOCK_DGRAM:
1197 proto = "udp";
1198 break;
1199 case SOCK_STREAM:
1200 proto = "tcp";
1201 break;
1202 default:
1203 proto = NULL;
1204 break;
1205 }
1206
1207 if ((sp = getservbyname(servname, proto)) == NULL)
1208 return EAI_SERVICE;
1209 port = sp->s_port;
1210 }
1211
1212 if (!matchonly) {
1213 switch (ai->ai_family) {
1214 case AF_INET:
1215 ((struct sockaddr_in *)(void *)
1216 ai->ai_addr)->sin_port = port;
1217 break;
1218#ifdef INET6
1219 case AF_INET6:
1220 ((struct sockaddr_in6 *)(void *)
1221 ai->ai_addr)->sin6_port = port;
1222 break;
1223#endif
1224 }
1225 }
1226
1227 return 0;
1228}
1229
1230static const struct afd *
1231find_afd(int af)
1232{
1233 const struct afd *afd;
1234
1235 if (af == PF_UNSPEC)
1236 return NULL;
1237 for (afd = afdl; afd->a_af; afd++) {
1238 if (afd->a_af == af)
1239 return afd;
1240 }
1241 return NULL;
1242}
1243
1244#ifdef INET6
1245/* convert a string to a scope identifier. XXX: IPv6 specific */
1246static int
1247ip6_str2scopeid(char *scope, struct sockaddr_in6 *sin6, u_int32_t *scopeid)
1248{
1249 u_long lscopeid;
1250 struct in6_addr *a6;
1251 char *ep;
1252
1253 assert(scope != NULL);
1254 assert(sin6 != NULL);
1255 assert(scopeid != NULL);
1256
1257 a6 = &sin6->sin6_addr;
1258
1259 /* empty scopeid portion is invalid */
1260 if (*scope == '\0')
1261 return -1;
1262
1263 if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
1264 /*
1265 * We currently assume a one-to-one mapping between links
1266 * and interfaces, so we simply use interface indices for
1267 * like-local scopes.
1268 */
1269 *scopeid = if_nametoindex(scope);
1270 if (*scopeid == 0)
1271 goto trynumeric;
1272 return 0;
1273 }
1274
1275 /* still unclear about literal, allow numeric only - placeholder */
1276 if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
1277 goto trynumeric;
1278 if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
1279 goto trynumeric;
1280 else
1281 goto trynumeric; /* global */
1282
1283 /* try to convert to a numeric id as a last resort */
1284 trynumeric:
1285 errno = 0;
1286 lscopeid = strtoul(scope, &ep, 10);
1287 *scopeid = (u_int32_t)(lscopeid & 0xffffffffUL);
1288 if (errno == 0 && ep && *ep == '\0' && *scopeid == lscopeid)
1289 return 0;
1290 else
1291 return -1;
1292}
1293#endif
1294
1295/* code duplicate with gethnamaddr.c */
1296
1297static const char AskedForGot[] =
1298 "gethostby*.getanswer: asked for \"%s\", got \"%s\"";
1299
Elliott Hughes87c0dba2016-11-14 13:56:32 -08001300#define BOUNDED_INCR(x) \
1301 do { \
1302 BOUNDS_CHECK(cp, x); \
1303 cp += (x); \
1304 } while (/*CONSTCOND*/0)
1305
1306#define BOUNDS_CHECK(ptr, count) \
1307 do { \
1308 if (eom - (ptr) < (count)) { h_errno = NO_RECOVERY; return NULL; } \
1309 } while (/*CONSTCOND*/0)
1310
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001311static struct addrinfo *
1312getanswer(const querybuf *answer, int anslen, const char *qname, int qtype,
1313 const struct addrinfo *pai)
1314{
1315 struct addrinfo sentinel, *cur;
1316 struct addrinfo ai;
1317 const struct afd *afd;
1318 char *canonname;
1319 const HEADER *hp;
1320 const u_char *cp;
1321 int n;
1322 const u_char *eom;
1323 char *bp, *ep;
1324 int type, class, ancount, qdcount;
1325 int haveanswer, had_error;
1326 char tbuf[MAXDNAME];
1327 int (*name_ok) (const char *);
1328 char hostbuf[8*1024];
1329
1330 assert(answer != NULL);
1331 assert(qname != NULL);
1332 assert(pai != NULL);
1333
1334 memset(&sentinel, 0, sizeof(sentinel));
1335 cur = &sentinel;
1336
1337 canonname = NULL;
1338 eom = answer->buf + anslen;
1339 switch (qtype) {
1340 case T_A:
1341 case T_AAAA:
1342 case T_ANY: /*use T_ANY only for T_A/T_AAAA lookup*/
1343 name_ok = res_hnok;
1344 break;
1345 default:
1346 return NULL; /* XXX should be abort(); */
1347 }
1348 /*
1349 * find first satisfactory answer
1350 */
1351 hp = &answer->hdr;
1352 ancount = ntohs(hp->ancount);
1353 qdcount = ntohs(hp->qdcount);
1354 bp = hostbuf;
1355 ep = hostbuf + sizeof hostbuf;
Elliott Hughes87c0dba2016-11-14 13:56:32 -08001356 cp = answer->buf;
1357 BOUNDED_INCR(HFIXEDSZ);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001358 if (qdcount != 1) {
1359 h_errno = NO_RECOVERY;
1360 return (NULL);
1361 }
1362 n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1363 if ((n < 0) || !(*name_ok)(bp)) {
1364 h_errno = NO_RECOVERY;
1365 return (NULL);
1366 }
Elliott Hughes87c0dba2016-11-14 13:56:32 -08001367 BOUNDED_INCR(n + QFIXEDSZ);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001368 if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
1369 /* res_send() has already verified that the query name is the
1370 * same as the one we sent; this just gets the expanded name
1371 * (i.e., with the succeeding search-domain tacked on).
1372 */
1373 n = strlen(bp) + 1; /* for the \0 */
1374 if (n >= MAXHOSTNAMELEN) {
1375 h_errno = NO_RECOVERY;
1376 return (NULL);
1377 }
1378 canonname = bp;
1379 bp += n;
1380 /* The qname can be abbreviated, but h_name is now absolute. */
1381 qname = canonname;
1382 }
1383 haveanswer = 0;
1384 had_error = 0;
1385 while (ancount-- > 0 && cp < eom && !had_error) {
1386 n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1387 if ((n < 0) || !(*name_ok)(bp)) {
1388 had_error++;
1389 continue;
1390 }
1391 cp += n; /* name */
Elliott Hughes87c0dba2016-11-14 13:56:32 -08001392 BOUNDS_CHECK(cp, 3 * INT16SZ + INT32SZ);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001393 type = _getshort(cp);
Lorenzo Colittib82532d2011-09-28 19:28:32 -07001394 cp += INT16SZ; /* type */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001395 class = _getshort(cp);
Lorenzo Colittib82532d2011-09-28 19:28:32 -07001396 cp += INT16SZ + INT32SZ; /* class, TTL */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001397 n = _getshort(cp);
1398 cp += INT16SZ; /* len */
Elliott Hughes87c0dba2016-11-14 13:56:32 -08001399 BOUNDS_CHECK(cp, n);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001400 if (class != C_IN) {
1401 /* XXX - debug? syslog? */
1402 cp += n;
1403 continue; /* XXX - had_error++ ? */
1404 }
1405 if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
1406 type == T_CNAME) {
1407 n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
1408 if ((n < 0) || !(*name_ok)(tbuf)) {
1409 had_error++;
1410 continue;
1411 }
1412 cp += n;
1413 /* Get canonical name. */
1414 n = strlen(tbuf) + 1; /* for the \0 */
1415 if (n > ep - bp || n >= MAXHOSTNAMELEN) {
1416 had_error++;
1417 continue;
1418 }
1419 strlcpy(bp, tbuf, (size_t)(ep - bp));
1420 canonname = bp;
1421 bp += n;
1422 continue;
1423 }
1424 if (qtype == T_ANY) {
1425 if (!(type == T_A || type == T_AAAA)) {
1426 cp += n;
1427 continue;
1428 }
1429 } else if (type != qtype) {
1430 if (type != T_KEY && type != T_SIG)
1431 syslog(LOG_NOTICE|LOG_AUTH,
1432 "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
1433 qname, p_class(C_IN), p_type(qtype),
1434 p_type(type));
1435 cp += n;
1436 continue; /* XXX - had_error++ ? */
1437 }
1438 switch (type) {
1439 case T_A:
1440 case T_AAAA:
1441 if (strcasecmp(canonname, bp) != 0) {
1442 syslog(LOG_NOTICE|LOG_AUTH,
1443 AskedForGot, canonname, bp);
1444 cp += n;
1445 continue; /* XXX - had_error++ ? */
1446 }
1447 if (type == T_A && n != INADDRSZ) {
1448 cp += n;
1449 continue;
1450 }
1451 if (type == T_AAAA && n != IN6ADDRSZ) {
1452 cp += n;
1453 continue;
1454 }
1455 if (type == T_AAAA) {
1456 struct in6_addr in6;
1457 memcpy(&in6, cp, IN6ADDRSZ);
1458 if (IN6_IS_ADDR_V4MAPPED(&in6)) {
1459 cp += n;
1460 continue;
1461 }
1462 }
1463 if (!haveanswer) {
1464 int nn;
1465
1466 canonname = bp;
1467 nn = strlen(bp) + 1; /* for the \0 */
1468 bp += nn;
1469 }
1470
1471 /* don't overwrite pai */
1472 ai = *pai;
1473 ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
1474 afd = find_afd(ai.ai_family);
1475 if (afd == NULL) {
1476 cp += n;
1477 continue;
1478 }
1479 cur->ai_next = get_ai(&ai, afd, (const char *)cp);
1480 if (cur->ai_next == NULL)
1481 had_error++;
1482 while (cur && cur->ai_next)
1483 cur = cur->ai_next;
1484 cp += n;
1485 break;
1486 default:
1487 abort();
1488 }
1489 if (!had_error)
1490 haveanswer++;
1491 }
1492 if (haveanswer) {
1493 if (!canonname)
1494 (void)get_canonname(pai, sentinel.ai_next, qname);
1495 else
1496 (void)get_canonname(pai, sentinel.ai_next, canonname);
1497 h_errno = NETDB_SUCCESS;
1498 return sentinel.ai_next;
1499 }
1500
1501 h_errno = NO_RECOVERY;
1502 return NULL;
1503}
1504
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001505struct addrinfo_sort_elem {
1506 struct addrinfo *ai;
1507 int has_src_addr;
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001508 sockaddr_union src_addr;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001509 int original_order;
1510};
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001511
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001512/*ARGSUSED*/
1513static int
1514_get_scope(const struct sockaddr *addr)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001515{
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001516 if (addr->sa_family == AF_INET6) {
1517 const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)addr;
1518 if (IN6_IS_ADDR_MULTICAST(&addr6->sin6_addr)) {
1519 return IPV6_ADDR_MC_SCOPE(&addr6->sin6_addr);
1520 } else if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr) ||
1521 IN6_IS_ADDR_LINKLOCAL(&addr6->sin6_addr)) {
1522 /*
1523 * RFC 4291 section 2.5.3 says loopback is to be treated as having
1524 * link-local scope.
1525 */
1526 return IPV6_ADDR_SCOPE_LINKLOCAL;
1527 } else if (IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr)) {
1528 return IPV6_ADDR_SCOPE_SITELOCAL;
1529 } else {
1530 return IPV6_ADDR_SCOPE_GLOBAL;
1531 }
1532 } else if (addr->sa_family == AF_INET) {
1533 const struct sockaddr_in *addr4 = (const struct sockaddr_in *)addr;
1534 unsigned long int na = ntohl(addr4->sin_addr.s_addr);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001535
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001536 if (IN_LOOPBACK(na) || /* 127.0.0.0/8 */
1537 (na & 0xffff0000) == 0xa9fe0000) { /* 169.254.0.0/16 */
1538 return IPV6_ADDR_SCOPE_LINKLOCAL;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001539 } else {
Steinar H. Gundersond1624ad2010-12-20 11:15:33 +01001540 /*
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001541 * RFC 6724 section 3.2. Other IPv4 addresses, including private addresses
1542 * and shared addresses (100.64.0.0/10), are assigned global scope.
Steinar H. Gundersond1624ad2010-12-20 11:15:33 +01001543 */
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001544 return IPV6_ADDR_SCOPE_GLOBAL;
1545 }
1546 } else {
1547 /*
1548 * This should never happen.
1549 * Return a scope with low priority as a last resort.
1550 */
1551 return IPV6_ADDR_SCOPE_NODELOCAL;
1552 }
1553}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001554
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001555/* These macros are modelled after the ones in <netinet/in6.h>. */
1556
1557/* RFC 4380, section 2.6 */
1558#define IN6_IS_ADDR_TEREDO(a) \
1559 ((*(const uint32_t *)(const void *)(&(a)->s6_addr[0]) == ntohl(0x20010000)))
1560
1561/* RFC 3056, section 2. */
1562#define IN6_IS_ADDR_6TO4(a) \
1563 (((a)->s6_addr[0] == 0x20) && ((a)->s6_addr[1] == 0x02))
1564
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001565/* 6bone testing address area (3ffe::/16), deprecated in RFC 3701. */
1566#define IN6_IS_ADDR_6BONE(a) \
1567 (((a)->s6_addr[0] == 0x3f) && ((a)->s6_addr[1] == 0xfe))
1568
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001569/*
1570 * Get the label for a given IPv4/IPv6 address.
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001571 * RFC 6724, section 2.1.
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001572 */
1573
1574/*ARGSUSED*/
1575static int
1576_get_label(const struct sockaddr *addr)
1577{
1578 if (addr->sa_family == AF_INET) {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001579 return 4;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001580 } else if (addr->sa_family == AF_INET6) {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001581 const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *) addr;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001582 if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr)) {
1583 return 0;
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001584 } else if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001585 return 4;
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001586 } else if (IN6_IS_ADDR_6TO4(&addr6->sin6_addr)) {
1587 return 2;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001588 } else if (IN6_IS_ADDR_TEREDO(&addr6->sin6_addr)) {
1589 return 5;
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001590 } else if (IN6_IS_ADDR_ULA(&addr6->sin6_addr)) {
1591 return 13;
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001592 } else if (IN6_IS_ADDR_V4COMPAT(&addr6->sin6_addr)) {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001593 return 3;
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001594 } else if (IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr)) {
1595 return 11;
1596 } else if (IN6_IS_ADDR_6BONE(&addr6->sin6_addr)) {
1597 return 12;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001598 } else {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001599 /* All other IPv6 addresses, including global unicast addresses. */
1600 return 1;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001601 }
1602 } else {
1603 /*
1604 * This should never happen.
1605 * Return a semi-random label as a last resort.
1606 */
1607 return 1;
1608 }
1609}
1610
1611/*
1612 * Get the precedence for a given IPv4/IPv6 address.
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001613 * RFC 6724, section 2.1.
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001614 */
1615
1616/*ARGSUSED*/
1617static int
1618_get_precedence(const struct sockaddr *addr)
1619{
1620 if (addr->sa_family == AF_INET) {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001621 return 35;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001622 } else if (addr->sa_family == AF_INET6) {
1623 const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)addr;
1624 if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr)) {
1625 return 50;
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001626 } else if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001627 return 35;
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001628 } else if (IN6_IS_ADDR_6TO4(&addr6->sin6_addr)) {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001629 return 30;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001630 } else if (IN6_IS_ADDR_TEREDO(&addr6->sin6_addr)) {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001631 return 5;
1632 } else if (IN6_IS_ADDR_ULA(&addr6->sin6_addr)) {
1633 return 3;
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001634 } else if (IN6_IS_ADDR_V4COMPAT(&addr6->sin6_addr) ||
Lorenzo Colittib82532d2011-09-28 19:28:32 -07001635 IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr) ||
1636 IN6_IS_ADDR_6BONE(&addr6->sin6_addr)) {
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001637 return 1;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001638 } else {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001639 /* All other IPv6 addresses, including global unicast addresses. */
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001640 return 40;
1641 }
1642 } else {
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001643 return 1;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001644 }
1645}
1646
1647/*
1648 * Find number of matching initial bits between the two addresses a1 and a2.
1649 */
1650
1651/*ARGSUSED*/
1652static int
1653_common_prefix_len(const struct in6_addr *a1, const struct in6_addr *a2)
1654{
1655 const char *p1 = (const char *)a1;
1656 const char *p2 = (const char *)a2;
1657 unsigned i;
1658
1659 for (i = 0; i < sizeof(*a1); ++i) {
1660 int x, j;
1661
1662 if (p1[i] == p2[i]) {
1663 continue;
1664 }
1665 x = p1[i] ^ p2[i];
1666 for (j = 0; j < CHAR_BIT; ++j) {
1667 if (x & (1 << (CHAR_BIT - 1))) {
1668 return i * CHAR_BIT + j;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001669 }
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001670 x <<= 1;
1671 }
1672 }
1673 return sizeof(*a1) * CHAR_BIT;
1674}
1675
1676/*
1677 * Compare two source/destination address pairs.
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001678 * RFC 6724, section 6.
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001679 */
1680
1681/*ARGSUSED*/
1682static int
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001683_rfc6724_compare(const void *ptr1, const void* ptr2)
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001684{
1685 const struct addrinfo_sort_elem *a1 = (const struct addrinfo_sort_elem *)ptr1;
1686 const struct addrinfo_sort_elem *a2 = (const struct addrinfo_sort_elem *)ptr2;
1687 int scope_src1, scope_dst1, scope_match1;
1688 int scope_src2, scope_dst2, scope_match2;
1689 int label_src1, label_dst1, label_match1;
1690 int label_src2, label_dst2, label_match2;
1691 int precedence1, precedence2;
1692 int prefixlen1, prefixlen2;
1693
1694 /* Rule 1: Avoid unusable destinations. */
1695 if (a1->has_src_addr != a2->has_src_addr) {
1696 return a2->has_src_addr - a1->has_src_addr;
1697 }
1698
1699 /* Rule 2: Prefer matching scope. */
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001700 scope_src1 = _get_scope(&a1->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001701 scope_dst1 = _get_scope(a1->ai->ai_addr);
1702 scope_match1 = (scope_src1 == scope_dst1);
1703
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001704 scope_src2 = _get_scope(&a2->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001705 scope_dst2 = _get_scope(a2->ai->ai_addr);
1706 scope_match2 = (scope_src2 == scope_dst2);
1707
1708 if (scope_match1 != scope_match2) {
1709 return scope_match2 - scope_match1;
1710 }
1711
1712 /*
1713 * Rule 3: Avoid deprecated addresses.
1714 * TODO(sesse): We don't currently have a good way of finding this.
1715 */
1716
1717 /*
1718 * Rule 4: Prefer home addresses.
1719 * TODO(sesse): We don't currently have a good way of finding this.
1720 */
1721
1722 /* Rule 5: Prefer matching label. */
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001723 label_src1 = _get_label(&a1->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001724 label_dst1 = _get_label(a1->ai->ai_addr);
1725 label_match1 = (label_src1 == label_dst1);
1726
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001727 label_src2 = _get_label(&a2->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001728 label_dst2 = _get_label(a2->ai->ai_addr);
1729 label_match2 = (label_src2 == label_dst2);
1730
1731 if (label_match1 != label_match2) {
1732 return label_match2 - label_match1;
1733 }
1734
1735 /* Rule 6: Prefer higher precedence. */
1736 precedence1 = _get_precedence(a1->ai->ai_addr);
1737 precedence2 = _get_precedence(a2->ai->ai_addr);
1738 if (precedence1 != precedence2) {
1739 return precedence2 - precedence1;
1740 }
1741
1742 /*
1743 * Rule 7: Prefer native transport.
1744 * TODO(sesse): We don't currently have a good way of finding this.
1745 */
1746
1747 /* Rule 8: Prefer smaller scope. */
1748 if (scope_dst1 != scope_dst2) {
1749 return scope_dst1 - scope_dst2;
1750 }
1751
1752 /*
1753 * Rule 9: Use longest matching prefix.
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001754 * We implement this for IPv6 only, as the rules in RFC 6724 don't seem
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001755 * to work very well directly applied to IPv4. (glibc uses information from
1756 * the routing table for a custom IPv4 implementation here.)
1757 */
1758 if (a1->has_src_addr && a1->ai->ai_addr->sa_family == AF_INET6 &&
1759 a2->has_src_addr && a2->ai->ai_addr->sa_family == AF_INET6) {
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001760 const struct sockaddr_in6 *a1_src = &a1->src_addr.in6;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001761 const struct sockaddr_in6 *a1_dst = (const struct sockaddr_in6 *)a1->ai->ai_addr;
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001762 const struct sockaddr_in6 *a2_src = &a2->src_addr.in6;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001763 const struct sockaddr_in6 *a2_dst = (const struct sockaddr_in6 *)a2->ai->ai_addr;
1764 prefixlen1 = _common_prefix_len(&a1_src->sin6_addr, &a1_dst->sin6_addr);
Kenny Root7e0bfb52010-03-24 18:06:20 -07001765 prefixlen2 = _common_prefix_len(&a2_src->sin6_addr, &a2_dst->sin6_addr);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001766 if (prefixlen1 != prefixlen2) {
1767 return prefixlen2 - prefixlen1;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001768 }
1769 }
1770
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001771 /*
1772 * Rule 10: Leave the order unchanged.
1773 * We need this since qsort() is not necessarily stable.
1774 */
1775 return a1->original_order - a2->original_order;
1776}
1777
1778/*
1779 * Find the source address that will be used if trying to connect to the given
1780 * address. src_addr must be large enough to hold a struct sockaddr_in6.
1781 *
1782 * Returns 1 if a source address was found, 0 if the address is unreachable,
Erik Kline01e37c92015-06-25 14:27:34 +09001783 * and -1 if a fatal error occurred. If 0 or -1, the contents of src_addr are
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001784 * undefined.
1785 */
1786
1787/*ARGSUSED*/
1788static int
Erik Kline01e37c92015-06-25 14:27:34 +09001789_find_src_addr(const struct sockaddr *addr, struct sockaddr *src_addr, unsigned mark, uid_t uid)
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001790{
1791 int sock;
1792 int ret;
1793 socklen_t len;
1794
1795 switch (addr->sa_family) {
1796 case AF_INET:
1797 len = sizeof(struct sockaddr_in);
1798 break;
1799 case AF_INET6:
1800 len = sizeof(struct sockaddr_in6);
1801 break;
1802 default:
1803 /* No known usable source address for non-INET families. */
1804 return 0;
1805 }
1806
Nick Kralevich1781ed72014-06-29 20:46:17 -07001807 sock = socket(addr->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001808 if (sock == -1) {
1809 if (errno == EAFNOSUPPORT) {
1810 return 0;
1811 } else {
1812 return -1;
1813 }
1814 }
Erik Kline7bbb1812016-03-04 17:16:55 +09001815 if (mark != MARK_UNSET && setsockopt(sock, SOL_SOCKET, SO_MARK, &mark, sizeof(mark)) < 0) {
1816 close(sock);
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001817 return 0;
Erik Kline7bbb1812016-03-04 17:16:55 +09001818 }
1819 if (uid > 0 && uid != NET_CONTEXT_INVALID_UID && fchown(sock, uid, (gid_t)-1) < 0) {
1820 close(sock);
Erik Kline01e37c92015-06-25 14:27:34 +09001821 return 0;
Erik Kline7bbb1812016-03-04 17:16:55 +09001822 }
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001823 do {
Paul Jensen31ad0372014-05-29 16:28:30 -04001824 ret = __connect(sock, addr, len);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001825 } while (ret == -1 && errno == EINTR);
1826
1827 if (ret == -1) {
1828 close(sock);
1829 return 0;
1830 }
1831
Erik Kline01e37c92015-06-25 14:27:34 +09001832 if (src_addr && getsockname(sock, src_addr, &len) == -1) {
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001833 close(sock);
1834 return -1;
1835 }
1836 close(sock);
1837 return 1;
1838}
1839
1840/*
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001841 * Sort the linked list starting at sentinel->ai_next in RFC6724 order.
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001842 * Will leave the list unchanged if an error occurs.
1843 */
1844
1845/*ARGSUSED*/
1846static void
Erik Kline01e37c92015-06-25 14:27:34 +09001847_rfc6724_sort(struct addrinfo *list_sentinel, unsigned mark, uid_t uid)
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001848{
1849 struct addrinfo *cur;
1850 int nelem = 0, i;
1851 struct addrinfo_sort_elem *elems;
1852
1853 cur = list_sentinel->ai_next;
1854 while (cur) {
1855 ++nelem;
1856 cur = cur->ai_next;
1857 }
1858
1859 elems = (struct addrinfo_sort_elem *)malloc(nelem * sizeof(struct addrinfo_sort_elem));
1860 if (elems == NULL) {
1861 goto error;
1862 }
1863
1864 /*
1865 * Convert the linked list to an array that also contains the candidate
1866 * source address for each destination address.
1867 */
1868 for (i = 0, cur = list_sentinel->ai_next; i < nelem; ++i, cur = cur->ai_next) {
1869 int has_src_addr;
1870 assert(cur != NULL);
1871 elems[i].ai = cur;
1872 elems[i].original_order = i;
1873
Erik Kline01e37c92015-06-25 14:27:34 +09001874 has_src_addr = _find_src_addr(cur->ai_addr, &elems[i].src_addr.generic, mark, uid);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001875 if (has_src_addr == -1) {
1876 goto error;
1877 }
1878 elems[i].has_src_addr = has_src_addr;
1879 }
1880
1881 /* Sort the addresses, and rearrange the linked list so it matches the sorted order. */
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001882 qsort((void *)elems, nelem, sizeof(struct addrinfo_sort_elem), _rfc6724_compare);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001883
1884 list_sentinel->ai_next = elems[0].ai;
1885 for (i = 0; i < nelem - 1; ++i) {
1886 elems[i].ai->ai_next = elems[i + 1].ai;
1887 }
1888 elems[nelem - 1].ai->ai_next = NULL;
1889
1890error:
1891 free(elems);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001892}
1893
1894/*ARGSUSED*/
1895static int
1896_dns_getaddrinfo(void *rv, void *cb_data, va_list ap)
1897{
1898 struct addrinfo *ai;
1899 querybuf *buf, *buf2;
1900 const char *name;
1901 const struct addrinfo *pai;
1902 struct addrinfo sentinel, *cur;
1903 struct res_target q, q2;
1904 res_state res;
Erik Kline01e37c92015-06-25 14:27:34 +09001905 const struct android_net_context *netcontext;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001906
1907 name = va_arg(ap, char *);
1908 pai = va_arg(ap, const struct addrinfo *);
Erik Kline01e37c92015-06-25 14:27:34 +09001909 netcontext = va_arg(ap, const struct android_net_context *);
David 'Digit' Turner5e563702009-05-05 15:50:24 +02001910 //fprintf(stderr, "_dns_getaddrinfo() name = '%s'\n", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001911
1912 memset(&q, 0, sizeof(q));
1913 memset(&q2, 0, sizeof(q2));
1914 memset(&sentinel, 0, sizeof(sentinel));
1915 cur = &sentinel;
1916
1917 buf = malloc(sizeof(*buf));
1918 if (buf == NULL) {
1919 h_errno = NETDB_INTERNAL;
1920 return NS_NOTFOUND;
1921 }
1922 buf2 = malloc(sizeof(*buf2));
1923 if (buf2 == NULL) {
1924 free(buf);
1925 h_errno = NETDB_INTERNAL;
1926 return NS_NOTFOUND;
1927 }
1928
1929 switch (pai->ai_family) {
1930 case AF_UNSPEC:
1931 /* prefer IPv6 */
1932 q.name = name;
1933 q.qclass = C_IN;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001934 q.answer = buf->buf;
1935 q.anslen = sizeof(buf->buf);
Lorenzo Colittiba96e302011-01-14 12:26:05 -08001936 int query_ipv6 = 1, query_ipv4 = 1;
1937 if (pai->ai_flags & AI_ADDRCONFIG) {
Erik Kline01e37c92015-06-25 14:27:34 +09001938 query_ipv6 = _have_ipv6(netcontext->app_mark, netcontext->uid);
1939 query_ipv4 = _have_ipv4(netcontext->app_mark, netcontext->uid);
Lorenzo Colittiba96e302011-01-14 12:26:05 -08001940 }
1941 if (query_ipv6) {
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -07001942 q.qtype = T_AAAA;
Lorenzo Colittiba96e302011-01-14 12:26:05 -08001943 if (query_ipv4) {
1944 q.next = &q2;
1945 q2.name = name;
1946 q2.qclass = C_IN;
1947 q2.qtype = T_A;
1948 q2.answer = buf2->buf;
1949 q2.anslen = sizeof(buf2->buf);
1950 }
1951 } else if (query_ipv4) {
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -07001952 q.qtype = T_A;
Lorenzo Colittiba96e302011-01-14 12:26:05 -08001953 } else {
1954 free(buf);
1955 free(buf2);
1956 return NS_NOTFOUND;
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -07001957 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001958 break;
1959 case AF_INET:
1960 q.name = name;
1961 q.qclass = C_IN;
1962 q.qtype = T_A;
1963 q.answer = buf->buf;
1964 q.anslen = sizeof(buf->buf);
1965 break;
1966 case AF_INET6:
1967 q.name = name;
1968 q.qclass = C_IN;
1969 q.qtype = T_AAAA;
1970 q.answer = buf->buf;
1971 q.anslen = sizeof(buf->buf);
1972 break;
1973 default:
1974 free(buf);
1975 free(buf2);
1976 return NS_UNAVAIL;
1977 }
1978
1979 res = __res_get_state();
1980 if (res == NULL) {
1981 free(buf);
1982 free(buf2);
1983 return NS_NOTFOUND;
1984 }
1985
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001986 /* this just sets our netid val in the thread private data so we don't have to
Mattias Falkc63e5902011-08-23 14:34:14 +02001987 * modify the api's all the way down to res_send.c's res_nsend. We could
1988 * fully populate the thread private data here, but if we get down there
1989 * and have a cache hit that would be wasted, so we do the rest there on miss
1990 */
Ben Schwartz90a83be2017-04-24 17:57:11 -04001991 res_setnetcontext(res, netcontext);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001992 if (res_searchN(name, &q, res) < 0) {
1993 __res_put_state(res);
1994 free(buf);
1995 free(buf2);
1996 return NS_NOTFOUND;
1997 }
1998 ai = getanswer(buf, q.n, q.name, q.qtype, pai);
1999 if (ai) {
2000 cur->ai_next = ai;
2001 while (cur && cur->ai_next)
2002 cur = cur->ai_next;
2003 }
2004 if (q.next) {
2005 ai = getanswer(buf2, q2.n, q2.name, q2.qtype, pai);
2006 if (ai)
2007 cur->ai_next = ai;
2008 }
2009 free(buf);
2010 free(buf2);
2011 if (sentinel.ai_next == NULL) {
2012 __res_put_state(res);
2013 switch (h_errno) {
2014 case HOST_NOT_FOUND:
2015 return NS_NOTFOUND;
2016 case TRY_AGAIN:
2017 return NS_TRYAGAIN;
2018 default:
2019 return NS_UNAVAIL;
2020 }
2021 }
2022
Erik Kline01e37c92015-06-25 14:27:34 +09002023 _rfc6724_sort(&sentinel, netcontext->app_mark, netcontext->uid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002024
2025 __res_put_state(res);
2026
2027 *((struct addrinfo **)rv) = sentinel.ai_next;
2028 return NS_SUCCESS;
2029}
2030
2031static void
2032_sethtent(FILE **hostf)
2033{
2034
2035 if (!*hostf)
Elliott Hughesc674edb2014-08-26 15:56:54 -07002036 *hostf = fopen(_PATH_HOSTS, "re");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002037 else
2038 rewind(*hostf);
2039}
2040
2041static void
2042_endhtent(FILE **hostf)
2043{
2044
2045 if (*hostf) {
2046 (void) fclose(*hostf);
2047 *hostf = NULL;
2048 }
2049}
2050
2051static struct addrinfo *
2052_gethtent(FILE **hostf, const char *name, const struct addrinfo *pai)
2053{
2054 char *p;
2055 char *cp, *tname, *cname;
2056 struct addrinfo hints, *res0, *res;
2057 int error;
2058 const char *addr;
2059 char hostbuf[8*1024];
2060
2061// fprintf(stderr, "_gethtent() name = '%s'\n", name);
2062 assert(name != NULL);
2063 assert(pai != NULL);
2064
Elliott Hughesc674edb2014-08-26 15:56:54 -07002065 if (!*hostf && !(*hostf = fopen(_PATH_HOSTS, "re")))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002066 return (NULL);
2067 again:
2068 if (!(p = fgets(hostbuf, sizeof hostbuf, *hostf)))
2069 return (NULL);
2070 if (*p == '#')
2071 goto again;
2072 if (!(cp = strpbrk(p, "#\n")))
2073 goto again;
2074 *cp = '\0';
2075 if (!(cp = strpbrk(p, " \t")))
2076 goto again;
2077 *cp++ = '\0';
2078 addr = p;
2079 /* if this is not something we're looking for, skip it. */
2080 cname = NULL;
2081 while (cp && *cp) {
2082 if (*cp == ' ' || *cp == '\t') {
2083 cp++;
2084 continue;
2085 }
2086 if (!cname)
2087 cname = cp;
2088 tname = cp;
2089 if ((cp = strpbrk(cp, " \t")) != NULL)
2090 *cp++ = '\0';
2091// fprintf(stderr, "\ttname = '%s'", tname);
2092 if (strcasecmp(name, tname) == 0)
2093 goto found;
2094 }
2095 goto again;
2096
2097found:
2098 hints = *pai;
2099 hints.ai_flags = AI_NUMERICHOST;
2100 error = getaddrinfo(addr, NULL, &hints, &res0);
2101 if (error)
2102 goto again;
2103 for (res = res0; res; res = res->ai_next) {
2104 /* cover it up */
2105 res->ai_flags = pai->ai_flags;
2106
2107 if (pai->ai_flags & AI_CANONNAME) {
2108 if (get_canonname(pai, res, cname) != 0) {
2109 freeaddrinfo(res0);
2110 goto again;
2111 }
2112 }
2113 }
2114 return res0;
2115}
2116
2117/*ARGSUSED*/
2118static int
2119_files_getaddrinfo(void *rv, void *cb_data, va_list ap)
2120{
2121 const char *name;
2122 const struct addrinfo *pai;
2123 struct addrinfo sentinel, *cur;
2124 struct addrinfo *p;
2125 FILE *hostf = NULL;
2126
2127 name = va_arg(ap, char *);
2128 pai = va_arg(ap, struct addrinfo *);
2129
Tom Marshall2af99722016-06-17 16:38:12 -07002130 memset(&sentinel, 0, sizeof(sentinel));
2131 cur = &sentinel;
2132 int gai_error = hc_getaddrinfo(name, NULL, pai, &cur);
2133 if (gai_error != EAI_SYSTEM) {
2134 *((struct addrinfo **)rv) = sentinel.ai_next;
2135 return (gai_error == 0 ? NS_SUCCESS : NS_NOTFOUND);
2136 }
2137
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002138// fprintf(stderr, "_files_getaddrinfo() name = '%s'\n", name);
2139 memset(&sentinel, 0, sizeof(sentinel));
2140 cur = &sentinel;
2141
2142 _sethtent(&hostf);
2143 while ((p = _gethtent(&hostf, name, pai)) != NULL) {
2144 cur->ai_next = p;
2145 while (cur && cur->ai_next)
2146 cur = cur->ai_next;
2147 }
2148 _endhtent(&hostf);
2149
2150 *((struct addrinfo **)rv) = sentinel.ai_next;
2151 if (sentinel.ai_next == NULL)
2152 return NS_NOTFOUND;
2153 return NS_SUCCESS;
2154}
2155
2156/* resolver logic */
2157
2158/*
2159 * Formulate a normal query, send, and await answer.
2160 * Returned answer is placed in supplied buffer "answer".
2161 * Perform preliminary check of answer, returning success only
2162 * if no error is indicated and the answer count is nonzero.
2163 * Return the size of the response on success, -1 on error.
2164 * Error number is left in h_errno.
2165 *
2166 * Caller must parse answer and determine whether it answers the question.
2167 */
2168static int
2169res_queryN(const char *name, /* domain name */ struct res_target *target,
2170 res_state res)
2171{
2172 u_char buf[MAXPACKET];
2173 HEADER *hp;
2174 int n;
2175 struct res_target *t;
2176 int rcode;
2177 int ancount;
2178
2179 assert(name != NULL);
2180 /* XXX: target may be NULL??? */
2181
2182 rcode = NOERROR;
2183 ancount = 0;
2184
2185 for (t = target; t; t = t->next) {
2186 int class, type;
2187 u_char *answer;
2188 int anslen;
Ben Schwartz6eed8e12017-10-02 12:26:05 -04002189 u_int oflags;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002190
2191 hp = (HEADER *)(void *)t->answer;
Ben Schwartz6eed8e12017-10-02 12:26:05 -04002192 oflags = res->_flags;
2193
2194again:
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002195 hp->rcode = NOERROR; /* default */
2196
2197 /* make it easier... */
2198 class = t->qclass;
2199 type = t->qtype;
2200 answer = t->answer;
2201 anslen = t->anslen;
2202#ifdef DEBUG
2203 if (res->options & RES_DEBUG)
2204 printf(";; res_nquery(%s, %d, %d)\n", name, class, type);
2205#endif
2206
2207 n = res_nmkquery(res, QUERY, name, class, type, NULL, 0, NULL,
2208 buf, sizeof(buf));
2209#ifdef RES_USE_EDNS0
Ben Schwartz6eed8e12017-10-02 12:26:05 -04002210 if (n > 0 && (res->_flags & RES_F_EDNS0ERR) == 0 &&
2211 (res->options & (RES_USE_EDNS0|RES_USE_DNSSEC)) != 0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002212 n = res_nopt(res, n, buf, sizeof(buf), anslen);
2213#endif
2214 if (n <= 0) {
2215#ifdef DEBUG
2216 if (res->options & RES_DEBUG)
2217 printf(";; res_nquery: mkquery failed\n");
2218#endif
2219 h_errno = NO_RECOVERY;
2220 return n;
2221 }
2222 n = res_nsend(res, buf, n, answer, anslen);
2223#if 0
2224 if (n < 0) {
2225#ifdef DEBUG
2226 if (res->options & RES_DEBUG)
2227 printf(";; res_query: send error\n");
2228#endif
2229 h_errno = TRY_AGAIN;
2230 return n;
2231 }
2232#endif
2233
2234 if (n < 0 || hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
2235 rcode = hp->rcode; /* record most recent error */
Ben Schwartz6eed8e12017-10-02 12:26:05 -04002236#ifdef RES_USE_EDNS0
2237 /* if the query choked with EDNS0, retry without EDNS0 */
2238 if ((res->options & (RES_USE_EDNS0|RES_USE_DNSSEC)) != 0 &&
2239 ((oflags ^ res->_flags) & RES_F_EDNS0ERR) != 0) {
2240 res->_flags |= RES_F_EDNS0ERR;
2241#ifdef DEBUG
2242 if (res->options & RES_DEBUG)
2243 printf(";; res_nquery: retry without EDNS0\n");
2244#endif
2245 goto again;
2246 }
2247#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002248#ifdef DEBUG
2249 if (res->options & RES_DEBUG)
2250 printf(";; rcode = %u, ancount=%u\n", hp->rcode,
2251 ntohs(hp->ancount));
2252#endif
2253 continue;
2254 }
2255
2256 ancount += ntohs(hp->ancount);
2257
2258 t->n = n;
2259 }
2260
2261 if (ancount == 0) {
2262 switch (rcode) {
2263 case NXDOMAIN:
2264 h_errno = HOST_NOT_FOUND;
2265 break;
2266 case SERVFAIL:
2267 h_errno = TRY_AGAIN;
2268 break;
2269 case NOERROR:
2270 h_errno = NO_DATA;
2271 break;
2272 case FORMERR:
2273 case NOTIMP:
2274 case REFUSED:
2275 default:
2276 h_errno = NO_RECOVERY;
2277 break;
2278 }
2279 return -1;
2280 }
2281 return ancount;
2282}
2283
2284/*
2285 * Formulate a normal query, send, and retrieve answer in supplied buffer.
2286 * Return the size of the response on success, -1 on error.
2287 * If enabled, implement search rules until answer or unrecoverable failure
2288 * is detected. Error code, if any, is left in h_errno.
2289 */
2290static int
2291res_searchN(const char *name, struct res_target *target, res_state res)
2292{
2293 const char *cp, * const *domain;
2294 HEADER *hp;
2295 u_int dots;
2296 int trailing_dot, ret, saved_herrno;
2297 int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
2298
2299 assert(name != NULL);
2300 assert(target != NULL);
2301
2302 hp = (HEADER *)(void *)target->answer; /*XXX*/
2303
2304 errno = 0;
2305 h_errno = HOST_NOT_FOUND; /* default, if we never query */
2306 dots = 0;
2307 for (cp = name; *cp; cp++)
2308 dots += (*cp == '.');
2309 trailing_dot = 0;
2310 if (cp > name && *--cp == '.')
2311 trailing_dot++;
2312
2313
David 'Digit' Turner5e563702009-05-05 15:50:24 +02002314 //fprintf(stderr, "res_searchN() name = '%s'\n", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002315
2316 /*
2317 * if there aren't any dots, it could be a user-level alias
2318 */
2319 if (!dots && (cp = __hostalias(name)) != NULL) {
2320 ret = res_queryN(cp, target, res);
2321 return ret;
2322 }
2323
2324 /*
2325 * If there are dots in the name already, let's just give it a try
2326 * 'as is'. The threshold can be set with the "ndots" option.
2327 */
2328 saved_herrno = -1;
2329 if (dots >= res->ndots) {
2330 ret = res_querydomainN(name, NULL, target, res);
2331 if (ret > 0)
2332 return (ret);
2333 saved_herrno = h_errno;
2334 tried_as_is++;
2335 }
2336
2337 /*
2338 * We do at least one level of search if
2339 * - there is no dot and RES_DEFNAME is set, or
2340 * - there is at least one dot, there is no trailing dot,
2341 * and RES_DNSRCH is set.
2342 */
2343 if ((!dots && (res->options & RES_DEFNAMES)) ||
2344 (dots && !trailing_dot && (res->options & RES_DNSRCH))) {
2345 int done = 0;
2346
Robert Greenwalte0805a92013-07-31 16:53:46 -07002347 /* Unfortunately we need to set stuff up before
2348 * the domain stuff is tried. Will have a better
2349 * fix after thread pools are used.
2350 */
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05002351 _resolv_populate_res_for_net(res);
Robert Greenwalte0805a92013-07-31 16:53:46 -07002352
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002353 for (domain = (const char * const *)res->dnsrch;
2354 *domain && !done;
2355 domain++) {
2356
2357 ret = res_querydomainN(name, *domain, target, res);
2358 if (ret > 0)
2359 return ret;
2360
2361 /*
2362 * If no server present, give up.
2363 * If name isn't found in this domain,
2364 * keep trying higher domains in the search list
2365 * (if that's enabled).
2366 * On a NO_DATA error, keep trying, otherwise
2367 * a wildcard entry of another type could keep us
2368 * from finding this entry higher in the domain.
2369 * If we get some other error (negative answer or
2370 * server failure), then stop searching up,
2371 * but try the input name below in case it's
2372 * fully-qualified.
2373 */
2374 if (errno == ECONNREFUSED) {
2375 h_errno = TRY_AGAIN;
2376 return -1;
2377 }
2378
2379 switch (h_errno) {
2380 case NO_DATA:
2381 got_nodata++;
2382 /* FALLTHROUGH */
2383 case HOST_NOT_FOUND:
2384 /* keep trying */
2385 break;
2386 case TRY_AGAIN:
2387 if (hp->rcode == SERVFAIL) {
2388 /* try next search element, if any */
2389 got_servfail++;
2390 break;
2391 }
2392 /* FALLTHROUGH */
2393 default:
2394 /* anything else implies that we're done */
2395 done++;
2396 }
2397 /*
2398 * if we got here for some reason other than DNSRCH,
2399 * we only wanted one iteration of the loop, so stop.
2400 */
2401 if (!(res->options & RES_DNSRCH))
Lorenzo Colittib82532d2011-09-28 19:28:32 -07002402 done++;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002403 }
2404 }
2405
2406 /*
2407 * if we have not already tried the name "as is", do that now.
2408 * note that we do this regardless of how many dots were in the
2409 * name or whether it ends with a dot.
2410 */
2411 if (!tried_as_is) {
2412 ret = res_querydomainN(name, NULL, target, res);
2413 if (ret > 0)
2414 return ret;
2415 }
2416
2417 /*
2418 * if we got here, we didn't satisfy the search.
2419 * if we did an initial full query, return that query's h_errno
2420 * (note that we wouldn't be here if that query had succeeded).
2421 * else if we ever got a nodata, send that back as the reason.
2422 * else send back meaningless h_errno, that being the one from
2423 * the last DNSRCH we did.
2424 */
2425 if (saved_herrno != -1)
2426 h_errno = saved_herrno;
2427 else if (got_nodata)
2428 h_errno = NO_DATA;
2429 else if (got_servfail)
2430 h_errno = TRY_AGAIN;
2431 return -1;
2432}
2433
2434/*
2435 * Perform a call on res_query on the concatenation of name and domain,
2436 * removing a trailing dot from name if domain is NULL.
2437 */
2438static int
2439res_querydomainN(const char *name, const char *domain,
2440 struct res_target *target, res_state res)
2441{
2442 char nbuf[MAXDNAME];
2443 const char *longname = nbuf;
2444 size_t n, d;
2445
2446 assert(name != NULL);
2447 /* XXX: target may be NULL??? */
2448
2449#ifdef DEBUG
2450 if (res->options & RES_DEBUG)
2451 printf(";; res_querydomain(%s, %s)\n",
2452 name, domain?domain:"<Nil>");
2453#endif
2454 if (domain == NULL) {
2455 /*
2456 * Check for trailing '.';
2457 * copy without '.' if present.
2458 */
2459 n = strlen(name);
2460 if (n + 1 > sizeof(nbuf)) {
2461 h_errno = NO_RECOVERY;
2462 return -1;
2463 }
2464 if (n > 0 && name[--n] == '.') {
2465 strncpy(nbuf, name, n);
2466 nbuf[n] = '\0';
2467 } else
2468 longname = name;
2469 } else {
2470 n = strlen(name);
2471 d = strlen(domain);
2472 if (n + 1 + d + 1 > sizeof(nbuf)) {
2473 h_errno = NO_RECOVERY;
2474 return -1;
2475 }
2476 snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
2477 }
2478 return res_queryN(longname, target, res);
2479}