blob: a10bbd1320850442bfb5c46a6933ba4d8f8a97ee [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 Huang5b30e712020-05-01 11:09:42 +000079#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>
98
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +090099#include <android-base/logging.h>
Luke Huang3caa42b2020-04-23 14:18:04 +0000100#include <android-base/result.h>
Bernie Innocenti758005f2019-02-19 18:08:36 +0900101#include <android/multinetwork.h> // ResNsendFlags
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900102
Mike Yub601ff72018-11-01 20:07:00 +0800103#include <netdutils/Slice.h>
lifr94981782019-05-17 21:15:19 +0800104#include <netdutils/Stopwatch.h>
Bernie Innocentiec4219b2019-01-30 11:16:36 +0900105#include "DnsTlsDispatcher.h"
106#include "DnsTlsTransport.h"
Luke Huang68fa5002020-04-23 15:48:47 +0000107#include "Experiments.h"
Bernie Innocentiec4219b2019-01-30 11:16:36 +0900108#include "PrivateDnsConfiguration.h"
Bernie Innocentiac18b122018-10-01 23:10:18 +0900109#include "netd_resolv/resolv.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900110#include "private/android_filesystem_config.h"
Bernie Innocenti10a90282020-01-23 23:28:00 +0900111
112#include "res_comp.h"
Mike Yu34433c62019-08-20 20:17:36 +0800113#include "res_debug.h"
Bernie Innocenti08487112019-10-11 21:14:13 +0900114#include "res_init.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 Huang5b30e712020-05-01 11:09:42 +0000120using 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 Huang3caa42b2020-04-23 14:18:04 +0000122using android::base::ErrnoError;
123using android::base::Result;
chenbruce99cbfd82019-09-05 15:08:13 +0800124using android::net::CacheStatus;
125using android::net::DnsQueryEvent;
126using android::net::DnsTlsDispatcher;
127using android::net::DnsTlsTransport;
128using android::net::gPrivateDnsConfiguration;
129using android::net::IpVersion;
130using android::net::IV_IPV4;
131using android::net::IV_IPV6;
132using android::net::IV_UNKNOWN;
lifr94981782019-05-17 21:15:19 +0800133using android::net::NetworkDnsEventReported;
chenbruce99cbfd82019-09-05 15:08:13 +0800134using android::net::NS_T_INVALID;
135using android::net::NsRcode;
136using android::net::NsType;
137using android::net::PrivateDnsMode;
138using android::net::PrivateDnsModes;
139using android::net::PrivateDnsStatus;
140using android::net::PROTO_TCP;
141using android::net::PROTO_UDP;
Mike Yue655b1d2019-08-28 17:49:59 +0800142using android::netdutils::IPSockAddr;
Bernie Innocentiec4219b2019-01-30 11:16:36 +0900143using android::netdutils::Slice;
lifr94981782019-05-17 21:15:19 +0800144using android::netdutils::Stopwatch;
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900145
Mike Yub601ff72018-11-01 20:07:00 +0800146static DnsTlsDispatcher sDnsTlsDispatcher;
147
Mike Yue48f7b52020-02-10 14:55:06 +0800148static int send_vc(res_state statp, res_params* params, const uint8_t* buf, int buflen,
149 uint8_t* ans, int anssiz, int* terrno, size_t ns, time_t* at, int* rcode,
150 int* delay);
151static int send_dg(res_state statp, res_params* params, const uint8_t* buf, int buflen,
Luke Huang3caa42b2020-04-23 14:18:04 +0000152 uint8_t* ans, int anssiz, int* terrno, size_t* ns, int* v_circuit,
Mike Yue48f7b52020-02-10 14:55:06 +0800153 int* gotsomewhere, time_t* at, int* rcode, int* delay);
154
chenbruce018fdb22019-06-12 18:08:04 +0800155static void dump_error(const char*, const struct sockaddr*, int);
chenbruceacb832c2019-02-20 19:45:50 +0800156
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900157static int sock_eq(struct sockaddr*, struct sockaddr*);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900158static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
159 const struct timespec timeout);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900160static int retrying_poll(const int sock, short events, const struct timespec* finish);
Luke Huangd7aa7b42018-11-21 20:37:50 +0800161static int res_tls_send(res_state, const Slice query, const Slice answer, int* rcode,
Mike Yubfb1b342018-11-06 15:42:36 +0800162 bool* fallback);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900163
lifr94981782019-05-17 21:15:19 +0800164NsType getQueryType(const uint8_t* msg, size_t msgLen) {
165 ns_msg handle;
166 ns_rr rr;
167 if (ns_initparse((const uint8_t*)msg, msgLen, &handle) < 0 ||
168 ns_parserr(&handle, ns_s_qd, 0, &rr) < 0) {
169 return NS_T_INVALID;
170 }
171 return static_cast<NsType>(ns_rr_type(rr));
172}
173
174IpVersion ipFamilyToIPVersion(const int ipFamily) {
175 switch (ipFamily) {
176 case AF_INET:
177 return IV_IPV4;
178 case AF_INET6:
179 return IV_IPV6;
180 default:
181 return IV_UNKNOWN;
182 }
183}
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900184
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900185// BEGIN: Code copied from ISC eventlib
186// TODO: move away from this code
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900187#define BILLION 1000000000
188
189static struct timespec evConsTime(time_t sec, long nsec) {
190 struct timespec x;
191
192 x.tv_sec = sec;
193 x.tv_nsec = nsec;
194 return (x);
195}
196
197static struct timespec evAddTime(struct timespec addend1, struct timespec addend2) {
198 struct timespec x;
199
200 x.tv_sec = addend1.tv_sec + addend2.tv_sec;
201 x.tv_nsec = addend1.tv_nsec + addend2.tv_nsec;
202 if (x.tv_nsec >= BILLION) {
203 x.tv_sec++;
204 x.tv_nsec -= BILLION;
205 }
206 return (x);
207}
208
209static struct timespec evSubTime(struct timespec minuend, struct timespec subtrahend) {
210 struct timespec x;
211
212 x.tv_sec = minuend.tv_sec - subtrahend.tv_sec;
213 if (minuend.tv_nsec >= subtrahend.tv_nsec)
214 x.tv_nsec = minuend.tv_nsec - subtrahend.tv_nsec;
215 else {
216 x.tv_nsec = BILLION - subtrahend.tv_nsec + minuend.tv_nsec;
217 x.tv_sec--;
218 }
219 return (x);
220}
221
222static int evCmpTime(struct timespec a, struct timespec b) {
223#define SGN(x) ((x) < 0 ? (-1) : (x) > 0 ? (1) : (0));
224 time_t s = a.tv_sec - b.tv_sec;
225 long n;
226
227 if (s != 0) return SGN(s);
228
229 n = a.tv_nsec - b.tv_nsec;
230 return SGN(n);
231}
232
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900233static struct timespec evNowTime(void) {
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900234 struct timespec tsnow;
Bernie Innocentic1834822018-08-31 16:11:41 +0900235 clock_gettime(CLOCK_REALTIME, &tsnow);
236 return tsnow;
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900237}
238
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900239// END: Code copied from ISC eventlib
240
lifr94981782019-05-17 21:15:19 +0800241/* BIONIC-BEGIN: implement source port randomization */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900242static int random_bind(int s, int family) {
nuccachenb980f2f2018-10-23 17:10:58 +0800243 sockaddr_union u;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900244 int j;
245 socklen_t slen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900246
247 /* clear all, this also sets the IP4/6 address to 'any' */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900248 memset(&u, 0, sizeof u);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900249
250 switch (family) {
251 case AF_INET:
252 u.sin.sin_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900253 slen = sizeof u.sin;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900254 break;
255 case AF_INET6:
256 u.sin6.sin6_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900257 slen = sizeof u.sin6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900258 break;
259 default:
260 errno = EPROTO;
261 return -1;
262 }
263
264 /* first try to bind to a random source port a few times */
265 for (j = 0; j < 10; j++) {
266 /* find a random port between 1025 .. 65534 */
Luke Huangdda920f2019-02-13 14:05:02 +0800267 int port = 1025 + (arc4random_uniform(65535 - 1025));
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900268 if (family == AF_INET)
269 u.sin.sin_port = htons(port);
270 else
271 u.sin6.sin6_port = htons(port);
272
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900273 if (!bind(s, &u.sa, slen)) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900274 }
275
Bernie Innocenti9c575932018-09-07 21:10:25 +0900276 // nothing after 10 attempts, our network table is probably busy
277 // let the system decide which port is best
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900278 if (family == AF_INET)
279 u.sin.sin_port = 0;
280 else
281 u.sin6.sin6_port = 0;
282
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900283 return bind(s, &u.sa, slen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900284}
285/* BIONIC-END */
286
Luke Huang70931aa2019-01-31 11:57:41 +0800287// Disables all nameservers other than selectedServer
288static void res_set_usable_server(int selectedServer, int nscount, bool usable_servers[]) {
289 int usableIndex = 0;
290 for (int ns = 0; ns < nscount; ns++) {
291 if (usable_servers[ns]) ++usableIndex;
292 if (usableIndex != selectedServer) usable_servers[ns] = false;
293 }
294}
295
Luke Huang3caa42b2020-04-23 14:18:04 +0000296// Looks up the nameserver address in res.nsaddrs[], returns the ns number if found, otherwise -1.
297static int res_ourserver_p(res_state statp, const sockaddr* sa) {
Bernie Innocenti2e8540b2018-09-26 11:52:04 +0900298 const sockaddr_in *inp, *srv;
299 const sockaddr_in6 *in6p, *srv6;
Luke Huang3caa42b2020-04-23 14:18:04 +0000300 int ns = 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900301 switch (sa->sa_family) {
302 case AF_INET:
303 inp = (const struct sockaddr_in*) (const void*) sa;
Luke Huang3caa42b2020-04-23 14:18:04 +0000304
Mike Yue48f7b52020-02-10 14:55:06 +0800305 for (const IPSockAddr& ipsa : statp->nsaddrs) {
306 sockaddr_storage ss = ipsa;
307 srv = reinterpret_cast<sockaddr_in*>(&ss);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900308 if (srv->sin_family == inp->sin_family && srv->sin_port == inp->sin_port &&
309 (srv->sin_addr.s_addr == INADDR_ANY ||
310 srv->sin_addr.s_addr == inp->sin_addr.s_addr))
Luke Huang3caa42b2020-04-23 14:18:04 +0000311 return ns;
312 ++ns;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900313 }
314 break;
315 case AF_INET6:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900316 in6p = (const struct sockaddr_in6*) (const void*) sa;
Mike Yue48f7b52020-02-10 14:55:06 +0800317 for (const IPSockAddr& ipsa : statp->nsaddrs) {
318 sockaddr_storage ss = ipsa;
319 srv6 = reinterpret_cast<sockaddr_in6*>(&ss);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900320 if (srv6->sin6_family == in6p->sin6_family && srv6->sin6_port == in6p->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900321#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900322 (srv6->sin6_scope_id == 0 || srv6->sin6_scope_id == in6p->sin6_scope_id) &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900323#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900324 (IN6_IS_ADDR_UNSPECIFIED(&srv6->sin6_addr) ||
325 IN6_ARE_ADDR_EQUAL(&srv6->sin6_addr, &in6p->sin6_addr)))
Luke Huang3caa42b2020-04-23 14:18:04 +0000326 return ns;
327 ++ns;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900328 }
329 break;
330 default:
331 break;
332 }
Luke Huang3caa42b2020-04-23 14:18:04 +0000333 return -1;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900334}
335
336/* int
Bernie Innocenti9c575932018-09-07 21:10:25 +0900337 * res_nameinquery(name, type, cl, buf, eom)
338 * look for (name, type, cl) in the query section of packet (buf, eom)
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900339 * requires:
340 * buf + HFIXEDSZ <= eom
341 * returns:
342 * -1 : format error
343 * 0 : not found
344 * >0 : found
345 * author:
346 * paul vixie, 29may94
347 */
chenbrucec51f1212019-09-12 16:59:33 +0800348int res_nameinquery(const char* name, int type, int cl, const uint8_t* buf, const uint8_t* eom) {
349 const uint8_t* cp = buf + HFIXEDSZ;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900350 int qdcount = ntohs(((const HEADER*) (const void*) buf)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900351
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900352 while (qdcount-- > 0) {
353 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900354 int n = dn_expand(buf, eom, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900355 if (n < 0) return (-1);
356 cp += n;
357 if (cp + 2 * INT16SZ > eom) return (-1);
chenbruce0d470422019-03-28 18:44:37 +0800358 int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900359 cp += INT16SZ;
chenbruce0d470422019-03-28 18:44:37 +0800360 int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900361 cp += INT16SZ;
Bernie Innocenti9c575932018-09-07 21:10:25 +0900362 if (ttype == type && tclass == cl && ns_samename(tname, name) == 1) return (1);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900363 }
364 return (0);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900365}
366
367/* int
368 * res_queriesmatch(buf1, eom1, buf2, eom2)
369 * is there a 1:1 mapping of (name,type,class)
370 * in (buf1,eom1) and (buf2,eom2)?
371 * returns:
372 * -1 : format error
373 * 0 : not a 1:1 mapping
374 * >0 : is a 1:1 mapping
375 * author:
376 * paul vixie, 29may94
377 */
chenbrucec51f1212019-09-12 16:59:33 +0800378int res_queriesmatch(const uint8_t* buf1, const uint8_t* eom1, const uint8_t* buf2,
379 const uint8_t* eom2) {
380 const uint8_t* cp = buf1 + HFIXEDSZ;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900381 int qdcount = ntohs(((const HEADER*) (const void*) buf1)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900382
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900383 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2) return (-1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900384
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900385 /*
386 * Only header section present in replies to
387 * dynamic update packets.
388 */
389 if ((((const HEADER*) (const void*) buf1)->opcode == ns_o_update) &&
390 (((const HEADER*) (const void*) buf2)->opcode == ns_o_update))
391 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900392
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900393 if (qdcount != ntohs(((const HEADER*) (const void*) buf2)->qdcount)) return (0);
394 while (qdcount-- > 0) {
395 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900396 int n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900397 if (n < 0) return (-1);
398 cp += n;
399 if (cp + 2 * INT16SZ > eom1) return (-1);
chenbruce0d470422019-03-28 18:44:37 +0800400 int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900401 cp += INT16SZ;
chenbruce0d470422019-03-28 18:44:37 +0800402 int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900403 cp += INT16SZ;
404 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2)) return (0);
405 }
406 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900407}
408
lifr94981782019-05-17 21:15:19 +0800409static DnsQueryEvent* addDnsQueryEvent(NetworkDnsEventReported* event) {
410 return event->mutable_dns_query_events()->add_dns_query_event();
411}
412
chenbrucec51f1212019-09-12 16:59:33 +0800413int res_nsend(res_state statp, const uint8_t* buf, int buflen, uint8_t* ans, int anssiz, int* rcode,
Luke Huang5b30e712020-05-01 11:09:42 +0000414 uint32_t flags, std::chrono::milliseconds sleepTimeMs) {
Luke Huang43cc1b12019-10-15 19:06:42 +0900415 LOG(DEBUG) << __func__;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900416
Luke Huang43cc1b12019-10-15 19:06:42 +0900417 // Should not happen
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900418 if (anssiz < HFIXEDSZ) {
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800419 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900420 errno = EINVAL;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800421 return -EINVAL;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900422 }
chenbrucedd210722019-03-06 13:52:43 +0800423 res_pquery(buf, buflen);
chenbruceacb832c2019-02-20 19:45:50 +0800424
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900425 int anslen = 0;
lifrd4d9fbb2019-07-31 20:18:35 +0800426 Stopwatch cacheStopwatch;
Luke Huang43cc1b12019-10-15 19:06:42 +0900427 ResolvCacheStatus cache_status =
428 resolv_cache_lookup(statp->netid, buf, buflen, ans, anssiz, &anslen, flags);
lifrd4d9fbb2019-07-31 20:18:35 +0800429 const int32_t cacheLatencyUs = saturate_cast<int32_t>(cacheStopwatch.timeTakenUs());
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900430 if (cache_status == RESOLV_CACHE_FOUND) {
Luke Huang83c9b4b2019-02-27 18:18:01 +0800431 HEADER* hp = (HEADER*)(void*)ans;
432 *rcode = hp->rcode;
lifr94981782019-05-17 21:15:19 +0800433 DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
434 dnsQueryEvent->set_latency_micros(cacheLatencyUs);
435 dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
lifre02d01c2019-12-31 17:24:57 +0800436 dnsQueryEvent->set_type(getQueryType(buf, buflen));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900437 return anslen;
438 } else if (cache_status != RESOLV_CACHE_UNSUPPORTED) {
439 // had a cache miss for a known network, so populate the thread private
440 // data so the normal resolve path can do its thing
Mike Yu021c3e12019-10-08 17:29:34 +0800441 resolv_populate_res_for_net(statp);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900442 }
Mike Yuecc52822020-02-14 14:36:46 +0800443 if (statp->nameserverCount() == 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900444 // We have no nameservers configured, so there's no point trying.
445 // Tell the cache the query failed, or any retries and anyone else asking the same
446 // question will block for PENDING_REQUEST_TIMEOUT seconds instead of failing fast.
Luke Huangba7bef92018-12-26 16:53:03 +0800447 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800448
449 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900450 errno = ESRCH;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800451 return -ESRCH;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900452 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900453
Luke Huang5b30e712020-05-01 11:09:42 +0000454 // If parallel_lookup is enabled, it might be required to wait some time to avoid
455 // gateways drop packets if queries are sent too close together
456 if (sleepTimeMs != 0ms) {
457 std::this_thread::sleep_for(sleepTimeMs);
458 }
Luke Huang272cb192019-10-15 16:52:28 +0900459 // DoT
460 if (!(statp->netcontext_flags & NET_CONTEXT_FLAG_USE_LOCAL_NAMESERVERS)) {
461 bool fallback = false;
Luke Huang43cc1b12019-10-15 19:06:42 +0900462 int resplen = res_tls_send(statp, Slice(const_cast<uint8_t*>(buf), buflen),
463 Slice(ans, anssiz), rcode, &fallback);
Luke Huang272cb192019-10-15 16:52:28 +0900464 if (resplen > 0) {
465 LOG(DEBUG) << __func__ << ": got answer from DoT";
466 res_pquery(ans, resplen);
467 if (cache_status == RESOLV_CACHE_NOTFOUND) {
468 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
469 }
470 return resplen;
471 }
472 if (!fallback) {
473 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huang43cc1b12019-10-15 19:06:42 +0900474 return -ETIMEDOUT;
Luke Huang272cb192019-10-15 16:52:28 +0900475 }
476 }
477
Mike Yuc573a3d2020-02-07 20:15:15 +0800478 res_stats stats[MAXNS]{};
Bernie Innocenti758005f2019-02-19 18:08:36 +0900479 res_params params;
Mike Yuc573a3d2020-02-07 20:15:15 +0800480 int revision_id = resolv_cache_get_resolver_stats(statp->netid, &params, stats, statp->nsaddrs);
lifra1b37f12019-02-13 17:33:57 +0800481 if (revision_id < 0) {
482 // TODO: Remove errno once callers stop using it
483 errno = ESRCH;
484 return -ESRCH;
485 }
waynema0161acd2019-02-18 17:47:59 +0800486 bool usable_servers[MAXNS];
Luke Huang70931aa2019-01-31 11:57:41 +0800487 int usableServersCount = android_net_res_stats_get_usable_servers(
Mike Yuecc52822020-02-14 14:36:46 +0800488 &params, stats, statp->nameserverCount(), usable_servers);
Luke Huang70931aa2019-01-31 11:57:41 +0800489
490 if ((flags & ANDROID_RESOLV_NO_RETRY) && usableServersCount > 1) {
491 auto hp = reinterpret_cast<const HEADER*>(buf);
492
493 // Select a random server based on the query id
494 int selectedServer = (hp->id % usableServersCount) + 1;
Mike Yuecc52822020-02-14 14:36:46 +0800495 res_set_usable_server(selectedServer, statp->nameserverCount(), usable_servers);
Luke Huang70931aa2019-01-31 11:57:41 +0800496 }
waynema0161acd2019-02-18 17:47:59 +0800497
Luke Huang43cc1b12019-10-15 19:06:42 +0900498 // Send request, RETRY times, or until successful.
waynemaa74195e2019-01-18 14:02:31 +0800499 int retryTimes = (flags & ANDROID_RESOLV_NO_RETRY) ? 1 : params.retry_count;
Luke Huang43cc1b12019-10-15 19:06:42 +0900500 int useTcp = buflen > PACKETSZ;
501 int gotsomewhere = 0;
502 int terrno = ETIMEDOUT;
Luke Huangba7bef92018-12-26 16:53:03 +0800503
504 for (int attempt = 0; attempt < retryTimes; ++attempt) {
Mike Yue48f7b52020-02-10 14:55:06 +0800505 for (size_t ns = 0; ns < statp->nsaddrs.size(); ++ns) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900506 if (!usable_servers[ns]) continue;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900507
Luke Huang43cc1b12019-10-15 19:06:42 +0900508 *rcode = RCODE_INTERNAL_ERROR;
509
510 // Get server addr
Mike Yue48f7b52020-02-10 14:55:06 +0800511 const IPSockAddr& serverSockAddr = statp->nsaddrs[ns];
512 LOG(DEBUG) << __func__ << ": Querying server (# " << ns + 1
513 << ") address = " << serverSockAddr.toString();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900514
Luke Huang43cc1b12019-10-15 19:06:42 +0900515 ::android::net::Protocol query_proto = useTcp ? PROTO_TCP : PROTO_UDP;
Luke Huang3caa42b2020-04-23 14:18:04 +0000516 time_t query_time = 0;
Luke Huang43cc1b12019-10-15 19:06:42 +0900517 int delay = 0;
518 bool fallbackTCP = false;
519 const bool shouldRecordStats = (attempt == 0);
520 int resplen;
lifrd4d9fbb2019-07-31 20:18:35 +0800521 Stopwatch queryStopwatch;
lifr128183a2020-01-08 18:04:50 +0800522 int retry_count_for_event = 0;
Luke Huang3caa42b2020-04-23 14:18:04 +0000523 size_t actualNs = ns;
Luke Huang43cc1b12019-10-15 19:06:42 +0900524 if (useTcp) {
525 // TCP; at most one attempt per server.
Luke Huangba7bef92018-12-26 16:53:03 +0800526 attempt = retryTimes;
Luke Huang3caa42b2020-04-23 14:18:04 +0000527 resplen = send_vc(statp, &params, buf, buflen, ans, anssiz, &terrno, ns,
528 &query_time, rcode, &delay);
Ken Chen99344882020-01-01 14:59:38 +0800529
530 if (buflen <= PACKETSZ && resplen <= 0 &&
531 statp->tc_mode == aidl::android::net::IDnsResolver::TC_MODE_UDP_TCP) {
532 // reset to UDP for next query on next DNS server if resolver is currently doing
533 // TCP fallback retry and current server does not support TCP connectin
534 useTcp = false;
535 }
536 LOG(INFO) << __func__ << ": used send_vc " << resplen;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900537 } else {
Luke Huang43cc1b12019-10-15 19:06:42 +0900538 // UDP
Luke Huang3caa42b2020-04-23 14:18:04 +0000539 resplen = send_dg(statp, &params, buf, buflen, ans, anssiz, &terrno, &actualNs,
540 &useTcp, &gotsomewhere, &query_time, rcode, &delay);
Luke Huang43cc1b12019-10-15 19:06:42 +0900541 fallbackTCP = useTcp ? true : false;
lifr128183a2020-01-08 18:04:50 +0800542 retry_count_for_event = attempt;
Ken Chen99344882020-01-01 14:59:38 +0800543 LOG(INFO) << __func__ << ": used send_dg " << resplen;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900544 }
Luke Huang43cc1b12019-10-15 19:06:42 +0900545
Luke Huang3caa42b2020-04-23 14:18:04 +0000546 const IPSockAddr& receivedServerAddr = statp->nsaddrs[actualNs];
Luke Huang43cc1b12019-10-15 19:06:42 +0900547 DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
548 dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
Luke Huang3caa42b2020-04-23 14:18:04 +0000549 // When |retryTimes| > 1, we cannot actually know the correct latency value if we
550 // received the answer from the previous server. So temporarily set the latency as -1 if
551 // that condition happened.
552 // TODO: make the latency value accurate.
553 dnsQueryEvent->set_latency_micros(
554 (actualNs == ns) ? saturate_cast<int32_t>(queryStopwatch.timeTakenUs()) : -1);
555 dnsQueryEvent->set_dns_server_index(actualNs);
556 dnsQueryEvent->set_ip_version(ipFamilyToIPVersion(receivedServerAddr.family()));
lifr128183a2020-01-08 18:04:50 +0800557 dnsQueryEvent->set_retry_times(retry_count_for_event);
Luke Huang43cc1b12019-10-15 19:06:42 +0900558 dnsQueryEvent->set_rcode(static_cast<NsRcode>(*rcode));
559 dnsQueryEvent->set_protocol(query_proto);
560 dnsQueryEvent->set_type(getQueryType(buf, buflen));
561
562 // Only record stats the first time we try a query. This ensures that
563 // queries that deterministically fail (e.g., a name that always returns
564 // SERVFAIL or times out) do not unduly affect the stats.
565 if (shouldRecordStats) {
566 res_sample sample;
Luke Huang3caa42b2020-04-23 14:18:04 +0000567 res_stats_set_sample(&sample, query_time, *rcode, delay);
568 // KeepListening UDP mechanism is incompatible with usable_servers of legacy stats,
569 // so keep the old logic for now.
570 // TODO: Replace usable_servers of legacy stats with new one.
Mike Yue48f7b52020-02-10 14:55:06 +0800571 resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, serverSockAddr,
572 sample, params.max_samples);
Luke Huang3caa42b2020-04-23 14:18:04 +0000573 resolv_stats_add(statp->netid, receivedServerAddr, dnsQueryEvent);
Luke Huang43cc1b12019-10-15 19:06:42 +0900574 }
575
576 if (resplen == 0) continue;
577 if (fallbackTCP) {
578 ns--;
579 continue;
580 }
581 if (resplen < 0) {
582 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800583 statp->closeSockets();
Luke Huang43cc1b12019-10-15 19:06:42 +0900584 return -terrno;
585 };
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900586
Ken Chenffc224a2019-03-19 17:41:28 +0800587 LOG(DEBUG) << __func__ << ": got answer:";
chenbrucedd210722019-03-06 13:52:43 +0800588 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900589
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900590 if (cache_status == RESOLV_CACHE_NOTFOUND) {
Mike Yud1ec2542019-06-06 17:17:53 +0800591 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900592 }
Luke Huangadb0f5b2019-11-27 15:51:48 +0800593 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900594 return (resplen);
Bernie Innocenti9c575932018-09-07 21:10:25 +0900595 } // for each ns
596 } // for each retry
Luke Huangadb0f5b2019-11-27 15:51:48 +0800597 statp->closeSockets();
Luke Huang43cc1b12019-10-15 19:06:42 +0900598 terrno = useTcp ? terrno : gotsomewhere ? ETIMEDOUT : ECONNREFUSED;
599 // TODO: Remove errno once callers stop using it
600 errno = useTcp ? terrno
601 : gotsomewhere ? ETIMEDOUT /* no answer obtained */
602 : ECONNREFUSED /* no nameservers found */;
603
Luke Huangba7bef92018-12-26 16:53:03 +0800604 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800605 return -terrno;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900606}
607
chenbruce99cbfd82019-09-05 15:08:13 +0800608static struct timespec get_timeout(res_state statp, const res_params* params, const int ns) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900609 int msec;
waynemaa74195e2019-01-18 14:02:31 +0800610 // Legacy algorithm which scales the timeout by nameserver number.
611 // For instance, with 4 nameservers: 5s, 2.5s, 5s, 10s
612 // This has no effect with 1 or 2 nameservers
613 msec = params->base_timeout_msec << ns;
614 if (ns > 0) {
Mike Yuecc52822020-02-14 14:36:46 +0800615 msec /= statp->nameserverCount();
waynemaa74195e2019-01-18 14:02:31 +0800616 }
617 // For safety, don't allow OEMs and experiments to configure a timeout shorter than 1s.
618 if (msec < 1000) {
619 msec = 1000; // Use at least 1000ms
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900620 }
Ken Chenffc224a2019-03-19 17:41:28 +0800621 LOG(INFO) << __func__ << ": using timeout of " << msec << " msec";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900622
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900623 struct timespec result;
624 result.tv_sec = msec / 1000;
625 result.tv_nsec = (msec % 1000) * 1000000;
626 return result;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900627}
628
chenbrucec51f1212019-09-12 16:59:33 +0800629static int send_vc(res_state statp, res_params* params, const uint8_t* buf, int buflen,
Mike Yue48f7b52020-02-10 14:55:06 +0800630 uint8_t* ans, int anssiz, int* terrno, size_t ns, time_t* at, int* rcode,
chenbrucec51f1212019-09-12 16:59:33 +0800631 int* delay) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900632 *at = time(NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900633 *delay = 0;
634 const HEADER* hp = (const HEADER*) (const void*) buf;
635 HEADER* anhp = (HEADER*) (void*) ans;
636 struct sockaddr* nsap;
637 int nsaplen;
chenbruce0d470422019-03-28 18:44:37 +0800638 int truncating, connreset, n;
chenbrucec51f1212019-09-12 16:59:33 +0800639 uint8_t* cp;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900640
Ken Chenffc224a2019-03-19 17:41:28 +0800641 LOG(INFO) << __func__ << ": using send_vc";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900642
Mike Yue48f7b52020-02-10 14:55:06 +0800643 // It should never happen, but just in case.
644 if (ns >= statp->nsaddrs.size()) {
645 LOG(ERROR) << __func__ << ": Out-of-bound indexing: " << ns;
646 return -1;
647 }
648
649 sockaddr_storage ss = statp->nsaddrs[ns];
650 nsap = reinterpret_cast<sockaddr*>(&ss);
Mike Yu021c3e12019-10-08 17:29:34 +0800651 nsaplen = sockaddrSize(nsap);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900652
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900653 connreset = 0;
654same_ns:
655 truncating = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900656
Luke Huang3caa42b2020-04-23 14:18:04 +0000657 struct timespec start_time = evNowTime();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900658
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900659 /* Are we still talking to whom we want to talk to? */
Luke Huangadb0f5b2019-11-27 15:51:48 +0800660 if (statp->tcp_nssock >= 0 && (statp->_flags & RES_F_VC) != 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900661 struct sockaddr_storage peer;
662 socklen_t size = sizeof peer;
663 unsigned old_mark;
664 socklen_t mark_size = sizeof(old_mark);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800665 if (getpeername(statp->tcp_nssock, (struct sockaddr*)(void*)&peer, &size) < 0 ||
666 !sock_eq((struct sockaddr*)(void*)&peer, nsap) ||
667 getsockopt(statp->tcp_nssock, SOL_SOCKET, SO_MARK, &old_mark, &mark_size) < 0 ||
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900668 old_mark != statp->_mark) {
Luke Huangadb0f5b2019-11-27 15:51:48 +0800669 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900670 }
671 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900672
Luke Huangadb0f5b2019-11-27 15:51:48 +0800673 if (statp->tcp_nssock < 0 || (statp->_flags & RES_F_VC) == 0) {
674 if (statp->tcp_nssock >= 0) statp->closeSockets();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900675
Luke Huangadb0f5b2019-11-27 15:51:48 +0800676 statp->tcp_nssock.reset(socket(nsap->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0));
677 if (statp->tcp_nssock < 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900678 switch (errno) {
679 case EPROTONOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900680 case EPFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900681 case EAFNOSUPPORT:
chenbruce018fdb22019-06-12 18:08:04 +0800682 PLOG(DEBUG) << __func__ << ": socket(vc): ";
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900683 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900684 default:
685 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800686 PLOG(DEBUG) << __func__ << ": socket(vc): ";
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900687 return -1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900688 }
689 }
Luke Huangadb0f5b2019-11-27 15:51:48 +0800690 resolv_tag_socket(statp->tcp_nssock, statp->uid, statp->pid);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900691 if (statp->_mark != MARK_UNSET) {
Luke Huangadb0f5b2019-11-27 15:51:48 +0800692 if (setsockopt(statp->tcp_nssock, SOL_SOCKET, SO_MARK, &statp->_mark,
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900693 sizeof(statp->_mark)) < 0) {
694 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800695 PLOG(DEBUG) << __func__ << ": setsockopt: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900696 return -1;
697 }
698 }
699 errno = 0;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800700 if (random_bind(statp->tcp_nssock, nsap->sa_family) < 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900701 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800702 dump_error("bind/vc", nsap, nsaplen);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800703 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900704 return (0);
705 }
Luke Huangadb0f5b2019-11-27 15:51:48 +0800706 if (connect_with_timeout(statp->tcp_nssock, nsap, (socklen_t)nsaplen,
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900707 get_timeout(statp, params, ns)) < 0) {
708 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800709 dump_error("connect/vc", nsap, nsaplen);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800710 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900711 /*
712 * The way connect_with_timeout() is implemented prevents us from reliably
713 * determining whether this was really a timeout or e.g. ECONNREFUSED. Since
714 * currently both cases are handled in the same way, there is no need to
715 * change this (yet). If we ever need to reliably distinguish between these
716 * cases, both connect_with_timeout() and retrying_poll() need to be
717 * modified, though.
718 */
719 *rcode = RCODE_TIMEOUT;
720 return (0);
721 }
722 statp->_flags |= RES_F_VC;
723 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900724
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900725 /*
726 * Send length & message
727 */
chenbruce0d470422019-03-28 18:44:37 +0800728 uint16_t len = htons(static_cast<uint16_t>(buflen));
Luke Huangc98fd802019-10-15 16:36:36 +0900729 const iovec iov[] = {
730 {.iov_base = &len, .iov_len = INT16SZ},
731 {.iov_base = const_cast<uint8_t*>(buf), .iov_len = static_cast<size_t>(buflen)},
732 };
Luke Huangadb0f5b2019-11-27 15:51:48 +0800733 if (writev(statp->tcp_nssock, iov, 2) != (INT16SZ + buflen)) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900734 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800735 PLOG(DEBUG) << __func__ << ": write failed: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800736 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900737 return (0);
738 }
739 /*
740 * Receive length & response
741 */
742read_len:
743 cp = ans;
744 len = INT16SZ;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800745 while ((n = read(statp->tcp_nssock, (char*)cp, (size_t)len)) > 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900746 cp += n;
747 if ((len -= n) == 0) break;
748 }
749 if (n <= 0) {
750 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800751 PLOG(DEBUG) << __func__ << ": read failed: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800752 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900753 /*
754 * A long running process might get its TCP
755 * connection reset if the remote server was
756 * restarted. Requery the server instead of
757 * trying a new one. When there is only one
758 * server, this means that a query might work
759 * instead of failing. We only allow one reset
760 * per query to prevent looping.
761 */
762 if (*terrno == ECONNRESET && !connreset) {
763 connreset = 1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900764 goto same_ns;
765 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900766 return (0);
767 }
chenbruce0d470422019-03-28 18:44:37 +0800768 uint16_t resplen = ntohs(*reinterpret_cast<const uint16_t*>(ans));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900769 if (resplen > anssiz) {
Ken Chenffc224a2019-03-19 17:41:28 +0800770 LOG(DEBUG) << __func__ << ": response truncated";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900771 truncating = 1;
772 len = anssiz;
773 } else
774 len = resplen;
775 if (len < HFIXEDSZ) {
776 /*
777 * Undersized message.
778 */
Ken Chenffc224a2019-03-19 17:41:28 +0800779 LOG(DEBUG) << __func__ << ": undersized: " << len;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900780 *terrno = EMSGSIZE;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800781 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900782 return (0);
783 }
784 cp = ans;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800785 while (len != 0 && (n = read(statp->tcp_nssock, (char*)cp, (size_t)len)) > 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900786 cp += n;
787 len -= n;
788 }
789 if (n <= 0) {
790 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800791 PLOG(DEBUG) << __func__ << ": read(vc): ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800792 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900793 return (0);
794 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900795
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900796 if (truncating) {
797 /*
798 * Flush rest of answer so connection stays in synch.
799 */
800 anhp->tc = 1;
801 len = resplen - anssiz;
802 while (len != 0) {
803 char junk[PACKETSZ];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900804
Luke Huangadb0f5b2019-11-27 15:51:48 +0800805 n = read(statp->tcp_nssock, junk, (len > sizeof junk) ? sizeof junk : len);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900806 if (n > 0)
807 len -= n;
808 else
809 break;
810 }
811 }
812 /*
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900813 * If the calling application has bailed out of
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900814 * a previous call and failed to arrange to have
815 * the circuit closed or the server has got
816 * itself confused, then drop the packet and
817 * wait for the correct one.
818 */
819 if (hp->id != anhp->id) {
Ken Chenffc224a2019-03-19 17:41:28 +0800820 LOG(DEBUG) << __func__ << ": ld answer (unexpected):";
chenbrucedd210722019-03-06 13:52:43 +0800821 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900822 goto read_len;
823 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900824
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900825 /*
826 * All is well, or the error is fatal. Signal that the
827 * next nameserver ought not be tried.
828 */
829 if (resplen > 0) {
830 struct timespec done = evNowTime();
Luke Huang3caa42b2020-04-23 14:18:04 +0000831 *delay = res_stats_calculate_rtt(&done, &start_time);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900832 *rcode = anhp->rcode;
833 }
834 return (resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900835}
836
837/* return -1 on error (errno set), 0 on success */
Luke Huangc98fd802019-10-15 16:36:36 +0900838static int connect_with_timeout(int sock, const sockaddr* nsap, socklen_t salen,
839 const timespec timeout) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900840 int res, origflags;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900841
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900842 origflags = fcntl(sock, F_GETFL, 0);
843 fcntl(sock, F_SETFL, origflags | O_NONBLOCK);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900844
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900845 res = connect(sock, nsap, salen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900846 if (res < 0 && errno != EINPROGRESS) {
847 res = -1;
848 goto done;
849 }
850 if (res != 0) {
Luke Huangc98fd802019-10-15 16:36:36 +0900851 timespec now = evNowTime();
852 timespec finish = evAddTime(now, timeout);
Ken Chenffc224a2019-03-19 17:41:28 +0800853 LOG(INFO) << __func__ << ": " << sock << " send_vc";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900854 res = retrying_poll(sock, POLLIN | POLLOUT, &finish);
855 if (res <= 0) {
856 res = -1;
857 }
858 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900859done:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900860 fcntl(sock, F_SETFL, origflags);
Ken Chenffc224a2019-03-19 17:41:28 +0800861 LOG(INFO) << __func__ << ": " << sock << " connect_with_const timeout returning " << res;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900862 return res;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900863}
864
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900865static int retrying_poll(const int sock, const short events, const struct timespec* finish) {
866 struct timespec now, timeout;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900867
868retry:
Ken Chenffc224a2019-03-19 17:41:28 +0800869 LOG(INFO) << __func__ << ": " << sock << " retrying_poll";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900870
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900871 now = evNowTime();
872 if (evCmpTime(*finish, now) > 0)
873 timeout = evSubTime(*finish, now);
874 else
875 timeout = evConsTime(0L, 0L);
876 struct pollfd fds = {.fd = sock, .events = events};
Treehugger Robotbcb51802020-04-24 03:57:49 +0000877 int n = ppoll(&fds, 1, &timeout, /*__mask=*/NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900878 if (n == 0) {
Luke Huang3caa42b2020-04-23 14:18:04 +0000879 LOG(INFO) << __func__ << ": " << sock << " retrying_poll timeout";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900880 errno = ETIMEDOUT;
881 return 0;
882 }
883 if (n < 0) {
884 if (errno == EINTR) goto retry;
Ken Chenffc224a2019-03-19 17:41:28 +0800885 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll failed";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900886 return n;
887 }
888 if (fds.revents & (POLLIN | POLLOUT | POLLERR)) {
889 int error;
890 socklen_t len = sizeof(error);
891 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error) {
892 errno = error;
Ken Chenffc224a2019-03-19 17:41:28 +0800893 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll getsockopt failed";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900894 return -1;
895 }
896 }
Ken Chenffc224a2019-03-19 17:41:28 +0800897 LOG(INFO) << __func__ << ": " << sock << " retrying_poll returning " << n;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900898 return n;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900899}
900
Luke Huang3caa42b2020-04-23 14:18:04 +0000901static std::vector<pollfd> extractUdpFdset(res_state statp, const short events = POLLIN) {
902 std::vector<pollfd> fdset(statp->nsaddrs.size());
903 for (size_t i = 0; i < statp->nsaddrs.size(); ++i) {
904 fdset[i] = {.fd = statp->nssocks[i], .events = events};
905 }
906 return fdset;
907}
908
909static Result<std::vector<int>> udpRetryingPoll(res_state statp, const timespec* finish) {
910 for (;;) {
911 LOG(DEBUG) << __func__ << ": poll";
912 timespec start_time = evNowTime();
913 timespec timeout = (evCmpTime(*finish, start_time) > 0) ? evSubTime(*finish, start_time)
914 : evConsTime(0L, 0L);
915 std::vector<pollfd> fdset = extractUdpFdset(statp);
Treehugger Robotbcb51802020-04-24 03:57:49 +0000916 const int n = ppoll(fdset.data(), fdset.size(), &timeout, /*__mask=*/nullptr);
Luke Huang3caa42b2020-04-23 14:18:04 +0000917 if (n <= 0) {
918 if (errno == EINTR && n < 0) continue;
919 if (n == 0) errno = ETIMEDOUT;
920 PLOG(INFO) << __func__ << ": failed";
921 return ErrnoError();
922 }
923 std::vector<int> fdsToRead;
924 for (const auto& pollfd : fdset) {
925 if (pollfd.revents & (POLLIN | POLLERR)) {
926 fdsToRead.push_back(pollfd.fd);
927 }
928 }
929 LOG(DEBUG) << __func__ << ": "
930 << " returning fd size: " << fdsToRead.size();
931 return fdsToRead;
932 }
933}
934
935static Result<std::vector<int>> udpRetryingPollWrapper(res_state statp, int ns,
936 const timespec* finish) {
Luke Huang68fa5002020-04-23 15:48:47 +0000937 const bool keepListeningUdp =
938 android::net::Experiments::getInstance()->getFlag("keep_listening_udp", 0);
Luke Huang3caa42b2020-04-23 14:18:04 +0000939 if (keepListeningUdp) return udpRetryingPoll(statp, finish);
940
941 if (int n = retrying_poll(statp->nssocks[ns], POLLIN, finish); n <= 0) {
942 return ErrnoError();
943 }
944 return std::vector<int>{statp->nssocks[ns]};
945}
946
Luke Huangbff43fc2019-11-12 15:54:47 +0800947bool ignoreInvalidAnswer(res_state statp, const sockaddr_storage& from, const uint8_t* buf,
Luke Huang3caa42b2020-04-23 14:18:04 +0000948 int buflen, uint8_t* ans, int anssiz, int* receivedFromNs) {
Luke Huangbff43fc2019-11-12 15:54:47 +0800949 const HEADER* hp = (const HEADER*)(const void*)buf;
950 HEADER* anhp = (HEADER*)(void*)ans;
951 if (hp->id != anhp->id) {
952 // response from old query, ignore it.
953 LOG(DEBUG) << __func__ << ": old answer:";
954 return true;
955 }
Luke Huang3caa42b2020-04-23 14:18:04 +0000956 if (*receivedFromNs = res_ourserver_p(statp, (sockaddr*)(void*)&from); *receivedFromNs < 0) {
Luke Huangbff43fc2019-11-12 15:54:47 +0800957 // response from wrong server? ignore it.
958 LOG(DEBUG) << __func__ << ": not our server:";
959 return true;
960 }
961 if (!res_queriesmatch(buf, buf + buflen, ans, ans + anssiz)) {
962 // response contains wrong query? ignore it.
963 LOG(DEBUG) << __func__ << ": wrong query name:";
964 return true;
965 }
966 return false;
967}
968
chenbrucec51f1212019-09-12 16:59:33 +0800969static int send_dg(res_state statp, res_params* params, const uint8_t* buf, int buflen,
Luke Huang3caa42b2020-04-23 14:18:04 +0000970 uint8_t* ans, int anssiz, int* terrno, size_t* ns, int* v_circuit,
Mike Yue48f7b52020-02-10 14:55:06 +0800971 int* gotsomewhere, time_t* at, int* rcode, int* delay) {
972 // It should never happen, but just in case.
Luke Huang3caa42b2020-04-23 14:18:04 +0000973 if (*ns >= statp->nsaddrs.size()) {
Mike Yue48f7b52020-02-10 14:55:06 +0800974 LOG(ERROR) << __func__ << ": Out-of-bound indexing: " << ns;
975 return -1;
976 }
977
Luke Huangbff43fc2019-11-12 15:54:47 +0800978 *at = time(nullptr);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900979 *delay = 0;
Luke Huang3caa42b2020-04-23 14:18:04 +0000980 const sockaddr_storage ss = statp->nsaddrs[*ns];
Mike Yue48f7b52020-02-10 14:55:06 +0800981 const sockaddr* nsap = reinterpret_cast<const sockaddr*>(&ss);
Luke Huangbff43fc2019-11-12 15:54:47 +0800982 const int nsaplen = sockaddrSize(nsap);
983
Luke Huang3caa42b2020-04-23 14:18:04 +0000984 if (statp->nssocks[*ns] == -1) {
985 statp->nssocks[*ns].reset(socket(nsap->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0));
986 if (statp->nssocks[*ns] < 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900987 switch (errno) {
988 case EPROTONOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900989 case EPFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900990 case EAFNOSUPPORT:
chenbruce018fdb22019-06-12 18:08:04 +0800991 PLOG(DEBUG) << __func__ << ": socket(dg): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900992 return (0);
993 default:
994 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800995 PLOG(DEBUG) << __func__ << ": socket(dg): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900996 return (-1);
997 }
998 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900999
Luke Huang3caa42b2020-04-23 14:18:04 +00001000 resolv_tag_socket(statp->nssocks[*ns], statp->uid, statp->pid);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001001 if (statp->_mark != MARK_UNSET) {
Luke Huang3caa42b2020-04-23 14:18:04 +00001002 if (setsockopt(statp->nssocks[*ns], SOL_SOCKET, SO_MARK, &(statp->_mark),
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001003 sizeof(statp->_mark)) < 0) {
Luke Huangadb0f5b2019-11-27 15:51:48 +08001004 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001005 return -1;
1006 }
1007 }
chenbruceb9cce7b2019-07-15 16:14:53 +08001008 // Use a "connected" datagram socket to receive an ECONNREFUSED error
1009 // on the next socket operation when the server responds with an
1010 // ICMP port-unreachable error. This way we can detect the absence of
1011 // a nameserver without timing out.
Luke Huang3caa42b2020-04-23 14:18:04 +00001012 if (random_bind(statp->nssocks[*ns], nsap->sa_family) < 0) {
chenbruce018fdb22019-06-12 18:08:04 +08001013 dump_error("bind(dg)", nsap, nsaplen);
Luke Huangadb0f5b2019-11-27 15:51:48 +08001014 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001015 return (0);
1016 }
Luke Huang3caa42b2020-04-23 14:18:04 +00001017 if (connect(statp->nssocks[*ns], nsap, (socklen_t)nsaplen) < 0) {
chenbruce018fdb22019-06-12 18:08:04 +08001018 dump_error("connect(dg)", nsap, nsaplen);
Luke Huangadb0f5b2019-11-27 15:51:48 +08001019 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001020 return (0);
1021 }
Ken Chenffc224a2019-03-19 17:41:28 +08001022 LOG(DEBUG) << __func__ << ": new DG socket";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001023 }
Luke Huang3caa42b2020-04-23 14:18:04 +00001024 if (send(statp->nssocks[*ns], (const char*)buf, (size_t)buflen, 0) != buflen) {
chenbruce018fdb22019-06-12 18:08:04 +08001025 PLOG(DEBUG) << __func__ << ": send: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +08001026 statp->closeSockets();
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001027 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001028 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001029
Luke Huang3caa42b2020-04-23 14:18:04 +00001030 timespec timeout = get_timeout(statp, params, *ns);
1031 timespec start_time = evNowTime();
1032 timespec finish = evAddTime(start_time, timeout);
Luke Huangbff43fc2019-11-12 15:54:47 +08001033 for (;;) {
1034 // Wait for reply.
Luke Huang3caa42b2020-04-23 14:18:04 +00001035 auto result = udpRetryingPollWrapper(statp, *ns, &finish);
1036
1037 if (!result.has_value()) {
1038 const bool isTimeout = (result.error().code() == ETIMEDOUT);
1039 *rcode = (isTimeout) ? RCODE_TIMEOUT : *rcode;
1040 *gotsomewhere = (isTimeout) ? 1 : *gotsomewhere;
1041 // Leave the UDP sockets open on timeout so we can keep listening for
1042 // a late response from this server while retrying on the next server.
1043 if (!isTimeout) statp->closeSockets();
1044 LOG(DEBUG) << __func__ << ": " << (isTimeout) ? "timeout" : "poll";
1045 return 0;
1046 }
1047 bool needRetry = false;
1048 for (int fd : result.value()) {
1049 needRetry = false;
1050 sockaddr_storage from;
1051 socklen_t fromlen = sizeof(from);
1052 int resplen =
1053 recvfrom(fd, (char*)ans, (size_t)anssiz, 0, (sockaddr*)(void*)&from, &fromlen);
1054 if (resplen <= 0) {
1055 PLOG(DEBUG) << __func__ << ": recvfrom: ";
1056 continue;
1057 }
Luke Huangbff43fc2019-11-12 15:54:47 +08001058 *gotsomewhere = 1;
Luke Huang3caa42b2020-04-23 14:18:04 +00001059 if (resplen < HFIXEDSZ) {
1060 // Undersized message.
1061 LOG(DEBUG) << __func__ << ": undersized: " << resplen;
1062 *terrno = EMSGSIZE;
1063 continue;
1064 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001065
Luke Huang3caa42b2020-04-23 14:18:04 +00001066 int receivedFromNs = *ns;
1067 if (needRetry =
1068 ignoreInvalidAnswer(statp, from, buf, buflen, ans, anssiz, &receivedFromNs);
1069 needRetry) {
1070 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
1071 continue;
1072 }
Luke Huangbff43fc2019-11-12 15:54:47 +08001073
Luke Huang3caa42b2020-04-23 14:18:04 +00001074 HEADER* anhp = (HEADER*)(void*)ans;
1075 if (anhp->rcode == FORMERR && (statp->netcontext_flags & NET_CONTEXT_FLAG_USE_EDNS)) {
1076 // Do not retry if the server do not understand EDNS0.
1077 // The case has to be captured here, as FORMERR packet do not
1078 // carry query section, hence res_queriesmatch() returns 0.
1079 LOG(DEBUG) << __func__ << ": server rejected query with EDNS0:";
1080 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
1081 // record the error
1082 statp->_flags |= RES_F_EDNS0ERR;
1083 continue;
1084 }
Luke Huangbff43fc2019-11-12 15:54:47 +08001085
Luke Huang3caa42b2020-04-23 14:18:04 +00001086 timespec done = evNowTime();
1087 *delay = res_stats_calculate_rtt(&done, &start_time);
1088 if (anhp->rcode == SERVFAIL || anhp->rcode == NOTIMP || anhp->rcode == REFUSED) {
1089 LOG(DEBUG) << __func__ << ": server rejected query:";
1090 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
1091 *rcode = anhp->rcode;
1092 continue;
1093 }
1094 if (anhp->tc) {
1095 // To get the rest of answer,
1096 // use TCP with same server.
1097 LOG(DEBUG) << __func__ << ": truncated answer";
1098 *v_circuit = 1;
1099 return 1;
1100 }
1101 // All is well, or the error is fatal. Signal that the
1102 // next nameserver ought not be tried.
Luke Huangbff43fc2019-11-12 15:54:47 +08001103
Luke Huangbff43fc2019-11-12 15:54:47 +08001104 *rcode = anhp->rcode;
Luke Huang3caa42b2020-04-23 14:18:04 +00001105 *ns = receivedFromNs;
1106 return resplen;
Luke Huangbff43fc2019-11-12 15:54:47 +08001107 }
Luke Huang3caa42b2020-04-23 14:18:04 +00001108 if (!needRetry) return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001109 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001110}
1111
chenbruce018fdb22019-06-12 18:08:04 +08001112static void dump_error(const char* str, const struct sockaddr* address, int alen) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001113 char hbuf[NI_MAXHOST];
1114 char sbuf[NI_MAXSERV];
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001115 constexpr int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
Luke Huangc98fd802019-10-15 16:36:36 +09001116 const int err = errno;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001117
chenbruce018fdb22019-06-12 18:08:04 +08001118 if (!WOULD_LOG(DEBUG)) return;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001119
chenbruce018fdb22019-06-12 18:08:04 +08001120 if (getnameinfo(address, (socklen_t)alen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf), niflags)) {
1121 strncpy(hbuf, "?", sizeof(hbuf) - 1);
1122 hbuf[sizeof(hbuf) - 1] = '\0';
1123 strncpy(sbuf, "?", sizeof(sbuf) - 1);
1124 sbuf[sizeof(sbuf) - 1] = '\0';
Elliott Hughes3b8f5902019-03-08 12:02:55 -08001125 }
Luke Huangc98fd802019-10-15 16:36:36 +09001126 errno = err;
chenbruce018fdb22019-06-12 18:08:04 +08001127 PLOG(DEBUG) << __func__ << ": " << str << " ([" << hbuf << "]." << sbuf << "): ";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001128}
1129
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001130static int sock_eq(struct sockaddr* a, struct sockaddr* b) {
1131 struct sockaddr_in *a4, *b4;
1132 struct sockaddr_in6 *a6, *b6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001133
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001134 if (a->sa_family != b->sa_family) return 0;
1135 switch (a->sa_family) {
1136 case AF_INET:
1137 a4 = (struct sockaddr_in*) (void*) a;
1138 b4 = (struct sockaddr_in*) (void*) b;
1139 return a4->sin_port == b4->sin_port && a4->sin_addr.s_addr == b4->sin_addr.s_addr;
1140 case AF_INET6:
1141 a6 = (struct sockaddr_in6*) (void*) a;
1142 b6 = (struct sockaddr_in6*) (void*) b;
1143 return a6->sin6_port == b6->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001144#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001145 a6->sin6_scope_id == b6->sin6_scope_id &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001146#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001147 IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
1148 default:
1149 return 0;
1150 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001151}
Mike Yub601ff72018-11-01 20:07:00 +08001152
lifr6b83a6f2019-07-26 03:17:43 +08001153PrivateDnsModes convertEnumType(PrivateDnsMode privateDnsmode) {
1154 switch (privateDnsmode) {
1155 case PrivateDnsMode::OFF:
1156 return PrivateDnsModes::PDM_OFF;
1157 case PrivateDnsMode::OPPORTUNISTIC:
1158 return PrivateDnsModes::PDM_OPPORTUNISTIC;
1159 case PrivateDnsMode::STRICT:
1160 return PrivateDnsModes::PDM_STRICT;
Mike Yu99b8dc72019-11-22 17:45:31 +08001161 default:
1162 return PrivateDnsModes::PDM_UNKNOWN;
lifr6b83a6f2019-07-26 03:17:43 +08001163 }
lifr6b83a6f2019-07-26 03:17:43 +08001164}
1165
Luke Huangd7aa7b42018-11-21 20:37:50 +08001166static int res_tls_send(res_state statp, const Slice query, const Slice answer, int* rcode,
Mike Yubfb1b342018-11-06 15:42:36 +08001167 bool* fallback) {
1168 int resplen = 0;
Mike Yub601ff72018-11-01 20:07:00 +08001169 const unsigned netId = statp->netid;
Mike Yub601ff72018-11-01 20:07:00 +08001170
Mike Yubfb1b342018-11-06 15:42:36 +08001171 PrivateDnsStatus privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
lifr6b83a6f2019-07-26 03:17:43 +08001172 statp->event->set_private_dns_modes(convertEnumType(privateDnsStatus.mode));
Mike Yubfb1b342018-11-06 15:42:36 +08001173
1174 if (privateDnsStatus.mode == PrivateDnsMode::OFF) {
1175 *fallback = true;
1176 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001177 }
1178
Mike Yu3e829062019-08-07 14:01:14 +08001179 if (privateDnsStatus.validatedServers().empty()) {
Mike Yub601ff72018-11-01 20:07:00 +08001180 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
Mike Yubfb1b342018-11-06 15:42:36 +08001181 *fallback = true;
1182 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001183 } else {
1184 // Sleep and iterate some small number of times checking for the
1185 // arrival of resolved and validated server IP addresses, instead
1186 // of returning an immediate error.
Mike Yu4f3747b2018-12-02 17:54:29 +09001187 // This is needed because as soon as a network becomes the default network, apps will
1188 // send DNS queries on that network. If no servers have yet validated, and we do not
1189 // block those queries, they would immediately fail, causing application-visible errors.
1190 // Note that this can happen even before the network validates, since an unvalidated
1191 // network can become the default network if no validated networks are available.
1192 //
1193 // TODO: see if there is a better way to address this problem, such as buffering the
1194 // queries in a queue or only blocking queries for the first few seconds after a default
1195 // network change.
Mike Yubfb1b342018-11-06 15:42:36 +08001196 for (int i = 0; i < 42; i++) {
1197 std::this_thread::sleep_for(std::chrono::milliseconds(100));
Mike Yu3e829062019-08-07 14:01:14 +08001198 // Calling getStatus() to merely check if there's any validated server seems
1199 // wasteful. Consider adding a new method in PrivateDnsConfiguration for speed ups.
1200 if (!gPrivateDnsConfiguration.getStatus(netId).validatedServers().empty()) {
Mike Yubfb1b342018-11-06 15:42:36 +08001201 privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
1202 break;
1203 }
1204 }
Mike Yu3e829062019-08-07 14:01:14 +08001205 if (privateDnsStatus.validatedServers().empty()) {
Mike Yubfb1b342018-11-06 15:42:36 +08001206 return -1;
1207 }
Mike Yub601ff72018-11-01 20:07:00 +08001208 }
1209 }
1210
chenbruceacb832c2019-02-20 19:45:50 +08001211 LOG(INFO) << __func__ << ": performing query over TLS";
Mike Yub601ff72018-11-01 20:07:00 +08001212
Mike Yu3e829062019-08-07 14:01:14 +08001213 const auto response = sDnsTlsDispatcher.query(privateDnsStatus.validatedServers(), statp, query,
Mike Yubfb1b342018-11-06 15:42:36 +08001214 answer, &resplen);
Mike Yub601ff72018-11-01 20:07:00 +08001215
chenbruceacb832c2019-02-20 19:45:50 +08001216 LOG(INFO) << __func__ << ": TLS query result: " << static_cast<int>(response);
Mike Yub601ff72018-11-01 20:07:00 +08001217
1218 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
1219 // In opportunistic mode, handle falling back to cleartext in some
1220 // cases (DNS shouldn't fail if a validated opportunistic mode server
1221 // becomes unreachable for some reason).
1222 switch (response) {
Mike Yubfb1b342018-11-06 15:42:36 +08001223 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001224 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001225 return resplen;
Mike Yub601ff72018-11-01 20:07:00 +08001226 case DnsTlsTransport::Response::network_error:
Mike Yubfb1b342018-11-06 15:42:36 +08001227 // No need to set the error timeout here since it will fallback to UDP.
Mike Yub601ff72018-11-01 20:07:00 +08001228 case DnsTlsTransport::Response::internal_error:
1229 // Note: this will cause cleartext queries to be emitted, with
1230 // all of the EDNS0 goodness enabled. Fingers crossed. :-/
Mike Yubfb1b342018-11-06 15:42:36 +08001231 *fallback = true;
1232 [[fallthrough]];
Mike Yub601ff72018-11-01 20:07:00 +08001233 default:
Mike Yubfb1b342018-11-06 15:42:36 +08001234 return -1;
1235 }
1236 } else {
1237 // Strict mode
1238 switch (response) {
1239 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001240 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001241 return resplen;
1242 case DnsTlsTransport::Response::network_error:
1243 // This case happens when the query stored in DnsTlsTransport is expired since
1244 // either 1) the query has been tried for 3 times but no response or 2) fail to
1245 // establish the connection with the server.
Luke Huangd7aa7b42018-11-21 20:37:50 +08001246 *rcode = RCODE_TIMEOUT;
Mike Yubfb1b342018-11-06 15:42:36 +08001247 [[fallthrough]];
1248 default:
1249 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001250 }
1251 }
Mike Yub601ff72018-11-01 20:07:00 +08001252}
Luke Huang4973a0d2018-11-19 20:17:26 +08001253
Luke Huangba7bef92018-12-26 16:53:03 +08001254int resolv_res_nsend(const android_net_context* netContext, const uint8_t* msg, int msgLen,
lifr94981782019-05-17 21:15:19 +08001255 uint8_t* ans, int ansLen, int* rcode, uint32_t flags,
1256 NetworkDnsEventReported* event) {
1257 assert(event != nullptr);
Bernie Innocenti08487112019-10-11 21:14:13 +09001258 ResState res;
1259 res_init(&res, netContext, event);
Mike Yu021c3e12019-10-08 17:29:34 +08001260 resolv_populate_res_for_net(&res);
Luke Huang4973a0d2018-11-19 20:17:26 +08001261 *rcode = NOERROR;
Bernie Innocenti08487112019-10-11 21:14:13 +09001262 return res_nsend(&res, msg, msgLen, ans, ansLen, rcode, flags);
Bernie Innocentiec4219b2019-01-30 11:16:36 +09001263}