blob: ab072cbbc02dee5a4760e36cce82adae365d2b97 [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
Luke Huangd1d734f2020-04-30 12:25:40 +080079#include <chrono>
80
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090081#include <sys/param.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090082#include <sys/socket.h>
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090083#include <sys/time.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090084#include <sys/uio.h>
85
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090086#include <arpa/inet.h>
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090087#include <arpa/nameser.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090088
89#include <errno.h>
90#include <fcntl.h>
91#include <netdb.h>
92#include <poll.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090093#include <signal.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090094#include <stdlib.h>
95#include <string.h>
96#include <time.h>
97#include <unistd.h>
chenbruceceb3c022021-06-15 21:36:19 +080098#include <span>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090099
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900100#include <android-base/logging.h>
Luke Huang420ee622019-11-27 17:52:44 +0800101#include <android-base/result.h>
Bernie Innocenti758005f2019-02-19 18:08:36 +0900102#include <android/multinetwork.h> // ResNsendFlags
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900103
Mike Yub601ff72018-11-01 20:07:00 +0800104#include <netdutils/Slice.h>
lifr94981782019-05-17 21:15:19 +0800105#include <netdutils/Stopwatch.h>
Bernie Innocentiec4219b2019-01-30 11:16:36 +0900106#include "DnsTlsDispatcher.h"
107#include "DnsTlsTransport.h"
Luke Huangf40df9c2020-04-21 08:51:48 +0800108#include "Experiments.h"
Bernie Innocentiec4219b2019-01-30 11:16:36 +0900109#include "PrivateDnsConfiguration.h"
Bernie Innocentiac18b122018-10-01 23:10:18 +0900110#include "netd_resolv/resolv.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900111#include "private/android_filesystem_config.h"
Bernie Innocenti10a90282020-01-23 23:28:00 +0900112
113#include "res_comp.h"
Mike Yu34433c62019-08-20 20:17:36 +0800114#include "res_debug.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900115#include "resolv_cache.h"
Ken Chen99c0b322019-11-20 14:24:09 +0800116#include "stats.h"
lifr94981782019-05-17 21:15:19 +0800117#include "stats.pb.h"
Mike Yu021c3e12019-10-08 17:29:34 +0800118#include "util.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900119
Luke Huangd1d734f2020-04-30 12:25:40 +0800120using namespace std::chrono_literals;
Mike Yub601ff72018-11-01 20:07:00 +0800121// TODO: use the namespace something like android::netd_resolv for libnetd_resolv
Luke Huang420ee622019-11-27 17:52:44 +0800122using android::base::ErrnoError;
123using android::base::Result;
chenbruceceb3c022021-06-15 21:36:19 +0800124using android::base::unique_fd;
chenbruce99cbfd82019-09-05 15:08:13 +0800125using android::net::CacheStatus;
126using android::net::DnsQueryEvent;
127using android::net::DnsTlsDispatcher;
128using android::net::DnsTlsTransport;
chenbruce99cbfd82019-09-05 15:08:13 +0800129using android::net::IpVersion;
130using android::net::IV_IPV4;
131using android::net::IV_IPV6;
132using android::net::IV_UNKNOWN;
Luke Huang23d55192020-04-16 11:47:30 +0800133using android::net::LinuxErrno;
lifr94981782019-05-17 21:15:19 +0800134using android::net::NetworkDnsEventReported;
chenbruce99cbfd82019-09-05 15:08:13 +0800135using android::net::NS_T_INVALID;
136using android::net::NsRcode;
137using android::net::NsType;
Mike Yu60248242020-07-29 16:45:26 +0800138using android::net::PrivateDnsConfiguration;
chenbruce99cbfd82019-09-05 15:08:13 +0800139using android::net::PrivateDnsMode;
140using android::net::PrivateDnsModes;
141using android::net::PrivateDnsStatus;
chenbrucebad8b882021-06-16 18:44:11 +0800142using android::net::PROTO_MDNS;
chenbruce99cbfd82019-09-05 15:08:13 +0800143using android::net::PROTO_TCP;
144using android::net::PROTO_UDP;
Mike Yue655b1d2019-08-28 17:49:59 +0800145using android::netdutils::IPSockAddr;
Bernie Innocentiec4219b2019-01-30 11:16:36 +0900146using android::netdutils::Slice;
lifr94981782019-05-17 21:15:19 +0800147using android::netdutils::Stopwatch;
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900148
chenbruceceb3c022021-06-15 21:36:19 +0800149const std::vector<IPSockAddr> mdns_addrs = {IPSockAddr::toIPSockAddr("ff02::fb", 5353),
150 IPSockAddr::toIPSockAddr("224.0.0.251", 5353)};
151
152static int setupUdpSocket(ResState* statp, const sockaddr* sockap, unique_fd* fd_out, int* terrno);
Mike Yue48f7b52020-02-10 14:55:06 +0800153static int send_dg(res_state statp, res_params* params, const uint8_t* buf, int buflen,
Luke Huang420ee622019-11-27 17:52:44 +0800154 uint8_t* ans, int anssiz, int* terrno, size_t* ns, int* v_circuit,
Mike Yue48f7b52020-02-10 14:55:06 +0800155 int* gotsomewhere, time_t* at, int* rcode, int* delay);
chenbruceceb3c022021-06-15 21:36:19 +0800156static int send_vc(res_state statp, res_params* params, const uint8_t* buf, int buflen,
157 uint8_t* ans, int anssiz, int* terrno, size_t ns, time_t* at, int* rcode,
158 int* delay);
159static int send_mdns(ResState* statp, std::span<const uint8_t> buf, uint8_t* ans, int anssiz,
160 int* terrno, int* rcode);
chenbruce76620642021-06-15 18:39:27 +0800161static void dump_error(const char*, const struct sockaddr*);
chenbruceacb832c2019-02-20 19:45:50 +0800162
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900163static int sock_eq(struct sockaddr*, struct sockaddr*);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900164static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
165 const struct timespec timeout);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900166static int retrying_poll(const int sock, short events, const struct timespec* finish);
Luke Huangd7aa7b42018-11-21 20:37:50 +0800167static int res_tls_send(res_state, const Slice query, const Slice answer, int* rcode,
Mike Yubfb1b342018-11-06 15:42:36 +0800168 bool* fallback);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900169
lifr94981782019-05-17 21:15:19 +0800170NsType getQueryType(const uint8_t* msg, size_t msgLen) {
171 ns_msg handle;
172 ns_rr rr;
173 if (ns_initparse((const uint8_t*)msg, msgLen, &handle) < 0 ||
174 ns_parserr(&handle, ns_s_qd, 0, &rr) < 0) {
175 return NS_T_INVALID;
176 }
177 return static_cast<NsType>(ns_rr_type(rr));
178}
179
180IpVersion ipFamilyToIPVersion(const int ipFamily) {
181 switch (ipFamily) {
182 case AF_INET:
183 return IV_IPV4;
184 case AF_INET6:
185 return IV_IPV6;
186 default:
187 return IV_UNKNOWN;
188 }
189}
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900190
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900191// BEGIN: Code copied from ISC eventlib
192// TODO: move away from this code
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900193#define BILLION 1000000000
194
195static struct timespec evConsTime(time_t sec, long nsec) {
196 struct timespec x;
197
198 x.tv_sec = sec;
199 x.tv_nsec = nsec;
200 return (x);
201}
202
203static struct timespec evAddTime(struct timespec addend1, struct timespec addend2) {
204 struct timespec x;
205
206 x.tv_sec = addend1.tv_sec + addend2.tv_sec;
207 x.tv_nsec = addend1.tv_nsec + addend2.tv_nsec;
208 if (x.tv_nsec >= BILLION) {
209 x.tv_sec++;
210 x.tv_nsec -= BILLION;
211 }
212 return (x);
213}
214
215static struct timespec evSubTime(struct timespec minuend, struct timespec subtrahend) {
216 struct timespec x;
217
218 x.tv_sec = minuend.tv_sec - subtrahend.tv_sec;
219 if (minuend.tv_nsec >= subtrahend.tv_nsec)
220 x.tv_nsec = minuend.tv_nsec - subtrahend.tv_nsec;
221 else {
222 x.tv_nsec = BILLION - subtrahend.tv_nsec + minuend.tv_nsec;
223 x.tv_sec--;
224 }
225 return (x);
226}
227
228static int evCmpTime(struct timespec a, struct timespec b) {
229#define SGN(x) ((x) < 0 ? (-1) : (x) > 0 ? (1) : (0));
230 time_t s = a.tv_sec - b.tv_sec;
231 long n;
232
233 if (s != 0) return SGN(s);
234
235 n = a.tv_nsec - b.tv_nsec;
236 return SGN(n);
237}
238
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900239static struct timespec evNowTime(void) {
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900240 struct timespec tsnow;
Bernie Innocentic1834822018-08-31 16:11:41 +0900241 clock_gettime(CLOCK_REALTIME, &tsnow);
242 return tsnow;
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900243}
244
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900245// END: Code copied from ISC eventlib
246
lifr94981782019-05-17 21:15:19 +0800247/* BIONIC-BEGIN: implement source port randomization */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900248static int random_bind(int s, int family) {
nuccachenb980f2f2018-10-23 17:10:58 +0800249 sockaddr_union u;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900250 int j;
251 socklen_t slen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900252
253 /* clear all, this also sets the IP4/6 address to 'any' */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900254 memset(&u, 0, sizeof u);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900255
256 switch (family) {
257 case AF_INET:
258 u.sin.sin_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900259 slen = sizeof u.sin;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900260 break;
261 case AF_INET6:
262 u.sin6.sin6_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900263 slen = sizeof u.sin6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900264 break;
265 default:
266 errno = EPROTO;
267 return -1;
268 }
269
270 /* first try to bind to a random source port a few times */
271 for (j = 0; j < 10; j++) {
272 /* find a random port between 1025 .. 65534 */
Luke Huangdda920f2019-02-13 14:05:02 +0800273 int port = 1025 + (arc4random_uniform(65535 - 1025));
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900274 if (family == AF_INET)
275 u.sin.sin_port = htons(port);
276 else
277 u.sin6.sin6_port = htons(port);
278
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900279 if (!bind(s, &u.sa, slen)) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900280 }
281
Bernie Innocenti9c575932018-09-07 21:10:25 +0900282 // nothing after 10 attempts, our network table is probably busy
283 // let the system decide which port is best
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900284 if (family == AF_INET)
285 u.sin.sin_port = 0;
286 else
287 u.sin6.sin6_port = 0;
288
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900289 return bind(s, &u.sa, slen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900290}
291/* BIONIC-END */
292
Luke Huang70931aa2019-01-31 11:57:41 +0800293// Disables all nameservers other than selectedServer
294static void res_set_usable_server(int selectedServer, int nscount, bool usable_servers[]) {
295 int usableIndex = 0;
296 for (int ns = 0; ns < nscount; ns++) {
297 if (usable_servers[ns]) ++usableIndex;
298 if (usableIndex != selectedServer) usable_servers[ns] = false;
299 }
300}
301
Luke Huang420ee622019-11-27 17:52:44 +0800302// Looks up the nameserver address in res.nsaddrs[], returns the ns number if found, otherwise -1.
303static int res_ourserver_p(res_state statp, const sockaddr* sa) {
Bernie Innocenti2e8540b2018-09-26 11:52:04 +0900304 const sockaddr_in *inp, *srv;
305 const sockaddr_in6 *in6p, *srv6;
Luke Huang420ee622019-11-27 17:52:44 +0800306 int ns = 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900307 switch (sa->sa_family) {
308 case AF_INET:
309 inp = (const struct sockaddr_in*) (const void*) sa;
Luke Huang420ee622019-11-27 17:52:44 +0800310
Mike Yue48f7b52020-02-10 14:55:06 +0800311 for (const IPSockAddr& ipsa : statp->nsaddrs) {
312 sockaddr_storage ss = ipsa;
313 srv = reinterpret_cast<sockaddr_in*>(&ss);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900314 if (srv->sin_family == inp->sin_family && srv->sin_port == inp->sin_port &&
315 (srv->sin_addr.s_addr == INADDR_ANY ||
316 srv->sin_addr.s_addr == inp->sin_addr.s_addr))
Luke Huang420ee622019-11-27 17:52:44 +0800317 return ns;
318 ++ns;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900319 }
320 break;
321 case AF_INET6:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900322 in6p = (const struct sockaddr_in6*) (const void*) sa;
Mike Yue48f7b52020-02-10 14:55:06 +0800323 for (const IPSockAddr& ipsa : statp->nsaddrs) {
324 sockaddr_storage ss = ipsa;
325 srv6 = reinterpret_cast<sockaddr_in6*>(&ss);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900326 if (srv6->sin6_family == in6p->sin6_family && srv6->sin6_port == in6p->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900327#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900328 (srv6->sin6_scope_id == 0 || srv6->sin6_scope_id == in6p->sin6_scope_id) &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900329#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900330 (IN6_IS_ADDR_UNSPECIFIED(&srv6->sin6_addr) ||
331 IN6_ARE_ADDR_EQUAL(&srv6->sin6_addr, &in6p->sin6_addr)))
Luke Huang420ee622019-11-27 17:52:44 +0800332 return ns;
333 ++ns;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900334 }
335 break;
336 default:
337 break;
338 }
Luke Huang420ee622019-11-27 17:52:44 +0800339 return -1;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900340}
341
342/* int
Bernie Innocenti9c575932018-09-07 21:10:25 +0900343 * res_nameinquery(name, type, cl, buf, eom)
344 * look for (name, type, cl) in the query section of packet (buf, eom)
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900345 * requires:
346 * buf + HFIXEDSZ <= eom
347 * returns:
348 * -1 : format error
349 * 0 : not found
350 * >0 : found
351 * author:
352 * paul vixie, 29may94
353 */
chenbrucec51f1212019-09-12 16:59:33 +0800354int res_nameinquery(const char* name, int type, int cl, const uint8_t* buf, const uint8_t* eom) {
355 const uint8_t* cp = buf + HFIXEDSZ;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900356 int qdcount = ntohs(((const HEADER*) (const void*) buf)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900357
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900358 while (qdcount-- > 0) {
359 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900360 int n = dn_expand(buf, eom, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900361 if (n < 0) return (-1);
362 cp += n;
363 if (cp + 2 * INT16SZ > eom) return (-1);
chenbruce0d470422019-03-28 18:44:37 +0800364 int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900365 cp += INT16SZ;
chenbruce0d470422019-03-28 18:44:37 +0800366 int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900367 cp += INT16SZ;
Bernie Innocenti9c575932018-09-07 21:10:25 +0900368 if (ttype == type && tclass == cl && ns_samename(tname, name) == 1) return (1);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900369 }
370 return (0);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900371}
372
373/* int
374 * res_queriesmatch(buf1, eom1, buf2, eom2)
375 * is there a 1:1 mapping of (name,type,class)
376 * in (buf1,eom1) and (buf2,eom2)?
377 * returns:
378 * -1 : format error
379 * 0 : not a 1:1 mapping
380 * >0 : is a 1:1 mapping
381 * author:
382 * paul vixie, 29may94
383 */
chenbrucec51f1212019-09-12 16:59:33 +0800384int res_queriesmatch(const uint8_t* buf1, const uint8_t* eom1, const uint8_t* buf2,
385 const uint8_t* eom2) {
386 const uint8_t* cp = buf1 + HFIXEDSZ;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900387 int qdcount = ntohs(((const HEADER*) (const void*) buf1)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900388
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900389 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2) return (-1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900390
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900391 /*
392 * Only header section present in replies to
393 * dynamic update packets.
394 */
395 if ((((const HEADER*) (const void*) buf1)->opcode == ns_o_update) &&
396 (((const HEADER*) (const void*) buf2)->opcode == ns_o_update))
397 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900398
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900399 if (qdcount != ntohs(((const HEADER*) (const void*) buf2)->qdcount)) return (0);
400 while (qdcount-- > 0) {
401 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900402 int n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900403 if (n < 0) return (-1);
404 cp += n;
405 if (cp + 2 * INT16SZ > eom1) return (-1);
chenbruce0d470422019-03-28 18:44:37 +0800406 int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900407 cp += INT16SZ;
chenbruce0d470422019-03-28 18:44:37 +0800408 int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900409 cp += INT16SZ;
410 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2)) return (0);
411 }
412 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900413}
414
lifr94981782019-05-17 21:15:19 +0800415static DnsQueryEvent* addDnsQueryEvent(NetworkDnsEventReported* event) {
416 return event->mutable_dns_query_events()->add_dns_query_event();
417}
418
Luke Huangeb618ef2020-05-26 14:17:02 +0800419static bool isNetworkRestricted(int terrno) {
420 // It's possible that system was in some network restricted mode, which blocked
421 // the operation of sending packet and resulted in EPERM errno.
422 // It would be no reason to keep retrying on that case.
423 // TODO: Check the system status to know if network restricted mode is
424 // enabled.
425 return (terrno == EPERM);
426}
427
chenbrucec51f1212019-09-12 16:59:33 +0800428int res_nsend(res_state statp, const uint8_t* buf, int buflen, uint8_t* ans, int anssiz, int* rcode,
Luke Huangd1d734f2020-04-30 12:25:40 +0800429 uint32_t flags, std::chrono::milliseconds sleepTimeMs) {
Luke Huang43cc1b12019-10-15 19:06:42 +0900430 LOG(DEBUG) << __func__;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900431
Luke Huang43cc1b12019-10-15 19:06:42 +0900432 // Should not happen
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900433 if (anssiz < HFIXEDSZ) {
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800434 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900435 errno = EINVAL;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800436 return -EINVAL;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900437 }
chenbrucedd210722019-03-06 13:52:43 +0800438 res_pquery(buf, buflen);
chenbruceacb832c2019-02-20 19:45:50 +0800439
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900440 int anslen = 0;
lifrd4d9fbb2019-07-31 20:18:35 +0800441 Stopwatch cacheStopwatch;
Luke Huang43cc1b12019-10-15 19:06:42 +0900442 ResolvCacheStatus cache_status =
443 resolv_cache_lookup(statp->netid, buf, buflen, ans, anssiz, &anslen, flags);
lifrd4d9fbb2019-07-31 20:18:35 +0800444 const int32_t cacheLatencyUs = saturate_cast<int32_t>(cacheStopwatch.timeTakenUs());
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900445 if (cache_status == RESOLV_CACHE_FOUND) {
Luke Huang83c9b4b2019-02-27 18:18:01 +0800446 HEADER* hp = (HEADER*)(void*)ans;
447 *rcode = hp->rcode;
lifr94981782019-05-17 21:15:19 +0800448 DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
449 dnsQueryEvent->set_latency_micros(cacheLatencyUs);
450 dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
lifre02d01c2019-12-31 17:24:57 +0800451 dnsQueryEvent->set_type(getQueryType(buf, buflen));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900452 return anslen;
453 } else if (cache_status != RESOLV_CACHE_UNSUPPORTED) {
454 // had a cache miss for a known network, so populate the thread private
455 // data so the normal resolve path can do its thing
Mike Yu021c3e12019-10-08 17:29:34 +0800456 resolv_populate_res_for_net(statp);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900457 }
chenbruceceb3c022021-06-15 21:36:19 +0800458
459 // MDNS
460 if (isMdnsResolution(statp->_flags)) {
461 // Use an impossible error code as default value.
462 int terrno = ETIME;
463 int resplen = 0;
464 *rcode = RCODE_INTERNAL_ERROR;
465 std::span<const uint8_t> buffer(buf, buflen);
chenbrucebad8b882021-06-16 18:44:11 +0800466 Stopwatch queryStopwatch;
chenbruceceb3c022021-06-15 21:36:19 +0800467 resplen = send_mdns(statp, buffer, ans, anssiz, &terrno, rcode);
chenbrucebad8b882021-06-16 18:44:11 +0800468 const IPSockAddr& receivedMdnsAddr =
469 (getQueryType(buf, buflen) == T_AAAA) ? mdns_addrs[0] : mdns_addrs[1];
470 DnsQueryEvent* mDnsQueryEvent = addDnsQueryEvent(statp->event);
471 mDnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
472 mDnsQueryEvent->set_latency_micros(saturate_cast<int32_t>(queryStopwatch.timeTakenUs()));
473 mDnsQueryEvent->set_ip_version(ipFamilyToIPVersion(receivedMdnsAddr.family()));
474 mDnsQueryEvent->set_rcode(static_cast<NsRcode>(*rcode));
475 mDnsQueryEvent->set_protocol(PROTO_MDNS);
476 mDnsQueryEvent->set_type(getQueryType(buf, buflen));
477 mDnsQueryEvent->set_linux_errno(static_cast<LinuxErrno>(terrno));
478 resolv_stats_add(statp->netid, receivedMdnsAddr, mDnsQueryEvent);
chenbruceceb3c022021-06-15 21:36:19 +0800479
480 if (resplen <= 0) {
481 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
482 return -terrno;
483 }
484 LOG(DEBUG) << __func__ << ": got answer:";
485 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
486
487 if (cache_status == RESOLV_CACHE_NOTFOUND) {
488 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
489 }
490 return resplen;
491 }
492
Mike Yuecc52822020-02-14 14:36:46 +0800493 if (statp->nameserverCount() == 0) {
chenbruceceb3c022021-06-15 21:36:19 +0800494 // We have no nameservers configured and it's not a MDNS resolution, so there's no
495 // point trying. Tell the cache the query failed, or any retries and anyone else
496 // asking the same question will block for PENDING_REQUEST_TIMEOUT seconds instead
497 // of failing fast.
Luke Huangba7bef92018-12-26 16:53:03 +0800498 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800499
500 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900501 errno = ESRCH;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800502 return -ESRCH;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900503 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900504
Luke Huangd1d734f2020-04-30 12:25:40 +0800505 // If parallel_lookup is enabled, it might be required to wait some time to avoid
506 // gateways drop packets if queries are sent too close together
507 if (sleepTimeMs != 0ms) {
508 std::this_thread::sleep_for(sleepTimeMs);
509 }
Luke Huang272cb192019-10-15 16:52:28 +0900510 // DoT
chenbruceceb3c022021-06-15 21:36:19 +0800511 if (!(statp->netcontext_flags & NET_CONTEXT_FLAG_USE_LOCAL_NAMESERVERS) &&
512 !isMdnsResolution(statp->_flags)) {
Luke Huang272cb192019-10-15 16:52:28 +0900513 bool fallback = false;
Luke Huang43cc1b12019-10-15 19:06:42 +0900514 int resplen = res_tls_send(statp, Slice(const_cast<uint8_t*>(buf), buflen),
515 Slice(ans, anssiz), rcode, &fallback);
Luke Huang272cb192019-10-15 16:52:28 +0900516 if (resplen > 0) {
517 LOG(DEBUG) << __func__ << ": got answer from DoT";
518 res_pquery(ans, resplen);
519 if (cache_status == RESOLV_CACHE_NOTFOUND) {
520 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
521 }
522 return resplen;
523 }
524 if (!fallback) {
525 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huang43cc1b12019-10-15 19:06:42 +0900526 return -ETIMEDOUT;
Luke Huang272cb192019-10-15 16:52:28 +0900527 }
528 }
529
Mike Yuc573a3d2020-02-07 20:15:15 +0800530 res_stats stats[MAXNS]{};
Bernie Innocenti758005f2019-02-19 18:08:36 +0900531 res_params params;
Mike Yuc573a3d2020-02-07 20:15:15 +0800532 int revision_id = resolv_cache_get_resolver_stats(statp->netid, &params, stats, statp->nsaddrs);
lifra1b37f12019-02-13 17:33:57 +0800533 if (revision_id < 0) {
534 // TODO: Remove errno once callers stop using it
535 errno = ESRCH;
536 return -ESRCH;
537 }
chenbruceceb3c022021-06-15 21:36:19 +0800538
waynema0161acd2019-02-18 17:47:59 +0800539 bool usable_servers[MAXNS];
Luke Huang70931aa2019-01-31 11:57:41 +0800540 int usableServersCount = android_net_res_stats_get_usable_servers(
Mike Yuecc52822020-02-14 14:36:46 +0800541 &params, stats, statp->nameserverCount(), usable_servers);
Luke Huang70931aa2019-01-31 11:57:41 +0800542
Mike Yu61d17262020-02-15 18:56:22 +0800543 if (statp->sort_nameservers) {
544 // It's unnecessary to mark a DNS server as unusable since broken servers will be less
545 // likely to be chosen.
546 for (int i = 0; i < statp->nameserverCount(); i++) {
547 usable_servers[i] = true;
548 }
549 }
550
551 // TODO: Let it always choose the first nameserver when sort_nameservers is enabled.
Luke Huang70931aa2019-01-31 11:57:41 +0800552 if ((flags & ANDROID_RESOLV_NO_RETRY) && usableServersCount > 1) {
553 auto hp = reinterpret_cast<const HEADER*>(buf);
554
555 // Select a random server based on the query id
556 int selectedServer = (hp->id % usableServersCount) + 1;
Mike Yuecc52822020-02-14 14:36:46 +0800557 res_set_usable_server(selectedServer, statp->nameserverCount(), usable_servers);
Luke Huang70931aa2019-01-31 11:57:41 +0800558 }
waynema0161acd2019-02-18 17:47:59 +0800559
Luke Huang43cc1b12019-10-15 19:06:42 +0900560 // Send request, RETRY times, or until successful.
waynemaa74195e2019-01-18 14:02:31 +0800561 int retryTimes = (flags & ANDROID_RESOLV_NO_RETRY) ? 1 : params.retry_count;
Luke Huang43cc1b12019-10-15 19:06:42 +0900562 int useTcp = buflen > PACKETSZ;
563 int gotsomewhere = 0;
chenbruceceb3c022021-06-15 21:36:19 +0800564
Luke Huang23d55192020-04-16 11:47:30 +0800565 // Use an impossible error code as default value
566 int terrno = ETIME;
chenbruceceb3c022021-06-15 21:36:19 +0800567 // plaintext DNS
Luke Huangba7bef92018-12-26 16:53:03 +0800568 for (int attempt = 0; attempt < retryTimes; ++attempt) {
Mike Yue48f7b52020-02-10 14:55:06 +0800569 for (size_t ns = 0; ns < statp->nsaddrs.size(); ++ns) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900570 if (!usable_servers[ns]) continue;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900571
Luke Huang43cc1b12019-10-15 19:06:42 +0900572 *rcode = RCODE_INTERNAL_ERROR;
573
574 // Get server addr
Mike Yue48f7b52020-02-10 14:55:06 +0800575 const IPSockAddr& serverSockAddr = statp->nsaddrs[ns];
576 LOG(DEBUG) << __func__ << ": Querying server (# " << ns + 1
577 << ") address = " << serverSockAddr.toString();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900578
Luke Huang43cc1b12019-10-15 19:06:42 +0900579 ::android::net::Protocol query_proto = useTcp ? PROTO_TCP : PROTO_UDP;
Luke Huang420ee622019-11-27 17:52:44 +0800580 time_t query_time = 0;
Luke Huang43cc1b12019-10-15 19:06:42 +0900581 int delay = 0;
582 bool fallbackTCP = false;
583 const bool shouldRecordStats = (attempt == 0);
584 int resplen;
lifrd4d9fbb2019-07-31 20:18:35 +0800585 Stopwatch queryStopwatch;
lifr128183a2020-01-08 18:04:50 +0800586 int retry_count_for_event = 0;
Luke Huang420ee622019-11-27 17:52:44 +0800587 size_t actualNs = ns;
Luke Huang23d55192020-04-16 11:47:30 +0800588 // Use an impossible error code as default value
589 terrno = ETIME;
Luke Huang43cc1b12019-10-15 19:06:42 +0900590 if (useTcp) {
591 // TCP; at most one attempt per server.
Luke Huangba7bef92018-12-26 16:53:03 +0800592 attempt = retryTimes;
Luke Huang420ee622019-11-27 17:52:44 +0800593 resplen = send_vc(statp, &params, buf, buflen, ans, anssiz, &terrno, ns,
594 &query_time, rcode, &delay);
Ken Chen99344882020-01-01 14:59:38 +0800595
596 if (buflen <= PACKETSZ && resplen <= 0 &&
597 statp->tc_mode == aidl::android::net::IDnsResolver::TC_MODE_UDP_TCP) {
598 // reset to UDP for next query on next DNS server if resolver is currently doing
599 // TCP fallback retry and current server does not support TCP connectin
600 useTcp = false;
601 }
Luke Huangeb618ef2020-05-26 14:17:02 +0800602 LOG(INFO) << __func__ << ": used send_vc " << resplen << " terrno: " << terrno;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900603 } else {
Luke Huang43cc1b12019-10-15 19:06:42 +0900604 // UDP
Luke Huang420ee622019-11-27 17:52:44 +0800605 resplen = send_dg(statp, &params, buf, buflen, ans, anssiz, &terrno, &actualNs,
606 &useTcp, &gotsomewhere, &query_time, rcode, &delay);
Luke Huang43cc1b12019-10-15 19:06:42 +0900607 fallbackTCP = useTcp ? true : false;
lifr128183a2020-01-08 18:04:50 +0800608 retry_count_for_event = attempt;
Luke Huangeb618ef2020-05-26 14:17:02 +0800609 LOG(INFO) << __func__ << ": used send_dg " << resplen << " terrno: " << terrno;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900610 }
Luke Huang43cc1b12019-10-15 19:06:42 +0900611
Luke Huang420ee622019-11-27 17:52:44 +0800612 const IPSockAddr& receivedServerAddr = statp->nsaddrs[actualNs];
Luke Huang43cc1b12019-10-15 19:06:42 +0900613 DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
614 dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
Luke Huang420ee622019-11-27 17:52:44 +0800615 // When |retryTimes| > 1, we cannot actually know the correct latency value if we
616 // received the answer from the previous server. So temporarily set the latency as -1 if
617 // that condition happened.
618 // TODO: make the latency value accurate.
619 dnsQueryEvent->set_latency_micros(
620 (actualNs == ns) ? saturate_cast<int32_t>(queryStopwatch.timeTakenUs()) : -1);
621 dnsQueryEvent->set_dns_server_index(actualNs);
622 dnsQueryEvent->set_ip_version(ipFamilyToIPVersion(receivedServerAddr.family()));
lifr128183a2020-01-08 18:04:50 +0800623 dnsQueryEvent->set_retry_times(retry_count_for_event);
Luke Huang43cc1b12019-10-15 19:06:42 +0900624 dnsQueryEvent->set_rcode(static_cast<NsRcode>(*rcode));
625 dnsQueryEvent->set_protocol(query_proto);
626 dnsQueryEvent->set_type(getQueryType(buf, buflen));
Luke Huang23d55192020-04-16 11:47:30 +0800627 dnsQueryEvent->set_linux_errno(static_cast<LinuxErrno>(terrno));
Luke Huang43cc1b12019-10-15 19:06:42 +0900628
629 // Only record stats the first time we try a query. This ensures that
630 // queries that deterministically fail (e.g., a name that always returns
631 // SERVFAIL or times out) do not unduly affect the stats.
632 if (shouldRecordStats) {
Luke Huangeb618ef2020-05-26 14:17:02 +0800633 // (b/151166599): This is a workaround to prevent that DnsResolver calculates the
634 // reliability of DNS servers from being broken when network restricted mode is
635 // enabled.
636 // TODO: Introduce the new server selection instead of skipping stats recording.
637 if (!isNetworkRestricted(terrno)) {
638 res_sample sample;
639 res_stats_set_sample(&sample, query_time, *rcode, delay);
640 // KeepListening UDP mechanism is incompatible with usable_servers of legacy
641 // stats, so keep the old logic for now.
642 // TODO: Replace usable_servers of legacy stats with new one.
643 resolv_cache_add_resolver_stats_sample(
644 statp->netid, revision_id, serverSockAddr, sample, params.max_samples);
Mike Yu30e0de92021-05-07 11:48:46 +0800645 resolv_stats_add(statp->netid, receivedServerAddr, dnsQueryEvent);
Luke Huangeb618ef2020-05-26 14:17:02 +0800646 }
Luke Huang43cc1b12019-10-15 19:06:42 +0900647 }
648
649 if (resplen == 0) continue;
650 if (fallbackTCP) {
651 ns--;
652 continue;
653 }
654 if (resplen < 0) {
655 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800656 statp->closeSockets();
Luke Huang43cc1b12019-10-15 19:06:42 +0900657 return -terrno;
chenbruceceb3c022021-06-15 21:36:19 +0800658 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900659
Ken Chenffc224a2019-03-19 17:41:28 +0800660 LOG(DEBUG) << __func__ << ": got answer:";
chenbrucedd210722019-03-06 13:52:43 +0800661 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900662
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900663 if (cache_status == RESOLV_CACHE_NOTFOUND) {
Mike Yud1ec2542019-06-06 17:17:53 +0800664 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900665 }
Luke Huangadb0f5b2019-11-27 15:51:48 +0800666 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900667 return (resplen);
Bernie Innocenti9c575932018-09-07 21:10:25 +0900668 } // for each ns
669 } // for each retry
Luke Huangadb0f5b2019-11-27 15:51:48 +0800670 statp->closeSockets();
Luke Huang43cc1b12019-10-15 19:06:42 +0900671 terrno = useTcp ? terrno : gotsomewhere ? ETIMEDOUT : ECONNREFUSED;
672 // TODO: Remove errno once callers stop using it
673 errno = useTcp ? terrno
674 : gotsomewhere ? ETIMEDOUT /* no answer obtained */
675 : ECONNREFUSED /* no nameservers found */;
676
Luke Huangba7bef92018-12-26 16:53:03 +0800677 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800678 return -terrno;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900679}
680
chenbruceceb3c022021-06-15 21:36:19 +0800681static struct timespec get_timeout(res_state statp, const res_params* params, const int addrIndex) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900682 int msec;
chenbruceceb3c022021-06-15 21:36:19 +0800683 msec = params->base_timeout_msec << addrIndex;
waynemaa74195e2019-01-18 14:02:31 +0800684 // Legacy algorithm which scales the timeout by nameserver number.
685 // For instance, with 4 nameservers: 5s, 2.5s, 5s, 10s
686 // This has no effect with 1 or 2 nameservers
chenbruceceb3c022021-06-15 21:36:19 +0800687 if (addrIndex > 0) {
Mike Yuecc52822020-02-14 14:36:46 +0800688 msec /= statp->nameserverCount();
waynemaa74195e2019-01-18 14:02:31 +0800689 }
690 // For safety, don't allow OEMs and experiments to configure a timeout shorter than 1s.
691 if (msec < 1000) {
692 msec = 1000; // Use at least 1000ms
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900693 }
Ken Chenffc224a2019-03-19 17:41:28 +0800694 LOG(INFO) << __func__ << ": using timeout of " << msec << " msec";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900695
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900696 struct timespec result;
697 result.tv_sec = msec / 1000;
698 result.tv_nsec = (msec % 1000) * 1000000;
699 return result;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900700}
701
chenbrucec51f1212019-09-12 16:59:33 +0800702static int send_vc(res_state statp, res_params* params, const uint8_t* buf, int buflen,
Mike Yue48f7b52020-02-10 14:55:06 +0800703 uint8_t* ans, int anssiz, int* terrno, size_t ns, time_t* at, int* rcode,
chenbrucec51f1212019-09-12 16:59:33 +0800704 int* delay) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900705 *at = time(NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900706 *delay = 0;
707 const HEADER* hp = (const HEADER*) (const void*) buf;
708 HEADER* anhp = (HEADER*) (void*) ans;
709 struct sockaddr* nsap;
710 int nsaplen;
chenbruce0d470422019-03-28 18:44:37 +0800711 int truncating, connreset, n;
chenbrucec51f1212019-09-12 16:59:33 +0800712 uint8_t* cp;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900713
Ken Chenffc224a2019-03-19 17:41:28 +0800714 LOG(INFO) << __func__ << ": using send_vc";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900715
Mike Yue48f7b52020-02-10 14:55:06 +0800716 // It should never happen, but just in case.
717 if (ns >= statp->nsaddrs.size()) {
718 LOG(ERROR) << __func__ << ": Out-of-bound indexing: " << ns;
Luke Huang23d55192020-04-16 11:47:30 +0800719 *terrno = EINVAL;
Mike Yue48f7b52020-02-10 14:55:06 +0800720 return -1;
721 }
722
723 sockaddr_storage ss = statp->nsaddrs[ns];
724 nsap = reinterpret_cast<sockaddr*>(&ss);
Mike Yu021c3e12019-10-08 17:29:34 +0800725 nsaplen = sockaddrSize(nsap);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900726
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900727 connreset = 0;
728same_ns:
729 truncating = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900730
Luke Huang420ee622019-11-27 17:52:44 +0800731 struct timespec start_time = evNowTime();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900732
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900733 /* Are we still talking to whom we want to talk to? */
Luke Huangadb0f5b2019-11-27 15:51:48 +0800734 if (statp->tcp_nssock >= 0 && (statp->_flags & RES_F_VC) != 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900735 struct sockaddr_storage peer;
736 socklen_t size = sizeof peer;
737 unsigned old_mark;
738 socklen_t mark_size = sizeof(old_mark);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800739 if (getpeername(statp->tcp_nssock, (struct sockaddr*)(void*)&peer, &size) < 0 ||
740 !sock_eq((struct sockaddr*)(void*)&peer, nsap) ||
741 getsockopt(statp->tcp_nssock, SOL_SOCKET, SO_MARK, &old_mark, &mark_size) < 0 ||
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900742 old_mark != statp->_mark) {
Luke Huangadb0f5b2019-11-27 15:51:48 +0800743 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900744 }
745 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900746
Luke Huangadb0f5b2019-11-27 15:51:48 +0800747 if (statp->tcp_nssock < 0 || (statp->_flags & RES_F_VC) == 0) {
748 if (statp->tcp_nssock >= 0) statp->closeSockets();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900749
Luke Huangadb0f5b2019-11-27 15:51:48 +0800750 statp->tcp_nssock.reset(socket(nsap->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0));
751 if (statp->tcp_nssock < 0) {
Luke Huang23d55192020-04-16 11:47:30 +0800752 *terrno = errno;
753 PLOG(DEBUG) << __func__ << ": socket(vc): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900754 switch (errno) {
755 case EPROTONOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900756 case EPFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900757 case EAFNOSUPPORT:
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900758 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900759 default:
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900760 return -1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900761 }
762 }
Ken Chenbc481b82020-05-21 23:30:01 +0800763 const uid_t uid = statp->enforce_dns_uid ? AID_DNS : statp->uid;
764 resolv_tag_socket(statp->tcp_nssock, uid, statp->pid);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900765 if (statp->_mark != MARK_UNSET) {
Luke Huangadb0f5b2019-11-27 15:51:48 +0800766 if (setsockopt(statp->tcp_nssock, SOL_SOCKET, SO_MARK, &statp->_mark,
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900767 sizeof(statp->_mark)) < 0) {
768 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800769 PLOG(DEBUG) << __func__ << ": setsockopt: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900770 return -1;
771 }
772 }
773 errno = 0;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800774 if (random_bind(statp->tcp_nssock, nsap->sa_family) < 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900775 *terrno = errno;
chenbruce76620642021-06-15 18:39:27 +0800776 dump_error("bind/vc", nsap);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800777 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900778 return (0);
779 }
Luke Huangadb0f5b2019-11-27 15:51:48 +0800780 if (connect_with_timeout(statp->tcp_nssock, nsap, (socklen_t)nsaplen,
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900781 get_timeout(statp, params, ns)) < 0) {
782 *terrno = errno;
chenbruce76620642021-06-15 18:39:27 +0800783 dump_error("connect/vc", nsap);
Luke Huangadb0f5b2019-11-27 15:51:48 +0800784 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900785 /*
786 * The way connect_with_timeout() is implemented prevents us from reliably
787 * determining whether this was really a timeout or e.g. ECONNREFUSED. Since
788 * currently both cases are handled in the same way, there is no need to
789 * change this (yet). If we ever need to reliably distinguish between these
790 * cases, both connect_with_timeout() and retrying_poll() need to be
791 * modified, though.
792 */
793 *rcode = RCODE_TIMEOUT;
794 return (0);
795 }
796 statp->_flags |= RES_F_VC;
797 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900798
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900799 /*
800 * Send length & message
801 */
chenbruce0d470422019-03-28 18:44:37 +0800802 uint16_t len = htons(static_cast<uint16_t>(buflen));
Luke Huangc98fd802019-10-15 16:36:36 +0900803 const iovec iov[] = {
804 {.iov_base = &len, .iov_len = INT16SZ},
805 {.iov_base = const_cast<uint8_t*>(buf), .iov_len = static_cast<size_t>(buflen)},
806 };
Luke Huangadb0f5b2019-11-27 15:51:48 +0800807 if (writev(statp->tcp_nssock, iov, 2) != (INT16SZ + buflen)) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900808 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800809 PLOG(DEBUG) << __func__ << ": write failed: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800810 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900811 return (0);
812 }
813 /*
814 * Receive length & response
815 */
816read_len:
817 cp = ans;
818 len = INT16SZ;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800819 while ((n = read(statp->tcp_nssock, (char*)cp, (size_t)len)) > 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900820 cp += n;
821 if ((len -= n) == 0) break;
822 }
823 if (n <= 0) {
824 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800825 PLOG(DEBUG) << __func__ << ": read failed: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800826 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900827 /*
828 * A long running process might get its TCP
829 * connection reset if the remote server was
830 * restarted. Requery the server instead of
831 * trying a new one. When there is only one
832 * server, this means that a query might work
833 * instead of failing. We only allow one reset
834 * per query to prevent looping.
835 */
836 if (*terrno == ECONNRESET && !connreset) {
837 connreset = 1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900838 goto same_ns;
839 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900840 return (0);
841 }
chenbruce0d470422019-03-28 18:44:37 +0800842 uint16_t resplen = ntohs(*reinterpret_cast<const uint16_t*>(ans));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900843 if (resplen > anssiz) {
Ken Chenffc224a2019-03-19 17:41:28 +0800844 LOG(DEBUG) << __func__ << ": response truncated";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900845 truncating = 1;
846 len = anssiz;
847 } else
848 len = resplen;
849 if (len < HFIXEDSZ) {
850 /*
851 * Undersized message.
852 */
Ken Chenffc224a2019-03-19 17:41:28 +0800853 LOG(DEBUG) << __func__ << ": undersized: " << len;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900854 *terrno = EMSGSIZE;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800855 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900856 return (0);
857 }
858 cp = ans;
Luke Huangadb0f5b2019-11-27 15:51:48 +0800859 while (len != 0 && (n = read(statp->tcp_nssock, (char*)cp, (size_t)len)) > 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900860 cp += n;
861 len -= n;
862 }
863 if (n <= 0) {
864 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800865 PLOG(DEBUG) << __func__ << ": read(vc): ";
Luke Huangadb0f5b2019-11-27 15:51:48 +0800866 statp->closeSockets();
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900867 return (0);
868 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900869
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900870 if (truncating) {
871 /*
872 * Flush rest of answer so connection stays in synch.
873 */
874 anhp->tc = 1;
875 len = resplen - anssiz;
876 while (len != 0) {
877 char junk[PACKETSZ];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900878
Luke Huangadb0f5b2019-11-27 15:51:48 +0800879 n = read(statp->tcp_nssock, junk, (len > sizeof junk) ? sizeof junk : len);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900880 if (n > 0)
881 len -= n;
882 else
883 break;
884 }
Ken Chena9e6f1d2020-07-30 13:24:16 +0800885 LOG(WARNING) << __func__ << ": resplen " << resplen << " exceeds buf size " << anssiz;
886 // return size should never exceed container size
887 resplen = anssiz;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900888 }
889 /*
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900890 * If the calling application has bailed out of
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900891 * a previous call and failed to arrange to have
892 * the circuit closed or the server has got
893 * itself confused, then drop the packet and
894 * wait for the correct one.
895 */
896 if (hp->id != anhp->id) {
Ken Chenffc224a2019-03-19 17:41:28 +0800897 LOG(DEBUG) << __func__ << ": ld answer (unexpected):";
Ken Chena9e6f1d2020-07-30 13:24:16 +0800898 res_pquery(ans, resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900899 goto read_len;
900 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900901
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900902 /*
903 * All is well, or the error is fatal. Signal that the
904 * next nameserver ought not be tried.
905 */
906 if (resplen > 0) {
907 struct timespec done = evNowTime();
Luke Huang420ee622019-11-27 17:52:44 +0800908 *delay = res_stats_calculate_rtt(&done, &start_time);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900909 *rcode = anhp->rcode;
910 }
Luke Huang23d55192020-04-16 11:47:30 +0800911 *terrno = 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900912 return (resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900913}
914
915/* return -1 on error (errno set), 0 on success */
Luke Huangc98fd802019-10-15 16:36:36 +0900916static int connect_with_timeout(int sock, const sockaddr* nsap, socklen_t salen,
917 const timespec timeout) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900918 int res, origflags;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900919
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900920 origflags = fcntl(sock, F_GETFL, 0);
921 fcntl(sock, F_SETFL, origflags | O_NONBLOCK);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900922
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900923 res = connect(sock, nsap, salen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900924 if (res < 0 && errno != EINPROGRESS) {
925 res = -1;
926 goto done;
927 }
928 if (res != 0) {
Luke Huangc98fd802019-10-15 16:36:36 +0900929 timespec now = evNowTime();
930 timespec finish = evAddTime(now, timeout);
Ken Chenffc224a2019-03-19 17:41:28 +0800931 LOG(INFO) << __func__ << ": " << sock << " send_vc";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900932 res = retrying_poll(sock, POLLIN | POLLOUT, &finish);
933 if (res <= 0) {
934 res = -1;
935 }
936 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900937done:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900938 fcntl(sock, F_SETFL, origflags);
Ken Chenffc224a2019-03-19 17:41:28 +0800939 LOG(INFO) << __func__ << ": " << sock << " connect_with_const timeout returning " << res;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900940 return res;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900941}
942
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900943static int retrying_poll(const int sock, const short events, const struct timespec* finish) {
944 struct timespec now, timeout;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900945
946retry:
Ken Chenffc224a2019-03-19 17:41:28 +0800947 LOG(INFO) << __func__ << ": " << sock << " retrying_poll";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900948
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900949 now = evNowTime();
950 if (evCmpTime(*finish, now) > 0)
951 timeout = evSubTime(*finish, now);
952 else
953 timeout = evConsTime(0L, 0L);
954 struct pollfd fds = {.fd = sock, .events = events};
Maciej Żenczykowski88f87552020-04-23 08:48:36 -0700955 int n = ppoll(&fds, 1, &timeout, /*__mask=*/NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900956 if (n == 0) {
Luke Huang420ee622019-11-27 17:52:44 +0800957 LOG(INFO) << __func__ << ": " << sock << " retrying_poll timeout";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900958 errno = ETIMEDOUT;
959 return 0;
960 }
961 if (n < 0) {
962 if (errno == EINTR) goto retry;
Ken Chenffc224a2019-03-19 17:41:28 +0800963 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll failed";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900964 return n;
965 }
966 if (fds.revents & (POLLIN | POLLOUT | POLLERR)) {
967 int error;
968 socklen_t len = sizeof(error);
969 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error) {
970 errno = error;
Ken Chenffc224a2019-03-19 17:41:28 +0800971 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll getsockopt failed";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900972 return -1;
973 }
974 }
Ken Chenffc224a2019-03-19 17:41:28 +0800975 LOG(INFO) << __func__ << ": " << sock << " retrying_poll returning " << n;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900976 return n;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900977}
978
Luke Huang420ee622019-11-27 17:52:44 +0800979static std::vector<pollfd> extractUdpFdset(res_state statp, const short events = POLLIN) {
980 std::vector<pollfd> fdset(statp->nsaddrs.size());
981 for (size_t i = 0; i < statp->nsaddrs.size(); ++i) {
chenbrucecc9bbc02021-06-15 17:38:14 +0800982 fdset[i] = {.fd = statp->udpsocks[i], .events = events};
Luke Huang420ee622019-11-27 17:52:44 +0800983 }
984 return fdset;
985}
986
987static Result<std::vector<int>> udpRetryingPoll(res_state statp, const timespec* finish) {
988 for (;;) {
989 LOG(DEBUG) << __func__ << ": poll";
990 timespec start_time = evNowTime();
991 timespec timeout = (evCmpTime(*finish, start_time) > 0) ? evSubTime(*finish, start_time)
992 : evConsTime(0L, 0L);
993 std::vector<pollfd> fdset = extractUdpFdset(statp);
Maciej Żenczykowski88f87552020-04-23 08:48:36 -0700994 const int n = ppoll(fdset.data(), fdset.size(), &timeout, /*__mask=*/nullptr);
Luke Huang420ee622019-11-27 17:52:44 +0800995 if (n <= 0) {
996 if (errno == EINTR && n < 0) continue;
997 if (n == 0) errno = ETIMEDOUT;
998 PLOG(INFO) << __func__ << ": failed";
999 return ErrnoError();
1000 }
1001 std::vector<int> fdsToRead;
1002 for (const auto& pollfd : fdset) {
1003 if (pollfd.revents & (POLLIN | POLLERR)) {
1004 fdsToRead.push_back(pollfd.fd);
1005 }
1006 }
1007 LOG(DEBUG) << __func__ << ": "
1008 << " returning fd size: " << fdsToRead.size();
1009 return fdsToRead;
1010 }
1011}
1012
chenbruceceb3c022021-06-15 21:36:19 +08001013static Result<std::vector<int>> udpRetryingPollWrapper(res_state statp, int addrInfo,
Luke Huang420ee622019-11-27 17:52:44 +08001014 const timespec* finish) {
Luke Huangf40df9c2020-04-21 08:51:48 +08001015 const bool keepListeningUdp =
1016 android::net::Experiments::getInstance()->getFlag("keep_listening_udp", 0);
Luke Huang420ee622019-11-27 17:52:44 +08001017 if (keepListeningUdp) return udpRetryingPoll(statp, finish);
1018
chenbruceceb3c022021-06-15 21:36:19 +08001019 if (int n = retrying_poll(statp->udpsocks[addrInfo], POLLIN, finish); n <= 0) {
Luke Huang420ee622019-11-27 17:52:44 +08001020 return ErrnoError();
1021 }
chenbruceceb3c022021-06-15 21:36:19 +08001022 return std::vector<int>{statp->udpsocks[addrInfo]};
Luke Huang420ee622019-11-27 17:52:44 +08001023}
1024
Luke Huangbff43fc2019-11-12 15:54:47 +08001025bool ignoreInvalidAnswer(res_state statp, const sockaddr_storage& from, const uint8_t* buf,
Luke Huang420ee622019-11-27 17:52:44 +08001026 int buflen, uint8_t* ans, int anssiz, int* receivedFromNs) {
Luke Huangbff43fc2019-11-12 15:54:47 +08001027 const HEADER* hp = (const HEADER*)(const void*)buf;
1028 HEADER* anhp = (HEADER*)(void*)ans;
1029 if (hp->id != anhp->id) {
1030 // response from old query, ignore it.
1031 LOG(DEBUG) << __func__ << ": old answer:";
1032 return true;
1033 }
Luke Huang420ee622019-11-27 17:52:44 +08001034 if (*receivedFromNs = res_ourserver_p(statp, (sockaddr*)(void*)&from); *receivedFromNs < 0) {
Luke Huangbff43fc2019-11-12 15:54:47 +08001035 // response from wrong server? ignore it.
1036 LOG(DEBUG) << __func__ << ": not our server:";
1037 return true;
1038 }
1039 if (!res_queriesmatch(buf, buf + buflen, ans, ans + anssiz)) {
1040 // response contains wrong query? ignore it.
1041 LOG(DEBUG) << __func__ << ": wrong query name:";
1042 return true;
1043 }
1044 return false;
1045}
1046
chenbruceceb3c022021-06-15 21:36:19 +08001047// return 1 - setup udp socket success.
1048// return 0 - bind error, protocol error.
1049// return -1 - create socket fail, except |EPROTONOSUPPORT| EPFNOSUPPORT |EAFNOSUPPORT|.
1050// set socket option fail.
1051static int setupUdpSocket(ResState* statp, const sockaddr* sockap, unique_fd* fd_out, int* terrno) {
1052 fd_out->reset(socket(sockap->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0));
chenbruceb1aa65a2021-06-15 19:37:05 +08001053
chenbruceceb3c022021-06-15 21:36:19 +08001054 if (*fd_out < 0) {
chenbruceb1aa65a2021-06-15 19:37:05 +08001055 *terrno = errno;
1056 PLOG(ERROR) << __func__ << ": socket: ";
1057 switch (errno) {
1058 case EPROTONOSUPPORT:
1059 case EPFNOSUPPORT:
1060 case EAFNOSUPPORT:
1061 return 0;
1062 default:
1063 return -1;
1064 }
1065 }
1066 const uid_t uid = statp->enforce_dns_uid ? AID_DNS : statp->uid;
chenbruceceb3c022021-06-15 21:36:19 +08001067 resolv_tag_socket(*fd_out, uid, statp->pid);
chenbruceb1aa65a2021-06-15 19:37:05 +08001068 if (statp->_mark != MARK_UNSET) {
chenbruceceb3c022021-06-15 21:36:19 +08001069 if (setsockopt(*fd_out, SOL_SOCKET, SO_MARK, &(statp->_mark), sizeof(statp->_mark)) < 0) {
chenbruceb1aa65a2021-06-15 19:37:05 +08001070 *terrno = errno;
chenbruceb1aa65a2021-06-15 19:37:05 +08001071 return -1;
1072 }
1073 }
1074
chenbruceceb3c022021-06-15 21:36:19 +08001075 if (random_bind(*fd_out, sockap->sa_family) < 0) {
chenbruceb1aa65a2021-06-15 19:37:05 +08001076 *terrno = errno;
1077 dump_error("bind", sockap);
chenbruceb1aa65a2021-06-15 19:37:05 +08001078 return 0;
1079 }
1080 return 1;
1081}
1082
chenbrucec51f1212019-09-12 16:59:33 +08001083static int send_dg(res_state statp, res_params* params, const uint8_t* buf, int buflen,
Luke Huang420ee622019-11-27 17:52:44 +08001084 uint8_t* ans, int anssiz, int* terrno, size_t* ns, int* v_circuit,
Mike Yue48f7b52020-02-10 14:55:06 +08001085 int* gotsomewhere, time_t* at, int* rcode, int* delay) {
1086 // It should never happen, but just in case.
Luke Huang420ee622019-11-27 17:52:44 +08001087 if (*ns >= statp->nsaddrs.size()) {
Mike Yue48f7b52020-02-10 14:55:06 +08001088 LOG(ERROR) << __func__ << ": Out-of-bound indexing: " << ns;
Luke Huang23d55192020-04-16 11:47:30 +08001089 *terrno = EINVAL;
Mike Yue48f7b52020-02-10 14:55:06 +08001090 return -1;
1091 }
1092
Luke Huangbff43fc2019-11-12 15:54:47 +08001093 *at = time(nullptr);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001094 *delay = 0;
Luke Huang420ee622019-11-27 17:52:44 +08001095 const sockaddr_storage ss = statp->nsaddrs[*ns];
Mike Yue48f7b52020-02-10 14:55:06 +08001096 const sockaddr* nsap = reinterpret_cast<const sockaddr*>(&ss);
Luke Huangbff43fc2019-11-12 15:54:47 +08001097
chenbrucecc9bbc02021-06-15 17:38:14 +08001098 if (statp->udpsocks[*ns] == -1) {
chenbruceceb3c022021-06-15 21:36:19 +08001099 int result = setupUdpSocket(statp, nsap, &statp->udpsocks[*ns], terrno);
chenbruceb1aa65a2021-06-15 19:37:05 +08001100 if (result <= 0) return result;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001101
chenbruceb9cce7b2019-07-15 16:14:53 +08001102 // Use a "connected" datagram socket to receive an ECONNREFUSED error
1103 // on the next socket operation when the server responds with an
1104 // ICMP port-unreachable error. This way we can detect the absence of
1105 // a nameserver without timing out.
chenbruceb1aa65a2021-06-15 19:37:05 +08001106 if (connect(statp->udpsocks[*ns], nsap, sockaddrSize(nsap)) < 0) {
Luke Huang23d55192020-04-16 11:47:30 +08001107 *terrno = errno;
chenbruce76620642021-06-15 18:39:27 +08001108 dump_error("connect(dg)", nsap);
Luke Huangadb0f5b2019-11-27 15:51:48 +08001109 statp->closeSockets();
chenbruceceb3c022021-06-15 21:36:19 +08001110 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001111 }
Ken Chenffc224a2019-03-19 17:41:28 +08001112 LOG(DEBUG) << __func__ << ": new DG socket";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001113 }
chenbrucecc9bbc02021-06-15 17:38:14 +08001114 if (send(statp->udpsocks[*ns], (const char*)buf, (size_t)buflen, 0) != buflen) {
Luke Huang23d55192020-04-16 11:47:30 +08001115 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +08001116 PLOG(DEBUG) << __func__ << ": send: ";
Luke Huangadb0f5b2019-11-27 15:51:48 +08001117 statp->closeSockets();
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001118 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001119 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001120
Luke Huang420ee622019-11-27 17:52:44 +08001121 timespec timeout = get_timeout(statp, params, *ns);
1122 timespec start_time = evNowTime();
1123 timespec finish = evAddTime(start_time, timeout);
Luke Huangbff43fc2019-11-12 15:54:47 +08001124 for (;;) {
1125 // Wait for reply.
Luke Huang420ee622019-11-27 17:52:44 +08001126 auto result = udpRetryingPollWrapper(statp, *ns, &finish);
1127
1128 if (!result.has_value()) {
1129 const bool isTimeout = (result.error().code() == ETIMEDOUT);
1130 *rcode = (isTimeout) ? RCODE_TIMEOUT : *rcode;
Luke Huang23d55192020-04-16 11:47:30 +08001131 *terrno = (isTimeout) ? ETIMEDOUT : errno;
Luke Huang420ee622019-11-27 17:52:44 +08001132 *gotsomewhere = (isTimeout) ? 1 : *gotsomewhere;
1133 // Leave the UDP sockets open on timeout so we can keep listening for
1134 // a late response from this server while retrying on the next server.
1135 if (!isTimeout) statp->closeSockets();
1136 LOG(DEBUG) << __func__ << ": " << (isTimeout) ? "timeout" : "poll";
1137 return 0;
1138 }
1139 bool needRetry = false;
1140 for (int fd : result.value()) {
1141 needRetry = false;
1142 sockaddr_storage from;
1143 socklen_t fromlen = sizeof(from);
1144 int resplen =
1145 recvfrom(fd, (char*)ans, (size_t)anssiz, 0, (sockaddr*)(void*)&from, &fromlen);
1146 if (resplen <= 0) {
Luke Huang23d55192020-04-16 11:47:30 +08001147 *terrno = errno;
Luke Huang420ee622019-11-27 17:52:44 +08001148 PLOG(DEBUG) << __func__ << ": recvfrom: ";
1149 continue;
1150 }
Luke Huangbff43fc2019-11-12 15:54:47 +08001151 *gotsomewhere = 1;
Luke Huang420ee622019-11-27 17:52:44 +08001152 if (resplen < HFIXEDSZ) {
1153 // Undersized message.
1154 LOG(DEBUG) << __func__ << ": undersized: " << resplen;
1155 *terrno = EMSGSIZE;
1156 continue;
1157 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001158
Luke Huang420ee622019-11-27 17:52:44 +08001159 int receivedFromNs = *ns;
1160 if (needRetry =
1161 ignoreInvalidAnswer(statp, from, buf, buflen, ans, anssiz, &receivedFromNs);
1162 needRetry) {
1163 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
1164 continue;
1165 }
Luke Huangbff43fc2019-11-12 15:54:47 +08001166
Luke Huang420ee622019-11-27 17:52:44 +08001167 HEADER* anhp = (HEADER*)(void*)ans;
1168 if (anhp->rcode == FORMERR && (statp->netcontext_flags & NET_CONTEXT_FLAG_USE_EDNS)) {
1169 // Do not retry if the server do not understand EDNS0.
1170 // The case has to be captured here, as FORMERR packet do not
1171 // carry query section, hence res_queriesmatch() returns 0.
1172 LOG(DEBUG) << __func__ << ": server rejected query with EDNS0:";
1173 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
1174 // record the error
1175 statp->_flags |= RES_F_EDNS0ERR;
Luke Huang23d55192020-04-16 11:47:30 +08001176 *terrno = EREMOTEIO;
Luke Huang420ee622019-11-27 17:52:44 +08001177 continue;
1178 }
Luke Huangbff43fc2019-11-12 15:54:47 +08001179
Luke Huang420ee622019-11-27 17:52:44 +08001180 timespec done = evNowTime();
1181 *delay = res_stats_calculate_rtt(&done, &start_time);
1182 if (anhp->rcode == SERVFAIL || anhp->rcode == NOTIMP || anhp->rcode == REFUSED) {
1183 LOG(DEBUG) << __func__ << ": server rejected query:";
1184 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
1185 *rcode = anhp->rcode;
1186 continue;
1187 }
1188 if (anhp->tc) {
1189 // To get the rest of answer,
1190 // use TCP with same server.
1191 LOG(DEBUG) << __func__ << ": truncated answer";
Luke Huang23d55192020-04-16 11:47:30 +08001192 *terrno = E2BIG;
Luke Huang420ee622019-11-27 17:52:44 +08001193 *v_circuit = 1;
1194 return 1;
1195 }
1196 // All is well, or the error is fatal. Signal that the
1197 // next nameserver ought not be tried.
Luke Huangbff43fc2019-11-12 15:54:47 +08001198
Luke Huangbff43fc2019-11-12 15:54:47 +08001199 *rcode = anhp->rcode;
Luke Huang420ee622019-11-27 17:52:44 +08001200 *ns = receivedFromNs;
Luke Huang23d55192020-04-16 11:47:30 +08001201 *terrno = 0;
Luke Huang420ee622019-11-27 17:52:44 +08001202 return resplen;
Luke Huangbff43fc2019-11-12 15:54:47 +08001203 }
Luke Huang420ee622019-11-27 17:52:44 +08001204 if (!needRetry) return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001205 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001206}
1207
chenbruceceb3c022021-06-15 21:36:19 +08001208// return length - when receiving valid packets.
1209// return 0 - when mdns packets transfer error.
1210static int send_mdns(ResState* statp, std::span<const uint8_t> buf, uint8_t* ans, int anssiz,
1211 int* terrno, int* rcode) {
1212 const sockaddr_storage ss =
1213 (getQueryType(buf.data(), buf.size()) == T_AAAA) ? mdns_addrs[0] : mdns_addrs[1];
1214 const sockaddr* mdnsap = reinterpret_cast<const sockaddr*>(&ss);
1215 unique_fd fd;
1216
1217 if (setupUdpSocket(statp, mdnsap, &fd, terrno) <= 0) return 0;
1218
1219 if (sendto(fd, buf.data(), buf.size(), 0, mdnsap, sockaddrSize(mdnsap)) != buf.size()) {
1220 *terrno = errno;
1221 return 0;
1222 }
1223 // RFC 6762: Typically, the timeout would also be shortened to two or three seconds.
1224 const struct timespec finish = evAddTime(evNowTime(), {2, 2000000});
1225
1226 // Wait for reply.
1227 if (retrying_poll(fd, POLLIN, &finish) <= 0) {
1228 *terrno = errno;
1229 if (*terrno == ETIMEDOUT) *rcode = RCODE_TIMEOUT;
1230 LOG(ERROR) << __func__ << ": " << (*terrno == ETIMEDOUT) ? "timeout" : "poll";
1231 return 0;
1232 }
1233
1234 sockaddr_storage from;
1235 socklen_t fromlen = sizeof(from);
1236 int resplen = recvfrom(fd, (char*)ans, (size_t)anssiz, 0, (sockaddr*)(void*)&from, &fromlen);
1237
1238 if (resplen <= 0) {
1239 *terrno = errno;
1240 return 0;
1241 }
1242
1243 if (resplen < HFIXEDSZ) {
1244 // Undersized message.
1245 LOG(ERROR) << __func__ << ": undersized: " << resplen;
1246 *terrno = EMSGSIZE;
1247 return 0;
1248 }
1249
1250 HEADER* anhp = (HEADER*)(void*)ans;
1251 if (anhp->tc) {
1252 LOG(DEBUG) << __func__ << ": truncated answer";
1253 *terrno = E2BIG;
1254 return 0;
1255 }
1256
1257 *rcode = anhp->rcode;
1258 *terrno = 0;
1259 return resplen;
1260}
1261
chenbruce76620642021-06-15 18:39:27 +08001262static void dump_error(const char* str, const struct sockaddr* address) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001263 char hbuf[NI_MAXHOST];
1264 char sbuf[NI_MAXSERV];
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001265 constexpr int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
Luke Huangc98fd802019-10-15 16:36:36 +09001266 const int err = errno;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001267
chenbruce018fdb22019-06-12 18:08:04 +08001268 if (!WOULD_LOG(DEBUG)) return;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001269
chenbruce76620642021-06-15 18:39:27 +08001270 if (getnameinfo(address, sockaddrSize(address), hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
1271 niflags)) {
chenbruce018fdb22019-06-12 18:08:04 +08001272 strncpy(hbuf, "?", sizeof(hbuf) - 1);
1273 hbuf[sizeof(hbuf) - 1] = '\0';
1274 strncpy(sbuf, "?", sizeof(sbuf) - 1);
1275 sbuf[sizeof(sbuf) - 1] = '\0';
Elliott Hughes3b8f5902019-03-08 12:02:55 -08001276 }
Luke Huangc98fd802019-10-15 16:36:36 +09001277 errno = err;
chenbruce018fdb22019-06-12 18:08:04 +08001278 PLOG(DEBUG) << __func__ << ": " << str << " ([" << hbuf << "]." << sbuf << "): ";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001279}
1280
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001281static int sock_eq(struct sockaddr* a, struct sockaddr* b) {
1282 struct sockaddr_in *a4, *b4;
1283 struct sockaddr_in6 *a6, *b6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001284
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001285 if (a->sa_family != b->sa_family) return 0;
1286 switch (a->sa_family) {
1287 case AF_INET:
1288 a4 = (struct sockaddr_in*) (void*) a;
1289 b4 = (struct sockaddr_in*) (void*) b;
1290 return a4->sin_port == b4->sin_port && a4->sin_addr.s_addr == b4->sin_addr.s_addr;
1291 case AF_INET6:
1292 a6 = (struct sockaddr_in6*) (void*) a;
1293 b6 = (struct sockaddr_in6*) (void*) b;
1294 return a6->sin6_port == b6->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001295#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001296 a6->sin6_scope_id == b6->sin6_scope_id &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001297#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001298 IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
1299 default:
1300 return 0;
1301 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001302}
Mike Yub601ff72018-11-01 20:07:00 +08001303
lifr6b83a6f2019-07-26 03:17:43 +08001304PrivateDnsModes convertEnumType(PrivateDnsMode privateDnsmode) {
1305 switch (privateDnsmode) {
1306 case PrivateDnsMode::OFF:
1307 return PrivateDnsModes::PDM_OFF;
1308 case PrivateDnsMode::OPPORTUNISTIC:
1309 return PrivateDnsModes::PDM_OPPORTUNISTIC;
1310 case PrivateDnsMode::STRICT:
1311 return PrivateDnsModes::PDM_STRICT;
Mike Yu99b8dc72019-11-22 17:45:31 +08001312 default:
1313 return PrivateDnsModes::PDM_UNKNOWN;
lifr6b83a6f2019-07-26 03:17:43 +08001314 }
lifr6b83a6f2019-07-26 03:17:43 +08001315}
1316
Luke Huangd7aa7b42018-11-21 20:37:50 +08001317static int res_tls_send(res_state statp, const Slice query, const Slice answer, int* rcode,
Mike Yubfb1b342018-11-06 15:42:36 +08001318 bool* fallback) {
1319 int resplen = 0;
Mike Yub601ff72018-11-01 20:07:00 +08001320 const unsigned netId = statp->netid;
Mike Yub601ff72018-11-01 20:07:00 +08001321
Mike Yu60248242020-07-29 16:45:26 +08001322 auto& privateDnsConfiguration = PrivateDnsConfiguration::getInstance();
1323 PrivateDnsStatus privateDnsStatus = privateDnsConfiguration.getStatus(netId);
lifr6b83a6f2019-07-26 03:17:43 +08001324 statp->event->set_private_dns_modes(convertEnumType(privateDnsStatus.mode));
Mike Yubfb1b342018-11-06 15:42:36 +08001325
1326 if (privateDnsStatus.mode == PrivateDnsMode::OFF) {
1327 *fallback = true;
1328 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001329 }
1330
Mike Yu3e829062019-08-07 14:01:14 +08001331 if (privateDnsStatus.validatedServers().empty()) {
Mike Yub601ff72018-11-01 20:07:00 +08001332 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
Mike Yubfb1b342018-11-06 15:42:36 +08001333 *fallback = true;
1334 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001335 } else {
1336 // Sleep and iterate some small number of times checking for the
1337 // arrival of resolved and validated server IP addresses, instead
1338 // of returning an immediate error.
Mike Yu4f3747b2018-12-02 17:54:29 +09001339 // This is needed because as soon as a network becomes the default network, apps will
1340 // send DNS queries on that network. If no servers have yet validated, and we do not
1341 // block those queries, they would immediately fail, causing application-visible errors.
1342 // Note that this can happen even before the network validates, since an unvalidated
1343 // network can become the default network if no validated networks are available.
1344 //
1345 // TODO: see if there is a better way to address this problem, such as buffering the
1346 // queries in a queue or only blocking queries for the first few seconds after a default
1347 // network change.
Mike Yubfb1b342018-11-06 15:42:36 +08001348 for (int i = 0; i < 42; i++) {
1349 std::this_thread::sleep_for(std::chrono::milliseconds(100));
Mike Yu3e829062019-08-07 14:01:14 +08001350 // Calling getStatus() to merely check if there's any validated server seems
1351 // wasteful. Consider adding a new method in PrivateDnsConfiguration for speed ups.
Mike Yu60248242020-07-29 16:45:26 +08001352 if (!privateDnsConfiguration.getStatus(netId).validatedServers().empty()) {
1353 privateDnsStatus = privateDnsConfiguration.getStatus(netId);
Mike Yubfb1b342018-11-06 15:42:36 +08001354 break;
1355 }
1356 }
Mike Yu3e829062019-08-07 14:01:14 +08001357 if (privateDnsStatus.validatedServers().empty()) {
Mike Yubfb1b342018-11-06 15:42:36 +08001358 return -1;
1359 }
Mike Yub601ff72018-11-01 20:07:00 +08001360 }
1361 }
1362
chenbruceacb832c2019-02-20 19:45:50 +08001363 LOG(INFO) << __func__ << ": performing query over TLS";
Mike Yub601ff72018-11-01 20:07:00 +08001364
Mike Yu9e8cf8d2020-10-26 19:04:33 +08001365 const auto response = DnsTlsDispatcher::getInstance().query(privateDnsStatus.validatedServers(),
1366 statp, query, answer, &resplen);
Mike Yub601ff72018-11-01 20:07:00 +08001367
chenbruceacb832c2019-02-20 19:45:50 +08001368 LOG(INFO) << __func__ << ": TLS query result: " << static_cast<int>(response);
Mike Yub601ff72018-11-01 20:07:00 +08001369
1370 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
1371 // In opportunistic mode, handle falling back to cleartext in some
1372 // cases (DNS shouldn't fail if a validated opportunistic mode server
1373 // becomes unreachable for some reason).
1374 switch (response) {
Mike Yubfb1b342018-11-06 15:42:36 +08001375 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001376 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001377 return resplen;
Mike Yub601ff72018-11-01 20:07:00 +08001378 case DnsTlsTransport::Response::network_error:
Mike Yubfb1b342018-11-06 15:42:36 +08001379 // No need to set the error timeout here since it will fallback to UDP.
Mike Yub601ff72018-11-01 20:07:00 +08001380 case DnsTlsTransport::Response::internal_error:
1381 // Note: this will cause cleartext queries to be emitted, with
1382 // all of the EDNS0 goodness enabled. Fingers crossed. :-/
Mike Yubfb1b342018-11-06 15:42:36 +08001383 *fallback = true;
1384 [[fallthrough]];
Mike Yub601ff72018-11-01 20:07:00 +08001385 default:
Mike Yubfb1b342018-11-06 15:42:36 +08001386 return -1;
1387 }
1388 } else {
1389 // Strict mode
1390 switch (response) {
1391 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001392 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001393 return resplen;
1394 case DnsTlsTransport::Response::network_error:
1395 // This case happens when the query stored in DnsTlsTransport is expired since
1396 // either 1) the query has been tried for 3 times but no response or 2) fail to
1397 // establish the connection with the server.
Luke Huangd7aa7b42018-11-21 20:37:50 +08001398 *rcode = RCODE_TIMEOUT;
Mike Yubfb1b342018-11-06 15:42:36 +08001399 [[fallthrough]];
1400 default:
1401 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001402 }
1403 }
Mike Yub601ff72018-11-01 20:07:00 +08001404}
Luke Huang4973a0d2018-11-19 20:17:26 +08001405
Luke Huangba7bef92018-12-26 16:53:03 +08001406int resolv_res_nsend(const android_net_context* netContext, const uint8_t* msg, int msgLen,
lifr94981782019-05-17 21:15:19 +08001407 uint8_t* ans, int ansLen, int* rcode, uint32_t flags,
1408 NetworkDnsEventReported* event) {
1409 assert(event != nullptr);
Luke Huang1b3f4462020-12-04 17:48:39 +08001410 ResState res(netContext, event);
Mike Yu021c3e12019-10-08 17:29:34 +08001411 resolv_populate_res_for_net(&res);
Luke Huang4973a0d2018-11-19 20:17:26 +08001412 *rcode = NOERROR;
Bernie Innocenti08487112019-10-11 21:14:13 +09001413 return res_nsend(&res, msg, msgLen, ans, ansLen, rcode, flags);
Bernie Innocentiec4219b2019-01-30 11:16:36 +09001414}