blob: 95605f446fae9b62a1fe6f4f7897e77e5372a542 [file] [log] [blame]
Bernie Innocenti55864192018-08-30 04:05:20 +09001/* $NetBSD: res_send.c,v 1.9 2006/01/24 17:41:25 christos Exp $ */
2
3/*
4 * Copyright (c) 1985, 1989, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. All advertising materials mentioning features or use of this software
16 * must display the following acknowledgement:
17 * This product includes software developed by the University of
18 * California, Berkeley and its contributors.
19 * 4. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 */
35
36/*
37 * Portions Copyright (c) 1993 by Digital Equipment Corporation.
38 *
39 * Permission to use, copy, modify, and distribute this software for any
40 * purpose with or without fee is hereby granted, provided that the above
41 * copyright notice and this permission notice appear in all copies, and that
42 * the name of Digital Equipment Corporation not be used in advertising or
43 * publicity pertaining to distribution of the document or software without
44 * specific, written prior permission.
45 *
46 * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
47 * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
48 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
49 * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
50 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
51 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
52 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
53 * SOFTWARE.
54 */
55
56/*
57 * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
58 * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
59 *
60 * Permission to use, copy, modify, and distribute this software for any
61 * purpose with or without fee is hereby granted, provided that the above
62 * copyright notice and this permission notice appear in all copies.
63 *
64 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
65 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
66 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR
67 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
68 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
69 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
70 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
71 */
72
Bernie Innocenti55864192018-08-30 04:05:20 +090073/*
74 * Send query to name server and wait for reply.
75 */
76
Bernie Innocentie9ba09c2018-09-12 23:20:10 +090077constexpr bool kVerboseLogging = false;
78#define LOG_TAG "res_send"
79
Bernie Innocenti55864192018-08-30 04:05:20 +090080#include <sys/param.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090081#include <sys/socket.h>
Bernie Innocentif12d5bb2018-08-31 14:09:46 +090082#include <sys/time.h>
83#include <sys/types.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090084#include <sys/uio.h>
85
Bernie Innocenti55864192018-08-30 04:05:20 +090086#include <arpa/inet.h>
Bernie Innocentif12d5bb2018-08-31 14:09:46 +090087#include <arpa/nameser.h>
88#include <netinet/in.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090089
90#include <errno.h>
91#include <fcntl.h>
92#include <netdb.h>
93#include <poll.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090094#include <signal.h>
95#include <stdio.h>
96#include <stdlib.h>
97#include <string.h>
98#include <time.h>
99#include <unistd.h>
100
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900101#include <android-base/logging.h>
Bernie Innocenti55864192018-08-30 04:05:20 +0900102
Bernie Innocenti2fd418e2018-08-30 12:04:03 +0900103#include "private/android_filesystem_config.h"
104#include "res_private.h"
105#include "resolv_cache.h"
106#include "resolv_netid.h"
107#include "resolv_private.h"
108#include "resolv_stats.h"
109
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900110#define EXT(res) ((res)->_u._ext)
111
112#define VLOG if (!kVerboseLogging) {} else LOG(INFO)
113
114#ifndef RESOLV_ALLOW_VERBOSE_LOGGING
115static_assert(kVerboseLogging == false,
116 "Verbose logging floods logs at high-rate and exposes privacy-sensitive information. "
117 "Do not enable in release builds.");
Bernie Innocenti55864192018-08-30 04:05:20 +0900118#endif
Bernie Innocenti2fd418e2018-08-30 12:04:03 +0900119
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900120#ifndef DEBUG
121#define Dprint(cond, args) /*empty*/
122#define DprintQ(cond, args, query, size) /*empty*/
123#else
124// TODO: convert to Android logging
125#define Dprint(cond, args) \
126 if (cond) { \
127 fprintf args; \
128 } else { \
129 }
130#define DprintQ(cond, args, query, size) \
131 if (cond) { \
132 fprintf args; \
133 res_pquery(statp, query, size, stdout); \
134 } else { \
135 }
136#endif // DEBUG
Bernie Innocenti55864192018-08-30 04:05:20 +0900137
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900138static int get_salen(const struct sockaddr*);
139static struct sockaddr* get_nsaddr(res_state, size_t);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900140static int send_vc(res_state, struct __res_params* params, const u_char*, int, u_char*, int, int*,
141 int, time_t*, int*, int*);
142static int send_dg(res_state, struct __res_params* params, const u_char*, int, u_char*, int, int*,
143 int, int*, int*, time_t*, int*, int*);
144static void Aerror(const res_state, FILE*, const char*, int, const struct sockaddr*, int);
145static void Perror(const res_state, FILE*, const char*, int);
146static int sock_eq(struct sockaddr*, struct sockaddr*);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900147static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
148 const struct timespec timeout);
Bernie Innocenti55864192018-08-30 04:05:20 +0900149static int retrying_poll(const int sock, short events, const struct timespec* finish);
150
151/* BIONIC-BEGIN: implement source port randomization */
152typedef union {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900153 struct sockaddr sa;
154 struct sockaddr_in sin;
155 struct sockaddr_in6 sin6;
Bernie Innocenti55864192018-08-30 04:05:20 +0900156} _sockaddr_union;
157
Bernie Innocentif89b3512018-08-30 07:34:37 +0900158// BEGIN: Code copied from ISC eventlib
159// TODO: move away from this code
160
161#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 Innocentif89b3512018-08-30 07:34:37 +0900207static struct timespec evNowTime(void) {
Bernie Innocentif89b3512018-08-30 07:34:37 +0900208 struct timespec tsnow;
Bernie Innocenti357339c2018-08-31 16:11:41 +0900209 clock_gettime(CLOCK_REALTIME, &tsnow);
210 return tsnow;
Bernie Innocentif89b3512018-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 Innocenti357339c2018-08-31 16:11:41 +0900219 return ret;
Bernie Innocentif89b3512018-08-30 07:34:37 +0900220}
221
222// END: Code copied from ISC eventlib
223
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900224static int random_bind(int s, int family) {
225 _sockaddr_union u;
226 int j;
227 socklen_t slen;
Bernie Innocenti55864192018-08-30 04:05:20 +0900228
229 /* clear all, this also sets the IP4/6 address to 'any' */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900230 memset(&u, 0, sizeof u);
Bernie Innocenti55864192018-08-30 04:05:20 +0900231
232 switch (family) {
233 case AF_INET:
234 u.sin.sin_family = family;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900235 slen = sizeof u.sin;
Bernie Innocenti55864192018-08-30 04:05:20 +0900236 break;
237 case AF_INET6:
238 u.sin6.sin6_family = family;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900239 slen = sizeof u.sin6;
Bernie Innocenti55864192018-08-30 04:05:20 +0900240 break;
241 default:
242 errno = EPROTO;
243 return -1;
244 }
245
246 /* first try to bind to a random source port a few times */
247 for (j = 0; j < 10; j++) {
248 /* find a random port between 1025 .. 65534 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900249 int port = 1025 + (res_randomid() % (65535 - 1025));
Bernie Innocenti55864192018-08-30 04:05:20 +0900250 if (family == AF_INET)
251 u.sin.sin_port = htons(port);
252 else
253 u.sin6.sin6_port = htons(port);
254
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900255 if (!bind(s, &u.sa, slen)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900256 }
257
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900258 // nothing after 10 attempts, our network table is probably busy
259 // let the system decide which port is best
Bernie Innocenti55864192018-08-30 04:05:20 +0900260 if (family == AF_INET)
261 u.sin.sin_port = 0;
262 else
263 u.sin6.sin6_port = 0;
264
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900265 return bind(s, &u.sa, slen);
Bernie Innocenti55864192018-08-30 04:05:20 +0900266}
267/* BIONIC-END */
268
Bernie Innocenti55864192018-08-30 04:05:20 +0900269/* int
270 * res_isourserver(ina)
271 * looks up "ina" in _res.ns_addr_list[]
272 * returns:
273 * 0 : not found
274 * >0 : found
275 * author:
276 * paul vixie, 29may94
277 */
Bernie Innocenti4acba1a2018-09-26 11:52:04 +0900278static int res_ourserver_p(const res_state statp, const sockaddr* sa) {
279 const sockaddr_in *inp, *srv;
280 const sockaddr_in6 *in6p, *srv6;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900281 int ns;
Bernie Innocenti55864192018-08-30 04:05:20 +0900282
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900283 switch (sa->sa_family) {
284 case AF_INET:
285 inp = (const struct sockaddr_in*) (const void*) sa;
286 for (ns = 0; ns < statp->nscount; ns++) {
287 srv = (struct sockaddr_in*) (void*) get_nsaddr(statp, (size_t) ns);
288 if (srv->sin_family == inp->sin_family && srv->sin_port == inp->sin_port &&
289 (srv->sin_addr.s_addr == INADDR_ANY ||
290 srv->sin_addr.s_addr == inp->sin_addr.s_addr))
Bernie Innocenti4acba1a2018-09-26 11:52:04 +0900291 return 1;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900292 }
293 break;
294 case AF_INET6:
295 if (EXT(statp).ext == NULL) break;
296 in6p = (const struct sockaddr_in6*) (const void*) sa;
297 for (ns = 0; ns < statp->nscount; ns++) {
298 srv6 = (struct sockaddr_in6*) (void*) get_nsaddr(statp, (size_t) ns);
299 if (srv6->sin6_family == in6p->sin6_family && srv6->sin6_port == in6p->sin6_port &&
Bernie Innocenti55864192018-08-30 04:05:20 +0900300#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900301 (srv6->sin6_scope_id == 0 || srv6->sin6_scope_id == in6p->sin6_scope_id) &&
Bernie Innocenti55864192018-08-30 04:05:20 +0900302#endif
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900303 (IN6_IS_ADDR_UNSPECIFIED(&srv6->sin6_addr) ||
304 IN6_ARE_ADDR_EQUAL(&srv6->sin6_addr, &in6p->sin6_addr)))
Bernie Innocenti4acba1a2018-09-26 11:52:04 +0900305 return 1;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900306 }
307 break;
308 default:
309 break;
310 }
Bernie Innocenti4acba1a2018-09-26 11:52:04 +0900311 return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900312}
313
314/* int
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900315 * res_nameinquery(name, type, cl, buf, eom)
316 * look for (name, type, cl) in the query section of packet (buf, eom)
Bernie Innocenti55864192018-08-30 04:05:20 +0900317 * requires:
318 * buf + HFIXEDSZ <= eom
319 * returns:
320 * -1 : format error
321 * 0 : not found
322 * >0 : found
323 * author:
324 * paul vixie, 29may94
325 */
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900326int res_nameinquery(const char* name, int type, int cl, const u_char* buf, const u_char* eom) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900327 const u_char* cp = buf + HFIXEDSZ;
328 int qdcount = ntohs(((const HEADER*) (const void*) buf)->qdcount);
Bernie Innocenti55864192018-08-30 04:05:20 +0900329
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900330 while (qdcount-- > 0) {
331 char tname[MAXDNAME + 1];
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900332 int n = dn_expand(buf, eom, cp, tname, sizeof tname);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900333 if (n < 0) return (-1);
334 cp += n;
335 if (cp + 2 * INT16SZ > eom) return (-1);
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900336 int ttype = ns_get16(cp);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900337 cp += INT16SZ;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900338 int tclass = ns_get16(cp);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900339 cp += INT16SZ;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900340 if (ttype == type && tclass == cl && ns_samename(tname, name) == 1) return (1);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900341 }
342 return (0);
Bernie Innocenti55864192018-08-30 04:05:20 +0900343}
344
345/* int
346 * res_queriesmatch(buf1, eom1, buf2, eom2)
347 * is there a 1:1 mapping of (name,type,class)
348 * in (buf1,eom1) and (buf2,eom2)?
349 * returns:
350 * -1 : format error
351 * 0 : not a 1:1 mapping
352 * >0 : is a 1:1 mapping
353 * author:
354 * paul vixie, 29may94
355 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900356int res_queriesmatch(const u_char* buf1, const u_char* eom1, const u_char* buf2,
357 const u_char* eom2) {
358 const u_char* cp = buf1 + HFIXEDSZ;
359 int qdcount = ntohs(((const HEADER*) (const void*) buf1)->qdcount);
Bernie Innocenti55864192018-08-30 04:05:20 +0900360
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900361 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2) return (-1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900362
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900363 /*
364 * Only header section present in replies to
365 * dynamic update packets.
366 */
367 if ((((const HEADER*) (const void*) buf1)->opcode == ns_o_update) &&
368 (((const HEADER*) (const void*) buf2)->opcode == ns_o_update))
369 return (1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900370
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900371 if (qdcount != ntohs(((const HEADER*) (const void*) buf2)->qdcount)) return (0);
372 while (qdcount-- > 0) {
373 char tname[MAXDNAME + 1];
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900374 int n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900375 if (n < 0) return (-1);
376 cp += n;
377 if (cp + 2 * INT16SZ > eom1) return (-1);
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900378 int ttype = ns_get16(cp);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900379 cp += INT16SZ;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900380 int tclass = ns_get16(cp);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900381 cp += INT16SZ;
382 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2)) return (0);
383 }
384 return (1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900385}
386
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900387int res_nsend(res_state statp, const u_char* buf, int buflen, u_char* ans, int anssiz) {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900388 int gotsomewhere, terrno, v_circuit, resplen, n;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900389 ResolvCacheStatus cache_status = RESOLV_CACHE_UNSUPPORTED;
Bernie Innocenti55864192018-08-30 04:05:20 +0900390
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900391 if (anssiz < HFIXEDSZ) {
392 errno = EINVAL;
393 return (-1);
394 }
395 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_QUERY),
396 (stdout, ";; res_send()\n"), buf, buflen);
397 v_circuit = (statp->options & RES_USEVC) || buflen > PACKETSZ;
398 gotsomewhere = 0;
399 terrno = ETIMEDOUT;
Bernie Innocenti55864192018-08-30 04:05:20 +0900400
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900401 int anslen = 0;
402 cache_status = _resolv_cache_lookup(statp->netid, buf, buflen, ans, anssiz, &anslen);
Bernie Innocenti55864192018-08-30 04:05:20 +0900403
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900404 if (cache_status == RESOLV_CACHE_FOUND) {
405 return anslen;
406 } else if (cache_status != RESOLV_CACHE_UNSUPPORTED) {
407 // had a cache miss for a known network, so populate the thread private
408 // data so the normal resolve path can do its thing
409 _resolv_populate_res_for_net(statp);
410 }
411 if (statp->nscount == 0) {
412 // We have no nameservers configured, so there's no point trying.
413 // Tell the cache the query failed, or any retries and anyone else asking the same
414 // question will block for PENDING_REQUEST_TIMEOUT seconds instead of failing fast.
415 _resolv_cache_query_failed(statp->netid, buf, buflen);
416 errno = ESRCH;
417 return (-1);
418 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900419
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900420 /*
421 * If the ns_addr_list in the resolver context has changed, then
422 * invalidate our cached copy and the associated timing data.
423 */
424 if (EXT(statp).nscount != 0) {
425 int needclose = 0;
426 struct sockaddr_storage peer;
427 socklen_t peerlen;
Bernie Innocenti55864192018-08-30 04:05:20 +0900428
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900429 if (EXT(statp).nscount != statp->nscount) {
430 needclose++;
431 } else {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900432 for (int ns = 0; ns < statp->nscount; ns++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900433 if (statp->nsaddr_list[ns].sin_family &&
434 !sock_eq((struct sockaddr*) (void*) &statp->nsaddr_list[ns],
435 (struct sockaddr*) (void*) &EXT(statp).ext->nsaddrs[ns])) {
436 needclose++;
437 break;
438 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900439
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900440 if (EXT(statp).nssocks[ns] == -1) continue;
441 peerlen = sizeof(peer);
442 if (getpeername(EXT(statp).nssocks[ns], (struct sockaddr*) (void*) &peer,
443 &peerlen) < 0) {
444 needclose++;
445 break;
446 }
447 if (!sock_eq((struct sockaddr*) (void*) &peer, get_nsaddr(statp, (size_t) ns))) {
448 needclose++;
449 break;
450 }
451 }
452 }
453 if (needclose) {
454 res_nclose(statp);
455 EXT(statp).nscount = 0;
456 }
457 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900458
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900459 /*
460 * Maybe initialize our private copy of the ns_addr_list.
461 */
462 if (EXT(statp).nscount == 0) {
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900463 for (int ns = 0; ns < statp->nscount; ns++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900464 EXT(statp).nstimes[ns] = RES_MAXTIME;
465 EXT(statp).nssocks[ns] = -1;
466 if (!statp->nsaddr_list[ns].sin_family) continue;
467 EXT(statp).ext->nsaddrs[ns].sin = statp->nsaddr_list[ns];
468 }
469 EXT(statp).nscount = statp->nscount;
470 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900471
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900472 /*
473 * Some resolvers want to even out the load on their nameservers.
474 * Note that RES_BLAST overrides RES_ROTATE.
475 */
476 if ((statp->options & RES_ROTATE) != 0U && (statp->options & RES_BLAST) == 0U) {
477 union res_sockaddr_union inu;
478 struct sockaddr_in ina;
479 int lastns = statp->nscount - 1;
480 int fd;
481 u_int16_t nstime;
Bernie Innocenti55864192018-08-30 04:05:20 +0900482
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900483 if (EXT(statp).ext != NULL) inu = EXT(statp).ext->nsaddrs[0];
484 ina = statp->nsaddr_list[0];
485 fd = EXT(statp).nssocks[0];
486 nstime = EXT(statp).nstimes[0];
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900487 for (int ns = 0; ns < lastns; ns++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900488 if (EXT(statp).ext != NULL)
489 EXT(statp).ext->nsaddrs[ns] = EXT(statp).ext->nsaddrs[ns + 1];
490 statp->nsaddr_list[ns] = statp->nsaddr_list[ns + 1];
491 EXT(statp).nssocks[ns] = EXT(statp).nssocks[ns + 1];
492 EXT(statp).nstimes[ns] = EXT(statp).nstimes[ns + 1];
493 }
494 if (EXT(statp).ext != NULL) EXT(statp).ext->nsaddrs[lastns] = inu;
495 statp->nsaddr_list[lastns] = ina;
496 EXT(statp).nssocks[lastns] = fd;
497 EXT(statp).nstimes[lastns] = nstime;
498 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900499
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900500 /*
501 * Send request, RETRY times, or until successful.
502 */
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900503 for (int attempt = 0; attempt < statp->retry; ++attempt) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900504 struct __res_stats stats[MAXNS];
505 struct __res_params params;
506 int revision_id = _resolv_cache_get_resolver_stats(statp->netid, &params, stats);
507 bool usable_servers[MAXNS];
508 android_net_res_stats_get_usable_servers(&params, stats, statp->nscount, usable_servers);
Bernie Innocenti55864192018-08-30 04:05:20 +0900509
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900510 for (int ns = 0; ns < statp->nscount; ns++) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900511 if (!usable_servers[ns]) continue;
512 struct sockaddr* nsap;
513 int nsaplen;
514 time_t now = 0;
515 int rcode = RCODE_INTERNAL_ERROR;
516 int delay = 0;
517 nsap = get_nsaddr(statp, (size_t) ns);
518 nsaplen = get_salen(nsap);
519 statp->_flags &= ~RES_F_LASTMASK;
520 statp->_flags |= (ns << RES_F_LASTSHIFT);
Bernie Innocenti55864192018-08-30 04:05:20 +0900521
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900522 same_ns:
523 if (statp->qhook) {
524 int done = 0, loops = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900525
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900526 do {
527 res_sendhookact act;
Bernie Innocenti55864192018-08-30 04:05:20 +0900528
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900529 act = (*statp->qhook)(&nsap, &buf, &buflen, ans, anssiz, &resplen);
530 switch (act) {
531 case res_goahead:
532 done = 1;
533 break;
534 case res_nextns:
535 res_nclose(statp);
536 goto next_ns;
537 case res_done:
538 if (cache_status == RESOLV_CACHE_NOTFOUND) {
539 _resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
540 }
541 return (resplen);
542 case res_modified:
543 /* give the hook another try */
544 if (++loops < 42) /*doug adams*/
545 break;
Bernie Innocenti8bb94ba2018-10-10 22:30:12 +0900546 [[fallthrough]];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900547 case res_error:
Bernie Innocenti8bb94ba2018-10-10 22:30:12 +0900548 [[fallthrough]];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900549 default:
550 goto fail;
551 }
552 } while (!done);
553 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900554
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900555 [[maybe_unused]] static const int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
556 [[maybe_unused]] char abuf[NI_MAXHOST];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900557 Dprint(((statp->options & RES_DEBUG) &&
558 getnameinfo(nsap, (socklen_t) nsaplen, abuf, sizeof(abuf), NULL, 0, niflags) ==
559 0),
560 (stdout, ";; Querying server (# %d) address = %s\n", ns + 1, abuf));
Bernie Innocenti55864192018-08-30 04:05:20 +0900561
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900562 if (v_circuit) {
563 /* Use VC; at most one attempt per server. */
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900564 attempt = statp->retry;
Bernie Innocenti55864192018-08-30 04:05:20 +0900565
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900566 n = send_vc(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &now, &rcode,
567 &delay);
Bernie Innocenti55864192018-08-30 04:05:20 +0900568
Bernie Innocentif12d5bb2018-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 */
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900574 if (attempt == 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900575 struct __res_sample sample;
576 _res_stats_set_sample(&sample, now, rcode, delay);
577 _resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, ns, &sample,
578 params.max_samples);
579 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900580
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900581 VLOG << "used send_vc " << n;
Bernie Innocenti55864192018-08-30 04:05:20 +0900582
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900583 if (n < 0) goto fail;
584 if (n == 0) goto next_ns;
585 resplen = n;
586 } else {
587 /* Use datagrams. */
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900588 VLOG << "using send_dg";
Bernie Innocenti55864192018-08-30 04:05:20 +0900589
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900590 n = send_dg(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &v_circuit,
591 &gotsomewhere, &now, &rcode, &delay);
Bernie Innocenti55864192018-08-30 04:05:20 +0900592
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900593 /* Only record stats the first time we try a query. See above. */
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900594 if (attempt == 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900595 struct __res_sample sample;
596 _res_stats_set_sample(&sample, now, rcode, delay);
597 _resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, ns, &sample,
598 params.max_samples);
599 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900600
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900601 VLOG << "used send_dg " << n;
Bernie Innocenti55864192018-08-30 04:05:20 +0900602
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900603 if (n < 0) goto fail;
604 if (n == 0) goto next_ns;
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900605 VLOG << "time=" << time(NULL);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900606 if (v_circuit) goto same_ns;
607 resplen = n;
608 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900609
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900610 Dprint((statp->options & RES_DEBUG) ||
611 ((statp->pfcode & RES_PRF_REPLY) && (statp->pfcode & RES_PRF_HEAD1)),
612 (stdout, ";; got answer:\n"));
Bernie Innocenti55864192018-08-30 04:05:20 +0900613
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900614 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
615 (stdout, "%s", ""), ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti55864192018-08-30 04:05:20 +0900616
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900617 if (cache_status == RESOLV_CACHE_NOTFOUND) {
618 _resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
619 }
620 /*
621 * If we have temporarily opened a virtual circuit,
622 * or if we haven't been asked to keep a socket open,
623 * close the socket.
624 */
625 if ((v_circuit && (statp->options & RES_USEVC) == 0U) ||
626 (statp->options & RES_STAYOPEN) == 0U) {
627 res_nclose(statp);
628 }
629 if (statp->rhook) {
630 int done = 0, loops = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900631
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900632 do {
633 res_sendhookact act;
Bernie Innocenti55864192018-08-30 04:05:20 +0900634
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900635 act = (*statp->rhook)(nsap, buf, buflen, ans, anssiz, &resplen);
636 switch (act) {
637 case res_goahead:
638 case res_done:
639 done = 1;
640 break;
641 case res_nextns:
642 res_nclose(statp);
643 goto next_ns;
644 case res_modified:
645 /* give the hook another try */
646 if (++loops < 42) /*doug adams*/
647 break;
Bernie Innocenti8bb94ba2018-10-10 22:30:12 +0900648 [[fallthrough]];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900649 case res_error:
Bernie Innocenti8bb94ba2018-10-10 22:30:12 +0900650 [[fallthrough]];
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900651 default:
652 goto fail;
653 }
654 } while (!done);
655 }
656 return (resplen);
657 next_ns:;
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900658 } // for each ns
659 } // for each retry
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900660 res_nclose(statp);
661 if (!v_circuit) {
662 if (!gotsomewhere)
663 errno = ECONNREFUSED; /* no nameservers found */
664 else
665 errno = ETIMEDOUT; /* no answer obtained */
666 } else
667 errno = terrno;
Bernie Innocenti55864192018-08-30 04:05:20 +0900668
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900669 _resolv_cache_query_failed(statp->netid, buf, buflen);
Bernie Innocenti55864192018-08-30 04:05:20 +0900670
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900671 return (-1);
672fail:
Bernie Innocenti55864192018-08-30 04:05:20 +0900673
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900674 _resolv_cache_query_failed(statp->netid, buf, buflen);
675 res_nclose(statp);
676 return (-1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900677}
678
679/* Private */
680
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900681static int get_salen(const struct sockaddr* sa) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900682 if (sa->sa_family == AF_INET)
683 return (sizeof(struct sockaddr_in));
684 else if (sa->sa_family == AF_INET6)
685 return (sizeof(struct sockaddr_in6));
686 else
687 return (0); /* unknown, die on connect */
Bernie Innocenti55864192018-08-30 04:05:20 +0900688}
689
690/*
691 * pick appropriate nsaddr_list for use. see res_init() for initialization.
692 */
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900693static struct sockaddr* get_nsaddr(res_state statp, size_t n) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900694 if (!statp->nsaddr_list[n].sin_family && EXT(statp).ext) {
695 /*
696 * - EXT(statp).ext->nsaddrs[n] holds an address that is larger
697 * than struct sockaddr, and
698 * - user code did not update statp->nsaddr_list[n].
699 */
700 return (struct sockaddr*) (void*) &EXT(statp).ext->nsaddrs[n];
701 } else {
702 /*
703 * - user code updated statp->nsaddr_list[n], or
704 * - statp->nsaddr_list[n] has the same content as
705 * EXT(statp).ext->nsaddrs[n].
706 */
707 return (struct sockaddr*) (void*) &statp->nsaddr_list[n];
708 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900709}
710
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900711static struct timespec get_timeout(const res_state statp, const struct __res_params* params,
712 const int ns) {
713 int msec;
714 if (params->base_timeout_msec != 0) {
715 // TODO: scale the timeout by retry attempt and maybe number of servers
716 msec = params->base_timeout_msec;
717 } else {
718 // Legacy algorithm which scales the timeout by nameserver number.
719 // For instance, with 4 nameservers: 5s, 2.5s, 5s, 10s
720 // This has no effect with 1 or 2 nameservers
721 msec = (statp->retrans * 1000) << ns;
722 if (ns > 0) {
723 msec /= statp->nscount;
724 }
725 if (msec < 1000) {
726 msec = 1000; // Use at least 100ms
727 }
728 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900729 VLOG << "using timeout of " << msec << " msec";
Bernie Innocenti55864192018-08-30 04:05:20 +0900730
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900731 struct timespec result;
732 result.tv_sec = msec / 1000;
733 result.tv_nsec = (msec % 1000) * 1000000;
734 return result;
Bernie Innocenti55864192018-08-30 04:05:20 +0900735}
736
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900737static int send_vc(res_state statp, struct __res_params* params, const u_char* buf, int buflen,
738 u_char* ans, int anssiz, int* terrno, int ns, time_t* at, int* rcode,
739 int* delay) {
740 *at = time(NULL);
741 *rcode = RCODE_INTERNAL_ERROR;
742 *delay = 0;
743 const HEADER* hp = (const HEADER*) (const void*) buf;
744 HEADER* anhp = (HEADER*) (void*) ans;
745 struct sockaddr* nsap;
746 int nsaplen;
747 int truncating, connreset, resplen, n;
748 struct iovec iov[2];
749 u_short len;
750 u_char* cp;
Bernie Innocenti55864192018-08-30 04:05:20 +0900751
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900752 VLOG << "using send_vc";
Bernie Innocenti55864192018-08-30 04:05:20 +0900753
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900754 nsap = get_nsaddr(statp, (size_t) ns);
755 nsaplen = get_salen(nsap);
Bernie Innocenti55864192018-08-30 04:05:20 +0900756
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900757 connreset = 0;
758same_ns:
759 truncating = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900760
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900761 struct timespec now = evNowTime();
Bernie Innocenti55864192018-08-30 04:05:20 +0900762
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900763 /* Are we still talking to whom we want to talk to? */
764 if (statp->_vcsock >= 0 && (statp->_flags & RES_F_VC) != 0) {
765 struct sockaddr_storage peer;
766 socklen_t size = sizeof peer;
767 unsigned old_mark;
768 socklen_t mark_size = sizeof(old_mark);
769 if (getpeername(statp->_vcsock, (struct sockaddr*) (void*) &peer, &size) < 0 ||
770 !sock_eq((struct sockaddr*) (void*) &peer, nsap) ||
771 getsockopt(statp->_vcsock, SOL_SOCKET, SO_MARK, &old_mark, &mark_size) < 0 ||
772 old_mark != statp->_mark) {
773 res_nclose(statp);
774 statp->_flags &= ~RES_F_VC;
775 }
776 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900777
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900778 if (statp->_vcsock < 0 || (statp->_flags & RES_F_VC) == 0) {
779 if (statp->_vcsock >= 0) res_nclose(statp);
Bernie Innocenti55864192018-08-30 04:05:20 +0900780
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900781 statp->_vcsock = socket(nsap->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0);
782 if (statp->_vcsock < 0) {
783 switch (errno) {
784 case EPROTONOSUPPORT:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900785 case EPFNOSUPPORT:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900786 case EAFNOSUPPORT:
787 Perror(statp, stderr, "socket(vc)", errno);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900788 return 0;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900789 default:
790 *terrno = errno;
791 Perror(statp, stderr, "socket(vc)", errno);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900792 return -1;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900793 }
794 }
795 fchown(statp->_vcsock, AID_DNS, -1);
796 if (statp->_mark != MARK_UNSET) {
797 if (setsockopt(statp->_vcsock, SOL_SOCKET, SO_MARK, &statp->_mark,
798 sizeof(statp->_mark)) < 0) {
799 *terrno = errno;
800 Perror(statp, stderr, "setsockopt", errno);
801 return -1;
802 }
803 }
804 errno = 0;
805 if (random_bind(statp->_vcsock, nsap->sa_family) < 0) {
806 *terrno = errno;
807 Aerror(statp, stderr, "bind/vc", errno, nsap, nsaplen);
808 res_nclose(statp);
809 return (0);
810 }
811 if (connect_with_timeout(statp->_vcsock, nsap, (socklen_t) nsaplen,
812 get_timeout(statp, params, ns)) < 0) {
813 *terrno = errno;
814 Aerror(statp, stderr, "connect/vc", errno, nsap, nsaplen);
815 res_nclose(statp);
816 /*
817 * The way connect_with_timeout() is implemented prevents us from reliably
818 * determining whether this was really a timeout or e.g. ECONNREFUSED. Since
819 * currently both cases are handled in the same way, there is no need to
820 * change this (yet). If we ever need to reliably distinguish between these
821 * cases, both connect_with_timeout() and retrying_poll() need to be
822 * modified, though.
823 */
824 *rcode = RCODE_TIMEOUT;
825 return (0);
826 }
827 statp->_flags |= RES_F_VC;
828 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900829
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900830 /*
831 * Send length & message
832 */
833 ns_put16((u_short) buflen, (u_char*) (void*) &len);
834 iov[0] = evConsIovec(&len, INT16SZ);
Bernie Innocenti1f4a9fd2018-09-07 21:10:25 +0900835 iov[1] = evConsIovec((void*) buf, (size_t) buflen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900836 if (writev(statp->_vcsock, iov, 2) != (INT16SZ + buflen)) {
837 *terrno = errno;
838 Perror(statp, stderr, "write failed", errno);
839 res_nclose(statp);
840 return (0);
841 }
842 /*
843 * Receive length & response
844 */
845read_len:
846 cp = ans;
847 len = INT16SZ;
848 while ((n = read(statp->_vcsock, (char*) cp, (size_t) len)) > 0) {
849 cp += n;
850 if ((len -= n) == 0) break;
851 }
852 if (n <= 0) {
853 *terrno = errno;
854 Perror(statp, stderr, "read failed", errno);
855 res_nclose(statp);
856 /*
857 * A long running process might get its TCP
858 * connection reset if the remote server was
859 * restarted. Requery the server instead of
860 * trying a new one. When there is only one
861 * server, this means that a query might work
862 * instead of failing. We only allow one reset
863 * per query to prevent looping.
864 */
865 if (*terrno == ECONNRESET && !connreset) {
866 connreset = 1;
867 res_nclose(statp);
868 goto same_ns;
869 }
870 res_nclose(statp);
871 return (0);
872 }
873 resplen = ns_get16(ans);
874 if (resplen > anssiz) {
875 Dprint(statp->options & RES_DEBUG, (stdout, ";; response truncated\n"));
876 truncating = 1;
877 len = anssiz;
878 } else
879 len = resplen;
880 if (len < HFIXEDSZ) {
881 /*
882 * Undersized message.
883 */
884 Dprint(statp->options & RES_DEBUG, (stdout, ";; undersized: %d\n", len));
885 *terrno = EMSGSIZE;
886 res_nclose(statp);
887 return (0);
888 }
889 cp = ans;
890 while (len != 0 && (n = read(statp->_vcsock, (char*) cp, (size_t) len)) > 0) {
891 cp += n;
892 len -= n;
893 }
894 if (n <= 0) {
895 *terrno = errno;
896 Perror(statp, stderr, "read(vc)", errno);
897 res_nclose(statp);
898 return (0);
899 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900900
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900901 if (truncating) {
902 /*
903 * Flush rest of answer so connection stays in synch.
904 */
905 anhp->tc = 1;
906 len = resplen - anssiz;
907 while (len != 0) {
908 char junk[PACKETSZ];
Bernie Innocenti55864192018-08-30 04:05:20 +0900909
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900910 n = read(statp->_vcsock, junk, (len > sizeof junk) ? sizeof junk : len);
911 if (n > 0)
912 len -= n;
913 else
914 break;
915 }
916 }
917 /*
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900918 * If the calling application has bailed out of
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900919 * a previous call and failed to arrange to have
920 * the circuit closed or the server has got
921 * itself confused, then drop the packet and
922 * wait for the correct one.
923 */
924 if (hp->id != anhp->id) {
925 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
926 (stdout, ";; old answer (unexpected):\n"), ans,
927 (resplen > anssiz) ? anssiz : resplen);
928 goto read_len;
929 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900930
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900931 /*
932 * All is well, or the error is fatal. Signal that the
933 * next nameserver ought not be tried.
934 */
935 if (resplen > 0) {
936 struct timespec done = evNowTime();
937 *delay = _res_stats_calculate_rtt(&done, &now);
938 *rcode = anhp->rcode;
939 }
940 return (resplen);
Bernie Innocenti55864192018-08-30 04:05:20 +0900941}
942
943/* return -1 on error (errno set), 0 on success */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900944static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
945 const struct timespec timeout) {
946 int res, origflags;
Bernie Innocenti55864192018-08-30 04:05:20 +0900947
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900948 origflags = fcntl(sock, F_GETFL, 0);
949 fcntl(sock, F_SETFL, origflags | O_NONBLOCK);
Bernie Innocenti55864192018-08-30 04:05:20 +0900950
Bernie Innocentif89b3512018-08-30 07:34:37 +0900951 res = connect(sock, nsap, salen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900952 if (res < 0 && errno != EINPROGRESS) {
953 res = -1;
954 goto done;
955 }
956 if (res != 0) {
957 struct timespec now = evNowTime();
958 struct timespec finish = evAddTime(now, timeout);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900959 VLOG << sock << " send_vc";
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900960 res = retrying_poll(sock, POLLIN | POLLOUT, &finish);
961 if (res <= 0) {
962 res = -1;
963 }
964 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900965done:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900966 fcntl(sock, F_SETFL, origflags);
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900967 VLOG << sock << " connect_with_const timeout returning " << res;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900968 return res;
Bernie Innocenti55864192018-08-30 04:05:20 +0900969}
970
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900971static int retrying_poll(const int sock, const short events, const struct timespec* finish) {
972 struct timespec now, timeout;
Bernie Innocenti55864192018-08-30 04:05:20 +0900973
974retry:
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900975 VLOG << " " << sock << " retrying_poll";
Bernie Innocenti55864192018-08-30 04:05:20 +0900976
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900977 now = evNowTime();
978 if (evCmpTime(*finish, now) > 0)
979 timeout = evSubTime(*finish, now);
980 else
981 timeout = evConsTime(0L, 0L);
982 struct pollfd fds = {.fd = sock, .events = events};
983 int n = ppoll(&fds, 1, &timeout, /*sigmask=*/NULL);
984 if (n == 0) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900985 VLOG << " " << sock << "retrying_poll timeout";
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900986 errno = ETIMEDOUT;
987 return 0;
988 }
989 if (n < 0) {
990 if (errno == EINTR) goto retry;
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900991 VLOG << " " << sock << " retrying_poll got error " << n;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900992 return n;
993 }
994 if (fds.revents & (POLLIN | POLLOUT | POLLERR)) {
995 int error;
996 socklen_t len = sizeof(error);
997 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error) {
998 errno = error;
Bernie Innocentie9ba09c2018-09-12 23:20:10 +0900999 VLOG << " " << sock << " retrying_poll dot error2 " << errno;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001000 return -1;
1001 }
1002 }
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001003 VLOG << " " << sock << " retrying_poll returning " << n;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001004 return n;
Bernie Innocenti55864192018-08-30 04:05:20 +09001005}
1006
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001007static int send_dg(res_state statp, struct __res_params* params, const u_char* buf, int buflen,
1008 u_char* ans, int anssiz, int* terrno, int ns, int* v_circuit, int* gotsomewhere,
1009 time_t* at, int* rcode, int* delay) {
1010 *at = time(NULL);
1011 *rcode = RCODE_INTERNAL_ERROR;
1012 *delay = 0;
1013 const HEADER* hp = (const HEADER*) (const void*) buf;
1014 HEADER* anhp = (HEADER*) (void*) ans;
1015 const struct sockaddr* nsap;
1016 int nsaplen;
1017 struct timespec now, timeout, finish, done;
1018 struct sockaddr_storage from;
1019 socklen_t fromlen;
1020 int resplen, n, s;
Bernie Innocenti55864192018-08-30 04:05:20 +09001021
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001022 nsap = get_nsaddr(statp, (size_t) ns);
1023 nsaplen = get_salen(nsap);
1024 if (EXT(statp).nssocks[ns] == -1) {
1025 EXT(statp).nssocks[ns] = socket(nsap->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
1026 if (EXT(statp).nssocks[ns] < 0) {
1027 switch (errno) {
1028 case EPROTONOSUPPORT:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001029 case EPFNOSUPPORT:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001030 case EAFNOSUPPORT:
1031 Perror(statp, stderr, "socket(dg)", errno);
1032 return (0);
1033 default:
1034 *terrno = errno;
1035 Perror(statp, stderr, "socket(dg)", errno);
1036 return (-1);
1037 }
1038 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001039
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001040 fchown(EXT(statp).nssocks[ns], AID_DNS, -1);
1041 if (statp->_mark != MARK_UNSET) {
1042 if (setsockopt(EXT(statp).nssocks[ns], SOL_SOCKET, SO_MARK, &(statp->_mark),
1043 sizeof(statp->_mark)) < 0) {
1044 res_nclose(statp);
1045 return -1;
1046 }
1047 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001048#ifndef CANNOT_CONNECT_DGRAM
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001049 /*
1050 * On a 4.3BSD+ machine (client and server,
1051 * actually), sending to a nameserver datagram
1052 * port with no nameserver will cause an
1053 * ICMP port unreachable message to be returned.
1054 * If our datagram socket is "connected" to the
1055 * server, we get an ECONNREFUSED error on the next
1056 * socket operation, and select returns if the
1057 * error message is received. We can thus detect
1058 * the absence of a nameserver without timing out.
1059 */
1060 if (random_bind(EXT(statp).nssocks[ns], nsap->sa_family) < 0) {
1061 Aerror(statp, stderr, "bind(dg)", errno, nsap, nsaplen);
1062 res_nclose(statp);
1063 return (0);
1064 }
Bernie Innocentif89b3512018-08-30 07:34:37 +09001065 if (connect(EXT(statp).nssocks[ns], nsap, (socklen_t) nsaplen) < 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001066 Aerror(statp, stderr, "connect(dg)", errno, nsap, nsaplen);
1067 res_nclose(statp);
1068 return (0);
1069 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001070#endif /* !CANNOT_CONNECT_DGRAM */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001071 Dprint(statp->options & RES_DEBUG, (stdout, ";; new DG socket\n"))
1072 }
1073 s = EXT(statp).nssocks[ns];
Bernie Innocenti55864192018-08-30 04:05:20 +09001074#ifndef CANNOT_CONNECT_DGRAM
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001075 if (send(s, (const char*) buf, (size_t) buflen, 0) != buflen) {
1076 Perror(statp, stderr, "send", errno);
1077 res_nclose(statp);
1078 return (0);
1079 }
1080#else /* !CANNOT_CONNECT_DGRAM */
1081 if (sendto(s, (const char*) buf, buflen, 0, nsap, nsaplen) != buflen) {
1082 Aerror(statp, stderr, "sendto", errno, nsap, nsaplen);
1083 res_nclose(statp);
1084 return (0);
1085 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001086#endif /* !CANNOT_CONNECT_DGRAM */
1087
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001088 /*
1089 * Wait for reply.
1090 */
1091 timeout = get_timeout(statp, params, ns);
1092 now = evNowTime();
1093 finish = evAddTime(now, timeout);
Bernie Innocenti55864192018-08-30 04:05:20 +09001094retry:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001095 n = retrying_poll(s, POLLIN, &finish);
Bernie Innocenti55864192018-08-30 04:05:20 +09001096
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001097 if (n == 0) {
1098 *rcode = RCODE_TIMEOUT;
1099 Dprint(statp->options & RES_DEBUG, (stdout, ";; timeout\n"));
1100 *gotsomewhere = 1;
1101 return (0);
1102 }
1103 if (n < 0) {
1104 Perror(statp, stderr, "poll", errno);
1105 res_nclose(statp);
1106 return (0);
1107 }
1108 errno = 0;
1109 fromlen = sizeof(from);
1110 resplen = recvfrom(s, (char*) ans, (size_t) anssiz, 0, (struct sockaddr*) (void*) &from,
1111 &fromlen);
1112 if (resplen <= 0) {
1113 Perror(statp, stderr, "recvfrom", errno);
1114 res_nclose(statp);
1115 return (0);
1116 }
1117 *gotsomewhere = 1;
1118 if (resplen < HFIXEDSZ) {
1119 /*
1120 * Undersized message.
1121 */
1122 Dprint(statp->options & RES_DEBUG, (stdout, ";; undersized: %d\n", resplen));
1123 *terrno = EMSGSIZE;
1124 res_nclose(statp);
1125 return (0);
1126 }
1127 if (hp->id != anhp->id) {
1128 /*
1129 * response from old query, ignore it.
1130 * XXX - potential security hazard could
1131 * be detected here.
1132 */
1133 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
1134 (stdout, ";; old answer:\n"), ans, (resplen > anssiz) ? anssiz : resplen);
1135 goto retry;
1136 }
1137 if (!(statp->options & RES_INSECURE1) &&
1138 !res_ourserver_p(statp, (struct sockaddr*) (void*) &from)) {
1139 /*
1140 * response from wrong server? ignore it.
1141 * XXX - potential security hazard could
1142 * be detected here.
1143 */
1144 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
1145 (stdout, ";; not our server:\n"), ans, (resplen > anssiz) ? anssiz : resplen);
1146 goto retry;
1147 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001148 if (anhp->rcode == FORMERR && (statp->options & RES_USE_EDNS0) != 0U) {
1149 /*
1150 * Do not retry if the server do not understand EDNS0.
1151 * The case has to be captured here, as FORMERR packet do not
1152 * carry query section, hence res_queriesmatch() returns 0.
1153 */
1154 DprintQ(statp->options & RES_DEBUG, (stdout, "server rejected query with EDNS0:\n"), ans,
1155 (resplen > anssiz) ? anssiz : resplen);
1156 /* record the error */
1157 statp->_flags |= RES_F_EDNS0ERR;
1158 res_nclose(statp);
1159 return (0);
1160 }
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001161 if (!(statp->options & RES_INSECURE2) &&
1162 !res_queriesmatch(buf, buf + buflen, ans, ans + anssiz)) {
1163 /*
1164 * response contains wrong query? ignore it.
1165 * XXX - potential security hazard could
1166 * be detected here.
1167 */
1168 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
1169 (stdout, ";; wrong query name:\n"), ans, (resplen > anssiz) ? anssiz : resplen);
1170 goto retry;
1171 ;
1172 }
1173 done = evNowTime();
1174 *delay = _res_stats_calculate_rtt(&done, &now);
1175 if (anhp->rcode == SERVFAIL || anhp->rcode == NOTIMP || anhp->rcode == REFUSED) {
1176 DprintQ(statp->options & RES_DEBUG, (stdout, "server rejected query:\n"), ans,
1177 (resplen > anssiz) ? anssiz : resplen);
1178 res_nclose(statp);
1179 /* don't retry if called from dig */
1180 if (!statp->pfcode) {
1181 *rcode = anhp->rcode;
1182 return (0);
1183 }
1184 }
1185 if (!(statp->options & RES_IGNTC) && anhp->tc) {
1186 /*
1187 * To get the rest of answer,
1188 * use TCP with same server.
1189 */
1190 Dprint(statp->options & RES_DEBUG, (stdout, ";; truncated answer\n"));
1191 *v_circuit = 1;
1192 res_nclose(statp);
1193 return (1);
1194 }
1195 /*
1196 * All is well, or the error is fatal. Signal that the
1197 * next nameserver ought not be tried.
1198 */
1199 if (resplen > 0) {
1200 *rcode = anhp->rcode;
1201 }
1202 return (resplen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001203}
1204
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001205static void Aerror(const res_state statp, FILE* file, const char* string, int error,
1206 const struct sockaddr* address, int alen) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001207 if (!kVerboseLogging) return;
1208
1209 const int save = errno;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001210 char hbuf[NI_MAXHOST];
1211 char sbuf[NI_MAXSERV];
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001212 constexpr int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
Bernie Innocenti55864192018-08-30 04:05:20 +09001213
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001214 if ((statp->options & RES_DEBUG) != 0U) {
1215 if (getnameinfo(address, (socklen_t) alen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
1216 niflags)) {
1217 strncpy(hbuf, "?", sizeof(hbuf) - 1);
1218 hbuf[sizeof(hbuf) - 1] = '\0';
1219 strncpy(sbuf, "?", sizeof(sbuf) - 1);
1220 sbuf[sizeof(sbuf) - 1] = '\0';
1221 }
1222 fprintf(file, "res_send: %s ([%s].%s): %s\n", string, hbuf, sbuf, strerror(error));
1223 }
1224 errno = save;
Bernie Innocenti55864192018-08-30 04:05:20 +09001225}
1226
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001227static void Perror(const res_state statp, FILE* file, const char* string, int error) {
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001228 if (!kVerboseLogging) return;
Bernie Innocenti55864192018-08-30 04:05:20 +09001229
Bernie Innocentie9ba09c2018-09-12 23:20:10 +09001230 const int save = errno;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001231 if ((statp->options & RES_DEBUG) != 0U)
1232 fprintf(file, "res_send: %s: %s\n", string, strerror(error));
1233 errno = save;
Bernie Innocenti55864192018-08-30 04:05:20 +09001234}
1235
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001236static int sock_eq(struct sockaddr* a, struct sockaddr* b) {
1237 struct sockaddr_in *a4, *b4;
1238 struct sockaddr_in6 *a6, *b6;
Bernie Innocenti55864192018-08-30 04:05:20 +09001239
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001240 if (a->sa_family != b->sa_family) return 0;
1241 switch (a->sa_family) {
1242 case AF_INET:
1243 a4 = (struct sockaddr_in*) (void*) a;
1244 b4 = (struct sockaddr_in*) (void*) b;
1245 return a4->sin_port == b4->sin_port && a4->sin_addr.s_addr == b4->sin_addr.s_addr;
1246 case AF_INET6:
1247 a6 = (struct sockaddr_in6*) (void*) a;
1248 b6 = (struct sockaddr_in6*) (void*) b;
1249 return a6->sin6_port == b6->sin6_port &&
Bernie Innocenti55864192018-08-30 04:05:20 +09001250#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001251 a6->sin6_scope_id == b6->sin6_scope_id &&
Bernie Innocenti55864192018-08-30 04:05:20 +09001252#endif
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001253 IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
1254 default:
1255 return 0;
1256 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001257}