blob: f40ee2d43da5d3b71ff4655dc0c34dbadf309d3b [file] [log] [blame]
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001/* $NetBSD: res_send.c,v 1.9 2006/01/24 17:41:25 christos Exp $ */
2
3/*
4 * Copyright (c) 1985, 1989, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. All advertising materials mentioning features or use of this software
16 * must display the following acknowledgement:
17 * This product includes software developed by the University of
18 * California, Berkeley and its contributors.
19 * 4. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 */
35
36/*
37 * Portions Copyright (c) 1993 by Digital Equipment Corporation.
38 *
39 * Permission to use, copy, modify, and distribute this software for any
40 * purpose with or without fee is hereby granted, provided that the above
41 * copyright notice and this permission notice appear in all copies, and that
42 * the name of Digital Equipment Corporation not be used in advertising or
43 * publicity pertaining to distribution of the document or software without
44 * specific, written prior permission.
45 *
46 * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
47 * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
48 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
49 * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
50 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
51 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
52 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
53 * SOFTWARE.
54 */
55
56/*
57 * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
58 * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
59 *
60 * Permission to use, copy, modify, and distribute this software for any
61 * purpose with or without fee is hereby granted, provided that the above
62 * copyright notice and this permission notice appear in all copies.
63 *
64 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
65 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
66 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR
67 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
68 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
69 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
70 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
71 */
72
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090073/*
74 * Send query to name server and wait for reply.
75 */
76
Ken Chen5471dca2019-04-15 15:25:35 +080077#define LOG_TAG "resolv"
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +090078
Luke Huangd1d734f2020-04-30 12:25:40 +080079#include <chrono>
80
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090081#include <sys/param.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090082#include <sys/socket.h>
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090083#include <sys/time.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090084#include <sys/uio.h>
85
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090086#include <arpa/inet.h>
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090087#include <arpa/nameser.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090088
89#include <errno.h>
90#include <fcntl.h>
91#include <netdb.h>
92#include <poll.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090093#include <signal.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090094#include <stdlib.h>
95#include <string.h>
96#include <time.h>
97#include <unistd.h>
chenbruceceb3c022021-06-15 21:36:19 +080098#include <span>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090099
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900100#include <android-base/logging.h>
Luke Huang420ee622019-11-27 17:52:44 +0800101#include <android-base/result.h>
Bernie Innocenti758005f2019-02-19 18:08:36 +0900102#include <android/multinetwork.h> // ResNsendFlags
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900103
Mike Yub601ff72018-11-01 20:07:00 +0800104#include <netdutils/Slice.h>
lifr94981782019-05-17 21:15:19 +0800105#include <netdutils/Stopwatch.h>
Bernie Innocentiec4219b2019-01-30 11:16:36 +0900106#include "DnsTlsDispatcher.h"
107#include "DnsTlsTransport.h"
Luke Huangf40df9c2020-04-21 08:51:48 +0800108#include "Experiments.h"
Bernie Innocentiec4219b2019-01-30 11:16:36 +0900109#include "PrivateDnsConfiguration.h"
Bernie Innocentiac18b122018-10-01 23:10:18 +0900110#include "netd_resolv/resolv.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900111#include "private/android_filesystem_config.h"
Bernie Innocenti10a90282020-01-23 23:28:00 +0900112
113#include "res_comp.h"
Mike Yu34433c62019-08-20 20:17:36 +0800114#include "res_debug.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900115#include "resolv_cache.h"
Ken Chen99c0b322019-11-20 14:24:09 +0800116#include "stats.h"
lifr94981782019-05-17 21:15:19 +0800117#include "stats.pb.h"
Mike Yu021c3e12019-10-08 17:29:34 +0800118#include "util.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900119
Luke Huangd1d734f2020-04-30 12:25:40 +0800120using namespace std::chrono_literals;
Mike Yub601ff72018-11-01 20:07:00 +0800121// TODO: use the namespace something like android::netd_resolv for libnetd_resolv
Luke Huang420ee622019-11-27 17:52:44 +0800122using android::base::ErrnoError;
123using android::base::Result;
chenbruceceb3c022021-06-15 21:36:19 +0800124using android::base::unique_fd;
chenbruce99cbfd82019-09-05 15:08:13 +0800125using android::net::CacheStatus;
126using android::net::DnsQueryEvent;
127using android::net::DnsTlsDispatcher;
128using android::net::DnsTlsTransport;
chenbruce99cbfd82019-09-05 15:08:13 +0800129using android::net::IpVersion;
130using android::net::IV_IPV4;
131using android::net::IV_IPV6;
132using android::net::IV_UNKNOWN;
Luke Huang23d55192020-04-16 11:47:30 +0800133using android::net::LinuxErrno;
lifr94981782019-05-17 21:15:19 +0800134using android::net::NetworkDnsEventReported;
chenbruce99cbfd82019-09-05 15:08:13 +0800135using android::net::NS_T_INVALID;
136using android::net::NsRcode;
137using android::net::NsType;
Mike Yu60248242020-07-29 16:45:26 +0800138using android::net::PrivateDnsConfiguration;
chenbruce99cbfd82019-09-05 15:08:13 +0800139using android::net::PrivateDnsMode;
140using android::net::PrivateDnsModes;
141using android::net::PrivateDnsStatus;
142using android::net::PROTO_TCP;
143using android::net::PROTO_UDP;
Mike Yue655b1d2019-08-28 17:49:59 +0800144using android::netdutils::IPSockAddr;
Bernie Innocentiec4219b2019-01-30 11:16:36 +0900145using android::netdutils::Slice;
lifr94981782019-05-17 21:15:19 +0800146using android::netdutils::Stopwatch;
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900147
chenbruceceb3c022021-06-15 21:36:19 +0800148const std::vector<IPSockAddr> mdns_addrs = {IPSockAddr::toIPSockAddr("ff02::fb", 5353),
149 IPSockAddr::toIPSockAddr("224.0.0.251", 5353)};
150
151static int setupUdpSocket(ResState* statp, const sockaddr* sockap, unique_fd* fd_out, int* terrno);
Mike Yue48f7b52020-02-10 14:55:06 +0800152static int send_dg(res_state statp, res_params* params, const uint8_t* buf, int buflen,
Luke Huang420ee622019-11-27 17:52:44 +0800153 uint8_t* ans, int anssiz, int* terrno, size_t* ns, int* v_circuit,
Mike Yue48f7b52020-02-10 14:55:06 +0800154 int* gotsomewhere, time_t* at, int* rcode, int* delay);
chenbruceceb3c022021-06-15 21:36:19 +0800155static int send_vc(res_state statp, res_params* params, const uint8_t* buf, int buflen,
156 uint8_t* ans, int anssiz, int* terrno, size_t ns, time_t* at, int* rcode,
157 int* delay);
158static int send_mdns(ResState* statp, std::span<const uint8_t> buf, uint8_t* ans, int anssiz,
159 int* terrno, int* rcode);
chenbruce76620642021-06-15 18:39:27 +0800160static void dump_error(const char*, const struct sockaddr*);
chenbruceacb832c2019-02-20 19:45:50 +0800161
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900162static int sock_eq(struct sockaddr*, struct sockaddr*);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900163static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
164 const struct timespec timeout);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900165static int retrying_poll(const int sock, short events, const struct timespec* finish);
Luke Huangd7aa7b42018-11-21 20:37:50 +0800166static int res_tls_send(res_state, const Slice query, const Slice answer, int* rcode,
Mike Yubfb1b342018-11-06 15:42:36 +0800167 bool* fallback);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900168
lifr94981782019-05-17 21:15:19 +0800169NsType getQueryType(const uint8_t* msg, size_t msgLen) {
170 ns_msg handle;
171 ns_rr rr;
172 if (ns_initparse((const uint8_t*)msg, msgLen, &handle) < 0 ||
173 ns_parserr(&handle, ns_s_qd, 0, &rr) < 0) {
174 return NS_T_INVALID;
175 }
176 return static_cast<NsType>(ns_rr_type(rr));
177}
178
179IpVersion ipFamilyToIPVersion(const int ipFamily) {
180 switch (ipFamily) {
181 case AF_INET:
182 return IV_IPV4;
183 case AF_INET6:
184 return IV_IPV6;
185 default:
186 return IV_UNKNOWN;
187 }
188}
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900189
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900190// BEGIN: Code copied from ISC eventlib
191// TODO: move away from this code
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900192#define BILLION 1000000000
193
194static struct timespec evConsTime(time_t sec, long nsec) {
195 struct timespec x;
196
197 x.tv_sec = sec;
198 x.tv_nsec = nsec;
199 return (x);
200}
201
202static struct timespec evAddTime(struct timespec addend1, struct timespec addend2) {
203 struct timespec x;
204
205 x.tv_sec = addend1.tv_sec + addend2.tv_sec;
206 x.tv_nsec = addend1.tv_nsec + addend2.tv_nsec;
207 if (x.tv_nsec >= BILLION) {
208 x.tv_sec++;
209 x.tv_nsec -= BILLION;
210 }
211 return (x);
212}
213
214static struct timespec evSubTime(struct timespec minuend, struct timespec subtrahend) {
215 struct timespec x;
216
217 x.tv_sec = minuend.tv_sec - subtrahend.tv_sec;
218 if (minuend.tv_nsec >= subtrahend.tv_nsec)
219 x.tv_nsec = minuend.tv_nsec - subtrahend.tv_nsec;
220 else {
221 x.tv_nsec = BILLION - subtrahend.tv_nsec + minuend.tv_nsec;
222 x.tv_sec--;
223 }
224 return (x);
225}
226
227static int evCmpTime(struct timespec a, struct timespec b) {
228#define SGN(x) ((x) < 0 ? (-1) : (x) > 0 ? (1) : (0));
229 time_t s = a.tv_sec - b.tv_sec;
230 long n;
231
232 if (s != 0) return SGN(s);
233
234 n = a.tv_nsec - b.tv_nsec;
235 return SGN(n);
236}
237
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900238static struct timespec evNowTime(void) {
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900239 struct timespec tsnow;
Bernie Innocentic1834822018-08-31 16:11:41 +0900240 clock_gettime(CLOCK_REALTIME, &tsnow);
241 return tsnow;
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900242}
243
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900244// END: Code copied from ISC eventlib
245
lifr94981782019-05-17 21:15:19 +0800246/* BIONIC-BEGIN: implement source port randomization */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900247static int random_bind(int s, int family) {
nuccachenb980f2f2018-10-23 17:10:58 +0800248 sockaddr_union u;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900249 int j;
250 socklen_t slen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900251
252 /* clear all, this also sets the IP4/6 address to 'any' */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900253 memset(&u, 0, sizeof u);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900254
255 switch (family) {
256 case AF_INET:
257 u.sin.sin_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900258 slen = sizeof u.sin;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900259 break;
260 case AF_INET6:
261 u.sin6.sin6_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900262 slen = sizeof u.sin6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900263 break;
264 default:
265 errno = EPROTO;
266 return -1;
267 }
268
269 /* first try to bind to a random source port a few times */
270 for (j = 0; j < 10; j++) {
271 /* find a random port between 1025 .. 65534 */
Luke Huangdda920f2019-02-13 14:05:02 +0800272 int port = 1025 + (arc4random_uniform(65535 - 1025));
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900273 if (family == AF_INET)
274 u.sin.sin_port = htons(port);
275 else
276 u.sin6.sin6_port = htons(port);
277
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900278 if (!bind(s, &u.sa, slen)) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900279 }
280
Bernie Innocenti9c575932018-09-07 21:10:25 +0900281 // nothing after 10 attempts, our network table is probably busy
282 // let the system decide which port is best
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900283 if (family == AF_INET)
284 u.sin.sin_port = 0;
285 else
286 u.sin6.sin6_port = 0;
287
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900288 return bind(s, &u.sa, slen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900289}
290/* BIONIC-END */
291
Luke Huang70931aa2019-01-31 11:57:41 +0800292// Disables all nameservers other than selectedServer
293static void res_set_usable_server(int selectedServer, int nscount, bool usable_servers[]) {
294 int usableIndex = 0;
295 for (int ns = 0; ns < nscount; ns++) {
296 if (usable_servers[ns]) ++usableIndex;
297 if (usableIndex != selectedServer) usable_servers[ns] = false;
298 }
299}
300
Luke Huang420ee622019-11-27 17:52:44 +0800301// Looks up the nameserver address in res.nsaddrs[], returns the ns number if found, otherwise -1.
302static int res_ourserver_p(res_state statp, const sockaddr* sa) {
Bernie Innocenti2e8540b2018-09-26 11:52:04 +0900303 const sockaddr_in *inp, *srv;
304 const sockaddr_in6 *in6p, *srv6;
Luke Huang420ee622019-11-27 17:52:44 +0800305 int ns = 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900306 switch (sa->sa_family) {
307 case AF_INET:
308 inp = (const struct sockaddr_in*) (const void*) sa;
Luke Huang420ee622019-11-27 17:52:44 +0800309
Mike Yue48f7b52020-02-10 14:55:06 +0800310 for (const IPSockAddr& ipsa : statp->nsaddrs) {
311 sockaddr_storage ss = ipsa;
312 srv = reinterpret_cast<sockaddr_in*>(&ss);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900313 if (srv->sin_family == inp->sin_family && srv->sin_port == inp->sin_port &&
314 (srv->sin_addr.s_addr == INADDR_ANY ||
315 srv->sin_addr.s_addr == inp->sin_addr.s_addr))
Luke Huang420ee622019-11-27 17:52:44 +0800316 return ns;
317 ++ns;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900318 }
319 break;
320 case AF_INET6:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900321 in6p = (const struct sockaddr_in6*) (const void*) sa;
Mike Yue48f7b52020-02-10 14:55:06 +0800322 for (const IPSockAddr& ipsa : statp->nsaddrs) {
323 sockaddr_storage ss = ipsa;
324 srv6 = reinterpret_cast<sockaddr_in6*>(&ss);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900325 if (srv6->sin6_family == in6p->sin6_family && srv6->sin6_port == in6p->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900326#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900327 (srv6->sin6_scope_id == 0 || srv6->sin6_scope_id == in6p->sin6_scope_id) &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900328#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900329 (IN6_IS_ADDR_UNSPECIFIED(&srv6->sin6_addr) ||
330 IN6_ARE_ADDR_EQUAL(&srv6->sin6_addr, &in6p->sin6_addr)))
Luke Huang420ee622019-11-27 17:52:44 +0800331 return ns;
332 ++ns;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900333 }
334 break;
335 default:
336 break;
337 }
Luke Huang420ee622019-11-27 17:52:44 +0800338 return -1;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900339}
340
341/* int
Bernie Innocenti9c575932018-09-07 21:10:25 +0900342 * res_nameinquery(name, type, cl, buf, eom)
343 * look for (name, type, cl) in the query section of packet (buf, eom)
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900344 * requires:
345 * buf + HFIXEDSZ <= eom
346 * returns:
347 * -1 : format error
348 * 0 : not found
349 * >0 : found
350 * author:
351 * paul vixie, 29may94
352 */
chenbrucec51f1212019-09-12 16:59:33 +0800353int res_nameinquery(const char* name, int type, int cl, const uint8_t* buf, const uint8_t* eom) {
354 const uint8_t* cp = buf + HFIXEDSZ;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900355 int qdcount = ntohs(((const HEADER*) (const void*) buf)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900356
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900357 while (qdcount-- > 0) {
358 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900359 int n = dn_expand(buf, eom, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900360 if (n < 0) return (-1);
361 cp += n;
362 if (cp + 2 * INT16SZ > eom) return (-1);
chenbruce0d470422019-03-28 18:44:37 +0800363 int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900364 cp += INT16SZ;
chenbruce0d470422019-03-28 18:44:37 +0800365 int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900366 cp += INT16SZ;
Bernie Innocenti9c575932018-09-07 21:10:25 +0900367 if (ttype == type && tclass == cl && ns_samename(tname, name) == 1) return (1);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900368 }
369 return (0);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900370}
371
372/* int
373 * res_queriesmatch(buf1, eom1, buf2, eom2)
374 * is there a 1:1 mapping of (name,type,class)
375 * in (buf1,eom1) and (buf2,eom2)?
376 * returns:
377 * -1 : format error
378 * 0 : not a 1:1 mapping
379 * >0 : is a 1:1 mapping
380 * author:
381 * paul vixie, 29may94
382 */
chenbrucec51f1212019-09-12 16:59:33 +0800383int res_queriesmatch(const uint8_t* buf1, const uint8_t* eom1, const uint8_t* buf2,
384 const uint8_t* eom2) {
385 const uint8_t* cp = buf1 + HFIXEDSZ;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900386 int qdcount = ntohs(((const HEADER*) (const void*) buf1)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900387
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900388 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2) return (-1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900389
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900390 /*
391 * Only header section present in replies to
392 * dynamic update packets.
393 */
394 if ((((const HEADER*) (const void*) buf1)->opcode == ns_o_update) &&
395 (((const HEADER*) (const void*) buf2)->opcode == ns_o_update))
396 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900397
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900398 if (qdcount != ntohs(((const HEADER*) (const void*) buf2)->qdcount)) return (0);
399 while (qdcount-- > 0) {
400 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900401 int n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900402 if (n < 0) return (-1);
403 cp += n;
404 if (cp + 2 * INT16SZ > eom1) return (-1);
chenbruce0d470422019-03-28 18:44:37 +0800405 int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900406 cp += INT16SZ;
chenbruce0d470422019-03-28 18:44:37 +0800407 int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900408 cp += INT16SZ;
409 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2)) return (0);
410 }
411 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900412}
413
lifr94981782019-05-17 21:15:19 +0800414static DnsQueryEvent* addDnsQueryEvent(NetworkDnsEventReported* event) {
415 return event->mutable_dns_query_events()->add_dns_query_event();
416}
417
Luke Huangeb618ef2020-05-26 14:17:02 +0800418static bool isNetworkRestricted(int terrno) {
419 // It's possible that system was in some network restricted mode, which blocked
420 // the operation of sending packet and resulted in EPERM errno.
421 // It would be no reason to keep retrying on that case.
422 // TODO: Check the system status to know if network restricted mode is
423 // enabled.
424 return (terrno == EPERM);
425}
426
chenbrucec51f1212019-09-12 16:59:33 +0800427int res_nsend(res_state statp, const uint8_t* buf, int buflen, uint8_t* ans, int anssiz, int* rcode,
Luke Huangd1d734f2020-04-30 12:25:40 +0800428 uint32_t flags, std::chrono::milliseconds sleepTimeMs) {
Luke Huang43cc1b12019-10-15 19:06:42 +0900429 LOG(DEBUG) << __func__;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900430
Luke Huang43cc1b12019-10-15 19:06:42 +0900431 // Should not happen
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900432 if (anssiz < HFIXEDSZ) {
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800433 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900434 errno = EINVAL;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800435 return -EINVAL;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900436 }
chenbrucedd210722019-03-06 13:52:43 +0800437 res_pquery(buf, buflen);
chenbruceacb832c2019-02-20 19:45:50 +0800438
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900439 int anslen = 0;
lifrd4d9fbb2019-07-31 20:18:35 +0800440 Stopwatch cacheStopwatch;
Luke Huang43cc1b12019-10-15 19:06:42 +0900441 ResolvCacheStatus cache_status =
442 resolv_cache_lookup(statp->netid, buf, buflen, ans, anssiz, &anslen, flags);
lifrd4d9fbb2019-07-31 20:18:35 +0800443 const int32_t cacheLatencyUs = saturate_cast<int32_t>(cacheStopwatch.timeTakenUs());
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900444 if (cache_status == RESOLV_CACHE_FOUND) {
Luke Huang83c9b4b2019-02-27 18:18:01 +0800445 HEADER* hp = (HEADER*)(void*)ans;
446 *rcode = hp->rcode;
lifr94981782019-05-17 21:15:19 +0800447 DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
448 dnsQueryEvent->set_latency_micros(cacheLatencyUs);
449 dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
lifre02d01c2019-12-31 17:24:57 +0800450 dnsQueryEvent->set_type(getQueryType(buf, buflen));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900451 return anslen;
452 } else if (cache_status != RESOLV_CACHE_UNSUPPORTED) {
453 // had a cache miss for a known network, so populate the thread private
454 // data so the normal resolve path can do its thing
Mike Yu021c3e12019-10-08 17:29:34 +0800455 resolv_populate_res_for_net(statp);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900456 }
chenbruceceb3c022021-06-15 21:36:19 +0800457
458 // MDNS
459 if (isMdnsResolution(statp->_flags)) {
460 // Use an impossible error code as default value.
461 int terrno = ETIME;
462 int resplen = 0;
463 *rcode = RCODE_INTERNAL_ERROR;
464 std::span<const uint8_t> buffer(buf, buflen);
465 resplen = send_mdns(statp, buffer, ans, anssiz, &terrno, rcode);
466
467 if (resplen <= 0) {
468 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
469 return -terrno;
470 }
471 LOG(DEBUG) << __func__ << ": got answer:";
472 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
473
474 if (cache_status == RESOLV_CACHE_NOTFOUND) {
475 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
476 }
477 return resplen;
478 }
479
Mike Yuecc52822020-02-14 14:36:46 +0800480 if (statp->nameserverCount() == 0) {
chenbruceceb3c022021-06-15 21:36:19 +0800481 // We have no nameservers configured and it's not a MDNS resolution, so there's no
482 // point trying. Tell the cache the query failed, or any retries and anyone else
483 // asking the same question will block for PENDING_REQUEST_TIMEOUT seconds instead
484 // of failing fast.
Luke Huangba7bef92018-12-26 16:53:03 +0800485 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800486
487 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900488 errno = ESRCH;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800489 return -ESRCH;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900490 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900491
Luke Huangd1d734f2020-04-30 12:25:40 +0800492 // If parallel_lookup is enabled, it might be required to wait some time to avoid
493 // gateways drop packets if queries are sent too close together
494 if (sleepTimeMs != 0ms) {
495 std::this_thread::sleep_for(sleepTimeMs);
496 }
Luke Huang272cb192019-10-15 16:52:28 +0900497 // DoT
chenbruceceb3c022021-06-15 21:36:19 +0800498 if (!(statp->netcontext_flags & NET_CONTEXT_FLAG_USE_LOCAL_NAMESERVERS) &&
499 !isMdnsResolution(statp->_flags)) {
Luke Huang272cb192019-10-15 16:52:28 +0900500 bool fallback = false;
Luke Huang43cc1b12019-10-15 19:06:42 +0900501 int resplen = res_tls_send(statp, Slice(const_cast<uint8_t*>(buf), buflen),
502 Slice(ans, anssiz), rcode, &fallback);
Luke Huang272cb192019-10-15 16:52:28 +0900503 if (resplen > 0) {
504 LOG(DEBUG) << __func__ << ": got answer from DoT";
505 res_pquery(ans, resplen);
506 if (cache_status == RESOLV_CACHE_NOTFOUND) {
507 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
508 }
509 return resplen;
510 }
511 if (!fallback) {
512 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huang43cc1b12019-10-15 19:06:42 +0900513 return -ETIMEDOUT;
Luke Huang272cb192019-10-15 16:52:28 +0900514 }
515 }
516
Mike Yuc573a3d2020-02-07 20:15:15 +0800517 res_stats stats[MAXNS]{};
Bernie Innocenti758005f2019-02-19 18:08:36 +0900518 res_params params;
Mike Yuc573a3d2020-02-07 20:15:15 +0800519 int revision_id = resolv_cache_get_resolver_stats(statp->netid, &params, stats, statp->nsaddrs);
lifra1b37f12019-02-13 17:33:57 +0800520 if (revision_id < 0) {
521 // TODO: Remove errno once callers stop using it
522 errno = ESRCH;
523 return -ESRCH;
524 }
chenbruceceb3c022021-06-15 21:36:19 +0800525
waynema0161acd2019-02-18 17:47:59 +0800526 bool usable_servers[MAXNS];
Luke Huang70931aa2019-01-31 11:57:41 +0800527 int usableServersCount = android_net_res_stats_get_usable_servers(
Mike Yuecc52822020-02-14 14:36:46 +0800528 &params, stats, statp->nameserverCount(), usable_servers);
Luke Huang70931aa2019-01-31 11:57:41 +0800529
Mike Yu61d17262020-02-15 18:56:22 +0800530 if (statp->sort_nameservers) {
531 // It's unnecessary to mark a DNS server as unusable since broken servers will be less
532 // likely to be chosen.
533 for (int i = 0; i < statp->nameserverCount(); i++) {
534 usable_servers[i] = true;
535 }
536 }
537
538 // TODO: Let it always choose the first nameserver when sort_nameservers is enabled.
Luke Huang70931aa2019-01-31 11:57:41 +0800539 if ((flags & ANDROID_RESOLV_NO_RETRY) && usableServersCount > 1) {
540 auto hp = reinterpret_cast<const HEADER*>(buf);
541
542 // Select a random server based on the query id
543 int selectedServer = (hp->id % usableServersCount) + 1;
Mike Yuecc52822020-02-14 14:36:46 +0800544 res_set_usable_server(selectedServer, statp->nameserverCount(), usable_servers);
Luke Huang70931aa2019-01-31 11:57:41 +0800545 }
waynema0161acd2019-02-18 17:47:59 +0800546
Luke Huang43cc1b12019-10-15 19:06:42 +0900547 // Send request, RETRY times, or until successful.
waynemaa74195e2019-01-18 14:02:31 +0800548 int retryTimes = (flags & ANDROID_RESOLV_NO_RETRY) ? 1 : params.retry_count;
Luke Huang43cc1b12019-10-15 19:06:42 +0900549 int useTcp = buflen > PACKETSZ;
550 int gotsomewhere = 0;
chenbruceceb3c022021-06-15 21:36:19 +0800551
Luke Huang23d55192020-04-16 11:47:30 +0800552 // Use an impossible error code as default value
553 int terrno = ETIME;
chenbruceceb3c022021-06-15 21:36:19 +0800554 // plaintext DNS
Luke Huangba7bef92018-12-26 16:53:03 +0800555 for (int attempt = 0; attempt < retryTimes; ++attempt) {
Mike Yue48f7b52020-02-10 14:55:06 +0800556 for (size_t ns = 0; ns < statp->nsaddrs.size(); ++ns) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900557 if (!usable_servers[ns]) continue;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900558
Luke Huang43cc1b12019-10-15 19:06:42 +0900559 *rcode = RCODE_INTERNAL_ERROR;
560
561 // Get server addr
Mike Yue48f7b52020-02-10 14:55:06 +0800562 const IPSockAddr& serverSockAddr = statp->nsaddrs[ns];
563 LOG(DEBUG) << __func__ << ": Querying server (# " << ns + 1
564 << ") address = " << serverSockAddr.toString();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900565
Luke Huang43cc1b12019-10-15 19:06:42 +0900566 ::android::net::Protocol query_proto = useTcp ? PROTO_TCP : PROTO_UDP;
Luke Huang420ee622019-11-27 17:52:44 +0800567 time_t query_time = 0;
Luke Huang43cc1b12019-10-15 19:06:42 +0900568 int delay = 0;
569 bool fallbackTCP = false;
570 const bool shouldRecordStats = (attempt == 0);
571 int resplen;
lifrd4d9fbb2019-07-31 20:18:35 +0800572 Stopwatch queryStopwatch;
lifr128183a2020-01-08 18:04:50 +0800573 int retry_count_for_event = 0;
Luke Huang420ee622019-11-27 17:52:44 +0800574 size_t actualNs = ns;
Luke Huang23d55192020-04-16 11:47:30 +0800575 // Use an impossible error code as default value
576 terrno = ETIME;
Luke Huang43cc1b12019-10-15 19:06:42 +0900577 if (useTcp) {
578 // TCP; at most one attempt per server.
Luke Huangba7bef92018-12-26 16:53:03 +0800579 attempt = retryTimes;
Luke Huang420ee622019-11-27 17:52:44 +0800580 resplen = send_vc(statp, &params, buf, buflen, ans, anssiz, &terrno, ns,
581 &query_time, rcode, &delay);
Ken Chen99344882020-01-01 14:59:38 +0800582
583 if (buflen <= PACKETSZ && resplen <= 0 &&
584 statp->tc_mode == aidl::android::net::IDnsResolver::TC_MODE_UDP_TCP) {
585 // reset to UDP for next query on next DNS server if resolver is currently doing
586 // TCP fallback retry and current server does not support TCP connectin
587 useTcp = false;
588 }
Luke Huangeb618ef2020-05-26 14:17:02 +0800589 LOG(INFO) << __func__ << ": used send_vc " << resplen << " terrno: " << terrno;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900590 } else {
Luke Huang43cc1b12019-10-15 19:06:42 +0900591 // UDP
Luke Huang420ee622019-11-27 17:52:44 +0800592 resplen = send_dg(statp, &params, buf, buflen, ans, anssiz, &terrno, &actualNs,
593 &useTcp, &gotsomewhere, &query_time, rcode, &delay);
Luke Huang43cc1b12019-10-15 19:06:42 +0900594 fallbackTCP = useTcp ? true : false;
lifr128183a2020-01-08 18:04:50 +0800595 retry_count_for_event = attempt;
Luke Huangeb618ef2020-05-26 14:17:02 +0800596 LOG(INFO) << __func__ << ": used send_dg " << resplen << " terrno: " << terrno;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900597 }
Luke Huang43cc1b12019-10-15 19:06:42 +0900598
Luke Huang420ee622019-11-27 17:52:44 +0800599 const IPSockAddr& receivedServerAddr = statp->nsaddrs[actualNs];
Luke Huang43cc1b12019-10-15 19:06:42 +0900600 DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
601 dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
Luke Huang420ee622019-11-27 17:52:44 +0800602 // When |retryTimes| > 1, we cannot actually know the correct latency value if we
603 // received the answer from the previous server. So temporarily set the latency as -1 if
604 // that condition happened.
605 // TODO: make the latency value accurate.
606 dnsQueryEvent->set_latency_micros(
607 (actualNs == ns) ? saturate_cast<int32_t>(queryStopwatch.timeTakenUs()) : -1);
608 dnsQueryEvent->set_dns_server_index(actualNs);
609 dnsQueryEvent->set_ip_version(ipFamilyToIPVersion(receivedServerAddr.family()));
lifr128183a2020-01-08 18:04:50 +0800610 dnsQueryEvent->set_retry_times(retry_count_for_event);
Luke Huang43cc1b12019-10-15 19:06:42 +0900611 dnsQueryEvent->set_rcode(static_cast<NsRcode>(*rcode));
612 dnsQueryEvent->set_protocol(query_proto);
613 dnsQueryEvent->set_type(getQueryType(buf, buflen));
Luke Huang23d55192020-04-16 11:47:30 +0800614 dnsQueryEvent->set_linux_errno(static_cast<LinuxErrno>(terrno));
Luke Huang43cc1b12019-10-15 19:06:42 +0900615
616 // Only record stats the first time we try a query. This ensures that
617 // queries that deterministically fail (e.g., a name that always returns
618 // SERVFAIL or times out) do not unduly affect the stats.
619 if (shouldRecordStats) {
Luke Huangeb618ef2020-05-26 14:17:02 +0800620 // (b/151166599): This is a workaround to prevent that DnsResolver calculates the
621 // reliability of DNS servers from being broken when network restricted mode is
622 // enabled.
623 // TODO: Introduce the new server selection instead of skipping stats recording.
624 if (!isNetworkRestricted(terrno)) {
625 res_sample sample;
626 res_stats_set_sample(&sample, query_time, *rcode, delay);
627 // KeepListening UDP mechanism is incompatible with usable_servers of legacy
628 // stats, so keep the old logic for now.
629 // TODO: Replace usable_servers of legacy stats with new one.
630 resolv_cache_add_resolver_stats_sample(
631 statp->netid, revision_id, serverSockAddr, sample, params.max_samples);
Mike Yu30e0de92021-05-07 11:48:46 +0800632 resolv_stats_add(statp->netid, receivedServerAddr, dnsQueryEvent);
Luke Huangeb618ef2020-05-26 14:17:02 +0800633 }
Luke Huang43cc1b12019-10-15 19:06:42 +0900634 }
635
636 if (resplen == 0) continue;
637 if (fallbackTCP) {
638 ns--;
639 continue;
640 }
641 if (resplen < 0) {
642 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800643 statp->closeSockets();
Luke Huang43cc1b12019-10-15 19:06:42 +0900644 return -terrno;
chenbruceceb3c022021-06-15 21:36:19 +0800645 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900646
Ken Chenffc224a2019-03-19 17:41:28 +0800647 LOG(DEBUG) << __func__ << ": got answer:";
chenbrucedd210722019-03-06 13:52:43 +0800648 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900649
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900650 if (cache_status == RESOLV_CACHE_NOTFOUND) {
Mike Yud1ec2542019-06-06 17:17:53 +0800651 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900652 }
Luke Huangadb0f5b2019-11-27 15:51:48 +0800653 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900654 return (resplen);
Bernie Innocenti9c575932018-09-07 21:10:25 +0900655 } // for each ns
656 } // for each retry
Luke Huangadb0f5b2019-11-27 15:51:48 +0800657 statp->closeSockets();
Luke Huang43cc1b12019-10-15 19:06:42 +0900658 terrno = useTcp ? terrno : gotsomewhere ? ETIMEDOUT : ECONNREFUSED;
659 // TODO: Remove errno once callers stop using it
660 errno = useTcp ? terrno
661 : gotsomewhere ? ETIMEDOUT /* no answer obtained */
662 : ECONNREFUSED /* no nameservers found */;
663
Luke Huangba7bef92018-12-26 16:53:03 +0800664 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800665 return -terrno;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900666}
667
chenbruceceb3c022021-06-15 21:36:19 +0800668static struct timespec get_timeout(res_state statp, const res_params* params, const int addrIndex) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900669 int msec;
chenbruceceb3c022021-06-15 21:36:19 +0800670 msec = params->base_timeout_msec << addrIndex;
waynemaa74195e2019-01-18 14:02:31 +0800671 // Legacy algorithm which scales the timeout by nameserver number.
672 // For instance, with 4 nameservers: 5s, 2.5s, 5s, 10s
673 // This has no effect with 1 or 2 nameservers
chenbruceceb3c022021-06-15 21:36:19 +0800674 if (addrIndex > 0) {
Mike Yuecc52822020-02-14 14:36:46 +0800675 msec /= statp->nameserverCount();
waynemaa74195e2019-01-18 14:02:31 +0800676 }
677 // For safety, don't allow OEMs and experiments to configure a timeout shorter than 1s.
678 if (msec < 1000) {
679 msec = 1000; // Use at least 1000ms
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900680 }
Ken Chenffc224a2019-03-19 17:41:28 +0800681 LOG(INFO) << __func__ << ": using timeout of " << msec << " msec";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900682
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900683 struct timespec result;
684 result.tv_sec = msec / 1000;
685 result.tv_nsec = (msec % 1000) * 1000000;
686 return result;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900687}
688
chenbrucec51f1212019-09-12 16:59:33 +0800689static int send_vc(res_state statp, res_params* params, const uint8_t* buf, int buflen,
Mike Yue48f7b52020-02-10 14:55:06 +0800690 uint8_t* ans, int anssiz, int* terrno, size_t ns, time_t* at, int* rcode,
chenbrucec51f1212019-09-12 16:59:33 +0800691 int* delay) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900692 *at = time(NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900693 *delay = 0;
694 const HEADER* hp = (const HEADER*) (const void*) buf;
695 HEADER* anhp = (HEADER*) (void*) ans;
696 struct sockaddr* nsap;
697 int nsaplen;
chenbruce0d470422019-03-28 18:44:37 +0800698 int truncating, connreset, n;
chenbrucec51f1212019-09-12 16:59:33 +0800699 uint8_t* cp;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900700
Ken Chenffc224a2019-03-19 17:41:28 +0800701 LOG(INFO) << __func__ << ": using send_vc";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900702
Mike Yue48f7b52020-02-10 14:55:06 +0800703 // It should never happen, but just in case.
704 if (ns >= statp->nsaddrs.size()) {
705 LOG(ERROR) << __func__ << ": Out-of-bound indexing: " << ns;
Luke Huang23d55192020-04-16 11:47:30 +0800706 *terrno = EINVAL;
Mike Yue48f7b52020-02-10 14:55:06 +0800707 return -1;
708 }
709
710 sockaddr_storage ss = statp->nsaddrs[ns];
711 nsap = reinterpret_cast<sockaddr*>(&ss);
Mike Yu021c3e12019-10-08 17:29:34 +0800712 nsaplen = sockaddrSize(nsap);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900713
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900714 connreset = 0;
715same_ns:
716 truncating = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900717
Luke Huang420ee622019-11-27 17:52:44 +0800718 struct timespec start_time = evNowTime();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900719
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900720 /* Are we still talking to whom we want to talk to? */
Luke Huangadb0f5b2019-11-27 15:51:48 +0800721 if (statp->tcp_nssock >= 0 && (statp->_flags & RES_F_VC) != 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900722 struct sockaddr_storage peer;
723 socklen_t size = sizeof peer;
724 unsigned old_mark;
725 socklen_t mark_size = sizeof(old_mark);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800726 if (getpeername(statp->tcp_nssock, (struct sockaddr*)(void*)&peer, &size) < 0 ||
727 !sock_eq((struct sockaddr*)(void*)&peer, nsap) ||
728 getsockopt(statp->tcp_nssock, SOL_SOCKET, SO_MARK, &old_mark, &mark_size) < 0 ||
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900729 old_mark != statp->_mark) {
Luke Huangadb0f5b2019-11-27 15:51:48 +0800730 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900731 }
732 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900733
Luke Huangadb0f5b2019-11-27 15:51:48 +0800734 if (statp->tcp_nssock < 0 || (statp->_flags & RES_F_VC) == 0) {
735 if (statp->tcp_nssock >= 0) statp->closeSockets();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900736
Luke Huangadb0f5b2019-11-27 15:51:48 +0800737 statp->tcp_nssock.reset(socket(nsap->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0));
738 if (statp->tcp_nssock < 0) {
Luke Huang23d55192020-04-16 11:47:30 +0800739 *terrno = errno;
740 PLOG(DEBUG) << __func__ << ": socket(vc): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900741 switch (errno) {
742 case EPROTONOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900743 case EPFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900744 case EAFNOSUPPORT:
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900745 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900746 default:
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900747 return -1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900748 }
749 }
Ken Chenbc481b82020-05-21 23:30:01 +0800750 const uid_t uid = statp->enforce_dns_uid ? AID_DNS : statp->uid;
751 resolv_tag_socket(statp->tcp_nssock, uid, statp->pid);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900752 if (statp->_mark != MARK_UNSET) {
Luke Huangadb0f5b2019-11-27 15:51:48 +0800753 if (setsockopt(statp->tcp_nssock, SOL_SOCKET, SO_MARK, &statp->_mark,
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900754 sizeof(statp->_mark)) < 0) {
755 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800756 PLOG(DEBUG) << __func__ << ": setsockopt: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900757 return -1;
758 }
759 }
760 errno = 0;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800761 if (random_bind(statp->tcp_nssock, nsap->sa_family) < 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900762 *terrno = errno;
chenbruce76620642021-06-15 18:39:27 +0800763 dump_error("bind/vc", nsap);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800764 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900765 return (0);
766 }
Luke Huangadb0f5b2019-11-27 15:51:48 +0800767 if (connect_with_timeout(statp->tcp_nssock, nsap, (socklen_t)nsaplen,
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900768 get_timeout(statp, params, ns)) < 0) {
769 *terrno = errno;
chenbruce76620642021-06-15 18:39:27 +0800770 dump_error("connect/vc", nsap);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800771 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900772 /*
773 * The way connect_with_timeout() is implemented prevents us from reliably
774 * determining whether this was really a timeout or e.g. ECONNREFUSED. Since
775 * currently both cases are handled in the same way, there is no need to
776 * change this (yet). If we ever need to reliably distinguish between these
777 * cases, both connect_with_timeout() and retrying_poll() need to be
778 * modified, though.
779 */
780 *rcode = RCODE_TIMEOUT;
781 return (0);
782 }
783 statp->_flags |= RES_F_VC;
784 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900785
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900786 /*
787 * Send length & message
788 */
chenbruce0d470422019-03-28 18:44:37 +0800789 uint16_t len = htons(static_cast<uint16_t>(buflen));
Luke Huangc98fd802019-10-15 16:36:36 +0900790 const iovec iov[] = {
791 {.iov_base = &len, .iov_len = INT16SZ},
792 {.iov_base = const_cast<uint8_t*>(buf), .iov_len = static_cast<size_t>(buflen)},
793 };
Luke Huangadb0f5b2019-11-27 15:51:48 +0800794 if (writev(statp->tcp_nssock, iov, 2) != (INT16SZ + buflen)) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900795 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800796 PLOG(DEBUG) << __func__ << ": write failed: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800797 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900798 return (0);
799 }
800 /*
801 * Receive length & response
802 */
803read_len:
804 cp = ans;
805 len = INT16SZ;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800806 while ((n = read(statp->tcp_nssock, (char*)cp, (size_t)len)) > 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900807 cp += n;
808 if ((len -= n) == 0) break;
809 }
810 if (n <= 0) {
811 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800812 PLOG(DEBUG) << __func__ << ": read failed: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800813 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900814 /*
815 * A long running process might get its TCP
816 * connection reset if the remote server was
817 * restarted. Requery the server instead of
818 * trying a new one. When there is only one
819 * server, this means that a query might work
820 * instead of failing. We only allow one reset
821 * per query to prevent looping.
822 */
823 if (*terrno == ECONNRESET && !connreset) {
824 connreset = 1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900825 goto same_ns;
826 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900827 return (0);
828 }
chenbruce0d470422019-03-28 18:44:37 +0800829 uint16_t resplen = ntohs(*reinterpret_cast<const uint16_t*>(ans));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900830 if (resplen > anssiz) {
Ken Chenffc224a2019-03-19 17:41:28 +0800831 LOG(DEBUG) << __func__ << ": response truncated";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900832 truncating = 1;
833 len = anssiz;
834 } else
835 len = resplen;
836 if (len < HFIXEDSZ) {
837 /*
838 * Undersized message.
839 */
Ken Chenffc224a2019-03-19 17:41:28 +0800840 LOG(DEBUG) << __func__ << ": undersized: " << len;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900841 *terrno = EMSGSIZE;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800842 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900843 return (0);
844 }
845 cp = ans;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800846 while (len != 0 && (n = read(statp->tcp_nssock, (char*)cp, (size_t)len)) > 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900847 cp += n;
848 len -= n;
849 }
850 if (n <= 0) {
851 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800852 PLOG(DEBUG) << __func__ << ": read(vc): ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800853 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900854 return (0);
855 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900856
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900857 if (truncating) {
858 /*
859 * Flush rest of answer so connection stays in synch.
860 */
861 anhp->tc = 1;
862 len = resplen - anssiz;
863 while (len != 0) {
864 char junk[PACKETSZ];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900865
Luke Huangadb0f5b2019-11-27 15:51:48 +0800866 n = read(statp->tcp_nssock, junk, (len > sizeof junk) ? sizeof junk : len);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900867 if (n > 0)
868 len -= n;
869 else
870 break;
871 }
Ken Chena9e6f1d2020-07-30 13:24:16 +0800872 LOG(WARNING) << __func__ << ": resplen " << resplen << " exceeds buf size " << anssiz;
873 // return size should never exceed container size
874 resplen = anssiz;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900875 }
876 /*
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900877 * If the calling application has bailed out of
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900878 * a previous call and failed to arrange to have
879 * the circuit closed or the server has got
880 * itself confused, then drop the packet and
881 * wait for the correct one.
882 */
883 if (hp->id != anhp->id) {
Ken Chenffc224a2019-03-19 17:41:28 +0800884 LOG(DEBUG) << __func__ << ": ld answer (unexpected):";
Ken Chena9e6f1d2020-07-30 13:24:16 +0800885 res_pquery(ans, resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900886 goto read_len;
887 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900888
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900889 /*
890 * All is well, or the error is fatal. Signal that the
891 * next nameserver ought not be tried.
892 */
893 if (resplen > 0) {
894 struct timespec done = evNowTime();
Luke Huang420ee622019-11-27 17:52:44 +0800895 *delay = res_stats_calculate_rtt(&done, &start_time);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900896 *rcode = anhp->rcode;
897 }
Luke Huang23d55192020-04-16 11:47:30 +0800898 *terrno = 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900899 return (resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900900}
901
902/* return -1 on error (errno set), 0 on success */
Luke Huangc98fd802019-10-15 16:36:36 +0900903static int connect_with_timeout(int sock, const sockaddr* nsap, socklen_t salen,
904 const timespec timeout) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900905 int res, origflags;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900906
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900907 origflags = fcntl(sock, F_GETFL, 0);
908 fcntl(sock, F_SETFL, origflags | O_NONBLOCK);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900909
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900910 res = connect(sock, nsap, salen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900911 if (res < 0 && errno != EINPROGRESS) {
912 res = -1;
913 goto done;
914 }
915 if (res != 0) {
Luke Huangc98fd802019-10-15 16:36:36 +0900916 timespec now = evNowTime();
917 timespec finish = evAddTime(now, timeout);
Ken Chenffc224a2019-03-19 17:41:28 +0800918 LOG(INFO) << __func__ << ": " << sock << " send_vc";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900919 res = retrying_poll(sock, POLLIN | POLLOUT, &finish);
920 if (res <= 0) {
921 res = -1;
922 }
923 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900924done:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900925 fcntl(sock, F_SETFL, origflags);
Ken Chenffc224a2019-03-19 17:41:28 +0800926 LOG(INFO) << __func__ << ": " << sock << " connect_with_const timeout returning " << res;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900927 return res;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900928}
929
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900930static int retrying_poll(const int sock, const short events, const struct timespec* finish) {
931 struct timespec now, timeout;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900932
933retry:
Ken Chenffc224a2019-03-19 17:41:28 +0800934 LOG(INFO) << __func__ << ": " << sock << " retrying_poll";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900935
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900936 now = evNowTime();
937 if (evCmpTime(*finish, now) > 0)
938 timeout = evSubTime(*finish, now);
939 else
940 timeout = evConsTime(0L, 0L);
941 struct pollfd fds = {.fd = sock, .events = events};
Maciej Żenczykowski88f87552020-04-23 08:48:36 -0700942 int n = ppoll(&fds, 1, &timeout, /*__mask=*/NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900943 if (n == 0) {
Luke Huang420ee622019-11-27 17:52:44 +0800944 LOG(INFO) << __func__ << ": " << sock << " retrying_poll timeout";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900945 errno = ETIMEDOUT;
946 return 0;
947 }
948 if (n < 0) {
949 if (errno == EINTR) goto retry;
Ken Chenffc224a2019-03-19 17:41:28 +0800950 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll failed";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900951 return n;
952 }
953 if (fds.revents & (POLLIN | POLLOUT | POLLERR)) {
954 int error;
955 socklen_t len = sizeof(error);
956 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error) {
957 errno = error;
Ken Chenffc224a2019-03-19 17:41:28 +0800958 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll getsockopt failed";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900959 return -1;
960 }
961 }
Ken Chenffc224a2019-03-19 17:41:28 +0800962 LOG(INFO) << __func__ << ": " << sock << " retrying_poll returning " << n;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900963 return n;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900964}
965
Luke Huang420ee622019-11-27 17:52:44 +0800966static std::vector<pollfd> extractUdpFdset(res_state statp, const short events = POLLIN) {
967 std::vector<pollfd> fdset(statp->nsaddrs.size());
968 for (size_t i = 0; i < statp->nsaddrs.size(); ++i) {
chenbrucecc9bbc02021-06-15 17:38:14 +0800969 fdset[i] = {.fd = statp->udpsocks[i], .events = events};
Luke Huang420ee622019-11-27 17:52:44 +0800970 }
971 return fdset;
972}
973
974static Result<std::vector<int>> udpRetryingPoll(res_state statp, const timespec* finish) {
975 for (;;) {
976 LOG(DEBUG) << __func__ << ": poll";
977 timespec start_time = evNowTime();
978 timespec timeout = (evCmpTime(*finish, start_time) > 0) ? evSubTime(*finish, start_time)
979 : evConsTime(0L, 0L);
980 std::vector<pollfd> fdset = extractUdpFdset(statp);
Maciej Żenczykowski88f87552020-04-23 08:48:36 -0700981 const int n = ppoll(fdset.data(), fdset.size(), &timeout, /*__mask=*/nullptr);
Luke Huang420ee622019-11-27 17:52:44 +0800982 if (n <= 0) {
983 if (errno == EINTR && n < 0) continue;
984 if (n == 0) errno = ETIMEDOUT;
985 PLOG(INFO) << __func__ << ": failed";
986 return ErrnoError();
987 }
988 std::vector<int> fdsToRead;
989 for (const auto& pollfd : fdset) {
990 if (pollfd.revents & (POLLIN | POLLERR)) {
991 fdsToRead.push_back(pollfd.fd);
992 }
993 }
994 LOG(DEBUG) << __func__ << ": "
995 << " returning fd size: " << fdsToRead.size();
996 return fdsToRead;
997 }
998}
999
chenbruceceb3c022021-06-15 21:36:19 +08001000static Result<std::vector<int>> udpRetryingPollWrapper(res_state statp, int addrInfo,
Luke Huang420ee622019-11-27 17:52:44 +08001001 const timespec* finish) {
Luke Huangf40df9c2020-04-21 08:51:48 +08001002 const bool keepListeningUdp =
1003 android::net::Experiments::getInstance()->getFlag("keep_listening_udp", 0);
Luke Huang420ee622019-11-27 17:52:44 +08001004 if (keepListeningUdp) return udpRetryingPoll(statp, finish);
1005
chenbruceceb3c022021-06-15 21:36:19 +08001006 if (int n = retrying_poll(statp->udpsocks[addrInfo], POLLIN, finish); n <= 0) {
Luke Huang420ee622019-11-27 17:52:44 +08001007 return ErrnoError();
1008 }
chenbruceceb3c022021-06-15 21:36:19 +08001009 return std::vector<int>{statp->udpsocks[addrInfo]};
Luke Huang420ee622019-11-27 17:52:44 +08001010}
1011
Luke Huangbff43fc2019-11-12 15:54:47 +08001012bool ignoreInvalidAnswer(res_state statp, const sockaddr_storage& from, const uint8_t* buf,
Luke Huang420ee622019-11-27 17:52:44 +08001013 int buflen, uint8_t* ans, int anssiz, int* receivedFromNs) {
Luke Huangbff43fc2019-11-12 15:54:47 +08001014 const HEADER* hp = (const HEADER*)(const void*)buf;
1015 HEADER* anhp = (HEADER*)(void*)ans;
1016 if (hp->id != anhp->id) {
1017 // response from old query, ignore it.
1018 LOG(DEBUG) << __func__ << ": old answer:";
1019 return true;
1020 }
Luke Huang420ee622019-11-27 17:52:44 +08001021 if (*receivedFromNs = res_ourserver_p(statp, (sockaddr*)(void*)&from); *receivedFromNs < 0) {
Luke Huangbff43fc2019-11-12 15:54:47 +08001022 // response from wrong server? ignore it.
1023 LOG(DEBUG) << __func__ << ": not our server:";
1024 return true;
1025 }
1026 if (!res_queriesmatch(buf, buf + buflen, ans, ans + anssiz)) {
1027 // response contains wrong query? ignore it.
1028 LOG(DEBUG) << __func__ << ": wrong query name:";
1029 return true;
1030 }
1031 return false;
1032}
1033
chenbruceceb3c022021-06-15 21:36:19 +08001034// return 1 - setup udp socket success.
1035// return 0 - bind error, protocol error.
1036// return -1 - create socket fail, except |EPROTONOSUPPORT| EPFNOSUPPORT |EAFNOSUPPORT|.
1037// set socket option fail.
1038static int setupUdpSocket(ResState* statp, const sockaddr* sockap, unique_fd* fd_out, int* terrno) {
1039 fd_out->reset(socket(sockap->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0));
chenbruceb1aa65a2021-06-15 19:37:05 +08001040
chenbruceceb3c022021-06-15 21:36:19 +08001041 if (*fd_out < 0) {
chenbruceb1aa65a2021-06-15 19:37:05 +08001042 *terrno = errno;
1043 PLOG(ERROR) << __func__ << ": socket: ";
1044 switch (errno) {
1045 case EPROTONOSUPPORT:
1046 case EPFNOSUPPORT:
1047 case EAFNOSUPPORT:
1048 return 0;
1049 default:
1050 return -1;
1051 }
1052 }
1053 const uid_t uid = statp->enforce_dns_uid ? AID_DNS : statp->uid;
chenbruceceb3c022021-06-15 21:36:19 +08001054 resolv_tag_socket(*fd_out, uid, statp->pid);
chenbruceb1aa65a2021-06-15 19:37:05 +08001055 if (statp->_mark != MARK_UNSET) {
chenbruceceb3c022021-06-15 21:36:19 +08001056 if (setsockopt(*fd_out, SOL_SOCKET, SO_MARK, &(statp->_mark), sizeof(statp->_mark)) < 0) {
chenbruceb1aa65a2021-06-15 19:37:05 +08001057 *terrno = errno;
chenbruceb1aa65a2021-06-15 19:37:05 +08001058 return -1;
1059 }
1060 }
1061
chenbruceceb3c022021-06-15 21:36:19 +08001062 if (random_bind(*fd_out, sockap->sa_family) < 0) {
chenbruceb1aa65a2021-06-15 19:37:05 +08001063 *terrno = errno;
1064 dump_error("bind", sockap);
chenbruceb1aa65a2021-06-15 19:37:05 +08001065 return 0;
1066 }
1067 return 1;
1068}
1069
chenbrucec51f1212019-09-12 16:59:33 +08001070static int send_dg(res_state statp, res_params* params, const uint8_t* buf, int buflen,
Luke Huang420ee622019-11-27 17:52:44 +08001071 uint8_t* ans, int anssiz, int* terrno, size_t* ns, int* v_circuit,
Mike Yue48f7b52020-02-10 14:55:06 +08001072 int* gotsomewhere, time_t* at, int* rcode, int* delay) {
1073 // It should never happen, but just in case.
Luke Huang420ee622019-11-27 17:52:44 +08001074 if (*ns >= statp->nsaddrs.size()) {
Mike Yue48f7b52020-02-10 14:55:06 +08001075 LOG(ERROR) << __func__ << ": Out-of-bound indexing: " << ns;
Luke Huang23d55192020-04-16 11:47:30 +08001076 *terrno = EINVAL;
Mike Yue48f7b52020-02-10 14:55:06 +08001077 return -1;
1078 }
1079
Luke Huangbff43fc2019-11-12 15:54:47 +08001080 *at = time(nullptr);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001081 *delay = 0;
Luke Huang420ee622019-11-27 17:52:44 +08001082 const sockaddr_storage ss = statp->nsaddrs[*ns];
Mike Yue48f7b52020-02-10 14:55:06 +08001083 const sockaddr* nsap = reinterpret_cast<const sockaddr*>(&ss);
Luke Huangbff43fc2019-11-12 15:54:47 +08001084
chenbrucecc9bbc02021-06-15 17:38:14 +08001085 if (statp->udpsocks[*ns] == -1) {
chenbruceceb3c022021-06-15 21:36:19 +08001086 int result = setupUdpSocket(statp, nsap, &statp->udpsocks[*ns], terrno);
chenbruceb1aa65a2021-06-15 19:37:05 +08001087 if (result <= 0) return result;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001088
chenbruceb9cce7b2019-07-15 16:14:53 +08001089 // Use a "connected" datagram socket to receive an ECONNREFUSED error
1090 // on the next socket operation when the server responds with an
1091 // ICMP port-unreachable error. This way we can detect the absence of
1092 // a nameserver without timing out.
chenbruceb1aa65a2021-06-15 19:37:05 +08001093 if (connect(statp->udpsocks[*ns], nsap, sockaddrSize(nsap)) < 0) {
Luke Huang23d55192020-04-16 11:47:30 +08001094 *terrno = errno;
chenbruce76620642021-06-15 18:39:27 +08001095 dump_error("connect(dg)", nsap);
Luke Huangadb0f5b2019-11-27 15:51:48 +08001096 statp->closeSockets();
chenbruceceb3c022021-06-15 21:36:19 +08001097 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001098 }
Ken Chenffc224a2019-03-19 17:41:28 +08001099 LOG(DEBUG) << __func__ << ": new DG socket";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001100 }
chenbrucecc9bbc02021-06-15 17:38:14 +08001101 if (send(statp->udpsocks[*ns], (const char*)buf, (size_t)buflen, 0) != buflen) {
Luke Huang23d55192020-04-16 11:47:30 +08001102 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +08001103 PLOG(DEBUG) << __func__ << ": send: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +08001104 statp->closeSockets();
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001105 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001106 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001107
Luke Huang420ee622019-11-27 17:52:44 +08001108 timespec timeout = get_timeout(statp, params, *ns);
1109 timespec start_time = evNowTime();
1110 timespec finish = evAddTime(start_time, timeout);
Luke Huangbff43fc2019-11-12 15:54:47 +08001111 for (;;) {
1112 // Wait for reply.
Luke Huang420ee622019-11-27 17:52:44 +08001113 auto result = udpRetryingPollWrapper(statp, *ns, &finish);
1114
1115 if (!result.has_value()) {
1116 const bool isTimeout = (result.error().code() == ETIMEDOUT);
1117 *rcode = (isTimeout) ? RCODE_TIMEOUT : *rcode;
Luke Huang23d55192020-04-16 11:47:30 +08001118 *terrno = (isTimeout) ? ETIMEDOUT : errno;
Luke Huang420ee622019-11-27 17:52:44 +08001119 *gotsomewhere = (isTimeout) ? 1 : *gotsomewhere;
1120 // Leave the UDP sockets open on timeout so we can keep listening for
1121 // a late response from this server while retrying on the next server.
1122 if (!isTimeout) statp->closeSockets();
1123 LOG(DEBUG) << __func__ << ": " << (isTimeout) ? "timeout" : "poll";
1124 return 0;
1125 }
1126 bool needRetry = false;
1127 for (int fd : result.value()) {
1128 needRetry = false;
1129 sockaddr_storage from;
1130 socklen_t fromlen = sizeof(from);
1131 int resplen =
1132 recvfrom(fd, (char*)ans, (size_t)anssiz, 0, (sockaddr*)(void*)&from, &fromlen);
1133 if (resplen <= 0) {
Luke Huang23d55192020-04-16 11:47:30 +08001134 *terrno = errno;
Luke Huang420ee622019-11-27 17:52:44 +08001135 PLOG(DEBUG) << __func__ << ": recvfrom: ";
1136 continue;
1137 }
Luke Huangbff43fc2019-11-12 15:54:47 +08001138 *gotsomewhere = 1;
Luke Huang420ee622019-11-27 17:52:44 +08001139 if (resplen < HFIXEDSZ) {
1140 // Undersized message.
1141 LOG(DEBUG) << __func__ << ": undersized: " << resplen;
1142 *terrno = EMSGSIZE;
1143 continue;
1144 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001145
Luke Huang420ee622019-11-27 17:52:44 +08001146 int receivedFromNs = *ns;
1147 if (needRetry =
1148 ignoreInvalidAnswer(statp, from, buf, buflen, ans, anssiz, &receivedFromNs);
1149 needRetry) {
1150 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
1151 continue;
1152 }
Luke Huangbff43fc2019-11-12 15:54:47 +08001153
Luke Huang420ee622019-11-27 17:52:44 +08001154 HEADER* anhp = (HEADER*)(void*)ans;
1155 if (anhp->rcode == FORMERR && (statp->netcontext_flags & NET_CONTEXT_FLAG_USE_EDNS)) {
1156 // Do not retry if the server do not understand EDNS0.
1157 // The case has to be captured here, as FORMERR packet do not
1158 // carry query section, hence res_queriesmatch() returns 0.
1159 LOG(DEBUG) << __func__ << ": server rejected query with EDNS0:";
1160 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
1161 // record the error
1162 statp->_flags |= RES_F_EDNS0ERR;
Luke Huang23d55192020-04-16 11:47:30 +08001163 *terrno = EREMOTEIO;
Luke Huang420ee622019-11-27 17:52:44 +08001164 continue;
1165 }
Luke Huangbff43fc2019-11-12 15:54:47 +08001166
Luke Huang420ee622019-11-27 17:52:44 +08001167 timespec done = evNowTime();
1168 *delay = res_stats_calculate_rtt(&done, &start_time);
1169 if (anhp->rcode == SERVFAIL || anhp->rcode == NOTIMP || anhp->rcode == REFUSED) {
1170 LOG(DEBUG) << __func__ << ": server rejected query:";
1171 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
1172 *rcode = anhp->rcode;
1173 continue;
1174 }
1175 if (anhp->tc) {
1176 // To get the rest of answer,
1177 // use TCP with same server.
1178 LOG(DEBUG) << __func__ << ": truncated answer";
Luke Huang23d55192020-04-16 11:47:30 +08001179 *terrno = E2BIG;
Luke Huang420ee622019-11-27 17:52:44 +08001180 *v_circuit = 1;
1181 return 1;
1182 }
1183 // All is well, or the error is fatal. Signal that the
1184 // next nameserver ought not be tried.
Luke Huangbff43fc2019-11-12 15:54:47 +08001185
Luke Huangbff43fc2019-11-12 15:54:47 +08001186 *rcode = anhp->rcode;
Luke Huang420ee622019-11-27 17:52:44 +08001187 *ns = receivedFromNs;
Luke Huang23d55192020-04-16 11:47:30 +08001188 *terrno = 0;
Luke Huang420ee622019-11-27 17:52:44 +08001189 return resplen;
Luke Huangbff43fc2019-11-12 15:54:47 +08001190 }
Luke Huang420ee622019-11-27 17:52:44 +08001191 if (!needRetry) return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001192 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001193}
1194
chenbruceceb3c022021-06-15 21:36:19 +08001195// return length - when receiving valid packets.
1196// return 0 - when mdns packets transfer error.
1197static int send_mdns(ResState* statp, std::span<const uint8_t> buf, uint8_t* ans, int anssiz,
1198 int* terrno, int* rcode) {
1199 const sockaddr_storage ss =
1200 (getQueryType(buf.data(), buf.size()) == T_AAAA) ? mdns_addrs[0] : mdns_addrs[1];
1201 const sockaddr* mdnsap = reinterpret_cast<const sockaddr*>(&ss);
1202 unique_fd fd;
1203
1204 if (setupUdpSocket(statp, mdnsap, &fd, terrno) <= 0) return 0;
1205
1206 if (sendto(fd, buf.data(), buf.size(), 0, mdnsap, sockaddrSize(mdnsap)) != buf.size()) {
1207 *terrno = errno;
1208 return 0;
1209 }
1210 // RFC 6762: Typically, the timeout would also be shortened to two or three seconds.
1211 const struct timespec finish = evAddTime(evNowTime(), {2, 2000000});
1212
1213 // Wait for reply.
1214 if (retrying_poll(fd, POLLIN, &finish) <= 0) {
1215 *terrno = errno;
1216 if (*terrno == ETIMEDOUT) *rcode = RCODE_TIMEOUT;
1217 LOG(ERROR) << __func__ << ": " << (*terrno == ETIMEDOUT) ? "timeout" : "poll";
1218 return 0;
1219 }
1220
1221 sockaddr_storage from;
1222 socklen_t fromlen = sizeof(from);
1223 int resplen = recvfrom(fd, (char*)ans, (size_t)anssiz, 0, (sockaddr*)(void*)&from, &fromlen);
1224
1225 if (resplen <= 0) {
1226 *terrno = errno;
1227 return 0;
1228 }
1229
1230 if (resplen < HFIXEDSZ) {
1231 // Undersized message.
1232 LOG(ERROR) << __func__ << ": undersized: " << resplen;
1233 *terrno = EMSGSIZE;
1234 return 0;
1235 }
1236
1237 HEADER* anhp = (HEADER*)(void*)ans;
1238 if (anhp->tc) {
1239 LOG(DEBUG) << __func__ << ": truncated answer";
1240 *terrno = E2BIG;
1241 return 0;
1242 }
1243
1244 *rcode = anhp->rcode;
1245 *terrno = 0;
1246 return resplen;
1247}
1248
chenbruce76620642021-06-15 18:39:27 +08001249static void dump_error(const char* str, const struct sockaddr* address) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001250 char hbuf[NI_MAXHOST];
1251 char sbuf[NI_MAXSERV];
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001252 constexpr int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
Luke Huangc98fd802019-10-15 16:36:36 +09001253 const int err = errno;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001254
chenbruce018fdb22019-06-12 18:08:04 +08001255 if (!WOULD_LOG(DEBUG)) return;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001256
chenbruce76620642021-06-15 18:39:27 +08001257 if (getnameinfo(address, sockaddrSize(address), hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
1258 niflags)) {
chenbruce018fdb22019-06-12 18:08:04 +08001259 strncpy(hbuf, "?", sizeof(hbuf) - 1);
1260 hbuf[sizeof(hbuf) - 1] = '\0';
1261 strncpy(sbuf, "?", sizeof(sbuf) - 1);
1262 sbuf[sizeof(sbuf) - 1] = '\0';
Elliott Hughes3b8f5902019-03-08 12:02:55 -08001263 }
Luke Huangc98fd802019-10-15 16:36:36 +09001264 errno = err;
chenbruce018fdb22019-06-12 18:08:04 +08001265 PLOG(DEBUG) << __func__ << ": " << str << " ([" << hbuf << "]." << sbuf << "): ";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001266}
1267
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001268static int sock_eq(struct sockaddr* a, struct sockaddr* b) {
1269 struct sockaddr_in *a4, *b4;
1270 struct sockaddr_in6 *a6, *b6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001271
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001272 if (a->sa_family != b->sa_family) return 0;
1273 switch (a->sa_family) {
1274 case AF_INET:
1275 a4 = (struct sockaddr_in*) (void*) a;
1276 b4 = (struct sockaddr_in*) (void*) b;
1277 return a4->sin_port == b4->sin_port && a4->sin_addr.s_addr == b4->sin_addr.s_addr;
1278 case AF_INET6:
1279 a6 = (struct sockaddr_in6*) (void*) a;
1280 b6 = (struct sockaddr_in6*) (void*) b;
1281 return a6->sin6_port == b6->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001282#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001283 a6->sin6_scope_id == b6->sin6_scope_id &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001284#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001285 IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
1286 default:
1287 return 0;
1288 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001289}
Mike Yub601ff72018-11-01 20:07:00 +08001290
lifr6b83a6f2019-07-26 03:17:43 +08001291PrivateDnsModes convertEnumType(PrivateDnsMode privateDnsmode) {
1292 switch (privateDnsmode) {
1293 case PrivateDnsMode::OFF:
1294 return PrivateDnsModes::PDM_OFF;
1295 case PrivateDnsMode::OPPORTUNISTIC:
1296 return PrivateDnsModes::PDM_OPPORTUNISTIC;
1297 case PrivateDnsMode::STRICT:
1298 return PrivateDnsModes::PDM_STRICT;
Mike Yu99b8dc72019-11-22 17:45:31 +08001299 default:
1300 return PrivateDnsModes::PDM_UNKNOWN;
lifr6b83a6f2019-07-26 03:17:43 +08001301 }
lifr6b83a6f2019-07-26 03:17:43 +08001302}
1303
Luke Huangd7aa7b42018-11-21 20:37:50 +08001304static int res_tls_send(res_state statp, const Slice query, const Slice answer, int* rcode,
Mike Yubfb1b342018-11-06 15:42:36 +08001305 bool* fallback) {
1306 int resplen = 0;
Mike Yub601ff72018-11-01 20:07:00 +08001307 const unsigned netId = statp->netid;
Mike Yub601ff72018-11-01 20:07:00 +08001308
Mike Yu60248242020-07-29 16:45:26 +08001309 auto& privateDnsConfiguration = PrivateDnsConfiguration::getInstance();
1310 PrivateDnsStatus privateDnsStatus = privateDnsConfiguration.getStatus(netId);
lifr6b83a6f2019-07-26 03:17:43 +08001311 statp->event->set_private_dns_modes(convertEnumType(privateDnsStatus.mode));
Mike Yubfb1b342018-11-06 15:42:36 +08001312
1313 if (privateDnsStatus.mode == PrivateDnsMode::OFF) {
1314 *fallback = true;
1315 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001316 }
1317
Mike Yu3e829062019-08-07 14:01:14 +08001318 if (privateDnsStatus.validatedServers().empty()) {
Mike Yub601ff72018-11-01 20:07:00 +08001319 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
Mike Yubfb1b342018-11-06 15:42:36 +08001320 *fallback = true;
1321 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001322 } else {
1323 // Sleep and iterate some small number of times checking for the
1324 // arrival of resolved and validated server IP addresses, instead
1325 // of returning an immediate error.
Mike Yu4f3747b2018-12-02 17:54:29 +09001326 // This is needed because as soon as a network becomes the default network, apps will
1327 // send DNS queries on that network. If no servers have yet validated, and we do not
1328 // block those queries, they would immediately fail, causing application-visible errors.
1329 // Note that this can happen even before the network validates, since an unvalidated
1330 // network can become the default network if no validated networks are available.
1331 //
1332 // TODO: see if there is a better way to address this problem, such as buffering the
1333 // queries in a queue or only blocking queries for the first few seconds after a default
1334 // network change.
Mike Yubfb1b342018-11-06 15:42:36 +08001335 for (int i = 0; i < 42; i++) {
1336 std::this_thread::sleep_for(std::chrono::milliseconds(100));
Mike Yu3e829062019-08-07 14:01:14 +08001337 // Calling getStatus() to merely check if there's any validated server seems
1338 // wasteful. Consider adding a new method in PrivateDnsConfiguration for speed ups.
Mike Yu60248242020-07-29 16:45:26 +08001339 if (!privateDnsConfiguration.getStatus(netId).validatedServers().empty()) {
1340 privateDnsStatus = privateDnsConfiguration.getStatus(netId);
Mike Yubfb1b342018-11-06 15:42:36 +08001341 break;
1342 }
1343 }
Mike Yu3e829062019-08-07 14:01:14 +08001344 if (privateDnsStatus.validatedServers().empty()) {
Mike Yubfb1b342018-11-06 15:42:36 +08001345 return -1;
1346 }
Mike Yub601ff72018-11-01 20:07:00 +08001347 }
1348 }
1349
chenbruceacb832c2019-02-20 19:45:50 +08001350 LOG(INFO) << __func__ << ": performing query over TLS";
Mike Yub601ff72018-11-01 20:07:00 +08001351
Mike Yu9e8cf8d2020-10-26 19:04:33 +08001352 const auto response = DnsTlsDispatcher::getInstance().query(privateDnsStatus.validatedServers(),
1353 statp, query, answer, &resplen);
Mike Yub601ff72018-11-01 20:07:00 +08001354
chenbruceacb832c2019-02-20 19:45:50 +08001355 LOG(INFO) << __func__ << ": TLS query result: " << static_cast<int>(response);
Mike Yub601ff72018-11-01 20:07:00 +08001356
1357 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
1358 // In opportunistic mode, handle falling back to cleartext in some
1359 // cases (DNS shouldn't fail if a validated opportunistic mode server
1360 // becomes unreachable for some reason).
1361 switch (response) {
Mike Yubfb1b342018-11-06 15:42:36 +08001362 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001363 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001364 return resplen;
Mike Yub601ff72018-11-01 20:07:00 +08001365 case DnsTlsTransport::Response::network_error:
Mike Yubfb1b342018-11-06 15:42:36 +08001366 // No need to set the error timeout here since it will fallback to UDP.
Mike Yub601ff72018-11-01 20:07:00 +08001367 case DnsTlsTransport::Response::internal_error:
1368 // Note: this will cause cleartext queries to be emitted, with
1369 // all of the EDNS0 goodness enabled. Fingers crossed. :-/
Mike Yubfb1b342018-11-06 15:42:36 +08001370 *fallback = true;
1371 [[fallthrough]];
Mike Yub601ff72018-11-01 20:07:00 +08001372 default:
Mike Yubfb1b342018-11-06 15:42:36 +08001373 return -1;
1374 }
1375 } else {
1376 // Strict mode
1377 switch (response) {
1378 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001379 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001380 return resplen;
1381 case DnsTlsTransport::Response::network_error:
1382 // This case happens when the query stored in DnsTlsTransport is expired since
1383 // either 1) the query has been tried for 3 times but no response or 2) fail to
1384 // establish the connection with the server.
Luke Huangd7aa7b42018-11-21 20:37:50 +08001385 *rcode = RCODE_TIMEOUT;
Mike Yubfb1b342018-11-06 15:42:36 +08001386 [[fallthrough]];
1387 default:
1388 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001389 }
1390 }
Mike Yub601ff72018-11-01 20:07:00 +08001391}
Luke Huang4973a0d2018-11-19 20:17:26 +08001392
Luke Huangba7bef92018-12-26 16:53:03 +08001393int resolv_res_nsend(const android_net_context* netContext, const uint8_t* msg, int msgLen,
lifr94981782019-05-17 21:15:19 +08001394 uint8_t* ans, int ansLen, int* rcode, uint32_t flags,
1395 NetworkDnsEventReported* event) {
1396 assert(event != nullptr);
Luke Huang1b3f4462020-12-04 17:48:39 +08001397 ResState res(netContext, event);
Mike Yu021c3e12019-10-08 17:29:34 +08001398 resolv_populate_res_for_net(&res);
Luke Huang4973a0d2018-11-19 20:17:26 +08001399 *rcode = NOERROR;
Bernie Innocenti08487112019-10-11 21:14:13 +09001400 return res_nsend(&res, msg, msgLen, ans, ansLen, rcode, flags);
Bernie Innocentiec4219b2019-01-30 11:16:36 +09001401}