blob: beb7f13a5ebe8e9c842e953164ac3b01a30206e8 [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"
105#include "PrivateDnsConfiguration.h"
Bernie Innocentiac18b122018-10-01 23:10:18 +0900106#include "netd_resolv/resolv.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900107#include "private/android_filesystem_config.h"
Bernie Innocenti10a90282020-01-23 23:28:00 +0900108
109#include "res_comp.h"
Mike Yu34433c62019-08-20 20:17:36 +0800110#include "res_debug.h"
Bernie Innocenti08487112019-10-11 21:14:13 +0900111#include "res_init.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900112#include "resolv_cache.h"
Ken Chen99c0b322019-11-20 14:24:09 +0800113#include "stats.h"
lifr94981782019-05-17 21:15:19 +0800114#include "stats.pb.h"
Mike Yu021c3e12019-10-08 17:29:34 +0800115#include "util.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900116
Mike Yub601ff72018-11-01 20:07:00 +0800117// TODO: use the namespace something like android::netd_resolv for libnetd_resolv
Luke Huang3caa42b2020-04-23 14:18:04 +0000118using android::base::ErrnoError;
119using android::base::Result;
chenbruce99cbfd82019-09-05 15:08:13 +0800120using android::net::CacheStatus;
121using android::net::DnsQueryEvent;
122using android::net::DnsTlsDispatcher;
123using android::net::DnsTlsTransport;
124using android::net::gPrivateDnsConfiguration;
125using android::net::IpVersion;
126using android::net::IV_IPV4;
127using android::net::IV_IPV6;
128using android::net::IV_UNKNOWN;
lifr94981782019-05-17 21:15:19 +0800129using android::net::NetworkDnsEventReported;
chenbruce99cbfd82019-09-05 15:08:13 +0800130using android::net::NS_T_INVALID;
131using android::net::NsRcode;
132using android::net::NsType;
133using android::net::PrivateDnsMode;
134using android::net::PrivateDnsModes;
135using android::net::PrivateDnsStatus;
136using android::net::PROTO_TCP;
137using android::net::PROTO_UDP;
Mike Yue655b1d2019-08-28 17:49:59 +0800138using android::netdutils::IPSockAddr;
Bernie Innocentiec4219b2019-01-30 11:16:36 +0900139using android::netdutils::Slice;
lifr94981782019-05-17 21:15:19 +0800140using android::netdutils::Stopwatch;
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900141
Mike Yub601ff72018-11-01 20:07:00 +0800142static DnsTlsDispatcher sDnsTlsDispatcher;
143
Mike Yue48f7b52020-02-10 14:55:06 +0800144static int send_vc(res_state statp, res_params* params, const uint8_t* buf, int buflen,
145 uint8_t* ans, int anssiz, int* terrno, size_t ns, time_t* at, int* rcode,
146 int* delay);
147static int send_dg(res_state statp, res_params* params, const uint8_t* buf, int buflen,
Luke Huang3caa42b2020-04-23 14:18:04 +0000148 uint8_t* ans, int anssiz, int* terrno, size_t* ns, int* v_circuit,
Mike Yue48f7b52020-02-10 14:55:06 +0800149 int* gotsomewhere, time_t* at, int* rcode, int* delay);
150
chenbruce018fdb22019-06-12 18:08:04 +0800151static void dump_error(const char*, const struct sockaddr*, int);
chenbruceacb832c2019-02-20 19:45:50 +0800152
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900153static int sock_eq(struct sockaddr*, struct sockaddr*);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900154static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
155 const struct timespec timeout);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900156static int retrying_poll(const int sock, short events, const struct timespec* finish);
Luke Huangd7aa7b42018-11-21 20:37:50 +0800157static int res_tls_send(res_state, const Slice query, const Slice answer, int* rcode,
Mike Yubfb1b342018-11-06 15:42:36 +0800158 bool* fallback);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900159
lifr94981782019-05-17 21:15:19 +0800160NsType getQueryType(const uint8_t* msg, size_t msgLen) {
161 ns_msg handle;
162 ns_rr rr;
163 if (ns_initparse((const uint8_t*)msg, msgLen, &handle) < 0 ||
164 ns_parserr(&handle, ns_s_qd, 0, &rr) < 0) {
165 return NS_T_INVALID;
166 }
167 return static_cast<NsType>(ns_rr_type(rr));
168}
169
170IpVersion ipFamilyToIPVersion(const int ipFamily) {
171 switch (ipFamily) {
172 case AF_INET:
173 return IV_IPV4;
174 case AF_INET6:
175 return IV_IPV6;
176 default:
177 return IV_UNKNOWN;
178 }
179}
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900180
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900181// BEGIN: Code copied from ISC eventlib
182// TODO: move away from this code
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900183#define BILLION 1000000000
184
185static struct timespec evConsTime(time_t sec, long nsec) {
186 struct timespec x;
187
188 x.tv_sec = sec;
189 x.tv_nsec = nsec;
190 return (x);
191}
192
193static struct timespec evAddTime(struct timespec addend1, struct timespec addend2) {
194 struct timespec x;
195
196 x.tv_sec = addend1.tv_sec + addend2.tv_sec;
197 x.tv_nsec = addend1.tv_nsec + addend2.tv_nsec;
198 if (x.tv_nsec >= BILLION) {
199 x.tv_sec++;
200 x.tv_nsec -= BILLION;
201 }
202 return (x);
203}
204
205static struct timespec evSubTime(struct timespec minuend, struct timespec subtrahend) {
206 struct timespec x;
207
208 x.tv_sec = minuend.tv_sec - subtrahend.tv_sec;
209 if (minuend.tv_nsec >= subtrahend.tv_nsec)
210 x.tv_nsec = minuend.tv_nsec - subtrahend.tv_nsec;
211 else {
212 x.tv_nsec = BILLION - subtrahend.tv_nsec + minuend.tv_nsec;
213 x.tv_sec--;
214 }
215 return (x);
216}
217
218static int evCmpTime(struct timespec a, struct timespec b) {
219#define SGN(x) ((x) < 0 ? (-1) : (x) > 0 ? (1) : (0));
220 time_t s = a.tv_sec - b.tv_sec;
221 long n;
222
223 if (s != 0) return SGN(s);
224
225 n = a.tv_nsec - b.tv_nsec;
226 return SGN(n);
227}
228
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900229static struct timespec evNowTime(void) {
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900230 struct timespec tsnow;
Bernie Innocentic1834822018-08-31 16:11:41 +0900231 clock_gettime(CLOCK_REALTIME, &tsnow);
232 return tsnow;
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900233}
234
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900235// END: Code copied from ISC eventlib
236
lifr94981782019-05-17 21:15:19 +0800237/* BIONIC-BEGIN: implement source port randomization */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900238static int random_bind(int s, int family) {
nuccachenb980f2f2018-10-23 17:10:58 +0800239 sockaddr_union u;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900240 int j;
241 socklen_t slen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900242
243 /* clear all, this also sets the IP4/6 address to 'any' */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900244 memset(&u, 0, sizeof u);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900245
246 switch (family) {
247 case AF_INET:
248 u.sin.sin_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900249 slen = sizeof u.sin;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900250 break;
251 case AF_INET6:
252 u.sin6.sin6_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900253 slen = sizeof u.sin6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900254 break;
255 default:
256 errno = EPROTO;
257 return -1;
258 }
259
260 /* first try to bind to a random source port a few times */
261 for (j = 0; j < 10; j++) {
262 /* find a random port between 1025 .. 65534 */
Luke Huangdda920f2019-02-13 14:05:02 +0800263 int port = 1025 + (arc4random_uniform(65535 - 1025));
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900264 if (family == AF_INET)
265 u.sin.sin_port = htons(port);
266 else
267 u.sin6.sin6_port = htons(port);
268
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900269 if (!bind(s, &u.sa, slen)) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900270 }
271
Bernie Innocenti9c575932018-09-07 21:10:25 +0900272 // nothing after 10 attempts, our network table is probably busy
273 // let the system decide which port is best
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900274 if (family == AF_INET)
275 u.sin.sin_port = 0;
276 else
277 u.sin6.sin6_port = 0;
278
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900279 return bind(s, &u.sa, slen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900280}
281/* BIONIC-END */
282
Luke Huang70931aa2019-01-31 11:57:41 +0800283// Disables all nameservers other than selectedServer
284static void res_set_usable_server(int selectedServer, int nscount, bool usable_servers[]) {
285 int usableIndex = 0;
286 for (int ns = 0; ns < nscount; ns++) {
287 if (usable_servers[ns]) ++usableIndex;
288 if (usableIndex != selectedServer) usable_servers[ns] = false;
289 }
290}
291
Luke Huang3caa42b2020-04-23 14:18:04 +0000292// Looks up the nameserver address in res.nsaddrs[], returns the ns number if found, otherwise -1.
293static int res_ourserver_p(res_state statp, const sockaddr* sa) {
Bernie Innocenti2e8540b2018-09-26 11:52:04 +0900294 const sockaddr_in *inp, *srv;
295 const sockaddr_in6 *in6p, *srv6;
Luke Huang3caa42b2020-04-23 14:18:04 +0000296 int ns = 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900297 switch (sa->sa_family) {
298 case AF_INET:
299 inp = (const struct sockaddr_in*) (const void*) sa;
Luke Huang3caa42b2020-04-23 14:18:04 +0000300
Mike Yue48f7b52020-02-10 14:55:06 +0800301 for (const IPSockAddr& ipsa : statp->nsaddrs) {
302 sockaddr_storage ss = ipsa;
303 srv = reinterpret_cast<sockaddr_in*>(&ss);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900304 if (srv->sin_family == inp->sin_family && srv->sin_port == inp->sin_port &&
305 (srv->sin_addr.s_addr == INADDR_ANY ||
306 srv->sin_addr.s_addr == inp->sin_addr.s_addr))
Luke Huang3caa42b2020-04-23 14:18:04 +0000307 return ns;
308 ++ns;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900309 }
310 break;
311 case AF_INET6:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900312 in6p = (const struct sockaddr_in6*) (const void*) sa;
Mike Yue48f7b52020-02-10 14:55:06 +0800313 for (const IPSockAddr& ipsa : statp->nsaddrs) {
314 sockaddr_storage ss = ipsa;
315 srv6 = reinterpret_cast<sockaddr_in6*>(&ss);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900316 if (srv6->sin6_family == in6p->sin6_family && srv6->sin6_port == in6p->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900317#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900318 (srv6->sin6_scope_id == 0 || srv6->sin6_scope_id == in6p->sin6_scope_id) &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900319#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900320 (IN6_IS_ADDR_UNSPECIFIED(&srv6->sin6_addr) ||
321 IN6_ARE_ADDR_EQUAL(&srv6->sin6_addr, &in6p->sin6_addr)))
Luke Huang3caa42b2020-04-23 14:18:04 +0000322 return ns;
323 ++ns;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900324 }
325 break;
326 default:
327 break;
328 }
Luke Huang3caa42b2020-04-23 14:18:04 +0000329 return -1;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900330}
331
332/* int
Bernie Innocenti9c575932018-09-07 21:10:25 +0900333 * res_nameinquery(name, type, cl, buf, eom)
334 * look for (name, type, cl) in the query section of packet (buf, eom)
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900335 * requires:
336 * buf + HFIXEDSZ <= eom
337 * returns:
338 * -1 : format error
339 * 0 : not found
340 * >0 : found
341 * author:
342 * paul vixie, 29may94
343 */
chenbrucec51f1212019-09-12 16:59:33 +0800344int res_nameinquery(const char* name, int type, int cl, const uint8_t* buf, const uint8_t* eom) {
345 const uint8_t* cp = buf + HFIXEDSZ;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900346 int qdcount = ntohs(((const HEADER*) (const void*) buf)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900347
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900348 while (qdcount-- > 0) {
349 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900350 int n = dn_expand(buf, eom, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900351 if (n < 0) return (-1);
352 cp += n;
353 if (cp + 2 * INT16SZ > eom) return (-1);
chenbruce0d470422019-03-28 18:44:37 +0800354 int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900355 cp += INT16SZ;
chenbruce0d470422019-03-28 18:44:37 +0800356 int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900357 cp += INT16SZ;
Bernie Innocenti9c575932018-09-07 21:10:25 +0900358 if (ttype == type && tclass == cl && ns_samename(tname, name) == 1) return (1);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900359 }
360 return (0);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900361}
362
363/* int
364 * res_queriesmatch(buf1, eom1, buf2, eom2)
365 * is there a 1:1 mapping of (name,type,class)
366 * in (buf1,eom1) and (buf2,eom2)?
367 * returns:
368 * -1 : format error
369 * 0 : not a 1:1 mapping
370 * >0 : is a 1:1 mapping
371 * author:
372 * paul vixie, 29may94
373 */
chenbrucec51f1212019-09-12 16:59:33 +0800374int res_queriesmatch(const uint8_t* buf1, const uint8_t* eom1, const uint8_t* buf2,
375 const uint8_t* eom2) {
376 const uint8_t* cp = buf1 + HFIXEDSZ;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900377 int qdcount = ntohs(((const HEADER*) (const void*) buf1)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900378
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900379 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2) return (-1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900380
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900381 /*
382 * Only header section present in replies to
383 * dynamic update packets.
384 */
385 if ((((const HEADER*) (const void*) buf1)->opcode == ns_o_update) &&
386 (((const HEADER*) (const void*) buf2)->opcode == ns_o_update))
387 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900388
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900389 if (qdcount != ntohs(((const HEADER*) (const void*) buf2)->qdcount)) return (0);
390 while (qdcount-- > 0) {
391 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900392 int n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900393 if (n < 0) return (-1);
394 cp += n;
395 if (cp + 2 * INT16SZ > eom1) return (-1);
chenbruce0d470422019-03-28 18:44:37 +0800396 int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900397 cp += INT16SZ;
chenbruce0d470422019-03-28 18:44:37 +0800398 int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900399 cp += INT16SZ;
400 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2)) return (0);
401 }
402 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900403}
404
lifr94981782019-05-17 21:15:19 +0800405static DnsQueryEvent* addDnsQueryEvent(NetworkDnsEventReported* event) {
406 return event->mutable_dns_query_events()->add_dns_query_event();
407}
408
chenbrucec51f1212019-09-12 16:59:33 +0800409int 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 +0800410 uint32_t flags) {
Luke Huang43cc1b12019-10-15 19:06:42 +0900411 LOG(DEBUG) << __func__;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900412
Luke Huang43cc1b12019-10-15 19:06:42 +0900413 // Should not happen
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900414 if (anssiz < HFIXEDSZ) {
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800415 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900416 errno = EINVAL;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800417 return -EINVAL;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900418 }
chenbrucedd210722019-03-06 13:52:43 +0800419 res_pquery(buf, buflen);
chenbruceacb832c2019-02-20 19:45:50 +0800420
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900421 int anslen = 0;
lifrd4d9fbb2019-07-31 20:18:35 +0800422 Stopwatch cacheStopwatch;
Luke Huang43cc1b12019-10-15 19:06:42 +0900423 ResolvCacheStatus cache_status =
424 resolv_cache_lookup(statp->netid, buf, buflen, ans, anssiz, &anslen, flags);
lifrd4d9fbb2019-07-31 20:18:35 +0800425 const int32_t cacheLatencyUs = saturate_cast<int32_t>(cacheStopwatch.timeTakenUs());
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900426 if (cache_status == RESOLV_CACHE_FOUND) {
Luke Huang83c9b4b2019-02-27 18:18:01 +0800427 HEADER* hp = (HEADER*)(void*)ans;
428 *rcode = hp->rcode;
lifr94981782019-05-17 21:15:19 +0800429 DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
430 dnsQueryEvent->set_latency_micros(cacheLatencyUs);
431 dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
lifre02d01c2019-12-31 17:24:57 +0800432 dnsQueryEvent->set_type(getQueryType(buf, buflen));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900433 return anslen;
434 } else if (cache_status != RESOLV_CACHE_UNSUPPORTED) {
435 // had a cache miss for a known network, so populate the thread private
436 // data so the normal resolve path can do its thing
Mike Yu021c3e12019-10-08 17:29:34 +0800437 resolv_populate_res_for_net(statp);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900438 }
Mike Yuecc52822020-02-14 14:36:46 +0800439 if (statp->nameserverCount() == 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900440 // We have no nameservers configured, so there's no point trying.
441 // Tell the cache the query failed, or any retries and anyone else asking the same
442 // question will block for PENDING_REQUEST_TIMEOUT seconds instead of failing fast.
Luke Huangba7bef92018-12-26 16:53:03 +0800443 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800444
445 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900446 errno = ESRCH;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800447 return -ESRCH;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900448 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900449
Luke Huang272cb192019-10-15 16:52:28 +0900450 // DoT
451 if (!(statp->netcontext_flags & NET_CONTEXT_FLAG_USE_LOCAL_NAMESERVERS)) {
452 bool fallback = false;
Luke Huang43cc1b12019-10-15 19:06:42 +0900453 int resplen = res_tls_send(statp, Slice(const_cast<uint8_t*>(buf), buflen),
454 Slice(ans, anssiz), rcode, &fallback);
Luke Huang272cb192019-10-15 16:52:28 +0900455 if (resplen > 0) {
456 LOG(DEBUG) << __func__ << ": got answer from DoT";
457 res_pquery(ans, resplen);
458 if (cache_status == RESOLV_CACHE_NOTFOUND) {
459 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
460 }
461 return resplen;
462 }
463 if (!fallback) {
464 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huang43cc1b12019-10-15 19:06:42 +0900465 return -ETIMEDOUT;
Luke Huang272cb192019-10-15 16:52:28 +0900466 }
467 }
468
Mike Yuc573a3d2020-02-07 20:15:15 +0800469 res_stats stats[MAXNS]{};
Bernie Innocenti758005f2019-02-19 18:08:36 +0900470 res_params params;
Mike Yuc573a3d2020-02-07 20:15:15 +0800471 int revision_id = resolv_cache_get_resolver_stats(statp->netid, &params, stats, statp->nsaddrs);
lifra1b37f12019-02-13 17:33:57 +0800472 if (revision_id < 0) {
473 // TODO: Remove errno once callers stop using it
474 errno = ESRCH;
475 return -ESRCH;
476 }
waynema0161acd2019-02-18 17:47:59 +0800477 bool usable_servers[MAXNS];
Luke Huang70931aa2019-01-31 11:57:41 +0800478 int usableServersCount = android_net_res_stats_get_usable_servers(
Mike Yuecc52822020-02-14 14:36:46 +0800479 &params, stats, statp->nameserverCount(), usable_servers);
Luke Huang70931aa2019-01-31 11:57:41 +0800480
481 if ((flags & ANDROID_RESOLV_NO_RETRY) && usableServersCount > 1) {
482 auto hp = reinterpret_cast<const HEADER*>(buf);
483
484 // Select a random server based on the query id
485 int selectedServer = (hp->id % usableServersCount) + 1;
Mike Yuecc52822020-02-14 14:36:46 +0800486 res_set_usable_server(selectedServer, statp->nameserverCount(), usable_servers);
Luke Huang70931aa2019-01-31 11:57:41 +0800487 }
waynema0161acd2019-02-18 17:47:59 +0800488
Luke Huang43cc1b12019-10-15 19:06:42 +0900489 // Send request, RETRY times, or until successful.
waynemaa74195e2019-01-18 14:02:31 +0800490 int retryTimes = (flags & ANDROID_RESOLV_NO_RETRY) ? 1 : params.retry_count;
Luke Huang43cc1b12019-10-15 19:06:42 +0900491 int useTcp = buflen > PACKETSZ;
492 int gotsomewhere = 0;
493 int terrno = ETIMEDOUT;
Luke Huangba7bef92018-12-26 16:53:03 +0800494
495 for (int attempt = 0; attempt < retryTimes; ++attempt) {
Mike Yue48f7b52020-02-10 14:55:06 +0800496 for (size_t ns = 0; ns < statp->nsaddrs.size(); ++ns) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900497 if (!usable_servers[ns]) continue;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900498
Luke Huang43cc1b12019-10-15 19:06:42 +0900499 *rcode = RCODE_INTERNAL_ERROR;
500
501 // Get server addr
Mike Yue48f7b52020-02-10 14:55:06 +0800502 const IPSockAddr& serverSockAddr = statp->nsaddrs[ns];
503 LOG(DEBUG) << __func__ << ": Querying server (# " << ns + 1
504 << ") address = " << serverSockAddr.toString();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900505
Luke Huang43cc1b12019-10-15 19:06:42 +0900506 ::android::net::Protocol query_proto = useTcp ? PROTO_TCP : PROTO_UDP;
Luke Huang3caa42b2020-04-23 14:18:04 +0000507 time_t query_time = 0;
Luke Huang43cc1b12019-10-15 19:06:42 +0900508 int delay = 0;
509 bool fallbackTCP = false;
510 const bool shouldRecordStats = (attempt == 0);
511 int resplen;
lifrd4d9fbb2019-07-31 20:18:35 +0800512 Stopwatch queryStopwatch;
lifr128183a2020-01-08 18:04:50 +0800513 int retry_count_for_event = 0;
Luke Huang3caa42b2020-04-23 14:18:04 +0000514 size_t actualNs = ns;
Luke Huang43cc1b12019-10-15 19:06:42 +0900515 if (useTcp) {
516 // TCP; at most one attempt per server.
Luke Huangba7bef92018-12-26 16:53:03 +0800517 attempt = retryTimes;
Luke Huang3caa42b2020-04-23 14:18:04 +0000518 resplen = send_vc(statp, &params, buf, buflen, ans, anssiz, &terrno, ns,
519 &query_time, rcode, &delay);
Ken Chen99344882020-01-01 14:59:38 +0800520
521 if (buflen <= PACKETSZ && resplen <= 0 &&
522 statp->tc_mode == aidl::android::net::IDnsResolver::TC_MODE_UDP_TCP) {
523 // reset to UDP for next query on next DNS server if resolver is currently doing
524 // TCP fallback retry and current server does not support TCP connectin
525 useTcp = false;
526 }
527 LOG(INFO) << __func__ << ": used send_vc " << resplen;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900528 } else {
Luke Huang43cc1b12019-10-15 19:06:42 +0900529 // UDP
Luke Huang3caa42b2020-04-23 14:18:04 +0000530 resplen = send_dg(statp, &params, buf, buflen, ans, anssiz, &terrno, &actualNs,
531 &useTcp, &gotsomewhere, &query_time, rcode, &delay);
Luke Huang43cc1b12019-10-15 19:06:42 +0900532 fallbackTCP = useTcp ? true : false;
lifr128183a2020-01-08 18:04:50 +0800533 retry_count_for_event = attempt;
Ken Chen99344882020-01-01 14:59:38 +0800534 LOG(INFO) << __func__ << ": used send_dg " << resplen;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900535 }
Luke Huang43cc1b12019-10-15 19:06:42 +0900536
Luke Huang3caa42b2020-04-23 14:18:04 +0000537 const IPSockAddr& receivedServerAddr = statp->nsaddrs[actualNs];
Luke Huang43cc1b12019-10-15 19:06:42 +0900538 DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
539 dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
Luke Huang3caa42b2020-04-23 14:18:04 +0000540 // When |retryTimes| > 1, we cannot actually know the correct latency value if we
541 // received the answer from the previous server. So temporarily set the latency as -1 if
542 // that condition happened.
543 // TODO: make the latency value accurate.
544 dnsQueryEvent->set_latency_micros(
545 (actualNs == ns) ? saturate_cast<int32_t>(queryStopwatch.timeTakenUs()) : -1);
546 dnsQueryEvent->set_dns_server_index(actualNs);
547 dnsQueryEvent->set_ip_version(ipFamilyToIPVersion(receivedServerAddr.family()));
lifr128183a2020-01-08 18:04:50 +0800548 dnsQueryEvent->set_retry_times(retry_count_for_event);
Luke Huang43cc1b12019-10-15 19:06:42 +0900549 dnsQueryEvent->set_rcode(static_cast<NsRcode>(*rcode));
550 dnsQueryEvent->set_protocol(query_proto);
551 dnsQueryEvent->set_type(getQueryType(buf, buflen));
552
553 // Only record stats the first time we try a query. This ensures that
554 // queries that deterministically fail (e.g., a name that always returns
555 // SERVFAIL or times out) do not unduly affect the stats.
556 if (shouldRecordStats) {
557 res_sample sample;
Luke Huang3caa42b2020-04-23 14:18:04 +0000558 res_stats_set_sample(&sample, query_time, *rcode, delay);
559 // KeepListening UDP mechanism is incompatible with usable_servers of legacy stats,
560 // so keep the old logic for now.
561 // TODO: Replace usable_servers of legacy stats with new one.
Mike Yue48f7b52020-02-10 14:55:06 +0800562 resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, serverSockAddr,
563 sample, params.max_samples);
Luke Huang3caa42b2020-04-23 14:18:04 +0000564 resolv_stats_add(statp->netid, receivedServerAddr, dnsQueryEvent);
Luke Huang43cc1b12019-10-15 19:06:42 +0900565 }
566
567 if (resplen == 0) continue;
568 if (fallbackTCP) {
569 ns--;
570 continue;
571 }
572 if (resplen < 0) {
573 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800574 statp->closeSockets();
Luke Huang43cc1b12019-10-15 19:06:42 +0900575 return -terrno;
576 };
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900577
Ken Chenffc224a2019-03-19 17:41:28 +0800578 LOG(DEBUG) << __func__ << ": got answer:";
chenbrucedd210722019-03-06 13:52:43 +0800579 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900580
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900581 if (cache_status == RESOLV_CACHE_NOTFOUND) {
Mike Yud1ec2542019-06-06 17:17:53 +0800582 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900583 }
Luke Huangadb0f5b2019-11-27 15:51:48 +0800584 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900585 return (resplen);
Bernie Innocenti9c575932018-09-07 21:10:25 +0900586 } // for each ns
587 } // for each retry
Luke Huangadb0f5b2019-11-27 15:51:48 +0800588 statp->closeSockets();
Luke Huang43cc1b12019-10-15 19:06:42 +0900589 terrno = useTcp ? terrno : gotsomewhere ? ETIMEDOUT : ECONNREFUSED;
590 // TODO: Remove errno once callers stop using it
591 errno = useTcp ? terrno
592 : gotsomewhere ? ETIMEDOUT /* no answer obtained */
593 : ECONNREFUSED /* no nameservers found */;
594
Luke Huangba7bef92018-12-26 16:53:03 +0800595 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800596 return -terrno;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900597}
598
chenbruce99cbfd82019-09-05 15:08:13 +0800599static struct timespec get_timeout(res_state statp, const res_params* params, const int ns) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900600 int msec;
waynemaa74195e2019-01-18 14:02:31 +0800601 // Legacy algorithm which scales the timeout by nameserver number.
602 // For instance, with 4 nameservers: 5s, 2.5s, 5s, 10s
603 // This has no effect with 1 or 2 nameservers
604 msec = params->base_timeout_msec << ns;
605 if (ns > 0) {
Mike Yuecc52822020-02-14 14:36:46 +0800606 msec /= statp->nameserverCount();
waynemaa74195e2019-01-18 14:02:31 +0800607 }
608 // For safety, don't allow OEMs and experiments to configure a timeout shorter than 1s.
609 if (msec < 1000) {
610 msec = 1000; // Use at least 1000ms
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900611 }
Ken Chenffc224a2019-03-19 17:41:28 +0800612 LOG(INFO) << __func__ << ": using timeout of " << msec << " msec";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900613
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900614 struct timespec result;
615 result.tv_sec = msec / 1000;
616 result.tv_nsec = (msec % 1000) * 1000000;
617 return result;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900618}
619
chenbrucec51f1212019-09-12 16:59:33 +0800620static int send_vc(res_state statp, res_params* params, const uint8_t* buf, int buflen,
Mike Yue48f7b52020-02-10 14:55:06 +0800621 uint8_t* ans, int anssiz, int* terrno, size_t ns, time_t* at, int* rcode,
chenbrucec51f1212019-09-12 16:59:33 +0800622 int* delay) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900623 *at = time(NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900624 *delay = 0;
625 const HEADER* hp = (const HEADER*) (const void*) buf;
626 HEADER* anhp = (HEADER*) (void*) ans;
627 struct sockaddr* nsap;
628 int nsaplen;
chenbruce0d470422019-03-28 18:44:37 +0800629 int truncating, connreset, n;
chenbrucec51f1212019-09-12 16:59:33 +0800630 uint8_t* cp;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900631
Ken Chenffc224a2019-03-19 17:41:28 +0800632 LOG(INFO) << __func__ << ": using send_vc";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900633
Mike Yue48f7b52020-02-10 14:55:06 +0800634 // It should never happen, but just in case.
635 if (ns >= statp->nsaddrs.size()) {
636 LOG(ERROR) << __func__ << ": Out-of-bound indexing: " << ns;
637 return -1;
638 }
639
640 sockaddr_storage ss = statp->nsaddrs[ns];
641 nsap = reinterpret_cast<sockaddr*>(&ss);
Mike Yu021c3e12019-10-08 17:29:34 +0800642 nsaplen = sockaddrSize(nsap);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900643
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900644 connreset = 0;
645same_ns:
646 truncating = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900647
Luke Huang3caa42b2020-04-23 14:18:04 +0000648 struct timespec start_time = evNowTime();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900649
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900650 /* Are we still talking to whom we want to talk to? */
Luke Huangadb0f5b2019-11-27 15:51:48 +0800651 if (statp->tcp_nssock >= 0 && (statp->_flags & RES_F_VC) != 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900652 struct sockaddr_storage peer;
653 socklen_t size = sizeof peer;
654 unsigned old_mark;
655 socklen_t mark_size = sizeof(old_mark);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800656 if (getpeername(statp->tcp_nssock, (struct sockaddr*)(void*)&peer, &size) < 0 ||
657 !sock_eq((struct sockaddr*)(void*)&peer, nsap) ||
658 getsockopt(statp->tcp_nssock, SOL_SOCKET, SO_MARK, &old_mark, &mark_size) < 0 ||
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900659 old_mark != statp->_mark) {
Luke Huangadb0f5b2019-11-27 15:51:48 +0800660 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900661 }
662 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900663
Luke Huangadb0f5b2019-11-27 15:51:48 +0800664 if (statp->tcp_nssock < 0 || (statp->_flags & RES_F_VC) == 0) {
665 if (statp->tcp_nssock >= 0) statp->closeSockets();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900666
Luke Huangadb0f5b2019-11-27 15:51:48 +0800667 statp->tcp_nssock.reset(socket(nsap->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0));
668 if (statp->tcp_nssock < 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900669 switch (errno) {
670 case EPROTONOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900671 case EPFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900672 case EAFNOSUPPORT:
chenbruce018fdb22019-06-12 18:08:04 +0800673 PLOG(DEBUG) << __func__ << ": socket(vc): ";
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900674 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900675 default:
676 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800677 PLOG(DEBUG) << __func__ << ": socket(vc): ";
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900678 return -1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900679 }
680 }
Luke Huangadb0f5b2019-11-27 15:51:48 +0800681 resolv_tag_socket(statp->tcp_nssock, statp->uid, statp->pid);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900682 if (statp->_mark != MARK_UNSET) {
Luke Huangadb0f5b2019-11-27 15:51:48 +0800683 if (setsockopt(statp->tcp_nssock, SOL_SOCKET, SO_MARK, &statp->_mark,
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900684 sizeof(statp->_mark)) < 0) {
685 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800686 PLOG(DEBUG) << __func__ << ": setsockopt: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900687 return -1;
688 }
689 }
690 errno = 0;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800691 if (random_bind(statp->tcp_nssock, nsap->sa_family) < 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900692 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800693 dump_error("bind/vc", nsap, nsaplen);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800694 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900695 return (0);
696 }
Luke Huangadb0f5b2019-11-27 15:51:48 +0800697 if (connect_with_timeout(statp->tcp_nssock, nsap, (socklen_t)nsaplen,
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900698 get_timeout(statp, params, ns)) < 0) {
699 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800700 dump_error("connect/vc", nsap, nsaplen);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800701 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900702 /*
703 * The way connect_with_timeout() is implemented prevents us from reliably
704 * determining whether this was really a timeout or e.g. ECONNREFUSED. Since
705 * currently both cases are handled in the same way, there is no need to
706 * change this (yet). If we ever need to reliably distinguish between these
707 * cases, both connect_with_timeout() and retrying_poll() need to be
708 * modified, though.
709 */
710 *rcode = RCODE_TIMEOUT;
711 return (0);
712 }
713 statp->_flags |= RES_F_VC;
714 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900715
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900716 /*
717 * Send length & message
718 */
chenbruce0d470422019-03-28 18:44:37 +0800719 uint16_t len = htons(static_cast<uint16_t>(buflen));
Luke Huangc98fd802019-10-15 16:36:36 +0900720 const iovec iov[] = {
721 {.iov_base = &len, .iov_len = INT16SZ},
722 {.iov_base = const_cast<uint8_t*>(buf), .iov_len = static_cast<size_t>(buflen)},
723 };
Luke Huangadb0f5b2019-11-27 15:51:48 +0800724 if (writev(statp->tcp_nssock, iov, 2) != (INT16SZ + buflen)) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900725 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800726 PLOG(DEBUG) << __func__ << ": write failed: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800727 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900728 return (0);
729 }
730 /*
731 * Receive length & response
732 */
733read_len:
734 cp = ans;
735 len = INT16SZ;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800736 while ((n = read(statp->tcp_nssock, (char*)cp, (size_t)len)) > 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900737 cp += n;
738 if ((len -= n) == 0) break;
739 }
740 if (n <= 0) {
741 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800742 PLOG(DEBUG) << __func__ << ": read failed: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800743 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900744 /*
745 * A long running process might get its TCP
746 * connection reset if the remote server was
747 * restarted. Requery the server instead of
748 * trying a new one. When there is only one
749 * server, this means that a query might work
750 * instead of failing. We only allow one reset
751 * per query to prevent looping.
752 */
753 if (*terrno == ECONNRESET && !connreset) {
754 connreset = 1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900755 goto same_ns;
756 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900757 return (0);
758 }
chenbruce0d470422019-03-28 18:44:37 +0800759 uint16_t resplen = ntohs(*reinterpret_cast<const uint16_t*>(ans));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900760 if (resplen > anssiz) {
Ken Chenffc224a2019-03-19 17:41:28 +0800761 LOG(DEBUG) << __func__ << ": response truncated";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900762 truncating = 1;
763 len = anssiz;
764 } else
765 len = resplen;
766 if (len < HFIXEDSZ) {
767 /*
768 * Undersized message.
769 */
Ken Chenffc224a2019-03-19 17:41:28 +0800770 LOG(DEBUG) << __func__ << ": undersized: " << len;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900771 *terrno = EMSGSIZE;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800772 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900773 return (0);
774 }
775 cp = ans;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800776 while (len != 0 && (n = read(statp->tcp_nssock, (char*)cp, (size_t)len)) > 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900777 cp += n;
778 len -= n;
779 }
780 if (n <= 0) {
781 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800782 PLOG(DEBUG) << __func__ << ": read(vc): ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800783 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900784 return (0);
785 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900786
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900787 if (truncating) {
788 /*
789 * Flush rest of answer so connection stays in synch.
790 */
791 anhp->tc = 1;
792 len = resplen - anssiz;
793 while (len != 0) {
794 char junk[PACKETSZ];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900795
Luke Huangadb0f5b2019-11-27 15:51:48 +0800796 n = read(statp->tcp_nssock, junk, (len > sizeof junk) ? sizeof junk : len);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900797 if (n > 0)
798 len -= n;
799 else
800 break;
801 }
802 }
803 /*
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900804 * If the calling application has bailed out of
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900805 * a previous call and failed to arrange to have
806 * the circuit closed or the server has got
807 * itself confused, then drop the packet and
808 * wait for the correct one.
809 */
810 if (hp->id != anhp->id) {
Ken Chenffc224a2019-03-19 17:41:28 +0800811 LOG(DEBUG) << __func__ << ": ld answer (unexpected):";
chenbrucedd210722019-03-06 13:52:43 +0800812 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900813 goto read_len;
814 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900815
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900816 /*
817 * All is well, or the error is fatal. Signal that the
818 * next nameserver ought not be tried.
819 */
820 if (resplen > 0) {
821 struct timespec done = evNowTime();
Luke Huang3caa42b2020-04-23 14:18:04 +0000822 *delay = res_stats_calculate_rtt(&done, &start_time);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900823 *rcode = anhp->rcode;
824 }
825 return (resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900826}
827
828/* return -1 on error (errno set), 0 on success */
Luke Huangc98fd802019-10-15 16:36:36 +0900829static int connect_with_timeout(int sock, const sockaddr* nsap, socklen_t salen,
830 const timespec timeout) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900831 int res, origflags;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900832
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900833 origflags = fcntl(sock, F_GETFL, 0);
834 fcntl(sock, F_SETFL, origflags | O_NONBLOCK);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900835
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900836 res = connect(sock, nsap, salen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900837 if (res < 0 && errno != EINPROGRESS) {
838 res = -1;
839 goto done;
840 }
841 if (res != 0) {
Luke Huangc98fd802019-10-15 16:36:36 +0900842 timespec now = evNowTime();
843 timespec finish = evAddTime(now, timeout);
Ken Chenffc224a2019-03-19 17:41:28 +0800844 LOG(INFO) << __func__ << ": " << sock << " send_vc";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900845 res = retrying_poll(sock, POLLIN | POLLOUT, &finish);
846 if (res <= 0) {
847 res = -1;
848 }
849 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900850done:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900851 fcntl(sock, F_SETFL, origflags);
Ken Chenffc224a2019-03-19 17:41:28 +0800852 LOG(INFO) << __func__ << ": " << sock << " connect_with_const timeout returning " << res;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900853 return res;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900854}
855
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900856static int retrying_poll(const int sock, const short events, const struct timespec* finish) {
857 struct timespec now, timeout;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900858
859retry:
Ken Chenffc224a2019-03-19 17:41:28 +0800860 LOG(INFO) << __func__ << ": " << sock << " retrying_poll";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900861
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900862 now = evNowTime();
863 if (evCmpTime(*finish, now) > 0)
864 timeout = evSubTime(*finish, now);
865 else
866 timeout = evConsTime(0L, 0L);
867 struct pollfd fds = {.fd = sock, .events = events};
868 int n = ppoll(&fds, 1, &timeout, /*sigmask=*/NULL);
869 if (n == 0) {
Luke Huang3caa42b2020-04-23 14:18:04 +0000870 LOG(INFO) << __func__ << ": " << sock << " retrying_poll timeout";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900871 errno = ETIMEDOUT;
872 return 0;
873 }
874 if (n < 0) {
875 if (errno == EINTR) goto retry;
Ken Chenffc224a2019-03-19 17:41:28 +0800876 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll failed";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900877 return n;
878 }
879 if (fds.revents & (POLLIN | POLLOUT | POLLERR)) {
880 int error;
881 socklen_t len = sizeof(error);
882 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error) {
883 errno = error;
Ken Chenffc224a2019-03-19 17:41:28 +0800884 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll getsockopt failed";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900885 return -1;
886 }
887 }
Ken Chenffc224a2019-03-19 17:41:28 +0800888 LOG(INFO) << __func__ << ": " << sock << " retrying_poll returning " << n;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900889 return n;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900890}
891
Luke Huang3caa42b2020-04-23 14:18:04 +0000892static std::vector<pollfd> extractUdpFdset(res_state statp, const short events = POLLIN) {
893 std::vector<pollfd> fdset(statp->nsaddrs.size());
894 for (size_t i = 0; i < statp->nsaddrs.size(); ++i) {
895 fdset[i] = {.fd = statp->nssocks[i], .events = events};
896 }
897 return fdset;
898}
899
900static Result<std::vector<int>> udpRetryingPoll(res_state statp, const timespec* finish) {
901 for (;;) {
902 LOG(DEBUG) << __func__ << ": poll";
903 timespec start_time = evNowTime();
904 timespec timeout = (evCmpTime(*finish, start_time) > 0) ? evSubTime(*finish, start_time)
905 : evConsTime(0L, 0L);
906 std::vector<pollfd> fdset = extractUdpFdset(statp);
907 const int n = ppoll(fdset.data(), fdset.size(), &timeout, /*sigmask=*/nullptr);
908 if (n <= 0) {
909 if (errno == EINTR && n < 0) continue;
910 if (n == 0) errno = ETIMEDOUT;
911 PLOG(INFO) << __func__ << ": failed";
912 return ErrnoError();
913 }
914 std::vector<int> fdsToRead;
915 for (const auto& pollfd : fdset) {
916 if (pollfd.revents & (POLLIN | POLLERR)) {
917 fdsToRead.push_back(pollfd.fd);
918 }
919 }
920 LOG(DEBUG) << __func__ << ": "
921 << " returning fd size: " << fdsToRead.size();
922 return fdsToRead;
923 }
924}
925
926static Result<std::vector<int>> udpRetryingPollWrapper(res_state statp, int ns,
927 const timespec* finish) {
928 const bool keepListeningUdp = getExperimentFlagInt("keep_listening_udp", 0);
929 if (keepListeningUdp) return udpRetryingPoll(statp, finish);
930
931 if (int n = retrying_poll(statp->nssocks[ns], POLLIN, finish); n <= 0) {
932 return ErrnoError();
933 }
934 return std::vector<int>{statp->nssocks[ns]};
935}
936
Luke Huangbff43fc2019-11-12 15:54:47 +0800937bool ignoreInvalidAnswer(res_state statp, const sockaddr_storage& from, const uint8_t* buf,
Luke Huang3caa42b2020-04-23 14:18:04 +0000938 int buflen, uint8_t* ans, int anssiz, int* receivedFromNs) {
Luke Huangbff43fc2019-11-12 15:54:47 +0800939 const HEADER* hp = (const HEADER*)(const void*)buf;
940 HEADER* anhp = (HEADER*)(void*)ans;
941 if (hp->id != anhp->id) {
942 // response from old query, ignore it.
943 LOG(DEBUG) << __func__ << ": old answer:";
944 return true;
945 }
Luke Huang3caa42b2020-04-23 14:18:04 +0000946 if (*receivedFromNs = res_ourserver_p(statp, (sockaddr*)(void*)&from); *receivedFromNs < 0) {
Luke Huangbff43fc2019-11-12 15:54:47 +0800947 // response from wrong server? ignore it.
948 LOG(DEBUG) << __func__ << ": not our server:";
949 return true;
950 }
951 if (!res_queriesmatch(buf, buf + buflen, ans, ans + anssiz)) {
952 // response contains wrong query? ignore it.
953 LOG(DEBUG) << __func__ << ": wrong query name:";
954 return true;
955 }
956 return false;
957}
958
chenbrucec51f1212019-09-12 16:59:33 +0800959static int send_dg(res_state statp, res_params* params, const uint8_t* buf, int buflen,
Luke Huang3caa42b2020-04-23 14:18:04 +0000960 uint8_t* ans, int anssiz, int* terrno, size_t* ns, int* v_circuit,
Mike Yue48f7b52020-02-10 14:55:06 +0800961 int* gotsomewhere, time_t* at, int* rcode, int* delay) {
962 // It should never happen, but just in case.
Luke Huang3caa42b2020-04-23 14:18:04 +0000963 if (*ns >= statp->nsaddrs.size()) {
Mike Yue48f7b52020-02-10 14:55:06 +0800964 LOG(ERROR) << __func__ << ": Out-of-bound indexing: " << ns;
965 return -1;
966 }
967
Luke Huangbff43fc2019-11-12 15:54:47 +0800968 *at = time(nullptr);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900969 *delay = 0;
Luke Huang3caa42b2020-04-23 14:18:04 +0000970 const sockaddr_storage ss = statp->nsaddrs[*ns];
Mike Yue48f7b52020-02-10 14:55:06 +0800971 const sockaddr* nsap = reinterpret_cast<const sockaddr*>(&ss);
Luke Huangbff43fc2019-11-12 15:54:47 +0800972 const int nsaplen = sockaddrSize(nsap);
973
Luke Huang3caa42b2020-04-23 14:18:04 +0000974 if (statp->nssocks[*ns] == -1) {
975 statp->nssocks[*ns].reset(socket(nsap->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0));
976 if (statp->nssocks[*ns] < 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900977 switch (errno) {
978 case EPROTONOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900979 case EPFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900980 case EAFNOSUPPORT:
chenbruce018fdb22019-06-12 18:08:04 +0800981 PLOG(DEBUG) << __func__ << ": socket(dg): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900982 return (0);
983 default:
984 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800985 PLOG(DEBUG) << __func__ << ": socket(dg): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900986 return (-1);
987 }
988 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900989
Luke Huang3caa42b2020-04-23 14:18:04 +0000990 resolv_tag_socket(statp->nssocks[*ns], statp->uid, statp->pid);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900991 if (statp->_mark != MARK_UNSET) {
Luke Huang3caa42b2020-04-23 14:18:04 +0000992 if (setsockopt(statp->nssocks[*ns], SOL_SOCKET, SO_MARK, &(statp->_mark),
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900993 sizeof(statp->_mark)) < 0) {
Luke Huangadb0f5b2019-11-27 15:51:48 +0800994 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900995 return -1;
996 }
997 }
chenbruceb9cce7b2019-07-15 16:14:53 +0800998 // Use a "connected" datagram socket to receive an ECONNREFUSED error
999 // on the next socket operation when the server responds with an
1000 // ICMP port-unreachable error. This way we can detect the absence of
1001 // a nameserver without timing out.
Luke Huang3caa42b2020-04-23 14:18:04 +00001002 if (random_bind(statp->nssocks[*ns], nsap->sa_family) < 0) {
chenbruce018fdb22019-06-12 18:08:04 +08001003 dump_error("bind(dg)", nsap, nsaplen);
Luke Huangadb0f5b2019-11-27 15:51:48 +08001004 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001005 return (0);
1006 }
Luke Huang3caa42b2020-04-23 14:18:04 +00001007 if (connect(statp->nssocks[*ns], nsap, (socklen_t)nsaplen) < 0) {
chenbruce018fdb22019-06-12 18:08:04 +08001008 dump_error("connect(dg)", nsap, nsaplen);
Luke Huangadb0f5b2019-11-27 15:51:48 +08001009 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001010 return (0);
1011 }
Ken Chenffc224a2019-03-19 17:41:28 +08001012 LOG(DEBUG) << __func__ << ": new DG socket";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001013 }
Luke Huang3caa42b2020-04-23 14:18:04 +00001014 if (send(statp->nssocks[*ns], (const char*)buf, (size_t)buflen, 0) != buflen) {
chenbruce018fdb22019-06-12 18:08:04 +08001015 PLOG(DEBUG) << __func__ << ": send: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +08001016 statp->closeSockets();
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001017 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001018 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001019
Luke Huang3caa42b2020-04-23 14:18:04 +00001020 timespec timeout = get_timeout(statp, params, *ns);
1021 timespec start_time = evNowTime();
1022 timespec finish = evAddTime(start_time, timeout);
Luke Huangbff43fc2019-11-12 15:54:47 +08001023 for (;;) {
1024 // Wait for reply.
Luke Huang3caa42b2020-04-23 14:18:04 +00001025 auto result = udpRetryingPollWrapper(statp, *ns, &finish);
1026
1027 if (!result.has_value()) {
1028 const bool isTimeout = (result.error().code() == ETIMEDOUT);
1029 *rcode = (isTimeout) ? RCODE_TIMEOUT : *rcode;
1030 *gotsomewhere = (isTimeout) ? 1 : *gotsomewhere;
1031 // Leave the UDP sockets open on timeout so we can keep listening for
1032 // a late response from this server while retrying on the next server.
1033 if (!isTimeout) statp->closeSockets();
1034 LOG(DEBUG) << __func__ << ": " << (isTimeout) ? "timeout" : "poll";
1035 return 0;
1036 }
1037 bool needRetry = false;
1038 for (int fd : result.value()) {
1039 needRetry = false;
1040 sockaddr_storage from;
1041 socklen_t fromlen = sizeof(from);
1042 int resplen =
1043 recvfrom(fd, (char*)ans, (size_t)anssiz, 0, (sockaddr*)(void*)&from, &fromlen);
1044 if (resplen <= 0) {
1045 PLOG(DEBUG) << __func__ << ": recvfrom: ";
1046 continue;
1047 }
Luke Huangbff43fc2019-11-12 15:54:47 +08001048 *gotsomewhere = 1;
Luke Huang3caa42b2020-04-23 14:18:04 +00001049 if (resplen < HFIXEDSZ) {
1050 // Undersized message.
1051 LOG(DEBUG) << __func__ << ": undersized: " << resplen;
1052 *terrno = EMSGSIZE;
1053 continue;
1054 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001055
Luke Huang3caa42b2020-04-23 14:18:04 +00001056 int receivedFromNs = *ns;
1057 if (needRetry =
1058 ignoreInvalidAnswer(statp, from, buf, buflen, ans, anssiz, &receivedFromNs);
1059 needRetry) {
1060 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
1061 continue;
1062 }
Luke Huangbff43fc2019-11-12 15:54:47 +08001063
Luke Huang3caa42b2020-04-23 14:18:04 +00001064 HEADER* anhp = (HEADER*)(void*)ans;
1065 if (anhp->rcode == FORMERR && (statp->netcontext_flags & NET_CONTEXT_FLAG_USE_EDNS)) {
1066 // Do not retry if the server do not understand EDNS0.
1067 // The case has to be captured here, as FORMERR packet do not
1068 // carry query section, hence res_queriesmatch() returns 0.
1069 LOG(DEBUG) << __func__ << ": server rejected query with EDNS0:";
1070 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
1071 // record the error
1072 statp->_flags |= RES_F_EDNS0ERR;
1073 continue;
1074 }
Luke Huangbff43fc2019-11-12 15:54:47 +08001075
Luke Huang3caa42b2020-04-23 14:18:04 +00001076 timespec done = evNowTime();
1077 *delay = res_stats_calculate_rtt(&done, &start_time);
1078 if (anhp->rcode == SERVFAIL || anhp->rcode == NOTIMP || anhp->rcode == REFUSED) {
1079 LOG(DEBUG) << __func__ << ": server rejected query:";
1080 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
1081 *rcode = anhp->rcode;
1082 continue;
1083 }
1084 if (anhp->tc) {
1085 // To get the rest of answer,
1086 // use TCP with same server.
1087 LOG(DEBUG) << __func__ << ": truncated answer";
1088 *v_circuit = 1;
1089 return 1;
1090 }
1091 // All is well, or the error is fatal. Signal that the
1092 // next nameserver ought not be tried.
Luke Huangbff43fc2019-11-12 15:54:47 +08001093
Luke Huangbff43fc2019-11-12 15:54:47 +08001094 *rcode = anhp->rcode;
Luke Huang3caa42b2020-04-23 14:18:04 +00001095 *ns = receivedFromNs;
1096 return resplen;
Luke Huangbff43fc2019-11-12 15:54:47 +08001097 }
Luke Huang3caa42b2020-04-23 14:18:04 +00001098 if (!needRetry) return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001099 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001100}
1101
chenbruce018fdb22019-06-12 18:08:04 +08001102static void dump_error(const char* str, const struct sockaddr* address, int alen) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001103 char hbuf[NI_MAXHOST];
1104 char sbuf[NI_MAXSERV];
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001105 constexpr int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
Luke Huangc98fd802019-10-15 16:36:36 +09001106 const int err = errno;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001107
chenbruce018fdb22019-06-12 18:08:04 +08001108 if (!WOULD_LOG(DEBUG)) return;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001109
chenbruce018fdb22019-06-12 18:08:04 +08001110 if (getnameinfo(address, (socklen_t)alen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf), niflags)) {
1111 strncpy(hbuf, "?", sizeof(hbuf) - 1);
1112 hbuf[sizeof(hbuf) - 1] = '\0';
1113 strncpy(sbuf, "?", sizeof(sbuf) - 1);
1114 sbuf[sizeof(sbuf) - 1] = '\0';
Elliott Hughes3b8f5902019-03-08 12:02:55 -08001115 }
Luke Huangc98fd802019-10-15 16:36:36 +09001116 errno = err;
chenbruce018fdb22019-06-12 18:08:04 +08001117 PLOG(DEBUG) << __func__ << ": " << str << " ([" << hbuf << "]." << sbuf << "): ";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001118}
1119
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001120static int sock_eq(struct sockaddr* a, struct sockaddr* b) {
1121 struct sockaddr_in *a4, *b4;
1122 struct sockaddr_in6 *a6, *b6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001123
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001124 if (a->sa_family != b->sa_family) return 0;
1125 switch (a->sa_family) {
1126 case AF_INET:
1127 a4 = (struct sockaddr_in*) (void*) a;
1128 b4 = (struct sockaddr_in*) (void*) b;
1129 return a4->sin_port == b4->sin_port && a4->sin_addr.s_addr == b4->sin_addr.s_addr;
1130 case AF_INET6:
1131 a6 = (struct sockaddr_in6*) (void*) a;
1132 b6 = (struct sockaddr_in6*) (void*) b;
1133 return a6->sin6_port == b6->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001134#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001135 a6->sin6_scope_id == b6->sin6_scope_id &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001136#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001137 IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
1138 default:
1139 return 0;
1140 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001141}
Mike Yub601ff72018-11-01 20:07:00 +08001142
lifr6b83a6f2019-07-26 03:17:43 +08001143PrivateDnsModes convertEnumType(PrivateDnsMode privateDnsmode) {
1144 switch (privateDnsmode) {
1145 case PrivateDnsMode::OFF:
1146 return PrivateDnsModes::PDM_OFF;
1147 case PrivateDnsMode::OPPORTUNISTIC:
1148 return PrivateDnsModes::PDM_OPPORTUNISTIC;
1149 case PrivateDnsMode::STRICT:
1150 return PrivateDnsModes::PDM_STRICT;
Mike Yu99b8dc72019-11-22 17:45:31 +08001151 default:
1152 return PrivateDnsModes::PDM_UNKNOWN;
lifr6b83a6f2019-07-26 03:17:43 +08001153 }
lifr6b83a6f2019-07-26 03:17:43 +08001154}
1155
Luke Huangd7aa7b42018-11-21 20:37:50 +08001156static int res_tls_send(res_state statp, const Slice query, const Slice answer, int* rcode,
Mike Yubfb1b342018-11-06 15:42:36 +08001157 bool* fallback) {
1158 int resplen = 0;
Mike Yub601ff72018-11-01 20:07:00 +08001159 const unsigned netId = statp->netid;
Mike Yub601ff72018-11-01 20:07:00 +08001160
Mike Yubfb1b342018-11-06 15:42:36 +08001161 PrivateDnsStatus privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
lifr6b83a6f2019-07-26 03:17:43 +08001162 statp->event->set_private_dns_modes(convertEnumType(privateDnsStatus.mode));
Mike Yubfb1b342018-11-06 15:42:36 +08001163
1164 if (privateDnsStatus.mode == PrivateDnsMode::OFF) {
1165 *fallback = true;
1166 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001167 }
1168
Mike Yu3e829062019-08-07 14:01:14 +08001169 if (privateDnsStatus.validatedServers().empty()) {
Mike Yub601ff72018-11-01 20:07:00 +08001170 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
Mike Yubfb1b342018-11-06 15:42:36 +08001171 *fallback = true;
1172 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001173 } else {
1174 // Sleep and iterate some small number of times checking for the
1175 // arrival of resolved and validated server IP addresses, instead
1176 // of returning an immediate error.
Mike Yu4f3747b2018-12-02 17:54:29 +09001177 // This is needed because as soon as a network becomes the default network, apps will
1178 // send DNS queries on that network. If no servers have yet validated, and we do not
1179 // block those queries, they would immediately fail, causing application-visible errors.
1180 // Note that this can happen even before the network validates, since an unvalidated
1181 // network can become the default network if no validated networks are available.
1182 //
1183 // TODO: see if there is a better way to address this problem, such as buffering the
1184 // queries in a queue or only blocking queries for the first few seconds after a default
1185 // network change.
Mike Yubfb1b342018-11-06 15:42:36 +08001186 for (int i = 0; i < 42; i++) {
1187 std::this_thread::sleep_for(std::chrono::milliseconds(100));
Mike Yu3e829062019-08-07 14:01:14 +08001188 // Calling getStatus() to merely check if there's any validated server seems
1189 // wasteful. Consider adding a new method in PrivateDnsConfiguration for speed ups.
1190 if (!gPrivateDnsConfiguration.getStatus(netId).validatedServers().empty()) {
Mike Yubfb1b342018-11-06 15:42:36 +08001191 privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
1192 break;
1193 }
1194 }
Mike Yu3e829062019-08-07 14:01:14 +08001195 if (privateDnsStatus.validatedServers().empty()) {
Mike Yubfb1b342018-11-06 15:42:36 +08001196 return -1;
1197 }
Mike Yub601ff72018-11-01 20:07:00 +08001198 }
1199 }
1200
chenbruceacb832c2019-02-20 19:45:50 +08001201 LOG(INFO) << __func__ << ": performing query over TLS";
Mike Yub601ff72018-11-01 20:07:00 +08001202
Mike Yu3e829062019-08-07 14:01:14 +08001203 const auto response = sDnsTlsDispatcher.query(privateDnsStatus.validatedServers(), statp, query,
Mike Yubfb1b342018-11-06 15:42:36 +08001204 answer, &resplen);
Mike Yub601ff72018-11-01 20:07:00 +08001205
chenbruceacb832c2019-02-20 19:45:50 +08001206 LOG(INFO) << __func__ << ": TLS query result: " << static_cast<int>(response);
Mike Yub601ff72018-11-01 20:07:00 +08001207
1208 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
1209 // In opportunistic mode, handle falling back to cleartext in some
1210 // cases (DNS shouldn't fail if a validated opportunistic mode server
1211 // becomes unreachable for some reason).
1212 switch (response) {
Mike Yubfb1b342018-11-06 15:42:36 +08001213 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001214 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001215 return resplen;
Mike Yub601ff72018-11-01 20:07:00 +08001216 case DnsTlsTransport::Response::network_error:
Mike Yubfb1b342018-11-06 15:42:36 +08001217 // No need to set the error timeout here since it will fallback to UDP.
Mike Yub601ff72018-11-01 20:07:00 +08001218 case DnsTlsTransport::Response::internal_error:
1219 // Note: this will cause cleartext queries to be emitted, with
1220 // all of the EDNS0 goodness enabled. Fingers crossed. :-/
Mike Yubfb1b342018-11-06 15:42:36 +08001221 *fallback = true;
1222 [[fallthrough]];
Mike Yub601ff72018-11-01 20:07:00 +08001223 default:
Mike Yubfb1b342018-11-06 15:42:36 +08001224 return -1;
1225 }
1226 } else {
1227 // Strict mode
1228 switch (response) {
1229 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001230 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001231 return resplen;
1232 case DnsTlsTransport::Response::network_error:
1233 // This case happens when the query stored in DnsTlsTransport is expired since
1234 // either 1) the query has been tried for 3 times but no response or 2) fail to
1235 // establish the connection with the server.
Luke Huangd7aa7b42018-11-21 20:37:50 +08001236 *rcode = RCODE_TIMEOUT;
Mike Yubfb1b342018-11-06 15:42:36 +08001237 [[fallthrough]];
1238 default:
1239 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001240 }
1241 }
Mike Yub601ff72018-11-01 20:07:00 +08001242}
Luke Huang4973a0d2018-11-19 20:17:26 +08001243
Luke Huangba7bef92018-12-26 16:53:03 +08001244int resolv_res_nsend(const android_net_context* netContext, const uint8_t* msg, int msgLen,
lifr94981782019-05-17 21:15:19 +08001245 uint8_t* ans, int ansLen, int* rcode, uint32_t flags,
1246 NetworkDnsEventReported* event) {
1247 assert(event != nullptr);
Bernie Innocenti08487112019-10-11 21:14:13 +09001248 ResState res;
1249 res_init(&res, netContext, event);
Mike Yu021c3e12019-10-08 17:29:34 +08001250 resolv_populate_res_for_net(&res);
Luke Huang4973a0d2018-11-19 20:17:26 +08001251 *rcode = NOERROR;
Bernie Innocenti08487112019-10-11 21:14:13 +09001252 return res_nsend(&res, msg, msgLen, ans, ansLen, rcode, flags);
Bernie Innocentiec4219b2019-01-30 11:16:36 +09001253}