blob: c523516dd480c6ce752aa55adf625b7730eb7be2 [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
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900229// END: Code copied from ISC eventlib
230
lifr94981782019-05-17 21:15:19 +0800231/* BIONIC-BEGIN: implement source port randomization */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900232static int random_bind(int s, int family) {
nuccachenb980f2f2018-10-23 17:10:58 +0800233 sockaddr_union u;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900234 int j;
235 socklen_t slen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900236
237 /* clear all, this also sets the IP4/6 address to 'any' */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900238 memset(&u, 0, sizeof u);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900239
240 switch (family) {
241 case AF_INET:
242 u.sin.sin_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900243 slen = sizeof u.sin;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900244 break;
245 case AF_INET6:
246 u.sin6.sin6_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900247 slen = sizeof u.sin6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900248 break;
249 default:
250 errno = EPROTO;
251 return -1;
252 }
253
254 /* first try to bind to a random source port a few times */
255 for (j = 0; j < 10; j++) {
256 /* find a random port between 1025 .. 65534 */
Luke Huangdda920f2019-02-13 14:05:02 +0800257 int port = 1025 + (arc4random_uniform(65535 - 1025));
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900258 if (family == AF_INET)
259 u.sin.sin_port = htons(port);
260 else
261 u.sin6.sin6_port = htons(port);
262
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900263 if (!bind(s, &u.sa, slen)) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900264 }
265
Bernie Innocenti9c575932018-09-07 21:10:25 +0900266 // nothing after 10 attempts, our network table is probably busy
267 // let the system decide which port is best
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900268 if (family == AF_INET)
269 u.sin.sin_port = 0;
270 else
271 u.sin6.sin6_port = 0;
272
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900273 return bind(s, &u.sa, slen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900274}
275/* BIONIC-END */
276
Luke Huang70931aa2019-01-31 11:57:41 +0800277// Disables all nameservers other than selectedServer
278static void res_set_usable_server(int selectedServer, int nscount, bool usable_servers[]) {
279 int usableIndex = 0;
280 for (int ns = 0; ns < nscount; ns++) {
281 if (usable_servers[ns]) ++usableIndex;
282 if (usableIndex != selectedServer) usable_servers[ns] = false;
283 }
284}
285
Bernie Innocentia6f40ca2019-10-09 15:22:41 +0900286// Looks up the nameserver address in res.nsaddrs[], returns true if found, otherwise false.
287static bool res_ourserver_p(res_state statp, const sockaddr* sa) {
Bernie Innocenti2e8540b2018-09-26 11:52:04 +0900288 const sockaddr_in *inp, *srv;
289 const sockaddr_in6 *in6p, *srv6;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900290 int ns;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900291
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900292 switch (sa->sa_family) {
293 case AF_INET:
294 inp = (const struct sockaddr_in*) (const void*) sa;
295 for (ns = 0; ns < statp->nscount; ns++) {
296 srv = (struct sockaddr_in*) (void*) get_nsaddr(statp, (size_t) ns);
297 if (srv->sin_family == inp->sin_family && srv->sin_port == inp->sin_port &&
298 (srv->sin_addr.s_addr == INADDR_ANY ||
299 srv->sin_addr.s_addr == inp->sin_addr.s_addr))
Bernie Innocentia6f40ca2019-10-09 15:22:41 +0900300 return true;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900301 }
302 break;
303 case AF_INET6:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900304 in6p = (const struct sockaddr_in6*) (const void*) sa;
305 for (ns = 0; ns < statp->nscount; ns++) {
306 srv6 = (struct sockaddr_in6*) (void*) get_nsaddr(statp, (size_t) ns);
307 if (srv6->sin6_family == in6p->sin6_family && srv6->sin6_port == in6p->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900308#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900309 (srv6->sin6_scope_id == 0 || srv6->sin6_scope_id == in6p->sin6_scope_id) &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900310#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900311 (IN6_IS_ADDR_UNSPECIFIED(&srv6->sin6_addr) ||
312 IN6_ARE_ADDR_EQUAL(&srv6->sin6_addr, &in6p->sin6_addr)))
Bernie Innocentia6f40ca2019-10-09 15:22:41 +0900313 return true;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900314 }
315 break;
316 default:
317 break;
318 }
Bernie Innocentia6f40ca2019-10-09 15:22:41 +0900319 return false;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900320}
321
322/* int
Bernie Innocenti9c575932018-09-07 21:10:25 +0900323 * res_nameinquery(name, type, cl, buf, eom)
324 * look for (name, type, cl) in the query section of packet (buf, eom)
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900325 * requires:
326 * buf + HFIXEDSZ <= eom
327 * returns:
328 * -1 : format error
329 * 0 : not found
330 * >0 : found
331 * author:
332 * paul vixie, 29may94
333 */
chenbrucec51f1212019-09-12 16:59:33 +0800334int res_nameinquery(const char* name, int type, int cl, const uint8_t* buf, const uint8_t* eom) {
335 const uint8_t* cp = buf + HFIXEDSZ;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900336 int qdcount = ntohs(((const HEADER*) (const void*) buf)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900337
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900338 while (qdcount-- > 0) {
339 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900340 int n = dn_expand(buf, eom, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900341 if (n < 0) return (-1);
342 cp += n;
343 if (cp + 2 * INT16SZ > eom) return (-1);
chenbruce0d470422019-03-28 18:44:37 +0800344 int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900345 cp += INT16SZ;
chenbruce0d470422019-03-28 18:44:37 +0800346 int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900347 cp += INT16SZ;
Bernie Innocenti9c575932018-09-07 21:10:25 +0900348 if (ttype == type && tclass == cl && ns_samename(tname, name) == 1) return (1);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900349 }
350 return (0);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900351}
352
353/* int
354 * res_queriesmatch(buf1, eom1, buf2, eom2)
355 * is there a 1:1 mapping of (name,type,class)
356 * in (buf1,eom1) and (buf2,eom2)?
357 * returns:
358 * -1 : format error
359 * 0 : not a 1:1 mapping
360 * >0 : is a 1:1 mapping
361 * author:
362 * paul vixie, 29may94
363 */
chenbrucec51f1212019-09-12 16:59:33 +0800364int res_queriesmatch(const uint8_t* buf1, const uint8_t* eom1, const uint8_t* buf2,
365 const uint8_t* eom2) {
366 const uint8_t* cp = buf1 + HFIXEDSZ;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900367 int qdcount = ntohs(((const HEADER*) (const void*) buf1)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900368
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900369 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2) return (-1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900370
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900371 /*
372 * Only header section present in replies to
373 * dynamic update packets.
374 */
375 if ((((const HEADER*) (const void*) buf1)->opcode == ns_o_update) &&
376 (((const HEADER*) (const void*) buf2)->opcode == ns_o_update))
377 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900378
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900379 if (qdcount != ntohs(((const HEADER*) (const void*) buf2)->qdcount)) return (0);
380 while (qdcount-- > 0) {
381 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900382 int n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900383 if (n < 0) return (-1);
384 cp += n;
385 if (cp + 2 * INT16SZ > eom1) return (-1);
chenbruce0d470422019-03-28 18:44:37 +0800386 int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900387 cp += INT16SZ;
chenbruce0d470422019-03-28 18:44:37 +0800388 int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900389 cp += INT16SZ;
390 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2)) return (0);
391 }
392 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900393}
394
lifr94981782019-05-17 21:15:19 +0800395static DnsQueryEvent* addDnsQueryEvent(NetworkDnsEventReported* event) {
396 return event->mutable_dns_query_events()->add_dns_query_event();
397}
398
chenbrucec51f1212019-09-12 16:59:33 +0800399int 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 +0800400 uint32_t flags) {
Bernie Innocenti9c575932018-09-07 21:10:25 +0900401 int gotsomewhere, terrno, v_circuit, resplen, n;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900402 ResolvCacheStatus cache_status = RESOLV_CACHE_UNSUPPORTED;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900403
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900404 if (anssiz < HFIXEDSZ) {
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800405 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900406 errno = EINVAL;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800407 return -EINVAL;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900408 }
Bernie Innocenti3952ccc2019-03-03 19:39:53 +0900409 LOG(DEBUG) << __func__;
chenbrucedd210722019-03-06 13:52:43 +0800410 res_pquery(buf, buflen);
chenbruceacb832c2019-02-20 19:45:50 +0800411
chenbruce018fdb22019-06-12 18:08:04 +0800412 v_circuit = buflen > PACKETSZ;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900413 gotsomewhere = 0;
414 terrno = ETIMEDOUT;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900415
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900416 int anslen = 0;
lifrd4d9fbb2019-07-31 20:18:35 +0800417 Stopwatch cacheStopwatch;
Mike Yud1ec2542019-06-06 17:17:53 +0800418 cache_status = resolv_cache_lookup(statp->netid, buf, buflen, ans, anssiz, &anslen, flags);
lifrd4d9fbb2019-07-31 20:18:35 +0800419 const int32_t cacheLatencyUs = saturate_cast<int32_t>(cacheStopwatch.timeTakenUs());
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900420 if (cache_status == RESOLV_CACHE_FOUND) {
Luke Huang83c9b4b2019-02-27 18:18:01 +0800421 HEADER* hp = (HEADER*)(void*)ans;
422 *rcode = hp->rcode;
lifr94981782019-05-17 21:15:19 +0800423 DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
424 dnsQueryEvent->set_latency_micros(cacheLatencyUs);
425 dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900426 return anslen;
427 } else if (cache_status != RESOLV_CACHE_UNSUPPORTED) {
428 // had a cache miss for a known network, so populate the thread private
429 // data so the normal resolve path can do its thing
430 _resolv_populate_res_for_net(statp);
431 }
432 if (statp->nscount == 0) {
433 // We have no nameservers configured, so there's no point trying.
434 // Tell the cache the query failed, or any retries and anyone else asking the same
435 // question will block for PENDING_REQUEST_TIMEOUT seconds instead of failing fast.
Luke Huangba7bef92018-12-26 16:53:03 +0800436 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800437
438 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900439 errno = ESRCH;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800440 return -ESRCH;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900441 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900442
Bernie Innocenti758005f2019-02-19 18:08:36 +0900443 res_stats stats[MAXNS];
444 res_params params;
waynema0161acd2019-02-18 17:47:59 +0800445 int revision_id = resolv_cache_get_resolver_stats(statp->netid, &params, stats);
lifra1b37f12019-02-13 17:33:57 +0800446 if (revision_id < 0) {
447 // TODO: Remove errno once callers stop using it
448 errno = ESRCH;
449 return -ESRCH;
450 }
waynema0161acd2019-02-18 17:47:59 +0800451 bool usable_servers[MAXNS];
Luke Huang70931aa2019-01-31 11:57:41 +0800452 int usableServersCount = android_net_res_stats_get_usable_servers(
453 &params, stats, statp->nscount, usable_servers);
454
455 if ((flags & ANDROID_RESOLV_NO_RETRY) && usableServersCount > 1) {
456 auto hp = reinterpret_cast<const HEADER*>(buf);
457
458 // Select a random server based on the query id
459 int selectedServer = (hp->id % usableServersCount) + 1;
460 res_set_usable_server(selectedServer, statp->nscount, usable_servers);
461 }
waynema0161acd2019-02-18 17:47:59 +0800462
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900463 /*
464 * Send request, RETRY times, or until successful.
465 */
waynemaa74195e2019-01-18 14:02:31 +0800466 int retryTimes = (flags & ANDROID_RESOLV_NO_RETRY) ? 1 : params.retry_count;
Luke Huangba7bef92018-12-26 16:53:03 +0800467
468 for (int attempt = 0; attempt < retryTimes; ++attempt) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900469
Bernie Innocenti9c575932018-09-07 21:10:25 +0900470 for (int ns = 0; ns < statp->nscount; ns++) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900471 if (!usable_servers[ns]) continue;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900472 int nsaplen;
473 time_t now = 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900474 int delay = 0;
Mike Yubfb1b342018-11-06 15:42:36 +0800475 *rcode = RCODE_INTERNAL_ERROR;
lifr94981782019-05-17 21:15:19 +0800476 const sockaddr* nsap = get_nsaddr(statp, ns);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900477 nsaplen = get_salen(nsap);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900478
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900479 same_ns:
Mike Yubfb1b342018-11-06 15:42:36 +0800480 // TODO: Since we expect there is only one DNS server being queried here while this
481 // function tries to query all of private DNS servers. Consider moving it to other
482 // reasonable place. In addition, maybe add stats for private DNS.
chenbruced8cbb9b2019-06-20 18:25:28 +0800483 if (!(statp->netcontext_flags & NET_CONTEXT_FLAG_USE_LOCAL_NAMESERVERS)) {
Mike Yubfb1b342018-11-06 15:42:36 +0800484 bool fallback = false;
chenbrucec51f1212019-09-12 16:59:33 +0800485 resplen = res_tls_send(statp, Slice(const_cast<uint8_t*>(buf), buflen),
Mike Yubfb1b342018-11-06 15:42:36 +0800486 Slice(ans, anssiz), rcode, &fallback);
487 if (resplen > 0) {
Mike Yu34433c62019-08-20 20:17:36 +0800488 LOG(DEBUG) << __func__ << ": got answer from DoT";
489 res_pquery(ans, resplen);
Mike Yubfb1b342018-11-06 15:42:36 +0800490 if (cache_status == RESOLV_CACHE_NOTFOUND) {
Mike Yud1ec2542019-06-06 17:17:53 +0800491 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
Mike Yubfb1b342018-11-06 15:42:36 +0800492 }
493 return resplen;
Mike Yub601ff72018-11-01 20:07:00 +0800494 }
Mike Yubfb1b342018-11-06 15:42:36 +0800495 if (!fallback) {
Luke Huangba7bef92018-12-26 16:53:03 +0800496 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800497 res_nclose(statp);
498 return -terrno;
Mike Yubfb1b342018-11-06 15:42:36 +0800499 }
500 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900501
lifr94981782019-05-17 21:15:19 +0800502 static const int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
503 char abuf[NI_MAXHOST];
504 DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
505 dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
chenbruceacb832c2019-02-20 19:45:50 +0800506
507 if (getnameinfo(nsap, (socklen_t)nsaplen, abuf, sizeof(abuf), NULL, 0, niflags) == 0)
Ken Chenffc224a2019-03-19 17:41:28 +0800508 LOG(DEBUG) << __func__ << ": Querying server (# " << ns + 1
509 << ") address = " << abuf;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900510
lifrd4d9fbb2019-07-31 20:18:35 +0800511 Stopwatch queryStopwatch;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900512 if (v_circuit) {
513 /* Use VC; at most one attempt per server. */
Luke Huangba7bef92018-12-26 16:53:03 +0800514 bool shouldRecordStats = (attempt == 0);
515 attempt = retryTimes;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900516
Mike Yubfb1b342018-11-06 15:42:36 +0800517 n = send_vc(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &now, rcode,
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900518 &delay);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900519
lifr94981782019-05-17 21:15:19 +0800520 dnsQueryEvent->set_latency_micros(
lifrd4d9fbb2019-07-31 20:18:35 +0800521 saturate_cast<int32_t>(queryStopwatch.timeTakenUs()));
lifr94981782019-05-17 21:15:19 +0800522 dnsQueryEvent->set_dns_server_index(ns);
523 dnsQueryEvent->set_ip_version(ipFamilyToIPVersion(nsap->sa_family));
524 dnsQueryEvent->set_retry_times(attempt);
525 dnsQueryEvent->set_rcode(static_cast<NsRcode>(*rcode));
526 dnsQueryEvent->set_protocol(PROTO_TCP);
527 dnsQueryEvent->set_type(getQueryType(buf, buflen));
528
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900529 /*
530 * Only record stats the first time we try a query. This ensures that
531 * queries that deterministically fail (e.g., a name that always returns
532 * SERVFAIL or times out) do not unduly affect the stats.
533 */
Luke Huangba7bef92018-12-26 16:53:03 +0800534 if (shouldRecordStats) {
Bernie Innocentiac18b122018-10-01 23:10:18 +0900535 res_sample sample;
Mike Yubfb1b342018-11-06 15:42:36 +0800536 _res_stats_set_sample(&sample, now, *rcode, delay);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900537 _resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, ns, &sample,
538 params.max_samples);
Mike Yue655b1d2019-08-28 17:49:59 +0800539 resolv_stats_add(statp->netid, IPSockAddr::toIPSockAddr(*nsap), dnsQueryEvent);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900540 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900541
Ken Chenffc224a2019-03-19 17:41:28 +0800542 LOG(INFO) << __func__ << ": used send_vc " << n;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900543
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800544 if (n < 0) {
Luke Huangba7bef92018-12-26 16:53:03 +0800545 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800546 res_nclose(statp);
547 return -terrno;
548 };
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900549 if (n == 0) goto next_ns;
550 resplen = n;
551 } else {
552 /* Use datagrams. */
Ken Chenffc224a2019-03-19 17:41:28 +0800553 LOG(INFO) << __func__ << ": using send_dg";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900554
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900555 n = send_dg(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &v_circuit,
Mike Yubfb1b342018-11-06 15:42:36 +0800556 &gotsomewhere, &now, rcode, &delay);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900557
lifr94981782019-05-17 21:15:19 +0800558 dnsQueryEvent->set_latency_micros(
lifrd4d9fbb2019-07-31 20:18:35 +0800559 saturate_cast<int32_t>(queryStopwatch.timeTakenUs()));
lifr94981782019-05-17 21:15:19 +0800560 dnsQueryEvent->set_dns_server_index(ns);
561 dnsQueryEvent->set_ip_version(ipFamilyToIPVersion(nsap->sa_family));
562 dnsQueryEvent->set_retry_times(attempt);
563 dnsQueryEvent->set_rcode(static_cast<NsRcode>(*rcode));
564 dnsQueryEvent->set_protocol(PROTO_UDP);
565 dnsQueryEvent->set_type(getQueryType(buf, buflen));
566
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900567 /* Only record stats the first time we try a query. See above. */
Bernie Innocenti9c575932018-09-07 21:10:25 +0900568 if (attempt == 0) {
Bernie Innocentiac18b122018-10-01 23:10:18 +0900569 res_sample sample;
Mike Yubfb1b342018-11-06 15:42:36 +0800570 _res_stats_set_sample(&sample, now, *rcode, delay);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900571 _resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, ns, &sample,
572 params.max_samples);
Mike Yue655b1d2019-08-28 17:49:59 +0800573 resolv_stats_add(statp->netid, IPSockAddr::toIPSockAddr(*nsap), dnsQueryEvent);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900574 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900575
Ken Chenffc224a2019-03-19 17:41:28 +0800576 LOG(INFO) << __func__ << ": used send_dg " << n;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900577
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800578 if (n < 0) {
Luke Huangba7bef92018-12-26 16:53:03 +0800579 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800580 res_nclose(statp);
581 return -terrno;
582 };
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900583 if (n == 0) goto next_ns;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900584 if (v_circuit) goto same_ns;
585 resplen = n;
586 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900587
Ken Chenffc224a2019-03-19 17:41:28 +0800588 LOG(DEBUG) << __func__ << ": got answer:";
chenbrucedd210722019-03-06 13:52:43 +0800589 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900590
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900591 if (cache_status == RESOLV_CACHE_NOTFOUND) {
Mike Yud1ec2542019-06-06 17:17:53 +0800592 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900593 }
chenbruce018fdb22019-06-12 18:08:04 +0800594 res_nclose(statp);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900595 return (resplen);
596 next_ns:;
Bernie Innocenti9c575932018-09-07 21:10:25 +0900597 } // for each ns
598 } // for each retry
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900599 res_nclose(statp);
600 if (!v_circuit) {
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800601 if (!gotsomewhere) {
602 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900603 errno = ECONNREFUSED; /* no nameservers found */
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800604 terrno = ECONNREFUSED;
605 } else {
606 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900607 errno = ETIMEDOUT; /* no answer obtained */
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800608 terrno = ETIMEDOUT;
609 }
610 } else {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900611 errno = terrno;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800612 }
Luke Huangba7bef92018-12-26 16:53:03 +0800613 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800614 return -terrno;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900615}
616
617/* Private */
618
Bernie Innocenti9c575932018-09-07 21:10:25 +0900619static int get_salen(const struct sockaddr* sa) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900620 if (sa->sa_family == AF_INET)
621 return (sizeof(struct sockaddr_in));
622 else if (sa->sa_family == AF_INET6)
623 return (sizeof(struct sockaddr_in6));
624 else
625 return (0); /* unknown, die on connect */
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900626}
627
Bernie Innocenti9c575932018-09-07 21:10:25 +0900628static struct sockaddr* get_nsaddr(res_state statp, size_t n) {
Bernie Innocentic977ab72019-10-09 00:34:06 +0900629 return (struct sockaddr*)(void*)&statp->nsaddrs[n];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900630}
631
chenbruce99cbfd82019-09-05 15:08:13 +0800632static struct timespec get_timeout(res_state statp, const res_params* params, const int ns) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900633 int msec;
waynemaa74195e2019-01-18 14:02:31 +0800634 // Legacy algorithm which scales the timeout by nameserver number.
635 // For instance, with 4 nameservers: 5s, 2.5s, 5s, 10s
636 // This has no effect with 1 or 2 nameservers
637 msec = params->base_timeout_msec << ns;
638 if (ns > 0) {
639 msec /= statp->nscount;
640 }
641 // For safety, don't allow OEMs and experiments to configure a timeout shorter than 1s.
642 if (msec < 1000) {
643 msec = 1000; // Use at least 1000ms
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900644 }
Ken Chenffc224a2019-03-19 17:41:28 +0800645 LOG(INFO) << __func__ << ": using timeout of " << msec << " msec";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900646
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900647 struct timespec result;
648 result.tv_sec = msec / 1000;
649 result.tv_nsec = (msec % 1000) * 1000000;
650 return result;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900651}
652
chenbrucec51f1212019-09-12 16:59:33 +0800653static int send_vc(res_state statp, res_params* params, const uint8_t* buf, int buflen,
654 uint8_t* ans, int anssiz, int* terrno, int ns, time_t* at, int* rcode,
655 int* delay) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900656 *at = time(NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900657 *delay = 0;
658 const HEADER* hp = (const HEADER*) (const void*) buf;
659 HEADER* anhp = (HEADER*) (void*) ans;
660 struct sockaddr* nsap;
661 int nsaplen;
chenbruce0d470422019-03-28 18:44:37 +0800662 int truncating, connreset, n;
chenbrucec51f1212019-09-12 16:59:33 +0800663 uint8_t* cp;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900664
Ken Chenffc224a2019-03-19 17:41:28 +0800665 LOG(INFO) << __func__ << ": using send_vc";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900666
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900667 nsap = get_nsaddr(statp, (size_t) ns);
668 nsaplen = get_salen(nsap);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900669
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900670 connreset = 0;
671same_ns:
672 truncating = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900673
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900674 struct timespec now = evNowTime();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900675
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900676 /* Are we still talking to whom we want to talk to? */
677 if (statp->_vcsock >= 0 && (statp->_flags & RES_F_VC) != 0) {
678 struct sockaddr_storage peer;
679 socklen_t size = sizeof peer;
680 unsigned old_mark;
681 socklen_t mark_size = sizeof(old_mark);
682 if (getpeername(statp->_vcsock, (struct sockaddr*) (void*) &peer, &size) < 0 ||
683 !sock_eq((struct sockaddr*) (void*) &peer, nsap) ||
684 getsockopt(statp->_vcsock, SOL_SOCKET, SO_MARK, &old_mark, &mark_size) < 0 ||
685 old_mark != statp->_mark) {
686 res_nclose(statp);
687 statp->_flags &= ~RES_F_VC;
688 }
689 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900690
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900691 if (statp->_vcsock < 0 || (statp->_flags & RES_F_VC) == 0) {
692 if (statp->_vcsock >= 0) res_nclose(statp);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900693
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900694 statp->_vcsock = socket(nsap->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0);
695 if (statp->_vcsock < 0) {
696 switch (errno) {
697 case EPROTONOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900698 case EPFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900699 case EAFNOSUPPORT:
chenbruce018fdb22019-06-12 18:08:04 +0800700 PLOG(DEBUG) << __func__ << ": socket(vc): ";
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900701 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900702 default:
703 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800704 PLOG(DEBUG) << __func__ << ": socket(vc): ";
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900705 return -1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900706 }
707 }
Praveen Moongalam Thyagarajan8ab18ba2019-09-04 14:46:50 -0700708 resolv_tag_socket(statp->_vcsock, statp->uid, statp->pid);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900709 if (statp->_mark != MARK_UNSET) {
710 if (setsockopt(statp->_vcsock, SOL_SOCKET, SO_MARK, &statp->_mark,
711 sizeof(statp->_mark)) < 0) {
712 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800713 PLOG(DEBUG) << __func__ << ": setsockopt: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900714 return -1;
715 }
716 }
717 errno = 0;
718 if (random_bind(statp->_vcsock, nsap->sa_family) < 0) {
719 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800720 dump_error("bind/vc", nsap, nsaplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900721 res_nclose(statp);
722 return (0);
723 }
724 if (connect_with_timeout(statp->_vcsock, nsap, (socklen_t) nsaplen,
725 get_timeout(statp, params, ns)) < 0) {
726 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800727 dump_error("connect/vc", nsap, nsaplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900728 res_nclose(statp);
729 /*
730 * The way connect_with_timeout() is implemented prevents us from reliably
731 * determining whether this was really a timeout or e.g. ECONNREFUSED. Since
732 * currently both cases are handled in the same way, there is no need to
733 * change this (yet). If we ever need to reliably distinguish between these
734 * cases, both connect_with_timeout() and retrying_poll() need to be
735 * modified, though.
736 */
737 *rcode = RCODE_TIMEOUT;
738 return (0);
739 }
740 statp->_flags |= RES_F_VC;
741 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900742
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900743 /*
744 * Send length & message
745 */
chenbruce0d470422019-03-28 18:44:37 +0800746 uint16_t len = htons(static_cast<uint16_t>(buflen));
Luke Huangc98fd802019-10-15 16:36:36 +0900747 const iovec iov[] = {
748 {.iov_base = &len, .iov_len = INT16SZ},
749 {.iov_base = const_cast<uint8_t*>(buf), .iov_len = static_cast<size_t>(buflen)},
750 };
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900751 if (writev(statp->_vcsock, iov, 2) != (INT16SZ + buflen)) {
752 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800753 PLOG(DEBUG) << __func__ << ": write failed: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900754 res_nclose(statp);
755 return (0);
756 }
757 /*
758 * Receive length & response
759 */
760read_len:
761 cp = ans;
762 len = INT16SZ;
763 while ((n = read(statp->_vcsock, (char*) cp, (size_t) len)) > 0) {
764 cp += n;
765 if ((len -= n) == 0) break;
766 }
767 if (n <= 0) {
768 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800769 PLOG(DEBUG) << __func__ << ": read failed: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900770 res_nclose(statp);
771 /*
772 * A long running process might get its TCP
773 * connection reset if the remote server was
774 * restarted. Requery the server instead of
775 * trying a new one. When there is only one
776 * server, this means that a query might work
777 * instead of failing. We only allow one reset
778 * per query to prevent looping.
779 */
780 if (*terrno == ECONNRESET && !connreset) {
781 connreset = 1;
782 res_nclose(statp);
783 goto same_ns;
784 }
785 res_nclose(statp);
786 return (0);
787 }
chenbruce0d470422019-03-28 18:44:37 +0800788 uint16_t resplen = ntohs(*reinterpret_cast<const uint16_t*>(ans));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900789 if (resplen > anssiz) {
Ken Chenffc224a2019-03-19 17:41:28 +0800790 LOG(DEBUG) << __func__ << ": response truncated";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900791 truncating = 1;
792 len = anssiz;
793 } else
794 len = resplen;
795 if (len < HFIXEDSZ) {
796 /*
797 * Undersized message.
798 */
Ken Chenffc224a2019-03-19 17:41:28 +0800799 LOG(DEBUG) << __func__ << ": undersized: " << len;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900800 *terrno = EMSGSIZE;
801 res_nclose(statp);
802 return (0);
803 }
804 cp = ans;
805 while (len != 0 && (n = read(statp->_vcsock, (char*) cp, (size_t) len)) > 0) {
806 cp += n;
807 len -= n;
808 }
809 if (n <= 0) {
810 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800811 PLOG(DEBUG) << __func__ << ": read(vc): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900812 res_nclose(statp);
813 return (0);
814 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900815
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900816 if (truncating) {
817 /*
818 * Flush rest of answer so connection stays in synch.
819 */
820 anhp->tc = 1;
821 len = resplen - anssiz;
822 while (len != 0) {
823 char junk[PACKETSZ];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900824
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900825 n = read(statp->_vcsock, junk, (len > sizeof junk) ? sizeof junk : len);
826 if (n > 0)
827 len -= n;
828 else
829 break;
830 }
831 }
832 /*
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900833 * If the calling application has bailed out of
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900834 * a previous call and failed to arrange to have
835 * the circuit closed or the server has got
836 * itself confused, then drop the packet and
837 * wait for the correct one.
838 */
839 if (hp->id != anhp->id) {
Ken Chenffc224a2019-03-19 17:41:28 +0800840 LOG(DEBUG) << __func__ << ": ld answer (unexpected):";
chenbrucedd210722019-03-06 13:52:43 +0800841 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900842 goto read_len;
843 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900844
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900845 /*
846 * All is well, or the error is fatal. Signal that the
847 * next nameserver ought not be tried.
848 */
849 if (resplen > 0) {
850 struct timespec done = evNowTime();
851 *delay = _res_stats_calculate_rtt(&done, &now);
852 *rcode = anhp->rcode;
853 }
854 return (resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900855}
856
857/* return -1 on error (errno set), 0 on success */
Luke Huangc98fd802019-10-15 16:36:36 +0900858static int connect_with_timeout(int sock, const sockaddr* nsap, socklen_t salen,
859 const timespec timeout) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900860 int res, origflags;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900861
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900862 origflags = fcntl(sock, F_GETFL, 0);
863 fcntl(sock, F_SETFL, origflags | O_NONBLOCK);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900864
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900865 res = connect(sock, nsap, salen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900866 if (res < 0 && errno != EINPROGRESS) {
867 res = -1;
868 goto done;
869 }
870 if (res != 0) {
Luke Huangc98fd802019-10-15 16:36:36 +0900871 timespec now = evNowTime();
872 timespec finish = evAddTime(now, timeout);
Ken Chenffc224a2019-03-19 17:41:28 +0800873 LOG(INFO) << __func__ << ": " << sock << " send_vc";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900874 res = retrying_poll(sock, POLLIN | POLLOUT, &finish);
875 if (res <= 0) {
876 res = -1;
877 }
878 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900879done:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900880 fcntl(sock, F_SETFL, origflags);
Ken Chenffc224a2019-03-19 17:41:28 +0800881 LOG(INFO) << __func__ << ": " << sock << " connect_with_const timeout returning " << res;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900882 return res;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900883}
884
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900885static int retrying_poll(const int sock, const short events, const struct timespec* finish) {
886 struct timespec now, timeout;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900887
888retry:
Ken Chenffc224a2019-03-19 17:41:28 +0800889 LOG(INFO) << __func__ << ": " << sock << " retrying_poll";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900890
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900891 now = evNowTime();
892 if (evCmpTime(*finish, now) > 0)
893 timeout = evSubTime(*finish, now);
894 else
895 timeout = evConsTime(0L, 0L);
896 struct pollfd fds = {.fd = sock, .events = events};
897 int n = ppoll(&fds, 1, &timeout, /*sigmask=*/NULL);
898 if (n == 0) {
Ken Chenffc224a2019-03-19 17:41:28 +0800899 LOG(INFO) << __func__ << ": " << sock << "retrying_poll timeout";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900900 errno = ETIMEDOUT;
901 return 0;
902 }
903 if (n < 0) {
904 if (errno == EINTR) goto retry;
Ken Chenffc224a2019-03-19 17:41:28 +0800905 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll failed";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900906 return n;
907 }
908 if (fds.revents & (POLLIN | POLLOUT | POLLERR)) {
909 int error;
910 socklen_t len = sizeof(error);
911 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error) {
912 errno = error;
Ken Chenffc224a2019-03-19 17:41:28 +0800913 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll getsockopt failed";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900914 return -1;
915 }
916 }
Ken Chenffc224a2019-03-19 17:41:28 +0800917 LOG(INFO) << __func__ << ": " << sock << " retrying_poll returning " << n;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900918 return n;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900919}
920
chenbrucec51f1212019-09-12 16:59:33 +0800921static int send_dg(res_state statp, res_params* params, const uint8_t* buf, int buflen,
922 uint8_t* ans, int anssiz, int* terrno, int ns, int* v_circuit, int* gotsomewhere,
923 time_t* at, int* rcode, int* delay) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900924 *at = time(NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900925 *delay = 0;
926 const HEADER* hp = (const HEADER*) (const void*) buf;
927 HEADER* anhp = (HEADER*) (void*) ans;
928 const struct sockaddr* nsap;
929 int nsaplen;
930 struct timespec now, timeout, finish, done;
931 struct sockaddr_storage from;
932 socklen_t fromlen;
933 int resplen, n, s;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900934
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900935 nsap = get_nsaddr(statp, (size_t) ns);
936 nsaplen = get_salen(nsap);
Bernie Innocentibb330742019-10-09 00:55:53 +0900937 if (statp->nssocks[ns] == -1) {
938 statp->nssocks[ns] = socket(nsap->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
939 if (statp->nssocks[ns] < 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900940 switch (errno) {
941 case EPROTONOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900942 case EPFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900943 case EAFNOSUPPORT:
chenbruce018fdb22019-06-12 18:08:04 +0800944 PLOG(DEBUG) << __func__ << ": socket(dg): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900945 return (0);
946 default:
947 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800948 PLOG(DEBUG) << __func__ << ": socket(dg): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900949 return (-1);
950 }
951 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900952
Praveen Moongalam Thyagarajan8ab18ba2019-09-04 14:46:50 -0700953 resolv_tag_socket(statp->nssocks[ns], statp->uid, statp->pid);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900954 if (statp->_mark != MARK_UNSET) {
Bernie Innocentibb330742019-10-09 00:55:53 +0900955 if (setsockopt(statp->nssocks[ns], SOL_SOCKET, SO_MARK, &(statp->_mark),
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900956 sizeof(statp->_mark)) < 0) {
957 res_nclose(statp);
958 return -1;
959 }
960 }
chenbruceb9cce7b2019-07-15 16:14:53 +0800961 // Use a "connected" datagram socket to receive an ECONNREFUSED error
962 // on the next socket operation when the server responds with an
963 // ICMP port-unreachable error. This way we can detect the absence of
964 // a nameserver without timing out.
Bernie Innocentibb330742019-10-09 00:55:53 +0900965 if (random_bind(statp->nssocks[ns], nsap->sa_family) < 0) {
chenbruce018fdb22019-06-12 18:08:04 +0800966 dump_error("bind(dg)", nsap, nsaplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900967 res_nclose(statp);
968 return (0);
969 }
Bernie Innocentibb330742019-10-09 00:55:53 +0900970 if (connect(statp->nssocks[ns], nsap, (socklen_t)nsaplen) < 0) {
chenbruce018fdb22019-06-12 18:08:04 +0800971 dump_error("connect(dg)", nsap, nsaplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900972 res_nclose(statp);
973 return (0);
974 }
Ken Chenffc224a2019-03-19 17:41:28 +0800975 LOG(DEBUG) << __func__ << ": new DG socket";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900976 }
Bernie Innocentibb330742019-10-09 00:55:53 +0900977 s = statp->nssocks[ns];
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900978 if (send(s, (const char*) buf, (size_t) buflen, 0) != buflen) {
chenbruce018fdb22019-06-12 18:08:04 +0800979 PLOG(DEBUG) << __func__ << ": send: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900980 res_nclose(statp);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +0900981 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900982 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900983
Bernie Innocenti3952ccc2019-03-03 19:39:53 +0900984 // Wait for reply.
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900985 timeout = get_timeout(statp, params, ns);
986 now = evNowTime();
987 finish = evAddTime(now, timeout);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900988retry:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900989 n = retrying_poll(s, POLLIN, &finish);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900990
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900991 if (n == 0) {
992 *rcode = RCODE_TIMEOUT;
Ken Chenffc224a2019-03-19 17:41:28 +0800993 LOG(DEBUG) << __func__ << ": timeout";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900994 *gotsomewhere = 1;
Bernie Innocenti3952ccc2019-03-03 19:39:53 +0900995 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900996 }
997 if (n < 0) {
chenbruce018fdb22019-06-12 18:08:04 +0800998 PLOG(DEBUG) << __func__ << ": poll: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900999 res_nclose(statp);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001000 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001001 }
1002 errno = 0;
1003 fromlen = sizeof(from);
1004 resplen = recvfrom(s, (char*) ans, (size_t) anssiz, 0, (struct sockaddr*) (void*) &from,
1005 &fromlen);
1006 if (resplen <= 0) {
chenbruce018fdb22019-06-12 18:08:04 +08001007 PLOG(DEBUG) << __func__ << ": recvfrom: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001008 res_nclose(statp);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001009 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001010 }
1011 *gotsomewhere = 1;
1012 if (resplen < HFIXEDSZ) {
1013 /*
1014 * Undersized message.
1015 */
Ken Chenffc224a2019-03-19 17:41:28 +08001016 LOG(DEBUG) << __func__ << ": undersized: " << resplen;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001017 *terrno = EMSGSIZE;
1018 res_nclose(statp);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001019 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001020 }
1021 if (hp->id != anhp->id) {
1022 /*
1023 * response from old query, ignore it.
1024 * XXX - potential security hazard could
1025 * be detected here.
1026 */
Ken Chenffc224a2019-03-19 17:41:28 +08001027 LOG(DEBUG) << __func__ << ": old answer:";
chenbrucedd210722019-03-06 13:52:43 +08001028 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001029 goto retry;
1030 }
chenbruce018fdb22019-06-12 18:08:04 +08001031 if (!res_ourserver_p(statp, (struct sockaddr*)(void*)&from)) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001032 /*
1033 * response from wrong server? ignore it.
1034 * XXX - potential security hazard could
1035 * be detected here.
1036 */
Ken Chenffc224a2019-03-19 17:41:28 +08001037 LOG(DEBUG) << __func__ << ": not our server:";
chenbrucedd210722019-03-06 13:52:43 +08001038 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001039 goto retry;
1040 }
chenbruced8cbb9b2019-06-20 18:25:28 +08001041 if (anhp->rcode == FORMERR && (statp->netcontext_flags & NET_CONTEXT_FLAG_USE_EDNS)) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001042 /*
1043 * Do not retry if the server do not understand EDNS0.
1044 * The case has to be captured here, as FORMERR packet do not
1045 * carry query section, hence res_queriesmatch() returns 0.
1046 */
Ken Chenffc224a2019-03-19 17:41:28 +08001047 LOG(DEBUG) << __func__ << ": server rejected query with EDNS0:";
chenbrucedd210722019-03-06 13:52:43 +08001048 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001049 /* record the error */
1050 statp->_flags |= RES_F_EDNS0ERR;
1051 res_nclose(statp);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001052 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001053 }
chenbruce018fdb22019-06-12 18:08:04 +08001054 if (!res_queriesmatch(buf, buf + buflen, ans, ans + anssiz)) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001055 /*
1056 * response contains wrong query? ignore it.
1057 * XXX - potential security hazard could
1058 * be detected here.
1059 */
Ken Chenffc224a2019-03-19 17:41:28 +08001060 LOG(DEBUG) << __func__ << ": wrong query name:";
chenbrucedd210722019-03-06 13:52:43 +08001061 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001062 goto retry;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001063 }
1064 done = evNowTime();
1065 *delay = _res_stats_calculate_rtt(&done, &now);
1066 if (anhp->rcode == SERVFAIL || anhp->rcode == NOTIMP || anhp->rcode == REFUSED) {
Ken Chenffc224a2019-03-19 17:41:28 +08001067 LOG(DEBUG) << __func__ << ": server rejected query:";
chenbrucedd210722019-03-06 13:52:43 +08001068 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001069 res_nclose(statp);
chenbrucedd210722019-03-06 13:52:43 +08001070 *rcode = anhp->rcode;
1071 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001072 }
chenbruce018fdb22019-06-12 18:08:04 +08001073 if (anhp->tc) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001074 /*
1075 * To get the rest of answer,
1076 * use TCP with same server.
1077 */
Ken Chenffc224a2019-03-19 17:41:28 +08001078 LOG(DEBUG) << __func__ << ": truncated answer";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001079 *v_circuit = 1;
1080 res_nclose(statp);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001081 return 1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001082 }
1083 /*
1084 * All is well, or the error is fatal. Signal that the
1085 * next nameserver ought not be tried.
1086 */
1087 if (resplen > 0) {
1088 *rcode = anhp->rcode;
1089 }
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001090 return resplen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001091}
1092
chenbruce018fdb22019-06-12 18:08:04 +08001093static void dump_error(const char* str, const struct sockaddr* address, int alen) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001094 char hbuf[NI_MAXHOST];
1095 char sbuf[NI_MAXSERV];
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001096 constexpr int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
Luke Huangc98fd802019-10-15 16:36:36 +09001097 const int err = errno;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001098
chenbruce018fdb22019-06-12 18:08:04 +08001099 if (!WOULD_LOG(DEBUG)) return;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001100
chenbruce018fdb22019-06-12 18:08:04 +08001101 if (getnameinfo(address, (socklen_t)alen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf), niflags)) {
1102 strncpy(hbuf, "?", sizeof(hbuf) - 1);
1103 hbuf[sizeof(hbuf) - 1] = '\0';
1104 strncpy(sbuf, "?", sizeof(sbuf) - 1);
1105 sbuf[sizeof(sbuf) - 1] = '\0';
Elliott Hughes3b8f5902019-03-08 12:02:55 -08001106 }
Luke Huangc98fd802019-10-15 16:36:36 +09001107 errno = err;
chenbruce018fdb22019-06-12 18:08:04 +08001108 PLOG(DEBUG) << __func__ << ": " << str << " ([" << hbuf << "]." << sbuf << "): ";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001109}
1110
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001111static int sock_eq(struct sockaddr* a, struct sockaddr* b) {
1112 struct sockaddr_in *a4, *b4;
1113 struct sockaddr_in6 *a6, *b6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001114
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001115 if (a->sa_family != b->sa_family) return 0;
1116 switch (a->sa_family) {
1117 case AF_INET:
1118 a4 = (struct sockaddr_in*) (void*) a;
1119 b4 = (struct sockaddr_in*) (void*) b;
1120 return a4->sin_port == b4->sin_port && a4->sin_addr.s_addr == b4->sin_addr.s_addr;
1121 case AF_INET6:
1122 a6 = (struct sockaddr_in6*) (void*) a;
1123 b6 = (struct sockaddr_in6*) (void*) b;
1124 return a6->sin6_port == b6->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001125#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001126 a6->sin6_scope_id == b6->sin6_scope_id &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001127#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001128 IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
1129 default:
1130 return 0;
1131 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001132}
Mike Yub601ff72018-11-01 20:07:00 +08001133
lifr6b83a6f2019-07-26 03:17:43 +08001134PrivateDnsModes convertEnumType(PrivateDnsMode privateDnsmode) {
1135 switch (privateDnsmode) {
1136 case PrivateDnsMode::OFF:
1137 return PrivateDnsModes::PDM_OFF;
1138 case PrivateDnsMode::OPPORTUNISTIC:
1139 return PrivateDnsModes::PDM_OPPORTUNISTIC;
1140 case PrivateDnsMode::STRICT:
1141 return PrivateDnsModes::PDM_STRICT;
1142 }
1143 return PrivateDnsModes::PDM_UNKNOWN;
1144}
1145
Luke Huangd7aa7b42018-11-21 20:37:50 +08001146static int res_tls_send(res_state statp, const Slice query, const Slice answer, int* rcode,
Mike Yubfb1b342018-11-06 15:42:36 +08001147 bool* fallback) {
1148 int resplen = 0;
Mike Yub601ff72018-11-01 20:07:00 +08001149 const unsigned netId = statp->netid;
Mike Yub601ff72018-11-01 20:07:00 +08001150
Mike Yubfb1b342018-11-06 15:42:36 +08001151 PrivateDnsStatus privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
lifr6b83a6f2019-07-26 03:17:43 +08001152 statp->event->set_private_dns_modes(convertEnumType(privateDnsStatus.mode));
Mike Yubfb1b342018-11-06 15:42:36 +08001153
1154 if (privateDnsStatus.mode == PrivateDnsMode::OFF) {
1155 *fallback = true;
1156 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001157 }
1158
Mike Yu3e829062019-08-07 14:01:14 +08001159 if (privateDnsStatus.validatedServers().empty()) {
Mike Yub601ff72018-11-01 20:07:00 +08001160 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
Mike Yubfb1b342018-11-06 15:42:36 +08001161 *fallback = true;
1162 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001163 } else {
1164 // Sleep and iterate some small number of times checking for the
1165 // arrival of resolved and validated server IP addresses, instead
1166 // of returning an immediate error.
Mike Yu4f3747b2018-12-02 17:54:29 +09001167 // This is needed because as soon as a network becomes the default network, apps will
1168 // send DNS queries on that network. If no servers have yet validated, and we do not
1169 // block those queries, they would immediately fail, causing application-visible errors.
1170 // Note that this can happen even before the network validates, since an unvalidated
1171 // network can become the default network if no validated networks are available.
1172 //
1173 // TODO: see if there is a better way to address this problem, such as buffering the
1174 // queries in a queue or only blocking queries for the first few seconds after a default
1175 // network change.
Mike Yubfb1b342018-11-06 15:42:36 +08001176 for (int i = 0; i < 42; i++) {
1177 std::this_thread::sleep_for(std::chrono::milliseconds(100));
Mike Yu3e829062019-08-07 14:01:14 +08001178 // Calling getStatus() to merely check if there's any validated server seems
1179 // wasteful. Consider adding a new method in PrivateDnsConfiguration for speed ups.
1180 if (!gPrivateDnsConfiguration.getStatus(netId).validatedServers().empty()) {
Mike Yubfb1b342018-11-06 15:42:36 +08001181 privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
1182 break;
1183 }
1184 }
Mike Yu3e829062019-08-07 14:01:14 +08001185 if (privateDnsStatus.validatedServers().empty()) {
Mike Yubfb1b342018-11-06 15:42:36 +08001186 return -1;
1187 }
Mike Yub601ff72018-11-01 20:07:00 +08001188 }
1189 }
1190
chenbruceacb832c2019-02-20 19:45:50 +08001191 LOG(INFO) << __func__ << ": performing query over TLS";
Mike Yub601ff72018-11-01 20:07:00 +08001192
Mike Yu3e829062019-08-07 14:01:14 +08001193 const auto response = sDnsTlsDispatcher.query(privateDnsStatus.validatedServers(), statp, query,
Mike Yubfb1b342018-11-06 15:42:36 +08001194 answer, &resplen);
Mike Yub601ff72018-11-01 20:07:00 +08001195
chenbruceacb832c2019-02-20 19:45:50 +08001196 LOG(INFO) << __func__ << ": TLS query result: " << static_cast<int>(response);
Mike Yub601ff72018-11-01 20:07:00 +08001197
1198 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
1199 // In opportunistic mode, handle falling back to cleartext in some
1200 // cases (DNS shouldn't fail if a validated opportunistic mode server
1201 // becomes unreachable for some reason).
1202 switch (response) {
Mike Yubfb1b342018-11-06 15:42:36 +08001203 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001204 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001205 return resplen;
Mike Yub601ff72018-11-01 20:07:00 +08001206 case DnsTlsTransport::Response::network_error:
Mike Yubfb1b342018-11-06 15:42:36 +08001207 // No need to set the error timeout here since it will fallback to UDP.
Mike Yub601ff72018-11-01 20:07:00 +08001208 case DnsTlsTransport::Response::internal_error:
1209 // Note: this will cause cleartext queries to be emitted, with
1210 // all of the EDNS0 goodness enabled. Fingers crossed. :-/
Mike Yubfb1b342018-11-06 15:42:36 +08001211 *fallback = true;
1212 [[fallthrough]];
Mike Yub601ff72018-11-01 20:07:00 +08001213 default:
Mike Yubfb1b342018-11-06 15:42:36 +08001214 return -1;
1215 }
1216 } else {
1217 // Strict mode
1218 switch (response) {
1219 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001220 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001221 return resplen;
1222 case DnsTlsTransport::Response::network_error:
1223 // This case happens when the query stored in DnsTlsTransport is expired since
1224 // either 1) the query has been tried for 3 times but no response or 2) fail to
1225 // establish the connection with the server.
Luke Huangd7aa7b42018-11-21 20:37:50 +08001226 *rcode = RCODE_TIMEOUT;
Mike Yubfb1b342018-11-06 15:42:36 +08001227 [[fallthrough]];
1228 default:
1229 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001230 }
1231 }
Mike Yub601ff72018-11-01 20:07:00 +08001232}
Luke Huang4973a0d2018-11-19 20:17:26 +08001233
Luke Huangba7bef92018-12-26 16:53:03 +08001234int resolv_res_nsend(const android_net_context* netContext, const uint8_t* msg, int msgLen,
lifr94981782019-05-17 21:15:19 +08001235 uint8_t* ans, int ansLen, int* rcode, uint32_t flags,
1236 NetworkDnsEventReported* event) {
1237 assert(event != nullptr);
Bernie Innocenti08487112019-10-11 21:14:13 +09001238 ResState res;
1239 res_init(&res, netContext, event);
1240 _resolv_populate_res_for_net(&res);
Luke Huang4973a0d2018-11-19 20:17:26 +08001241 *rcode = NOERROR;
Bernie Innocenti08487112019-10-11 21:14:13 +09001242 return res_nsend(&res, msg, msgLen, ans, ansLen, rcode, flags);
Bernie Innocentiec4219b2019-01-30 11:16:36 +09001243}