blob: 1ccfc741c1018aad3e2c734eb49777ddb06a8f36 [file] [log] [blame]
Bernie Innocenti55864192018-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 Innocenti55864192018-08-30 04:05:20 +090073/*
74 * Send query to name server and wait for reply.
75 */
76
Bernie Innocentie9ba09c2018-09-12 23:20:10 +090077#define LOG_TAG "res_send"
78
Bernie Innocenti55864192018-08-30 04:05:20 +090079#include <sys/param.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090080#include <sys/socket.h>
Bernie Innocentif12d5bb2018-08-31 14:09:46 +090081#include <sys/time.h>
82#include <sys/types.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090083#include <sys/uio.h>
84
Bernie Innocenti55864192018-08-30 04:05:20 +090085#include <arpa/inet.h>
Bernie Innocentif12d5bb2018-08-31 14:09:46 +090086#include <arpa/nameser.h>
87#include <netinet/in.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090088
89#include <errno.h>
90#include <fcntl.h>
91#include <netdb.h>
92#include <poll.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090093#include <signal.h>
94#include <stdio.h>
95#include <stdlib.h>
96#include <string.h>
97#include <time.h>
98#include <unistd.h>
99
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900100#include <android-base/logging.h>
Bernie Innocenti34de3ba2019-02-19 18:08:36 +0900101#include <android/multinetwork.h> // ResNsendFlags
Bernie Innocenti55864192018-08-30 04:05:20 +0900102
Mike Yua46fae72018-11-01 20:07:00 +0800103#include <netdutils/Slice.h>
Frank Li08ce7b82019-06-27 10:11:52 -0700104#include <netdutils/Stopwatch.h>
Bernie Innocentiad4e26e2019-01-30 11:16:36 +0900105#include "DnsTlsDispatcher.h"
106#include "DnsTlsTransport.h"
107#include "PrivateDnsConfiguration.h"
Bernie Innocenti189eb502018-10-01 23:10:18 +0900108#include "netd_resolv/resolv.h"
109#include "netd_resolv/stats.h"
Bernie Innocenti2fd418e2018-08-30 12:04:03 +0900110#include "private/android_filesystem_config.h"
Bernie Innocenti189eb502018-10-01 23:10:18 +0900111#include "res_state_ext.h"
Bernie Innocenti2fd418e2018-08-30 12:04:03 +0900112#include "resolv_cache.h"
Bernie Innocenti2fd418e2018-08-30 12:04:03 +0900113#include "resolv_private.h"
Frank Li08ce7b82019-06-27 10:11:52 -0700114#include "stats.pb.h"
Bernie Innocenti2fd418e2018-08-30 12:04:03 +0900115
Mike Yua46fae72018-11-01 20:07:00 +0800116// TODO: use the namespace something like android::netd_resolv for libnetd_resolv
117using namespace android::net;
Frank Li08ce7b82019-06-27 10:11:52 -0700118using android::net::NetworkDnsEventReported;
Bernie Innocentiad4e26e2019-01-30 11:16:36 +0900119using android::netdutils::Slice;
Frank Li08ce7b82019-06-27 10:11:52 -0700120using android::netdutils::Stopwatch;
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900121
Mike Yua46fae72018-11-01 20:07:00 +0800122static DnsTlsDispatcher sDnsTlsDispatcher;
123
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900124static int get_salen(const struct sockaddr*);
125static struct sockaddr* get_nsaddr(res_state, size_t);
Bernie Innocenti34de3ba2019-02-19 18:08:36 +0900126static int send_vc(res_state, res_params* params, const u_char*, int, u_char*, int, int*, int,
127 time_t*, int*, int*);
128static int send_dg(res_state, res_params* params, const u_char*, int, u_char*, int, int*, int, int*,
129 int*, time_t*, int*, int*);
chenbruce16adee42019-02-20 19:45:50 +0800130static void Aerror(const res_state, const char*, int, const struct sockaddr*, int);
131static void Perror(const res_state, const char*, int);
132
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900133static int sock_eq(struct sockaddr*, struct sockaddr*);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900134static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
135 const struct timespec timeout);
Bernie Innocenti55864192018-08-30 04:05:20 +0900136static int retrying_poll(const int sock, short events, const struct timespec* finish);
Luke Huang490551d2018-11-21 20:37:50 +0800137static int res_tls_send(res_state, const Slice query, const Slice answer, int* rcode,
Mike Yu69615f62018-11-06 15:42:36 +0800138 bool* fallback);
Bernie Innocenti55864192018-08-30 04:05:20 +0900139
Frank Li08ce7b82019-06-27 10:11:52 -0700140NsType getQueryType(const uint8_t* msg, size_t msgLen) {
141 ns_msg handle;
142 ns_rr rr;
143 if (ns_initparse((const uint8_t*)msg, msgLen, &handle) < 0 ||
144 ns_parserr(&handle, ns_s_qd, 0, &rr) < 0) {
145 return NS_T_INVALID;
146 }
147 return static_cast<NsType>(ns_rr_type(rr));
148}
149
150IpVersion ipFamilyToIPVersion(const int ipFamily) {
151 switch (ipFamily) {
152 case AF_INET:
153 return IV_IPV4;
154 case AF_INET6:
155 return IV_IPV6;
156 default:
157 return IV_UNKNOWN;
158 }
159}
Bernie Innocenti55864192018-08-30 04:05:20 +0900160
Bernie Innocentif89b3512018-08-30 07:34:37 +0900161// BEGIN: Code copied from ISC eventlib
162// TODO: move away from this code
Bernie Innocentif89b3512018-08-30 07:34:37 +0900163#define BILLION 1000000000
164
165static struct timespec evConsTime(time_t sec, long nsec) {
166 struct timespec x;
167
168 x.tv_sec = sec;
169 x.tv_nsec = nsec;
170 return (x);
171}
172
173static struct timespec evAddTime(struct timespec addend1, struct timespec addend2) {
174 struct timespec x;
175
176 x.tv_sec = addend1.tv_sec + addend2.tv_sec;
177 x.tv_nsec = addend1.tv_nsec + addend2.tv_nsec;
178 if (x.tv_nsec >= BILLION) {
179 x.tv_sec++;
180 x.tv_nsec -= BILLION;
181 }
182 return (x);
183}
184
185static struct timespec evSubTime(struct timespec minuend, struct timespec subtrahend) {
186 struct timespec x;
187
188 x.tv_sec = minuend.tv_sec - subtrahend.tv_sec;
189 if (minuend.tv_nsec >= subtrahend.tv_nsec)
190 x.tv_nsec = minuend.tv_nsec - subtrahend.tv_nsec;
191 else {
192 x.tv_nsec = BILLION - subtrahend.tv_nsec + minuend.tv_nsec;
193 x.tv_sec--;
194 }
195 return (x);
196}
197
198static int evCmpTime(struct timespec a, struct timespec b) {
199#define SGN(x) ((x) < 0 ? (-1) : (x) > 0 ? (1) : (0));
200 time_t s = a.tv_sec - b.tv_sec;
201 long n;
202
203 if (s != 0) return SGN(s);
204
205 n = a.tv_nsec - b.tv_nsec;
206 return SGN(n);
207}
208
Bernie Innocentif89b3512018-08-30 07:34:37 +0900209static struct timespec evNowTime(void) {
Bernie Innocentif89b3512018-08-30 07:34:37 +0900210 struct timespec tsnow;
Bernie Innocenti357339c2018-08-31 16:11:41 +0900211 clock_gettime(CLOCK_REALTIME, &tsnow);
212 return tsnow;
Bernie Innocentif89b3512018-08-30 07:34:37 +0900213}
214
215static struct iovec evConsIovec(void* buf, size_t cnt) {
216 struct iovec ret;
217
218 memset(&ret, 0xf5, sizeof ret);
219 ret.iov_base = buf;
220 ret.iov_len = cnt;
Bernie Innocenti357339c2018-08-31 16:11:41 +0900221 return ret;
Bernie Innocentif89b3512018-08-30 07:34:37 +0900222}
223
224// END: Code copied from ISC eventlib
225
Frank Li08ce7b82019-06-27 10:11:52 -0700226/* BIONIC-BEGIN: implement source port randomization */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900227static int random_bind(int s, int family) {
nuccachene172a4e2018-10-23 17:10:58 +0800228 sockaddr_union u;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900229 int j;
230 socklen_t slen;
Bernie Innocenti55864192018-08-30 04:05:20 +0900231
232 /* clear all, this also sets the IP4/6 address to 'any' */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900233 memset(&u, 0, sizeof u);
Bernie Innocenti55864192018-08-30 04:05:20 +0900234
235 switch (family) {
236 case AF_INET:
237 u.sin.sin_family = family;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900238 slen = sizeof u.sin;
Bernie Innocenti55864192018-08-30 04:05:20 +0900239 break;
240 case AF_INET6:
241 u.sin6.sin6_family = family;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900242 slen = sizeof u.sin6;
Bernie Innocenti55864192018-08-30 04:05:20 +0900243 break;
244 default:
245 errno = EPROTO;
246 return -1;
247 }
248
249 /* first try to bind to a random source port a few times */
250 for (j = 0; j < 10; j++) {
251 /* find a random port between 1025 .. 65534 */
Luke Huang042e9422019-02-13 14:05:02 +0800252 int port = 1025 + (arc4random_uniform(65535 - 1025));
Bernie Innocenti55864192018-08-30 04:05:20 +0900253 if (family == AF_INET)
254 u.sin.sin_port = htons(port);
255 else
256 u.sin6.sin6_port = htons(port);
257
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900258 if (!bind(s, &u.sa, slen)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900259 }
260
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900261 // nothing after 10 attempts, our network table is probably busy
262 // let the system decide which port is best
Bernie Innocenti55864192018-08-30 04:05:20 +0900263 if (family == AF_INET)
264 u.sin.sin_port = 0;
265 else
266 u.sin6.sin6_port = 0;
267
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900268 return bind(s, &u.sa, slen);
Bernie Innocenti55864192018-08-30 04:05:20 +0900269}
270/* BIONIC-END */
271
Luke Huang92915e52019-01-31 11:57:41 +0800272// Disables all nameservers other than selectedServer
273static void res_set_usable_server(int selectedServer, int nscount, bool usable_servers[]) {
274 int usableIndex = 0;
275 for (int ns = 0; ns < nscount; ns++) {
276 if (usable_servers[ns]) ++usableIndex;
277 if (usableIndex != selectedServer) usable_servers[ns] = false;
278 }
279}
280
Bernie Innocenti55864192018-08-30 04:05:20 +0900281/* int
282 * res_isourserver(ina)
283 * looks up "ina" in _res.ns_addr_list[]
284 * returns:
285 * 0 : not found
286 * >0 : found
287 * author:
288 * paul vixie, 29may94
289 */
Bernie Innocenti4acba1a2018-09-26 11:52:04 +0900290static int res_ourserver_p(const res_state statp, const sockaddr* sa) {
291 const sockaddr_in *inp, *srv;
292 const sockaddr_in6 *in6p, *srv6;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900293 int ns;
Bernie Innocenti55864192018-08-30 04:05:20 +0900294
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900295 switch (sa->sa_family) {
296 case AF_INET:
297 inp = (const struct sockaddr_in*) (const void*) sa;
298 for (ns = 0; ns < statp->nscount; ns++) {
299 srv = (struct sockaddr_in*) (void*) get_nsaddr(statp, (size_t) ns);
300 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 Innocenti4acba1a2018-09-26 11:52:04 +0900303 return 1;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900304 }
305 break;
306 case AF_INET6:
Ken Chencf6ded62018-10-16 23:12:09 +0800307 if (statp->_u._ext.ext == NULL) break;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900308 in6p = (const struct sockaddr_in6*) (const void*) sa;
309 for (ns = 0; ns < statp->nscount; ns++) {
310 srv6 = (struct sockaddr_in6*) (void*) get_nsaddr(statp, (size_t) ns);
311 if (srv6->sin6_family == in6p->sin6_family && srv6->sin6_port == in6p->sin6_port &&
Bernie Innocenti55864192018-08-30 04:05:20 +0900312#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900313 (srv6->sin6_scope_id == 0 || srv6->sin6_scope_id == in6p->sin6_scope_id) &&
Bernie Innocenti55864192018-08-30 04:05:20 +0900314#endif
Bernie Innocentif12d5bb2018-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 Innocenti4acba1a2018-09-26 11:52:04 +0900317 return 1;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900318 }
319 break;
320 default:
321 break;
322 }
Bernie Innocenti4acba1a2018-09-26 11:52:04 +0900323 return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900324}
325
326/* int
Bernie Innocenti1f4a9fd2018-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 Innocenti55864192018-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 */
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900338int res_nameinquery(const char* name, int type, int cl, const u_char* buf, const u_char* eom) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900339 const u_char* cp = buf + HFIXEDSZ;
340 int qdcount = ntohs(((const HEADER*) (const void*) buf)->qdcount);
Bernie Innocenti55864192018-08-30 04:05:20 +0900341
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900342 while (qdcount-- > 0) {
343 char tname[MAXDNAME + 1];
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900344 int n = dn_expand(buf, eom, cp, tname, sizeof tname);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900345 if (n < 0) return (-1);
346 cp += n;
347 if (cp + 2 * INT16SZ > eom) return (-1);
chenbruce86a50bb2019-03-28 18:44:37 +0800348 int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900349 cp += INT16SZ;
chenbruce86a50bb2019-03-28 18:44:37 +0800350 int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900351 cp += INT16SZ;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900352 if (ttype == type && tclass == cl && ns_samename(tname, name) == 1) return (1);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900353 }
354 return (0);
Bernie Innocenti55864192018-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 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900368int res_queriesmatch(const u_char* buf1, const u_char* eom1, const u_char* buf2,
369 const u_char* eom2) {
370 const u_char* cp = buf1 + HFIXEDSZ;
371 int qdcount = ntohs(((const HEADER*) (const void*) buf1)->qdcount);
Bernie Innocenti55864192018-08-30 04:05:20 +0900372
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900373 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2) return (-1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900374
Bernie Innocentif12d5bb2018-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 Innocenti55864192018-08-30 04:05:20 +0900382
Bernie Innocentif12d5bb2018-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 Innocenti1f4a9fd2018-09-07 21:10:25 +0900386 int n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900387 if (n < 0) return (-1);
388 cp += n;
389 if (cp + 2 * INT16SZ > eom1) return (-1);
chenbruce86a50bb2019-03-28 18:44:37 +0800390 int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900391 cp += INT16SZ;
chenbruce86a50bb2019-03-28 18:44:37 +0800392 int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900393 cp += INT16SZ;
394 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2)) return (0);
395 }
396 return (1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900397}
398
Frank Li08ce7b82019-06-27 10:11:52 -0700399static DnsQueryEvent* addDnsQueryEvent(NetworkDnsEventReported* event) {
400 return event->mutable_dns_query_events()->add_dns_query_event();
401}
402
Luke Huang952d0942018-12-26 16:53:03 +0800403int res_nsend(res_state statp, const u_char* buf, int buflen, u_char* ans, int anssiz, int* rcode,
404 uint32_t flags) {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900405 int gotsomewhere, terrno, v_circuit, resplen, n;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900406 ResolvCacheStatus cache_status = RESOLV_CACHE_UNSUPPORTED;
Bernie Innocenti55864192018-08-30 04:05:20 +0900407
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900408 if (anssiz < HFIXEDSZ) {
Luke Huang8c0e98f2018-12-03 15:37:28 +0800409 // TODO: Remove errno once callers stop using it
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900410 errno = EINVAL;
Luke Huang8c0e98f2018-12-03 15:37:28 +0800411 return -EINVAL;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900412 }
Bernie Innocentid017e972019-03-03 19:39:53 +0900413 LOG(DEBUG) << __func__;
chenbrucee8911f92019-03-06 13:52:43 +0800414 res_pquery(buf, buflen);
chenbruce16adee42019-02-20 19:45:50 +0800415
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900416 v_circuit = (statp->options & RES_USEVC) || buflen > PACKETSZ;
417 gotsomewhere = 0;
418 terrno = ETIMEDOUT;
Bernie Innocenti55864192018-08-30 04:05:20 +0900419
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900420 int anslen = 0;
Frank Li08ce7b82019-06-27 10:11:52 -0700421 Stopwatch cache_stopwatch;
Luke Huang952d0942018-12-26 16:53:03 +0800422 cache_status = _resolv_cache_lookup(statp->netid, buf, buflen, ans, anssiz, &anslen, flags);
Frank Li08ce7b82019-06-27 10:11:52 -0700423 const int32_t cacheLatencyUs = saturate_cast<int32_t>(cache_stopwatch.timeTakenUs());
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900424 if (cache_status == RESOLV_CACHE_FOUND) {
Luke Huang85b24392019-02-27 18:18:01 +0800425 HEADER* hp = (HEADER*)(void*)ans;
426 *rcode = hp->rcode;
Frank Li08ce7b82019-06-27 10:11:52 -0700427 DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
428 dnsQueryEvent->set_latency_micros(cacheLatencyUs);
429 dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900430 return anslen;
431 } else if (cache_status != RESOLV_CACHE_UNSUPPORTED) {
432 // had a cache miss for a known network, so populate the thread private
433 // data so the normal resolve path can do its thing
434 _resolv_populate_res_for_net(statp);
435 }
436 if (statp->nscount == 0) {
437 // We have no nameservers configured, so there's no point trying.
438 // Tell the cache the query failed, or any retries and anyone else asking the same
439 // question will block for PENDING_REQUEST_TIMEOUT seconds instead of failing fast.
Luke Huang952d0942018-12-26 16:53:03 +0800440 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huang8c0e98f2018-12-03 15:37:28 +0800441
442 // TODO: Remove errno once callers stop using it
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900443 errno = ESRCH;
Luke Huang8c0e98f2018-12-03 15:37:28 +0800444 return -ESRCH;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900445 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900446
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900447 /*
448 * If the ns_addr_list in the resolver context has changed, then
449 * invalidate our cached copy and the associated timing data.
450 */
Ken Chencf6ded62018-10-16 23:12:09 +0800451 if (statp->_u._ext.nscount != 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900452 int needclose = 0;
453 struct sockaddr_storage peer;
454 socklen_t peerlen;
Bernie Innocenti55864192018-08-30 04:05:20 +0900455
Ken Chencf6ded62018-10-16 23:12:09 +0800456 if (statp->_u._ext.nscount != statp->nscount) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900457 needclose++;
458 } else {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900459 for (int ns = 0; ns < statp->nscount; ns++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900460 if (statp->nsaddr_list[ns].sin_family &&
461 !sock_eq((struct sockaddr*) (void*) &statp->nsaddr_list[ns],
Ken Chencf6ded62018-10-16 23:12:09 +0800462 (struct sockaddr*) (void*) &statp->_u._ext.ext->nsaddrs[ns])) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900463 needclose++;
464 break;
465 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900466
Ken Chencf6ded62018-10-16 23:12:09 +0800467 if (statp->_u._ext.nssocks[ns] == -1) continue;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900468 peerlen = sizeof(peer);
Ken Chencf6ded62018-10-16 23:12:09 +0800469 if (getpeername(statp->_u._ext.nssocks[ns], (struct sockaddr*) (void*) &peer,
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900470 &peerlen) < 0) {
471 needclose++;
472 break;
473 }
474 if (!sock_eq((struct sockaddr*) (void*) &peer, get_nsaddr(statp, (size_t) ns))) {
475 needclose++;
476 break;
477 }
478 }
479 }
480 if (needclose) {
481 res_nclose(statp);
Ken Chencf6ded62018-10-16 23:12:09 +0800482 statp->_u._ext.nscount = 0;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900483 }
484 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900485
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900486 /*
487 * Maybe initialize our private copy of the ns_addr_list.
488 */
Ken Chencf6ded62018-10-16 23:12:09 +0800489 if (statp->_u._ext.nscount == 0) {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900490 for (int ns = 0; ns < statp->nscount; ns++) {
Ken Chencf6ded62018-10-16 23:12:09 +0800491 statp->_u._ext.nstimes[ns] = RES_MAXTIME;
492 statp->_u._ext.nssocks[ns] = -1;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900493 if (!statp->nsaddr_list[ns].sin_family) continue;
Ken Chencf6ded62018-10-16 23:12:09 +0800494 statp->_u._ext.ext->nsaddrs[ns].sin = statp->nsaddr_list[ns];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900495 }
Ken Chencf6ded62018-10-16 23:12:09 +0800496 statp->_u._ext.nscount = statp->nscount;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900497 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900498
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900499 /*
500 * Some resolvers want to even out the load on their nameservers.
501 * Note that RES_BLAST overrides RES_ROTATE.
502 */
503 if ((statp->options & RES_ROTATE) != 0U && (statp->options & RES_BLAST) == 0U) {
nuccachene172a4e2018-10-23 17:10:58 +0800504 sockaddr_union inu;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900505 struct sockaddr_in ina;
506 int lastns = statp->nscount - 1;
507 int fd;
508 u_int16_t nstime;
Bernie Innocenti55864192018-08-30 04:05:20 +0900509
Ken Chencf6ded62018-10-16 23:12:09 +0800510 if (statp->_u._ext.ext != NULL) inu = statp->_u._ext.ext->nsaddrs[0];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900511 ina = statp->nsaddr_list[0];
Ken Chencf6ded62018-10-16 23:12:09 +0800512 fd = statp->_u._ext.nssocks[0];
513 nstime = statp->_u._ext.nstimes[0];
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900514 for (int ns = 0; ns < lastns; ns++) {
Ken Chencf6ded62018-10-16 23:12:09 +0800515 if (statp->_u._ext.ext != NULL)
516 statp->_u._ext.ext->nsaddrs[ns] = statp->_u._ext.ext->nsaddrs[ns + 1];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900517 statp->nsaddr_list[ns] = statp->nsaddr_list[ns + 1];
Ken Chencf6ded62018-10-16 23:12:09 +0800518 statp->_u._ext.nssocks[ns] = statp->_u._ext.nssocks[ns + 1];
519 statp->_u._ext.nstimes[ns] = statp->_u._ext.nstimes[ns + 1];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900520 }
Ken Chencf6ded62018-10-16 23:12:09 +0800521 if (statp->_u._ext.ext != NULL) statp->_u._ext.ext->nsaddrs[lastns] = inu;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900522 statp->nsaddr_list[lastns] = ina;
Ken Chencf6ded62018-10-16 23:12:09 +0800523 statp->_u._ext.nssocks[lastns] = fd;
524 statp->_u._ext.nstimes[lastns] = nstime;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900525 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900526
Bernie Innocenti34de3ba2019-02-19 18:08:36 +0900527 res_stats stats[MAXNS];
528 res_params params;
waynemad193e4d2019-02-18 17:47:59 +0800529 int revision_id = resolv_cache_get_resolver_stats(statp->netid, &params, stats);
lifrcf395c52019-02-13 17:33:57 +0800530 if (revision_id < 0) {
531 // TODO: Remove errno once callers stop using it
532 errno = ESRCH;
533 return -ESRCH;
534 }
waynemad193e4d2019-02-18 17:47:59 +0800535 bool usable_servers[MAXNS];
Luke Huang92915e52019-01-31 11:57:41 +0800536 int usableServersCount = android_net_res_stats_get_usable_servers(
537 &params, stats, statp->nscount, usable_servers);
538
539 if ((flags & ANDROID_RESOLV_NO_RETRY) && usableServersCount > 1) {
540 auto hp = reinterpret_cast<const HEADER*>(buf);
541
542 // Select a random server based on the query id
543 int selectedServer = (hp->id % usableServersCount) + 1;
544 res_set_usable_server(selectedServer, statp->nscount, usable_servers);
545 }
waynemad193e4d2019-02-18 17:47:59 +0800546
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900547 /*
548 * Send request, RETRY times, or until successful.
549 */
waynema2371eab2019-01-18 14:02:31 +0800550 int retryTimes = (flags & ANDROID_RESOLV_NO_RETRY) ? 1 : params.retry_count;
Luke Huang952d0942018-12-26 16:53:03 +0800551
552 for (int attempt = 0; attempt < retryTimes; ++attempt) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900553
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900554 for (int ns = 0; ns < statp->nscount; ns++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900555 if (!usable_servers[ns]) continue;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900556 int nsaplen;
557 time_t now = 0;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900558 int delay = 0;
Mike Yu69615f62018-11-06 15:42:36 +0800559 *rcode = RCODE_INTERNAL_ERROR;
Frank Li08ce7b82019-06-27 10:11:52 -0700560 const sockaddr* nsap = get_nsaddr(statp, ns);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900561 nsaplen = get_salen(nsap);
Bernie Innocenti55864192018-08-30 04:05:20 +0900562
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900563 same_ns:
Mike Yu69615f62018-11-06 15:42:36 +0800564 // TODO: Since we expect there is only one DNS server being queried here while this
565 // function tries to query all of private DNS servers. Consider moving it to other
566 // reasonable place. In addition, maybe add stats for private DNS.
567 if (!statp->use_local_nameserver) {
568 bool fallback = false;
569 resplen = res_tls_send(statp, Slice(const_cast<u_char*>(buf), buflen),
570 Slice(ans, anssiz), rcode, &fallback);
571 if (resplen > 0) {
572 if (cache_status == RESOLV_CACHE_NOTFOUND) {
573 _resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
574 }
575 return resplen;
Mike Yua46fae72018-11-01 20:07:00 +0800576 }
Mike Yu69615f62018-11-06 15:42:36 +0800577 if (!fallback) {
Luke Huang952d0942018-12-26 16:53:03 +0800578 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huang8c0e98f2018-12-03 15:37:28 +0800579 res_nclose(statp);
580 return -terrno;
Mike Yu69615f62018-11-06 15:42:36 +0800581 }
582 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900583
Frank Li08ce7b82019-06-27 10:11:52 -0700584 static const int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
585 char abuf[NI_MAXHOST];
586 DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
587 dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
chenbruce16adee42019-02-20 19:45:50 +0800588
589 if (getnameinfo(nsap, (socklen_t)nsaplen, abuf, sizeof(abuf), NULL, 0, niflags) == 0)
Ken Chenbab50142019-03-19 17:41:28 +0800590 LOG(DEBUG) << __func__ << ": Querying server (# " << ns + 1
591 << ") address = " << abuf;
Bernie Innocenti55864192018-08-30 04:05:20 +0900592
Frank Li08ce7b82019-06-27 10:11:52 -0700593 Stopwatch query_stopwatch;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900594 if (v_circuit) {
595 /* Use VC; at most one attempt per server. */
Luke Huang952d0942018-12-26 16:53:03 +0800596 bool shouldRecordStats = (attempt == 0);
597 attempt = retryTimes;
Bernie Innocenti55864192018-08-30 04:05:20 +0900598
Mike Yu69615f62018-11-06 15:42:36 +0800599 n = send_vc(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &now, rcode,
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900600 &delay);
Bernie Innocenti55864192018-08-30 04:05:20 +0900601
Frank Li08ce7b82019-06-27 10:11:52 -0700602 dnsQueryEvent->set_latency_micros(
603 saturate_cast<int32_t>(query_stopwatch.timeTakenUs()));
604 dnsQueryEvent->set_dns_server_index(ns);
605 dnsQueryEvent->set_ip_version(ipFamilyToIPVersion(nsap->sa_family));
606 dnsQueryEvent->set_retry_times(attempt);
607 dnsQueryEvent->set_rcode(static_cast<NsRcode>(*rcode));
608 dnsQueryEvent->set_protocol(PROTO_TCP);
609 dnsQueryEvent->set_type(getQueryType(buf, buflen));
610
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900611 /*
612 * Only record stats the first time we try a query. This ensures that
613 * queries that deterministically fail (e.g., a name that always returns
614 * SERVFAIL or times out) do not unduly affect the stats.
615 */
Luke Huang952d0942018-12-26 16:53:03 +0800616 if (shouldRecordStats) {
Bernie Innocenti189eb502018-10-01 23:10:18 +0900617 res_sample sample;
Mike Yu69615f62018-11-06 15:42:36 +0800618 _res_stats_set_sample(&sample, now, *rcode, delay);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900619 _resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, ns, &sample,
620 params.max_samples);
621 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900622
Ken Chenbab50142019-03-19 17:41:28 +0800623 LOG(INFO) << __func__ << ": used send_vc " << n;
Bernie Innocenti55864192018-08-30 04:05:20 +0900624
Luke Huang8c0e98f2018-12-03 15:37:28 +0800625 if (n < 0) {
Luke Huang952d0942018-12-26 16:53:03 +0800626 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huang8c0e98f2018-12-03 15:37:28 +0800627 res_nclose(statp);
628 return -terrno;
629 };
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900630 if (n == 0) goto next_ns;
631 resplen = n;
632 } else {
633 /* Use datagrams. */
Ken Chenbab50142019-03-19 17:41:28 +0800634 LOG(INFO) << __func__ << ": using send_dg";
Bernie Innocenti55864192018-08-30 04:05:20 +0900635
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900636 n = send_dg(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &v_circuit,
Mike Yu69615f62018-11-06 15:42:36 +0800637 &gotsomewhere, &now, rcode, &delay);
Bernie Innocenti55864192018-08-30 04:05:20 +0900638
Frank Li08ce7b82019-06-27 10:11:52 -0700639 dnsQueryEvent->set_latency_micros(
640 saturate_cast<int32_t>(query_stopwatch.timeTakenUs()));
641 dnsQueryEvent->set_dns_server_index(ns);
642 dnsQueryEvent->set_ip_version(ipFamilyToIPVersion(nsap->sa_family));
643 dnsQueryEvent->set_retry_times(attempt);
644 dnsQueryEvent->set_rcode(static_cast<NsRcode>(*rcode));
645 dnsQueryEvent->set_protocol(PROTO_UDP);
646 dnsQueryEvent->set_type(getQueryType(buf, buflen));
647
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900648 /* Only record stats the first time we try a query. See above. */
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900649 if (attempt == 0) {
Bernie Innocenti189eb502018-10-01 23:10:18 +0900650 res_sample sample;
Mike Yu69615f62018-11-06 15:42:36 +0800651 _res_stats_set_sample(&sample, now, *rcode, delay);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900652 _resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, ns, &sample,
653 params.max_samples);
654 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900655
Ken Chenbab50142019-03-19 17:41:28 +0800656 LOG(INFO) << __func__ << ": used send_dg " << n;
Bernie Innocenti55864192018-08-30 04:05:20 +0900657
Luke Huang8c0e98f2018-12-03 15:37:28 +0800658 if (n < 0) {
Luke Huang952d0942018-12-26 16:53:03 +0800659 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huang8c0e98f2018-12-03 15:37:28 +0800660 res_nclose(statp);
661 return -terrno;
662 };
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900663 if (n == 0) goto next_ns;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900664 if (v_circuit) goto same_ns;
665 resplen = n;
666 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900667
Ken Chenbab50142019-03-19 17:41:28 +0800668 LOG(DEBUG) << __func__ << ": got answer:";
chenbrucee8911f92019-03-06 13:52:43 +0800669 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti55864192018-08-30 04:05:20 +0900670
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900671 if (cache_status == RESOLV_CACHE_NOTFOUND) {
672 _resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
673 }
674 /*
675 * If we have temporarily opened a virtual circuit,
676 * or if we haven't been asked to keep a socket open,
677 * close the socket.
678 */
679 if ((v_circuit && (statp->options & RES_USEVC) == 0U) ||
680 (statp->options & RES_STAYOPEN) == 0U) {
681 res_nclose(statp);
682 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900683 return (resplen);
684 next_ns:;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900685 } // for each ns
686 } // for each retry
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900687 res_nclose(statp);
688 if (!v_circuit) {
Luke Huang8c0e98f2018-12-03 15:37:28 +0800689 if (!gotsomewhere) {
690 // TODO: Remove errno once callers stop using it
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900691 errno = ECONNREFUSED; /* no nameservers found */
Luke Huang8c0e98f2018-12-03 15:37:28 +0800692 terrno = ECONNREFUSED;
693 } else {
694 // TODO: Remove errno once callers stop using it
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900695 errno = ETIMEDOUT; /* no answer obtained */
Luke Huang8c0e98f2018-12-03 15:37:28 +0800696 terrno = ETIMEDOUT;
697 }
698 } else {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900699 errno = terrno;
Luke Huang8c0e98f2018-12-03 15:37:28 +0800700 }
Luke Huang952d0942018-12-26 16:53:03 +0800701 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huang8c0e98f2018-12-03 15:37:28 +0800702 return -terrno;
Bernie Innocenti55864192018-08-30 04:05:20 +0900703}
704
705/* Private */
706
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900707static int get_salen(const struct sockaddr* sa) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900708 if (sa->sa_family == AF_INET)
709 return (sizeof(struct sockaddr_in));
710 else if (sa->sa_family == AF_INET6)
711 return (sizeof(struct sockaddr_in6));
712 else
713 return (0); /* unknown, die on connect */
Bernie Innocenti55864192018-08-30 04:05:20 +0900714}
715
716/*
717 * pick appropriate nsaddr_list for use. see res_init() for initialization.
718 */
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900719static struct sockaddr* get_nsaddr(res_state statp, size_t n) {
Ken Chencf6ded62018-10-16 23:12:09 +0800720 if (!statp->nsaddr_list[n].sin_family && statp->_u._ext.ext) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900721 /*
Ken Chencf6ded62018-10-16 23:12:09 +0800722 * - statp->_u._ext.ext->nsaddrs[n] holds an address that is larger
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900723 * than struct sockaddr, and
724 * - user code did not update statp->nsaddr_list[n].
725 */
Ken Chencf6ded62018-10-16 23:12:09 +0800726 return (struct sockaddr*) (void*) &statp->_u._ext.ext->nsaddrs[n];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900727 } else {
728 /*
729 * - user code updated statp->nsaddr_list[n], or
730 * - statp->nsaddr_list[n] has the same content as
Ken Chencf6ded62018-10-16 23:12:09 +0800731 * statp->_u._ext.ext->nsaddrs[n].
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900732 */
733 return (struct sockaddr*) (void*) &statp->nsaddr_list[n];
734 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900735}
736
Bernie Innocenti34de3ba2019-02-19 18:08:36 +0900737static struct timespec get_timeout(const res_state statp, const res_params* params, const int ns) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900738 int msec;
waynema2371eab2019-01-18 14:02:31 +0800739 // Legacy algorithm which scales the timeout by nameserver number.
740 // For instance, with 4 nameservers: 5s, 2.5s, 5s, 10s
741 // This has no effect with 1 or 2 nameservers
742 msec = params->base_timeout_msec << ns;
743 if (ns > 0) {
744 msec /= statp->nscount;
745 }
746 // For safety, don't allow OEMs and experiments to configure a timeout shorter than 1s.
747 if (msec < 1000) {
748 msec = 1000; // Use at least 1000ms
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900749 }
Ken Chenbab50142019-03-19 17:41:28 +0800750 LOG(INFO) << __func__ << ": using timeout of " << msec << " msec";
Bernie Innocenti55864192018-08-30 04:05:20 +0900751
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900752 struct timespec result;
753 result.tv_sec = msec / 1000;
754 result.tv_nsec = (msec % 1000) * 1000000;
755 return result;
Bernie Innocenti55864192018-08-30 04:05:20 +0900756}
757
Bernie Innocenti34de3ba2019-02-19 18:08:36 +0900758static int send_vc(res_state statp, res_params* params, const u_char* buf, int buflen, u_char* ans,
759 int anssiz, int* terrno, int ns, time_t* at, int* rcode, int* delay) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900760 *at = time(NULL);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900761 *delay = 0;
762 const HEADER* hp = (const HEADER*) (const void*) buf;
763 HEADER* anhp = (HEADER*) (void*) ans;
764 struct sockaddr* nsap;
765 int nsaplen;
chenbruce86a50bb2019-03-28 18:44:37 +0800766 int truncating, connreset, n;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900767 struct iovec iov[2];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900768 u_char* cp;
Bernie Innocenti55864192018-08-30 04:05:20 +0900769
Ken Chenbab50142019-03-19 17:41:28 +0800770 LOG(INFO) << __func__ << ": using send_vc";
Bernie Innocenti55864192018-08-30 04:05:20 +0900771
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900772 nsap = get_nsaddr(statp, (size_t) ns);
773 nsaplen = get_salen(nsap);
Bernie Innocenti55864192018-08-30 04:05:20 +0900774
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900775 connreset = 0;
776same_ns:
777 truncating = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900778
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900779 struct timespec now = evNowTime();
Bernie Innocenti55864192018-08-30 04:05:20 +0900780
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900781 /* Are we still talking to whom we want to talk to? */
782 if (statp->_vcsock >= 0 && (statp->_flags & RES_F_VC) != 0) {
783 struct sockaddr_storage peer;
784 socklen_t size = sizeof peer;
785 unsigned old_mark;
786 socklen_t mark_size = sizeof(old_mark);
787 if (getpeername(statp->_vcsock, (struct sockaddr*) (void*) &peer, &size) < 0 ||
788 !sock_eq((struct sockaddr*) (void*) &peer, nsap) ||
789 getsockopt(statp->_vcsock, SOL_SOCKET, SO_MARK, &old_mark, &mark_size) < 0 ||
790 old_mark != statp->_mark) {
791 res_nclose(statp);
792 statp->_flags &= ~RES_F_VC;
793 }
794 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900795
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900796 if (statp->_vcsock < 0 || (statp->_flags & RES_F_VC) == 0) {
797 if (statp->_vcsock >= 0) res_nclose(statp);
Bernie Innocenti55864192018-08-30 04:05:20 +0900798
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900799 statp->_vcsock = socket(nsap->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0);
800 if (statp->_vcsock < 0) {
801 switch (errno) {
802 case EPROTONOSUPPORT:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900803 case EPFNOSUPPORT:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900804 case EAFNOSUPPORT:
chenbruce16adee42019-02-20 19:45:50 +0800805 Perror(statp, "socket(vc)", errno);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900806 return 0;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900807 default:
808 *terrno = errno;
chenbruce16adee42019-02-20 19:45:50 +0800809 Perror(statp, "socket(vc)", errno);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900810 return -1;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900811 }
812 }
813 fchown(statp->_vcsock, AID_DNS, -1);
814 if (statp->_mark != MARK_UNSET) {
815 if (setsockopt(statp->_vcsock, SOL_SOCKET, SO_MARK, &statp->_mark,
816 sizeof(statp->_mark)) < 0) {
817 *terrno = errno;
chenbruce16adee42019-02-20 19:45:50 +0800818 Perror(statp, "setsockopt", errno);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900819 return -1;
820 }
821 }
822 errno = 0;
823 if (random_bind(statp->_vcsock, nsap->sa_family) < 0) {
824 *terrno = errno;
chenbruce16adee42019-02-20 19:45:50 +0800825 Aerror(statp, "bind/vc", errno, nsap, nsaplen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900826 res_nclose(statp);
827 return (0);
828 }
829 if (connect_with_timeout(statp->_vcsock, nsap, (socklen_t) nsaplen,
830 get_timeout(statp, params, ns)) < 0) {
831 *terrno = errno;
chenbruce16adee42019-02-20 19:45:50 +0800832 Aerror(statp, "connect/vc", errno, nsap, nsaplen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900833 res_nclose(statp);
834 /*
835 * The way connect_with_timeout() is implemented prevents us from reliably
836 * determining whether this was really a timeout or e.g. ECONNREFUSED. Since
837 * currently both cases are handled in the same way, there is no need to
838 * change this (yet). If we ever need to reliably distinguish between these
839 * cases, both connect_with_timeout() and retrying_poll() need to be
840 * modified, though.
841 */
842 *rcode = RCODE_TIMEOUT;
843 return (0);
844 }
845 statp->_flags |= RES_F_VC;
846 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900847
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900848 /*
849 * Send length & message
850 */
chenbruce86a50bb2019-03-28 18:44:37 +0800851 uint16_t len = htons(static_cast<uint16_t>(buflen));
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900852 iov[0] = evConsIovec(&len, INT16SZ);
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900853 iov[1] = evConsIovec((void*) buf, (size_t) buflen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900854 if (writev(statp->_vcsock, iov, 2) != (INT16SZ + buflen)) {
855 *terrno = errno;
chenbruce16adee42019-02-20 19:45:50 +0800856 Perror(statp, "write failed", errno);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900857 res_nclose(statp);
858 return (0);
859 }
860 /*
861 * Receive length & response
862 */
863read_len:
864 cp = ans;
865 len = INT16SZ;
866 while ((n = read(statp->_vcsock, (char*) cp, (size_t) len)) > 0) {
867 cp += n;
868 if ((len -= n) == 0) break;
869 }
870 if (n <= 0) {
871 *terrno = errno;
chenbruce16adee42019-02-20 19:45:50 +0800872 Perror(statp, "read failed", errno);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900873 res_nclose(statp);
874 /*
875 * A long running process might get its TCP
876 * connection reset if the remote server was
877 * restarted. Requery the server instead of
878 * trying a new one. When there is only one
879 * server, this means that a query might work
880 * instead of failing. We only allow one reset
881 * per query to prevent looping.
882 */
883 if (*terrno == ECONNRESET && !connreset) {
884 connreset = 1;
885 res_nclose(statp);
886 goto same_ns;
887 }
888 res_nclose(statp);
889 return (0);
890 }
chenbruce86a50bb2019-03-28 18:44:37 +0800891 uint16_t resplen = ntohs(*reinterpret_cast<const uint16_t*>(ans));
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900892 if (resplen > anssiz) {
Ken Chenbab50142019-03-19 17:41:28 +0800893 LOG(DEBUG) << __func__ << ": response truncated";
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900894 truncating = 1;
895 len = anssiz;
896 } else
897 len = resplen;
898 if (len < HFIXEDSZ) {
899 /*
900 * Undersized message.
901 */
Ken Chenbab50142019-03-19 17:41:28 +0800902 LOG(DEBUG) << __func__ << ": undersized: " << len;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900903 *terrno = EMSGSIZE;
904 res_nclose(statp);
905 return (0);
906 }
907 cp = ans;
908 while (len != 0 && (n = read(statp->_vcsock, (char*) cp, (size_t) len)) > 0) {
909 cp += n;
910 len -= n;
911 }
912 if (n <= 0) {
913 *terrno = errno;
chenbruce16adee42019-02-20 19:45:50 +0800914 Perror(statp, "read(vc)", errno);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900915 res_nclose(statp);
916 return (0);
917 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900918
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900919 if (truncating) {
920 /*
921 * Flush rest of answer so connection stays in synch.
922 */
923 anhp->tc = 1;
924 len = resplen - anssiz;
925 while (len != 0) {
926 char junk[PACKETSZ];
Bernie Innocenti55864192018-08-30 04:05:20 +0900927
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900928 n = read(statp->_vcsock, junk, (len > sizeof junk) ? sizeof junk : len);
929 if (n > 0)
930 len -= n;
931 else
932 break;
933 }
934 }
935 /*
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900936 * If the calling application has bailed out of
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900937 * a previous call and failed to arrange to have
938 * the circuit closed or the server has got
939 * itself confused, then drop the packet and
940 * wait for the correct one.
941 */
942 if (hp->id != anhp->id) {
Ken Chenbab50142019-03-19 17:41:28 +0800943 LOG(DEBUG) << __func__ << ": ld answer (unexpected):";
chenbrucee8911f92019-03-06 13:52:43 +0800944 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900945 goto read_len;
946 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900947
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900948 /*
949 * All is well, or the error is fatal. Signal that the
950 * next nameserver ought not be tried.
951 */
952 if (resplen > 0) {
953 struct timespec done = evNowTime();
954 *delay = _res_stats_calculate_rtt(&done, &now);
955 *rcode = anhp->rcode;
956 }
957 return (resplen);
Bernie Innocenti55864192018-08-30 04:05:20 +0900958}
959
960/* return -1 on error (errno set), 0 on success */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900961static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
962 const struct timespec timeout) {
963 int res, origflags;
Bernie Innocenti55864192018-08-30 04:05:20 +0900964
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900965 origflags = fcntl(sock, F_GETFL, 0);
966 fcntl(sock, F_SETFL, origflags | O_NONBLOCK);
Bernie Innocenti55864192018-08-30 04:05:20 +0900967
Bernie Innocentif89b3512018-08-30 07:34:37 +0900968 res = connect(sock, nsap, salen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900969 if (res < 0 && errno != EINPROGRESS) {
970 res = -1;
971 goto done;
972 }
973 if (res != 0) {
974 struct timespec now = evNowTime();
975 struct timespec finish = evAddTime(now, timeout);
Ken Chenbab50142019-03-19 17:41:28 +0800976 LOG(INFO) << __func__ << ": " << sock << " send_vc";
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900977 res = retrying_poll(sock, POLLIN | POLLOUT, &finish);
978 if (res <= 0) {
979 res = -1;
980 }
981 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900982done:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900983 fcntl(sock, F_SETFL, origflags);
Ken Chenbab50142019-03-19 17:41:28 +0800984 LOG(INFO) << __func__ << ": " << sock << " connect_with_const timeout returning " << res;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900985 return res;
Bernie Innocenti55864192018-08-30 04:05:20 +0900986}
987
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900988static int retrying_poll(const int sock, const short events, const struct timespec* finish) {
989 struct timespec now, timeout;
Bernie Innocenti55864192018-08-30 04:05:20 +0900990
991retry:
Ken Chenbab50142019-03-19 17:41:28 +0800992 LOG(INFO) << __func__ << ": " << sock << " retrying_poll";
Bernie Innocenti55864192018-08-30 04:05:20 +0900993
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900994 now = evNowTime();
995 if (evCmpTime(*finish, now) > 0)
996 timeout = evSubTime(*finish, now);
997 else
998 timeout = evConsTime(0L, 0L);
999 struct pollfd fds = {.fd = sock, .events = events};
1000 int n = ppoll(&fds, 1, &timeout, /*sigmask=*/NULL);
1001 if (n == 0) {
Ken Chenbab50142019-03-19 17:41:28 +08001002 LOG(INFO) << __func__ << ": " << sock << "retrying_poll timeout";
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001003 errno = ETIMEDOUT;
1004 return 0;
1005 }
1006 if (n < 0) {
1007 if (errno == EINTR) goto retry;
Ken Chenbab50142019-03-19 17:41:28 +08001008 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll failed";
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001009 return n;
1010 }
1011 if (fds.revents & (POLLIN | POLLOUT | POLLERR)) {
1012 int error;
1013 socklen_t len = sizeof(error);
1014 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error) {
1015 errno = error;
Ken Chenbab50142019-03-19 17:41:28 +08001016 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll getsockopt failed";
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001017 return -1;
1018 }
1019 }
Ken Chenbab50142019-03-19 17:41:28 +08001020 LOG(INFO) << __func__ << ": " << sock << " retrying_poll returning " << n;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001021 return n;
Bernie Innocenti55864192018-08-30 04:05:20 +09001022}
1023
Bernie Innocenti34de3ba2019-02-19 18:08:36 +09001024static int send_dg(res_state statp, res_params* params, const u_char* buf, int buflen, u_char* ans,
1025 int anssiz, int* terrno, int ns, int* v_circuit, int* gotsomewhere, time_t* at,
1026 int* rcode, int* delay) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001027 *at = time(NULL);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001028 *delay = 0;
1029 const HEADER* hp = (const HEADER*) (const void*) buf;
1030 HEADER* anhp = (HEADER*) (void*) ans;
1031 const struct sockaddr* nsap;
1032 int nsaplen;
1033 struct timespec now, timeout, finish, done;
1034 struct sockaddr_storage from;
1035 socklen_t fromlen;
1036 int resplen, n, s;
Bernie Innocenti55864192018-08-30 04:05:20 +09001037
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001038 nsap = get_nsaddr(statp, (size_t) ns);
1039 nsaplen = get_salen(nsap);
Ken Chencf6ded62018-10-16 23:12:09 +08001040 if (statp->_u._ext.nssocks[ns] == -1) {
1041 statp->_u._ext.nssocks[ns] = socket(nsap->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
1042 if (statp->_u._ext.nssocks[ns] < 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001043 switch (errno) {
1044 case EPROTONOSUPPORT:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001045 case EPFNOSUPPORT:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001046 case EAFNOSUPPORT:
chenbruce16adee42019-02-20 19:45:50 +08001047 Perror(statp, "socket(dg)", errno);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001048 return (0);
1049 default:
1050 *terrno = errno;
chenbruce16adee42019-02-20 19:45:50 +08001051 Perror(statp, "socket(dg)", errno);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001052 return (-1);
1053 }
1054 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001055
Ken Chencf6ded62018-10-16 23:12:09 +08001056 fchown(statp->_u._ext.nssocks[ns], AID_DNS, -1);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001057 if (statp->_mark != MARK_UNSET) {
Ken Chencf6ded62018-10-16 23:12:09 +08001058 if (setsockopt(statp->_u._ext.nssocks[ns], SOL_SOCKET, SO_MARK, &(statp->_mark),
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001059 sizeof(statp->_mark)) < 0) {
1060 res_nclose(statp);
1061 return -1;
1062 }
1063 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001064#ifndef CANNOT_CONNECT_DGRAM
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001065 /*
1066 * On a 4.3BSD+ machine (client and server,
1067 * actually), sending to a nameserver datagram
1068 * port with no nameserver will cause an
1069 * ICMP port unreachable message to be returned.
1070 * If our datagram socket is "connected" to the
1071 * server, we get an ECONNREFUSED error on the next
1072 * socket operation, and select returns if the
1073 * error message is received. We can thus detect
1074 * the absence of a nameserver without timing out.
1075 */
Ken Chencf6ded62018-10-16 23:12:09 +08001076 if (random_bind(statp->_u._ext.nssocks[ns], nsap->sa_family) < 0) {
chenbruce16adee42019-02-20 19:45:50 +08001077 Aerror(statp, "bind(dg)", errno, nsap, nsaplen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001078 res_nclose(statp);
1079 return (0);
1080 }
Ken Chencf6ded62018-10-16 23:12:09 +08001081 if (connect(statp->_u._ext.nssocks[ns], nsap, (socklen_t) nsaplen) < 0) {
chenbruce16adee42019-02-20 19:45:50 +08001082 Aerror(statp, "connect(dg)", errno, nsap, nsaplen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001083 res_nclose(statp);
1084 return (0);
1085 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001086#endif /* !CANNOT_CONNECT_DGRAM */
Ken Chenbab50142019-03-19 17:41:28 +08001087 LOG(DEBUG) << __func__ << ": new DG socket";
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001088 }
Ken Chencf6ded62018-10-16 23:12:09 +08001089 s = statp->_u._ext.nssocks[ns];
Bernie Innocenti55864192018-08-30 04:05:20 +09001090#ifndef CANNOT_CONNECT_DGRAM
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001091 if (send(s, (const char*) buf, (size_t) buflen, 0) != buflen) {
chenbruce16adee42019-02-20 19:45:50 +08001092 Perror(statp, "send", errno);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001093 res_nclose(statp);
Bernie Innocentid017e972019-03-03 19:39:53 +09001094 return 0;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001095 }
1096#else /* !CANNOT_CONNECT_DGRAM */
1097 if (sendto(s, (const char*) buf, buflen, 0, nsap, nsaplen) != buflen) {
chenbruce16adee42019-02-20 19:45:50 +08001098 Aerror(statp, "sendto", errno, nsap, nsaplen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001099 res_nclose(statp);
Bernie Innocentid017e972019-03-03 19:39:53 +09001100 return 0;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001101 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001102#endif /* !CANNOT_CONNECT_DGRAM */
1103
Bernie Innocentid017e972019-03-03 19:39:53 +09001104 // Wait for reply.
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001105 timeout = get_timeout(statp, params, ns);
1106 now = evNowTime();
1107 finish = evAddTime(now, timeout);
Bernie Innocenti55864192018-08-30 04:05:20 +09001108retry:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001109 n = retrying_poll(s, POLLIN, &finish);
Bernie Innocenti55864192018-08-30 04:05:20 +09001110
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001111 if (n == 0) {
1112 *rcode = RCODE_TIMEOUT;
Ken Chenbab50142019-03-19 17:41:28 +08001113 LOG(DEBUG) << __func__ << ": timeout";
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001114 *gotsomewhere = 1;
Bernie Innocentid017e972019-03-03 19:39:53 +09001115 return 0;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001116 }
1117 if (n < 0) {
chenbruce16adee42019-02-20 19:45:50 +08001118 Perror(statp, "poll", errno);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001119 res_nclose(statp);
Bernie Innocentid017e972019-03-03 19:39:53 +09001120 return 0;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001121 }
1122 errno = 0;
1123 fromlen = sizeof(from);
1124 resplen = recvfrom(s, (char*) ans, (size_t) anssiz, 0, (struct sockaddr*) (void*) &from,
1125 &fromlen);
1126 if (resplen <= 0) {
chenbruce16adee42019-02-20 19:45:50 +08001127 Perror(statp, "recvfrom", errno);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001128 res_nclose(statp);
Bernie Innocentid017e972019-03-03 19:39:53 +09001129 return 0;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001130 }
1131 *gotsomewhere = 1;
1132 if (resplen < HFIXEDSZ) {
1133 /*
1134 * Undersized message.
1135 */
Ken Chenbab50142019-03-19 17:41:28 +08001136 LOG(DEBUG) << __func__ << ": undersized: " << resplen;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001137 *terrno = EMSGSIZE;
1138 res_nclose(statp);
Bernie Innocentid017e972019-03-03 19:39:53 +09001139 return 0;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001140 }
1141 if (hp->id != anhp->id) {
1142 /*
1143 * response from old query, ignore it.
1144 * XXX - potential security hazard could
1145 * be detected here.
1146 */
Ken Chenbab50142019-03-19 17:41:28 +08001147 LOG(DEBUG) << __func__ << ": old answer:";
chenbrucee8911f92019-03-06 13:52:43 +08001148 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001149 goto retry;
1150 }
1151 if (!(statp->options & RES_INSECURE1) &&
1152 !res_ourserver_p(statp, (struct sockaddr*) (void*) &from)) {
1153 /*
1154 * response from wrong server? ignore it.
1155 * XXX - potential security hazard could
1156 * be detected here.
1157 */
Ken Chenbab50142019-03-19 17:41:28 +08001158 LOG(DEBUG) << __func__ << ": not our server:";
chenbrucee8911f92019-03-06 13:52:43 +08001159 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001160 goto retry;
1161 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001162 if (anhp->rcode == FORMERR && (statp->options & RES_USE_EDNS0) != 0U) {
1163 /*
1164 * Do not retry if the server do not understand EDNS0.
1165 * The case has to be captured here, as FORMERR packet do not
1166 * carry query section, hence res_queriesmatch() returns 0.
1167 */
Ken Chenbab50142019-03-19 17:41:28 +08001168 LOG(DEBUG) << __func__ << ": server rejected query with EDNS0:";
chenbrucee8911f92019-03-06 13:52:43 +08001169 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001170 /* record the error */
1171 statp->_flags |= RES_F_EDNS0ERR;
1172 res_nclose(statp);
Bernie Innocentid017e972019-03-03 19:39:53 +09001173 return 0;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001174 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001175 if (!(statp->options & RES_INSECURE2) &&
1176 !res_queriesmatch(buf, buf + buflen, ans, ans + anssiz)) {
1177 /*
1178 * response contains wrong query? ignore it.
1179 * XXX - potential security hazard could
1180 * be detected here.
1181 */
Ken Chenbab50142019-03-19 17:41:28 +08001182 LOG(DEBUG) << __func__ << ": wrong query name:";
chenbrucee8911f92019-03-06 13:52:43 +08001183 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001184 goto retry;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001185 }
1186 done = evNowTime();
1187 *delay = _res_stats_calculate_rtt(&done, &now);
1188 if (anhp->rcode == SERVFAIL || anhp->rcode == NOTIMP || anhp->rcode == REFUSED) {
Ken Chenbab50142019-03-19 17:41:28 +08001189 LOG(DEBUG) << __func__ << ": server rejected query:";
chenbrucee8911f92019-03-06 13:52:43 +08001190 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001191 res_nclose(statp);
chenbrucee8911f92019-03-06 13:52:43 +08001192 *rcode = anhp->rcode;
1193 return 0;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001194 }
1195 if (!(statp->options & RES_IGNTC) && anhp->tc) {
1196 /*
1197 * To get the rest of answer,
1198 * use TCP with same server.
1199 */
Ken Chenbab50142019-03-19 17:41:28 +08001200 LOG(DEBUG) << __func__ << ": truncated answer";
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001201 *v_circuit = 1;
1202 res_nclose(statp);
Bernie Innocentid017e972019-03-03 19:39:53 +09001203 return 1;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001204 }
1205 /*
1206 * All is well, or the error is fatal. Signal that the
1207 * next nameserver ought not be tried.
1208 */
1209 if (resplen > 0) {
1210 *rcode = anhp->rcode;
1211 }
Bernie Innocentid017e972019-03-03 19:39:53 +09001212 return resplen;
Bernie Innocenti55864192018-08-30 04:05:20 +09001213}
1214
chenbruce16adee42019-02-20 19:45:50 +08001215static void Aerror(const res_state statp, const char* string, int error,
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001216 const struct sockaddr* address, int alen) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001217 const int save = errno;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001218 char hbuf[NI_MAXHOST];
1219 char sbuf[NI_MAXSERV];
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001220 constexpr int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
Bernie Innocenti55864192018-08-30 04:05:20 +09001221
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001222 if ((statp->options & RES_DEBUG) != 0U) {
1223 if (getnameinfo(address, (socklen_t) alen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
1224 niflags)) {
1225 strncpy(hbuf, "?", sizeof(hbuf) - 1);
1226 hbuf[sizeof(hbuf) - 1] = '\0';
1227 strncpy(sbuf, "?", sizeof(sbuf) - 1);
1228 sbuf[sizeof(sbuf) - 1] = '\0';
1229 }
Ken Chenbab50142019-03-19 17:41:28 +08001230 LOG(DEBUG) << __func__ << ": " << string << " ([" << hbuf << "]." << sbuf
chenbruce16adee42019-02-20 19:45:50 +08001231 << "): " << strerror(error);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001232 }
1233 errno = save;
Bernie Innocenti55864192018-08-30 04:05:20 +09001234}
1235
chenbruce16adee42019-02-20 19:45:50 +08001236static void Perror(const res_state statp, const char* string, int error) {
Elliott Hughes569386e2019-03-08 12:02:55 -08001237 if ((statp->options & RES_DEBUG) != 0U) {
Ken Chenbab50142019-03-19 17:41:28 +08001238 LOG(DEBUG) << __func__ << ": " << string << ": " << strerror(error);
Elliott Hughes569386e2019-03-08 12:02:55 -08001239 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001240}
1241
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001242static int sock_eq(struct sockaddr* a, struct sockaddr* b) {
1243 struct sockaddr_in *a4, *b4;
1244 struct sockaddr_in6 *a6, *b6;
Bernie Innocenti55864192018-08-30 04:05:20 +09001245
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001246 if (a->sa_family != b->sa_family) return 0;
1247 switch (a->sa_family) {
1248 case AF_INET:
1249 a4 = (struct sockaddr_in*) (void*) a;
1250 b4 = (struct sockaddr_in*) (void*) b;
1251 return a4->sin_port == b4->sin_port && a4->sin_addr.s_addr == b4->sin_addr.s_addr;
1252 case AF_INET6:
1253 a6 = (struct sockaddr_in6*) (void*) a;
1254 b6 = (struct sockaddr_in6*) (void*) b;
1255 return a6->sin6_port == b6->sin6_port &&
Bernie Innocenti55864192018-08-30 04:05:20 +09001256#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001257 a6->sin6_scope_id == b6->sin6_scope_id &&
Bernie Innocenti55864192018-08-30 04:05:20 +09001258#endif
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001259 IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
1260 default:
1261 return 0;
1262 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001263}
Mike Yua46fae72018-11-01 20:07:00 +08001264
lifr72e88a72019-07-26 03:17:43 +08001265PrivateDnsModes convertEnumType(PrivateDnsMode privateDnsmode) {
1266 switch (privateDnsmode) {
1267 case PrivateDnsMode::OFF:
1268 return PrivateDnsModes::PDM_OFF;
1269 case PrivateDnsMode::OPPORTUNISTIC:
1270 return PrivateDnsModes::PDM_OPPORTUNISTIC;
1271 case PrivateDnsMode::STRICT:
1272 return PrivateDnsModes::PDM_STRICT;
1273 }
1274 return PrivateDnsModes::PDM_UNKNOWN;
1275}
1276
Luke Huang490551d2018-11-21 20:37:50 +08001277static int res_tls_send(res_state statp, const Slice query, const Slice answer, int* rcode,
Mike Yu69615f62018-11-06 15:42:36 +08001278 bool* fallback) {
1279 int resplen = 0;
Mike Yua46fae72018-11-01 20:07:00 +08001280 const unsigned netId = statp->netid;
Mike Yua46fae72018-11-01 20:07:00 +08001281
Mike Yu69615f62018-11-06 15:42:36 +08001282 PrivateDnsStatus privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
lifr72e88a72019-07-26 03:17:43 +08001283 statp->event->set_private_dns_modes(convertEnumType(privateDnsStatus.mode));
Mike Yu69615f62018-11-06 15:42:36 +08001284
1285 if (privateDnsStatus.mode == PrivateDnsMode::OFF) {
1286 *fallback = true;
1287 return -1;
Mike Yua46fae72018-11-01 20:07:00 +08001288 }
1289
Mike Yua46fae72018-11-01 20:07:00 +08001290 if (privateDnsStatus.validatedServers.empty()) {
1291 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
Mike Yu69615f62018-11-06 15:42:36 +08001292 *fallback = true;
1293 return -1;
Mike Yua46fae72018-11-01 20:07:00 +08001294 } else {
1295 // Sleep and iterate some small number of times checking for the
1296 // arrival of resolved and validated server IP addresses, instead
1297 // of returning an immediate error.
Mike Yu5b9ffb22018-12-02 17:54:29 +09001298 // This is needed because as soon as a network becomes the default network, apps will
1299 // send DNS queries on that network. If no servers have yet validated, and we do not
1300 // block those queries, they would immediately fail, causing application-visible errors.
1301 // Note that this can happen even before the network validates, since an unvalidated
1302 // network can become the default network if no validated networks are available.
1303 //
1304 // TODO: see if there is a better way to address this problem, such as buffering the
1305 // queries in a queue or only blocking queries for the first few seconds after a default
1306 // network change.
Mike Yu69615f62018-11-06 15:42:36 +08001307 for (int i = 0; i < 42; i++) {
1308 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1309 if (!gPrivateDnsConfiguration.getStatus(netId).validatedServers.empty()) {
1310 privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
1311 break;
1312 }
1313 }
1314 if (privateDnsStatus.validatedServers.empty()) {
1315 return -1;
1316 }
Mike Yua46fae72018-11-01 20:07:00 +08001317 }
1318 }
1319
chenbruce16adee42019-02-20 19:45:50 +08001320 LOG(INFO) << __func__ << ": performing query over TLS";
Mike Yua46fae72018-11-01 20:07:00 +08001321
Frank Li08ce7b82019-06-27 10:11:52 -07001322 const auto response = sDnsTlsDispatcher.query(privateDnsStatus.validatedServers, statp, query,
Mike Yu69615f62018-11-06 15:42:36 +08001323 answer, &resplen);
Mike Yua46fae72018-11-01 20:07:00 +08001324
chenbruce16adee42019-02-20 19:45:50 +08001325 LOG(INFO) << __func__ << ": TLS query result: " << static_cast<int>(response);
Mike Yua46fae72018-11-01 20:07:00 +08001326
1327 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
1328 // In opportunistic mode, handle falling back to cleartext in some
1329 // cases (DNS shouldn't fail if a validated opportunistic mode server
1330 // becomes unreachable for some reason).
1331 switch (response) {
Mike Yu69615f62018-11-06 15:42:36 +08001332 case DnsTlsTransport::Response::success:
Luke Huang490551d2018-11-21 20:37:50 +08001333 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yu69615f62018-11-06 15:42:36 +08001334 return resplen;
Mike Yua46fae72018-11-01 20:07:00 +08001335 case DnsTlsTransport::Response::network_error:
Mike Yu69615f62018-11-06 15:42:36 +08001336 // No need to set the error timeout here since it will fallback to UDP.
Mike Yua46fae72018-11-01 20:07:00 +08001337 case DnsTlsTransport::Response::internal_error:
1338 // Note: this will cause cleartext queries to be emitted, with
1339 // all of the EDNS0 goodness enabled. Fingers crossed. :-/
Mike Yu69615f62018-11-06 15:42:36 +08001340 *fallback = true;
1341 [[fallthrough]];
Mike Yua46fae72018-11-01 20:07:00 +08001342 default:
Mike Yu69615f62018-11-06 15:42:36 +08001343 return -1;
1344 }
1345 } else {
1346 // Strict mode
1347 switch (response) {
1348 case DnsTlsTransport::Response::success:
Luke Huang490551d2018-11-21 20:37:50 +08001349 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yu69615f62018-11-06 15:42:36 +08001350 return resplen;
1351 case DnsTlsTransport::Response::network_error:
1352 // This case happens when the query stored in DnsTlsTransport is expired since
1353 // either 1) the query has been tried for 3 times but no response or 2) fail to
1354 // establish the connection with the server.
Luke Huang490551d2018-11-21 20:37:50 +08001355 *rcode = RCODE_TIMEOUT;
Mike Yu69615f62018-11-06 15:42:36 +08001356 [[fallthrough]];
1357 default:
1358 return -1;
Mike Yua46fae72018-11-01 20:07:00 +08001359 }
1360 }
Mike Yua46fae72018-11-01 20:07:00 +08001361}
Luke Huangeefb7772018-11-19 20:17:26 +08001362
Luke Huang952d0942018-12-26 16:53:03 +08001363int resolv_res_nsend(const android_net_context* netContext, const uint8_t* msg, int msgLen,
Frank Li08ce7b82019-06-27 10:11:52 -07001364 uint8_t* ans, int ansLen, int* rcode, uint32_t flags,
1365 NetworkDnsEventReported* event) {
1366 assert(event != nullptr);
Luke Huangeefb7772018-11-19 20:17:26 +08001367 res_state res = res_get_state();
Frank Li08ce7b82019-06-27 10:11:52 -07001368 res_setnetcontext(res, netContext, event);
Luke Huangeefb7772018-11-19 20:17:26 +08001369 _resolv_populate_res_for_net(res);
1370 *rcode = NOERROR;
Luke Huang952d0942018-12-26 16:53:03 +08001371 return res_nsend(res, msg, msgLen, ans, ansLen, rcode, flags);
Bernie Innocentiad4e26e2019-01-30 11:16:36 +09001372}