blob: 3b088b99f775ecbb7cd426120393cfbb6a2a3915 [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>
Bernie Innocenti758005f2019-02-19 18:08:36 +090098#include <android/multinetwork.h> // ResNsendFlags
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090099
Mike Yub601ff72018-11-01 20:07:00 +0800100#include <netdutils/Slice.h>
lifr94981782019-05-17 21:15:19 +0800101#include <netdutils/Stopwatch.h>
Bernie Innocentiec4219b2019-01-30 11:16:36 +0900102#include "DnsTlsDispatcher.h"
103#include "DnsTlsTransport.h"
104#include "PrivateDnsConfiguration.h"
Bernie Innocentiac18b122018-10-01 23:10:18 +0900105#include "netd_resolv/resolv.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900106#include "private/android_filesystem_config.h"
Mike Yu34433c62019-08-20 20:17:36 +0800107#include "res_debug.h"
Bernie Innocenti08487112019-10-11 21:14:13 +0900108#include "res_init.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900109#include "resolv_cache.h"
Ken Chen99c0b322019-11-20 14:24:09 +0800110#include "stats.h"
lifr94981782019-05-17 21:15:19 +0800111#include "stats.pb.h"
Mike Yu021c3e12019-10-08 17:29:34 +0800112#include "util.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900113
Mike Yub601ff72018-11-01 20:07:00 +0800114// TODO: use the namespace something like android::netd_resolv for libnetd_resolv
chenbruce99cbfd82019-09-05 15:08:13 +0800115using android::net::CacheStatus;
116using android::net::DnsQueryEvent;
117using android::net::DnsTlsDispatcher;
118using android::net::DnsTlsTransport;
119using android::net::gPrivateDnsConfiguration;
120using android::net::IpVersion;
121using android::net::IV_IPV4;
122using android::net::IV_IPV6;
123using android::net::IV_UNKNOWN;
lifr94981782019-05-17 21:15:19 +0800124using android::net::NetworkDnsEventReported;
chenbruce99cbfd82019-09-05 15:08:13 +0800125using android::net::NS_T_INVALID;
126using android::net::NsRcode;
127using android::net::NsType;
128using android::net::PrivateDnsMode;
129using android::net::PrivateDnsModes;
130using android::net::PrivateDnsStatus;
131using android::net::PROTO_TCP;
132using android::net::PROTO_UDP;
Mike Yue655b1d2019-08-28 17:49:59 +0800133using android::netdutils::IPSockAddr;
Bernie Innocentiec4219b2019-01-30 11:16:36 +0900134using android::netdutils::Slice;
lifr94981782019-05-17 21:15:19 +0800135using android::netdutils::Stopwatch;
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900136
Mike Yub601ff72018-11-01 20:07:00 +0800137static DnsTlsDispatcher sDnsTlsDispatcher;
138
Bernie Innocenti9c575932018-09-07 21:10:25 +0900139static struct sockaddr* get_nsaddr(res_state, size_t);
chenbrucec51f1212019-09-12 16:59:33 +0800140static int send_vc(res_state, res_params* params, const uint8_t*, int, uint8_t*, int, int*, int,
Bernie Innocenti758005f2019-02-19 18:08:36 +0900141 time_t*, int*, int*);
chenbrucec51f1212019-09-12 16:59:33 +0800142static int send_dg(res_state, res_params* params, const uint8_t*, int, uint8_t*, int, int*, int,
143 int*, int*, time_t*, int*, int*);
chenbruce018fdb22019-06-12 18:08:04 +0800144static void dump_error(const char*, const struct sockaddr*, int);
chenbruceacb832c2019-02-20 19:45:50 +0800145
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900146static int sock_eq(struct sockaddr*, struct sockaddr*);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900147static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
148 const struct timespec timeout);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900149static int retrying_poll(const int sock, short events, const struct timespec* finish);
Luke Huangd7aa7b42018-11-21 20:37:50 +0800150static int res_tls_send(res_state, const Slice query, const Slice answer, int* rcode,
Mike Yubfb1b342018-11-06 15:42:36 +0800151 bool* fallback);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900152
lifr94981782019-05-17 21:15:19 +0800153NsType getQueryType(const uint8_t* msg, size_t msgLen) {
154 ns_msg handle;
155 ns_rr rr;
156 if (ns_initparse((const uint8_t*)msg, msgLen, &handle) < 0 ||
157 ns_parserr(&handle, ns_s_qd, 0, &rr) < 0) {
158 return NS_T_INVALID;
159 }
160 return static_cast<NsType>(ns_rr_type(rr));
161}
162
163IpVersion ipFamilyToIPVersion(const int ipFamily) {
164 switch (ipFamily) {
165 case AF_INET:
166 return IV_IPV4;
167 case AF_INET6:
168 return IV_IPV6;
169 default:
170 return IV_UNKNOWN;
171 }
172}
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900173
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900174// BEGIN: Code copied from ISC eventlib
175// TODO: move away from this code
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900176#define BILLION 1000000000
177
178static struct timespec evConsTime(time_t sec, long nsec) {
179 struct timespec x;
180
181 x.tv_sec = sec;
182 x.tv_nsec = nsec;
183 return (x);
184}
185
186static struct timespec evAddTime(struct timespec addend1, struct timespec addend2) {
187 struct timespec x;
188
189 x.tv_sec = addend1.tv_sec + addend2.tv_sec;
190 x.tv_nsec = addend1.tv_nsec + addend2.tv_nsec;
191 if (x.tv_nsec >= BILLION) {
192 x.tv_sec++;
193 x.tv_nsec -= BILLION;
194 }
195 return (x);
196}
197
198static struct timespec evSubTime(struct timespec minuend, struct timespec subtrahend) {
199 struct timespec x;
200
201 x.tv_sec = minuend.tv_sec - subtrahend.tv_sec;
202 if (minuend.tv_nsec >= subtrahend.tv_nsec)
203 x.tv_nsec = minuend.tv_nsec - subtrahend.tv_nsec;
204 else {
205 x.tv_nsec = BILLION - subtrahend.tv_nsec + minuend.tv_nsec;
206 x.tv_sec--;
207 }
208 return (x);
209}
210
211static int evCmpTime(struct timespec a, struct timespec b) {
212#define SGN(x) ((x) < 0 ? (-1) : (x) > 0 ? (1) : (0));
213 time_t s = a.tv_sec - b.tv_sec;
214 long n;
215
216 if (s != 0) return SGN(s);
217
218 n = a.tv_nsec - b.tv_nsec;
219 return SGN(n);
220}
221
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900222static struct timespec evNowTime(void) {
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900223 struct timespec tsnow;
Bernie Innocentic1834822018-08-31 16:11:41 +0900224 clock_gettime(CLOCK_REALTIME, &tsnow);
225 return tsnow;
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900226}
227
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900228// END: Code copied from ISC eventlib
229
lifr94981782019-05-17 21:15:19 +0800230/* BIONIC-BEGIN: implement source port randomization */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900231static int random_bind(int s, int family) {
nuccachenb980f2f2018-10-23 17:10:58 +0800232 sockaddr_union u;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900233 int j;
234 socklen_t slen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900235
236 /* clear all, this also sets the IP4/6 address to 'any' */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900237 memset(&u, 0, sizeof u);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900238
239 switch (family) {
240 case AF_INET:
241 u.sin.sin_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900242 slen = sizeof u.sin;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900243 break;
244 case AF_INET6:
245 u.sin6.sin6_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900246 slen = sizeof u.sin6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900247 break;
248 default:
249 errno = EPROTO;
250 return -1;
251 }
252
253 /* first try to bind to a random source port a few times */
254 for (j = 0; j < 10; j++) {
255 /* find a random port between 1025 .. 65534 */
Luke Huangdda920f2019-02-13 14:05:02 +0800256 int port = 1025 + (arc4random_uniform(65535 - 1025));
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900257 if (family == AF_INET)
258 u.sin.sin_port = htons(port);
259 else
260 u.sin6.sin6_port = htons(port);
261
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900262 if (!bind(s, &u.sa, slen)) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900263 }
264
Bernie Innocenti9c575932018-09-07 21:10:25 +0900265 // nothing after 10 attempts, our network table is probably busy
266 // let the system decide which port is best
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900267 if (family == AF_INET)
268 u.sin.sin_port = 0;
269 else
270 u.sin6.sin6_port = 0;
271
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900272 return bind(s, &u.sa, slen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900273}
274/* BIONIC-END */
275
Luke Huang70931aa2019-01-31 11:57:41 +0800276// Disables all nameservers other than selectedServer
277static void res_set_usable_server(int selectedServer, int nscount, bool usable_servers[]) {
278 int usableIndex = 0;
279 for (int ns = 0; ns < nscount; ns++) {
280 if (usable_servers[ns]) ++usableIndex;
281 if (usableIndex != selectedServer) usable_servers[ns] = false;
282 }
283}
284
Bernie Innocentia6f40ca2019-10-09 15:22:41 +0900285// Looks up the nameserver address in res.nsaddrs[], returns true if found, otherwise false.
286static bool res_ourserver_p(res_state statp, const sockaddr* sa) {
Bernie Innocenti2e8540b2018-09-26 11:52:04 +0900287 const sockaddr_in *inp, *srv;
288 const sockaddr_in6 *in6p, *srv6;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900289 int ns;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900290
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900291 switch (sa->sa_family) {
292 case AF_INET:
293 inp = (const struct sockaddr_in*) (const void*) sa;
294 for (ns = 0; ns < statp->nscount; ns++) {
295 srv = (struct sockaddr_in*) (void*) get_nsaddr(statp, (size_t) ns);
296 if (srv->sin_family == inp->sin_family && srv->sin_port == inp->sin_port &&
297 (srv->sin_addr.s_addr == INADDR_ANY ||
298 srv->sin_addr.s_addr == inp->sin_addr.s_addr))
Bernie Innocentia6f40ca2019-10-09 15:22:41 +0900299 return true;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900300 }
301 break;
302 case AF_INET6:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900303 in6p = (const struct sockaddr_in6*) (const void*) sa;
304 for (ns = 0; ns < statp->nscount; ns++) {
305 srv6 = (struct sockaddr_in6*) (void*) get_nsaddr(statp, (size_t) ns);
306 if (srv6->sin6_family == in6p->sin6_family && srv6->sin6_port == in6p->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900307#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900308 (srv6->sin6_scope_id == 0 || srv6->sin6_scope_id == in6p->sin6_scope_id) &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900309#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900310 (IN6_IS_ADDR_UNSPECIFIED(&srv6->sin6_addr) ||
311 IN6_ARE_ADDR_EQUAL(&srv6->sin6_addr, &in6p->sin6_addr)))
Bernie Innocentia6f40ca2019-10-09 15:22:41 +0900312 return true;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900313 }
314 break;
315 default:
316 break;
317 }
Bernie Innocentia6f40ca2019-10-09 15:22:41 +0900318 return false;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900319}
320
321/* int
Bernie Innocenti9c575932018-09-07 21:10:25 +0900322 * res_nameinquery(name, type, cl, buf, eom)
323 * look for (name, type, cl) in the query section of packet (buf, eom)
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900324 * requires:
325 * buf + HFIXEDSZ <= eom
326 * returns:
327 * -1 : format error
328 * 0 : not found
329 * >0 : found
330 * author:
331 * paul vixie, 29may94
332 */
chenbrucec51f1212019-09-12 16:59:33 +0800333int res_nameinquery(const char* name, int type, int cl, const uint8_t* buf, const uint8_t* eom) {
334 const uint8_t* cp = buf + HFIXEDSZ;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900335 int qdcount = ntohs(((const HEADER*) (const void*) buf)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900336
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900337 while (qdcount-- > 0) {
338 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900339 int n = dn_expand(buf, eom, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900340 if (n < 0) return (-1);
341 cp += n;
342 if (cp + 2 * INT16SZ > eom) return (-1);
chenbruce0d470422019-03-28 18:44:37 +0800343 int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900344 cp += INT16SZ;
chenbruce0d470422019-03-28 18:44:37 +0800345 int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900346 cp += INT16SZ;
Bernie Innocenti9c575932018-09-07 21:10:25 +0900347 if (ttype == type && tclass == cl && ns_samename(tname, name) == 1) return (1);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900348 }
349 return (0);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900350}
351
352/* int
353 * res_queriesmatch(buf1, eom1, buf2, eom2)
354 * is there a 1:1 mapping of (name,type,class)
355 * in (buf1,eom1) and (buf2,eom2)?
356 * returns:
357 * -1 : format error
358 * 0 : not a 1:1 mapping
359 * >0 : is a 1:1 mapping
360 * author:
361 * paul vixie, 29may94
362 */
chenbrucec51f1212019-09-12 16:59:33 +0800363int res_queriesmatch(const uint8_t* buf1, const uint8_t* eom1, const uint8_t* buf2,
364 const uint8_t* eom2) {
365 const uint8_t* cp = buf1 + HFIXEDSZ;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900366 int qdcount = ntohs(((const HEADER*) (const void*) buf1)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900367
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900368 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2) return (-1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900369
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900370 /*
371 * Only header section present in replies to
372 * dynamic update packets.
373 */
374 if ((((const HEADER*) (const void*) buf1)->opcode == ns_o_update) &&
375 (((const HEADER*) (const void*) buf2)->opcode == ns_o_update))
376 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900377
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900378 if (qdcount != ntohs(((const HEADER*) (const void*) buf2)->qdcount)) return (0);
379 while (qdcount-- > 0) {
380 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900381 int n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900382 if (n < 0) return (-1);
383 cp += n;
384 if (cp + 2 * INT16SZ > eom1) return (-1);
chenbruce0d470422019-03-28 18:44:37 +0800385 int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900386 cp += INT16SZ;
chenbruce0d470422019-03-28 18:44:37 +0800387 int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900388 cp += INT16SZ;
389 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2)) return (0);
390 }
391 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900392}
393
lifr94981782019-05-17 21:15:19 +0800394static DnsQueryEvent* addDnsQueryEvent(NetworkDnsEventReported* event) {
395 return event->mutable_dns_query_events()->add_dns_query_event();
396}
397
chenbrucec51f1212019-09-12 16:59:33 +0800398int 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 +0800399 uint32_t flags) {
Luke Huang43cc1b12019-10-15 19:06:42 +0900400 LOG(DEBUG) << __func__;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900401
Luke Huang43cc1b12019-10-15 19:06:42 +0900402 // Should not happen
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900403 if (anssiz < HFIXEDSZ) {
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800404 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900405 errno = EINVAL;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800406 return -EINVAL;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900407 }
chenbrucedd210722019-03-06 13:52:43 +0800408 res_pquery(buf, buflen);
chenbruceacb832c2019-02-20 19:45:50 +0800409
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900410 int anslen = 0;
lifrd4d9fbb2019-07-31 20:18:35 +0800411 Stopwatch cacheStopwatch;
Luke Huang43cc1b12019-10-15 19:06:42 +0900412 ResolvCacheStatus cache_status =
413 resolv_cache_lookup(statp->netid, buf, buflen, ans, anssiz, &anslen, flags);
lifrd4d9fbb2019-07-31 20:18:35 +0800414 const int32_t cacheLatencyUs = saturate_cast<int32_t>(cacheStopwatch.timeTakenUs());
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900415 if (cache_status == RESOLV_CACHE_FOUND) {
Luke Huang83c9b4b2019-02-27 18:18:01 +0800416 HEADER* hp = (HEADER*)(void*)ans;
417 *rcode = hp->rcode;
lifr94981782019-05-17 21:15:19 +0800418 DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
419 dnsQueryEvent->set_latency_micros(cacheLatencyUs);
420 dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
lifre02d01c2019-12-31 17:24:57 +0800421 dnsQueryEvent->set_type(getQueryType(buf, buflen));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900422 return anslen;
423 } else if (cache_status != RESOLV_CACHE_UNSUPPORTED) {
424 // had a cache miss for a known network, so populate the thread private
425 // data so the normal resolve path can do its thing
Mike Yu021c3e12019-10-08 17:29:34 +0800426 resolv_populate_res_for_net(statp);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900427 }
428 if (statp->nscount == 0) {
429 // We have no nameservers configured, so there's no point trying.
430 // Tell the cache the query failed, or any retries and anyone else asking the same
431 // question will block for PENDING_REQUEST_TIMEOUT seconds instead of failing fast.
Luke Huangba7bef92018-12-26 16:53:03 +0800432 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800433
434 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900435 errno = ESRCH;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800436 return -ESRCH;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900437 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900438
Luke Huang272cb192019-10-15 16:52:28 +0900439 // DoT
440 if (!(statp->netcontext_flags & NET_CONTEXT_FLAG_USE_LOCAL_NAMESERVERS)) {
441 bool fallback = false;
Luke Huang43cc1b12019-10-15 19:06:42 +0900442 int resplen = res_tls_send(statp, Slice(const_cast<uint8_t*>(buf), buflen),
443 Slice(ans, anssiz), rcode, &fallback);
Luke Huang272cb192019-10-15 16:52:28 +0900444 if (resplen > 0) {
445 LOG(DEBUG) << __func__ << ": got answer from DoT";
446 res_pquery(ans, resplen);
447 if (cache_status == RESOLV_CACHE_NOTFOUND) {
448 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
449 }
450 return resplen;
451 }
452 if (!fallback) {
453 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huang43cc1b12019-10-15 19:06:42 +0900454 return -ETIMEDOUT;
Luke Huang272cb192019-10-15 16:52:28 +0900455 }
456 }
457
Bernie Innocenti758005f2019-02-19 18:08:36 +0900458 res_stats stats[MAXNS];
459 res_params params;
waynema0161acd2019-02-18 17:47:59 +0800460 int revision_id = resolv_cache_get_resolver_stats(statp->netid, &params, stats);
lifra1b37f12019-02-13 17:33:57 +0800461 if (revision_id < 0) {
462 // TODO: Remove errno once callers stop using it
463 errno = ESRCH;
464 return -ESRCH;
465 }
waynema0161acd2019-02-18 17:47:59 +0800466 bool usable_servers[MAXNS];
Luke Huang70931aa2019-01-31 11:57:41 +0800467 int usableServersCount = android_net_res_stats_get_usable_servers(
468 &params, stats, statp->nscount, usable_servers);
469
470 if ((flags & ANDROID_RESOLV_NO_RETRY) && usableServersCount > 1) {
471 auto hp = reinterpret_cast<const HEADER*>(buf);
472
473 // Select a random server based on the query id
474 int selectedServer = (hp->id % usableServersCount) + 1;
475 res_set_usable_server(selectedServer, statp->nscount, usable_servers);
476 }
waynema0161acd2019-02-18 17:47:59 +0800477
Luke Huang43cc1b12019-10-15 19:06:42 +0900478 // Send request, RETRY times, or until successful.
waynemaa74195e2019-01-18 14:02:31 +0800479 int retryTimes = (flags & ANDROID_RESOLV_NO_RETRY) ? 1 : params.retry_count;
Luke Huang43cc1b12019-10-15 19:06:42 +0900480 int useTcp = buflen > PACKETSZ;
481 int gotsomewhere = 0;
482 int terrno = ETIMEDOUT;
Luke Huangba7bef92018-12-26 16:53:03 +0800483
484 for (int attempt = 0; attempt < retryTimes; ++attempt) {
Luke Huang43cc1b12019-10-15 19:06:42 +0900485 for (int ns = 0; ns < statp->nscount; ++ns) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900486 if (!usable_servers[ns]) continue;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900487
Luke Huang43cc1b12019-10-15 19:06:42 +0900488 *rcode = RCODE_INTERNAL_ERROR;
489
490 // Get server addr
491 const sockaddr* nsap = get_nsaddr(statp, ns);
492 const int nsaplen = sockaddrSize(nsap);
493
lifr94981782019-05-17 21:15:19 +0800494 static const int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
495 char abuf[NI_MAXHOST];
chenbruceacb832c2019-02-20 19:45:50 +0800496 if (getnameinfo(nsap, (socklen_t)nsaplen, abuf, sizeof(abuf), NULL, 0, niflags) == 0)
Ken Chenffc224a2019-03-19 17:41:28 +0800497 LOG(DEBUG) << __func__ << ": Querying server (# " << ns + 1
498 << ") address = " << abuf;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900499
Luke Huang43cc1b12019-10-15 19:06:42 +0900500 ::android::net::Protocol query_proto = useTcp ? PROTO_TCP : PROTO_UDP;
501 time_t now = 0;
502 int delay = 0;
503 bool fallbackTCP = false;
504 const bool shouldRecordStats = (attempt == 0);
505 int resplen;
lifrd4d9fbb2019-07-31 20:18:35 +0800506 Stopwatch queryStopwatch;
Luke Huang43cc1b12019-10-15 19:06:42 +0900507 if (useTcp) {
508 // TCP; at most one attempt per server.
Luke Huangba7bef92018-12-26 16:53:03 +0800509 attempt = retryTimes;
Luke Huang43cc1b12019-10-15 19:06:42 +0900510 resplen = send_vc(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &now,
511 rcode, &delay);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900512 } else {
Luke Huang43cc1b12019-10-15 19:06:42 +0900513 // UDP
514 resplen = send_dg(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &useTcp,
515 &gotsomewhere, &now, rcode, &delay);
516 fallbackTCP = useTcp ? true : false;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900517 }
Luke Huang43cc1b12019-10-15 19:06:42 +0900518 LOG(INFO) << __func__ << ": used send_" << ((useTcp) ? "vc " : "dg ") << resplen;
519
520 DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
521 dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
522 dnsQueryEvent->set_latency_micros(saturate_cast<int32_t>(queryStopwatch.timeTakenUs()));
523 dnsQueryEvent->set_dns_server_index(ns);
524 dnsQueryEvent->set_ip_version(ipFamilyToIPVersion(nsap->sa_family));
525 dnsQueryEvent->set_retry_times(attempt);
526 dnsQueryEvent->set_rcode(static_cast<NsRcode>(*rcode));
527 dnsQueryEvent->set_protocol(query_proto);
528 dnsQueryEvent->set_type(getQueryType(buf, buflen));
529
530 // Only record stats the first time we try a query. This ensures that
531 // queries that deterministically fail (e.g., a name that always returns
532 // SERVFAIL or times out) do not unduly affect the stats.
533 if (shouldRecordStats) {
534 res_sample sample;
535 _res_stats_set_sample(&sample, now, *rcode, delay);
536 resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, nsap, sample,
537 params.max_samples);
538 resolv_stats_add(statp->netid, IPSockAddr::toIPSockAddr(*nsap), dnsQueryEvent);
539 }
540
541 if (resplen == 0) continue;
542 if (fallbackTCP) {
543 ns--;
544 continue;
545 }
546 if (resplen < 0) {
547 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
548 res_nclose(statp);
549 return -terrno;
550 };
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900551
Ken Chenffc224a2019-03-19 17:41:28 +0800552 LOG(DEBUG) << __func__ << ": got answer:";
chenbrucedd210722019-03-06 13:52:43 +0800553 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900554
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900555 if (cache_status == RESOLV_CACHE_NOTFOUND) {
Mike Yud1ec2542019-06-06 17:17:53 +0800556 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900557 }
chenbruce018fdb22019-06-12 18:08:04 +0800558 res_nclose(statp);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900559 return (resplen);
Bernie Innocenti9c575932018-09-07 21:10:25 +0900560 } // for each ns
561 } // for each retry
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900562 res_nclose(statp);
Luke Huang43cc1b12019-10-15 19:06:42 +0900563 terrno = useTcp ? terrno : gotsomewhere ? ETIMEDOUT : ECONNREFUSED;
564 // TODO: Remove errno once callers stop using it
565 errno = useTcp ? terrno
566 : gotsomewhere ? ETIMEDOUT /* no answer obtained */
567 : ECONNREFUSED /* no nameservers found */;
568
Luke Huangba7bef92018-12-26 16:53:03 +0800569 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800570 return -terrno;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900571}
572
573/* Private */
574
Bernie Innocenti9c575932018-09-07 21:10:25 +0900575static struct sockaddr* get_nsaddr(res_state statp, size_t n) {
Bernie Innocentic977ab72019-10-09 00:34:06 +0900576 return (struct sockaddr*)(void*)&statp->nsaddrs[n];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900577}
578
chenbruce99cbfd82019-09-05 15:08:13 +0800579static struct timespec get_timeout(res_state statp, const res_params* params, const int ns) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900580 int msec;
waynemaa74195e2019-01-18 14:02:31 +0800581 // Legacy algorithm which scales the timeout by nameserver number.
582 // For instance, with 4 nameservers: 5s, 2.5s, 5s, 10s
583 // This has no effect with 1 or 2 nameservers
584 msec = params->base_timeout_msec << ns;
585 if (ns > 0) {
586 msec /= statp->nscount;
587 }
588 // For safety, don't allow OEMs and experiments to configure a timeout shorter than 1s.
589 if (msec < 1000) {
590 msec = 1000; // Use at least 1000ms
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900591 }
Ken Chenffc224a2019-03-19 17:41:28 +0800592 LOG(INFO) << __func__ << ": using timeout of " << msec << " msec";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900593
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900594 struct timespec result;
595 result.tv_sec = msec / 1000;
596 result.tv_nsec = (msec % 1000) * 1000000;
597 return result;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900598}
599
chenbrucec51f1212019-09-12 16:59:33 +0800600static int send_vc(res_state statp, res_params* params, const uint8_t* buf, int buflen,
601 uint8_t* ans, int anssiz, int* terrno, int ns, time_t* at, int* rcode,
602 int* delay) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900603 *at = time(NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900604 *delay = 0;
605 const HEADER* hp = (const HEADER*) (const void*) buf;
606 HEADER* anhp = (HEADER*) (void*) ans;
607 struct sockaddr* nsap;
608 int nsaplen;
chenbruce0d470422019-03-28 18:44:37 +0800609 int truncating, connreset, n;
chenbrucec51f1212019-09-12 16:59:33 +0800610 uint8_t* cp;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900611
Ken Chenffc224a2019-03-19 17:41:28 +0800612 LOG(INFO) << __func__ << ": using send_vc";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900613
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900614 nsap = get_nsaddr(statp, (size_t) ns);
Mike Yu021c3e12019-10-08 17:29:34 +0800615 nsaplen = sockaddrSize(nsap);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900616
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900617 connreset = 0;
618same_ns:
619 truncating = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900620
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900621 struct timespec now = evNowTime();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900622
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900623 /* Are we still talking to whom we want to talk to? */
624 if (statp->_vcsock >= 0 && (statp->_flags & RES_F_VC) != 0) {
625 struct sockaddr_storage peer;
626 socklen_t size = sizeof peer;
627 unsigned old_mark;
628 socklen_t mark_size = sizeof(old_mark);
629 if (getpeername(statp->_vcsock, (struct sockaddr*) (void*) &peer, &size) < 0 ||
630 !sock_eq((struct sockaddr*) (void*) &peer, nsap) ||
631 getsockopt(statp->_vcsock, SOL_SOCKET, SO_MARK, &old_mark, &mark_size) < 0 ||
632 old_mark != statp->_mark) {
633 res_nclose(statp);
634 statp->_flags &= ~RES_F_VC;
635 }
636 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900637
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900638 if (statp->_vcsock < 0 || (statp->_flags & RES_F_VC) == 0) {
639 if (statp->_vcsock >= 0) res_nclose(statp);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900640
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900641 statp->_vcsock = socket(nsap->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0);
642 if (statp->_vcsock < 0) {
643 switch (errno) {
644 case EPROTONOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900645 case EPFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900646 case EAFNOSUPPORT:
chenbruce018fdb22019-06-12 18:08:04 +0800647 PLOG(DEBUG) << __func__ << ": socket(vc): ";
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900648 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900649 default:
650 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800651 PLOG(DEBUG) << __func__ << ": socket(vc): ";
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900652 return -1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900653 }
654 }
Praveen Moongalam Thyagarajan8ab18ba2019-09-04 14:46:50 -0700655 resolv_tag_socket(statp->_vcsock, statp->uid, statp->pid);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900656 if (statp->_mark != MARK_UNSET) {
657 if (setsockopt(statp->_vcsock, SOL_SOCKET, SO_MARK, &statp->_mark,
658 sizeof(statp->_mark)) < 0) {
659 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800660 PLOG(DEBUG) << __func__ << ": setsockopt: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900661 return -1;
662 }
663 }
664 errno = 0;
665 if (random_bind(statp->_vcsock, nsap->sa_family) < 0) {
666 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800667 dump_error("bind/vc", nsap, nsaplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900668 res_nclose(statp);
669 return (0);
670 }
671 if (connect_with_timeout(statp->_vcsock, nsap, (socklen_t) nsaplen,
672 get_timeout(statp, params, ns)) < 0) {
673 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800674 dump_error("connect/vc", nsap, nsaplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900675 res_nclose(statp);
676 /*
677 * The way connect_with_timeout() is implemented prevents us from reliably
678 * determining whether this was really a timeout or e.g. ECONNREFUSED. Since
679 * currently both cases are handled in the same way, there is no need to
680 * change this (yet). If we ever need to reliably distinguish between these
681 * cases, both connect_with_timeout() and retrying_poll() need to be
682 * modified, though.
683 */
684 *rcode = RCODE_TIMEOUT;
685 return (0);
686 }
687 statp->_flags |= RES_F_VC;
688 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900689
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900690 /*
691 * Send length & message
692 */
chenbruce0d470422019-03-28 18:44:37 +0800693 uint16_t len = htons(static_cast<uint16_t>(buflen));
Luke Huangc98fd802019-10-15 16:36:36 +0900694 const iovec iov[] = {
695 {.iov_base = &len, .iov_len = INT16SZ},
696 {.iov_base = const_cast<uint8_t*>(buf), .iov_len = static_cast<size_t>(buflen)},
697 };
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900698 if (writev(statp->_vcsock, iov, 2) != (INT16SZ + buflen)) {
699 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800700 PLOG(DEBUG) << __func__ << ": write failed: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900701 res_nclose(statp);
702 return (0);
703 }
704 /*
705 * Receive length & response
706 */
707read_len:
708 cp = ans;
709 len = INT16SZ;
710 while ((n = read(statp->_vcsock, (char*) cp, (size_t) len)) > 0) {
711 cp += n;
712 if ((len -= n) == 0) break;
713 }
714 if (n <= 0) {
715 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800716 PLOG(DEBUG) << __func__ << ": read failed: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900717 res_nclose(statp);
718 /*
719 * A long running process might get its TCP
720 * connection reset if the remote server was
721 * restarted. Requery the server instead of
722 * trying a new one. When there is only one
723 * server, this means that a query might work
724 * instead of failing. We only allow one reset
725 * per query to prevent looping.
726 */
727 if (*terrno == ECONNRESET && !connreset) {
728 connreset = 1;
729 res_nclose(statp);
730 goto same_ns;
731 }
732 res_nclose(statp);
733 return (0);
734 }
chenbruce0d470422019-03-28 18:44:37 +0800735 uint16_t resplen = ntohs(*reinterpret_cast<const uint16_t*>(ans));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900736 if (resplen > anssiz) {
Ken Chenffc224a2019-03-19 17:41:28 +0800737 LOG(DEBUG) << __func__ << ": response truncated";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900738 truncating = 1;
739 len = anssiz;
740 } else
741 len = resplen;
742 if (len < HFIXEDSZ) {
743 /*
744 * Undersized message.
745 */
Ken Chenffc224a2019-03-19 17:41:28 +0800746 LOG(DEBUG) << __func__ << ": undersized: " << len;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900747 *terrno = EMSGSIZE;
748 res_nclose(statp);
749 return (0);
750 }
751 cp = ans;
752 while (len != 0 && (n = read(statp->_vcsock, (char*) cp, (size_t) len)) > 0) {
753 cp += n;
754 len -= n;
755 }
756 if (n <= 0) {
757 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800758 PLOG(DEBUG) << __func__ << ": read(vc): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900759 res_nclose(statp);
760 return (0);
761 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900762
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900763 if (truncating) {
764 /*
765 * Flush rest of answer so connection stays in synch.
766 */
767 anhp->tc = 1;
768 len = resplen - anssiz;
769 while (len != 0) {
770 char junk[PACKETSZ];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900771
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900772 n = read(statp->_vcsock, junk, (len > sizeof junk) ? sizeof junk : len);
773 if (n > 0)
774 len -= n;
775 else
776 break;
777 }
778 }
779 /*
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900780 * If the calling application has bailed out of
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900781 * a previous call and failed to arrange to have
782 * the circuit closed or the server has got
783 * itself confused, then drop the packet and
784 * wait for the correct one.
785 */
786 if (hp->id != anhp->id) {
Ken Chenffc224a2019-03-19 17:41:28 +0800787 LOG(DEBUG) << __func__ << ": ld answer (unexpected):";
chenbrucedd210722019-03-06 13:52:43 +0800788 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900789 goto read_len;
790 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900791
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900792 /*
793 * All is well, or the error is fatal. Signal that the
794 * next nameserver ought not be tried.
795 */
796 if (resplen > 0) {
797 struct timespec done = evNowTime();
798 *delay = _res_stats_calculate_rtt(&done, &now);
799 *rcode = anhp->rcode;
800 }
801 return (resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900802}
803
804/* return -1 on error (errno set), 0 on success */
Luke Huangc98fd802019-10-15 16:36:36 +0900805static int connect_with_timeout(int sock, const sockaddr* nsap, socklen_t salen,
806 const timespec timeout) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900807 int res, origflags;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900808
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900809 origflags = fcntl(sock, F_GETFL, 0);
810 fcntl(sock, F_SETFL, origflags | O_NONBLOCK);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900811
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900812 res = connect(sock, nsap, salen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900813 if (res < 0 && errno != EINPROGRESS) {
814 res = -1;
815 goto done;
816 }
817 if (res != 0) {
Luke Huangc98fd802019-10-15 16:36:36 +0900818 timespec now = evNowTime();
819 timespec finish = evAddTime(now, timeout);
Ken Chenffc224a2019-03-19 17:41:28 +0800820 LOG(INFO) << __func__ << ": " << sock << " send_vc";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900821 res = retrying_poll(sock, POLLIN | POLLOUT, &finish);
822 if (res <= 0) {
823 res = -1;
824 }
825 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900826done:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900827 fcntl(sock, F_SETFL, origflags);
Ken Chenffc224a2019-03-19 17:41:28 +0800828 LOG(INFO) << __func__ << ": " << sock << " connect_with_const timeout returning " << res;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900829 return res;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900830}
831
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900832static int retrying_poll(const int sock, const short events, const struct timespec* finish) {
833 struct timespec now, timeout;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900834
835retry:
Ken Chenffc224a2019-03-19 17:41:28 +0800836 LOG(INFO) << __func__ << ": " << sock << " retrying_poll";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900837
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900838 now = evNowTime();
839 if (evCmpTime(*finish, now) > 0)
840 timeout = evSubTime(*finish, now);
841 else
842 timeout = evConsTime(0L, 0L);
843 struct pollfd fds = {.fd = sock, .events = events};
844 int n = ppoll(&fds, 1, &timeout, /*sigmask=*/NULL);
845 if (n == 0) {
Ken Chenffc224a2019-03-19 17:41:28 +0800846 LOG(INFO) << __func__ << ": " << sock << "retrying_poll timeout";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900847 errno = ETIMEDOUT;
848 return 0;
849 }
850 if (n < 0) {
851 if (errno == EINTR) goto retry;
Ken Chenffc224a2019-03-19 17:41:28 +0800852 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll failed";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900853 return n;
854 }
855 if (fds.revents & (POLLIN | POLLOUT | POLLERR)) {
856 int error;
857 socklen_t len = sizeof(error);
858 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error) {
859 errno = error;
Ken Chenffc224a2019-03-19 17:41:28 +0800860 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll getsockopt failed";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900861 return -1;
862 }
863 }
Ken Chenffc224a2019-03-19 17:41:28 +0800864 LOG(INFO) << __func__ << ": " << sock << " retrying_poll returning " << n;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900865 return n;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900866}
867
chenbrucec51f1212019-09-12 16:59:33 +0800868static int send_dg(res_state statp, res_params* params, const uint8_t* buf, int buflen,
869 uint8_t* ans, int anssiz, int* terrno, int ns, int* v_circuit, int* gotsomewhere,
870 time_t* at, int* rcode, int* delay) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900871 *at = time(NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900872 *delay = 0;
873 const HEADER* hp = (const HEADER*) (const void*) buf;
874 HEADER* anhp = (HEADER*) (void*) ans;
875 const struct sockaddr* nsap;
876 int nsaplen;
877 struct timespec now, timeout, finish, done;
878 struct sockaddr_storage from;
879 socklen_t fromlen;
880 int resplen, n, s;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900881
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900882 nsap = get_nsaddr(statp, (size_t) ns);
Mike Yu021c3e12019-10-08 17:29:34 +0800883 nsaplen = sockaddrSize(nsap);
Bernie Innocentibb330742019-10-09 00:55:53 +0900884 if (statp->nssocks[ns] == -1) {
885 statp->nssocks[ns] = socket(nsap->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
886 if (statp->nssocks[ns] < 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900887 switch (errno) {
888 case EPROTONOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900889 case EPFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900890 case EAFNOSUPPORT:
chenbruce018fdb22019-06-12 18:08:04 +0800891 PLOG(DEBUG) << __func__ << ": socket(dg): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900892 return (0);
893 default:
894 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800895 PLOG(DEBUG) << __func__ << ": socket(dg): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900896 return (-1);
897 }
898 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900899
Praveen Moongalam Thyagarajan8ab18ba2019-09-04 14:46:50 -0700900 resolv_tag_socket(statp->nssocks[ns], statp->uid, statp->pid);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900901 if (statp->_mark != MARK_UNSET) {
Bernie Innocentibb330742019-10-09 00:55:53 +0900902 if (setsockopt(statp->nssocks[ns], SOL_SOCKET, SO_MARK, &(statp->_mark),
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900903 sizeof(statp->_mark)) < 0) {
904 res_nclose(statp);
905 return -1;
906 }
907 }
chenbruceb9cce7b2019-07-15 16:14:53 +0800908 // Use a "connected" datagram socket to receive an ECONNREFUSED error
909 // on the next socket operation when the server responds with an
910 // ICMP port-unreachable error. This way we can detect the absence of
911 // a nameserver without timing out.
Bernie Innocentibb330742019-10-09 00:55:53 +0900912 if (random_bind(statp->nssocks[ns], nsap->sa_family) < 0) {
chenbruce018fdb22019-06-12 18:08:04 +0800913 dump_error("bind(dg)", nsap, nsaplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900914 res_nclose(statp);
915 return (0);
916 }
Bernie Innocentibb330742019-10-09 00:55:53 +0900917 if (connect(statp->nssocks[ns], nsap, (socklen_t)nsaplen) < 0) {
chenbruce018fdb22019-06-12 18:08:04 +0800918 dump_error("connect(dg)", nsap, nsaplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900919 res_nclose(statp);
920 return (0);
921 }
Ken Chenffc224a2019-03-19 17:41:28 +0800922 LOG(DEBUG) << __func__ << ": new DG socket";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900923 }
Bernie Innocentibb330742019-10-09 00:55:53 +0900924 s = statp->nssocks[ns];
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900925 if (send(s, (const char*) buf, (size_t) buflen, 0) != buflen) {
chenbruce018fdb22019-06-12 18:08:04 +0800926 PLOG(DEBUG) << __func__ << ": send: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900927 res_nclose(statp);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +0900928 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900929 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900930
Bernie Innocenti3952ccc2019-03-03 19:39:53 +0900931 // Wait for reply.
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900932 timeout = get_timeout(statp, params, ns);
933 now = evNowTime();
934 finish = evAddTime(now, timeout);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900935retry:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900936 n = retrying_poll(s, POLLIN, &finish);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900937
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900938 if (n == 0) {
939 *rcode = RCODE_TIMEOUT;
Ken Chenffc224a2019-03-19 17:41:28 +0800940 LOG(DEBUG) << __func__ << ": timeout";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900941 *gotsomewhere = 1;
Bernie Innocenti3952ccc2019-03-03 19:39:53 +0900942 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900943 }
944 if (n < 0) {
chenbruce018fdb22019-06-12 18:08:04 +0800945 PLOG(DEBUG) << __func__ << ": poll: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900946 res_nclose(statp);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +0900947 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900948 }
949 errno = 0;
950 fromlen = sizeof(from);
951 resplen = recvfrom(s, (char*) ans, (size_t) anssiz, 0, (struct sockaddr*) (void*) &from,
952 &fromlen);
953 if (resplen <= 0) {
chenbruce018fdb22019-06-12 18:08:04 +0800954 PLOG(DEBUG) << __func__ << ": recvfrom: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900955 res_nclose(statp);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +0900956 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900957 }
958 *gotsomewhere = 1;
959 if (resplen < HFIXEDSZ) {
960 /*
961 * Undersized message.
962 */
Ken Chenffc224a2019-03-19 17:41:28 +0800963 LOG(DEBUG) << __func__ << ": undersized: " << resplen;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900964 *terrno = EMSGSIZE;
965 res_nclose(statp);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +0900966 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900967 }
968 if (hp->id != anhp->id) {
969 /*
970 * response from old query, ignore it.
971 * XXX - potential security hazard could
972 * be detected here.
973 */
Ken Chenffc224a2019-03-19 17:41:28 +0800974 LOG(DEBUG) << __func__ << ": old answer:";
chenbrucedd210722019-03-06 13:52:43 +0800975 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900976 goto retry;
977 }
chenbruce018fdb22019-06-12 18:08:04 +0800978 if (!res_ourserver_p(statp, (struct sockaddr*)(void*)&from)) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900979 /*
980 * response from wrong server? ignore it.
981 * XXX - potential security hazard could
982 * be detected here.
983 */
Ken Chenffc224a2019-03-19 17:41:28 +0800984 LOG(DEBUG) << __func__ << ": not our server:";
chenbrucedd210722019-03-06 13:52:43 +0800985 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900986 goto retry;
987 }
chenbruced8cbb9b2019-06-20 18:25:28 +0800988 if (anhp->rcode == FORMERR && (statp->netcontext_flags & NET_CONTEXT_FLAG_USE_EDNS)) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900989 /*
990 * Do not retry if the server do not understand EDNS0.
991 * The case has to be captured here, as FORMERR packet do not
992 * carry query section, hence res_queriesmatch() returns 0.
993 */
Ken Chenffc224a2019-03-19 17:41:28 +0800994 LOG(DEBUG) << __func__ << ": server rejected query with EDNS0:";
chenbrucedd210722019-03-06 13:52:43 +0800995 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900996 /* record the error */
997 statp->_flags |= RES_F_EDNS0ERR;
998 res_nclose(statp);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +0900999 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001000 }
chenbruce018fdb22019-06-12 18:08:04 +08001001 if (!res_queriesmatch(buf, buf + buflen, ans, ans + anssiz)) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001002 /*
1003 * response contains wrong query? ignore it.
1004 * XXX - potential security hazard could
1005 * be detected here.
1006 */
Ken Chenffc224a2019-03-19 17:41:28 +08001007 LOG(DEBUG) << __func__ << ": wrong query name:";
chenbrucedd210722019-03-06 13:52:43 +08001008 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001009 goto retry;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001010 }
1011 done = evNowTime();
1012 *delay = _res_stats_calculate_rtt(&done, &now);
1013 if (anhp->rcode == SERVFAIL || anhp->rcode == NOTIMP || anhp->rcode == REFUSED) {
Ken Chenffc224a2019-03-19 17:41:28 +08001014 LOG(DEBUG) << __func__ << ": server rejected query:";
chenbrucedd210722019-03-06 13:52:43 +08001015 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001016 res_nclose(statp);
chenbrucedd210722019-03-06 13:52:43 +08001017 *rcode = anhp->rcode;
1018 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001019 }
chenbruce018fdb22019-06-12 18:08:04 +08001020 if (anhp->tc) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001021 /*
1022 * To get the rest of answer,
1023 * use TCP with same server.
1024 */
Ken Chenffc224a2019-03-19 17:41:28 +08001025 LOG(DEBUG) << __func__ << ": truncated answer";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001026 *v_circuit = 1;
1027 res_nclose(statp);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001028 return 1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001029 }
1030 /*
1031 * All is well, or the error is fatal. Signal that the
1032 * next nameserver ought not be tried.
1033 */
1034 if (resplen > 0) {
1035 *rcode = anhp->rcode;
1036 }
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001037 return resplen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001038}
1039
chenbruce018fdb22019-06-12 18:08:04 +08001040static void dump_error(const char* str, const struct sockaddr* address, int alen) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001041 char hbuf[NI_MAXHOST];
1042 char sbuf[NI_MAXSERV];
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001043 constexpr int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
Luke Huangc98fd802019-10-15 16:36:36 +09001044 const int err = errno;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001045
chenbruce018fdb22019-06-12 18:08:04 +08001046 if (!WOULD_LOG(DEBUG)) return;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001047
chenbruce018fdb22019-06-12 18:08:04 +08001048 if (getnameinfo(address, (socklen_t)alen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf), niflags)) {
1049 strncpy(hbuf, "?", sizeof(hbuf) - 1);
1050 hbuf[sizeof(hbuf) - 1] = '\0';
1051 strncpy(sbuf, "?", sizeof(sbuf) - 1);
1052 sbuf[sizeof(sbuf) - 1] = '\0';
Elliott Hughes3b8f5902019-03-08 12:02:55 -08001053 }
Luke Huangc98fd802019-10-15 16:36:36 +09001054 errno = err;
chenbruce018fdb22019-06-12 18:08:04 +08001055 PLOG(DEBUG) << __func__ << ": " << str << " ([" << hbuf << "]." << sbuf << "): ";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001056}
1057
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001058static int sock_eq(struct sockaddr* a, struct sockaddr* b) {
1059 struct sockaddr_in *a4, *b4;
1060 struct sockaddr_in6 *a6, *b6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001061
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001062 if (a->sa_family != b->sa_family) return 0;
1063 switch (a->sa_family) {
1064 case AF_INET:
1065 a4 = (struct sockaddr_in*) (void*) a;
1066 b4 = (struct sockaddr_in*) (void*) b;
1067 return a4->sin_port == b4->sin_port && a4->sin_addr.s_addr == b4->sin_addr.s_addr;
1068 case AF_INET6:
1069 a6 = (struct sockaddr_in6*) (void*) a;
1070 b6 = (struct sockaddr_in6*) (void*) b;
1071 return a6->sin6_port == b6->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001072#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001073 a6->sin6_scope_id == b6->sin6_scope_id &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001074#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001075 IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
1076 default:
1077 return 0;
1078 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001079}
Mike Yub601ff72018-11-01 20:07:00 +08001080
lifr6b83a6f2019-07-26 03:17:43 +08001081PrivateDnsModes convertEnumType(PrivateDnsMode privateDnsmode) {
1082 switch (privateDnsmode) {
1083 case PrivateDnsMode::OFF:
1084 return PrivateDnsModes::PDM_OFF;
1085 case PrivateDnsMode::OPPORTUNISTIC:
1086 return PrivateDnsModes::PDM_OPPORTUNISTIC;
1087 case PrivateDnsMode::STRICT:
1088 return PrivateDnsModes::PDM_STRICT;
Mike Yu99b8dc72019-11-22 17:45:31 +08001089 default:
1090 return PrivateDnsModes::PDM_UNKNOWN;
lifr6b83a6f2019-07-26 03:17:43 +08001091 }
lifr6b83a6f2019-07-26 03:17:43 +08001092}
1093
Luke Huangd7aa7b42018-11-21 20:37:50 +08001094static int res_tls_send(res_state statp, const Slice query, const Slice answer, int* rcode,
Mike Yubfb1b342018-11-06 15:42:36 +08001095 bool* fallback) {
1096 int resplen = 0;
Mike Yub601ff72018-11-01 20:07:00 +08001097 const unsigned netId = statp->netid;
Mike Yub601ff72018-11-01 20:07:00 +08001098
Mike Yubfb1b342018-11-06 15:42:36 +08001099 PrivateDnsStatus privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
lifr6b83a6f2019-07-26 03:17:43 +08001100 statp->event->set_private_dns_modes(convertEnumType(privateDnsStatus.mode));
Mike Yubfb1b342018-11-06 15:42:36 +08001101
1102 if (privateDnsStatus.mode == PrivateDnsMode::OFF) {
1103 *fallback = true;
1104 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001105 }
1106
Mike Yu3e829062019-08-07 14:01:14 +08001107 if (privateDnsStatus.validatedServers().empty()) {
Mike Yub601ff72018-11-01 20:07:00 +08001108 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
Mike Yubfb1b342018-11-06 15:42:36 +08001109 *fallback = true;
1110 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001111 } else {
1112 // Sleep and iterate some small number of times checking for the
1113 // arrival of resolved and validated server IP addresses, instead
1114 // of returning an immediate error.
Mike Yu4f3747b2018-12-02 17:54:29 +09001115 // This is needed because as soon as a network becomes the default network, apps will
1116 // send DNS queries on that network. If no servers have yet validated, and we do not
1117 // block those queries, they would immediately fail, causing application-visible errors.
1118 // Note that this can happen even before the network validates, since an unvalidated
1119 // network can become the default network if no validated networks are available.
1120 //
1121 // TODO: see if there is a better way to address this problem, such as buffering the
1122 // queries in a queue or only blocking queries for the first few seconds after a default
1123 // network change.
Mike Yubfb1b342018-11-06 15:42:36 +08001124 for (int i = 0; i < 42; i++) {
1125 std::this_thread::sleep_for(std::chrono::milliseconds(100));
Mike Yu3e829062019-08-07 14:01:14 +08001126 // Calling getStatus() to merely check if there's any validated server seems
1127 // wasteful. Consider adding a new method in PrivateDnsConfiguration for speed ups.
1128 if (!gPrivateDnsConfiguration.getStatus(netId).validatedServers().empty()) {
Mike Yubfb1b342018-11-06 15:42:36 +08001129 privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
1130 break;
1131 }
1132 }
Mike Yu3e829062019-08-07 14:01:14 +08001133 if (privateDnsStatus.validatedServers().empty()) {
Mike Yubfb1b342018-11-06 15:42:36 +08001134 return -1;
1135 }
Mike Yub601ff72018-11-01 20:07:00 +08001136 }
1137 }
1138
chenbruceacb832c2019-02-20 19:45:50 +08001139 LOG(INFO) << __func__ << ": performing query over TLS";
Mike Yub601ff72018-11-01 20:07:00 +08001140
Mike Yu3e829062019-08-07 14:01:14 +08001141 const auto response = sDnsTlsDispatcher.query(privateDnsStatus.validatedServers(), statp, query,
Mike Yubfb1b342018-11-06 15:42:36 +08001142 answer, &resplen);
Mike Yub601ff72018-11-01 20:07:00 +08001143
chenbruceacb832c2019-02-20 19:45:50 +08001144 LOG(INFO) << __func__ << ": TLS query result: " << static_cast<int>(response);
Mike Yub601ff72018-11-01 20:07:00 +08001145
1146 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
1147 // In opportunistic mode, handle falling back to cleartext in some
1148 // cases (DNS shouldn't fail if a validated opportunistic mode server
1149 // becomes unreachable for some reason).
1150 switch (response) {
Mike Yubfb1b342018-11-06 15:42:36 +08001151 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001152 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001153 return resplen;
Mike Yub601ff72018-11-01 20:07:00 +08001154 case DnsTlsTransport::Response::network_error:
Mike Yubfb1b342018-11-06 15:42:36 +08001155 // No need to set the error timeout here since it will fallback to UDP.
Mike Yub601ff72018-11-01 20:07:00 +08001156 case DnsTlsTransport::Response::internal_error:
1157 // Note: this will cause cleartext queries to be emitted, with
1158 // all of the EDNS0 goodness enabled. Fingers crossed. :-/
Mike Yubfb1b342018-11-06 15:42:36 +08001159 *fallback = true;
1160 [[fallthrough]];
Mike Yub601ff72018-11-01 20:07:00 +08001161 default:
Mike Yubfb1b342018-11-06 15:42:36 +08001162 return -1;
1163 }
1164 } else {
1165 // Strict mode
1166 switch (response) {
1167 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001168 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001169 return resplen;
1170 case DnsTlsTransport::Response::network_error:
1171 // This case happens when the query stored in DnsTlsTransport is expired since
1172 // either 1) the query has been tried for 3 times but no response or 2) fail to
1173 // establish the connection with the server.
Luke Huangd7aa7b42018-11-21 20:37:50 +08001174 *rcode = RCODE_TIMEOUT;
Mike Yubfb1b342018-11-06 15:42:36 +08001175 [[fallthrough]];
1176 default:
1177 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001178 }
1179 }
Mike Yub601ff72018-11-01 20:07:00 +08001180}
Luke Huang4973a0d2018-11-19 20:17:26 +08001181
Luke Huangba7bef92018-12-26 16:53:03 +08001182int resolv_res_nsend(const android_net_context* netContext, const uint8_t* msg, int msgLen,
lifr94981782019-05-17 21:15:19 +08001183 uint8_t* ans, int ansLen, int* rcode, uint32_t flags,
1184 NetworkDnsEventReported* event) {
1185 assert(event != nullptr);
Bernie Innocenti08487112019-10-11 21:14:13 +09001186 ResState res;
1187 res_init(&res, netContext, event);
Mike Yu021c3e12019-10-08 17:29:34 +08001188 resolv_populate_res_for_net(&res);
Luke Huang4973a0d2018-11-19 20:17:26 +08001189 *rcode = NOERROR;
Bernie Innocenti08487112019-10-11 21:14:13 +09001190 return res_nsend(&res, msg, msgLen, ans, ansLen, rcode, flags);
Bernie Innocentiec4219b2019-01-30 11:16:36 +09001191}