blob: f86e5f6249abce14b6c8640334da636f0d07fb35 [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
Ken Chen5471dca2019-04-15 15:25:35 +080077#define LOG_TAG "resolv"
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +090078
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090079#include <sys/param.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090080#include <sys/socket.h>
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090081#include <sys/time.h>
82#include <sys/types.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090083#include <sys/uio.h>
84
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090085#include <arpa/inet.h>
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090086#include <arpa/nameser.h>
87#include <netinet/in.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090088
89#include <errno.h>
90#include <fcntl.h>
91#include <netdb.h>
92#include <poll.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090093#include <signal.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090094#include <stdlib.h>
95#include <string.h>
96#include <time.h>
97#include <unistd.h>
98
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +090099#include <android-base/logging.h>
Bernie Innocenti758005f2019-02-19 18:08:36 +0900100#include <android/multinetwork.h> // ResNsendFlags
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900101
Mike Yub601ff72018-11-01 20:07:00 +0800102#include <netdutils/Slice.h>
lifr94981782019-05-17 21:15:19 +0800103#include <netdutils/Stopwatch.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"
lifr94981782019-05-17 21:15:19 +0800113#include "stats.pb.h"
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900114
Mike Yub601ff72018-11-01 20:07:00 +0800115// TODO: use the namespace something like android::netd_resolv for libnetd_resolv
116using namespace android::net;
lifr94981782019-05-17 21:15:19 +0800117using android::net::NetworkDnsEventReported;
Bernie Innocentiec4219b2019-01-30 11:16:36 +0900118using android::netdutils::Slice;
lifr94981782019-05-17 21:15:19 +0800119using android::netdutils::Stopwatch;
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900120
Mike Yub601ff72018-11-01 20:07:00 +0800121static DnsTlsDispatcher sDnsTlsDispatcher;
122
Bernie Innocenti9c575932018-09-07 21:10:25 +0900123static int get_salen(const struct sockaddr*);
124static struct sockaddr* get_nsaddr(res_state, size_t);
Bernie Innocenti758005f2019-02-19 18:08:36 +0900125static int send_vc(res_state, res_params* params, const u_char*, int, u_char*, int, int*, int,
126 time_t*, int*, int*);
127static int send_dg(res_state, res_params* params, const u_char*, int, u_char*, int, int*, int, int*,
128 int*, time_t*, int*, int*);
chenbruce018fdb22019-06-12 18:08:04 +0800129static void dump_error(const char*, const struct sockaddr*, int);
chenbruceacb832c2019-02-20 19:45:50 +0800130
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900131static int sock_eq(struct sockaddr*, struct sockaddr*);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900132static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
133 const struct timespec timeout);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900134static int retrying_poll(const int sock, short events, const struct timespec* finish);
Luke Huangd7aa7b42018-11-21 20:37:50 +0800135static int res_tls_send(res_state, const Slice query, const Slice answer, int* rcode,
Mike Yubfb1b342018-11-06 15:42:36 +0800136 bool* fallback);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900137
lifr94981782019-05-17 21:15:19 +0800138NsType getQueryType(const uint8_t* msg, size_t msgLen) {
139 ns_msg handle;
140 ns_rr rr;
141 if (ns_initparse((const uint8_t*)msg, msgLen, &handle) < 0 ||
142 ns_parserr(&handle, ns_s_qd, 0, &rr) < 0) {
143 return NS_T_INVALID;
144 }
145 return static_cast<NsType>(ns_rr_type(rr));
146}
147
148IpVersion ipFamilyToIPVersion(const int ipFamily) {
149 switch (ipFamily) {
150 case AF_INET:
151 return IV_IPV4;
152 case AF_INET6:
153 return IV_IPV6;
154 default:
155 return IV_UNKNOWN;
156 }
157}
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900158
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900159// BEGIN: Code copied from ISC eventlib
160// TODO: move away from this code
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900161#define BILLION 1000000000
162
163static struct timespec evConsTime(time_t sec, long nsec) {
164 struct timespec x;
165
166 x.tv_sec = sec;
167 x.tv_nsec = nsec;
168 return (x);
169}
170
171static struct timespec evAddTime(struct timespec addend1, struct timespec addend2) {
172 struct timespec x;
173
174 x.tv_sec = addend1.tv_sec + addend2.tv_sec;
175 x.tv_nsec = addend1.tv_nsec + addend2.tv_nsec;
176 if (x.tv_nsec >= BILLION) {
177 x.tv_sec++;
178 x.tv_nsec -= BILLION;
179 }
180 return (x);
181}
182
183static struct timespec evSubTime(struct timespec minuend, struct timespec subtrahend) {
184 struct timespec x;
185
186 x.tv_sec = minuend.tv_sec - subtrahend.tv_sec;
187 if (minuend.tv_nsec >= subtrahend.tv_nsec)
188 x.tv_nsec = minuend.tv_nsec - subtrahend.tv_nsec;
189 else {
190 x.tv_nsec = BILLION - subtrahend.tv_nsec + minuend.tv_nsec;
191 x.tv_sec--;
192 }
193 return (x);
194}
195
196static int evCmpTime(struct timespec a, struct timespec b) {
197#define SGN(x) ((x) < 0 ? (-1) : (x) > 0 ? (1) : (0));
198 time_t s = a.tv_sec - b.tv_sec;
199 long n;
200
201 if (s != 0) return SGN(s);
202
203 n = a.tv_nsec - b.tv_nsec;
204 return SGN(n);
205}
206
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900207static struct timespec evNowTime(void) {
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900208 struct timespec tsnow;
Bernie Innocentic1834822018-08-31 16:11:41 +0900209 clock_gettime(CLOCK_REALTIME, &tsnow);
210 return tsnow;
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900211}
212
213static struct iovec evConsIovec(void* buf, size_t cnt) {
214 struct iovec ret;
215
216 memset(&ret, 0xf5, sizeof ret);
217 ret.iov_base = buf;
218 ret.iov_len = cnt;
Bernie Innocentic1834822018-08-31 16:11:41 +0900219 return ret;
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900220}
221
222// END: Code copied from ISC eventlib
223
lifr94981782019-05-17 21:15:19 +0800224/* BIONIC-BEGIN: implement source port randomization */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900225static int random_bind(int s, int family) {
nuccachenb980f2f2018-10-23 17:10:58 +0800226 sockaddr_union u;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900227 int j;
228 socklen_t slen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900229
230 /* clear all, this also sets the IP4/6 address to 'any' */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900231 memset(&u, 0, sizeof u);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900232
233 switch (family) {
234 case AF_INET:
235 u.sin.sin_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900236 slen = sizeof u.sin;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900237 break;
238 case AF_INET6:
239 u.sin6.sin6_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900240 slen = sizeof u.sin6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900241 break;
242 default:
243 errno = EPROTO;
244 return -1;
245 }
246
247 /* first try to bind to a random source port a few times */
248 for (j = 0; j < 10; j++) {
249 /* find a random port between 1025 .. 65534 */
Luke Huangdda920f2019-02-13 14:05:02 +0800250 int port = 1025 + (arc4random_uniform(65535 - 1025));
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900251 if (family == AF_INET)
252 u.sin.sin_port = htons(port);
253 else
254 u.sin6.sin6_port = htons(port);
255
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900256 if (!bind(s, &u.sa, slen)) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900257 }
258
Bernie Innocenti9c575932018-09-07 21:10:25 +0900259 // nothing after 10 attempts, our network table is probably busy
260 // let the system decide which port is best
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900261 if (family == AF_INET)
262 u.sin.sin_port = 0;
263 else
264 u.sin6.sin6_port = 0;
265
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900266 return bind(s, &u.sa, slen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900267}
268/* BIONIC-END */
269
Luke Huang70931aa2019-01-31 11:57:41 +0800270// Disables all nameservers other than selectedServer
271static void res_set_usable_server(int selectedServer, int nscount, bool usable_servers[]) {
272 int usableIndex = 0;
273 for (int ns = 0; ns < nscount; ns++) {
274 if (usable_servers[ns]) ++usableIndex;
275 if (usableIndex != selectedServer) usable_servers[ns] = false;
276 }
277}
278
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900279/* int
280 * res_isourserver(ina)
281 * looks up "ina" in _res.ns_addr_list[]
282 * returns:
283 * 0 : not found
284 * >0 : found
285 * author:
286 * paul vixie, 29may94
287 */
Bernie Innocenti2e8540b2018-09-26 11:52:04 +0900288static int res_ourserver_p(const res_state statp, const sockaddr* sa) {
289 const sockaddr_in *inp, *srv;
290 const sockaddr_in6 *in6p, *srv6;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900291 int ns;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900292
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900293 switch (sa->sa_family) {
294 case AF_INET:
295 inp = (const struct sockaddr_in*) (const void*) sa;
296 for (ns = 0; ns < statp->nscount; ns++) {
297 srv = (struct sockaddr_in*) (void*) get_nsaddr(statp, (size_t) ns);
298 if (srv->sin_family == inp->sin_family && srv->sin_port == inp->sin_port &&
299 (srv->sin_addr.s_addr == INADDR_ANY ||
300 srv->sin_addr.s_addr == inp->sin_addr.s_addr))
Bernie Innocenti2e8540b2018-09-26 11:52:04 +0900301 return 1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900302 }
303 break;
304 case AF_INET6:
Ken Chene6fa86e2018-10-16 23:12:09 +0800305 if (statp->_u._ext.ext == NULL) break;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900306 in6p = (const struct sockaddr_in6*) (const void*) sa;
307 for (ns = 0; ns < statp->nscount; ns++) {
308 srv6 = (struct sockaddr_in6*) (void*) get_nsaddr(statp, (size_t) ns);
309 if (srv6->sin6_family == in6p->sin6_family && srv6->sin6_port == in6p->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900310#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900311 (srv6->sin6_scope_id == 0 || srv6->sin6_scope_id == in6p->sin6_scope_id) &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900312#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900313 (IN6_IS_ADDR_UNSPECIFIED(&srv6->sin6_addr) ||
314 IN6_ARE_ADDR_EQUAL(&srv6->sin6_addr, &in6p->sin6_addr)))
Bernie Innocenti2e8540b2018-09-26 11:52:04 +0900315 return 1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900316 }
317 break;
318 default:
319 break;
320 }
Bernie Innocenti2e8540b2018-09-26 11:52:04 +0900321 return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900322}
323
324/* int
Bernie Innocenti9c575932018-09-07 21:10:25 +0900325 * res_nameinquery(name, type, cl, buf, eom)
326 * look for (name, type, cl) in the query section of packet (buf, eom)
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900327 * requires:
328 * buf + HFIXEDSZ <= eom
329 * returns:
330 * -1 : format error
331 * 0 : not found
332 * >0 : found
333 * author:
334 * paul vixie, 29may94
335 */
Bernie Innocenti9c575932018-09-07 21:10:25 +0900336int res_nameinquery(const char* name, int type, int cl, const u_char* buf, const u_char* eom) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900337 const u_char* cp = buf + HFIXEDSZ;
338 int qdcount = ntohs(((const HEADER*) (const void*) buf)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900339
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900340 while (qdcount-- > 0) {
341 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900342 int n = dn_expand(buf, eom, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900343 if (n < 0) return (-1);
344 cp += n;
345 if (cp + 2 * INT16SZ > eom) return (-1);
chenbruce0d470422019-03-28 18:44:37 +0800346 int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900347 cp += INT16SZ;
chenbruce0d470422019-03-28 18:44:37 +0800348 int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900349 cp += INT16SZ;
Bernie Innocenti9c575932018-09-07 21:10:25 +0900350 if (ttype == type && tclass == cl && ns_samename(tname, name) == 1) return (1);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900351 }
352 return (0);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900353}
354
355/* int
356 * res_queriesmatch(buf1, eom1, buf2, eom2)
357 * is there a 1:1 mapping of (name,type,class)
358 * in (buf1,eom1) and (buf2,eom2)?
359 * returns:
360 * -1 : format error
361 * 0 : not a 1:1 mapping
362 * >0 : is a 1:1 mapping
363 * author:
364 * paul vixie, 29may94
365 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900366int res_queriesmatch(const u_char* buf1, const u_char* eom1, const u_char* buf2,
367 const u_char* eom2) {
368 const u_char* cp = buf1 + HFIXEDSZ;
369 int qdcount = ntohs(((const HEADER*) (const void*) buf1)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900370
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900371 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2) return (-1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900372
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900373 /*
374 * Only header section present in replies to
375 * dynamic update packets.
376 */
377 if ((((const HEADER*) (const void*) buf1)->opcode == ns_o_update) &&
378 (((const HEADER*) (const void*) buf2)->opcode == ns_o_update))
379 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900380
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900381 if (qdcount != ntohs(((const HEADER*) (const void*) buf2)->qdcount)) return (0);
382 while (qdcount-- > 0) {
383 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900384 int n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900385 if (n < 0) return (-1);
386 cp += n;
387 if (cp + 2 * INT16SZ > eom1) return (-1);
chenbruce0d470422019-03-28 18:44:37 +0800388 int ttype = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900389 cp += INT16SZ;
chenbruce0d470422019-03-28 18:44:37 +0800390 int tclass = ntohs(*reinterpret_cast<const uint16_t*>(cp));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900391 cp += INT16SZ;
392 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2)) return (0);
393 }
394 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900395}
396
lifr94981782019-05-17 21:15:19 +0800397static DnsQueryEvent* addDnsQueryEvent(NetworkDnsEventReported* event) {
398 return event->mutable_dns_query_events()->add_dns_query_event();
399}
400
Luke Huangba7bef92018-12-26 16:53:03 +0800401int res_nsend(res_state statp, const u_char* buf, int buflen, u_char* ans, int anssiz, int* rcode,
402 uint32_t flags) {
Bernie Innocenti9c575932018-09-07 21:10:25 +0900403 int gotsomewhere, terrno, v_circuit, resplen, n;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900404 ResolvCacheStatus cache_status = RESOLV_CACHE_UNSUPPORTED;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900405
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900406 if (anssiz < HFIXEDSZ) {
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800407 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900408 errno = EINVAL;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800409 return -EINVAL;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900410 }
Bernie Innocenti3952ccc2019-03-03 19:39:53 +0900411 LOG(DEBUG) << __func__;
chenbrucedd210722019-03-06 13:52:43 +0800412 res_pquery(buf, buflen);
chenbruceacb832c2019-02-20 19:45:50 +0800413
chenbruce018fdb22019-06-12 18:08:04 +0800414 v_circuit = buflen > PACKETSZ;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900415 gotsomewhere = 0;
416 terrno = ETIMEDOUT;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900417
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900418 int anslen = 0;
lifrd4d9fbb2019-07-31 20:18:35 +0800419 Stopwatch cacheStopwatch;
Mike Yud1ec2542019-06-06 17:17:53 +0800420 cache_status = resolv_cache_lookup(statp->netid, buf, buflen, ans, anssiz, &anslen, flags);
lifrd4d9fbb2019-07-31 20:18:35 +0800421 const int32_t cacheLatencyUs = saturate_cast<int32_t>(cacheStopwatch.timeTakenUs());
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900422 if (cache_status == RESOLV_CACHE_FOUND) {
Luke Huang83c9b4b2019-02-27 18:18:01 +0800423 HEADER* hp = (HEADER*)(void*)ans;
424 *rcode = hp->rcode;
lifr94981782019-05-17 21:15:19 +0800425 DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
426 dnsQueryEvent->set_latency_micros(cacheLatencyUs);
427 dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900428 return anslen;
429 } else if (cache_status != RESOLV_CACHE_UNSUPPORTED) {
430 // had a cache miss for a known network, so populate the thread private
431 // data so the normal resolve path can do its thing
432 _resolv_populate_res_for_net(statp);
433 }
434 if (statp->nscount == 0) {
435 // We have no nameservers configured, so there's no point trying.
436 // Tell the cache the query failed, or any retries and anyone else asking the same
437 // question will block for PENDING_REQUEST_TIMEOUT seconds instead of failing fast.
Luke Huangba7bef92018-12-26 16:53:03 +0800438 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800439
440 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900441 errno = ESRCH;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800442 return -ESRCH;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900443 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900444
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900445 /*
446 * If the ns_addr_list in the resolver context has changed, then
447 * invalidate our cached copy and the associated timing data.
448 */
Ken Chene6fa86e2018-10-16 23:12:09 +0800449 if (statp->_u._ext.nscount != 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900450 int needclose = 0;
451 struct sockaddr_storage peer;
452 socklen_t peerlen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900453
Ken Chene6fa86e2018-10-16 23:12:09 +0800454 if (statp->_u._ext.nscount != statp->nscount) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900455 needclose++;
456 } else {
Bernie Innocenti9c575932018-09-07 21:10:25 +0900457 for (int ns = 0; ns < statp->nscount; ns++) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900458 if (statp->nsaddr_list[ns].sin_family &&
459 !sock_eq((struct sockaddr*) (void*) &statp->nsaddr_list[ns],
Ken Chene6fa86e2018-10-16 23:12:09 +0800460 (struct sockaddr*) (void*) &statp->_u._ext.ext->nsaddrs[ns])) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900461 needclose++;
462 break;
463 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900464
Ken Chene6fa86e2018-10-16 23:12:09 +0800465 if (statp->_u._ext.nssocks[ns] == -1) continue;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900466 peerlen = sizeof(peer);
Ken Chene6fa86e2018-10-16 23:12:09 +0800467 if (getpeername(statp->_u._ext.nssocks[ns], (struct sockaddr*) (void*) &peer,
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900468 &peerlen) < 0) {
469 needclose++;
470 break;
471 }
472 if (!sock_eq((struct sockaddr*) (void*) &peer, get_nsaddr(statp, (size_t) ns))) {
473 needclose++;
474 break;
475 }
476 }
477 }
478 if (needclose) {
479 res_nclose(statp);
Ken Chene6fa86e2018-10-16 23:12:09 +0800480 statp->_u._ext.nscount = 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900481 }
482 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900483
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900484 /*
485 * Maybe initialize our private copy of the ns_addr_list.
486 */
Ken Chene6fa86e2018-10-16 23:12:09 +0800487 if (statp->_u._ext.nscount == 0) {
Bernie Innocenti9c575932018-09-07 21:10:25 +0900488 for (int ns = 0; ns < statp->nscount; ns++) {
Ken Chene6fa86e2018-10-16 23:12:09 +0800489 statp->_u._ext.nstimes[ns] = RES_MAXTIME;
490 statp->_u._ext.nssocks[ns] = -1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900491 if (!statp->nsaddr_list[ns].sin_family) continue;
Ken Chene6fa86e2018-10-16 23:12:09 +0800492 statp->_u._ext.ext->nsaddrs[ns].sin = statp->nsaddr_list[ns];
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900493 }
Ken Chene6fa86e2018-10-16 23:12:09 +0800494 statp->_u._ext.nscount = statp->nscount;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900495 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900496
Bernie Innocenti758005f2019-02-19 18:08:36 +0900497 res_stats stats[MAXNS];
498 res_params params;
waynema0161acd2019-02-18 17:47:59 +0800499 int revision_id = resolv_cache_get_resolver_stats(statp->netid, &params, stats);
lifra1b37f12019-02-13 17:33:57 +0800500 if (revision_id < 0) {
501 // TODO: Remove errno once callers stop using it
502 errno = ESRCH;
503 return -ESRCH;
504 }
waynema0161acd2019-02-18 17:47:59 +0800505 bool usable_servers[MAXNS];
Luke Huang70931aa2019-01-31 11:57:41 +0800506 int usableServersCount = android_net_res_stats_get_usable_servers(
507 &params, stats, statp->nscount, usable_servers);
508
509 if ((flags & ANDROID_RESOLV_NO_RETRY) && usableServersCount > 1) {
510 auto hp = reinterpret_cast<const HEADER*>(buf);
511
512 // Select a random server based on the query id
513 int selectedServer = (hp->id % usableServersCount) + 1;
514 res_set_usable_server(selectedServer, statp->nscount, usable_servers);
515 }
waynema0161acd2019-02-18 17:47:59 +0800516
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900517 /*
518 * Send request, RETRY times, or until successful.
519 */
waynemaa74195e2019-01-18 14:02:31 +0800520 int retryTimes = (flags & ANDROID_RESOLV_NO_RETRY) ? 1 : params.retry_count;
Luke Huangba7bef92018-12-26 16:53:03 +0800521
522 for (int attempt = 0; attempt < retryTimes; ++attempt) {
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900523
Bernie Innocenti9c575932018-09-07 21:10:25 +0900524 for (int ns = 0; ns < statp->nscount; ns++) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900525 if (!usable_servers[ns]) continue;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900526 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;
lifr94981782019-05-17 21:15:19 +0800530 const sockaddr* nsap = get_nsaddr(statp, ns);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900531 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.
chenbruced8cbb9b2019-06-20 18:25:28 +0800537 if (!(statp->netcontext_flags & NET_CONTEXT_FLAG_USE_LOCAL_NAMESERVERS)) {
Mike Yubfb1b342018-11-06 15:42:36 +0800538 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) {
Mike Yud1ec2542019-06-06 17:17:53 +0800543 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
Mike Yubfb1b342018-11-06 15:42:36 +0800544 }
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
lifr94981782019-05-17 21:15:19 +0800554 static const int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
555 char abuf[NI_MAXHOST];
556 DnsQueryEvent* dnsQueryEvent = addDnsQueryEvent(statp->event);
557 dnsQueryEvent->set_cache_hit(static_cast<CacheStatus>(cache_status));
chenbruceacb832c2019-02-20 19:45:50 +0800558
559 if (getnameinfo(nsap, (socklen_t)nsaplen, abuf, sizeof(abuf), NULL, 0, niflags) == 0)
Ken Chenffc224a2019-03-19 17:41:28 +0800560 LOG(DEBUG) << __func__ << ": Querying server (# " << ns + 1
561 << ") address = " << abuf;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900562
lifrd4d9fbb2019-07-31 20:18:35 +0800563 Stopwatch queryStopwatch;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900564 if (v_circuit) {
565 /* Use VC; at most one attempt per server. */
Luke Huangba7bef92018-12-26 16:53:03 +0800566 bool shouldRecordStats = (attempt == 0);
567 attempt = retryTimes;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900568
Mike Yubfb1b342018-11-06 15:42:36 +0800569 n = send_vc(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &now, rcode,
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900570 &delay);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900571
lifr94981782019-05-17 21:15:19 +0800572 dnsQueryEvent->set_latency_micros(
lifrd4d9fbb2019-07-31 20:18:35 +0800573 saturate_cast<int32_t>(queryStopwatch.timeTakenUs()));
lifr94981782019-05-17 21:15:19 +0800574 dnsQueryEvent->set_dns_server_index(ns);
575 dnsQueryEvent->set_ip_version(ipFamilyToIPVersion(nsap->sa_family));
576 dnsQueryEvent->set_retry_times(attempt);
577 dnsQueryEvent->set_rcode(static_cast<NsRcode>(*rcode));
578 dnsQueryEvent->set_protocol(PROTO_TCP);
579 dnsQueryEvent->set_type(getQueryType(buf, buflen));
580
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900581 /*
582 * Only record stats the first time we try a query. This ensures that
583 * queries that deterministically fail (e.g., a name that always returns
584 * SERVFAIL or times out) do not unduly affect the stats.
585 */
Luke Huangba7bef92018-12-26 16:53:03 +0800586 if (shouldRecordStats) {
Bernie Innocentiac18b122018-10-01 23:10:18 +0900587 res_sample sample;
Mike Yubfb1b342018-11-06 15:42:36 +0800588 _res_stats_set_sample(&sample, now, *rcode, delay);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900589 _resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, ns, &sample,
590 params.max_samples);
591 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900592
Ken Chenffc224a2019-03-19 17:41:28 +0800593 LOG(INFO) << __func__ << ": used send_vc " << n;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900594
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800595 if (n < 0) {
Luke Huangba7bef92018-12-26 16:53:03 +0800596 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800597 res_nclose(statp);
598 return -terrno;
599 };
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900600 if (n == 0) goto next_ns;
601 resplen = n;
602 } else {
603 /* Use datagrams. */
Ken Chenffc224a2019-03-19 17:41:28 +0800604 LOG(INFO) << __func__ << ": using send_dg";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900605
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900606 n = send_dg(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &v_circuit,
Mike Yubfb1b342018-11-06 15:42:36 +0800607 &gotsomewhere, &now, rcode, &delay);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900608
lifr94981782019-05-17 21:15:19 +0800609 dnsQueryEvent->set_latency_micros(
lifrd4d9fbb2019-07-31 20:18:35 +0800610 saturate_cast<int32_t>(queryStopwatch.timeTakenUs()));
lifr94981782019-05-17 21:15:19 +0800611 dnsQueryEvent->set_dns_server_index(ns);
612 dnsQueryEvent->set_ip_version(ipFamilyToIPVersion(nsap->sa_family));
613 dnsQueryEvent->set_retry_times(attempt);
614 dnsQueryEvent->set_rcode(static_cast<NsRcode>(*rcode));
615 dnsQueryEvent->set_protocol(PROTO_UDP);
616 dnsQueryEvent->set_type(getQueryType(buf, buflen));
617
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900618 /* Only record stats the first time we try a query. See above. */
Bernie Innocenti9c575932018-09-07 21:10:25 +0900619 if (attempt == 0) {
Bernie Innocentiac18b122018-10-01 23:10:18 +0900620 res_sample sample;
Mike Yubfb1b342018-11-06 15:42:36 +0800621 _res_stats_set_sample(&sample, now, *rcode, delay);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900622 _resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, ns, &sample,
623 params.max_samples);
624 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900625
Ken Chenffc224a2019-03-19 17:41:28 +0800626 LOG(INFO) << __func__ << ": used send_dg " << n;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900627
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800628 if (n < 0) {
Luke Huangba7bef92018-12-26 16:53:03 +0800629 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800630 res_nclose(statp);
631 return -terrno;
632 };
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900633 if (n == 0) goto next_ns;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900634 if (v_circuit) goto same_ns;
635 resplen = n;
636 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900637
Ken Chenffc224a2019-03-19 17:41:28 +0800638 LOG(DEBUG) << __func__ << ": got answer:";
chenbrucedd210722019-03-06 13:52:43 +0800639 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900640
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900641 if (cache_status == RESOLV_CACHE_NOTFOUND) {
Mike Yud1ec2542019-06-06 17:17:53 +0800642 resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900643 }
chenbruce018fdb22019-06-12 18:08:04 +0800644 res_nclose(statp);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900645 return (resplen);
646 next_ns:;
Bernie Innocenti9c575932018-09-07 21:10:25 +0900647 } // for each ns
648 } // for each retry
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900649 res_nclose(statp);
650 if (!v_circuit) {
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800651 if (!gotsomewhere) {
652 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900653 errno = ECONNREFUSED; /* no nameservers found */
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800654 terrno = ECONNREFUSED;
655 } else {
656 // TODO: Remove errno once callers stop using it
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900657 errno = ETIMEDOUT; /* no answer obtained */
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800658 terrno = ETIMEDOUT;
659 }
660 } else {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900661 errno = terrno;
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800662 }
Luke Huangba7bef92018-12-26 16:53:03 +0800663 _resolv_cache_query_failed(statp->netid, buf, buflen, flags);
Luke Huangaa6e5ed2018-12-03 15:37:28 +0800664 return -terrno;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900665}
666
667/* Private */
668
Bernie Innocenti9c575932018-09-07 21:10:25 +0900669static int get_salen(const struct sockaddr* sa) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900670 if (sa->sa_family == AF_INET)
671 return (sizeof(struct sockaddr_in));
672 else if (sa->sa_family == AF_INET6)
673 return (sizeof(struct sockaddr_in6));
674 else
675 return (0); /* unknown, die on connect */
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900676}
677
678/*
679 * pick appropriate nsaddr_list for use. see res_init() for initialization.
680 */
Bernie Innocenti9c575932018-09-07 21:10:25 +0900681static struct sockaddr* get_nsaddr(res_state statp, size_t n) {
Ken Chene6fa86e2018-10-16 23:12:09 +0800682 if (!statp->nsaddr_list[n].sin_family && statp->_u._ext.ext) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900683 /*
Ken Chene6fa86e2018-10-16 23:12:09 +0800684 * - statp->_u._ext.ext->nsaddrs[n] holds an address that is larger
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900685 * than struct sockaddr, and
686 * - user code did not update statp->nsaddr_list[n].
687 */
Ken Chene6fa86e2018-10-16 23:12:09 +0800688 return (struct sockaddr*) (void*) &statp->_u._ext.ext->nsaddrs[n];
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900689 } else {
690 /*
691 * - user code updated statp->nsaddr_list[n], or
692 * - statp->nsaddr_list[n] has the same content as
Ken Chene6fa86e2018-10-16 23:12:09 +0800693 * statp->_u._ext.ext->nsaddrs[n].
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900694 */
695 return (struct sockaddr*) (void*) &statp->nsaddr_list[n];
696 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900697}
698
Bernie Innocenti758005f2019-02-19 18:08:36 +0900699static struct timespec get_timeout(const res_state statp, const res_params* params, const int ns) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900700 int msec;
waynemaa74195e2019-01-18 14:02:31 +0800701 // Legacy algorithm which scales the timeout by nameserver number.
702 // For instance, with 4 nameservers: 5s, 2.5s, 5s, 10s
703 // This has no effect with 1 or 2 nameservers
704 msec = params->base_timeout_msec << ns;
705 if (ns > 0) {
706 msec /= statp->nscount;
707 }
708 // For safety, don't allow OEMs and experiments to configure a timeout shorter than 1s.
709 if (msec < 1000) {
710 msec = 1000; // Use at least 1000ms
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900711 }
Ken Chenffc224a2019-03-19 17:41:28 +0800712 LOG(INFO) << __func__ << ": using timeout of " << msec << " msec";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900713
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900714 struct timespec result;
715 result.tv_sec = msec / 1000;
716 result.tv_nsec = (msec % 1000) * 1000000;
717 return result;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900718}
719
Bernie Innocenti758005f2019-02-19 18:08:36 +0900720static int send_vc(res_state statp, res_params* params, const u_char* buf, int buflen, u_char* ans,
721 int anssiz, int* terrno, int ns, time_t* at, int* rcode, int* delay) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900722 *at = time(NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900723 *delay = 0;
724 const HEADER* hp = (const HEADER*) (const void*) buf;
725 HEADER* anhp = (HEADER*) (void*) ans;
726 struct sockaddr* nsap;
727 int nsaplen;
chenbruce0d470422019-03-28 18:44:37 +0800728 int truncating, connreset, n;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900729 struct iovec iov[2];
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900730 u_char* cp;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900731
Ken Chenffc224a2019-03-19 17:41:28 +0800732 LOG(INFO) << __func__ << ": 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:
chenbruce018fdb22019-06-12 18:08:04 +0800767 PLOG(DEBUG) << __func__ << ": socket(vc): ";
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900768 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900769 default:
770 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800771 PLOG(DEBUG) << __func__ << ": socket(vc): ";
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900772 return -1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900773 }
774 }
Sehee Park2c118782019-05-07 13:02:45 +0900775 if (fchown(statp->_vcsock, statp->uid, -1) == -1) {
776 PLOG(WARNING) << __func__ << ": Failed to chown socket";
777 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900778 if (statp->_mark != MARK_UNSET) {
779 if (setsockopt(statp->_vcsock, SOL_SOCKET, SO_MARK, &statp->_mark,
780 sizeof(statp->_mark)) < 0) {
781 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800782 PLOG(DEBUG) << __func__ << ": setsockopt: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900783 return -1;
784 }
785 }
786 errno = 0;
787 if (random_bind(statp->_vcsock, nsap->sa_family) < 0) {
788 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800789 dump_error("bind/vc", nsap, nsaplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900790 res_nclose(statp);
791 return (0);
792 }
793 if (connect_with_timeout(statp->_vcsock, nsap, (socklen_t) nsaplen,
794 get_timeout(statp, params, ns)) < 0) {
795 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800796 dump_error("connect/vc", nsap, nsaplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900797 res_nclose(statp);
798 /*
799 * The way connect_with_timeout() is implemented prevents us from reliably
800 * determining whether this was really a timeout or e.g. ECONNREFUSED. Since
801 * currently both cases are handled in the same way, there is no need to
802 * change this (yet). If we ever need to reliably distinguish between these
803 * cases, both connect_with_timeout() and retrying_poll() need to be
804 * modified, though.
805 */
806 *rcode = RCODE_TIMEOUT;
807 return (0);
808 }
809 statp->_flags |= RES_F_VC;
810 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900811
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900812 /*
813 * Send length & message
814 */
chenbruce0d470422019-03-28 18:44:37 +0800815 uint16_t len = htons(static_cast<uint16_t>(buflen));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900816 iov[0] = evConsIovec(&len, INT16SZ);
Bernie Innocenti9c575932018-09-07 21:10:25 +0900817 iov[1] = evConsIovec((void*) buf, (size_t) buflen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900818 if (writev(statp->_vcsock, iov, 2) != (INT16SZ + buflen)) {
819 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800820 PLOG(DEBUG) << __func__ << ": write failed: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900821 res_nclose(statp);
822 return (0);
823 }
824 /*
825 * Receive length & response
826 */
827read_len:
828 cp = ans;
829 len = INT16SZ;
830 while ((n = read(statp->_vcsock, (char*) cp, (size_t) len)) > 0) {
831 cp += n;
832 if ((len -= n) == 0) break;
833 }
834 if (n <= 0) {
835 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800836 PLOG(DEBUG) << __func__ << ": read failed: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900837 res_nclose(statp);
838 /*
839 * A long running process might get its TCP
840 * connection reset if the remote server was
841 * restarted. Requery the server instead of
842 * trying a new one. When there is only one
843 * server, this means that a query might work
844 * instead of failing. We only allow one reset
845 * per query to prevent looping.
846 */
847 if (*terrno == ECONNRESET && !connreset) {
848 connreset = 1;
849 res_nclose(statp);
850 goto same_ns;
851 }
852 res_nclose(statp);
853 return (0);
854 }
chenbruce0d470422019-03-28 18:44:37 +0800855 uint16_t resplen = ntohs(*reinterpret_cast<const uint16_t*>(ans));
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900856 if (resplen > anssiz) {
Ken Chenffc224a2019-03-19 17:41:28 +0800857 LOG(DEBUG) << __func__ << ": response truncated";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900858 truncating = 1;
859 len = anssiz;
860 } else
861 len = resplen;
862 if (len < HFIXEDSZ) {
863 /*
864 * Undersized message.
865 */
Ken Chenffc224a2019-03-19 17:41:28 +0800866 LOG(DEBUG) << __func__ << ": undersized: " << len;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900867 *terrno = EMSGSIZE;
868 res_nclose(statp);
869 return (0);
870 }
871 cp = ans;
872 while (len != 0 && (n = read(statp->_vcsock, (char*) cp, (size_t) len)) > 0) {
873 cp += n;
874 len -= n;
875 }
876 if (n <= 0) {
877 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +0800878 PLOG(DEBUG) << __func__ << ": read(vc): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900879 res_nclose(statp);
880 return (0);
881 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900882
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900883 if (truncating) {
884 /*
885 * Flush rest of answer so connection stays in synch.
886 */
887 anhp->tc = 1;
888 len = resplen - anssiz;
889 while (len != 0) {
890 char junk[PACKETSZ];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900891
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900892 n = read(statp->_vcsock, junk, (len > sizeof junk) ? sizeof junk : len);
893 if (n > 0)
894 len -= n;
895 else
896 break;
897 }
898 }
899 /*
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900900 * If the calling application has bailed out of
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900901 * a previous call and failed to arrange to have
902 * the circuit closed or the server has got
903 * itself confused, then drop the packet and
904 * wait for the correct one.
905 */
906 if (hp->id != anhp->id) {
Ken Chenffc224a2019-03-19 17:41:28 +0800907 LOG(DEBUG) << __func__ << ": ld answer (unexpected):";
chenbrucedd210722019-03-06 13:52:43 +0800908 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900909 goto read_len;
910 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900911
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900912 /*
913 * All is well, or the error is fatal. Signal that the
914 * next nameserver ought not be tried.
915 */
916 if (resplen > 0) {
917 struct timespec done = evNowTime();
918 *delay = _res_stats_calculate_rtt(&done, &now);
919 *rcode = anhp->rcode;
920 }
921 return (resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900922}
923
924/* return -1 on error (errno set), 0 on success */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900925static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
926 const struct timespec timeout) {
927 int res, origflags;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900928
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900929 origflags = fcntl(sock, F_GETFL, 0);
930 fcntl(sock, F_SETFL, origflags | O_NONBLOCK);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900931
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900932 res = connect(sock, nsap, salen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900933 if (res < 0 && errno != EINPROGRESS) {
934 res = -1;
935 goto done;
936 }
937 if (res != 0) {
938 struct timespec now = evNowTime();
939 struct timespec finish = evAddTime(now, timeout);
Ken Chenffc224a2019-03-19 17:41:28 +0800940 LOG(INFO) << __func__ << ": " << sock << " send_vc";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900941 res = retrying_poll(sock, POLLIN | POLLOUT, &finish);
942 if (res <= 0) {
943 res = -1;
944 }
945 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900946done:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900947 fcntl(sock, F_SETFL, origflags);
Ken Chenffc224a2019-03-19 17:41:28 +0800948 LOG(INFO) << __func__ << ": " << sock << " connect_with_const timeout returning " << res;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900949 return res;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900950}
951
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900952static int retrying_poll(const int sock, const short events, const struct timespec* finish) {
953 struct timespec now, timeout;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900954
955retry:
Ken Chenffc224a2019-03-19 17:41:28 +0800956 LOG(INFO) << __func__ << ": " << sock << " retrying_poll";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900957
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900958 now = evNowTime();
959 if (evCmpTime(*finish, now) > 0)
960 timeout = evSubTime(*finish, now);
961 else
962 timeout = evConsTime(0L, 0L);
963 struct pollfd fds = {.fd = sock, .events = events};
964 int n = ppoll(&fds, 1, &timeout, /*sigmask=*/NULL);
965 if (n == 0) {
Ken Chenffc224a2019-03-19 17:41:28 +0800966 LOG(INFO) << __func__ << ": " << sock << "retrying_poll timeout";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900967 errno = ETIMEDOUT;
968 return 0;
969 }
970 if (n < 0) {
971 if (errno == EINTR) goto retry;
Ken Chenffc224a2019-03-19 17:41:28 +0800972 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll failed";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900973 return n;
974 }
975 if (fds.revents & (POLLIN | POLLOUT | POLLERR)) {
976 int error;
977 socklen_t len = sizeof(error);
978 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error) {
979 errno = error;
Ken Chenffc224a2019-03-19 17:41:28 +0800980 PLOG(INFO) << __func__ << ": " << sock << " retrying_poll getsockopt failed";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900981 return -1;
982 }
983 }
Ken Chenffc224a2019-03-19 17:41:28 +0800984 LOG(INFO) << __func__ << ": " << sock << " retrying_poll returning " << n;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900985 return n;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900986}
987
Bernie Innocenti758005f2019-02-19 18:08:36 +0900988static int send_dg(res_state statp, res_params* params, const u_char* buf, int buflen, u_char* ans,
989 int anssiz, int* terrno, int ns, int* v_circuit, int* gotsomewhere, time_t* at,
990 int* rcode, int* delay) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900991 *at = time(NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900992 *delay = 0;
993 const HEADER* hp = (const HEADER*) (const void*) buf;
994 HEADER* anhp = (HEADER*) (void*) ans;
995 const struct sockaddr* nsap;
996 int nsaplen;
997 struct timespec now, timeout, finish, done;
998 struct sockaddr_storage from;
999 socklen_t fromlen;
1000 int resplen, n, s;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001001
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001002 nsap = get_nsaddr(statp, (size_t) ns);
1003 nsaplen = get_salen(nsap);
Ken Chene6fa86e2018-10-16 23:12:09 +08001004 if (statp->_u._ext.nssocks[ns] == -1) {
1005 statp->_u._ext.nssocks[ns] = socket(nsap->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
1006 if (statp->_u._ext.nssocks[ns] < 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001007 switch (errno) {
1008 case EPROTONOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001009 case EPFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001010 case EAFNOSUPPORT:
chenbruce018fdb22019-06-12 18:08:04 +08001011 PLOG(DEBUG) << __func__ << ": socket(dg): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001012 return (0);
1013 default:
1014 *terrno = errno;
chenbruce018fdb22019-06-12 18:08:04 +08001015 PLOG(DEBUG) << __func__ << ": socket(dg): ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001016 return (-1);
1017 }
1018 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001019
Sehee Park2c118782019-05-07 13:02:45 +09001020 if (fchown(statp->_u._ext.nssocks[ns], statp->uid, -1) == -1) {
1021 PLOG(WARNING) << __func__ << ": Failed to chown socket";
1022 }
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001023 if (statp->_mark != MARK_UNSET) {
Ken Chene6fa86e2018-10-16 23:12:09 +08001024 if (setsockopt(statp->_u._ext.nssocks[ns], SOL_SOCKET, SO_MARK, &(statp->_mark),
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001025 sizeof(statp->_mark)) < 0) {
1026 res_nclose(statp);
1027 return -1;
1028 }
1029 }
chenbruceb9cce7b2019-07-15 16:14:53 +08001030 // Use a "connected" datagram socket to receive an ECONNREFUSED error
1031 // on the next socket operation when the server responds with an
1032 // ICMP port-unreachable error. This way we can detect the absence of
1033 // a nameserver without timing out.
Ken Chene6fa86e2018-10-16 23:12:09 +08001034 if (random_bind(statp->_u._ext.nssocks[ns], nsap->sa_family) < 0) {
chenbruce018fdb22019-06-12 18:08:04 +08001035 dump_error("bind(dg)", nsap, nsaplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001036 res_nclose(statp);
1037 return (0);
1038 }
Ken Chene6fa86e2018-10-16 23:12:09 +08001039 if (connect(statp->_u._ext.nssocks[ns], nsap, (socklen_t) nsaplen) < 0) {
chenbruce018fdb22019-06-12 18:08:04 +08001040 dump_error("connect(dg)", nsap, nsaplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001041 res_nclose(statp);
1042 return (0);
1043 }
Ken Chenffc224a2019-03-19 17:41:28 +08001044 LOG(DEBUG) << __func__ << ": new DG socket";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001045 }
Ken Chene6fa86e2018-10-16 23:12:09 +08001046 s = statp->_u._ext.nssocks[ns];
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001047 if (send(s, (const char*) buf, (size_t) buflen, 0) != buflen) {
chenbruce018fdb22019-06-12 18:08:04 +08001048 PLOG(DEBUG) << __func__ << ": send: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001049 res_nclose(statp);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001050 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001051 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001052
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001053 // Wait for reply.
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001054 timeout = get_timeout(statp, params, ns);
1055 now = evNowTime();
1056 finish = evAddTime(now, timeout);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001057retry:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001058 n = retrying_poll(s, POLLIN, &finish);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001059
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001060 if (n == 0) {
1061 *rcode = RCODE_TIMEOUT;
Ken Chenffc224a2019-03-19 17:41:28 +08001062 LOG(DEBUG) << __func__ << ": timeout";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001063 *gotsomewhere = 1;
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001064 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001065 }
1066 if (n < 0) {
chenbruce018fdb22019-06-12 18:08:04 +08001067 PLOG(DEBUG) << __func__ << ": poll: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001068 res_nclose(statp);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001069 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001070 }
1071 errno = 0;
1072 fromlen = sizeof(from);
1073 resplen = recvfrom(s, (char*) ans, (size_t) anssiz, 0, (struct sockaddr*) (void*) &from,
1074 &fromlen);
1075 if (resplen <= 0) {
chenbruce018fdb22019-06-12 18:08:04 +08001076 PLOG(DEBUG) << __func__ << ": recvfrom: ";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001077 res_nclose(statp);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001078 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001079 }
1080 *gotsomewhere = 1;
1081 if (resplen < HFIXEDSZ) {
1082 /*
1083 * Undersized message.
1084 */
Ken Chenffc224a2019-03-19 17:41:28 +08001085 LOG(DEBUG) << __func__ << ": undersized: " << resplen;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001086 *terrno = EMSGSIZE;
1087 res_nclose(statp);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001088 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001089 }
1090 if (hp->id != anhp->id) {
1091 /*
1092 * response from old query, ignore it.
1093 * XXX - potential security hazard could
1094 * be detected here.
1095 */
Ken Chenffc224a2019-03-19 17:41:28 +08001096 LOG(DEBUG) << __func__ << ": old answer:";
chenbrucedd210722019-03-06 13:52:43 +08001097 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001098 goto retry;
1099 }
chenbruce018fdb22019-06-12 18:08:04 +08001100 if (!res_ourserver_p(statp, (struct sockaddr*)(void*)&from)) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001101 /*
1102 * response from wrong server? ignore it.
1103 * XXX - potential security hazard could
1104 * be detected here.
1105 */
Ken Chenffc224a2019-03-19 17:41:28 +08001106 LOG(DEBUG) << __func__ << ": not our server:";
chenbrucedd210722019-03-06 13:52:43 +08001107 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001108 goto retry;
1109 }
chenbruced8cbb9b2019-06-20 18:25:28 +08001110 if (anhp->rcode == FORMERR && (statp->netcontext_flags & NET_CONTEXT_FLAG_USE_EDNS)) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001111 /*
1112 * Do not retry if the server do not understand EDNS0.
1113 * The case has to be captured here, as FORMERR packet do not
1114 * carry query section, hence res_queriesmatch() returns 0.
1115 */
Ken Chenffc224a2019-03-19 17:41:28 +08001116 LOG(DEBUG) << __func__ << ": server rejected query with EDNS0:";
chenbrucedd210722019-03-06 13:52:43 +08001117 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001118 /* record the error */
1119 statp->_flags |= RES_F_EDNS0ERR;
1120 res_nclose(statp);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001121 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001122 }
chenbruce018fdb22019-06-12 18:08:04 +08001123 if (!res_queriesmatch(buf, buf + buflen, ans, ans + anssiz)) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001124 /*
1125 * response contains wrong query? ignore it.
1126 * XXX - potential security hazard could
1127 * be detected here.
1128 */
Ken Chenffc224a2019-03-19 17:41:28 +08001129 LOG(DEBUG) << __func__ << ": wrong query name:";
chenbrucedd210722019-03-06 13:52:43 +08001130 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001131 goto retry;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001132 }
1133 done = evNowTime();
1134 *delay = _res_stats_calculate_rtt(&done, &now);
1135 if (anhp->rcode == SERVFAIL || anhp->rcode == NOTIMP || anhp->rcode == REFUSED) {
Ken Chenffc224a2019-03-19 17:41:28 +08001136 LOG(DEBUG) << __func__ << ": server rejected query:";
chenbrucedd210722019-03-06 13:52:43 +08001137 res_pquery(ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001138 res_nclose(statp);
chenbrucedd210722019-03-06 13:52:43 +08001139 *rcode = anhp->rcode;
1140 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001141 }
chenbruce018fdb22019-06-12 18:08:04 +08001142 if (anhp->tc) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001143 /*
1144 * To get the rest of answer,
1145 * use TCP with same server.
1146 */
Ken Chenffc224a2019-03-19 17:41:28 +08001147 LOG(DEBUG) << __func__ << ": truncated answer";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001148 *v_circuit = 1;
1149 res_nclose(statp);
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001150 return 1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001151 }
1152 /*
1153 * All is well, or the error is fatal. Signal that the
1154 * next nameserver ought not be tried.
1155 */
1156 if (resplen > 0) {
1157 *rcode = anhp->rcode;
1158 }
Bernie Innocenti3952ccc2019-03-03 19:39:53 +09001159 return resplen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001160}
1161
chenbruce018fdb22019-06-12 18:08:04 +08001162static void dump_error(const char* str, const struct sockaddr* address, int alen) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001163 char hbuf[NI_MAXHOST];
1164 char sbuf[NI_MAXSERV];
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001165 constexpr int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001166
chenbruce018fdb22019-06-12 18:08:04 +08001167 if (!WOULD_LOG(DEBUG)) return;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001168
chenbruce018fdb22019-06-12 18:08:04 +08001169 if (getnameinfo(address, (socklen_t)alen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf), niflags)) {
1170 strncpy(hbuf, "?", sizeof(hbuf) - 1);
1171 hbuf[sizeof(hbuf) - 1] = '\0';
1172 strncpy(sbuf, "?", sizeof(sbuf) - 1);
1173 sbuf[sizeof(sbuf) - 1] = '\0';
Elliott Hughes3b8f5902019-03-08 12:02:55 -08001174 }
chenbruce018fdb22019-06-12 18:08:04 +08001175 PLOG(DEBUG) << __func__ << ": " << str << " ([" << hbuf << "]." << sbuf << "): ";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001176}
1177
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001178static int sock_eq(struct sockaddr* a, struct sockaddr* b) {
1179 struct sockaddr_in *a4, *b4;
1180 struct sockaddr_in6 *a6, *b6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001181
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001182 if (a->sa_family != b->sa_family) return 0;
1183 switch (a->sa_family) {
1184 case AF_INET:
1185 a4 = (struct sockaddr_in*) (void*) a;
1186 b4 = (struct sockaddr_in*) (void*) b;
1187 return a4->sin_port == b4->sin_port && a4->sin_addr.s_addr == b4->sin_addr.s_addr;
1188 case AF_INET6:
1189 a6 = (struct sockaddr_in6*) (void*) a;
1190 b6 = (struct sockaddr_in6*) (void*) b;
1191 return a6->sin6_port == b6->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001192#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001193 a6->sin6_scope_id == b6->sin6_scope_id &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001194#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001195 IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
1196 default:
1197 return 0;
1198 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001199}
Mike Yub601ff72018-11-01 20:07:00 +08001200
lifr6b83a6f2019-07-26 03:17:43 +08001201PrivateDnsModes convertEnumType(PrivateDnsMode privateDnsmode) {
1202 switch (privateDnsmode) {
1203 case PrivateDnsMode::OFF:
1204 return PrivateDnsModes::PDM_OFF;
1205 case PrivateDnsMode::OPPORTUNISTIC:
1206 return PrivateDnsModes::PDM_OPPORTUNISTIC;
1207 case PrivateDnsMode::STRICT:
1208 return PrivateDnsModes::PDM_STRICT;
1209 }
1210 return PrivateDnsModes::PDM_UNKNOWN;
1211}
1212
Luke Huangd7aa7b42018-11-21 20:37:50 +08001213static int res_tls_send(res_state statp, const Slice query, const Slice answer, int* rcode,
Mike Yubfb1b342018-11-06 15:42:36 +08001214 bool* fallback) {
1215 int resplen = 0;
Mike Yub601ff72018-11-01 20:07:00 +08001216 const unsigned netId = statp->netid;
Mike Yub601ff72018-11-01 20:07:00 +08001217
Mike Yubfb1b342018-11-06 15:42:36 +08001218 PrivateDnsStatus privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
lifr6b83a6f2019-07-26 03:17:43 +08001219 statp->event->set_private_dns_modes(convertEnumType(privateDnsStatus.mode));
Mike Yubfb1b342018-11-06 15:42:36 +08001220
1221 if (privateDnsStatus.mode == PrivateDnsMode::OFF) {
1222 *fallback = true;
1223 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001224 }
1225
Mike Yu3e829062019-08-07 14:01:14 +08001226 if (privateDnsStatus.validatedServers().empty()) {
Mike Yub601ff72018-11-01 20:07:00 +08001227 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
Mike Yubfb1b342018-11-06 15:42:36 +08001228 *fallback = true;
1229 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001230 } else {
1231 // Sleep and iterate some small number of times checking for the
1232 // arrival of resolved and validated server IP addresses, instead
1233 // of returning an immediate error.
Mike Yu4f3747b2018-12-02 17:54:29 +09001234 // This is needed because as soon as a network becomes the default network, apps will
1235 // send DNS queries on that network. If no servers have yet validated, and we do not
1236 // block those queries, they would immediately fail, causing application-visible errors.
1237 // Note that this can happen even before the network validates, since an unvalidated
1238 // network can become the default network if no validated networks are available.
1239 //
1240 // TODO: see if there is a better way to address this problem, such as buffering the
1241 // queries in a queue or only blocking queries for the first few seconds after a default
1242 // network change.
Mike Yubfb1b342018-11-06 15:42:36 +08001243 for (int i = 0; i < 42; i++) {
1244 std::this_thread::sleep_for(std::chrono::milliseconds(100));
Mike Yu3e829062019-08-07 14:01:14 +08001245 // Calling getStatus() to merely check if there's any validated server seems
1246 // wasteful. Consider adding a new method in PrivateDnsConfiguration for speed ups.
1247 if (!gPrivateDnsConfiguration.getStatus(netId).validatedServers().empty()) {
Mike Yubfb1b342018-11-06 15:42:36 +08001248 privateDnsStatus = gPrivateDnsConfiguration.getStatus(netId);
1249 break;
1250 }
1251 }
Mike Yu3e829062019-08-07 14:01:14 +08001252 if (privateDnsStatus.validatedServers().empty()) {
Mike Yubfb1b342018-11-06 15:42:36 +08001253 return -1;
1254 }
Mike Yub601ff72018-11-01 20:07:00 +08001255 }
1256 }
1257
chenbruceacb832c2019-02-20 19:45:50 +08001258 LOG(INFO) << __func__ << ": performing query over TLS";
Mike Yub601ff72018-11-01 20:07:00 +08001259
Mike Yu3e829062019-08-07 14:01:14 +08001260 const auto response = sDnsTlsDispatcher.query(privateDnsStatus.validatedServers(), statp, query,
Mike Yubfb1b342018-11-06 15:42:36 +08001261 answer, &resplen);
Mike Yub601ff72018-11-01 20:07:00 +08001262
chenbruceacb832c2019-02-20 19:45:50 +08001263 LOG(INFO) << __func__ << ": TLS query result: " << static_cast<int>(response);
Mike Yub601ff72018-11-01 20:07:00 +08001264
1265 if (privateDnsStatus.mode == PrivateDnsMode::OPPORTUNISTIC) {
1266 // In opportunistic mode, handle falling back to cleartext in some
1267 // cases (DNS shouldn't fail if a validated opportunistic mode server
1268 // becomes unreachable for some reason).
1269 switch (response) {
Mike Yubfb1b342018-11-06 15:42:36 +08001270 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001271 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001272 return resplen;
Mike Yub601ff72018-11-01 20:07:00 +08001273 case DnsTlsTransport::Response::network_error:
Mike Yubfb1b342018-11-06 15:42:36 +08001274 // No need to set the error timeout here since it will fallback to UDP.
Mike Yub601ff72018-11-01 20:07:00 +08001275 case DnsTlsTransport::Response::internal_error:
1276 // Note: this will cause cleartext queries to be emitted, with
1277 // all of the EDNS0 goodness enabled. Fingers crossed. :-/
Mike Yubfb1b342018-11-06 15:42:36 +08001278 *fallback = true;
1279 [[fallthrough]];
Mike Yub601ff72018-11-01 20:07:00 +08001280 default:
Mike Yubfb1b342018-11-06 15:42:36 +08001281 return -1;
1282 }
1283 } else {
1284 // Strict mode
1285 switch (response) {
1286 case DnsTlsTransport::Response::success:
Luke Huangd7aa7b42018-11-21 20:37:50 +08001287 *rcode = reinterpret_cast<HEADER*>(answer.base())->rcode;
Mike Yubfb1b342018-11-06 15:42:36 +08001288 return resplen;
1289 case DnsTlsTransport::Response::network_error:
1290 // This case happens when the query stored in DnsTlsTransport is expired since
1291 // either 1) the query has been tried for 3 times but no response or 2) fail to
1292 // establish the connection with the server.
Luke Huangd7aa7b42018-11-21 20:37:50 +08001293 *rcode = RCODE_TIMEOUT;
Mike Yubfb1b342018-11-06 15:42:36 +08001294 [[fallthrough]];
1295 default:
1296 return -1;
Mike Yub601ff72018-11-01 20:07:00 +08001297 }
1298 }
Mike Yub601ff72018-11-01 20:07:00 +08001299}
Luke Huang4973a0d2018-11-19 20:17:26 +08001300
Luke Huangba7bef92018-12-26 16:53:03 +08001301int resolv_res_nsend(const android_net_context* netContext, const uint8_t* msg, int msgLen,
lifr94981782019-05-17 21:15:19 +08001302 uint8_t* ans, int ansLen, int* rcode, uint32_t flags,
1303 NetworkDnsEventReported* event) {
1304 assert(event != nullptr);
Luke Huang4973a0d2018-11-19 20:17:26 +08001305 res_state res = res_get_state();
lifr94981782019-05-17 21:15:19 +08001306 res_setnetcontext(res, netContext, event);
Luke Huang4973a0d2018-11-19 20:17:26 +08001307 _resolv_populate_res_for_net(res);
1308 *rcode = NOERROR;
Luke Huangba7bef92018-12-26 16:53:03 +08001309 return res_nsend(res, msg, msgLen, ans, ansLen, rcode, flags);
Bernie Innocentiec4219b2019-01-30 11:16:36 +09001310}