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