blob: c6f0d248c84f24e359611a7962ea807593738454 [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
Elliott Hughesa9209d72016-09-16 18:16:47 -0700111#if defined(__BIONIC__)
Brad Fitzpatrick78585642010-10-28 13:22:20 -0700112#include <sys/system_properties.h>
Elliott Hughesa9209d72016-09-16 18:16:47 -0700113#endif
Brad Fitzpatrick78585642010-10-28 13:22:20 -0700114
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -0700115typedef union sockaddr_union {
116 struct sockaddr generic;
117 struct sockaddr_in in;
118 struct sockaddr_in6 in6;
119} sockaddr_union;
120
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800121#define SUCCESS 0
122#define ANY 0
123#define YES 1
124#define NO 0
125
126static const char in_addrany[] = { 0, 0, 0, 0 };
127static const char in_loopback[] = { 127, 0, 0, 1 };
128#ifdef INET6
129static const char in6_addrany[] = {
130 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
131};
132static const char in6_loopback[] = {
133 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
134};
135#endif
136
Dan Willemsen7ec52b12016-11-28 17:02:25 -0800137#if defined(__ANDROID__)
Selim Gurun06e18312012-02-27 15:58:54 -0800138// This should be synchronized to ResponseCode.h
139static const int DnsProxyQueryResult = 222;
Dan Willemsen7ec52b12016-11-28 17:02:25 -0800140#endif
Selim Gurun06e18312012-02-27 15:58:54 -0800141
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800142static const struct afd {
143 int a_af;
144 int a_addrlen;
145 int a_socklen;
146 int a_off;
147 const char *a_addrany;
148 const char *a_loopback;
149 int a_scoped;
150} afdl [] = {
151#ifdef INET6
152 {PF_INET6, sizeof(struct in6_addr),
153 sizeof(struct sockaddr_in6),
154 offsetof(struct sockaddr_in6, sin6_addr),
155 in6_addrany, in6_loopback, 1},
156#endif
157 {PF_INET, sizeof(struct in_addr),
158 sizeof(struct sockaddr_in),
159 offsetof(struct sockaddr_in, sin_addr),
160 in_addrany, in_loopback, 0},
161 {0, 0, 0, 0, NULL, NULL, 0},
162};
163
164struct explore {
165 int e_af;
166 int e_socktype;
167 int e_protocol;
168 const char *e_protostr;
169 int e_wild;
170#define WILD_AF(ex) ((ex)->e_wild & 0x01)
171#define WILD_SOCKTYPE(ex) ((ex)->e_wild & 0x02)
172#define WILD_PROTOCOL(ex) ((ex)->e_wild & 0x04)
173};
174
175static const struct explore explore[] = {
176#if 0
177 { PF_LOCAL, 0, ANY, ANY, NULL, 0x01 },
178#endif
179#ifdef INET6
180 { PF_INET6, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
181 { PF_INET6, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
182 { PF_INET6, SOCK_RAW, ANY, NULL, 0x05 },
183#endif
184 { PF_INET, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
185 { PF_INET, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
186 { PF_INET, SOCK_RAW, ANY, NULL, 0x05 },
187 { PF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 },
188 { PF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 },
189 { PF_UNSPEC, SOCK_RAW, ANY, NULL, 0x05 },
190 { -1, 0, 0, NULL, 0 },
191};
192
193#ifdef INET6
194#define PTON_MAX 16
195#else
196#define PTON_MAX 4
197#endif
198
199static const ns_src default_dns_files[] = {
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700200 { NSSRC_FILES, NS_SUCCESS },
201 { NSSRC_DNS, NS_SUCCESS },
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800202 { 0, 0 }
203};
204
205#define MAXPACKET (64*1024)
206
207typedef union {
208 HEADER hdr;
209 u_char buf[MAXPACKET];
210} querybuf;
211
212struct res_target {
213 struct res_target *next;
214 const char *name; /* domain name */
215 int qclass, qtype; /* class and type of query */
216 u_char *answer; /* buffer to put answer */
217 int anslen; /* size of answer buffer */
218 int n; /* result length */
219};
220
221static int str2number(const char *);
222static int explore_fqdn(const struct addrinfo *, const char *,
Erik Kline01e37c92015-06-25 14:27:34 +0900223 const char *, struct addrinfo **, const struct android_net_context *);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800224static int explore_null(const struct addrinfo *,
225 const char *, struct addrinfo **);
226static int explore_numeric(const struct addrinfo *, const char *,
227 const char *, struct addrinfo **, const char *);
228static int explore_numeric_scope(const struct addrinfo *, const char *,
229 const char *, struct addrinfo **);
230static int get_canonname(const struct addrinfo *,
231 struct addrinfo *, const char *);
232static struct addrinfo *get_ai(const struct addrinfo *,
233 const struct afd *, const char *);
234static int get_portmatch(const struct addrinfo *, const char *);
235static int get_port(const struct addrinfo *, const char *, int);
236static const struct afd *find_afd(int);
237#ifdef INET6
238static int ip6_str2scopeid(char *, struct sockaddr_in6 *, u_int32_t *);
239#endif
240
241static struct addrinfo *getanswer(const querybuf *, int, const char *, int,
242 const struct addrinfo *);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800243static int _dns_getaddrinfo(void *, void *, va_list);
244static void _sethtent(FILE **);
245static void _endhtent(FILE **);
246static struct addrinfo *_gethtent(FILE **, const char *,
247 const struct addrinfo *);
248static int _files_getaddrinfo(void *, void *, va_list);
Erik Kline01e37c92015-06-25 14:27:34 +0900249static int _find_src_addr(const struct sockaddr *, struct sockaddr *, unsigned , uid_t);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800250
251static int res_queryN(const char *, struct res_target *, res_state);
252static int res_searchN(const char *, struct res_target *, res_state);
253static int res_querydomainN(const char *, const char *,
254 struct res_target *, res_state);
255
256static const char * const ai_errlist[] = {
257 "Success",
258 "Address family for hostname not supported", /* EAI_ADDRFAMILY */
259 "Temporary failure in name resolution", /* EAI_AGAIN */
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700260 "Invalid value for ai_flags", /* EAI_BADFLAGS */
261 "Non-recoverable failure in name resolution", /* EAI_FAIL */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800262 "ai_family not supported", /* EAI_FAMILY */
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700263 "Memory allocation failure", /* EAI_MEMORY */
264 "No address associated with hostname", /* EAI_NODATA */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800265 "hostname nor servname provided, or not known", /* EAI_NONAME */
266 "servname not supported for ai_socktype", /* EAI_SERVICE */
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700267 "ai_socktype not supported", /* EAI_SOCKTYPE */
268 "System error returned in errno", /* EAI_SYSTEM */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800269 "Invalid value for hints", /* EAI_BADHINTS */
270 "Resolved protocol is unknown", /* EAI_PROTOCOL */
271 "Argument buffer overflow", /* EAI_OVERFLOW */
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700272 "Unknown error", /* EAI_MAX */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800273};
274
275/* XXX macros that make external reference is BAD. */
276
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700277#define GET_AI(ai, afd, addr) \
278do { \
279 /* external reference: pai, error, and label free */ \
280 (ai) = get_ai(pai, (afd), (addr)); \
281 if ((ai) == NULL) { \
282 error = EAI_MEMORY; \
283 goto free; \
284 } \
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800285} while (/*CONSTCOND*/0)
286
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700287#define GET_PORT(ai, serv) \
288do { \
289 /* external reference: error and label free */ \
290 error = get_port((ai), (serv), 0); \
291 if (error != 0) \
292 goto free; \
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800293} while (/*CONSTCOND*/0)
294
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700295#define GET_CANONNAME(ai, str) \
296do { \
297 /* external reference: pai, error and label free */ \
298 error = get_canonname(pai, (ai), (str)); \
299 if (error != 0) \
300 goto free; \
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800301} while (/*CONSTCOND*/0)
302
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700303#define ERR(err) \
304do { \
305 /* external reference: error, and label bad */ \
306 error = (err); \
307 goto bad; \
308 /*NOTREACHED*/ \
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800309} while (/*CONSTCOND*/0)
310
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700311#define MATCH_FAMILY(x, y, w) \
312 ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC || \
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800313 (y) == PF_UNSPEC)))
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700314#define MATCH(x, y, w) \
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800315 ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY)))
316
317const char *
318gai_strerror(int ecode)
319{
320 if (ecode < 0 || ecode > EAI_MAX)
321 ecode = EAI_MAX;
322 return ai_errlist[ecode];
323}
324
325void
326freeaddrinfo(struct addrinfo *ai)
327{
328 struct addrinfo *next;
329
Elliott Hughesa9209d72016-09-16 18:16:47 -0700330#if defined(__BIONIC__)
Elliott Hughesc62a4b52015-01-08 17:28:46 -0800331 if (ai == NULL) return;
332#else
333 _DIAGASSERT(ai != NULL);
334#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800335
336 do {
337 next = ai->ai_next;
338 if (ai->ai_canonname)
339 free(ai->ai_canonname);
340 /* no need to free(ai->ai_addr) */
341 free(ai);
342 ai = next;
343 } while (ai);
344}
345
346static int
347str2number(const char *p)
348{
349 char *ep;
350 unsigned long v;
351
352 assert(p != NULL);
353
354 if (*p == '\0')
355 return -1;
356 ep = NULL;
357 errno = 0;
358 v = strtoul(p, &ep, 10);
359 if (errno == 0 && ep && *ep == '\0' && v <= UINT_MAX)
360 return v;
361 else
362 return -1;
363}
364
Lorenzo Colittiba96e302011-01-14 12:26:05 -0800365/*
Lorenzo Colittiba96e302011-01-14 12:26:05 -0800366 * The following functions determine whether IPv4 or IPv6 connectivity is
367 * available in order to implement AI_ADDRCONFIG.
368 *
369 * Strictly speaking, AI_ADDRCONFIG should not look at whether connectivity is
370 * available, but whether addresses of the specified family are "configured
371 * on the local system". However, bionic doesn't currently support getifaddrs,
372 * so checking for connectivity is the next best thing.
373 */
374static int
Erik Kline01e37c92015-06-25 14:27:34 +0900375_have_ipv6(unsigned mark, uid_t uid) {
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700376 static const struct sockaddr_in6 sin6_test = {
377 .sin6_family = AF_INET6,
378 .sin6_addr.s6_addr = { // 2000::
379 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
380 };
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500381 sockaddr_union addr = { .in6 = sin6_test };
Erik Kline01e37c92015-06-25 14:27:34 +0900382 return _find_src_addr(&addr.generic, NULL, mark, uid) == 1;
Lorenzo Colittiba96e302011-01-14 12:26:05 -0800383}
384
385static int
Erik Kline01e37c92015-06-25 14:27:34 +0900386_have_ipv4(unsigned mark, uid_t uid) {
Lorenzo Colittib82532d2011-09-28 19:28:32 -0700387 static const struct sockaddr_in sin_test = {
388 .sin_family = AF_INET,
389 .sin_addr.s_addr = __constant_htonl(0x08080808L) // 8.8.8.8
390 };
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500391 sockaddr_union addr = { .in = sin_test };
Erik Kline01e37c92015-06-25 14:27:34 +0900392 return _find_src_addr(&addr.generic, NULL, mark, uid) == 1;
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -0700393}
394
Elliott Hughes55293c12014-11-12 17:00:30 -0800395bool readBE32(FILE* fp, int32_t* result) {
396 int32_t tmp;
397 if (fread(&tmp, sizeof(tmp), 1, fp) != 1) {
398 return false;
399 }
400 *result = ntohl(tmp);
401 return true;
402}
403
Dan Willemsen7ec52b12016-11-28 17:02:25 -0800404#if defined(__ANDROID__)
Mattias Falkc63e5902011-08-23 14:34:14 +0200405// Returns 0 on success, else returns on error.
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700406static int
407android_getaddrinfo_proxy(
408 const char *hostname, const char *servname,
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500409 const struct addrinfo *hints, struct addrinfo **res, unsigned netid)
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700410{
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700411 int success = 0;
412
413 // Clear this at start, as we use its non-NULLness later (in the
414 // error path) to decide if we have to free up any memory we
415 // allocated in the process (before failing).
416 *res = NULL;
417
Mattias Falkc63e5902011-08-23 14:34:14 +0200418 // Bogus things we can't serialize. Don't use the proxy. These will fail - let them.
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700419 if ((hostname != NULL &&
420 strcspn(hostname, " \n\r\t^'\"") != strlen(hostname)) ||
421 (servname != NULL &&
422 strcspn(servname, " \n\r\t^'\"") != strlen(servname))) {
Mattias Falkc63e5902011-08-23 14:34:14 +0200423 return EAI_NODATA;
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700424 }
425
Elliott Hughes9773fa32014-12-10 14:56:46 -0800426 FILE* proxy = android_open_proxy();
427 if (proxy == NULL) {
428 return EAI_SYSTEM;
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700429 }
430
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 Hughes55293c12014-11-12 17:00:30 -0800475 struct addrinfo* 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
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800563int
564getaddrinfo(const char *hostname, const char *servname,
565 const struct addrinfo *hints, struct addrinfo **res)
566{
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500567 return android_getaddrinfofornet(hostname, servname, hints, NETID_UNSET, MARK_UNSET, res);
Mattias Falkc63e5902011-08-23 14:34:14 +0200568}
569
570int
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500571android_getaddrinfofornet(const char *hostname, const char *servname,
572 const struct addrinfo *hints, unsigned netid, unsigned mark, struct addrinfo **res)
Mattias Falkc63e5902011-08-23 14:34:14 +0200573{
Erik Kline01e37c92015-06-25 14:27:34 +0900574 struct android_net_context netcontext = {
575 .app_netid = netid,
576 .app_mark = mark,
577 .dns_netid = netid,
578 .dns_mark = mark,
579 .uid = NET_CONTEXT_INVALID_UID,
580 };
581 return android_getaddrinfofornetcontext(hostname, servname, hints, &netcontext, res);
582}
583
584int
585android_getaddrinfofornetcontext(const char *hostname, const char *servname,
586 const struct addrinfo *hints, const struct android_net_context *netcontext,
587 struct addrinfo **res)
588{
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800589 struct addrinfo sentinel;
590 struct addrinfo *cur;
591 int error = 0;
592 struct addrinfo ai;
593 struct addrinfo ai0;
594 struct addrinfo *pai;
595 const struct explore *ex;
596
597 /* hostname is allowed to be NULL */
598 /* servname is allowed to be NULL */
599 /* hints is allowed to be NULL */
600 assert(res != NULL);
Erik Kline01e37c92015-06-25 14:27:34 +0900601 assert(netcontext != NULL);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800602 memset(&sentinel, 0, sizeof(sentinel));
603 cur = &sentinel;
604 pai = &ai;
605 pai->ai_flags = 0;
606 pai->ai_family = PF_UNSPEC;
607 pai->ai_socktype = ANY;
608 pai->ai_protocol = ANY;
609 pai->ai_addrlen = 0;
610 pai->ai_canonname = NULL;
611 pai->ai_addr = NULL;
612 pai->ai_next = NULL;
613
614 if (hostname == NULL && servname == NULL)
615 return EAI_NONAME;
616 if (hints) {
617 /* error check for hints */
618 if (hints->ai_addrlen || hints->ai_canonname ||
619 hints->ai_addr || hints->ai_next)
620 ERR(EAI_BADHINTS); /* xxx */
621 if (hints->ai_flags & ~AI_MASK)
622 ERR(EAI_BADFLAGS);
623 switch (hints->ai_family) {
624 case PF_UNSPEC:
625 case PF_INET:
626#ifdef INET6
627 case PF_INET6:
628#endif
629 break;
630 default:
631 ERR(EAI_FAMILY);
632 }
633 memcpy(pai, hints, sizeof(*pai));
634
635 /*
636 * if both socktype/protocol are specified, check if they
637 * are meaningful combination.
638 */
639 if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) {
640 for (ex = explore; ex->e_af >= 0; ex++) {
641 if (pai->ai_family != ex->e_af)
642 continue;
643 if (ex->e_socktype == ANY)
644 continue;
645 if (ex->e_protocol == ANY)
646 continue;
647 if (pai->ai_socktype == ex->e_socktype
648 && pai->ai_protocol != ex->e_protocol) {
649 ERR(EAI_BADHINTS);
650 }
651 }
652 }
653 }
654
655 /*
656 * check for special cases. (1) numeric servname is disallowed if
657 * socktype/protocol are left unspecified. (2) servname is disallowed
658 * for raw and other inet{,6} sockets.
659 */
660 if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
661#ifdef PF_INET6
662 || MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
663#endif
664 ) {
665 ai0 = *pai; /* backup *pai */
666
667 if (pai->ai_family == PF_UNSPEC) {
668#ifdef PF_INET6
669 pai->ai_family = PF_INET6;
670#else
671 pai->ai_family = PF_INET;
672#endif
673 }
674 error = get_portmatch(pai, servname);
675 if (error)
676 ERR(error);
677
678 *pai = ai0;
679 }
680
681 ai0 = *pai;
682
683 /* NULL hostname, or numeric hostname */
684 for (ex = explore; ex->e_af >= 0; ex++) {
685 *pai = ai0;
686
687 /* PF_UNSPEC entries are prepared for DNS queries only */
688 if (ex->e_af == PF_UNSPEC)
689 continue;
690
691 if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex)))
692 continue;
693 if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex)))
694 continue;
695 if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex)))
696 continue;
697
698 if (pai->ai_family == PF_UNSPEC)
699 pai->ai_family = ex->e_af;
700 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
701 pai->ai_socktype = ex->e_socktype;
702 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
703 pai->ai_protocol = ex->e_protocol;
704
705 if (hostname == NULL)
706 error = explore_null(pai, servname, &cur->ai_next);
707 else
708 error = explore_numeric_scope(pai, hostname, servname,
709 &cur->ai_next);
710
711 if (error)
712 goto free;
713
714 while (cur->ai_next)
715 cur = cur->ai_next;
716 }
717
718 /*
719 * XXX
720 * If numeric representation of AF1 can be interpreted as FQDN
721 * representation of AF2, we need to think again about the code below.
722 */
723 if (sentinel.ai_next)
724 goto good;
725
726 if (hostname == NULL)
727 ERR(EAI_NODATA);
728 if (pai->ai_flags & AI_NUMERICHOST)
729 ERR(EAI_NONAME);
730
Elliott Hughes9773fa32014-12-10 14:56:46 -0800731#if defined(__ANDROID__)
Erik Kline01e37c92015-06-25 14:27:34 +0900732 int gai_error = android_getaddrinfo_proxy(
733 hostname, servname, hints, res, netcontext->app_netid);
Elliott Hughes9773fa32014-12-10 14:56:46 -0800734 if (gai_error != EAI_SYSTEM) {
735 return gai_error;
Mattias Falkc63e5902011-08-23 14:34:14 +0200736 }
Elliott Hughes9773fa32014-12-10 14:56:46 -0800737#endif
Brad Fitzpatricka1dbf0b2010-10-27 10:36:36 -0700738
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800739 /*
740 * hostname as alphabetical name.
741 * we would like to prefer AF_INET6 than AF_INET, so we'll make a
742 * outer loop by AFs.
743 */
744 for (ex = explore; ex->e_af >= 0; ex++) {
745 *pai = ai0;
746
747 /* require exact match for family field */
748 if (pai->ai_family != ex->e_af)
749 continue;
750
751 if (!MATCH(pai->ai_socktype, ex->e_socktype,
752 WILD_SOCKTYPE(ex))) {
753 continue;
754 }
755 if (!MATCH(pai->ai_protocol, ex->e_protocol,
756 WILD_PROTOCOL(ex))) {
757 continue;
758 }
759
760 if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
761 pai->ai_socktype = ex->e_socktype;
762 if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
763 pai->ai_protocol = ex->e_protocol;
764
Erik Kline01e37c92015-06-25 14:27:34 +0900765 error = explore_fqdn(
766 pai, hostname, servname, &cur->ai_next, netcontext);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800767
768 while (cur && cur->ai_next)
769 cur = cur->ai_next;
770 }
771
772 /* XXX */
773 if (sentinel.ai_next)
774 error = 0;
775
776 if (error)
777 goto free;
778 if (error == 0) {
779 if (sentinel.ai_next) {
780 good:
781 *res = sentinel.ai_next;
782 return SUCCESS;
783 } else
784 error = EAI_FAIL;
785 }
786 free:
787 bad:
788 if (sentinel.ai_next)
789 freeaddrinfo(sentinel.ai_next);
790 *res = NULL;
791 return error;
792}
793
794/*
795 * FQDN hostname, DNS lookup
796 */
797static int
798explore_fqdn(const struct addrinfo *pai, const char *hostname,
Erik Kline01e37c92015-06-25 14:27:34 +0900799 const char *servname, struct addrinfo **res,
800 const struct android_net_context *netcontext)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800801{
802 struct addrinfo *result;
803 struct addrinfo *cur;
804 int error = 0;
805 static const ns_dtab dtab[] = {
806 NS_FILES_CB(_files_getaddrinfo, NULL)
807 { NSSRC_DNS, _dns_getaddrinfo, NULL }, /* force -DHESIOD */
808 NS_NIS_CB(_yp_getaddrinfo, NULL)
809 { 0, 0, 0 }
810 };
811
812 assert(pai != NULL);
813 /* hostname may be NULL */
814 /* servname may be NULL */
815 assert(res != NULL);
816
817 result = NULL;
818
819 /*
820 * if the servname does not match socktype/protocol, ignore it.
821 */
822 if (get_portmatch(pai, servname) != 0)
823 return 0;
824
825 switch (nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo",
Erik Kline01e37c92015-06-25 14:27:34 +0900826 default_dns_files, hostname, pai, netcontext)) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800827 case NS_TRYAGAIN:
828 error = EAI_AGAIN;
829 goto free;
830 case NS_UNAVAIL:
831 error = EAI_FAIL;
832 goto free;
833 case NS_NOTFOUND:
834 error = EAI_NODATA;
835 goto free;
836 case NS_SUCCESS:
837 error = 0;
838 for (cur = result; cur; cur = cur->ai_next) {
839 GET_PORT(cur, servname);
840 /* canonname should be filled already */
841 }
842 break;
843 }
844
845 *res = result;
846
847 return 0;
848
849free:
850 if (result)
851 freeaddrinfo(result);
852 return error;
853}
854
855/*
856 * hostname == NULL.
857 * passive socket -> anyaddr (0.0.0.0 or ::)
858 * non-passive socket -> localhost (127.0.0.1 or ::1)
859 */
860static int
861explore_null(const struct addrinfo *pai, const char *servname,
862 struct addrinfo **res)
863{
864 int s;
865 const struct afd *afd;
866 struct addrinfo *cur;
867 struct addrinfo sentinel;
868 int error;
869
870 assert(pai != NULL);
871 /* servname may be NULL */
872 assert(res != NULL);
873
874 *res = NULL;
875 sentinel.ai_next = NULL;
876 cur = &sentinel;
877
878 /*
879 * filter out AFs that are not supported by the kernel
880 * XXX errno?
881 */
Nick Kralevich1781ed72014-06-29 20:46:17 -0700882 s = socket(pai->ai_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800883 if (s < 0) {
884 if (errno != EMFILE)
885 return 0;
886 } else
887 close(s);
888
889 /*
890 * if the servname does not match socktype/protocol, ignore it.
891 */
892 if (get_portmatch(pai, servname) != 0)
893 return 0;
894
895 afd = find_afd(pai->ai_family);
896 if (afd == NULL)
897 return 0;
898
899 if (pai->ai_flags & AI_PASSIVE) {
900 GET_AI(cur->ai_next, afd, afd->a_addrany);
901 /* xxx meaningless?
902 * GET_CANONNAME(cur->ai_next, "anyaddr");
903 */
904 GET_PORT(cur->ai_next, servname);
905 } else {
906 GET_AI(cur->ai_next, afd, afd->a_loopback);
907 /* xxx meaningless?
908 * GET_CANONNAME(cur->ai_next, "localhost");
909 */
910 GET_PORT(cur->ai_next, servname);
911 }
912 cur = cur->ai_next;
913
914 *res = sentinel.ai_next;
915 return 0;
916
917free:
918 if (sentinel.ai_next)
919 freeaddrinfo(sentinel.ai_next);
920 return error;
921}
922
923/*
924 * numeric hostname
925 */
926static int
927explore_numeric(const struct addrinfo *pai, const char *hostname,
928 const char *servname, struct addrinfo **res, const char *canonname)
929{
930 const struct afd *afd;
931 struct addrinfo *cur;
932 struct addrinfo sentinel;
933 int error;
934 char pton[PTON_MAX];
935
936 assert(pai != NULL);
937 /* hostname may be NULL */
938 /* servname may be NULL */
939 assert(res != NULL);
940
941 *res = NULL;
942 sentinel.ai_next = NULL;
943 cur = &sentinel;
944
945 /*
946 * if the servname does not match socktype/protocol, ignore it.
947 */
948 if (get_portmatch(pai, servname) != 0)
949 return 0;
950
951 afd = find_afd(pai->ai_family);
952 if (afd == NULL)
953 return 0;
954
955 switch (afd->a_af) {
956#if 0 /*X/Open spec*/
957 case AF_INET:
958 if (inet_aton(hostname, (struct in_addr *)pton) == 1) {
959 if (pai->ai_family == afd->a_af ||
960 pai->ai_family == PF_UNSPEC /*?*/) {
961 GET_AI(cur->ai_next, afd, pton);
962 GET_PORT(cur->ai_next, servname);
963 if ((pai->ai_flags & AI_CANONNAME)) {
964 /*
965 * Set the numeric address itself as
966 * the canonical name, based on a
967 * clarification in rfc2553bis-03.
968 */
969 GET_CANONNAME(cur->ai_next, canonname);
970 }
971 while (cur && cur->ai_next)
972 cur = cur->ai_next;
973 } else
974 ERR(EAI_FAMILY); /*xxx*/
975 }
976 break;
977#endif
978 default:
979 if (inet_pton(afd->a_af, hostname, pton) == 1) {
980 if (pai->ai_family == afd->a_af ||
981 pai->ai_family == PF_UNSPEC /*?*/) {
982 GET_AI(cur->ai_next, afd, pton);
983 GET_PORT(cur->ai_next, servname);
984 if ((pai->ai_flags & AI_CANONNAME)) {
985 /*
986 * Set the numeric address itself as
987 * the canonical name, based on a
988 * clarification in rfc2553bis-03.
989 */
990 GET_CANONNAME(cur->ai_next, canonname);
991 }
992 while (cur->ai_next)
993 cur = cur->ai_next;
994 } else
995 ERR(EAI_FAMILY); /*xxx*/
996 }
997 break;
998 }
999
1000 *res = sentinel.ai_next;
1001 return 0;
1002
1003free:
1004bad:
1005 if (sentinel.ai_next)
1006 freeaddrinfo(sentinel.ai_next);
1007 return error;
1008}
1009
1010/*
1011 * numeric hostname with scope
1012 */
1013static int
1014explore_numeric_scope(const struct addrinfo *pai, const char *hostname,
1015 const char *servname, struct addrinfo **res)
1016{
1017#if !defined(SCOPE_DELIMITER) || !defined(INET6)
1018 return explore_numeric(pai, hostname, servname, res, hostname);
1019#else
1020 const struct afd *afd;
1021 struct addrinfo *cur;
1022 int error;
1023 char *cp, *hostname2 = NULL, *scope, *addr;
1024 struct sockaddr_in6 *sin6;
1025
1026 assert(pai != NULL);
1027 /* hostname may be NULL */
1028 /* servname may be NULL */
1029 assert(res != NULL);
1030
1031 /*
1032 * if the servname does not match socktype/protocol, ignore it.
1033 */
1034 if (get_portmatch(pai, servname) != 0)
1035 return 0;
1036
1037 afd = find_afd(pai->ai_family);
1038 if (afd == NULL)
1039 return 0;
1040
1041 if (!afd->a_scoped)
1042 return explore_numeric(pai, hostname, servname, res, hostname);
1043
1044 cp = strchr(hostname, SCOPE_DELIMITER);
1045 if (cp == NULL)
1046 return explore_numeric(pai, hostname, servname, res, hostname);
1047
1048 /*
1049 * Handle special case of <scoped_address><delimiter><scope id>
1050 */
1051 hostname2 = strdup(hostname);
1052 if (hostname2 == NULL)
1053 return EAI_MEMORY;
1054 /* terminate at the delimiter */
1055 hostname2[cp - hostname] = '\0';
1056 addr = hostname2;
1057 scope = cp + 1;
1058
1059 error = explore_numeric(pai, addr, servname, res, hostname);
1060 if (error == 0) {
1061 u_int32_t scopeid;
1062
1063 for (cur = *res; cur; cur = cur->ai_next) {
1064 if (cur->ai_family != AF_INET6)
1065 continue;
1066 sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr;
1067 if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) {
1068 free(hostname2);
1069 return(EAI_NODATA); /* XXX: is return OK? */
1070 }
1071 sin6->sin6_scope_id = scopeid;
1072 }
1073 }
1074
1075 free(hostname2);
1076
1077 return error;
1078#endif
1079}
1080
1081static int
1082get_canonname(const struct addrinfo *pai, struct addrinfo *ai, const char *str)
1083{
1084
1085 assert(pai != NULL);
1086 assert(ai != NULL);
1087 assert(str != NULL);
1088
1089 if ((pai->ai_flags & AI_CANONNAME) != 0) {
1090 ai->ai_canonname = strdup(str);
1091 if (ai->ai_canonname == NULL)
1092 return EAI_MEMORY;
1093 }
1094 return 0;
1095}
1096
1097static struct addrinfo *
1098get_ai(const struct addrinfo *pai, const struct afd *afd, const char *addr)
1099{
1100 char *p;
1101 struct addrinfo *ai;
1102
1103 assert(pai != NULL);
1104 assert(afd != NULL);
1105 assert(addr != NULL);
1106
1107 ai = (struct addrinfo *)malloc(sizeof(struct addrinfo)
1108 + (afd->a_socklen));
1109 if (ai == NULL)
1110 return NULL;
1111
1112 memcpy(ai, pai, sizeof(struct addrinfo));
1113 ai->ai_addr = (struct sockaddr *)(void *)(ai + 1);
1114 memset(ai->ai_addr, 0, (size_t)afd->a_socklen);
1115
1116#ifdef HAVE_SA_LEN
1117 ai->ai_addr->sa_len = afd->a_socklen;
1118#endif
1119
1120 ai->ai_addrlen = afd->a_socklen;
1121#if defined (__alpha__) || (defined(__i386__) && defined(_LP64)) || defined(__sparc64__)
1122 ai->__ai_pad0 = 0;
1123#endif
1124 ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
1125 p = (char *)(void *)(ai->ai_addr);
1126 memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen);
1127 return ai;
1128}
1129
1130static int
1131get_portmatch(const struct addrinfo *ai, const char *servname)
1132{
1133
1134 assert(ai != NULL);
1135 /* servname may be NULL */
1136
1137 return get_port(ai, servname, 1);
1138}
1139
1140static int
1141get_port(const struct addrinfo *ai, const char *servname, int matchonly)
1142{
1143 const char *proto;
1144 struct servent *sp;
1145 int port;
1146 int allownumeric;
1147
1148 assert(ai != NULL);
1149 /* servname may be NULL */
1150
1151 if (servname == NULL)
1152 return 0;
1153 switch (ai->ai_family) {
1154 case AF_INET:
1155#ifdef AF_INET6
1156 case AF_INET6:
1157#endif
1158 break;
1159 default:
1160 return 0;
1161 }
1162
1163 switch (ai->ai_socktype) {
1164 case SOCK_RAW:
1165 return EAI_SERVICE;
1166 case SOCK_DGRAM:
1167 case SOCK_STREAM:
1168 allownumeric = 1;
1169 break;
1170 case ANY:
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001171#if 1 /* ANDROID-SPECIFIC CHANGE TO MATCH GLIBC */
David 'Digit' Turner5e563702009-05-05 15:50:24 +02001172 allownumeric = 1;
1173#else
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001174 allownumeric = 0;
David 'Digit' Turner5e563702009-05-05 15:50:24 +02001175#endif
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001176 break;
1177 default:
1178 return EAI_SOCKTYPE;
1179 }
1180
1181 port = str2number(servname);
1182 if (port >= 0) {
1183 if (!allownumeric)
1184 return EAI_SERVICE;
1185 if (port < 0 || port > 65535)
1186 return EAI_SERVICE;
1187 port = htons(port);
1188 } else {
1189 if (ai->ai_flags & AI_NUMERICSERV)
1190 return EAI_NONAME;
1191
1192 switch (ai->ai_socktype) {
1193 case SOCK_DGRAM:
1194 proto = "udp";
1195 break;
1196 case SOCK_STREAM:
1197 proto = "tcp";
1198 break;
1199 default:
1200 proto = NULL;
1201 break;
1202 }
1203
1204 if ((sp = getservbyname(servname, proto)) == NULL)
1205 return EAI_SERVICE;
1206 port = sp->s_port;
1207 }
1208
1209 if (!matchonly) {
1210 switch (ai->ai_family) {
1211 case AF_INET:
1212 ((struct sockaddr_in *)(void *)
1213 ai->ai_addr)->sin_port = port;
1214 break;
1215#ifdef INET6
1216 case AF_INET6:
1217 ((struct sockaddr_in6 *)(void *)
1218 ai->ai_addr)->sin6_port = port;
1219 break;
1220#endif
1221 }
1222 }
1223
1224 return 0;
1225}
1226
1227static const struct afd *
1228find_afd(int af)
1229{
1230 const struct afd *afd;
1231
1232 if (af == PF_UNSPEC)
1233 return NULL;
1234 for (afd = afdl; afd->a_af; afd++) {
1235 if (afd->a_af == af)
1236 return afd;
1237 }
1238 return NULL;
1239}
1240
1241#ifdef INET6
1242/* convert a string to a scope identifier. XXX: IPv6 specific */
1243static int
1244ip6_str2scopeid(char *scope, struct sockaddr_in6 *sin6, u_int32_t *scopeid)
1245{
1246 u_long lscopeid;
1247 struct in6_addr *a6;
1248 char *ep;
1249
1250 assert(scope != NULL);
1251 assert(sin6 != NULL);
1252 assert(scopeid != NULL);
1253
1254 a6 = &sin6->sin6_addr;
1255
1256 /* empty scopeid portion is invalid */
1257 if (*scope == '\0')
1258 return -1;
1259
1260 if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
1261 /*
1262 * We currently assume a one-to-one mapping between links
1263 * and interfaces, so we simply use interface indices for
1264 * like-local scopes.
1265 */
1266 *scopeid = if_nametoindex(scope);
1267 if (*scopeid == 0)
1268 goto trynumeric;
1269 return 0;
1270 }
1271
1272 /* still unclear about literal, allow numeric only - placeholder */
1273 if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6))
1274 goto trynumeric;
1275 if (IN6_IS_ADDR_MC_ORGLOCAL(a6))
1276 goto trynumeric;
1277 else
1278 goto trynumeric; /* global */
1279
1280 /* try to convert to a numeric id as a last resort */
1281 trynumeric:
1282 errno = 0;
1283 lscopeid = strtoul(scope, &ep, 10);
1284 *scopeid = (u_int32_t)(lscopeid & 0xffffffffUL);
1285 if (errno == 0 && ep && *ep == '\0' && *scopeid == lscopeid)
1286 return 0;
1287 else
1288 return -1;
1289}
1290#endif
1291
1292/* code duplicate with gethnamaddr.c */
1293
1294static const char AskedForGot[] =
1295 "gethostby*.getanswer: asked for \"%s\", got \"%s\"";
1296
1297static struct addrinfo *
1298getanswer(const querybuf *answer, int anslen, const char *qname, int qtype,
1299 const struct addrinfo *pai)
1300{
1301 struct addrinfo sentinel, *cur;
1302 struct addrinfo ai;
1303 const struct afd *afd;
1304 char *canonname;
1305 const HEADER *hp;
1306 const u_char *cp;
1307 int n;
1308 const u_char *eom;
1309 char *bp, *ep;
1310 int type, class, ancount, qdcount;
1311 int haveanswer, had_error;
1312 char tbuf[MAXDNAME];
1313 int (*name_ok) (const char *);
1314 char hostbuf[8*1024];
1315
1316 assert(answer != NULL);
1317 assert(qname != NULL);
1318 assert(pai != NULL);
1319
1320 memset(&sentinel, 0, sizeof(sentinel));
1321 cur = &sentinel;
1322
1323 canonname = NULL;
1324 eom = answer->buf + anslen;
1325 switch (qtype) {
1326 case T_A:
1327 case T_AAAA:
1328 case T_ANY: /*use T_ANY only for T_A/T_AAAA lookup*/
1329 name_ok = res_hnok;
1330 break;
1331 default:
1332 return NULL; /* XXX should be abort(); */
1333 }
1334 /*
1335 * find first satisfactory answer
1336 */
1337 hp = &answer->hdr;
1338 ancount = ntohs(hp->ancount);
1339 qdcount = ntohs(hp->qdcount);
1340 bp = hostbuf;
1341 ep = hostbuf + sizeof hostbuf;
1342 cp = answer->buf + HFIXEDSZ;
1343 if (qdcount != 1) {
1344 h_errno = NO_RECOVERY;
1345 return (NULL);
1346 }
1347 n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1348 if ((n < 0) || !(*name_ok)(bp)) {
1349 h_errno = NO_RECOVERY;
1350 return (NULL);
1351 }
1352 cp += n + QFIXEDSZ;
1353 if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
1354 /* res_send() has already verified that the query name is the
1355 * same as the one we sent; this just gets the expanded name
1356 * (i.e., with the succeeding search-domain tacked on).
1357 */
1358 n = strlen(bp) + 1; /* for the \0 */
1359 if (n >= MAXHOSTNAMELEN) {
1360 h_errno = NO_RECOVERY;
1361 return (NULL);
1362 }
1363 canonname = bp;
1364 bp += n;
1365 /* The qname can be abbreviated, but h_name is now absolute. */
1366 qname = canonname;
1367 }
1368 haveanswer = 0;
1369 had_error = 0;
1370 while (ancount-- > 0 && cp < eom && !had_error) {
1371 n = dn_expand(answer->buf, eom, cp, bp, ep - bp);
1372 if ((n < 0) || !(*name_ok)(bp)) {
1373 had_error++;
1374 continue;
1375 }
1376 cp += n; /* name */
1377 type = _getshort(cp);
Lorenzo Colittib82532d2011-09-28 19:28:32 -07001378 cp += INT16SZ; /* type */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001379 class = _getshort(cp);
Lorenzo Colittib82532d2011-09-28 19:28:32 -07001380 cp += INT16SZ + INT32SZ; /* class, TTL */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001381 n = _getshort(cp);
1382 cp += INT16SZ; /* len */
1383 if (class != C_IN) {
1384 /* XXX - debug? syslog? */
1385 cp += n;
1386 continue; /* XXX - had_error++ ? */
1387 }
1388 if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) &&
1389 type == T_CNAME) {
1390 n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf);
1391 if ((n < 0) || !(*name_ok)(tbuf)) {
1392 had_error++;
1393 continue;
1394 }
1395 cp += n;
1396 /* Get canonical name. */
1397 n = strlen(tbuf) + 1; /* for the \0 */
1398 if (n > ep - bp || n >= MAXHOSTNAMELEN) {
1399 had_error++;
1400 continue;
1401 }
1402 strlcpy(bp, tbuf, (size_t)(ep - bp));
1403 canonname = bp;
1404 bp += n;
1405 continue;
1406 }
1407 if (qtype == T_ANY) {
1408 if (!(type == T_A || type == T_AAAA)) {
1409 cp += n;
1410 continue;
1411 }
1412 } else if (type != qtype) {
1413 if (type != T_KEY && type != T_SIG)
1414 syslog(LOG_NOTICE|LOG_AUTH,
1415 "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"",
1416 qname, p_class(C_IN), p_type(qtype),
1417 p_type(type));
1418 cp += n;
1419 continue; /* XXX - had_error++ ? */
1420 }
1421 switch (type) {
1422 case T_A:
1423 case T_AAAA:
1424 if (strcasecmp(canonname, bp) != 0) {
1425 syslog(LOG_NOTICE|LOG_AUTH,
1426 AskedForGot, canonname, bp);
1427 cp += n;
1428 continue; /* XXX - had_error++ ? */
1429 }
1430 if (type == T_A && n != INADDRSZ) {
1431 cp += n;
1432 continue;
1433 }
1434 if (type == T_AAAA && n != IN6ADDRSZ) {
1435 cp += n;
1436 continue;
1437 }
1438 if (type == T_AAAA) {
1439 struct in6_addr in6;
1440 memcpy(&in6, cp, IN6ADDRSZ);
1441 if (IN6_IS_ADDR_V4MAPPED(&in6)) {
1442 cp += n;
1443 continue;
1444 }
1445 }
1446 if (!haveanswer) {
1447 int nn;
1448
1449 canonname = bp;
1450 nn = strlen(bp) + 1; /* for the \0 */
1451 bp += nn;
1452 }
1453
1454 /* don't overwrite pai */
1455 ai = *pai;
1456 ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
1457 afd = find_afd(ai.ai_family);
1458 if (afd == NULL) {
1459 cp += n;
1460 continue;
1461 }
1462 cur->ai_next = get_ai(&ai, afd, (const char *)cp);
1463 if (cur->ai_next == NULL)
1464 had_error++;
1465 while (cur && cur->ai_next)
1466 cur = cur->ai_next;
1467 cp += n;
1468 break;
1469 default:
1470 abort();
1471 }
1472 if (!had_error)
1473 haveanswer++;
1474 }
1475 if (haveanswer) {
1476 if (!canonname)
1477 (void)get_canonname(pai, sentinel.ai_next, qname);
1478 else
1479 (void)get_canonname(pai, sentinel.ai_next, canonname);
1480 h_errno = NETDB_SUCCESS;
1481 return sentinel.ai_next;
1482 }
1483
1484 h_errno = NO_RECOVERY;
1485 return NULL;
1486}
1487
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001488struct addrinfo_sort_elem {
1489 struct addrinfo *ai;
1490 int has_src_addr;
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001491 sockaddr_union src_addr;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001492 int original_order;
1493};
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001494
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001495/*ARGSUSED*/
1496static int
1497_get_scope(const struct sockaddr *addr)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001498{
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001499 if (addr->sa_family == AF_INET6) {
1500 const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)addr;
1501 if (IN6_IS_ADDR_MULTICAST(&addr6->sin6_addr)) {
1502 return IPV6_ADDR_MC_SCOPE(&addr6->sin6_addr);
1503 } else if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr) ||
1504 IN6_IS_ADDR_LINKLOCAL(&addr6->sin6_addr)) {
1505 /*
1506 * RFC 4291 section 2.5.3 says loopback is to be treated as having
1507 * link-local scope.
1508 */
1509 return IPV6_ADDR_SCOPE_LINKLOCAL;
1510 } else if (IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr)) {
1511 return IPV6_ADDR_SCOPE_SITELOCAL;
1512 } else {
1513 return IPV6_ADDR_SCOPE_GLOBAL;
1514 }
1515 } else if (addr->sa_family == AF_INET) {
1516 const struct sockaddr_in *addr4 = (const struct sockaddr_in *)addr;
1517 unsigned long int na = ntohl(addr4->sin_addr.s_addr);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001518
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001519 if (IN_LOOPBACK(na) || /* 127.0.0.0/8 */
1520 (na & 0xffff0000) == 0xa9fe0000) { /* 169.254.0.0/16 */
1521 return IPV6_ADDR_SCOPE_LINKLOCAL;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001522 } else {
Steinar H. Gundersond1624ad2010-12-20 11:15:33 +01001523 /*
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001524 * RFC 6724 section 3.2. Other IPv4 addresses, including private addresses
1525 * and shared addresses (100.64.0.0/10), are assigned global scope.
Steinar H. Gundersond1624ad2010-12-20 11:15:33 +01001526 */
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001527 return IPV6_ADDR_SCOPE_GLOBAL;
1528 }
1529 } else {
1530 /*
1531 * This should never happen.
1532 * Return a scope with low priority as a last resort.
1533 */
1534 return IPV6_ADDR_SCOPE_NODELOCAL;
1535 }
1536}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001537
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001538/* These macros are modelled after the ones in <netinet/in6.h>. */
1539
1540/* RFC 4380, section 2.6 */
1541#define IN6_IS_ADDR_TEREDO(a) \
1542 ((*(const uint32_t *)(const void *)(&(a)->s6_addr[0]) == ntohl(0x20010000)))
1543
1544/* RFC 3056, section 2. */
1545#define IN6_IS_ADDR_6TO4(a) \
1546 (((a)->s6_addr[0] == 0x20) && ((a)->s6_addr[1] == 0x02))
1547
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001548/* 6bone testing address area (3ffe::/16), deprecated in RFC 3701. */
1549#define IN6_IS_ADDR_6BONE(a) \
1550 (((a)->s6_addr[0] == 0x3f) && ((a)->s6_addr[1] == 0xfe))
1551
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001552/*
1553 * Get the label for a given IPv4/IPv6 address.
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001554 * RFC 6724, section 2.1.
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001555 */
1556
1557/*ARGSUSED*/
1558static int
1559_get_label(const struct sockaddr *addr)
1560{
1561 if (addr->sa_family == AF_INET) {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001562 return 4;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001563 } else if (addr->sa_family == AF_INET6) {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001564 const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *) addr;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001565 if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr)) {
1566 return 0;
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001567 } else if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001568 return 4;
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001569 } else if (IN6_IS_ADDR_6TO4(&addr6->sin6_addr)) {
1570 return 2;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001571 } else if (IN6_IS_ADDR_TEREDO(&addr6->sin6_addr)) {
1572 return 5;
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001573 } else if (IN6_IS_ADDR_ULA(&addr6->sin6_addr)) {
1574 return 13;
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001575 } else if (IN6_IS_ADDR_V4COMPAT(&addr6->sin6_addr)) {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001576 return 3;
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001577 } else if (IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr)) {
1578 return 11;
1579 } else if (IN6_IS_ADDR_6BONE(&addr6->sin6_addr)) {
1580 return 12;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001581 } else {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001582 /* All other IPv6 addresses, including global unicast addresses. */
1583 return 1;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001584 }
1585 } else {
1586 /*
1587 * This should never happen.
1588 * Return a semi-random label as a last resort.
1589 */
1590 return 1;
1591 }
1592}
1593
1594/*
1595 * Get the precedence for a given IPv4/IPv6 address.
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001596 * RFC 6724, section 2.1.
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001597 */
1598
1599/*ARGSUSED*/
1600static int
1601_get_precedence(const struct sockaddr *addr)
1602{
1603 if (addr->sa_family == AF_INET) {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001604 return 35;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001605 } else if (addr->sa_family == AF_INET6) {
1606 const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)addr;
1607 if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr)) {
1608 return 50;
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001609 } else if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001610 return 35;
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001611 } else if (IN6_IS_ADDR_6TO4(&addr6->sin6_addr)) {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001612 return 30;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001613 } else if (IN6_IS_ADDR_TEREDO(&addr6->sin6_addr)) {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001614 return 5;
1615 } else if (IN6_IS_ADDR_ULA(&addr6->sin6_addr)) {
1616 return 3;
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001617 } else if (IN6_IS_ADDR_V4COMPAT(&addr6->sin6_addr) ||
Lorenzo Colittib82532d2011-09-28 19:28:32 -07001618 IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr) ||
1619 IN6_IS_ADDR_6BONE(&addr6->sin6_addr)) {
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001620 return 1;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001621 } else {
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001622 /* All other IPv6 addresses, including global unicast addresses. */
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001623 return 40;
1624 }
1625 } else {
Steinar H. Gunderson2e23e292010-12-20 11:48:07 +01001626 return 1;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001627 }
1628}
1629
1630/*
1631 * Find number of matching initial bits between the two addresses a1 and a2.
1632 */
1633
1634/*ARGSUSED*/
1635static int
1636_common_prefix_len(const struct in6_addr *a1, const struct in6_addr *a2)
1637{
1638 const char *p1 = (const char *)a1;
1639 const char *p2 = (const char *)a2;
1640 unsigned i;
1641
1642 for (i = 0; i < sizeof(*a1); ++i) {
1643 int x, j;
1644
1645 if (p1[i] == p2[i]) {
1646 continue;
1647 }
1648 x = p1[i] ^ p2[i];
1649 for (j = 0; j < CHAR_BIT; ++j) {
1650 if (x & (1 << (CHAR_BIT - 1))) {
1651 return i * CHAR_BIT + j;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001652 }
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001653 x <<= 1;
1654 }
1655 }
1656 return sizeof(*a1) * CHAR_BIT;
1657}
1658
1659/*
1660 * Compare two source/destination address pairs.
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001661 * RFC 6724, section 6.
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001662 */
1663
1664/*ARGSUSED*/
1665static int
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001666_rfc6724_compare(const void *ptr1, const void* ptr2)
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001667{
1668 const struct addrinfo_sort_elem *a1 = (const struct addrinfo_sort_elem *)ptr1;
1669 const struct addrinfo_sort_elem *a2 = (const struct addrinfo_sort_elem *)ptr2;
1670 int scope_src1, scope_dst1, scope_match1;
1671 int scope_src2, scope_dst2, scope_match2;
1672 int label_src1, label_dst1, label_match1;
1673 int label_src2, label_dst2, label_match2;
1674 int precedence1, precedence2;
1675 int prefixlen1, prefixlen2;
1676
1677 /* Rule 1: Avoid unusable destinations. */
1678 if (a1->has_src_addr != a2->has_src_addr) {
1679 return a2->has_src_addr - a1->has_src_addr;
1680 }
1681
1682 /* Rule 2: Prefer matching scope. */
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001683 scope_src1 = _get_scope(&a1->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001684 scope_dst1 = _get_scope(a1->ai->ai_addr);
1685 scope_match1 = (scope_src1 == scope_dst1);
1686
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001687 scope_src2 = _get_scope(&a2->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001688 scope_dst2 = _get_scope(a2->ai->ai_addr);
1689 scope_match2 = (scope_src2 == scope_dst2);
1690
1691 if (scope_match1 != scope_match2) {
1692 return scope_match2 - scope_match1;
1693 }
1694
1695 /*
1696 * Rule 3: Avoid deprecated addresses.
1697 * TODO(sesse): We don't currently have a good way of finding this.
1698 */
1699
1700 /*
1701 * Rule 4: Prefer home addresses.
1702 * TODO(sesse): We don't currently have a good way of finding this.
1703 */
1704
1705 /* Rule 5: Prefer matching label. */
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001706 label_src1 = _get_label(&a1->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001707 label_dst1 = _get_label(a1->ai->ai_addr);
1708 label_match1 = (label_src1 == label_dst1);
1709
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001710 label_src2 = _get_label(&a2->src_addr.generic);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001711 label_dst2 = _get_label(a2->ai->ai_addr);
1712 label_match2 = (label_src2 == label_dst2);
1713
1714 if (label_match1 != label_match2) {
1715 return label_match2 - label_match1;
1716 }
1717
1718 /* Rule 6: Prefer higher precedence. */
1719 precedence1 = _get_precedence(a1->ai->ai_addr);
1720 precedence2 = _get_precedence(a2->ai->ai_addr);
1721 if (precedence1 != precedence2) {
1722 return precedence2 - precedence1;
1723 }
1724
1725 /*
1726 * Rule 7: Prefer native transport.
1727 * TODO(sesse): We don't currently have a good way of finding this.
1728 */
1729
1730 /* Rule 8: Prefer smaller scope. */
1731 if (scope_dst1 != scope_dst2) {
1732 return scope_dst1 - scope_dst2;
1733 }
1734
1735 /*
1736 * Rule 9: Use longest matching prefix.
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001737 * We implement this for IPv6 only, as the rules in RFC 6724 don't seem
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001738 * to work very well directly applied to IPv4. (glibc uses information from
1739 * the routing table for a custom IPv4 implementation here.)
1740 */
1741 if (a1->has_src_addr && a1->ai->ai_addr->sa_family == AF_INET6 &&
1742 a2->has_src_addr && a2->ai->ai_addr->sa_family == AF_INET6) {
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001743 const struct sockaddr_in6 *a1_src = &a1->src_addr.in6;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001744 const struct sockaddr_in6 *a1_dst = (const struct sockaddr_in6 *)a1->ai->ai_addr;
David 'Digit' Turner50ace4f2010-06-16 16:36:41 -07001745 const struct sockaddr_in6 *a2_src = &a2->src_addr.in6;
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001746 const struct sockaddr_in6 *a2_dst = (const struct sockaddr_in6 *)a2->ai->ai_addr;
1747 prefixlen1 = _common_prefix_len(&a1_src->sin6_addr, &a1_dst->sin6_addr);
Kenny Root7e0bfb52010-03-24 18:06:20 -07001748 prefixlen2 = _common_prefix_len(&a2_src->sin6_addr, &a2_dst->sin6_addr);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001749 if (prefixlen1 != prefixlen2) {
1750 return prefixlen2 - prefixlen1;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001751 }
1752 }
1753
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001754 /*
1755 * Rule 10: Leave the order unchanged.
1756 * We need this since qsort() is not necessarily stable.
1757 */
1758 return a1->original_order - a2->original_order;
1759}
1760
1761/*
1762 * Find the source address that will be used if trying to connect to the given
1763 * address. src_addr must be large enough to hold a struct sockaddr_in6.
1764 *
1765 * Returns 1 if a source address was found, 0 if the address is unreachable,
Erik Kline01e37c92015-06-25 14:27:34 +09001766 * 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 +01001767 * undefined.
1768 */
1769
1770/*ARGSUSED*/
1771static int
Erik Kline01e37c92015-06-25 14:27:34 +09001772_find_src_addr(const struct sockaddr *addr, struct sockaddr *src_addr, unsigned mark, uid_t uid)
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001773{
1774 int sock;
1775 int ret;
1776 socklen_t len;
1777
1778 switch (addr->sa_family) {
1779 case AF_INET:
1780 len = sizeof(struct sockaddr_in);
1781 break;
1782 case AF_INET6:
1783 len = sizeof(struct sockaddr_in6);
1784 break;
1785 default:
1786 /* No known usable source address for non-INET families. */
1787 return 0;
1788 }
1789
Nick Kralevich1781ed72014-06-29 20:46:17 -07001790 sock = socket(addr->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001791 if (sock == -1) {
1792 if (errno == EAFNOSUPPORT) {
1793 return 0;
1794 } else {
1795 return -1;
1796 }
1797 }
Erik Kline7bbb1812016-03-04 17:16:55 +09001798 if (mark != MARK_UNSET && setsockopt(sock, SOL_SOCKET, SO_MARK, &mark, sizeof(mark)) < 0) {
1799 close(sock);
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001800 return 0;
Erik Kline7bbb1812016-03-04 17:16:55 +09001801 }
1802 if (uid > 0 && uid != NET_CONTEXT_INVALID_UID && fchown(sock, uid, (gid_t)-1) < 0) {
1803 close(sock);
Erik Kline01e37c92015-06-25 14:27:34 +09001804 return 0;
Erik Kline7bbb1812016-03-04 17:16:55 +09001805 }
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001806 do {
Paul Jensen31ad0372014-05-29 16:28:30 -04001807 ret = __connect(sock, addr, len);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001808 } while (ret == -1 && errno == EINTR);
1809
1810 if (ret == -1) {
1811 close(sock);
1812 return 0;
1813 }
1814
Erik Kline01e37c92015-06-25 14:27:34 +09001815 if (src_addr && getsockname(sock, src_addr, &len) == -1) {
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001816 close(sock);
1817 return -1;
1818 }
1819 close(sock);
1820 return 1;
1821}
1822
1823/*
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001824 * Sort the linked list starting at sentinel->ai_next in RFC6724 order.
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001825 * Will leave the list unchanged if an error occurs.
1826 */
1827
1828/*ARGSUSED*/
1829static void
Erik Kline01e37c92015-06-25 14:27:34 +09001830_rfc6724_sort(struct addrinfo *list_sentinel, unsigned mark, uid_t uid)
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001831{
1832 struct addrinfo *cur;
1833 int nelem = 0, i;
1834 struct addrinfo_sort_elem *elems;
1835
1836 cur = list_sentinel->ai_next;
1837 while (cur) {
1838 ++nelem;
1839 cur = cur->ai_next;
1840 }
1841
1842 elems = (struct addrinfo_sort_elem *)malloc(nelem * sizeof(struct addrinfo_sort_elem));
1843 if (elems == NULL) {
1844 goto error;
1845 }
1846
1847 /*
1848 * Convert the linked list to an array that also contains the candidate
1849 * source address for each destination address.
1850 */
1851 for (i = 0, cur = list_sentinel->ai_next; i < nelem; ++i, cur = cur->ai_next) {
1852 int has_src_addr;
1853 assert(cur != NULL);
1854 elems[i].ai = cur;
1855 elems[i].original_order = i;
1856
Erik Kline01e37c92015-06-25 14:27:34 +09001857 has_src_addr = _find_src_addr(cur->ai_addr, &elems[i].src_addr.generic, mark, uid);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001858 if (has_src_addr == -1) {
1859 goto error;
1860 }
1861 elems[i].has_src_addr = has_src_addr;
1862 }
1863
1864 /* Sort the addresses, and rearrange the linked list so it matches the sorted order. */
Lorenzo Colitti378b0e12013-03-30 12:24:19 +09001865 qsort((void *)elems, nelem, sizeof(struct addrinfo_sort_elem), _rfc6724_compare);
Steinar H. Gunderson9ab75d42010-02-11 15:44:55 +01001866
1867 list_sentinel->ai_next = elems[0].ai;
1868 for (i = 0; i < nelem - 1; ++i) {
1869 elems[i].ai->ai_next = elems[i + 1].ai;
1870 }
1871 elems[nelem - 1].ai->ai_next = NULL;
1872
1873error:
1874 free(elems);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001875}
1876
1877/*ARGSUSED*/
1878static int
1879_dns_getaddrinfo(void *rv, void *cb_data, va_list ap)
1880{
1881 struct addrinfo *ai;
1882 querybuf *buf, *buf2;
1883 const char *name;
1884 const struct addrinfo *pai;
1885 struct addrinfo sentinel, *cur;
1886 struct res_target q, q2;
1887 res_state res;
Erik Kline01e37c92015-06-25 14:27:34 +09001888 const struct android_net_context *netcontext;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001889
1890 name = va_arg(ap, char *);
1891 pai = va_arg(ap, const struct addrinfo *);
Erik Kline01e37c92015-06-25 14:27:34 +09001892 netcontext = va_arg(ap, const struct android_net_context *);
David 'Digit' Turner5e563702009-05-05 15:50:24 +02001893 //fprintf(stderr, "_dns_getaddrinfo() name = '%s'\n", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001894
1895 memset(&q, 0, sizeof(q));
1896 memset(&q2, 0, sizeof(q2));
1897 memset(&sentinel, 0, sizeof(sentinel));
1898 cur = &sentinel;
1899
1900 buf = malloc(sizeof(*buf));
1901 if (buf == NULL) {
1902 h_errno = NETDB_INTERNAL;
1903 return NS_NOTFOUND;
1904 }
1905 buf2 = malloc(sizeof(*buf2));
1906 if (buf2 == NULL) {
1907 free(buf);
1908 h_errno = NETDB_INTERNAL;
1909 return NS_NOTFOUND;
1910 }
1911
1912 switch (pai->ai_family) {
1913 case AF_UNSPEC:
1914 /* prefer IPv6 */
1915 q.name = name;
1916 q.qclass = C_IN;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001917 q.answer = buf->buf;
1918 q.anslen = sizeof(buf->buf);
Lorenzo Colittiba96e302011-01-14 12:26:05 -08001919 int query_ipv6 = 1, query_ipv4 = 1;
1920 if (pai->ai_flags & AI_ADDRCONFIG) {
Erik Kline01e37c92015-06-25 14:27:34 +09001921 query_ipv6 = _have_ipv6(netcontext->app_mark, netcontext->uid);
1922 query_ipv4 = _have_ipv4(netcontext->app_mark, netcontext->uid);
Lorenzo Colittiba96e302011-01-14 12:26:05 -08001923 }
1924 if (query_ipv6) {
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -07001925 q.qtype = T_AAAA;
Lorenzo Colittiba96e302011-01-14 12:26:05 -08001926 if (query_ipv4) {
1927 q.next = &q2;
1928 q2.name = name;
1929 q2.qclass = C_IN;
1930 q2.qtype = T_A;
1931 q2.answer = buf2->buf;
1932 q2.anslen = sizeof(buf2->buf);
1933 }
1934 } else if (query_ipv4) {
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -07001935 q.qtype = T_A;
Lorenzo Colittiba96e302011-01-14 12:26:05 -08001936 } else {
1937 free(buf);
1938 free(buf2);
1939 return NS_NOTFOUND;
Lorenzo Colitti3d8f4ad2009-08-03 22:36:31 -07001940 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001941 break;
1942 case AF_INET:
1943 q.name = name;
1944 q.qclass = C_IN;
1945 q.qtype = T_A;
1946 q.answer = buf->buf;
1947 q.anslen = sizeof(buf->buf);
1948 break;
1949 case AF_INET6:
1950 q.name = name;
1951 q.qclass = C_IN;
1952 q.qtype = T_AAAA;
1953 q.answer = buf->buf;
1954 q.anslen = sizeof(buf->buf);
1955 break;
1956 default:
1957 free(buf);
1958 free(buf2);
1959 return NS_UNAVAIL;
1960 }
1961
1962 res = __res_get_state();
1963 if (res == NULL) {
1964 free(buf);
1965 free(buf2);
1966 return NS_NOTFOUND;
1967 }
1968
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001969 /* this just sets our netid val in the thread private data so we don't have to
Mattias Falkc63e5902011-08-23 14:34:14 +02001970 * modify the api's all the way down to res_send.c's res_nsend. We could
1971 * fully populate the thread private data here, but if we get down there
1972 * and have a cache hit that would be wasted, so we do the rest there on miss
1973 */
Erik Kline01e37c92015-06-25 14:27:34 +09001974 res_setnetid(res, netcontext->dns_netid);
1975 res_setmark(res, netcontext->dns_mark);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001976 if (res_searchN(name, &q, res) < 0) {
1977 __res_put_state(res);
1978 free(buf);
1979 free(buf2);
1980 return NS_NOTFOUND;
1981 }
1982 ai = getanswer(buf, q.n, q.name, q.qtype, pai);
1983 if (ai) {
1984 cur->ai_next = ai;
1985 while (cur && cur->ai_next)
1986 cur = cur->ai_next;
1987 }
1988 if (q.next) {
1989 ai = getanswer(buf2, q2.n, q2.name, q2.qtype, pai);
1990 if (ai)
1991 cur->ai_next = ai;
1992 }
1993 free(buf);
1994 free(buf2);
1995 if (sentinel.ai_next == NULL) {
1996 __res_put_state(res);
1997 switch (h_errno) {
1998 case HOST_NOT_FOUND:
1999 return NS_NOTFOUND;
2000 case TRY_AGAIN:
2001 return NS_TRYAGAIN;
2002 default:
2003 return NS_UNAVAIL;
2004 }
2005 }
2006
Erik Kline01e37c92015-06-25 14:27:34 +09002007 _rfc6724_sort(&sentinel, netcontext->app_mark, netcontext->uid);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002008
2009 __res_put_state(res);
2010
2011 *((struct addrinfo **)rv) = sentinel.ai_next;
2012 return NS_SUCCESS;
2013}
2014
2015static void
2016_sethtent(FILE **hostf)
2017{
2018
2019 if (!*hostf)
Elliott Hughesc674edb2014-08-26 15:56:54 -07002020 *hostf = fopen(_PATH_HOSTS, "re");
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002021 else
2022 rewind(*hostf);
2023}
2024
2025static void
2026_endhtent(FILE **hostf)
2027{
2028
2029 if (*hostf) {
2030 (void) fclose(*hostf);
2031 *hostf = NULL;
2032 }
2033}
2034
2035static struct addrinfo *
2036_gethtent(FILE **hostf, const char *name, const struct addrinfo *pai)
2037{
2038 char *p;
2039 char *cp, *tname, *cname;
2040 struct addrinfo hints, *res0, *res;
2041 int error;
2042 const char *addr;
2043 char hostbuf[8*1024];
2044
2045// fprintf(stderr, "_gethtent() name = '%s'\n", name);
2046 assert(name != NULL);
2047 assert(pai != NULL);
2048
Elliott Hughesc674edb2014-08-26 15:56:54 -07002049 if (!*hostf && !(*hostf = fopen(_PATH_HOSTS, "re")))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002050 return (NULL);
2051 again:
2052 if (!(p = fgets(hostbuf, sizeof hostbuf, *hostf)))
2053 return (NULL);
2054 if (*p == '#')
2055 goto again;
2056 if (!(cp = strpbrk(p, "#\n")))
2057 goto again;
2058 *cp = '\0';
2059 if (!(cp = strpbrk(p, " \t")))
2060 goto again;
2061 *cp++ = '\0';
2062 addr = p;
2063 /* if this is not something we're looking for, skip it. */
2064 cname = NULL;
2065 while (cp && *cp) {
2066 if (*cp == ' ' || *cp == '\t') {
2067 cp++;
2068 continue;
2069 }
2070 if (!cname)
2071 cname = cp;
2072 tname = cp;
2073 if ((cp = strpbrk(cp, " \t")) != NULL)
2074 *cp++ = '\0';
2075// fprintf(stderr, "\ttname = '%s'", tname);
2076 if (strcasecmp(name, tname) == 0)
2077 goto found;
2078 }
2079 goto again;
2080
2081found:
2082 hints = *pai;
2083 hints.ai_flags = AI_NUMERICHOST;
2084 error = getaddrinfo(addr, NULL, &hints, &res0);
2085 if (error)
2086 goto again;
2087 for (res = res0; res; res = res->ai_next) {
2088 /* cover it up */
2089 res->ai_flags = pai->ai_flags;
2090
2091 if (pai->ai_flags & AI_CANONNAME) {
2092 if (get_canonname(pai, res, cname) != 0) {
2093 freeaddrinfo(res0);
2094 goto again;
2095 }
2096 }
2097 }
2098 return res0;
2099}
2100
2101/*ARGSUSED*/
2102static int
2103_files_getaddrinfo(void *rv, void *cb_data, va_list ap)
2104{
2105 const char *name;
2106 const struct addrinfo *pai;
2107 struct addrinfo sentinel, *cur;
2108 struct addrinfo *p;
2109 FILE *hostf = NULL;
2110
2111 name = va_arg(ap, char *);
2112 pai = va_arg(ap, struct addrinfo *);
2113
2114// fprintf(stderr, "_files_getaddrinfo() name = '%s'\n", name);
2115 memset(&sentinel, 0, sizeof(sentinel));
2116 cur = &sentinel;
2117
2118 _sethtent(&hostf);
2119 while ((p = _gethtent(&hostf, name, pai)) != NULL) {
2120 cur->ai_next = p;
2121 while (cur && cur->ai_next)
2122 cur = cur->ai_next;
2123 }
2124 _endhtent(&hostf);
2125
2126 *((struct addrinfo **)rv) = sentinel.ai_next;
2127 if (sentinel.ai_next == NULL)
2128 return NS_NOTFOUND;
2129 return NS_SUCCESS;
2130}
2131
2132/* resolver logic */
2133
2134/*
2135 * Formulate a normal query, send, and await answer.
2136 * Returned answer is placed in supplied buffer "answer".
2137 * Perform preliminary check of answer, returning success only
2138 * if no error is indicated and the answer count is nonzero.
2139 * Return the size of the response on success, -1 on error.
2140 * Error number is left in h_errno.
2141 *
2142 * Caller must parse answer and determine whether it answers the question.
2143 */
2144static int
2145res_queryN(const char *name, /* domain name */ struct res_target *target,
2146 res_state res)
2147{
2148 u_char buf[MAXPACKET];
2149 HEADER *hp;
2150 int n;
2151 struct res_target *t;
2152 int rcode;
2153 int ancount;
2154
2155 assert(name != NULL);
2156 /* XXX: target may be NULL??? */
2157
2158 rcode = NOERROR;
2159 ancount = 0;
2160
2161 for (t = target; t; t = t->next) {
2162 int class, type;
2163 u_char *answer;
2164 int anslen;
2165
2166 hp = (HEADER *)(void *)t->answer;
2167 hp->rcode = NOERROR; /* default */
2168
2169 /* make it easier... */
2170 class = t->qclass;
2171 type = t->qtype;
2172 answer = t->answer;
2173 anslen = t->anslen;
2174#ifdef DEBUG
2175 if (res->options & RES_DEBUG)
2176 printf(";; res_nquery(%s, %d, %d)\n", name, class, type);
2177#endif
2178
2179 n = res_nmkquery(res, QUERY, name, class, type, NULL, 0, NULL,
2180 buf, sizeof(buf));
2181#ifdef RES_USE_EDNS0
2182 if (n > 0 && (res->options & RES_USE_EDNS0) != 0)
2183 n = res_nopt(res, n, buf, sizeof(buf), anslen);
2184#endif
2185 if (n <= 0) {
2186#ifdef DEBUG
2187 if (res->options & RES_DEBUG)
2188 printf(";; res_nquery: mkquery failed\n");
2189#endif
2190 h_errno = NO_RECOVERY;
2191 return n;
2192 }
2193 n = res_nsend(res, buf, n, answer, anslen);
2194#if 0
2195 if (n < 0) {
2196#ifdef DEBUG
2197 if (res->options & RES_DEBUG)
2198 printf(";; res_query: send error\n");
2199#endif
2200 h_errno = TRY_AGAIN;
2201 return n;
2202 }
2203#endif
2204
2205 if (n < 0 || hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
2206 rcode = hp->rcode; /* record most recent error */
2207#ifdef DEBUG
2208 if (res->options & RES_DEBUG)
2209 printf(";; rcode = %u, ancount=%u\n", hp->rcode,
2210 ntohs(hp->ancount));
2211#endif
2212 continue;
2213 }
2214
2215 ancount += ntohs(hp->ancount);
2216
2217 t->n = n;
2218 }
2219
2220 if (ancount == 0) {
2221 switch (rcode) {
2222 case NXDOMAIN:
2223 h_errno = HOST_NOT_FOUND;
2224 break;
2225 case SERVFAIL:
2226 h_errno = TRY_AGAIN;
2227 break;
2228 case NOERROR:
2229 h_errno = NO_DATA;
2230 break;
2231 case FORMERR:
2232 case NOTIMP:
2233 case REFUSED:
2234 default:
2235 h_errno = NO_RECOVERY;
2236 break;
2237 }
2238 return -1;
2239 }
2240 return ancount;
2241}
2242
2243/*
2244 * Formulate a normal query, send, and retrieve answer in supplied buffer.
2245 * Return the size of the response on success, -1 on error.
2246 * If enabled, implement search rules until answer or unrecoverable failure
2247 * is detected. Error code, if any, is left in h_errno.
2248 */
2249static int
2250res_searchN(const char *name, struct res_target *target, res_state res)
2251{
2252 const char *cp, * const *domain;
2253 HEADER *hp;
2254 u_int dots;
2255 int trailing_dot, ret, saved_herrno;
2256 int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
2257
2258 assert(name != NULL);
2259 assert(target != NULL);
2260
2261 hp = (HEADER *)(void *)target->answer; /*XXX*/
2262
2263 errno = 0;
2264 h_errno = HOST_NOT_FOUND; /* default, if we never query */
2265 dots = 0;
2266 for (cp = name; *cp; cp++)
2267 dots += (*cp == '.');
2268 trailing_dot = 0;
2269 if (cp > name && *--cp == '.')
2270 trailing_dot++;
2271
2272
David 'Digit' Turner5e563702009-05-05 15:50:24 +02002273 //fprintf(stderr, "res_searchN() name = '%s'\n", name);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002274
2275 /*
2276 * if there aren't any dots, it could be a user-level alias
2277 */
2278 if (!dots && (cp = __hostalias(name)) != NULL) {
2279 ret = res_queryN(cp, target, res);
2280 return ret;
2281 }
2282
2283 /*
2284 * If there are dots in the name already, let's just give it a try
2285 * 'as is'. The threshold can be set with the "ndots" option.
2286 */
2287 saved_herrno = -1;
2288 if (dots >= res->ndots) {
2289 ret = res_querydomainN(name, NULL, target, res);
2290 if (ret > 0)
2291 return (ret);
2292 saved_herrno = h_errno;
2293 tried_as_is++;
2294 }
2295
2296 /*
2297 * We do at least one level of search if
2298 * - there is no dot and RES_DEFNAME is set, or
2299 * - there is at least one dot, there is no trailing dot,
2300 * and RES_DNSRCH is set.
2301 */
2302 if ((!dots && (res->options & RES_DEFNAMES)) ||
2303 (dots && !trailing_dot && (res->options & RES_DNSRCH))) {
2304 int done = 0;
2305
Robert Greenwalte0805a92013-07-31 16:53:46 -07002306 /* Unfortunately we need to set stuff up before
2307 * the domain stuff is tried. Will have a better
2308 * fix after thread pools are used.
2309 */
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05002310 _resolv_populate_res_for_net(res);
Robert Greenwalte0805a92013-07-31 16:53:46 -07002311
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002312 for (domain = (const char * const *)res->dnsrch;
2313 *domain && !done;
2314 domain++) {
2315
2316 ret = res_querydomainN(name, *domain, target, res);
2317 if (ret > 0)
2318 return ret;
2319
2320 /*
2321 * If no server present, give up.
2322 * If name isn't found in this domain,
2323 * keep trying higher domains in the search list
2324 * (if that's enabled).
2325 * On a NO_DATA error, keep trying, otherwise
2326 * a wildcard entry of another type could keep us
2327 * from finding this entry higher in the domain.
2328 * If we get some other error (negative answer or
2329 * server failure), then stop searching up,
2330 * but try the input name below in case it's
2331 * fully-qualified.
2332 */
2333 if (errno == ECONNREFUSED) {
2334 h_errno = TRY_AGAIN;
2335 return -1;
2336 }
2337
2338 switch (h_errno) {
2339 case NO_DATA:
2340 got_nodata++;
2341 /* FALLTHROUGH */
2342 case HOST_NOT_FOUND:
2343 /* keep trying */
2344 break;
2345 case TRY_AGAIN:
2346 if (hp->rcode == SERVFAIL) {
2347 /* try next search element, if any */
2348 got_servfail++;
2349 break;
2350 }
2351 /* FALLTHROUGH */
2352 default:
2353 /* anything else implies that we're done */
2354 done++;
2355 }
2356 /*
2357 * if we got here for some reason other than DNSRCH,
2358 * we only wanted one iteration of the loop, so stop.
2359 */
2360 if (!(res->options & RES_DNSRCH))
Lorenzo Colittib82532d2011-09-28 19:28:32 -07002361 done++;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08002362 }
2363 }
2364
2365 /*
2366 * if we have not already tried the name "as is", do that now.
2367 * note that we do this regardless of how many dots were in the
2368 * name or whether it ends with a dot.
2369 */
2370 if (!tried_as_is) {
2371 ret = res_querydomainN(name, NULL, target, res);
2372 if (ret > 0)
2373 return ret;
2374 }
2375
2376 /*
2377 * if we got here, we didn't satisfy the search.
2378 * if we did an initial full query, return that query's h_errno
2379 * (note that we wouldn't be here if that query had succeeded).
2380 * else if we ever got a nodata, send that back as the reason.
2381 * else send back meaningless h_errno, that being the one from
2382 * the last DNSRCH we did.
2383 */
2384 if (saved_herrno != -1)
2385 h_errno = saved_herrno;
2386 else if (got_nodata)
2387 h_errno = NO_DATA;
2388 else if (got_servfail)
2389 h_errno = TRY_AGAIN;
2390 return -1;
2391}
2392
2393/*
2394 * Perform a call on res_query on the concatenation of name and domain,
2395 * removing a trailing dot from name if domain is NULL.
2396 */
2397static int
2398res_querydomainN(const char *name, const char *domain,
2399 struct res_target *target, res_state res)
2400{
2401 char nbuf[MAXDNAME];
2402 const char *longname = nbuf;
2403 size_t n, d;
2404
2405 assert(name != NULL);
2406 /* XXX: target may be NULL??? */
2407
2408#ifdef DEBUG
2409 if (res->options & RES_DEBUG)
2410 printf(";; res_querydomain(%s, %s)\n",
2411 name, domain?domain:"<Nil>");
2412#endif
2413 if (domain == NULL) {
2414 /*
2415 * Check for trailing '.';
2416 * copy without '.' if present.
2417 */
2418 n = strlen(name);
2419 if (n + 1 > sizeof(nbuf)) {
2420 h_errno = NO_RECOVERY;
2421 return -1;
2422 }
2423 if (n > 0 && name[--n] == '.') {
2424 strncpy(nbuf, name, n);
2425 nbuf[n] = '\0';
2426 } else
2427 longname = name;
2428 } else {
2429 n = strlen(name);
2430 d = strlen(domain);
2431 if (n + 1 + d + 1 > sizeof(nbuf)) {
2432 h_errno = NO_RECOVERY;
2433 return -1;
2434 }
2435 snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
2436 }
2437 return res_queryN(longname, target, res);
2438}