blob: b1a95b87140f3e4c52424705e923a75750d59322 [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>
98
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +090099#include <android-base/logging.h>
Luke Huang420ee622019-11-27 17:52:44 +0800100#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 Huangf40df9c2020-04-21 08:51:48 +0800107#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 Innocentif33a63f2018-08-30 12:04:03 +0900114#include "resolv_cache.h"
Ken Chen99c0b322019-11-20 14:24:09 +0800115#include "stats.h"
lifr94981782019-05-17 21:15:19 +0800116#include "stats.pb.h"
Mike Yu021c3e12019-10-08 17:29:34 +0800117#include "util.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900118
Luke Huangd1d734f2020-04-30 12:25:40 +0800119using namespace std::chrono_literals;
Mike Yub601ff72018-11-01 20:07:00 +0800120// TODO: use the namespace something like android::netd_resolv for libnetd_resolv
Luke Huang420ee622019-11-27 17:52:44 +0800121using android::base::ErrnoError;
122using android::base::Result;
chenbruce99cbfd82019-09-05 15:08:13 +0800123using android::net::CacheStatus;
124using android::net::DnsQueryEvent;
125using android::net::DnsTlsDispatcher;
126using android::net::DnsTlsTransport;
chenbruce99cbfd82019-09-05 15:08:13 +0800127using android::net::IpVersion;
128using android::net::IV_IPV4;
129using android::net::IV_IPV6;
130using android::net::IV_UNKNOWN;
Luke Huang23d55192020-04-16 11:47:30 +0800131using android::net::LinuxErrno;
lifr94981782019-05-17 21:15:19 +0800132using android::net::NetworkDnsEventReported;
chenbruce99cbfd82019-09-05 15:08:13 +0800133using android::net::NS_T_INVALID;
134using android::net::NsRcode;
135using android::net::NsType;
Mike Yu60248242020-07-29 16:45:26 +0800136using android::net::PrivateDnsConfiguration;
chenbruce99cbfd82019-09-05 15:08:13 +0800137using 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 Yue48f7b52020-02-10 14:55:06 +0800146static int send_vc(res_state statp, res_params* params, const uint8_t* buf, int buflen,
147 uint8_t* ans, int anssiz, int* terrno, size_t ns, time_t* at, int* rcode,
148 int* delay);
chenbruceb1aa65a2021-06-15 19:37:05 +0800149static int setupUdpSocket(ResState* statp, const sockaddr* sockap, size_t addrIndex, int* terrno);
Mike Yue48f7b52020-02-10 14:55:06 +0800150static int send_dg(res_state statp, res_params* params, const uint8_t* buf, int buflen,
Luke Huang420ee622019-11-27 17:52:44 +0800151 uint8_t* ans, int anssiz, int* terrno, size_t* ns, int* v_circuit,
Mike Yue48f7b52020-02-10 14:55:06 +0800152 int* gotsomewhere, time_t* at, int* rcode, int* delay);
153
chenbruce76620642021-06-15 18:39:27 +0800154static void dump_error(const char*, const struct sockaddr*);
chenbruceacb832c2019-02-20 19:45:50 +0800155
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900156static int sock_eq(struct sockaddr*, struct sockaddr*);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900157static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
158 const struct timespec timeout);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900159static int retrying_poll(const int sock, short events, const struct timespec* finish);
Luke Huangd7aa7b42018-11-21 20:37:50 +0800160static int res_tls_send(res_state, const Slice query, const Slice answer, int* rcode,
Mike Yubfb1b342018-11-06 15:42:36 +0800161 bool* fallback);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900162
lifr94981782019-05-17 21:15:19 +0800163NsType getQueryType(const uint8_t* msg, size_t msgLen) {
164 ns_msg handle;
165 ns_rr rr;
166 if (ns_initparse((const uint8_t*)msg, msgLen, &handle) < 0 ||
167 ns_parserr(&handle, ns_s_qd, 0, &rr) < 0) {
168 return NS_T_INVALID;
169 }
170 return static_cast<NsType>(ns_rr_type(rr));
171}
172
173IpVersion ipFamilyToIPVersion(const int ipFamily) {
174 switch (ipFamily) {
175 case AF_INET:
176 return IV_IPV4;
177 case AF_INET6:
178 return IV_IPV6;
179 default:
180 return IV_UNKNOWN;
181 }
182}
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900183
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900184// BEGIN: Code copied from ISC eventlib
185// TODO: move away from this code
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900186#define BILLION 1000000000
187
188static struct timespec evConsTime(time_t sec, long nsec) {
189 struct timespec x;
190
191 x.tv_sec = sec;
192 x.tv_nsec = nsec;
193 return (x);
194}
195
196static struct timespec evAddTime(struct timespec addend1, struct timespec addend2) {
197 struct timespec x;
198
199 x.tv_sec = addend1.tv_sec + addend2.tv_sec;
200 x.tv_nsec = addend1.tv_nsec + addend2.tv_nsec;
201 if (x.tv_nsec >= BILLION) {
202 x.tv_sec++;
203 x.tv_nsec -= BILLION;
204 }
205 return (x);
206}
207
208static struct timespec evSubTime(struct timespec minuend, struct timespec subtrahend) {
209 struct timespec x;
210
211 x.tv_sec = minuend.tv_sec - subtrahend.tv_sec;
212 if (minuend.tv_nsec >= subtrahend.tv_nsec)
213 x.tv_nsec = minuend.tv_nsec - subtrahend.tv_nsec;
214 else {
215 x.tv_nsec = BILLION - subtrahend.tv_nsec + minuend.tv_nsec;
216 x.tv_sec--;
217 }
218 return (x);
219}
220
221static int evCmpTime(struct timespec a, struct timespec b) {
222#define SGN(x) ((x) < 0 ? (-1) : (x) > 0 ? (1) : (0));
223 time_t s = a.tv_sec - b.tv_sec;
224 long n;
225
226 if (s != 0) return SGN(s);
227
228 n = a.tv_nsec - b.tv_nsec;
229 return SGN(n);
230}
231
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900232static struct timespec evNowTime(void) {
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900233 struct timespec tsnow;
Bernie Innocentic1834822018-08-31 16:11:41 +0900234 clock_gettime(CLOCK_REALTIME, &tsnow);
235 return tsnow;
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900236}
237
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900238// END: Code copied from ISC eventlib
239
lifr94981782019-05-17 21:15:19 +0800240/* BIONIC-BEGIN: implement source port randomization */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900241static int random_bind(int s, int family) {
nuccachenb980f2f2018-10-23 17:10:58 +0800242 sockaddr_union u;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900243 int j;
244 socklen_t slen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900245
246 /* clear all, this also sets the IP4/6 address to 'any' */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900247 memset(&u, 0, sizeof u);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900248
249 switch (family) {
250 case AF_INET:
251 u.sin.sin_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900252 slen = sizeof u.sin;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900253 break;
254 case AF_INET6:
255 u.sin6.sin6_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900256 slen = sizeof u.sin6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900257 break;
258 default:
259 errno = EPROTO;
260 return -1;
261 }
262
263 /* first try to bind to a random source port a few times */
264 for (j = 0; j < 10; j++) {
265 /* find a random port between 1025 .. 65534 */
Luke Huangdda920f2019-02-13 14:05:02 +0800266 int port = 1025 + (arc4random_uniform(65535 - 1025));
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900267 if (family == AF_INET)
268 u.sin.sin_port = htons(port);
269 else
270 u.sin6.sin6_port = htons(port);
271
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900272 if (!bind(s, &u.sa, slen)) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900273 }
274
Bernie Innocenti9c575932018-09-07 21:10:25 +0900275 // nothing after 10 attempts, our network table is probably busy
276 // let the system decide which port is best
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900277 if (family == AF_INET)
278 u.sin.sin_port = 0;
279 else
280 u.sin6.sin6_port = 0;
281
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900282 return bind(s, &u.sa, slen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900283}
284/* BIONIC-END */
285
Luke Huang70931aa2019-01-31 11:57:41 +0800286// Disables all nameservers other than selectedServer
287static void res_set_usable_server(int selectedServer, int nscount, bool usable_servers[]) {
288 int usableIndex = 0;
289 for (int ns = 0; ns < nscount; ns++) {
290 if (usable_servers[ns]) ++usableIndex;
291 if (usableIndex != selectedServer) usable_servers[ns] = false;
292 }
293}
294
Luke Huang420ee622019-11-27 17:52:44 +0800295// Looks up the nameserver address in res.nsaddrs[], returns the ns number if found, otherwise -1.
296static int res_ourserver_p(res_state statp, const sockaddr* sa) {
Bernie Innocenti2e8540b2018-09-26 11:52:04 +0900297 const sockaddr_in *inp, *srv;
298 const sockaddr_in6 *in6p, *srv6;
Luke Huang420ee622019-11-27 17:52:44 +0800299 int ns = 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900300 switch (sa->sa_family) {
301 case AF_INET:
302 inp = (const struct sockaddr_in*) (const void*) sa;
Luke Huang420ee622019-11-27 17:52:44 +0800303
Mike Yue48f7b52020-02-10 14:55:06 +0800304 for (const IPSockAddr& ipsa : statp->nsaddrs) {
305 sockaddr_storage ss = ipsa;
306 srv = reinterpret_cast<sockaddr_in*>(&ss);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900307 if (srv->sin_family == inp->sin_family && srv->sin_port == inp->sin_port &&
308 (srv->sin_addr.s_addr == INADDR_ANY ||
309 srv->sin_addr.s_addr == inp->sin_addr.s_addr))
Luke Huang420ee622019-11-27 17:52:44 +0800310 return ns;
311 ++ns;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900312 }
313 break;
314 case AF_INET6:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900315 in6p = (const struct sockaddr_in6*) (const void*) sa;
Mike Yue48f7b52020-02-10 14:55:06 +0800316 for (const IPSockAddr& ipsa : statp->nsaddrs) {
317 sockaddr_storage ss = ipsa;
318 srv6 = reinterpret_cast<sockaddr_in6*>(&ss);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900319 if (srv6->sin6_family == in6p->sin6_family && srv6->sin6_port == in6p->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900320#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900321 (srv6->sin6_scope_id == 0 || srv6->sin6_scope_id == in6p->sin6_scope_id) &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900322#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900323 (IN6_IS_ADDR_UNSPECIFIED(&srv6->sin6_addr) ||
324 IN6_ARE_ADDR_EQUAL(&srv6->sin6_addr, &in6p->sin6_addr)))
Luke Huang420ee622019-11-27 17:52:44 +0800325 return ns;
326 ++ns;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900327 }
328 break;
329 default:
330 break;
331 }
Luke Huang420ee622019-11-27 17:52:44 +0800332 return -1;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900333}
334
335/* int
Bernie Innocenti9c575932018-09-07 21:10:25 +0900336 * res_nameinquery(name, type, cl, buf, eom)
337 * look for (name, type, cl) in the query section of packet (buf, eom)
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900338 * requires:
339 * buf + HFIXEDSZ <= eom
340 * returns:
341 * -1 : format error
342 * 0 : not found
343 * >0 : found
344 * author:
345 * paul vixie, 29may94
346 */
chenbrucec51f1212019-09-12 16:59:33 +0800347int res_nameinquery(const char* name, int type, int cl, const uint8_t* buf, const uint8_t* eom) {
348 const uint8_t* cp = buf + HFIXEDSZ;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900349 int qdcount = ntohs(((const HEADER*) (const void*) buf)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900350
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900351 while (qdcount-- > 0) {
352 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900353 int n = dn_expand(buf, eom, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900354 if (n < 0) return (-1);
355 cp += n;
356 if (cp + 2 * INT16SZ > eom) return (-1);
chenbruce0d470422019-03-28 18:44:37 +0800357 int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900358 cp += INT16SZ;
chenbruce0d470422019-03-28 18:44:37 +0800359 int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900360 cp += INT16SZ;
Bernie Innocenti9c575932018-09-07 21:10:25 +0900361 if (ttype == type && tclass == cl && ns_samename(tname, name) == 1) return (1);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900362 }
363 return (0);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900364}
365
366/* int
367 * res_queriesmatch(buf1, eom1, buf2, eom2)
368 * is there a 1:1 mapping of (name,type,class)
369 * in (buf1,eom1) and (buf2,eom2)?
370 * returns:
371 * -1 : format error
372 * 0 : not a 1:1 mapping
373 * >0 : is a 1:1 mapping
374 * author:
375 * paul vixie, 29may94
376 */
chenbrucec51f1212019-09-12 16:59:33 +0800377int res_queriesmatch(const uint8_t* buf1, const uint8_t* eom1, const uint8_t* buf2,
378 const uint8_t* eom2) {
379 const uint8_t* cp = buf1 + HFIXEDSZ;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900380 int qdcount = ntohs(((const HEADER*) (const void*) buf1)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900381
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900382 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2) return (-1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900383
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900384 /*
385 * Only header section present in replies to
386 * dynamic update packets.
387 */
388 if ((((const HEADER*) (const void*) buf1)->opcode == ns_o_update) &&
389 (((const HEADER*) (const void*) buf2)->opcode == ns_o_update))
390 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900391
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900392 if (qdcount != ntohs(((const HEADER*) (const void*) buf2)->qdcount)) return (0);
393 while (qdcount-- > 0) {
394 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900395 int n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900396 if (n < 0) return (-1);
397 cp += n;
398 if (cp + 2 * INT16SZ > eom1) return (-1);
chenbruce0d470422019-03-28 18:44:37 +0800399 int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900400 cp += INT16SZ;
chenbruce0d470422019-03-28 18:44:37 +0800401 int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900402 cp += INT16SZ;
403 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2)) return (0);
404 }
405 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900406}
407
lifr94981782019-05-17 21:15:19 +0800408static DnsQueryEvent* addDnsQueryEvent(NetworkDnsEventReported* event) {
409 return event->mutable_dns_query_events()->add_dns_query_event();
410}
411
Luke Huangeb618ef2020-05-26 14:17:02 +0800412static bool isNetworkRestricted(int terrno) {
413 // It's possible that system was in some network restricted mode, which blocked
414 // the operation of sending packet and resulted in EPERM errno.
415 // It would be no reason to keep retrying on that case.
416 // TODO: Check the system status to know if network restricted mode is
417 // enabled.
418 return (terrno == EPERM);
419}
420
chenbrucec51f1212019-09-12 16:59:33 +0800421int 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 +0800422 uint32_t flags, std::chrono::milliseconds sleepTimeMs) {
Luke Huang43cc1b12019-10-15 19:06:42 +0900423 LOG(DEBUG) << __func__;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900424
Luke Huang43cc1b12019-10-15 19:06:42 +0900425 // Should not happen
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900426 if (anssiz < HFIXEDSZ) {
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800427 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900428 errno = EINVAL;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800429 return -EINVAL;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900430 }
chenbrucedd210722019-03-06 13:52:43 +0800431 res_pquery(buf, buflen);
chenbruceacb832c2019-02-20 19:45:50 +0800432
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900433 int anslen = 0;
lifrd4d9fbb2019-07-31 20:18:35 +0800434 Stopwatch cacheStopwatch;
Luke Huang43cc1b12019-10-15 19:06:42 +0900435 ResolvCacheStatus cache_status =
436 resolv_cache_lookup(statp->netid, buf, buflen, ans, anssiz, &anslen, flags);
lifrd4d9fbb2019-07-31 20:18:35 +0800437 const int32_t cacheLatencyUs = saturate_cast<int32_t>(cacheStopwatch.timeTakenUs());
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900438 if (cache_status == RESOLV_CACHE_FOUND) {
Luke Huang83c9b4b2019-02-27 18:18:01 +0800439 HEADER* hp = (HEADER*)(void*)ans;
440 *rcode = hp->rcode;
lifr94981782019-05-17 21:15:19 +0800441 DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
442 dnsQueryEvent->set_latency_micros(cacheLatencyUs);
443 dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
lifre02d01c2019-12-31 17:24:57 +0800444 dnsQueryEvent->set_type(getQueryType(buf, buflen));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900445 return anslen;
446 } else if (cache_status != RESOLV_CACHE_UNSUPPORTED) {
447 // had a cache miss for a known network, so populate the thread private
448 // data so the normal resolve path can do its thing
Mike Yu021c3e12019-10-08 17:29:34 +0800449 resolv_populate_res_for_net(statp);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900450 }
Mike Yuecc52822020-02-14 14:36:46 +0800451 if (statp->nameserverCount() == 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900452 // We have no nameservers configured, so there's no point trying.
453 // Tell the cache the query failed, or any retries and anyone else asking the same
454 // question will block for PENDING_REQUEST_TIMEOUT seconds instead of failing fast.
Luke Huangba7bef92018-12-26 16:53:03 +0800455 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800456
457 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900458 errno = ESRCH;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800459 return -ESRCH;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900460 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900461
Luke Huangd1d734f2020-04-30 12:25:40 +0800462 // If parallel_lookup is enabled, it might be required to wait some time to avoid
463 // gateways drop packets if queries are sent too close together
464 if (sleepTimeMs != 0ms) {
465 std::this_thread::sleep_for(sleepTimeMs);
466 }
Luke Huang272cb192019-10-15 16:52:28 +0900467 // DoT
468 if (!(statp->netcontext_flags & NET_CONTEXT_FLAG_USE_LOCAL_NAMESERVERS)) {
469 bool fallback = false;
Luke Huang43cc1b12019-10-15 19:06:42 +0900470 int resplen = res_tls_send(statp, Slice(const_cast<uint8_t*>(buf), buflen),
471 Slice(ans, anssiz), rcode, &fallback);
Luke Huang272cb192019-10-15 16:52:28 +0900472 if (resplen > 0) {
473 LOG(DEBUG) << __func__ << ": got answer from DoT";
474 res_pquery(ans, resplen);
475 if (cache_status == RESOLV_CACHE_NOTFOUND) {
476 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
477 }
478 return resplen;
479 }
480 if (!fallback) {
481 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huang43cc1b12019-10-15 19:06:42 +0900482 return -ETIMEDOUT;
Luke Huang272cb192019-10-15 16:52:28 +0900483 }
484 }
485
Mike Yuc573a3d2020-02-07 20:15:15 +0800486 res_stats stats[MAXNS]{};
Bernie Innocenti758005f2019-02-19 18:08:36 +0900487 res_params params;
Mike Yuc573a3d2020-02-07 20:15:15 +0800488 int revision_id = resolv_cache_get_resolver_stats(statp->netid, &params, stats, statp->nsaddrs);
lifra1b37f12019-02-13 17:33:57 +0800489 if (revision_id < 0) {
490 // TODO: Remove errno once callers stop using it
491 errno = ESRCH;
492 return -ESRCH;
493 }
waynema0161acd2019-02-18 17:47:59 +0800494 bool usable_servers[MAXNS];
Luke Huang70931aa2019-01-31 11:57:41 +0800495 int usableServersCount = android_net_res_stats_get_usable_servers(
Mike Yuecc52822020-02-14 14:36:46 +0800496 &params, stats, statp->nameserverCount(), usable_servers);
Luke Huang70931aa2019-01-31 11:57:41 +0800497
Mike Yu61d17262020-02-15 18:56:22 +0800498 if (statp->sort_nameservers) {
499 // It's unnecessary to mark a DNS server as unusable since broken servers will be less
500 // likely to be chosen.
501 for (int i = 0; i < statp->nameserverCount(); i++) {
502 usable_servers[i] = true;
503 }
504 }
505
506 // TODO: Let it always choose the first nameserver when sort_nameservers is enabled.
Luke Huang70931aa2019-01-31 11:57:41 +0800507 if ((flags & ANDROID_RESOLV_NO_RETRY) && usableServersCount > 1) {
508 auto hp = reinterpret_cast<const HEADER*>(buf);
509
510 // Select a random server based on the query id
511 int selectedServer = (hp->id % usableServersCount) + 1;
Mike Yuecc52822020-02-14 14:36:46 +0800512 res_set_usable_server(selectedServer, statp->nameserverCount(), usable_servers);
Luke Huang70931aa2019-01-31 11:57:41 +0800513 }
waynema0161acd2019-02-18 17:47:59 +0800514
Luke Huang43cc1b12019-10-15 19:06:42 +0900515 // Send request, RETRY times, or until successful.
waynemaa74195e2019-01-18 14:02:31 +0800516 int retryTimes = (flags & ANDROID_RESOLV_NO_RETRY) ? 1 : params.retry_count;
Luke Huang43cc1b12019-10-15 19:06:42 +0900517 int useTcp = buflen > PACKETSZ;
518 int gotsomewhere = 0;
Luke Huang23d55192020-04-16 11:47:30 +0800519 // Use an impossible error code as default value
520 int terrno = ETIME;
Luke Huangba7bef92018-12-26 16:53:03 +0800521
522 for (int attempt = 0; attempt < retryTimes; ++attempt) {
Mike Yue48f7b52020-02-10 14:55:06 +0800523 for (size_t ns = 0; ns < statp->nsaddrs.size(); ++ns) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900524 if (!usable_servers[ns]) continue;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900525
Luke Huang43cc1b12019-10-15 19:06:42 +0900526 *rcode = RCODE_INTERNAL_ERROR;
527
528 // Get server addr
Mike Yue48f7b52020-02-10 14:55:06 +0800529 const IPSockAddr& serverSockAddr = statp->nsaddrs[ns];
530 LOG(DEBUG) << __func__ << ": Querying server (# " << ns + 1
531 << ") address = " << serverSockAddr.toString();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900532
Luke Huang43cc1b12019-10-15 19:06:42 +0900533 ::android::net::Protocol query_proto = useTcp ? PROTO_TCP : PROTO_UDP;
Luke Huang420ee622019-11-27 17:52:44 +0800534 time_t query_time = 0;
Luke Huang43cc1b12019-10-15 19:06:42 +0900535 int delay = 0;
536 bool fallbackTCP = false;
537 const bool shouldRecordStats = (attempt == 0);
538 int resplen;
lifrd4d9fbb2019-07-31 20:18:35 +0800539 Stopwatch queryStopwatch;
lifr128183a2020-01-08 18:04:50 +0800540 int retry_count_for_event = 0;
Luke Huang420ee622019-11-27 17:52:44 +0800541 size_t actualNs = ns;
Luke Huang23d55192020-04-16 11:47:30 +0800542 // Use an impossible error code as default value
543 terrno = ETIME;
Luke Huang43cc1b12019-10-15 19:06:42 +0900544 if (useTcp) {
545 // TCP; at most one attempt per server.
Luke Huangba7bef92018-12-26 16:53:03 +0800546 attempt = retryTimes;
Luke Huang420ee622019-11-27 17:52:44 +0800547 resplen = send_vc(statp, &params, buf, buflen, ans, anssiz, &terrno, ns,
548 &query_time, rcode, &delay);
Ken Chen99344882020-01-01 14:59:38 +0800549
550 if (buflen <= PACKETSZ && resplen <= 0 &&
551 statp->tc_mode == aidl::android::net::IDnsResolver::TC_MODE_UDP_TCP) {
552 // reset to UDP for next query on next DNS server if resolver is currently doing
553 // TCP fallback retry and current server does not support TCP connectin
554 useTcp = false;
555 }
Luke Huangeb618ef2020-05-26 14:17:02 +0800556 LOG(INFO) << __func__ << ": used send_vc " << resplen << " terrno: " << terrno;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900557 } else {
Luke Huang43cc1b12019-10-15 19:06:42 +0900558 // UDP
Luke Huang420ee622019-11-27 17:52:44 +0800559 resplen = send_dg(statp, &params, buf, buflen, ans, anssiz, &terrno, &actualNs,
560 &useTcp, &gotsomewhere, &query_time, rcode, &delay);
Luke Huang43cc1b12019-10-15 19:06:42 +0900561 fallbackTCP = useTcp ? true : false;
lifr128183a2020-01-08 18:04:50 +0800562 retry_count_for_event = attempt;
Luke Huangeb618ef2020-05-26 14:17:02 +0800563 LOG(INFO) << __func__ << ": used send_dg " << resplen << " terrno: " << terrno;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900564 }
Luke Huang43cc1b12019-10-15 19:06:42 +0900565
Luke Huang420ee622019-11-27 17:52:44 +0800566 const IPSockAddr& receivedServerAddr = statp->nsaddrs[actualNs];
Luke Huang43cc1b12019-10-15 19:06:42 +0900567 DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
568 dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
Luke Huang420ee622019-11-27 17:52:44 +0800569 // When |retryTimes| > 1, we cannot actually know the correct latency value if we
570 // received the answer from the previous server. So temporarily set the latency as -1 if
571 // that condition happened.
572 // TODO: make the latency value accurate.
573 dnsQueryEvent->set_latency_micros(
574 (actualNs == ns) ? saturate_cast<int32_t>(queryStopwatch.timeTakenUs()) : -1);
575 dnsQueryEvent->set_dns_server_index(actualNs);
576 dnsQueryEvent->set_ip_version(ipFamilyToIPVersion(receivedServerAddr.family()));
lifr128183a2020-01-08 18:04:50 +0800577 dnsQueryEvent->set_retry_times(retry_count_for_event);
Luke Huang43cc1b12019-10-15 19:06:42 +0900578 dnsQueryEvent->set_rcode(static_cast<NsRcode>(*rcode));
579 dnsQueryEvent->set_protocol(query_proto);
580 dnsQueryEvent->set_type(getQueryType(buf, buflen));
Luke Huang23d55192020-04-16 11:47:30 +0800581 dnsQueryEvent->set_linux_errno(static_cast<LinuxErrno>(terrno));
Luke Huang43cc1b12019-10-15 19:06:42 +0900582
583 // Only record stats the first time we try a query. This ensures that
584 // queries that deterministically fail (e.g., a name that always returns
585 // SERVFAIL or times out) do not unduly affect the stats.
586 if (shouldRecordStats) {
Luke Huangeb618ef2020-05-26 14:17:02 +0800587 // (b/151166599): This is a workaround to prevent that DnsResolver calculates the
588 // reliability of DNS servers from being broken when network restricted mode is
589 // enabled.
590 // TODO: Introduce the new server selection instead of skipping stats recording.
591 if (!isNetworkRestricted(terrno)) {
592 res_sample sample;
593 res_stats_set_sample(&sample, query_time, *rcode, delay);
594 // KeepListening UDP mechanism is incompatible with usable_servers of legacy
595 // stats, so keep the old logic for now.
596 // TODO: Replace usable_servers of legacy stats with new one.
597 resolv_cache_add_resolver_stats_sample(
598 statp->netid, revision_id, serverSockAddr, sample, params.max_samples);
Mike Yu30e0de92021-05-07 11:48:46 +0800599 resolv_stats_add(statp->netid, receivedServerAddr, dnsQueryEvent);
Luke Huangeb618ef2020-05-26 14:17:02 +0800600 }
Luke Huang43cc1b12019-10-15 19:06:42 +0900601 }
602
603 if (resplen == 0) continue;
604 if (fallbackTCP) {
605 ns--;
606 continue;
607 }
608 if (resplen < 0) {
609 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800610 statp->closeSockets();
Luke Huang43cc1b12019-10-15 19:06:42 +0900611 return -terrno;
612 };
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900613
Ken Chenffc224a2019-03-19 17:41:28 +0800614 LOG(DEBUG) << __func__ << ": got answer:";
chenbrucedd210722019-03-06 13:52:43 +0800615 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900616
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900617 if (cache_status == RESOLV_CACHE_NOTFOUND) {
Mike Yud1ec2542019-06-06 17:17:53 +0800618 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900619 }
Luke Huangadb0f5b2019-11-27 15:51:48 +0800620 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900621 return (resplen);
Bernie Innocenti9c575932018-09-07 21:10:25 +0900622 } // for each ns
623 } // for each retry
Luke Huangadb0f5b2019-11-27 15:51:48 +0800624 statp->closeSockets();
Luke Huang43cc1b12019-10-15 19:06:42 +0900625 terrno = useTcp ? terrno : gotsomewhere ? ETIMEDOUT : ECONNREFUSED;
626 // TODO: Remove errno once callers stop using it
627 errno = useTcp ? terrno
628 : gotsomewhere ? ETIMEDOUT /* no answer obtained */
629 : ECONNREFUSED /* no nameservers found */;
630
Luke Huangba7bef92018-12-26 16:53:03 +0800631 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800632 return -terrno;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900633}
634
chenbruce99cbfd82019-09-05 15:08:13 +0800635static struct timespec get_timeout(res_state statp, const res_params* params, const int ns) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900636 int msec;
waynemaa74195e2019-01-18 14:02:31 +0800637 // Legacy algorithm which scales the timeout by nameserver number.
638 // For instance, with 4 nameservers: 5s, 2.5s, 5s, 10s
639 // This has no effect with 1 or 2 nameservers
640 msec = params->base_timeout_msec << ns;
641 if (ns > 0) {
Mike Yuecc52822020-02-14 14:36:46 +0800642 msec /= statp->nameserverCount();
waynemaa74195e2019-01-18 14:02:31 +0800643 }
644 // For safety, don't allow OEMs and experiments to configure a timeout shorter than 1s.
645 if (msec < 1000) {
646 msec = 1000; // Use at least 1000ms
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900647 }
Ken Chenffc224a2019-03-19 17:41:28 +0800648 LOG(INFO) << __func__ << ": using timeout of " << msec << " msec";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900649
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900650 struct timespec result;
651 result.tv_sec = msec / 1000;
652 result.tv_nsec = (msec % 1000) * 1000000;
653 return result;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900654}
655
chenbrucec51f1212019-09-12 16:59:33 +0800656static int send_vc(res_state statp, res_params* params, const uint8_t* buf, int buflen,
Mike Yue48f7b52020-02-10 14:55:06 +0800657 uint8_t* ans, int anssiz, int* terrno, size_t ns, time_t* at, int* rcode,
chenbrucec51f1212019-09-12 16:59:33 +0800658 int* delay) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900659 *at = time(NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900660 *delay = 0;
661 const HEADER* hp = (const HEADER*) (const void*) buf;
662 HEADER* anhp = (HEADER*) (void*) ans;
663 struct sockaddr* nsap;
664 int nsaplen;
chenbruce0d470422019-03-28 18:44:37 +0800665 int truncating, connreset, n;
chenbrucec51f1212019-09-12 16:59:33 +0800666 uint8_t* cp;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900667
Ken Chenffc224a2019-03-19 17:41:28 +0800668 LOG(INFO) << __func__ << ": using send_vc";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900669
Mike Yue48f7b52020-02-10 14:55:06 +0800670 // It should never happen, but just in case.
671 if (ns >= statp->nsaddrs.size()) {
672 LOG(ERROR) << __func__ << ": Out-of-bound indexing: " << ns;
Luke Huang23d55192020-04-16 11:47:30 +0800673 *terrno = EINVAL;
Mike Yue48f7b52020-02-10 14:55:06 +0800674 return -1;
675 }
676
677 sockaddr_storage ss = statp->nsaddrs[ns];
678 nsap = reinterpret_cast<sockaddr*>(&ss);
Mike Yu021c3e12019-10-08 17:29:34 +0800679 nsaplen = sockaddrSize(nsap);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900680
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900681 connreset = 0;
682same_ns:
683 truncating = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900684
Luke Huang420ee622019-11-27 17:52:44 +0800685 struct timespec start_time = evNowTime();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900686
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900687 /* Are we still talking to whom we want to talk to? */
Luke Huangadb0f5b2019-11-27 15:51:48 +0800688 if (statp->tcp_nssock >= 0 && (statp->_flags & RES_F_VC) != 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900689 struct sockaddr_storage peer;
690 socklen_t size = sizeof peer;
691 unsigned old_mark;
692 socklen_t mark_size = sizeof(old_mark);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800693 if (getpeername(statp->tcp_nssock, (struct sockaddr*)(void*)&peer, &size) < 0 ||
694 !sock_eq((struct sockaddr*)(void*)&peer, nsap) ||
695 getsockopt(statp->tcp_nssock, SOL_SOCKET, SO_MARK, &old_mark, &mark_size) < 0 ||
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900696 old_mark != statp->_mark) {
Luke Huangadb0f5b2019-11-27 15:51:48 +0800697 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900698 }
699 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900700
Luke Huangadb0f5b2019-11-27 15:51:48 +0800701 if (statp->tcp_nssock < 0 || (statp->_flags & RES_F_VC) == 0) {
702 if (statp->tcp_nssock >= 0) statp->closeSockets();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900703
Luke Huangadb0f5b2019-11-27 15:51:48 +0800704 statp->tcp_nssock.reset(socket(nsap->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0));
705 if (statp->tcp_nssock < 0) {
Luke Huang23d55192020-04-16 11:47:30 +0800706 *terrno = errno;
707 PLOG(DEBUG) << __func__ << ": socket(vc): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900708 switch (errno) {
709 case EPROTONOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900710 case EPFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900711 case EAFNOSUPPORT:
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900712 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900713 default:
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900714 return -1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900715 }
716 }
Ken Chenbc481b82020-05-21 23:30:01 +0800717 const uid_t uid = statp->enforce_dns_uid ? AID_DNS : statp->uid;
718 resolv_tag_socket(statp->tcp_nssock, uid, statp->pid);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900719 if (statp->_mark != MARK_UNSET) {
Luke Huangadb0f5b2019-11-27 15:51:48 +0800720 if (setsockopt(statp->tcp_nssock, SOL_SOCKET, SO_MARK, &statp->_mark,
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900721 sizeof(statp->_mark)) < 0) {
722 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800723 PLOG(DEBUG) << __func__ << ": setsockopt: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900724 return -1;
725 }
726 }
727 errno = 0;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800728 if (random_bind(statp->tcp_nssock, nsap->sa_family) < 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900729 *terrno = errno;
chenbruce76620642021-06-15 18:39:27 +0800730 dump_error("bind/vc", nsap);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800731 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900732 return (0);
733 }
Luke Huangadb0f5b2019-11-27 15:51:48 +0800734 if (connect_with_timeout(statp->tcp_nssock, nsap, (socklen_t)nsaplen,
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900735 get_timeout(statp, params, ns)) < 0) {
736 *terrno = errno;
chenbruce76620642021-06-15 18:39:27 +0800737 dump_error("connect/vc", nsap);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800738 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900739 /*
740 * The way connect_with_timeout() is implemented prevents us from reliably
741 * determining whether this was really a timeout or e.g. ECONNREFUSED. Since
742 * currently both cases are handled in the same way, there is no need to
743 * change this (yet). If we ever need to reliably distinguish between these
744 * cases, both connect_with_timeout() and retrying_poll() need to be
745 * modified, though.
746 */
747 *rcode = RCODE_TIMEOUT;
748 return (0);
749 }
750 statp->_flags |= RES_F_VC;
751 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900752
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900753 /*
754 * Send length & message
755 */
chenbruce0d470422019-03-28 18:44:37 +0800756 uint16_t len = htons(static_cast<uint16_t>(buflen));
Luke Huangc98fd802019-10-15 16:36:36 +0900757 const iovec iov[] = {
758 {.iov_base = &len, .iov_len = INT16SZ},
759 {.iov_base = const_cast<uint8_t*>(buf), .iov_len = static_cast<size_t>(buflen)},
760 };
Luke Huangadb0f5b2019-11-27 15:51:48 +0800761 if (writev(statp->tcp_nssock, iov, 2) != (INT16SZ + buflen)) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900762 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800763 PLOG(DEBUG) << __func__ << ": write failed: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800764 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900765 return (0);
766 }
767 /*
768 * Receive length & response
769 */
770read_len:
771 cp = ans;
772 len = INT16SZ;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800773 while ((n = read(statp->tcp_nssock, (char*)cp, (size_t)len)) > 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900774 cp += n;
775 if ((len -= n) == 0) break;
776 }
777 if (n <= 0) {
778 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800779 PLOG(DEBUG) << __func__ << ": read failed: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800780 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900781 /*
782 * A long running process might get its TCP
783 * connection reset if the remote server was
784 * restarted. Requery the server instead of
785 * trying a new one. When there is only one
786 * server, this means that a query might work
787 * instead of failing. We only allow one reset
788 * per query to prevent looping.
789 */
790 if (*terrno == ECONNRESET && !connreset) {
791 connreset = 1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900792 goto same_ns;
793 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900794 return (0);
795 }
chenbruce0d470422019-03-28 18:44:37 +0800796 uint16_t resplen = ntohs(*reinterpret_cast<const uint16_t*>(ans));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900797 if (resplen > anssiz) {
Ken Chenffc224a2019-03-19 17:41:28 +0800798 LOG(DEBUG) << __func__ << ": response truncated";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900799 truncating = 1;
800 len = anssiz;
801 } else
802 len = resplen;
803 if (len < HFIXEDSZ) {
804 /*
805 * Undersized message.
806 */
Ken Chenffc224a2019-03-19 17:41:28 +0800807 LOG(DEBUG) << __func__ << ": undersized: " << len;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900808 *terrno = EMSGSIZE;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800809 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900810 return (0);
811 }
812 cp = ans;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800813 while (len != 0 && (n = read(statp->tcp_nssock, (char*)cp, (size_t)len)) > 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900814 cp += n;
815 len -= n;
816 }
817 if (n <= 0) {
818 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800819 PLOG(DEBUG) << __func__ << ": read(vc): ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800820 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900821 return (0);
822 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900823
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900824 if (truncating) {
825 /*
826 * Flush rest of answer so connection stays in synch.
827 */
828 anhp->tc = 1;
829 len = resplen - anssiz;
830 while (len != 0) {
831 char junk[PACKETSZ];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900832
Luke Huangadb0f5b2019-11-27 15:51:48 +0800833 n = read(statp->tcp_nssock, junk, (len > sizeof junk) ? sizeof junk : len);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900834 if (n > 0)
835 len -= n;
836 else
837 break;
838 }
Ken Chena9e6f1d2020-07-30 13:24:16 +0800839 LOG(WARNING) << __func__ << ": resplen " << resplen << " exceeds buf size " << anssiz;
840 // return size should never exceed container size
841 resplen = anssiz;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900842 }
843 /*
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900844 * If the calling application has bailed out of
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900845 * a previous call and failed to arrange to have
846 * the circuit closed or the server has got
847 * itself confused, then drop the packet and
848 * wait for the correct one.
849 */
850 if (hp->id != anhp->id) {
Ken Chenffc224a2019-03-19 17:41:28 +0800851 LOG(DEBUG) << __func__ << ": ld answer (unexpected):";
Ken Chena9e6f1d2020-07-30 13:24:16 +0800852 res_pquery(ans, resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900853 goto read_len;
854 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900855
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900856 /*
857 * All is well, or the error is fatal. Signal that the
858 * next nameserver ought not be tried.
859 */
860 if (resplen > 0) {
861 struct timespec done = evNowTime();
Luke Huang420ee622019-11-27 17:52:44 +0800862 *delay = res_stats_calculate_rtt(&done, &start_time);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900863 *rcode = anhp->rcode;
864 }
Luke Huang23d55192020-04-16 11:47:30 +0800865 *terrno = 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900866 return (resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900867}
868
869/* return -1 on error (errno set), 0 on success */
Luke Huangc98fd802019-10-15 16:36:36 +0900870static int connect_with_timeout(int sock, const sockaddr* nsap, socklen_t salen,
871 const timespec timeout) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900872 int res, origflags;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900873
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900874 origflags = fcntl(sock, F_GETFL, 0);
875 fcntl(sock, F_SETFL, origflags | O_NONBLOCK);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900876
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900877 res = connect(sock, nsap, salen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900878 if (res < 0 && errno != EINPROGRESS) {
879 res = -1;
880 goto done;
881 }
882 if (res != 0) {
Luke Huangc98fd802019-10-15 16:36:36 +0900883 timespec now = evNowTime();
884 timespec finish = evAddTime(now, timeout);
Ken Chenffc224a2019-03-19 17:41:28 +0800885 LOG(INFO) << __func__ << ": " << sock << " send_vc";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900886 res = retrying_poll(sock, POLLIN | POLLOUT, &finish);
887 if (res <= 0) {
888 res = -1;
889 }
890 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900891done:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900892 fcntl(sock, F_SETFL, origflags);
Ken Chenffc224a2019-03-19 17:41:28 +0800893 LOG(INFO) << __func__ << ": " << sock << " connect_with_const timeout returning " << res;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900894 return res;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900895}
896
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900897static int retrying_poll(const int sock, const short events, const struct timespec* finish) {
898 struct timespec now, timeout;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900899
900retry:
Ken Chenffc224a2019-03-19 17:41:28 +0800901 LOG(INFO) << __func__ << ": " << sock << " retrying_poll";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900902
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900903 now = evNowTime();
904 if (evCmpTime(*finish, now) > 0)
905 timeout = evSubTime(*finish, now);
906 else
907 timeout = evConsTime(0L, 0L);
908 struct pollfd fds = {.fd = sock, .events = events};
Maciej Żenczykowski88f87552020-04-23 08:48:36 -0700909 int n = ppoll(&fds, 1, &timeout, /*__mask=*/NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900910 if (n == 0) {
Luke Huang420ee622019-11-27 17:52:44 +0800911 LOG(INFO) << __func__ << ": " << sock << " retrying_poll timeout";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900912 errno = ETIMEDOUT;
913 return 0;
914 }
915 if (n < 0) {
916 if (errno == EINTR) goto retry;
Ken Chenffc224a2019-03-19 17:41:28 +0800917 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll failed";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900918 return n;
919 }
920 if (fds.revents & (POLLIN | POLLOUT | POLLERR)) {
921 int error;
922 socklen_t len = sizeof(error);
923 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error) {
924 errno = error;
Ken Chenffc224a2019-03-19 17:41:28 +0800925 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll getsockopt failed";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900926 return -1;
927 }
928 }
Ken Chenffc224a2019-03-19 17:41:28 +0800929 LOG(INFO) << __func__ << ": " << sock << " retrying_poll returning " << n;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900930 return n;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900931}
932
Luke Huang420ee622019-11-27 17:52:44 +0800933static std::vector<pollfd> extractUdpFdset(res_state statp, const short events = POLLIN) {
934 std::vector<pollfd> fdset(statp->nsaddrs.size());
935 for (size_t i = 0; i < statp->nsaddrs.size(); ++i) {
chenbrucecc9bbc02021-06-15 17:38:14 +0800936 fdset[i] = {.fd = statp->udpsocks[i], .events = events};
Luke Huang420ee622019-11-27 17:52:44 +0800937 }
938 return fdset;
939}
940
941static Result<std::vector<int>> udpRetryingPoll(res_state statp, const timespec* finish) {
942 for (;;) {
943 LOG(DEBUG) << __func__ << ": poll";
944 timespec start_time = evNowTime();
945 timespec timeout = (evCmpTime(*finish, start_time) > 0) ? evSubTime(*finish, start_time)
946 : evConsTime(0L, 0L);
947 std::vector<pollfd> fdset = extractUdpFdset(statp);
Maciej Żenczykowski88f87552020-04-23 08:48:36 -0700948 const int n = ppoll(fdset.data(), fdset.size(), &timeout, /*__mask=*/nullptr);
Luke Huang420ee622019-11-27 17:52:44 +0800949 if (n <= 0) {
950 if (errno == EINTR && n < 0) continue;
951 if (n == 0) errno = ETIMEDOUT;
952 PLOG(INFO) << __func__ << ": failed";
953 return ErrnoError();
954 }
955 std::vector<int> fdsToRead;
956 for (const auto& pollfd : fdset) {
957 if (pollfd.revents & (POLLIN | POLLERR)) {
958 fdsToRead.push_back(pollfd.fd);
959 }
960 }
961 LOG(DEBUG) << __func__ << ": "
962 << " returning fd size: " << fdsToRead.size();
963 return fdsToRead;
964 }
965}
966
967static Result<std::vector<int>> udpRetryingPollWrapper(res_state statp, int ns,
968 const timespec* finish) {
Luke Huangf40df9c2020-04-21 08:51:48 +0800969 const bool keepListeningUdp =
970 android::net::Experiments::getInstance()->getFlag("keep_listening_udp", 0);
Luke Huang420ee622019-11-27 17:52:44 +0800971 if (keepListeningUdp) return udpRetryingPoll(statp, finish);
972
chenbrucecc9bbc02021-06-15 17:38:14 +0800973 if (int n = retrying_poll(statp->udpsocks[ns], POLLIN, finish); n <= 0) {
Luke Huang420ee622019-11-27 17:52:44 +0800974 return ErrnoError();
975 }
chenbrucecc9bbc02021-06-15 17:38:14 +0800976 return std::vector<int>{statp->udpsocks[ns]};
Luke Huang420ee622019-11-27 17:52:44 +0800977}
978
Luke Huangbff43fc2019-11-12 15:54:47 +0800979bool ignoreInvalidAnswer(res_state statp, const sockaddr_storage& from, const uint8_t* buf,
Luke Huang420ee622019-11-27 17:52:44 +0800980 int buflen, uint8_t* ans, int anssiz, int* receivedFromNs) {
Luke Huangbff43fc2019-11-12 15:54:47 +0800981 const HEADER* hp = (const HEADER*)(const void*)buf;
982 HEADER* anhp = (HEADER*)(void*)ans;
983 if (hp->id != anhp->id) {
984 // response from old query, ignore it.
985 LOG(DEBUG) << __func__ << ": old answer:";
986 return true;
987 }
Luke Huang420ee622019-11-27 17:52:44 +0800988 if (*receivedFromNs = res_ourserver_p(statp, (sockaddr*)(void*)&from); *receivedFromNs < 0) {
Luke Huangbff43fc2019-11-12 15:54:47 +0800989 // response from wrong server? ignore it.
990 LOG(DEBUG) << __func__ << ": not our server:";
991 return true;
992 }
993 if (!res_queriesmatch(buf, buf + buflen, ans, ans + anssiz)) {
994 // response contains wrong query? ignore it.
995 LOG(DEBUG) << __func__ << ": wrong query name:";
996 return true;
997 }
998 return false;
999}
1000
chenbruceb1aa65a2021-06-15 19:37:05 +08001001// return 1 when setup udp socket success.
1002// return 0 when timeout , bind error, network error(ex: Protocol not supported ...).
1003// return -1 when create socket fail, set socket option fail.
1004static int setupUdpSocket(ResState* statp, const sockaddr* sockap, size_t addrIndex, int* terrno) {
1005 statp->udpsocks[addrIndex].reset(socket(sockap->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0));
1006
1007 if (statp->udpsocks[addrIndex] < 0) {
1008 *terrno = errno;
1009 PLOG(ERROR) << __func__ << ": socket: ";
1010 switch (errno) {
1011 case EPROTONOSUPPORT:
1012 case EPFNOSUPPORT:
1013 case EAFNOSUPPORT:
1014 return 0;
1015 default:
1016 return -1;
1017 }
1018 }
1019 const uid_t uid = statp->enforce_dns_uid ? AID_DNS : statp->uid;
1020 resolv_tag_socket(statp->udpsocks[addrIndex], uid, statp->pid);
1021 if (statp->_mark != MARK_UNSET) {
1022 if (setsockopt(statp->udpsocks[addrIndex], SOL_SOCKET, SO_MARK, &(statp->_mark),
1023 sizeof(statp->_mark)) < 0) {
1024 *terrno = errno;
1025 statp->closeSockets();
1026 return -1;
1027 }
1028 }
1029
1030 if (random_bind(statp->udpsocks[addrIndex], sockap->sa_family) < 0) {
1031 *terrno = errno;
1032 dump_error("bind", sockap);
1033 statp->closeSockets();
1034 return 0;
1035 }
1036 return 1;
1037}
1038
chenbrucec51f1212019-09-12 16:59:33 +08001039static int send_dg(res_state statp, res_params* params, const uint8_t* buf, int buflen,
Luke Huang420ee622019-11-27 17:52:44 +08001040 uint8_t* ans, int anssiz, int* terrno, size_t* ns, int* v_circuit,
Mike Yue48f7b52020-02-10 14:55:06 +08001041 int* gotsomewhere, time_t* at, int* rcode, int* delay) {
1042 // It should never happen, but just in case.
Luke Huang420ee622019-11-27 17:52:44 +08001043 if (*ns >= statp->nsaddrs.size()) {
Mike Yue48f7b52020-02-10 14:55:06 +08001044 LOG(ERROR) << __func__ << ": Out-of-bound indexing: " << ns;
Luke Huang23d55192020-04-16 11:47:30 +08001045 *terrno = EINVAL;
Mike Yue48f7b52020-02-10 14:55:06 +08001046 return -1;
1047 }
1048
Luke Huangbff43fc2019-11-12 15:54:47 +08001049 *at = time(nullptr);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001050 *delay = 0;
Luke Huang420ee622019-11-27 17:52:44 +08001051 const sockaddr_storage ss = statp->nsaddrs[*ns];
Mike Yue48f7b52020-02-10 14:55:06 +08001052 const sockaddr* nsap = reinterpret_cast<const sockaddr*>(&ss);
Luke Huangbff43fc2019-11-12 15:54:47 +08001053
chenbrucecc9bbc02021-06-15 17:38:14 +08001054 if (statp->udpsocks[*ns] == -1) {
chenbruceb1aa65a2021-06-15 19:37:05 +08001055 int result = setupUdpSocket(statp, nsap, *ns, terrno);
1056 if (result <= 0) return result;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001057
chenbruceb9cce7b2019-07-15 16:14:53 +08001058 // Use a "connected" datagram socket to receive an ECONNREFUSED error
1059 // on the next socket operation when the server responds with an
1060 // ICMP port-unreachable error. This way we can detect the absence of
1061 // a nameserver without timing out.
chenbruceb1aa65a2021-06-15 19:37:05 +08001062 if (connect(statp->udpsocks[*ns], nsap, sockaddrSize(nsap)) < 0) {
Luke Huang23d55192020-04-16 11:47:30 +08001063 *terrno = errno;
chenbruce76620642021-06-15 18:39:27 +08001064 dump_error("connect(dg)", nsap);
Luke Huangadb0f5b2019-11-27 15:51:48 +08001065 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001066 return (0);
1067 }
Ken Chenffc224a2019-03-19 17:41:28 +08001068 LOG(DEBUG) << __func__ << ": new DG socket";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001069 }
chenbrucecc9bbc02021-06-15 17:38:14 +08001070 if (send(statp->udpsocks[*ns], (const char*)buf, (size_t)buflen, 0) != buflen) {
Luke Huang23d55192020-04-16 11:47:30 +08001071 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +08001072 PLOG(DEBUG) << __func__ << ": send: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +08001073 statp->closeSockets();
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001074 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001075 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001076
Luke Huang420ee622019-11-27 17:52:44 +08001077 timespec timeout = get_timeout(statp, params, *ns);
1078 timespec start_time = evNowTime();
1079 timespec finish = evAddTime(start_time, timeout);
Luke Huangbff43fc2019-11-12 15:54:47 +08001080 for (;;) {
1081 // Wait for reply.
Luke Huang420ee622019-11-27 17:52:44 +08001082 auto result = udpRetryingPollWrapper(statp, *ns, &finish);
1083
1084 if (!result.has_value()) {
1085 const bool isTimeout = (result.error().code() == ETIMEDOUT);
1086 *rcode = (isTimeout) ? RCODE_TIMEOUT : *rcode;
Luke Huang23d55192020-04-16 11:47:30 +08001087 *terrno = (isTimeout) ? ETIMEDOUT : errno;
Luke Huang420ee622019-11-27 17:52:44 +08001088 *gotsomewhere = (isTimeout) ? 1 : *gotsomewhere;
1089 // Leave the UDP sockets open on timeout so we can keep listening for
1090 // a late response from this server while retrying on the next server.
1091 if (!isTimeout) statp->closeSockets();
1092 LOG(DEBUG) << __func__ << ": " << (isTimeout) ? "timeout" : "poll";
1093 return 0;
1094 }
1095 bool needRetry = false;
1096 for (int fd : result.value()) {
1097 needRetry = false;
1098 sockaddr_storage from;
1099 socklen_t fromlen = sizeof(from);
1100 int resplen =
1101 recvfrom(fd, (char*)ans, (size_t)anssiz, 0, (sockaddr*)(void*)&from, &fromlen);
1102 if (resplen <= 0) {
Luke Huang23d55192020-04-16 11:47:30 +08001103 *terrno = errno;
Luke Huang420ee622019-11-27 17:52:44 +08001104 PLOG(DEBUG) << __func__ << ": recvfrom: ";
1105 continue;
1106 }
Luke Huangbff43fc2019-11-12 15:54:47 +08001107 *gotsomewhere = 1;
Luke Huang420ee622019-11-27 17:52:44 +08001108 if (resplen < HFIXEDSZ) {
1109 // Undersized message.
1110 LOG(DEBUG) << __func__ << ": undersized: " << resplen;
1111 *terrno = EMSGSIZE;
1112 continue;
1113 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001114
Luke Huang420ee622019-11-27 17:52:44 +08001115 int receivedFromNs = *ns;
1116 if (needRetry =
1117 ignoreInvalidAnswer(statp, from, buf, buflen, ans, anssiz, &receivedFromNs);
1118 needRetry) {
1119 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
1120 continue;
1121 }
Luke Huangbff43fc2019-11-12 15:54:47 +08001122
Luke Huang420ee622019-11-27 17:52:44 +08001123 HEADER* anhp = (HEADER*)(void*)ans;
1124 if (anhp->rcode == FORMERR && (statp->netcontext_flags & NET_CONTEXT_FLAG_USE_EDNS)) {
1125 // Do not retry if the server do not understand EDNS0.
1126 // The case has to be captured here, as FORMERR packet do not
1127 // carry query section, hence res_queriesmatch() returns 0.
1128 LOG(DEBUG) << __func__ << ": server rejected query with EDNS0:";
1129 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
1130 // record the error
1131 statp->_flags |= RES_F_EDNS0ERR;
Luke Huang23d55192020-04-16 11:47:30 +08001132 *terrno = EREMOTEIO;
Luke Huang420ee622019-11-27 17:52:44 +08001133 continue;
1134 }
Luke Huangbff43fc2019-11-12 15:54:47 +08001135
Luke Huang420ee622019-11-27 17:52:44 +08001136 timespec done = evNowTime();
1137 *delay = res_stats_calculate_rtt(&done, &start_time);
1138 if (anhp->rcode == SERVFAIL || anhp->rcode == NOTIMP || anhp->rcode == REFUSED) {
1139 LOG(DEBUG) << __func__ << ": server rejected query:";
1140 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
1141 *rcode = anhp->rcode;
1142 continue;
1143 }
1144 if (anhp->tc) {
1145 // To get the rest of answer,
1146 // use TCP with same server.
1147 LOG(DEBUG) << __func__ << ": truncated answer";
Luke Huang23d55192020-04-16 11:47:30 +08001148 *terrno = E2BIG;
Luke Huang420ee622019-11-27 17:52:44 +08001149 *v_circuit = 1;
1150 return 1;
1151 }
1152 // All is well, or the error is fatal. Signal that the
1153 // next nameserver ought not be tried.
Luke Huangbff43fc2019-11-12 15:54:47 +08001154
Luke Huangbff43fc2019-11-12 15:54:47 +08001155 *rcode = anhp->rcode;
Luke Huang420ee622019-11-27 17:52:44 +08001156 *ns = receivedFromNs;
Luke Huang23d55192020-04-16 11:47:30 +08001157 *terrno = 0;
Luke Huang420ee622019-11-27 17:52:44 +08001158 return resplen;
Luke Huangbff43fc2019-11-12 15:54:47 +08001159 }
Luke Huang420ee622019-11-27 17:52:44 +08001160 if (!needRetry) return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001161 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001162}
1163
chenbruce76620642021-06-15 18:39:27 +08001164static void dump_error(const char* str, const struct sockaddr* address) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001165 char hbuf[NI_MAXHOST];
1166 char sbuf[NI_MAXSERV];
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001167 constexpr int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
Luke Huangc98fd802019-10-15 16:36:36 +09001168 const int err = errno;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001169
chenbruce018fdb22019-06-12 18:08:04 +08001170 if (!WOULD_LOG(DEBUG)) return;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001171
chenbruce76620642021-06-15 18:39:27 +08001172 if (getnameinfo(address, sockaddrSize(address), hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
1173 niflags)) {
chenbruce018fdb22019-06-12 18:08:04 +08001174 strncpy(hbuf, "?", sizeof(hbuf) - 1);
1175 hbuf[sizeof(hbuf) - 1] = '\0';
1176 strncpy(sbuf, "?", sizeof(sbuf) - 1);
1177 sbuf[sizeof(sbuf) - 1] = '\0';
Elliott Hughes3b8f5902019-03-08 12:02:55 -08001178 }
Luke Huangc98fd802019-10-15 16:36:36 +09001179 errno = err;
chenbruce018fdb22019-06-12 18:08:04 +08001180 PLOG(DEBUG) << __func__ << ": " << str << " ([" << hbuf << "]." << sbuf << "): ";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001181}
1182
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001183static int sock_eq(struct sockaddr* a, struct sockaddr* b) {
1184 struct sockaddr_in *a4, *b4;
1185 struct sockaddr_in6 *a6, *b6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001186
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001187 if (a->sa_family != b->sa_family) return 0;
1188 switch (a->sa_family) {
1189 case AF_INET:
1190 a4 = (struct sockaddr_in*) (void*) a;
1191 b4 = (struct sockaddr_in*) (void*) b;
1192 return a4->sin_port == b4->sin_port && a4->sin_addr.s_addr == b4->sin_addr.s_addr;
1193 case AF_INET6:
1194 a6 = (struct sockaddr_in6*) (void*) a;
1195 b6 = (struct sockaddr_in6*) (void*) b;
1196 return a6->sin6_port == b6->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001197#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001198 a6->sin6_scope_id == b6->sin6_scope_id &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001199#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001200 IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
1201 default:
1202 return 0;
1203 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001204}
Mike Yub601ff72018-11-01 20:07:00 +08001205
lifr6b83a6f2019-07-26 03:17:43 +08001206PrivateDnsModes convertEnumType(PrivateDnsMode privateDnsmode) {
1207 switch (privateDnsmode) {
1208 case PrivateDnsMode::OFF:
1209 return PrivateDnsModes::PDM_OFF;
1210 case PrivateDnsMode::OPPORTUNISTIC:
1211 return PrivateDnsModes::PDM_OPPORTUNISTIC;
1212 case PrivateDnsMode::STRICT:
1213 return PrivateDnsModes::PDM_STRICT;
Mike Yu99b8dc72019-11-22 17:45:31 +08001214 default:
1215 return PrivateDnsModes::PDM_UNKNOWN;
lifr6b83a6f2019-07-26 03:17:43 +08001216 }
lifr6b83a6f2019-07-26 03:17:43 +08001217}
1218
Luke Huangd7aa7b42018-11-21 20:37:50 +08001219static int res_tls_send(res_state statp, const Slice query, const Slice answer, int* rcode,
Mike Yubfb1b342018-11-06 15:42:36 +08001220 bool* fallback) {
1221 int resplen = 0;
Mike Yub601ff72018-11-01 20:07:00 +08001222 const unsigned netId = statp->netid;
Mike Yub601ff72018-11-01 20:07:00 +08001223
Mike Yu60248242020-07-29 16:45:26 +08001224 auto& privateDnsConfiguration = PrivateDnsConfiguration::getInstance();
1225 PrivateDnsStatus privateDnsStatus = privateDnsConfiguration.getStatus(netId);
lifr6b83a6f2019-07-26 03:17:43 +08001226 statp->event->set_private_dns_modes(convertEnumType(privateDnsStatus.mode));
Mike Yubfb1b342018-11-06 15:42:36 +08001227
1228 if (privateDnsStatus.mode == PrivateDnsMode::OFF) {
1229 *fallback = true;
1230 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001231 }
1232
Mike Yu3e829062019-08-07 14:01:14 +08001233 if (privateDnsStatus.validatedServers().empty()) {
Mike Yub601ff72018-11-01 20:07:00 +08001234 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
Mike Yubfb1b342018-11-06 15:42:36 +08001235 *fallback = true;
1236 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001237 } else {
1238 // Sleep and iterate some small number of times checking for the
1239 // arrival of resolved and validated server IP addresses, instead
1240 // of returning an immediate error.
Mike Yu4f3747b2018-12-02 17:54:29 +09001241 // This is needed because as soon as a network becomes the default network, apps will
1242 // send DNS queries on that network. If no servers have yet validated, and we do not
1243 // block those queries, they would immediately fail, causing application-visible errors.
1244 // Note that this can happen even before the network validates, since an unvalidated
1245 // network can become the default network if no validated networks are available.
1246 //
1247 // TODO: see if there is a better way to address this problem, such as buffering the
1248 // queries in a queue or only blocking queries for the first few seconds after a default
1249 // network change.
Mike Yubfb1b342018-11-06 15:42:36 +08001250 for (int i = 0; i < 42; i++) {
1251 std::this_thread::sleep_for(std::chrono::milliseconds(100));
Mike Yu3e829062019-08-07 14:01:14 +08001252 // Calling getStatus() to merely check if there's any validated server seems
1253 // wasteful. Consider adding a new method in PrivateDnsConfiguration for speed ups.
Mike Yu60248242020-07-29 16:45:26 +08001254 if (!privateDnsConfiguration.getStatus(netId).validatedServers().empty()) {
1255 privateDnsStatus = privateDnsConfiguration.getStatus(netId);
Mike Yubfb1b342018-11-06 15:42:36 +08001256 break;
1257 }
1258 }
Mike Yu3e829062019-08-07 14:01:14 +08001259 if (privateDnsStatus.validatedServers().empty()) {
Mike Yubfb1b342018-11-06 15:42:36 +08001260 return -1;
1261 }
Mike Yub601ff72018-11-01 20:07:00 +08001262 }
1263 }
1264
chenbruceacb832c2019-02-20 19:45:50 +08001265 LOG(INFO) << __func__ << ": performing query over TLS";
Mike Yub601ff72018-11-01 20:07:00 +08001266
Mike Yu9e8cf8d2020-10-26 19:04:33 +08001267 const auto response = DnsTlsDispatcher::getInstance().query(privateDnsStatus.validatedServers(),
1268 statp, query, answer, &resplen);
Mike Yub601ff72018-11-01 20:07:00 +08001269
chenbruceacb832c2019-02-20 19:45:50 +08001270 LOG(INFO) << __func__ << ": TLS query result: " << static_cast<int>(response);
Mike Yub601ff72018-11-01 20:07:00 +08001271
1272 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
1273 // In opportunistic mode, handle falling back to cleartext in some
1274 // cases (DNS shouldn't fail if a validated opportunistic mode server
1275 // becomes unreachable for some reason).
1276 switch (response) {
Mike Yubfb1b342018-11-06 15:42:36 +08001277 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001278 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001279 return resplen;
Mike Yub601ff72018-11-01 20:07:00 +08001280 case DnsTlsTransport::Response::network_error:
Mike Yubfb1b342018-11-06 15:42:36 +08001281 // No need to set the error timeout here since it will fallback to UDP.
Mike Yub601ff72018-11-01 20:07:00 +08001282 case DnsTlsTransport::Response::internal_error:
1283 // Note: this will cause cleartext queries to be emitted, with
1284 // all of the EDNS0 goodness enabled. Fingers crossed. :-/
Mike Yubfb1b342018-11-06 15:42:36 +08001285 *fallback = true;
1286 [[fallthrough]];
Mike Yub601ff72018-11-01 20:07:00 +08001287 default:
Mike Yubfb1b342018-11-06 15:42:36 +08001288 return -1;
1289 }
1290 } else {
1291 // Strict mode
1292 switch (response) {
1293 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001294 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001295 return resplen;
1296 case DnsTlsTransport::Response::network_error:
1297 // This case happens when the query stored in DnsTlsTransport is expired since
1298 // either 1) the query has been tried for 3 times but no response or 2) fail to
1299 // establish the connection with the server.
Luke Huangd7aa7b42018-11-21 20:37:50 +08001300 *rcode = RCODE_TIMEOUT;
Mike Yubfb1b342018-11-06 15:42:36 +08001301 [[fallthrough]];
1302 default:
1303 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001304 }
1305 }
Mike Yub601ff72018-11-01 20:07:00 +08001306}
Luke Huang4973a0d2018-11-19 20:17:26 +08001307
Luke Huangba7bef92018-12-26 16:53:03 +08001308int resolv_res_nsend(const android_net_context* netContext, const uint8_t* msg, int msgLen,
lifr94981782019-05-17 21:15:19 +08001309 uint8_t* ans, int ansLen, int* rcode, uint32_t flags,
1310 NetworkDnsEventReported* event) {
1311 assert(event != nullptr);
Luke Huang1b3f4462020-12-04 17:48:39 +08001312 ResState res(netContext, event);
Mike Yu021c3e12019-10-08 17:29:34 +08001313 resolv_populate_res_for_net(&res);
Luke Huang4973a0d2018-11-19 20:17:26 +08001314 *rcode = NOERROR;
Bernie Innocenti08487112019-10-11 21:14:13 +09001315 return res_nsend(&res, msg, msgLen, ans, ansLen, rcode, flags);
Bernie Innocentiec4219b2019-01-30 11:16:36 +09001316}