blob: e917b13dc712743af10f18a0f39f4854780ddf3c [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
Luke Huang272cb192019-10-15 16:52:28 +0900443 // DoT
444 if (!(statp->netcontext_flags & NET_CONTEXT_FLAG_USE_LOCAL_NAMESERVERS)) {
445 bool fallback = false;
446 resplen = res_tls_send(statp, Slice(const_cast<uint8_t*>(buf), buflen), Slice(ans, anssiz),
447 rcode, &fallback);
448 if (resplen > 0) {
449 LOG(DEBUG) << __func__ << ": got answer from DoT";
450 res_pquery(ans, resplen);
451 if (cache_status == RESOLV_CACHE_NOTFOUND) {
452 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
453 }
454 return resplen;
455 }
456 if (!fallback) {
457 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
458 return -terrno;
459 }
460 }
461
Bernie Innocenti758005f2019-02-19 18:08:36 +0900462 res_stats stats[MAXNS];
463 res_params params;
waynema0161acd2019-02-18 17:47:59 +0800464 int revision_id = resolv_cache_get_resolver_stats(statp->netid, &params, stats);
lifra1b37f12019-02-13 17:33:57 +0800465 if (revision_id < 0) {
466 // TODO: Remove errno once callers stop using it
467 errno = ESRCH;
468 return -ESRCH;
469 }
waynema0161acd2019-02-18 17:47:59 +0800470 bool usable_servers[MAXNS];
Luke Huang70931aa2019-01-31 11:57:41 +0800471 int usableServersCount = android_net_res_stats_get_usable_servers(
472 &params, stats, statp->nscount, usable_servers);
473
474 if ((flags & ANDROID_RESOLV_NO_RETRY) && usableServersCount > 1) {
475 auto hp = reinterpret_cast<const HEADER*>(buf);
476
477 // Select a random server based on the query id
478 int selectedServer = (hp->id % usableServersCount) + 1;
479 res_set_usable_server(selectedServer, statp->nscount, usable_servers);
480 }
waynema0161acd2019-02-18 17:47:59 +0800481
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900482 /*
483 * Send request, RETRY times, or until successful.
484 */
waynemaa74195e2019-01-18 14:02:31 +0800485 int retryTimes = (flags & ANDROID_RESOLV_NO_RETRY) ? 1 : params.retry_count;
Luke Huangba7bef92018-12-26 16:53:03 +0800486
487 for (int attempt = 0; attempt < retryTimes; ++attempt) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900488
Bernie Innocenti9c575932018-09-07 21:10:25 +0900489 for (int ns = 0; ns < statp->nscount; ns++) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900490 if (!usable_servers[ns]) continue;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900491 int nsaplen;
492 time_t now = 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900493 int delay = 0;
Mike Yubfb1b342018-11-06 15:42:36 +0800494 *rcode = RCODE_INTERNAL_ERROR;
lifr94981782019-05-17 21:15:19 +0800495 const sockaddr* nsap = get_nsaddr(statp, ns);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900496 nsaplen = get_salen(nsap);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900497
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900498 same_ns:
lifr94981782019-05-17 21:15:19 +0800499 static const int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
500 char abuf[NI_MAXHOST];
501 DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
502 dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
chenbruceacb832c2019-02-20 19:45:50 +0800503
504 if (getnameinfo(nsap, (socklen_t)nsaplen, abuf, sizeof(abuf), NULL, 0, niflags) == 0)
Ken Chenffc224a2019-03-19 17:41:28 +0800505 LOG(DEBUG) << __func__ << ": Querying server (# " << ns + 1
506 << ") address = " << abuf;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900507
lifrd4d9fbb2019-07-31 20:18:35 +0800508 Stopwatch queryStopwatch;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900509 if (v_circuit) {
510 /* Use VC; at most one attempt per server. */
Luke Huangba7bef92018-12-26 16:53:03 +0800511 bool shouldRecordStats = (attempt == 0);
512 attempt = retryTimes;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900513
Mike Yubfb1b342018-11-06 15:42:36 +0800514 n = send_vc(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &now, rcode,
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900515 &delay);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900516
lifr94981782019-05-17 21:15:19 +0800517 dnsQueryEvent->set_latency_micros(
lifrd4d9fbb2019-07-31 20:18:35 +0800518 saturate_cast<int32_t>(queryStopwatch.timeTakenUs()));
lifr94981782019-05-17 21:15:19 +0800519 dnsQueryEvent->set_dns_server_index(ns);
520 dnsQueryEvent->set_ip_version(ipFamilyToIPVersion(nsap->sa_family));
521 dnsQueryEvent->set_retry_times(attempt);
522 dnsQueryEvent->set_rcode(static_cast<NsRcode>(*rcode));
523 dnsQueryEvent->set_protocol(PROTO_TCP);
524 dnsQueryEvent->set_type(getQueryType(buf, buflen));
525
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900526 /*
527 * Only record stats the first time we try a query. This ensures that
528 * queries that deterministically fail (e.g., a name that always returns
529 * SERVFAIL or times out) do not unduly affect the stats.
530 */
Luke Huangba7bef92018-12-26 16:53:03 +0800531 if (shouldRecordStats) {
Bernie Innocentiac18b122018-10-01 23:10:18 +0900532 res_sample sample;
Mike Yubfb1b342018-11-06 15:42:36 +0800533 _res_stats_set_sample(&sample, now, *rcode, delay);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900534 _resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, ns, &sample,
535 params.max_samples);
Mike Yue655b1d2019-08-28 17:49:59 +0800536 resolv_stats_add(statp->netid, IPSockAddr::toIPSockAddr(*nsap), dnsQueryEvent);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900537 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900538
Ken Chenffc224a2019-03-19 17:41:28 +0800539 LOG(INFO) << __func__ << ": used send_vc " << n;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900540
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800541 if (n < 0) {
Luke Huangba7bef92018-12-26 16:53:03 +0800542 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800543 res_nclose(statp);
544 return -terrno;
545 };
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900546 if (n == 0) goto next_ns;
547 resplen = n;
548 } else {
549 /* Use datagrams. */
Ken Chenffc224a2019-03-19 17:41:28 +0800550 LOG(INFO) << __func__ << ": using send_dg";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900551
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900552 n = send_dg(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &v_circuit,
Mike Yubfb1b342018-11-06 15:42:36 +0800553 &gotsomewhere, &now, rcode, &delay);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900554
lifr94981782019-05-17 21:15:19 +0800555 dnsQueryEvent->set_latency_micros(
lifrd4d9fbb2019-07-31 20:18:35 +0800556 saturate_cast<int32_t>(queryStopwatch.timeTakenUs()));
lifr94981782019-05-17 21:15:19 +0800557 dnsQueryEvent->set_dns_server_index(ns);
558 dnsQueryEvent->set_ip_version(ipFamilyToIPVersion(nsap->sa_family));
559 dnsQueryEvent->set_retry_times(attempt);
560 dnsQueryEvent->set_rcode(static_cast<NsRcode>(*rcode));
561 dnsQueryEvent->set_protocol(PROTO_UDP);
562 dnsQueryEvent->set_type(getQueryType(buf, buflen));
563
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900564 /* Only record stats the first time we try a query. See above. */
Bernie Innocenti9c575932018-09-07 21:10:25 +0900565 if (attempt == 0) {
Bernie Innocentiac18b122018-10-01 23:10:18 +0900566 res_sample sample;
Mike Yubfb1b342018-11-06 15:42:36 +0800567 _res_stats_set_sample(&sample, now, *rcode, delay);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900568 _resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, ns, &sample,
569 params.max_samples);
Mike Yue655b1d2019-08-28 17:49:59 +0800570 resolv_stats_add(statp->netid, IPSockAddr::toIPSockAddr(*nsap), dnsQueryEvent);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900571 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900572
Ken Chenffc224a2019-03-19 17:41:28 +0800573 LOG(INFO) << __func__ << ": used send_dg " << n;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900574
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800575 if (n < 0) {
Luke Huangba7bef92018-12-26 16:53:03 +0800576 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800577 res_nclose(statp);
578 return -terrno;
579 };
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900580 if (n == 0) goto next_ns;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900581 if (v_circuit) goto same_ns;
582 resplen = n;
583 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900584
Ken Chenffc224a2019-03-19 17:41:28 +0800585 LOG(DEBUG) << __func__ << ": got answer:";
chenbrucedd210722019-03-06 13:52:43 +0800586 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900587
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900588 if (cache_status == RESOLV_CACHE_NOTFOUND) {
Mike Yud1ec2542019-06-06 17:17:53 +0800589 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900590 }
chenbruce018fdb22019-06-12 18:08:04 +0800591 res_nclose(statp);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900592 return (resplen);
593 next_ns:;
Bernie Innocenti9c575932018-09-07 21:10:25 +0900594 } // for each ns
595 } // for each retry
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900596 res_nclose(statp);
597 if (!v_circuit) {
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800598 if (!gotsomewhere) {
599 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900600 errno = ECONNREFUSED; /* no nameservers found */
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800601 terrno = ECONNREFUSED;
602 } else {
603 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900604 errno = ETIMEDOUT; /* no answer obtained */
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800605 terrno = ETIMEDOUT;
606 }
607 } else {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900608 errno = terrno;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800609 }
Luke Huangba7bef92018-12-26 16:53:03 +0800610 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800611 return -terrno;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900612}
613
614/* Private */
615
Bernie Innocenti9c575932018-09-07 21:10:25 +0900616static int get_salen(const struct sockaddr* sa) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900617 if (sa->sa_family == AF_INET)
618 return (sizeof(struct sockaddr_in));
619 else if (sa->sa_family == AF_INET6)
620 return (sizeof(struct sockaddr_in6));
621 else
622 return (0); /* unknown, die on connect */
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900623}
624
Bernie Innocenti9c575932018-09-07 21:10:25 +0900625static struct sockaddr* get_nsaddr(res_state statp, size_t n) {
Bernie Innocentic977ab72019-10-09 00:34:06 +0900626 return (struct sockaddr*)(void*)&statp->nsaddrs[n];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900627}
628
chenbruce99cbfd82019-09-05 15:08:13 +0800629static struct timespec get_timeout(res_state statp, const res_params* params, const int ns) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900630 int msec;
waynemaa74195e2019-01-18 14:02:31 +0800631 // Legacy algorithm which scales the timeout by nameserver number.
632 // For instance, with 4 nameservers: 5s, 2.5s, 5s, 10s
633 // This has no effect with 1 or 2 nameservers
634 msec = params->base_timeout_msec << ns;
635 if (ns > 0) {
636 msec /= statp->nscount;
637 }
638 // For safety, don't allow OEMs and experiments to configure a timeout shorter than 1s.
639 if (msec < 1000) {
640 msec = 1000; // Use at least 1000ms
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900641 }
Ken Chenffc224a2019-03-19 17:41:28 +0800642 LOG(INFO) << __func__ << ": using timeout of " << msec << " msec";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900643
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900644 struct timespec result;
645 result.tv_sec = msec / 1000;
646 result.tv_nsec = (msec % 1000) * 1000000;
647 return result;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900648}
649
chenbrucec51f1212019-09-12 16:59:33 +0800650static int send_vc(res_state statp, res_params* params, const uint8_t* buf, int buflen,
651 uint8_t* ans, int anssiz, int* terrno, int ns, time_t* at, int* rcode,
652 int* delay) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900653 *at = time(NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900654 *delay = 0;
655 const HEADER* hp = (const HEADER*) (const void*) buf;
656 HEADER* anhp = (HEADER*) (void*) ans;
657 struct sockaddr* nsap;
658 int nsaplen;
chenbruce0d470422019-03-28 18:44:37 +0800659 int truncating, connreset, n;
chenbrucec51f1212019-09-12 16:59:33 +0800660 uint8_t* cp;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900661
Ken Chenffc224a2019-03-19 17:41:28 +0800662 LOG(INFO) << __func__ << ": using send_vc";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900663
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900664 nsap = get_nsaddr(statp, (size_t) ns);
665 nsaplen = get_salen(nsap);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900666
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900667 connreset = 0;
668same_ns:
669 truncating = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900670
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900671 struct timespec now = evNowTime();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900672
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900673 /* Are we still talking to whom we want to talk to? */
674 if (statp->_vcsock >= 0 && (statp->_flags & RES_F_VC) != 0) {
675 struct sockaddr_storage peer;
676 socklen_t size = sizeof peer;
677 unsigned old_mark;
678 socklen_t mark_size = sizeof(old_mark);
679 if (getpeername(statp->_vcsock, (struct sockaddr*) (void*) &peer, &size) < 0 ||
680 !sock_eq((struct sockaddr*) (void*) &peer, nsap) ||
681 getsockopt(statp->_vcsock, SOL_SOCKET, SO_MARK, &old_mark, &mark_size) < 0 ||
682 old_mark != statp->_mark) {
683 res_nclose(statp);
684 statp->_flags &= ~RES_F_VC;
685 }
686 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900687
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900688 if (statp->_vcsock < 0 || (statp->_flags & RES_F_VC) == 0) {
689 if (statp->_vcsock >= 0) res_nclose(statp);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900690
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900691 statp->_vcsock = socket(nsap->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0);
692 if (statp->_vcsock < 0) {
693 switch (errno) {
694 case EPROTONOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900695 case EPFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900696 case EAFNOSUPPORT:
chenbruce018fdb22019-06-12 18:08:04 +0800697 PLOG(DEBUG) << __func__ << ": socket(vc): ";
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900698 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900699 default:
700 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800701 PLOG(DEBUG) << __func__ << ": socket(vc): ";
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900702 return -1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900703 }
704 }
Praveen Moongalam Thyagarajan8ab18ba2019-09-04 14:46:50 -0700705 resolv_tag_socket(statp->_vcsock, statp->uid, statp->pid);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900706 if (statp->_mark != MARK_UNSET) {
707 if (setsockopt(statp->_vcsock, SOL_SOCKET, SO_MARK, &statp->_mark,
708 sizeof(statp->_mark)) < 0) {
709 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800710 PLOG(DEBUG) << __func__ << ": setsockopt: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900711 return -1;
712 }
713 }
714 errno = 0;
715 if (random_bind(statp->_vcsock, nsap->sa_family) < 0) {
716 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800717 dump_error("bind/vc", nsap, nsaplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900718 res_nclose(statp);
719 return (0);
720 }
721 if (connect_with_timeout(statp->_vcsock, nsap, (socklen_t) nsaplen,
722 get_timeout(statp, params, ns)) < 0) {
723 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800724 dump_error("connect/vc", nsap, nsaplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900725 res_nclose(statp);
726 /*
727 * The way connect_with_timeout() is implemented prevents us from reliably
728 * determining whether this was really a timeout or e.g. ECONNREFUSED. Since
729 * currently both cases are handled in the same way, there is no need to
730 * change this (yet). If we ever need to reliably distinguish between these
731 * cases, both connect_with_timeout() and retrying_poll() need to be
732 * modified, though.
733 */
734 *rcode = RCODE_TIMEOUT;
735 return (0);
736 }
737 statp->_flags |= RES_F_VC;
738 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900739
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900740 /*
741 * Send length & message
742 */
chenbruce0d470422019-03-28 18:44:37 +0800743 uint16_t len = htons(static_cast<uint16_t>(buflen));
Luke Huangc98fd802019-10-15 16:36:36 +0900744 const iovec iov[] = {
745 {.iov_base = &len, .iov_len = INT16SZ},
746 {.iov_base = const_cast<uint8_t*>(buf), .iov_len = static_cast<size_t>(buflen)},
747 };
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900748 if (writev(statp->_vcsock, iov, 2) != (INT16SZ + buflen)) {
749 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800750 PLOG(DEBUG) << __func__ << ": write failed: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900751 res_nclose(statp);
752 return (0);
753 }
754 /*
755 * Receive length & response
756 */
757read_len:
758 cp = ans;
759 len = INT16SZ;
760 while ((n = read(statp->_vcsock, (char*) cp, (size_t) len)) > 0) {
761 cp += n;
762 if ((len -= n) == 0) break;
763 }
764 if (n <= 0) {
765 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800766 PLOG(DEBUG) << __func__ << ": read failed: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900767 res_nclose(statp);
768 /*
769 * A long running process might get its TCP
770 * connection reset if the remote server was
771 * restarted. Requery the server instead of
772 * trying a new one. When there is only one
773 * server, this means that a query might work
774 * instead of failing. We only allow one reset
775 * per query to prevent looping.
776 */
777 if (*terrno == ECONNRESET && !connreset) {
778 connreset = 1;
779 res_nclose(statp);
780 goto same_ns;
781 }
782 res_nclose(statp);
783 return (0);
784 }
chenbruce0d470422019-03-28 18:44:37 +0800785 uint16_t resplen = ntohs(*reinterpret_cast<const uint16_t*>(ans));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900786 if (resplen > anssiz) {
Ken Chenffc224a2019-03-19 17:41:28 +0800787 LOG(DEBUG) << __func__ << ": response truncated";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900788 truncating = 1;
789 len = anssiz;
790 } else
791 len = resplen;
792 if (len < HFIXEDSZ) {
793 /*
794 * Undersized message.
795 */
Ken Chenffc224a2019-03-19 17:41:28 +0800796 LOG(DEBUG) << __func__ << ": undersized: " << len;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900797 *terrno = EMSGSIZE;
798 res_nclose(statp);
799 return (0);
800 }
801 cp = ans;
802 while (len != 0 && (n = read(statp->_vcsock, (char*) cp, (size_t) len)) > 0) {
803 cp += n;
804 len -= n;
805 }
806 if (n <= 0) {
807 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800808 PLOG(DEBUG) << __func__ << ": read(vc): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900809 res_nclose(statp);
810 return (0);
811 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900812
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900813 if (truncating) {
814 /*
815 * Flush rest of answer so connection stays in synch.
816 */
817 anhp->tc = 1;
818 len = resplen - anssiz;
819 while (len != 0) {
820 char junk[PACKETSZ];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900821
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900822 n = read(statp->_vcsock, junk, (len > sizeof junk) ? sizeof junk : len);
823 if (n > 0)
824 len -= n;
825 else
826 break;
827 }
828 }
829 /*
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900830 * If the calling application has bailed out of
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900831 * a previous call and failed to arrange to have
832 * the circuit closed or the server has got
833 * itself confused, then drop the packet and
834 * wait for the correct one.
835 */
836 if (hp->id != anhp->id) {
Ken Chenffc224a2019-03-19 17:41:28 +0800837 LOG(DEBUG) << __func__ << ": ld answer (unexpected):";
chenbrucedd210722019-03-06 13:52:43 +0800838 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900839 goto read_len;
840 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900841
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900842 /*
843 * All is well, or the error is fatal. Signal that the
844 * next nameserver ought not be tried.
845 */
846 if (resplen > 0) {
847 struct timespec done = evNowTime();
848 *delay = _res_stats_calculate_rtt(&done, &now);
849 *rcode = anhp->rcode;
850 }
851 return (resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900852}
853
854/* return -1 on error (errno set), 0 on success */
Luke Huangc98fd802019-10-15 16:36:36 +0900855static int connect_with_timeout(int sock, const sockaddr* nsap, socklen_t salen,
856 const timespec timeout) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900857 int res, origflags;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900858
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900859 origflags = fcntl(sock, F_GETFL, 0);
860 fcntl(sock, F_SETFL, origflags | O_NONBLOCK);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900861
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900862 res = connect(sock, nsap, salen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900863 if (res < 0 && errno != EINPROGRESS) {
864 res = -1;
865 goto done;
866 }
867 if (res != 0) {
Luke Huangc98fd802019-10-15 16:36:36 +0900868 timespec now = evNowTime();
869 timespec finish = evAddTime(now, timeout);
Ken Chenffc224a2019-03-19 17:41:28 +0800870 LOG(INFO) << __func__ << ": " << sock << " send_vc";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900871 res = retrying_poll(sock, POLLIN | POLLOUT, &finish);
872 if (res <= 0) {
873 res = -1;
874 }
875 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900876done:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900877 fcntl(sock, F_SETFL, origflags);
Ken Chenffc224a2019-03-19 17:41:28 +0800878 LOG(INFO) << __func__ << ": " << sock << " connect_with_const timeout returning " << res;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900879 return res;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900880}
881
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900882static int retrying_poll(const int sock, const short events, const struct timespec* finish) {
883 struct timespec now, timeout;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900884
885retry:
Ken Chenffc224a2019-03-19 17:41:28 +0800886 LOG(INFO) << __func__ << ": " << sock << " retrying_poll";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900887
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900888 now = evNowTime();
889 if (evCmpTime(*finish, now) > 0)
890 timeout = evSubTime(*finish, now);
891 else
892 timeout = evConsTime(0L, 0L);
893 struct pollfd fds = {.fd = sock, .events = events};
894 int n = ppoll(&fds, 1, &timeout, /*sigmask=*/NULL);
895 if (n == 0) {
Ken Chenffc224a2019-03-19 17:41:28 +0800896 LOG(INFO) << __func__ << ": " << sock << "retrying_poll timeout";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900897 errno = ETIMEDOUT;
898 return 0;
899 }
900 if (n < 0) {
901 if (errno == EINTR) goto retry;
Ken Chenffc224a2019-03-19 17:41:28 +0800902 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll failed";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900903 return n;
904 }
905 if (fds.revents & (POLLIN | POLLOUT | POLLERR)) {
906 int error;
907 socklen_t len = sizeof(error);
908 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error) {
909 errno = error;
Ken Chenffc224a2019-03-19 17:41:28 +0800910 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll getsockopt failed";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900911 return -1;
912 }
913 }
Ken Chenffc224a2019-03-19 17:41:28 +0800914 LOG(INFO) << __func__ << ": " << sock << " retrying_poll returning " << n;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900915 return n;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900916}
917
chenbrucec51f1212019-09-12 16:59:33 +0800918static int send_dg(res_state statp, res_params* params, const uint8_t* buf, int buflen,
919 uint8_t* ans, int anssiz, int* terrno, int ns, int* v_circuit, int* gotsomewhere,
920 time_t* at, int* rcode, int* delay) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900921 *at = time(NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900922 *delay = 0;
923 const HEADER* hp = (const HEADER*) (const void*) buf;
924 HEADER* anhp = (HEADER*) (void*) ans;
925 const struct sockaddr* nsap;
926 int nsaplen;
927 struct timespec now, timeout, finish, done;
928 struct sockaddr_storage from;
929 socklen_t fromlen;
930 int resplen, n, s;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900931
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900932 nsap = get_nsaddr(statp, (size_t) ns);
933 nsaplen = get_salen(nsap);
Bernie Innocentibb330742019-10-09 00:55:53 +0900934 if (statp->nssocks[ns] == -1) {
935 statp->nssocks[ns] = socket(nsap->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
936 if (statp->nssocks[ns] < 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900937 switch (errno) {
938 case EPROTONOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900939 case EPFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900940 case EAFNOSUPPORT:
chenbruce018fdb22019-06-12 18:08:04 +0800941 PLOG(DEBUG) << __func__ << ": socket(dg): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900942 return (0);
943 default:
944 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800945 PLOG(DEBUG) << __func__ << ": socket(dg): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900946 return (-1);
947 }
948 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900949
Praveen Moongalam Thyagarajan8ab18ba2019-09-04 14:46:50 -0700950 resolv_tag_socket(statp->nssocks[ns], statp->uid, statp->pid);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900951 if (statp->_mark != MARK_UNSET) {
Bernie Innocentibb330742019-10-09 00:55:53 +0900952 if (setsockopt(statp->nssocks[ns], SOL_SOCKET, SO_MARK, &(statp->_mark),
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900953 sizeof(statp->_mark)) < 0) {
954 res_nclose(statp);
955 return -1;
956 }
957 }
chenbruceb9cce7b2019-07-15 16:14:53 +0800958 // Use a "connected" datagram socket to receive an ECONNREFUSED error
959 // on the next socket operation when the server responds with an
960 // ICMP port-unreachable error. This way we can detect the absence of
961 // a nameserver without timing out.
Bernie Innocentibb330742019-10-09 00:55:53 +0900962 if (random_bind(statp->nssocks[ns], nsap->sa_family) < 0) {
chenbruce018fdb22019-06-12 18:08:04 +0800963 dump_error("bind(dg)", nsap, nsaplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900964 res_nclose(statp);
965 return (0);
966 }
Bernie Innocentibb330742019-10-09 00:55:53 +0900967 if (connect(statp->nssocks[ns], nsap, (socklen_t)nsaplen) < 0) {
chenbruce018fdb22019-06-12 18:08:04 +0800968 dump_error("connect(dg)", nsap, nsaplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900969 res_nclose(statp);
970 return (0);
971 }
Ken Chenffc224a2019-03-19 17:41:28 +0800972 LOG(DEBUG) << __func__ << ": new DG socket";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900973 }
Bernie Innocentibb330742019-10-09 00:55:53 +0900974 s = statp->nssocks[ns];
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900975 if (send(s, (const char*) buf, (size_t) buflen, 0) != buflen) {
chenbruce018fdb22019-06-12 18:08:04 +0800976 PLOG(DEBUG) << __func__ << ": send: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900977 res_nclose(statp);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +0900978 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900979 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900980
Bernie Innocenti3952ccc2019-03-03 19:39:53 +0900981 // Wait for reply.
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900982 timeout = get_timeout(statp, params, ns);
983 now = evNowTime();
984 finish = evAddTime(now, timeout);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900985retry:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900986 n = retrying_poll(s, POLLIN, &finish);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900987
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900988 if (n == 0) {
989 *rcode = RCODE_TIMEOUT;
Ken Chenffc224a2019-03-19 17:41:28 +0800990 LOG(DEBUG) << __func__ << ": timeout";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900991 *gotsomewhere = 1;
Bernie Innocenti3952ccc2019-03-03 19:39:53 +0900992 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900993 }
994 if (n < 0) {
chenbruce018fdb22019-06-12 18:08:04 +0800995 PLOG(DEBUG) << __func__ << ": poll: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900996 res_nclose(statp);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +0900997 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900998 }
999 errno = 0;
1000 fromlen = sizeof(from);
1001 resplen = recvfrom(s, (char*) ans, (size_t) anssiz, 0, (struct sockaddr*) (void*) &from,
1002 &fromlen);
1003 if (resplen <= 0) {
chenbruce018fdb22019-06-12 18:08:04 +08001004 PLOG(DEBUG) << __func__ << ": recvfrom: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001005 res_nclose(statp);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001006 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001007 }
1008 *gotsomewhere = 1;
1009 if (resplen < HFIXEDSZ) {
1010 /*
1011 * Undersized message.
1012 */
Ken Chenffc224a2019-03-19 17:41:28 +08001013 LOG(DEBUG) << __func__ << ": undersized: " << resplen;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001014 *terrno = EMSGSIZE;
1015 res_nclose(statp);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001016 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001017 }
1018 if (hp->id != anhp->id) {
1019 /*
1020 * response from old query, ignore it.
1021 * XXX - potential security hazard could
1022 * be detected here.
1023 */
Ken Chenffc224a2019-03-19 17:41:28 +08001024 LOG(DEBUG) << __func__ << ": old answer:";
chenbrucedd210722019-03-06 13:52:43 +08001025 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001026 goto retry;
1027 }
chenbruce018fdb22019-06-12 18:08:04 +08001028 if (!res_ourserver_p(statp, (struct sockaddr*)(void*)&from)) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001029 /*
1030 * response from wrong server? ignore it.
1031 * XXX - potential security hazard could
1032 * be detected here.
1033 */
Ken Chenffc224a2019-03-19 17:41:28 +08001034 LOG(DEBUG) << __func__ << ": not our server:";
chenbrucedd210722019-03-06 13:52:43 +08001035 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001036 goto retry;
1037 }
chenbruced8cbb9b2019-06-20 18:25:28 +08001038 if (anhp->rcode == FORMERR && (statp->netcontext_flags & NET_CONTEXT_FLAG_USE_EDNS)) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001039 /*
1040 * Do not retry if the server do not understand EDNS0.
1041 * The case has to be captured here, as FORMERR packet do not
1042 * carry query section, hence res_queriesmatch() returns 0.
1043 */
Ken Chenffc224a2019-03-19 17:41:28 +08001044 LOG(DEBUG) << __func__ << ": server rejected query with EDNS0:";
chenbrucedd210722019-03-06 13:52:43 +08001045 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001046 /* record the error */
1047 statp->_flags |= RES_F_EDNS0ERR;
1048 res_nclose(statp);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001049 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001050 }
chenbruce018fdb22019-06-12 18:08:04 +08001051 if (!res_queriesmatch(buf, buf + buflen, ans, ans + anssiz)) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001052 /*
1053 * response contains wrong query? ignore it.
1054 * XXX - potential security hazard could
1055 * be detected here.
1056 */
Ken Chenffc224a2019-03-19 17:41:28 +08001057 LOG(DEBUG) << __func__ << ": wrong query name:";
chenbrucedd210722019-03-06 13:52:43 +08001058 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001059 goto retry;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001060 }
1061 done = evNowTime();
1062 *delay = _res_stats_calculate_rtt(&done, &now);
1063 if (anhp->rcode == SERVFAIL || anhp->rcode == NOTIMP || anhp->rcode == REFUSED) {
Ken Chenffc224a2019-03-19 17:41:28 +08001064 LOG(DEBUG) << __func__ << ": server rejected query:";
chenbrucedd210722019-03-06 13:52:43 +08001065 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001066 res_nclose(statp);
chenbrucedd210722019-03-06 13:52:43 +08001067 *rcode = anhp->rcode;
1068 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001069 }
chenbruce018fdb22019-06-12 18:08:04 +08001070 if (anhp->tc) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001071 /*
1072 * To get the rest of answer,
1073 * use TCP with same server.
1074 */
Ken Chenffc224a2019-03-19 17:41:28 +08001075 LOG(DEBUG) << __func__ << ": truncated answer";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001076 *v_circuit = 1;
1077 res_nclose(statp);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001078 return 1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001079 }
1080 /*
1081 * All is well, or the error is fatal. Signal that the
1082 * next nameserver ought not be tried.
1083 */
1084 if (resplen > 0) {
1085 *rcode = anhp->rcode;
1086 }
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001087 return resplen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001088}
1089
chenbruce018fdb22019-06-12 18:08:04 +08001090static void dump_error(const char* str, const struct sockaddr* address, int alen) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001091 char hbuf[NI_MAXHOST];
1092 char sbuf[NI_MAXSERV];
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001093 constexpr int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
Luke Huangc98fd802019-10-15 16:36:36 +09001094 const int err = errno;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001095
chenbruce018fdb22019-06-12 18:08:04 +08001096 if (!WOULD_LOG(DEBUG)) return;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001097
chenbruce018fdb22019-06-12 18:08:04 +08001098 if (getnameinfo(address, (socklen_t)alen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf), niflags)) {
1099 strncpy(hbuf, "?", sizeof(hbuf) - 1);
1100 hbuf[sizeof(hbuf) - 1] = '\0';
1101 strncpy(sbuf, "?", sizeof(sbuf) - 1);
1102 sbuf[sizeof(sbuf) - 1] = '\0';
Elliott Hughes3b8f5902019-03-08 12:02:55 -08001103 }
Luke Huangc98fd802019-10-15 16:36:36 +09001104 errno = err;
chenbruce018fdb22019-06-12 18:08:04 +08001105 PLOG(DEBUG) << __func__ << ": " << str << " ([" << hbuf << "]." << sbuf << "): ";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001106}
1107
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001108static int sock_eq(struct sockaddr* a, struct sockaddr* b) {
1109 struct sockaddr_in *a4, *b4;
1110 struct sockaddr_in6 *a6, *b6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001111
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001112 if (a->sa_family != b->sa_family) return 0;
1113 switch (a->sa_family) {
1114 case AF_INET:
1115 a4 = (struct sockaddr_in*) (void*) a;
1116 b4 = (struct sockaddr_in*) (void*) b;
1117 return a4->sin_port == b4->sin_port && a4->sin_addr.s_addr == b4->sin_addr.s_addr;
1118 case AF_INET6:
1119 a6 = (struct sockaddr_in6*) (void*) a;
1120 b6 = (struct sockaddr_in6*) (void*) b;
1121 return a6->sin6_port == b6->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001122#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001123 a6->sin6_scope_id == b6->sin6_scope_id &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001124#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001125 IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
1126 default:
1127 return 0;
1128 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001129}
Mike Yub601ff72018-11-01 20:07:00 +08001130
lifr6b83a6f2019-07-26 03:17:43 +08001131PrivateDnsModes convertEnumType(PrivateDnsMode privateDnsmode) {
1132 switch (privateDnsmode) {
1133 case PrivateDnsMode::OFF:
1134 return PrivateDnsModes::PDM_OFF;
1135 case PrivateDnsMode::OPPORTUNISTIC:
1136 return PrivateDnsModes::PDM_OPPORTUNISTIC;
1137 case PrivateDnsMode::STRICT:
1138 return PrivateDnsModes::PDM_STRICT;
1139 }
1140 return PrivateDnsModes::PDM_UNKNOWN;
1141}
1142
Luke Huangd7aa7b42018-11-21 20:37:50 +08001143static int res_tls_send(res_state statp, const Slice query, const Slice answer, int* rcode,
Mike Yubfb1b342018-11-06 15:42:36 +08001144 bool* fallback) {
1145 int resplen = 0;
Mike Yub601ff72018-11-01 20:07:00 +08001146 const unsigned netId = statp->netid;
Mike Yub601ff72018-11-01 20:07:00 +08001147
Mike Yubfb1b342018-11-06 15:42:36 +08001148 PrivateDnsStatus privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
lifr6b83a6f2019-07-26 03:17:43 +08001149 statp->event->set_private_dns_modes(convertEnumType(privateDnsStatus.mode));
Mike Yubfb1b342018-11-06 15:42:36 +08001150
1151 if (privateDnsStatus.mode == PrivateDnsMode::OFF) {
1152 *fallback = true;
1153 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001154 }
1155
Mike Yu3e829062019-08-07 14:01:14 +08001156 if (privateDnsStatus.validatedServers().empty()) {
Mike Yub601ff72018-11-01 20:07:00 +08001157 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
Mike Yubfb1b342018-11-06 15:42:36 +08001158 *fallback = true;
1159 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001160 } else {
1161 // Sleep and iterate some small number of times checking for the
1162 // arrival of resolved and validated server IP addresses, instead
1163 // of returning an immediate error.
Mike Yu4f3747b2018-12-02 17:54:29 +09001164 // This is needed because as soon as a network becomes the default network, apps will
1165 // send DNS queries on that network. If no servers have yet validated, and we do not
1166 // block those queries, they would immediately fail, causing application-visible errors.
1167 // Note that this can happen even before the network validates, since an unvalidated
1168 // network can become the default network if no validated networks are available.
1169 //
1170 // TODO: see if there is a better way to address this problem, such as buffering the
1171 // queries in a queue or only blocking queries for the first few seconds after a default
1172 // network change.
Mike Yubfb1b342018-11-06 15:42:36 +08001173 for (int i = 0; i < 42; i++) {
1174 std::this_thread::sleep_for(std::chrono::milliseconds(100));
Mike Yu3e829062019-08-07 14:01:14 +08001175 // Calling getStatus() to merely check if there's any validated server seems
1176 // wasteful. Consider adding a new method in PrivateDnsConfiguration for speed ups.
1177 if (!gPrivateDnsConfiguration.getStatus(netId).validatedServers().empty()) {
Mike Yubfb1b342018-11-06 15:42:36 +08001178 privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
1179 break;
1180 }
1181 }
Mike Yu3e829062019-08-07 14:01:14 +08001182 if (privateDnsStatus.validatedServers().empty()) {
Mike Yubfb1b342018-11-06 15:42:36 +08001183 return -1;
1184 }
Mike Yub601ff72018-11-01 20:07:00 +08001185 }
1186 }
1187
chenbruceacb832c2019-02-20 19:45:50 +08001188 LOG(INFO) << __func__ << ": performing query over TLS";
Mike Yub601ff72018-11-01 20:07:00 +08001189
Mike Yu3e829062019-08-07 14:01:14 +08001190 const auto response = sDnsTlsDispatcher.query(privateDnsStatus.validatedServers(), statp, query,
Mike Yubfb1b342018-11-06 15:42:36 +08001191 answer, &resplen);
Mike Yub601ff72018-11-01 20:07:00 +08001192
chenbruceacb832c2019-02-20 19:45:50 +08001193 LOG(INFO) << __func__ << ": TLS query result: " << static_cast<int>(response);
Mike Yub601ff72018-11-01 20:07:00 +08001194
1195 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
1196 // In opportunistic mode, handle falling back to cleartext in some
1197 // cases (DNS shouldn't fail if a validated opportunistic mode server
1198 // becomes unreachable for some reason).
1199 switch (response) {
Mike Yubfb1b342018-11-06 15:42:36 +08001200 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001201 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001202 return resplen;
Mike Yub601ff72018-11-01 20:07:00 +08001203 case DnsTlsTransport::Response::network_error:
Mike Yubfb1b342018-11-06 15:42:36 +08001204 // No need to set the error timeout here since it will fallback to UDP.
Mike Yub601ff72018-11-01 20:07:00 +08001205 case DnsTlsTransport::Response::internal_error:
1206 // Note: this will cause cleartext queries to be emitted, with
1207 // all of the EDNS0 goodness enabled. Fingers crossed. :-/
Mike Yubfb1b342018-11-06 15:42:36 +08001208 *fallback = true;
1209 [[fallthrough]];
Mike Yub601ff72018-11-01 20:07:00 +08001210 default:
Mike Yubfb1b342018-11-06 15:42:36 +08001211 return -1;
1212 }
1213 } else {
1214 // Strict mode
1215 switch (response) {
1216 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001217 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001218 return resplen;
1219 case DnsTlsTransport::Response::network_error:
1220 // This case happens when the query stored in DnsTlsTransport is expired since
1221 // either 1) the query has been tried for 3 times but no response or 2) fail to
1222 // establish the connection with the server.
Luke Huangd7aa7b42018-11-21 20:37:50 +08001223 *rcode = RCODE_TIMEOUT;
Mike Yubfb1b342018-11-06 15:42:36 +08001224 [[fallthrough]];
1225 default:
1226 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001227 }
1228 }
Mike Yub601ff72018-11-01 20:07:00 +08001229}
Luke Huang4973a0d2018-11-19 20:17:26 +08001230
Luke Huangba7bef92018-12-26 16:53:03 +08001231int resolv_res_nsend(const android_net_context* netContext, const uint8_t* msg, int msgLen,
lifr94981782019-05-17 21:15:19 +08001232 uint8_t* ans, int ansLen, int* rcode, uint32_t flags,
1233 NetworkDnsEventReported* event) {
1234 assert(event != nullptr);
Bernie Innocenti08487112019-10-11 21:14:13 +09001235 ResState res;
1236 res_init(&res, netContext, event);
1237 _resolv_populate_res_for_net(&res);
Luke Huang4973a0d2018-11-19 20:17:26 +08001238 *rcode = NOERROR;
Bernie Innocenti08487112019-10-11 21:14:13 +09001239 return res_nsend(&res, msg, msgLen, ans, ansLen, rcode, flags);
Bernie Innocentiec4219b2019-01-30 11:16:36 +09001240}