blob: 9a212038763603f21b5abd9e702e85a0e9d2417d [file] [log] [blame]
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001/* $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
Ken Chen5471dca2019-04-15 15:25:35 +080033#define LOG_TAG "resolv"
Bernie Innocenti3952ccc2019-03-03 19:39:53 +090034
Bernie Innocentie71a28a2019-05-29 00:42:35 +090035#include "getaddrinfo.h"
36
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090037#include <arpa/inet.h>
38#include <arpa/nameser.h>
39#include <assert.h>
40#include <ctype.h>
41#include <errno.h>
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090042#include <fcntl.h>
43#include <net/if.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090044#include <netdb.h>
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090045#include <netinet/in.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090046#include <stdbool.h>
47#include <stddef.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090048#include <stdlib.h>
49#include <string.h>
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090050#include <sys/param.h>
51#include <sys/socket.h>
52#include <sys/stat.h>
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090053#include <sys/un.h>
Bernie Innocentiac18b122018-10-01 23:10:18 +090054#include <unistd.h>
Bernie Innocentiafaacf72018-08-30 07:34:37 +090055
Luke Huang0a0870d2020-02-12 20:41:10 +080056#include <future>
57
chenbruceacb832c2019-02-20 19:45:50 +080058#include <android-base/logging.h>
59
Luke Huangf40df9c2020-04-21 08:51:48 +080060#include "Experiments.h"
Bernie Innocentiac18b122018-10-01 23:10:18 +090061#include "netd_resolv/resolv.h"
Bernie Innocenti10a90282020-01-23 23:28:00 +090062#include "res_comp.h"
63#include "res_debug.h"
Bernie Innocenti08487112019-10-11 21:14:13 +090064#include "res_init.h"
Bernie Innocentiac18b122018-10-01 23:10:18 +090065#include "resolv_cache.h"
66#include "resolv_private.h"
Luke Huang0a0870d2020-02-12 20:41:10 +080067#include "util.h"
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090068
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090069#define ANY 0
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090070
lifr94981782019-05-17 21:15:19 +080071using android::net::NetworkDnsEventReported;
72
Bernie Innocenti4e374b62018-12-12 00:43:02 +090073const char in_addrany[] = {0, 0, 0, 0};
74const char in_loopback[] = {127, 0, 0, 1};
75const char in6_addrany[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
76const char in6_loopback[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090077
Bernie Innocenti4e374b62018-12-12 00:43:02 +090078const struct afd {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090079 int a_af;
80 int a_addrlen;
81 int a_socklen;
82 int a_off;
83 const char* a_addrany;
84 const char* a_loopback;
85 int a_scoped;
86} afdl[] = {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090087 {PF_INET6, sizeof(struct in6_addr), sizeof(struct sockaddr_in6),
88 offsetof(struct sockaddr_in6, sin6_addr), in6_addrany, in6_loopback, 1},
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090089 {PF_INET, sizeof(struct in_addr), sizeof(struct sockaddr_in),
90 offsetof(struct sockaddr_in, sin_addr), in_addrany, in_loopback, 0},
91 {0, 0, 0, 0, NULL, NULL, 0},
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090092};
93
Bernie Innocentib0b32bc2019-02-20 18:21:24 +090094struct Explore {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090095 int e_af;
96 int e_socktype;
97 int e_protocol;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090098 int e_wild;
Bernie Innocentib0b32bc2019-02-20 18:21:24 +090099#define WILD_AF(ex) ((ex).e_wild & 0x01)
100#define WILD_SOCKTYPE(ex) ((ex).e_wild & 0x02)
101#define WILD_PROTOCOL(ex) ((ex).e_wild & 0x04)
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900102};
103
Bernie Innocentib0b32bc2019-02-20 18:21:24 +0900104const Explore explore_options[] = {
Ken Chene0d73c92018-11-07 01:20:48 +0800105 {PF_INET6, SOCK_DGRAM, IPPROTO_UDP, 0x07},
106 {PF_INET6, SOCK_STREAM, IPPROTO_TCP, 0x07},
107 {PF_INET6, SOCK_RAW, ANY, 0x05},
108 {PF_INET, SOCK_DGRAM, IPPROTO_UDP, 0x07},
109 {PF_INET, SOCK_STREAM, IPPROTO_TCP, 0x07},
110 {PF_INET, SOCK_RAW, ANY, 0x05},
111 {PF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, 0x07},
112 {PF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, 0x07},
113 {PF_UNSPEC, SOCK_RAW, ANY, 0x05},
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900114};
115
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900116#define PTON_MAX 16
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900117
118struct res_target {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900119 struct res_target* next;
Luke Huangc98fd802019-10-15 16:36:36 +0900120 const char* name; // domain name
121 int qclass, qtype; // class and type of query
122 std::vector<uint8_t> answer = std::vector<uint8_t>(MAXPACKET, 0); // buffer to put answer
123 int n = 0; // result length
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900124};
125
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900126static int str2number(const char*);
127static int explore_fqdn(const struct addrinfo*, const char*, const char*, struct addrinfo**,
lifr94981782019-05-17 21:15:19 +0800128 const struct android_net_context*, NetworkDnsEventReported* event);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900129static int explore_null(const struct addrinfo*, const char*, struct addrinfo**);
130static int explore_numeric(const struct addrinfo*, const char*, const char*, struct addrinfo**,
131 const char*);
132static int explore_numeric_scope(const struct addrinfo*, const char*, const char*,
133 struct addrinfo**);
134static int get_canonname(const struct addrinfo*, struct addrinfo*, const char*);
135static struct addrinfo* get_ai(const struct addrinfo*, const struct afd*, const char*);
136static int get_portmatch(const struct addrinfo*, const char*);
137static int get_port(const struct addrinfo*, const char*, int);
138static const struct afd* find_afd(int);
chenbrucec51f1212019-09-12 16:59:33 +0800139static int ip6_str2scopeid(const char*, struct sockaddr_in6*, uint32_t*);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900140
Luke Huangc98fd802019-10-15 16:36:36 +0900141static struct addrinfo* getanswer(const std::vector<uint8_t>&, int, const char*, int,
142 const struct addrinfo*, int* herrno);
Bernie Innocenti455c6232018-09-12 21:32:42 +0900143static int dns_getaddrinfo(const char* name, const addrinfo* pai,
lifr94981782019-05-17 21:15:19 +0800144 const android_net_context* netcontext, addrinfo** rv,
145 NetworkDnsEventReported* event);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900146static void _sethtent(FILE**);
147static void _endhtent(FILE**);
148static struct addrinfo* _gethtent(FILE**, const char*, const struct addrinfo*);
chenbrucefd837fa2019-10-29 18:35:36 +0800149static struct addrinfo* getCustomHosts(const size_t netid, const char*, const struct addrinfo*);
150static bool files_getaddrinfo(const size_t netid, const char* name, const addrinfo* pai,
151 addrinfo** res);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900152static int _find_src_addr(const struct sockaddr*, struct sockaddr*, unsigned, uid_t);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900153
Hungming Chen947aab02018-12-27 18:33:19 +0800154static int res_queryN(const char* name, res_target* target, res_state res, int* herrno);
155static int res_searchN(const char* name, res_target* target, res_state res, int* herrno);
Mike Yubfb1b342018-11-06 15:42:36 +0800156static int res_querydomainN(const char* name, const char* domain, res_target* target, res_state res,
Hungming Chen947aab02018-12-27 18:33:19 +0800157 int* herrno);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900158
Bernie Innocenti4e374b62018-12-12 00:43:02 +0900159const char* const ai_errlist[] = {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900160 "Success",
161 "Address family for hostname not supported", /* EAI_ADDRFAMILY */
162 "Temporary failure in name resolution", /* EAI_AGAIN */
163 "Invalid value for ai_flags", /* EAI_BADFLAGS */
164 "Non-recoverable failure in name resolution", /* EAI_FAIL */
165 "ai_family not supported", /* EAI_FAMILY */
166 "Memory allocation failure", /* EAI_MEMORY */
167 "No address associated with hostname", /* EAI_NODATA */
168 "hostname nor servname provided, or not known", /* EAI_NONAME */
169 "servname not supported for ai_socktype", /* EAI_SERVICE */
170 "ai_socktype not supported", /* EAI_SOCKTYPE */
171 "System error returned in errno", /* EAI_SYSTEM */
172 "Invalid value for hints", /* EAI_BADHINTS */
173 "Resolved protocol is unknown", /* EAI_PROTOCOL */
174 "Argument buffer overflow", /* EAI_OVERFLOW */
175 "Unknown error", /* EAI_MAX */
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900176};
177
178/* XXX macros that make external reference is BAD. */
179
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900180#define GET_AI(ai, afd, addr) \
181 do { \
182 /* external reference: pai, error, and label free */ \
183 (ai) = get_ai(pai, (afd), (addr)); \
184 if ((ai) == NULL) { \
185 error = EAI_MEMORY; \
186 goto free; \
187 } \
Bernie Innocenti9c575932018-09-07 21:10:25 +0900188 } while (0)
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900189
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900190#define GET_PORT(ai, serv) \
191 do { \
192 /* external reference: error and label free */ \
193 error = get_port((ai), (serv), 0); \
194 if (error != 0) goto free; \
Bernie Innocenti9c575932018-09-07 21:10:25 +0900195 } while (0)
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900196
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900197#define MATCH_FAMILY(x, y, w) \
Bernie Innocenti9c575932018-09-07 21:10:25 +0900198 ((x) == (y) || ((w) && ((x) == PF_UNSPEC || (y) == PF_UNSPEC)))
199#define MATCH(x, y, w) ((x) == (y) || ((w) && ((x) == ANY || (y) == ANY)))
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900200
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900201const char* gai_strerror(int ecode) {
202 if (ecode < 0 || ecode > EAI_MAX) ecode = EAI_MAX;
203 return ai_errlist[ecode];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900204}
205
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900206void freeaddrinfo(struct addrinfo* ai) {
Bernie Innocenti18a5ab52018-10-02 12:53:39 +0900207 while (ai) {
208 struct addrinfo* next = ai->ai_next;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900209 if (ai->ai_canonname) free(ai->ai_canonname);
Bernie Innocenti18a5ab52018-10-02 12:53:39 +0900210 // Also frees ai->ai_addr which points to extra space beyond addrinfo
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900211 free(ai);
212 ai = next;
Bernie Innocenti18a5ab52018-10-02 12:53:39 +0900213 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900214}
215
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900216static int str2number(const char* p) {
217 char* ep;
218 unsigned long v;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900219
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900220 assert(p != NULL);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900221
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900222 if (*p == '\0') return -1;
223 ep = NULL;
224 errno = 0;
225 v = strtoul(p, &ep, 10);
226 if (errno == 0 && ep && *ep == '\0' && v <= UINT_MAX)
227 return v;
228 else
229 return -1;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900230}
231
232/*
233 * The following functions determine whether IPv4 or IPv6 connectivity is
234 * available in order to implement AI_ADDRCONFIG.
235 *
236 * Strictly speaking, AI_ADDRCONFIG should not look at whether connectivity is
237 * available, but whether addresses of the specified family are "configured
238 * on the local system". However, bionic doesn't currently support getifaddrs,
239 * so checking for connectivity is the next best thing.
240 */
Bernie Innocentic50c43d2019-03-05 15:45:03 +0900241static int have_ipv6(unsigned mark, uid_t uid) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900242 static const struct sockaddr_in6 sin6_test = {
243 .sin6_family = AF_INET6,
244 .sin6_addr.s6_addr = {// 2000::
245 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}};
nuccachenb980f2f2018-10-23 17:10:58 +0800246 sockaddr_union addr = {.sin6 = sin6_test};
247 return _find_src_addr(&addr.sa, NULL, mark, uid) == 1;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900248}
249
Bernie Innocentic50c43d2019-03-05 15:45:03 +0900250static int have_ipv4(unsigned mark, uid_t uid) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900251 static const struct sockaddr_in sin_test = {
252 .sin_family = AF_INET,
253 .sin_addr.s_addr = __constant_htonl(0x08080808L) // 8.8.8.8
254 };
nuccachenb980f2f2018-10-23 17:10:58 +0800255 sockaddr_union addr = {.sin = sin_test};
256 return _find_src_addr(&addr.sa, NULL, mark, uid) == 1;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900257}
258
Bernie Innocentie2bc46f2018-10-16 23:35:28 +0900259// Internal version of getaddrinfo(), but limited to AI_NUMERICHOST.
Mike Yuc7649d12019-05-22 15:28:07 +0800260// NOTE: also called by resolv_set_nameservers().
Bernie Innocentie2bc46f2018-10-16 23:35:28 +0900261int getaddrinfo_numeric(const char* hostname, const char* servname, addrinfo hints,
262 addrinfo** result) {
263 hints.ai_flags = AI_NUMERICHOST;
264 const android_net_context netcontext = {
265 .app_netid = NETID_UNSET,
266 .app_mark = MARK_UNSET,
267 .dns_netid = NETID_UNSET,
268 .dns_mark = MARK_UNSET,
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900269 .uid = NET_CONTEXT_INVALID_UID,
Praveen Moongalam Thyagarajan8ab18ba2019-09-04 14:46:50 -0700270 .pid = NET_CONTEXT_INVALID_PID,
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900271 };
lifr94981782019-05-17 21:15:19 +0800272 NetworkDnsEventReported event;
273 return android_getaddrinfofornetcontext(hostname, servname, &hints, &netcontext, result,
274 &event);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900275}
276
Luke Huang69e67182019-06-17 17:06:41 +0800277namespace {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900278
Luke Huang69e67182019-06-17 17:06:41 +0800279int validateHints(const addrinfo* _Nonnull hints) {
280 if (!hints) return EAI_BADHINTS;
281
282 // error check for hints
283 if (hints->ai_addrlen || hints->ai_canonname || hints->ai_addr || hints->ai_next) {
284 return EAI_BADHINTS;
285 }
286 if (hints->ai_flags & ~AI_MASK) {
287 return EAI_BADFLAGS;
288 }
289 if (!(hints->ai_family == PF_UNSPEC || hints->ai_family == PF_INET ||
290 hints->ai_family == PF_INET6)) {
291 return EAI_FAMILY;
292 }
293
Luke Huangd8ac4752019-06-18 17:05:47 +0800294 // Socket types which are not in explore_options.
295 switch (hints->ai_socktype) {
296 case SOCK_RAW:
297 case SOCK_DGRAM:
298 case SOCK_STREAM:
299 case ANY:
300 break;
301 default:
302 return EAI_SOCKTYPE;
303 }
304
Luke Huang69e67182019-06-17 17:06:41 +0800305 if (hints->ai_socktype == ANY || hints->ai_protocol == ANY) return 0;
306
307 // if both socktype/protocol are specified, check if they are meaningful combination.
308 for (const Explore& ex : explore_options) {
309 if (hints->ai_family != ex.e_af) continue;
310 if (ex.e_socktype == ANY) continue;
311 if (ex.e_protocol == ANY) continue;
312 if (hints->ai_socktype == ex.e_socktype && hints->ai_protocol != ex.e_protocol) {
313 return EAI_BADHINTS;
314 }
315 }
316
317 return 0;
318}
319
320} // namespace
321
322int android_getaddrinfofornetcontext(const char* hostname, const char* servname,
323 const addrinfo* hints, const android_net_context* netcontext,
lifr94981782019-05-17 21:15:19 +0800324 addrinfo** res, NetworkDnsEventReported* event) {
Bernie Innocenti0cfe9dc2019-02-20 18:39:35 +0900325 // hostname is allowed to be nullptr
326 // servname is allowed to be nullptr
327 // hints is allowed to be nullptr
328 assert(res != nullptr);
329 assert(netcontext != nullptr);
lifr94981782019-05-17 21:15:19 +0800330 assert(event != nullptr);
Bernie Innocenti2b1afbe2019-02-20 17:50:38 +0900331
Luke Huang69e67182019-06-17 17:06:41 +0800332 addrinfo sentinel = {};
333 addrinfo* cur = &sentinel;
334 int error = 0;
Bernie Innocenti2b1afbe2019-02-20 17:50:38 +0900335
Ken Chene0d73c92018-11-07 01:20:48 +0800336 do {
Luke Huang69e67182019-06-17 17:06:41 +0800337 if (hostname == nullptr && servname == nullptr) {
Ken Chene0d73c92018-11-07 01:20:48 +0800338 error = EAI_NONAME;
339 break;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900340 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900341
Luke Huang69e67182019-06-17 17:06:41 +0800342 if (hints && (error = validateHints(hints))) break;
343 addrinfo ai = hints ? *hints : addrinfo{};
Bernie Innocenti2b1afbe2019-02-20 17:50:38 +0900344
Luke Huang69e67182019-06-17 17:06:41 +0800345 // Check for special cases:
346 // (1) numeric servname is disallowed if socktype/protocol are left unspecified.
347 // (2) servname is disallowed for raw and other inet{,6} sockets.
Bernie Innocenti2b1afbe2019-02-20 17:50:38 +0900348 if (MATCH_FAMILY(ai.ai_family, PF_INET, 1) || MATCH_FAMILY(ai.ai_family, PF_INET6, 1)) {
Luke Huang69e67182019-06-17 17:06:41 +0800349 addrinfo tmp = ai;
Bernie Innocenti0cfe9dc2019-02-20 18:39:35 +0900350 if (tmp.ai_family == PF_UNSPEC) {
351 tmp.ai_family = PF_INET6;
Ken Chene0d73c92018-11-07 01:20:48 +0800352 }
Bernie Innocenti0cfe9dc2019-02-20 18:39:35 +0900353 error = get_portmatch(&tmp, servname);
Ken Chene0d73c92018-11-07 01:20:48 +0800354 if (error) break;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900355 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900356
Bernie Innocentib0b32bc2019-02-20 18:21:24 +0900357 // NULL hostname, or numeric hostname
358 for (const Explore& ex : explore_options) {
Ken Chene0d73c92018-11-07 01:20:48 +0800359 /* PF_UNSPEC entries are prepared for DNS queries only */
Bernie Innocentib0b32bc2019-02-20 18:21:24 +0900360 if (ex.e_af == PF_UNSPEC) continue;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900361
Bernie Innocentib0b32bc2019-02-20 18:21:24 +0900362 if (!MATCH_FAMILY(ai.ai_family, ex.e_af, WILD_AF(ex))) continue;
363 if (!MATCH(ai.ai_socktype, ex.e_socktype, WILD_SOCKTYPE(ex))) continue;
364 if (!MATCH(ai.ai_protocol, ex.e_protocol, WILD_PROTOCOL(ex))) continue;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900365
Luke Huang69e67182019-06-17 17:06:41 +0800366 addrinfo tmp = ai;
Bernie Innocenti0cfe9dc2019-02-20 18:39:35 +0900367 if (tmp.ai_family == PF_UNSPEC) tmp.ai_family = ex.e_af;
368 if (tmp.ai_socktype == ANY && ex.e_socktype != ANY) tmp.ai_socktype = ex.e_socktype;
369 if (tmp.ai_protocol == ANY && ex.e_protocol != ANY) tmp.ai_protocol = ex.e_protocol;
Ken Chene0d73c92018-11-07 01:20:48 +0800370
Ken Chenffc224a2019-03-19 17:41:28 +0800371 LOG(DEBUG) << __func__ << ": explore_numeric: ai_family=" << tmp.ai_family
Bernie Innocenti3952ccc2019-03-03 19:39:53 +0900372 << " ai_socktype=" << tmp.ai_socktype << " ai_protocol=" << tmp.ai_protocol;
Bernie Innocenti0cfe9dc2019-02-20 18:39:35 +0900373 if (hostname == nullptr)
374 error = explore_null(&tmp, servname, &cur->ai_next);
Ken Chene0d73c92018-11-07 01:20:48 +0800375 else
Bernie Innocenti0cfe9dc2019-02-20 18:39:35 +0900376 error = explore_numeric_scope(&tmp, hostname, servname, &cur->ai_next);
Ken Chene0d73c92018-11-07 01:20:48 +0800377
378 if (error) break;
379
380 while (cur->ai_next) cur = cur->ai_next;
381 }
382 if (error) break;
383
Luke Huang69e67182019-06-17 17:06:41 +0800384 // If numeric representation of AF1 can be interpreted as FQDN
385 // representation of AF2, we need to think again about the code below.
Ken Chene0d73c92018-11-07 01:20:48 +0800386 if (sentinel.ai_next) break;
387
Bernie Innocentib0b32bc2019-02-20 18:21:24 +0900388 if (hostname == nullptr) {
Ken Chene0d73c92018-11-07 01:20:48 +0800389 error = EAI_NODATA;
390 break;
391 }
Bernie Innocenti2b1afbe2019-02-20 17:50:38 +0900392 if (ai.ai_flags & AI_NUMERICHOST) {
Ken Chene0d73c92018-11-07 01:20:48 +0800393 error = EAI_NONAME;
394 break;
395 }
396
lifr94981782019-05-17 21:15:19 +0800397 return resolv_getaddrinfo(hostname, servname, hints, netcontext, res, event);
Ken Chene0d73c92018-11-07 01:20:48 +0800398 } while (0);
399
400 if (error) {
401 freeaddrinfo(sentinel.ai_next);
Bernie Innocentic50c43d2019-03-05 15:45:03 +0900402 *res = nullptr;
Ken Chene0d73c92018-11-07 01:20:48 +0800403 } else {
404 *res = sentinel.ai_next;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900405 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900406 return error;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900407}
408
Luke Huang69e67182019-06-17 17:06:41 +0800409int resolv_getaddrinfo(const char* _Nonnull hostname, const char* servname, const addrinfo* hints,
lifr94981782019-05-17 21:15:19 +0800410 const android_net_context* _Nonnull netcontext, addrinfo** _Nonnull res,
411 NetworkDnsEventReported* _Nonnull event) {
Luke Huang69e67182019-06-17 17:06:41 +0800412 if (hostname == nullptr && servname == nullptr) return EAI_NONAME;
413 if (hostname == nullptr) return EAI_NODATA;
414
Luke Huang69e67182019-06-17 17:06:41 +0800415 // servname is allowed to be nullptr
416 // hints is allowed to be nullptr
417 assert(res != nullptr);
418 assert(netcontext != nullptr);
lifr94981782019-05-17 21:15:19 +0800419 assert(event != nullptr);
Luke Huang69e67182019-06-17 17:06:41 +0800420
421 int error = EAI_FAIL;
422 if (hints && (error = validateHints(hints))) {
423 *res = nullptr;
424 return error;
425 }
426
427 addrinfo ai = hints ? *hints : addrinfo{};
428 addrinfo sentinel = {};
429 addrinfo* cur = &sentinel;
430 // hostname as alphanumeric name.
431 // We would like to prefer AF_INET6 over AF_INET, so we'll make a outer loop by AFs.
432 for (const Explore& ex : explore_options) {
433 // Require exact match for family field
434 if (ai.ai_family != ex.e_af) continue;
435
436 if (!MATCH(ai.ai_socktype, ex.e_socktype, WILD_SOCKTYPE(ex))) continue;
437
438 if (!MATCH(ai.ai_protocol, ex.e_protocol, WILD_PROTOCOL(ex))) continue;
439
440 addrinfo tmp = ai;
441 if (tmp.ai_socktype == ANY && ex.e_socktype != ANY) tmp.ai_socktype = ex.e_socktype;
442 if (tmp.ai_protocol == ANY && ex.e_protocol != ANY) tmp.ai_protocol = ex.e_protocol;
443
444 LOG(DEBUG) << __func__ << ": explore_fqdn(): ai_family=" << tmp.ai_family
445 << " ai_socktype=" << tmp.ai_socktype << " ai_protocol=" << tmp.ai_protocol;
lifr94981782019-05-17 21:15:19 +0800446 error = explore_fqdn(&tmp, hostname, servname, &cur->ai_next, netcontext, event);
Luke Huang69e67182019-06-17 17:06:41 +0800447
448 while (cur->ai_next) cur = cur->ai_next;
449 }
450
Luke Huangd8ac4752019-06-18 17:05:47 +0800451 // Propagate the last error from explore_fqdn(), but only when *all* attempts failed.
Luke Huang69e67182019-06-17 17:06:41 +0800452 if ((*res = sentinel.ai_next)) return 0;
453
Luke Huangd8ac4752019-06-18 17:05:47 +0800454 // TODO: consider removing freeaddrinfo.
Luke Huang69e67182019-06-17 17:06:41 +0800455 freeaddrinfo(sentinel.ai_next);
456 *res = nullptr;
Luke Huangd8ac4752019-06-18 17:05:47 +0800457 return (error == 0) ? EAI_FAIL : error;
Luke Huang69e67182019-06-17 17:06:41 +0800458}
459
Bernie Innocenti9c575932018-09-07 21:10:25 +0900460// FQDN hostname, DNS lookup
Luke Huang69e67182019-06-17 17:06:41 +0800461static int explore_fqdn(const addrinfo* pai, const char* hostname, const char* servname,
lifr94981782019-05-17 21:15:19 +0800462 addrinfo** res, const android_net_context* netcontext,
463 NetworkDnsEventReported* event) {
Luke Huang69e67182019-06-17 17:06:41 +0800464 assert(pai != nullptr);
465 // hostname may be nullptr
466 // servname may be nullptr
467 assert(res != nullptr);
468
469 addrinfo* result = nullptr;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900470 int error = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900471
Luke Huang69e67182019-06-17 17:06:41 +0800472 // If the servname does not match socktype/protocol, return error code.
473 if ((error = get_portmatch(pai, servname))) return error;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900474
chenbrucefd837fa2019-10-29 18:35:36 +0800475 if (!files_getaddrinfo(netcontext->dns_netid, hostname, pai, &result)) {
lifr94981782019-05-17 21:15:19 +0800476 error = dns_getaddrinfo(hostname, pai, netcontext, &result, event);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900477 }
Luke Huang69e67182019-06-17 17:06:41 +0800478 if (error) {
479 freeaddrinfo(result);
480 return error;
Bernie Innocenti455c6232018-09-12 21:32:42 +0900481 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900482
Luke Huang69e67182019-06-17 17:06:41 +0800483 for (addrinfo* cur = result; cur; cur = cur->ai_next) {
484 // canonname should be filled already
485 if ((error = get_port(cur, servname, 0))) {
486 freeaddrinfo(result);
487 return error;
488 }
489 }
490 *res = result;
491 return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900492}
493
494/*
495 * hostname == NULL.
496 * passive socket -> anyaddr (0.0.0.0 or ::)
497 * non-passive socket -> localhost (127.0.0.1 or ::1)
498 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900499static int explore_null(const struct addrinfo* pai, const char* servname, struct addrinfo** res) {
500 int s;
501 const struct afd* afd;
502 struct addrinfo* cur;
503 struct addrinfo sentinel;
504 int error;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900505
Ken Chenffc224a2019-03-19 17:41:28 +0800506 LOG(DEBUG) << __func__;
507
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900508 assert(pai != NULL);
509 /* servname may be NULL */
510 assert(res != NULL);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900511
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900512 *res = NULL;
513 sentinel.ai_next = NULL;
514 cur = &sentinel;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900515
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900516 /*
517 * filter out AFs that are not supported by the kernel
518 * XXX errno?
519 */
520 s = socket(pai->ai_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
521 if (s < 0) {
522 if (errno != EMFILE) return 0;
523 } else
524 close(s);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900525
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900526 /*
527 * if the servname does not match socktype/protocol, ignore it.
528 */
529 if (get_portmatch(pai, servname) != 0) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900530
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900531 afd = find_afd(pai->ai_family);
532 if (afd == NULL) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900533
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900534 if (pai->ai_flags & AI_PASSIVE) {
535 GET_AI(cur->ai_next, afd, afd->a_addrany);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900536 GET_PORT(cur->ai_next, servname);
537 } else {
538 GET_AI(cur->ai_next, afd, afd->a_loopback);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900539 GET_PORT(cur->ai_next, servname);
540 }
541 cur = cur->ai_next;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900542
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900543 *res = sentinel.ai_next;
544 return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900545
546free:
Bernie Innocenti18a5ab52018-10-02 12:53:39 +0900547 freeaddrinfo(sentinel.ai_next);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900548 return error;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900549}
550
551/*
552 * numeric hostname
553 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900554static int explore_numeric(const struct addrinfo* pai, const char* hostname, const char* servname,
555 struct addrinfo** res, const char* canonname) {
556 const struct afd* afd;
557 struct addrinfo* cur;
558 struct addrinfo sentinel;
559 int error;
560 char pton[PTON_MAX];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900561
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900562 assert(pai != NULL);
563 /* hostname may be NULL */
564 /* servname may be NULL */
565 assert(res != NULL);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900566
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900567 *res = NULL;
568 sentinel.ai_next = NULL;
569 cur = &sentinel;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900570
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900571 /*
572 * if the servname does not match socktype/protocol, ignore it.
573 */
574 if (get_portmatch(pai, servname) != 0) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900575
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900576 afd = find_afd(pai->ai_family);
577 if (afd == NULL) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900578
Ken Chena4b33022018-10-17 00:19:59 +0800579 if (inet_pton(afd->a_af, hostname, pton) == 1) {
580 if (pai->ai_family == afd->a_af || pai->ai_family == PF_UNSPEC /*?*/) {
581 GET_AI(cur->ai_next, afd, pton);
582 GET_PORT(cur->ai_next, servname);
583 if ((pai->ai_flags & AI_CANONNAME)) {
584 /*
585 * Set the numeric address itself as
586 * the canonical name, based on a
587 * clarification in rfc2553bis-03.
588 */
Ken Chene0d73c92018-11-07 01:20:48 +0800589 error = get_canonname(pai, cur->ai_next, canonname);
590 if (error != 0) {
591 freeaddrinfo(sentinel.ai_next);
592 return error;
593 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900594 }
Ken Chena4b33022018-10-17 00:19:59 +0800595 while (cur->ai_next) cur = cur->ai_next;
596 } else
Ken Chene0d73c92018-11-07 01:20:48 +0800597 return EAI_FAMILY;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900598 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900599
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900600 *res = sentinel.ai_next;
601 return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900602
603free:
Bernie Innocenti18a5ab52018-10-02 12:53:39 +0900604 freeaddrinfo(sentinel.ai_next);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900605 return error;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900606}
607
608/*
609 * numeric hostname with scope
610 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900611static int explore_numeric_scope(const struct addrinfo* pai, const char* hostname,
612 const char* servname, struct addrinfo** res) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900613 const struct afd* afd;
614 struct addrinfo* cur;
615 int error;
Bernie Innocenti9c575932018-09-07 21:10:25 +0900616 const char *cp, *scope, *addr;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900617 struct sockaddr_in6* sin6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900618
Ken Chenffc224a2019-03-19 17:41:28 +0800619 LOG(DEBUG) << __func__;
620
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900621 assert(pai != NULL);
622 /* hostname may be NULL */
623 /* servname may be NULL */
624 assert(res != NULL);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900625
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900626 /*
627 * if the servname does not match socktype/protocol, ignore it.
628 */
629 if (get_portmatch(pai, servname) != 0) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900630
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900631 afd = find_afd(pai->ai_family);
632 if (afd == NULL) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900633
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900634 if (!afd->a_scoped) return explore_numeric(pai, hostname, servname, res, hostname);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900635
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900636 cp = strchr(hostname, SCOPE_DELIMITER);
637 if (cp == NULL) return explore_numeric(pai, hostname, servname, res, hostname);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900638
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900639 /*
640 * Handle special case of <scoped_address><delimiter><scope id>
641 */
Bernie Innocenti9c575932018-09-07 21:10:25 +0900642 char* hostname2 = strdup(hostname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900643 if (hostname2 == NULL) return EAI_MEMORY;
644 /* terminate at the delimiter */
645 hostname2[cp - hostname] = '\0';
646 addr = hostname2;
647 scope = cp + 1;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900648
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900649 error = explore_numeric(pai, addr, servname, res, hostname);
650 if (error == 0) {
chenbrucec51f1212019-09-12 16:59:33 +0800651 uint32_t scopeid;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900652
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900653 for (cur = *res; cur; cur = cur->ai_next) {
654 if (cur->ai_family != AF_INET6) continue;
655 sin6 = (struct sockaddr_in6*) (void*) cur->ai_addr;
656 if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) {
657 free(hostname2);
658 return (EAI_NODATA); /* XXX: is return OK? */
659 }
660 sin6->sin6_scope_id = scopeid;
661 }
662 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900663
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900664 free(hostname2);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900665
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900666 return error;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900667}
668
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900669static int get_canonname(const struct addrinfo* pai, struct addrinfo* ai, const char* str) {
670 assert(pai != NULL);
671 assert(ai != NULL);
672 assert(str != NULL);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900673
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900674 if ((pai->ai_flags & AI_CANONNAME) != 0) {
675 ai->ai_canonname = strdup(str);
676 if (ai->ai_canonname == NULL) return EAI_MEMORY;
677 }
678 return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900679}
680
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900681static struct addrinfo* get_ai(const struct addrinfo* pai, const struct afd* afd,
682 const char* addr) {
683 char* p;
684 struct addrinfo* ai;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900685
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900686 assert(pai != NULL);
687 assert(afd != NULL);
688 assert(addr != NULL);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900689
nuccachena49c0ba2018-09-11 11:13:44 +0800690 ai = (struct addrinfo*) malloc(sizeof(struct addrinfo) + sizeof(sockaddr_union));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900691 if (ai == NULL) return NULL;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900692
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900693 memcpy(ai, pai, sizeof(struct addrinfo));
694 ai->ai_addr = (struct sockaddr*) (void*) (ai + 1);
nuccachena49c0ba2018-09-11 11:13:44 +0800695 memset(ai->ai_addr, 0, sizeof(sockaddr_union));
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900696
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900697 ai->ai_addrlen = afd->a_socklen;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900698 ai->ai_addr->sa_family = ai->ai_family = afd->a_af;
699 p = (char*) (void*) (ai->ai_addr);
700 memcpy(p + afd->a_off, addr, (size_t) afd->a_addrlen);
701 return ai;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900702}
703
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900704static int get_portmatch(const struct addrinfo* ai, const char* servname) {
705 assert(ai != NULL);
706 /* servname may be NULL */
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900707
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900708 return get_port(ai, servname, 1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900709}
710
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900711static int get_port(const struct addrinfo* ai, const char* servname, int matchonly) {
712 const char* proto;
713 struct servent* sp;
714 int port;
715 int allownumeric;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900716
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900717 assert(ai != NULL);
718 /* servname may be NULL */
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900719
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900720 if (servname == NULL) return 0;
721 switch (ai->ai_family) {
722 case AF_INET:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900723 case AF_INET6:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900724 break;
725 default:
726 return 0;
727 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900728
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900729 switch (ai->ai_socktype) {
730 case SOCK_RAW:
731 return EAI_SERVICE;
732 case SOCK_DGRAM:
733 case SOCK_STREAM:
734 allownumeric = 1;
735 break;
736 case ANY:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900737 allownumeric = 1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900738 break;
739 default:
740 return EAI_SOCKTYPE;
741 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900742
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900743 port = str2number(servname);
744 if (port >= 0) {
745 if (!allownumeric) return EAI_SERVICE;
746 if (port < 0 || port > 65535) return EAI_SERVICE;
747 port = htons(port);
748 } else {
749 if (ai->ai_flags & AI_NUMERICSERV) return EAI_NONAME;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900750
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900751 switch (ai->ai_socktype) {
752 case SOCK_DGRAM:
753 proto = "udp";
754 break;
755 case SOCK_STREAM:
756 proto = "tcp";
757 break;
758 default:
759 proto = NULL;
760 break;
761 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900762
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900763 if ((sp = getservbyname(servname, proto)) == NULL) return EAI_SERVICE;
764 port = sp->s_port;
765 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900766
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900767 if (!matchonly) {
768 switch (ai->ai_family) {
769 case AF_INET:
770 ((struct sockaddr_in*) (void*) ai->ai_addr)->sin_port = port;
771 break;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900772 case AF_INET6:
773 ((struct sockaddr_in6*) (void*) ai->ai_addr)->sin6_port = port;
774 break;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900775 }
776 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900777
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900778 return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900779}
780
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900781static const struct afd* find_afd(int af) {
782 const struct afd* afd;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900783
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900784 if (af == PF_UNSPEC) return NULL;
785 for (afd = afdl; afd->a_af; afd++) {
786 if (afd->a_af == af) return afd;
787 }
788 return NULL;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900789}
790
Bernie Innocenti9c575932018-09-07 21:10:25 +0900791// Convert a string to a scope identifier.
chenbrucec51f1212019-09-12 16:59:33 +0800792static int ip6_str2scopeid(const char* scope, struct sockaddr_in6* sin6, uint32_t* scopeid) {
793 uint64_t lscopeid;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900794 struct in6_addr* a6;
795 char* ep;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900796
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900797 assert(scope != NULL);
798 assert(sin6 != NULL);
799 assert(scopeid != NULL);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900800
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900801 a6 = &sin6->sin6_addr;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900802
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900803 /* empty scopeid portion is invalid */
804 if (*scope == '\0') return -1;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900805
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900806 if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) {
807 /*
808 * We currently assume a one-to-one mapping between links
809 * and interfaces, so we simply use interface indices for
810 * like-local scopes.
811 */
812 *scopeid = if_nametoindex(scope);
Bernie Innocenti63abf5b2019-06-11 21:46:51 +0900813 if (*scopeid != 0) return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900814 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900815
Bernie Innocenti63abf5b2019-06-11 21:46:51 +0900816 // try to convert to a numeric id as a last resort
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900817 errno = 0;
818 lscopeid = strtoul(scope, &ep, 10);
chenbrucec51f1212019-09-12 16:59:33 +0800819 *scopeid = (uint32_t)(lscopeid & 0xffffffffUL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900820 if (errno == 0 && ep && *ep == '\0' && *scopeid == lscopeid)
821 return 0;
822 else
823 return -1;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900824}
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900825
826/* code duplicate with gethnamaddr.c */
827
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900828#define BOUNDED_INCR(x) \
829 do { \
830 BOUNDS_CHECK(cp, x); \
831 cp += (x); \
Bernie Innocenti9c575932018-09-07 21:10:25 +0900832 } while (0)
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900833
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900834#define BOUNDS_CHECK(ptr, count) \
835 do { \
836 if (eom - (ptr) < (count)) { \
Hungming Chendd4bfb92018-12-25 15:47:47 +0800837 *herrno = NO_RECOVERY; \
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900838 return NULL; \
839 } \
Bernie Innocenti9c575932018-09-07 21:10:25 +0900840 } while (0)
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900841
Luke Huangc98fd802019-10-15 16:36:36 +0900842static struct addrinfo* getanswer(const std::vector<uint8_t>& answer, int anslen, const char* qname,
843 int qtype, const struct addrinfo* pai, int* herrno) {
Ken Chene0d73c92018-11-07 01:20:48 +0800844 struct addrinfo sentinel = {};
845 struct addrinfo *cur;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900846 struct addrinfo ai;
847 const struct afd* afd;
848 char* canonname;
849 const HEADER* hp;
chenbrucec51f1212019-09-12 16:59:33 +0800850 const uint8_t* cp;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900851 int n;
chenbrucec51f1212019-09-12 16:59:33 +0800852 const uint8_t* eom;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900853 char *bp, *ep;
Bernie Innocenti9c575932018-09-07 21:10:25 +0900854 int type, ancount, qdcount;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900855 int haveanswer, had_error;
856 char tbuf[MAXDNAME];
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900857 char hostbuf[8 * 1024];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900858
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900859 assert(qname != NULL);
860 assert(pai != NULL);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900861
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900862 cur = &sentinel;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900863
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900864 canonname = NULL;
Luke Huangc98fd802019-10-15 16:36:36 +0900865 eom = answer.data() + anslen;
Bernie Innocenti10a90282020-01-23 23:28:00 +0900866
867 bool (*name_ok)(const char* dn);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900868 switch (qtype) {
869 case T_A:
870 case T_AAAA:
871 case T_ANY: /*use T_ANY only for T_A/T_AAAA lookup*/
872 name_ok = res_hnok;
873 break;
874 default:
875 return NULL; /* XXX should be abort(); */
876 }
877 /*
878 * find first satisfactory answer
879 */
Luke Huangc98fd802019-10-15 16:36:36 +0900880 hp = reinterpret_cast<const HEADER*>(answer.data());
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900881 ancount = ntohs(hp->ancount);
882 qdcount = ntohs(hp->qdcount);
883 bp = hostbuf;
884 ep = hostbuf + sizeof hostbuf;
Luke Huangc98fd802019-10-15 16:36:36 +0900885 cp = answer.data();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900886 BOUNDED_INCR(HFIXEDSZ);
887 if (qdcount != 1) {
Hungming Chendd4bfb92018-12-25 15:47:47 +0800888 *herrno = NO_RECOVERY;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900889 return (NULL);
890 }
Luke Huangc98fd802019-10-15 16:36:36 +0900891 n = dn_expand(answer.data(), eom, cp, bp, ep - bp);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900892 if ((n < 0) || !(*name_ok)(bp)) {
Hungming Chendd4bfb92018-12-25 15:47:47 +0800893 *herrno = NO_RECOVERY;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900894 return (NULL);
895 }
896 BOUNDED_INCR(n + QFIXEDSZ);
897 if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) {
898 /* res_send() has already verified that the query name is the
899 * same as the one we sent; this just gets the expanded name
900 * (i.e., with the succeeding search-domain tacked on).
901 */
902 n = strlen(bp) + 1; /* for the \0 */
903 if (n >= MAXHOSTNAMELEN) {
Hungming Chendd4bfb92018-12-25 15:47:47 +0800904 *herrno = NO_RECOVERY;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900905 return (NULL);
906 }
907 canonname = bp;
908 bp += n;
909 /* The qname can be abbreviated, but h_name is now absolute. */
910 qname = canonname;
911 }
912 haveanswer = 0;
913 had_error = 0;
914 while (ancount-- > 0 && cp < eom && !had_error) {
Luke Huangc98fd802019-10-15 16:36:36 +0900915 n = dn_expand(answer.data(), eom, cp, bp, ep - bp);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900916 if ((n < 0) || !(*name_ok)(bp)) {
917 had_error++;
918 continue;
919 }
920 cp += n; /* name */
921 BOUNDS_CHECK(cp, 3 * INT16SZ + INT32SZ);
chenbruce0d470422019-03-28 18:44:37 +0800922 type = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900923 cp += INT16SZ; /* type */
chenbruce0d470422019-03-28 18:44:37 +0800924 int cl = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900925 cp += INT16SZ + INT32SZ; /* class, TTL */
chenbruce0d470422019-03-28 18:44:37 +0800926 n = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900927 cp += INT16SZ; /* len */
928 BOUNDS_CHECK(cp, n);
Bernie Innocenti9c575932018-09-07 21:10:25 +0900929 if (cl != C_IN) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900930 /* XXX - debug? syslog? */
931 cp += n;
932 continue; /* XXX - had_error++ ? */
933 }
934 if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) && type == T_CNAME) {
Luke Huangc98fd802019-10-15 16:36:36 +0900935 n = dn_expand(answer.data(), eom, cp, tbuf, sizeof tbuf);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900936 if ((n < 0) || !(*name_ok)(tbuf)) {
937 had_error++;
938 continue;
939 }
940 cp += n;
941 /* Get canonical name. */
942 n = strlen(tbuf) + 1; /* for the \0 */
943 if (n > ep - bp || n >= MAXHOSTNAMELEN) {
944 had_error++;
945 continue;
946 }
947 strlcpy(bp, tbuf, (size_t)(ep - bp));
948 canonname = bp;
949 bp += n;
950 continue;
951 }
952 if (qtype == T_ANY) {
953 if (!(type == T_A || type == T_AAAA)) {
954 cp += n;
955 continue;
956 }
957 } else if (type != qtype) {
958 if (type != T_KEY && type != T_SIG)
Ken Chenffc224a2019-03-19 17:41:28 +0800959 LOG(DEBUG) << __func__ << ": asked for \"" << qname << " " << p_class(C_IN) << " "
960 << p_type(qtype) << "\", got type \"" << p_type(type) << "\"";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900961 cp += n;
962 continue; /* XXX - had_error++ ? */
963 }
964 switch (type) {
965 case T_A:
966 case T_AAAA:
967 if (strcasecmp(canonname, bp) != 0) {
Ken Chenffc224a2019-03-19 17:41:28 +0800968 LOG(DEBUG) << __func__ << ": asked for \"" << canonname << "\", got \"" << bp
969 << "\"";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900970 cp += n;
971 continue; /* XXX - had_error++ ? */
972 }
973 if (type == T_A && n != INADDRSZ) {
974 cp += n;
975 continue;
976 }
977 if (type == T_AAAA && n != IN6ADDRSZ) {
978 cp += n;
979 continue;
980 }
981 if (type == T_AAAA) {
982 struct in6_addr in6;
983 memcpy(&in6, cp, IN6ADDRSZ);
984 if (IN6_IS_ADDR_V4MAPPED(&in6)) {
985 cp += n;
986 continue;
987 }
988 }
989 if (!haveanswer) {
990 int nn;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900991
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900992 canonname = bp;
993 nn = strlen(bp) + 1; /* for the \0 */
994 bp += nn;
995 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900996
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900997 /* don't overwrite pai */
998 ai = *pai;
999 ai.ai_family = (type == T_A) ? AF_INET : AF_INET6;
1000 afd = find_afd(ai.ai_family);
1001 if (afd == NULL) {
1002 cp += n;
1003 continue;
1004 }
1005 cur->ai_next = get_ai(&ai, afd, (const char*) cp);
1006 if (cur->ai_next == NULL) had_error++;
1007 while (cur && cur->ai_next) cur = cur->ai_next;
1008 cp += n;
1009 break;
1010 default:
1011 abort();
1012 }
1013 if (!had_error) haveanswer++;
1014 }
1015 if (haveanswer) {
1016 if (!canonname)
1017 (void) get_canonname(pai, sentinel.ai_next, qname);
1018 else
1019 (void) get_canonname(pai, sentinel.ai_next, canonname);
Hungming Chendd4bfb92018-12-25 15:47:47 +08001020 *herrno = NETDB_SUCCESS;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001021 return sentinel.ai_next;
1022 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001023
Hungming Chendd4bfb92018-12-25 15:47:47 +08001024 *herrno = NO_RECOVERY;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001025 return NULL;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001026}
1027
1028struct addrinfo_sort_elem {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001029 struct addrinfo* ai;
1030 int has_src_addr;
1031 sockaddr_union src_addr;
1032 int original_order;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001033};
1034
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001035static int _get_scope(const struct sockaddr* addr) {
1036 if (addr->sa_family == AF_INET6) {
1037 const struct sockaddr_in6* addr6 = (const struct sockaddr_in6*) addr;
1038 if (IN6_IS_ADDR_MULTICAST(&addr6->sin6_addr)) {
1039 return IPV6_ADDR_MC_SCOPE(&addr6->sin6_addr);
1040 } else if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr) ||
1041 IN6_IS_ADDR_LINKLOCAL(&addr6->sin6_addr)) {
1042 /*
1043 * RFC 4291 section 2.5.3 says loopback is to be treated as having
1044 * link-local scope.
1045 */
1046 return IPV6_ADDR_SCOPE_LINKLOCAL;
1047 } else if (IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr)) {
1048 return IPV6_ADDR_SCOPE_SITELOCAL;
1049 } else {
1050 return IPV6_ADDR_SCOPE_GLOBAL;
1051 }
1052 } else if (addr->sa_family == AF_INET) {
1053 const struct sockaddr_in* addr4 = (const struct sockaddr_in*) addr;
1054 unsigned long int na = ntohl(addr4->sin_addr.s_addr);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001055
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001056 if (IN_LOOPBACK(na) || /* 127.0.0.0/8 */
1057 (na & 0xffff0000) == 0xa9fe0000) { /* 169.254.0.0/16 */
1058 return IPV6_ADDR_SCOPE_LINKLOCAL;
1059 } else {
1060 /*
1061 * RFC 6724 section 3.2. Other IPv4 addresses, including private addresses
1062 * and shared addresses (100.64.0.0/10), are assigned global scope.
1063 */
1064 return IPV6_ADDR_SCOPE_GLOBAL;
1065 }
1066 } else {
1067 /*
1068 * This should never happen.
1069 * Return a scope with low priority as a last resort.
1070 */
1071 return IPV6_ADDR_SCOPE_NODELOCAL;
1072 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001073}
1074
1075/* These macros are modelled after the ones in <netinet/in6.h>. */
1076
1077/* RFC 4380, section 2.6 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001078#define IN6_IS_ADDR_TEREDO(a) \
1079 ((*(const uint32_t*) (const void*) (&(a)->s6_addr[0]) == ntohl(0x20010000)))
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001080
1081/* RFC 3056, section 2. */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001082#define IN6_IS_ADDR_6TO4(a) (((a)->s6_addr[0] == 0x20) && ((a)->s6_addr[1] == 0x02))
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001083
1084/* 6bone testing address area (3ffe::/16), deprecated in RFC 3701. */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001085#define IN6_IS_ADDR_6BONE(a) (((a)->s6_addr[0] == 0x3f) && ((a)->s6_addr[1] == 0xfe))
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001086
1087/*
1088 * Get the label for a given IPv4/IPv6 address.
1089 * RFC 6724, section 2.1.
1090 */
1091
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001092static int _get_label(const struct sockaddr* addr) {
1093 if (addr->sa_family == AF_INET) {
1094 return 4;
1095 } else if (addr->sa_family == AF_INET6) {
1096 const struct sockaddr_in6* addr6 = (const struct sockaddr_in6*) addr;
1097 if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr)) {
1098 return 0;
1099 } else if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
1100 return 4;
1101 } else if (IN6_IS_ADDR_6TO4(&addr6->sin6_addr)) {
1102 return 2;
1103 } else if (IN6_IS_ADDR_TEREDO(&addr6->sin6_addr)) {
1104 return 5;
1105 } else if (IN6_IS_ADDR_ULA(&addr6->sin6_addr)) {
1106 return 13;
1107 } else if (IN6_IS_ADDR_V4COMPAT(&addr6->sin6_addr)) {
1108 return 3;
1109 } else if (IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr)) {
1110 return 11;
1111 } else if (IN6_IS_ADDR_6BONE(&addr6->sin6_addr)) {
1112 return 12;
1113 } else {
1114 /* All other IPv6 addresses, including global unicast addresses. */
1115 return 1;
1116 }
1117 } else {
1118 /*
1119 * This should never happen.
1120 * Return a semi-random label as a last resort.
1121 */
1122 return 1;
1123 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001124}
1125
1126/*
1127 * Get the precedence for a given IPv4/IPv6 address.
1128 * RFC 6724, section 2.1.
1129 */
1130
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001131static int _get_precedence(const struct sockaddr* addr) {
1132 if (addr->sa_family == AF_INET) {
1133 return 35;
1134 } else if (addr->sa_family == AF_INET6) {
1135 const struct sockaddr_in6* addr6 = (const struct sockaddr_in6*) addr;
1136 if (IN6_IS_ADDR_LOOPBACK(&addr6->sin6_addr)) {
1137 return 50;
1138 } else if (IN6_IS_ADDR_V4MAPPED(&addr6->sin6_addr)) {
1139 return 35;
1140 } else if (IN6_IS_ADDR_6TO4(&addr6->sin6_addr)) {
1141 return 30;
1142 } else if (IN6_IS_ADDR_TEREDO(&addr6->sin6_addr)) {
1143 return 5;
1144 } else if (IN6_IS_ADDR_ULA(&addr6->sin6_addr)) {
1145 return 3;
1146 } else if (IN6_IS_ADDR_V4COMPAT(&addr6->sin6_addr) ||
1147 IN6_IS_ADDR_SITELOCAL(&addr6->sin6_addr) ||
1148 IN6_IS_ADDR_6BONE(&addr6->sin6_addr)) {
1149 return 1;
1150 } else {
1151 /* All other IPv6 addresses, including global unicast addresses. */
1152 return 40;
1153 }
1154 } else {
1155 return 1;
1156 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001157}
1158
1159/*
1160 * Find number of matching initial bits between the two addresses a1 and a2.
1161 */
1162
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001163static int _common_prefix_len(const struct in6_addr* a1, const struct in6_addr* a2) {
1164 const char* p1 = (const char*) a1;
1165 const char* p2 = (const char*) a2;
1166 unsigned i;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001167
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001168 for (i = 0; i < sizeof(*a1); ++i) {
1169 int x, j;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001170
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001171 if (p1[i] == p2[i]) {
1172 continue;
1173 }
1174 x = p1[i] ^ p2[i];
1175 for (j = 0; j < CHAR_BIT; ++j) {
1176 if (x & (1 << (CHAR_BIT - 1))) {
1177 return i * CHAR_BIT + j;
1178 }
1179 x <<= 1;
1180 }
1181 }
1182 return sizeof(*a1) * CHAR_BIT;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001183}
1184
1185/*
1186 * Compare two source/destination address pairs.
1187 * RFC 6724, section 6.
1188 */
1189
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001190static int _rfc6724_compare(const void* ptr1, const void* ptr2) {
1191 const struct addrinfo_sort_elem* a1 = (const struct addrinfo_sort_elem*) ptr1;
1192 const struct addrinfo_sort_elem* a2 = (const struct addrinfo_sort_elem*) ptr2;
1193 int scope_src1, scope_dst1, scope_match1;
1194 int scope_src2, scope_dst2, scope_match2;
1195 int label_src1, label_dst1, label_match1;
1196 int label_src2, label_dst2, label_match2;
1197 int precedence1, precedence2;
1198 int prefixlen1, prefixlen2;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001199
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001200 /* Rule 1: Avoid unusable destinations. */
1201 if (a1->has_src_addr != a2->has_src_addr) {
1202 return a2->has_src_addr - a1->has_src_addr;
1203 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001204
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001205 /* Rule 2: Prefer matching scope. */
nuccachenb980f2f2018-10-23 17:10:58 +08001206 scope_src1 = _get_scope(&a1->src_addr.sa);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001207 scope_dst1 = _get_scope(a1->ai->ai_addr);
1208 scope_match1 = (scope_src1 == scope_dst1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001209
nuccachenb980f2f2018-10-23 17:10:58 +08001210 scope_src2 = _get_scope(&a2->src_addr.sa);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001211 scope_dst2 = _get_scope(a2->ai->ai_addr);
1212 scope_match2 = (scope_src2 == scope_dst2);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001213
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001214 if (scope_match1 != scope_match2) {
1215 return scope_match2 - scope_match1;
1216 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001217
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001218 /*
1219 * Rule 3: Avoid deprecated addresses.
1220 * TODO(sesse): We don't currently have a good way of finding this.
1221 */
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001222
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001223 /*
1224 * Rule 4: Prefer home addresses.
1225 * TODO(sesse): We don't currently have a good way of finding this.
1226 */
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001227
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001228 /* Rule 5: Prefer matching label. */
nuccachenb980f2f2018-10-23 17:10:58 +08001229 label_src1 = _get_label(&a1->src_addr.sa);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001230 label_dst1 = _get_label(a1->ai->ai_addr);
1231 label_match1 = (label_src1 == label_dst1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001232
nuccachenb980f2f2018-10-23 17:10:58 +08001233 label_src2 = _get_label(&a2->src_addr.sa);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001234 label_dst2 = _get_label(a2->ai->ai_addr);
1235 label_match2 = (label_src2 == label_dst2);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001236
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001237 if (label_match1 != label_match2) {
1238 return label_match2 - label_match1;
1239 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001240
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001241 /* Rule 6: Prefer higher precedence. */
1242 precedence1 = _get_precedence(a1->ai->ai_addr);
1243 precedence2 = _get_precedence(a2->ai->ai_addr);
1244 if (precedence1 != precedence2) {
1245 return precedence2 - precedence1;
1246 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001247
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001248 /*
1249 * Rule 7: Prefer native transport.
1250 * TODO(sesse): We don't currently have a good way of finding this.
1251 */
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001252
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001253 /* Rule 8: Prefer smaller scope. */
1254 if (scope_dst1 != scope_dst2) {
1255 return scope_dst1 - scope_dst2;
1256 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001257
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001258 /*
1259 * Rule 9: Use longest matching prefix.
1260 * We implement this for IPv6 only, as the rules in RFC 6724 don't seem
1261 * to work very well directly applied to IPv4. (glibc uses information from
1262 * the routing table for a custom IPv4 implementation here.)
1263 */
1264 if (a1->has_src_addr && a1->ai->ai_addr->sa_family == AF_INET6 && a2->has_src_addr &&
1265 a2->ai->ai_addr->sa_family == AF_INET6) {
nuccachenb980f2f2018-10-23 17:10:58 +08001266 const struct sockaddr_in6* a1_src = &a1->src_addr.sin6;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001267 const struct sockaddr_in6* a1_dst = (const struct sockaddr_in6*) a1->ai->ai_addr;
nuccachenb980f2f2018-10-23 17:10:58 +08001268 const struct sockaddr_in6* a2_src = &a2->src_addr.sin6;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001269 const struct sockaddr_in6* a2_dst = (const struct sockaddr_in6*) a2->ai->ai_addr;
1270 prefixlen1 = _common_prefix_len(&a1_src->sin6_addr, &a1_dst->sin6_addr);
1271 prefixlen2 = _common_prefix_len(&a2_src->sin6_addr, &a2_dst->sin6_addr);
1272 if (prefixlen1 != prefixlen2) {
1273 return prefixlen2 - prefixlen1;
1274 }
1275 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001276
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001277 /*
1278 * Rule 10: Leave the order unchanged.
1279 * We need this since qsort() is not necessarily stable.
1280 */
1281 return a1->original_order - a2->original_order;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001282}
1283
1284/*
1285 * Find the source address that will be used if trying to connect to the given
1286 * address. src_addr must be large enough to hold a struct sockaddr_in6.
1287 *
1288 * Returns 1 if a source address was found, 0 if the address is unreachable,
1289 * and -1 if a fatal error occurred. If 0 or -1, the contents of src_addr are
1290 * undefined.
1291 */
1292
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001293static int _find_src_addr(const struct sockaddr* addr, struct sockaddr* src_addr, unsigned mark,
1294 uid_t uid) {
1295 int sock;
1296 int ret;
1297 socklen_t len;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001298
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001299 switch (addr->sa_family) {
1300 case AF_INET:
1301 len = sizeof(struct sockaddr_in);
1302 break;
1303 case AF_INET6:
1304 len = sizeof(struct sockaddr_in6);
1305 break;
1306 default:
1307 /* No known usable source address for non-INET families. */
1308 return 0;
1309 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001310
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001311 sock = socket(addr->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
1312 if (sock == -1) {
1313 if (errno == EAFNOSUPPORT) {
1314 return 0;
1315 } else {
1316 return -1;
1317 }
1318 }
1319 if (mark != MARK_UNSET && setsockopt(sock, SOL_SOCKET, SO_MARK, &mark, sizeof(mark)) < 0) {
1320 close(sock);
1321 return 0;
1322 }
1323 if (uid > 0 && uid != NET_CONTEXT_INVALID_UID && fchown(sock, uid, (gid_t) -1) < 0) {
1324 close(sock);
1325 return 0;
1326 }
1327 do {
Bernie Innocentiafaacf72018-08-30 07:34:37 +09001328 ret = connect(sock, addr, len);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001329 } while (ret == -1 && errno == EINTR);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001330
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001331 if (ret == -1) {
1332 close(sock);
1333 return 0;
1334 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001335
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001336 if (src_addr && getsockname(sock, src_addr, &len) == -1) {
1337 close(sock);
1338 return -1;
1339 }
1340 close(sock);
1341 return 1;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001342}
1343
1344/*
1345 * Sort the linked list starting at sentinel->ai_next in RFC6724 order.
1346 * Will leave the list unchanged if an error occurs.
1347 */
1348
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001349static void _rfc6724_sort(struct addrinfo* list_sentinel, unsigned mark, uid_t uid) {
1350 struct addrinfo* cur;
1351 int nelem = 0, i;
1352 struct addrinfo_sort_elem* elems;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001353
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001354 cur = list_sentinel->ai_next;
1355 while (cur) {
1356 ++nelem;
1357 cur = cur->ai_next;
1358 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001359
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001360 elems = (struct addrinfo_sort_elem*) malloc(nelem * sizeof(struct addrinfo_sort_elem));
1361 if (elems == NULL) {
1362 goto error;
1363 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001364
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001365 /*
1366 * Convert the linked list to an array that also contains the candidate
1367 * source address for each destination address.
1368 */
1369 for (i = 0, cur = list_sentinel->ai_next; i < nelem; ++i, cur = cur->ai_next) {
1370 int has_src_addr;
1371 assert(cur != NULL);
1372 elems[i].ai = cur;
1373 elems[i].original_order = i;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001374
nuccachenb980f2f2018-10-23 17:10:58 +08001375 has_src_addr = _find_src_addr(cur->ai_addr, &elems[i].src_addr.sa, mark, uid);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001376 if (has_src_addr == -1) {
1377 goto error;
1378 }
1379 elems[i].has_src_addr = has_src_addr;
1380 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001381
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001382 /* Sort the addresses, and rearrange the linked list so it matches the sorted order. */
1383 qsort((void*) elems, nelem, sizeof(struct addrinfo_sort_elem), _rfc6724_compare);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001384
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001385 list_sentinel->ai_next = elems[0].ai;
1386 for (i = 0; i < nelem - 1; ++i) {
1387 elems[i].ai->ai_next = elems[i + 1].ai;
1388 }
1389 elems[nelem - 1].ai->ai_next = NULL;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001390
1391error:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001392 free(elems);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001393}
1394
Bernie Innocenti455c6232018-09-12 21:32:42 +09001395static int dns_getaddrinfo(const char* name, const addrinfo* pai,
lifr94981782019-05-17 21:15:19 +08001396 const android_net_context* netcontext, addrinfo** rv,
1397 NetworkDnsEventReported* event) {
Bernie Innocentic50c43d2019-03-05 15:45:03 +09001398 res_target q = {};
1399 res_target q2 = {};
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001400
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001401 switch (pai->ai_family) {
Bernie Innocenti9c575932018-09-07 21:10:25 +09001402 case AF_UNSPEC: {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001403 /* prefer IPv6 */
1404 q.name = name;
1405 q.qclass = C_IN;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001406 int query_ipv6 = 1, query_ipv4 = 1;
1407 if (pai->ai_flags & AI_ADDRCONFIG) {
Bernie Innocentic50c43d2019-03-05 15:45:03 +09001408 query_ipv6 = have_ipv6(netcontext->app_mark, netcontext->uid);
1409 query_ipv4 = have_ipv4(netcontext->app_mark, netcontext->uid);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001410 }
1411 if (query_ipv6) {
1412 q.qtype = T_AAAA;
1413 if (query_ipv4) {
1414 q.next = &q2;
1415 q2.name = name;
1416 q2.qclass = C_IN;
1417 q2.qtype = T_A;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001418 }
1419 } else if (query_ipv4) {
1420 q.qtype = T_A;
1421 } else {
Bernie Innocenti455c6232018-09-12 21:32:42 +09001422 return EAI_NODATA;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001423 }
1424 break;
Bernie Innocenti9c575932018-09-07 21:10:25 +09001425 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001426 case AF_INET:
1427 q.name = name;
1428 q.qclass = C_IN;
1429 q.qtype = T_A;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001430 break;
1431 case AF_INET6:
1432 q.name = name;
1433 q.qclass = C_IN;
1434 q.qtype = T_AAAA;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001435 break;
1436 default:
Bernie Innocenti455c6232018-09-12 21:32:42 +09001437 return EAI_FAMILY;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001438 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001439
Bernie Innocenti08487112019-10-11 21:14:13 +09001440 ResState res;
1441 res_init(&res, netcontext, event);
Mike Yubfb1b342018-11-06 15:42:36 +08001442
Hungming Chena6914a62019-01-19 15:07:04 +08001443 int he;
Bernie Innocenti08487112019-10-11 21:14:13 +09001444 if (res_searchN(name, &q, &res, &he) < 0) {
Hungming Chena6914a62019-01-19 15:07:04 +08001445 // Return h_errno (he) to catch more detailed errors rather than EAI_NODATA.
1446 // Note that res_searchN() doesn't set the pair NETDB_INTERNAL and errno.
1447 // See also herrnoToAiErrno().
1448 return herrnoToAiErrno(he);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001449 }
Bernie Innocentic50c43d2019-03-05 15:45:03 +09001450
1451 addrinfo sentinel = {};
1452 addrinfo* cur = &sentinel;
Luke Huangc98fd802019-10-15 16:36:36 +09001453 addrinfo* ai = getanswer(q.answer, q.n, q.name, q.qtype, pai, &he);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001454 if (ai) {
1455 cur->ai_next = ai;
1456 while (cur && cur->ai_next) cur = cur->ai_next;
1457 }
1458 if (q.next) {
Luke Huangc98fd802019-10-15 16:36:36 +09001459 ai = getanswer(q2.answer, q2.n, q2.name, q2.qtype, pai, &he);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001460 if (ai) cur->ai_next = ai;
1461 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001462 if (sentinel.ai_next == NULL) {
Hungming Chena6914a62019-01-19 15:07:04 +08001463 // Note that getanswer() doesn't set the pair NETDB_INTERNAL and errno.
1464 // See also herrnoToAiErrno().
1465 return herrnoToAiErrno(he);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001466 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001467
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001468 _rfc6724_sort(&sentinel, netcontext->app_mark, netcontext->uid);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001469
Bernie Innocenti455c6232018-09-12 21:32:42 +09001470 *rv = sentinel.ai_next;
1471 return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001472}
1473
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001474static void _sethtent(FILE** hostf) {
1475 if (!*hostf)
1476 *hostf = fopen(_PATH_HOSTS, "re");
1477 else
1478 rewind(*hostf);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001479}
1480
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001481static void _endhtent(FILE** hostf) {
1482 if (*hostf) {
1483 (void) fclose(*hostf);
1484 *hostf = NULL;
1485 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001486}
1487
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001488static struct addrinfo* _gethtent(FILE** hostf, const char* name, const struct addrinfo* pai) {
1489 char* p;
1490 char *cp, *tname, *cname;
Bernie Innocentie2bc46f2018-10-16 23:35:28 +09001491 struct addrinfo *res0, *res;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001492 int error;
1493 const char* addr;
1494 char hostbuf[8 * 1024];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001495
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001496 assert(name != NULL);
1497 assert(pai != NULL);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001498
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001499 if (!*hostf && !(*hostf = fopen(_PATH_HOSTS, "re"))) return (NULL);
1500again:
1501 if (!(p = fgets(hostbuf, sizeof hostbuf, *hostf))) return (NULL);
1502 if (*p == '#') goto again;
1503 if (!(cp = strpbrk(p, "#\n"))) goto again;
1504 *cp = '\0';
1505 if (!(cp = strpbrk(p, " \t"))) goto again;
1506 *cp++ = '\0';
1507 addr = p;
1508 /* if this is not something we're looking for, skip it. */
1509 cname = NULL;
1510 while (cp && *cp) {
1511 if (*cp == ' ' || *cp == '\t') {
1512 cp++;
1513 continue;
1514 }
1515 if (!cname) cname = cp;
1516 tname = cp;
1517 if ((cp = strpbrk(cp, " \t")) != NULL) *cp++ = '\0';
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001518 if (strcasecmp(name, tname) == 0) goto found;
1519 }
1520 goto again;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001521
1522found:
Bernie Innocentie2bc46f2018-10-16 23:35:28 +09001523 error = getaddrinfo_numeric(addr, nullptr, *pai, &res0);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001524 if (error) goto again;
1525 for (res = res0; res; res = res->ai_next) {
1526 /* cover it up */
1527 res->ai_flags = pai->ai_flags;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001528
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001529 if (pai->ai_flags & AI_CANONNAME) {
1530 if (get_canonname(pai, res, cname) != 0) {
1531 freeaddrinfo(res0);
1532 goto again;
1533 }
1534 }
1535 }
1536 return res0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001537}
1538
chenbrucefd837fa2019-10-29 18:35:36 +08001539static struct addrinfo* getCustomHosts(const size_t netid, const char* _Nonnull name,
1540 const struct addrinfo* _Nonnull pai) {
1541 struct addrinfo sentinel = {};
1542 struct addrinfo *res0, *res;
1543 res = &sentinel;
1544 std::vector<std::string> hosts = getCustomizedTableByName(netid, name);
1545 for (const std::string& host : hosts) {
1546 int error = getaddrinfo_numeric(host.c_str(), nullptr, *pai, &res0);
1547 if (!error && res0 != nullptr) {
1548 res->ai_next = res0;
1549 res = res0;
1550 res0 = nullptr;
1551 }
1552 }
1553 return sentinel.ai_next;
1554}
1555
1556static bool files_getaddrinfo(const size_t netid, const char* name, const addrinfo* pai,
1557 addrinfo** res) {
Ken Chene0d73c92018-11-07 01:20:48 +08001558 struct addrinfo sentinel = {};
1559 struct addrinfo *p, *cur;
chenbrucefd837fa2019-10-29 18:35:36 +08001560 FILE* hostf = nullptr;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001561
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001562 cur = &sentinel;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001563 _sethtent(&hostf);
chenbrucefd837fa2019-10-29 18:35:36 +08001564 while ((p = _gethtent(&hostf, name, pai)) != nullptr) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001565 cur->ai_next = p;
1566 while (cur && cur->ai_next) cur = cur->ai_next;
1567 }
1568 _endhtent(&hostf);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001569
chenbrucefd837fa2019-10-29 18:35:36 +08001570 if ((p = getCustomHosts(netid, name, pai)) != nullptr) {
1571 cur->ai_next = p;
1572 }
1573
Bernie Innocenti455c6232018-09-12 21:32:42 +09001574 *res = sentinel.ai_next;
chenbrucefd837fa2019-10-29 18:35:36 +08001575 return sentinel.ai_next != nullptr;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001576}
1577
1578/* resolver logic */
1579
Luke Huang0a0870d2020-02-12 20:41:10 +08001580namespace {
1581
1582constexpr int SLEEP_TIME_MS = 2;
1583
1584int getHerrnoFromRcode(int rcode) {
1585 switch (rcode) {
1586 // Not defined in RFC.
1587 case RCODE_TIMEOUT:
1588 // DNS metrics monitors DNS query timeout.
1589 return NETD_RESOLV_H_ERRNO_EXT_TIMEOUT; // extended h_errno.
1590 // Defined in RFC 1035 section 4.1.1.
1591 case NXDOMAIN:
1592 return HOST_NOT_FOUND;
1593 case SERVFAIL:
1594 return TRY_AGAIN;
1595 case NOERROR:
1596 return NO_DATA;
1597 case FORMERR:
1598 case NOTIMP:
1599 case REFUSED:
1600 default:
1601 return NO_RECOVERY;
1602 }
1603}
1604
1605struct QueryResult {
1606 int ancount;
1607 int rcode;
1608 int herrno;
1609 NetworkDnsEventReported event;
1610};
1611
1612QueryResult doQuery(const char* name, res_target* t, res_state res) {
1613 HEADER* hp = (HEADER*)(void*)t->answer.data();
1614
1615 hp->rcode = NOERROR; // default
1616
1617 const int cl = t->qclass;
1618 const int type = t->qtype;
1619 const int anslen = t->answer.size();
1620
1621 LOG(DEBUG) << __func__ << ": (" << cl << ", " << type << ")";
1622
1623 uint8_t buf[MAXPACKET];
1624
1625 int n = res_nmkquery(QUERY, name, cl, type, /*data=*/nullptr, /*datalen=*/0, buf, sizeof(buf),
1626 res->netcontext_flags);
1627
1628 if (n > 0 &&
1629 (res->netcontext_flags & (NET_CONTEXT_FLAG_USE_DNS_OVER_TLS | NET_CONTEXT_FLAG_USE_EDNS))) {
1630 n = res_nopt(res, n, buf, sizeof(buf), anslen);
1631 }
1632
1633 NetworkDnsEventReported event;
1634 if (n <= 0) {
1635 LOG(ERROR) << __func__ << ": res_nmkquery failed";
1636 return {0, -1, NO_RECOVERY, event};
1637 return {
1638 .ancount = 0,
1639 .rcode = -1,
1640 .herrno = NO_RECOVERY,
1641 .event = event,
1642 };
1643 }
1644
1645 ResState res_temp = fromResState(*res, &event);
1646
1647 int rcode = NOERROR;
1648 n = res_nsend(&res_temp, buf, n, t->answer.data(), anslen, &rcode, 0);
1649 if (n < 0 || hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
1650 // if the query choked with EDNS0, retry without EDNS0
1651 if ((res_temp.netcontext_flags &
1652 (NET_CONTEXT_FLAG_USE_DNS_OVER_TLS | NET_CONTEXT_FLAG_USE_EDNS)) &&
1653 (res_temp._flags & RES_F_EDNS0ERR)) {
1654 LOG(DEBUG) << __func__ << ": retry without EDNS0";
1655 n = res_nmkquery(QUERY, name, cl, type, /*data=*/nullptr, /*datalen=*/0, buf,
1656 sizeof(buf), res->netcontext_flags);
1657 n = res_nsend(&res_temp, buf, n, t->answer.data(), anslen, &rcode, 0);
1658 }
1659 }
1660
1661 LOG(DEBUG) << __func__ << ": rcode=" << hp->rcode << ", ancount=" << ntohs(hp->ancount);
1662
1663 t->n = n;
1664 return {
1665 .ancount = ntohs(hp->ancount),
1666 .rcode = rcode,
1667 .event = event,
1668 };
1669}
1670
1671} // namespace
1672
1673static int res_queryN_parallel(const char* name, res_target* target, res_state res, int* herrno) {
1674 std::vector<std::future<QueryResult>> results;
1675 results.reserve(2);
1676 for (res_target* t = target; t; t = t->next) {
1677 results.emplace_back(std::async(std::launch::async, doQuery, name, t, res));
1678 // Avoiding gateways drop packets if queries are sent too close together
Luke Huangf40df9c2020-04-21 08:51:48 +08001679 int sleepTime = android::net::Experiments::getInstance()->getFlag(
1680 "parallel_lookup_sleep_time", SLEEP_TIME_MS);
1681 if (sleepTime > 1000) sleepTime = 1000;
1682 if (t->next) usleep(sleepTime * 1000);
Luke Huang0a0870d2020-02-12 20:41:10 +08001683 }
1684
1685 int ancount = 0;
1686 int rcode = 0;
1687
1688 for (auto& f : results) {
1689 const QueryResult& r = f.get();
1690 if (r.herrno == NO_RECOVERY) {
1691 *herrno = r.herrno;
1692 return -1;
1693 }
1694 res->event->MergeFrom(r.event);
1695 ancount += r.ancount;
1696 rcode = r.rcode;
1697 }
1698
1699 if (ancount == 0) {
1700 *herrno = getHerrnoFromRcode(rcode);
1701 return -1;
1702 }
1703
1704 return ancount;
1705}
1706
1707static int res_queryN_wrapper(const char* name, res_target* target, res_state res, int* herrno) {
Luke Huangf40df9c2020-04-21 08:51:48 +08001708 const bool parallel_lookup =
1709 android::net::Experiments::getInstance()->getFlag("parallel_lookup", 0);
Luke Huang0a0870d2020-02-12 20:41:10 +08001710 if (parallel_lookup) return res_queryN_parallel(name, target, res, herrno);
1711
1712 return res_queryN(name, target, res, herrno);
1713}
1714
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001715/*
1716 * Formulate a normal query, send, and await answer.
1717 * Returned answer is placed in supplied buffer "answer".
1718 * Perform preliminary check of answer, returning success only
1719 * if no error is indicated and the answer count is nonzero.
1720 * Return the size of the response on success, -1 on error.
Hungming Chendd4bfb92018-12-25 15:47:47 +08001721 * Error number is left in *herrno.
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001722 *
1723 * Caller must parse answer and determine whether it answers the question.
1724 */
Hungming Chen947aab02018-12-27 18:33:19 +08001725static int res_queryN(const char* name, res_target* target, res_state res, int* herrno) {
chenbrucec51f1212019-09-12 16:59:33 +08001726 uint8_t buf[MAXPACKET];
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001727 int n;
1728 struct res_target* t;
1729 int rcode;
1730 int ancount;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001731
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001732 assert(name != NULL);
1733 /* XXX: target may be NULL??? */
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001734
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001735 rcode = NOERROR;
1736 ancount = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001737
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001738 for (t = target; t; t = t->next) {
Luke Huangc98fd802019-10-15 16:36:36 +09001739 HEADER* hp = (HEADER*)(void*)t->answer.data();
Ken Chen0a015532019-01-02 14:59:38 +08001740 bool retried = false;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001741 again:
1742 hp->rcode = NOERROR; /* default */
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001743
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001744 /* make it easier... */
Bernie Innocenti9c575932018-09-07 21:10:25 +09001745 int cl = t->qclass;
1746 int type = t->qtype;
Luke Huangc98fd802019-10-15 16:36:36 +09001747 const int anslen = t->answer.size();
chenbruceacb832c2019-02-20 19:45:50 +08001748
Ken Chenffc224a2019-03-19 17:41:28 +08001749 LOG(DEBUG) << __func__ << ": (" << cl << ", " << type << ")";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001750
Bernie Innocenti08487112019-10-11 21:14:13 +09001751 n = res_nmkquery(QUERY, name, cl, type, /*data=*/nullptr, /*datalen=*/0, buf, sizeof(buf),
1752 res->netcontext_flags);
chenbruced8cbb9b2019-06-20 18:25:28 +08001753 if (n > 0 &&
1754 (res->netcontext_flags &
1755 (NET_CONTEXT_FLAG_USE_DNS_OVER_TLS | NET_CONTEXT_FLAG_USE_EDNS)) &&
1756 !retried) // TODO: remove the retry flag and provide a sufficient test coverage.
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001757 n = res_nopt(res, n, buf, sizeof(buf), anslen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001758 if (n <= 0) {
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001759 LOG(ERROR) << __func__ << ": res_nmkquery failed";
Hungming Chendd4bfb92018-12-25 15:47:47 +08001760 *herrno = NO_RECOVERY;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001761 return n;
1762 }
Mike Yubfb1b342018-11-06 15:42:36 +08001763
Luke Huangc98fd802019-10-15 16:36:36 +09001764 n = res_nsend(res, buf, n, t->answer.data(), anslen, &rcode, 0);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001765 if (n < 0 || hp->rcode != NOERROR || ntohs(hp->ancount) == 0) {
Hungming Chen947aab02018-12-27 18:33:19 +08001766 // Record rcode from DNS response header only if no timeout.
1767 // Keep rcode timeout for reporting later if any.
chenbruced8cbb9b2019-06-20 18:25:28 +08001768 if (rcode != RCODE_TIMEOUT) rcode = hp->rcode; // record most recent error
1769 // if the query choked with EDNS0, retry without EDNS0 that when the server
1770 // has no response, resovler won't retry and do nothing. Even fallback to UDP,
1771 // we also has the same symptom if EDNS is enabled.
1772 if ((res->netcontext_flags &
1773 (NET_CONTEXT_FLAG_USE_DNS_OVER_TLS | NET_CONTEXT_FLAG_USE_EDNS)) &&
Ken Chen0a015532019-01-02 14:59:38 +08001774 (res->_flags & RES_F_EDNS0ERR) && !retried) {
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001775 LOG(DEBUG) << __func__ << ": retry without EDNS0";
Ken Chen0a015532019-01-02 14:59:38 +08001776 retried = true;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001777 goto again;
1778 }
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001779 LOG(DEBUG) << __func__ << ": rcode=" << hp->rcode << ", ancount=" << ntohs(hp->ancount);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001780 continue;
1781 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001782
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001783 ancount += ntohs(hp->ancount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001784
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001785 t->n = n;
1786 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001787
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001788 if (ancount == 0) {
Luke Huang0a0870d2020-02-12 20:41:10 +08001789 *herrno = getHerrnoFromRcode(rcode);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001790 return -1;
1791 }
1792 return ancount;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001793}
1794
1795/*
1796 * Formulate a normal query, send, and retrieve answer in supplied buffer.
1797 * Return the size of the response on success, -1 on error.
1798 * If enabled, implement search rules until answer or unrecoverable failure
Hungming Chendd4bfb92018-12-25 15:47:47 +08001799 * is detected. Error code, if any, is left in *herrno.
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001800 */
Hungming Chen947aab02018-12-27 18:33:19 +08001801static int res_searchN(const char* name, res_target* target, res_state res, int* herrno) {
Luke Huang2dac4382019-06-24 13:28:44 +08001802 const char* cp;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001803 HEADER* hp;
chenbrucec51f1212019-09-12 16:59:33 +08001804 uint32_t dots;
chenbruce018fdb22019-06-12 18:08:04 +08001805 int ret, saved_herrno;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001806 int got_nodata = 0, got_servfail = 0, tried_as_is = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001807
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001808 assert(name != NULL);
1809 assert(target != NULL);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001810
Luke Huangc98fd802019-10-15 16:36:36 +09001811 hp = (HEADER*)(void*)target->answer.data();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001812
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001813 errno = 0;
Hungming Chendd4bfb92018-12-25 15:47:47 +08001814 *herrno = HOST_NOT_FOUND; /* default, if we never query */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001815 dots = 0;
1816 for (cp = name; *cp; cp++) dots += (*cp == '.');
chenbruce018fdb22019-06-12 18:08:04 +08001817 const bool trailing_dot = (cp > name && *--cp == '.') ? true : false;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001818
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001819 /*
1820 * If there are dots in the name already, let's just give it a try
1821 * 'as is'. The threshold can be set with the "ndots" option.
1822 */
1823 saved_herrno = -1;
1824 if (dots >= res->ndots) {
Hungming Chen947aab02018-12-27 18:33:19 +08001825 ret = res_querydomainN(name, NULL, target, res, herrno);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001826 if (ret > 0) return (ret);
Hungming Chendd4bfb92018-12-25 15:47:47 +08001827 saved_herrno = *herrno;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001828 tried_as_is++;
1829 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001830
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001831 /*
1832 * We do at least one level of search if
chenbruce018fdb22019-06-12 18:08:04 +08001833 * - there is no dot, or
1834 * - there is at least one dot and there is no trailing dot.
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001835 */
chenbruce018fdb22019-06-12 18:08:04 +08001836 if ((!dots) || (dots && !trailing_dot)) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001837 int done = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001838
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001839 /* Unfortunately we need to set stuff up before
1840 * the domain stuff is tried. Will have a better
1841 * fix after thread pools are used.
1842 */
Mike Yu021c3e12019-10-08 17:29:34 +08001843 resolv_populate_res_for_net(res);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001844
Luke Huang2dac4382019-06-24 13:28:44 +08001845 for (const auto& domain : res->search_domains) {
1846 ret = res_querydomainN(name, domain.c_str(), target, res, herrno);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001847 if (ret > 0) return ret;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001848
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001849 /*
1850 * If no server present, give up.
1851 * If name isn't found in this domain,
1852 * keep trying higher domains in the search list
1853 * (if that's enabled).
1854 * On a NO_DATA error, keep trying, otherwise
1855 * a wildcard entry of another type could keep us
1856 * from finding this entry higher in the domain.
1857 * If we get some other error (negative answer or
1858 * server failure), then stop searching up,
1859 * but try the input name below in case it's
1860 * fully-qualified.
1861 */
1862 if (errno == ECONNREFUSED) {
Hungming Chendd4bfb92018-12-25 15:47:47 +08001863 *herrno = TRY_AGAIN;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001864 return -1;
1865 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001866
Hungming Chendd4bfb92018-12-25 15:47:47 +08001867 switch (*herrno) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001868 case NO_DATA:
1869 got_nodata++;
Bernie Innocentif40b3bd2018-10-10 22:30:12 +09001870 [[fallthrough]];
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001871 case HOST_NOT_FOUND:
1872 /* keep trying */
1873 break;
1874 case TRY_AGAIN:
1875 if (hp->rcode == SERVFAIL) {
1876 /* try next search element, if any */
1877 got_servfail++;
1878 break;
1879 }
Bernie Innocentif40b3bd2018-10-10 22:30:12 +09001880 [[fallthrough]];
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001881 default:
1882 /* anything else implies that we're done */
1883 done++;
1884 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001885 }
1886 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001887
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001888 /*
1889 * if we have not already tried the name "as is", do that now.
1890 * note that we do this regardless of how many dots were in the
1891 * name or whether it ends with a dot.
1892 */
1893 if (!tried_as_is) {
Hungming Chen947aab02018-12-27 18:33:19 +08001894 ret = res_querydomainN(name, NULL, target, res, herrno);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001895 if (ret > 0) return ret;
1896 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001897
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001898 /*
1899 * if we got here, we didn't satisfy the search.
1900 * if we did an initial full query, return that query's h_errno
1901 * (note that we wouldn't be here if that query had succeeded).
1902 * else if we ever got a nodata, send that back as the reason.
1903 * else send back meaningless h_errno, that being the one from
1904 * the last DNSRCH we did.
1905 */
1906 if (saved_herrno != -1)
Hungming Chendd4bfb92018-12-25 15:47:47 +08001907 *herrno = saved_herrno;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001908 else if (got_nodata)
Hungming Chendd4bfb92018-12-25 15:47:47 +08001909 *herrno = NO_DATA;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001910 else if (got_servfail)
Hungming Chendd4bfb92018-12-25 15:47:47 +08001911 *herrno = TRY_AGAIN;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001912 return -1;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001913}
1914
Luke Huang0a0870d2020-02-12 20:41:10 +08001915// Perform a call on res_query on the concatenation of name and domain,
1916// removing a trailing dot from name if domain is NULL.
Mike Yubfb1b342018-11-06 15:42:36 +08001917static int res_querydomainN(const char* name, const char* domain, res_target* target, res_state res,
Hungming Chen947aab02018-12-27 18:33:19 +08001918 int* herrno) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001919 char nbuf[MAXDNAME];
1920 const char* longname = nbuf;
1921 size_t n, d;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001922
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001923 assert(name != NULL);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001924
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001925 if (domain == NULL) {
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001926 // Check for trailing '.'; copy without '.' if present.
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001927 n = strlen(name);
1928 if (n + 1 > sizeof(nbuf)) {
Hungming Chendd4bfb92018-12-25 15:47:47 +08001929 *herrno = NO_RECOVERY;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001930 return -1;
1931 }
1932 if (n > 0 && name[--n] == '.') {
1933 strncpy(nbuf, name, n);
1934 nbuf[n] = '\0';
1935 } else
1936 longname = name;
1937 } else {
1938 n = strlen(name);
1939 d = strlen(domain);
1940 if (n + 1 + d + 1 > sizeof(nbuf)) {
Hungming Chendd4bfb92018-12-25 15:47:47 +08001941 *herrno = NO_RECOVERY;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001942 return -1;
1943 }
1944 snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain);
1945 }
Luke Huang0a0870d2020-02-12 20:41:10 +08001946 return res_queryN_wrapper(longname, target, res, herrno);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001947}