blob: 2b84e82fbfd32d4c67197bc9ea62dff355d3fd92 [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;
Luke Huang816b6a72020-05-15 07:53:52 +0000133using android::net::LinuxErrno;
lifr94981782019-05-17 21:15:19 +0800134using android::net::NetworkDnsEventReported;
chenbruce99cbfd82019-09-05 15:08:13 +0800135using android::net::NS_T_INVALID;
136using android::net::NsRcode;
137using android::net::NsType;
138using android::net::PrivateDnsMode;
139using android::net::PrivateDnsModes;
140using android::net::PrivateDnsStatus;
141using android::net::PROTO_TCP;
142using android::net::PROTO_UDP;
Mike Yue655b1d2019-08-28 17:49:59 +0800143using android::netdutils::IPSockAddr;
Bernie Innocentiec4219b2019-01-30 11:16:36 +0900144using android::netdutils::Slice;
lifr94981782019-05-17 21:15:19 +0800145using android::netdutils::Stopwatch;
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900146
Mike Yub601ff72018-11-01 20:07:00 +0800147static DnsTlsDispatcher sDnsTlsDispatcher;
148
Mike Yue48f7b52020-02-10 14:55:06 +0800149static int send_vc(res_state statp, res_params* params, const uint8_t* buf, int buflen,
150 uint8_t* ans, int anssiz, int* terrno, size_t ns, time_t* at, int* rcode,
151 int* delay);
152static int send_dg(res_state statp, res_params* params, const uint8_t* buf, int buflen,
Luke Huang3caa42b2020-04-23 14:18:04 +0000153 uint8_t* ans, int anssiz, int* terrno, size_t* ns, int* v_circuit,
Mike Yue48f7b52020-02-10 14:55:06 +0800154 int* gotsomewhere, time_t* at, int* rcode, int* delay);
155
chenbruce018fdb22019-06-12 18:08:04 +0800156static void dump_error(const char*, const struct sockaddr*, int);
chenbruceacb832c2019-02-20 19:45:50 +0800157
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900158static int sock_eq(struct sockaddr*, struct sockaddr*);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900159static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
160 const struct timespec timeout);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900161static int retrying_poll(const int sock, short events, const struct timespec* finish);
Luke Huangd7aa7b42018-11-21 20:37:50 +0800162static int res_tls_send(res_state, const Slice query, const Slice answer, int* rcode,
Mike Yubfb1b342018-11-06 15:42:36 +0800163 bool* fallback);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900164
lifr94981782019-05-17 21:15:19 +0800165NsType getQueryType(const uint8_t* msg, size_t msgLen) {
166 ns_msg handle;
167 ns_rr rr;
168 if (ns_initparse((const uint8_t*)msg, msgLen, &handle) < 0 ||
169 ns_parserr(&handle, ns_s_qd, 0, &rr) < 0) {
170 return NS_T_INVALID;
171 }
172 return static_cast<NsType>(ns_rr_type(rr));
173}
174
175IpVersion ipFamilyToIPVersion(const int ipFamily) {
176 switch (ipFamily) {
177 case AF_INET:
178 return IV_IPV4;
179 case AF_INET6:
180 return IV_IPV6;
181 default:
182 return IV_UNKNOWN;
183 }
184}
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900185
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900186// BEGIN: Code copied from ISC eventlib
187// TODO: move away from this code
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900188#define BILLION 1000000000
189
190static struct timespec evConsTime(time_t sec, long nsec) {
191 struct timespec x;
192
193 x.tv_sec = sec;
194 x.tv_nsec = nsec;
195 return (x);
196}
197
198static struct timespec evAddTime(struct timespec addend1, struct timespec addend2) {
199 struct timespec x;
200
201 x.tv_sec = addend1.tv_sec + addend2.tv_sec;
202 x.tv_nsec = addend1.tv_nsec + addend2.tv_nsec;
203 if (x.tv_nsec >= BILLION) {
204 x.tv_sec++;
205 x.tv_nsec -= BILLION;
206 }
207 return (x);
208}
209
210static struct timespec evSubTime(struct timespec minuend, struct timespec subtrahend) {
211 struct timespec x;
212
213 x.tv_sec = minuend.tv_sec - subtrahend.tv_sec;
214 if (minuend.tv_nsec >= subtrahend.tv_nsec)
215 x.tv_nsec = minuend.tv_nsec - subtrahend.tv_nsec;
216 else {
217 x.tv_nsec = BILLION - subtrahend.tv_nsec + minuend.tv_nsec;
218 x.tv_sec--;
219 }
220 return (x);
221}
222
223static int evCmpTime(struct timespec a, struct timespec b) {
224#define SGN(x) ((x) < 0 ? (-1) : (x) > 0 ? (1) : (0));
225 time_t s = a.tv_sec - b.tv_sec;
226 long n;
227
228 if (s != 0) return SGN(s);
229
230 n = a.tv_nsec - b.tv_nsec;
231 return SGN(n);
232}
233
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900234static struct timespec evNowTime(void) {
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900235 struct timespec tsnow;
Bernie Innocentic1834822018-08-31 16:11:41 +0900236 clock_gettime(CLOCK_REALTIME, &tsnow);
237 return tsnow;
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900238}
239
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900240// END: Code copied from ISC eventlib
241
lifr94981782019-05-17 21:15:19 +0800242/* BIONIC-BEGIN: implement source port randomization */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900243static int random_bind(int s, int family) {
nuccachenb980f2f2018-10-23 17:10:58 +0800244 sockaddr_union u;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900245 int j;
246 socklen_t slen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900247
248 /* clear all, this also sets the IP4/6 address to 'any' */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900249 memset(&u, 0, sizeof u);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900250
251 switch (family) {
252 case AF_INET:
253 u.sin.sin_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900254 slen = sizeof u.sin;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900255 break;
256 case AF_INET6:
257 u.sin6.sin6_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900258 slen = sizeof u.sin6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900259 break;
260 default:
261 errno = EPROTO;
262 return -1;
263 }
264
265 /* first try to bind to a random source port a few times */
266 for (j = 0; j < 10; j++) {
267 /* find a random port between 1025 .. 65534 */
Luke Huangdda920f2019-02-13 14:05:02 +0800268 int port = 1025 + (arc4random_uniform(65535 - 1025));
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900269 if (family == AF_INET)
270 u.sin.sin_port = htons(port);
271 else
272 u.sin6.sin6_port = htons(port);
273
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900274 if (!bind(s, &u.sa, slen)) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900275 }
276
Bernie Innocenti9c575932018-09-07 21:10:25 +0900277 // nothing after 10 attempts, our network table is probably busy
278 // let the system decide which port is best
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900279 if (family == AF_INET)
280 u.sin.sin_port = 0;
281 else
282 u.sin6.sin6_port = 0;
283
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900284 return bind(s, &u.sa, slen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900285}
286/* BIONIC-END */
287
Luke Huang70931aa2019-01-31 11:57:41 +0800288// Disables all nameservers other than selectedServer
289static void res_set_usable_server(int selectedServer, int nscount, bool usable_servers[]) {
290 int usableIndex = 0;
291 for (int ns = 0; ns < nscount; ns++) {
292 if (usable_servers[ns]) ++usableIndex;
293 if (usableIndex != selectedServer) usable_servers[ns] = false;
294 }
295}
296
Luke Huang3caa42b2020-04-23 14:18:04 +0000297// Looks up the nameserver address in res.nsaddrs[], returns the ns number if found, otherwise -1.
298static int res_ourserver_p(res_state statp, const sockaddr* sa) {
Bernie Innocenti2e8540b2018-09-26 11:52:04 +0900299 const sockaddr_in *inp, *srv;
300 const sockaddr_in6 *in6p, *srv6;
Luke Huang3caa42b2020-04-23 14:18:04 +0000301 int ns = 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900302 switch (sa->sa_family) {
303 case AF_INET:
304 inp = (const struct sockaddr_in*) (const void*) sa;
Luke Huang3caa42b2020-04-23 14:18:04 +0000305
Mike Yue48f7b52020-02-10 14:55:06 +0800306 for (const IPSockAddr& ipsa : statp->nsaddrs) {
307 sockaddr_storage ss = ipsa;
308 srv = reinterpret_cast<sockaddr_in*>(&ss);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900309 if (srv->sin_family == inp->sin_family && srv->sin_port == inp->sin_port &&
310 (srv->sin_addr.s_addr == INADDR_ANY ||
311 srv->sin_addr.s_addr == inp->sin_addr.s_addr))
Luke Huang3caa42b2020-04-23 14:18:04 +0000312 return ns;
313 ++ns;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900314 }
315 break;
316 case AF_INET6:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900317 in6p = (const struct sockaddr_in6*) (const void*) sa;
Mike Yue48f7b52020-02-10 14:55:06 +0800318 for (const IPSockAddr& ipsa : statp->nsaddrs) {
319 sockaddr_storage ss = ipsa;
320 srv6 = reinterpret_cast<sockaddr_in6*>(&ss);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900321 if (srv6->sin6_family == in6p->sin6_family && srv6->sin6_port == in6p->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900322#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900323 (srv6->sin6_scope_id == 0 || srv6->sin6_scope_id == in6p->sin6_scope_id) &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900324#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900325 (IN6_IS_ADDR_UNSPECIFIED(&srv6->sin6_addr) ||
326 IN6_ARE_ADDR_EQUAL(&srv6->sin6_addr, &in6p->sin6_addr)))
Luke Huang3caa42b2020-04-23 14:18:04 +0000327 return ns;
328 ++ns;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900329 }
330 break;
331 default:
332 break;
333 }
Luke Huang3caa42b2020-04-23 14:18:04 +0000334 return -1;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900335}
336
337/* int
Bernie Innocenti9c575932018-09-07 21:10:25 +0900338 * res_nameinquery(name, type, cl, buf, eom)
339 * look for (name, type, cl) in the query section of packet (buf, eom)
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900340 * requires:
341 * buf + HFIXEDSZ <= eom
342 * returns:
343 * -1 : format error
344 * 0 : not found
345 * >0 : found
346 * author:
347 * paul vixie, 29may94
348 */
chenbrucec51f1212019-09-12 16:59:33 +0800349int res_nameinquery(const char* name, int type, int cl, const uint8_t* buf, const uint8_t* eom) {
350 const uint8_t* cp = buf + HFIXEDSZ;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900351 int qdcount = ntohs(((const HEADER*) (const void*) buf)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900352
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900353 while (qdcount-- > 0) {
354 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900355 int n = dn_expand(buf, eom, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900356 if (n < 0) return (-1);
357 cp += n;
358 if (cp + 2 * INT16SZ > eom) return (-1);
chenbruce0d470422019-03-28 18:44:37 +0800359 int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900360 cp += INT16SZ;
chenbruce0d470422019-03-28 18:44:37 +0800361 int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900362 cp += INT16SZ;
Bernie Innocenti9c575932018-09-07 21:10:25 +0900363 if (ttype == type && tclass == cl && ns_samename(tname, name) == 1) return (1);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900364 }
365 return (0);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900366}
367
368/* int
369 * res_queriesmatch(buf1, eom1, buf2, eom2)
370 * is there a 1:1 mapping of (name,type,class)
371 * in (buf1,eom1) and (buf2,eom2)?
372 * returns:
373 * -1 : format error
374 * 0 : not a 1:1 mapping
375 * >0 : is a 1:1 mapping
376 * author:
377 * paul vixie, 29may94
378 */
chenbrucec51f1212019-09-12 16:59:33 +0800379int res_queriesmatch(const uint8_t* buf1, const uint8_t* eom1, const uint8_t* buf2,
380 const uint8_t* eom2) {
381 const uint8_t* cp = buf1 + HFIXEDSZ;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900382 int qdcount = ntohs(((const HEADER*) (const void*) buf1)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900383
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900384 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2) return (-1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900385
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900386 /*
387 * Only header section present in replies to
388 * dynamic update packets.
389 */
390 if ((((const HEADER*) (const void*) buf1)->opcode == ns_o_update) &&
391 (((const HEADER*) (const void*) buf2)->opcode == ns_o_update))
392 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900393
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900394 if (qdcount != ntohs(((const HEADER*) (const void*) buf2)->qdcount)) return (0);
395 while (qdcount-- > 0) {
396 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900397 int n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900398 if (n < 0) return (-1);
399 cp += n;
400 if (cp + 2 * INT16SZ > eom1) return (-1);
chenbruce0d470422019-03-28 18:44:37 +0800401 int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900402 cp += INT16SZ;
chenbruce0d470422019-03-28 18:44:37 +0800403 int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900404 cp += INT16SZ;
405 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2)) return (0);
406 }
407 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900408}
409
lifr94981782019-05-17 21:15:19 +0800410static DnsQueryEvent* addDnsQueryEvent(NetworkDnsEventReported* event) {
411 return event->mutable_dns_query_events()->add_dns_query_event();
412}
413
chenbrucec51f1212019-09-12 16:59:33 +0800414int 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 +0000415 uint32_t flags, std::chrono::milliseconds sleepTimeMs) {
Luke Huang43cc1b12019-10-15 19:06:42 +0900416 LOG(DEBUG) << __func__;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900417
Luke Huang43cc1b12019-10-15 19:06:42 +0900418 // Should not happen
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900419 if (anssiz < HFIXEDSZ) {
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800420 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900421 errno = EINVAL;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800422 return -EINVAL;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900423 }
chenbrucedd210722019-03-06 13:52:43 +0800424 res_pquery(buf, buflen);
chenbruceacb832c2019-02-20 19:45:50 +0800425
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900426 int anslen = 0;
lifrd4d9fbb2019-07-31 20:18:35 +0800427 Stopwatch cacheStopwatch;
Luke Huang43cc1b12019-10-15 19:06:42 +0900428 ResolvCacheStatus cache_status =
429 resolv_cache_lookup(statp->netid, buf, buflen, ans, anssiz, &anslen, flags);
lifrd4d9fbb2019-07-31 20:18:35 +0800430 const int32_t cacheLatencyUs = saturate_cast<int32_t>(cacheStopwatch.timeTakenUs());
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900431 if (cache_status == RESOLV_CACHE_FOUND) {
Luke Huang83c9b4b2019-02-27 18:18:01 +0800432 HEADER* hp = (HEADER*)(void*)ans;
433 *rcode = hp->rcode;
lifr94981782019-05-17 21:15:19 +0800434 DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
435 dnsQueryEvent->set_latency_micros(cacheLatencyUs);
436 dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
lifre02d01c2019-12-31 17:24:57 +0800437 dnsQueryEvent->set_type(getQueryType(buf, buflen));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900438 return anslen;
439 } else if (cache_status != RESOLV_CACHE_UNSUPPORTED) {
440 // had a cache miss for a known network, so populate the thread private
441 // data so the normal resolve path can do its thing
Mike Yu021c3e12019-10-08 17:29:34 +0800442 resolv_populate_res_for_net(statp);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900443 }
Mike Yuecc52822020-02-14 14:36:46 +0800444 if (statp->nameserverCount() == 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900445 // We have no nameservers configured, so there's no point trying.
446 // Tell the cache the query failed, or any retries and anyone else asking the same
447 // question will block for PENDING_REQUEST_TIMEOUT seconds instead of failing fast.
Luke Huangba7bef92018-12-26 16:53:03 +0800448 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800449
450 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900451 errno = ESRCH;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800452 return -ESRCH;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900453 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900454
Luke Huang5b30e712020-05-01 11:09:42 +0000455 // If parallel_lookup is enabled, it might be required to wait some time to avoid
456 // gateways drop packets if queries are sent too close together
457 if (sleepTimeMs != 0ms) {
458 std::this_thread::sleep_for(sleepTimeMs);
459 }
Luke Huang272cb192019-10-15 16:52:28 +0900460 // DoT
461 if (!(statp->netcontext_flags & NET_CONTEXT_FLAG_USE_LOCAL_NAMESERVERS)) {
462 bool fallback = false;
Luke Huang43cc1b12019-10-15 19:06:42 +0900463 int resplen = res_tls_send(statp, Slice(const_cast<uint8_t*>(buf), buflen),
464 Slice(ans, anssiz), rcode, &fallback);
Luke Huang272cb192019-10-15 16:52:28 +0900465 if (resplen > 0) {
466 LOG(DEBUG) << __func__ << ": got answer from DoT";
467 res_pquery(ans, resplen);
468 if (cache_status == RESOLV_CACHE_NOTFOUND) {
469 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
470 }
471 return resplen;
472 }
473 if (!fallback) {
474 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huang43cc1b12019-10-15 19:06:42 +0900475 return -ETIMEDOUT;
Luke Huang272cb192019-10-15 16:52:28 +0900476 }
477 }
478
Mike Yuc573a3d2020-02-07 20:15:15 +0800479 res_stats stats[MAXNS]{};
Bernie Innocenti758005f2019-02-19 18:08:36 +0900480 res_params params;
Mike Yuc573a3d2020-02-07 20:15:15 +0800481 int revision_id = resolv_cache_get_resolver_stats(statp->netid, &params, stats, statp->nsaddrs);
lifra1b37f12019-02-13 17:33:57 +0800482 if (revision_id < 0) {
483 // TODO: Remove errno once callers stop using it
484 errno = ESRCH;
485 return -ESRCH;
486 }
waynema0161acd2019-02-18 17:47:59 +0800487 bool usable_servers[MAXNS];
Luke Huang70931aa2019-01-31 11:57:41 +0800488 int usableServersCount = android_net_res_stats_get_usable_servers(
Mike Yuecc52822020-02-14 14:36:46 +0800489 &params, stats, statp->nameserverCount(), usable_servers);
Luke Huang70931aa2019-01-31 11:57:41 +0800490
491 if ((flags & ANDROID_RESOLV_NO_RETRY) && usableServersCount > 1) {
492 auto hp = reinterpret_cast<const HEADER*>(buf);
493
494 // Select a random server based on the query id
495 int selectedServer = (hp->id % usableServersCount) + 1;
Mike Yuecc52822020-02-14 14:36:46 +0800496 res_set_usable_server(selectedServer, statp->nameserverCount(), usable_servers);
Luke Huang70931aa2019-01-31 11:57:41 +0800497 }
waynema0161acd2019-02-18 17:47:59 +0800498
Luke Huang43cc1b12019-10-15 19:06:42 +0900499 // Send request, RETRY times, or until successful.
waynemaa74195e2019-01-18 14:02:31 +0800500 int retryTimes = (flags & ANDROID_RESOLV_NO_RETRY) ? 1 : params.retry_count;
Luke Huang43cc1b12019-10-15 19:06:42 +0900501 int useTcp = buflen > PACKETSZ;
502 int gotsomewhere = 0;
Luke Huang816b6a72020-05-15 07:53:52 +0000503 // Use an impossible error code as default value
504 int terrno = ETIME;
Luke Huangba7bef92018-12-26 16:53:03 +0800505
506 for (int attempt = 0; attempt < retryTimes; ++attempt) {
Mike Yue48f7b52020-02-10 14:55:06 +0800507 for (size_t ns = 0; ns < statp->nsaddrs.size(); ++ns) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900508 if (!usable_servers[ns]) continue;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900509
Luke Huang43cc1b12019-10-15 19:06:42 +0900510 *rcode = RCODE_INTERNAL_ERROR;
511
512 // Get server addr
Mike Yue48f7b52020-02-10 14:55:06 +0800513 const IPSockAddr& serverSockAddr = statp->nsaddrs[ns];
514 LOG(DEBUG) << __func__ << ": Querying server (# " << ns + 1
515 << ") address = " << serverSockAddr.toString();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900516
Luke Huang43cc1b12019-10-15 19:06:42 +0900517 ::android::net::Protocol query_proto = useTcp ? PROTO_TCP : PROTO_UDP;
Luke Huang3caa42b2020-04-23 14:18:04 +0000518 time_t query_time = 0;
Luke Huang43cc1b12019-10-15 19:06:42 +0900519 int delay = 0;
520 bool fallbackTCP = false;
521 const bool shouldRecordStats = (attempt == 0);
522 int resplen;
lifrd4d9fbb2019-07-31 20:18:35 +0800523 Stopwatch queryStopwatch;
lifr128183a2020-01-08 18:04:50 +0800524 int retry_count_for_event = 0;
Luke Huang3caa42b2020-04-23 14:18:04 +0000525 size_t actualNs = ns;
Luke Huang816b6a72020-05-15 07:53:52 +0000526 // Use an impossible error code as default value
527 terrno = ETIME;
Luke Huang43cc1b12019-10-15 19:06:42 +0900528 if (useTcp) {
529 // TCP; at most one attempt per server.
Luke Huangba7bef92018-12-26 16:53:03 +0800530 attempt = retryTimes;
Luke Huang3caa42b2020-04-23 14:18:04 +0000531 resplen = send_vc(statp, &params, buf, buflen, ans, anssiz, &terrno, ns,
532 &query_time, rcode, &delay);
Ken Chen99344882020-01-01 14:59:38 +0800533
534 if (buflen <= PACKETSZ && resplen <= 0 &&
535 statp->tc_mode == aidl::android::net::IDnsResolver::TC_MODE_UDP_TCP) {
536 // reset to UDP for next query on next DNS server if resolver is currently doing
537 // TCP fallback retry and current server does not support TCP connectin
538 useTcp = false;
539 }
540 LOG(INFO) << __func__ << ": used send_vc " << resplen;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900541 } else {
Luke Huang43cc1b12019-10-15 19:06:42 +0900542 // UDP
Luke Huang3caa42b2020-04-23 14:18:04 +0000543 resplen = send_dg(statp, &params, buf, buflen, ans, anssiz, &terrno, &actualNs,
544 &useTcp, &gotsomewhere, &query_time, rcode, &delay);
Luke Huang43cc1b12019-10-15 19:06:42 +0900545 fallbackTCP = useTcp ? true : false;
lifr128183a2020-01-08 18:04:50 +0800546 retry_count_for_event = attempt;
Ken Chen99344882020-01-01 14:59:38 +0800547 LOG(INFO) << __func__ << ": used send_dg " << resplen;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900548 }
Luke Huang43cc1b12019-10-15 19:06:42 +0900549
Luke Huang3caa42b2020-04-23 14:18:04 +0000550 const IPSockAddr& receivedServerAddr = statp->nsaddrs[actualNs];
Luke Huang43cc1b12019-10-15 19:06:42 +0900551 DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
552 dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
Luke Huang3caa42b2020-04-23 14:18:04 +0000553 // When |retryTimes| > 1, we cannot actually know the correct latency value if we
554 // received the answer from the previous server. So temporarily set the latency as -1 if
555 // that condition happened.
556 // TODO: make the latency value accurate.
557 dnsQueryEvent->set_latency_micros(
558 (actualNs == ns) ? saturate_cast<int32_t>(queryStopwatch.timeTakenUs()) : -1);
559 dnsQueryEvent->set_dns_server_index(actualNs);
560 dnsQueryEvent->set_ip_version(ipFamilyToIPVersion(receivedServerAddr.family()));
lifr128183a2020-01-08 18:04:50 +0800561 dnsQueryEvent->set_retry_times(retry_count_for_event);
Luke Huang43cc1b12019-10-15 19:06:42 +0900562 dnsQueryEvent->set_rcode(static_cast<NsRcode>(*rcode));
563 dnsQueryEvent->set_protocol(query_proto);
564 dnsQueryEvent->set_type(getQueryType(buf, buflen));
Luke Huang816b6a72020-05-15 07:53:52 +0000565 dnsQueryEvent->set_linux_errno(static_cast<LinuxErrno>(terrno));
Luke Huang43cc1b12019-10-15 19:06:42 +0900566
567 // Only record stats the first time we try a query. This ensures that
568 // queries that deterministically fail (e.g., a name that always returns
569 // SERVFAIL or times out) do not unduly affect the stats.
570 if (shouldRecordStats) {
571 res_sample sample;
Luke Huang3caa42b2020-04-23 14:18:04 +0000572 res_stats_set_sample(&sample, query_time, *rcode, delay);
573 // KeepListening UDP mechanism is incompatible with usable_servers of legacy stats,
574 // so keep the old logic for now.
575 // TODO: Replace usable_servers of legacy stats with new one.
Mike Yue48f7b52020-02-10 14:55:06 +0800576 resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, serverSockAddr,
577 sample, params.max_samples);
Luke Huang3caa42b2020-04-23 14:18:04 +0000578 resolv_stats_add(statp->netid, receivedServerAddr, dnsQueryEvent);
Luke Huang43cc1b12019-10-15 19:06:42 +0900579 }
580
581 if (resplen == 0) continue;
582 if (fallbackTCP) {
583 ns--;
584 continue;
585 }
586 if (resplen < 0) {
587 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800588 statp->closeSockets();
Luke Huang43cc1b12019-10-15 19:06:42 +0900589 return -terrno;
590 };
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900591
Ken Chenffc224a2019-03-19 17:41:28 +0800592 LOG(DEBUG) << __func__ << ": got answer:";
chenbrucedd210722019-03-06 13:52:43 +0800593 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900594
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900595 if (cache_status == RESOLV_CACHE_NOTFOUND) {
Mike Yud1ec2542019-06-06 17:17:53 +0800596 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900597 }
Luke Huangadb0f5b2019-11-27 15:51:48 +0800598 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900599 return (resplen);
Bernie Innocenti9c575932018-09-07 21:10:25 +0900600 } // for each ns
601 } // for each retry
Luke Huangadb0f5b2019-11-27 15:51:48 +0800602 statp->closeSockets();
Luke Huang43cc1b12019-10-15 19:06:42 +0900603 terrno = useTcp ? terrno : gotsomewhere ? ETIMEDOUT : ECONNREFUSED;
604 // TODO: Remove errno once callers stop using it
605 errno = useTcp ? terrno
606 : gotsomewhere ? ETIMEDOUT /* no answer obtained */
607 : ECONNREFUSED /* no nameservers found */;
608
Luke Huangba7bef92018-12-26 16:53:03 +0800609 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800610 return -terrno;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900611}
612
chenbruce99cbfd82019-09-05 15:08:13 +0800613static struct timespec get_timeout(res_state statp, const res_params* params, const int ns) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900614 int msec;
waynemaa74195e2019-01-18 14:02:31 +0800615 // Legacy algorithm which scales the timeout by nameserver number.
616 // For instance, with 4 nameservers: 5s, 2.5s, 5s, 10s
617 // This has no effect with 1 or 2 nameservers
618 msec = params->base_timeout_msec << ns;
619 if (ns > 0) {
Mike Yuecc52822020-02-14 14:36:46 +0800620 msec /= statp->nameserverCount();
waynemaa74195e2019-01-18 14:02:31 +0800621 }
622 // For safety, don't allow OEMs and experiments to configure a timeout shorter than 1s.
623 if (msec < 1000) {
624 msec = 1000; // Use at least 1000ms
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900625 }
Ken Chenffc224a2019-03-19 17:41:28 +0800626 LOG(INFO) << __func__ << ": using timeout of " << msec << " msec";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900627
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900628 struct timespec result;
629 result.tv_sec = msec / 1000;
630 result.tv_nsec = (msec % 1000) * 1000000;
631 return result;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900632}
633
chenbrucec51f1212019-09-12 16:59:33 +0800634static int send_vc(res_state statp, res_params* params, const uint8_t* buf, int buflen,
Mike Yue48f7b52020-02-10 14:55:06 +0800635 uint8_t* ans, int anssiz, int* terrno, size_t ns, time_t* at, int* rcode,
chenbrucec51f1212019-09-12 16:59:33 +0800636 int* delay) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900637 *at = time(NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900638 *delay = 0;
639 const HEADER* hp = (const HEADER*) (const void*) buf;
640 HEADER* anhp = (HEADER*) (void*) ans;
641 struct sockaddr* nsap;
642 int nsaplen;
chenbruce0d470422019-03-28 18:44:37 +0800643 int truncating, connreset, n;
chenbrucec51f1212019-09-12 16:59:33 +0800644 uint8_t* cp;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900645
Ken Chenffc224a2019-03-19 17:41:28 +0800646 LOG(INFO) << __func__ << ": using send_vc";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900647
Mike Yue48f7b52020-02-10 14:55:06 +0800648 // It should never happen, but just in case.
649 if (ns >= statp->nsaddrs.size()) {
650 LOG(ERROR) << __func__ << ": Out-of-bound indexing: " << ns;
Luke Huang816b6a72020-05-15 07:53:52 +0000651 *terrno = EINVAL;
Mike Yue48f7b52020-02-10 14:55:06 +0800652 return -1;
653 }
654
655 sockaddr_storage ss = statp->nsaddrs[ns];
656 nsap = reinterpret_cast<sockaddr*>(&ss);
Mike Yu021c3e12019-10-08 17:29:34 +0800657 nsaplen = sockaddrSize(nsap);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900658
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900659 connreset = 0;
660same_ns:
661 truncating = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900662
Luke Huang3caa42b2020-04-23 14:18:04 +0000663 struct timespec start_time = evNowTime();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900664
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900665 /* Are we still talking to whom we want to talk to? */
Luke Huangadb0f5b2019-11-27 15:51:48 +0800666 if (statp->tcp_nssock >= 0 && (statp->_flags & RES_F_VC) != 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900667 struct sockaddr_storage peer;
668 socklen_t size = sizeof peer;
669 unsigned old_mark;
670 socklen_t mark_size = sizeof(old_mark);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800671 if (getpeername(statp->tcp_nssock, (struct sockaddr*)(void*)&peer, &size) < 0 ||
672 !sock_eq((struct sockaddr*)(void*)&peer, nsap) ||
673 getsockopt(statp->tcp_nssock, SOL_SOCKET, SO_MARK, &old_mark, &mark_size) < 0 ||
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900674 old_mark != statp->_mark) {
Luke Huangadb0f5b2019-11-27 15:51:48 +0800675 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900676 }
677 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900678
Luke Huangadb0f5b2019-11-27 15:51:48 +0800679 if (statp->tcp_nssock < 0 || (statp->_flags & RES_F_VC) == 0) {
680 if (statp->tcp_nssock >= 0) statp->closeSockets();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900681
Luke Huangadb0f5b2019-11-27 15:51:48 +0800682 statp->tcp_nssock.reset(socket(nsap->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0));
683 if (statp->tcp_nssock < 0) {
Luke Huang816b6a72020-05-15 07:53:52 +0000684 *terrno = errno;
685 PLOG(DEBUG) << __func__ << ": socket(vc): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900686 switch (errno) {
687 case EPROTONOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900688 case EPFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900689 case EAFNOSUPPORT:
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900690 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900691 default:
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900692 return -1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900693 }
694 }
Luke Huangadb0f5b2019-11-27 15:51:48 +0800695 resolv_tag_socket(statp->tcp_nssock, statp->uid, statp->pid);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900696 if (statp->_mark != MARK_UNSET) {
Luke Huangadb0f5b2019-11-27 15:51:48 +0800697 if (setsockopt(statp->tcp_nssock, SOL_SOCKET, SO_MARK, &statp->_mark,
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900698 sizeof(statp->_mark)) < 0) {
699 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800700 PLOG(DEBUG) << __func__ << ": setsockopt: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900701 return -1;
702 }
703 }
704 errno = 0;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800705 if (random_bind(statp->tcp_nssock, nsap->sa_family) < 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900706 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800707 dump_error("bind/vc", nsap, nsaplen);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800708 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900709 return (0);
710 }
Luke Huangadb0f5b2019-11-27 15:51:48 +0800711 if (connect_with_timeout(statp->tcp_nssock, nsap, (socklen_t)nsaplen,
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900712 get_timeout(statp, params, ns)) < 0) {
713 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800714 dump_error("connect/vc", nsap, nsaplen);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800715 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900716 /*
717 * The way connect_with_timeout() is implemented prevents us from reliably
718 * determining whether this was really a timeout or e.g. ECONNREFUSED. Since
719 * currently both cases are handled in the same way, there is no need to
720 * change this (yet). If we ever need to reliably distinguish between these
721 * cases, both connect_with_timeout() and retrying_poll() need to be
722 * modified, though.
723 */
724 *rcode = RCODE_TIMEOUT;
725 return (0);
726 }
727 statp->_flags |= RES_F_VC;
728 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900729
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900730 /*
731 * Send length & message
732 */
chenbruce0d470422019-03-28 18:44:37 +0800733 uint16_t len = htons(static_cast<uint16_t>(buflen));
Luke Huangc98fd802019-10-15 16:36:36 +0900734 const iovec iov[] = {
735 {.iov_base = &len, .iov_len = INT16SZ},
736 {.iov_base = const_cast<uint8_t*>(buf), .iov_len = static_cast<size_t>(buflen)},
737 };
Luke Huangadb0f5b2019-11-27 15:51:48 +0800738 if (writev(statp->tcp_nssock, iov, 2) != (INT16SZ + buflen)) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900739 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800740 PLOG(DEBUG) << __func__ << ": write failed: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800741 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900742 return (0);
743 }
744 /*
745 * Receive length & response
746 */
747read_len:
748 cp = ans;
749 len = INT16SZ;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800750 while ((n = read(statp->tcp_nssock, (char*)cp, (size_t)len)) > 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900751 cp += n;
752 if ((len -= n) == 0) break;
753 }
754 if (n <= 0) {
755 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800756 PLOG(DEBUG) << __func__ << ": read failed: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800757 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900758 /*
759 * A long running process might get its TCP
760 * connection reset if the remote server was
761 * restarted. Requery the server instead of
762 * trying a new one. When there is only one
763 * server, this means that a query might work
764 * instead of failing. We only allow one reset
765 * per query to prevent looping.
766 */
767 if (*terrno == ECONNRESET && !connreset) {
768 connreset = 1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900769 goto same_ns;
770 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900771 return (0);
772 }
chenbruce0d470422019-03-28 18:44:37 +0800773 uint16_t resplen = ntohs(*reinterpret_cast<const uint16_t*>(ans));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900774 if (resplen > anssiz) {
Ken Chenffc224a2019-03-19 17:41:28 +0800775 LOG(DEBUG) << __func__ << ": response truncated";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900776 truncating = 1;
777 len = anssiz;
778 } else
779 len = resplen;
780 if (len < HFIXEDSZ) {
781 /*
782 * Undersized message.
783 */
Ken Chenffc224a2019-03-19 17:41:28 +0800784 LOG(DEBUG) << __func__ << ": undersized: " << len;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900785 *terrno = EMSGSIZE;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800786 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900787 return (0);
788 }
789 cp = ans;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800790 while (len != 0 && (n = read(statp->tcp_nssock, (char*)cp, (size_t)len)) > 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900791 cp += n;
792 len -= n;
793 }
794 if (n <= 0) {
795 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800796 PLOG(DEBUG) << __func__ << ": read(vc): ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800797 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900798 return (0);
799 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900800
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900801 if (truncating) {
802 /*
803 * Flush rest of answer so connection stays in synch.
804 */
805 anhp->tc = 1;
806 len = resplen - anssiz;
807 while (len != 0) {
808 char junk[PACKETSZ];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900809
Luke Huangadb0f5b2019-11-27 15:51:48 +0800810 n = read(statp->tcp_nssock, junk, (len > sizeof junk) ? sizeof junk : len);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900811 if (n > 0)
812 len -= n;
813 else
814 break;
815 }
816 }
817 /*
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900818 * If the calling application has bailed out of
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900819 * a previous call and failed to arrange to have
820 * the circuit closed or the server has got
821 * itself confused, then drop the packet and
822 * wait for the correct one.
823 */
824 if (hp->id != anhp->id) {
Ken Chenffc224a2019-03-19 17:41:28 +0800825 LOG(DEBUG) << __func__ << ": ld answer (unexpected):";
chenbrucedd210722019-03-06 13:52:43 +0800826 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900827 goto read_len;
828 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900829
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900830 /*
831 * All is well, or the error is fatal. Signal that the
832 * next nameserver ought not be tried.
833 */
834 if (resplen > 0) {
835 struct timespec done = evNowTime();
Luke Huang3caa42b2020-04-23 14:18:04 +0000836 *delay = res_stats_calculate_rtt(&done, &start_time);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900837 *rcode = anhp->rcode;
838 }
Luke Huang816b6a72020-05-15 07:53:52 +0000839 *terrno = 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900840 return (resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900841}
842
843/* return -1 on error (errno set), 0 on success */
Luke Huangc98fd802019-10-15 16:36:36 +0900844static int connect_with_timeout(int sock, const sockaddr* nsap, socklen_t salen,
845 const timespec timeout) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900846 int res, origflags;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900847
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900848 origflags = fcntl(sock, F_GETFL, 0);
849 fcntl(sock, F_SETFL, origflags | O_NONBLOCK);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900850
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900851 res = connect(sock, nsap, salen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900852 if (res < 0 && errno != EINPROGRESS) {
853 res = -1;
854 goto done;
855 }
856 if (res != 0) {
Luke Huangc98fd802019-10-15 16:36:36 +0900857 timespec now = evNowTime();
858 timespec finish = evAddTime(now, timeout);
Ken Chenffc224a2019-03-19 17:41:28 +0800859 LOG(INFO) << __func__ << ": " << sock << " send_vc";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900860 res = retrying_poll(sock, POLLIN | POLLOUT, &finish);
861 if (res <= 0) {
862 res = -1;
863 }
864 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900865done:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900866 fcntl(sock, F_SETFL, origflags);
Ken Chenffc224a2019-03-19 17:41:28 +0800867 LOG(INFO) << __func__ << ": " << sock << " connect_with_const timeout returning " << res;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900868 return res;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900869}
870
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900871static int retrying_poll(const int sock, const short events, const struct timespec* finish) {
872 struct timespec now, timeout;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900873
874retry:
Ken Chenffc224a2019-03-19 17:41:28 +0800875 LOG(INFO) << __func__ << ": " << sock << " retrying_poll";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900876
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900877 now = evNowTime();
878 if (evCmpTime(*finish, now) > 0)
879 timeout = evSubTime(*finish, now);
880 else
881 timeout = evConsTime(0L, 0L);
882 struct pollfd fds = {.fd = sock, .events = events};
Treehugger Robotbcb51802020-04-24 03:57:49 +0000883 int n = ppoll(&fds, 1, &timeout, /*__mask=*/NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900884 if (n == 0) {
Luke Huang3caa42b2020-04-23 14:18:04 +0000885 LOG(INFO) << __func__ << ": " << sock << " retrying_poll timeout";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900886 errno = ETIMEDOUT;
887 return 0;
888 }
889 if (n < 0) {
890 if (errno == EINTR) goto retry;
Ken Chenffc224a2019-03-19 17:41:28 +0800891 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll failed";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900892 return n;
893 }
894 if (fds.revents & (POLLIN | POLLOUT | POLLERR)) {
895 int error;
896 socklen_t len = sizeof(error);
897 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error) {
898 errno = error;
Ken Chenffc224a2019-03-19 17:41:28 +0800899 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll getsockopt failed";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900900 return -1;
901 }
902 }
Ken Chenffc224a2019-03-19 17:41:28 +0800903 LOG(INFO) << __func__ << ": " << sock << " retrying_poll returning " << n;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900904 return n;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900905}
906
Luke Huang3caa42b2020-04-23 14:18:04 +0000907static std::vector<pollfd> extractUdpFdset(res_state statp, const short events = POLLIN) {
908 std::vector<pollfd> fdset(statp->nsaddrs.size());
909 for (size_t i = 0; i < statp->nsaddrs.size(); ++i) {
910 fdset[i] = {.fd = statp->nssocks[i], .events = events};
911 }
912 return fdset;
913}
914
915static Result<std::vector<int>> udpRetryingPoll(res_state statp, const timespec* finish) {
916 for (;;) {
917 LOG(DEBUG) << __func__ << ": poll";
918 timespec start_time = evNowTime();
919 timespec timeout = (evCmpTime(*finish, start_time) > 0) ? evSubTime(*finish, start_time)
920 : evConsTime(0L, 0L);
921 std::vector<pollfd> fdset = extractUdpFdset(statp);
Treehugger Robotbcb51802020-04-24 03:57:49 +0000922 const int n = ppoll(fdset.data(), fdset.size(), &timeout, /*__mask=*/nullptr);
Luke Huang3caa42b2020-04-23 14:18:04 +0000923 if (n <= 0) {
924 if (errno == EINTR && n < 0) continue;
925 if (n == 0) errno = ETIMEDOUT;
926 PLOG(INFO) << __func__ << ": failed";
927 return ErrnoError();
928 }
929 std::vector<int> fdsToRead;
930 for (const auto& pollfd : fdset) {
931 if (pollfd.revents & (POLLIN | POLLERR)) {
932 fdsToRead.push_back(pollfd.fd);
933 }
934 }
935 LOG(DEBUG) << __func__ << ": "
936 << " returning fd size: " << fdsToRead.size();
937 return fdsToRead;
938 }
939}
940
941static Result<std::vector<int>> udpRetryingPollWrapper(res_state statp, int ns,
942 const timespec* finish) {
Luke Huang68fa5002020-04-23 15:48:47 +0000943 const bool keepListeningUdp =
944 android::net::Experiments::getInstance()->getFlag("keep_listening_udp", 0);
Luke Huang3caa42b2020-04-23 14:18:04 +0000945 if (keepListeningUdp) return udpRetryingPoll(statp, finish);
946
947 if (int n = retrying_poll(statp->nssocks[ns], POLLIN, finish); n <= 0) {
948 return ErrnoError();
949 }
950 return std::vector<int>{statp->nssocks[ns]};
951}
952
Luke Huangbff43fc2019-11-12 15:54:47 +0800953bool ignoreInvalidAnswer(res_state statp, const sockaddr_storage& from, const uint8_t* buf,
Luke Huang3caa42b2020-04-23 14:18:04 +0000954 int buflen, uint8_t* ans, int anssiz, int* receivedFromNs) {
Luke Huangbff43fc2019-11-12 15:54:47 +0800955 const HEADER* hp = (const HEADER*)(const void*)buf;
956 HEADER* anhp = (HEADER*)(void*)ans;
957 if (hp->id != anhp->id) {
958 // response from old query, ignore it.
959 LOG(DEBUG) << __func__ << ": old answer:";
960 return true;
961 }
Luke Huang3caa42b2020-04-23 14:18:04 +0000962 if (*receivedFromNs = res_ourserver_p(statp, (sockaddr*)(void*)&from); *receivedFromNs < 0) {
Luke Huangbff43fc2019-11-12 15:54:47 +0800963 // response from wrong server? ignore it.
964 LOG(DEBUG) << __func__ << ": not our server:";
965 return true;
966 }
967 if (!res_queriesmatch(buf, buf + buflen, ans, ans + anssiz)) {
968 // response contains wrong query? ignore it.
969 LOG(DEBUG) << __func__ << ": wrong query name:";
970 return true;
971 }
972 return false;
973}
974
chenbrucec51f1212019-09-12 16:59:33 +0800975static int send_dg(res_state statp, res_params* params, const uint8_t* buf, int buflen,
Luke Huang3caa42b2020-04-23 14:18:04 +0000976 uint8_t* ans, int anssiz, int* terrno, size_t* ns, int* v_circuit,
Mike Yue48f7b52020-02-10 14:55:06 +0800977 int* gotsomewhere, time_t* at, int* rcode, int* delay) {
978 // It should never happen, but just in case.
Luke Huang3caa42b2020-04-23 14:18:04 +0000979 if (*ns >= statp->nsaddrs.size()) {
Mike Yue48f7b52020-02-10 14:55:06 +0800980 LOG(ERROR) << __func__ << ": Out-of-bound indexing: " << ns;
Luke Huang816b6a72020-05-15 07:53:52 +0000981 *terrno = EINVAL;
Mike Yue48f7b52020-02-10 14:55:06 +0800982 return -1;
983 }
984
Luke Huangbff43fc2019-11-12 15:54:47 +0800985 *at = time(nullptr);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900986 *delay = 0;
Luke Huang3caa42b2020-04-23 14:18:04 +0000987 const sockaddr_storage ss = statp->nsaddrs[*ns];
Mike Yue48f7b52020-02-10 14:55:06 +0800988 const sockaddr* nsap = reinterpret_cast<const sockaddr*>(&ss);
Luke Huangbff43fc2019-11-12 15:54:47 +0800989 const int nsaplen = sockaddrSize(nsap);
990
Luke Huang3caa42b2020-04-23 14:18:04 +0000991 if (statp->nssocks[*ns] == -1) {
992 statp->nssocks[*ns].reset(socket(nsap->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0));
993 if (statp->nssocks[*ns] < 0) {
Luke Huang816b6a72020-05-15 07:53:52 +0000994 *terrno = errno;
995 PLOG(DEBUG) << __func__ << ": socket(dg): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900996 switch (errno) {
997 case EPROTONOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900998 case EPFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900999 case EAFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001000 return (0);
1001 default:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001002 return (-1);
1003 }
1004 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001005
Luke Huang3caa42b2020-04-23 14:18:04 +00001006 resolv_tag_socket(statp->nssocks[*ns], statp->uid, statp->pid);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001007 if (statp->_mark != MARK_UNSET) {
Luke Huang3caa42b2020-04-23 14:18:04 +00001008 if (setsockopt(statp->nssocks[*ns], SOL_SOCKET, SO_MARK, &(statp->_mark),
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001009 sizeof(statp->_mark)) < 0) {
Luke Huang816b6a72020-05-15 07:53:52 +00001010 *terrno = errno;
Luke Huangadb0f5b2019-11-27 15:51:48 +08001011 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001012 return -1;
1013 }
1014 }
chenbruceb9cce7b2019-07-15 16:14:53 +08001015 // Use a "connected" datagram socket to receive an ECONNREFUSED error
1016 // on the next socket operation when the server responds with an
1017 // ICMP port-unreachable error. This way we can detect the absence of
1018 // a nameserver without timing out.
Luke Huang3caa42b2020-04-23 14:18:04 +00001019 if (random_bind(statp->nssocks[*ns], nsap->sa_family) < 0) {
Luke Huang816b6a72020-05-15 07:53:52 +00001020 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +08001021 dump_error("bind(dg)", nsap, nsaplen);
Luke Huangadb0f5b2019-11-27 15:51:48 +08001022 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001023 return (0);
1024 }
Luke Huang3caa42b2020-04-23 14:18:04 +00001025 if (connect(statp->nssocks[*ns], nsap, (socklen_t)nsaplen) < 0) {
Luke Huang816b6a72020-05-15 07:53:52 +00001026 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +08001027 dump_error("connect(dg)", nsap, nsaplen);
Luke Huangadb0f5b2019-11-27 15:51:48 +08001028 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001029 return (0);
1030 }
Ken Chenffc224a2019-03-19 17:41:28 +08001031 LOG(DEBUG) << __func__ << ": new DG socket";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001032 }
Luke Huang3caa42b2020-04-23 14:18:04 +00001033 if (send(statp->nssocks[*ns], (const char*)buf, (size_t)buflen, 0) != buflen) {
Luke Huang816b6a72020-05-15 07:53:52 +00001034 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +08001035 PLOG(DEBUG) << __func__ << ": send: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +08001036 statp->closeSockets();
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001037 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001038 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001039
Luke Huang3caa42b2020-04-23 14:18:04 +00001040 timespec timeout = get_timeout(statp, params, *ns);
1041 timespec start_time = evNowTime();
1042 timespec finish = evAddTime(start_time, timeout);
Luke Huangbff43fc2019-11-12 15:54:47 +08001043 for (;;) {
1044 // Wait for reply.
Luke Huang3caa42b2020-04-23 14:18:04 +00001045 auto result = udpRetryingPollWrapper(statp, *ns, &finish);
1046
1047 if (!result.has_value()) {
1048 const bool isTimeout = (result.error().code() == ETIMEDOUT);
1049 *rcode = (isTimeout) ? RCODE_TIMEOUT : *rcode;
Luke Huang816b6a72020-05-15 07:53:52 +00001050 *terrno = (isTimeout) ? ETIMEDOUT : errno;
Luke Huang3caa42b2020-04-23 14:18:04 +00001051 *gotsomewhere = (isTimeout) ? 1 : *gotsomewhere;
1052 // Leave the UDP sockets open on timeout so we can keep listening for
1053 // a late response from this server while retrying on the next server.
1054 if (!isTimeout) statp->closeSockets();
1055 LOG(DEBUG) << __func__ << ": " << (isTimeout) ? "timeout" : "poll";
1056 return 0;
1057 }
1058 bool needRetry = false;
1059 for (int fd : result.value()) {
1060 needRetry = false;
1061 sockaddr_storage from;
1062 socklen_t fromlen = sizeof(from);
1063 int resplen =
1064 recvfrom(fd, (char*)ans, (size_t)anssiz, 0, (sockaddr*)(void*)&from, &fromlen);
1065 if (resplen <= 0) {
Luke Huang816b6a72020-05-15 07:53:52 +00001066 *terrno = errno;
Luke Huang3caa42b2020-04-23 14:18:04 +00001067 PLOG(DEBUG) << __func__ << ": recvfrom: ";
1068 continue;
1069 }
Luke Huangbff43fc2019-11-12 15:54:47 +08001070 *gotsomewhere = 1;
Luke Huang3caa42b2020-04-23 14:18:04 +00001071 if (resplen < HFIXEDSZ) {
1072 // Undersized message.
1073 LOG(DEBUG) << __func__ << ": undersized: " << resplen;
1074 *terrno = EMSGSIZE;
1075 continue;
1076 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001077
Luke Huang3caa42b2020-04-23 14:18:04 +00001078 int receivedFromNs = *ns;
1079 if (needRetry =
1080 ignoreInvalidAnswer(statp, from, buf, buflen, ans, anssiz, &receivedFromNs);
1081 needRetry) {
1082 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
1083 continue;
1084 }
Luke Huangbff43fc2019-11-12 15:54:47 +08001085
Luke Huang3caa42b2020-04-23 14:18:04 +00001086 HEADER* anhp = (HEADER*)(void*)ans;
1087 if (anhp->rcode == FORMERR && (statp->netcontext_flags & NET_CONTEXT_FLAG_USE_EDNS)) {
1088 // Do not retry if the server do not understand EDNS0.
1089 // The case has to be captured here, as FORMERR packet do not
1090 // carry query section, hence res_queriesmatch() returns 0.
1091 LOG(DEBUG) << __func__ << ": server rejected query with EDNS0:";
1092 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
1093 // record the error
1094 statp->_flags |= RES_F_EDNS0ERR;
Luke Huang816b6a72020-05-15 07:53:52 +00001095 *terrno = EREMOTEIO;
Luke Huang3caa42b2020-04-23 14:18:04 +00001096 continue;
1097 }
Luke Huangbff43fc2019-11-12 15:54:47 +08001098
Luke Huang3caa42b2020-04-23 14:18:04 +00001099 timespec done = evNowTime();
1100 *delay = res_stats_calculate_rtt(&done, &start_time);
1101 if (anhp->rcode == SERVFAIL || anhp->rcode == NOTIMP || anhp->rcode == REFUSED) {
1102 LOG(DEBUG) << __func__ << ": server rejected query:";
1103 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
1104 *rcode = anhp->rcode;
1105 continue;
1106 }
1107 if (anhp->tc) {
1108 // To get the rest of answer,
1109 // use TCP with same server.
1110 LOG(DEBUG) << __func__ << ": truncated answer";
Luke Huang816b6a72020-05-15 07:53:52 +00001111 *terrno = E2BIG;
Luke Huang3caa42b2020-04-23 14:18:04 +00001112 *v_circuit = 1;
1113 return 1;
1114 }
1115 // All is well, or the error is fatal. Signal that the
1116 // next nameserver ought not be tried.
Luke Huangbff43fc2019-11-12 15:54:47 +08001117
Luke Huangbff43fc2019-11-12 15:54:47 +08001118 *rcode = anhp->rcode;
Luke Huang3caa42b2020-04-23 14:18:04 +00001119 *ns = receivedFromNs;
Luke Huang816b6a72020-05-15 07:53:52 +00001120 *terrno = 0;
Luke Huang3caa42b2020-04-23 14:18:04 +00001121 return resplen;
Luke Huangbff43fc2019-11-12 15:54:47 +08001122 }
Luke Huang3caa42b2020-04-23 14:18:04 +00001123 if (!needRetry) return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001124 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001125}
1126
chenbruce018fdb22019-06-12 18:08:04 +08001127static void dump_error(const char* str, const struct sockaddr* address, int alen) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001128 char hbuf[NI_MAXHOST];
1129 char sbuf[NI_MAXSERV];
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001130 constexpr int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
Luke Huangc98fd802019-10-15 16:36:36 +09001131 const int err = errno;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001132
chenbruce018fdb22019-06-12 18:08:04 +08001133 if (!WOULD_LOG(DEBUG)) return;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001134
chenbruce018fdb22019-06-12 18:08:04 +08001135 if (getnameinfo(address, (socklen_t)alen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf), niflags)) {
1136 strncpy(hbuf, "?", sizeof(hbuf) - 1);
1137 hbuf[sizeof(hbuf) - 1] = '\0';
1138 strncpy(sbuf, "?", sizeof(sbuf) - 1);
1139 sbuf[sizeof(sbuf) - 1] = '\0';
Elliott Hughes3b8f5902019-03-08 12:02:55 -08001140 }
Luke Huangc98fd802019-10-15 16:36:36 +09001141 errno = err;
chenbruce018fdb22019-06-12 18:08:04 +08001142 PLOG(DEBUG) << __func__ << ": " << str << " ([" << hbuf << "]." << sbuf << "): ";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001143}
1144
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001145static int sock_eq(struct sockaddr* a, struct sockaddr* b) {
1146 struct sockaddr_in *a4, *b4;
1147 struct sockaddr_in6 *a6, *b6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001148
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001149 if (a->sa_family != b->sa_family) return 0;
1150 switch (a->sa_family) {
1151 case AF_INET:
1152 a4 = (struct sockaddr_in*) (void*) a;
1153 b4 = (struct sockaddr_in*) (void*) b;
1154 return a4->sin_port == b4->sin_port && a4->sin_addr.s_addr == b4->sin_addr.s_addr;
1155 case AF_INET6:
1156 a6 = (struct sockaddr_in6*) (void*) a;
1157 b6 = (struct sockaddr_in6*) (void*) b;
1158 return a6->sin6_port == b6->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001159#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001160 a6->sin6_scope_id == b6->sin6_scope_id &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001161#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001162 IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
1163 default:
1164 return 0;
1165 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001166}
Mike Yub601ff72018-11-01 20:07:00 +08001167
lifr6b83a6f2019-07-26 03:17:43 +08001168PrivateDnsModes convertEnumType(PrivateDnsMode privateDnsmode) {
1169 switch (privateDnsmode) {
1170 case PrivateDnsMode::OFF:
1171 return PrivateDnsModes::PDM_OFF;
1172 case PrivateDnsMode::OPPORTUNISTIC:
1173 return PrivateDnsModes::PDM_OPPORTUNISTIC;
1174 case PrivateDnsMode::STRICT:
1175 return PrivateDnsModes::PDM_STRICT;
Mike Yu99b8dc72019-11-22 17:45:31 +08001176 default:
1177 return PrivateDnsModes::PDM_UNKNOWN;
lifr6b83a6f2019-07-26 03:17:43 +08001178 }
lifr6b83a6f2019-07-26 03:17:43 +08001179}
1180
Luke Huangd7aa7b42018-11-21 20:37:50 +08001181static int res_tls_send(res_state statp, const Slice query, const Slice answer, int* rcode,
Mike Yubfb1b342018-11-06 15:42:36 +08001182 bool* fallback) {
1183 int resplen = 0;
Mike Yub601ff72018-11-01 20:07:00 +08001184 const unsigned netId = statp->netid;
Mike Yub601ff72018-11-01 20:07:00 +08001185
Mike Yubfb1b342018-11-06 15:42:36 +08001186 PrivateDnsStatus privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
lifr6b83a6f2019-07-26 03:17:43 +08001187 statp->event->set_private_dns_modes(convertEnumType(privateDnsStatus.mode));
Mike Yubfb1b342018-11-06 15:42:36 +08001188
1189 if (privateDnsStatus.mode == PrivateDnsMode::OFF) {
1190 *fallback = true;
1191 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001192 }
1193
Mike Yu3e829062019-08-07 14:01:14 +08001194 if (privateDnsStatus.validatedServers().empty()) {
Mike Yub601ff72018-11-01 20:07:00 +08001195 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
Mike Yubfb1b342018-11-06 15:42:36 +08001196 *fallback = true;
1197 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001198 } else {
1199 // Sleep and iterate some small number of times checking for the
1200 // arrival of resolved and validated server IP addresses, instead
1201 // of returning an immediate error.
Mike Yu4f3747b2018-12-02 17:54:29 +09001202 // This is needed because as soon as a network becomes the default network, apps will
1203 // send DNS queries on that network. If no servers have yet validated, and we do not
1204 // block those queries, they would immediately fail, causing application-visible errors.
1205 // Note that this can happen even before the network validates, since an unvalidated
1206 // network can become the default network if no validated networks are available.
1207 //
1208 // TODO: see if there is a better way to address this problem, such as buffering the
1209 // queries in a queue or only blocking queries for the first few seconds after a default
1210 // network change.
Mike Yubfb1b342018-11-06 15:42:36 +08001211 for (int i = 0; i < 42; i++) {
1212 std::this_thread::sleep_for(std::chrono::milliseconds(100));
Mike Yu3e829062019-08-07 14:01:14 +08001213 // Calling getStatus() to merely check if there's any validated server seems
1214 // wasteful. Consider adding a new method in PrivateDnsConfiguration for speed ups.
1215 if (!gPrivateDnsConfiguration.getStatus(netId).validatedServers().empty()) {
Mike Yubfb1b342018-11-06 15:42:36 +08001216 privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
1217 break;
1218 }
1219 }
Mike Yu3e829062019-08-07 14:01:14 +08001220 if (privateDnsStatus.validatedServers().empty()) {
Mike Yubfb1b342018-11-06 15:42:36 +08001221 return -1;
1222 }
Mike Yub601ff72018-11-01 20:07:00 +08001223 }
1224 }
1225
chenbruceacb832c2019-02-20 19:45:50 +08001226 LOG(INFO) << __func__ << ": performing query over TLS";
Mike Yub601ff72018-11-01 20:07:00 +08001227
Mike Yu3e829062019-08-07 14:01:14 +08001228 const auto response = sDnsTlsDispatcher.query(privateDnsStatus.validatedServers(), statp, query,
Mike Yubfb1b342018-11-06 15:42:36 +08001229 answer, &resplen);
Mike Yub601ff72018-11-01 20:07:00 +08001230
chenbruceacb832c2019-02-20 19:45:50 +08001231 LOG(INFO) << __func__ << ": TLS query result: " << static_cast<int>(response);
Mike Yub601ff72018-11-01 20:07:00 +08001232
1233 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
1234 // In opportunistic mode, handle falling back to cleartext in some
1235 // cases (DNS shouldn't fail if a validated opportunistic mode server
1236 // becomes unreachable for some reason).
1237 switch (response) {
Mike Yubfb1b342018-11-06 15:42:36 +08001238 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001239 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001240 return resplen;
Mike Yub601ff72018-11-01 20:07:00 +08001241 case DnsTlsTransport::Response::network_error:
Mike Yubfb1b342018-11-06 15:42:36 +08001242 // No need to set the error timeout here since it will fallback to UDP.
Mike Yub601ff72018-11-01 20:07:00 +08001243 case DnsTlsTransport::Response::internal_error:
1244 // Note: this will cause cleartext queries to be emitted, with
1245 // all of the EDNS0 goodness enabled. Fingers crossed. :-/
Mike Yubfb1b342018-11-06 15:42:36 +08001246 *fallback = true;
1247 [[fallthrough]];
Mike Yub601ff72018-11-01 20:07:00 +08001248 default:
Mike Yubfb1b342018-11-06 15:42:36 +08001249 return -1;
1250 }
1251 } else {
1252 // Strict mode
1253 switch (response) {
1254 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001255 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001256 return resplen;
1257 case DnsTlsTransport::Response::network_error:
1258 // This case happens when the query stored in DnsTlsTransport is expired since
1259 // either 1) the query has been tried for 3 times but no response or 2) fail to
1260 // establish the connection with the server.
Luke Huangd7aa7b42018-11-21 20:37:50 +08001261 *rcode = RCODE_TIMEOUT;
Mike Yubfb1b342018-11-06 15:42:36 +08001262 [[fallthrough]];
1263 default:
1264 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001265 }
1266 }
Mike Yub601ff72018-11-01 20:07:00 +08001267}
Luke Huang4973a0d2018-11-19 20:17:26 +08001268
Luke Huangba7bef92018-12-26 16:53:03 +08001269int resolv_res_nsend(const android_net_context* netContext, const uint8_t* msg, int msgLen,
lifr94981782019-05-17 21:15:19 +08001270 uint8_t* ans, int ansLen, int* rcode, uint32_t flags,
1271 NetworkDnsEventReported* event) {
1272 assert(event != nullptr);
Bernie Innocenti08487112019-10-11 21:14:13 +09001273 ResState res;
1274 res_init(&res, netContext, event);
Mike Yu021c3e12019-10-08 17:29:34 +08001275 resolv_populate_res_for_net(&res);
Luke Huang4973a0d2018-11-19 20:17:26 +08001276 *rcode = NOERROR;
Bernie Innocenti08487112019-10-11 21:14:13 +09001277 return res_nsend(&res, msg, msgLen, ans, ansLen, rcode, flags);
Bernie Innocentiec4219b2019-01-30 11:16:36 +09001278}