blob: a8b2aebd333d8f90d513348eea0ed72e243b3057 [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 +090077constexpr bool kVerboseLogging = false;
78#define LOG_TAG "res_send"
79
Bernie Innocenti55864192018-08-30 04:05:20 +090080#include <sys/param.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090081#include <sys/socket.h>
Bernie Innocentif12d5bb2018-08-31 14:09:46 +090082#include <sys/time.h>
83#include <sys/types.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090084#include <sys/uio.h>
85
Bernie Innocenti55864192018-08-30 04:05:20 +090086#include <arpa/inet.h>
Bernie Innocentif12d5bb2018-08-31 14:09:46 +090087#include <arpa/nameser.h>
88#include <netinet/in.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090089
90#include <errno.h>
91#include <fcntl.h>
92#include <netdb.h>
93#include <poll.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090094#include <signal.h>
95#include <stdio.h>
96#include <stdlib.h>
97#include <string.h>
98#include <time.h>
99#include <unistd.h>
100
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900101#include <android-base/logging.h>
Bernie Innocenti55864192018-08-30 04:05:20 +0900102
Mike Yua46fae72018-11-01 20:07:00 +0800103#include <netdutils/Slice.h>
104#include "netd_resolv/DnsTlsDispatcher.h"
105#include "netd_resolv/DnsTlsTransport.h"
106#include "netd_resolv/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 Innocentie9ba09c2018-09-12 23:20:10 +0900116
117#define VLOG if (!kVerboseLogging) {} else LOG(INFO)
118
119#ifndef RESOLV_ALLOW_VERBOSE_LOGGING
120static_assert(kVerboseLogging == false,
121 "Verbose logging floods logs at high-rate and exposes privacy-sensitive information. "
122 "Do not enable in release builds.");
Bernie Innocenti55864192018-08-30 04:05:20 +0900123#endif
Bernie Innocenti2fd418e2018-08-30 12:04:03 +0900124
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900125#ifndef DEBUG
126#define Dprint(cond, args) /*empty*/
127#define DprintQ(cond, args, query, size) /*empty*/
128#else
129// TODO: convert to Android logging
130#define Dprint(cond, args) \
131 if (cond) { \
132 fprintf args; \
133 } else { \
134 }
135#define DprintQ(cond, args, query, size) \
136 if (cond) { \
137 fprintf args; \
138 res_pquery(statp, query, size, stdout); \
139 } else { \
140 }
141#endif // DEBUG
Bernie Innocenti55864192018-08-30 04:05:20 +0900142
Mike Yua46fae72018-11-01 20:07:00 +0800143static DnsTlsDispatcher sDnsTlsDispatcher;
144
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900145static int get_salen(const struct sockaddr*);
146static struct sockaddr* get_nsaddr(res_state, size_t);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900147static int send_vc(res_state, struct __res_params* params, const u_char*, int, u_char*, int, int*,
148 int, time_t*, int*, int*);
149static int send_dg(res_state, struct __res_params* params, const u_char*, int, u_char*, int, int*,
150 int, int*, int*, time_t*, int*, int*);
151static void Aerror(const res_state, FILE*, const char*, int, const struct sockaddr*, int);
152static void Perror(const res_state, FILE*, const char*, int);
153static int sock_eq(struct sockaddr*, struct sockaddr*);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900154static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
155 const struct timespec timeout);
Bernie Innocenti55864192018-08-30 04:05:20 +0900156static int retrying_poll(const int sock, short events, const struct timespec* finish);
Luke Huang490551d2018-11-21 20:37:50 +0800157static int res_tls_send(res_state, const Slice query, const Slice answer, int* rcode,
Mike Yu69615f62018-11-06 15:42:36 +0800158 bool* fallback);
Bernie Innocenti55864192018-08-30 04:05:20 +0900159
160/* BIONIC-BEGIN: implement source port randomization */
Bernie Innocenti55864192018-08-30 04:05:20 +0900161
Bernie Innocentif89b3512018-08-30 07:34:37 +0900162// BEGIN: Code copied from ISC eventlib
163// TODO: move away from this code
164
165#define BILLION 1000000000
166
167static struct timespec evConsTime(time_t sec, long nsec) {
168 struct timespec x;
169
170 x.tv_sec = sec;
171 x.tv_nsec = nsec;
172 return (x);
173}
174
175static struct timespec evAddTime(struct timespec addend1, struct timespec addend2) {
176 struct timespec x;
177
178 x.tv_sec = addend1.tv_sec + addend2.tv_sec;
179 x.tv_nsec = addend1.tv_nsec + addend2.tv_nsec;
180 if (x.tv_nsec >= BILLION) {
181 x.tv_sec++;
182 x.tv_nsec -= BILLION;
183 }
184 return (x);
185}
186
187static struct timespec evSubTime(struct timespec minuend, struct timespec subtrahend) {
188 struct timespec x;
189
190 x.tv_sec = minuend.tv_sec - subtrahend.tv_sec;
191 if (minuend.tv_nsec >= subtrahend.tv_nsec)
192 x.tv_nsec = minuend.tv_nsec - subtrahend.tv_nsec;
193 else {
194 x.tv_nsec = BILLION - subtrahend.tv_nsec + minuend.tv_nsec;
195 x.tv_sec--;
196 }
197 return (x);
198}
199
200static int evCmpTime(struct timespec a, struct timespec b) {
201#define SGN(x) ((x) < 0 ? (-1) : (x) > 0 ? (1) : (0));
202 time_t s = a.tv_sec - b.tv_sec;
203 long n;
204
205 if (s != 0) return SGN(s);
206
207 n = a.tv_nsec - b.tv_nsec;
208 return SGN(n);
209}
210
Bernie Innocentif89b3512018-08-30 07:34:37 +0900211static struct timespec evNowTime(void) {
Bernie Innocentif89b3512018-08-30 07:34:37 +0900212 struct timespec tsnow;
Bernie Innocenti357339c2018-08-31 16:11:41 +0900213 clock_gettime(CLOCK_REALTIME, &tsnow);
214 return tsnow;
Bernie Innocentif89b3512018-08-30 07:34:37 +0900215}
216
217static struct iovec evConsIovec(void* buf, size_t cnt) {
218 struct iovec ret;
219
220 memset(&ret, 0xf5, sizeof ret);
221 ret.iov_base = buf;
222 ret.iov_len = cnt;
Bernie Innocenti357339c2018-08-31 16:11:41 +0900223 return ret;
Bernie Innocentif89b3512018-08-30 07:34:37 +0900224}
225
226// END: Code copied from ISC eventlib
227
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900228static int random_bind(int s, int family) {
nuccachene172a4e2018-10-23 17:10:58 +0800229 sockaddr_union u;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900230 int j;
231 socklen_t slen;
Bernie Innocenti55864192018-08-30 04:05:20 +0900232
233 /* clear all, this also sets the IP4/6 address to 'any' */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900234 memset(&u, 0, sizeof u);
Bernie Innocenti55864192018-08-30 04:05:20 +0900235
236 switch (family) {
237 case AF_INET:
238 u.sin.sin_family = family;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900239 slen = sizeof u.sin;
Bernie Innocenti55864192018-08-30 04:05:20 +0900240 break;
241 case AF_INET6:
242 u.sin6.sin6_family = family;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900243 slen = sizeof u.sin6;
Bernie Innocenti55864192018-08-30 04:05:20 +0900244 break;
245 default:
246 errno = EPROTO;
247 return -1;
248 }
249
250 /* first try to bind to a random source port a few times */
251 for (j = 0; j < 10; j++) {
252 /* find a random port between 1025 .. 65534 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900253 int port = 1025 + (res_randomid() % (65535 - 1025));
Bernie Innocenti55864192018-08-30 04:05:20 +0900254 if (family == AF_INET)
255 u.sin.sin_port = htons(port);
256 else
257 u.sin6.sin6_port = htons(port);
258
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900259 if (!bind(s, &u.sa, slen)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900260 }
261
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900262 // nothing after 10 attempts, our network table is probably busy
263 // let the system decide which port is best
Bernie Innocenti55864192018-08-30 04:05:20 +0900264 if (family == AF_INET)
265 u.sin.sin_port = 0;
266 else
267 u.sin6.sin6_port = 0;
268
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900269 return bind(s, &u.sa, slen);
Bernie Innocenti55864192018-08-30 04:05:20 +0900270}
271/* BIONIC-END */
272
Bernie Innocenti55864192018-08-30 04:05:20 +0900273/* int
274 * res_isourserver(ina)
275 * looks up "ina" in _res.ns_addr_list[]
276 * returns:
277 * 0 : not found
278 * >0 : found
279 * author:
280 * paul vixie, 29may94
281 */
Bernie Innocenti4acba1a2018-09-26 11:52:04 +0900282static int res_ourserver_p(const res_state statp, const sockaddr* sa) {
283 const sockaddr_in *inp, *srv;
284 const sockaddr_in6 *in6p, *srv6;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900285 int ns;
Bernie Innocenti55864192018-08-30 04:05:20 +0900286
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900287 switch (sa->sa_family) {
288 case AF_INET:
289 inp = (const struct sockaddr_in*) (const void*) sa;
290 for (ns = 0; ns < statp->nscount; ns++) {
291 srv = (struct sockaddr_in*) (void*) get_nsaddr(statp, (size_t) ns);
292 if (srv->sin_family == inp->sin_family && srv->sin_port == inp->sin_port &&
293 (srv->sin_addr.s_addr == INADDR_ANY ||
294 srv->sin_addr.s_addr == inp->sin_addr.s_addr))
Bernie Innocenti4acba1a2018-09-26 11:52:04 +0900295 return 1;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900296 }
297 break;
298 case AF_INET6:
Ken Chencf6ded62018-10-16 23:12:09 +0800299 if (statp->_u._ext.ext == NULL) break;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900300 in6p = (const struct sockaddr_in6*) (const void*) sa;
301 for (ns = 0; ns < statp->nscount; ns++) {
302 srv6 = (struct sockaddr_in6*) (void*) get_nsaddr(statp, (size_t) ns);
303 if (srv6->sin6_family == in6p->sin6_family && srv6->sin6_port == in6p->sin6_port &&
Bernie Innocenti55864192018-08-30 04:05:20 +0900304#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900305 (srv6->sin6_scope_id == 0 || srv6->sin6_scope_id == in6p->sin6_scope_id) &&
Bernie Innocenti55864192018-08-30 04:05:20 +0900306#endif
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900307 (IN6_IS_ADDR_UNSPECIFIED(&srv6->sin6_addr) ||
308 IN6_ARE_ADDR_EQUAL(&srv6->sin6_addr, &in6p->sin6_addr)))
Bernie Innocenti4acba1a2018-09-26 11:52:04 +0900309 return 1;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900310 }
311 break;
312 default:
313 break;
314 }
Bernie Innocenti4acba1a2018-09-26 11:52:04 +0900315 return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900316}
317
318/* int
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900319 * res_nameinquery(name, type, cl, buf, eom)
320 * look for (name, type, cl) in the query section of packet (buf, eom)
Bernie Innocenti55864192018-08-30 04:05:20 +0900321 * requires:
322 * buf + HFIXEDSZ <= eom
323 * returns:
324 * -1 : format error
325 * 0 : not found
326 * >0 : found
327 * author:
328 * paul vixie, 29may94
329 */
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900330int res_nameinquery(const char* name, int type, int cl, const u_char* buf, const u_char* eom) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900331 const u_char* cp = buf + HFIXEDSZ;
332 int qdcount = ntohs(((const HEADER*) (const void*) buf)->qdcount);
Bernie Innocenti55864192018-08-30 04:05:20 +0900333
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900334 while (qdcount-- > 0) {
335 char tname[MAXDNAME + 1];
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900336 int n = dn_expand(buf, eom, cp, tname, sizeof tname);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900337 if (n < 0) return (-1);
338 cp += n;
339 if (cp + 2 * INT16SZ > eom) return (-1);
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900340 int ttype = ns_get16(cp);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900341 cp += INT16SZ;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900342 int tclass = ns_get16(cp);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900343 cp += INT16SZ;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900344 if (ttype == type && tclass == cl && ns_samename(tname, name) == 1) return (1);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900345 }
346 return (0);
Bernie Innocenti55864192018-08-30 04:05:20 +0900347}
348
349/* int
350 * res_queriesmatch(buf1, eom1, buf2, eom2)
351 * is there a 1:1 mapping of (name,type,class)
352 * in (buf1,eom1) and (buf2,eom2)?
353 * returns:
354 * -1 : format error
355 * 0 : not a 1:1 mapping
356 * >0 : is a 1:1 mapping
357 * author:
358 * paul vixie, 29may94
359 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900360int res_queriesmatch(const u_char* buf1, const u_char* eom1, const u_char* buf2,
361 const u_char* eom2) {
362 const u_char* cp = buf1 + HFIXEDSZ;
363 int qdcount = ntohs(((const HEADER*) (const void*) buf1)->qdcount);
Bernie Innocenti55864192018-08-30 04:05:20 +0900364
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900365 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2) return (-1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900366
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900367 /*
368 * Only header section present in replies to
369 * dynamic update packets.
370 */
371 if ((((const HEADER*) (const void*) buf1)->opcode == ns_o_update) &&
372 (((const HEADER*) (const void*) buf2)->opcode == ns_o_update))
373 return (1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900374
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900375 if (qdcount != ntohs(((const HEADER*) (const void*) buf2)->qdcount)) return (0);
376 while (qdcount-- > 0) {
377 char tname[MAXDNAME + 1];
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900378 int n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900379 if (n < 0) return (-1);
380 cp += n;
381 if (cp + 2 * INT16SZ > eom1) return (-1);
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900382 int ttype = ns_get16(cp);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900383 cp += INT16SZ;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900384 int tclass = ns_get16(cp);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900385 cp += INT16SZ;
386 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2)) return (0);
387 }
388 return (1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900389}
390
Mike Yu69615f62018-11-06 15:42:36 +0800391int res_nsend(res_state statp, const u_char* buf, int buflen, u_char* ans, int anssiz, int* rcode) {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900392 int gotsomewhere, terrno, v_circuit, resplen, n;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900393 ResolvCacheStatus cache_status = RESOLV_CACHE_UNSUPPORTED;
Bernie Innocenti55864192018-08-30 04:05:20 +0900394
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900395 if (anssiz < HFIXEDSZ) {
Luke Huang8c0e98f2018-12-03 15:37:28 +0800396 // TODO: Remove errno once callers stop using it
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900397 errno = EINVAL;
Luke Huang8c0e98f2018-12-03 15:37:28 +0800398 return -EINVAL;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900399 }
400 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_QUERY),
401 (stdout, ";; res_send()\n"), buf, buflen);
402 v_circuit = (statp->options & RES_USEVC) || buflen > PACKETSZ;
403 gotsomewhere = 0;
404 terrno = ETIMEDOUT;
Bernie Innocenti55864192018-08-30 04:05:20 +0900405
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900406 int anslen = 0;
407 cache_status = _resolv_cache_lookup(statp->netid, buf, buflen, ans, anssiz, &anslen);
Bernie Innocenti55864192018-08-30 04:05:20 +0900408
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900409 if (cache_status == RESOLV_CACHE_FOUND) {
410 return anslen;
411 } else if (cache_status != RESOLV_CACHE_UNSUPPORTED) {
412 // had a cache miss for a known network, so populate the thread private
413 // data so the normal resolve path can do its thing
414 _resolv_populate_res_for_net(statp);
415 }
416 if (statp->nscount == 0) {
417 // We have no nameservers configured, so there's no point trying.
418 // Tell the cache the query failed, or any retries and anyone else asking the same
419 // question will block for PENDING_REQUEST_TIMEOUT seconds instead of failing fast.
420 _resolv_cache_query_failed(statp->netid, buf, buflen);
Luke Huang8c0e98f2018-12-03 15:37:28 +0800421
422 // TODO: Remove errno once callers stop using it
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900423 errno = ESRCH;
Luke Huang8c0e98f2018-12-03 15:37:28 +0800424 return -ESRCH;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900425 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900426
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900427 /*
428 * If the ns_addr_list in the resolver context has changed, then
429 * invalidate our cached copy and the associated timing data.
430 */
Ken Chencf6ded62018-10-16 23:12:09 +0800431 if (statp->_u._ext.nscount != 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900432 int needclose = 0;
433 struct sockaddr_storage peer;
434 socklen_t peerlen;
Bernie Innocenti55864192018-08-30 04:05:20 +0900435
Ken Chencf6ded62018-10-16 23:12:09 +0800436 if (statp->_u._ext.nscount != statp->nscount) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900437 needclose++;
438 } else {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900439 for (int ns = 0; ns < statp->nscount; ns++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900440 if (statp->nsaddr_list[ns].sin_family &&
441 !sock_eq((struct sockaddr*) (void*) &statp->nsaddr_list[ns],
Ken Chencf6ded62018-10-16 23:12:09 +0800442 (struct sockaddr*) (void*) &statp->_u._ext.ext->nsaddrs[ns])) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900443 needclose++;
444 break;
445 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900446
Ken Chencf6ded62018-10-16 23:12:09 +0800447 if (statp->_u._ext.nssocks[ns] == -1) continue;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900448 peerlen = sizeof(peer);
Ken Chencf6ded62018-10-16 23:12:09 +0800449 if (getpeername(statp->_u._ext.nssocks[ns], (struct sockaddr*) (void*) &peer,
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900450 &peerlen) < 0) {
451 needclose++;
452 break;
453 }
454 if (!sock_eq((struct sockaddr*) (void*) &peer, get_nsaddr(statp, (size_t) ns))) {
455 needclose++;
456 break;
457 }
458 }
459 }
460 if (needclose) {
461 res_nclose(statp);
Ken Chencf6ded62018-10-16 23:12:09 +0800462 statp->_u._ext.nscount = 0;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900463 }
464 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900465
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900466 /*
467 * Maybe initialize our private copy of the ns_addr_list.
468 */
Ken Chencf6ded62018-10-16 23:12:09 +0800469 if (statp->_u._ext.nscount == 0) {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900470 for (int ns = 0; ns < statp->nscount; ns++) {
Ken Chencf6ded62018-10-16 23:12:09 +0800471 statp->_u._ext.nstimes[ns] = RES_MAXTIME;
472 statp->_u._ext.nssocks[ns] = -1;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900473 if (!statp->nsaddr_list[ns].sin_family) continue;
Ken Chencf6ded62018-10-16 23:12:09 +0800474 statp->_u._ext.ext->nsaddrs[ns].sin = statp->nsaddr_list[ns];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900475 }
Ken Chencf6ded62018-10-16 23:12:09 +0800476 statp->_u._ext.nscount = statp->nscount;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900477 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900478
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900479 /*
480 * Some resolvers want to even out the load on their nameservers.
481 * Note that RES_BLAST overrides RES_ROTATE.
482 */
483 if ((statp->options & RES_ROTATE) != 0U && (statp->options & RES_BLAST) == 0U) {
nuccachene172a4e2018-10-23 17:10:58 +0800484 sockaddr_union inu;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900485 struct sockaddr_in ina;
486 int lastns = statp->nscount - 1;
487 int fd;
488 u_int16_t nstime;
Bernie Innocenti55864192018-08-30 04:05:20 +0900489
Ken Chencf6ded62018-10-16 23:12:09 +0800490 if (statp->_u._ext.ext != NULL) inu = statp->_u._ext.ext->nsaddrs[0];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900491 ina = statp->nsaddr_list[0];
Ken Chencf6ded62018-10-16 23:12:09 +0800492 fd = statp->_u._ext.nssocks[0];
493 nstime = statp->_u._ext.nstimes[0];
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900494 for (int ns = 0; ns < lastns; ns++) {
Ken Chencf6ded62018-10-16 23:12:09 +0800495 if (statp->_u._ext.ext != NULL)
496 statp->_u._ext.ext->nsaddrs[ns] = statp->_u._ext.ext->nsaddrs[ns + 1];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900497 statp->nsaddr_list[ns] = statp->nsaddr_list[ns + 1];
Ken Chencf6ded62018-10-16 23:12:09 +0800498 statp->_u._ext.nssocks[ns] = statp->_u._ext.nssocks[ns + 1];
499 statp->_u._ext.nstimes[ns] = statp->_u._ext.nstimes[ns + 1];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900500 }
Ken Chencf6ded62018-10-16 23:12:09 +0800501 if (statp->_u._ext.ext != NULL) statp->_u._ext.ext->nsaddrs[lastns] = inu;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900502 statp->nsaddr_list[lastns] = ina;
Ken Chencf6ded62018-10-16 23:12:09 +0800503 statp->_u._ext.nssocks[lastns] = fd;
504 statp->_u._ext.nstimes[lastns] = nstime;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900505 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900506
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900507 /*
508 * Send request, RETRY times, or until successful.
509 */
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900510 for (int attempt = 0; attempt < statp->retry; ++attempt) {
Bernie Innocenti189eb502018-10-01 23:10:18 +0900511 struct res_stats stats[MAXNS];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900512 struct __res_params params;
Bernie Innocenti189eb502018-10-01 23:10:18 +0900513 int revision_id = resolv_cache_get_resolver_stats(statp->netid, &params, stats);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900514 bool usable_servers[MAXNS];
515 android_net_res_stats_get_usable_servers(&params, stats, statp->nscount, usable_servers);
Bernie Innocenti55864192018-08-30 04:05:20 +0900516
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900517 for (int ns = 0; ns < statp->nscount; ns++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900518 if (!usable_servers[ns]) continue;
519 struct sockaddr* nsap;
520 int nsaplen;
521 time_t now = 0;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900522 int delay = 0;
Mike Yu69615f62018-11-06 15:42:36 +0800523 *rcode = RCODE_INTERNAL_ERROR;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900524 nsap = get_nsaddr(statp, (size_t) ns);
525 nsaplen = get_salen(nsap);
Bernie Innocenti55864192018-08-30 04:05:20 +0900526
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900527 same_ns:
Mike Yu69615f62018-11-06 15:42:36 +0800528 // TODO: Since we expect there is only one DNS server being queried here while this
529 // function tries to query all of private DNS servers. Consider moving it to other
530 // reasonable place. In addition, maybe add stats for private DNS.
531 if (!statp->use_local_nameserver) {
532 bool fallback = false;
533 resplen = res_tls_send(statp, Slice(const_cast<u_char*>(buf), buflen),
534 Slice(ans, anssiz), rcode, &fallback);
535 if (resplen > 0) {
536 if (cache_status == RESOLV_CACHE_NOTFOUND) {
537 _resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
538 }
539 return resplen;
Mike Yua46fae72018-11-01 20:07:00 +0800540 }
Mike Yu69615f62018-11-06 15:42:36 +0800541 if (!fallback) {
Luke Huang8c0e98f2018-12-03 15:37:28 +0800542 _resolv_cache_query_failed(statp->netid, buf, buflen);
543 res_nclose(statp);
544 return -terrno;
Mike Yu69615f62018-11-06 15:42:36 +0800545 }
546 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900547
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900548 [[maybe_unused]] static const int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
549 [[maybe_unused]] char abuf[NI_MAXHOST];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900550 Dprint(((statp->options & RES_DEBUG) &&
551 getnameinfo(nsap, (socklen_t) nsaplen, abuf, sizeof(abuf), NULL, 0, niflags) ==
552 0),
553 (stdout, ";; Querying server (# %d) address = %s\n", ns + 1, abuf));
Bernie Innocenti55864192018-08-30 04:05:20 +0900554
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900555 if (v_circuit) {
556 /* Use VC; at most one attempt per server. */
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900557 attempt = statp->retry;
Bernie Innocenti55864192018-08-30 04:05:20 +0900558
Mike Yu69615f62018-11-06 15:42:36 +0800559 n = send_vc(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &now, rcode,
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900560 &delay);
Bernie Innocenti55864192018-08-30 04:05:20 +0900561
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900562 /*
563 * Only record stats the first time we try a query. This ensures that
564 * queries that deterministically fail (e.g., a name that always returns
565 * SERVFAIL or times out) do not unduly affect the stats.
566 */
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900567 if (attempt == 0) {
Bernie Innocenti189eb502018-10-01 23:10:18 +0900568 res_sample sample;
Mike Yu69615f62018-11-06 15:42:36 +0800569 _res_stats_set_sample(&sample, now, *rcode, delay);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900570 _resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, ns, &sample,
571 params.max_samples);
572 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900573
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900574 VLOG << "used send_vc " << n;
Bernie Innocenti55864192018-08-30 04:05:20 +0900575
Luke Huang8c0e98f2018-12-03 15:37:28 +0800576 if (n < 0) {
577 _resolv_cache_query_failed(statp->netid, buf, buflen);
578 res_nclose(statp);
579 return -terrno;
580 };
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900581 if (n == 0) goto next_ns;
582 resplen = n;
583 } else {
584 /* Use datagrams. */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900585 VLOG << "using send_dg";
Bernie Innocenti55864192018-08-30 04:05:20 +0900586
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900587 n = send_dg(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &v_circuit,
Mike Yu69615f62018-11-06 15:42:36 +0800588 &gotsomewhere, &now, rcode, &delay);
Bernie Innocenti55864192018-08-30 04:05:20 +0900589
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900590 /* Only record stats the first time we try a query. See above. */
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900591 if (attempt == 0) {
Bernie Innocenti189eb502018-10-01 23:10:18 +0900592 res_sample sample;
Mike Yu69615f62018-11-06 15:42:36 +0800593 _res_stats_set_sample(&sample, now, *rcode, delay);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900594 _resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, ns, &sample,
595 params.max_samples);
596 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900597
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900598 VLOG << "used send_dg " << n;
Bernie Innocenti55864192018-08-30 04:05:20 +0900599
Luke Huang8c0e98f2018-12-03 15:37:28 +0800600 if (n < 0) {
601 _resolv_cache_query_failed(statp->netid, buf, buflen);
602 res_nclose(statp);
603 return -terrno;
604 };
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900605 if (n == 0) goto next_ns;
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900606 VLOG << "time=" << time(NULL);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900607 if (v_circuit) goto same_ns;
608 resplen = n;
609 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900610
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900611 Dprint((statp->options & RES_DEBUG) ||
612 ((statp->pfcode & RES_PRF_REPLY) && (statp->pfcode & RES_PRF_HEAD1)),
613 (stdout, ";; got answer:\n"));
Bernie Innocenti55864192018-08-30 04:05:20 +0900614
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900615 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
616 (stdout, "%s", ""), ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti55864192018-08-30 04:05:20 +0900617
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900618 if (cache_status == RESOLV_CACHE_NOTFOUND) {
619 _resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
620 }
621 /*
622 * If we have temporarily opened a virtual circuit,
623 * or if we haven't been asked to keep a socket open,
624 * close the socket.
625 */
626 if ((v_circuit && (statp->options & RES_USEVC) == 0U) ||
627 (statp->options & RES_STAYOPEN) == 0U) {
628 res_nclose(statp);
629 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900630 return (resplen);
631 next_ns:;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900632 } // for each ns
633 } // for each retry
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900634 res_nclose(statp);
635 if (!v_circuit) {
Luke Huang8c0e98f2018-12-03 15:37:28 +0800636 if (!gotsomewhere) {
637 // TODO: Remove errno once callers stop using it
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900638 errno = ECONNREFUSED; /* no nameservers found */
Luke Huang8c0e98f2018-12-03 15:37:28 +0800639 terrno = ECONNREFUSED;
640 } else {
641 // TODO: Remove errno once callers stop using it
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900642 errno = ETIMEDOUT; /* no answer obtained */
Luke Huang8c0e98f2018-12-03 15:37:28 +0800643 terrno = ETIMEDOUT;
644 }
645 } else {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900646 errno = terrno;
Luke Huang8c0e98f2018-12-03 15:37:28 +0800647 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900648 _resolv_cache_query_failed(statp->netid, buf, buflen);
Bernie Innocenti55864192018-08-30 04:05:20 +0900649
Luke Huang8c0e98f2018-12-03 15:37:28 +0800650 return -terrno;
Bernie Innocenti55864192018-08-30 04:05:20 +0900651}
652
653/* Private */
654
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900655static int get_salen(const struct sockaddr* sa) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900656 if (sa->sa_family == AF_INET)
657 return (sizeof(struct sockaddr_in));
658 else if (sa->sa_family == AF_INET6)
659 return (sizeof(struct sockaddr_in6));
660 else
661 return (0); /* unknown, die on connect */
Bernie Innocenti55864192018-08-30 04:05:20 +0900662}
663
664/*
665 * pick appropriate nsaddr_list for use. see res_init() for initialization.
666 */
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900667static struct sockaddr* get_nsaddr(res_state statp, size_t n) {
Ken Chencf6ded62018-10-16 23:12:09 +0800668 if (!statp->nsaddr_list[n].sin_family && statp->_u._ext.ext) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900669 /*
Ken Chencf6ded62018-10-16 23:12:09 +0800670 * - statp->_u._ext.ext->nsaddrs[n] holds an address that is larger
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900671 * than struct sockaddr, and
672 * - user code did not update statp->nsaddr_list[n].
673 */
Ken Chencf6ded62018-10-16 23:12:09 +0800674 return (struct sockaddr*) (void*) &statp->_u._ext.ext->nsaddrs[n];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900675 } else {
676 /*
677 * - user code updated statp->nsaddr_list[n], or
678 * - statp->nsaddr_list[n] has the same content as
Ken Chencf6ded62018-10-16 23:12:09 +0800679 * statp->_u._ext.ext->nsaddrs[n].
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900680 */
681 return (struct sockaddr*) (void*) &statp->nsaddr_list[n];
682 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900683}
684
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900685static struct timespec get_timeout(const res_state statp, const struct __res_params* params,
686 const int ns) {
687 int msec;
688 if (params->base_timeout_msec != 0) {
689 // TODO: scale the timeout by retry attempt and maybe number of servers
690 msec = params->base_timeout_msec;
691 } else {
692 // Legacy algorithm which scales the timeout by nameserver number.
693 // For instance, with 4 nameservers: 5s, 2.5s, 5s, 10s
694 // This has no effect with 1 or 2 nameservers
695 msec = (statp->retrans * 1000) << ns;
696 if (ns > 0) {
697 msec /= statp->nscount;
698 }
699 if (msec < 1000) {
700 msec = 1000; // Use at least 100ms
701 }
702 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900703 VLOG << "using timeout of " << msec << " msec";
Bernie Innocenti55864192018-08-30 04:05:20 +0900704
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900705 struct timespec result;
706 result.tv_sec = msec / 1000;
707 result.tv_nsec = (msec % 1000) * 1000000;
708 return result;
Bernie Innocenti55864192018-08-30 04:05:20 +0900709}
710
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900711static int send_vc(res_state statp, struct __res_params* params, const u_char* buf, int buflen,
712 u_char* ans, int anssiz, int* terrno, int ns, time_t* at, int* rcode,
713 int* delay) {
714 *at = time(NULL);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900715 *delay = 0;
716 const HEADER* hp = (const HEADER*) (const void*) buf;
717 HEADER* anhp = (HEADER*) (void*) ans;
718 struct sockaddr* nsap;
719 int nsaplen;
720 int truncating, connreset, resplen, n;
721 struct iovec iov[2];
722 u_short len;
723 u_char* cp;
Bernie Innocenti55864192018-08-30 04:05:20 +0900724
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900725 VLOG << "using send_vc";
Bernie Innocenti55864192018-08-30 04:05:20 +0900726
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900727 nsap = get_nsaddr(statp, (size_t) ns);
728 nsaplen = get_salen(nsap);
Bernie Innocenti55864192018-08-30 04:05:20 +0900729
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900730 connreset = 0;
731same_ns:
732 truncating = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900733
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900734 struct timespec now = evNowTime();
Bernie Innocenti55864192018-08-30 04:05:20 +0900735
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900736 /* Are we still talking to whom we want to talk to? */
737 if (statp->_vcsock >= 0 && (statp->_flags & RES_F_VC) != 0) {
738 struct sockaddr_storage peer;
739 socklen_t size = sizeof peer;
740 unsigned old_mark;
741 socklen_t mark_size = sizeof(old_mark);
742 if (getpeername(statp->_vcsock, (struct sockaddr*) (void*) &peer, &size) < 0 ||
743 !sock_eq((struct sockaddr*) (void*) &peer, nsap) ||
744 getsockopt(statp->_vcsock, SOL_SOCKET, SO_MARK, &old_mark, &mark_size) < 0 ||
745 old_mark != statp->_mark) {
746 res_nclose(statp);
747 statp->_flags &= ~RES_F_VC;
748 }
749 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900750
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900751 if (statp->_vcsock < 0 || (statp->_flags & RES_F_VC) == 0) {
752 if (statp->_vcsock >= 0) res_nclose(statp);
Bernie Innocenti55864192018-08-30 04:05:20 +0900753
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900754 statp->_vcsock = socket(nsap->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0);
755 if (statp->_vcsock < 0) {
756 switch (errno) {
757 case EPROTONOSUPPORT:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900758 case EPFNOSUPPORT:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900759 case EAFNOSUPPORT:
760 Perror(statp, stderr, "socket(vc)", errno);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900761 return 0;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900762 default:
763 *terrno = errno;
764 Perror(statp, stderr, "socket(vc)", errno);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900765 return -1;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900766 }
767 }
768 fchown(statp->_vcsock, AID_DNS, -1);
769 if (statp->_mark != MARK_UNSET) {
770 if (setsockopt(statp->_vcsock, SOL_SOCKET, SO_MARK, &statp->_mark,
771 sizeof(statp->_mark)) < 0) {
772 *terrno = errno;
773 Perror(statp, stderr, "setsockopt", errno);
774 return -1;
775 }
776 }
777 errno = 0;
778 if (random_bind(statp->_vcsock, nsap->sa_family) < 0) {
779 *terrno = errno;
780 Aerror(statp, stderr, "bind/vc", errno, nsap, nsaplen);
781 res_nclose(statp);
782 return (0);
783 }
784 if (connect_with_timeout(statp->_vcsock, nsap, (socklen_t) nsaplen,
785 get_timeout(statp, params, ns)) < 0) {
786 *terrno = errno;
787 Aerror(statp, stderr, "connect/vc", errno, nsap, nsaplen);
788 res_nclose(statp);
789 /*
790 * The way connect_with_timeout() is implemented prevents us from reliably
791 * determining whether this was really a timeout or e.g. ECONNREFUSED. Since
792 * currently both cases are handled in the same way, there is no need to
793 * change this (yet). If we ever need to reliably distinguish between these
794 * cases, both connect_with_timeout() and retrying_poll() need to be
795 * modified, though.
796 */
797 *rcode = RCODE_TIMEOUT;
798 return (0);
799 }
800 statp->_flags |= RES_F_VC;
801 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900802
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900803 /*
804 * Send length & message
805 */
806 ns_put16((u_short) buflen, (u_char*) (void*) &len);
807 iov[0] = evConsIovec(&len, INT16SZ);
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900808 iov[1] = evConsIovec((void*) buf, (size_t) buflen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900809 if (writev(statp->_vcsock, iov, 2) != (INT16SZ + buflen)) {
810 *terrno = errno;
811 Perror(statp, stderr, "write failed", errno);
812 res_nclose(statp);
813 return (0);
814 }
815 /*
816 * Receive length & response
817 */
818read_len:
819 cp = ans;
820 len = INT16SZ;
821 while ((n = read(statp->_vcsock, (char*) cp, (size_t) len)) > 0) {
822 cp += n;
823 if ((len -= n) == 0) break;
824 }
825 if (n <= 0) {
826 *terrno = errno;
827 Perror(statp, stderr, "read failed", errno);
828 res_nclose(statp);
829 /*
830 * A long running process might get its TCP
831 * connection reset if the remote server was
832 * restarted. Requery the server instead of
833 * trying a new one. When there is only one
834 * server, this means that a query might work
835 * instead of failing. We only allow one reset
836 * per query to prevent looping.
837 */
838 if (*terrno == ECONNRESET && !connreset) {
839 connreset = 1;
840 res_nclose(statp);
841 goto same_ns;
842 }
843 res_nclose(statp);
844 return (0);
845 }
846 resplen = ns_get16(ans);
847 if (resplen > anssiz) {
848 Dprint(statp->options & RES_DEBUG, (stdout, ";; response truncated\n"));
849 truncating = 1;
850 len = anssiz;
851 } else
852 len = resplen;
853 if (len < HFIXEDSZ) {
854 /*
855 * Undersized message.
856 */
857 Dprint(statp->options & RES_DEBUG, (stdout, ";; undersized: %d\n", len));
858 *terrno = EMSGSIZE;
859 res_nclose(statp);
860 return (0);
861 }
862 cp = ans;
863 while (len != 0 && (n = read(statp->_vcsock, (char*) cp, (size_t) len)) > 0) {
864 cp += n;
865 len -= n;
866 }
867 if (n <= 0) {
868 *terrno = errno;
869 Perror(statp, stderr, "read(vc)", errno);
870 res_nclose(statp);
871 return (0);
872 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900873
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900874 if (truncating) {
875 /*
876 * Flush rest of answer so connection stays in synch.
877 */
878 anhp->tc = 1;
879 len = resplen - anssiz;
880 while (len != 0) {
881 char junk[PACKETSZ];
Bernie Innocenti55864192018-08-30 04:05:20 +0900882
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900883 n = read(statp->_vcsock, junk, (len > sizeof junk) ? sizeof junk : len);
884 if (n > 0)
885 len -= n;
886 else
887 break;
888 }
889 }
890 /*
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900891 * If the calling application has bailed out of
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900892 * a previous call and failed to arrange to have
893 * the circuit closed or the server has got
894 * itself confused, then drop the packet and
895 * wait for the correct one.
896 */
897 if (hp->id != anhp->id) {
898 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
899 (stdout, ";; old answer (unexpected):\n"), ans,
900 (resplen > anssiz) ? anssiz : resplen);
901 goto read_len;
902 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900903
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900904 /*
905 * All is well, or the error is fatal. Signal that the
906 * next nameserver ought not be tried.
907 */
908 if (resplen > 0) {
909 struct timespec done = evNowTime();
910 *delay = _res_stats_calculate_rtt(&done, &now);
911 *rcode = anhp->rcode;
912 }
913 return (resplen);
Bernie Innocenti55864192018-08-30 04:05:20 +0900914}
915
916/* return -1 on error (errno set), 0 on success */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900917static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
918 const struct timespec timeout) {
919 int res, origflags;
Bernie Innocenti55864192018-08-30 04:05:20 +0900920
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900921 origflags = fcntl(sock, F_GETFL, 0);
922 fcntl(sock, F_SETFL, origflags | O_NONBLOCK);
Bernie Innocenti55864192018-08-30 04:05:20 +0900923
Bernie Innocentif89b3512018-08-30 07:34:37 +0900924 res = connect(sock, nsap, salen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900925 if (res < 0 && errno != EINPROGRESS) {
926 res = -1;
927 goto done;
928 }
929 if (res != 0) {
930 struct timespec now = evNowTime();
931 struct timespec finish = evAddTime(now, timeout);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900932 VLOG << sock << " send_vc";
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900933 res = retrying_poll(sock, POLLIN | POLLOUT, &finish);
934 if (res <= 0) {
935 res = -1;
936 }
937 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900938done:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900939 fcntl(sock, F_SETFL, origflags);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900940 VLOG << sock << " connect_with_const timeout returning " << res;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900941 return res;
Bernie Innocenti55864192018-08-30 04:05:20 +0900942}
943
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900944static int retrying_poll(const int sock, const short events, const struct timespec* finish) {
945 struct timespec now, timeout;
Bernie Innocenti55864192018-08-30 04:05:20 +0900946
947retry:
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900948 VLOG << " " << sock << " retrying_poll";
Bernie Innocenti55864192018-08-30 04:05:20 +0900949
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900950 now = evNowTime();
951 if (evCmpTime(*finish, now) > 0)
952 timeout = evSubTime(*finish, now);
953 else
954 timeout = evConsTime(0L, 0L);
955 struct pollfd fds = {.fd = sock, .events = events};
956 int n = ppoll(&fds, 1, &timeout, /*sigmask=*/NULL);
957 if (n == 0) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900958 VLOG << " " << sock << "retrying_poll timeout";
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900959 errno = ETIMEDOUT;
960 return 0;
961 }
962 if (n < 0) {
963 if (errno == EINTR) goto retry;
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900964 VLOG << " " << sock << " retrying_poll got error " << n;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900965 return n;
966 }
967 if (fds.revents & (POLLIN | POLLOUT | POLLERR)) {
968 int error;
969 socklen_t len = sizeof(error);
970 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error) {
971 errno = error;
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900972 VLOG << " " << sock << " retrying_poll dot error2 " << errno;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900973 return -1;
974 }
975 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900976 VLOG << " " << sock << " retrying_poll returning " << n;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900977 return n;
Bernie Innocenti55864192018-08-30 04:05:20 +0900978}
979
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900980static int send_dg(res_state statp, struct __res_params* params, const u_char* buf, int buflen,
981 u_char* ans, int anssiz, int* terrno, int ns, int* v_circuit, int* gotsomewhere,
982 time_t* at, int* rcode, int* delay) {
983 *at = time(NULL);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900984 *delay = 0;
985 const HEADER* hp = (const HEADER*) (const void*) buf;
986 HEADER* anhp = (HEADER*) (void*) ans;
987 const struct sockaddr* nsap;
988 int nsaplen;
989 struct timespec now, timeout, finish, done;
990 struct sockaddr_storage from;
991 socklen_t fromlen;
992 int resplen, n, s;
Bernie Innocenti55864192018-08-30 04:05:20 +0900993
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900994 nsap = get_nsaddr(statp, (size_t) ns);
995 nsaplen = get_salen(nsap);
Ken Chencf6ded62018-10-16 23:12:09 +0800996 if (statp->_u._ext.nssocks[ns] == -1) {
997 statp->_u._ext.nssocks[ns] = socket(nsap->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
998 if (statp->_u._ext.nssocks[ns] < 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900999 switch (errno) {
1000 case EPROTONOSUPPORT:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001001 case EPFNOSUPPORT:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001002 case EAFNOSUPPORT:
1003 Perror(statp, stderr, "socket(dg)", errno);
1004 return (0);
1005 default:
1006 *terrno = errno;
1007 Perror(statp, stderr, "socket(dg)", errno);
1008 return (-1);
1009 }
1010 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001011
Ken Chencf6ded62018-10-16 23:12:09 +08001012 fchown(statp->_u._ext.nssocks[ns], AID_DNS, -1);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001013 if (statp->_mark != MARK_UNSET) {
Ken Chencf6ded62018-10-16 23:12:09 +08001014 if (setsockopt(statp->_u._ext.nssocks[ns], SOL_SOCKET, SO_MARK, &(statp->_mark),
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001015 sizeof(statp->_mark)) < 0) {
1016 res_nclose(statp);
1017 return -1;
1018 }
1019 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001020#ifndef CANNOT_CONNECT_DGRAM
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001021 /*
1022 * On a 4.3BSD+ machine (client and server,
1023 * actually), sending to a nameserver datagram
1024 * port with no nameserver will cause an
1025 * ICMP port unreachable message to be returned.
1026 * If our datagram socket is "connected" to the
1027 * server, we get an ECONNREFUSED error on the next
1028 * socket operation, and select returns if the
1029 * error message is received. We can thus detect
1030 * the absence of a nameserver without timing out.
1031 */
Ken Chencf6ded62018-10-16 23:12:09 +08001032 if (random_bind(statp->_u._ext.nssocks[ns], nsap->sa_family) < 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001033 Aerror(statp, stderr, "bind(dg)", errno, nsap, nsaplen);
1034 res_nclose(statp);
1035 return (0);
1036 }
Ken Chencf6ded62018-10-16 23:12:09 +08001037 if (connect(statp->_u._ext.nssocks[ns], nsap, (socklen_t) nsaplen) < 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001038 Aerror(statp, stderr, "connect(dg)", errno, nsap, nsaplen);
1039 res_nclose(statp);
1040 return (0);
1041 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001042#endif /* !CANNOT_CONNECT_DGRAM */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001043 Dprint(statp->options & RES_DEBUG, (stdout, ";; new DG socket\n"))
1044 }
Ken Chencf6ded62018-10-16 23:12:09 +08001045 s = statp->_u._ext.nssocks[ns];
Bernie Innocenti55864192018-08-30 04:05:20 +09001046#ifndef CANNOT_CONNECT_DGRAM
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001047 if (send(s, (const char*) buf, (size_t) buflen, 0) != buflen) {
1048 Perror(statp, stderr, "send", errno);
1049 res_nclose(statp);
1050 return (0);
1051 }
1052#else /* !CANNOT_CONNECT_DGRAM */
1053 if (sendto(s, (const char*) buf, buflen, 0, nsap, nsaplen) != buflen) {
1054 Aerror(statp, stderr, "sendto", errno, nsap, nsaplen);
1055 res_nclose(statp);
1056 return (0);
1057 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001058#endif /* !CANNOT_CONNECT_DGRAM */
1059
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001060 /*
1061 * Wait for reply.
1062 */
1063 timeout = get_timeout(statp, params, ns);
1064 now = evNowTime();
1065 finish = evAddTime(now, timeout);
Bernie Innocenti55864192018-08-30 04:05:20 +09001066retry:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001067 n = retrying_poll(s, POLLIN, &finish);
Bernie Innocenti55864192018-08-30 04:05:20 +09001068
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001069 if (n == 0) {
1070 *rcode = RCODE_TIMEOUT;
1071 Dprint(statp->options & RES_DEBUG, (stdout, ";; timeout\n"));
1072 *gotsomewhere = 1;
1073 return (0);
1074 }
1075 if (n < 0) {
1076 Perror(statp, stderr, "poll", errno);
1077 res_nclose(statp);
1078 return (0);
1079 }
1080 errno = 0;
1081 fromlen = sizeof(from);
1082 resplen = recvfrom(s, (char*) ans, (size_t) anssiz, 0, (struct sockaddr*) (void*) &from,
1083 &fromlen);
1084 if (resplen <= 0) {
1085 Perror(statp, stderr, "recvfrom", errno);
1086 res_nclose(statp);
1087 return (0);
1088 }
1089 *gotsomewhere = 1;
1090 if (resplen < HFIXEDSZ) {
1091 /*
1092 * Undersized message.
1093 */
1094 Dprint(statp->options & RES_DEBUG, (stdout, ";; undersized: %d\n", resplen));
1095 *terrno = EMSGSIZE;
1096 res_nclose(statp);
1097 return (0);
1098 }
1099 if (hp->id != anhp->id) {
1100 /*
1101 * response from old query, ignore it.
1102 * XXX - potential security hazard could
1103 * be detected here.
1104 */
1105 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
1106 (stdout, ";; old answer:\n"), ans, (resplen > anssiz) ? anssiz : resplen);
1107 goto retry;
1108 }
1109 if (!(statp->options & RES_INSECURE1) &&
1110 !res_ourserver_p(statp, (struct sockaddr*) (void*) &from)) {
1111 /*
1112 * response from wrong server? ignore it.
1113 * XXX - potential security hazard could
1114 * be detected here.
1115 */
1116 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
1117 (stdout, ";; not our server:\n"), ans, (resplen > anssiz) ? anssiz : resplen);
1118 goto retry;
1119 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001120 if (anhp->rcode == FORMERR && (statp->options & RES_USE_EDNS0) != 0U) {
1121 /*
1122 * Do not retry if the server do not understand EDNS0.
1123 * The case has to be captured here, as FORMERR packet do not
1124 * carry query section, hence res_queriesmatch() returns 0.
1125 */
1126 DprintQ(statp->options & RES_DEBUG, (stdout, "server rejected query with EDNS0:\n"), ans,
1127 (resplen > anssiz) ? anssiz : resplen);
1128 /* record the error */
1129 statp->_flags |= RES_F_EDNS0ERR;
1130 res_nclose(statp);
1131 return (0);
1132 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001133 if (!(statp->options & RES_INSECURE2) &&
1134 !res_queriesmatch(buf, buf + buflen, ans, ans + anssiz)) {
1135 /*
1136 * response contains wrong query? ignore it.
1137 * XXX - potential security hazard could
1138 * be detected here.
1139 */
1140 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
1141 (stdout, ";; wrong query name:\n"), ans, (resplen > anssiz) ? anssiz : resplen);
1142 goto retry;
1143 ;
1144 }
1145 done = evNowTime();
1146 *delay = _res_stats_calculate_rtt(&done, &now);
1147 if (anhp->rcode == SERVFAIL || anhp->rcode == NOTIMP || anhp->rcode == REFUSED) {
1148 DprintQ(statp->options & RES_DEBUG, (stdout, "server rejected query:\n"), ans,
1149 (resplen > anssiz) ? anssiz : resplen);
1150 res_nclose(statp);
1151 /* don't retry if called from dig */
1152 if (!statp->pfcode) {
1153 *rcode = anhp->rcode;
1154 return (0);
1155 }
1156 }
1157 if (!(statp->options & RES_IGNTC) && anhp->tc) {
1158 /*
1159 * To get the rest of answer,
1160 * use TCP with same server.
1161 */
1162 Dprint(statp->options & RES_DEBUG, (stdout, ";; truncated answer\n"));
1163 *v_circuit = 1;
1164 res_nclose(statp);
1165 return (1);
1166 }
1167 /*
1168 * All is well, or the error is fatal. Signal that the
1169 * next nameserver ought not be tried.
1170 */
1171 if (resplen > 0) {
1172 *rcode = anhp->rcode;
1173 }
1174 return (resplen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001175}
1176
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001177static void Aerror(const res_state statp, FILE* file, const char* string, int error,
1178 const struct sockaddr* address, int alen) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001179 if (!kVerboseLogging) return;
1180
1181 const int save = errno;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001182 char hbuf[NI_MAXHOST];
1183 char sbuf[NI_MAXSERV];
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001184 constexpr int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
Bernie Innocenti55864192018-08-30 04:05:20 +09001185
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001186 if ((statp->options & RES_DEBUG) != 0U) {
1187 if (getnameinfo(address, (socklen_t) alen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
1188 niflags)) {
1189 strncpy(hbuf, "?", sizeof(hbuf) - 1);
1190 hbuf[sizeof(hbuf) - 1] = '\0';
1191 strncpy(sbuf, "?", sizeof(sbuf) - 1);
1192 sbuf[sizeof(sbuf) - 1] = '\0';
1193 }
1194 fprintf(file, "res_send: %s ([%s].%s): %s\n", string, hbuf, sbuf, strerror(error));
1195 }
1196 errno = save;
Bernie Innocenti55864192018-08-30 04:05:20 +09001197}
1198
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001199static void Perror(const res_state statp, FILE* file, const char* string, int error) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001200 if (!kVerboseLogging) return;
Bernie Innocenti55864192018-08-30 04:05:20 +09001201
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001202 const int save = errno;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001203 if ((statp->options & RES_DEBUG) != 0U)
1204 fprintf(file, "res_send: %s: %s\n", string, strerror(error));
1205 errno = save;
Bernie Innocenti55864192018-08-30 04:05:20 +09001206}
1207
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001208static int sock_eq(struct sockaddr* a, struct sockaddr* b) {
1209 struct sockaddr_in *a4, *b4;
1210 struct sockaddr_in6 *a6, *b6;
Bernie Innocenti55864192018-08-30 04:05:20 +09001211
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001212 if (a->sa_family != b->sa_family) return 0;
1213 switch (a->sa_family) {
1214 case AF_INET:
1215 a4 = (struct sockaddr_in*) (void*) a;
1216 b4 = (struct sockaddr_in*) (void*) b;
1217 return a4->sin_port == b4->sin_port && a4->sin_addr.s_addr == b4->sin_addr.s_addr;
1218 case AF_INET6:
1219 a6 = (struct sockaddr_in6*) (void*) a;
1220 b6 = (struct sockaddr_in6*) (void*) b;
1221 return a6->sin6_port == b6->sin6_port &&
Bernie Innocenti55864192018-08-30 04:05:20 +09001222#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001223 a6->sin6_scope_id == b6->sin6_scope_id &&
Bernie Innocenti55864192018-08-30 04:05:20 +09001224#endif
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001225 IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
1226 default:
1227 return 0;
1228 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001229}
Mike Yua46fae72018-11-01 20:07:00 +08001230
Luke Huang490551d2018-11-21 20:37:50 +08001231static int res_tls_send(res_state statp, const Slice query, const Slice answer, int* rcode,
Mike Yu69615f62018-11-06 15:42:36 +08001232 bool* fallback) {
1233 int resplen = 0;
Mike Yua46fae72018-11-01 20:07:00 +08001234 const unsigned netId = statp->netid;
1235 const unsigned mark = statp->_mark;
1236
Mike Yu69615f62018-11-06 15:42:36 +08001237 PrivateDnsStatus privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
1238
1239 if (privateDnsStatus.mode == PrivateDnsMode::OFF) {
1240 *fallback = true;
1241 return -1;
Mike Yua46fae72018-11-01 20:07:00 +08001242 }
1243
Mike Yua46fae72018-11-01 20:07:00 +08001244 if (privateDnsStatus.validatedServers.empty()) {
1245 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
Mike Yu69615f62018-11-06 15:42:36 +08001246 *fallback = true;
1247 return -1;
Mike Yua46fae72018-11-01 20:07:00 +08001248 } else {
1249 // Sleep and iterate some small number of times checking for the
1250 // arrival of resolved and validated server IP addresses, instead
1251 // of returning an immediate error.
Mike Yu5b9ffb22018-12-02 17:54:29 +09001252 // This is needed because as soon as a network becomes the default network, apps will
1253 // send DNS queries on that network. If no servers have yet validated, and we do not
1254 // block those queries, they would immediately fail, causing application-visible errors.
1255 // Note that this can happen even before the network validates, since an unvalidated
1256 // network can become the default network if no validated networks are available.
1257 //
1258 // TODO: see if there is a better way to address this problem, such as buffering the
1259 // queries in a queue or only blocking queries for the first few seconds after a default
1260 // network change.
Mike Yu69615f62018-11-06 15:42:36 +08001261 for (int i = 0; i < 42; i++) {
1262 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1263 if (!gPrivateDnsConfiguration.getStatus(netId).validatedServers.empty()) {
1264 privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
1265 break;
1266 }
1267 }
1268 if (privateDnsStatus.validatedServers.empty()) {
1269 return -1;
1270 }
Mike Yua46fae72018-11-01 20:07:00 +08001271 }
1272 }
1273
1274 VLOG << __func__ << ": performing query over TLS";
1275
1276 const auto response = sDnsTlsDispatcher.query(privateDnsStatus.validatedServers, mark, query,
Mike Yu69615f62018-11-06 15:42:36 +08001277 answer, &resplen);
Mike Yua46fae72018-11-01 20:07:00 +08001278
Mike Yu69615f62018-11-06 15:42:36 +08001279 VLOG << __func__ << ": TLS query result: " << static_cast<int>(response);
Mike Yua46fae72018-11-01 20:07:00 +08001280
1281 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
1282 // In opportunistic mode, handle falling back to cleartext in some
1283 // cases (DNS shouldn't fail if a validated opportunistic mode server
1284 // becomes unreachable for some reason).
1285 switch (response) {
Mike Yu69615f62018-11-06 15:42:36 +08001286 case DnsTlsTransport::Response::success:
Luke Huang490551d2018-11-21 20:37:50 +08001287 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yu69615f62018-11-06 15:42:36 +08001288 return resplen;
Mike Yua46fae72018-11-01 20:07:00 +08001289 case DnsTlsTransport::Response::network_error:
Mike Yu69615f62018-11-06 15:42:36 +08001290 // No need to set the error timeout here since it will fallback to UDP.
Mike Yua46fae72018-11-01 20:07:00 +08001291 case DnsTlsTransport::Response::internal_error:
1292 // Note: this will cause cleartext queries to be emitted, with
1293 // all of the EDNS0 goodness enabled. Fingers crossed. :-/
Mike Yu69615f62018-11-06 15:42:36 +08001294 *fallback = true;
1295 [[fallthrough]];
Mike Yua46fae72018-11-01 20:07:00 +08001296 default:
Mike Yu69615f62018-11-06 15:42:36 +08001297 return -1;
1298 }
1299 } else {
1300 // Strict mode
1301 switch (response) {
1302 case DnsTlsTransport::Response::success:
Luke Huang490551d2018-11-21 20:37:50 +08001303 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yu69615f62018-11-06 15:42:36 +08001304 return resplen;
1305 case DnsTlsTransport::Response::network_error:
1306 // This case happens when the query stored in DnsTlsTransport is expired since
1307 // either 1) the query has been tried for 3 times but no response or 2) fail to
1308 // establish the connection with the server.
Luke Huang490551d2018-11-21 20:37:50 +08001309 *rcode = RCODE_TIMEOUT;
Mike Yu69615f62018-11-06 15:42:36 +08001310 [[fallthrough]];
1311 default:
1312 return -1;
Mike Yua46fae72018-11-01 20:07:00 +08001313 }
1314 }
Mike Yua46fae72018-11-01 20:07:00 +08001315}
Luke Huangeefb7772018-11-19 20:17:26 +08001316
1317int resolv_res_nsend(const android_net_context* netContext, const u_char* msg, int msgLen,
1318 u_char* ans, int ansLen, int* rcode) {
1319 res_state res = res_get_state();
1320 res_setnetcontext(res, netContext);
1321 _resolv_populate_res_for_net(res);
1322 *rcode = NOERROR;
1323 return res_nsend(res, msg, msgLen, ans, ansLen, rcode);
1324}