blob: 1dc5f57feeca2702a91ae4b2762608e3e3f51a57 [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>
86#include <netinet/in.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090087
88#include <errno.h>
89#include <fcntl.h>
90#include <netdb.h>
91#include <poll.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090092#include <signal.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090093#include <stdlib.h>
94#include <string.h>
95#include <time.h>
96#include <unistd.h>
97
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +090098#include <android-base/logging.h>
Bernie Innocenti758005f2019-02-19 18:08:36 +090099#include <android/multinetwork.h> // ResNsendFlags
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900100
Mike Yub601ff72018-11-01 20:07:00 +0800101#include <netdutils/Slice.h>
lifr94981782019-05-17 21:15:19 +0800102#include <netdutils/Stopwatch.h>
Bernie Innocentiec4219b2019-01-30 11:16:36 +0900103#include "DnsTlsDispatcher.h"
104#include "DnsTlsTransport.h"
105#include "PrivateDnsConfiguration.h"
Bernie Innocentiac18b122018-10-01 23:10:18 +0900106#include "netd_resolv/resolv.h"
107#include "netd_resolv/stats.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900108#include "private/android_filesystem_config.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"
lifr94981782019-05-17 21:15:19 +0800112#include "stats.pb.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 int get_salen(const struct sockaddr*);
140static struct sockaddr* get_nsaddr(res_state, size_t);
chenbrucec51f1212019-09-12 16:59:33 +0800141static int send_vc(res_state, res_params* params, const uint8_t*, int, uint8_t*, int, int*, int,
Bernie Innocenti758005f2019-02-19 18:08:36 +0900142 time_t*, int*, int*);
chenbrucec51f1212019-09-12 16:59:33 +0800143static int send_dg(res_state, res_params* params, const uint8_t*, int, uint8_t*, int, int*, int,
144 int*, int*, time_t*, int*, int*);
chenbruce018fdb22019-06-12 18:08:04 +0800145static void dump_error(const char*, const struct sockaddr*, int);
chenbruceacb832c2019-02-20 19:45:50 +0800146
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900147static int sock_eq(struct sockaddr*, struct sockaddr*);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900148static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
149 const struct timespec timeout);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900150static int retrying_poll(const int sock, short events, const struct timespec* finish);
Luke Huangd7aa7b42018-11-21 20:37:50 +0800151static int res_tls_send(res_state, const Slice query, const Slice answer, int* rcode,
Mike Yubfb1b342018-11-06 15:42:36 +0800152 bool* fallback);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900153
lifr94981782019-05-17 21:15:19 +0800154NsType getQueryType(const uint8_t* msg, size_t msgLen) {
155 ns_msg handle;
156 ns_rr rr;
157 if (ns_initparse((const uint8_t*)msg, msgLen, &handle) < 0 ||
158 ns_parserr(&handle, ns_s_qd, 0, &rr) < 0) {
159 return NS_T_INVALID;
160 }
161 return static_cast<NsType>(ns_rr_type(rr));
162}
163
164IpVersion ipFamilyToIPVersion(const int ipFamily) {
165 switch (ipFamily) {
166 case AF_INET:
167 return IV_IPV4;
168 case AF_INET6:
169 return IV_IPV6;
170 default:
171 return IV_UNKNOWN;
172 }
173}
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900174
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900175// BEGIN: Code copied from ISC eventlib
176// TODO: move away from this code
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900177#define BILLION 1000000000
178
179static struct timespec evConsTime(time_t sec, long nsec) {
180 struct timespec x;
181
182 x.tv_sec = sec;
183 x.tv_nsec = nsec;
184 return (x);
185}
186
187static struct timespec evAddTime(struct timespec addend1, struct timespec addend2) {
188 struct timespec x;
189
190 x.tv_sec = addend1.tv_sec + addend2.tv_sec;
191 x.tv_nsec = addend1.tv_nsec + addend2.tv_nsec;
192 if (x.tv_nsec >= BILLION) {
193 x.tv_sec++;
194 x.tv_nsec -= BILLION;
195 }
196 return (x);
197}
198
199static struct timespec evSubTime(struct timespec minuend, struct timespec subtrahend) {
200 struct timespec x;
201
202 x.tv_sec = minuend.tv_sec - subtrahend.tv_sec;
203 if (minuend.tv_nsec >= subtrahend.tv_nsec)
204 x.tv_nsec = minuend.tv_nsec - subtrahend.tv_nsec;
205 else {
206 x.tv_nsec = BILLION - subtrahend.tv_nsec + minuend.tv_nsec;
207 x.tv_sec--;
208 }
209 return (x);
210}
211
212static int evCmpTime(struct timespec a, struct timespec b) {
213#define SGN(x) ((x) < 0 ? (-1) : (x) > 0 ? (1) : (0));
214 time_t s = a.tv_sec - b.tv_sec;
215 long n;
216
217 if (s != 0) return SGN(s);
218
219 n = a.tv_nsec - b.tv_nsec;
220 return SGN(n);
221}
222
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900223static struct timespec evNowTime(void) {
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900224 struct timespec tsnow;
Bernie Innocentic1834822018-08-31 16:11:41 +0900225 clock_gettime(CLOCK_REALTIME, &tsnow);
226 return tsnow;
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900227}
228
229static struct iovec evConsIovec(void* buf, size_t cnt) {
230 struct iovec ret;
231
232 memset(&ret, 0xf5, sizeof ret);
233 ret.iov_base = buf;
234 ret.iov_len = cnt;
Bernie Innocentic1834822018-08-31 16:11:41 +0900235 return ret;
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900236}
237
238// END: Code copied from ISC eventlib
239
lifr94981782019-05-17 21:15:19 +0800240/* BIONIC-BEGIN: implement source port randomization */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900241static int random_bind(int s, int family) {
nuccachenb980f2f2018-10-23 17:10:58 +0800242 sockaddr_union u;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900243 int j;
244 socklen_t slen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900245
246 /* clear all, this also sets the IP4/6 address to 'any' */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900247 memset(&u, 0, sizeof u);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900248
249 switch (family) {
250 case AF_INET:
251 u.sin.sin_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900252 slen = sizeof u.sin;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900253 break;
254 case AF_INET6:
255 u.sin6.sin6_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900256 slen = sizeof u.sin6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900257 break;
258 default:
259 errno = EPROTO;
260 return -1;
261 }
262
263 /* first try to bind to a random source port a few times */
264 for (j = 0; j < 10; j++) {
265 /* find a random port between 1025 .. 65534 */
Luke Huangdda920f2019-02-13 14:05:02 +0800266 int port = 1025 + (arc4random_uniform(65535 - 1025));
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900267 if (family == AF_INET)
268 u.sin.sin_port = htons(port);
269 else
270 u.sin6.sin6_port = htons(port);
271
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900272 if (!bind(s, &u.sa, slen)) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900273 }
274
Bernie Innocenti9c575932018-09-07 21:10:25 +0900275 // nothing after 10 attempts, our network table is probably busy
276 // let the system decide which port is best
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900277 if (family == AF_INET)
278 u.sin.sin_port = 0;
279 else
280 u.sin6.sin6_port = 0;
281
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900282 return bind(s, &u.sa, slen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900283}
284/* BIONIC-END */
285
Luke Huang70931aa2019-01-31 11:57:41 +0800286// Disables all nameservers other than selectedServer
287static void res_set_usable_server(int selectedServer, int nscount, bool usable_servers[]) {
288 int usableIndex = 0;
289 for (int ns = 0; ns < nscount; ns++) {
290 if (usable_servers[ns]) ++usableIndex;
291 if (usableIndex != selectedServer) usable_servers[ns] = false;
292 }
293}
294
Bernie Innocentia6f40ca2019-10-09 15:22:41 +0900295// Looks up the nameserver address in res.nsaddrs[], returns true if found, otherwise false.
296static bool res_ourserver_p(res_state statp, const sockaddr* sa) {
Bernie Innocenti2e8540b2018-09-26 11:52:04 +0900297 const sockaddr_in *inp, *srv;
298 const sockaddr_in6 *in6p, *srv6;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900299 int ns;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900300
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900301 switch (sa->sa_family) {
302 case AF_INET:
303 inp = (const struct sockaddr_in*) (const void*) sa;
304 for (ns = 0; ns < statp->nscount; ns++) {
305 srv = (struct sockaddr_in*) (void*) get_nsaddr(statp, (size_t) ns);
306 if (srv->sin_family == inp->sin_family && srv->sin_port == inp->sin_port &&
307 (srv->sin_addr.s_addr == INADDR_ANY ||
308 srv->sin_addr.s_addr == inp->sin_addr.s_addr))
Bernie Innocentia6f40ca2019-10-09 15:22:41 +0900309 return true;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900310 }
311 break;
312 case AF_INET6:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900313 in6p = (const struct sockaddr_in6*) (const void*) sa;
314 for (ns = 0; ns < statp->nscount; ns++) {
315 srv6 = (struct sockaddr_in6*) (void*) get_nsaddr(statp, (size_t) ns);
316 if (srv6->sin6_family == in6p->sin6_family && srv6->sin6_port == in6p->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900317#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900318 (srv6->sin6_scope_id == 0 || srv6->sin6_scope_id == in6p->sin6_scope_id) &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900319#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900320 (IN6_IS_ADDR_UNSPECIFIED(&srv6->sin6_addr) ||
321 IN6_ARE_ADDR_EQUAL(&srv6->sin6_addr, &in6p->sin6_addr)))
Bernie Innocentia6f40ca2019-10-09 15:22:41 +0900322 return true;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900323 }
324 break;
325 default:
326 break;
327 }
Bernie Innocentia6f40ca2019-10-09 15:22:41 +0900328 return false;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900329}
330
331/* int
Bernie Innocenti9c575932018-09-07 21:10:25 +0900332 * res_nameinquery(name, type, cl, buf, eom)
333 * look for (name, type, cl) in the query section of packet (buf, eom)
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900334 * requires:
335 * buf + HFIXEDSZ <= eom
336 * returns:
337 * -1 : format error
338 * 0 : not found
339 * >0 : found
340 * author:
341 * paul vixie, 29may94
342 */
chenbrucec51f1212019-09-12 16:59:33 +0800343int res_nameinquery(const char* name, int type, int cl, const uint8_t* buf, const uint8_t* eom) {
344 const uint8_t* cp = buf + HFIXEDSZ;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900345 int qdcount = ntohs(((const HEADER*) (const void*) buf)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900346
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900347 while (qdcount-- > 0) {
348 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900349 int n = dn_expand(buf, eom, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900350 if (n < 0) return (-1);
351 cp += n;
352 if (cp + 2 * INT16SZ > eom) return (-1);
chenbruce0d470422019-03-28 18:44:37 +0800353 int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900354 cp += INT16SZ;
chenbruce0d470422019-03-28 18:44:37 +0800355 int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900356 cp += INT16SZ;
Bernie Innocenti9c575932018-09-07 21:10:25 +0900357 if (ttype == type && tclass == cl && ns_samename(tname, name) == 1) return (1);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900358 }
359 return (0);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900360}
361
362/* int
363 * res_queriesmatch(buf1, eom1, buf2, eom2)
364 * is there a 1:1 mapping of (name,type,class)
365 * in (buf1,eom1) and (buf2,eom2)?
366 * returns:
367 * -1 : format error
368 * 0 : not a 1:1 mapping
369 * >0 : is a 1:1 mapping
370 * author:
371 * paul vixie, 29may94
372 */
chenbrucec51f1212019-09-12 16:59:33 +0800373int res_queriesmatch(const uint8_t* buf1, const uint8_t* eom1, const uint8_t* buf2,
374 const uint8_t* eom2) {
375 const uint8_t* cp = buf1 + HFIXEDSZ;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900376 int qdcount = ntohs(((const HEADER*) (const void*) buf1)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900377
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900378 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2) return (-1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900379
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900380 /*
381 * Only header section present in replies to
382 * dynamic update packets.
383 */
384 if ((((const HEADER*) (const void*) buf1)->opcode == ns_o_update) &&
385 (((const HEADER*) (const void*) buf2)->opcode == ns_o_update))
386 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900387
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900388 if (qdcount != ntohs(((const HEADER*) (const void*) buf2)->qdcount)) return (0);
389 while (qdcount-- > 0) {
390 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900391 int n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900392 if (n < 0) return (-1);
393 cp += n;
394 if (cp + 2 * INT16SZ > eom1) return (-1);
chenbruce0d470422019-03-28 18:44:37 +0800395 int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900396 cp += INT16SZ;
chenbruce0d470422019-03-28 18:44:37 +0800397 int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900398 cp += INT16SZ;
399 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2)) return (0);
400 }
401 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900402}
403
lifr94981782019-05-17 21:15:19 +0800404static DnsQueryEvent* addDnsQueryEvent(NetworkDnsEventReported* event) {
405 return event->mutable_dns_query_events()->add_dns_query_event();
406}
407
chenbrucec51f1212019-09-12 16:59:33 +0800408int 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 +0800409 uint32_t flags) {
Bernie Innocenti9c575932018-09-07 21:10:25 +0900410 int gotsomewhere, terrno, v_circuit, resplen, n;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900411 ResolvCacheStatus cache_status = RESOLV_CACHE_UNSUPPORTED;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900412
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900413 if (anssiz < HFIXEDSZ) {
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800414 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900415 errno = EINVAL;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800416 return -EINVAL;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900417 }
Bernie Innocenti3952ccc2019-03-03 19:39:53 +0900418 LOG(DEBUG) << __func__;
chenbrucedd210722019-03-06 13:52:43 +0800419 res_pquery(buf, buflen);
chenbruceacb832c2019-02-20 19:45:50 +0800420
chenbruce018fdb22019-06-12 18:08:04 +0800421 v_circuit = buflen > PACKETSZ;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900422 gotsomewhere = 0;
423 terrno = ETIMEDOUT;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900424
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900425 int anslen = 0;
lifrd4d9fbb2019-07-31 20:18:35 +0800426 Stopwatch cacheStopwatch;
Mike Yud1ec2542019-06-06 17:17:53 +0800427 cache_status = resolv_cache_lookup(statp->netid, buf, buflen, ans, anssiz, &anslen, flags);
lifrd4d9fbb2019-07-31 20:18:35 +0800428 const int32_t cacheLatencyUs = saturate_cast<int32_t>(cacheStopwatch.timeTakenUs());
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900429 if (cache_status == RESOLV_CACHE_FOUND) {
Luke Huang83c9b4b2019-02-27 18:18:01 +0800430 HEADER* hp = (HEADER*)(void*)ans;
431 *rcode = hp->rcode;
lifr94981782019-05-17 21:15:19 +0800432 DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
433 dnsQueryEvent->set_latency_micros(cacheLatencyUs);
434 dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900435 return anslen;
436 } else if (cache_status != RESOLV_CACHE_UNSUPPORTED) {
437 // had a cache miss for a known network, so populate the thread private
438 // data so the normal resolve path can do its thing
439 _resolv_populate_res_for_net(statp);
440 }
441 if (statp->nscount == 0) {
442 // We have no nameservers configured, so there's no point trying.
443 // Tell the cache the query failed, or any retries and anyone else asking the same
444 // question will block for PENDING_REQUEST_TIMEOUT seconds instead of failing fast.
Luke Huangba7bef92018-12-26 16:53:03 +0800445 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800446
447 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900448 errno = ESRCH;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800449 return -ESRCH;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900450 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900451
Bernie Innocenti758005f2019-02-19 18:08:36 +0900452 res_stats stats[MAXNS];
453 res_params params;
waynema0161acd2019-02-18 17:47:59 +0800454 int revision_id = resolv_cache_get_resolver_stats(statp->netid, &params, stats);
lifra1b37f12019-02-13 17:33:57 +0800455 if (revision_id < 0) {
456 // TODO: Remove errno once callers stop using it
457 errno = ESRCH;
458 return -ESRCH;
459 }
waynema0161acd2019-02-18 17:47:59 +0800460 bool usable_servers[MAXNS];
Luke Huang70931aa2019-01-31 11:57:41 +0800461 int usableServersCount = android_net_res_stats_get_usable_servers(
462 &params, stats, statp->nscount, usable_servers);
463
464 if ((flags & ANDROID_RESOLV_NO_RETRY) && usableServersCount > 1) {
465 auto hp = reinterpret_cast<const HEADER*>(buf);
466
467 // Select a random server based on the query id
468 int selectedServer = (hp->id % usableServersCount) + 1;
469 res_set_usable_server(selectedServer, statp->nscount, usable_servers);
470 }
waynema0161acd2019-02-18 17:47:59 +0800471
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900472 /*
473 * Send request, RETRY times, or until successful.
474 */
waynemaa74195e2019-01-18 14:02:31 +0800475 int retryTimes = (flags & ANDROID_RESOLV_NO_RETRY) ? 1 : params.retry_count;
Luke Huangba7bef92018-12-26 16:53:03 +0800476
477 for (int attempt = 0; attempt < retryTimes; ++attempt) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900478
Bernie Innocenti9c575932018-09-07 21:10:25 +0900479 for (int ns = 0; ns < statp->nscount; ns++) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900480 if (!usable_servers[ns]) continue;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900481 int nsaplen;
482 time_t now = 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900483 int delay = 0;
Mike Yubfb1b342018-11-06 15:42:36 +0800484 *rcode = RCODE_INTERNAL_ERROR;
lifr94981782019-05-17 21:15:19 +0800485 const sockaddr* nsap = get_nsaddr(statp, ns);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900486 nsaplen = get_salen(nsap);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900487
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900488 same_ns:
Mike Yubfb1b342018-11-06 15:42:36 +0800489 // TODO: Since we expect there is only one DNS server being queried here while this
490 // function tries to query all of private DNS servers. Consider moving it to other
491 // reasonable place. In addition, maybe add stats for private DNS.
chenbruced8cbb9b2019-06-20 18:25:28 +0800492 if (!(statp->netcontext_flags & NET_CONTEXT_FLAG_USE_LOCAL_NAMESERVERS)) {
Mike Yubfb1b342018-11-06 15:42:36 +0800493 bool fallback = false;
chenbrucec51f1212019-09-12 16:59:33 +0800494 resplen = res_tls_send(statp, Slice(const_cast<uint8_t*>(buf), buflen),
Mike Yubfb1b342018-11-06 15:42:36 +0800495 Slice(ans, anssiz), rcode, &fallback);
496 if (resplen > 0) {
Mike Yu34433c62019-08-20 20:17:36 +0800497 LOG(DEBUG) << __func__ << ": got answer from DoT";
498 res_pquery(ans, resplen);
Mike Yubfb1b342018-11-06 15:42:36 +0800499 if (cache_status == RESOLV_CACHE_NOTFOUND) {
Mike Yud1ec2542019-06-06 17:17:53 +0800500 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
Mike Yubfb1b342018-11-06 15:42:36 +0800501 }
502 return resplen;
Mike Yub601ff72018-11-01 20:07:00 +0800503 }
Mike Yubfb1b342018-11-06 15:42:36 +0800504 if (!fallback) {
Luke Huangba7bef92018-12-26 16:53:03 +0800505 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800506 res_nclose(statp);
507 return -terrno;
Mike Yubfb1b342018-11-06 15:42:36 +0800508 }
509 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900510
lifr94981782019-05-17 21:15:19 +0800511 static const int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
512 char abuf[NI_MAXHOST];
513 DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
514 dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
chenbruceacb832c2019-02-20 19:45:50 +0800515
516 if (getnameinfo(nsap, (socklen_t)nsaplen, abuf, sizeof(abuf), NULL, 0, niflags) == 0)
Ken Chenffc224a2019-03-19 17:41:28 +0800517 LOG(DEBUG) << __func__ << ": Querying server (# " << ns + 1
518 << ") address = " << abuf;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900519
lifrd4d9fbb2019-07-31 20:18:35 +0800520 Stopwatch queryStopwatch;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900521 if (v_circuit) {
522 /* Use VC; at most one attempt per server. */
Luke Huangba7bef92018-12-26 16:53:03 +0800523 bool shouldRecordStats = (attempt == 0);
524 attempt = retryTimes;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900525
Mike Yubfb1b342018-11-06 15:42:36 +0800526 n = send_vc(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &now, rcode,
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900527 &delay);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900528
lifr94981782019-05-17 21:15:19 +0800529 dnsQueryEvent->set_latency_micros(
lifrd4d9fbb2019-07-31 20:18:35 +0800530 saturate_cast<int32_t>(queryStopwatch.timeTakenUs()));
lifr94981782019-05-17 21:15:19 +0800531 dnsQueryEvent->set_dns_server_index(ns);
532 dnsQueryEvent->set_ip_version(ipFamilyToIPVersion(nsap->sa_family));
533 dnsQueryEvent->set_retry_times(attempt);
534 dnsQueryEvent->set_rcode(static_cast<NsRcode>(*rcode));
535 dnsQueryEvent->set_protocol(PROTO_TCP);
536 dnsQueryEvent->set_type(getQueryType(buf, buflen));
537
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900538 /*
539 * Only record stats the first time we try a query. This ensures that
540 * queries that deterministically fail (e.g., a name that always returns
541 * SERVFAIL or times out) do not unduly affect the stats.
542 */
Luke Huangba7bef92018-12-26 16:53:03 +0800543 if (shouldRecordStats) {
Bernie Innocentiac18b122018-10-01 23:10:18 +0900544 res_sample sample;
Mike Yubfb1b342018-11-06 15:42:36 +0800545 _res_stats_set_sample(&sample, now, *rcode, delay);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900546 _resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, ns, &sample,
547 params.max_samples);
Mike Yue655b1d2019-08-28 17:49:59 +0800548 resolv_stats_add(statp->netid, IPSockAddr::toIPSockAddr(*nsap), dnsQueryEvent);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900549 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900550
Ken Chenffc224a2019-03-19 17:41:28 +0800551 LOG(INFO) << __func__ << ": used send_vc " << n;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900552
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800553 if (n < 0) {
Luke Huangba7bef92018-12-26 16:53:03 +0800554 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800555 res_nclose(statp);
556 return -terrno;
557 };
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900558 if (n == 0) goto next_ns;
559 resplen = n;
560 } else {
561 /* Use datagrams. */
Ken Chenffc224a2019-03-19 17:41:28 +0800562 LOG(INFO) << __func__ << ": using send_dg";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900563
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900564 n = send_dg(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &v_circuit,
Mike Yubfb1b342018-11-06 15:42:36 +0800565 &gotsomewhere, &now, rcode, &delay);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900566
lifr94981782019-05-17 21:15:19 +0800567 dnsQueryEvent->set_latency_micros(
lifrd4d9fbb2019-07-31 20:18:35 +0800568 saturate_cast<int32_t>(queryStopwatch.timeTakenUs()));
lifr94981782019-05-17 21:15:19 +0800569 dnsQueryEvent->set_dns_server_index(ns);
570 dnsQueryEvent->set_ip_version(ipFamilyToIPVersion(nsap->sa_family));
571 dnsQueryEvent->set_retry_times(attempt);
572 dnsQueryEvent->set_rcode(static_cast<NsRcode>(*rcode));
573 dnsQueryEvent->set_protocol(PROTO_UDP);
574 dnsQueryEvent->set_type(getQueryType(buf, buflen));
575
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900576 /* Only record stats the first time we try a query. See above. */
Bernie Innocenti9c575932018-09-07 21:10:25 +0900577 if (attempt == 0) {
Bernie Innocentiac18b122018-10-01 23:10:18 +0900578 res_sample sample;
Mike Yubfb1b342018-11-06 15:42:36 +0800579 _res_stats_set_sample(&sample, now, *rcode, delay);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900580 _resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, ns, &sample,
581 params.max_samples);
Mike Yue655b1d2019-08-28 17:49:59 +0800582 resolv_stats_add(statp->netid, IPSockAddr::toIPSockAddr(*nsap), dnsQueryEvent);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900583 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900584
Ken Chenffc224a2019-03-19 17:41:28 +0800585 LOG(INFO) << __func__ << ": used send_dg " << n;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900586
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800587 if (n < 0) {
Luke Huangba7bef92018-12-26 16:53:03 +0800588 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800589 res_nclose(statp);
590 return -terrno;
591 };
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900592 if (n == 0) goto next_ns;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900593 if (v_circuit) goto same_ns;
594 resplen = n;
595 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900596
Ken Chenffc224a2019-03-19 17:41:28 +0800597 LOG(DEBUG) << __func__ << ": got answer:";
chenbrucedd210722019-03-06 13:52:43 +0800598 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900599
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900600 if (cache_status == RESOLV_CACHE_NOTFOUND) {
Mike Yud1ec2542019-06-06 17:17:53 +0800601 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900602 }
chenbruce018fdb22019-06-12 18:08:04 +0800603 res_nclose(statp);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900604 return (resplen);
605 next_ns:;
Bernie Innocenti9c575932018-09-07 21:10:25 +0900606 } // for each ns
607 } // for each retry
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900608 res_nclose(statp);
609 if (!v_circuit) {
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800610 if (!gotsomewhere) {
611 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900612 errno = ECONNREFUSED; /* no nameservers found */
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800613 terrno = ECONNREFUSED;
614 } else {
615 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900616 errno = ETIMEDOUT; /* no answer obtained */
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800617 terrno = ETIMEDOUT;
618 }
619 } else {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900620 errno = terrno;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800621 }
Luke Huangba7bef92018-12-26 16:53:03 +0800622 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800623 return -terrno;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900624}
625
626/* Private */
627
Bernie Innocenti9c575932018-09-07 21:10:25 +0900628static int get_salen(const struct sockaddr* sa) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900629 if (sa->sa_family == AF_INET)
630 return (sizeof(struct sockaddr_in));
631 else if (sa->sa_family == AF_INET6)
632 return (sizeof(struct sockaddr_in6));
633 else
634 return (0); /* unknown, die on connect */
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900635}
636
Bernie Innocenti9c575932018-09-07 21:10:25 +0900637static struct sockaddr* get_nsaddr(res_state statp, size_t n) {
Bernie Innocentic977ab72019-10-09 00:34:06 +0900638 return (struct sockaddr*)(void*)&statp->nsaddrs[n];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900639}
640
chenbruce99cbfd82019-09-05 15:08:13 +0800641static struct timespec get_timeout(res_state statp, const res_params* params, const int ns) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900642 int msec;
waynemaa74195e2019-01-18 14:02:31 +0800643 // Legacy algorithm which scales the timeout by nameserver number.
644 // For instance, with 4 nameservers: 5s, 2.5s, 5s, 10s
645 // This has no effect with 1 or 2 nameservers
646 msec = params->base_timeout_msec << ns;
647 if (ns > 0) {
648 msec /= statp->nscount;
649 }
650 // For safety, don't allow OEMs and experiments to configure a timeout shorter than 1s.
651 if (msec < 1000) {
652 msec = 1000; // Use at least 1000ms
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900653 }
Ken Chenffc224a2019-03-19 17:41:28 +0800654 LOG(INFO) << __func__ << ": using timeout of " << msec << " msec";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900655
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900656 struct timespec result;
657 result.tv_sec = msec / 1000;
658 result.tv_nsec = (msec % 1000) * 1000000;
659 return result;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900660}
661
chenbrucec51f1212019-09-12 16:59:33 +0800662static int send_vc(res_state statp, res_params* params, const uint8_t* buf, int buflen,
663 uint8_t* ans, int anssiz, int* terrno, int ns, time_t* at, int* rcode,
664 int* delay) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900665 *at = time(NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900666 *delay = 0;
667 const HEADER* hp = (const HEADER*) (const void*) buf;
668 HEADER* anhp = (HEADER*) (void*) ans;
669 struct sockaddr* nsap;
670 int nsaplen;
chenbruce0d470422019-03-28 18:44:37 +0800671 int truncating, connreset, n;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900672 struct iovec iov[2];
chenbrucec51f1212019-09-12 16:59:33 +0800673 uint8_t* cp;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900674
Ken Chenffc224a2019-03-19 17:41:28 +0800675 LOG(INFO) << __func__ << ": using send_vc";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900676
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900677 nsap = get_nsaddr(statp, (size_t) ns);
678 nsaplen = get_salen(nsap);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900679
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900680 connreset = 0;
681same_ns:
682 truncating = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900683
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900684 struct timespec now = evNowTime();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900685
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900686 /* Are we still talking to whom we want to talk to? */
687 if (statp->_vcsock >= 0 && (statp->_flags & RES_F_VC) != 0) {
688 struct sockaddr_storage peer;
689 socklen_t size = sizeof peer;
690 unsigned old_mark;
691 socklen_t mark_size = sizeof(old_mark);
692 if (getpeername(statp->_vcsock, (struct sockaddr*) (void*) &peer, &size) < 0 ||
693 !sock_eq((struct sockaddr*) (void*) &peer, nsap) ||
694 getsockopt(statp->_vcsock, SOL_SOCKET, SO_MARK, &old_mark, &mark_size) < 0 ||
695 old_mark != statp->_mark) {
696 res_nclose(statp);
697 statp->_flags &= ~RES_F_VC;
698 }
699 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900700
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900701 if (statp->_vcsock < 0 || (statp->_flags & RES_F_VC) == 0) {
702 if (statp->_vcsock >= 0) res_nclose(statp);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900703
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900704 statp->_vcsock = socket(nsap->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0);
705 if (statp->_vcsock < 0) {
706 switch (errno) {
707 case EPROTONOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900708 case EPFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900709 case EAFNOSUPPORT:
chenbruce018fdb22019-06-12 18:08:04 +0800710 PLOG(DEBUG) << __func__ << ": socket(vc): ";
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900711 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900712 default:
713 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800714 PLOG(DEBUG) << __func__ << ": socket(vc): ";
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900715 return -1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900716 }
717 }
Sehee Parkd975bf32019-08-07 13:21:16 +0900718 resolv_tag_socket(statp->_vcsock, statp->uid);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900719 if (statp->_mark != MARK_UNSET) {
720 if (setsockopt(statp->_vcsock, SOL_SOCKET, SO_MARK, &statp->_mark,
721 sizeof(statp->_mark)) < 0) {
722 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800723 PLOG(DEBUG) << __func__ << ": setsockopt: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900724 return -1;
725 }
726 }
727 errno = 0;
728 if (random_bind(statp->_vcsock, nsap->sa_family) < 0) {
729 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800730 dump_error("bind/vc", nsap, nsaplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900731 res_nclose(statp);
732 return (0);
733 }
734 if (connect_with_timeout(statp->_vcsock, nsap, (socklen_t) nsaplen,
735 get_timeout(statp, params, ns)) < 0) {
736 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800737 dump_error("connect/vc", nsap, nsaplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900738 res_nclose(statp);
739 /*
740 * The way connect_with_timeout() is implemented prevents us from reliably
741 * determining whether this was really a timeout or e.g. ECONNREFUSED. Since
742 * currently both cases are handled in the same way, there is no need to
743 * change this (yet). If we ever need to reliably distinguish between these
744 * cases, both connect_with_timeout() and retrying_poll() need to be
745 * modified, though.
746 */
747 *rcode = RCODE_TIMEOUT;
748 return (0);
749 }
750 statp->_flags |= RES_F_VC;
751 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900752
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900753 /*
754 * Send length & message
755 */
chenbruce0d470422019-03-28 18:44:37 +0800756 uint16_t len = htons(static_cast<uint16_t>(buflen));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900757 iov[0] = evConsIovec(&len, INT16SZ);
Bernie Innocenti9c575932018-09-07 21:10:25 +0900758 iov[1] = evConsIovec((void*) buf, (size_t) buflen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900759 if (writev(statp->_vcsock, iov, 2) != (INT16SZ + buflen)) {
760 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800761 PLOG(DEBUG) << __func__ << ": write failed: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900762 res_nclose(statp);
763 return (0);
764 }
765 /*
766 * Receive length & response
767 */
768read_len:
769 cp = ans;
770 len = INT16SZ;
771 while ((n = read(statp->_vcsock, (char*) cp, (size_t) len)) > 0) {
772 cp += n;
773 if ((len -= n) == 0) break;
774 }
775 if (n <= 0) {
776 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800777 PLOG(DEBUG) << __func__ << ": read failed: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900778 res_nclose(statp);
779 /*
780 * A long running process might get its TCP
781 * connection reset if the remote server was
782 * restarted. Requery the server instead of
783 * trying a new one. When there is only one
784 * server, this means that a query might work
785 * instead of failing. We only allow one reset
786 * per query to prevent looping.
787 */
788 if (*terrno == ECONNRESET && !connreset) {
789 connreset = 1;
790 res_nclose(statp);
791 goto same_ns;
792 }
793 res_nclose(statp);
794 return (0);
795 }
chenbruce0d470422019-03-28 18:44:37 +0800796 uint16_t resplen = ntohs(*reinterpret_cast<const uint16_t*>(ans));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900797 if (resplen > anssiz) {
Ken Chenffc224a2019-03-19 17:41:28 +0800798 LOG(DEBUG) << __func__ << ": response truncated";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900799 truncating = 1;
800 len = anssiz;
801 } else
802 len = resplen;
803 if (len < HFIXEDSZ) {
804 /*
805 * Undersized message.
806 */
Ken Chenffc224a2019-03-19 17:41:28 +0800807 LOG(DEBUG) << __func__ << ": undersized: " << len;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900808 *terrno = EMSGSIZE;
809 res_nclose(statp);
810 return (0);
811 }
812 cp = ans;
813 while (len != 0 && (n = read(statp->_vcsock, (char*) cp, (size_t) len)) > 0) {
814 cp += n;
815 len -= n;
816 }
817 if (n <= 0) {
818 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800819 PLOG(DEBUG) << __func__ << ": read(vc): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900820 res_nclose(statp);
821 return (0);
822 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900823
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900824 if (truncating) {
825 /*
826 * Flush rest of answer so connection stays in synch.
827 */
828 anhp->tc = 1;
829 len = resplen - anssiz;
830 while (len != 0) {
831 char junk[PACKETSZ];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900832
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900833 n = read(statp->_vcsock, junk, (len > sizeof junk) ? sizeof junk : len);
834 if (n > 0)
835 len -= n;
836 else
837 break;
838 }
839 }
840 /*
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900841 * If the calling application has bailed out of
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900842 * a previous call and failed to arrange to have
843 * the circuit closed or the server has got
844 * itself confused, then drop the packet and
845 * wait for the correct one.
846 */
847 if (hp->id != anhp->id) {
Ken Chenffc224a2019-03-19 17:41:28 +0800848 LOG(DEBUG) << __func__ << ": ld answer (unexpected):";
chenbrucedd210722019-03-06 13:52:43 +0800849 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900850 goto read_len;
851 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900852
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900853 /*
854 * All is well, or the error is fatal. Signal that the
855 * next nameserver ought not be tried.
856 */
857 if (resplen > 0) {
858 struct timespec done = evNowTime();
859 *delay = _res_stats_calculate_rtt(&done, &now);
860 *rcode = anhp->rcode;
861 }
862 return (resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900863}
864
865/* return -1 on error (errno set), 0 on success */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900866static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
867 const struct timespec timeout) {
868 int res, origflags;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900869
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900870 origflags = fcntl(sock, F_GETFL, 0);
871 fcntl(sock, F_SETFL, origflags | O_NONBLOCK);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900872
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900873 res = connect(sock, nsap, salen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900874 if (res < 0 && errno != EINPROGRESS) {
875 res = -1;
876 goto done;
877 }
878 if (res != 0) {
879 struct timespec now = evNowTime();
880 struct timespec finish = evAddTime(now, timeout);
Ken Chenffc224a2019-03-19 17:41:28 +0800881 LOG(INFO) << __func__ << ": " << sock << " send_vc";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900882 res = retrying_poll(sock, POLLIN | POLLOUT, &finish);
883 if (res <= 0) {
884 res = -1;
885 }
886 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900887done:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900888 fcntl(sock, F_SETFL, origflags);
Ken Chenffc224a2019-03-19 17:41:28 +0800889 LOG(INFO) << __func__ << ": " << sock << " connect_with_const timeout returning " << res;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900890 return res;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900891}
892
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900893static int retrying_poll(const int sock, const short events, const struct timespec* finish) {
894 struct timespec now, timeout;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900895
896retry:
Ken Chenffc224a2019-03-19 17:41:28 +0800897 LOG(INFO) << __func__ << ": " << sock << " retrying_poll";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900898
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900899 now = evNowTime();
900 if (evCmpTime(*finish, now) > 0)
901 timeout = evSubTime(*finish, now);
902 else
903 timeout = evConsTime(0L, 0L);
904 struct pollfd fds = {.fd = sock, .events = events};
905 int n = ppoll(&fds, 1, &timeout, /*sigmask=*/NULL);
906 if (n == 0) {
Ken Chenffc224a2019-03-19 17:41:28 +0800907 LOG(INFO) << __func__ << ": " << sock << "retrying_poll timeout";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900908 errno = ETIMEDOUT;
909 return 0;
910 }
911 if (n < 0) {
912 if (errno == EINTR) goto retry;
Ken Chenffc224a2019-03-19 17:41:28 +0800913 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll failed";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900914 return n;
915 }
916 if (fds.revents & (POLLIN | POLLOUT | POLLERR)) {
917 int error;
918 socklen_t len = sizeof(error);
919 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error) {
920 errno = error;
Ken Chenffc224a2019-03-19 17:41:28 +0800921 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll getsockopt failed";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900922 return -1;
923 }
924 }
Ken Chenffc224a2019-03-19 17:41:28 +0800925 LOG(INFO) << __func__ << ": " << sock << " retrying_poll returning " << n;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900926 return n;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900927}
928
chenbrucec51f1212019-09-12 16:59:33 +0800929static int send_dg(res_state statp, res_params* params, const uint8_t* buf, int buflen,
930 uint8_t* ans, int anssiz, int* terrno, int ns, int* v_circuit, int* gotsomewhere,
931 time_t* at, int* rcode, int* delay) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900932 *at = time(NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900933 *delay = 0;
934 const HEADER* hp = (const HEADER*) (const void*) buf;
935 HEADER* anhp = (HEADER*) (void*) ans;
936 const struct sockaddr* nsap;
937 int nsaplen;
938 struct timespec now, timeout, finish, done;
939 struct sockaddr_storage from;
940 socklen_t fromlen;
941 int resplen, n, s;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900942
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900943 nsap = get_nsaddr(statp, (size_t) ns);
944 nsaplen = get_salen(nsap);
Bernie Innocentibb330742019-10-09 00:55:53 +0900945 if (statp->nssocks[ns] == -1) {
946 statp->nssocks[ns] = socket(nsap->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
947 if (statp->nssocks[ns] < 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900948 switch (errno) {
949 case EPROTONOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900950 case EPFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900951 case EAFNOSUPPORT:
chenbruce018fdb22019-06-12 18:08:04 +0800952 PLOG(DEBUG) << __func__ << ": socket(dg): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900953 return (0);
954 default:
955 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800956 PLOG(DEBUG) << __func__ << ": socket(dg): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900957 return (-1);
958 }
959 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900960
Bernie Innocentibb330742019-10-09 00:55:53 +0900961 resolv_tag_socket(statp->nssocks[ns], statp->uid);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900962 if (statp->_mark != MARK_UNSET) {
Bernie Innocentibb330742019-10-09 00:55:53 +0900963 if (setsockopt(statp->nssocks[ns], SOL_SOCKET, SO_MARK, &(statp->_mark),
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900964 sizeof(statp->_mark)) < 0) {
965 res_nclose(statp);
966 return -1;
967 }
968 }
chenbruceb9cce7b2019-07-15 16:14:53 +0800969 // Use a "connected" datagram socket to receive an ECONNREFUSED error
970 // on the next socket operation when the server responds with an
971 // ICMP port-unreachable error. This way we can detect the absence of
972 // a nameserver without timing out.
Bernie Innocentibb330742019-10-09 00:55:53 +0900973 if (random_bind(statp->nssocks[ns], nsap->sa_family) < 0) {
chenbruce018fdb22019-06-12 18:08:04 +0800974 dump_error("bind(dg)", nsap, nsaplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900975 res_nclose(statp);
976 return (0);
977 }
Bernie Innocentibb330742019-10-09 00:55:53 +0900978 if (connect(statp->nssocks[ns], nsap, (socklen_t)nsaplen) < 0) {
chenbruce018fdb22019-06-12 18:08:04 +0800979 dump_error("connect(dg)", nsap, nsaplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900980 res_nclose(statp);
981 return (0);
982 }
Ken Chenffc224a2019-03-19 17:41:28 +0800983 LOG(DEBUG) << __func__ << ": new DG socket";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900984 }
Bernie Innocentibb330742019-10-09 00:55:53 +0900985 s = statp->nssocks[ns];
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900986 if (send(s, (const char*) buf, (size_t) buflen, 0) != buflen) {
chenbruce018fdb22019-06-12 18:08:04 +0800987 PLOG(DEBUG) << __func__ << ": send: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900988 res_nclose(statp);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +0900989 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900990 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900991
Bernie Innocenti3952ccc2019-03-03 19:39:53 +0900992 // Wait for reply.
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900993 timeout = get_timeout(statp, params, ns);
994 now = evNowTime();
995 finish = evAddTime(now, timeout);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900996retry:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900997 n = retrying_poll(s, POLLIN, &finish);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900998
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900999 if (n == 0) {
1000 *rcode = RCODE_TIMEOUT;
Ken Chenffc224a2019-03-19 17:41:28 +08001001 LOG(DEBUG) << __func__ << ": timeout";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001002 *gotsomewhere = 1;
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001003 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001004 }
1005 if (n < 0) {
chenbruce018fdb22019-06-12 18:08:04 +08001006 PLOG(DEBUG) << __func__ << ": poll: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001007 res_nclose(statp);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001008 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001009 }
1010 errno = 0;
1011 fromlen = sizeof(from);
1012 resplen = recvfrom(s, (char*) ans, (size_t) anssiz, 0, (struct sockaddr*) (void*) &from,
1013 &fromlen);
1014 if (resplen <= 0) {
chenbruce018fdb22019-06-12 18:08:04 +08001015 PLOG(DEBUG) << __func__ << ": recvfrom: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001016 res_nclose(statp);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001017 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001018 }
1019 *gotsomewhere = 1;
1020 if (resplen < HFIXEDSZ) {
1021 /*
1022 * Undersized message.
1023 */
Ken Chenffc224a2019-03-19 17:41:28 +08001024 LOG(DEBUG) << __func__ << ": undersized: " << resplen;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001025 *terrno = EMSGSIZE;
1026 res_nclose(statp);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001027 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001028 }
1029 if (hp->id != anhp->id) {
1030 /*
1031 * response from old query, ignore it.
1032 * XXX - potential security hazard could
1033 * be detected here.
1034 */
Ken Chenffc224a2019-03-19 17:41:28 +08001035 LOG(DEBUG) << __func__ << ": old answer:";
chenbrucedd210722019-03-06 13:52:43 +08001036 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001037 goto retry;
1038 }
chenbruce018fdb22019-06-12 18:08:04 +08001039 if (!res_ourserver_p(statp, (struct sockaddr*)(void*)&from)) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001040 /*
1041 * response from wrong server? ignore it.
1042 * XXX - potential security hazard could
1043 * be detected here.
1044 */
Ken Chenffc224a2019-03-19 17:41:28 +08001045 LOG(DEBUG) << __func__ << ": not our server:";
chenbrucedd210722019-03-06 13:52:43 +08001046 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001047 goto retry;
1048 }
chenbruced8cbb9b2019-06-20 18:25:28 +08001049 if (anhp->rcode == FORMERR && (statp->netcontext_flags & NET_CONTEXT_FLAG_USE_EDNS)) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001050 /*
1051 * Do not retry if the server do not understand EDNS0.
1052 * The case has to be captured here, as FORMERR packet do not
1053 * carry query section, hence res_queriesmatch() returns 0.
1054 */
Ken Chenffc224a2019-03-19 17:41:28 +08001055 LOG(DEBUG) << __func__ << ": server rejected query with EDNS0:";
chenbrucedd210722019-03-06 13:52:43 +08001056 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001057 /* record the error */
1058 statp->_flags |= RES_F_EDNS0ERR;
1059 res_nclose(statp);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001060 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001061 }
chenbruce018fdb22019-06-12 18:08:04 +08001062 if (!res_queriesmatch(buf, buf + buflen, ans, ans + anssiz)) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001063 /*
1064 * response contains wrong query? ignore it.
1065 * XXX - potential security hazard could
1066 * be detected here.
1067 */
Ken Chenffc224a2019-03-19 17:41:28 +08001068 LOG(DEBUG) << __func__ << ": wrong query name:";
chenbrucedd210722019-03-06 13:52:43 +08001069 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001070 goto retry;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001071 }
1072 done = evNowTime();
1073 *delay = _res_stats_calculate_rtt(&done, &now);
1074 if (anhp->rcode == SERVFAIL || anhp->rcode == NOTIMP || anhp->rcode == REFUSED) {
Ken Chenffc224a2019-03-19 17:41:28 +08001075 LOG(DEBUG) << __func__ << ": server rejected query:";
chenbrucedd210722019-03-06 13:52:43 +08001076 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001077 res_nclose(statp);
chenbrucedd210722019-03-06 13:52:43 +08001078 *rcode = anhp->rcode;
1079 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001080 }
chenbruce018fdb22019-06-12 18:08:04 +08001081 if (anhp->tc) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001082 /*
1083 * To get the rest of answer,
1084 * use TCP with same server.
1085 */
Ken Chenffc224a2019-03-19 17:41:28 +08001086 LOG(DEBUG) << __func__ << ": truncated answer";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001087 *v_circuit = 1;
1088 res_nclose(statp);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001089 return 1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001090 }
1091 /*
1092 * All is well, or the error is fatal. Signal that the
1093 * next nameserver ought not be tried.
1094 */
1095 if (resplen > 0) {
1096 *rcode = anhp->rcode;
1097 }
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001098 return resplen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001099}
1100
chenbruce018fdb22019-06-12 18:08:04 +08001101static void dump_error(const char* str, const struct sockaddr* address, int alen) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001102 char hbuf[NI_MAXHOST];
1103 char sbuf[NI_MAXSERV];
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001104 constexpr int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001105
chenbruce018fdb22019-06-12 18:08:04 +08001106 if (!WOULD_LOG(DEBUG)) return;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001107
chenbruce018fdb22019-06-12 18:08:04 +08001108 if (getnameinfo(address, (socklen_t)alen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf), niflags)) {
1109 strncpy(hbuf, "?", sizeof(hbuf) - 1);
1110 hbuf[sizeof(hbuf) - 1] = '\0';
1111 strncpy(sbuf, "?", sizeof(sbuf) - 1);
1112 sbuf[sizeof(sbuf) - 1] = '\0';
Elliott Hughes3b8f5902019-03-08 12:02:55 -08001113 }
chenbruce018fdb22019-06-12 18:08:04 +08001114 PLOG(DEBUG) << __func__ << ": " << str << " ([" << hbuf << "]." << sbuf << "): ";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001115}
1116
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001117static int sock_eq(struct sockaddr* a, struct sockaddr* b) {
1118 struct sockaddr_in *a4, *b4;
1119 struct sockaddr_in6 *a6, *b6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001120
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001121 if (a->sa_family != b->sa_family) return 0;
1122 switch (a->sa_family) {
1123 case AF_INET:
1124 a4 = (struct sockaddr_in*) (void*) a;
1125 b4 = (struct sockaddr_in*) (void*) b;
1126 return a4->sin_port == b4->sin_port && a4->sin_addr.s_addr == b4->sin_addr.s_addr;
1127 case AF_INET6:
1128 a6 = (struct sockaddr_in6*) (void*) a;
1129 b6 = (struct sockaddr_in6*) (void*) b;
1130 return a6->sin6_port == b6->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001131#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001132 a6->sin6_scope_id == b6->sin6_scope_id &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001133#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001134 IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
1135 default:
1136 return 0;
1137 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001138}
Mike Yub601ff72018-11-01 20:07:00 +08001139
lifr6b83a6f2019-07-26 03:17:43 +08001140PrivateDnsModes convertEnumType(PrivateDnsMode privateDnsmode) {
1141 switch (privateDnsmode) {
1142 case PrivateDnsMode::OFF:
1143 return PrivateDnsModes::PDM_OFF;
1144 case PrivateDnsMode::OPPORTUNISTIC:
1145 return PrivateDnsModes::PDM_OPPORTUNISTIC;
1146 case PrivateDnsMode::STRICT:
1147 return PrivateDnsModes::PDM_STRICT;
1148 }
1149 return PrivateDnsModes::PDM_UNKNOWN;
1150}
1151
Luke Huangd7aa7b42018-11-21 20:37:50 +08001152static int res_tls_send(res_state statp, const Slice query, const Slice answer, int* rcode,
Mike Yubfb1b342018-11-06 15:42:36 +08001153 bool* fallback) {
1154 int resplen = 0;
Mike Yub601ff72018-11-01 20:07:00 +08001155 const unsigned netId = statp->netid;
Mike Yub601ff72018-11-01 20:07:00 +08001156
Mike Yubfb1b342018-11-06 15:42:36 +08001157 PrivateDnsStatus privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
lifr6b83a6f2019-07-26 03:17:43 +08001158 statp->event->set_private_dns_modes(convertEnumType(privateDnsStatus.mode));
Mike Yubfb1b342018-11-06 15:42:36 +08001159
1160 if (privateDnsStatus.mode == PrivateDnsMode::OFF) {
1161 *fallback = true;
1162 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001163 }
1164
Mike Yu3e829062019-08-07 14:01:14 +08001165 if (privateDnsStatus.validatedServers().empty()) {
Mike Yub601ff72018-11-01 20:07:00 +08001166 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
Mike Yubfb1b342018-11-06 15:42:36 +08001167 *fallback = true;
1168 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001169 } else {
1170 // Sleep and iterate some small number of times checking for the
1171 // arrival of resolved and validated server IP addresses, instead
1172 // of returning an immediate error.
Mike Yu4f3747b2018-12-02 17:54:29 +09001173 // This is needed because as soon as a network becomes the default network, apps will
1174 // send DNS queries on that network. If no servers have yet validated, and we do not
1175 // block those queries, they would immediately fail, causing application-visible errors.
1176 // Note that this can happen even before the network validates, since an unvalidated
1177 // network can become the default network if no validated networks are available.
1178 //
1179 // TODO: see if there is a better way to address this problem, such as buffering the
1180 // queries in a queue or only blocking queries for the first few seconds after a default
1181 // network change.
Mike Yubfb1b342018-11-06 15:42:36 +08001182 for (int i = 0; i < 42; i++) {
1183 std::this_thread::sleep_for(std::chrono::milliseconds(100));
Mike Yu3e829062019-08-07 14:01:14 +08001184 // Calling getStatus() to merely check if there's any validated server seems
1185 // wasteful. Consider adding a new method in PrivateDnsConfiguration for speed ups.
1186 if (!gPrivateDnsConfiguration.getStatus(netId).validatedServers().empty()) {
Mike Yubfb1b342018-11-06 15:42:36 +08001187 privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
1188 break;
1189 }
1190 }
Mike Yu3e829062019-08-07 14:01:14 +08001191 if (privateDnsStatus.validatedServers().empty()) {
Mike Yubfb1b342018-11-06 15:42:36 +08001192 return -1;
1193 }
Mike Yub601ff72018-11-01 20:07:00 +08001194 }
1195 }
1196
chenbruceacb832c2019-02-20 19:45:50 +08001197 LOG(INFO) << __func__ << ": performing query over TLS";
Mike Yub601ff72018-11-01 20:07:00 +08001198
Mike Yu3e829062019-08-07 14:01:14 +08001199 const auto response = sDnsTlsDispatcher.query(privateDnsStatus.validatedServers(), statp, query,
Mike Yubfb1b342018-11-06 15:42:36 +08001200 answer, &resplen);
Mike Yub601ff72018-11-01 20:07:00 +08001201
chenbruceacb832c2019-02-20 19:45:50 +08001202 LOG(INFO) << __func__ << ": TLS query result: " << static_cast<int>(response);
Mike Yub601ff72018-11-01 20:07:00 +08001203
1204 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
1205 // In opportunistic mode, handle falling back to cleartext in some
1206 // cases (DNS shouldn't fail if a validated opportunistic mode server
1207 // becomes unreachable for some reason).
1208 switch (response) {
Mike Yubfb1b342018-11-06 15:42:36 +08001209 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001210 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001211 return resplen;
Mike Yub601ff72018-11-01 20:07:00 +08001212 case DnsTlsTransport::Response::network_error:
Mike Yubfb1b342018-11-06 15:42:36 +08001213 // No need to set the error timeout here since it will fallback to UDP.
Mike Yub601ff72018-11-01 20:07:00 +08001214 case DnsTlsTransport::Response::internal_error:
1215 // Note: this will cause cleartext queries to be emitted, with
1216 // all of the EDNS0 goodness enabled. Fingers crossed. :-/
Mike Yubfb1b342018-11-06 15:42:36 +08001217 *fallback = true;
1218 [[fallthrough]];
Mike Yub601ff72018-11-01 20:07:00 +08001219 default:
Mike Yubfb1b342018-11-06 15:42:36 +08001220 return -1;
1221 }
1222 } else {
1223 // Strict mode
1224 switch (response) {
1225 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001226 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001227 return resplen;
1228 case DnsTlsTransport::Response::network_error:
1229 // This case happens when the query stored in DnsTlsTransport is expired since
1230 // either 1) the query has been tried for 3 times but no response or 2) fail to
1231 // establish the connection with the server.
Luke Huangd7aa7b42018-11-21 20:37:50 +08001232 *rcode = RCODE_TIMEOUT;
Mike Yubfb1b342018-11-06 15:42:36 +08001233 [[fallthrough]];
1234 default:
1235 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001236 }
1237 }
Mike Yub601ff72018-11-01 20:07:00 +08001238}
Luke Huang4973a0d2018-11-19 20:17:26 +08001239
Luke Huangba7bef92018-12-26 16:53:03 +08001240int resolv_res_nsend(const android_net_context* netContext, const uint8_t* msg, int msgLen,
lifr94981782019-05-17 21:15:19 +08001241 uint8_t* ans, int ansLen, int* rcode, uint32_t flags,
1242 NetworkDnsEventReported* event) {
1243 assert(event != nullptr);
Bernie Innocenti08487112019-10-11 21:14:13 +09001244 ResState res;
1245 res_init(&res, netContext, event);
1246 _resolv_populate_res_for_net(&res);
Luke Huang4973a0d2018-11-19 20:17:26 +08001247 *rcode = NOERROR;
Bernie Innocenti08487112019-10-11 21:14:13 +09001248 return res_nsend(&res, msg, msgLen, ans, ansLen, rcode, flags);
Bernie Innocentiec4219b2019-01-30 11:16:36 +09001249}