blob: c78e02f84485f1f48640219735af9ef4bbd0c669 [file] [log] [blame]
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001/* $NetBSD: res_send.c,v 1.9 2006/01/24 17:41:25 christos Exp $ */
2
3/*
4 * Copyright (c) 1985, 1989, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. All advertising materials mentioning features or use of this software
16 * must display the following acknowledgement:
17 * This product includes software developed by the University of
18 * California, Berkeley and its contributors.
19 * 4. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 */
35
36/*
37 * Portions Copyright (c) 1993 by Digital Equipment Corporation.
38 *
39 * Permission to use, copy, modify, and distribute this software for any
40 * purpose with or without fee is hereby granted, provided that the above
41 * copyright notice and this permission notice appear in all copies, and that
42 * the name of Digital Equipment Corporation not be used in advertising or
43 * publicity pertaining to distribution of the document or software without
44 * specific, written prior permission.
45 *
46 * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
47 * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
48 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
49 * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
50 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
51 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
52 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
53 * SOFTWARE.
54 */
55
56/*
57 * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
58 * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
59 *
60 * Permission to use, copy, modify, and distribute this software for any
61 * purpose with or without fee is hereby granted, provided that the above
62 * copyright notice and this permission notice appear in all copies.
63 *
64 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
65 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
66 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR
67 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
68 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
69 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
70 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
71 */
72
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090073/*
74 * Send query to name server and wait for reply.
75 */
76
Ken Chen5471dca2019-04-15 15:25:35 +080077#define LOG_TAG "resolv"
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +090078
Luke Huangd1d734f2020-04-30 12:25:40 +080079#include <chrono>
80
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090081#include <sys/param.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090082#include <sys/socket.h>
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090083#include <sys/time.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090084#include <sys/uio.h>
85
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090086#include <arpa/inet.h>
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090087#include <arpa/nameser.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090088
89#include <errno.h>
90#include <fcntl.h>
91#include <netdb.h>
92#include <poll.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090093#include <signal.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090094#include <stdlib.h>
95#include <string.h>
96#include <time.h>
97#include <unistd.h>
98
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +090099#include <android-base/logging.h>
Luke Huang420ee622019-11-27 17:52:44 +0800100#include <android-base/result.h>
Bernie Innocenti758005f2019-02-19 18:08:36 +0900101#include <android/multinetwork.h> // ResNsendFlags
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900102
Mike Yub601ff72018-11-01 20:07:00 +0800103#include <netdutils/Slice.h>
lifr94981782019-05-17 21:15:19 +0800104#include <netdutils/Stopwatch.h>
Bernie Innocentiec4219b2019-01-30 11:16:36 +0900105#include "DnsTlsDispatcher.h"
106#include "DnsTlsTransport.h"
Luke Huangf40df9c2020-04-21 08:51:48 +0800107#include "Experiments.h"
Bernie Innocentiec4219b2019-01-30 11:16:36 +0900108#include "PrivateDnsConfiguration.h"
Bernie Innocentiac18b122018-10-01 23:10:18 +0900109#include "netd_resolv/resolv.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900110#include "private/android_filesystem_config.h"
Bernie Innocenti10a90282020-01-23 23:28:00 +0900111
112#include "res_comp.h"
Mike Yu34433c62019-08-20 20:17:36 +0800113#include "res_debug.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900114#include "resolv_cache.h"
Ken Chen99c0b322019-11-20 14:24:09 +0800115#include "stats.h"
lifr94981782019-05-17 21:15:19 +0800116#include "stats.pb.h"
Mike Yu021c3e12019-10-08 17:29:34 +0800117#include "util.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900118
Luke Huangd1d734f2020-04-30 12:25:40 +0800119using namespace std::chrono_literals;
Mike Yub601ff72018-11-01 20:07:00 +0800120// TODO: use the namespace something like android::netd_resolv for libnetd_resolv
Luke Huang420ee622019-11-27 17:52:44 +0800121using android::base::ErrnoError;
122using android::base::Result;
chenbruce99cbfd82019-09-05 15:08:13 +0800123using android::net::CacheStatus;
124using android::net::DnsQueryEvent;
125using android::net::DnsTlsDispatcher;
126using android::net::DnsTlsTransport;
chenbruce99cbfd82019-09-05 15:08:13 +0800127using android::net::IpVersion;
128using android::net::IV_IPV4;
129using android::net::IV_IPV6;
130using android::net::IV_UNKNOWN;
Luke Huang23d55192020-04-16 11:47:30 +0800131using android::net::LinuxErrno;
lifr94981782019-05-17 21:15:19 +0800132using android::net::NetworkDnsEventReported;
chenbruce99cbfd82019-09-05 15:08:13 +0800133using android::net::NS_T_INVALID;
134using android::net::NsRcode;
135using android::net::NsType;
Mike Yu60248242020-07-29 16:45:26 +0800136using android::net::PrivateDnsConfiguration;
chenbruce99cbfd82019-09-05 15:08:13 +0800137using android::net::PrivateDnsMode;
138using android::net::PrivateDnsModes;
139using android::net::PrivateDnsStatus;
140using android::net::PROTO_TCP;
141using android::net::PROTO_UDP;
Mike Yue655b1d2019-08-28 17:49:59 +0800142using android::netdutils::IPSockAddr;
Bernie Innocentiec4219b2019-01-30 11:16:36 +0900143using android::netdutils::Slice;
lifr94981782019-05-17 21:15:19 +0800144using android::netdutils::Stopwatch;
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900145
Mike Yue48f7b52020-02-10 14:55:06 +0800146static int send_vc(res_state statp, res_params* params, const uint8_t* buf, int buflen,
147 uint8_t* ans, int anssiz, int* terrno, size_t ns, time_t* at, int* rcode,
148 int* delay);
149static int send_dg(res_state statp, res_params* params, const uint8_t* buf, int buflen,
Luke Huang420ee622019-11-27 17:52:44 +0800150 uint8_t* ans, int anssiz, int* terrno, size_t* ns, int* v_circuit,
Mike Yue48f7b52020-02-10 14:55:06 +0800151 int* gotsomewhere, time_t* at, int* rcode, int* delay);
152
chenbruce018fdb22019-06-12 18:08:04 +0800153static void dump_error(const char*, const struct sockaddr*, int);
chenbruceacb832c2019-02-20 19:45:50 +0800154
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900155static int sock_eq(struct sockaddr*, struct sockaddr*);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900156static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
157 const struct timespec timeout);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900158static int retrying_poll(const int sock, short events, const struct timespec* finish);
Luke Huangd7aa7b42018-11-21 20:37:50 +0800159static int res_tls_send(res_state, const Slice query, const Slice answer, int* rcode,
Mike Yubfb1b342018-11-06 15:42:36 +0800160 bool* fallback);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900161
lifr94981782019-05-17 21:15:19 +0800162NsType getQueryType(const uint8_t* msg, size_t msgLen) {
163 ns_msg handle;
164 ns_rr rr;
165 if (ns_initparse((const uint8_t*)msg, msgLen, &handle) < 0 ||
166 ns_parserr(&handle, ns_s_qd, 0, &rr) < 0) {
167 return NS_T_INVALID;
168 }
169 return static_cast<NsType>(ns_rr_type(rr));
170}
171
172IpVersion ipFamilyToIPVersion(const int ipFamily) {
173 switch (ipFamily) {
174 case AF_INET:
175 return IV_IPV4;
176 case AF_INET6:
177 return IV_IPV6;
178 default:
179 return IV_UNKNOWN;
180 }
181}
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900182
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900183// BEGIN: Code copied from ISC eventlib
184// TODO: move away from this code
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900185#define BILLION 1000000000
186
187static struct timespec evConsTime(time_t sec, long nsec) {
188 struct timespec x;
189
190 x.tv_sec = sec;
191 x.tv_nsec = nsec;
192 return (x);
193}
194
195static struct timespec evAddTime(struct timespec addend1, struct timespec addend2) {
196 struct timespec x;
197
198 x.tv_sec = addend1.tv_sec + addend2.tv_sec;
199 x.tv_nsec = addend1.tv_nsec + addend2.tv_nsec;
200 if (x.tv_nsec >= BILLION) {
201 x.tv_sec++;
202 x.tv_nsec -= BILLION;
203 }
204 return (x);
205}
206
207static struct timespec evSubTime(struct timespec minuend, struct timespec subtrahend) {
208 struct timespec x;
209
210 x.tv_sec = minuend.tv_sec - subtrahend.tv_sec;
211 if (minuend.tv_nsec >= subtrahend.tv_nsec)
212 x.tv_nsec = minuend.tv_nsec - subtrahend.tv_nsec;
213 else {
214 x.tv_nsec = BILLION - subtrahend.tv_nsec + minuend.tv_nsec;
215 x.tv_sec--;
216 }
217 return (x);
218}
219
220static int evCmpTime(struct timespec a, struct timespec b) {
221#define SGN(x) ((x) < 0 ? (-1) : (x) > 0 ? (1) : (0));
222 time_t s = a.tv_sec - b.tv_sec;
223 long n;
224
225 if (s != 0) return SGN(s);
226
227 n = a.tv_nsec - b.tv_nsec;
228 return SGN(n);
229}
230
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900231static struct timespec evNowTime(void) {
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900232 struct timespec tsnow;
Bernie Innocentic1834822018-08-31 16:11:41 +0900233 clock_gettime(CLOCK_REALTIME, &tsnow);
234 return tsnow;
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900235}
236
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900237// END: Code copied from ISC eventlib
238
lifr94981782019-05-17 21:15:19 +0800239/* BIONIC-BEGIN: implement source port randomization */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900240static int random_bind(int s, int family) {
nuccachenb980f2f2018-10-23 17:10:58 +0800241 sockaddr_union u;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900242 int j;
243 socklen_t slen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900244
245 /* clear all, this also sets the IP4/6 address to 'any' */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900246 memset(&u, 0, sizeof u);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900247
248 switch (family) {
249 case AF_INET:
250 u.sin.sin_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900251 slen = sizeof u.sin;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900252 break;
253 case AF_INET6:
254 u.sin6.sin6_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900255 slen = sizeof u.sin6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900256 break;
257 default:
258 errno = EPROTO;
259 return -1;
260 }
261
262 /* first try to bind to a random source port a few times */
263 for (j = 0; j < 10; j++) {
264 /* find a random port between 1025 .. 65534 */
Luke Huangdda920f2019-02-13 14:05:02 +0800265 int port = 1025 + (arc4random_uniform(65535 - 1025));
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900266 if (family == AF_INET)
267 u.sin.sin_port = htons(port);
268 else
269 u.sin6.sin6_port = htons(port);
270
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900271 if (!bind(s, &u.sa, slen)) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900272 }
273
Bernie Innocenti9c575932018-09-07 21:10:25 +0900274 // nothing after 10 attempts, our network table is probably busy
275 // let the system decide which port is best
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900276 if (family == AF_INET)
277 u.sin.sin_port = 0;
278 else
279 u.sin6.sin6_port = 0;
280
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900281 return bind(s, &u.sa, slen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900282}
283/* BIONIC-END */
284
Luke Huang70931aa2019-01-31 11:57:41 +0800285// Disables all nameservers other than selectedServer
286static void res_set_usable_server(int selectedServer, int nscount, bool usable_servers[]) {
287 int usableIndex = 0;
288 for (int ns = 0; ns < nscount; ns++) {
289 if (usable_servers[ns]) ++usableIndex;
290 if (usableIndex != selectedServer) usable_servers[ns] = false;
291 }
292}
293
Luke Huang420ee622019-11-27 17:52:44 +0800294// Looks up the nameserver address in res.nsaddrs[], returns the ns number if found, otherwise -1.
295static int res_ourserver_p(res_state statp, const sockaddr* sa) {
Bernie Innocenti2e8540b2018-09-26 11:52:04 +0900296 const sockaddr_in *inp, *srv;
297 const sockaddr_in6 *in6p, *srv6;
Luke Huang420ee622019-11-27 17:52:44 +0800298 int ns = 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900299 switch (sa->sa_family) {
300 case AF_INET:
301 inp = (const struct sockaddr_in*) (const void*) sa;
Luke Huang420ee622019-11-27 17:52:44 +0800302
Mike Yue48f7b52020-02-10 14:55:06 +0800303 for (const IPSockAddr& ipsa : statp->nsaddrs) {
304 sockaddr_storage ss = ipsa;
305 srv = reinterpret_cast<sockaddr_in*>(&ss);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900306 if (srv->sin_family == inp->sin_family && srv->sin_port == inp->sin_port &&
307 (srv->sin_addr.s_addr == INADDR_ANY ||
308 srv->sin_addr.s_addr == inp->sin_addr.s_addr))
Luke Huang420ee622019-11-27 17:52:44 +0800309 return ns;
310 ++ns;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900311 }
312 break;
313 case AF_INET6:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900314 in6p = (const struct sockaddr_in6*) (const void*) sa;
Mike Yue48f7b52020-02-10 14:55:06 +0800315 for (const IPSockAddr& ipsa : statp->nsaddrs) {
316 sockaddr_storage ss = ipsa;
317 srv6 = reinterpret_cast<sockaddr_in6*>(&ss);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900318 if (srv6->sin6_family == in6p->sin6_family && srv6->sin6_port == in6p->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900319#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900320 (srv6->sin6_scope_id == 0 || srv6->sin6_scope_id == in6p->sin6_scope_id) &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900321#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900322 (IN6_IS_ADDR_UNSPECIFIED(&srv6->sin6_addr) ||
323 IN6_ARE_ADDR_EQUAL(&srv6->sin6_addr, &in6p->sin6_addr)))
Luke Huang420ee622019-11-27 17:52:44 +0800324 return ns;
325 ++ns;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900326 }
327 break;
328 default:
329 break;
330 }
Luke Huang420ee622019-11-27 17:52:44 +0800331 return -1;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900332}
333
334/* int
Bernie Innocenti9c575932018-09-07 21:10:25 +0900335 * res_nameinquery(name, type, cl, buf, eom)
336 * look for (name, type, cl) in the query section of packet (buf, eom)
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900337 * requires:
338 * buf + HFIXEDSZ <= eom
339 * returns:
340 * -1 : format error
341 * 0 : not found
342 * >0 : found
343 * author:
344 * paul vixie, 29may94
345 */
chenbrucec51f1212019-09-12 16:59:33 +0800346int res_nameinquery(const char* name, int type, int cl, const uint8_t* buf, const uint8_t* eom) {
347 const uint8_t* cp = buf + HFIXEDSZ;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900348 int qdcount = ntohs(((const HEADER*) (const void*) buf)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900349
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900350 while (qdcount-- > 0) {
351 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900352 int n = dn_expand(buf, eom, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900353 if (n < 0) return (-1);
354 cp += n;
355 if (cp + 2 * INT16SZ > eom) return (-1);
chenbruce0d470422019-03-28 18:44:37 +0800356 int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900357 cp += INT16SZ;
chenbruce0d470422019-03-28 18:44:37 +0800358 int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900359 cp += INT16SZ;
Bernie Innocenti9c575932018-09-07 21:10:25 +0900360 if (ttype == type && tclass == cl && ns_samename(tname, name) == 1) return (1);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900361 }
362 return (0);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900363}
364
365/* int
366 * res_queriesmatch(buf1, eom1, buf2, eom2)
367 * is there a 1:1 mapping of (name,type,class)
368 * in (buf1,eom1) and (buf2,eom2)?
369 * returns:
370 * -1 : format error
371 * 0 : not a 1:1 mapping
372 * >0 : is a 1:1 mapping
373 * author:
374 * paul vixie, 29may94
375 */
chenbrucec51f1212019-09-12 16:59:33 +0800376int res_queriesmatch(const uint8_t* buf1, const uint8_t* eom1, const uint8_t* buf2,
377 const uint8_t* eom2) {
378 const uint8_t* cp = buf1 + HFIXEDSZ;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900379 int qdcount = ntohs(((const HEADER*) (const void*) buf1)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900380
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900381 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2) return (-1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900382
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900383 /*
384 * Only header section present in replies to
385 * dynamic update packets.
386 */
387 if ((((const HEADER*) (const void*) buf1)->opcode == ns_o_update) &&
388 (((const HEADER*) (const void*) buf2)->opcode == ns_o_update))
389 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900390
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900391 if (qdcount != ntohs(((const HEADER*) (const void*) buf2)->qdcount)) return (0);
392 while (qdcount-- > 0) {
393 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900394 int n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900395 if (n < 0) return (-1);
396 cp += n;
397 if (cp + 2 * INT16SZ > eom1) return (-1);
chenbruce0d470422019-03-28 18:44:37 +0800398 int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900399 cp += INT16SZ;
chenbruce0d470422019-03-28 18:44:37 +0800400 int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900401 cp += INT16SZ;
402 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2)) return (0);
403 }
404 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900405}
406
lifr94981782019-05-17 21:15:19 +0800407static DnsQueryEvent* addDnsQueryEvent(NetworkDnsEventReported* event) {
408 return event->mutable_dns_query_events()->add_dns_query_event();
409}
410
Luke Huangeb618ef2020-05-26 14:17:02 +0800411static bool isNetworkRestricted(int terrno) {
412 // It's possible that system was in some network restricted mode, which blocked
413 // the operation of sending packet and resulted in EPERM errno.
414 // It would be no reason to keep retrying on that case.
415 // TODO: Check the system status to know if network restricted mode is
416 // enabled.
417 return (terrno == EPERM);
418}
419
chenbrucec51f1212019-09-12 16:59:33 +0800420int res_nsend(res_state statp, const uint8_t* buf, int buflen, uint8_t* ans, int anssiz, int* rcode,
Luke Huangd1d734f2020-04-30 12:25:40 +0800421 uint32_t flags, std::chrono::milliseconds sleepTimeMs) {
Luke Huang43cc1b12019-10-15 19:06:42 +0900422 LOG(DEBUG) << __func__;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900423
Luke Huang43cc1b12019-10-15 19:06:42 +0900424 // Should not happen
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900425 if (anssiz < HFIXEDSZ) {
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800426 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900427 errno = EINVAL;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800428 return -EINVAL;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900429 }
chenbrucedd210722019-03-06 13:52:43 +0800430 res_pquery(buf, buflen);
chenbruceacb832c2019-02-20 19:45:50 +0800431
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900432 int anslen = 0;
lifrd4d9fbb2019-07-31 20:18:35 +0800433 Stopwatch cacheStopwatch;
Luke Huang43cc1b12019-10-15 19:06:42 +0900434 ResolvCacheStatus cache_status =
435 resolv_cache_lookup(statp->netid, buf, buflen, ans, anssiz, &anslen, flags);
lifrd4d9fbb2019-07-31 20:18:35 +0800436 const int32_t cacheLatencyUs = saturate_cast<int32_t>(cacheStopwatch.timeTakenUs());
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900437 if (cache_status == RESOLV_CACHE_FOUND) {
Luke Huang83c9b4b2019-02-27 18:18:01 +0800438 HEADER* hp = (HEADER*)(void*)ans;
439 *rcode = hp->rcode;
lifr94981782019-05-17 21:15:19 +0800440 DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
441 dnsQueryEvent->set_latency_micros(cacheLatencyUs);
442 dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
lifre02d01c2019-12-31 17:24:57 +0800443 dnsQueryEvent->set_type(getQueryType(buf, buflen));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900444 return anslen;
445 } else if (cache_status != RESOLV_CACHE_UNSUPPORTED) {
446 // had a cache miss for a known network, so populate the thread private
447 // data so the normal resolve path can do its thing
Mike Yu021c3e12019-10-08 17:29:34 +0800448 resolv_populate_res_for_net(statp);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900449 }
Mike Yuecc52822020-02-14 14:36:46 +0800450 if (statp->nameserverCount() == 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900451 // We have no nameservers configured, so there's no point trying.
452 // Tell the cache the query failed, or any retries and anyone else asking the same
453 // question will block for PENDING_REQUEST_TIMEOUT seconds instead of failing fast.
Luke Huangba7bef92018-12-26 16:53:03 +0800454 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800455
456 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900457 errno = ESRCH;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800458 return -ESRCH;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900459 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900460
Luke Huangd1d734f2020-04-30 12:25:40 +0800461 // If parallel_lookup is enabled, it might be required to wait some time to avoid
462 // gateways drop packets if queries are sent too close together
463 if (sleepTimeMs != 0ms) {
464 std::this_thread::sleep_for(sleepTimeMs);
465 }
Luke Huang272cb192019-10-15 16:52:28 +0900466 // DoT
467 if (!(statp->netcontext_flags & NET_CONTEXT_FLAG_USE_LOCAL_NAMESERVERS)) {
468 bool fallback = false;
Luke Huang43cc1b12019-10-15 19:06:42 +0900469 int resplen = res_tls_send(statp, Slice(const_cast<uint8_t*>(buf), buflen),
470 Slice(ans, anssiz), rcode, &fallback);
Luke Huang272cb192019-10-15 16:52:28 +0900471 if (resplen > 0) {
472 LOG(DEBUG) << __func__ << ": got answer from DoT";
473 res_pquery(ans, resplen);
474 if (cache_status == RESOLV_CACHE_NOTFOUND) {
475 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
476 }
477 return resplen;
478 }
479 if (!fallback) {
480 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huang43cc1b12019-10-15 19:06:42 +0900481 return -ETIMEDOUT;
Luke Huang272cb192019-10-15 16:52:28 +0900482 }
483 }
484
Mike Yuc573a3d2020-02-07 20:15:15 +0800485 res_stats stats[MAXNS]{};
Bernie Innocenti758005f2019-02-19 18:08:36 +0900486 res_params params;
Mike Yuc573a3d2020-02-07 20:15:15 +0800487 int revision_id = resolv_cache_get_resolver_stats(statp->netid, &params, stats, statp->nsaddrs);
lifra1b37f12019-02-13 17:33:57 +0800488 if (revision_id < 0) {
489 // TODO: Remove errno once callers stop using it
490 errno = ESRCH;
491 return -ESRCH;
492 }
waynema0161acd2019-02-18 17:47:59 +0800493 bool usable_servers[MAXNS];
Luke Huang70931aa2019-01-31 11:57:41 +0800494 int usableServersCount = android_net_res_stats_get_usable_servers(
Mike Yuecc52822020-02-14 14:36:46 +0800495 &params, stats, statp->nameserverCount(), usable_servers);
Luke Huang70931aa2019-01-31 11:57:41 +0800496
Mike Yu61d17262020-02-15 18:56:22 +0800497 if (statp->sort_nameservers) {
498 // It's unnecessary to mark a DNS server as unusable since broken servers will be less
499 // likely to be chosen.
500 for (int i = 0; i < statp->nameserverCount(); i++) {
501 usable_servers[i] = true;
502 }
503 }
504
505 // TODO: Let it always choose the first nameserver when sort_nameservers is enabled.
Luke Huang70931aa2019-01-31 11:57:41 +0800506 if ((flags & ANDROID_RESOLV_NO_RETRY) && usableServersCount > 1) {
507 auto hp = reinterpret_cast<const HEADER*>(buf);
508
509 // Select a random server based on the query id
510 int selectedServer = (hp->id % usableServersCount) + 1;
Mike Yuecc52822020-02-14 14:36:46 +0800511 res_set_usable_server(selectedServer, statp->nameserverCount(), usable_servers);
Luke Huang70931aa2019-01-31 11:57:41 +0800512 }
waynema0161acd2019-02-18 17:47:59 +0800513
Luke Huang43cc1b12019-10-15 19:06:42 +0900514 // Send request, RETRY times, or until successful.
waynemaa74195e2019-01-18 14:02:31 +0800515 int retryTimes = (flags & ANDROID_RESOLV_NO_RETRY) ? 1 : params.retry_count;
Luke Huang43cc1b12019-10-15 19:06:42 +0900516 int useTcp = buflen > PACKETSZ;
517 int gotsomewhere = 0;
Luke Huang23d55192020-04-16 11:47:30 +0800518 // Use an impossible error code as default value
519 int terrno = ETIME;
Luke Huangba7bef92018-12-26 16:53:03 +0800520
521 for (int attempt = 0; attempt < retryTimes; ++attempt) {
Mike Yue48f7b52020-02-10 14:55:06 +0800522 for (size_t ns = 0; ns < statp->nsaddrs.size(); ++ns) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900523 if (!usable_servers[ns]) continue;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900524
Luke Huang43cc1b12019-10-15 19:06:42 +0900525 *rcode = RCODE_INTERNAL_ERROR;
526
527 // Get server addr
Mike Yue48f7b52020-02-10 14:55:06 +0800528 const IPSockAddr& serverSockAddr = statp->nsaddrs[ns];
529 LOG(DEBUG) << __func__ << ": Querying server (# " << ns + 1
530 << ") address = " << serverSockAddr.toString();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900531
Luke Huang43cc1b12019-10-15 19:06:42 +0900532 ::android::net::Protocol query_proto = useTcp ? PROTO_TCP : PROTO_UDP;
Luke Huang420ee622019-11-27 17:52:44 +0800533 time_t query_time = 0;
Luke Huang43cc1b12019-10-15 19:06:42 +0900534 int delay = 0;
535 bool fallbackTCP = false;
536 const bool shouldRecordStats = (attempt == 0);
537 int resplen;
lifrd4d9fbb2019-07-31 20:18:35 +0800538 Stopwatch queryStopwatch;
lifr128183a2020-01-08 18:04:50 +0800539 int retry_count_for_event = 0;
Luke Huang420ee622019-11-27 17:52:44 +0800540 size_t actualNs = ns;
Luke Huang23d55192020-04-16 11:47:30 +0800541 // Use an impossible error code as default value
542 terrno = ETIME;
Luke Huang43cc1b12019-10-15 19:06:42 +0900543 if (useTcp) {
544 // TCP; at most one attempt per server.
Luke Huangba7bef92018-12-26 16:53:03 +0800545 attempt = retryTimes;
Luke Huang420ee622019-11-27 17:52:44 +0800546 resplen = send_vc(statp, &params, buf, buflen, ans, anssiz, &terrno, ns,
547 &query_time, rcode, &delay);
Ken Chen99344882020-01-01 14:59:38 +0800548
549 if (buflen <= PACKETSZ && resplen <= 0 &&
550 statp->tc_mode == aidl::android::net::IDnsResolver::TC_MODE_UDP_TCP) {
551 // reset to UDP for next query on next DNS server if resolver is currently doing
552 // TCP fallback retry and current server does not support TCP connectin
553 useTcp = false;
554 }
Luke Huangeb618ef2020-05-26 14:17:02 +0800555 LOG(INFO) << __func__ << ": used send_vc " << resplen << " terrno: " << terrno;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900556 } else {
Luke Huang43cc1b12019-10-15 19:06:42 +0900557 // UDP
Luke Huang420ee622019-11-27 17:52:44 +0800558 resplen = send_dg(statp, &params, buf, buflen, ans, anssiz, &terrno, &actualNs,
559 &useTcp, &gotsomewhere, &query_time, rcode, &delay);
Luke Huang43cc1b12019-10-15 19:06:42 +0900560 fallbackTCP = useTcp ? true : false;
lifr128183a2020-01-08 18:04:50 +0800561 retry_count_for_event = attempt;
Luke Huangeb618ef2020-05-26 14:17:02 +0800562 LOG(INFO) << __func__ << ": used send_dg " << resplen << " terrno: " << terrno;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900563 }
Luke Huang43cc1b12019-10-15 19:06:42 +0900564
Luke Huang420ee622019-11-27 17:52:44 +0800565 const IPSockAddr& receivedServerAddr = statp->nsaddrs[actualNs];
Luke Huang43cc1b12019-10-15 19:06:42 +0900566 DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
567 dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
Luke Huang420ee622019-11-27 17:52:44 +0800568 // When |retryTimes| > 1, we cannot actually know the correct latency value if we
569 // received the answer from the previous server. So temporarily set the latency as -1 if
570 // that condition happened.
571 // TODO: make the latency value accurate.
572 dnsQueryEvent->set_latency_micros(
573 (actualNs == ns) ? saturate_cast<int32_t>(queryStopwatch.timeTakenUs()) : -1);
574 dnsQueryEvent->set_dns_server_index(actualNs);
575 dnsQueryEvent->set_ip_version(ipFamilyToIPVersion(receivedServerAddr.family()));
lifr128183a2020-01-08 18:04:50 +0800576 dnsQueryEvent->set_retry_times(retry_count_for_event);
Luke Huang43cc1b12019-10-15 19:06:42 +0900577 dnsQueryEvent->set_rcode(static_cast<NsRcode>(*rcode));
578 dnsQueryEvent->set_protocol(query_proto);
579 dnsQueryEvent->set_type(getQueryType(buf, buflen));
Luke Huang23d55192020-04-16 11:47:30 +0800580 dnsQueryEvent->set_linux_errno(static_cast<LinuxErrno>(terrno));
Luke Huang43cc1b12019-10-15 19:06:42 +0900581
582 // Only record stats the first time we try a query. This ensures that
583 // queries that deterministically fail (e.g., a name that always returns
584 // SERVFAIL or times out) do not unduly affect the stats.
585 if (shouldRecordStats) {
Luke Huangeb618ef2020-05-26 14:17:02 +0800586 // (b/151166599): This is a workaround to prevent that DnsResolver calculates the
587 // reliability of DNS servers from being broken when network restricted mode is
588 // enabled.
589 // TODO: Introduce the new server selection instead of skipping stats recording.
590 if (!isNetworkRestricted(terrno)) {
591 res_sample sample;
592 res_stats_set_sample(&sample, query_time, *rcode, delay);
593 // KeepListening UDP mechanism is incompatible with usable_servers of legacy
594 // stats, so keep the old logic for now.
595 // TODO: Replace usable_servers of legacy stats with new one.
596 resolv_cache_add_resolver_stats_sample(
597 statp->netid, revision_id, serverSockAddr, sample, params.max_samples);
598 }
Luke Huang420ee622019-11-27 17:52:44 +0800599 resolv_stats_add(statp->netid, receivedServerAddr, dnsQueryEvent);
Luke Huang43cc1b12019-10-15 19:06:42 +0900600 }
601
602 if (resplen == 0) continue;
603 if (fallbackTCP) {
604 ns--;
605 continue;
606 }
607 if (resplen < 0) {
608 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800609 statp->closeSockets();
Luke Huang43cc1b12019-10-15 19:06:42 +0900610 return -terrno;
611 };
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900612
Ken Chenffc224a2019-03-19 17:41:28 +0800613 LOG(DEBUG) << __func__ << ": got answer:";
chenbrucedd210722019-03-06 13:52:43 +0800614 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900615
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900616 if (cache_status == RESOLV_CACHE_NOTFOUND) {
Mike Yud1ec2542019-06-06 17:17:53 +0800617 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900618 }
Luke Huangadb0f5b2019-11-27 15:51:48 +0800619 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900620 return (resplen);
Bernie Innocenti9c575932018-09-07 21:10:25 +0900621 } // for each ns
622 } // for each retry
Luke Huangadb0f5b2019-11-27 15:51:48 +0800623 statp->closeSockets();
Luke Huang43cc1b12019-10-15 19:06:42 +0900624 terrno = useTcp ? terrno : gotsomewhere ? ETIMEDOUT : ECONNREFUSED;
625 // TODO: Remove errno once callers stop using it
626 errno = useTcp ? terrno
627 : gotsomewhere ? ETIMEDOUT /* no answer obtained */
628 : ECONNREFUSED /* no nameservers found */;
629
Luke Huangba7bef92018-12-26 16:53:03 +0800630 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800631 return -terrno;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900632}
633
chenbruce99cbfd82019-09-05 15:08:13 +0800634static struct timespec get_timeout(res_state statp, const res_params* params, const int ns) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900635 int msec;
waynemaa74195e2019-01-18 14:02:31 +0800636 // Legacy algorithm which scales the timeout by nameserver number.
637 // For instance, with 4 nameservers: 5s, 2.5s, 5s, 10s
638 // This has no effect with 1 or 2 nameservers
639 msec = params->base_timeout_msec << ns;
640 if (ns > 0) {
Mike Yuecc52822020-02-14 14:36:46 +0800641 msec /= statp->nameserverCount();
waynemaa74195e2019-01-18 14:02:31 +0800642 }
643 // For safety, don't allow OEMs and experiments to configure a timeout shorter than 1s.
644 if (msec < 1000) {
645 msec = 1000; // Use at least 1000ms
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900646 }
Ken Chenffc224a2019-03-19 17:41:28 +0800647 LOG(INFO) << __func__ << ": using timeout of " << msec << " msec";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900648
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900649 struct timespec result;
650 result.tv_sec = msec / 1000;
651 result.tv_nsec = (msec % 1000) * 1000000;
652 return result;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900653}
654
chenbrucec51f1212019-09-12 16:59:33 +0800655static int send_vc(res_state statp, res_params* params, const uint8_t* buf, int buflen,
Mike Yue48f7b52020-02-10 14:55:06 +0800656 uint8_t* ans, int anssiz, int* terrno, size_t ns, time_t* at, int* rcode,
chenbrucec51f1212019-09-12 16:59:33 +0800657 int* delay) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900658 *at = time(NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900659 *delay = 0;
660 const HEADER* hp = (const HEADER*) (const void*) buf;
661 HEADER* anhp = (HEADER*) (void*) ans;
662 struct sockaddr* nsap;
663 int nsaplen;
chenbruce0d470422019-03-28 18:44:37 +0800664 int truncating, connreset, n;
chenbrucec51f1212019-09-12 16:59:33 +0800665 uint8_t* cp;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900666
Ken Chenffc224a2019-03-19 17:41:28 +0800667 LOG(INFO) << __func__ << ": using send_vc";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900668
Mike Yue48f7b52020-02-10 14:55:06 +0800669 // It should never happen, but just in case.
670 if (ns >= statp->nsaddrs.size()) {
671 LOG(ERROR) << __func__ << ": Out-of-bound indexing: " << ns;
Luke Huang23d55192020-04-16 11:47:30 +0800672 *terrno = EINVAL;
Mike Yue48f7b52020-02-10 14:55:06 +0800673 return -1;
674 }
675
676 sockaddr_storage ss = statp->nsaddrs[ns];
677 nsap = reinterpret_cast<sockaddr*>(&ss);
Mike Yu021c3e12019-10-08 17:29:34 +0800678 nsaplen = sockaddrSize(nsap);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900679
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900680 connreset = 0;
681same_ns:
682 truncating = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900683
Luke Huang420ee622019-11-27 17:52:44 +0800684 struct timespec start_time = evNowTime();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900685
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900686 /* Are we still talking to whom we want to talk to? */
Luke Huangadb0f5b2019-11-27 15:51:48 +0800687 if (statp->tcp_nssock >= 0 && (statp->_flags & RES_F_VC) != 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900688 struct sockaddr_storage peer;
689 socklen_t size = sizeof peer;
690 unsigned old_mark;
691 socklen_t mark_size = sizeof(old_mark);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800692 if (getpeername(statp->tcp_nssock, (struct sockaddr*)(void*)&peer, &size) < 0 ||
693 !sock_eq((struct sockaddr*)(void*)&peer, nsap) ||
694 getsockopt(statp->tcp_nssock, SOL_SOCKET, SO_MARK, &old_mark, &mark_size) < 0 ||
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900695 old_mark != statp->_mark) {
Luke Huangadb0f5b2019-11-27 15:51:48 +0800696 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900697 }
698 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900699
Luke Huangadb0f5b2019-11-27 15:51:48 +0800700 if (statp->tcp_nssock < 0 || (statp->_flags & RES_F_VC) == 0) {
701 if (statp->tcp_nssock >= 0) statp->closeSockets();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900702
Luke Huangadb0f5b2019-11-27 15:51:48 +0800703 statp->tcp_nssock.reset(socket(nsap->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0));
704 if (statp->tcp_nssock < 0) {
Luke Huang23d55192020-04-16 11:47:30 +0800705 *terrno = errno;
706 PLOG(DEBUG) << __func__ << ": socket(vc): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900707 switch (errno) {
708 case EPROTONOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900709 case EPFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900710 case EAFNOSUPPORT:
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900711 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900712 default:
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900713 return -1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900714 }
715 }
Ken Chenbc481b82020-05-21 23:30:01 +0800716 const uid_t uid = statp->enforce_dns_uid ? AID_DNS : statp->uid;
717 resolv_tag_socket(statp->tcp_nssock, uid, statp->pid);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900718 if (statp->_mark != MARK_UNSET) {
Luke Huangadb0f5b2019-11-27 15:51:48 +0800719 if (setsockopt(statp->tcp_nssock, SOL_SOCKET, SO_MARK, &statp->_mark,
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900720 sizeof(statp->_mark)) < 0) {
721 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800722 PLOG(DEBUG) << __func__ << ": setsockopt: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900723 return -1;
724 }
725 }
726 errno = 0;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800727 if (random_bind(statp->tcp_nssock, nsap->sa_family) < 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900728 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800729 dump_error("bind/vc", nsap, nsaplen);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800730 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900731 return (0);
732 }
Luke Huangadb0f5b2019-11-27 15:51:48 +0800733 if (connect_with_timeout(statp->tcp_nssock, nsap, (socklen_t)nsaplen,
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900734 get_timeout(statp, params, ns)) < 0) {
735 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800736 dump_error("connect/vc", nsap, nsaplen);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800737 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900738 /*
739 * The way connect_with_timeout() is implemented prevents us from reliably
740 * determining whether this was really a timeout or e.g. ECONNREFUSED. Since
741 * currently both cases are handled in the same way, there is no need to
742 * change this (yet). If we ever need to reliably distinguish between these
743 * cases, both connect_with_timeout() and retrying_poll() need to be
744 * modified, though.
745 */
746 *rcode = RCODE_TIMEOUT;
747 return (0);
748 }
749 statp->_flags |= RES_F_VC;
750 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900751
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900752 /*
753 * Send length & message
754 */
chenbruce0d470422019-03-28 18:44:37 +0800755 uint16_t len = htons(static_cast<uint16_t>(buflen));
Luke Huangc98fd802019-10-15 16:36:36 +0900756 const iovec iov[] = {
757 {.iov_base = &len, .iov_len = INT16SZ},
758 {.iov_base = const_cast<uint8_t*>(buf), .iov_len = static_cast<size_t>(buflen)},
759 };
Luke Huangadb0f5b2019-11-27 15:51:48 +0800760 if (writev(statp->tcp_nssock, iov, 2) != (INT16SZ + buflen)) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900761 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800762 PLOG(DEBUG) << __func__ << ": write failed: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800763 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900764 return (0);
765 }
766 /*
767 * Receive length & response
768 */
769read_len:
770 cp = ans;
771 len = INT16SZ;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800772 while ((n = read(statp->tcp_nssock, (char*)cp, (size_t)len)) > 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900773 cp += n;
774 if ((len -= n) == 0) break;
775 }
776 if (n <= 0) {
777 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800778 PLOG(DEBUG) << __func__ << ": read failed: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800779 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900780 /*
781 * A long running process might get its TCP
782 * connection reset if the remote server was
783 * restarted. Requery the server instead of
784 * trying a new one. When there is only one
785 * server, this means that a query might work
786 * instead of failing. We only allow one reset
787 * per query to prevent looping.
788 */
789 if (*terrno == ECONNRESET && !connreset) {
790 connreset = 1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900791 goto same_ns;
792 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900793 return (0);
794 }
chenbruce0d470422019-03-28 18:44:37 +0800795 uint16_t resplen = ntohs(*reinterpret_cast<const uint16_t*>(ans));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900796 if (resplen > anssiz) {
Ken Chenffc224a2019-03-19 17:41:28 +0800797 LOG(DEBUG) << __func__ << ": response truncated";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900798 truncating = 1;
799 len = anssiz;
800 } else
801 len = resplen;
802 if (len < HFIXEDSZ) {
803 /*
804 * Undersized message.
805 */
Ken Chenffc224a2019-03-19 17:41:28 +0800806 LOG(DEBUG) << __func__ << ": undersized: " << len;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900807 *terrno = EMSGSIZE;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800808 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900809 return (0);
810 }
811 cp = ans;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800812 while (len != 0 && (n = read(statp->tcp_nssock, (char*)cp, (size_t)len)) > 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900813 cp += n;
814 len -= n;
815 }
816 if (n <= 0) {
817 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800818 PLOG(DEBUG) << __func__ << ": read(vc): ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800819 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900820 return (0);
821 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900822
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900823 if (truncating) {
824 /*
825 * Flush rest of answer so connection stays in synch.
826 */
827 anhp->tc = 1;
828 len = resplen - anssiz;
829 while (len != 0) {
830 char junk[PACKETSZ];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900831
Luke Huangadb0f5b2019-11-27 15:51:48 +0800832 n = read(statp->tcp_nssock, junk, (len > sizeof junk) ? sizeof junk : len);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900833 if (n > 0)
834 len -= n;
835 else
836 break;
837 }
Ken Chena9e6f1d2020-07-30 13:24:16 +0800838 LOG(WARNING) << __func__ << ": resplen " << resplen << " exceeds buf size " << anssiz;
839 // return size should never exceed container size
840 resplen = anssiz;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900841 }
842 /*
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900843 * If the calling application has bailed out of
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900844 * a previous call and failed to arrange to have
845 * the circuit closed or the server has got
846 * itself confused, then drop the packet and
847 * wait for the correct one.
848 */
849 if (hp->id != anhp->id) {
Ken Chenffc224a2019-03-19 17:41:28 +0800850 LOG(DEBUG) << __func__ << ": ld answer (unexpected):";
Ken Chena9e6f1d2020-07-30 13:24:16 +0800851 res_pquery(ans, resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900852 goto read_len;
853 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900854
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900855 /*
856 * All is well, or the error is fatal. Signal that the
857 * next nameserver ought not be tried.
858 */
859 if (resplen > 0) {
860 struct timespec done = evNowTime();
Luke Huang420ee622019-11-27 17:52:44 +0800861 *delay = res_stats_calculate_rtt(&done, &start_time);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900862 *rcode = anhp->rcode;
863 }
Luke Huang23d55192020-04-16 11:47:30 +0800864 *terrno = 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900865 return (resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900866}
867
868/* return -1 on error (errno set), 0 on success */
Luke Huangc98fd802019-10-15 16:36:36 +0900869static int connect_with_timeout(int sock, const sockaddr* nsap, socklen_t salen,
870 const timespec timeout) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900871 int res, origflags;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900872
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900873 origflags = fcntl(sock, F_GETFL, 0);
874 fcntl(sock, F_SETFL, origflags | O_NONBLOCK);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900875
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900876 res = connect(sock, nsap, salen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900877 if (res < 0 && errno != EINPROGRESS) {
878 res = -1;
879 goto done;
880 }
881 if (res != 0) {
Luke Huangc98fd802019-10-15 16:36:36 +0900882 timespec now = evNowTime();
883 timespec finish = evAddTime(now, timeout);
Ken Chenffc224a2019-03-19 17:41:28 +0800884 LOG(INFO) << __func__ << ": " << sock << " send_vc";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900885 res = retrying_poll(sock, POLLIN | POLLOUT, &finish);
886 if (res <= 0) {
887 res = -1;
888 }
889 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900890done:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900891 fcntl(sock, F_SETFL, origflags);
Ken Chenffc224a2019-03-19 17:41:28 +0800892 LOG(INFO) << __func__ << ": " << sock << " connect_with_const timeout returning " << res;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900893 return res;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900894}
895
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900896static int retrying_poll(const int sock, const short events, const struct timespec* finish) {
897 struct timespec now, timeout;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900898
899retry:
Ken Chenffc224a2019-03-19 17:41:28 +0800900 LOG(INFO) << __func__ << ": " << sock << " retrying_poll";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900901
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900902 now = evNowTime();
903 if (evCmpTime(*finish, now) > 0)
904 timeout = evSubTime(*finish, now);
905 else
906 timeout = evConsTime(0L, 0L);
907 struct pollfd fds = {.fd = sock, .events = events};
Maciej Żenczykowski88f87552020-04-23 08:48:36 -0700908 int n = ppoll(&fds, 1, &timeout, /*__mask=*/NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900909 if (n == 0) {
Luke Huang420ee622019-11-27 17:52:44 +0800910 LOG(INFO) << __func__ << ": " << sock << " retrying_poll timeout";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900911 errno = ETIMEDOUT;
912 return 0;
913 }
914 if (n < 0) {
915 if (errno == EINTR) goto retry;
Ken Chenffc224a2019-03-19 17:41:28 +0800916 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll failed";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900917 return n;
918 }
919 if (fds.revents & (POLLIN | POLLOUT | POLLERR)) {
920 int error;
921 socklen_t len = sizeof(error);
922 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error) {
923 errno = error;
Ken Chenffc224a2019-03-19 17:41:28 +0800924 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll getsockopt failed";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900925 return -1;
926 }
927 }
Ken Chenffc224a2019-03-19 17:41:28 +0800928 LOG(INFO) << __func__ << ": " << sock << " retrying_poll returning " << n;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900929 return n;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900930}
931
Luke Huang420ee622019-11-27 17:52:44 +0800932static std::vector<pollfd> extractUdpFdset(res_state statp, const short events = POLLIN) {
933 std::vector<pollfd> fdset(statp->nsaddrs.size());
934 for (size_t i = 0; i < statp->nsaddrs.size(); ++i) {
935 fdset[i] = {.fd = statp->nssocks[i], .events = events};
936 }
937 return fdset;
938}
939
940static Result<std::vector<int>> udpRetryingPoll(res_state statp, const timespec* finish) {
941 for (;;) {
942 LOG(DEBUG) << __func__ << ": poll";
943 timespec start_time = evNowTime();
944 timespec timeout = (evCmpTime(*finish, start_time) > 0) ? evSubTime(*finish, start_time)
945 : evConsTime(0L, 0L);
946 std::vector<pollfd> fdset = extractUdpFdset(statp);
Maciej Żenczykowski88f87552020-04-23 08:48:36 -0700947 const int n = ppoll(fdset.data(), fdset.size(), &timeout, /*__mask=*/nullptr);
Luke Huang420ee622019-11-27 17:52:44 +0800948 if (n <= 0) {
949 if (errno == EINTR && n < 0) continue;
950 if (n == 0) errno = ETIMEDOUT;
951 PLOG(INFO) << __func__ << ": failed";
952 return ErrnoError();
953 }
954 std::vector<int> fdsToRead;
955 for (const auto& pollfd : fdset) {
956 if (pollfd.revents & (POLLIN | POLLERR)) {
957 fdsToRead.push_back(pollfd.fd);
958 }
959 }
960 LOG(DEBUG) << __func__ << ": "
961 << " returning fd size: " << fdsToRead.size();
962 return fdsToRead;
963 }
964}
965
966static Result<std::vector<int>> udpRetryingPollWrapper(res_state statp, int ns,
967 const timespec* finish) {
Luke Huangf40df9c2020-04-21 08:51:48 +0800968 const bool keepListeningUdp =
969 android::net::Experiments::getInstance()->getFlag("keep_listening_udp", 0);
Luke Huang420ee622019-11-27 17:52:44 +0800970 if (keepListeningUdp) return udpRetryingPoll(statp, finish);
971
972 if (int n = retrying_poll(statp->nssocks[ns], POLLIN, finish); n <= 0) {
973 return ErrnoError();
974 }
975 return std::vector<int>{statp->nssocks[ns]};
976}
977
Luke Huangbff43fc2019-11-12 15:54:47 +0800978bool ignoreInvalidAnswer(res_state statp, const sockaddr_storage& from, const uint8_t* buf,
Luke Huang420ee622019-11-27 17:52:44 +0800979 int buflen, uint8_t* ans, int anssiz, int* receivedFromNs) {
Luke Huangbff43fc2019-11-12 15:54:47 +0800980 const HEADER* hp = (const HEADER*)(const void*)buf;
981 HEADER* anhp = (HEADER*)(void*)ans;
982 if (hp->id != anhp->id) {
983 // response from old query, ignore it.
984 LOG(DEBUG) << __func__ << ": old answer:";
985 return true;
986 }
Luke Huang420ee622019-11-27 17:52:44 +0800987 if (*receivedFromNs = res_ourserver_p(statp, (sockaddr*)(void*)&from); *receivedFromNs < 0) {
Luke Huangbff43fc2019-11-12 15:54:47 +0800988 // response from wrong server? ignore it.
989 LOG(DEBUG) << __func__ << ": not our server:";
990 return true;
991 }
992 if (!res_queriesmatch(buf, buf + buflen, ans, ans + anssiz)) {
993 // response contains wrong query? ignore it.
994 LOG(DEBUG) << __func__ << ": wrong query name:";
995 return true;
996 }
997 return false;
998}
999
chenbrucec51f1212019-09-12 16:59:33 +08001000static int send_dg(res_state statp, res_params* params, const uint8_t* buf, int buflen,
Luke Huang420ee622019-11-27 17:52:44 +08001001 uint8_t* ans, int anssiz, int* terrno, size_t* ns, int* v_circuit,
Mike Yue48f7b52020-02-10 14:55:06 +08001002 int* gotsomewhere, time_t* at, int* rcode, int* delay) {
1003 // It should never happen, but just in case.
Luke Huang420ee622019-11-27 17:52:44 +08001004 if (*ns >= statp->nsaddrs.size()) {
Mike Yue48f7b52020-02-10 14:55:06 +08001005 LOG(ERROR) << __func__ << ": Out-of-bound indexing: " << ns;
Luke Huang23d55192020-04-16 11:47:30 +08001006 *terrno = EINVAL;
Mike Yue48f7b52020-02-10 14:55:06 +08001007 return -1;
1008 }
1009
Luke Huangbff43fc2019-11-12 15:54:47 +08001010 *at = time(nullptr);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001011 *delay = 0;
Luke Huang420ee622019-11-27 17:52:44 +08001012 const sockaddr_storage ss = statp->nsaddrs[*ns];
Mike Yue48f7b52020-02-10 14:55:06 +08001013 const sockaddr* nsap = reinterpret_cast<const sockaddr*>(&ss);
Luke Huangbff43fc2019-11-12 15:54:47 +08001014 const int nsaplen = sockaddrSize(nsap);
1015
Luke Huang420ee622019-11-27 17:52:44 +08001016 if (statp->nssocks[*ns] == -1) {
1017 statp->nssocks[*ns].reset(socket(nsap->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0));
1018 if (statp->nssocks[*ns] < 0) {
Luke Huang23d55192020-04-16 11:47:30 +08001019 *terrno = errno;
1020 PLOG(DEBUG) << __func__ << ": socket(dg): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001021 switch (errno) {
1022 case EPROTONOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001023 case EPFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001024 case EAFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001025 return (0);
1026 default:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001027 return (-1);
1028 }
1029 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001030
Ken Chenbc481b82020-05-21 23:30:01 +08001031 const uid_t uid = statp->enforce_dns_uid ? AID_DNS : statp->uid;
1032 resolv_tag_socket(statp->nssocks[*ns], uid, statp->pid);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001033 if (statp->_mark != MARK_UNSET) {
Luke Huang420ee622019-11-27 17:52:44 +08001034 if (setsockopt(statp->nssocks[*ns], SOL_SOCKET, SO_MARK, &(statp->_mark),
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001035 sizeof(statp->_mark)) < 0) {
Luke Huang23d55192020-04-16 11:47:30 +08001036 *terrno = errno;
Luke Huangadb0f5b2019-11-27 15:51:48 +08001037 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001038 return -1;
1039 }
1040 }
chenbruceb9cce7b2019-07-15 16:14:53 +08001041 // Use a "connected" datagram socket to receive an ECONNREFUSED error
1042 // on the next socket operation when the server responds with an
1043 // ICMP port-unreachable error. This way we can detect the absence of
1044 // a nameserver without timing out.
Luke Huang420ee622019-11-27 17:52:44 +08001045 if (random_bind(statp->nssocks[*ns], nsap->sa_family) < 0) {
Luke Huang23d55192020-04-16 11:47:30 +08001046 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +08001047 dump_error("bind(dg)", nsap, nsaplen);
Luke Huangadb0f5b2019-11-27 15:51:48 +08001048 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001049 return (0);
1050 }
Luke Huang420ee622019-11-27 17:52:44 +08001051 if (connect(statp->nssocks[*ns], nsap, (socklen_t)nsaplen) < 0) {
Luke Huang23d55192020-04-16 11:47:30 +08001052 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +08001053 dump_error("connect(dg)", nsap, nsaplen);
Luke Huangadb0f5b2019-11-27 15:51:48 +08001054 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001055 return (0);
1056 }
Ken Chenffc224a2019-03-19 17:41:28 +08001057 LOG(DEBUG) << __func__ << ": new DG socket";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001058 }
Luke Huang420ee622019-11-27 17:52:44 +08001059 if (send(statp->nssocks[*ns], (const char*)buf, (size_t)buflen, 0) != buflen) {
Luke Huang23d55192020-04-16 11:47:30 +08001060 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +08001061 PLOG(DEBUG) << __func__ << ": send: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +08001062 statp->closeSockets();
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001063 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001064 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001065
Luke Huang420ee622019-11-27 17:52:44 +08001066 timespec timeout = get_timeout(statp, params, *ns);
1067 timespec start_time = evNowTime();
1068 timespec finish = evAddTime(start_time, timeout);
Luke Huangbff43fc2019-11-12 15:54:47 +08001069 for (;;) {
1070 // Wait for reply.
Luke Huang420ee622019-11-27 17:52:44 +08001071 auto result = udpRetryingPollWrapper(statp, *ns, &finish);
1072
1073 if (!result.has_value()) {
1074 const bool isTimeout = (result.error().code() == ETIMEDOUT);
1075 *rcode = (isTimeout) ? RCODE_TIMEOUT : *rcode;
Luke Huang23d55192020-04-16 11:47:30 +08001076 *terrno = (isTimeout) ? ETIMEDOUT : errno;
Luke Huang420ee622019-11-27 17:52:44 +08001077 *gotsomewhere = (isTimeout) ? 1 : *gotsomewhere;
1078 // Leave the UDP sockets open on timeout so we can keep listening for
1079 // a late response from this server while retrying on the next server.
1080 if (!isTimeout) statp->closeSockets();
1081 LOG(DEBUG) << __func__ << ": " << (isTimeout) ? "timeout" : "poll";
1082 return 0;
1083 }
1084 bool needRetry = false;
1085 for (int fd : result.value()) {
1086 needRetry = false;
1087 sockaddr_storage from;
1088 socklen_t fromlen = sizeof(from);
1089 int resplen =
1090 recvfrom(fd, (char*)ans, (size_t)anssiz, 0, (sockaddr*)(void*)&from, &fromlen);
1091 if (resplen <= 0) {
Luke Huang23d55192020-04-16 11:47:30 +08001092 *terrno = errno;
Luke Huang420ee622019-11-27 17:52:44 +08001093 PLOG(DEBUG) << __func__ << ": recvfrom: ";
1094 continue;
1095 }
Luke Huangbff43fc2019-11-12 15:54:47 +08001096 *gotsomewhere = 1;
Luke Huang420ee622019-11-27 17:52:44 +08001097 if (resplen < HFIXEDSZ) {
1098 // Undersized message.
1099 LOG(DEBUG) << __func__ << ": undersized: " << resplen;
1100 *terrno = EMSGSIZE;
1101 continue;
1102 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001103
Luke Huang420ee622019-11-27 17:52:44 +08001104 int receivedFromNs = *ns;
1105 if (needRetry =
1106 ignoreInvalidAnswer(statp, from, buf, buflen, ans, anssiz, &receivedFromNs);
1107 needRetry) {
1108 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
1109 continue;
1110 }
Luke Huangbff43fc2019-11-12 15:54:47 +08001111
Luke Huang420ee622019-11-27 17:52:44 +08001112 HEADER* anhp = (HEADER*)(void*)ans;
1113 if (anhp->rcode == FORMERR && (statp->netcontext_flags & NET_CONTEXT_FLAG_USE_EDNS)) {
1114 // Do not retry if the server do not understand EDNS0.
1115 // The case has to be captured here, as FORMERR packet do not
1116 // carry query section, hence res_queriesmatch() returns 0.
1117 LOG(DEBUG) << __func__ << ": server rejected query with EDNS0:";
1118 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
1119 // record the error
1120 statp->_flags |= RES_F_EDNS0ERR;
Luke Huang23d55192020-04-16 11:47:30 +08001121 *terrno = EREMOTEIO;
Luke Huang420ee622019-11-27 17:52:44 +08001122 continue;
1123 }
Luke Huangbff43fc2019-11-12 15:54:47 +08001124
Luke Huang420ee622019-11-27 17:52:44 +08001125 timespec done = evNowTime();
1126 *delay = res_stats_calculate_rtt(&done, &start_time);
1127 if (anhp->rcode == SERVFAIL || anhp->rcode == NOTIMP || anhp->rcode == REFUSED) {
1128 LOG(DEBUG) << __func__ << ": server rejected query:";
1129 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
1130 *rcode = anhp->rcode;
1131 continue;
1132 }
1133 if (anhp->tc) {
1134 // To get the rest of answer,
1135 // use TCP with same server.
1136 LOG(DEBUG) << __func__ << ": truncated answer";
Luke Huang23d55192020-04-16 11:47:30 +08001137 *terrno = E2BIG;
Luke Huang420ee622019-11-27 17:52:44 +08001138 *v_circuit = 1;
1139 return 1;
1140 }
1141 // All is well, or the error is fatal. Signal that the
1142 // next nameserver ought not be tried.
Luke Huangbff43fc2019-11-12 15:54:47 +08001143
Luke Huangbff43fc2019-11-12 15:54:47 +08001144 *rcode = anhp->rcode;
Luke Huang420ee622019-11-27 17:52:44 +08001145 *ns = receivedFromNs;
Luke Huang23d55192020-04-16 11:47:30 +08001146 *terrno = 0;
Luke Huang420ee622019-11-27 17:52:44 +08001147 return resplen;
Luke Huangbff43fc2019-11-12 15:54:47 +08001148 }
Luke Huang420ee622019-11-27 17:52:44 +08001149 if (!needRetry) return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001150 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001151}
1152
chenbruce018fdb22019-06-12 18:08:04 +08001153static void dump_error(const char* str, const struct sockaddr* address, int alen) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001154 char hbuf[NI_MAXHOST];
1155 char sbuf[NI_MAXSERV];
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001156 constexpr int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
Luke Huangc98fd802019-10-15 16:36:36 +09001157 const int err = errno;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001158
chenbruce018fdb22019-06-12 18:08:04 +08001159 if (!WOULD_LOG(DEBUG)) return;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001160
chenbruce018fdb22019-06-12 18:08:04 +08001161 if (getnameinfo(address, (socklen_t)alen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf), niflags)) {
1162 strncpy(hbuf, "?", sizeof(hbuf) - 1);
1163 hbuf[sizeof(hbuf) - 1] = '\0';
1164 strncpy(sbuf, "?", sizeof(sbuf) - 1);
1165 sbuf[sizeof(sbuf) - 1] = '\0';
Elliott Hughes3b8f5902019-03-08 12:02:55 -08001166 }
Luke Huangc98fd802019-10-15 16:36:36 +09001167 errno = err;
chenbruce018fdb22019-06-12 18:08:04 +08001168 PLOG(DEBUG) << __func__ << ": " << str << " ([" << hbuf << "]." << sbuf << "): ";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001169}
1170
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001171static int sock_eq(struct sockaddr* a, struct sockaddr* b) {
1172 struct sockaddr_in *a4, *b4;
1173 struct sockaddr_in6 *a6, *b6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001174
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001175 if (a->sa_family != b->sa_family) return 0;
1176 switch (a->sa_family) {
1177 case AF_INET:
1178 a4 = (struct sockaddr_in*) (void*) a;
1179 b4 = (struct sockaddr_in*) (void*) b;
1180 return a4->sin_port == b4->sin_port && a4->sin_addr.s_addr == b4->sin_addr.s_addr;
1181 case AF_INET6:
1182 a6 = (struct sockaddr_in6*) (void*) a;
1183 b6 = (struct sockaddr_in6*) (void*) b;
1184 return a6->sin6_port == b6->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001185#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001186 a6->sin6_scope_id == b6->sin6_scope_id &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001187#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001188 IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
1189 default:
1190 return 0;
1191 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001192}
Mike Yub601ff72018-11-01 20:07:00 +08001193
lifr6b83a6f2019-07-26 03:17:43 +08001194PrivateDnsModes convertEnumType(PrivateDnsMode privateDnsmode) {
1195 switch (privateDnsmode) {
1196 case PrivateDnsMode::OFF:
1197 return PrivateDnsModes::PDM_OFF;
1198 case PrivateDnsMode::OPPORTUNISTIC:
1199 return PrivateDnsModes::PDM_OPPORTUNISTIC;
1200 case PrivateDnsMode::STRICT:
1201 return PrivateDnsModes::PDM_STRICT;
Mike Yu99b8dc72019-11-22 17:45:31 +08001202 default:
1203 return PrivateDnsModes::PDM_UNKNOWN;
lifr6b83a6f2019-07-26 03:17:43 +08001204 }
lifr6b83a6f2019-07-26 03:17:43 +08001205}
1206
Luke Huangd7aa7b42018-11-21 20:37:50 +08001207static int res_tls_send(res_state statp, const Slice query, const Slice answer, int* rcode,
Mike Yubfb1b342018-11-06 15:42:36 +08001208 bool* fallback) {
1209 int resplen = 0;
Mike Yub601ff72018-11-01 20:07:00 +08001210 const unsigned netId = statp->netid;
Mike Yub601ff72018-11-01 20:07:00 +08001211
Mike Yu60248242020-07-29 16:45:26 +08001212 auto& privateDnsConfiguration = PrivateDnsConfiguration::getInstance();
1213 PrivateDnsStatus privateDnsStatus = privateDnsConfiguration.getStatus(netId);
lifr6b83a6f2019-07-26 03:17:43 +08001214 statp->event->set_private_dns_modes(convertEnumType(privateDnsStatus.mode));
Mike Yubfb1b342018-11-06 15:42:36 +08001215
1216 if (privateDnsStatus.mode == PrivateDnsMode::OFF) {
1217 *fallback = true;
1218 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001219 }
1220
Mike Yu3e829062019-08-07 14:01:14 +08001221 if (privateDnsStatus.validatedServers().empty()) {
Mike Yub601ff72018-11-01 20:07:00 +08001222 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
Mike Yubfb1b342018-11-06 15:42:36 +08001223 *fallback = true;
1224 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001225 } else {
1226 // Sleep and iterate some small number of times checking for the
1227 // arrival of resolved and validated server IP addresses, instead
1228 // of returning an immediate error.
Mike Yu4f3747b2018-12-02 17:54:29 +09001229 // This is needed because as soon as a network becomes the default network, apps will
1230 // send DNS queries on that network. If no servers have yet validated, and we do not
1231 // block those queries, they would immediately fail, causing application-visible errors.
1232 // Note that this can happen even before the network validates, since an unvalidated
1233 // network can become the default network if no validated networks are available.
1234 //
1235 // TODO: see if there is a better way to address this problem, such as buffering the
1236 // queries in a queue or only blocking queries for the first few seconds after a default
1237 // network change.
Mike Yubfb1b342018-11-06 15:42:36 +08001238 for (int i = 0; i < 42; i++) {
1239 std::this_thread::sleep_for(std::chrono::milliseconds(100));
Mike Yu3e829062019-08-07 14:01:14 +08001240 // Calling getStatus() to merely check if there's any validated server seems
1241 // wasteful. Consider adding a new method in PrivateDnsConfiguration for speed ups.
Mike Yu60248242020-07-29 16:45:26 +08001242 if (!privateDnsConfiguration.getStatus(netId).validatedServers().empty()) {
1243 privateDnsStatus = privateDnsConfiguration.getStatus(netId);
Mike Yubfb1b342018-11-06 15:42:36 +08001244 break;
1245 }
1246 }
Mike Yu3e829062019-08-07 14:01:14 +08001247 if (privateDnsStatus.validatedServers().empty()) {
Mike Yubfb1b342018-11-06 15:42:36 +08001248 return -1;
1249 }
Mike Yub601ff72018-11-01 20:07:00 +08001250 }
1251 }
1252
chenbruceacb832c2019-02-20 19:45:50 +08001253 LOG(INFO) << __func__ << ": performing query over TLS";
Mike Yub601ff72018-11-01 20:07:00 +08001254
Mike Yu9e8cf8d2020-10-26 19:04:33 +08001255 const auto response = DnsTlsDispatcher::getInstance().query(privateDnsStatus.validatedServers(),
1256 statp, query, answer, &resplen);
Mike Yub601ff72018-11-01 20:07:00 +08001257
chenbruceacb832c2019-02-20 19:45:50 +08001258 LOG(INFO) << __func__ << ": TLS query result: " << static_cast<int>(response);
Mike Yub601ff72018-11-01 20:07:00 +08001259
1260 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
1261 // In opportunistic mode, handle falling back to cleartext in some
1262 // cases (DNS shouldn't fail if a validated opportunistic mode server
1263 // becomes unreachable for some reason).
1264 switch (response) {
Mike Yubfb1b342018-11-06 15:42:36 +08001265 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001266 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001267 return resplen;
Mike Yub601ff72018-11-01 20:07:00 +08001268 case DnsTlsTransport::Response::network_error:
Mike Yubfb1b342018-11-06 15:42:36 +08001269 // No need to set the error timeout here since it will fallback to UDP.
Mike Yub601ff72018-11-01 20:07:00 +08001270 case DnsTlsTransport::Response::internal_error:
1271 // Note: this will cause cleartext queries to be emitted, with
1272 // all of the EDNS0 goodness enabled. Fingers crossed. :-/
Mike Yubfb1b342018-11-06 15:42:36 +08001273 *fallback = true;
1274 [[fallthrough]];
Mike Yub601ff72018-11-01 20:07:00 +08001275 default:
Mike Yubfb1b342018-11-06 15:42:36 +08001276 return -1;
1277 }
1278 } else {
1279 // Strict mode
1280 switch (response) {
1281 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001282 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001283 return resplen;
1284 case DnsTlsTransport::Response::network_error:
1285 // This case happens when the query stored in DnsTlsTransport is expired since
1286 // either 1) the query has been tried for 3 times but no response or 2) fail to
1287 // establish the connection with the server.
Luke Huangd7aa7b42018-11-21 20:37:50 +08001288 *rcode = RCODE_TIMEOUT;
Mike Yubfb1b342018-11-06 15:42:36 +08001289 [[fallthrough]];
1290 default:
1291 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001292 }
1293 }
Mike Yub601ff72018-11-01 20:07:00 +08001294}
Luke Huang4973a0d2018-11-19 20:17:26 +08001295
Luke Huangba7bef92018-12-26 16:53:03 +08001296int resolv_res_nsend(const android_net_context* netContext, const uint8_t* msg, int msgLen,
lifr94981782019-05-17 21:15:19 +08001297 uint8_t* ans, int ansLen, int* rcode, uint32_t flags,
1298 NetworkDnsEventReported* event) {
1299 assert(event != nullptr);
Luke Huang1b3f4462020-12-04 17:48:39 +08001300 ResState res(netContext, event);
Mike Yu021c3e12019-10-08 17:29:34 +08001301 resolv_populate_res_for_net(&res);
Luke Huang4973a0d2018-11-19 20:17:26 +08001302 *rcode = NOERROR;
Bernie Innocenti08487112019-10-11 21:14:13 +09001303 return res_nsend(&res, msg, msgLen, ans, ansLen, rcode, flags);
Bernie Innocentiec4219b2019-01-30 11:16:36 +09001304}