blob: 012e680fe97b155a8d739bd76bd363c5a123bab3 [file] [log] [blame]
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001/* $NetBSD: res_send.c,v 1.9 2006/01/24 17:41:25 christos Exp $ */
2
3/*
4 * Copyright (c) 1985, 1989, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. All advertising materials mentioning features or use of this software
16 * must display the following acknowledgement:
17 * This product includes software developed by the University of
18 * California, Berkeley and its contributors.
19 * 4. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 */
35
36/*
37 * Portions Copyright (c) 1993 by Digital Equipment Corporation.
38 *
39 * Permission to use, copy, modify, and distribute this software for any
40 * purpose with or without fee is hereby granted, provided that the above
41 * copyright notice and this permission notice appear in all copies, and that
42 * the name of Digital Equipment Corporation not be used in advertising or
43 * publicity pertaining to distribution of the document or software without
44 * specific, written prior permission.
45 *
46 * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
47 * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
48 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
49 * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
50 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
51 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
52 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
53 * SOFTWARE.
54 */
55
56/*
57 * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
58 * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
59 *
60 * Permission to use, copy, modify, and distribute this software for any
61 * purpose with or without fee is hereby granted, provided that the above
62 * copyright notice and this permission notice appear in all copies.
63 *
64 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
65 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
66 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR
67 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
68 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
69 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
70 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
71 */
72
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090073/*
74 * Send query to name server and wait for reply.
75 */
76
Ken Chen5471dca2019-04-15 15:25:35 +080077#define LOG_TAG "resolv"
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +090078
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090079#include <sys/param.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090080#include <sys/socket.h>
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090081#include <sys/time.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090082#include <sys/uio.h>
83
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090084#include <arpa/inet.h>
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090085#include <arpa/nameser.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090086
87#include <errno.h>
88#include <fcntl.h>
89#include <netdb.h>
90#include <poll.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090091#include <signal.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090092#include <stdlib.h>
93#include <string.h>
94#include <time.h>
95#include <unistd.h>
96
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +090097#include <android-base/logging.h>
Bernie Innocenti758005f2019-02-19 18:08:36 +090098#include <android/multinetwork.h> // ResNsendFlags
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090099
Mike Yub601ff72018-11-01 20:07:00 +0800100#include <netdutils/Slice.h>
lifr94981782019-05-17 21:15:19 +0800101#include <netdutils/Stopwatch.h>
Bernie Innocentiec4219b2019-01-30 11:16:36 +0900102#include "DnsTlsDispatcher.h"
103#include "DnsTlsTransport.h"
104#include "PrivateDnsConfiguration.h"
Bernie Innocentiac18b122018-10-01 23:10:18 +0900105#include "netd_resolv/resolv.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900106#include "private/android_filesystem_config.h"
Bernie Innocenti10a90282020-01-23 23:28:00 +0900107
108#include "res_comp.h"
Mike Yu34433c62019-08-20 20:17:36 +0800109#include "res_debug.h"
Bernie Innocenti08487112019-10-11 21:14:13 +0900110#include "res_init.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900111#include "resolv_cache.h"
Ken Chen99c0b322019-11-20 14:24:09 +0800112#include "stats.h"
lifr94981782019-05-17 21:15:19 +0800113#include "stats.pb.h"
Mike Yu021c3e12019-10-08 17:29:34 +0800114#include "util.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900115
Mike Yub601ff72018-11-01 20:07:00 +0800116// TODO: use the namespace something like android::netd_resolv for libnetd_resolv
chenbruce99cbfd82019-09-05 15:08:13 +0800117using android::net::CacheStatus;
118using android::net::DnsQueryEvent;
119using android::net::DnsTlsDispatcher;
120using android::net::DnsTlsTransport;
121using android::net::gPrivateDnsConfiguration;
122using android::net::IpVersion;
123using android::net::IV_IPV4;
124using android::net::IV_IPV6;
125using android::net::IV_UNKNOWN;
lifr94981782019-05-17 21:15:19 +0800126using android::net::NetworkDnsEventReported;
chenbruce99cbfd82019-09-05 15:08:13 +0800127using android::net::NS_T_INVALID;
128using android::net::NsRcode;
129using android::net::NsType;
130using android::net::PrivateDnsMode;
131using android::net::PrivateDnsModes;
132using android::net::PrivateDnsStatus;
133using android::net::PROTO_TCP;
134using android::net::PROTO_UDP;
Mike Yue655b1d2019-08-28 17:49:59 +0800135using android::netdutils::IPSockAddr;
Bernie Innocentiec4219b2019-01-30 11:16:36 +0900136using android::netdutils::Slice;
lifr94981782019-05-17 21:15:19 +0800137using android::netdutils::Stopwatch;
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900138
Mike Yub601ff72018-11-01 20:07:00 +0800139static DnsTlsDispatcher sDnsTlsDispatcher;
140
Mike Yue48f7b52020-02-10 14:55:06 +0800141static int send_vc(res_state statp, res_params* params, const uint8_t* buf, int buflen,
142 uint8_t* ans, int anssiz, int* terrno, size_t ns, time_t* at, int* rcode,
143 int* delay);
144static int send_dg(res_state statp, res_params* params, const uint8_t* buf, int buflen,
145 uint8_t* ans, int anssiz, int* terrno, size_t ns, int* v_circuit,
146 int* gotsomewhere, time_t* at, int* rcode, int* delay);
147
chenbruce018fdb22019-06-12 18:08:04 +0800148static void dump_error(const char*, const struct sockaddr*, int);
chenbruceacb832c2019-02-20 19:45:50 +0800149
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900150static int sock_eq(struct sockaddr*, struct sockaddr*);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900151static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
152 const struct timespec timeout);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900153static int retrying_poll(const int sock, short events, const struct timespec* finish);
Luke Huangd7aa7b42018-11-21 20:37:50 +0800154static int res_tls_send(res_state, const Slice query, const Slice answer, int* rcode,
Mike Yubfb1b342018-11-06 15:42:36 +0800155 bool* fallback);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900156
lifr94981782019-05-17 21:15:19 +0800157NsType getQueryType(const uint8_t* msg, size_t msgLen) {
158 ns_msg handle;
159 ns_rr rr;
160 if (ns_initparse((const uint8_t*)msg, msgLen, &handle) < 0 ||
161 ns_parserr(&handle, ns_s_qd, 0, &rr) < 0) {
162 return NS_T_INVALID;
163 }
164 return static_cast<NsType>(ns_rr_type(rr));
165}
166
167IpVersion ipFamilyToIPVersion(const int ipFamily) {
168 switch (ipFamily) {
169 case AF_INET:
170 return IV_IPV4;
171 case AF_INET6:
172 return IV_IPV6;
173 default:
174 return IV_UNKNOWN;
175 }
176}
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900177
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900178// BEGIN: Code copied from ISC eventlib
179// TODO: move away from this code
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900180#define BILLION 1000000000
181
182static struct timespec evConsTime(time_t sec, long nsec) {
183 struct timespec x;
184
185 x.tv_sec = sec;
186 x.tv_nsec = nsec;
187 return (x);
188}
189
190static struct timespec evAddTime(struct timespec addend1, struct timespec addend2) {
191 struct timespec x;
192
193 x.tv_sec = addend1.tv_sec + addend2.tv_sec;
194 x.tv_nsec = addend1.tv_nsec + addend2.tv_nsec;
195 if (x.tv_nsec >= BILLION) {
196 x.tv_sec++;
197 x.tv_nsec -= BILLION;
198 }
199 return (x);
200}
201
202static struct timespec evSubTime(struct timespec minuend, struct timespec subtrahend) {
203 struct timespec x;
204
205 x.tv_sec = minuend.tv_sec - subtrahend.tv_sec;
206 if (minuend.tv_nsec >= subtrahend.tv_nsec)
207 x.tv_nsec = minuend.tv_nsec - subtrahend.tv_nsec;
208 else {
209 x.tv_nsec = BILLION - subtrahend.tv_nsec + minuend.tv_nsec;
210 x.tv_sec--;
211 }
212 return (x);
213}
214
215static int evCmpTime(struct timespec a, struct timespec b) {
216#define SGN(x) ((x) < 0 ? (-1) : (x) > 0 ? (1) : (0));
217 time_t s = a.tv_sec - b.tv_sec;
218 long n;
219
220 if (s != 0) return SGN(s);
221
222 n = a.tv_nsec - b.tv_nsec;
223 return SGN(n);
224}
225
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900226static struct timespec evNowTime(void) {
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900227 struct timespec tsnow;
Bernie Innocentic1834822018-08-31 16:11:41 +0900228 clock_gettime(CLOCK_REALTIME, &tsnow);
229 return tsnow;
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900230}
231
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900232// END: Code copied from ISC eventlib
233
lifr94981782019-05-17 21:15:19 +0800234/* BIONIC-BEGIN: implement source port randomization */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900235static int random_bind(int s, int family) {
nuccachenb980f2f2018-10-23 17:10:58 +0800236 sockaddr_union u;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900237 int j;
238 socklen_t slen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900239
240 /* clear all, this also sets the IP4/6 address to 'any' */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900241 memset(&u, 0, sizeof u);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900242
243 switch (family) {
244 case AF_INET:
245 u.sin.sin_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900246 slen = sizeof u.sin;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900247 break;
248 case AF_INET6:
249 u.sin6.sin6_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900250 slen = sizeof u.sin6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900251 break;
252 default:
253 errno = EPROTO;
254 return -1;
255 }
256
257 /* first try to bind to a random source port a few times */
258 for (j = 0; j < 10; j++) {
259 /* find a random port between 1025 .. 65534 */
Luke Huangdda920f2019-02-13 14:05:02 +0800260 int port = 1025 + (arc4random_uniform(65535 - 1025));
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900261 if (family == AF_INET)
262 u.sin.sin_port = htons(port);
263 else
264 u.sin6.sin6_port = htons(port);
265
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900266 if (!bind(s, &u.sa, slen)) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900267 }
268
Bernie Innocenti9c575932018-09-07 21:10:25 +0900269 // nothing after 10 attempts, our network table is probably busy
270 // let the system decide which port is best
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900271 if (family == AF_INET)
272 u.sin.sin_port = 0;
273 else
274 u.sin6.sin6_port = 0;
275
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900276 return bind(s, &u.sa, slen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900277}
278/* BIONIC-END */
279
Luke Huang70931aa2019-01-31 11:57:41 +0800280// Disables all nameservers other than selectedServer
281static void res_set_usable_server(int selectedServer, int nscount, bool usable_servers[]) {
282 int usableIndex = 0;
283 for (int ns = 0; ns < nscount; ns++) {
284 if (usable_servers[ns]) ++usableIndex;
285 if (usableIndex != selectedServer) usable_servers[ns] = false;
286 }
287}
288
Bernie Innocentia6f40ca2019-10-09 15:22:41 +0900289// Looks up the nameserver address in res.nsaddrs[], returns true if found, otherwise false.
290static bool res_ourserver_p(res_state statp, const sockaddr* sa) {
Bernie Innocenti2e8540b2018-09-26 11:52:04 +0900291 const sockaddr_in *inp, *srv;
292 const sockaddr_in6 *in6p, *srv6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900293
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900294 switch (sa->sa_family) {
295 case AF_INET:
296 inp = (const struct sockaddr_in*) (const void*) sa;
Mike Yue48f7b52020-02-10 14:55:06 +0800297 for (const IPSockAddr& ipsa : statp->nsaddrs) {
298 sockaddr_storage ss = ipsa;
299 srv = reinterpret_cast<sockaddr_in*>(&ss);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900300 if (srv->sin_family == inp->sin_family && srv->sin_port == inp->sin_port &&
301 (srv->sin_addr.s_addr == INADDR_ANY ||
302 srv->sin_addr.s_addr == inp->sin_addr.s_addr))
Bernie Innocentia6f40ca2019-10-09 15:22:41 +0900303 return true;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900304 }
305 break;
306 case AF_INET6:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900307 in6p = (const struct sockaddr_in6*) (const void*) sa;
Mike Yue48f7b52020-02-10 14:55:06 +0800308 for (const IPSockAddr& ipsa : statp->nsaddrs) {
309 sockaddr_storage ss = ipsa;
310 srv6 = reinterpret_cast<sockaddr_in6*>(&ss);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900311 if (srv6->sin6_family == in6p->sin6_family && srv6->sin6_port == in6p->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900312#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900313 (srv6->sin6_scope_id == 0 || srv6->sin6_scope_id == in6p->sin6_scope_id) &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900314#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900315 (IN6_IS_ADDR_UNSPECIFIED(&srv6->sin6_addr) ||
316 IN6_ARE_ADDR_EQUAL(&srv6->sin6_addr, &in6p->sin6_addr)))
Bernie Innocentia6f40ca2019-10-09 15:22:41 +0900317 return true;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900318 }
319 break;
320 default:
321 break;
322 }
Bernie Innocentia6f40ca2019-10-09 15:22:41 +0900323 return false;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900324}
325
326/* int
Bernie Innocenti9c575932018-09-07 21:10:25 +0900327 * res_nameinquery(name, type, cl, buf, eom)
328 * look for (name, type, cl) in the query section of packet (buf, eom)
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900329 * requires:
330 * buf + HFIXEDSZ <= eom
331 * returns:
332 * -1 : format error
333 * 0 : not found
334 * >0 : found
335 * author:
336 * paul vixie, 29may94
337 */
chenbrucec51f1212019-09-12 16:59:33 +0800338int res_nameinquery(const char* name, int type, int cl, const uint8_t* buf, const uint8_t* eom) {
339 const uint8_t* cp = buf + HFIXEDSZ;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900340 int qdcount = ntohs(((const HEADER*) (const void*) buf)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900341
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900342 while (qdcount-- > 0) {
343 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900344 int n = dn_expand(buf, eom, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900345 if (n < 0) return (-1);
346 cp += n;
347 if (cp + 2 * INT16SZ > eom) return (-1);
chenbruce0d470422019-03-28 18:44:37 +0800348 int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900349 cp += INT16SZ;
chenbruce0d470422019-03-28 18:44:37 +0800350 int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900351 cp += INT16SZ;
Bernie Innocenti9c575932018-09-07 21:10:25 +0900352 if (ttype == type && tclass == cl && ns_samename(tname, name) == 1) return (1);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900353 }
354 return (0);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900355}
356
357/* int
358 * res_queriesmatch(buf1, eom1, buf2, eom2)
359 * is there a 1:1 mapping of (name,type,class)
360 * in (buf1,eom1) and (buf2,eom2)?
361 * returns:
362 * -1 : format error
363 * 0 : not a 1:1 mapping
364 * >0 : is a 1:1 mapping
365 * author:
366 * paul vixie, 29may94
367 */
chenbrucec51f1212019-09-12 16:59:33 +0800368int res_queriesmatch(const uint8_t* buf1, const uint8_t* eom1, const uint8_t* buf2,
369 const uint8_t* eom2) {
370 const uint8_t* cp = buf1 + HFIXEDSZ;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900371 int qdcount = ntohs(((const HEADER*) (const void*) buf1)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900372
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900373 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2) return (-1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900374
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900375 /*
376 * Only header section present in replies to
377 * dynamic update packets.
378 */
379 if ((((const HEADER*) (const void*) buf1)->opcode == ns_o_update) &&
380 (((const HEADER*) (const void*) buf2)->opcode == ns_o_update))
381 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900382
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900383 if (qdcount != ntohs(((const HEADER*) (const void*) buf2)->qdcount)) return (0);
384 while (qdcount-- > 0) {
385 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900386 int n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900387 if (n < 0) return (-1);
388 cp += n;
389 if (cp + 2 * INT16SZ > eom1) return (-1);
chenbruce0d470422019-03-28 18:44:37 +0800390 int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900391 cp += INT16SZ;
chenbruce0d470422019-03-28 18:44:37 +0800392 int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900393 cp += INT16SZ;
394 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2)) return (0);
395 }
396 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900397}
398
lifr94981782019-05-17 21:15:19 +0800399static DnsQueryEvent* addDnsQueryEvent(NetworkDnsEventReported* event) {
400 return event->mutable_dns_query_events()->add_dns_query_event();
401}
402
chenbrucec51f1212019-09-12 16:59:33 +0800403int 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 +0800404 uint32_t flags) {
Luke Huang43cc1b12019-10-15 19:06:42 +0900405 LOG(DEBUG) << __func__;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900406
Luke Huang43cc1b12019-10-15 19:06:42 +0900407 // Should not happen
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900408 if (anssiz < HFIXEDSZ) {
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800409 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900410 errno = EINVAL;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800411 return -EINVAL;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900412 }
chenbrucedd210722019-03-06 13:52:43 +0800413 res_pquery(buf, buflen);
chenbruceacb832c2019-02-20 19:45:50 +0800414
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900415 int anslen = 0;
lifrd4d9fbb2019-07-31 20:18:35 +0800416 Stopwatch cacheStopwatch;
Luke Huang43cc1b12019-10-15 19:06:42 +0900417 ResolvCacheStatus cache_status =
418 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));
lifre02d01c2019-12-31 17:24:57 +0800426 dnsQueryEvent->set_type(getQueryType(buf, buflen));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900427 return anslen;
428 } else if (cache_status != RESOLV_CACHE_UNSUPPORTED) {
429 // had a cache miss for a known network, so populate the thread private
430 // data so the normal resolve path can do its thing
Mike Yu021c3e12019-10-08 17:29:34 +0800431 resolv_populate_res_for_net(statp);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900432 }
Mike Yuecc52822020-02-14 14:36:46 +0800433 if (statp->nameserverCount() == 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900434 // We have no nameservers configured, so there's no point trying.
435 // Tell the cache the query failed, or any retries and anyone else asking the same
436 // question will block for PENDING_REQUEST_TIMEOUT seconds instead of failing fast.
Luke Huangba7bef92018-12-26 16:53:03 +0800437 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800438
439 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900440 errno = ESRCH;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800441 return -ESRCH;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900442 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900443
Luke Huang272cb192019-10-15 16:52:28 +0900444 // DoT
445 if (!(statp->netcontext_flags & NET_CONTEXT_FLAG_USE_LOCAL_NAMESERVERS)) {
446 bool fallback = false;
Luke Huang43cc1b12019-10-15 19:06:42 +0900447 int resplen = res_tls_send(statp, Slice(const_cast<uint8_t*>(buf), buflen),
448 Slice(ans, anssiz), rcode, &fallback);
Luke Huang272cb192019-10-15 16:52:28 +0900449 if (resplen > 0) {
450 LOG(DEBUG) << __func__ << ": got answer from DoT";
451 res_pquery(ans, resplen);
452 if (cache_status == RESOLV_CACHE_NOTFOUND) {
453 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
454 }
455 return resplen;
456 }
457 if (!fallback) {
458 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huang43cc1b12019-10-15 19:06:42 +0900459 return -ETIMEDOUT;
Luke Huang272cb192019-10-15 16:52:28 +0900460 }
461 }
462
Mike Yuc573a3d2020-02-07 20:15:15 +0800463 res_stats stats[MAXNS]{};
Bernie Innocenti758005f2019-02-19 18:08:36 +0900464 res_params params;
Mike Yuc573a3d2020-02-07 20:15:15 +0800465 int revision_id = resolv_cache_get_resolver_stats(statp->netid, &params, stats, statp->nsaddrs);
lifra1b37f12019-02-13 17:33:57 +0800466 if (revision_id < 0) {
467 // TODO: Remove errno once callers stop using it
468 errno = ESRCH;
469 return -ESRCH;
470 }
waynema0161acd2019-02-18 17:47:59 +0800471 bool usable_servers[MAXNS];
Luke Huang70931aa2019-01-31 11:57:41 +0800472 int usableServersCount = android_net_res_stats_get_usable_servers(
Mike Yuecc52822020-02-14 14:36:46 +0800473 &params, stats, statp->nameserverCount(), usable_servers);
Luke Huang70931aa2019-01-31 11:57:41 +0800474
475 if ((flags & ANDROID_RESOLV_NO_RETRY) && usableServersCount > 1) {
476 auto hp = reinterpret_cast<const HEADER*>(buf);
477
478 // Select a random server based on the query id
479 int selectedServer = (hp->id % usableServersCount) + 1;
Mike Yuecc52822020-02-14 14:36:46 +0800480 res_set_usable_server(selectedServer, statp->nameserverCount(), usable_servers);
Luke Huang70931aa2019-01-31 11:57:41 +0800481 }
waynema0161acd2019-02-18 17:47:59 +0800482
Luke Huang43cc1b12019-10-15 19:06:42 +0900483 // Send request, RETRY times, or until successful.
waynemaa74195e2019-01-18 14:02:31 +0800484 int retryTimes = (flags & ANDROID_RESOLV_NO_RETRY) ? 1 : params.retry_count;
Luke Huang43cc1b12019-10-15 19:06:42 +0900485 int useTcp = buflen > PACKETSZ;
486 int gotsomewhere = 0;
487 int terrno = ETIMEDOUT;
Luke Huangba7bef92018-12-26 16:53:03 +0800488
489 for (int attempt = 0; attempt < retryTimes; ++attempt) {
Mike Yue48f7b52020-02-10 14:55:06 +0800490 for (size_t ns = 0; ns < statp->nsaddrs.size(); ++ns) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900491 if (!usable_servers[ns]) continue;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900492
Luke Huang43cc1b12019-10-15 19:06:42 +0900493 *rcode = RCODE_INTERNAL_ERROR;
494
495 // Get server addr
Mike Yue48f7b52020-02-10 14:55:06 +0800496 const IPSockAddr& serverSockAddr = statp->nsaddrs[ns];
497 LOG(DEBUG) << __func__ << ": Querying server (# " << ns + 1
498 << ") address = " << serverSockAddr.toString();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900499
Luke Huang43cc1b12019-10-15 19:06:42 +0900500 ::android::net::Protocol query_proto = useTcp ? PROTO_TCP : PROTO_UDP;
501 time_t now = 0;
502 int delay = 0;
503 bool fallbackTCP = false;
504 const bool shouldRecordStats = (attempt == 0);
505 int resplen;
lifrd4d9fbb2019-07-31 20:18:35 +0800506 Stopwatch queryStopwatch;
lifr128183a2020-01-08 18:04:50 +0800507 int retry_count_for_event = 0;
Luke Huang43cc1b12019-10-15 19:06:42 +0900508 if (useTcp) {
509 // TCP; at most one attempt per server.
Luke Huangba7bef92018-12-26 16:53:03 +0800510 attempt = retryTimes;
Luke Huang43cc1b12019-10-15 19:06:42 +0900511 resplen = send_vc(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &now,
512 rcode, &delay);
Ken Chen99344882020-01-01 14:59:38 +0800513
514 if (buflen <= PACKETSZ && resplen <= 0 &&
515 statp->tc_mode == aidl::android::net::IDnsResolver::TC_MODE_UDP_TCP) {
516 // reset to UDP for next query on next DNS server if resolver is currently doing
517 // TCP fallback retry and current server does not support TCP connectin
518 useTcp = false;
519 }
520 LOG(INFO) << __func__ << ": used send_vc " << resplen;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900521 } else {
Luke Huang43cc1b12019-10-15 19:06:42 +0900522 // UDP
523 resplen = send_dg(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &useTcp,
524 &gotsomewhere, &now, rcode, &delay);
525 fallbackTCP = useTcp ? true : false;
lifr128183a2020-01-08 18:04:50 +0800526 retry_count_for_event = attempt;
Ken Chen99344882020-01-01 14:59:38 +0800527 LOG(INFO) << __func__ << ": used send_dg " << resplen;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900528 }
Luke Huang43cc1b12019-10-15 19:06:42 +0900529
530 DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
531 dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
532 dnsQueryEvent->set_latency_micros(saturate_cast<int32_t>(queryStopwatch.timeTakenUs()));
533 dnsQueryEvent->set_dns_server_index(ns);
Mike Yue48f7b52020-02-10 14:55:06 +0800534 dnsQueryEvent->set_ip_version(ipFamilyToIPVersion(serverSockAddr.family()));
lifr128183a2020-01-08 18:04:50 +0800535 dnsQueryEvent->set_retry_times(retry_count_for_event);
Luke Huang43cc1b12019-10-15 19:06:42 +0900536 dnsQueryEvent->set_rcode(static_cast<NsRcode>(*rcode));
537 dnsQueryEvent->set_protocol(query_proto);
538 dnsQueryEvent->set_type(getQueryType(buf, buflen));
539
540 // Only record stats the first time we try a query. This ensures that
541 // queries that deterministically fail (e.g., a name that always returns
542 // SERVFAIL or times out) do not unduly affect the stats.
543 if (shouldRecordStats) {
544 res_sample sample;
Mike Yu6407ae42020-02-10 21:11:05 +0800545 res_stats_set_sample(&sample, now, *rcode, delay);
Mike Yue48f7b52020-02-10 14:55:06 +0800546 resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, serverSockAddr,
547 sample, params.max_samples);
548 resolv_stats_add(statp->netid, serverSockAddr, dnsQueryEvent);
Luke Huang43cc1b12019-10-15 19:06:42 +0900549 }
550
551 if (resplen == 0) continue;
552 if (fallbackTCP) {
553 ns--;
554 continue;
555 }
556 if (resplen < 0) {
557 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800558 statp->closeSockets();
Luke Huang43cc1b12019-10-15 19:06:42 +0900559 return -terrno;
560 };
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900561
Ken Chenffc224a2019-03-19 17:41:28 +0800562 LOG(DEBUG) << __func__ << ": got answer:";
chenbrucedd210722019-03-06 13:52:43 +0800563 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900564
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900565 if (cache_status == RESOLV_CACHE_NOTFOUND) {
Mike Yud1ec2542019-06-06 17:17:53 +0800566 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900567 }
Luke Huangadb0f5b2019-11-27 15:51:48 +0800568 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900569 return (resplen);
Bernie Innocenti9c575932018-09-07 21:10:25 +0900570 } // for each ns
571 } // for each retry
Luke Huangadb0f5b2019-11-27 15:51:48 +0800572 statp->closeSockets();
Luke Huang43cc1b12019-10-15 19:06:42 +0900573 terrno = useTcp ? terrno : gotsomewhere ? ETIMEDOUT : ECONNREFUSED;
574 // TODO: Remove errno once callers stop using it
575 errno = useTcp ? terrno
576 : gotsomewhere ? ETIMEDOUT /* no answer obtained */
577 : ECONNREFUSED /* no nameservers found */;
578
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 return -terrno;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900581}
582
chenbruce99cbfd82019-09-05 15:08:13 +0800583static struct timespec get_timeout(res_state statp, const res_params* params, const int ns) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900584 int msec;
waynemaa74195e2019-01-18 14:02:31 +0800585 // Legacy algorithm which scales the timeout by nameserver number.
586 // For instance, with 4 nameservers: 5s, 2.5s, 5s, 10s
587 // This has no effect with 1 or 2 nameservers
588 msec = params->base_timeout_msec << ns;
589 if (ns > 0) {
Mike Yuecc52822020-02-14 14:36:46 +0800590 msec /= statp->nameserverCount();
waynemaa74195e2019-01-18 14:02:31 +0800591 }
592 // For safety, don't allow OEMs and experiments to configure a timeout shorter than 1s.
593 if (msec < 1000) {
594 msec = 1000; // Use at least 1000ms
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900595 }
Ken Chenffc224a2019-03-19 17:41:28 +0800596 LOG(INFO) << __func__ << ": using timeout of " << msec << " msec";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900597
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900598 struct timespec result;
599 result.tv_sec = msec / 1000;
600 result.tv_nsec = (msec % 1000) * 1000000;
601 return result;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900602}
603
chenbrucec51f1212019-09-12 16:59:33 +0800604static int send_vc(res_state statp, res_params* params, const uint8_t* buf, int buflen,
Mike Yue48f7b52020-02-10 14:55:06 +0800605 uint8_t* ans, int anssiz, int* terrno, size_t ns, time_t* at, int* rcode,
chenbrucec51f1212019-09-12 16:59:33 +0800606 int* delay) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900607 *at = time(NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900608 *delay = 0;
609 const HEADER* hp = (const HEADER*) (const void*) buf;
610 HEADER* anhp = (HEADER*) (void*) ans;
611 struct sockaddr* nsap;
612 int nsaplen;
chenbruce0d470422019-03-28 18:44:37 +0800613 int truncating, connreset, n;
chenbrucec51f1212019-09-12 16:59:33 +0800614 uint8_t* cp;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900615
Ken Chenffc224a2019-03-19 17:41:28 +0800616 LOG(INFO) << __func__ << ": using send_vc";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900617
Mike Yue48f7b52020-02-10 14:55:06 +0800618 // It should never happen, but just in case.
619 if (ns >= statp->nsaddrs.size()) {
620 LOG(ERROR) << __func__ << ": Out-of-bound indexing: " << ns;
621 return -1;
622 }
623
624 sockaddr_storage ss = statp->nsaddrs[ns];
625 nsap = reinterpret_cast<sockaddr*>(&ss);
Mike Yu021c3e12019-10-08 17:29:34 +0800626 nsaplen = sockaddrSize(nsap);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900627
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900628 connreset = 0;
629same_ns:
630 truncating = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900631
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900632 struct timespec now = evNowTime();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900633
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900634 /* Are we still talking to whom we want to talk to? */
Luke Huangadb0f5b2019-11-27 15:51:48 +0800635 if (statp->tcp_nssock >= 0 && (statp->_flags & RES_F_VC) != 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900636 struct sockaddr_storage peer;
637 socklen_t size = sizeof peer;
638 unsigned old_mark;
639 socklen_t mark_size = sizeof(old_mark);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800640 if (getpeername(statp->tcp_nssock, (struct sockaddr*)(void*)&peer, &size) < 0 ||
641 !sock_eq((struct sockaddr*)(void*)&peer, nsap) ||
642 getsockopt(statp->tcp_nssock, SOL_SOCKET, SO_MARK, &old_mark, &mark_size) < 0 ||
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900643 old_mark != statp->_mark) {
Luke Huangadb0f5b2019-11-27 15:51:48 +0800644 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900645 }
646 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900647
Luke Huangadb0f5b2019-11-27 15:51:48 +0800648 if (statp->tcp_nssock < 0 || (statp->_flags & RES_F_VC) == 0) {
649 if (statp->tcp_nssock >= 0) statp->closeSockets();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900650
Luke Huangadb0f5b2019-11-27 15:51:48 +0800651 statp->tcp_nssock.reset(socket(nsap->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0));
652 if (statp->tcp_nssock < 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900653 switch (errno) {
654 case EPROTONOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900655 case EPFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900656 case EAFNOSUPPORT:
chenbruce018fdb22019-06-12 18:08:04 +0800657 PLOG(DEBUG) << __func__ << ": socket(vc): ";
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900658 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900659 default:
660 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800661 PLOG(DEBUG) << __func__ << ": socket(vc): ";
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900662 return -1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900663 }
664 }
Luke Huangadb0f5b2019-11-27 15:51:48 +0800665 resolv_tag_socket(statp->tcp_nssock, statp->uid, statp->pid);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900666 if (statp->_mark != MARK_UNSET) {
Luke Huangadb0f5b2019-11-27 15:51:48 +0800667 if (setsockopt(statp->tcp_nssock, SOL_SOCKET, SO_MARK, &statp->_mark,
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900668 sizeof(statp->_mark)) < 0) {
669 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800670 PLOG(DEBUG) << __func__ << ": setsockopt: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900671 return -1;
672 }
673 }
674 errno = 0;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800675 if (random_bind(statp->tcp_nssock, nsap->sa_family) < 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900676 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800677 dump_error("bind/vc", nsap, nsaplen);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800678 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900679 return (0);
680 }
Luke Huangadb0f5b2019-11-27 15:51:48 +0800681 if (connect_with_timeout(statp->tcp_nssock, nsap, (socklen_t)nsaplen,
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900682 get_timeout(statp, params, ns)) < 0) {
683 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800684 dump_error("connect/vc", nsap, nsaplen);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800685 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900686 /*
687 * The way connect_with_timeout() is implemented prevents us from reliably
688 * determining whether this was really a timeout or e.g. ECONNREFUSED. Since
689 * currently both cases are handled in the same way, there is no need to
690 * change this (yet). If we ever need to reliably distinguish between these
691 * cases, both connect_with_timeout() and retrying_poll() need to be
692 * modified, though.
693 */
694 *rcode = RCODE_TIMEOUT;
695 return (0);
696 }
697 statp->_flags |= RES_F_VC;
698 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900699
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900700 /*
701 * Send length & message
702 */
chenbruce0d470422019-03-28 18:44:37 +0800703 uint16_t len = htons(static_cast<uint16_t>(buflen));
Luke Huangc98fd802019-10-15 16:36:36 +0900704 const iovec iov[] = {
705 {.iov_base = &len, .iov_len = INT16SZ},
706 {.iov_base = const_cast<uint8_t*>(buf), .iov_len = static_cast<size_t>(buflen)},
707 };
Luke Huangadb0f5b2019-11-27 15:51:48 +0800708 if (writev(statp->tcp_nssock, iov, 2) != (INT16SZ + buflen)) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900709 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800710 PLOG(DEBUG) << __func__ << ": write failed: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800711 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900712 return (0);
713 }
714 /*
715 * Receive length & response
716 */
717read_len:
718 cp = ans;
719 len = INT16SZ;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800720 while ((n = read(statp->tcp_nssock, (char*)cp, (size_t)len)) > 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900721 cp += n;
722 if ((len -= n) == 0) break;
723 }
724 if (n <= 0) {
725 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800726 PLOG(DEBUG) << __func__ << ": read failed: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800727 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900728 /*
729 * A long running process might get its TCP
730 * connection reset if the remote server was
731 * restarted. Requery the server instead of
732 * trying a new one. When there is only one
733 * server, this means that a query might work
734 * instead of failing. We only allow one reset
735 * per query to prevent looping.
736 */
737 if (*terrno == ECONNRESET && !connreset) {
738 connreset = 1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900739 goto same_ns;
740 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900741 return (0);
742 }
chenbruce0d470422019-03-28 18:44:37 +0800743 uint16_t resplen = ntohs(*reinterpret_cast<const uint16_t*>(ans));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900744 if (resplen > anssiz) {
Ken Chenffc224a2019-03-19 17:41:28 +0800745 LOG(DEBUG) << __func__ << ": response truncated";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900746 truncating = 1;
747 len = anssiz;
748 } else
749 len = resplen;
750 if (len < HFIXEDSZ) {
751 /*
752 * Undersized message.
753 */
Ken Chenffc224a2019-03-19 17:41:28 +0800754 LOG(DEBUG) << __func__ << ": undersized: " << len;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900755 *terrno = EMSGSIZE;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800756 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900757 return (0);
758 }
759 cp = ans;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800760 while (len != 0 && (n = read(statp->tcp_nssock, (char*)cp, (size_t)len)) > 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900761 cp += n;
762 len -= n;
763 }
764 if (n <= 0) {
765 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800766 PLOG(DEBUG) << __func__ << ": read(vc): ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800767 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900768 return (0);
769 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900770
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900771 if (truncating) {
772 /*
773 * Flush rest of answer so connection stays in synch.
774 */
775 anhp->tc = 1;
776 len = resplen - anssiz;
777 while (len != 0) {
778 char junk[PACKETSZ];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900779
Luke Huangadb0f5b2019-11-27 15:51:48 +0800780 n = read(statp->tcp_nssock, junk, (len > sizeof junk) ? sizeof junk : len);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900781 if (n > 0)
782 len -= n;
783 else
784 break;
785 }
786 }
787 /*
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900788 * If the calling application has bailed out of
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900789 * a previous call and failed to arrange to have
790 * the circuit closed or the server has got
791 * itself confused, then drop the packet and
792 * wait for the correct one.
793 */
794 if (hp->id != anhp->id) {
Ken Chenffc224a2019-03-19 17:41:28 +0800795 LOG(DEBUG) << __func__ << ": ld answer (unexpected):";
chenbrucedd210722019-03-06 13:52:43 +0800796 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900797 goto read_len;
798 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900799
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900800 /*
801 * All is well, or the error is fatal. Signal that the
802 * next nameserver ought not be tried.
803 */
804 if (resplen > 0) {
805 struct timespec done = evNowTime();
Mike Yu6407ae42020-02-10 21:11:05 +0800806 *delay = res_stats_calculate_rtt(&done, &now);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900807 *rcode = anhp->rcode;
808 }
809 return (resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900810}
811
812/* return -1 on error (errno set), 0 on success */
Luke Huangc98fd802019-10-15 16:36:36 +0900813static int connect_with_timeout(int sock, const sockaddr* nsap, socklen_t salen,
814 const timespec timeout) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900815 int res, origflags;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900816
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900817 origflags = fcntl(sock, F_GETFL, 0);
818 fcntl(sock, F_SETFL, origflags | O_NONBLOCK);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900819
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900820 res = connect(sock, nsap, salen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900821 if (res < 0 && errno != EINPROGRESS) {
822 res = -1;
823 goto done;
824 }
825 if (res != 0) {
Luke Huangc98fd802019-10-15 16:36:36 +0900826 timespec now = evNowTime();
827 timespec finish = evAddTime(now, timeout);
Ken Chenffc224a2019-03-19 17:41:28 +0800828 LOG(INFO) << __func__ << ": " << sock << " send_vc";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900829 res = retrying_poll(sock, POLLIN | POLLOUT, &finish);
830 if (res <= 0) {
831 res = -1;
832 }
833 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900834done:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900835 fcntl(sock, F_SETFL, origflags);
Ken Chenffc224a2019-03-19 17:41:28 +0800836 LOG(INFO) << __func__ << ": " << sock << " connect_with_const timeout returning " << res;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900837 return res;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900838}
839
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900840static int retrying_poll(const int sock, const short events, const struct timespec* finish) {
841 struct timespec now, timeout;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900842
843retry:
Ken Chenffc224a2019-03-19 17:41:28 +0800844 LOG(INFO) << __func__ << ": " << sock << " retrying_poll";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900845
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900846 now = evNowTime();
847 if (evCmpTime(*finish, now) > 0)
848 timeout = evSubTime(*finish, now);
849 else
850 timeout = evConsTime(0L, 0L);
851 struct pollfd fds = {.fd = sock, .events = events};
852 int n = ppoll(&fds, 1, &timeout, /*sigmask=*/NULL);
853 if (n == 0) {
Ken Chenffc224a2019-03-19 17:41:28 +0800854 LOG(INFO) << __func__ << ": " << sock << "retrying_poll timeout";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900855 errno = ETIMEDOUT;
856 return 0;
857 }
858 if (n < 0) {
859 if (errno == EINTR) goto retry;
Ken Chenffc224a2019-03-19 17:41:28 +0800860 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll failed";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900861 return n;
862 }
863 if (fds.revents & (POLLIN | POLLOUT | POLLERR)) {
864 int error;
865 socklen_t len = sizeof(error);
866 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error) {
867 errno = error;
Ken Chenffc224a2019-03-19 17:41:28 +0800868 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll getsockopt failed";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900869 return -1;
870 }
871 }
Ken Chenffc224a2019-03-19 17:41:28 +0800872 LOG(INFO) << __func__ << ": " << sock << " retrying_poll returning " << n;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900873 return n;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900874}
875
Luke Huangbff43fc2019-11-12 15:54:47 +0800876bool ignoreInvalidAnswer(res_state statp, const sockaddr_storage& from, const uint8_t* buf,
877 int buflen, uint8_t* ans, int anssiz) {
878 const HEADER* hp = (const HEADER*)(const void*)buf;
879 HEADER* anhp = (HEADER*)(void*)ans;
880 if (hp->id != anhp->id) {
881 // response from old query, ignore it.
882 LOG(DEBUG) << __func__ << ": old answer:";
883 return true;
884 }
885 if (!res_ourserver_p(statp, (sockaddr*)(void*)&from)) {
886 // response from wrong server? ignore it.
887 LOG(DEBUG) << __func__ << ": not our server:";
888 return true;
889 }
890 if (!res_queriesmatch(buf, buf + buflen, ans, ans + anssiz)) {
891 // response contains wrong query? ignore it.
892 LOG(DEBUG) << __func__ << ": wrong query name:";
893 return true;
894 }
895 return false;
896}
897
chenbrucec51f1212019-09-12 16:59:33 +0800898static int send_dg(res_state statp, res_params* params, const uint8_t* buf, int buflen,
Mike Yue48f7b52020-02-10 14:55:06 +0800899 uint8_t* ans, int anssiz, int* terrno, size_t ns, int* v_circuit,
900 int* gotsomewhere, time_t* at, int* rcode, int* delay) {
901 // It should never happen, but just in case.
902 if (ns >= statp->nsaddrs.size()) {
903 LOG(ERROR) << __func__ << ": Out-of-bound indexing: " << ns;
904 return -1;
905 }
906
Luke Huangbff43fc2019-11-12 15:54:47 +0800907 *at = time(nullptr);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900908 *delay = 0;
Mike Yue48f7b52020-02-10 14:55:06 +0800909 const sockaddr_storage ss = statp->nsaddrs[ns];
910 const sockaddr* nsap = reinterpret_cast<const sockaddr*>(&ss);
Luke Huangbff43fc2019-11-12 15:54:47 +0800911 const int nsaplen = sockaddrSize(nsap);
912
Bernie Innocentibb330742019-10-09 00:55:53 +0900913 if (statp->nssocks[ns] == -1) {
Luke Huangadb0f5b2019-11-27 15:51:48 +0800914 statp->nssocks[ns].reset(socket(nsap->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0));
Bernie Innocentibb330742019-10-09 00:55:53 +0900915 if (statp->nssocks[ns] < 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900916 switch (errno) {
917 case EPROTONOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900918 case EPFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900919 case EAFNOSUPPORT:
chenbruce018fdb22019-06-12 18:08:04 +0800920 PLOG(DEBUG) << __func__ << ": socket(dg): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900921 return (0);
922 default:
923 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800924 PLOG(DEBUG) << __func__ << ": socket(dg): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900925 return (-1);
926 }
927 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900928
Praveen Moongalam Thyagarajan8ab18ba2019-09-04 14:46:50 -0700929 resolv_tag_socket(statp->nssocks[ns], statp->uid, statp->pid);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900930 if (statp->_mark != MARK_UNSET) {
Bernie Innocentibb330742019-10-09 00:55:53 +0900931 if (setsockopt(statp->nssocks[ns], SOL_SOCKET, SO_MARK, &(statp->_mark),
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900932 sizeof(statp->_mark)) < 0) {
Luke Huangadb0f5b2019-11-27 15:51:48 +0800933 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900934 return -1;
935 }
936 }
chenbruceb9cce7b2019-07-15 16:14:53 +0800937 // Use a "connected" datagram socket to receive an ECONNREFUSED error
938 // on the next socket operation when the server responds with an
939 // ICMP port-unreachable error. This way we can detect the absence of
940 // a nameserver without timing out.
Bernie Innocentibb330742019-10-09 00:55:53 +0900941 if (random_bind(statp->nssocks[ns], nsap->sa_family) < 0) {
chenbruce018fdb22019-06-12 18:08:04 +0800942 dump_error("bind(dg)", nsap, nsaplen);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800943 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900944 return (0);
945 }
Bernie Innocentibb330742019-10-09 00:55:53 +0900946 if (connect(statp->nssocks[ns], nsap, (socklen_t)nsaplen) < 0) {
chenbruce018fdb22019-06-12 18:08:04 +0800947 dump_error("connect(dg)", nsap, nsaplen);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800948 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900949 return (0);
950 }
Ken Chenffc224a2019-03-19 17:41:28 +0800951 LOG(DEBUG) << __func__ << ": new DG socket";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900952 }
Luke Huangbff43fc2019-11-12 15:54:47 +0800953 if (send(statp->nssocks[ns], (const char*)buf, (size_t)buflen, 0) != buflen) {
chenbruce018fdb22019-06-12 18:08:04 +0800954 PLOG(DEBUG) << __func__ << ": send: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800955 statp->closeSockets();
Bernie Innocenti3952ccc2019-03-03 19:39:53 +0900956 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900957 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900958
Luke Huangbff43fc2019-11-12 15:54:47 +0800959 timespec timeout = get_timeout(statp, params, ns);
960 timespec now = evNowTime();
961 timespec finish = evAddTime(now, timeout);
962 for (;;) {
963 // Wait for reply.
964 int n = retrying_poll(statp->nssocks[ns], POLLIN, &finish);
965 if (n == 0) {
966 *rcode = RCODE_TIMEOUT;
967 LOG(DEBUG) << __func__ << ": timeout";
968 *gotsomewhere = 1;
969 return 0;
970 }
971 if (n < 0) {
972 PLOG(DEBUG) << __func__ << ": poll: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800973 statp->closeSockets();
Luke Huangbff43fc2019-11-12 15:54:47 +0800974 return 0;
975 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900976
Luke Huangbff43fc2019-11-12 15:54:47 +0800977 errno = 0;
978 sockaddr_storage from;
979 socklen_t fromlen = sizeof(from);
980 int resplen = recvfrom(statp->nssocks[ns], (char*)ans, (size_t)anssiz, 0,
981 (sockaddr*)(void*)&from, &fromlen);
982 if (resplen <= 0) {
983 PLOG(DEBUG) << __func__ << ": recvfrom: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800984 statp->closeSockets();
Luke Huangbff43fc2019-11-12 15:54:47 +0800985 return 0;
986 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900987 *gotsomewhere = 1;
Luke Huangbff43fc2019-11-12 15:54:47 +0800988 if (resplen < HFIXEDSZ) {
989 // Undersized message.
990 LOG(DEBUG) << __func__ << ": undersized: " << resplen;
991 *terrno = EMSGSIZE;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800992 statp->closeSockets();
Luke Huangbff43fc2019-11-12 15:54:47 +0800993 return 0;
994 }
995
996 if (ignoreInvalidAnswer(statp, from, buf, buflen, ans, anssiz)) {
997 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
998 continue;
999 }
1000
1001 HEADER* anhp = (HEADER*)(void*)ans;
1002 if (anhp->rcode == FORMERR && (statp->netcontext_flags & NET_CONTEXT_FLAG_USE_EDNS)) {
1003 // Do not retry if the server do not understand EDNS0.
1004 // The case has to be captured here, as FORMERR packet do not
1005 // carry query section, hence res_queriesmatch() returns 0.
1006 LOG(DEBUG) << __func__ << ": server rejected query with EDNS0:";
1007 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
1008 // record the error
1009 statp->_flags |= RES_F_EDNS0ERR;
Luke Huangadb0f5b2019-11-27 15:51:48 +08001010 statp->closeSockets();
Luke Huangbff43fc2019-11-12 15:54:47 +08001011 return 0;
1012 }
1013
1014 timespec done = evNowTime();
Mike Yu6407ae42020-02-10 21:11:05 +08001015 *delay = res_stats_calculate_rtt(&done, &now);
Luke Huangbff43fc2019-11-12 15:54:47 +08001016 if (anhp->rcode == SERVFAIL || anhp->rcode == NOTIMP || anhp->rcode == REFUSED) {
1017 LOG(DEBUG) << __func__ << ": server rejected query:";
1018 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Luke Huangadb0f5b2019-11-27 15:51:48 +08001019 statp->closeSockets();
Luke Huangbff43fc2019-11-12 15:54:47 +08001020 *rcode = anhp->rcode;
1021 return 0;
1022 }
1023 if (anhp->tc) {
1024 // To get the rest of answer,
1025 // use TCP with same server.
1026 LOG(DEBUG) << __func__ << ": truncated answer";
1027 *v_circuit = 1;
Luke Huangadb0f5b2019-11-27 15:51:48 +08001028 statp->closeSockets();
Luke Huangbff43fc2019-11-12 15:54:47 +08001029 return 1;
1030 }
1031 // All is well, or the error is fatal. Signal that the
1032 // next nameserver ought not be tried.
1033 if (resplen > 0) {
1034 *rcode = anhp->rcode;
1035 }
1036 return resplen;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001037 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001038}
1039
chenbruce018fdb22019-06-12 18:08:04 +08001040static void dump_error(const char* str, const struct sockaddr* address, int alen) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001041 char hbuf[NI_MAXHOST];
1042 char sbuf[NI_MAXSERV];
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001043 constexpr int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
Luke Huangc98fd802019-10-15 16:36:36 +09001044 const int err = errno;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001045
chenbruce018fdb22019-06-12 18:08:04 +08001046 if (!WOULD_LOG(DEBUG)) return;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001047
chenbruce018fdb22019-06-12 18:08:04 +08001048 if (getnameinfo(address, (socklen_t)alen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf), niflags)) {
1049 strncpy(hbuf, "?", sizeof(hbuf) - 1);
1050 hbuf[sizeof(hbuf) - 1] = '\0';
1051 strncpy(sbuf, "?", sizeof(sbuf) - 1);
1052 sbuf[sizeof(sbuf) - 1] = '\0';
Elliott Hughes3b8f5902019-03-08 12:02:55 -08001053 }
Luke Huangc98fd802019-10-15 16:36:36 +09001054 errno = err;
chenbruce018fdb22019-06-12 18:08:04 +08001055 PLOG(DEBUG) << __func__ << ": " << str << " ([" << hbuf << "]." << sbuf << "): ";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001056}
1057
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001058static int sock_eq(struct sockaddr* a, struct sockaddr* b) {
1059 struct sockaddr_in *a4, *b4;
1060 struct sockaddr_in6 *a6, *b6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001061
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001062 if (a->sa_family != b->sa_family) return 0;
1063 switch (a->sa_family) {
1064 case AF_INET:
1065 a4 = (struct sockaddr_in*) (void*) a;
1066 b4 = (struct sockaddr_in*) (void*) b;
1067 return a4->sin_port == b4->sin_port && a4->sin_addr.s_addr == b4->sin_addr.s_addr;
1068 case AF_INET6:
1069 a6 = (struct sockaddr_in6*) (void*) a;
1070 b6 = (struct sockaddr_in6*) (void*) b;
1071 return a6->sin6_port == b6->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001072#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001073 a6->sin6_scope_id == b6->sin6_scope_id &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001074#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001075 IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
1076 default:
1077 return 0;
1078 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001079}
Mike Yub601ff72018-11-01 20:07:00 +08001080
lifr6b83a6f2019-07-26 03:17:43 +08001081PrivateDnsModes convertEnumType(PrivateDnsMode privateDnsmode) {
1082 switch (privateDnsmode) {
1083 case PrivateDnsMode::OFF:
1084 return PrivateDnsModes::PDM_OFF;
1085 case PrivateDnsMode::OPPORTUNISTIC:
1086 return PrivateDnsModes::PDM_OPPORTUNISTIC;
1087 case PrivateDnsMode::STRICT:
1088 return PrivateDnsModes::PDM_STRICT;
Mike Yu99b8dc72019-11-22 17:45:31 +08001089 default:
1090 return PrivateDnsModes::PDM_UNKNOWN;
lifr6b83a6f2019-07-26 03:17:43 +08001091 }
lifr6b83a6f2019-07-26 03:17:43 +08001092}
1093
Luke Huangd7aa7b42018-11-21 20:37:50 +08001094static int res_tls_send(res_state statp, const Slice query, const Slice answer, int* rcode,
Mike Yubfb1b342018-11-06 15:42:36 +08001095 bool* fallback) {
1096 int resplen = 0;
Mike Yub601ff72018-11-01 20:07:00 +08001097 const unsigned netId = statp->netid;
Mike Yub601ff72018-11-01 20:07:00 +08001098
Mike Yubfb1b342018-11-06 15:42:36 +08001099 PrivateDnsStatus privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
lifr6b83a6f2019-07-26 03:17:43 +08001100 statp->event->set_private_dns_modes(convertEnumType(privateDnsStatus.mode));
Mike Yubfb1b342018-11-06 15:42:36 +08001101
1102 if (privateDnsStatus.mode == PrivateDnsMode::OFF) {
1103 *fallback = true;
1104 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001105 }
1106
Mike Yu3e829062019-08-07 14:01:14 +08001107 if (privateDnsStatus.validatedServers().empty()) {
Mike Yub601ff72018-11-01 20:07:00 +08001108 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
Mike Yubfb1b342018-11-06 15:42:36 +08001109 *fallback = true;
1110 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001111 } else {
1112 // Sleep and iterate some small number of times checking for the
1113 // arrival of resolved and validated server IP addresses, instead
1114 // of returning an immediate error.
Mike Yu4f3747b2018-12-02 17:54:29 +09001115 // This is needed because as soon as a network becomes the default network, apps will
1116 // send DNS queries on that network. If no servers have yet validated, and we do not
1117 // block those queries, they would immediately fail, causing application-visible errors.
1118 // Note that this can happen even before the network validates, since an unvalidated
1119 // network can become the default network if no validated networks are available.
1120 //
1121 // TODO: see if there is a better way to address this problem, such as buffering the
1122 // queries in a queue or only blocking queries for the first few seconds after a default
1123 // network change.
Mike Yubfb1b342018-11-06 15:42:36 +08001124 for (int i = 0; i < 42; i++) {
1125 std::this_thread::sleep_for(std::chrono::milliseconds(100));
Mike Yu3e829062019-08-07 14:01:14 +08001126 // Calling getStatus() to merely check if there's any validated server seems
1127 // wasteful. Consider adding a new method in PrivateDnsConfiguration for speed ups.
1128 if (!gPrivateDnsConfiguration.getStatus(netId).validatedServers().empty()) {
Mike Yubfb1b342018-11-06 15:42:36 +08001129 privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
1130 break;
1131 }
1132 }
Mike Yu3e829062019-08-07 14:01:14 +08001133 if (privateDnsStatus.validatedServers().empty()) {
Mike Yubfb1b342018-11-06 15:42:36 +08001134 return -1;
1135 }
Mike Yub601ff72018-11-01 20:07:00 +08001136 }
1137 }
1138
chenbruceacb832c2019-02-20 19:45:50 +08001139 LOG(INFO) << __func__ << ": performing query over TLS";
Mike Yub601ff72018-11-01 20:07:00 +08001140
Mike Yu3e829062019-08-07 14:01:14 +08001141 const auto response = sDnsTlsDispatcher.query(privateDnsStatus.validatedServers(), statp, query,
Mike Yubfb1b342018-11-06 15:42:36 +08001142 answer, &resplen);
Mike Yub601ff72018-11-01 20:07:00 +08001143
chenbruceacb832c2019-02-20 19:45:50 +08001144 LOG(INFO) << __func__ << ": TLS query result: " << static_cast<int>(response);
Mike Yub601ff72018-11-01 20:07:00 +08001145
1146 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
1147 // In opportunistic mode, handle falling back to cleartext in some
1148 // cases (DNS shouldn't fail if a validated opportunistic mode server
1149 // becomes unreachable for some reason).
1150 switch (response) {
Mike Yubfb1b342018-11-06 15:42:36 +08001151 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001152 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001153 return resplen;
Mike Yub601ff72018-11-01 20:07:00 +08001154 case DnsTlsTransport::Response::network_error:
Mike Yubfb1b342018-11-06 15:42:36 +08001155 // No need to set the error timeout here since it will fallback to UDP.
Mike Yub601ff72018-11-01 20:07:00 +08001156 case DnsTlsTransport::Response::internal_error:
1157 // Note: this will cause cleartext queries to be emitted, with
1158 // all of the EDNS0 goodness enabled. Fingers crossed. :-/
Mike Yubfb1b342018-11-06 15:42:36 +08001159 *fallback = true;
1160 [[fallthrough]];
Mike Yub601ff72018-11-01 20:07:00 +08001161 default:
Mike Yubfb1b342018-11-06 15:42:36 +08001162 return -1;
1163 }
1164 } else {
1165 // Strict mode
1166 switch (response) {
1167 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001168 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001169 return resplen;
1170 case DnsTlsTransport::Response::network_error:
1171 // This case happens when the query stored in DnsTlsTransport is expired since
1172 // either 1) the query has been tried for 3 times but no response or 2) fail to
1173 // establish the connection with the server.
Luke Huangd7aa7b42018-11-21 20:37:50 +08001174 *rcode = RCODE_TIMEOUT;
Mike Yubfb1b342018-11-06 15:42:36 +08001175 [[fallthrough]];
1176 default:
1177 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001178 }
1179 }
Mike Yub601ff72018-11-01 20:07:00 +08001180}
Luke Huang4973a0d2018-11-19 20:17:26 +08001181
Luke Huangba7bef92018-12-26 16:53:03 +08001182int resolv_res_nsend(const android_net_context* netContext, const uint8_t* msg, int msgLen,
lifr94981782019-05-17 21:15:19 +08001183 uint8_t* ans, int ansLen, int* rcode, uint32_t flags,
1184 NetworkDnsEventReported* event) {
1185 assert(event != nullptr);
Bernie Innocenti08487112019-10-11 21:14:13 +09001186 ResState res;
1187 res_init(&res, netContext, event);
Mike Yu021c3e12019-10-08 17:29:34 +08001188 resolv_populate_res_for_net(&res);
Luke Huang4973a0d2018-11-19 20:17:26 +08001189 *rcode = NOERROR;
Bernie Innocenti08487112019-10-11 21:14:13 +09001190 return res_nsend(&res, msg, msgLen, ans, ansLen, rcode, flags);
Bernie Innocentiec4219b2019-01-30 11:16:36 +09001191}