blob: 66af1c2ec277982acff220a1b8b290142dda0657 [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>
Bernie Innocentiad4e26e2019-01-30 11:16:36 +0900104#include "DnsTlsDispatcher.h"
105#include "DnsTlsTransport.h"
106#include "PrivateDnsConfiguration.h"
Bernie Innocenti189eb502018-10-01 23:10:18 +0900107#include "netd_resolv/resolv.h"
108#include "netd_resolv/stats.h"
Bernie Innocenti2fd418e2018-08-30 12:04:03 +0900109#include "private/android_filesystem_config.h"
Bernie Innocenti189eb502018-10-01 23:10:18 +0900110#include "res_state_ext.h"
Bernie Innocenti2fd418e2018-08-30 12:04:03 +0900111#include "resolv_cache.h"
Bernie Innocenti2fd418e2018-08-30 12:04:03 +0900112#include "resolv_private.h"
Bernie Innocenti2fd418e2018-08-30 12:04:03 +0900113
Mike Yua46fae72018-11-01 20:07:00 +0800114// TODO: use the namespace something like android::netd_resolv for libnetd_resolv
115using namespace android::net;
Bernie Innocentiad4e26e2019-01-30 11:16:36 +0900116using android::netdutils::Slice;
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900117
Mike Yua46fae72018-11-01 20:07:00 +0800118static DnsTlsDispatcher sDnsTlsDispatcher;
119
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900120static int get_salen(const struct sockaddr*);
121static struct sockaddr* get_nsaddr(res_state, size_t);
Bernie Innocenti34de3ba2019-02-19 18:08:36 +0900122static int send_vc(res_state, res_params* params, const u_char*, int, u_char*, int, int*, int,
123 time_t*, int*, int*);
124static int send_dg(res_state, res_params* params, const u_char*, int, u_char*, int, int*, int, int*,
125 int*, time_t*, int*, int*);
chenbruce16adee42019-02-20 19:45:50 +0800126static void Aerror(const res_state, const char*, int, const struct sockaddr*, int);
127static void Perror(const res_state, const char*, int);
128
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900129static int sock_eq(struct sockaddr*, struct sockaddr*);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900130static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
131 const struct timespec timeout);
Bernie Innocenti55864192018-08-30 04:05:20 +0900132static int retrying_poll(const int sock, short events, const struct timespec* finish);
Luke Huang490551d2018-11-21 20:37:50 +0800133static int res_tls_send(res_state, const Slice query, const Slice answer, int* rcode,
Mike Yu69615f62018-11-06 15:42:36 +0800134 bool* fallback);
Bernie Innocenti55864192018-08-30 04:05:20 +0900135
136/* BIONIC-BEGIN: implement source port randomization */
Bernie Innocenti55864192018-08-30 04:05:20 +0900137
Bernie Innocentif89b3512018-08-30 07:34:37 +0900138// BEGIN: Code copied from ISC eventlib
139// TODO: move away from this code
140
141#define BILLION 1000000000
142
143static struct timespec evConsTime(time_t sec, long nsec) {
144 struct timespec x;
145
146 x.tv_sec = sec;
147 x.tv_nsec = nsec;
148 return (x);
149}
150
151static struct timespec evAddTime(struct timespec addend1, struct timespec addend2) {
152 struct timespec x;
153
154 x.tv_sec = addend1.tv_sec + addend2.tv_sec;
155 x.tv_nsec = addend1.tv_nsec + addend2.tv_nsec;
156 if (x.tv_nsec >= BILLION) {
157 x.tv_sec++;
158 x.tv_nsec -= BILLION;
159 }
160 return (x);
161}
162
163static struct timespec evSubTime(struct timespec minuend, struct timespec subtrahend) {
164 struct timespec x;
165
166 x.tv_sec = minuend.tv_sec - subtrahend.tv_sec;
167 if (minuend.tv_nsec >= subtrahend.tv_nsec)
168 x.tv_nsec = minuend.tv_nsec - subtrahend.tv_nsec;
169 else {
170 x.tv_nsec = BILLION - subtrahend.tv_nsec + minuend.tv_nsec;
171 x.tv_sec--;
172 }
173 return (x);
174}
175
176static int evCmpTime(struct timespec a, struct timespec b) {
177#define SGN(x) ((x) < 0 ? (-1) : (x) > 0 ? (1) : (0));
178 time_t s = a.tv_sec - b.tv_sec;
179 long n;
180
181 if (s != 0) return SGN(s);
182
183 n = a.tv_nsec - b.tv_nsec;
184 return SGN(n);
185}
186
Bernie Innocentif89b3512018-08-30 07:34:37 +0900187static struct timespec evNowTime(void) {
Bernie Innocentif89b3512018-08-30 07:34:37 +0900188 struct timespec tsnow;
Bernie Innocenti357339c2018-08-31 16:11:41 +0900189 clock_gettime(CLOCK_REALTIME, &tsnow);
190 return tsnow;
Bernie Innocentif89b3512018-08-30 07:34:37 +0900191}
192
193static struct iovec evConsIovec(void* buf, size_t cnt) {
194 struct iovec ret;
195
196 memset(&ret, 0xf5, sizeof ret);
197 ret.iov_base = buf;
198 ret.iov_len = cnt;
Bernie Innocenti357339c2018-08-31 16:11:41 +0900199 return ret;
Bernie Innocentif89b3512018-08-30 07:34:37 +0900200}
201
202// END: Code copied from ISC eventlib
203
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900204static int random_bind(int s, int family) {
nuccachene172a4e2018-10-23 17:10:58 +0800205 sockaddr_union u;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900206 int j;
207 socklen_t slen;
Bernie Innocenti55864192018-08-30 04:05:20 +0900208
209 /* clear all, this also sets the IP4/6 address to 'any' */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900210 memset(&u, 0, sizeof u);
Bernie Innocenti55864192018-08-30 04:05:20 +0900211
212 switch (family) {
213 case AF_INET:
214 u.sin.sin_family = family;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900215 slen = sizeof u.sin;
Bernie Innocenti55864192018-08-30 04:05:20 +0900216 break;
217 case AF_INET6:
218 u.sin6.sin6_family = family;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900219 slen = sizeof u.sin6;
Bernie Innocenti55864192018-08-30 04:05:20 +0900220 break;
221 default:
222 errno = EPROTO;
223 return -1;
224 }
225
226 /* first try to bind to a random source port a few times */
227 for (j = 0; j < 10; j++) {
228 /* find a random port between 1025 .. 65534 */
Luke Huang042e9422019-02-13 14:05:02 +0800229 int port = 1025 + (arc4random_uniform(65535 - 1025));
Bernie Innocenti55864192018-08-30 04:05:20 +0900230 if (family == AF_INET)
231 u.sin.sin_port = htons(port);
232 else
233 u.sin6.sin6_port = htons(port);
234
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900235 if (!bind(s, &u.sa, slen)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900236 }
237
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900238 // nothing after 10 attempts, our network table is probably busy
239 // let the system decide which port is best
Bernie Innocenti55864192018-08-30 04:05:20 +0900240 if (family == AF_INET)
241 u.sin.sin_port = 0;
242 else
243 u.sin6.sin6_port = 0;
244
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900245 return bind(s, &u.sa, slen);
Bernie Innocenti55864192018-08-30 04:05:20 +0900246}
247/* BIONIC-END */
248
Bernie Innocenti55864192018-08-30 04:05:20 +0900249/* int
250 * res_isourserver(ina)
251 * looks up "ina" in _res.ns_addr_list[]
252 * returns:
253 * 0 : not found
254 * >0 : found
255 * author:
256 * paul vixie, 29may94
257 */
Bernie Innocenti4acba1a2018-09-26 11:52:04 +0900258static int res_ourserver_p(const res_state statp, const sockaddr* sa) {
259 const sockaddr_in *inp, *srv;
260 const sockaddr_in6 *in6p, *srv6;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900261 int ns;
Bernie Innocenti55864192018-08-30 04:05:20 +0900262
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900263 switch (sa->sa_family) {
264 case AF_INET:
265 inp = (const struct sockaddr_in*) (const void*) sa;
266 for (ns = 0; ns < statp->nscount; ns++) {
267 srv = (struct sockaddr_in*) (void*) get_nsaddr(statp, (size_t) ns);
268 if (srv->sin_family == inp->sin_family && srv->sin_port == inp->sin_port &&
269 (srv->sin_addr.s_addr == INADDR_ANY ||
270 srv->sin_addr.s_addr == inp->sin_addr.s_addr))
Bernie Innocenti4acba1a2018-09-26 11:52:04 +0900271 return 1;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900272 }
273 break;
274 case AF_INET6:
Ken Chencf6ded62018-10-16 23:12:09 +0800275 if (statp->_u._ext.ext == NULL) break;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900276 in6p = (const struct sockaddr_in6*) (const void*) sa;
277 for (ns = 0; ns < statp->nscount; ns++) {
278 srv6 = (struct sockaddr_in6*) (void*) get_nsaddr(statp, (size_t) ns);
279 if (srv6->sin6_family == in6p->sin6_family && srv6->sin6_port == in6p->sin6_port &&
Bernie Innocenti55864192018-08-30 04:05:20 +0900280#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900281 (srv6->sin6_scope_id == 0 || srv6->sin6_scope_id == in6p->sin6_scope_id) &&
Bernie Innocenti55864192018-08-30 04:05:20 +0900282#endif
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900283 (IN6_IS_ADDR_UNSPECIFIED(&srv6->sin6_addr) ||
284 IN6_ARE_ADDR_EQUAL(&srv6->sin6_addr, &in6p->sin6_addr)))
Bernie Innocenti4acba1a2018-09-26 11:52:04 +0900285 return 1;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900286 }
287 break;
288 default:
289 break;
290 }
Bernie Innocenti4acba1a2018-09-26 11:52:04 +0900291 return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900292}
293
294/* int
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900295 * res_nameinquery(name, type, cl, buf, eom)
296 * look for (name, type, cl) in the query section of packet (buf, eom)
Bernie Innocenti55864192018-08-30 04:05:20 +0900297 * requires:
298 * buf + HFIXEDSZ <= eom
299 * returns:
300 * -1 : format error
301 * 0 : not found
302 * >0 : found
303 * author:
304 * paul vixie, 29may94
305 */
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900306int res_nameinquery(const char* name, int type, int cl, const u_char* buf, const u_char* eom) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900307 const u_char* cp = buf + HFIXEDSZ;
308 int qdcount = ntohs(((const HEADER*) (const void*) buf)->qdcount);
Bernie Innocenti55864192018-08-30 04:05:20 +0900309
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900310 while (qdcount-- > 0) {
311 char tname[MAXDNAME + 1];
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900312 int n = dn_expand(buf, eom, cp, tname, sizeof tname);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900313 if (n < 0) return (-1);
314 cp += n;
315 if (cp + 2 * INT16SZ > eom) return (-1);
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900316 int ttype = ns_get16(cp);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900317 cp += INT16SZ;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900318 int tclass = ns_get16(cp);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900319 cp += INT16SZ;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900320 if (ttype == type && tclass == cl && ns_samename(tname, name) == 1) return (1);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900321 }
322 return (0);
Bernie Innocenti55864192018-08-30 04:05:20 +0900323}
324
325/* int
326 * res_queriesmatch(buf1, eom1, buf2, eom2)
327 * is there a 1:1 mapping of (name,type,class)
328 * in (buf1,eom1) and (buf2,eom2)?
329 * returns:
330 * -1 : format error
331 * 0 : not a 1:1 mapping
332 * >0 : is a 1:1 mapping
333 * author:
334 * paul vixie, 29may94
335 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900336int res_queriesmatch(const u_char* buf1, const u_char* eom1, const u_char* buf2,
337 const u_char* eom2) {
338 const u_char* cp = buf1 + HFIXEDSZ;
339 int qdcount = ntohs(((const HEADER*) (const void*) buf1)->qdcount);
Bernie Innocenti55864192018-08-30 04:05:20 +0900340
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900341 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2) return (-1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900342
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900343 /*
344 * Only header section present in replies to
345 * dynamic update packets.
346 */
347 if ((((const HEADER*) (const void*) buf1)->opcode == ns_o_update) &&
348 (((const HEADER*) (const void*) buf2)->opcode == ns_o_update))
349 return (1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900350
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900351 if (qdcount != ntohs(((const HEADER*) (const void*) buf2)->qdcount)) return (0);
352 while (qdcount-- > 0) {
353 char tname[MAXDNAME + 1];
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900354 int n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900355 if (n < 0) return (-1);
356 cp += n;
357 if (cp + 2 * INT16SZ > eom1) return (-1);
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900358 int ttype = ns_get16(cp);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900359 cp += INT16SZ;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900360 int tclass = ns_get16(cp);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900361 cp += INT16SZ;
362 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2)) return (0);
363 }
364 return (1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900365}
366
Luke Huang952d0942018-12-26 16:53:03 +0800367int res_nsend(res_state statp, const u_char* buf, int buflen, u_char* ans, int anssiz, int* rcode,
368 uint32_t flags) {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900369 int gotsomewhere, terrno, v_circuit, resplen, n;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900370 ResolvCacheStatus cache_status = RESOLV_CACHE_UNSUPPORTED;
Bernie Innocenti55864192018-08-30 04:05:20 +0900371
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900372 if (anssiz < HFIXEDSZ) {
Luke Huang8c0e98f2018-12-03 15:37:28 +0800373 // TODO: Remove errno once callers stop using it
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900374 errno = EINVAL;
Luke Huang8c0e98f2018-12-03 15:37:28 +0800375 return -EINVAL;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900376 }
chenbruce16adee42019-02-20 19:45:50 +0800377 LOG(DEBUG) << ";; " << __func__;
378 res_pquery(statp, buf, buflen);
379
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900380 v_circuit = (statp->options & RES_USEVC) || buflen > PACKETSZ;
381 gotsomewhere = 0;
382 terrno = ETIMEDOUT;
Bernie Innocenti55864192018-08-30 04:05:20 +0900383
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900384 int anslen = 0;
Luke Huang952d0942018-12-26 16:53:03 +0800385 cache_status = _resolv_cache_lookup(statp->netid, buf, buflen, ans, anssiz, &anslen, flags);
Bernie Innocenti55864192018-08-30 04:05:20 +0900386
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900387 if (cache_status == RESOLV_CACHE_FOUND) {
388 return anslen;
389 } else if (cache_status != RESOLV_CACHE_UNSUPPORTED) {
390 // had a cache miss for a known network, so populate the thread private
391 // data so the normal resolve path can do its thing
392 _resolv_populate_res_for_net(statp);
393 }
394 if (statp->nscount == 0) {
395 // We have no nameservers configured, so there's no point trying.
396 // Tell the cache the query failed, or any retries and anyone else asking the same
397 // question will block for PENDING_REQUEST_TIMEOUT seconds instead of failing fast.
Luke Huang952d0942018-12-26 16:53:03 +0800398 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huang8c0e98f2018-12-03 15:37:28 +0800399
400 // TODO: Remove errno once callers stop using it
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900401 errno = ESRCH;
Luke Huang8c0e98f2018-12-03 15:37:28 +0800402 return -ESRCH;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900403 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900404
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900405 /*
406 * If the ns_addr_list in the resolver context has changed, then
407 * invalidate our cached copy and the associated timing data.
408 */
Ken Chencf6ded62018-10-16 23:12:09 +0800409 if (statp->_u._ext.nscount != 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900410 int needclose = 0;
411 struct sockaddr_storage peer;
412 socklen_t peerlen;
Bernie Innocenti55864192018-08-30 04:05:20 +0900413
Ken Chencf6ded62018-10-16 23:12:09 +0800414 if (statp->_u._ext.nscount != statp->nscount) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900415 needclose++;
416 } else {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900417 for (int ns = 0; ns < statp->nscount; ns++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900418 if (statp->nsaddr_list[ns].sin_family &&
419 !sock_eq((struct sockaddr*) (void*) &statp->nsaddr_list[ns],
Ken Chencf6ded62018-10-16 23:12:09 +0800420 (struct sockaddr*) (void*) &statp->_u._ext.ext->nsaddrs[ns])) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900421 needclose++;
422 break;
423 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900424
Ken Chencf6ded62018-10-16 23:12:09 +0800425 if (statp->_u._ext.nssocks[ns] == -1) continue;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900426 peerlen = sizeof(peer);
Ken Chencf6ded62018-10-16 23:12:09 +0800427 if (getpeername(statp->_u._ext.nssocks[ns], (struct sockaddr*) (void*) &peer,
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900428 &peerlen) < 0) {
429 needclose++;
430 break;
431 }
432 if (!sock_eq((struct sockaddr*) (void*) &peer, get_nsaddr(statp, (size_t) ns))) {
433 needclose++;
434 break;
435 }
436 }
437 }
438 if (needclose) {
439 res_nclose(statp);
Ken Chencf6ded62018-10-16 23:12:09 +0800440 statp->_u._ext.nscount = 0;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900441 }
442 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900443
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900444 /*
445 * Maybe initialize our private copy of the ns_addr_list.
446 */
Ken Chencf6ded62018-10-16 23:12:09 +0800447 if (statp->_u._ext.nscount == 0) {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900448 for (int ns = 0; ns < statp->nscount; ns++) {
Ken Chencf6ded62018-10-16 23:12:09 +0800449 statp->_u._ext.nstimes[ns] = RES_MAXTIME;
450 statp->_u._ext.nssocks[ns] = -1;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900451 if (!statp->nsaddr_list[ns].sin_family) continue;
Ken Chencf6ded62018-10-16 23:12:09 +0800452 statp->_u._ext.ext->nsaddrs[ns].sin = statp->nsaddr_list[ns];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900453 }
Ken Chencf6ded62018-10-16 23:12:09 +0800454 statp->_u._ext.nscount = statp->nscount;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900455 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900456
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900457 /*
458 * Some resolvers want to even out the load on their nameservers.
459 * Note that RES_BLAST overrides RES_ROTATE.
460 */
461 if ((statp->options & RES_ROTATE) != 0U && (statp->options & RES_BLAST) == 0U) {
nuccachene172a4e2018-10-23 17:10:58 +0800462 sockaddr_union inu;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900463 struct sockaddr_in ina;
464 int lastns = statp->nscount - 1;
465 int fd;
466 u_int16_t nstime;
Bernie Innocenti55864192018-08-30 04:05:20 +0900467
Ken Chencf6ded62018-10-16 23:12:09 +0800468 if (statp->_u._ext.ext != NULL) inu = statp->_u._ext.ext->nsaddrs[0];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900469 ina = statp->nsaddr_list[0];
Ken Chencf6ded62018-10-16 23:12:09 +0800470 fd = statp->_u._ext.nssocks[0];
471 nstime = statp->_u._ext.nstimes[0];
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900472 for (int ns = 0; ns < lastns; ns++) {
Ken Chencf6ded62018-10-16 23:12:09 +0800473 if (statp->_u._ext.ext != NULL)
474 statp->_u._ext.ext->nsaddrs[ns] = statp->_u._ext.ext->nsaddrs[ns + 1];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900475 statp->nsaddr_list[ns] = statp->nsaddr_list[ns + 1];
Ken Chencf6ded62018-10-16 23:12:09 +0800476 statp->_u._ext.nssocks[ns] = statp->_u._ext.nssocks[ns + 1];
477 statp->_u._ext.nstimes[ns] = statp->_u._ext.nstimes[ns + 1];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900478 }
Ken Chencf6ded62018-10-16 23:12:09 +0800479 if (statp->_u._ext.ext != NULL) statp->_u._ext.ext->nsaddrs[lastns] = inu;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900480 statp->nsaddr_list[lastns] = ina;
Ken Chencf6ded62018-10-16 23:12:09 +0800481 statp->_u._ext.nssocks[lastns] = fd;
482 statp->_u._ext.nstimes[lastns] = nstime;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900483 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900484
Bernie Innocenti34de3ba2019-02-19 18:08:36 +0900485 res_stats stats[MAXNS];
486 res_params params;
waynemad193e4d2019-02-18 17:47:59 +0800487 int revision_id = resolv_cache_get_resolver_stats(statp->netid, &params, stats);
488 bool usable_servers[MAXNS];
489 android_net_res_stats_get_usable_servers(&params, stats, statp->nscount, usable_servers);
490 if (params.retry_count != 0) statp->retry = params.retry_count;
491
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900492 /*
493 * Send request, RETRY times, or until successful.
494 */
Luke Huang952d0942018-12-26 16:53:03 +0800495 int retryTimes = (flags & ANDROID_RESOLV_NO_RETRY) ? 1 : statp->retry;
496
497 for (int attempt = 0; attempt < retryTimes; ++attempt) {
Bernie Innocenti55864192018-08-30 04:05:20 +0900498
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900499 for (int ns = 0; ns < statp->nscount; ns++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900500 if (!usable_servers[ns]) continue;
501 struct sockaddr* nsap;
502 int nsaplen;
503 time_t now = 0;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900504 int delay = 0;
Mike Yu69615f62018-11-06 15:42:36 +0800505 *rcode = RCODE_INTERNAL_ERROR;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900506 nsap = get_nsaddr(statp, (size_t) ns);
507 nsaplen = get_salen(nsap);
Bernie Innocenti55864192018-08-30 04:05:20 +0900508
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900509 same_ns:
Mike Yu69615f62018-11-06 15:42:36 +0800510 // TODO: Since we expect there is only one DNS server being queried here while this
511 // function tries to query all of private DNS servers. Consider moving it to other
512 // reasonable place. In addition, maybe add stats for private DNS.
513 if (!statp->use_local_nameserver) {
514 bool fallback = false;
515 resplen = res_tls_send(statp, Slice(const_cast<u_char*>(buf), buflen),
516 Slice(ans, anssiz), rcode, &fallback);
517 if (resplen > 0) {
518 if (cache_status == RESOLV_CACHE_NOTFOUND) {
519 _resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
520 }
521 return resplen;
Mike Yua46fae72018-11-01 20:07:00 +0800522 }
Mike Yu69615f62018-11-06 15:42:36 +0800523 if (!fallback) {
Luke Huang952d0942018-12-26 16:53:03 +0800524 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huang8c0e98f2018-12-03 15:37:28 +0800525 res_nclose(statp);
526 return -terrno;
Mike Yu69615f62018-11-06 15:42:36 +0800527 }
528 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900529
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900530 [[maybe_unused]] static const int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
531 [[maybe_unused]] char abuf[NI_MAXHOST];
chenbruce16adee42019-02-20 19:45:50 +0800532
533 if (getnameinfo(nsap, (socklen_t)nsaplen, abuf, sizeof(abuf), NULL, 0, niflags) == 0)
534 LOG(DEBUG) << ";; Querying server (# " << ns + 1 << ") address = " << abuf;
Bernie Innocenti55864192018-08-30 04:05:20 +0900535
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900536 if (v_circuit) {
537 /* Use VC; at most one attempt per server. */
Luke Huang952d0942018-12-26 16:53:03 +0800538 bool shouldRecordStats = (attempt == 0);
539 attempt = retryTimes;
Bernie Innocenti55864192018-08-30 04:05:20 +0900540
Mike Yu69615f62018-11-06 15:42:36 +0800541 n = send_vc(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &now, rcode,
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900542 &delay);
Bernie Innocenti55864192018-08-30 04:05:20 +0900543
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900544 /*
545 * Only record stats the first time we try a query. This ensures that
546 * queries that deterministically fail (e.g., a name that always returns
547 * SERVFAIL or times out) do not unduly affect the stats.
548 */
Luke Huang952d0942018-12-26 16:53:03 +0800549 if (shouldRecordStats) {
Bernie Innocenti189eb502018-10-01 23:10:18 +0900550 res_sample sample;
Mike Yu69615f62018-11-06 15:42:36 +0800551 _res_stats_set_sample(&sample, now, *rcode, delay);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900552 _resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, ns, &sample,
553 params.max_samples);
554 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900555
chenbruce16adee42019-02-20 19:45:50 +0800556 LOG(INFO) << "used send_vc " << n;
Bernie Innocenti55864192018-08-30 04:05:20 +0900557
Luke Huang8c0e98f2018-12-03 15:37:28 +0800558 if (n < 0) {
Luke Huang952d0942018-12-26 16:53:03 +0800559 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huang8c0e98f2018-12-03 15:37:28 +0800560 res_nclose(statp);
561 return -terrno;
562 };
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900563 if (n == 0) goto next_ns;
564 resplen = n;
565 } else {
566 /* Use datagrams. */
chenbruce16adee42019-02-20 19:45:50 +0800567 LOG(INFO) << "using send_dg";
Bernie Innocenti55864192018-08-30 04:05:20 +0900568
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900569 n = send_dg(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &v_circuit,
Mike Yu69615f62018-11-06 15:42:36 +0800570 &gotsomewhere, &now, rcode, &delay);
Bernie Innocenti55864192018-08-30 04:05:20 +0900571
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900572 /* Only record stats the first time we try a query. See above. */
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900573 if (attempt == 0) {
Bernie Innocenti189eb502018-10-01 23:10:18 +0900574 res_sample sample;
Mike Yu69615f62018-11-06 15:42:36 +0800575 _res_stats_set_sample(&sample, now, *rcode, delay);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900576 _resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, ns, &sample,
577 params.max_samples);
578 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900579
chenbruce16adee42019-02-20 19:45:50 +0800580 LOG(INFO) << "used send_dg " << n;
Bernie Innocenti55864192018-08-30 04:05:20 +0900581
Luke Huang8c0e98f2018-12-03 15:37:28 +0800582 if (n < 0) {
Luke Huang952d0942018-12-26 16:53:03 +0800583 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huang8c0e98f2018-12-03 15:37:28 +0800584 res_nclose(statp);
585 return -terrno;
586 };
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900587 if (n == 0) goto next_ns;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900588 if (v_circuit) goto same_ns;
589 resplen = n;
590 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900591
chenbruce16adee42019-02-20 19:45:50 +0800592 LOG(DEBUG) << ";; got answer:";
593 res_pquery(statp, ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti55864192018-08-30 04:05:20 +0900594
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900595 if (cache_status == RESOLV_CACHE_NOTFOUND) {
596 _resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
597 }
598 /*
599 * If we have temporarily opened a virtual circuit,
600 * or if we haven't been asked to keep a socket open,
601 * close the socket.
602 */
603 if ((v_circuit && (statp->options & RES_USEVC) == 0U) ||
604 (statp->options & RES_STAYOPEN) == 0U) {
605 res_nclose(statp);
606 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900607 return (resplen);
608 next_ns:;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900609 } // for each ns
610 } // for each retry
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900611 res_nclose(statp);
612 if (!v_circuit) {
Luke Huang8c0e98f2018-12-03 15:37:28 +0800613 if (!gotsomewhere) {
614 // TODO: Remove errno once callers stop using it
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900615 errno = ECONNREFUSED; /* no nameservers found */
Luke Huang8c0e98f2018-12-03 15:37:28 +0800616 terrno = ECONNREFUSED;
617 } else {
618 // TODO: Remove errno once callers stop using it
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900619 errno = ETIMEDOUT; /* no answer obtained */
Luke Huang8c0e98f2018-12-03 15:37:28 +0800620 terrno = ETIMEDOUT;
621 }
622 } else {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900623 errno = terrno;
Luke Huang8c0e98f2018-12-03 15:37:28 +0800624 }
Luke Huang952d0942018-12-26 16:53:03 +0800625 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huang8c0e98f2018-12-03 15:37:28 +0800626 return -terrno;
Bernie Innocenti55864192018-08-30 04:05:20 +0900627}
628
629/* Private */
630
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900631static int get_salen(const struct sockaddr* sa) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900632 if (sa->sa_family == AF_INET)
633 return (sizeof(struct sockaddr_in));
634 else if (sa->sa_family == AF_INET6)
635 return (sizeof(struct sockaddr_in6));
636 else
637 return (0); /* unknown, die on connect */
Bernie Innocenti55864192018-08-30 04:05:20 +0900638}
639
640/*
641 * pick appropriate nsaddr_list for use. see res_init() for initialization.
642 */
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900643static struct sockaddr* get_nsaddr(res_state statp, size_t n) {
Ken Chencf6ded62018-10-16 23:12:09 +0800644 if (!statp->nsaddr_list[n].sin_family && statp->_u._ext.ext) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900645 /*
Ken Chencf6ded62018-10-16 23:12:09 +0800646 * - statp->_u._ext.ext->nsaddrs[n] holds an address that is larger
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900647 * than struct sockaddr, and
648 * - user code did not update statp->nsaddr_list[n].
649 */
Ken Chencf6ded62018-10-16 23:12:09 +0800650 return (struct sockaddr*) (void*) &statp->_u._ext.ext->nsaddrs[n];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900651 } else {
652 /*
653 * - user code updated statp->nsaddr_list[n], or
654 * - statp->nsaddr_list[n] has the same content as
Ken Chencf6ded62018-10-16 23:12:09 +0800655 * statp->_u._ext.ext->nsaddrs[n].
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900656 */
657 return (struct sockaddr*) (void*) &statp->nsaddr_list[n];
658 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900659}
660
Bernie Innocenti34de3ba2019-02-19 18:08:36 +0900661static struct timespec get_timeout(const res_state statp, const res_params* params, const int ns) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900662 int msec;
663 if (params->base_timeout_msec != 0) {
664 // TODO: scale the timeout by retry attempt and maybe number of servers
665 msec = params->base_timeout_msec;
666 } else {
667 // Legacy algorithm which scales the timeout by nameserver number.
668 // For instance, with 4 nameservers: 5s, 2.5s, 5s, 10s
669 // This has no effect with 1 or 2 nameservers
670 msec = (statp->retrans * 1000) << ns;
671 if (ns > 0) {
672 msec /= statp->nscount;
673 }
674 if (msec < 1000) {
675 msec = 1000; // Use at least 100ms
676 }
677 }
chenbruce16adee42019-02-20 19:45:50 +0800678 LOG(INFO) << "using timeout of " << msec << " msec";
Bernie Innocenti55864192018-08-30 04:05:20 +0900679
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900680 struct timespec result;
681 result.tv_sec = msec / 1000;
682 result.tv_nsec = (msec % 1000) * 1000000;
683 return result;
Bernie Innocenti55864192018-08-30 04:05:20 +0900684}
685
Bernie Innocenti34de3ba2019-02-19 18:08:36 +0900686static int send_vc(res_state statp, res_params* params, const u_char* buf, int buflen, u_char* ans,
687 int anssiz, int* terrno, int ns, time_t* at, int* rcode, int* delay) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900688 *at = time(NULL);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900689 *delay = 0;
690 const HEADER* hp = (const HEADER*) (const void*) buf;
691 HEADER* anhp = (HEADER*) (void*) ans;
692 struct sockaddr* nsap;
693 int nsaplen;
694 int truncating, connreset, resplen, n;
695 struct iovec iov[2];
696 u_short len;
697 u_char* cp;
Bernie Innocenti55864192018-08-30 04:05:20 +0900698
chenbruce16adee42019-02-20 19:45:50 +0800699 LOG(INFO) << "using send_vc";
Bernie Innocenti55864192018-08-30 04:05:20 +0900700
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900701 nsap = get_nsaddr(statp, (size_t) ns);
702 nsaplen = get_salen(nsap);
Bernie Innocenti55864192018-08-30 04:05:20 +0900703
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900704 connreset = 0;
705same_ns:
706 truncating = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900707
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900708 struct timespec now = evNowTime();
Bernie Innocenti55864192018-08-30 04:05:20 +0900709
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900710 /* Are we still talking to whom we want to talk to? */
711 if (statp->_vcsock >= 0 && (statp->_flags & RES_F_VC) != 0) {
712 struct sockaddr_storage peer;
713 socklen_t size = sizeof peer;
714 unsigned old_mark;
715 socklen_t mark_size = sizeof(old_mark);
716 if (getpeername(statp->_vcsock, (struct sockaddr*) (void*) &peer, &size) < 0 ||
717 !sock_eq((struct sockaddr*) (void*) &peer, nsap) ||
718 getsockopt(statp->_vcsock, SOL_SOCKET, SO_MARK, &old_mark, &mark_size) < 0 ||
719 old_mark != statp->_mark) {
720 res_nclose(statp);
721 statp->_flags &= ~RES_F_VC;
722 }
723 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900724
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900725 if (statp->_vcsock < 0 || (statp->_flags & RES_F_VC) == 0) {
726 if (statp->_vcsock >= 0) res_nclose(statp);
Bernie Innocenti55864192018-08-30 04:05:20 +0900727
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900728 statp->_vcsock = socket(nsap->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0);
729 if (statp->_vcsock < 0) {
730 switch (errno) {
731 case EPROTONOSUPPORT:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900732 case EPFNOSUPPORT:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900733 case EAFNOSUPPORT:
chenbruce16adee42019-02-20 19:45:50 +0800734 Perror(statp, "socket(vc)", errno);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900735 return 0;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900736 default:
737 *terrno = errno;
chenbruce16adee42019-02-20 19:45:50 +0800738 Perror(statp, "socket(vc)", errno);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900739 return -1;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900740 }
741 }
742 fchown(statp->_vcsock, AID_DNS, -1);
743 if (statp->_mark != MARK_UNSET) {
744 if (setsockopt(statp->_vcsock, SOL_SOCKET, SO_MARK, &statp->_mark,
745 sizeof(statp->_mark)) < 0) {
746 *terrno = errno;
chenbruce16adee42019-02-20 19:45:50 +0800747 Perror(statp, "setsockopt", errno);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900748 return -1;
749 }
750 }
751 errno = 0;
752 if (random_bind(statp->_vcsock, nsap->sa_family) < 0) {
753 *terrno = errno;
chenbruce16adee42019-02-20 19:45:50 +0800754 Aerror(statp, "bind/vc", errno, nsap, nsaplen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900755 res_nclose(statp);
756 return (0);
757 }
758 if (connect_with_timeout(statp->_vcsock, nsap, (socklen_t) nsaplen,
759 get_timeout(statp, params, ns)) < 0) {
760 *terrno = errno;
chenbruce16adee42019-02-20 19:45:50 +0800761 Aerror(statp, "connect/vc", errno, nsap, nsaplen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900762 res_nclose(statp);
763 /*
764 * The way connect_with_timeout() is implemented prevents us from reliably
765 * determining whether this was really a timeout or e.g. ECONNREFUSED. Since
766 * currently both cases are handled in the same way, there is no need to
767 * change this (yet). If we ever need to reliably distinguish between these
768 * cases, both connect_with_timeout() and retrying_poll() need to be
769 * modified, though.
770 */
771 *rcode = RCODE_TIMEOUT;
772 return (0);
773 }
774 statp->_flags |= RES_F_VC;
775 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900776
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900777 /*
778 * Send length & message
779 */
780 ns_put16((u_short) buflen, (u_char*) (void*) &len);
781 iov[0] = evConsIovec(&len, INT16SZ);
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900782 iov[1] = evConsIovec((void*) buf, (size_t) buflen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900783 if (writev(statp->_vcsock, iov, 2) != (INT16SZ + buflen)) {
784 *terrno = errno;
chenbruce16adee42019-02-20 19:45:50 +0800785 Perror(statp, "write failed", errno);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900786 res_nclose(statp);
787 return (0);
788 }
789 /*
790 * Receive length & response
791 */
792read_len:
793 cp = ans;
794 len = INT16SZ;
795 while ((n = read(statp->_vcsock, (char*) cp, (size_t) len)) > 0) {
796 cp += n;
797 if ((len -= n) == 0) break;
798 }
799 if (n <= 0) {
800 *terrno = errno;
chenbruce16adee42019-02-20 19:45:50 +0800801 Perror(statp, "read failed", errno);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900802 res_nclose(statp);
803 /*
804 * A long running process might get its TCP
805 * connection reset if the remote server was
806 * restarted. Requery the server instead of
807 * trying a new one. When there is only one
808 * server, this means that a query might work
809 * instead of failing. We only allow one reset
810 * per query to prevent looping.
811 */
812 if (*terrno == ECONNRESET && !connreset) {
813 connreset = 1;
814 res_nclose(statp);
815 goto same_ns;
816 }
817 res_nclose(statp);
818 return (0);
819 }
820 resplen = ns_get16(ans);
821 if (resplen > anssiz) {
chenbruce16adee42019-02-20 19:45:50 +0800822 LOG(DEBUG) << ";; response truncated";
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900823 truncating = 1;
824 len = anssiz;
825 } else
826 len = resplen;
827 if (len < HFIXEDSZ) {
828 /*
829 * Undersized message.
830 */
chenbruce16adee42019-02-20 19:45:50 +0800831 LOG(DEBUG) << ";; undersized: " << len;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900832 *terrno = EMSGSIZE;
833 res_nclose(statp);
834 return (0);
835 }
836 cp = ans;
837 while (len != 0 && (n = read(statp->_vcsock, (char*) cp, (size_t) len)) > 0) {
838 cp += n;
839 len -= n;
840 }
841 if (n <= 0) {
842 *terrno = errno;
chenbruce16adee42019-02-20 19:45:50 +0800843 Perror(statp, "read(vc)", errno);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900844 res_nclose(statp);
845 return (0);
846 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900847
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900848 if (truncating) {
849 /*
850 * Flush rest of answer so connection stays in synch.
851 */
852 anhp->tc = 1;
853 len = resplen - anssiz;
854 while (len != 0) {
855 char junk[PACKETSZ];
Bernie Innocenti55864192018-08-30 04:05:20 +0900856
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900857 n = read(statp->_vcsock, junk, (len > sizeof junk) ? sizeof junk : len);
858 if (n > 0)
859 len -= n;
860 else
861 break;
862 }
863 }
864 /*
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900865 * If the calling application has bailed out of
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900866 * a previous call and failed to arrange to have
867 * the circuit closed or the server has got
868 * itself confused, then drop the packet and
869 * wait for the correct one.
870 */
871 if (hp->id != anhp->id) {
chenbruce16adee42019-02-20 19:45:50 +0800872 LOG(DEBUG) << ";; old answer (unexpected):";
873 res_pquery(statp, ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900874 goto read_len;
875 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900876
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900877 /*
878 * All is well, or the error is fatal. Signal that the
879 * next nameserver ought not be tried.
880 */
881 if (resplen > 0) {
882 struct timespec done = evNowTime();
883 *delay = _res_stats_calculate_rtt(&done, &now);
884 *rcode = anhp->rcode;
885 }
886 return (resplen);
Bernie Innocenti55864192018-08-30 04:05:20 +0900887}
888
889/* return -1 on error (errno set), 0 on success */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900890static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
891 const struct timespec timeout) {
892 int res, origflags;
Bernie Innocenti55864192018-08-30 04:05:20 +0900893
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900894 origflags = fcntl(sock, F_GETFL, 0);
895 fcntl(sock, F_SETFL, origflags | O_NONBLOCK);
Bernie Innocenti55864192018-08-30 04:05:20 +0900896
Bernie Innocentif89b3512018-08-30 07:34:37 +0900897 res = connect(sock, nsap, salen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900898 if (res < 0 && errno != EINPROGRESS) {
899 res = -1;
900 goto done;
901 }
902 if (res != 0) {
903 struct timespec now = evNowTime();
904 struct timespec finish = evAddTime(now, timeout);
chenbruce16adee42019-02-20 19:45:50 +0800905 LOG(INFO) << sock << " send_vc";
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900906 res = retrying_poll(sock, POLLIN | POLLOUT, &finish);
907 if (res <= 0) {
908 res = -1;
909 }
910 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900911done:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900912 fcntl(sock, F_SETFL, origflags);
chenbruce16adee42019-02-20 19:45:50 +0800913 LOG(INFO) << sock << " connect_with_const timeout returning " << res;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900914 return res;
Bernie Innocenti55864192018-08-30 04:05:20 +0900915}
916
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900917static int retrying_poll(const int sock, const short events, const struct timespec* finish) {
918 struct timespec now, timeout;
Bernie Innocenti55864192018-08-30 04:05:20 +0900919
920retry:
chenbruce16adee42019-02-20 19:45:50 +0800921 LOG(INFO) << " " << sock << " retrying_poll";
Bernie Innocenti55864192018-08-30 04:05:20 +0900922
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900923 now = evNowTime();
924 if (evCmpTime(*finish, now) > 0)
925 timeout = evSubTime(*finish, now);
926 else
927 timeout = evConsTime(0L, 0L);
928 struct pollfd fds = {.fd = sock, .events = events};
929 int n = ppoll(&fds, 1, &timeout, /*sigmask=*/NULL);
930 if (n == 0) {
chenbruce16adee42019-02-20 19:45:50 +0800931 LOG(INFO) << " " << sock << "retrying_poll timeout";
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900932 errno = ETIMEDOUT;
933 return 0;
934 }
935 if (n < 0) {
936 if (errno == EINTR) goto retry;
chenbruce16adee42019-02-20 19:45:50 +0800937 LOG(INFO) << " " << sock << " retrying_poll got error " << n;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900938 return n;
939 }
940 if (fds.revents & (POLLIN | POLLOUT | POLLERR)) {
941 int error;
942 socklen_t len = sizeof(error);
943 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error) {
944 errno = error;
chenbruce16adee42019-02-20 19:45:50 +0800945 LOG(INFO) << " " << sock << " retrying_poll dot error2 " << errno;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900946 return -1;
947 }
948 }
chenbruce16adee42019-02-20 19:45:50 +0800949 LOG(INFO) << " " << sock << " retrying_poll returning " << n;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900950 return n;
Bernie Innocenti55864192018-08-30 04:05:20 +0900951}
952
Bernie Innocenti34de3ba2019-02-19 18:08:36 +0900953static int send_dg(res_state statp, res_params* params, const u_char* buf, int buflen, u_char* ans,
954 int anssiz, int* terrno, int ns, int* v_circuit, int* gotsomewhere, time_t* at,
955 int* rcode, int* delay) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900956 *at = time(NULL);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900957 *delay = 0;
958 const HEADER* hp = (const HEADER*) (const void*) buf;
959 HEADER* anhp = (HEADER*) (void*) ans;
960 const struct sockaddr* nsap;
961 int nsaplen;
962 struct timespec now, timeout, finish, done;
963 struct sockaddr_storage from;
964 socklen_t fromlen;
965 int resplen, n, s;
Bernie Innocenti55864192018-08-30 04:05:20 +0900966
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900967 nsap = get_nsaddr(statp, (size_t) ns);
968 nsaplen = get_salen(nsap);
Ken Chencf6ded62018-10-16 23:12:09 +0800969 if (statp->_u._ext.nssocks[ns] == -1) {
970 statp->_u._ext.nssocks[ns] = socket(nsap->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
971 if (statp->_u._ext.nssocks[ns] < 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900972 switch (errno) {
973 case EPROTONOSUPPORT:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900974 case EPFNOSUPPORT:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900975 case EAFNOSUPPORT:
chenbruce16adee42019-02-20 19:45:50 +0800976 Perror(statp, "socket(dg)", errno);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900977 return (0);
978 default:
979 *terrno = errno;
chenbruce16adee42019-02-20 19:45:50 +0800980 Perror(statp, "socket(dg)", errno);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900981 return (-1);
982 }
983 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900984
Ken Chencf6ded62018-10-16 23:12:09 +0800985 fchown(statp->_u._ext.nssocks[ns], AID_DNS, -1);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900986 if (statp->_mark != MARK_UNSET) {
Ken Chencf6ded62018-10-16 23:12:09 +0800987 if (setsockopt(statp->_u._ext.nssocks[ns], SOL_SOCKET, SO_MARK, &(statp->_mark),
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900988 sizeof(statp->_mark)) < 0) {
989 res_nclose(statp);
990 return -1;
991 }
992 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900993#ifndef CANNOT_CONNECT_DGRAM
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900994 /*
995 * On a 4.3BSD+ machine (client and server,
996 * actually), sending to a nameserver datagram
997 * port with no nameserver will cause an
998 * ICMP port unreachable message to be returned.
999 * If our datagram socket is "connected" to the
1000 * server, we get an ECONNREFUSED error on the next
1001 * socket operation, and select returns if the
1002 * error message is received. We can thus detect
1003 * the absence of a nameserver without timing out.
1004 */
Ken Chencf6ded62018-10-16 23:12:09 +08001005 if (random_bind(statp->_u._ext.nssocks[ns], nsap->sa_family) < 0) {
chenbruce16adee42019-02-20 19:45:50 +08001006 Aerror(statp, "bind(dg)", errno, nsap, nsaplen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001007 res_nclose(statp);
1008 return (0);
1009 }
Ken Chencf6ded62018-10-16 23:12:09 +08001010 if (connect(statp->_u._ext.nssocks[ns], nsap, (socklen_t) nsaplen) < 0) {
chenbruce16adee42019-02-20 19:45:50 +08001011 Aerror(statp, "connect(dg)", errno, nsap, nsaplen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001012 res_nclose(statp);
1013 return (0);
1014 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001015#endif /* !CANNOT_CONNECT_DGRAM */
chenbruce16adee42019-02-20 19:45:50 +08001016 LOG(DEBUG) << ";; new DG socket";
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001017 }
Ken Chencf6ded62018-10-16 23:12:09 +08001018 s = statp->_u._ext.nssocks[ns];
Bernie Innocenti55864192018-08-30 04:05:20 +09001019#ifndef CANNOT_CONNECT_DGRAM
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001020 if (send(s, (const char*) buf, (size_t) buflen, 0) != buflen) {
chenbruce16adee42019-02-20 19:45:50 +08001021 Perror(statp, "send", errno);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001022 res_nclose(statp);
1023 return (0);
1024 }
1025#else /* !CANNOT_CONNECT_DGRAM */
1026 if (sendto(s, (const char*) buf, buflen, 0, nsap, nsaplen) != buflen) {
chenbruce16adee42019-02-20 19:45:50 +08001027 Aerror(statp, "sendto", errno, nsap, nsaplen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001028 res_nclose(statp);
1029 return (0);
1030 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001031#endif /* !CANNOT_CONNECT_DGRAM */
1032
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001033 /*
1034 * Wait for reply.
1035 */
1036 timeout = get_timeout(statp, params, ns);
1037 now = evNowTime();
1038 finish = evAddTime(now, timeout);
Bernie Innocenti55864192018-08-30 04:05:20 +09001039retry:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001040 n = retrying_poll(s, POLLIN, &finish);
Bernie Innocenti55864192018-08-30 04:05:20 +09001041
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001042 if (n == 0) {
1043 *rcode = RCODE_TIMEOUT;
chenbruce16adee42019-02-20 19:45:50 +08001044 LOG(DEBUG) << ";; timeout";
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001045 *gotsomewhere = 1;
1046 return (0);
1047 }
1048 if (n < 0) {
chenbruce16adee42019-02-20 19:45:50 +08001049 Perror(statp, "poll", errno);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001050 res_nclose(statp);
1051 return (0);
1052 }
1053 errno = 0;
1054 fromlen = sizeof(from);
1055 resplen = recvfrom(s, (char*) ans, (size_t) anssiz, 0, (struct sockaddr*) (void*) &from,
1056 &fromlen);
1057 if (resplen <= 0) {
chenbruce16adee42019-02-20 19:45:50 +08001058 Perror(statp, "recvfrom", errno);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001059 res_nclose(statp);
1060 return (0);
1061 }
1062 *gotsomewhere = 1;
1063 if (resplen < HFIXEDSZ) {
1064 /*
1065 * Undersized message.
1066 */
chenbruce16adee42019-02-20 19:45:50 +08001067 LOG(DEBUG) << ";; undersized: " << resplen;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001068 *terrno = EMSGSIZE;
1069 res_nclose(statp);
1070 return (0);
1071 }
1072 if (hp->id != anhp->id) {
1073 /*
1074 * response from old query, ignore it.
1075 * XXX - potential security hazard could
1076 * be detected here.
1077 */
chenbruce16adee42019-02-20 19:45:50 +08001078 LOG(DEBUG) << ";; old answer:";
1079 res_pquery(statp, ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001080 goto retry;
1081 }
1082 if (!(statp->options & RES_INSECURE1) &&
1083 !res_ourserver_p(statp, (struct sockaddr*) (void*) &from)) {
1084 /*
1085 * response from wrong server? ignore it.
1086 * XXX - potential security hazard could
1087 * be detected here.
1088 */
chenbruce16adee42019-02-20 19:45:50 +08001089 LOG(DEBUG) << ";; not our server:";
1090 res_pquery(statp, ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001091 goto retry;
1092 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001093 if (anhp->rcode == FORMERR && (statp->options & RES_USE_EDNS0) != 0U) {
1094 /*
1095 * Do not retry if the server do not understand EDNS0.
1096 * The case has to be captured here, as FORMERR packet do not
1097 * carry query section, hence res_queriesmatch() returns 0.
1098 */
chenbruce16adee42019-02-20 19:45:50 +08001099 LOG(DEBUG) << "server rejected query with EDNS0:";
1100 res_pquery(statp, ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001101 /* record the error */
1102 statp->_flags |= RES_F_EDNS0ERR;
1103 res_nclose(statp);
1104 return (0);
1105 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001106 if (!(statp->options & RES_INSECURE2) &&
1107 !res_queriesmatch(buf, buf + buflen, ans, ans + anssiz)) {
1108 /*
1109 * response contains wrong query? ignore it.
1110 * XXX - potential security hazard could
1111 * be detected here.
1112 */
chenbruce16adee42019-02-20 19:45:50 +08001113 LOG(DEBUG) << ";; wrong query name:";
1114 res_pquery(statp, ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001115 goto retry;
1116 ;
1117 }
1118 done = evNowTime();
1119 *delay = _res_stats_calculate_rtt(&done, &now);
1120 if (anhp->rcode == SERVFAIL || anhp->rcode == NOTIMP || anhp->rcode == REFUSED) {
chenbruce16adee42019-02-20 19:45:50 +08001121 LOG(DEBUG) << "server rejected query:";
1122 res_pquery(statp, ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001123 res_nclose(statp);
1124 /* don't retry if called from dig */
1125 if (!statp->pfcode) {
1126 *rcode = anhp->rcode;
1127 return (0);
1128 }
1129 }
1130 if (!(statp->options & RES_IGNTC) && anhp->tc) {
1131 /*
1132 * To get the rest of answer,
1133 * use TCP with same server.
1134 */
chenbruce16adee42019-02-20 19:45:50 +08001135 LOG(DEBUG) << ";; truncated answer";
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001136 *v_circuit = 1;
1137 res_nclose(statp);
1138 return (1);
1139 }
1140 /*
1141 * All is well, or the error is fatal. Signal that the
1142 * next nameserver ought not be tried.
1143 */
1144 if (resplen > 0) {
1145 *rcode = anhp->rcode;
1146 }
1147 return (resplen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001148}
1149
chenbruce16adee42019-02-20 19:45:50 +08001150static void Aerror(const res_state statp, const char* string, int error,
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001151 const struct sockaddr* address, int alen) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001152 const int save = errno;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001153 char hbuf[NI_MAXHOST];
1154 char sbuf[NI_MAXSERV];
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001155 constexpr int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
Bernie Innocenti55864192018-08-30 04:05:20 +09001156
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001157 if ((statp->options & RES_DEBUG) != 0U) {
1158 if (getnameinfo(address, (socklen_t) alen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
1159 niflags)) {
1160 strncpy(hbuf, "?", sizeof(hbuf) - 1);
1161 hbuf[sizeof(hbuf) - 1] = '\0';
1162 strncpy(sbuf, "?", sizeof(sbuf) - 1);
1163 sbuf[sizeof(sbuf) - 1] = '\0';
1164 }
chenbruce16adee42019-02-20 19:45:50 +08001165 LOG(DEBUG) << "res_send: " << string << " ([" << hbuf << "]." << sbuf
1166 << "): " << strerror(error);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001167 }
1168 errno = save;
Bernie Innocenti55864192018-08-30 04:05:20 +09001169}
1170
chenbruce16adee42019-02-20 19:45:50 +08001171static void Perror(const res_state statp, const char* string, int error) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001172 const int save = errno;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001173 if ((statp->options & RES_DEBUG) != 0U)
chenbruce16adee42019-02-20 19:45:50 +08001174 LOG(DEBUG) << "res_send: " << string << ": " << strerror(error);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001175 errno = save;
Bernie Innocenti55864192018-08-30 04:05:20 +09001176}
1177
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001178static int sock_eq(struct sockaddr* a, struct sockaddr* b) {
1179 struct sockaddr_in *a4, *b4;
1180 struct sockaddr_in6 *a6, *b6;
Bernie Innocenti55864192018-08-30 04:05:20 +09001181
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001182 if (a->sa_family != b->sa_family) return 0;
1183 switch (a->sa_family) {
1184 case AF_INET:
1185 a4 = (struct sockaddr_in*) (void*) a;
1186 b4 = (struct sockaddr_in*) (void*) b;
1187 return a4->sin_port == b4->sin_port && a4->sin_addr.s_addr == b4->sin_addr.s_addr;
1188 case AF_INET6:
1189 a6 = (struct sockaddr_in6*) (void*) a;
1190 b6 = (struct sockaddr_in6*) (void*) b;
1191 return a6->sin6_port == b6->sin6_port &&
Bernie Innocenti55864192018-08-30 04:05:20 +09001192#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001193 a6->sin6_scope_id == b6->sin6_scope_id &&
Bernie Innocenti55864192018-08-30 04:05:20 +09001194#endif
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001195 IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
1196 default:
1197 return 0;
1198 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001199}
Mike Yua46fae72018-11-01 20:07:00 +08001200
Luke Huang490551d2018-11-21 20:37:50 +08001201static int res_tls_send(res_state statp, const Slice query, const Slice answer, int* rcode,
Mike Yu69615f62018-11-06 15:42:36 +08001202 bool* fallback) {
1203 int resplen = 0;
Mike Yua46fae72018-11-01 20:07:00 +08001204 const unsigned netId = statp->netid;
1205 const unsigned mark = statp->_mark;
1206
Mike Yu69615f62018-11-06 15:42:36 +08001207 PrivateDnsStatus privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
1208
1209 if (privateDnsStatus.mode == PrivateDnsMode::OFF) {
1210 *fallback = true;
1211 return -1;
Mike Yua46fae72018-11-01 20:07:00 +08001212 }
1213
Mike Yua46fae72018-11-01 20:07:00 +08001214 if (privateDnsStatus.validatedServers.empty()) {
1215 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
Mike Yu69615f62018-11-06 15:42:36 +08001216 *fallback = true;
1217 return -1;
Mike Yua46fae72018-11-01 20:07:00 +08001218 } else {
1219 // Sleep and iterate some small number of times checking for the
1220 // arrival of resolved and validated server IP addresses, instead
1221 // of returning an immediate error.
Mike Yu5b9ffb22018-12-02 17:54:29 +09001222 // This is needed because as soon as a network becomes the default network, apps will
1223 // send DNS queries on that network. If no servers have yet validated, and we do not
1224 // block those queries, they would immediately fail, causing application-visible errors.
1225 // Note that this can happen even before the network validates, since an unvalidated
1226 // network can become the default network if no validated networks are available.
1227 //
1228 // TODO: see if there is a better way to address this problem, such as buffering the
1229 // queries in a queue or only blocking queries for the first few seconds after a default
1230 // network change.
Mike Yu69615f62018-11-06 15:42:36 +08001231 for (int i = 0; i < 42; i++) {
1232 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1233 if (!gPrivateDnsConfiguration.getStatus(netId).validatedServers.empty()) {
1234 privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
1235 break;
1236 }
1237 }
1238 if (privateDnsStatus.validatedServers.empty()) {
1239 return -1;
1240 }
Mike Yua46fae72018-11-01 20:07:00 +08001241 }
1242 }
1243
chenbruce16adee42019-02-20 19:45:50 +08001244 LOG(INFO) << __func__ << ": performing query over TLS";
Mike Yua46fae72018-11-01 20:07:00 +08001245
1246 const auto response = sDnsTlsDispatcher.query(privateDnsStatus.validatedServers, mark, query,
Mike Yu69615f62018-11-06 15:42:36 +08001247 answer, &resplen);
Mike Yua46fae72018-11-01 20:07:00 +08001248
chenbruce16adee42019-02-20 19:45:50 +08001249 LOG(INFO) << __func__ << ": TLS query result: " << static_cast<int>(response);
Mike Yua46fae72018-11-01 20:07:00 +08001250
1251 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
1252 // In opportunistic mode, handle falling back to cleartext in some
1253 // cases (DNS shouldn't fail if a validated opportunistic mode server
1254 // becomes unreachable for some reason).
1255 switch (response) {
Mike Yu69615f62018-11-06 15:42:36 +08001256 case DnsTlsTransport::Response::success:
Luke Huang490551d2018-11-21 20:37:50 +08001257 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yu69615f62018-11-06 15:42:36 +08001258 return resplen;
Mike Yua46fae72018-11-01 20:07:00 +08001259 case DnsTlsTransport::Response::network_error:
Mike Yu69615f62018-11-06 15:42:36 +08001260 // No need to set the error timeout here since it will fallback to UDP.
Mike Yua46fae72018-11-01 20:07:00 +08001261 case DnsTlsTransport::Response::internal_error:
1262 // Note: this will cause cleartext queries to be emitted, with
1263 // all of the EDNS0 goodness enabled. Fingers crossed. :-/
Mike Yu69615f62018-11-06 15:42:36 +08001264 *fallback = true;
1265 [[fallthrough]];
Mike Yua46fae72018-11-01 20:07:00 +08001266 default:
Mike Yu69615f62018-11-06 15:42:36 +08001267 return -1;
1268 }
1269 } else {
1270 // Strict mode
1271 switch (response) {
1272 case DnsTlsTransport::Response::success:
Luke Huang490551d2018-11-21 20:37:50 +08001273 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yu69615f62018-11-06 15:42:36 +08001274 return resplen;
1275 case DnsTlsTransport::Response::network_error:
1276 // This case happens when the query stored in DnsTlsTransport is expired since
1277 // either 1) the query has been tried for 3 times but no response or 2) fail to
1278 // establish the connection with the server.
Luke Huang490551d2018-11-21 20:37:50 +08001279 *rcode = RCODE_TIMEOUT;
Mike Yu69615f62018-11-06 15:42:36 +08001280 [[fallthrough]];
1281 default:
1282 return -1;
Mike Yua46fae72018-11-01 20:07:00 +08001283 }
1284 }
Mike Yua46fae72018-11-01 20:07:00 +08001285}
Luke Huangeefb7772018-11-19 20:17:26 +08001286
Luke Huang952d0942018-12-26 16:53:03 +08001287int resolv_res_nsend(const android_net_context* netContext, const uint8_t* msg, int msgLen,
1288 uint8_t* ans, int ansLen, int* rcode, uint32_t flags) {
Luke Huangeefb7772018-11-19 20:17:26 +08001289 res_state res = res_get_state();
1290 res_setnetcontext(res, netContext);
1291 _resolv_populate_res_for_net(res);
1292 *rcode = NOERROR;
Luke Huang952d0942018-12-26 16:53:03 +08001293 return res_nsend(res, msg, msgLen, ans, ansLen, rcode, flags);
Bernie Innocentiad4e26e2019-01-30 11:16:36 +09001294}