blob: 06cdb5bd2f733f4b996bffff88b5f814ed00e654 [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>
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
118#define VLOG if (!kVerboseLogging) {} else LOG(INFO)
119
120#ifndef RESOLV_ALLOW_VERBOSE_LOGGING
121static_assert(kVerboseLogging == false,
122 "Verbose logging floods logs at high-rate and exposes privacy-sensitive information. "
123 "Do not enable in release builds.");
Bernie Innocenti55864192018-08-30 04:05:20 +0900124#endif
Bernie Innocenti2fd418e2018-08-30 12:04:03 +0900125
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900126#ifndef DEBUG
127#define Dprint(cond, args) /*empty*/
128#define DprintQ(cond, args, query, size) /*empty*/
129#else
130// TODO: convert to Android logging
131#define Dprint(cond, args) \
132 if (cond) { \
133 fprintf args; \
134 } else { \
135 }
136#define DprintQ(cond, args, query, size) \
137 if (cond) { \
138 fprintf args; \
139 res_pquery(statp, query, size, stdout); \
140 } else { \
141 }
142#endif // DEBUG
Bernie Innocenti55864192018-08-30 04:05:20 +0900143
Mike Yua46fae72018-11-01 20:07:00 +0800144static DnsTlsDispatcher sDnsTlsDispatcher;
145
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900146static int get_salen(const struct sockaddr*);
147static struct sockaddr* get_nsaddr(res_state, size_t);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900148static int send_vc(res_state, struct __res_params* params, const u_char*, int, u_char*, int, int*,
149 int, time_t*, int*, int*);
150static int send_dg(res_state, struct __res_params* params, const u_char*, int, u_char*, int, int*,
151 int, int*, int*, time_t*, int*, int*);
152static void Aerror(const res_state, FILE*, const char*, int, const struct sockaddr*, int);
153static void Perror(const res_state, FILE*, const char*, int);
154static int sock_eq(struct sockaddr*, struct sockaddr*);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900155static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
156 const struct timespec timeout);
Bernie Innocenti55864192018-08-30 04:05:20 +0900157static int retrying_poll(const int sock, short events, const struct timespec* finish);
Luke Huang490551d2018-11-21 20:37:50 +0800158static int res_tls_send(res_state, const Slice query, const Slice answer, int* rcode,
Mike Yu69615f62018-11-06 15:42:36 +0800159 bool* fallback);
Bernie Innocenti55864192018-08-30 04:05:20 +0900160
161/* BIONIC-BEGIN: implement source port randomization */
Bernie Innocenti55864192018-08-30 04:05:20 +0900162
Bernie Innocentif89b3512018-08-30 07:34:37 +0900163// BEGIN: Code copied from ISC eventlib
164// TODO: move away from this code
165
166#define BILLION 1000000000
167
168static struct timespec evConsTime(time_t sec, long nsec) {
169 struct timespec x;
170
171 x.tv_sec = sec;
172 x.tv_nsec = nsec;
173 return (x);
174}
175
176static struct timespec evAddTime(struct timespec addend1, struct timespec addend2) {
177 struct timespec x;
178
179 x.tv_sec = addend1.tv_sec + addend2.tv_sec;
180 x.tv_nsec = addend1.tv_nsec + addend2.tv_nsec;
181 if (x.tv_nsec >= BILLION) {
182 x.tv_sec++;
183 x.tv_nsec -= BILLION;
184 }
185 return (x);
186}
187
188static struct timespec evSubTime(struct timespec minuend, struct timespec subtrahend) {
189 struct timespec x;
190
191 x.tv_sec = minuend.tv_sec - subtrahend.tv_sec;
192 if (minuend.tv_nsec >= subtrahend.tv_nsec)
193 x.tv_nsec = minuend.tv_nsec - subtrahend.tv_nsec;
194 else {
195 x.tv_nsec = BILLION - subtrahend.tv_nsec + minuend.tv_nsec;
196 x.tv_sec--;
197 }
198 return (x);
199}
200
201static int evCmpTime(struct timespec a, struct timespec b) {
202#define SGN(x) ((x) < 0 ? (-1) : (x) > 0 ? (1) : (0));
203 time_t s = a.tv_sec - b.tv_sec;
204 long n;
205
206 if (s != 0) return SGN(s);
207
208 n = a.tv_nsec - b.tv_nsec;
209 return SGN(n);
210}
211
Bernie Innocentif89b3512018-08-30 07:34:37 +0900212static struct timespec evNowTime(void) {
Bernie Innocentif89b3512018-08-30 07:34:37 +0900213 struct timespec tsnow;
Bernie Innocenti357339c2018-08-31 16:11:41 +0900214 clock_gettime(CLOCK_REALTIME, &tsnow);
215 return tsnow;
Bernie Innocentif89b3512018-08-30 07:34:37 +0900216}
217
218static struct iovec evConsIovec(void* buf, size_t cnt) {
219 struct iovec ret;
220
221 memset(&ret, 0xf5, sizeof ret);
222 ret.iov_base = buf;
223 ret.iov_len = cnt;
Bernie Innocenti357339c2018-08-31 16:11:41 +0900224 return ret;
Bernie Innocentif89b3512018-08-30 07:34:37 +0900225}
226
227// END: Code copied from ISC eventlib
228
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900229static int random_bind(int s, int family) {
nuccachene172a4e2018-10-23 17:10:58 +0800230 sockaddr_union u;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900231 int j;
232 socklen_t slen;
Bernie Innocenti55864192018-08-30 04:05:20 +0900233
234 /* clear all, this also sets the IP4/6 address to 'any' */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900235 memset(&u, 0, sizeof u);
Bernie Innocenti55864192018-08-30 04:05:20 +0900236
237 switch (family) {
238 case AF_INET:
239 u.sin.sin_family = family;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900240 slen = sizeof u.sin;
Bernie Innocenti55864192018-08-30 04:05:20 +0900241 break;
242 case AF_INET6:
243 u.sin6.sin6_family = family;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900244 slen = sizeof u.sin6;
Bernie Innocenti55864192018-08-30 04:05:20 +0900245 break;
246 default:
247 errno = EPROTO;
248 return -1;
249 }
250
251 /* first try to bind to a random source port a few times */
252 for (j = 0; j < 10; j++) {
253 /* find a random port between 1025 .. 65534 */
Luke Huang042e9422019-02-13 14:05:02 +0800254 int port = 1025 + (arc4random_uniform(65535 - 1025));
Bernie Innocenti55864192018-08-30 04:05:20 +0900255 if (family == AF_INET)
256 u.sin.sin_port = htons(port);
257 else
258 u.sin6.sin6_port = htons(port);
259
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900260 if (!bind(s, &u.sa, slen)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900261 }
262
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900263 // nothing after 10 attempts, our network table is probably busy
264 // let the system decide which port is best
Bernie Innocenti55864192018-08-30 04:05:20 +0900265 if (family == AF_INET)
266 u.sin.sin_port = 0;
267 else
268 u.sin6.sin6_port = 0;
269
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900270 return bind(s, &u.sa, slen);
Bernie Innocenti55864192018-08-30 04:05:20 +0900271}
272/* BIONIC-END */
273
Bernie Innocenti55864192018-08-30 04:05:20 +0900274/* int
275 * res_isourserver(ina)
276 * looks up "ina" in _res.ns_addr_list[]
277 * returns:
278 * 0 : not found
279 * >0 : found
280 * author:
281 * paul vixie, 29may94
282 */
Bernie Innocenti4acba1a2018-09-26 11:52:04 +0900283static int res_ourserver_p(const res_state statp, const sockaddr* sa) {
284 const sockaddr_in *inp, *srv;
285 const sockaddr_in6 *in6p, *srv6;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900286 int ns;
Bernie Innocenti55864192018-08-30 04:05:20 +0900287
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900288 switch (sa->sa_family) {
289 case AF_INET:
290 inp = (const struct sockaddr_in*) (const void*) sa;
291 for (ns = 0; ns < statp->nscount; ns++) {
292 srv = (struct sockaddr_in*) (void*) get_nsaddr(statp, (size_t) ns);
293 if (srv->sin_family == inp->sin_family && srv->sin_port == inp->sin_port &&
294 (srv->sin_addr.s_addr == INADDR_ANY ||
295 srv->sin_addr.s_addr == inp->sin_addr.s_addr))
Bernie Innocenti4acba1a2018-09-26 11:52:04 +0900296 return 1;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900297 }
298 break;
299 case AF_INET6:
Ken Chencf6ded62018-10-16 23:12:09 +0800300 if (statp->_u._ext.ext == NULL) break;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900301 in6p = (const struct sockaddr_in6*) (const void*) sa;
302 for (ns = 0; ns < statp->nscount; ns++) {
303 srv6 = (struct sockaddr_in6*) (void*) get_nsaddr(statp, (size_t) ns);
304 if (srv6->sin6_family == in6p->sin6_family && srv6->sin6_port == in6p->sin6_port &&
Bernie Innocenti55864192018-08-30 04:05:20 +0900305#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900306 (srv6->sin6_scope_id == 0 || srv6->sin6_scope_id == in6p->sin6_scope_id) &&
Bernie Innocenti55864192018-08-30 04:05:20 +0900307#endif
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900308 (IN6_IS_ADDR_UNSPECIFIED(&srv6->sin6_addr) ||
309 IN6_ARE_ADDR_EQUAL(&srv6->sin6_addr, &in6p->sin6_addr)))
Bernie Innocenti4acba1a2018-09-26 11:52:04 +0900310 return 1;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900311 }
312 break;
313 default:
314 break;
315 }
Bernie Innocenti4acba1a2018-09-26 11:52:04 +0900316 return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900317}
318
319/* int
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900320 * res_nameinquery(name, type, cl, buf, eom)
321 * look for (name, type, cl) in the query section of packet (buf, eom)
Bernie Innocenti55864192018-08-30 04:05:20 +0900322 * requires:
323 * buf + HFIXEDSZ <= eom
324 * returns:
325 * -1 : format error
326 * 0 : not found
327 * >0 : found
328 * author:
329 * paul vixie, 29may94
330 */
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900331int res_nameinquery(const char* name, int type, int cl, const u_char* buf, const u_char* eom) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900332 const u_char* cp = buf + HFIXEDSZ;
333 int qdcount = ntohs(((const HEADER*) (const void*) buf)->qdcount);
Bernie Innocenti55864192018-08-30 04:05:20 +0900334
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900335 while (qdcount-- > 0) {
336 char tname[MAXDNAME + 1];
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900337 int n = dn_expand(buf, eom, cp, tname, sizeof tname);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900338 if (n < 0) return (-1);
339 cp += n;
340 if (cp + 2 * INT16SZ > eom) return (-1);
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900341 int ttype = ns_get16(cp);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900342 cp += INT16SZ;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900343 int tclass = ns_get16(cp);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900344 cp += INT16SZ;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900345 if (ttype == type && tclass == cl && ns_samename(tname, name) == 1) return (1);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900346 }
347 return (0);
Bernie Innocenti55864192018-08-30 04:05:20 +0900348}
349
350/* int
351 * res_queriesmatch(buf1, eom1, buf2, eom2)
352 * is there a 1:1 mapping of (name,type,class)
353 * in (buf1,eom1) and (buf2,eom2)?
354 * returns:
355 * -1 : format error
356 * 0 : not a 1:1 mapping
357 * >0 : is a 1:1 mapping
358 * author:
359 * paul vixie, 29may94
360 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900361int res_queriesmatch(const u_char* buf1, const u_char* eom1, const u_char* buf2,
362 const u_char* eom2) {
363 const u_char* cp = buf1 + HFIXEDSZ;
364 int qdcount = ntohs(((const HEADER*) (const void*) buf1)->qdcount);
Bernie Innocenti55864192018-08-30 04:05:20 +0900365
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900366 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2) return (-1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900367
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900368 /*
369 * Only header section present in replies to
370 * dynamic update packets.
371 */
372 if ((((const HEADER*) (const void*) buf1)->opcode == ns_o_update) &&
373 (((const HEADER*) (const void*) buf2)->opcode == ns_o_update))
374 return (1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900375
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900376 if (qdcount != ntohs(((const HEADER*) (const void*) buf2)->qdcount)) return (0);
377 while (qdcount-- > 0) {
378 char tname[MAXDNAME + 1];
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900379 int n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900380 if (n < 0) return (-1);
381 cp += n;
382 if (cp + 2 * INT16SZ > eom1) return (-1);
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900383 int ttype = ns_get16(cp);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900384 cp += INT16SZ;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900385 int tclass = ns_get16(cp);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900386 cp += INT16SZ;
387 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2)) return (0);
388 }
389 return (1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900390}
391
Luke Huang952d0942018-12-26 16:53:03 +0800392int res_nsend(res_state statp, const u_char* buf, int buflen, u_char* ans, int anssiz, int* rcode,
393 uint32_t flags) {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900394 int gotsomewhere, terrno, v_circuit, resplen, n;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900395 ResolvCacheStatus cache_status = RESOLV_CACHE_UNSUPPORTED;
Bernie Innocenti55864192018-08-30 04:05:20 +0900396
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900397 if (anssiz < HFIXEDSZ) {
Luke Huang8c0e98f2018-12-03 15:37:28 +0800398 // TODO: Remove errno once callers stop using it
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900399 errno = EINVAL;
Luke Huang8c0e98f2018-12-03 15:37:28 +0800400 return -EINVAL;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900401 }
402 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_QUERY),
403 (stdout, ";; res_send()\n"), buf, buflen);
404 v_circuit = (statp->options & RES_USEVC) || buflen > PACKETSZ;
405 gotsomewhere = 0;
406 terrno = ETIMEDOUT;
Bernie Innocenti55864192018-08-30 04:05:20 +0900407
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900408 int anslen = 0;
Luke Huang952d0942018-12-26 16:53:03 +0800409 cache_status = _resolv_cache_lookup(statp->netid, buf, buflen, ans, anssiz, &anslen, flags);
Bernie Innocenti55864192018-08-30 04:05:20 +0900410
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900411 if (cache_status == RESOLV_CACHE_FOUND) {
412 return anslen;
413 } else if (cache_status != RESOLV_CACHE_UNSUPPORTED) {
414 // had a cache miss for a known network, so populate the thread private
415 // data so the normal resolve path can do its thing
416 _resolv_populate_res_for_net(statp);
417 }
418 if (statp->nscount == 0) {
419 // We have no nameservers configured, so there's no point trying.
420 // Tell the cache the query failed, or any retries and anyone else asking the same
421 // question will block for PENDING_REQUEST_TIMEOUT seconds instead of failing fast.
Luke Huang952d0942018-12-26 16:53:03 +0800422 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huang8c0e98f2018-12-03 15:37:28 +0800423
424 // TODO: Remove errno once callers stop using it
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900425 errno = ESRCH;
Luke Huang8c0e98f2018-12-03 15:37:28 +0800426 return -ESRCH;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900427 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900428
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900429 /*
430 * If the ns_addr_list in the resolver context has changed, then
431 * invalidate our cached copy and the associated timing data.
432 */
Ken Chencf6ded62018-10-16 23:12:09 +0800433 if (statp->_u._ext.nscount != 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900434 int needclose = 0;
435 struct sockaddr_storage peer;
436 socklen_t peerlen;
Bernie Innocenti55864192018-08-30 04:05:20 +0900437
Ken Chencf6ded62018-10-16 23:12:09 +0800438 if (statp->_u._ext.nscount != statp->nscount) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900439 needclose++;
440 } else {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900441 for (int ns = 0; ns < statp->nscount; ns++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900442 if (statp->nsaddr_list[ns].sin_family &&
443 !sock_eq((struct sockaddr*) (void*) &statp->nsaddr_list[ns],
Ken Chencf6ded62018-10-16 23:12:09 +0800444 (struct sockaddr*) (void*) &statp->_u._ext.ext->nsaddrs[ns])) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900445 needclose++;
446 break;
447 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900448
Ken Chencf6ded62018-10-16 23:12:09 +0800449 if (statp->_u._ext.nssocks[ns] == -1) continue;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900450 peerlen = sizeof(peer);
Ken Chencf6ded62018-10-16 23:12:09 +0800451 if (getpeername(statp->_u._ext.nssocks[ns], (struct sockaddr*) (void*) &peer,
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900452 &peerlen) < 0) {
453 needclose++;
454 break;
455 }
456 if (!sock_eq((struct sockaddr*) (void*) &peer, get_nsaddr(statp, (size_t) ns))) {
457 needclose++;
458 break;
459 }
460 }
461 }
462 if (needclose) {
463 res_nclose(statp);
Ken Chencf6ded62018-10-16 23:12:09 +0800464 statp->_u._ext.nscount = 0;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900465 }
466 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900467
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900468 /*
469 * Maybe initialize our private copy of the ns_addr_list.
470 */
Ken Chencf6ded62018-10-16 23:12:09 +0800471 if (statp->_u._ext.nscount == 0) {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900472 for (int ns = 0; ns < statp->nscount; ns++) {
Ken Chencf6ded62018-10-16 23:12:09 +0800473 statp->_u._ext.nstimes[ns] = RES_MAXTIME;
474 statp->_u._ext.nssocks[ns] = -1;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900475 if (!statp->nsaddr_list[ns].sin_family) continue;
Ken Chencf6ded62018-10-16 23:12:09 +0800476 statp->_u._ext.ext->nsaddrs[ns].sin = statp->nsaddr_list[ns];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900477 }
Ken Chencf6ded62018-10-16 23:12:09 +0800478 statp->_u._ext.nscount = statp->nscount;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900479 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900480
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900481 /*
482 * Some resolvers want to even out the load on their nameservers.
483 * Note that RES_BLAST overrides RES_ROTATE.
484 */
485 if ((statp->options & RES_ROTATE) != 0U && (statp->options & RES_BLAST) == 0U) {
nuccachene172a4e2018-10-23 17:10:58 +0800486 sockaddr_union inu;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900487 struct sockaddr_in ina;
488 int lastns = statp->nscount - 1;
489 int fd;
490 u_int16_t nstime;
Bernie Innocenti55864192018-08-30 04:05:20 +0900491
Ken Chencf6ded62018-10-16 23:12:09 +0800492 if (statp->_u._ext.ext != NULL) inu = statp->_u._ext.ext->nsaddrs[0];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900493 ina = statp->nsaddr_list[0];
Ken Chencf6ded62018-10-16 23:12:09 +0800494 fd = statp->_u._ext.nssocks[0];
495 nstime = statp->_u._ext.nstimes[0];
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900496 for (int ns = 0; ns < lastns; ns++) {
Ken Chencf6ded62018-10-16 23:12:09 +0800497 if (statp->_u._ext.ext != NULL)
498 statp->_u._ext.ext->nsaddrs[ns] = statp->_u._ext.ext->nsaddrs[ns + 1];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900499 statp->nsaddr_list[ns] = statp->nsaddr_list[ns + 1];
Ken Chencf6ded62018-10-16 23:12:09 +0800500 statp->_u._ext.nssocks[ns] = statp->_u._ext.nssocks[ns + 1];
501 statp->_u._ext.nstimes[ns] = statp->_u._ext.nstimes[ns + 1];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900502 }
Ken Chencf6ded62018-10-16 23:12:09 +0800503 if (statp->_u._ext.ext != NULL) statp->_u._ext.ext->nsaddrs[lastns] = inu;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900504 statp->nsaddr_list[lastns] = ina;
Ken Chencf6ded62018-10-16 23:12:09 +0800505 statp->_u._ext.nssocks[lastns] = fd;
506 statp->_u._ext.nstimes[lastns] = nstime;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900507 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900508
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900509 /*
510 * Send request, RETRY times, or until successful.
511 */
Luke Huang952d0942018-12-26 16:53:03 +0800512 int retryTimes = (flags & ANDROID_RESOLV_NO_RETRY) ? 1 : statp->retry;
513
514 for (int attempt = 0; attempt < retryTimes; ++attempt) {
Bernie Innocenti189eb502018-10-01 23:10:18 +0900515 struct res_stats stats[MAXNS];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900516 struct __res_params params;
Bernie Innocenti189eb502018-10-01 23:10:18 +0900517 int revision_id = resolv_cache_get_resolver_stats(statp->netid, &params, stats);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900518 bool usable_servers[MAXNS];
519 android_net_res_stats_get_usable_servers(&params, stats, statp->nscount, usable_servers);
Bernie Innocenti55864192018-08-30 04:05:20 +0900520
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900521 for (int ns = 0; ns < statp->nscount; ns++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900522 if (!usable_servers[ns]) continue;
523 struct sockaddr* nsap;
524 int nsaplen;
525 time_t now = 0;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900526 int delay = 0;
Mike Yu69615f62018-11-06 15:42:36 +0800527 *rcode = RCODE_INTERNAL_ERROR;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900528 nsap = get_nsaddr(statp, (size_t) ns);
529 nsaplen = get_salen(nsap);
Bernie Innocenti55864192018-08-30 04:05:20 +0900530
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900531 same_ns:
Mike Yu69615f62018-11-06 15:42:36 +0800532 // TODO: Since we expect there is only one DNS server being queried here while this
533 // function tries to query all of private DNS servers. Consider moving it to other
534 // reasonable place. In addition, maybe add stats for private DNS.
535 if (!statp->use_local_nameserver) {
536 bool fallback = false;
537 resplen = res_tls_send(statp, Slice(const_cast<u_char*>(buf), buflen),
538 Slice(ans, anssiz), rcode, &fallback);
539 if (resplen > 0) {
540 if (cache_status == RESOLV_CACHE_NOTFOUND) {
541 _resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
542 }
543 return resplen;
Mike Yua46fae72018-11-01 20:07:00 +0800544 }
Mike Yu69615f62018-11-06 15:42:36 +0800545 if (!fallback) {
Luke Huang952d0942018-12-26 16:53:03 +0800546 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huang8c0e98f2018-12-03 15:37:28 +0800547 res_nclose(statp);
548 return -terrno;
Mike Yu69615f62018-11-06 15:42:36 +0800549 }
550 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900551
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900552 [[maybe_unused]] static const int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
553 [[maybe_unused]] char abuf[NI_MAXHOST];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900554 Dprint(((statp->options & RES_DEBUG) &&
555 getnameinfo(nsap, (socklen_t) nsaplen, abuf, sizeof(abuf), NULL, 0, niflags) ==
556 0),
557 (stdout, ";; Querying server (# %d) address = %s\n", ns + 1, abuf));
Bernie Innocenti55864192018-08-30 04:05:20 +0900558
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900559 if (v_circuit) {
560 /* Use VC; at most one attempt per server. */
Luke Huang952d0942018-12-26 16:53:03 +0800561 bool shouldRecordStats = (attempt == 0);
562 attempt = retryTimes;
Bernie Innocenti55864192018-08-30 04:05:20 +0900563
Mike Yu69615f62018-11-06 15:42:36 +0800564 n = send_vc(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &now, rcode,
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900565 &delay);
Bernie Innocenti55864192018-08-30 04:05:20 +0900566
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900567 /*
568 * Only record stats the first time we try a query. This ensures that
569 * queries that deterministically fail (e.g., a name that always returns
570 * SERVFAIL or times out) do not unduly affect the stats.
571 */
Luke Huang952d0942018-12-26 16:53:03 +0800572 if (shouldRecordStats) {
Bernie Innocenti189eb502018-10-01 23:10:18 +0900573 res_sample sample;
Mike Yu69615f62018-11-06 15:42:36 +0800574 _res_stats_set_sample(&sample, now, *rcode, delay);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900575 _resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, ns, &sample,
576 params.max_samples);
577 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900578
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900579 VLOG << "used send_vc " << n;
Bernie Innocenti55864192018-08-30 04:05:20 +0900580
Luke Huang8c0e98f2018-12-03 15:37:28 +0800581 if (n < 0) {
Luke Huang952d0942018-12-26 16:53:03 +0800582 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huang8c0e98f2018-12-03 15:37:28 +0800583 res_nclose(statp);
584 return -terrno;
585 };
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900586 if (n == 0) goto next_ns;
587 resplen = n;
588 } else {
589 /* Use datagrams. */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900590 VLOG << "using send_dg";
Bernie Innocenti55864192018-08-30 04:05:20 +0900591
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900592 n = send_dg(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &v_circuit,
Mike Yu69615f62018-11-06 15:42:36 +0800593 &gotsomewhere, &now, rcode, &delay);
Bernie Innocenti55864192018-08-30 04:05:20 +0900594
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900595 /* Only record stats the first time we try a query. See above. */
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900596 if (attempt == 0) {
Bernie Innocenti189eb502018-10-01 23:10:18 +0900597 res_sample sample;
Mike Yu69615f62018-11-06 15:42:36 +0800598 _res_stats_set_sample(&sample, now, *rcode, delay);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900599 _resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, ns, &sample,
600 params.max_samples);
601 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900602
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900603 VLOG << "used send_dg " << n;
Bernie Innocenti55864192018-08-30 04:05:20 +0900604
Luke Huang8c0e98f2018-12-03 15:37:28 +0800605 if (n < 0) {
Luke Huang952d0942018-12-26 16:53:03 +0800606 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huang8c0e98f2018-12-03 15:37:28 +0800607 res_nclose(statp);
608 return -terrno;
609 };
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900610 if (n == 0) goto next_ns;
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900611 VLOG << "time=" << time(NULL);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900612 if (v_circuit) goto same_ns;
613 resplen = n;
614 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900615
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900616 Dprint((statp->options & RES_DEBUG) ||
617 ((statp->pfcode & RES_PRF_REPLY) && (statp->pfcode & RES_PRF_HEAD1)),
618 (stdout, ";; got answer:\n"));
Bernie Innocenti55864192018-08-30 04:05:20 +0900619
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900620 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
621 (stdout, "%s", ""), ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti55864192018-08-30 04:05:20 +0900622
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900623 if (cache_status == RESOLV_CACHE_NOTFOUND) {
624 _resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
625 }
626 /*
627 * If we have temporarily opened a virtual circuit,
628 * or if we haven't been asked to keep a socket open,
629 * close the socket.
630 */
631 if ((v_circuit && (statp->options & RES_USEVC) == 0U) ||
632 (statp->options & RES_STAYOPEN) == 0U) {
633 res_nclose(statp);
634 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900635 return (resplen);
636 next_ns:;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900637 } // for each ns
638 } // for each retry
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900639 res_nclose(statp);
640 if (!v_circuit) {
Luke Huang8c0e98f2018-12-03 15:37:28 +0800641 if (!gotsomewhere) {
642 // TODO: Remove errno once callers stop using it
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900643 errno = ECONNREFUSED; /* no nameservers found */
Luke Huang8c0e98f2018-12-03 15:37:28 +0800644 terrno = ECONNREFUSED;
645 } else {
646 // TODO: Remove errno once callers stop using it
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900647 errno = ETIMEDOUT; /* no answer obtained */
Luke Huang8c0e98f2018-12-03 15:37:28 +0800648 terrno = ETIMEDOUT;
649 }
650 } else {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900651 errno = terrno;
Luke Huang8c0e98f2018-12-03 15:37:28 +0800652 }
Luke Huang952d0942018-12-26 16:53:03 +0800653 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Bernie Innocenti55864192018-08-30 04:05:20 +0900654
Luke Huang8c0e98f2018-12-03 15:37:28 +0800655 return -terrno;
Bernie Innocenti55864192018-08-30 04:05:20 +0900656}
657
658/* Private */
659
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900660static int get_salen(const struct sockaddr* sa) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900661 if (sa->sa_family == AF_INET)
662 return (sizeof(struct sockaddr_in));
663 else if (sa->sa_family == AF_INET6)
664 return (sizeof(struct sockaddr_in6));
665 else
666 return (0); /* unknown, die on connect */
Bernie Innocenti55864192018-08-30 04:05:20 +0900667}
668
669/*
670 * pick appropriate nsaddr_list for use. see res_init() for initialization.
671 */
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900672static struct sockaddr* get_nsaddr(res_state statp, size_t n) {
Ken Chencf6ded62018-10-16 23:12:09 +0800673 if (!statp->nsaddr_list[n].sin_family && statp->_u._ext.ext) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900674 /*
Ken Chencf6ded62018-10-16 23:12:09 +0800675 * - statp->_u._ext.ext->nsaddrs[n] holds an address that is larger
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900676 * than struct sockaddr, and
677 * - user code did not update statp->nsaddr_list[n].
678 */
Ken Chencf6ded62018-10-16 23:12:09 +0800679 return (struct sockaddr*) (void*) &statp->_u._ext.ext->nsaddrs[n];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900680 } else {
681 /*
682 * - user code updated statp->nsaddr_list[n], or
683 * - statp->nsaddr_list[n] has the same content as
Ken Chencf6ded62018-10-16 23:12:09 +0800684 * statp->_u._ext.ext->nsaddrs[n].
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900685 */
686 return (struct sockaddr*) (void*) &statp->nsaddr_list[n];
687 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900688}
689
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900690static struct timespec get_timeout(const res_state statp, const struct __res_params* params,
691 const int ns) {
692 int msec;
693 if (params->base_timeout_msec != 0) {
694 // TODO: scale the timeout by retry attempt and maybe number of servers
695 msec = params->base_timeout_msec;
696 } else {
697 // Legacy algorithm which scales the timeout by nameserver number.
698 // For instance, with 4 nameservers: 5s, 2.5s, 5s, 10s
699 // This has no effect with 1 or 2 nameservers
700 msec = (statp->retrans * 1000) << ns;
701 if (ns > 0) {
702 msec /= statp->nscount;
703 }
704 if (msec < 1000) {
705 msec = 1000; // Use at least 100ms
706 }
707 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900708 VLOG << "using timeout of " << msec << " msec";
Bernie Innocenti55864192018-08-30 04:05:20 +0900709
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900710 struct timespec result;
711 result.tv_sec = msec / 1000;
712 result.tv_nsec = (msec % 1000) * 1000000;
713 return result;
Bernie Innocenti55864192018-08-30 04:05:20 +0900714}
715
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900716static int send_vc(res_state statp, struct __res_params* params, const u_char* buf, int buflen,
717 u_char* ans, int anssiz, int* terrno, int ns, time_t* at, int* rcode,
718 int* delay) {
719 *at = time(NULL);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900720 *delay = 0;
721 const HEADER* hp = (const HEADER*) (const void*) buf;
722 HEADER* anhp = (HEADER*) (void*) ans;
723 struct sockaddr* nsap;
724 int nsaplen;
725 int truncating, connreset, resplen, n;
726 struct iovec iov[2];
727 u_short len;
728 u_char* cp;
Bernie Innocenti55864192018-08-30 04:05:20 +0900729
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900730 VLOG << "using send_vc";
Bernie Innocenti55864192018-08-30 04:05:20 +0900731
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900732 nsap = get_nsaddr(statp, (size_t) ns);
733 nsaplen = get_salen(nsap);
Bernie Innocenti55864192018-08-30 04:05:20 +0900734
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900735 connreset = 0;
736same_ns:
737 truncating = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900738
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900739 struct timespec now = evNowTime();
Bernie Innocenti55864192018-08-30 04:05:20 +0900740
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900741 /* Are we still talking to whom we want to talk to? */
742 if (statp->_vcsock >= 0 && (statp->_flags & RES_F_VC) != 0) {
743 struct sockaddr_storage peer;
744 socklen_t size = sizeof peer;
745 unsigned old_mark;
746 socklen_t mark_size = sizeof(old_mark);
747 if (getpeername(statp->_vcsock, (struct sockaddr*) (void*) &peer, &size) < 0 ||
748 !sock_eq((struct sockaddr*) (void*) &peer, nsap) ||
749 getsockopt(statp->_vcsock, SOL_SOCKET, SO_MARK, &old_mark, &mark_size) < 0 ||
750 old_mark != statp->_mark) {
751 res_nclose(statp);
752 statp->_flags &= ~RES_F_VC;
753 }
754 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900755
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900756 if (statp->_vcsock < 0 || (statp->_flags & RES_F_VC) == 0) {
757 if (statp->_vcsock >= 0) res_nclose(statp);
Bernie Innocenti55864192018-08-30 04:05:20 +0900758
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900759 statp->_vcsock = socket(nsap->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0);
760 if (statp->_vcsock < 0) {
761 switch (errno) {
762 case EPROTONOSUPPORT:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900763 case EPFNOSUPPORT:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900764 case EAFNOSUPPORT:
765 Perror(statp, stderr, "socket(vc)", errno);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900766 return 0;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900767 default:
768 *terrno = errno;
769 Perror(statp, stderr, "socket(vc)", errno);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900770 return -1;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900771 }
772 }
773 fchown(statp->_vcsock, AID_DNS, -1);
774 if (statp->_mark != MARK_UNSET) {
775 if (setsockopt(statp->_vcsock, SOL_SOCKET, SO_MARK, &statp->_mark,
776 sizeof(statp->_mark)) < 0) {
777 *terrno = errno;
778 Perror(statp, stderr, "setsockopt", errno);
779 return -1;
780 }
781 }
782 errno = 0;
783 if (random_bind(statp->_vcsock, nsap->sa_family) < 0) {
784 *terrno = errno;
785 Aerror(statp, stderr, "bind/vc", errno, nsap, nsaplen);
786 res_nclose(statp);
787 return (0);
788 }
789 if (connect_with_timeout(statp->_vcsock, nsap, (socklen_t) nsaplen,
790 get_timeout(statp, params, ns)) < 0) {
791 *terrno = errno;
792 Aerror(statp, stderr, "connect/vc", errno, nsap, nsaplen);
793 res_nclose(statp);
794 /*
795 * The way connect_with_timeout() is implemented prevents us from reliably
796 * determining whether this was really a timeout or e.g. ECONNREFUSED. Since
797 * currently both cases are handled in the same way, there is no need to
798 * change this (yet). If we ever need to reliably distinguish between these
799 * cases, both connect_with_timeout() and retrying_poll() need to be
800 * modified, though.
801 */
802 *rcode = RCODE_TIMEOUT;
803 return (0);
804 }
805 statp->_flags |= RES_F_VC;
806 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900807
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900808 /*
809 * Send length & message
810 */
811 ns_put16((u_short) buflen, (u_char*) (void*) &len);
812 iov[0] = evConsIovec(&len, INT16SZ);
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900813 iov[1] = evConsIovec((void*) buf, (size_t) buflen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900814 if (writev(statp->_vcsock, iov, 2) != (INT16SZ + buflen)) {
815 *terrno = errno;
816 Perror(statp, stderr, "write failed", errno);
817 res_nclose(statp);
818 return (0);
819 }
820 /*
821 * Receive length & response
822 */
823read_len:
824 cp = ans;
825 len = INT16SZ;
826 while ((n = read(statp->_vcsock, (char*) cp, (size_t) len)) > 0) {
827 cp += n;
828 if ((len -= n) == 0) break;
829 }
830 if (n <= 0) {
831 *terrno = errno;
832 Perror(statp, stderr, "read failed", errno);
833 res_nclose(statp);
834 /*
835 * A long running process might get its TCP
836 * connection reset if the remote server was
837 * restarted. Requery the server instead of
838 * trying a new one. When there is only one
839 * server, this means that a query might work
840 * instead of failing. We only allow one reset
841 * per query to prevent looping.
842 */
843 if (*terrno == ECONNRESET && !connreset) {
844 connreset = 1;
845 res_nclose(statp);
846 goto same_ns;
847 }
848 res_nclose(statp);
849 return (0);
850 }
851 resplen = ns_get16(ans);
852 if (resplen > anssiz) {
853 Dprint(statp->options & RES_DEBUG, (stdout, ";; response truncated\n"));
854 truncating = 1;
855 len = anssiz;
856 } else
857 len = resplen;
858 if (len < HFIXEDSZ) {
859 /*
860 * Undersized message.
861 */
862 Dprint(statp->options & RES_DEBUG, (stdout, ";; undersized: %d\n", len));
863 *terrno = EMSGSIZE;
864 res_nclose(statp);
865 return (0);
866 }
867 cp = ans;
868 while (len != 0 && (n = read(statp->_vcsock, (char*) cp, (size_t) len)) > 0) {
869 cp += n;
870 len -= n;
871 }
872 if (n <= 0) {
873 *terrno = errno;
874 Perror(statp, stderr, "read(vc)", errno);
875 res_nclose(statp);
876 return (0);
877 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900878
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900879 if (truncating) {
880 /*
881 * Flush rest of answer so connection stays in synch.
882 */
883 anhp->tc = 1;
884 len = resplen - anssiz;
885 while (len != 0) {
886 char junk[PACKETSZ];
Bernie Innocenti55864192018-08-30 04:05:20 +0900887
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900888 n = read(statp->_vcsock, junk, (len > sizeof junk) ? sizeof junk : len);
889 if (n > 0)
890 len -= n;
891 else
892 break;
893 }
894 }
895 /*
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900896 * If the calling application has bailed out of
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900897 * a previous call and failed to arrange to have
898 * the circuit closed or the server has got
899 * itself confused, then drop the packet and
900 * wait for the correct one.
901 */
902 if (hp->id != anhp->id) {
903 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
904 (stdout, ";; old answer (unexpected):\n"), ans,
905 (resplen > anssiz) ? anssiz : resplen);
906 goto read_len;
907 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900908
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900909 /*
910 * All is well, or the error is fatal. Signal that the
911 * next nameserver ought not be tried.
912 */
913 if (resplen > 0) {
914 struct timespec done = evNowTime();
915 *delay = _res_stats_calculate_rtt(&done, &now);
916 *rcode = anhp->rcode;
917 }
918 return (resplen);
Bernie Innocenti55864192018-08-30 04:05:20 +0900919}
920
921/* return -1 on error (errno set), 0 on success */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900922static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
923 const struct timespec timeout) {
924 int res, origflags;
Bernie Innocenti55864192018-08-30 04:05:20 +0900925
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900926 origflags = fcntl(sock, F_GETFL, 0);
927 fcntl(sock, F_SETFL, origflags | O_NONBLOCK);
Bernie Innocenti55864192018-08-30 04:05:20 +0900928
Bernie Innocentif89b3512018-08-30 07:34:37 +0900929 res = connect(sock, nsap, salen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900930 if (res < 0 && errno != EINPROGRESS) {
931 res = -1;
932 goto done;
933 }
934 if (res != 0) {
935 struct timespec now = evNowTime();
936 struct timespec finish = evAddTime(now, timeout);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900937 VLOG << sock << " send_vc";
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900938 res = retrying_poll(sock, POLLIN | POLLOUT, &finish);
939 if (res <= 0) {
940 res = -1;
941 }
942 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900943done:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900944 fcntl(sock, F_SETFL, origflags);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900945 VLOG << sock << " connect_with_const timeout returning " << res;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900946 return res;
Bernie Innocenti55864192018-08-30 04:05:20 +0900947}
948
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900949static int retrying_poll(const int sock, const short events, const struct timespec* finish) {
950 struct timespec now, timeout;
Bernie Innocenti55864192018-08-30 04:05:20 +0900951
952retry:
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900953 VLOG << " " << sock << " retrying_poll";
Bernie Innocenti55864192018-08-30 04:05:20 +0900954
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900955 now = evNowTime();
956 if (evCmpTime(*finish, now) > 0)
957 timeout = evSubTime(*finish, now);
958 else
959 timeout = evConsTime(0L, 0L);
960 struct pollfd fds = {.fd = sock, .events = events};
961 int n = ppoll(&fds, 1, &timeout, /*sigmask=*/NULL);
962 if (n == 0) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900963 VLOG << " " << sock << "retrying_poll timeout";
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900964 errno = ETIMEDOUT;
965 return 0;
966 }
967 if (n < 0) {
968 if (errno == EINTR) goto retry;
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900969 VLOG << " " << sock << " retrying_poll got error " << n;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900970 return n;
971 }
972 if (fds.revents & (POLLIN | POLLOUT | POLLERR)) {
973 int error;
974 socklen_t len = sizeof(error);
975 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error) {
976 errno = error;
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900977 VLOG << " " << sock << " retrying_poll dot error2 " << errno;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900978 return -1;
979 }
980 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900981 VLOG << " " << sock << " retrying_poll returning " << n;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900982 return n;
Bernie Innocenti55864192018-08-30 04:05:20 +0900983}
984
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900985static int send_dg(res_state statp, struct __res_params* params, const u_char* buf, int buflen,
986 u_char* ans, int anssiz, int* terrno, int ns, int* v_circuit, int* gotsomewhere,
987 time_t* at, int* rcode, int* delay) {
988 *at = time(NULL);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900989 *delay = 0;
990 const HEADER* hp = (const HEADER*) (const void*) buf;
991 HEADER* anhp = (HEADER*) (void*) ans;
992 const struct sockaddr* nsap;
993 int nsaplen;
994 struct timespec now, timeout, finish, done;
995 struct sockaddr_storage from;
996 socklen_t fromlen;
997 int resplen, n, s;
Bernie Innocenti55864192018-08-30 04:05:20 +0900998
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900999 nsap = get_nsaddr(statp, (size_t) ns);
1000 nsaplen = get_salen(nsap);
Ken Chencf6ded62018-10-16 23:12:09 +08001001 if (statp->_u._ext.nssocks[ns] == -1) {
1002 statp->_u._ext.nssocks[ns] = socket(nsap->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
1003 if (statp->_u._ext.nssocks[ns] < 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001004 switch (errno) {
1005 case EPROTONOSUPPORT:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001006 case EPFNOSUPPORT:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001007 case EAFNOSUPPORT:
1008 Perror(statp, stderr, "socket(dg)", errno);
1009 return (0);
1010 default:
1011 *terrno = errno;
1012 Perror(statp, stderr, "socket(dg)", errno);
1013 return (-1);
1014 }
1015 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001016
Ken Chencf6ded62018-10-16 23:12:09 +08001017 fchown(statp->_u._ext.nssocks[ns], AID_DNS, -1);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001018 if (statp->_mark != MARK_UNSET) {
Ken Chencf6ded62018-10-16 23:12:09 +08001019 if (setsockopt(statp->_u._ext.nssocks[ns], SOL_SOCKET, SO_MARK, &(statp->_mark),
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001020 sizeof(statp->_mark)) < 0) {
1021 res_nclose(statp);
1022 return -1;
1023 }
1024 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001025#ifndef CANNOT_CONNECT_DGRAM
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001026 /*
1027 * On a 4.3BSD+ machine (client and server,
1028 * actually), sending to a nameserver datagram
1029 * port with no nameserver will cause an
1030 * ICMP port unreachable message to be returned.
1031 * If our datagram socket is "connected" to the
1032 * server, we get an ECONNREFUSED error on the next
1033 * socket operation, and select returns if the
1034 * error message is received. We can thus detect
1035 * the absence of a nameserver without timing out.
1036 */
Ken Chencf6ded62018-10-16 23:12:09 +08001037 if (random_bind(statp->_u._ext.nssocks[ns], nsap->sa_family) < 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001038 Aerror(statp, stderr, "bind(dg)", errno, nsap, nsaplen);
1039 res_nclose(statp);
1040 return (0);
1041 }
Ken Chencf6ded62018-10-16 23:12:09 +08001042 if (connect(statp->_u._ext.nssocks[ns], nsap, (socklen_t) nsaplen) < 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001043 Aerror(statp, stderr, "connect(dg)", errno, nsap, nsaplen);
1044 res_nclose(statp);
1045 return (0);
1046 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001047#endif /* !CANNOT_CONNECT_DGRAM */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001048 Dprint(statp->options & RES_DEBUG, (stdout, ";; new DG socket\n"))
1049 }
Ken Chencf6ded62018-10-16 23:12:09 +08001050 s = statp->_u._ext.nssocks[ns];
Bernie Innocenti55864192018-08-30 04:05:20 +09001051#ifndef CANNOT_CONNECT_DGRAM
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001052 if (send(s, (const char*) buf, (size_t) buflen, 0) != buflen) {
1053 Perror(statp, stderr, "send", errno);
1054 res_nclose(statp);
1055 return (0);
1056 }
1057#else /* !CANNOT_CONNECT_DGRAM */
1058 if (sendto(s, (const char*) buf, buflen, 0, nsap, nsaplen) != buflen) {
1059 Aerror(statp, stderr, "sendto", errno, nsap, nsaplen);
1060 res_nclose(statp);
1061 return (0);
1062 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001063#endif /* !CANNOT_CONNECT_DGRAM */
1064
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001065 /*
1066 * Wait for reply.
1067 */
1068 timeout = get_timeout(statp, params, ns);
1069 now = evNowTime();
1070 finish = evAddTime(now, timeout);
Bernie Innocenti55864192018-08-30 04:05:20 +09001071retry:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001072 n = retrying_poll(s, POLLIN, &finish);
Bernie Innocenti55864192018-08-30 04:05:20 +09001073
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001074 if (n == 0) {
1075 *rcode = RCODE_TIMEOUT;
1076 Dprint(statp->options & RES_DEBUG, (stdout, ";; timeout\n"));
1077 *gotsomewhere = 1;
1078 return (0);
1079 }
1080 if (n < 0) {
1081 Perror(statp, stderr, "poll", errno);
1082 res_nclose(statp);
1083 return (0);
1084 }
1085 errno = 0;
1086 fromlen = sizeof(from);
1087 resplen = recvfrom(s, (char*) ans, (size_t) anssiz, 0, (struct sockaddr*) (void*) &from,
1088 &fromlen);
1089 if (resplen <= 0) {
1090 Perror(statp, stderr, "recvfrom", errno);
1091 res_nclose(statp);
1092 return (0);
1093 }
1094 *gotsomewhere = 1;
1095 if (resplen < HFIXEDSZ) {
1096 /*
1097 * Undersized message.
1098 */
1099 Dprint(statp->options & RES_DEBUG, (stdout, ";; undersized: %d\n", resplen));
1100 *terrno = EMSGSIZE;
1101 res_nclose(statp);
1102 return (0);
1103 }
1104 if (hp->id != anhp->id) {
1105 /*
1106 * response from old query, ignore it.
1107 * XXX - potential security hazard could
1108 * be detected here.
1109 */
1110 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
1111 (stdout, ";; old answer:\n"), ans, (resplen > anssiz) ? anssiz : resplen);
1112 goto retry;
1113 }
1114 if (!(statp->options & RES_INSECURE1) &&
1115 !res_ourserver_p(statp, (struct sockaddr*) (void*) &from)) {
1116 /*
1117 * response from wrong server? ignore it.
1118 * XXX - potential security hazard could
1119 * be detected here.
1120 */
1121 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
1122 (stdout, ";; not our server:\n"), ans, (resplen > anssiz) ? anssiz : resplen);
1123 goto retry;
1124 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001125 if (anhp->rcode == FORMERR && (statp->options & RES_USE_EDNS0) != 0U) {
1126 /*
1127 * Do not retry if the server do not understand EDNS0.
1128 * The case has to be captured here, as FORMERR packet do not
1129 * carry query section, hence res_queriesmatch() returns 0.
1130 */
1131 DprintQ(statp->options & RES_DEBUG, (stdout, "server rejected query with EDNS0:\n"), ans,
1132 (resplen > anssiz) ? anssiz : resplen);
1133 /* record the error */
1134 statp->_flags |= RES_F_EDNS0ERR;
1135 res_nclose(statp);
1136 return (0);
1137 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001138 if (!(statp->options & RES_INSECURE2) &&
1139 !res_queriesmatch(buf, buf + buflen, ans, ans + anssiz)) {
1140 /*
1141 * response contains wrong query? ignore it.
1142 * XXX - potential security hazard could
1143 * be detected here.
1144 */
1145 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
1146 (stdout, ";; wrong query name:\n"), ans, (resplen > anssiz) ? anssiz : resplen);
1147 goto retry;
1148 ;
1149 }
1150 done = evNowTime();
1151 *delay = _res_stats_calculate_rtt(&done, &now);
1152 if (anhp->rcode == SERVFAIL || anhp->rcode == NOTIMP || anhp->rcode == REFUSED) {
1153 DprintQ(statp->options & RES_DEBUG, (stdout, "server rejected query:\n"), ans,
1154 (resplen > anssiz) ? anssiz : resplen);
1155 res_nclose(statp);
1156 /* don't retry if called from dig */
1157 if (!statp->pfcode) {
1158 *rcode = anhp->rcode;
1159 return (0);
1160 }
1161 }
1162 if (!(statp->options & RES_IGNTC) && anhp->tc) {
1163 /*
1164 * To get the rest of answer,
1165 * use TCP with same server.
1166 */
1167 Dprint(statp->options & RES_DEBUG, (stdout, ";; truncated answer\n"));
1168 *v_circuit = 1;
1169 res_nclose(statp);
1170 return (1);
1171 }
1172 /*
1173 * All is well, or the error is fatal. Signal that the
1174 * next nameserver ought not be tried.
1175 */
1176 if (resplen > 0) {
1177 *rcode = anhp->rcode;
1178 }
1179 return (resplen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001180}
1181
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001182static void Aerror(const res_state statp, FILE* file, const char* string, int error,
1183 const struct sockaddr* address, int alen) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001184 if (!kVerboseLogging) return;
1185
1186 const int save = errno;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001187 char hbuf[NI_MAXHOST];
1188 char sbuf[NI_MAXSERV];
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001189 constexpr int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
Bernie Innocenti55864192018-08-30 04:05:20 +09001190
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001191 if ((statp->options & RES_DEBUG) != 0U) {
1192 if (getnameinfo(address, (socklen_t) alen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
1193 niflags)) {
1194 strncpy(hbuf, "?", sizeof(hbuf) - 1);
1195 hbuf[sizeof(hbuf) - 1] = '\0';
1196 strncpy(sbuf, "?", sizeof(sbuf) - 1);
1197 sbuf[sizeof(sbuf) - 1] = '\0';
1198 }
1199 fprintf(file, "res_send: %s ([%s].%s): %s\n", string, hbuf, sbuf, strerror(error));
1200 }
1201 errno = save;
Bernie Innocenti55864192018-08-30 04:05:20 +09001202}
1203
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001204static void Perror(const res_state statp, FILE* file, const char* string, int error) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001205 if (!kVerboseLogging) return;
Bernie Innocenti55864192018-08-30 04:05:20 +09001206
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001207 const int save = errno;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001208 if ((statp->options & RES_DEBUG) != 0U)
1209 fprintf(file, "res_send: %s: %s\n", string, strerror(error));
1210 errno = save;
Bernie Innocenti55864192018-08-30 04:05:20 +09001211}
1212
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001213static int sock_eq(struct sockaddr* a, struct sockaddr* b) {
1214 struct sockaddr_in *a4, *b4;
1215 struct sockaddr_in6 *a6, *b6;
Bernie Innocenti55864192018-08-30 04:05:20 +09001216
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001217 if (a->sa_family != b->sa_family) return 0;
1218 switch (a->sa_family) {
1219 case AF_INET:
1220 a4 = (struct sockaddr_in*) (void*) a;
1221 b4 = (struct sockaddr_in*) (void*) b;
1222 return a4->sin_port == b4->sin_port && a4->sin_addr.s_addr == b4->sin_addr.s_addr;
1223 case AF_INET6:
1224 a6 = (struct sockaddr_in6*) (void*) a;
1225 b6 = (struct sockaddr_in6*) (void*) b;
1226 return a6->sin6_port == b6->sin6_port &&
Bernie Innocenti55864192018-08-30 04:05:20 +09001227#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001228 a6->sin6_scope_id == b6->sin6_scope_id &&
Bernie Innocenti55864192018-08-30 04:05:20 +09001229#endif
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001230 IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
1231 default:
1232 return 0;
1233 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001234}
Mike Yua46fae72018-11-01 20:07:00 +08001235
Luke Huang490551d2018-11-21 20:37:50 +08001236static int res_tls_send(res_state statp, const Slice query, const Slice answer, int* rcode,
Mike Yu69615f62018-11-06 15:42:36 +08001237 bool* fallback) {
1238 int resplen = 0;
Mike Yua46fae72018-11-01 20:07:00 +08001239 const unsigned netId = statp->netid;
1240 const unsigned mark = statp->_mark;
1241
Mike Yu69615f62018-11-06 15:42:36 +08001242 PrivateDnsStatus privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
1243
1244 if (privateDnsStatus.mode == PrivateDnsMode::OFF) {
1245 *fallback = true;
1246 return -1;
Mike Yua46fae72018-11-01 20:07:00 +08001247 }
1248
Mike Yua46fae72018-11-01 20:07:00 +08001249 if (privateDnsStatus.validatedServers.empty()) {
1250 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
Mike Yu69615f62018-11-06 15:42:36 +08001251 *fallback = true;
1252 return -1;
Mike Yua46fae72018-11-01 20:07:00 +08001253 } else {
1254 // Sleep and iterate some small number of times checking for the
1255 // arrival of resolved and validated server IP addresses, instead
1256 // of returning an immediate error.
Mike Yu5b9ffb22018-12-02 17:54:29 +09001257 // This is needed because as soon as a network becomes the default network, apps will
1258 // send DNS queries on that network. If no servers have yet validated, and we do not
1259 // block those queries, they would immediately fail, causing application-visible errors.
1260 // Note that this can happen even before the network validates, since an unvalidated
1261 // network can become the default network if no validated networks are available.
1262 //
1263 // TODO: see if there is a better way to address this problem, such as buffering the
1264 // queries in a queue or only blocking queries for the first few seconds after a default
1265 // network change.
Mike Yu69615f62018-11-06 15:42:36 +08001266 for (int i = 0; i < 42; i++) {
1267 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1268 if (!gPrivateDnsConfiguration.getStatus(netId).validatedServers.empty()) {
1269 privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
1270 break;
1271 }
1272 }
1273 if (privateDnsStatus.validatedServers.empty()) {
1274 return -1;
1275 }
Mike Yua46fae72018-11-01 20:07:00 +08001276 }
1277 }
1278
1279 VLOG << __func__ << ": performing query over TLS";
1280
1281 const auto response = sDnsTlsDispatcher.query(privateDnsStatus.validatedServers, mark, query,
Mike Yu69615f62018-11-06 15:42:36 +08001282 answer, &resplen);
Mike Yua46fae72018-11-01 20:07:00 +08001283
Mike Yu69615f62018-11-06 15:42:36 +08001284 VLOG << __func__ << ": TLS query result: " << static_cast<int>(response);
Mike Yua46fae72018-11-01 20:07:00 +08001285
1286 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
1287 // In opportunistic mode, handle falling back to cleartext in some
1288 // cases (DNS shouldn't fail if a validated opportunistic mode server
1289 // becomes unreachable for some reason).
1290 switch (response) {
Mike Yu69615f62018-11-06 15:42:36 +08001291 case DnsTlsTransport::Response::success:
Luke Huang490551d2018-11-21 20:37:50 +08001292 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yu69615f62018-11-06 15:42:36 +08001293 return resplen;
Mike Yua46fae72018-11-01 20:07:00 +08001294 case DnsTlsTransport::Response::network_error:
Mike Yu69615f62018-11-06 15:42:36 +08001295 // No need to set the error timeout here since it will fallback to UDP.
Mike Yua46fae72018-11-01 20:07:00 +08001296 case DnsTlsTransport::Response::internal_error:
1297 // Note: this will cause cleartext queries to be emitted, with
1298 // all of the EDNS0 goodness enabled. Fingers crossed. :-/
Mike Yu69615f62018-11-06 15:42:36 +08001299 *fallback = true;
1300 [[fallthrough]];
Mike Yua46fae72018-11-01 20:07:00 +08001301 default:
Mike Yu69615f62018-11-06 15:42:36 +08001302 return -1;
1303 }
1304 } else {
1305 // Strict mode
1306 switch (response) {
1307 case DnsTlsTransport::Response::success:
Luke Huang490551d2018-11-21 20:37:50 +08001308 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yu69615f62018-11-06 15:42:36 +08001309 return resplen;
1310 case DnsTlsTransport::Response::network_error:
1311 // This case happens when the query stored in DnsTlsTransport is expired since
1312 // either 1) the query has been tried for 3 times but no response or 2) fail to
1313 // establish the connection with the server.
Luke Huang490551d2018-11-21 20:37:50 +08001314 *rcode = RCODE_TIMEOUT;
Mike Yu69615f62018-11-06 15:42:36 +08001315 [[fallthrough]];
1316 default:
1317 return -1;
Mike Yua46fae72018-11-01 20:07:00 +08001318 }
1319 }
Mike Yua46fae72018-11-01 20:07:00 +08001320}
Luke Huangeefb7772018-11-19 20:17:26 +08001321
Luke Huang952d0942018-12-26 16:53:03 +08001322int resolv_res_nsend(const android_net_context* netContext, const uint8_t* msg, int msgLen,
1323 uint8_t* ans, int ansLen, int* rcode, uint32_t flags) {
Luke Huangeefb7772018-11-19 20:17:26 +08001324 res_state res = res_get_state();
1325 res_setnetcontext(res, netContext);
1326 _resolv_populate_res_for_net(res);
1327 *rcode = NOERROR;
Luke Huang952d0942018-12-26 16:53:03 +08001328 return res_nsend(res, msg, msgLen, ans, ansLen, rcode, flags);
Bernie Innocentiad4e26e2019-01-30 11:16:36 +09001329}