blob: 4db1b8baab55fd7330ccb9d3c78120362fea8229 [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"
Bernie Innocenti10a90282020-01-23 23:28:00 +0900107
108#include "res_comp.h"
Mike Yu34433c62019-08-20 20:17:36 +0800109#include "res_debug.h"
Bernie Innocenti08487112019-10-11 21:14:13 +0900110#include "res_init.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900111#include "resolv_cache.h"
Ken Chen99c0b322019-11-20 14:24:09 +0800112#include "stats.h"
lifr94981782019-05-17 21:15:19 +0800113#include "stats.pb.h"
Mike Yu021c3e12019-10-08 17:29:34 +0800114#include "util.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900115
Mike Yub601ff72018-11-01 20:07:00 +0800116// TODO: use the namespace something like android::netd_resolv for libnetd_resolv
chenbruce99cbfd82019-09-05 15:08:13 +0800117using android::net::CacheStatus;
118using android::net::DnsQueryEvent;
119using android::net::DnsTlsDispatcher;
120using android::net::DnsTlsTransport;
121using android::net::gPrivateDnsConfiguration;
122using android::net::IpVersion;
123using android::net::IV_IPV4;
124using android::net::IV_IPV6;
125using android::net::IV_UNKNOWN;
lifr94981782019-05-17 21:15:19 +0800126using android::net::NetworkDnsEventReported;
chenbruce99cbfd82019-09-05 15:08:13 +0800127using android::net::NS_T_INVALID;
128using android::net::NsRcode;
129using android::net::NsType;
130using android::net::PrivateDnsMode;
131using android::net::PrivateDnsModes;
132using android::net::PrivateDnsStatus;
133using android::net::PROTO_TCP;
134using android::net::PROTO_UDP;
Mike Yue655b1d2019-08-28 17:49:59 +0800135using android::netdutils::IPSockAddr;
Bernie Innocentiec4219b2019-01-30 11:16:36 +0900136using android::netdutils::Slice;
lifr94981782019-05-17 21:15:19 +0800137using android::netdutils::Stopwatch;
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900138
Mike Yub601ff72018-11-01 20:07:00 +0800139static DnsTlsDispatcher sDnsTlsDispatcher;
140
Bernie Innocenti9c575932018-09-07 21:10:25 +0900141static struct sockaddr* get_nsaddr(res_state, size_t);
chenbrucec51f1212019-09-12 16:59:33 +0800142static int send_vc(res_state, res_params* params, const uint8_t*, int, uint8_t*, int, int*, int,
Bernie Innocenti758005f2019-02-19 18:08:36 +0900143 time_t*, int*, int*);
chenbrucec51f1212019-09-12 16:59:33 +0800144static int send_dg(res_state, res_params* params, const uint8_t*, int, uint8_t*, int, int*, int,
145 int*, int*, time_t*, int*, int*);
chenbruce018fdb22019-06-12 18:08:04 +0800146static void dump_error(const char*, const struct sockaddr*, int);
chenbruceacb832c2019-02-20 19:45:50 +0800147
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900148static int sock_eq(struct sockaddr*, struct sockaddr*);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900149static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
150 const struct timespec timeout);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900151static int retrying_poll(const int sock, short events, const struct timespec* finish);
Luke Huangd7aa7b42018-11-21 20:37:50 +0800152static int res_tls_send(res_state, const Slice query, const Slice answer, int* rcode,
Mike Yubfb1b342018-11-06 15:42:36 +0800153 bool* fallback);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900154
lifr94981782019-05-17 21:15:19 +0800155NsType getQueryType(const uint8_t* msg, size_t msgLen) {
156 ns_msg handle;
157 ns_rr rr;
158 if (ns_initparse((const uint8_t*)msg, msgLen, &handle) < 0 ||
159 ns_parserr(&handle, ns_s_qd, 0, &rr) < 0) {
160 return NS_T_INVALID;
161 }
162 return static_cast<NsType>(ns_rr_type(rr));
163}
164
165IpVersion ipFamilyToIPVersion(const int ipFamily) {
166 switch (ipFamily) {
167 case AF_INET:
168 return IV_IPV4;
169 case AF_INET6:
170 return IV_IPV6;
171 default:
172 return IV_UNKNOWN;
173 }
174}
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900175
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900176// BEGIN: Code copied from ISC eventlib
177// TODO: move away from this code
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900178#define BILLION 1000000000
179
180static struct timespec evConsTime(time_t sec, long nsec) {
181 struct timespec x;
182
183 x.tv_sec = sec;
184 x.tv_nsec = nsec;
185 return (x);
186}
187
188static struct timespec evAddTime(struct timespec addend1, struct timespec addend2) {
189 struct timespec x;
190
191 x.tv_sec = addend1.tv_sec + addend2.tv_sec;
192 x.tv_nsec = addend1.tv_nsec + addend2.tv_nsec;
193 if (x.tv_nsec >= BILLION) {
194 x.tv_sec++;
195 x.tv_nsec -= BILLION;
196 }
197 return (x);
198}
199
200static struct timespec evSubTime(struct timespec minuend, struct timespec subtrahend) {
201 struct timespec x;
202
203 x.tv_sec = minuend.tv_sec - subtrahend.tv_sec;
204 if (minuend.tv_nsec >= subtrahend.tv_nsec)
205 x.tv_nsec = minuend.tv_nsec - subtrahend.tv_nsec;
206 else {
207 x.tv_nsec = BILLION - subtrahend.tv_nsec + minuend.tv_nsec;
208 x.tv_sec--;
209 }
210 return (x);
211}
212
213static int evCmpTime(struct timespec a, struct timespec b) {
214#define SGN(x) ((x) < 0 ? (-1) : (x) > 0 ? (1) : (0));
215 time_t s = a.tv_sec - b.tv_sec;
216 long n;
217
218 if (s != 0) return SGN(s);
219
220 n = a.tv_nsec - b.tv_nsec;
221 return SGN(n);
222}
223
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900224static struct timespec evNowTime(void) {
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900225 struct timespec tsnow;
Bernie Innocentic1834822018-08-31 16:11:41 +0900226 clock_gettime(CLOCK_REALTIME, &tsnow);
227 return tsnow;
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900228}
229
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900230// END: Code copied from ISC eventlib
231
lifr94981782019-05-17 21:15:19 +0800232/* BIONIC-BEGIN: implement source port randomization */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900233static int random_bind(int s, int family) {
nuccachenb980f2f2018-10-23 17:10:58 +0800234 sockaddr_union u;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900235 int j;
236 socklen_t slen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900237
238 /* clear all, this also sets the IP4/6 address to 'any' */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900239 memset(&u, 0, sizeof u);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900240
241 switch (family) {
242 case AF_INET:
243 u.sin.sin_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900244 slen = sizeof u.sin;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900245 break;
246 case AF_INET6:
247 u.sin6.sin6_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900248 slen = sizeof u.sin6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900249 break;
250 default:
251 errno = EPROTO;
252 return -1;
253 }
254
255 /* first try to bind to a random source port a few times */
256 for (j = 0; j < 10; j++) {
257 /* find a random port between 1025 .. 65534 */
Luke Huangdda920f2019-02-13 14:05:02 +0800258 int port = 1025 + (arc4random_uniform(65535 - 1025));
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900259 if (family == AF_INET)
260 u.sin.sin_port = htons(port);
261 else
262 u.sin6.sin6_port = htons(port);
263
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900264 if (!bind(s, &u.sa, slen)) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900265 }
266
Bernie Innocenti9c575932018-09-07 21:10:25 +0900267 // nothing after 10 attempts, our network table is probably busy
268 // let the system decide which port is best
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900269 if (family == AF_INET)
270 u.sin.sin_port = 0;
271 else
272 u.sin6.sin6_port = 0;
273
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900274 return bind(s, &u.sa, slen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900275}
276/* BIONIC-END */
277
Luke Huang70931aa2019-01-31 11:57:41 +0800278// Disables all nameservers other than selectedServer
279static void res_set_usable_server(int selectedServer, int nscount, bool usable_servers[]) {
280 int usableIndex = 0;
281 for (int ns = 0; ns < nscount; ns++) {
282 if (usable_servers[ns]) ++usableIndex;
283 if (usableIndex != selectedServer) usable_servers[ns] = false;
284 }
285}
286
Bernie Innocentia6f40ca2019-10-09 15:22:41 +0900287// Looks up the nameserver address in res.nsaddrs[], returns true if found, otherwise false.
288static bool res_ourserver_p(res_state statp, const sockaddr* sa) {
Bernie Innocenti2e8540b2018-09-26 11:52:04 +0900289 const sockaddr_in *inp, *srv;
290 const sockaddr_in6 *in6p, *srv6;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900291 int ns;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900292
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900293 switch (sa->sa_family) {
294 case AF_INET:
295 inp = (const struct sockaddr_in*) (const void*) sa;
296 for (ns = 0; ns < statp->nscount; ns++) {
297 srv = (struct sockaddr_in*) (void*) get_nsaddr(statp, (size_t) ns);
298 if (srv->sin_family == inp->sin_family && srv->sin_port == inp->sin_port &&
299 (srv->sin_addr.s_addr == INADDR_ANY ||
300 srv->sin_addr.s_addr == inp->sin_addr.s_addr))
Bernie Innocentia6f40ca2019-10-09 15:22:41 +0900301 return true;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900302 }
303 break;
304 case AF_INET6:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900305 in6p = (const struct sockaddr_in6*) (const void*) sa;
306 for (ns = 0; ns < statp->nscount; ns++) {
307 srv6 = (struct sockaddr_in6*) (void*) get_nsaddr(statp, (size_t) ns);
308 if (srv6->sin6_family == in6p->sin6_family && srv6->sin6_port == in6p->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900309#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900310 (srv6->sin6_scope_id == 0 || srv6->sin6_scope_id == in6p->sin6_scope_id) &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900311#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900312 (IN6_IS_ADDR_UNSPECIFIED(&srv6->sin6_addr) ||
313 IN6_ARE_ADDR_EQUAL(&srv6->sin6_addr, &in6p->sin6_addr)))
Bernie Innocentia6f40ca2019-10-09 15:22:41 +0900314 return true;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900315 }
316 break;
317 default:
318 break;
319 }
Bernie Innocentia6f40ca2019-10-09 15:22:41 +0900320 return false;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900321}
322
323/* int
Bernie Innocenti9c575932018-09-07 21:10:25 +0900324 * res_nameinquery(name, type, cl, buf, eom)
325 * look for (name, type, cl) in the query section of packet (buf, eom)
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900326 * requires:
327 * buf + HFIXEDSZ <= eom
328 * returns:
329 * -1 : format error
330 * 0 : not found
331 * >0 : found
332 * author:
333 * paul vixie, 29may94
334 */
chenbrucec51f1212019-09-12 16:59:33 +0800335int res_nameinquery(const char* name, int type, int cl, const uint8_t* buf, const uint8_t* eom) {
336 const uint8_t* cp = buf + HFIXEDSZ;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900337 int qdcount = ntohs(((const HEADER*) (const void*) buf)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900338
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900339 while (qdcount-- > 0) {
340 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900341 int n = dn_expand(buf, eom, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900342 if (n < 0) return (-1);
343 cp += n;
344 if (cp + 2 * INT16SZ > eom) return (-1);
chenbruce0d470422019-03-28 18:44:37 +0800345 int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900346 cp += INT16SZ;
chenbruce0d470422019-03-28 18:44:37 +0800347 int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900348 cp += INT16SZ;
Bernie Innocenti9c575932018-09-07 21:10:25 +0900349 if (ttype == type && tclass == cl && ns_samename(tname, name) == 1) return (1);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900350 }
351 return (0);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900352}
353
354/* int
355 * res_queriesmatch(buf1, eom1, buf2, eom2)
356 * is there a 1:1 mapping of (name,type,class)
357 * in (buf1,eom1) and (buf2,eom2)?
358 * returns:
359 * -1 : format error
360 * 0 : not a 1:1 mapping
361 * >0 : is a 1:1 mapping
362 * author:
363 * paul vixie, 29may94
364 */
chenbrucec51f1212019-09-12 16:59:33 +0800365int res_queriesmatch(const uint8_t* buf1, const uint8_t* eom1, const uint8_t* buf2,
366 const uint8_t* eom2) {
367 const uint8_t* cp = buf1 + HFIXEDSZ;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900368 int qdcount = ntohs(((const HEADER*) (const void*) buf1)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900369
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900370 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2) return (-1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900371
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900372 /*
373 * Only header section present in replies to
374 * dynamic update packets.
375 */
376 if ((((const HEADER*) (const void*) buf1)->opcode == ns_o_update) &&
377 (((const HEADER*) (const void*) buf2)->opcode == ns_o_update))
378 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900379
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900380 if (qdcount != ntohs(((const HEADER*) (const void*) buf2)->qdcount)) return (0);
381 while (qdcount-- > 0) {
382 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900383 int n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900384 if (n < 0) return (-1);
385 cp += n;
386 if (cp + 2 * INT16SZ > eom1) return (-1);
chenbruce0d470422019-03-28 18:44:37 +0800387 int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900388 cp += INT16SZ;
chenbruce0d470422019-03-28 18:44:37 +0800389 int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900390 cp += INT16SZ;
391 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2)) return (0);
392 }
393 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900394}
395
lifr94981782019-05-17 21:15:19 +0800396static DnsQueryEvent* addDnsQueryEvent(NetworkDnsEventReported* event) {
397 return event->mutable_dns_query_events()->add_dns_query_event();
398}
399
chenbrucec51f1212019-09-12 16:59:33 +0800400int 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 +0800401 uint32_t flags) {
Luke Huang43cc1b12019-10-15 19:06:42 +0900402 LOG(DEBUG) << __func__;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900403
Luke Huang43cc1b12019-10-15 19:06:42 +0900404 // Should not happen
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900405 if (anssiz < HFIXEDSZ) {
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800406 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900407 errno = EINVAL;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800408 return -EINVAL;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900409 }
chenbrucedd210722019-03-06 13:52:43 +0800410 res_pquery(buf, buflen);
chenbruceacb832c2019-02-20 19:45:50 +0800411
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900412 int anslen = 0;
lifrd4d9fbb2019-07-31 20:18:35 +0800413 Stopwatch cacheStopwatch;
Luke Huang43cc1b12019-10-15 19:06:42 +0900414 ResolvCacheStatus cache_status =
415 resolv_cache_lookup(statp->netid, buf, buflen, ans, anssiz, &anslen, flags);
lifrd4d9fbb2019-07-31 20:18:35 +0800416 const int32_t cacheLatencyUs = saturate_cast<int32_t>(cacheStopwatch.timeTakenUs());
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900417 if (cache_status == RESOLV_CACHE_FOUND) {
Luke Huang83c9b4b2019-02-27 18:18:01 +0800418 HEADER* hp = (HEADER*)(void*)ans;
419 *rcode = hp->rcode;
lifr94981782019-05-17 21:15:19 +0800420 DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
421 dnsQueryEvent->set_latency_micros(cacheLatencyUs);
422 dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
lifre02d01c2019-12-31 17:24:57 +0800423 dnsQueryEvent->set_type(getQueryType(buf, buflen));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900424 return anslen;
425 } else if (cache_status != RESOLV_CACHE_UNSUPPORTED) {
426 // had a cache miss for a known network, so populate the thread private
427 // data so the normal resolve path can do its thing
Mike Yu021c3e12019-10-08 17:29:34 +0800428 resolv_populate_res_for_net(statp);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900429 }
430 if (statp->nscount == 0) {
431 // We have no nameservers configured, so there's no point trying.
432 // Tell the cache the query failed, or any retries and anyone else asking the same
433 // question will block for PENDING_REQUEST_TIMEOUT seconds instead of failing fast.
Luke Huangba7bef92018-12-26 16:53:03 +0800434 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800435
436 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900437 errno = ESRCH;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800438 return -ESRCH;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900439 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900440
Luke Huang272cb192019-10-15 16:52:28 +0900441 // DoT
442 if (!(statp->netcontext_flags & NET_CONTEXT_FLAG_USE_LOCAL_NAMESERVERS)) {
443 bool fallback = false;
Luke Huang43cc1b12019-10-15 19:06:42 +0900444 int resplen = res_tls_send(statp, Slice(const_cast<uint8_t*>(buf), buflen),
445 Slice(ans, anssiz), rcode, &fallback);
Luke Huang272cb192019-10-15 16:52:28 +0900446 if (resplen > 0) {
447 LOG(DEBUG) << __func__ << ": got answer from DoT";
448 res_pquery(ans, resplen);
449 if (cache_status == RESOLV_CACHE_NOTFOUND) {
450 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
451 }
452 return resplen;
453 }
454 if (!fallback) {
455 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huang43cc1b12019-10-15 19:06:42 +0900456 return -ETIMEDOUT;
Luke Huang272cb192019-10-15 16:52:28 +0900457 }
458 }
459
Bernie Innocenti758005f2019-02-19 18:08:36 +0900460 res_stats stats[MAXNS];
461 res_params params;
waynema0161acd2019-02-18 17:47:59 +0800462 int revision_id = resolv_cache_get_resolver_stats(statp->netid, &params, stats);
lifra1b37f12019-02-13 17:33:57 +0800463 if (revision_id < 0) {
464 // TODO: Remove errno once callers stop using it
465 errno = ESRCH;
466 return -ESRCH;
467 }
waynema0161acd2019-02-18 17:47:59 +0800468 bool usable_servers[MAXNS];
Luke Huang70931aa2019-01-31 11:57:41 +0800469 int usableServersCount = android_net_res_stats_get_usable_servers(
470 &params, stats, statp->nscount, usable_servers);
471
472 if ((flags & ANDROID_RESOLV_NO_RETRY) && usableServersCount > 1) {
473 auto hp = reinterpret_cast<const HEADER*>(buf);
474
475 // Select a random server based on the query id
476 int selectedServer = (hp->id % usableServersCount) + 1;
477 res_set_usable_server(selectedServer, statp->nscount, usable_servers);
478 }
waynema0161acd2019-02-18 17:47:59 +0800479
Luke Huang43cc1b12019-10-15 19:06:42 +0900480 // Send request, RETRY times, or until successful.
waynemaa74195e2019-01-18 14:02:31 +0800481 int retryTimes = (flags & ANDROID_RESOLV_NO_RETRY) ? 1 : params.retry_count;
Luke Huang43cc1b12019-10-15 19:06:42 +0900482 int useTcp = buflen > PACKETSZ;
483 int gotsomewhere = 0;
484 int terrno = ETIMEDOUT;
Luke Huangba7bef92018-12-26 16:53:03 +0800485
486 for (int attempt = 0; attempt < retryTimes; ++attempt) {
Luke Huang43cc1b12019-10-15 19:06:42 +0900487 for (int ns = 0; ns < statp->nscount; ++ns) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900488 if (!usable_servers[ns]) continue;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900489
Luke Huang43cc1b12019-10-15 19:06:42 +0900490 *rcode = RCODE_INTERNAL_ERROR;
491
492 // Get server addr
493 const sockaddr* nsap = get_nsaddr(statp, ns);
494 const int nsaplen = sockaddrSize(nsap);
495
lifr94981782019-05-17 21:15:19 +0800496 static const int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
497 char abuf[NI_MAXHOST];
chenbruceacb832c2019-02-20 19:45:50 +0800498 if (getnameinfo(nsap, (socklen_t)nsaplen, abuf, sizeof(abuf), NULL, 0, niflags) == 0)
Ken Chenffc224a2019-03-19 17:41:28 +0800499 LOG(DEBUG) << __func__ << ": Querying server (# " << ns + 1
500 << ") address = " << abuf;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900501
Luke Huang43cc1b12019-10-15 19:06:42 +0900502 ::android::net::Protocol query_proto = useTcp ? PROTO_TCP : PROTO_UDP;
503 time_t now = 0;
504 int delay = 0;
505 bool fallbackTCP = false;
506 const bool shouldRecordStats = (attempt == 0);
507 int resplen;
lifrd4d9fbb2019-07-31 20:18:35 +0800508 Stopwatch queryStopwatch;
lifr128183a2020-01-08 18:04:50 +0800509 int retry_count_for_event = 0;
Luke Huang43cc1b12019-10-15 19:06:42 +0900510 if (useTcp) {
511 // TCP; at most one attempt per server.
Luke Huangba7bef92018-12-26 16:53:03 +0800512 attempt = retryTimes;
Luke Huang43cc1b12019-10-15 19:06:42 +0900513 resplen = send_vc(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &now,
514 rcode, &delay);
Ken Chen99344882020-01-01 14:59:38 +0800515
516 if (buflen <= PACKETSZ && resplen <= 0 &&
517 statp->tc_mode == aidl::android::net::IDnsResolver::TC_MODE_UDP_TCP) {
518 // reset to UDP for next query on next DNS server if resolver is currently doing
519 // TCP fallback retry and current server does not support TCP connectin
520 useTcp = false;
521 }
522 LOG(INFO) << __func__ << ": used send_vc " << resplen;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900523 } else {
Luke Huang43cc1b12019-10-15 19:06:42 +0900524 // UDP
525 resplen = send_dg(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &useTcp,
526 &gotsomewhere, &now, rcode, &delay);
527 fallbackTCP = useTcp ? true : false;
lifr128183a2020-01-08 18:04:50 +0800528 retry_count_for_event = attempt;
Ken Chen99344882020-01-01 14:59:38 +0800529 LOG(INFO) << __func__ << ": used send_dg " << resplen;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900530 }
Luke Huang43cc1b12019-10-15 19:06:42 +0900531
532 DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
533 dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
534 dnsQueryEvent->set_latency_micros(saturate_cast<int32_t>(queryStopwatch.timeTakenUs()));
535 dnsQueryEvent->set_dns_server_index(ns);
536 dnsQueryEvent->set_ip_version(ipFamilyToIPVersion(nsap->sa_family));
lifr128183a2020-01-08 18:04:50 +0800537 dnsQueryEvent->set_retry_times(retry_count_for_event);
Luke Huang43cc1b12019-10-15 19:06:42 +0900538 dnsQueryEvent->set_rcode(static_cast<NsRcode>(*rcode));
539 dnsQueryEvent->set_protocol(query_proto);
540 dnsQueryEvent->set_type(getQueryType(buf, buflen));
541
542 // Only record stats the first time we try a query. This ensures that
543 // queries that deterministically fail (e.g., a name that always returns
544 // SERVFAIL or times out) do not unduly affect the stats.
545 if (shouldRecordStats) {
546 res_sample sample;
547 _res_stats_set_sample(&sample, now, *rcode, delay);
548 resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, nsap, sample,
549 params.max_samples);
550 resolv_stats_add(statp->netid, IPSockAddr::toIPSockAddr(*nsap), dnsQueryEvent);
551 }
552
553 if (resplen == 0) continue;
554 if (fallbackTCP) {
555 ns--;
556 continue;
557 }
558 if (resplen < 0) {
559 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800560 statp->closeSockets();
Luke Huang43cc1b12019-10-15 19:06:42 +0900561 return -terrno;
562 };
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900563
Ken Chenffc224a2019-03-19 17:41:28 +0800564 LOG(DEBUG) << __func__ << ": got answer:";
chenbrucedd210722019-03-06 13:52:43 +0800565 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900566
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900567 if (cache_status == RESOLV_CACHE_NOTFOUND) {
Mike Yud1ec2542019-06-06 17:17:53 +0800568 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900569 }
Luke Huangadb0f5b2019-11-27 15:51:48 +0800570 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900571 return (resplen);
Bernie Innocenti9c575932018-09-07 21:10:25 +0900572 } // for each ns
573 } // for each retry
Luke Huangadb0f5b2019-11-27 15:51:48 +0800574 statp->closeSockets();
Luke Huang43cc1b12019-10-15 19:06:42 +0900575 terrno = useTcp ? terrno : gotsomewhere ? ETIMEDOUT : ECONNREFUSED;
576 // TODO: Remove errno once callers stop using it
577 errno = useTcp ? terrno
578 : gotsomewhere ? ETIMEDOUT /* no answer obtained */
579 : ECONNREFUSED /* no nameservers found */;
580
Luke Huangba7bef92018-12-26 16:53:03 +0800581 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800582 return -terrno;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900583}
584
585/* Private */
586
Bernie Innocenti9c575932018-09-07 21:10:25 +0900587static struct sockaddr* get_nsaddr(res_state statp, size_t n) {
Bernie Innocentic977ab72019-10-09 00:34:06 +0900588 return (struct sockaddr*)(void*)&statp->nsaddrs[n];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900589}
590
chenbruce99cbfd82019-09-05 15:08:13 +0800591static struct timespec get_timeout(res_state statp, const res_params* params, const int ns) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900592 int msec;
waynemaa74195e2019-01-18 14:02:31 +0800593 // Legacy algorithm which scales the timeout by nameserver number.
594 // For instance, with 4 nameservers: 5s, 2.5s, 5s, 10s
595 // This has no effect with 1 or 2 nameservers
596 msec = params->base_timeout_msec << ns;
597 if (ns > 0) {
598 msec /= statp->nscount;
599 }
600 // For safety, don't allow OEMs and experiments to configure a timeout shorter than 1s.
601 if (msec < 1000) {
602 msec = 1000; // Use at least 1000ms
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900603 }
Ken Chenffc224a2019-03-19 17:41:28 +0800604 LOG(INFO) << __func__ << ": using timeout of " << msec << " msec";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900605
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900606 struct timespec result;
607 result.tv_sec = msec / 1000;
608 result.tv_nsec = (msec % 1000) * 1000000;
609 return result;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900610}
611
chenbrucec51f1212019-09-12 16:59:33 +0800612static int send_vc(res_state statp, res_params* params, const uint8_t* buf, int buflen,
613 uint8_t* ans, int anssiz, int* terrno, int ns, time_t* at, int* rcode,
614 int* delay) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900615 *at = time(NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900616 *delay = 0;
617 const HEADER* hp = (const HEADER*) (const void*) buf;
618 HEADER* anhp = (HEADER*) (void*) ans;
619 struct sockaddr* nsap;
620 int nsaplen;
chenbruce0d470422019-03-28 18:44:37 +0800621 int truncating, connreset, n;
chenbrucec51f1212019-09-12 16:59:33 +0800622 uint8_t* cp;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900623
Ken Chenffc224a2019-03-19 17:41:28 +0800624 LOG(INFO) << __func__ << ": using send_vc";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900625
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900626 nsap = get_nsaddr(statp, (size_t) ns);
Mike Yu021c3e12019-10-08 17:29:34 +0800627 nsaplen = sockaddrSize(nsap);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900628
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900629 connreset = 0;
630same_ns:
631 truncating = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900632
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900633 struct timespec now = evNowTime();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900634
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900635 /* Are we still talking to whom we want to talk to? */
Luke Huangadb0f5b2019-11-27 15:51:48 +0800636 if (statp->tcp_nssock >= 0 && (statp->_flags & RES_F_VC) != 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900637 struct sockaddr_storage peer;
638 socklen_t size = sizeof peer;
639 unsigned old_mark;
640 socklen_t mark_size = sizeof(old_mark);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800641 if (getpeername(statp->tcp_nssock, (struct sockaddr*)(void*)&peer, &size) < 0 ||
642 !sock_eq((struct sockaddr*)(void*)&peer, nsap) ||
643 getsockopt(statp->tcp_nssock, SOL_SOCKET, SO_MARK, &old_mark, &mark_size) < 0 ||
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900644 old_mark != statp->_mark) {
Luke Huangadb0f5b2019-11-27 15:51:48 +0800645 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900646 }
647 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900648
Luke Huangadb0f5b2019-11-27 15:51:48 +0800649 if (statp->tcp_nssock < 0 || (statp->_flags & RES_F_VC) == 0) {
650 if (statp->tcp_nssock >= 0) statp->closeSockets();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900651
Luke Huangadb0f5b2019-11-27 15:51:48 +0800652 statp->tcp_nssock.reset(socket(nsap->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0));
653 if (statp->tcp_nssock < 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900654 switch (errno) {
655 case EPROTONOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900656 case EPFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900657 case EAFNOSUPPORT:
chenbruce018fdb22019-06-12 18:08:04 +0800658 PLOG(DEBUG) << __func__ << ": socket(vc): ";
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900659 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900660 default:
661 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800662 PLOG(DEBUG) << __func__ << ": socket(vc): ";
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900663 return -1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900664 }
665 }
Luke Huangadb0f5b2019-11-27 15:51:48 +0800666 resolv_tag_socket(statp->tcp_nssock, statp->uid, statp->pid);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900667 if (statp->_mark != MARK_UNSET) {
Luke Huangadb0f5b2019-11-27 15:51:48 +0800668 if (setsockopt(statp->tcp_nssock, SOL_SOCKET, SO_MARK, &statp->_mark,
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900669 sizeof(statp->_mark)) < 0) {
670 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800671 PLOG(DEBUG) << __func__ << ": setsockopt: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900672 return -1;
673 }
674 }
675 errno = 0;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800676 if (random_bind(statp->tcp_nssock, nsap->sa_family) < 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900677 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800678 dump_error("bind/vc", nsap, nsaplen);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800679 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900680 return (0);
681 }
Luke Huangadb0f5b2019-11-27 15:51:48 +0800682 if (connect_with_timeout(statp->tcp_nssock, nsap, (socklen_t)nsaplen,
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900683 get_timeout(statp, params, ns)) < 0) {
684 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800685 dump_error("connect/vc", nsap, nsaplen);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800686 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900687 /*
688 * The way connect_with_timeout() is implemented prevents us from reliably
689 * determining whether this was really a timeout or e.g. ECONNREFUSED. Since
690 * currently both cases are handled in the same way, there is no need to
691 * change this (yet). If we ever need to reliably distinguish between these
692 * cases, both connect_with_timeout() and retrying_poll() need to be
693 * modified, though.
694 */
695 *rcode = RCODE_TIMEOUT;
696 return (0);
697 }
698 statp->_flags |= RES_F_VC;
699 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900700
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900701 /*
702 * Send length & message
703 */
chenbruce0d470422019-03-28 18:44:37 +0800704 uint16_t len = htons(static_cast<uint16_t>(buflen));
Luke Huangc98fd802019-10-15 16:36:36 +0900705 const iovec iov[] = {
706 {.iov_base = &len, .iov_len = INT16SZ},
707 {.iov_base = const_cast<uint8_t*>(buf), .iov_len = static_cast<size_t>(buflen)},
708 };
Luke Huangadb0f5b2019-11-27 15:51:48 +0800709 if (writev(statp->tcp_nssock, iov, 2) != (INT16SZ + buflen)) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900710 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800711 PLOG(DEBUG) << __func__ << ": write failed: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800712 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900713 return (0);
714 }
715 /*
716 * Receive length & response
717 */
718read_len:
719 cp = ans;
720 len = INT16SZ;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800721 while ((n = read(statp->tcp_nssock, (char*)cp, (size_t)len)) > 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900722 cp += n;
723 if ((len -= n) == 0) break;
724 }
725 if (n <= 0) {
726 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800727 PLOG(DEBUG) << __func__ << ": read failed: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800728 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900729 /*
730 * A long running process might get its TCP
731 * connection reset if the remote server was
732 * restarted. Requery the server instead of
733 * trying a new one. When there is only one
734 * server, this means that a query might work
735 * instead of failing. We only allow one reset
736 * per query to prevent looping.
737 */
738 if (*terrno == ECONNRESET && !connreset) {
739 connreset = 1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900740 goto same_ns;
741 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900742 return (0);
743 }
chenbruce0d470422019-03-28 18:44:37 +0800744 uint16_t resplen = ntohs(*reinterpret_cast<const uint16_t*>(ans));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900745 if (resplen > anssiz) {
Ken Chenffc224a2019-03-19 17:41:28 +0800746 LOG(DEBUG) << __func__ << ": response truncated";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900747 truncating = 1;
748 len = anssiz;
749 } else
750 len = resplen;
751 if (len < HFIXEDSZ) {
752 /*
753 * Undersized message.
754 */
Ken Chenffc224a2019-03-19 17:41:28 +0800755 LOG(DEBUG) << __func__ << ": undersized: " << len;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900756 *terrno = EMSGSIZE;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800757 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900758 return (0);
759 }
760 cp = ans;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800761 while (len != 0 && (n = read(statp->tcp_nssock, (char*)cp, (size_t)len)) > 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900762 cp += n;
763 len -= n;
764 }
765 if (n <= 0) {
766 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800767 PLOG(DEBUG) << __func__ << ": read(vc): ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800768 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900769 return (0);
770 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900771
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900772 if (truncating) {
773 /*
774 * Flush rest of answer so connection stays in synch.
775 */
776 anhp->tc = 1;
777 len = resplen - anssiz;
778 while (len != 0) {
779 char junk[PACKETSZ];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900780
Luke Huangadb0f5b2019-11-27 15:51:48 +0800781 n = read(statp->tcp_nssock, junk, (len > sizeof junk) ? sizeof junk : len);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900782 if (n > 0)
783 len -= n;
784 else
785 break;
786 }
787 }
788 /*
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900789 * If the calling application has bailed out of
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900790 * a previous call and failed to arrange to have
791 * the circuit closed or the server has got
792 * itself confused, then drop the packet and
793 * wait for the correct one.
794 */
795 if (hp->id != anhp->id) {
Ken Chenffc224a2019-03-19 17:41:28 +0800796 LOG(DEBUG) << __func__ << ": ld answer (unexpected):";
chenbrucedd210722019-03-06 13:52:43 +0800797 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900798 goto read_len;
799 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900800
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900801 /*
802 * All is well, or the error is fatal. Signal that the
803 * next nameserver ought not be tried.
804 */
805 if (resplen > 0) {
806 struct timespec done = evNowTime();
807 *delay = _res_stats_calculate_rtt(&done, &now);
808 *rcode = anhp->rcode;
809 }
810 return (resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900811}
812
813/* return -1 on error (errno set), 0 on success */
Luke Huangc98fd802019-10-15 16:36:36 +0900814static int connect_with_timeout(int sock, const sockaddr* nsap, socklen_t salen,
815 const timespec timeout) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900816 int res, origflags;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900817
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900818 origflags = fcntl(sock, F_GETFL, 0);
819 fcntl(sock, F_SETFL, origflags | O_NONBLOCK);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900820
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900821 res = connect(sock, nsap, salen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900822 if (res < 0 && errno != EINPROGRESS) {
823 res = -1;
824 goto done;
825 }
826 if (res != 0) {
Luke Huangc98fd802019-10-15 16:36:36 +0900827 timespec now = evNowTime();
828 timespec finish = evAddTime(now, timeout);
Ken Chenffc224a2019-03-19 17:41:28 +0800829 LOG(INFO) << __func__ << ": " << sock << " send_vc";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900830 res = retrying_poll(sock, POLLIN | POLLOUT, &finish);
831 if (res <= 0) {
832 res = -1;
833 }
834 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900835done:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900836 fcntl(sock, F_SETFL, origflags);
Ken Chenffc224a2019-03-19 17:41:28 +0800837 LOG(INFO) << __func__ << ": " << sock << " connect_with_const timeout returning " << res;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900838 return res;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900839}
840
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900841static int retrying_poll(const int sock, const short events, const struct timespec* finish) {
842 struct timespec now, timeout;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900843
844retry:
Ken Chenffc224a2019-03-19 17:41:28 +0800845 LOG(INFO) << __func__ << ": " << sock << " retrying_poll";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900846
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900847 now = evNowTime();
848 if (evCmpTime(*finish, now) > 0)
849 timeout = evSubTime(*finish, now);
850 else
851 timeout = evConsTime(0L, 0L);
852 struct pollfd fds = {.fd = sock, .events = events};
853 int n = ppoll(&fds, 1, &timeout, /*sigmask=*/NULL);
854 if (n == 0) {
Ken Chenffc224a2019-03-19 17:41:28 +0800855 LOG(INFO) << __func__ << ": " << sock << "retrying_poll timeout";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900856 errno = ETIMEDOUT;
857 return 0;
858 }
859 if (n < 0) {
860 if (errno == EINTR) goto retry;
Ken Chenffc224a2019-03-19 17:41:28 +0800861 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll failed";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900862 return n;
863 }
864 if (fds.revents & (POLLIN | POLLOUT | POLLERR)) {
865 int error;
866 socklen_t len = sizeof(error);
867 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error) {
868 errno = error;
Ken Chenffc224a2019-03-19 17:41:28 +0800869 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll getsockopt failed";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900870 return -1;
871 }
872 }
Ken Chenffc224a2019-03-19 17:41:28 +0800873 LOG(INFO) << __func__ << ": " << sock << " retrying_poll returning " << n;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900874 return n;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900875}
876
Luke Huangbff43fc2019-11-12 15:54:47 +0800877bool ignoreInvalidAnswer(res_state statp, const sockaddr_storage& from, const uint8_t* buf,
878 int buflen, uint8_t* ans, int anssiz) {
879 const HEADER* hp = (const HEADER*)(const void*)buf;
880 HEADER* anhp = (HEADER*)(void*)ans;
881 if (hp->id != anhp->id) {
882 // response from old query, ignore it.
883 LOG(DEBUG) << __func__ << ": old answer:";
884 return true;
885 }
886 if (!res_ourserver_p(statp, (sockaddr*)(void*)&from)) {
887 // response from wrong server? ignore it.
888 LOG(DEBUG) << __func__ << ": not our server:";
889 return true;
890 }
891 if (!res_queriesmatch(buf, buf + buflen, ans, ans + anssiz)) {
892 // response contains wrong query? ignore it.
893 LOG(DEBUG) << __func__ << ": wrong query name:";
894 return true;
895 }
896 return false;
897}
898
chenbrucec51f1212019-09-12 16:59:33 +0800899static int send_dg(res_state statp, res_params* params, const uint8_t* buf, int buflen,
900 uint8_t* ans, int anssiz, int* terrno, int ns, int* v_circuit, int* gotsomewhere,
901 time_t* at, int* rcode, int* delay) {
Luke Huangbff43fc2019-11-12 15:54:47 +0800902 *at = time(nullptr);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900903 *delay = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900904
Luke Huangbff43fc2019-11-12 15:54:47 +0800905 const sockaddr* nsap = get_nsaddr(statp, (size_t)ns);
906 const int nsaplen = sockaddrSize(nsap);
907
Bernie Innocentibb330742019-10-09 00:55:53 +0900908 if (statp->nssocks[ns] == -1) {
Luke Huangadb0f5b2019-11-27 15:51:48 +0800909 statp->nssocks[ns].reset(socket(nsap->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0));
Bernie Innocentibb330742019-10-09 00:55:53 +0900910 if (statp->nssocks[ns] < 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900911 switch (errno) {
912 case EPROTONOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900913 case EPFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900914 case EAFNOSUPPORT:
chenbruce018fdb22019-06-12 18:08:04 +0800915 PLOG(DEBUG) << __func__ << ": socket(dg): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900916 return (0);
917 default:
918 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800919 PLOG(DEBUG) << __func__ << ": socket(dg): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900920 return (-1);
921 }
922 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900923
Praveen Moongalam Thyagarajan8ab18ba2019-09-04 14:46:50 -0700924 resolv_tag_socket(statp->nssocks[ns], statp->uid, statp->pid);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900925 if (statp->_mark != MARK_UNSET) {
Bernie Innocentibb330742019-10-09 00:55:53 +0900926 if (setsockopt(statp->nssocks[ns], SOL_SOCKET, SO_MARK, &(statp->_mark),
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900927 sizeof(statp->_mark)) < 0) {
Luke Huangadb0f5b2019-11-27 15:51:48 +0800928 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900929 return -1;
930 }
931 }
chenbruceb9cce7b2019-07-15 16:14:53 +0800932 // Use a "connected" datagram socket to receive an ECONNREFUSED error
933 // on the next socket operation when the server responds with an
934 // ICMP port-unreachable error. This way we can detect the absence of
935 // a nameserver without timing out.
Bernie Innocentibb330742019-10-09 00:55:53 +0900936 if (random_bind(statp->nssocks[ns], nsap->sa_family) < 0) {
chenbruce018fdb22019-06-12 18:08:04 +0800937 dump_error("bind(dg)", nsap, nsaplen);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800938 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900939 return (0);
940 }
Bernie Innocentibb330742019-10-09 00:55:53 +0900941 if (connect(statp->nssocks[ns], nsap, (socklen_t)nsaplen) < 0) {
chenbruce018fdb22019-06-12 18:08:04 +0800942 dump_error("connect(dg)", nsap, nsaplen);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800943 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900944 return (0);
945 }
Ken Chenffc224a2019-03-19 17:41:28 +0800946 LOG(DEBUG) << __func__ << ": new DG socket";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900947 }
Luke Huangbff43fc2019-11-12 15:54:47 +0800948 if (send(statp->nssocks[ns], (const char*)buf, (size_t)buflen, 0) != buflen) {
chenbruce018fdb22019-06-12 18:08:04 +0800949 PLOG(DEBUG) << __func__ << ": send: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800950 statp->closeSockets();
Bernie Innocenti3952ccc2019-03-03 19:39:53 +0900951 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900952 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900953
Luke Huangbff43fc2019-11-12 15:54:47 +0800954 timespec timeout = get_timeout(statp, params, ns);
955 timespec now = evNowTime();
956 timespec finish = evAddTime(now, timeout);
957 for (;;) {
958 // Wait for reply.
959 int n = retrying_poll(statp->nssocks[ns], POLLIN, &finish);
960 if (n == 0) {
961 *rcode = RCODE_TIMEOUT;
962 LOG(DEBUG) << __func__ << ": timeout";
963 *gotsomewhere = 1;
964 return 0;
965 }
966 if (n < 0) {
967 PLOG(DEBUG) << __func__ << ": poll: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800968 statp->closeSockets();
Luke Huangbff43fc2019-11-12 15:54:47 +0800969 return 0;
970 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900971
Luke Huangbff43fc2019-11-12 15:54:47 +0800972 errno = 0;
973 sockaddr_storage from;
974 socklen_t fromlen = sizeof(from);
975 int resplen = recvfrom(statp->nssocks[ns], (char*)ans, (size_t)anssiz, 0,
976 (sockaddr*)(void*)&from, &fromlen);
977 if (resplen <= 0) {
978 PLOG(DEBUG) << __func__ << ": recvfrom: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800979 statp->closeSockets();
Luke Huangbff43fc2019-11-12 15:54:47 +0800980 return 0;
981 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900982 *gotsomewhere = 1;
Luke Huangbff43fc2019-11-12 15:54:47 +0800983 if (resplen < HFIXEDSZ) {
984 // Undersized message.
985 LOG(DEBUG) << __func__ << ": undersized: " << resplen;
986 *terrno = EMSGSIZE;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800987 statp->closeSockets();
Luke Huangbff43fc2019-11-12 15:54:47 +0800988 return 0;
989 }
990
991 if (ignoreInvalidAnswer(statp, from, buf, buflen, ans, anssiz)) {
992 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
993 continue;
994 }
995
996 HEADER* anhp = (HEADER*)(void*)ans;
997 if (anhp->rcode == FORMERR && (statp->netcontext_flags & NET_CONTEXT_FLAG_USE_EDNS)) {
998 // Do not retry if the server do not understand EDNS0.
999 // The case has to be captured here, as FORMERR packet do not
1000 // carry query section, hence res_queriesmatch() returns 0.
1001 LOG(DEBUG) << __func__ << ": server rejected query with EDNS0:";
1002 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
1003 // record the error
1004 statp->_flags |= RES_F_EDNS0ERR;
Luke Huangadb0f5b2019-11-27 15:51:48 +08001005 statp->closeSockets();
Luke Huangbff43fc2019-11-12 15:54:47 +08001006 return 0;
1007 }
1008
1009 timespec done = evNowTime();
1010 *delay = _res_stats_calculate_rtt(&done, &now);
1011 if (anhp->rcode == SERVFAIL || anhp->rcode == NOTIMP || anhp->rcode == REFUSED) {
1012 LOG(DEBUG) << __func__ << ": server rejected query:";
1013 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Luke Huangadb0f5b2019-11-27 15:51:48 +08001014 statp->closeSockets();
Luke Huangbff43fc2019-11-12 15:54:47 +08001015 *rcode = anhp->rcode;
1016 return 0;
1017 }
1018 if (anhp->tc) {
1019 // To get the rest of answer,
1020 // use TCP with same server.
1021 LOG(DEBUG) << __func__ << ": truncated answer";
1022 *v_circuit = 1;
Luke Huangadb0f5b2019-11-27 15:51:48 +08001023 statp->closeSockets();
Luke Huangbff43fc2019-11-12 15:54:47 +08001024 return 1;
1025 }
1026 // All is well, or the error is fatal. Signal that the
1027 // next nameserver ought not be tried.
1028 if (resplen > 0) {
1029 *rcode = anhp->rcode;
1030 }
1031 return resplen;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001032 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001033}
1034
chenbruce018fdb22019-06-12 18:08:04 +08001035static void dump_error(const char* str, const struct sockaddr* address, int alen) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001036 char hbuf[NI_MAXHOST];
1037 char sbuf[NI_MAXSERV];
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001038 constexpr int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
Luke Huangc98fd802019-10-15 16:36:36 +09001039 const int err = errno;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001040
chenbruce018fdb22019-06-12 18:08:04 +08001041 if (!WOULD_LOG(DEBUG)) return;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001042
chenbruce018fdb22019-06-12 18:08:04 +08001043 if (getnameinfo(address, (socklen_t)alen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf), niflags)) {
1044 strncpy(hbuf, "?", sizeof(hbuf) - 1);
1045 hbuf[sizeof(hbuf) - 1] = '\0';
1046 strncpy(sbuf, "?", sizeof(sbuf) - 1);
1047 sbuf[sizeof(sbuf) - 1] = '\0';
Elliott Hughes3b8f5902019-03-08 12:02:55 -08001048 }
Luke Huangc98fd802019-10-15 16:36:36 +09001049 errno = err;
chenbruce018fdb22019-06-12 18:08:04 +08001050 PLOG(DEBUG) << __func__ << ": " << str << " ([" << hbuf << "]." << sbuf << "): ";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001051}
1052
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001053static int sock_eq(struct sockaddr* a, struct sockaddr* b) {
1054 struct sockaddr_in *a4, *b4;
1055 struct sockaddr_in6 *a6, *b6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001056
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001057 if (a->sa_family != b->sa_family) return 0;
1058 switch (a->sa_family) {
1059 case AF_INET:
1060 a4 = (struct sockaddr_in*) (void*) a;
1061 b4 = (struct sockaddr_in*) (void*) b;
1062 return a4->sin_port == b4->sin_port && a4->sin_addr.s_addr == b4->sin_addr.s_addr;
1063 case AF_INET6:
1064 a6 = (struct sockaddr_in6*) (void*) a;
1065 b6 = (struct sockaddr_in6*) (void*) b;
1066 return a6->sin6_port == b6->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001067#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001068 a6->sin6_scope_id == b6->sin6_scope_id &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001069#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001070 IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
1071 default:
1072 return 0;
1073 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001074}
Mike Yub601ff72018-11-01 20:07:00 +08001075
lifr6b83a6f2019-07-26 03:17:43 +08001076PrivateDnsModes convertEnumType(PrivateDnsMode privateDnsmode) {
1077 switch (privateDnsmode) {
1078 case PrivateDnsMode::OFF:
1079 return PrivateDnsModes::PDM_OFF;
1080 case PrivateDnsMode::OPPORTUNISTIC:
1081 return PrivateDnsModes::PDM_OPPORTUNISTIC;
1082 case PrivateDnsMode::STRICT:
1083 return PrivateDnsModes::PDM_STRICT;
Mike Yu99b8dc72019-11-22 17:45:31 +08001084 default:
1085 return PrivateDnsModes::PDM_UNKNOWN;
lifr6b83a6f2019-07-26 03:17:43 +08001086 }
lifr6b83a6f2019-07-26 03:17:43 +08001087}
1088
Luke Huangd7aa7b42018-11-21 20:37:50 +08001089static int res_tls_send(res_state statp, const Slice query, const Slice answer, int* rcode,
Mike Yubfb1b342018-11-06 15:42:36 +08001090 bool* fallback) {
1091 int resplen = 0;
Mike Yub601ff72018-11-01 20:07:00 +08001092 const unsigned netId = statp->netid;
Mike Yub601ff72018-11-01 20:07:00 +08001093
Mike Yubfb1b342018-11-06 15:42:36 +08001094 PrivateDnsStatus privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
lifr6b83a6f2019-07-26 03:17:43 +08001095 statp->event->set_private_dns_modes(convertEnumType(privateDnsStatus.mode));
Mike Yubfb1b342018-11-06 15:42:36 +08001096
1097 if (privateDnsStatus.mode == PrivateDnsMode::OFF) {
1098 *fallback = true;
1099 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001100 }
1101
Mike Yu3e829062019-08-07 14:01:14 +08001102 if (privateDnsStatus.validatedServers().empty()) {
Mike Yub601ff72018-11-01 20:07:00 +08001103 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
Mike Yubfb1b342018-11-06 15:42:36 +08001104 *fallback = true;
1105 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001106 } else {
1107 // Sleep and iterate some small number of times checking for the
1108 // arrival of resolved and validated server IP addresses, instead
1109 // of returning an immediate error.
Mike Yu4f3747b2018-12-02 17:54:29 +09001110 // This is needed because as soon as a network becomes the default network, apps will
1111 // send DNS queries on that network. If no servers have yet validated, and we do not
1112 // block those queries, they would immediately fail, causing application-visible errors.
1113 // Note that this can happen even before the network validates, since an unvalidated
1114 // network can become the default network if no validated networks are available.
1115 //
1116 // TODO: see if there is a better way to address this problem, such as buffering the
1117 // queries in a queue or only blocking queries for the first few seconds after a default
1118 // network change.
Mike Yubfb1b342018-11-06 15:42:36 +08001119 for (int i = 0; i < 42; i++) {
1120 std::this_thread::sleep_for(std::chrono::milliseconds(100));
Mike Yu3e829062019-08-07 14:01:14 +08001121 // Calling getStatus() to merely check if there's any validated server seems
1122 // wasteful. Consider adding a new method in PrivateDnsConfiguration for speed ups.
1123 if (!gPrivateDnsConfiguration.getStatus(netId).validatedServers().empty()) {
Mike Yubfb1b342018-11-06 15:42:36 +08001124 privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
1125 break;
1126 }
1127 }
Mike Yu3e829062019-08-07 14:01:14 +08001128 if (privateDnsStatus.validatedServers().empty()) {
Mike Yubfb1b342018-11-06 15:42:36 +08001129 return -1;
1130 }
Mike Yub601ff72018-11-01 20:07:00 +08001131 }
1132 }
1133
chenbruceacb832c2019-02-20 19:45:50 +08001134 LOG(INFO) << __func__ << ": performing query over TLS";
Mike Yub601ff72018-11-01 20:07:00 +08001135
Mike Yu3e829062019-08-07 14:01:14 +08001136 const auto response = sDnsTlsDispatcher.query(privateDnsStatus.validatedServers(), statp, query,
Mike Yubfb1b342018-11-06 15:42:36 +08001137 answer, &resplen);
Mike Yub601ff72018-11-01 20:07:00 +08001138
chenbruceacb832c2019-02-20 19:45:50 +08001139 LOG(INFO) << __func__ << ": TLS query result: " << static_cast<int>(response);
Mike Yub601ff72018-11-01 20:07:00 +08001140
1141 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
1142 // In opportunistic mode, handle falling back to cleartext in some
1143 // cases (DNS shouldn't fail if a validated opportunistic mode server
1144 // becomes unreachable for some reason).
1145 switch (response) {
Mike Yubfb1b342018-11-06 15:42:36 +08001146 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001147 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001148 return resplen;
Mike Yub601ff72018-11-01 20:07:00 +08001149 case DnsTlsTransport::Response::network_error:
Mike Yubfb1b342018-11-06 15:42:36 +08001150 // No need to set the error timeout here since it will fallback to UDP.
Mike Yub601ff72018-11-01 20:07:00 +08001151 case DnsTlsTransport::Response::internal_error:
1152 // Note: this will cause cleartext queries to be emitted, with
1153 // all of the EDNS0 goodness enabled. Fingers crossed. :-/
Mike Yubfb1b342018-11-06 15:42:36 +08001154 *fallback = true;
1155 [[fallthrough]];
Mike Yub601ff72018-11-01 20:07:00 +08001156 default:
Mike Yubfb1b342018-11-06 15:42:36 +08001157 return -1;
1158 }
1159 } else {
1160 // Strict mode
1161 switch (response) {
1162 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001163 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001164 return resplen;
1165 case DnsTlsTransport::Response::network_error:
1166 // This case happens when the query stored in DnsTlsTransport is expired since
1167 // either 1) the query has been tried for 3 times but no response or 2) fail to
1168 // establish the connection with the server.
Luke Huangd7aa7b42018-11-21 20:37:50 +08001169 *rcode = RCODE_TIMEOUT;
Mike Yubfb1b342018-11-06 15:42:36 +08001170 [[fallthrough]];
1171 default:
1172 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001173 }
1174 }
Mike Yub601ff72018-11-01 20:07:00 +08001175}
Luke Huang4973a0d2018-11-19 20:17:26 +08001176
Luke Huangba7bef92018-12-26 16:53:03 +08001177int resolv_res_nsend(const android_net_context* netContext, const uint8_t* msg, int msgLen,
lifr94981782019-05-17 21:15:19 +08001178 uint8_t* ans, int ansLen, int* rcode, uint32_t flags,
1179 NetworkDnsEventReported* event) {
1180 assert(event != nullptr);
Bernie Innocenti08487112019-10-11 21:14:13 +09001181 ResState res;
1182 res_init(&res, netContext, event);
Mike Yu021c3e12019-10-08 17:29:34 +08001183 resolv_populate_res_for_net(&res);
Luke Huang4973a0d2018-11-19 20:17:26 +08001184 *rcode = NOERROR;
Bernie Innocenti08487112019-10-11 21:14:13 +09001185 return res_nsend(&res, msg, msgLen, ans, ansLen, rcode, flags);
Bernie Innocentiec4219b2019-01-30 11:16:36 +09001186}