blob: 0938ea9f7f844835965906e9904f717e80d1959f [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
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090079#include <sys/param.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090080#include <sys/socket.h>
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090081#include <sys/time.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090082#include <sys/uio.h>
83
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090084#include <arpa/inet.h>
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090085#include <arpa/nameser.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090086
87#include <errno.h>
88#include <fcntl.h>
89#include <netdb.h>
90#include <poll.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090091#include <signal.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090092#include <stdlib.h>
93#include <string.h>
94#include <time.h>
95#include <unistd.h>
96
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +090097#include <android-base/logging.h>
Luke Huang3caa42b2020-04-23 14:18:04 +000098#include <android-base/result.h>
Bernie Innocenti758005f2019-02-19 18:08:36 +090099#include <android/multinetwork.h> // ResNsendFlags
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900100
Mike Yub601ff72018-11-01 20:07:00 +0800101#include <netdutils/Slice.h>
lifr94981782019-05-17 21:15:19 +0800102#include <netdutils/Stopwatch.h>
Bernie Innocentiec4219b2019-01-30 11:16:36 +0900103#include "DnsTlsDispatcher.h"
104#include "DnsTlsTransport.h"
Luke Huang68fa5002020-04-23 15:48:47 +0000105#include "Experiments.h"
Bernie Innocentiec4219b2019-01-30 11:16:36 +0900106#include "PrivateDnsConfiguration.h"
Bernie Innocentiac18b122018-10-01 23:10:18 +0900107#include "netd_resolv/resolv.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900108#include "private/android_filesystem_config.h"
Bernie Innocenti10a90282020-01-23 23:28:00 +0900109
110#include "res_comp.h"
Mike Yu34433c62019-08-20 20:17:36 +0800111#include "res_debug.h"
Bernie Innocenti08487112019-10-11 21:14:13 +0900112#include "res_init.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900113#include "resolv_cache.h"
Ken Chen99c0b322019-11-20 14:24:09 +0800114#include "stats.h"
lifr94981782019-05-17 21:15:19 +0800115#include "stats.pb.h"
Mike Yu021c3e12019-10-08 17:29:34 +0800116#include "util.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900117
Mike Yub601ff72018-11-01 20:07:00 +0800118// TODO: use the namespace something like android::netd_resolv for libnetd_resolv
Luke Huang3caa42b2020-04-23 14:18:04 +0000119using android::base::ErrnoError;
120using android::base::Result;
chenbruce99cbfd82019-09-05 15:08:13 +0800121using android::net::CacheStatus;
122using android::net::DnsQueryEvent;
123using android::net::DnsTlsDispatcher;
124using android::net::DnsTlsTransport;
125using android::net::gPrivateDnsConfiguration;
126using android::net::IpVersion;
127using android::net::IV_IPV4;
128using android::net::IV_IPV6;
129using android::net::IV_UNKNOWN;
lifr94981782019-05-17 21:15:19 +0800130using android::net::NetworkDnsEventReported;
chenbruce99cbfd82019-09-05 15:08:13 +0800131using android::net::NS_T_INVALID;
132using android::net::NsRcode;
133using android::net::NsType;
134using android::net::PrivateDnsMode;
135using android::net::PrivateDnsModes;
136using android::net::PrivateDnsStatus;
137using android::net::PROTO_TCP;
138using android::net::PROTO_UDP;
Mike Yue655b1d2019-08-28 17:49:59 +0800139using android::netdutils::IPSockAddr;
Bernie Innocentiec4219b2019-01-30 11:16:36 +0900140using android::netdutils::Slice;
lifr94981782019-05-17 21:15:19 +0800141using android::netdutils::Stopwatch;
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900142
Mike Yub601ff72018-11-01 20:07:00 +0800143static DnsTlsDispatcher sDnsTlsDispatcher;
144
Mike Yue48f7b52020-02-10 14:55:06 +0800145static int send_vc(res_state statp, res_params* params, const uint8_t* buf, int buflen,
146 uint8_t* ans, int anssiz, int* terrno, size_t ns, time_t* at, int* rcode,
147 int* delay);
148static int send_dg(res_state statp, res_params* params, const uint8_t* buf, int buflen,
Luke Huang3caa42b2020-04-23 14:18:04 +0000149 uint8_t* ans, int anssiz, int* terrno, size_t* ns, int* v_circuit,
Mike Yue48f7b52020-02-10 14:55:06 +0800150 int* gotsomewhere, time_t* at, int* rcode, int* delay);
151
chenbruce018fdb22019-06-12 18:08:04 +0800152static void dump_error(const char*, const struct sockaddr*, int);
chenbruceacb832c2019-02-20 19:45:50 +0800153
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900154static int sock_eq(struct sockaddr*, struct sockaddr*);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900155static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
156 const struct timespec timeout);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900157static int retrying_poll(const int sock, short events, const struct timespec* finish);
Luke Huangd7aa7b42018-11-21 20:37:50 +0800158static int res_tls_send(res_state, const Slice query, const Slice answer, int* rcode,
Mike Yubfb1b342018-11-06 15:42:36 +0800159 bool* fallback);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900160
lifr94981782019-05-17 21:15:19 +0800161NsType getQueryType(const uint8_t* msg, size_t msgLen) {
162 ns_msg handle;
163 ns_rr rr;
164 if (ns_initparse((const uint8_t*)msg, msgLen, &handle) < 0 ||
165 ns_parserr(&handle, ns_s_qd, 0, &rr) < 0) {
166 return NS_T_INVALID;
167 }
168 return static_cast<NsType>(ns_rr_type(rr));
169}
170
171IpVersion ipFamilyToIPVersion(const int ipFamily) {
172 switch (ipFamily) {
173 case AF_INET:
174 return IV_IPV4;
175 case AF_INET6:
176 return IV_IPV6;
177 default:
178 return IV_UNKNOWN;
179 }
180}
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900181
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900182// BEGIN: Code copied from ISC eventlib
183// TODO: move away from this code
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900184#define BILLION 1000000000
185
186static struct timespec evConsTime(time_t sec, long nsec) {
187 struct timespec x;
188
189 x.tv_sec = sec;
190 x.tv_nsec = nsec;
191 return (x);
192}
193
194static struct timespec evAddTime(struct timespec addend1, struct timespec addend2) {
195 struct timespec x;
196
197 x.tv_sec = addend1.tv_sec + addend2.tv_sec;
198 x.tv_nsec = addend1.tv_nsec + addend2.tv_nsec;
199 if (x.tv_nsec >= BILLION) {
200 x.tv_sec++;
201 x.tv_nsec -= BILLION;
202 }
203 return (x);
204}
205
206static struct timespec evSubTime(struct timespec minuend, struct timespec subtrahend) {
207 struct timespec x;
208
209 x.tv_sec = minuend.tv_sec - subtrahend.tv_sec;
210 if (minuend.tv_nsec >= subtrahend.tv_nsec)
211 x.tv_nsec = minuend.tv_nsec - subtrahend.tv_nsec;
212 else {
213 x.tv_nsec = BILLION - subtrahend.tv_nsec + minuend.tv_nsec;
214 x.tv_sec--;
215 }
216 return (x);
217}
218
219static int evCmpTime(struct timespec a, struct timespec b) {
220#define SGN(x) ((x) < 0 ? (-1) : (x) > 0 ? (1) : (0));
221 time_t s = a.tv_sec - b.tv_sec;
222 long n;
223
224 if (s != 0) return SGN(s);
225
226 n = a.tv_nsec - b.tv_nsec;
227 return SGN(n);
228}
229
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900230static struct timespec evNowTime(void) {
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900231 struct timespec tsnow;
Bernie Innocentic1834822018-08-31 16:11:41 +0900232 clock_gettime(CLOCK_REALTIME, &tsnow);
233 return tsnow;
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900234}
235
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900236// END: Code copied from ISC eventlib
237
lifr94981782019-05-17 21:15:19 +0800238/* BIONIC-BEGIN: implement source port randomization */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900239static int random_bind(int s, int family) {
nuccachenb980f2f2018-10-23 17:10:58 +0800240 sockaddr_union u;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900241 int j;
242 socklen_t slen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900243
244 /* clear all, this also sets the IP4/6 address to 'any' */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900245 memset(&u, 0, sizeof u);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900246
247 switch (family) {
248 case AF_INET:
249 u.sin.sin_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900250 slen = sizeof u.sin;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900251 break;
252 case AF_INET6:
253 u.sin6.sin6_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900254 slen = sizeof u.sin6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900255 break;
256 default:
257 errno = EPROTO;
258 return -1;
259 }
260
261 /* first try to bind to a random source port a few times */
262 for (j = 0; j < 10; j++) {
263 /* find a random port between 1025 .. 65534 */
Luke Huangdda920f2019-02-13 14:05:02 +0800264 int port = 1025 + (arc4random_uniform(65535 - 1025));
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900265 if (family == AF_INET)
266 u.sin.sin_port = htons(port);
267 else
268 u.sin6.sin6_port = htons(port);
269
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900270 if (!bind(s, &u.sa, slen)) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900271 }
272
Bernie Innocenti9c575932018-09-07 21:10:25 +0900273 // nothing after 10 attempts, our network table is probably busy
274 // let the system decide which port is best
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900275 if (family == AF_INET)
276 u.sin.sin_port = 0;
277 else
278 u.sin6.sin6_port = 0;
279
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900280 return bind(s, &u.sa, slen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900281}
282/* BIONIC-END */
283
Luke Huang70931aa2019-01-31 11:57:41 +0800284// Disables all nameservers other than selectedServer
285static void res_set_usable_server(int selectedServer, int nscount, bool usable_servers[]) {
286 int usableIndex = 0;
287 for (int ns = 0; ns < nscount; ns++) {
288 if (usable_servers[ns]) ++usableIndex;
289 if (usableIndex != selectedServer) usable_servers[ns] = false;
290 }
291}
292
Luke Huang3caa42b2020-04-23 14:18:04 +0000293// Looks up the nameserver address in res.nsaddrs[], returns the ns number if found, otherwise -1.
294static int res_ourserver_p(res_state statp, const sockaddr* sa) {
Bernie Innocenti2e8540b2018-09-26 11:52:04 +0900295 const sockaddr_in *inp, *srv;
296 const sockaddr_in6 *in6p, *srv6;
Luke Huang3caa42b2020-04-23 14:18:04 +0000297 int ns = 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900298 switch (sa->sa_family) {
299 case AF_INET:
300 inp = (const struct sockaddr_in*) (const void*) sa;
Luke Huang3caa42b2020-04-23 14:18:04 +0000301
Mike Yue48f7b52020-02-10 14:55:06 +0800302 for (const IPSockAddr& ipsa : statp->nsaddrs) {
303 sockaddr_storage ss = ipsa;
304 srv = reinterpret_cast<sockaddr_in*>(&ss);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900305 if (srv->sin_family == inp->sin_family && srv->sin_port == inp->sin_port &&
306 (srv->sin_addr.s_addr == INADDR_ANY ||
307 srv->sin_addr.s_addr == inp->sin_addr.s_addr))
Luke Huang3caa42b2020-04-23 14:18:04 +0000308 return ns;
309 ++ns;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900310 }
311 break;
312 case AF_INET6:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900313 in6p = (const struct sockaddr_in6*) (const void*) sa;
Mike Yue48f7b52020-02-10 14:55:06 +0800314 for (const IPSockAddr& ipsa : statp->nsaddrs) {
315 sockaddr_storage ss = ipsa;
316 srv6 = reinterpret_cast<sockaddr_in6*>(&ss);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900317 if (srv6->sin6_family == in6p->sin6_family && srv6->sin6_port == in6p->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900318#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900319 (srv6->sin6_scope_id == 0 || srv6->sin6_scope_id == in6p->sin6_scope_id) &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900320#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900321 (IN6_IS_ADDR_UNSPECIFIED(&srv6->sin6_addr) ||
322 IN6_ARE_ADDR_EQUAL(&srv6->sin6_addr, &in6p->sin6_addr)))
Luke Huang3caa42b2020-04-23 14:18:04 +0000323 return ns;
324 ++ns;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900325 }
326 break;
327 default:
328 break;
329 }
Luke Huang3caa42b2020-04-23 14:18:04 +0000330 return -1;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900331}
332
333/* int
Bernie Innocenti9c575932018-09-07 21:10:25 +0900334 * res_nameinquery(name, type, cl, buf, eom)
335 * look for (name, type, cl) in the query section of packet (buf, eom)
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900336 * requires:
337 * buf + HFIXEDSZ <= eom
338 * returns:
339 * -1 : format error
340 * 0 : not found
341 * >0 : found
342 * author:
343 * paul vixie, 29may94
344 */
chenbrucec51f1212019-09-12 16:59:33 +0800345int res_nameinquery(const char* name, int type, int cl, const uint8_t* buf, const uint8_t* eom) {
346 const uint8_t* cp = buf + HFIXEDSZ;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900347 int qdcount = ntohs(((const HEADER*) (const void*) buf)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900348
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900349 while (qdcount-- > 0) {
350 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900351 int n = dn_expand(buf, eom, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900352 if (n < 0) return (-1);
353 cp += n;
354 if (cp + 2 * INT16SZ > eom) return (-1);
chenbruce0d470422019-03-28 18:44:37 +0800355 int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900356 cp += INT16SZ;
chenbruce0d470422019-03-28 18:44:37 +0800357 int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900358 cp += INT16SZ;
Bernie Innocenti9c575932018-09-07 21:10:25 +0900359 if (ttype == type && tclass == cl && ns_samename(tname, name) == 1) return (1);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900360 }
361 return (0);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900362}
363
364/* int
365 * res_queriesmatch(buf1, eom1, buf2, eom2)
366 * is there a 1:1 mapping of (name,type,class)
367 * in (buf1,eom1) and (buf2,eom2)?
368 * returns:
369 * -1 : format error
370 * 0 : not a 1:1 mapping
371 * >0 : is a 1:1 mapping
372 * author:
373 * paul vixie, 29may94
374 */
chenbrucec51f1212019-09-12 16:59:33 +0800375int res_queriesmatch(const uint8_t* buf1, const uint8_t* eom1, const uint8_t* buf2,
376 const uint8_t* eom2) {
377 const uint8_t* cp = buf1 + HFIXEDSZ;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900378 int qdcount = ntohs(((const HEADER*) (const void*) buf1)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900379
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900380 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2) return (-1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900381
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900382 /*
383 * Only header section present in replies to
384 * dynamic update packets.
385 */
386 if ((((const HEADER*) (const void*) buf1)->opcode == ns_o_update) &&
387 (((const HEADER*) (const void*) buf2)->opcode == ns_o_update))
388 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900389
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900390 if (qdcount != ntohs(((const HEADER*) (const void*) buf2)->qdcount)) return (0);
391 while (qdcount-- > 0) {
392 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900393 int n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900394 if (n < 0) return (-1);
395 cp += n;
396 if (cp + 2 * INT16SZ > eom1) return (-1);
chenbruce0d470422019-03-28 18:44:37 +0800397 int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900398 cp += INT16SZ;
chenbruce0d470422019-03-28 18:44:37 +0800399 int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900400 cp += INT16SZ;
401 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2)) return (0);
402 }
403 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900404}
405
lifr94981782019-05-17 21:15:19 +0800406static DnsQueryEvent* addDnsQueryEvent(NetworkDnsEventReported* event) {
407 return event->mutable_dns_query_events()->add_dns_query_event();
408}
409
chenbrucec51f1212019-09-12 16:59:33 +0800410int res_nsend(res_state statp, const uint8_t* buf, int buflen, uint8_t* ans, int anssiz, int* rcode,
Luke Huangba7bef92018-12-26 16:53:03 +0800411 uint32_t flags) {
Luke Huang43cc1b12019-10-15 19:06:42 +0900412 LOG(DEBUG) << __func__;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900413
Luke Huang43cc1b12019-10-15 19:06:42 +0900414 // Should not happen
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900415 if (anssiz < HFIXEDSZ) {
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800416 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900417 errno = EINVAL;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800418 return -EINVAL;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900419 }
chenbrucedd210722019-03-06 13:52:43 +0800420 res_pquery(buf, buflen);
chenbruceacb832c2019-02-20 19:45:50 +0800421
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900422 int anslen = 0;
lifrd4d9fbb2019-07-31 20:18:35 +0800423 Stopwatch cacheStopwatch;
Luke Huang43cc1b12019-10-15 19:06:42 +0900424 ResolvCacheStatus cache_status =
425 resolv_cache_lookup(statp->netid, buf, buflen, ans, anssiz, &anslen, flags);
lifrd4d9fbb2019-07-31 20:18:35 +0800426 const int32_t cacheLatencyUs = saturate_cast<int32_t>(cacheStopwatch.timeTakenUs());
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900427 if (cache_status == RESOLV_CACHE_FOUND) {
Luke Huang83c9b4b2019-02-27 18:18:01 +0800428 HEADER* hp = (HEADER*)(void*)ans;
429 *rcode = hp->rcode;
lifr94981782019-05-17 21:15:19 +0800430 DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
431 dnsQueryEvent->set_latency_micros(cacheLatencyUs);
432 dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
lifre02d01c2019-12-31 17:24:57 +0800433 dnsQueryEvent->set_type(getQueryType(buf, buflen));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900434 return anslen;
435 } else if (cache_status != RESOLV_CACHE_UNSUPPORTED) {
436 // had a cache miss for a known network, so populate the thread private
437 // data so the normal resolve path can do its thing
Mike Yu021c3e12019-10-08 17:29:34 +0800438 resolv_populate_res_for_net(statp);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900439 }
Mike Yuecc52822020-02-14 14:36:46 +0800440 if (statp->nameserverCount() == 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900441 // We have no nameservers configured, so there's no point trying.
442 // Tell the cache the query failed, or any retries and anyone else asking the same
443 // question will block for PENDING_REQUEST_TIMEOUT seconds instead of failing fast.
Luke Huangba7bef92018-12-26 16:53:03 +0800444 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800445
446 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900447 errno = ESRCH;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800448 return -ESRCH;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900449 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900450
Luke Huang272cb192019-10-15 16:52:28 +0900451 // DoT
452 if (!(statp->netcontext_flags & NET_CONTEXT_FLAG_USE_LOCAL_NAMESERVERS)) {
453 bool fallback = false;
Luke Huang43cc1b12019-10-15 19:06:42 +0900454 int resplen = res_tls_send(statp, Slice(const_cast<uint8_t*>(buf), buflen),
455 Slice(ans, anssiz), rcode, &fallback);
Luke Huang272cb192019-10-15 16:52:28 +0900456 if (resplen > 0) {
457 LOG(DEBUG) << __func__ << ": got answer from DoT";
458 res_pquery(ans, resplen);
459 if (cache_status == RESOLV_CACHE_NOTFOUND) {
460 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
461 }
462 return resplen;
463 }
464 if (!fallback) {
465 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huang43cc1b12019-10-15 19:06:42 +0900466 return -ETIMEDOUT;
Luke Huang272cb192019-10-15 16:52:28 +0900467 }
468 }
469
Mike Yuc573a3d2020-02-07 20:15:15 +0800470 res_stats stats[MAXNS]{};
Bernie Innocenti758005f2019-02-19 18:08:36 +0900471 res_params params;
Mike Yuc573a3d2020-02-07 20:15:15 +0800472 int revision_id = resolv_cache_get_resolver_stats(statp->netid, &params, stats, statp->nsaddrs);
lifra1b37f12019-02-13 17:33:57 +0800473 if (revision_id < 0) {
474 // TODO: Remove errno once callers stop using it
475 errno = ESRCH;
476 return -ESRCH;
477 }
waynema0161acd2019-02-18 17:47:59 +0800478 bool usable_servers[MAXNS];
Luke Huang70931aa2019-01-31 11:57:41 +0800479 int usableServersCount = android_net_res_stats_get_usable_servers(
Mike Yuecc52822020-02-14 14:36:46 +0800480 &params, stats, statp->nameserverCount(), usable_servers);
Luke Huang70931aa2019-01-31 11:57:41 +0800481
482 if ((flags & ANDROID_RESOLV_NO_RETRY) && usableServersCount > 1) {
483 auto hp = reinterpret_cast<const HEADER*>(buf);
484
485 // Select a random server based on the query id
486 int selectedServer = (hp->id % usableServersCount) + 1;
Mike Yuecc52822020-02-14 14:36:46 +0800487 res_set_usable_server(selectedServer, statp->nameserverCount(), usable_servers);
Luke Huang70931aa2019-01-31 11:57:41 +0800488 }
waynema0161acd2019-02-18 17:47:59 +0800489
Luke Huang43cc1b12019-10-15 19:06:42 +0900490 // Send request, RETRY times, or until successful.
waynemaa74195e2019-01-18 14:02:31 +0800491 int retryTimes = (flags & ANDROID_RESOLV_NO_RETRY) ? 1 : params.retry_count;
Luke Huang43cc1b12019-10-15 19:06:42 +0900492 int useTcp = buflen > PACKETSZ;
493 int gotsomewhere = 0;
494 int terrno = ETIMEDOUT;
Luke Huangba7bef92018-12-26 16:53:03 +0800495
496 for (int attempt = 0; attempt < retryTimes; ++attempt) {
Mike Yue48f7b52020-02-10 14:55:06 +0800497 for (size_t ns = 0; ns < statp->nsaddrs.size(); ++ns) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900498 if (!usable_servers[ns]) continue;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900499
Luke Huang43cc1b12019-10-15 19:06:42 +0900500 *rcode = RCODE_INTERNAL_ERROR;
501
502 // Get server addr
Mike Yue48f7b52020-02-10 14:55:06 +0800503 const IPSockAddr& serverSockAddr = statp->nsaddrs[ns];
504 LOG(DEBUG) << __func__ << ": Querying server (# " << ns + 1
505 << ") address = " << serverSockAddr.toString();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900506
Luke Huang43cc1b12019-10-15 19:06:42 +0900507 ::android::net::Protocol query_proto = useTcp ? PROTO_TCP : PROTO_UDP;
Luke Huang3caa42b2020-04-23 14:18:04 +0000508 time_t query_time = 0;
Luke Huang43cc1b12019-10-15 19:06:42 +0900509 int delay = 0;
510 bool fallbackTCP = false;
511 const bool shouldRecordStats = (attempt == 0);
512 int resplen;
lifrd4d9fbb2019-07-31 20:18:35 +0800513 Stopwatch queryStopwatch;
lifr128183a2020-01-08 18:04:50 +0800514 int retry_count_for_event = 0;
Luke Huang3caa42b2020-04-23 14:18:04 +0000515 size_t actualNs = ns;
Luke Huang43cc1b12019-10-15 19:06:42 +0900516 if (useTcp) {
517 // TCP; at most one attempt per server.
Luke Huangba7bef92018-12-26 16:53:03 +0800518 attempt = retryTimes;
Luke Huang3caa42b2020-04-23 14:18:04 +0000519 resplen = send_vc(statp, &params, buf, buflen, ans, anssiz, &terrno, ns,
520 &query_time, rcode, &delay);
Ken Chen99344882020-01-01 14:59:38 +0800521
522 if (buflen <= PACKETSZ && resplen <= 0 &&
523 statp->tc_mode == aidl::android::net::IDnsResolver::TC_MODE_UDP_TCP) {
524 // reset to UDP for next query on next DNS server if resolver is currently doing
525 // TCP fallback retry and current server does not support TCP connectin
526 useTcp = false;
527 }
528 LOG(INFO) << __func__ << ": used send_vc " << resplen;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900529 } else {
Luke Huang43cc1b12019-10-15 19:06:42 +0900530 // UDP
Luke Huang3caa42b2020-04-23 14:18:04 +0000531 resplen = send_dg(statp, &params, buf, buflen, ans, anssiz, &terrno, &actualNs,
532 &useTcp, &gotsomewhere, &query_time, rcode, &delay);
Luke Huang43cc1b12019-10-15 19:06:42 +0900533 fallbackTCP = useTcp ? true : false;
lifr128183a2020-01-08 18:04:50 +0800534 retry_count_for_event = attempt;
Ken Chen99344882020-01-01 14:59:38 +0800535 LOG(INFO) << __func__ << ": used send_dg " << resplen;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900536 }
Luke Huang43cc1b12019-10-15 19:06:42 +0900537
Luke Huang3caa42b2020-04-23 14:18:04 +0000538 const IPSockAddr& receivedServerAddr = statp->nsaddrs[actualNs];
Luke Huang43cc1b12019-10-15 19:06:42 +0900539 DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
540 dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
Luke Huang3caa42b2020-04-23 14:18:04 +0000541 // When |retryTimes| > 1, we cannot actually know the correct latency value if we
542 // received the answer from the previous server. So temporarily set the latency as -1 if
543 // that condition happened.
544 // TODO: make the latency value accurate.
545 dnsQueryEvent->set_latency_micros(
546 (actualNs == ns) ? saturate_cast<int32_t>(queryStopwatch.timeTakenUs()) : -1);
547 dnsQueryEvent->set_dns_server_index(actualNs);
548 dnsQueryEvent->set_ip_version(ipFamilyToIPVersion(receivedServerAddr.family()));
lifr128183a2020-01-08 18:04:50 +0800549 dnsQueryEvent->set_retry_times(retry_count_for_event);
Luke Huang43cc1b12019-10-15 19:06:42 +0900550 dnsQueryEvent->set_rcode(static_cast<NsRcode>(*rcode));
551 dnsQueryEvent->set_protocol(query_proto);
552 dnsQueryEvent->set_type(getQueryType(buf, buflen));
553
554 // Only record stats the first time we try a query. This ensures that
555 // queries that deterministically fail (e.g., a name that always returns
556 // SERVFAIL or times out) do not unduly affect the stats.
557 if (shouldRecordStats) {
558 res_sample sample;
Luke Huang3caa42b2020-04-23 14:18:04 +0000559 res_stats_set_sample(&sample, query_time, *rcode, delay);
560 // KeepListening UDP mechanism is incompatible with usable_servers of legacy stats,
561 // so keep the old logic for now.
562 // TODO: Replace usable_servers of legacy stats with new one.
Mike Yue48f7b52020-02-10 14:55:06 +0800563 resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, serverSockAddr,
564 sample, params.max_samples);
Luke Huang3caa42b2020-04-23 14:18:04 +0000565 resolv_stats_add(statp->netid, receivedServerAddr, dnsQueryEvent);
Luke Huang43cc1b12019-10-15 19:06:42 +0900566 }
567
568 if (resplen == 0) continue;
569 if (fallbackTCP) {
570 ns--;
571 continue;
572 }
573 if (resplen < 0) {
574 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800575 statp->closeSockets();
Luke Huang43cc1b12019-10-15 19:06:42 +0900576 return -terrno;
577 };
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900578
Ken Chenffc224a2019-03-19 17:41:28 +0800579 LOG(DEBUG) << __func__ << ": got answer:";
chenbrucedd210722019-03-06 13:52:43 +0800580 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900581
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900582 if (cache_status == RESOLV_CACHE_NOTFOUND) {
Mike Yud1ec2542019-06-06 17:17:53 +0800583 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900584 }
Luke Huangadb0f5b2019-11-27 15:51:48 +0800585 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900586 return (resplen);
Bernie Innocenti9c575932018-09-07 21:10:25 +0900587 } // for each ns
588 } // for each retry
Luke Huangadb0f5b2019-11-27 15:51:48 +0800589 statp->closeSockets();
Luke Huang43cc1b12019-10-15 19:06:42 +0900590 terrno = useTcp ? terrno : gotsomewhere ? ETIMEDOUT : ECONNREFUSED;
591 // TODO: Remove errno once callers stop using it
592 errno = useTcp ? terrno
593 : gotsomewhere ? ETIMEDOUT /* no answer obtained */
594 : ECONNREFUSED /* no nameservers found */;
595
Luke Huangba7bef92018-12-26 16:53:03 +0800596 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800597 return -terrno;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900598}
599
chenbruce99cbfd82019-09-05 15:08:13 +0800600static struct timespec get_timeout(res_state statp, const res_params* params, const int ns) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900601 int msec;
waynemaa74195e2019-01-18 14:02:31 +0800602 // Legacy algorithm which scales the timeout by nameserver number.
603 // For instance, with 4 nameservers: 5s, 2.5s, 5s, 10s
604 // This has no effect with 1 or 2 nameservers
605 msec = params->base_timeout_msec << ns;
606 if (ns > 0) {
Mike Yuecc52822020-02-14 14:36:46 +0800607 msec /= statp->nameserverCount();
waynemaa74195e2019-01-18 14:02:31 +0800608 }
609 // For safety, don't allow OEMs and experiments to configure a timeout shorter than 1s.
610 if (msec < 1000) {
611 msec = 1000; // Use at least 1000ms
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900612 }
Ken Chenffc224a2019-03-19 17:41:28 +0800613 LOG(INFO) << __func__ << ": using timeout of " << msec << " msec";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900614
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900615 struct timespec result;
616 result.tv_sec = msec / 1000;
617 result.tv_nsec = (msec % 1000) * 1000000;
618 return result;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900619}
620
chenbrucec51f1212019-09-12 16:59:33 +0800621static int send_vc(res_state statp, res_params* params, const uint8_t* buf, int buflen,
Mike Yue48f7b52020-02-10 14:55:06 +0800622 uint8_t* ans, int anssiz, int* terrno, size_t ns, time_t* at, int* rcode,
chenbrucec51f1212019-09-12 16:59:33 +0800623 int* delay) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900624 *at = time(NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900625 *delay = 0;
626 const HEADER* hp = (const HEADER*) (const void*) buf;
627 HEADER* anhp = (HEADER*) (void*) ans;
628 struct sockaddr* nsap;
629 int nsaplen;
chenbruce0d470422019-03-28 18:44:37 +0800630 int truncating, connreset, n;
chenbrucec51f1212019-09-12 16:59:33 +0800631 uint8_t* cp;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900632
Ken Chenffc224a2019-03-19 17:41:28 +0800633 LOG(INFO) << __func__ << ": using send_vc";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900634
Mike Yue48f7b52020-02-10 14:55:06 +0800635 // It should never happen, but just in case.
636 if (ns >= statp->nsaddrs.size()) {
637 LOG(ERROR) << __func__ << ": Out-of-bound indexing: " << ns;
638 return -1;
639 }
640
641 sockaddr_storage ss = statp->nsaddrs[ns];
642 nsap = reinterpret_cast<sockaddr*>(&ss);
Mike Yu021c3e12019-10-08 17:29:34 +0800643 nsaplen = sockaddrSize(nsap);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900644
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900645 connreset = 0;
646same_ns:
647 truncating = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900648
Luke Huang3caa42b2020-04-23 14:18:04 +0000649 struct timespec start_time = evNowTime();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900650
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900651 /* Are we still talking to whom we want to talk to? */
Luke Huangadb0f5b2019-11-27 15:51:48 +0800652 if (statp->tcp_nssock >= 0 && (statp->_flags & RES_F_VC) != 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900653 struct sockaddr_storage peer;
654 socklen_t size = sizeof peer;
655 unsigned old_mark;
656 socklen_t mark_size = sizeof(old_mark);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800657 if (getpeername(statp->tcp_nssock, (struct sockaddr*)(void*)&peer, &size) < 0 ||
658 !sock_eq((struct sockaddr*)(void*)&peer, nsap) ||
659 getsockopt(statp->tcp_nssock, SOL_SOCKET, SO_MARK, &old_mark, &mark_size) < 0 ||
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900660 old_mark != statp->_mark) {
Luke Huangadb0f5b2019-11-27 15:51:48 +0800661 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900662 }
663 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900664
Luke Huangadb0f5b2019-11-27 15:51:48 +0800665 if (statp->tcp_nssock < 0 || (statp->_flags & RES_F_VC) == 0) {
666 if (statp->tcp_nssock >= 0) statp->closeSockets();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900667
Luke Huangadb0f5b2019-11-27 15:51:48 +0800668 statp->tcp_nssock.reset(socket(nsap->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0));
669 if (statp->tcp_nssock < 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900670 switch (errno) {
671 case EPROTONOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900672 case EPFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900673 case EAFNOSUPPORT:
chenbruce018fdb22019-06-12 18:08:04 +0800674 PLOG(DEBUG) << __func__ << ": socket(vc): ";
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900675 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900676 default:
677 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800678 PLOG(DEBUG) << __func__ << ": socket(vc): ";
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900679 return -1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900680 }
681 }
Luke Huangadb0f5b2019-11-27 15:51:48 +0800682 resolv_tag_socket(statp->tcp_nssock, statp->uid, statp->pid);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900683 if (statp->_mark != MARK_UNSET) {
Luke Huangadb0f5b2019-11-27 15:51:48 +0800684 if (setsockopt(statp->tcp_nssock, SOL_SOCKET, SO_MARK, &statp->_mark,
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900685 sizeof(statp->_mark)) < 0) {
686 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800687 PLOG(DEBUG) << __func__ << ": setsockopt: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900688 return -1;
689 }
690 }
691 errno = 0;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800692 if (random_bind(statp->tcp_nssock, nsap->sa_family) < 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900693 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800694 dump_error("bind/vc", nsap, nsaplen);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800695 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900696 return (0);
697 }
Luke Huangadb0f5b2019-11-27 15:51:48 +0800698 if (connect_with_timeout(statp->tcp_nssock, nsap, (socklen_t)nsaplen,
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900699 get_timeout(statp, params, ns)) < 0) {
700 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800701 dump_error("connect/vc", nsap, nsaplen);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800702 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900703 /*
704 * The way connect_with_timeout() is implemented prevents us from reliably
705 * determining whether this was really a timeout or e.g. ECONNREFUSED. Since
706 * currently both cases are handled in the same way, there is no need to
707 * change this (yet). If we ever need to reliably distinguish between these
708 * cases, both connect_with_timeout() and retrying_poll() need to be
709 * modified, though.
710 */
711 *rcode = RCODE_TIMEOUT;
712 return (0);
713 }
714 statp->_flags |= RES_F_VC;
715 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900716
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900717 /*
718 * Send length & message
719 */
chenbruce0d470422019-03-28 18:44:37 +0800720 uint16_t len = htons(static_cast<uint16_t>(buflen));
Luke Huangc98fd802019-10-15 16:36:36 +0900721 const iovec iov[] = {
722 {.iov_base = &len, .iov_len = INT16SZ},
723 {.iov_base = const_cast<uint8_t*>(buf), .iov_len = static_cast<size_t>(buflen)},
724 };
Luke Huangadb0f5b2019-11-27 15:51:48 +0800725 if (writev(statp->tcp_nssock, iov, 2) != (INT16SZ + buflen)) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900726 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800727 PLOG(DEBUG) << __func__ << ": write failed: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800728 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900729 return (0);
730 }
731 /*
732 * Receive length & response
733 */
734read_len:
735 cp = ans;
736 len = INT16SZ;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800737 while ((n = read(statp->tcp_nssock, (char*)cp, (size_t)len)) > 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900738 cp += n;
739 if ((len -= n) == 0) break;
740 }
741 if (n <= 0) {
742 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800743 PLOG(DEBUG) << __func__ << ": read failed: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800744 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900745 /*
746 * A long running process might get its TCP
747 * connection reset if the remote server was
748 * restarted. Requery the server instead of
749 * trying a new one. When there is only one
750 * server, this means that a query might work
751 * instead of failing. We only allow one reset
752 * per query to prevent looping.
753 */
754 if (*terrno == ECONNRESET && !connreset) {
755 connreset = 1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900756 goto same_ns;
757 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900758 return (0);
759 }
chenbruce0d470422019-03-28 18:44:37 +0800760 uint16_t resplen = ntohs(*reinterpret_cast<const uint16_t*>(ans));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900761 if (resplen > anssiz) {
Ken Chenffc224a2019-03-19 17:41:28 +0800762 LOG(DEBUG) << __func__ << ": response truncated";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900763 truncating = 1;
764 len = anssiz;
765 } else
766 len = resplen;
767 if (len < HFIXEDSZ) {
768 /*
769 * Undersized message.
770 */
Ken Chenffc224a2019-03-19 17:41:28 +0800771 LOG(DEBUG) << __func__ << ": undersized: " << len;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900772 *terrno = EMSGSIZE;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800773 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900774 return (0);
775 }
776 cp = ans;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800777 while (len != 0 && (n = read(statp->tcp_nssock, (char*)cp, (size_t)len)) > 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900778 cp += n;
779 len -= n;
780 }
781 if (n <= 0) {
782 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800783 PLOG(DEBUG) << __func__ << ": read(vc): ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800784 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900785 return (0);
786 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900787
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900788 if (truncating) {
789 /*
790 * Flush rest of answer so connection stays in synch.
791 */
792 anhp->tc = 1;
793 len = resplen - anssiz;
794 while (len != 0) {
795 char junk[PACKETSZ];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900796
Luke Huangadb0f5b2019-11-27 15:51:48 +0800797 n = read(statp->tcp_nssock, junk, (len > sizeof junk) ? sizeof junk : len);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900798 if (n > 0)
799 len -= n;
800 else
801 break;
802 }
803 }
804 /*
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900805 * If the calling application has bailed out of
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900806 * a previous call and failed to arrange to have
807 * the circuit closed or the server has got
808 * itself confused, then drop the packet and
809 * wait for the correct one.
810 */
811 if (hp->id != anhp->id) {
Ken Chenffc224a2019-03-19 17:41:28 +0800812 LOG(DEBUG) << __func__ << ": ld answer (unexpected):";
chenbrucedd210722019-03-06 13:52:43 +0800813 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900814 goto read_len;
815 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900816
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900817 /*
818 * All is well, or the error is fatal. Signal that the
819 * next nameserver ought not be tried.
820 */
821 if (resplen > 0) {
822 struct timespec done = evNowTime();
Luke Huang3caa42b2020-04-23 14:18:04 +0000823 *delay = res_stats_calculate_rtt(&done, &start_time);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900824 *rcode = anhp->rcode;
825 }
826 return (resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900827}
828
829/* return -1 on error (errno set), 0 on success */
Luke Huangc98fd802019-10-15 16:36:36 +0900830static int connect_with_timeout(int sock, const sockaddr* nsap, socklen_t salen,
831 const timespec timeout) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900832 int res, origflags;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900833
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900834 origflags = fcntl(sock, F_GETFL, 0);
835 fcntl(sock, F_SETFL, origflags | O_NONBLOCK);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900836
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900837 res = connect(sock, nsap, salen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900838 if (res < 0 && errno != EINPROGRESS) {
839 res = -1;
840 goto done;
841 }
842 if (res != 0) {
Luke Huangc98fd802019-10-15 16:36:36 +0900843 timespec now = evNowTime();
844 timespec finish = evAddTime(now, timeout);
Ken Chenffc224a2019-03-19 17:41:28 +0800845 LOG(INFO) << __func__ << ": " << sock << " send_vc";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900846 res = retrying_poll(sock, POLLIN | POLLOUT, &finish);
847 if (res <= 0) {
848 res = -1;
849 }
850 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900851done:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900852 fcntl(sock, F_SETFL, origflags);
Ken Chenffc224a2019-03-19 17:41:28 +0800853 LOG(INFO) << __func__ << ": " << sock << " connect_with_const timeout returning " << res;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900854 return res;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900855}
856
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900857static int retrying_poll(const int sock, const short events, const struct timespec* finish) {
858 struct timespec now, timeout;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900859
860retry:
Ken Chenffc224a2019-03-19 17:41:28 +0800861 LOG(INFO) << __func__ << ": " << sock << " retrying_poll";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900862
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900863 now = evNowTime();
864 if (evCmpTime(*finish, now) > 0)
865 timeout = evSubTime(*finish, now);
866 else
867 timeout = evConsTime(0L, 0L);
868 struct pollfd fds = {.fd = sock, .events = events};
Treehugger Robotbcb51802020-04-24 03:57:49 +0000869 int n = ppoll(&fds, 1, &timeout, /*__mask=*/NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900870 if (n == 0) {
Luke Huang3caa42b2020-04-23 14:18:04 +0000871 LOG(INFO) << __func__ << ": " << sock << " retrying_poll timeout";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900872 errno = ETIMEDOUT;
873 return 0;
874 }
875 if (n < 0) {
876 if (errno == EINTR) goto retry;
Ken Chenffc224a2019-03-19 17:41:28 +0800877 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll failed";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900878 return n;
879 }
880 if (fds.revents & (POLLIN | POLLOUT | POLLERR)) {
881 int error;
882 socklen_t len = sizeof(error);
883 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error) {
884 errno = error;
Ken Chenffc224a2019-03-19 17:41:28 +0800885 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll getsockopt failed";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900886 return -1;
887 }
888 }
Ken Chenffc224a2019-03-19 17:41:28 +0800889 LOG(INFO) << __func__ << ": " << sock << " retrying_poll returning " << n;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900890 return n;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900891}
892
Luke Huang3caa42b2020-04-23 14:18:04 +0000893static std::vector<pollfd> extractUdpFdset(res_state statp, const short events = POLLIN) {
894 std::vector<pollfd> fdset(statp->nsaddrs.size());
895 for (size_t i = 0; i < statp->nsaddrs.size(); ++i) {
896 fdset[i] = {.fd = statp->nssocks[i], .events = events};
897 }
898 return fdset;
899}
900
901static Result<std::vector<int>> udpRetryingPoll(res_state statp, const timespec* finish) {
902 for (;;) {
903 LOG(DEBUG) << __func__ << ": poll";
904 timespec start_time = evNowTime();
905 timespec timeout = (evCmpTime(*finish, start_time) > 0) ? evSubTime(*finish, start_time)
906 : evConsTime(0L, 0L);
907 std::vector<pollfd> fdset = extractUdpFdset(statp);
Treehugger Robotbcb51802020-04-24 03:57:49 +0000908 const int n = ppoll(fdset.data(), fdset.size(), &timeout, /*__mask=*/nullptr);
Luke Huang3caa42b2020-04-23 14:18:04 +0000909 if (n <= 0) {
910 if (errno == EINTR && n < 0) continue;
911 if (n == 0) errno = ETIMEDOUT;
912 PLOG(INFO) << __func__ << ": failed";
913 return ErrnoError();
914 }
915 std::vector<int> fdsToRead;
916 for (const auto& pollfd : fdset) {
917 if (pollfd.revents & (POLLIN | POLLERR)) {
918 fdsToRead.push_back(pollfd.fd);
919 }
920 }
921 LOG(DEBUG) << __func__ << ": "
922 << " returning fd size: " << fdsToRead.size();
923 return fdsToRead;
924 }
925}
926
927static Result<std::vector<int>> udpRetryingPollWrapper(res_state statp, int ns,
928 const timespec* finish) {
Luke Huang68fa5002020-04-23 15:48:47 +0000929 const bool keepListeningUdp =
930 android::net::Experiments::getInstance()->getFlag("keep_listening_udp", 0);
Luke Huang3caa42b2020-04-23 14:18:04 +0000931 if (keepListeningUdp) return udpRetryingPoll(statp, finish);
932
933 if (int n = retrying_poll(statp->nssocks[ns], POLLIN, finish); n <= 0) {
934 return ErrnoError();
935 }
936 return std::vector<int>{statp->nssocks[ns]};
937}
938
Luke Huangbff43fc2019-11-12 15:54:47 +0800939bool ignoreInvalidAnswer(res_state statp, const sockaddr_storage& from, const uint8_t* buf,
Luke Huang3caa42b2020-04-23 14:18:04 +0000940 int buflen, uint8_t* ans, int anssiz, int* receivedFromNs) {
Luke Huangbff43fc2019-11-12 15:54:47 +0800941 const HEADER* hp = (const HEADER*)(const void*)buf;
942 HEADER* anhp = (HEADER*)(void*)ans;
943 if (hp->id != anhp->id) {
944 // response from old query, ignore it.
945 LOG(DEBUG) << __func__ << ": old answer:";
946 return true;
947 }
Luke Huang3caa42b2020-04-23 14:18:04 +0000948 if (*receivedFromNs = res_ourserver_p(statp, (sockaddr*)(void*)&from); *receivedFromNs < 0) {
Luke Huangbff43fc2019-11-12 15:54:47 +0800949 // response from wrong server? ignore it.
950 LOG(DEBUG) << __func__ << ": not our server:";
951 return true;
952 }
953 if (!res_queriesmatch(buf, buf + buflen, ans, ans + anssiz)) {
954 // response contains wrong query? ignore it.
955 LOG(DEBUG) << __func__ << ": wrong query name:";
956 return true;
957 }
958 return false;
959}
960
chenbrucec51f1212019-09-12 16:59:33 +0800961static int send_dg(res_state statp, res_params* params, const uint8_t* buf, int buflen,
Luke Huang3caa42b2020-04-23 14:18:04 +0000962 uint8_t* ans, int anssiz, int* terrno, size_t* ns, int* v_circuit,
Mike Yue48f7b52020-02-10 14:55:06 +0800963 int* gotsomewhere, time_t* at, int* rcode, int* delay) {
964 // It should never happen, but just in case.
Luke Huang3caa42b2020-04-23 14:18:04 +0000965 if (*ns >= statp->nsaddrs.size()) {
Mike Yue48f7b52020-02-10 14:55:06 +0800966 LOG(ERROR) << __func__ << ": Out-of-bound indexing: " << ns;
967 return -1;
968 }
969
Luke Huangbff43fc2019-11-12 15:54:47 +0800970 *at = time(nullptr);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900971 *delay = 0;
Luke Huang3caa42b2020-04-23 14:18:04 +0000972 const sockaddr_storage ss = statp->nsaddrs[*ns];
Mike Yue48f7b52020-02-10 14:55:06 +0800973 const sockaddr* nsap = reinterpret_cast<const sockaddr*>(&ss);
Luke Huangbff43fc2019-11-12 15:54:47 +0800974 const int nsaplen = sockaddrSize(nsap);
975
Luke Huang3caa42b2020-04-23 14:18:04 +0000976 if (statp->nssocks[*ns] == -1) {
977 statp->nssocks[*ns].reset(socket(nsap->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0));
978 if (statp->nssocks[*ns] < 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900979 switch (errno) {
980 case EPROTONOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900981 case EPFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900982 case EAFNOSUPPORT:
chenbruce018fdb22019-06-12 18:08:04 +0800983 PLOG(DEBUG) << __func__ << ": socket(dg): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900984 return (0);
985 default:
986 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800987 PLOG(DEBUG) << __func__ << ": socket(dg): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900988 return (-1);
989 }
990 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900991
Luke Huang3caa42b2020-04-23 14:18:04 +0000992 resolv_tag_socket(statp->nssocks[*ns], statp->uid, statp->pid);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900993 if (statp->_mark != MARK_UNSET) {
Luke Huang3caa42b2020-04-23 14:18:04 +0000994 if (setsockopt(statp->nssocks[*ns], SOL_SOCKET, SO_MARK, &(statp->_mark),
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900995 sizeof(statp->_mark)) < 0) {
Luke Huangadb0f5b2019-11-27 15:51:48 +0800996 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900997 return -1;
998 }
999 }
chenbruceb9cce7b2019-07-15 16:14:53 +08001000 // Use a "connected" datagram socket to receive an ECONNREFUSED error
1001 // on the next socket operation when the server responds with an
1002 // ICMP port-unreachable error. This way we can detect the absence of
1003 // a nameserver without timing out.
Luke Huang3caa42b2020-04-23 14:18:04 +00001004 if (random_bind(statp->nssocks[*ns], nsap->sa_family) < 0) {
chenbruce018fdb22019-06-12 18:08:04 +08001005 dump_error("bind(dg)", nsap, nsaplen);
Luke Huangadb0f5b2019-11-27 15:51:48 +08001006 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001007 return (0);
1008 }
Luke Huang3caa42b2020-04-23 14:18:04 +00001009 if (connect(statp->nssocks[*ns], nsap, (socklen_t)nsaplen) < 0) {
chenbruce018fdb22019-06-12 18:08:04 +08001010 dump_error("connect(dg)", nsap, nsaplen);
Luke Huangadb0f5b2019-11-27 15:51:48 +08001011 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001012 return (0);
1013 }
Ken Chenffc224a2019-03-19 17:41:28 +08001014 LOG(DEBUG) << __func__ << ": new DG socket";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001015 }
Luke Huang3caa42b2020-04-23 14:18:04 +00001016 if (send(statp->nssocks[*ns], (const char*)buf, (size_t)buflen, 0) != buflen) {
chenbruce018fdb22019-06-12 18:08:04 +08001017 PLOG(DEBUG) << __func__ << ": send: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +08001018 statp->closeSockets();
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001019 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001020 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001021
Luke Huang3caa42b2020-04-23 14:18:04 +00001022 timespec timeout = get_timeout(statp, params, *ns);
1023 timespec start_time = evNowTime();
1024 timespec finish = evAddTime(start_time, timeout);
Luke Huangbff43fc2019-11-12 15:54:47 +08001025 for (;;) {
1026 // Wait for reply.
Luke Huang3caa42b2020-04-23 14:18:04 +00001027 auto result = udpRetryingPollWrapper(statp, *ns, &finish);
1028
1029 if (!result.has_value()) {
1030 const bool isTimeout = (result.error().code() == ETIMEDOUT);
1031 *rcode = (isTimeout) ? RCODE_TIMEOUT : *rcode;
1032 *gotsomewhere = (isTimeout) ? 1 : *gotsomewhere;
1033 // Leave the UDP sockets open on timeout so we can keep listening for
1034 // a late response from this server while retrying on the next server.
1035 if (!isTimeout) statp->closeSockets();
1036 LOG(DEBUG) << __func__ << ": " << (isTimeout) ? "timeout" : "poll";
1037 return 0;
1038 }
1039 bool needRetry = false;
1040 for (int fd : result.value()) {
1041 needRetry = false;
1042 sockaddr_storage from;
1043 socklen_t fromlen = sizeof(from);
1044 int resplen =
1045 recvfrom(fd, (char*)ans, (size_t)anssiz, 0, (sockaddr*)(void*)&from, &fromlen);
1046 if (resplen <= 0) {
1047 PLOG(DEBUG) << __func__ << ": recvfrom: ";
1048 continue;
1049 }
Luke Huangbff43fc2019-11-12 15:54:47 +08001050 *gotsomewhere = 1;
Luke Huang3caa42b2020-04-23 14:18:04 +00001051 if (resplen < HFIXEDSZ) {
1052 // Undersized message.
1053 LOG(DEBUG) << __func__ << ": undersized: " << resplen;
1054 *terrno = EMSGSIZE;
1055 continue;
1056 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001057
Luke Huang3caa42b2020-04-23 14:18:04 +00001058 int receivedFromNs = *ns;
1059 if (needRetry =
1060 ignoreInvalidAnswer(statp, from, buf, buflen, ans, anssiz, &receivedFromNs);
1061 needRetry) {
1062 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
1063 continue;
1064 }
Luke Huangbff43fc2019-11-12 15:54:47 +08001065
Luke Huang3caa42b2020-04-23 14:18:04 +00001066 HEADER* anhp = (HEADER*)(void*)ans;
1067 if (anhp->rcode == FORMERR && (statp->netcontext_flags & NET_CONTEXT_FLAG_USE_EDNS)) {
1068 // Do not retry if the server do not understand EDNS0.
1069 // The case has to be captured here, as FORMERR packet do not
1070 // carry query section, hence res_queriesmatch() returns 0.
1071 LOG(DEBUG) << __func__ << ": server rejected query with EDNS0:";
1072 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
1073 // record the error
1074 statp->_flags |= RES_F_EDNS0ERR;
1075 continue;
1076 }
Luke Huangbff43fc2019-11-12 15:54:47 +08001077
Luke Huang3caa42b2020-04-23 14:18:04 +00001078 timespec done = evNowTime();
1079 *delay = res_stats_calculate_rtt(&done, &start_time);
1080 if (anhp->rcode == SERVFAIL || anhp->rcode == NOTIMP || anhp->rcode == REFUSED) {
1081 LOG(DEBUG) << __func__ << ": server rejected query:";
1082 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
1083 *rcode = anhp->rcode;
1084 continue;
1085 }
1086 if (anhp->tc) {
1087 // To get the rest of answer,
1088 // use TCP with same server.
1089 LOG(DEBUG) << __func__ << ": truncated answer";
1090 *v_circuit = 1;
1091 return 1;
1092 }
1093 // All is well, or the error is fatal. Signal that the
1094 // next nameserver ought not be tried.
Luke Huangbff43fc2019-11-12 15:54:47 +08001095
Luke Huangbff43fc2019-11-12 15:54:47 +08001096 *rcode = anhp->rcode;
Luke Huang3caa42b2020-04-23 14:18:04 +00001097 *ns = receivedFromNs;
1098 return resplen;
Luke Huangbff43fc2019-11-12 15:54:47 +08001099 }
Luke Huang3caa42b2020-04-23 14:18:04 +00001100 if (!needRetry) return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001101 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001102}
1103
chenbruce018fdb22019-06-12 18:08:04 +08001104static void dump_error(const char* str, const struct sockaddr* address, int alen) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001105 char hbuf[NI_MAXHOST];
1106 char sbuf[NI_MAXSERV];
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001107 constexpr int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
Luke Huangc98fd802019-10-15 16:36:36 +09001108 const int err = errno;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001109
chenbruce018fdb22019-06-12 18:08:04 +08001110 if (!WOULD_LOG(DEBUG)) return;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001111
chenbruce018fdb22019-06-12 18:08:04 +08001112 if (getnameinfo(address, (socklen_t)alen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf), niflags)) {
1113 strncpy(hbuf, "?", sizeof(hbuf) - 1);
1114 hbuf[sizeof(hbuf) - 1] = '\0';
1115 strncpy(sbuf, "?", sizeof(sbuf) - 1);
1116 sbuf[sizeof(sbuf) - 1] = '\0';
Elliott Hughes3b8f5902019-03-08 12:02:55 -08001117 }
Luke Huangc98fd802019-10-15 16:36:36 +09001118 errno = err;
chenbruce018fdb22019-06-12 18:08:04 +08001119 PLOG(DEBUG) << __func__ << ": " << str << " ([" << hbuf << "]." << sbuf << "): ";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001120}
1121
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001122static int sock_eq(struct sockaddr* a, struct sockaddr* b) {
1123 struct sockaddr_in *a4, *b4;
1124 struct sockaddr_in6 *a6, *b6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001125
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001126 if (a->sa_family != b->sa_family) return 0;
1127 switch (a->sa_family) {
1128 case AF_INET:
1129 a4 = (struct sockaddr_in*) (void*) a;
1130 b4 = (struct sockaddr_in*) (void*) b;
1131 return a4->sin_port == b4->sin_port && a4->sin_addr.s_addr == b4->sin_addr.s_addr;
1132 case AF_INET6:
1133 a6 = (struct sockaddr_in6*) (void*) a;
1134 b6 = (struct sockaddr_in6*) (void*) b;
1135 return a6->sin6_port == b6->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001136#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001137 a6->sin6_scope_id == b6->sin6_scope_id &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001138#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001139 IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
1140 default:
1141 return 0;
1142 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001143}
Mike Yub601ff72018-11-01 20:07:00 +08001144
lifr6b83a6f2019-07-26 03:17:43 +08001145PrivateDnsModes convertEnumType(PrivateDnsMode privateDnsmode) {
1146 switch (privateDnsmode) {
1147 case PrivateDnsMode::OFF:
1148 return PrivateDnsModes::PDM_OFF;
1149 case PrivateDnsMode::OPPORTUNISTIC:
1150 return PrivateDnsModes::PDM_OPPORTUNISTIC;
1151 case PrivateDnsMode::STRICT:
1152 return PrivateDnsModes::PDM_STRICT;
Mike Yu99b8dc72019-11-22 17:45:31 +08001153 default:
1154 return PrivateDnsModes::PDM_UNKNOWN;
lifr6b83a6f2019-07-26 03:17:43 +08001155 }
lifr6b83a6f2019-07-26 03:17:43 +08001156}
1157
Luke Huangd7aa7b42018-11-21 20:37:50 +08001158static int res_tls_send(res_state statp, const Slice query, const Slice answer, int* rcode,
Mike Yubfb1b342018-11-06 15:42:36 +08001159 bool* fallback) {
1160 int resplen = 0;
Mike Yub601ff72018-11-01 20:07:00 +08001161 const unsigned netId = statp->netid;
Mike Yub601ff72018-11-01 20:07:00 +08001162
Mike Yubfb1b342018-11-06 15:42:36 +08001163 PrivateDnsStatus privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
lifr6b83a6f2019-07-26 03:17:43 +08001164 statp->event->set_private_dns_modes(convertEnumType(privateDnsStatus.mode));
Mike Yubfb1b342018-11-06 15:42:36 +08001165
1166 if (privateDnsStatus.mode == PrivateDnsMode::OFF) {
1167 *fallback = true;
1168 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001169 }
1170
Mike Yu3e829062019-08-07 14:01:14 +08001171 if (privateDnsStatus.validatedServers().empty()) {
Mike Yub601ff72018-11-01 20:07:00 +08001172 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
Mike Yubfb1b342018-11-06 15:42:36 +08001173 *fallback = true;
1174 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001175 } else {
1176 // Sleep and iterate some small number of times checking for the
1177 // arrival of resolved and validated server IP addresses, instead
1178 // of returning an immediate error.
Mike Yu4f3747b2018-12-02 17:54:29 +09001179 // This is needed because as soon as a network becomes the default network, apps will
1180 // send DNS queries on that network. If no servers have yet validated, and we do not
1181 // block those queries, they would immediately fail, causing application-visible errors.
1182 // Note that this can happen even before the network validates, since an unvalidated
1183 // network can become the default network if no validated networks are available.
1184 //
1185 // TODO: see if there is a better way to address this problem, such as buffering the
1186 // queries in a queue or only blocking queries for the first few seconds after a default
1187 // network change.
Mike Yubfb1b342018-11-06 15:42:36 +08001188 for (int i = 0; i < 42; i++) {
1189 std::this_thread::sleep_for(std::chrono::milliseconds(100));
Mike Yu3e829062019-08-07 14:01:14 +08001190 // Calling getStatus() to merely check if there's any validated server seems
1191 // wasteful. Consider adding a new method in PrivateDnsConfiguration for speed ups.
1192 if (!gPrivateDnsConfiguration.getStatus(netId).validatedServers().empty()) {
Mike Yubfb1b342018-11-06 15:42:36 +08001193 privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
1194 break;
1195 }
1196 }
Mike Yu3e829062019-08-07 14:01:14 +08001197 if (privateDnsStatus.validatedServers().empty()) {
Mike Yubfb1b342018-11-06 15:42:36 +08001198 return -1;
1199 }
Mike Yub601ff72018-11-01 20:07:00 +08001200 }
1201 }
1202
chenbruceacb832c2019-02-20 19:45:50 +08001203 LOG(INFO) << __func__ << ": performing query over TLS";
Mike Yub601ff72018-11-01 20:07:00 +08001204
Mike Yu3e829062019-08-07 14:01:14 +08001205 const auto response = sDnsTlsDispatcher.query(privateDnsStatus.validatedServers(), statp, query,
Mike Yubfb1b342018-11-06 15:42:36 +08001206 answer, &resplen);
Mike Yub601ff72018-11-01 20:07:00 +08001207
chenbruceacb832c2019-02-20 19:45:50 +08001208 LOG(INFO) << __func__ << ": TLS query result: " << static_cast<int>(response);
Mike Yub601ff72018-11-01 20:07:00 +08001209
1210 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
1211 // In opportunistic mode, handle falling back to cleartext in some
1212 // cases (DNS shouldn't fail if a validated opportunistic mode server
1213 // becomes unreachable for some reason).
1214 switch (response) {
Mike Yubfb1b342018-11-06 15:42:36 +08001215 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001216 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001217 return resplen;
Mike Yub601ff72018-11-01 20:07:00 +08001218 case DnsTlsTransport::Response::network_error:
Mike Yubfb1b342018-11-06 15:42:36 +08001219 // No need to set the error timeout here since it will fallback to UDP.
Mike Yub601ff72018-11-01 20:07:00 +08001220 case DnsTlsTransport::Response::internal_error:
1221 // Note: this will cause cleartext queries to be emitted, with
1222 // all of the EDNS0 goodness enabled. Fingers crossed. :-/
Mike Yubfb1b342018-11-06 15:42:36 +08001223 *fallback = true;
1224 [[fallthrough]];
Mike Yub601ff72018-11-01 20:07:00 +08001225 default:
Mike Yubfb1b342018-11-06 15:42:36 +08001226 return -1;
1227 }
1228 } else {
1229 // Strict mode
1230 switch (response) {
1231 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001232 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001233 return resplen;
1234 case DnsTlsTransport::Response::network_error:
1235 // This case happens when the query stored in DnsTlsTransport is expired since
1236 // either 1) the query has been tried for 3 times but no response or 2) fail to
1237 // establish the connection with the server.
Luke Huangd7aa7b42018-11-21 20:37:50 +08001238 *rcode = RCODE_TIMEOUT;
Mike Yubfb1b342018-11-06 15:42:36 +08001239 [[fallthrough]];
1240 default:
1241 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001242 }
1243 }
Mike Yub601ff72018-11-01 20:07:00 +08001244}
Luke Huang4973a0d2018-11-19 20:17:26 +08001245
Luke Huangba7bef92018-12-26 16:53:03 +08001246int resolv_res_nsend(const android_net_context* netContext, const uint8_t* msg, int msgLen,
lifr94981782019-05-17 21:15:19 +08001247 uint8_t* ans, int ansLen, int* rcode, uint32_t flags,
1248 NetworkDnsEventReported* event) {
1249 assert(event != nullptr);
Bernie Innocenti08487112019-10-11 21:14:13 +09001250 ResState res;
1251 res_init(&res, netContext, event);
Mike Yu021c3e12019-10-08 17:29:34 +08001252 resolv_populate_res_for_net(&res);
Luke Huang4973a0d2018-11-19 20:17:26 +08001253 *rcode = NOERROR;
Bernie Innocenti08487112019-10-11 21:14:13 +09001254 return res_nsend(&res, msg, msgLen, ans, ansLen, rcode, flags);
Bernie Innocentiec4219b2019-01-30 11:16:36 +09001255}