blob: 0f048b4d21c536b869d73649587632821f7795c1 [file] [log] [blame]
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001/* $NetBSD: res_send.c,v 1.9 2006/01/24 17:41:25 christos Exp $ */
2
3/*
4 * Copyright (c) 1985, 1989, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. All advertising materials mentioning features or use of this software
16 * must display the following acknowledgement:
17 * This product includes software developed by the University of
18 * California, Berkeley and its contributors.
19 * 4. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 */
35
36/*
37 * Portions Copyright (c) 1993 by Digital Equipment Corporation.
38 *
39 * Permission to use, copy, modify, and distribute this software for any
40 * purpose with or without fee is hereby granted, provided that the above
41 * copyright notice and this permission notice appear in all copies, and that
42 * the name of Digital Equipment Corporation not be used in advertising or
43 * publicity pertaining to distribution of the document or software without
44 * specific, written prior permission.
45 *
46 * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
47 * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
48 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
49 * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
50 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
51 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
52 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
53 * SOFTWARE.
54 */
55
56/*
57 * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
58 * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
59 *
60 * Permission to use, copy, modify, and distribute this software for any
61 * purpose with or without fee is hereby granted, provided that the above
62 * copyright notice and this permission notice appear in all copies.
63 *
64 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
65 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
66 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR
67 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
68 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
69 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
70 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
71 */
72
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090073/*
74 * Send query to name server and wait for reply.
75 */
76
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +090077constexpr bool kVerboseLogging = false;
78#define LOG_TAG "res_send"
79
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090080#include <sys/param.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090081#include <sys/socket.h>
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090082#include <sys/time.h>
83#include <sys/types.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090084#include <sys/uio.h>
85
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090086#include <arpa/inet.h>
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090087#include <arpa/nameser.h>
88#include <netinet/in.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090089
90#include <errno.h>
91#include <fcntl.h>
92#include <netdb.h>
93#include <poll.h>
Bernie Innocenti318ed2d2018-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 Innocenti9f05f5e2018-09-12 23:20:10 +0900101#include <android-base/logging.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900102
Mike Yub601ff72018-11-01 20:07:00 +0800103#include <netdutils/Slice.h>
Bernie Innocentiec4219b2019-01-30 11:16:36 +0900104#include "DnsTlsDispatcher.h"
105#include "DnsTlsTransport.h"
106#include "PrivateDnsConfiguration.h"
Bernie Innocentiac18b122018-10-01 23:10:18 +0900107#include "netd_resolv/resolv.h"
108#include "netd_resolv/stats.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900109#include "private/android_filesystem_config.h"
Bernie Innocentiac18b122018-10-01 23:10:18 +0900110#include "res_state_ext.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900111#include "resolv_cache.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900112#include "resolv_private.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900113
Mike Yub601ff72018-11-01 20:07:00 +0800114// TODO: use the namespace something like android::netd_resolv for libnetd_resolv
115using namespace android::net;
Bernie Innocentiec4219b2019-01-30 11:16:36 +0900116using android::netdutils::Slice;
Bernie Innocenti9f05f5e2018-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 Innocenti318ed2d2018-08-30 04:05:20 +0900124#endif
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900125
Bernie Innocenti9f05f5e2018-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 Innocenti318ed2d2018-08-30 04:05:20 +0900143
Mike Yub601ff72018-11-01 20:07:00 +0800144static DnsTlsDispatcher sDnsTlsDispatcher;
145
Bernie Innocenti9c575932018-09-07 21:10:25 +0900146static int get_salen(const struct sockaddr*);
147static struct sockaddr* get_nsaddr(res_state, size_t);
Bernie Innocenti8ad893f2018-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 Innocenti8ad893f2018-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 Innocenti318ed2d2018-08-30 04:05:20 +0900157static int retrying_poll(const int sock, short events, const struct timespec* finish);
Luke Huangd7aa7b42018-11-21 20:37:50 +0800158static int res_tls_send(res_state, const Slice query, const Slice answer, int* rcode,
Mike Yubfb1b342018-11-06 15:42:36 +0800159 bool* fallback);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900160
161/* BIONIC-BEGIN: implement source port randomization */
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900162
Bernie Innocentiafaacf72018-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 Innocentiafaacf72018-08-30 07:34:37 +0900212static struct timespec evNowTime(void) {
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900213 struct timespec tsnow;
Bernie Innocentic1834822018-08-31 16:11:41 +0900214 clock_gettime(CLOCK_REALTIME, &tsnow);
215 return tsnow;
Bernie Innocentiafaacf72018-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 Innocentic1834822018-08-31 16:11:41 +0900224 return ret;
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900225}
226
227// END: Code copied from ISC eventlib
228
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900229static int random_bind(int s, int family) {
nuccachenb980f2f2018-10-23 17:10:58 +0800230 sockaddr_union u;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900231 int j;
232 socklen_t slen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900233
234 /* clear all, this also sets the IP4/6 address to 'any' */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900235 memset(&u, 0, sizeof u);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900236
237 switch (family) {
238 case AF_INET:
239 u.sin.sin_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900240 slen = sizeof u.sin;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900241 break;
242 case AF_INET6:
243 u.sin6.sin6_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900244 slen = sizeof u.sin6;
Bernie Innocenti318ed2d2018-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 Huangdda920f2019-02-13 14:05:02 +0800254 int port = 1025 + (arc4random_uniform(65535 - 1025));
Bernie Innocenti318ed2d2018-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 Innocenti8ad893f2018-08-31 14:09:46 +0900260 if (!bind(s, &u.sa, slen)) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900261 }
262
Bernie Innocenti9c575932018-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 Innocenti318ed2d2018-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 Innocenti8ad893f2018-08-31 14:09:46 +0900270 return bind(s, &u.sa, slen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900271}
272/* BIONIC-END */
273
Bernie Innocenti318ed2d2018-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 Innocenti2e8540b2018-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 Innocenti8ad893f2018-08-31 14:09:46 +0900286 int ns;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900287
Bernie Innocenti8ad893f2018-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 Innocenti2e8540b2018-09-26 11:52:04 +0900296 return 1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900297 }
298 break;
299 case AF_INET6:
Ken Chene6fa86e2018-10-16 23:12:09 +0800300 if (statp->_u._ext.ext == NULL) break;
Bernie Innocenti8ad893f2018-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 Innocenti318ed2d2018-08-30 04:05:20 +0900305#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900306 (srv6->sin6_scope_id == 0 || srv6->sin6_scope_id == in6p->sin6_scope_id) &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900307#endif
Bernie Innocenti8ad893f2018-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 Innocenti2e8540b2018-09-26 11:52:04 +0900310 return 1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900311 }
312 break;
313 default:
314 break;
315 }
Bernie Innocenti2e8540b2018-09-26 11:52:04 +0900316 return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900317}
318
319/* int
Bernie Innocenti9c575932018-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 Innocenti318ed2d2018-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 Innocenti9c575932018-09-07 21:10:25 +0900331int res_nameinquery(const char* name, int type, int cl, const u_char* buf, const u_char* eom) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900332 const u_char* cp = buf + HFIXEDSZ;
333 int qdcount = ntohs(((const HEADER*) (const void*) buf)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900334
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900335 while (qdcount-- > 0) {
336 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900337 int n = dn_expand(buf, eom, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900338 if (n < 0) return (-1);
339 cp += n;
340 if (cp + 2 * INT16SZ > eom) return (-1);
Bernie Innocenti9c575932018-09-07 21:10:25 +0900341 int ttype = ns_get16(cp);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900342 cp += INT16SZ;
Bernie Innocenti9c575932018-09-07 21:10:25 +0900343 int tclass = ns_get16(cp);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900344 cp += INT16SZ;
Bernie Innocenti9c575932018-09-07 21:10:25 +0900345 if (ttype == type && tclass == cl && ns_samename(tname, name) == 1) return (1);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900346 }
347 return (0);
Bernie Innocenti318ed2d2018-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 Innocenti8ad893f2018-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 Innocenti318ed2d2018-08-30 04:05:20 +0900365
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900366 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2) return (-1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900367
Bernie Innocenti8ad893f2018-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 Innocenti318ed2d2018-08-30 04:05:20 +0900375
Bernie Innocenti8ad893f2018-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 Innocenti9c575932018-09-07 21:10:25 +0900379 int n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900380 if (n < 0) return (-1);
381 cp += n;
382 if (cp + 2 * INT16SZ > eom1) return (-1);
Bernie Innocenti9c575932018-09-07 21:10:25 +0900383 int ttype = ns_get16(cp);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900384 cp += INT16SZ;
Bernie Innocenti9c575932018-09-07 21:10:25 +0900385 int tclass = ns_get16(cp);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900386 cp += INT16SZ;
387 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2)) return (0);
388 }
389 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900390}
391
Luke Huangba7bef92018-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 Innocenti9c575932018-09-07 21:10:25 +0900394 int gotsomewhere, terrno, v_circuit, resplen, n;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900395 ResolvCacheStatus cache_status = RESOLV_CACHE_UNSUPPORTED;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900396
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900397 if (anssiz < HFIXEDSZ) {
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800398 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900399 errno = EINVAL;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800400 return -EINVAL;
Bernie Innocenti8ad893f2018-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 Innocenti318ed2d2018-08-30 04:05:20 +0900407
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900408 int anslen = 0;
Luke Huangba7bef92018-12-26 16:53:03 +0800409 cache_status = _resolv_cache_lookup(statp->netid, buf, buflen, ans, anssiz, &anslen, flags);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900410
Bernie Innocenti8ad893f2018-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 Huangba7bef92018-12-26 16:53:03 +0800422 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800423
424 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900425 errno = ESRCH;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800426 return -ESRCH;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900427 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900428
Bernie Innocenti8ad893f2018-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 Chene6fa86e2018-10-16 23:12:09 +0800433 if (statp->_u._ext.nscount != 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900434 int needclose = 0;
435 struct sockaddr_storage peer;
436 socklen_t peerlen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900437
Ken Chene6fa86e2018-10-16 23:12:09 +0800438 if (statp->_u._ext.nscount != statp->nscount) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900439 needclose++;
440 } else {
Bernie Innocenti9c575932018-09-07 21:10:25 +0900441 for (int ns = 0; ns < statp->nscount; ns++) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900442 if (statp->nsaddr_list[ns].sin_family &&
443 !sock_eq((struct sockaddr*) (void*) &statp->nsaddr_list[ns],
Ken Chene6fa86e2018-10-16 23:12:09 +0800444 (struct sockaddr*) (void*) &statp->_u._ext.ext->nsaddrs[ns])) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900445 needclose++;
446 break;
447 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900448
Ken Chene6fa86e2018-10-16 23:12:09 +0800449 if (statp->_u._ext.nssocks[ns] == -1) continue;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900450 peerlen = sizeof(peer);
Ken Chene6fa86e2018-10-16 23:12:09 +0800451 if (getpeername(statp->_u._ext.nssocks[ns], (struct sockaddr*) (void*) &peer,
Bernie Innocenti8ad893f2018-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 Chene6fa86e2018-10-16 23:12:09 +0800464 statp->_u._ext.nscount = 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900465 }
466 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900467
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900468 /*
469 * Maybe initialize our private copy of the ns_addr_list.
470 */
Ken Chene6fa86e2018-10-16 23:12:09 +0800471 if (statp->_u._ext.nscount == 0) {
Bernie Innocenti9c575932018-09-07 21:10:25 +0900472 for (int ns = 0; ns < statp->nscount; ns++) {
Ken Chene6fa86e2018-10-16 23:12:09 +0800473 statp->_u._ext.nstimes[ns] = RES_MAXTIME;
474 statp->_u._ext.nssocks[ns] = -1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900475 if (!statp->nsaddr_list[ns].sin_family) continue;
Ken Chene6fa86e2018-10-16 23:12:09 +0800476 statp->_u._ext.ext->nsaddrs[ns].sin = statp->nsaddr_list[ns];
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900477 }
Ken Chene6fa86e2018-10-16 23:12:09 +0800478 statp->_u._ext.nscount = statp->nscount;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900479 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900480
Bernie Innocenti8ad893f2018-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) {
nuccachenb980f2f2018-10-23 17:10:58 +0800486 sockaddr_union inu;
Bernie Innocenti8ad893f2018-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 Innocenti318ed2d2018-08-30 04:05:20 +0900491
Ken Chene6fa86e2018-10-16 23:12:09 +0800492 if (statp->_u._ext.ext != NULL) inu = statp->_u._ext.ext->nsaddrs[0];
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900493 ina = statp->nsaddr_list[0];
Ken Chene6fa86e2018-10-16 23:12:09 +0800494 fd = statp->_u._ext.nssocks[0];
495 nstime = statp->_u._ext.nstimes[0];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900496 for (int ns = 0; ns < lastns; ns++) {
Ken Chene6fa86e2018-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 Innocenti8ad893f2018-08-31 14:09:46 +0900499 statp->nsaddr_list[ns] = statp->nsaddr_list[ns + 1];
Ken Chene6fa86e2018-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 Innocenti8ad893f2018-08-31 14:09:46 +0900502 }
Ken Chene6fa86e2018-10-16 23:12:09 +0800503 if (statp->_u._ext.ext != NULL) statp->_u._ext.ext->nsaddrs[lastns] = inu;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900504 statp->nsaddr_list[lastns] = ina;
Ken Chene6fa86e2018-10-16 23:12:09 +0800505 statp->_u._ext.nssocks[lastns] = fd;
506 statp->_u._ext.nstimes[lastns] = nstime;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900507 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900508
waynema0161acd2019-02-18 17:47:59 +0800509 struct res_stats stats[MAXNS];
510 struct __res_params params;
511 int revision_id = resolv_cache_get_resolver_stats(statp->netid, &params, stats);
512 bool usable_servers[MAXNS];
513 android_net_res_stats_get_usable_servers(&params, stats, statp->nscount, usable_servers);
514 if (params.retry_count != 0) statp->retry = params.retry_count;
515
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900516 /*
517 * Send request, RETRY times, or until successful.
518 */
Luke Huangba7bef92018-12-26 16:53:03 +0800519 int retryTimes = (flags & ANDROID_RESOLV_NO_RETRY) ? 1 : statp->retry;
520
521 for (int attempt = 0; attempt < retryTimes; ++attempt) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900522
Bernie Innocenti9c575932018-09-07 21:10:25 +0900523 for (int ns = 0; ns < statp->nscount; ns++) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900524 if (!usable_servers[ns]) continue;
525 struct sockaddr* nsap;
526 int nsaplen;
527 time_t now = 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900528 int delay = 0;
Mike Yubfb1b342018-11-06 15:42:36 +0800529 *rcode = RCODE_INTERNAL_ERROR;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900530 nsap = get_nsaddr(statp, (size_t) ns);
531 nsaplen = get_salen(nsap);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900532
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900533 same_ns:
Mike Yubfb1b342018-11-06 15:42:36 +0800534 // TODO: Since we expect there is only one DNS server being queried here while this
535 // function tries to query all of private DNS servers. Consider moving it to other
536 // reasonable place. In addition, maybe add stats for private DNS.
537 if (!statp->use_local_nameserver) {
538 bool fallback = false;
539 resplen = res_tls_send(statp, Slice(const_cast<u_char*>(buf), buflen),
540 Slice(ans, anssiz), rcode, &fallback);
541 if (resplen > 0) {
542 if (cache_status == RESOLV_CACHE_NOTFOUND) {
543 _resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
544 }
545 return resplen;
Mike Yub601ff72018-11-01 20:07:00 +0800546 }
Mike Yubfb1b342018-11-06 15:42:36 +0800547 if (!fallback) {
Luke Huangba7bef92018-12-26 16:53:03 +0800548 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800549 res_nclose(statp);
550 return -terrno;
Mike Yubfb1b342018-11-06 15:42:36 +0800551 }
552 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900553
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900554 [[maybe_unused]] static const int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
555 [[maybe_unused]] char abuf[NI_MAXHOST];
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900556 Dprint(((statp->options & RES_DEBUG) &&
557 getnameinfo(nsap, (socklen_t) nsaplen, abuf, sizeof(abuf), NULL, 0, niflags) ==
558 0),
559 (stdout, ";; Querying server (# %d) address = %s\n", ns + 1, abuf));
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900560
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900561 if (v_circuit) {
562 /* Use VC; at most one attempt per server. */
Luke Huangba7bef92018-12-26 16:53:03 +0800563 bool shouldRecordStats = (attempt == 0);
564 attempt = retryTimes;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900565
Mike Yubfb1b342018-11-06 15:42:36 +0800566 n = send_vc(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &now, rcode,
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900567 &delay);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900568
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900569 /*
570 * Only record stats the first time we try a query. This ensures that
571 * queries that deterministically fail (e.g., a name that always returns
572 * SERVFAIL or times out) do not unduly affect the stats.
573 */
Luke Huangba7bef92018-12-26 16:53:03 +0800574 if (shouldRecordStats) {
Bernie Innocentiac18b122018-10-01 23:10:18 +0900575 res_sample sample;
Mike Yubfb1b342018-11-06 15:42:36 +0800576 _res_stats_set_sample(&sample, now, *rcode, delay);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900577 _resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, ns, &sample,
578 params.max_samples);
579 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900580
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900581 VLOG << "used send_vc " << n;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900582
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800583 if (n < 0) {
Luke Huangba7bef92018-12-26 16:53:03 +0800584 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800585 res_nclose(statp);
586 return -terrno;
587 };
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900588 if (n == 0) goto next_ns;
589 resplen = n;
590 } else {
591 /* Use datagrams. */
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900592 VLOG << "using send_dg";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900593
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900594 n = send_dg(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &v_circuit,
Mike Yubfb1b342018-11-06 15:42:36 +0800595 &gotsomewhere, &now, rcode, &delay);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900596
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900597 /* Only record stats the first time we try a query. See above. */
Bernie Innocenti9c575932018-09-07 21:10:25 +0900598 if (attempt == 0) {
Bernie Innocentiac18b122018-10-01 23:10:18 +0900599 res_sample sample;
Mike Yubfb1b342018-11-06 15:42:36 +0800600 _res_stats_set_sample(&sample, now, *rcode, delay);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900601 _resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, ns, &sample,
602 params.max_samples);
603 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900604
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900605 VLOG << "used send_dg " << n;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900606
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800607 if (n < 0) {
Luke Huangba7bef92018-12-26 16:53:03 +0800608 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800609 res_nclose(statp);
610 return -terrno;
611 };
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900612 if (n == 0) goto next_ns;
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900613 VLOG << "time=" << time(NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900614 if (v_circuit) goto same_ns;
615 resplen = n;
616 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900617
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900618 Dprint((statp->options & RES_DEBUG) ||
619 ((statp->pfcode & RES_PRF_REPLY) && (statp->pfcode & RES_PRF_HEAD1)),
620 (stdout, ";; got answer:\n"));
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900621
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900622 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
623 (stdout, "%s", ""), ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900624
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900625 if (cache_status == RESOLV_CACHE_NOTFOUND) {
626 _resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
627 }
628 /*
629 * If we have temporarily opened a virtual circuit,
630 * or if we haven't been asked to keep a socket open,
631 * close the socket.
632 */
633 if ((v_circuit && (statp->options & RES_USEVC) == 0U) ||
634 (statp->options & RES_STAYOPEN) == 0U) {
635 res_nclose(statp);
636 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900637 return (resplen);
638 next_ns:;
Bernie Innocenti9c575932018-09-07 21:10:25 +0900639 } // for each ns
640 } // for each retry
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900641 res_nclose(statp);
642 if (!v_circuit) {
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800643 if (!gotsomewhere) {
644 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900645 errno = ECONNREFUSED; /* no nameservers found */
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800646 terrno = ECONNREFUSED;
647 } else {
648 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900649 errno = ETIMEDOUT; /* no answer obtained */
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800650 terrno = ETIMEDOUT;
651 }
652 } else {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900653 errno = terrno;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800654 }
Luke Huangba7bef92018-12-26 16:53:03 +0800655 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900656
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800657 return -terrno;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900658}
659
660/* Private */
661
Bernie Innocenti9c575932018-09-07 21:10:25 +0900662static int get_salen(const struct sockaddr* sa) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900663 if (sa->sa_family == AF_INET)
664 return (sizeof(struct sockaddr_in));
665 else if (sa->sa_family == AF_INET6)
666 return (sizeof(struct sockaddr_in6));
667 else
668 return (0); /* unknown, die on connect */
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900669}
670
671/*
672 * pick appropriate nsaddr_list for use. see res_init() for initialization.
673 */
Bernie Innocenti9c575932018-09-07 21:10:25 +0900674static struct sockaddr* get_nsaddr(res_state statp, size_t n) {
Ken Chene6fa86e2018-10-16 23:12:09 +0800675 if (!statp->nsaddr_list[n].sin_family && statp->_u._ext.ext) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900676 /*
Ken Chene6fa86e2018-10-16 23:12:09 +0800677 * - statp->_u._ext.ext->nsaddrs[n] holds an address that is larger
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900678 * than struct sockaddr, and
679 * - user code did not update statp->nsaddr_list[n].
680 */
Ken Chene6fa86e2018-10-16 23:12:09 +0800681 return (struct sockaddr*) (void*) &statp->_u._ext.ext->nsaddrs[n];
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900682 } else {
683 /*
684 * - user code updated statp->nsaddr_list[n], or
685 * - statp->nsaddr_list[n] has the same content as
Ken Chene6fa86e2018-10-16 23:12:09 +0800686 * statp->_u._ext.ext->nsaddrs[n].
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900687 */
688 return (struct sockaddr*) (void*) &statp->nsaddr_list[n];
689 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900690}
691
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900692static struct timespec get_timeout(const res_state statp, const struct __res_params* params,
693 const int ns) {
694 int msec;
695 if (params->base_timeout_msec != 0) {
696 // TODO: scale the timeout by retry attempt and maybe number of servers
697 msec = params->base_timeout_msec;
698 } else {
699 // Legacy algorithm which scales the timeout by nameserver number.
700 // For instance, with 4 nameservers: 5s, 2.5s, 5s, 10s
701 // This has no effect with 1 or 2 nameservers
702 msec = (statp->retrans * 1000) << ns;
703 if (ns > 0) {
704 msec /= statp->nscount;
705 }
706 if (msec < 1000) {
707 msec = 1000; // Use at least 100ms
708 }
709 }
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900710 VLOG << "using timeout of " << msec << " msec";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900711
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900712 struct timespec result;
713 result.tv_sec = msec / 1000;
714 result.tv_nsec = (msec % 1000) * 1000000;
715 return result;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900716}
717
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900718static int send_vc(res_state statp, struct __res_params* params, const u_char* buf, int buflen,
719 u_char* ans, int anssiz, int* terrno, int ns, time_t* at, int* rcode,
720 int* delay) {
721 *at = time(NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900722 *delay = 0;
723 const HEADER* hp = (const HEADER*) (const void*) buf;
724 HEADER* anhp = (HEADER*) (void*) ans;
725 struct sockaddr* nsap;
726 int nsaplen;
727 int truncating, connreset, resplen, n;
728 struct iovec iov[2];
729 u_short len;
730 u_char* cp;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900731
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900732 VLOG << "using send_vc";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900733
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900734 nsap = get_nsaddr(statp, (size_t) ns);
735 nsaplen = get_salen(nsap);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900736
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900737 connreset = 0;
738same_ns:
739 truncating = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900740
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900741 struct timespec now = evNowTime();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900742
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900743 /* Are we still talking to whom we want to talk to? */
744 if (statp->_vcsock >= 0 && (statp->_flags & RES_F_VC) != 0) {
745 struct sockaddr_storage peer;
746 socklen_t size = sizeof peer;
747 unsigned old_mark;
748 socklen_t mark_size = sizeof(old_mark);
749 if (getpeername(statp->_vcsock, (struct sockaddr*) (void*) &peer, &size) < 0 ||
750 !sock_eq((struct sockaddr*) (void*) &peer, nsap) ||
751 getsockopt(statp->_vcsock, SOL_SOCKET, SO_MARK, &old_mark, &mark_size) < 0 ||
752 old_mark != statp->_mark) {
753 res_nclose(statp);
754 statp->_flags &= ~RES_F_VC;
755 }
756 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900757
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900758 if (statp->_vcsock < 0 || (statp->_flags & RES_F_VC) == 0) {
759 if (statp->_vcsock >= 0) res_nclose(statp);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900760
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900761 statp->_vcsock = socket(nsap->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0);
762 if (statp->_vcsock < 0) {
763 switch (errno) {
764 case EPROTONOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900765 case EPFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900766 case EAFNOSUPPORT:
767 Perror(statp, stderr, "socket(vc)", errno);
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900768 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900769 default:
770 *terrno = errno;
771 Perror(statp, stderr, "socket(vc)", errno);
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900772 return -1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900773 }
774 }
775 fchown(statp->_vcsock, AID_DNS, -1);
776 if (statp->_mark != MARK_UNSET) {
777 if (setsockopt(statp->_vcsock, SOL_SOCKET, SO_MARK, &statp->_mark,
778 sizeof(statp->_mark)) < 0) {
779 *terrno = errno;
780 Perror(statp, stderr, "setsockopt", errno);
781 return -1;
782 }
783 }
784 errno = 0;
785 if (random_bind(statp->_vcsock, nsap->sa_family) < 0) {
786 *terrno = errno;
787 Aerror(statp, stderr, "bind/vc", errno, nsap, nsaplen);
788 res_nclose(statp);
789 return (0);
790 }
791 if (connect_with_timeout(statp->_vcsock, nsap, (socklen_t) nsaplen,
792 get_timeout(statp, params, ns)) < 0) {
793 *terrno = errno;
794 Aerror(statp, stderr, "connect/vc", errno, nsap, nsaplen);
795 res_nclose(statp);
796 /*
797 * The way connect_with_timeout() is implemented prevents us from reliably
798 * determining whether this was really a timeout or e.g. ECONNREFUSED. Since
799 * currently both cases are handled in the same way, there is no need to
800 * change this (yet). If we ever need to reliably distinguish between these
801 * cases, both connect_with_timeout() and retrying_poll() need to be
802 * modified, though.
803 */
804 *rcode = RCODE_TIMEOUT;
805 return (0);
806 }
807 statp->_flags |= RES_F_VC;
808 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900809
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900810 /*
811 * Send length & message
812 */
813 ns_put16((u_short) buflen, (u_char*) (void*) &len);
814 iov[0] = evConsIovec(&len, INT16SZ);
Bernie Innocenti9c575932018-09-07 21:10:25 +0900815 iov[1] = evConsIovec((void*) buf, (size_t) buflen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900816 if (writev(statp->_vcsock, iov, 2) != (INT16SZ + buflen)) {
817 *terrno = errno;
818 Perror(statp, stderr, "write failed", errno);
819 res_nclose(statp);
820 return (0);
821 }
822 /*
823 * Receive length & response
824 */
825read_len:
826 cp = ans;
827 len = INT16SZ;
828 while ((n = read(statp->_vcsock, (char*) cp, (size_t) len)) > 0) {
829 cp += n;
830 if ((len -= n) == 0) break;
831 }
832 if (n <= 0) {
833 *terrno = errno;
834 Perror(statp, stderr, "read failed", errno);
835 res_nclose(statp);
836 /*
837 * A long running process might get its TCP
838 * connection reset if the remote server was
839 * restarted. Requery the server instead of
840 * trying a new one. When there is only one
841 * server, this means that a query might work
842 * instead of failing. We only allow one reset
843 * per query to prevent looping.
844 */
845 if (*terrno == ECONNRESET && !connreset) {
846 connreset = 1;
847 res_nclose(statp);
848 goto same_ns;
849 }
850 res_nclose(statp);
851 return (0);
852 }
853 resplen = ns_get16(ans);
854 if (resplen > anssiz) {
855 Dprint(statp->options & RES_DEBUG, (stdout, ";; response truncated\n"));
856 truncating = 1;
857 len = anssiz;
858 } else
859 len = resplen;
860 if (len < HFIXEDSZ) {
861 /*
862 * Undersized message.
863 */
864 Dprint(statp->options & RES_DEBUG, (stdout, ";; undersized: %d\n", len));
865 *terrno = EMSGSIZE;
866 res_nclose(statp);
867 return (0);
868 }
869 cp = ans;
870 while (len != 0 && (n = read(statp->_vcsock, (char*) cp, (size_t) len)) > 0) {
871 cp += n;
872 len -= n;
873 }
874 if (n <= 0) {
875 *terrno = errno;
876 Perror(statp, stderr, "read(vc)", errno);
877 res_nclose(statp);
878 return (0);
879 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900880
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900881 if (truncating) {
882 /*
883 * Flush rest of answer so connection stays in synch.
884 */
885 anhp->tc = 1;
886 len = resplen - anssiz;
887 while (len != 0) {
888 char junk[PACKETSZ];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900889
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900890 n = read(statp->_vcsock, junk, (len > sizeof junk) ? sizeof junk : len);
891 if (n > 0)
892 len -= n;
893 else
894 break;
895 }
896 }
897 /*
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900898 * If the calling application has bailed out of
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900899 * a previous call and failed to arrange to have
900 * the circuit closed or the server has got
901 * itself confused, then drop the packet and
902 * wait for the correct one.
903 */
904 if (hp->id != anhp->id) {
905 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
906 (stdout, ";; old answer (unexpected):\n"), ans,
907 (resplen > anssiz) ? anssiz : resplen);
908 goto read_len;
909 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900910
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900911 /*
912 * All is well, or the error is fatal. Signal that the
913 * next nameserver ought not be tried.
914 */
915 if (resplen > 0) {
916 struct timespec done = evNowTime();
917 *delay = _res_stats_calculate_rtt(&done, &now);
918 *rcode = anhp->rcode;
919 }
920 return (resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900921}
922
923/* return -1 on error (errno set), 0 on success */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900924static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
925 const struct timespec timeout) {
926 int res, origflags;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900927
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900928 origflags = fcntl(sock, F_GETFL, 0);
929 fcntl(sock, F_SETFL, origflags | O_NONBLOCK);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900930
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900931 res = connect(sock, nsap, salen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900932 if (res < 0 && errno != EINPROGRESS) {
933 res = -1;
934 goto done;
935 }
936 if (res != 0) {
937 struct timespec now = evNowTime();
938 struct timespec finish = evAddTime(now, timeout);
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900939 VLOG << sock << " send_vc";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900940 res = retrying_poll(sock, POLLIN | POLLOUT, &finish);
941 if (res <= 0) {
942 res = -1;
943 }
944 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900945done:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900946 fcntl(sock, F_SETFL, origflags);
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900947 VLOG << sock << " connect_with_const timeout returning " << res;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900948 return res;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900949}
950
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900951static int retrying_poll(const int sock, const short events, const struct timespec* finish) {
952 struct timespec now, timeout;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900953
954retry:
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900955 VLOG << " " << sock << " retrying_poll";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900956
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900957 now = evNowTime();
958 if (evCmpTime(*finish, now) > 0)
959 timeout = evSubTime(*finish, now);
960 else
961 timeout = evConsTime(0L, 0L);
962 struct pollfd fds = {.fd = sock, .events = events};
963 int n = ppoll(&fds, 1, &timeout, /*sigmask=*/NULL);
964 if (n == 0) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900965 VLOG << " " << sock << "retrying_poll timeout";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900966 errno = ETIMEDOUT;
967 return 0;
968 }
969 if (n < 0) {
970 if (errno == EINTR) goto retry;
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900971 VLOG << " " << sock << " retrying_poll got error " << n;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900972 return n;
973 }
974 if (fds.revents & (POLLIN | POLLOUT | POLLERR)) {
975 int error;
976 socklen_t len = sizeof(error);
977 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error) {
978 errno = error;
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900979 VLOG << " " << sock << " retrying_poll dot error2 " << errno;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900980 return -1;
981 }
982 }
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900983 VLOG << " " << sock << " retrying_poll returning " << n;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900984 return n;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900985}
986
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900987static int send_dg(res_state statp, struct __res_params* params, const u_char* buf, int buflen,
988 u_char* ans, int anssiz, int* terrno, int ns, int* v_circuit, int* gotsomewhere,
989 time_t* at, int* rcode, int* delay) {
990 *at = time(NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900991 *delay = 0;
992 const HEADER* hp = (const HEADER*) (const void*) buf;
993 HEADER* anhp = (HEADER*) (void*) ans;
994 const struct sockaddr* nsap;
995 int nsaplen;
996 struct timespec now, timeout, finish, done;
997 struct sockaddr_storage from;
998 socklen_t fromlen;
999 int resplen, n, s;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001000
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001001 nsap = get_nsaddr(statp, (size_t) ns);
1002 nsaplen = get_salen(nsap);
Ken Chene6fa86e2018-10-16 23:12:09 +08001003 if (statp->_u._ext.nssocks[ns] == -1) {
1004 statp->_u._ext.nssocks[ns] = socket(nsap->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
1005 if (statp->_u._ext.nssocks[ns] < 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001006 switch (errno) {
1007 case EPROTONOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001008 case EPFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001009 case EAFNOSUPPORT:
1010 Perror(statp, stderr, "socket(dg)", errno);
1011 return (0);
1012 default:
1013 *terrno = errno;
1014 Perror(statp, stderr, "socket(dg)", errno);
1015 return (-1);
1016 }
1017 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001018
Ken Chene6fa86e2018-10-16 23:12:09 +08001019 fchown(statp->_u._ext.nssocks[ns], AID_DNS, -1);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001020 if (statp->_mark != MARK_UNSET) {
Ken Chene6fa86e2018-10-16 23:12:09 +08001021 if (setsockopt(statp->_u._ext.nssocks[ns], SOL_SOCKET, SO_MARK, &(statp->_mark),
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001022 sizeof(statp->_mark)) < 0) {
1023 res_nclose(statp);
1024 return -1;
1025 }
1026 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001027#ifndef CANNOT_CONNECT_DGRAM
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001028 /*
1029 * On a 4.3BSD+ machine (client and server,
1030 * actually), sending to a nameserver datagram
1031 * port with no nameserver will cause an
1032 * ICMP port unreachable message to be returned.
1033 * If our datagram socket is "connected" to the
1034 * server, we get an ECONNREFUSED error on the next
1035 * socket operation, and select returns if the
1036 * error message is received. We can thus detect
1037 * the absence of a nameserver without timing out.
1038 */
Ken Chene6fa86e2018-10-16 23:12:09 +08001039 if (random_bind(statp->_u._ext.nssocks[ns], nsap->sa_family) < 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001040 Aerror(statp, stderr, "bind(dg)", errno, nsap, nsaplen);
1041 res_nclose(statp);
1042 return (0);
1043 }
Ken Chene6fa86e2018-10-16 23:12:09 +08001044 if (connect(statp->_u._ext.nssocks[ns], nsap, (socklen_t) nsaplen) < 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001045 Aerror(statp, stderr, "connect(dg)", errno, nsap, nsaplen);
1046 res_nclose(statp);
1047 return (0);
1048 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001049#endif /* !CANNOT_CONNECT_DGRAM */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001050 Dprint(statp->options & RES_DEBUG, (stdout, ";; new DG socket\n"))
1051 }
Ken Chene6fa86e2018-10-16 23:12:09 +08001052 s = statp->_u._ext.nssocks[ns];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001053#ifndef CANNOT_CONNECT_DGRAM
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001054 if (send(s, (const char*) buf, (size_t) buflen, 0) != buflen) {
1055 Perror(statp, stderr, "send", errno);
1056 res_nclose(statp);
1057 return (0);
1058 }
1059#else /* !CANNOT_CONNECT_DGRAM */
1060 if (sendto(s, (const char*) buf, buflen, 0, nsap, nsaplen) != buflen) {
1061 Aerror(statp, stderr, "sendto", errno, nsap, nsaplen);
1062 res_nclose(statp);
1063 return (0);
1064 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001065#endif /* !CANNOT_CONNECT_DGRAM */
1066
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001067 /*
1068 * Wait for reply.
1069 */
1070 timeout = get_timeout(statp, params, ns);
1071 now = evNowTime();
1072 finish = evAddTime(now, timeout);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001073retry:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001074 n = retrying_poll(s, POLLIN, &finish);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001075
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001076 if (n == 0) {
1077 *rcode = RCODE_TIMEOUT;
1078 Dprint(statp->options & RES_DEBUG, (stdout, ";; timeout\n"));
1079 *gotsomewhere = 1;
1080 return (0);
1081 }
1082 if (n < 0) {
1083 Perror(statp, stderr, "poll", errno);
1084 res_nclose(statp);
1085 return (0);
1086 }
1087 errno = 0;
1088 fromlen = sizeof(from);
1089 resplen = recvfrom(s, (char*) ans, (size_t) anssiz, 0, (struct sockaddr*) (void*) &from,
1090 &fromlen);
1091 if (resplen <= 0) {
1092 Perror(statp, stderr, "recvfrom", errno);
1093 res_nclose(statp);
1094 return (0);
1095 }
1096 *gotsomewhere = 1;
1097 if (resplen < HFIXEDSZ) {
1098 /*
1099 * Undersized message.
1100 */
1101 Dprint(statp->options & RES_DEBUG, (stdout, ";; undersized: %d\n", resplen));
1102 *terrno = EMSGSIZE;
1103 res_nclose(statp);
1104 return (0);
1105 }
1106 if (hp->id != anhp->id) {
1107 /*
1108 * response from old query, ignore it.
1109 * XXX - potential security hazard could
1110 * be detected here.
1111 */
1112 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
1113 (stdout, ";; old answer:\n"), ans, (resplen > anssiz) ? anssiz : resplen);
1114 goto retry;
1115 }
1116 if (!(statp->options & RES_INSECURE1) &&
1117 !res_ourserver_p(statp, (struct sockaddr*) (void*) &from)) {
1118 /*
1119 * response from wrong server? ignore it.
1120 * XXX - potential security hazard could
1121 * be detected here.
1122 */
1123 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
1124 (stdout, ";; not our server:\n"), ans, (resplen > anssiz) ? anssiz : resplen);
1125 goto retry;
1126 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001127 if (anhp->rcode == FORMERR && (statp->options & RES_USE_EDNS0) != 0U) {
1128 /*
1129 * Do not retry if the server do not understand EDNS0.
1130 * The case has to be captured here, as FORMERR packet do not
1131 * carry query section, hence res_queriesmatch() returns 0.
1132 */
1133 DprintQ(statp->options & RES_DEBUG, (stdout, "server rejected query with EDNS0:\n"), ans,
1134 (resplen > anssiz) ? anssiz : resplen);
1135 /* record the error */
1136 statp->_flags |= RES_F_EDNS0ERR;
1137 res_nclose(statp);
1138 return (0);
1139 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001140 if (!(statp->options & RES_INSECURE2) &&
1141 !res_queriesmatch(buf, buf + buflen, ans, ans + anssiz)) {
1142 /*
1143 * response contains wrong query? ignore it.
1144 * XXX - potential security hazard could
1145 * be detected here.
1146 */
1147 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
1148 (stdout, ";; wrong query name:\n"), ans, (resplen > anssiz) ? anssiz : resplen);
1149 goto retry;
1150 ;
1151 }
1152 done = evNowTime();
1153 *delay = _res_stats_calculate_rtt(&done, &now);
1154 if (anhp->rcode == SERVFAIL || anhp->rcode == NOTIMP || anhp->rcode == REFUSED) {
1155 DprintQ(statp->options & RES_DEBUG, (stdout, "server rejected query:\n"), ans,
1156 (resplen > anssiz) ? anssiz : resplen);
1157 res_nclose(statp);
1158 /* don't retry if called from dig */
1159 if (!statp->pfcode) {
1160 *rcode = anhp->rcode;
1161 return (0);
1162 }
1163 }
1164 if (!(statp->options & RES_IGNTC) && anhp->tc) {
1165 /*
1166 * To get the rest of answer,
1167 * use TCP with same server.
1168 */
1169 Dprint(statp->options & RES_DEBUG, (stdout, ";; truncated answer\n"));
1170 *v_circuit = 1;
1171 res_nclose(statp);
1172 return (1);
1173 }
1174 /*
1175 * All is well, or the error is fatal. Signal that the
1176 * next nameserver ought not be tried.
1177 */
1178 if (resplen > 0) {
1179 *rcode = anhp->rcode;
1180 }
1181 return (resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001182}
1183
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001184static void Aerror(const res_state statp, FILE* file, const char* string, int error,
1185 const struct sockaddr* address, int alen) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001186 if (!kVerboseLogging) return;
1187
1188 const int save = errno;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001189 char hbuf[NI_MAXHOST];
1190 char sbuf[NI_MAXSERV];
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001191 constexpr int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001192
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001193 if ((statp->options & RES_DEBUG) != 0U) {
1194 if (getnameinfo(address, (socklen_t) alen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
1195 niflags)) {
1196 strncpy(hbuf, "?", sizeof(hbuf) - 1);
1197 hbuf[sizeof(hbuf) - 1] = '\0';
1198 strncpy(sbuf, "?", sizeof(sbuf) - 1);
1199 sbuf[sizeof(sbuf) - 1] = '\0';
1200 }
1201 fprintf(file, "res_send: %s ([%s].%s): %s\n", string, hbuf, sbuf, strerror(error));
1202 }
1203 errno = save;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001204}
1205
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001206static void Perror(const res_state statp, FILE* file, const char* string, int error) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001207 if (!kVerboseLogging) return;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001208
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001209 const int save = errno;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001210 if ((statp->options & RES_DEBUG) != 0U)
1211 fprintf(file, "res_send: %s: %s\n", string, strerror(error));
1212 errno = save;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001213}
1214
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001215static int sock_eq(struct sockaddr* a, struct sockaddr* b) {
1216 struct sockaddr_in *a4, *b4;
1217 struct sockaddr_in6 *a6, *b6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001218
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001219 if (a->sa_family != b->sa_family) return 0;
1220 switch (a->sa_family) {
1221 case AF_INET:
1222 a4 = (struct sockaddr_in*) (void*) a;
1223 b4 = (struct sockaddr_in*) (void*) b;
1224 return a4->sin_port == b4->sin_port && a4->sin_addr.s_addr == b4->sin_addr.s_addr;
1225 case AF_INET6:
1226 a6 = (struct sockaddr_in6*) (void*) a;
1227 b6 = (struct sockaddr_in6*) (void*) b;
1228 return a6->sin6_port == b6->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001229#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001230 a6->sin6_scope_id == b6->sin6_scope_id &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001231#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001232 IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
1233 default:
1234 return 0;
1235 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001236}
Mike Yub601ff72018-11-01 20:07:00 +08001237
Luke Huangd7aa7b42018-11-21 20:37:50 +08001238static int res_tls_send(res_state statp, const Slice query, const Slice answer, int* rcode,
Mike Yubfb1b342018-11-06 15:42:36 +08001239 bool* fallback) {
1240 int resplen = 0;
Mike Yub601ff72018-11-01 20:07:00 +08001241 const unsigned netId = statp->netid;
1242 const unsigned mark = statp->_mark;
1243
Mike Yubfb1b342018-11-06 15:42:36 +08001244 PrivateDnsStatus privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
1245
1246 if (privateDnsStatus.mode == PrivateDnsMode::OFF) {
1247 *fallback = true;
1248 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001249 }
1250
Mike Yub601ff72018-11-01 20:07:00 +08001251 if (privateDnsStatus.validatedServers.empty()) {
1252 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
Mike Yubfb1b342018-11-06 15:42:36 +08001253 *fallback = true;
1254 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001255 } else {
1256 // Sleep and iterate some small number of times checking for the
1257 // arrival of resolved and validated server IP addresses, instead
1258 // of returning an immediate error.
Mike Yu4f3747b2018-12-02 17:54:29 +09001259 // This is needed because as soon as a network becomes the default network, apps will
1260 // send DNS queries on that network. If no servers have yet validated, and we do not
1261 // block those queries, they would immediately fail, causing application-visible errors.
1262 // Note that this can happen even before the network validates, since an unvalidated
1263 // network can become the default network if no validated networks are available.
1264 //
1265 // TODO: see if there is a better way to address this problem, such as buffering the
1266 // queries in a queue or only blocking queries for the first few seconds after a default
1267 // network change.
Mike Yubfb1b342018-11-06 15:42:36 +08001268 for (int i = 0; i < 42; i++) {
1269 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1270 if (!gPrivateDnsConfiguration.getStatus(netId).validatedServers.empty()) {
1271 privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
1272 break;
1273 }
1274 }
1275 if (privateDnsStatus.validatedServers.empty()) {
1276 return -1;
1277 }
Mike Yub601ff72018-11-01 20:07:00 +08001278 }
1279 }
1280
1281 VLOG << __func__ << ": performing query over TLS";
1282
1283 const auto response = sDnsTlsDispatcher.query(privateDnsStatus.validatedServers, mark, query,
Mike Yubfb1b342018-11-06 15:42:36 +08001284 answer, &resplen);
Mike Yub601ff72018-11-01 20:07:00 +08001285
Mike Yubfb1b342018-11-06 15:42:36 +08001286 VLOG << __func__ << ": TLS query result: " << static_cast<int>(response);
Mike Yub601ff72018-11-01 20:07:00 +08001287
1288 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
1289 // In opportunistic mode, handle falling back to cleartext in some
1290 // cases (DNS shouldn't fail if a validated opportunistic mode server
1291 // becomes unreachable for some reason).
1292 switch (response) {
Mike Yubfb1b342018-11-06 15:42:36 +08001293 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001294 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001295 return resplen;
Mike Yub601ff72018-11-01 20:07:00 +08001296 case DnsTlsTransport::Response::network_error:
Mike Yubfb1b342018-11-06 15:42:36 +08001297 // No need to set the error timeout here since it will fallback to UDP.
Mike Yub601ff72018-11-01 20:07:00 +08001298 case DnsTlsTransport::Response::internal_error:
1299 // Note: this will cause cleartext queries to be emitted, with
1300 // all of the EDNS0 goodness enabled. Fingers crossed. :-/
Mike Yubfb1b342018-11-06 15:42:36 +08001301 *fallback = true;
1302 [[fallthrough]];
Mike Yub601ff72018-11-01 20:07:00 +08001303 default:
Mike Yubfb1b342018-11-06 15:42:36 +08001304 return -1;
1305 }
1306 } else {
1307 // Strict mode
1308 switch (response) {
1309 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001310 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001311 return resplen;
1312 case DnsTlsTransport::Response::network_error:
1313 // This case happens when the query stored in DnsTlsTransport is expired since
1314 // either 1) the query has been tried for 3 times but no response or 2) fail to
1315 // establish the connection with the server.
Luke Huangd7aa7b42018-11-21 20:37:50 +08001316 *rcode = RCODE_TIMEOUT;
Mike Yubfb1b342018-11-06 15:42:36 +08001317 [[fallthrough]];
1318 default:
1319 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001320 }
1321 }
Mike Yub601ff72018-11-01 20:07:00 +08001322}
Luke Huang4973a0d2018-11-19 20:17:26 +08001323
Luke Huangba7bef92018-12-26 16:53:03 +08001324int resolv_res_nsend(const android_net_context* netContext, const uint8_t* msg, int msgLen,
1325 uint8_t* ans, int ansLen, int* rcode, uint32_t flags) {
Luke Huang4973a0d2018-11-19 20:17:26 +08001326 res_state res = res_get_state();
1327 res_setnetcontext(res, netContext);
1328 _resolv_populate_res_for_net(res);
1329 *rcode = NOERROR;
Luke Huangba7bef92018-12-26 16:53:03 +08001330 return res_nsend(res, msg, msgLen, ans, ansLen, rcode, flags);
Bernie Innocentiec4219b2019-01-30 11:16:36 +09001331}