blob: ad655c9dc411848bf38f3fb55e94fcb852f9b916 [file] [log] [blame]
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001/* $NetBSD: res_send.c,v 1.9 2006/01/24 17:41:25 christos Exp $ */
2
3/*
4 * Copyright (c) 1985, 1989, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. All advertising materials mentioning features or use of this software
16 * must display the following acknowledgement:
17 * This product includes software developed by the University of
18 * California, Berkeley and its contributors.
19 * 4. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 */
35
36/*
37 * Portions Copyright (c) 1993 by Digital Equipment Corporation.
38 *
39 * Permission to use, copy, modify, and distribute this software for any
40 * purpose with or without fee is hereby granted, provided that the above
41 * copyright notice and this permission notice appear in all copies, and that
42 * the name of Digital Equipment Corporation not be used in advertising or
43 * publicity pertaining to distribution of the document or software without
44 * specific, written prior permission.
45 *
46 * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
47 * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
48 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
49 * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
50 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
51 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
52 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
53 * SOFTWARE.
54 */
55
56/*
57 * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
58 * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
59 *
60 * Permission to use, copy, modify, and distribute this software for any
61 * purpose with or without fee is hereby granted, provided that the above
62 * copyright notice and this permission notice appear in all copies.
63 *
64 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
65 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
66 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR
67 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
68 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
69 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
70 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
71 */
72
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090073/*
74 * Send query to name server and wait for reply.
75 */
76
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +090077constexpr bool kVerboseLogging = false;
78#define LOG_TAG "res_send"
79
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090080#include <sys/param.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090081#include <sys/socket.h>
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090082#include <sys/time.h>
83#include <sys/types.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090084#include <sys/uio.h>
85
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090086#include <arpa/inet.h>
Bernie Innocenti8ad893f2018-08-31 14:09:46 +090087#include <arpa/nameser.h>
88#include <netinet/in.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090089
90#include <errno.h>
91#include <fcntl.h>
92#include <netdb.h>
93#include <poll.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +090094#include <signal.h>
95#include <stdio.h>
96#include <stdlib.h>
97#include <string.h>
98#include <time.h>
99#include <unistd.h>
100
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900101#include <android-base/logging.h>
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900102
Bernie Innocentif33a63f2018-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 Innocenti9f05f5e2018-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 Innocenti318ed2d2018-08-30 04:05:20 +0900118#endif
Bernie Innocentif33a63f2018-08-30 12:04:03 +0900119
Bernie Innocenti9f05f5e2018-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 Innocenti318ed2d2018-08-30 04:05:20 +0900137
Bernie Innocenti9c575932018-09-07 21:10:25 +0900138static int get_salen(const struct sockaddr*);
139static struct sockaddr* get_nsaddr(res_state, size_t);
Bernie Innocenti8ad893f2018-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 Innocenti8ad893f2018-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 Innocenti318ed2d2018-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 Innocenti8ad893f2018-08-31 14:09:46 +0900153 struct sockaddr sa;
154 struct sockaddr_in sin;
155 struct sockaddr_in6 sin6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900156} _sockaddr_union;
157
Bernie Innocentiafaacf72018-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 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
Bernie Innocenti8ad893f2018-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 Innocenti318ed2d2018-08-30 04:05:20 +0900228
229 /* clear all, this also sets the IP4/6 address to 'any' */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900230 memset(&u, 0, sizeof u);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900231
232 switch (family) {
233 case AF_INET:
234 u.sin.sin_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900235 slen = sizeof u.sin;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900236 break;
237 case AF_INET6:
238 u.sin6.sin6_family = family;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900239 slen = sizeof u.sin6;
Bernie Innocenti318ed2d2018-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 Innocenti8ad893f2018-08-31 14:09:46 +0900249 int port = 1025 + (res_randomid() % (65535 - 1025));
Bernie Innocenti318ed2d2018-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 Innocenti8ad893f2018-08-31 14:09:46 +0900255 if (!bind(s, &u.sa, slen)) return 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900256 }
257
Bernie Innocenti9c575932018-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 Innocenti318ed2d2018-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 Innocenti8ad893f2018-08-31 14:09:46 +0900265 return bind(s, &u.sa, slen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900266}
267/* BIONIC-END */
268
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900269/* Public. */
270
271/* int
272 * res_isourserver(ina)
273 * looks up "ina" in _res.ns_addr_list[]
274 * returns:
275 * 0 : not found
276 * >0 : found
277 * author:
278 * paul vixie, 29may94
279 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900280__LIBC_HIDDEN__ int res_ourserver_p(const res_state statp, const struct sockaddr* sa) {
281 const struct sockaddr_in *inp, *srv;
282 const struct sockaddr_in6 *in6p, *srv6;
283 int ns;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900284
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900285 switch (sa->sa_family) {
286 case AF_INET:
287 inp = (const struct sockaddr_in*) (const void*) sa;
288 for (ns = 0; ns < statp->nscount; ns++) {
289 srv = (struct sockaddr_in*) (void*) get_nsaddr(statp, (size_t) ns);
290 if (srv->sin_family == inp->sin_family && srv->sin_port == inp->sin_port &&
291 (srv->sin_addr.s_addr == INADDR_ANY ||
292 srv->sin_addr.s_addr == inp->sin_addr.s_addr))
293 return (1);
294 }
295 break;
296 case AF_INET6:
297 if (EXT(statp).ext == NULL) break;
298 in6p = (const struct sockaddr_in6*) (const void*) sa;
299 for (ns = 0; ns < statp->nscount; ns++) {
300 srv6 = (struct sockaddr_in6*) (void*) get_nsaddr(statp, (size_t) ns);
301 if (srv6->sin6_family == in6p->sin6_family && srv6->sin6_port == in6p->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900302#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900303 (srv6->sin6_scope_id == 0 || srv6->sin6_scope_id == in6p->sin6_scope_id) &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900304#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900305 (IN6_IS_ADDR_UNSPECIFIED(&srv6->sin6_addr) ||
306 IN6_ARE_ADDR_EQUAL(&srv6->sin6_addr, &in6p->sin6_addr)))
307 return (1);
308 }
309 break;
310 default:
311 break;
312 }
313 return (0);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900314}
315
316/* int
Bernie Innocenti9c575932018-09-07 21:10:25 +0900317 * res_nameinquery(name, type, cl, buf, eom)
318 * look for (name, type, cl) in the query section of packet (buf, eom)
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900319 * requires:
320 * buf + HFIXEDSZ <= eom
321 * returns:
322 * -1 : format error
323 * 0 : not found
324 * >0 : found
325 * author:
326 * paul vixie, 29may94
327 */
Bernie Innocenti9c575932018-09-07 21:10:25 +0900328int res_nameinquery(const char* name, int type, int cl, const u_char* buf, const u_char* eom) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900329 const u_char* cp = buf + HFIXEDSZ;
330 int qdcount = ntohs(((const HEADER*) (const void*) buf)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900331
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900332 while (qdcount-- > 0) {
333 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900334 int n = dn_expand(buf, eom, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900335 if (n < 0) return (-1);
336 cp += n;
337 if (cp + 2 * INT16SZ > eom) return (-1);
Bernie Innocenti9c575932018-09-07 21:10:25 +0900338 int ttype = ns_get16(cp);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900339 cp += INT16SZ;
Bernie Innocenti9c575932018-09-07 21:10:25 +0900340 int tclass = ns_get16(cp);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900341 cp += INT16SZ;
Bernie Innocenti9c575932018-09-07 21:10:25 +0900342 if (ttype == type && tclass == cl && ns_samename(tname, name) == 1) return (1);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900343 }
344 return (0);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900345}
346
347/* int
348 * res_queriesmatch(buf1, eom1, buf2, eom2)
349 * is there a 1:1 mapping of (name,type,class)
350 * in (buf1,eom1) and (buf2,eom2)?
351 * returns:
352 * -1 : format error
353 * 0 : not a 1:1 mapping
354 * >0 : is a 1:1 mapping
355 * author:
356 * paul vixie, 29may94
357 */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900358int res_queriesmatch(const u_char* buf1, const u_char* eom1, const u_char* buf2,
359 const u_char* eom2) {
360 const u_char* cp = buf1 + HFIXEDSZ;
361 int qdcount = ntohs(((const HEADER*) (const void*) buf1)->qdcount);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900362
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900363 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2) return (-1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900364
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900365 /*
366 * Only header section present in replies to
367 * dynamic update packets.
368 */
369 if ((((const HEADER*) (const void*) buf1)->opcode == ns_o_update) &&
370 (((const HEADER*) (const void*) buf2)->opcode == ns_o_update))
371 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900372
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900373 if (qdcount != ntohs(((const HEADER*) (const void*) buf2)->qdcount)) return (0);
374 while (qdcount-- > 0) {
375 char tname[MAXDNAME + 1];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900376 int n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900377 if (n < 0) return (-1);
378 cp += n;
379 if (cp + 2 * INT16SZ > eom1) return (-1);
Bernie Innocenti9c575932018-09-07 21:10:25 +0900380 int ttype = ns_get16(cp);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900381 cp += INT16SZ;
Bernie Innocenti9c575932018-09-07 21:10:25 +0900382 int tclass = ns_get16(cp);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900383 cp += INT16SZ;
384 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2)) return (0);
385 }
386 return (1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900387}
388
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900389int res_nsend(res_state statp, const u_char* buf, int buflen, u_char* ans, int anssiz) {
Bernie Innocenti9c575932018-09-07 21:10:25 +0900390 int gotsomewhere, terrno, v_circuit, resplen, n;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900391 ResolvCacheStatus cache_status = RESOLV_CACHE_UNSUPPORTED;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900392
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900393 if (anssiz < HFIXEDSZ) {
394 errno = EINVAL;
395 return (-1);
396 }
397 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_QUERY),
398 (stdout, ";; res_send()\n"), buf, buflen);
399 v_circuit = (statp->options & RES_USEVC) || buflen > PACKETSZ;
400 gotsomewhere = 0;
401 terrno = ETIMEDOUT;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900402
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900403 int anslen = 0;
404 cache_status = _resolv_cache_lookup(statp->netid, buf, buflen, ans, anssiz, &anslen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900405
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900406 if (cache_status == RESOLV_CACHE_FOUND) {
407 return anslen;
408 } else if (cache_status != RESOLV_CACHE_UNSUPPORTED) {
409 // had a cache miss for a known network, so populate the thread private
410 // data so the normal resolve path can do its thing
411 _resolv_populate_res_for_net(statp);
412 }
413 if (statp->nscount == 0) {
414 // We have no nameservers configured, so there's no point trying.
415 // Tell the cache the query failed, or any retries and anyone else asking the same
416 // question will block for PENDING_REQUEST_TIMEOUT seconds instead of failing fast.
417 _resolv_cache_query_failed(statp->netid, buf, buflen);
418 errno = ESRCH;
419 return (-1);
420 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900421
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900422 /*
423 * If the ns_addr_list in the resolver context has changed, then
424 * invalidate our cached copy and the associated timing data.
425 */
426 if (EXT(statp).nscount != 0) {
427 int needclose = 0;
428 struct sockaddr_storage peer;
429 socklen_t peerlen;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900430
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900431 if (EXT(statp).nscount != statp->nscount) {
432 needclose++;
433 } else {
Bernie Innocenti9c575932018-09-07 21:10:25 +0900434 for (int ns = 0; ns < statp->nscount; ns++) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900435 if (statp->nsaddr_list[ns].sin_family &&
436 !sock_eq((struct sockaddr*) (void*) &statp->nsaddr_list[ns],
437 (struct sockaddr*) (void*) &EXT(statp).ext->nsaddrs[ns])) {
438 needclose++;
439 break;
440 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900441
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900442 if (EXT(statp).nssocks[ns] == -1) continue;
443 peerlen = sizeof(peer);
444 if (getpeername(EXT(statp).nssocks[ns], (struct sockaddr*) (void*) &peer,
445 &peerlen) < 0) {
446 needclose++;
447 break;
448 }
449 if (!sock_eq((struct sockaddr*) (void*) &peer, get_nsaddr(statp, (size_t) ns))) {
450 needclose++;
451 break;
452 }
453 }
454 }
455 if (needclose) {
456 res_nclose(statp);
457 EXT(statp).nscount = 0;
458 }
459 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900460
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900461 /*
462 * Maybe initialize our private copy of the ns_addr_list.
463 */
464 if (EXT(statp).nscount == 0) {
Bernie Innocenti9c575932018-09-07 21:10:25 +0900465 for (int ns = 0; ns < statp->nscount; ns++) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900466 EXT(statp).nstimes[ns] = RES_MAXTIME;
467 EXT(statp).nssocks[ns] = -1;
468 if (!statp->nsaddr_list[ns].sin_family) continue;
469 EXT(statp).ext->nsaddrs[ns].sin = statp->nsaddr_list[ns];
470 }
471 EXT(statp).nscount = statp->nscount;
472 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900473
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900474 /*
475 * Some resolvers want to even out the load on their nameservers.
476 * Note that RES_BLAST overrides RES_ROTATE.
477 */
478 if ((statp->options & RES_ROTATE) != 0U && (statp->options & RES_BLAST) == 0U) {
479 union res_sockaddr_union inu;
480 struct sockaddr_in ina;
481 int lastns = statp->nscount - 1;
482 int fd;
483 u_int16_t nstime;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900484
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900485 if (EXT(statp).ext != NULL) inu = EXT(statp).ext->nsaddrs[0];
486 ina = statp->nsaddr_list[0];
487 fd = EXT(statp).nssocks[0];
488 nstime = EXT(statp).nstimes[0];
Bernie Innocenti9c575932018-09-07 21:10:25 +0900489 for (int ns = 0; ns < lastns; ns++) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900490 if (EXT(statp).ext != NULL)
491 EXT(statp).ext->nsaddrs[ns] = EXT(statp).ext->nsaddrs[ns + 1];
492 statp->nsaddr_list[ns] = statp->nsaddr_list[ns + 1];
493 EXT(statp).nssocks[ns] = EXT(statp).nssocks[ns + 1];
494 EXT(statp).nstimes[ns] = EXT(statp).nstimes[ns + 1];
495 }
496 if (EXT(statp).ext != NULL) EXT(statp).ext->nsaddrs[lastns] = inu;
497 statp->nsaddr_list[lastns] = ina;
498 EXT(statp).nssocks[lastns] = fd;
499 EXT(statp).nstimes[lastns] = nstime;
500 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900501
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900502 /*
503 * Send request, RETRY times, or until successful.
504 */
Bernie Innocenti9c575932018-09-07 21:10:25 +0900505 for (int attempt = 0; attempt < statp->retry; ++attempt) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900506 struct __res_stats stats[MAXNS];
507 struct __res_params params;
508 int revision_id = _resolv_cache_get_resolver_stats(statp->netid, &params, stats);
509 bool usable_servers[MAXNS];
510 android_net_res_stats_get_usable_servers(&params, stats, statp->nscount, usable_servers);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900511
Bernie Innocenti9c575932018-09-07 21:10:25 +0900512 for (int ns = 0; ns < statp->nscount; ns++) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900513 if (!usable_servers[ns]) continue;
514 struct sockaddr* nsap;
515 int nsaplen;
516 time_t now = 0;
517 int rcode = RCODE_INTERNAL_ERROR;
518 int delay = 0;
519 nsap = get_nsaddr(statp, (size_t) ns);
520 nsaplen = get_salen(nsap);
521 statp->_flags &= ~RES_F_LASTMASK;
522 statp->_flags |= (ns << RES_F_LASTSHIFT);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900523
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900524 same_ns:
525 if (statp->qhook) {
526 int done = 0, loops = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900527
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900528 do {
529 res_sendhookact act;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900530
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900531 act = (*statp->qhook)(&nsap, &buf, &buflen, ans, anssiz, &resplen);
532 switch (act) {
533 case res_goahead:
534 done = 1;
535 break;
536 case res_nextns:
537 res_nclose(statp);
538 goto next_ns;
539 case res_done:
540 if (cache_status == RESOLV_CACHE_NOTFOUND) {
541 _resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
542 }
543 return (resplen);
544 case res_modified:
545 /* give the hook another try */
546 if (++loops < 42) /*doug adams*/
547 break;
548 /*FALLTHROUGH*/
549 case res_error:
550 /*FALLTHROUGH*/
551 default:
552 goto fail;
553 }
554 } while (!done);
555 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900556
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900557 [[maybe_unused]] static const int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
558 [[maybe_unused]] char abuf[NI_MAXHOST];
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900559 Dprint(((statp->options & RES_DEBUG) &&
560 getnameinfo(nsap, (socklen_t) nsaplen, abuf, sizeof(abuf), NULL, 0, niflags) ==
561 0),
562 (stdout, ";; Querying server (# %d) address = %s\n", ns + 1, abuf));
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900563
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900564 if (v_circuit) {
565 /* Use VC; at most one attempt per server. */
Bernie Innocenti9c575932018-09-07 21:10:25 +0900566 attempt = statp->retry;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900567
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900568 n = send_vc(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &now, &rcode,
569 &delay);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900570
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900571 /*
572 * Only record stats the first time we try a query. This ensures that
573 * queries that deterministically fail (e.g., a name that always returns
574 * SERVFAIL or times out) do not unduly affect the stats.
575 */
Bernie Innocenti9c575932018-09-07 21:10:25 +0900576 if (attempt == 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900577 struct __res_sample sample;
578 _res_stats_set_sample(&sample, now, rcode, delay);
579 _resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, ns, &sample,
580 params.max_samples);
581 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900582
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900583 VLOG << "used send_vc " << n;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900584
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900585 if (n < 0) goto fail;
586 if (n == 0) goto next_ns;
587 resplen = n;
588 } else {
589 /* Use datagrams. */
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900590 VLOG << "using send_dg";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900591
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900592 n = send_dg(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &v_circuit,
593 &gotsomewhere, &now, &rcode, &delay);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900594
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900595 /* Only record stats the first time we try a query. See above. */
Bernie Innocenti9c575932018-09-07 21:10:25 +0900596 if (attempt == 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900597 struct __res_sample sample;
598 _res_stats_set_sample(&sample, now, rcode, delay);
599 _resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, ns, &sample,
600 params.max_samples);
601 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900602
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900603 VLOG << "used send_dg " << n;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900604
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900605 if (n < 0) goto fail;
606 if (n == 0) goto next_ns;
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900607 VLOG << "time=" << time(NULL);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900608 if (v_circuit) goto same_ns;
609 resplen = n;
610 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900611
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900612 Dprint((statp->options & RES_DEBUG) ||
613 ((statp->pfcode & RES_PRF_REPLY) && (statp->pfcode & RES_PRF_HEAD1)),
614 (stdout, ";; got answer:\n"));
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900615
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900616 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
617 (stdout, "%s", ""), ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900618
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900619 if (cache_status == RESOLV_CACHE_NOTFOUND) {
620 _resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
621 }
622 /*
623 * If we have temporarily opened a virtual circuit,
624 * or if we haven't been asked to keep a socket open,
625 * close the socket.
626 */
627 if ((v_circuit && (statp->options & RES_USEVC) == 0U) ||
628 (statp->options & RES_STAYOPEN) == 0U) {
629 res_nclose(statp);
630 }
631 if (statp->rhook) {
632 int done = 0, loops = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900633
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900634 do {
635 res_sendhookact act;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900636
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900637 act = (*statp->rhook)(nsap, buf, buflen, ans, anssiz, &resplen);
638 switch (act) {
639 case res_goahead:
640 case res_done:
641 done = 1;
642 break;
643 case res_nextns:
644 res_nclose(statp);
645 goto next_ns;
646 case res_modified:
647 /* give the hook another try */
648 if (++loops < 42) /*doug adams*/
649 break;
650 /*FALLTHROUGH*/
651 case res_error:
652 /*FALLTHROUGH*/
653 default:
654 goto fail;
655 }
656 } while (!done);
657 }
658 return (resplen);
659 next_ns:;
Bernie Innocenti9c575932018-09-07 21:10:25 +0900660 } // for each ns
661 } // for each retry
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900662 res_nclose(statp);
663 if (!v_circuit) {
664 if (!gotsomewhere)
665 errno = ECONNREFUSED; /* no nameservers found */
666 else
667 errno = ETIMEDOUT; /* no answer obtained */
668 } else
669 errno = terrno;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900670
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900671 _resolv_cache_query_failed(statp->netid, buf, buflen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900672
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900673 return (-1);
674fail:
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900675
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900676 _resolv_cache_query_failed(statp->netid, buf, buflen);
677 res_nclose(statp);
678 return (-1);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900679}
680
681/* Private */
682
Bernie Innocenti9c575932018-09-07 21:10:25 +0900683static int get_salen(const struct sockaddr* sa) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900684 if (sa->sa_family == AF_INET)
685 return (sizeof(struct sockaddr_in));
686 else if (sa->sa_family == AF_INET6)
687 return (sizeof(struct sockaddr_in6));
688 else
689 return (0); /* unknown, die on connect */
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900690}
691
692/*
693 * pick appropriate nsaddr_list for use. see res_init() for initialization.
694 */
Bernie Innocenti9c575932018-09-07 21:10:25 +0900695static struct sockaddr* get_nsaddr(res_state statp, size_t n) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900696 if (!statp->nsaddr_list[n].sin_family && EXT(statp).ext) {
697 /*
698 * - EXT(statp).ext->nsaddrs[n] holds an address that is larger
699 * than struct sockaddr, and
700 * - user code did not update statp->nsaddr_list[n].
701 */
702 return (struct sockaddr*) (void*) &EXT(statp).ext->nsaddrs[n];
703 } else {
704 /*
705 * - user code updated statp->nsaddr_list[n], or
706 * - statp->nsaddr_list[n] has the same content as
707 * EXT(statp).ext->nsaddrs[n].
708 */
709 return (struct sockaddr*) (void*) &statp->nsaddr_list[n];
710 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900711}
712
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900713static struct timespec get_timeout(const res_state statp, const struct __res_params* params,
714 const int ns) {
715 int msec;
716 if (params->base_timeout_msec != 0) {
717 // TODO: scale the timeout by retry attempt and maybe number of servers
718 msec = params->base_timeout_msec;
719 } else {
720 // Legacy algorithm which scales the timeout by nameserver number.
721 // For instance, with 4 nameservers: 5s, 2.5s, 5s, 10s
722 // This has no effect with 1 or 2 nameservers
723 msec = (statp->retrans * 1000) << ns;
724 if (ns > 0) {
725 msec /= statp->nscount;
726 }
727 if (msec < 1000) {
728 msec = 1000; // Use at least 100ms
729 }
730 }
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900731 VLOG << "using timeout of " << msec << " msec";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900732
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900733 struct timespec result;
734 result.tv_sec = msec / 1000;
735 result.tv_nsec = (msec % 1000) * 1000000;
736 return result;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900737}
738
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900739static int send_vc(res_state statp, struct __res_params* params, const u_char* buf, int buflen,
740 u_char* ans, int anssiz, int* terrno, int ns, time_t* at, int* rcode,
741 int* delay) {
742 *at = time(NULL);
743 *rcode = RCODE_INTERNAL_ERROR;
744 *delay = 0;
745 const HEADER* hp = (const HEADER*) (const void*) buf;
746 HEADER* anhp = (HEADER*) (void*) ans;
747 struct sockaddr* nsap;
748 int nsaplen;
749 int truncating, connreset, resplen, n;
750 struct iovec iov[2];
751 u_short len;
752 u_char* cp;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900753
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900754 VLOG << "using send_vc";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900755
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900756 nsap = get_nsaddr(statp, (size_t) ns);
757 nsaplen = get_salen(nsap);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900758
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900759 connreset = 0;
760same_ns:
761 truncating = 0;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900762
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900763 struct timespec now = evNowTime();
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900764
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900765 /* Are we still talking to whom we want to talk to? */
766 if (statp->_vcsock >= 0 && (statp->_flags & RES_F_VC) != 0) {
767 struct sockaddr_storage peer;
768 socklen_t size = sizeof peer;
769 unsigned old_mark;
770 socklen_t mark_size = sizeof(old_mark);
771 if (getpeername(statp->_vcsock, (struct sockaddr*) (void*) &peer, &size) < 0 ||
772 !sock_eq((struct sockaddr*) (void*) &peer, nsap) ||
773 getsockopt(statp->_vcsock, SOL_SOCKET, SO_MARK, &old_mark, &mark_size) < 0 ||
774 old_mark != statp->_mark) {
775 res_nclose(statp);
776 statp->_flags &= ~RES_F_VC;
777 }
778 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900779
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900780 if (statp->_vcsock < 0 || (statp->_flags & RES_F_VC) == 0) {
781 if (statp->_vcsock >= 0) res_nclose(statp);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900782
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900783 statp->_vcsock = socket(nsap->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0);
784 if (statp->_vcsock < 0) {
785 switch (errno) {
786 case EPROTONOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900787 case EPFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900788 case EAFNOSUPPORT:
789 Perror(statp, stderr, "socket(vc)", errno);
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900790 return 0;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900791 default:
792 *terrno = errno;
793 Perror(statp, stderr, "socket(vc)", errno);
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900794 return -1;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900795 }
796 }
797 fchown(statp->_vcsock, AID_DNS, -1);
798 if (statp->_mark != MARK_UNSET) {
799 if (setsockopt(statp->_vcsock, SOL_SOCKET, SO_MARK, &statp->_mark,
800 sizeof(statp->_mark)) < 0) {
801 *terrno = errno;
802 Perror(statp, stderr, "setsockopt", errno);
803 return -1;
804 }
805 }
806 errno = 0;
807 if (random_bind(statp->_vcsock, nsap->sa_family) < 0) {
808 *terrno = errno;
809 Aerror(statp, stderr, "bind/vc", errno, nsap, nsaplen);
810 res_nclose(statp);
811 return (0);
812 }
813 if (connect_with_timeout(statp->_vcsock, nsap, (socklen_t) nsaplen,
814 get_timeout(statp, params, ns)) < 0) {
815 *terrno = errno;
816 Aerror(statp, stderr, "connect/vc", errno, nsap, nsaplen);
817 res_nclose(statp);
818 /*
819 * The way connect_with_timeout() is implemented prevents us from reliably
820 * determining whether this was really a timeout or e.g. ECONNREFUSED. Since
821 * currently both cases are handled in the same way, there is no need to
822 * change this (yet). If we ever need to reliably distinguish between these
823 * cases, both connect_with_timeout() and retrying_poll() need to be
824 * modified, though.
825 */
826 *rcode = RCODE_TIMEOUT;
827 return (0);
828 }
829 statp->_flags |= RES_F_VC;
830 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900831
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900832 /*
833 * Send length & message
834 */
835 ns_put16((u_short) buflen, (u_char*) (void*) &len);
836 iov[0] = evConsIovec(&len, INT16SZ);
Bernie Innocenti9c575932018-09-07 21:10:25 +0900837 iov[1] = evConsIovec((void*) buf, (size_t) buflen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900838 if (writev(statp->_vcsock, iov, 2) != (INT16SZ + buflen)) {
839 *terrno = errno;
840 Perror(statp, stderr, "write failed", errno);
841 res_nclose(statp);
842 return (0);
843 }
844 /*
845 * Receive length & response
846 */
847read_len:
848 cp = ans;
849 len = INT16SZ;
850 while ((n = read(statp->_vcsock, (char*) cp, (size_t) len)) > 0) {
851 cp += n;
852 if ((len -= n) == 0) break;
853 }
854 if (n <= 0) {
855 *terrno = errno;
856 Perror(statp, stderr, "read failed", errno);
857 res_nclose(statp);
858 /*
859 * A long running process might get its TCP
860 * connection reset if the remote server was
861 * restarted. Requery the server instead of
862 * trying a new one. When there is only one
863 * server, this means that a query might work
864 * instead of failing. We only allow one reset
865 * per query to prevent looping.
866 */
867 if (*terrno == ECONNRESET && !connreset) {
868 connreset = 1;
869 res_nclose(statp);
870 goto same_ns;
871 }
872 res_nclose(statp);
873 return (0);
874 }
875 resplen = ns_get16(ans);
876 if (resplen > anssiz) {
877 Dprint(statp->options & RES_DEBUG, (stdout, ";; response truncated\n"));
878 truncating = 1;
879 len = anssiz;
880 } else
881 len = resplen;
882 if (len < HFIXEDSZ) {
883 /*
884 * Undersized message.
885 */
886 Dprint(statp->options & RES_DEBUG, (stdout, ";; undersized: %d\n", len));
887 *terrno = EMSGSIZE;
888 res_nclose(statp);
889 return (0);
890 }
891 cp = ans;
892 while (len != 0 && (n = read(statp->_vcsock, (char*) cp, (size_t) len)) > 0) {
893 cp += n;
894 len -= n;
895 }
896 if (n <= 0) {
897 *terrno = errno;
898 Perror(statp, stderr, "read(vc)", errno);
899 res_nclose(statp);
900 return (0);
901 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900902
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900903 if (truncating) {
904 /*
905 * Flush rest of answer so connection stays in synch.
906 */
907 anhp->tc = 1;
908 len = resplen - anssiz;
909 while (len != 0) {
910 char junk[PACKETSZ];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900911
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900912 n = read(statp->_vcsock, junk, (len > sizeof junk) ? sizeof junk : len);
913 if (n > 0)
914 len -= n;
915 else
916 break;
917 }
918 }
919 /*
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900920 * If the calling application has bailed out of
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900921 * a previous call and failed to arrange to have
922 * the circuit closed or the server has got
923 * itself confused, then drop the packet and
924 * wait for the correct one.
925 */
926 if (hp->id != anhp->id) {
927 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
928 (stdout, ";; old answer (unexpected):\n"), ans,
929 (resplen > anssiz) ? anssiz : resplen);
930 goto read_len;
931 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900932
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900933 /*
934 * All is well, or the error is fatal. Signal that the
935 * next nameserver ought not be tried.
936 */
937 if (resplen > 0) {
938 struct timespec done = evNowTime();
939 *delay = _res_stats_calculate_rtt(&done, &now);
940 *rcode = anhp->rcode;
941 }
942 return (resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900943}
944
945/* return -1 on error (errno set), 0 on success */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900946static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
947 const struct timespec timeout) {
948 int res, origflags;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900949
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900950 origflags = fcntl(sock, F_GETFL, 0);
951 fcntl(sock, F_SETFL, origflags | O_NONBLOCK);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900952
Bernie Innocentiafaacf72018-08-30 07:34:37 +0900953 res = connect(sock, nsap, salen);
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900954 if (res < 0 && errno != EINPROGRESS) {
955 res = -1;
956 goto done;
957 }
958 if (res != 0) {
959 struct timespec now = evNowTime();
960 struct timespec finish = evAddTime(now, timeout);
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900961 VLOG << sock << " send_vc";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900962 res = retrying_poll(sock, POLLIN | POLLOUT, &finish);
963 if (res <= 0) {
964 res = -1;
965 }
966 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900967done:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900968 fcntl(sock, F_SETFL, origflags);
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900969 VLOG << sock << " connect_with_const timeout returning " << res;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900970 return res;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900971}
972
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900973static int retrying_poll(const int sock, const short events, const struct timespec* finish) {
974 struct timespec now, timeout;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900975
976retry:
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900977 VLOG << " " << sock << " retrying_poll";
Bernie Innocenti318ed2d2018-08-30 04:05:20 +0900978
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900979 now = evNowTime();
980 if (evCmpTime(*finish, now) > 0)
981 timeout = evSubTime(*finish, now);
982 else
983 timeout = evConsTime(0L, 0L);
984 struct pollfd fds = {.fd = sock, .events = events};
985 int n = ppoll(&fds, 1, &timeout, /*sigmask=*/NULL);
986 if (n == 0) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900987 VLOG << " " << sock << "retrying_poll timeout";
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900988 errno = ETIMEDOUT;
989 return 0;
990 }
991 if (n < 0) {
992 if (errno == EINTR) goto retry;
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +0900993 VLOG << " " << sock << " retrying_poll got error " << n;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +0900994 return n;
995 }
996 if (fds.revents & (POLLIN | POLLOUT | POLLERR)) {
997 int error;
998 socklen_t len = sizeof(error);
999 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error) {
1000 errno = error;
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001001 VLOG << " " << sock << " retrying_poll dot error2 " << errno;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001002 return -1;
1003 }
1004 }
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001005 VLOG << " " << sock << " retrying_poll returning " << n;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001006 return n;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001007}
1008
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001009static int send_dg(res_state statp, struct __res_params* params, const u_char* buf, int buflen,
1010 u_char* ans, int anssiz, int* terrno, int ns, int* v_circuit, int* gotsomewhere,
1011 time_t* at, int* rcode, int* delay) {
1012 *at = time(NULL);
1013 *rcode = RCODE_INTERNAL_ERROR;
1014 *delay = 0;
1015 const HEADER* hp = (const HEADER*) (const void*) buf;
1016 HEADER* anhp = (HEADER*) (void*) ans;
1017 const struct sockaddr* nsap;
1018 int nsaplen;
1019 struct timespec now, timeout, finish, done;
1020 struct sockaddr_storage from;
1021 socklen_t fromlen;
1022 int resplen, n, s;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001023
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001024 nsap = get_nsaddr(statp, (size_t) ns);
1025 nsaplen = get_salen(nsap);
1026 if (EXT(statp).nssocks[ns] == -1) {
1027 EXT(statp).nssocks[ns] = socket(nsap->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
1028 if (EXT(statp).nssocks[ns] < 0) {
1029 switch (errno) {
1030 case EPROTONOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001031 case EPFNOSUPPORT:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001032 case EAFNOSUPPORT:
1033 Perror(statp, stderr, "socket(dg)", errno);
1034 return (0);
1035 default:
1036 *terrno = errno;
1037 Perror(statp, stderr, "socket(dg)", errno);
1038 return (-1);
1039 }
1040 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001041
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001042 fchown(EXT(statp).nssocks[ns], AID_DNS, -1);
1043 if (statp->_mark != MARK_UNSET) {
1044 if (setsockopt(EXT(statp).nssocks[ns], SOL_SOCKET, SO_MARK, &(statp->_mark),
1045 sizeof(statp->_mark)) < 0) {
1046 res_nclose(statp);
1047 return -1;
1048 }
1049 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001050#ifndef CANNOT_CONNECT_DGRAM
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001051 /*
1052 * On a 4.3BSD+ machine (client and server,
1053 * actually), sending to a nameserver datagram
1054 * port with no nameserver will cause an
1055 * ICMP port unreachable message to be returned.
1056 * If our datagram socket is "connected" to the
1057 * server, we get an ECONNREFUSED error on the next
1058 * socket operation, and select returns if the
1059 * error message is received. We can thus detect
1060 * the absence of a nameserver without timing out.
1061 */
1062 if (random_bind(EXT(statp).nssocks[ns], nsap->sa_family) < 0) {
1063 Aerror(statp, stderr, "bind(dg)", errno, nsap, nsaplen);
1064 res_nclose(statp);
1065 return (0);
1066 }
Bernie Innocentiafaacf72018-08-30 07:34:37 +09001067 if (connect(EXT(statp).nssocks[ns], nsap, (socklen_t) nsaplen) < 0) {
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001068 Aerror(statp, stderr, "connect(dg)", errno, nsap, nsaplen);
1069 res_nclose(statp);
1070 return (0);
1071 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001072#endif /* !CANNOT_CONNECT_DGRAM */
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001073 Dprint(statp->options & RES_DEBUG, (stdout, ";; new DG socket\n"))
1074 }
1075 s = EXT(statp).nssocks[ns];
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001076#ifndef CANNOT_CONNECT_DGRAM
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001077 if (send(s, (const char*) buf, (size_t) buflen, 0) != buflen) {
1078 Perror(statp, stderr, "send", errno);
1079 res_nclose(statp);
1080 return (0);
1081 }
1082#else /* !CANNOT_CONNECT_DGRAM */
1083 if (sendto(s, (const char*) buf, buflen, 0, nsap, nsaplen) != buflen) {
1084 Aerror(statp, stderr, "sendto", errno, nsap, nsaplen);
1085 res_nclose(statp);
1086 return (0);
1087 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001088#endif /* !CANNOT_CONNECT_DGRAM */
1089
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001090 /*
1091 * Wait for reply.
1092 */
1093 timeout = get_timeout(statp, params, ns);
1094 now = evNowTime();
1095 finish = evAddTime(now, timeout);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001096retry:
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001097 n = retrying_poll(s, POLLIN, &finish);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001098
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001099 if (n == 0) {
1100 *rcode = RCODE_TIMEOUT;
1101 Dprint(statp->options & RES_DEBUG, (stdout, ";; timeout\n"));
1102 *gotsomewhere = 1;
1103 return (0);
1104 }
1105 if (n < 0) {
1106 Perror(statp, stderr, "poll", errno);
1107 res_nclose(statp);
1108 return (0);
1109 }
1110 errno = 0;
1111 fromlen = sizeof(from);
1112 resplen = recvfrom(s, (char*) ans, (size_t) anssiz, 0, (struct sockaddr*) (void*) &from,
1113 &fromlen);
1114 if (resplen <= 0) {
1115 Perror(statp, stderr, "recvfrom", errno);
1116 res_nclose(statp);
1117 return (0);
1118 }
1119 *gotsomewhere = 1;
1120 if (resplen < HFIXEDSZ) {
1121 /*
1122 * Undersized message.
1123 */
1124 Dprint(statp->options & RES_DEBUG, (stdout, ";; undersized: %d\n", resplen));
1125 *terrno = EMSGSIZE;
1126 res_nclose(statp);
1127 return (0);
1128 }
1129 if (hp->id != anhp->id) {
1130 /*
1131 * response from old query, ignore it.
1132 * XXX - potential security hazard could
1133 * be detected here.
1134 */
1135 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
1136 (stdout, ";; old answer:\n"), ans, (resplen > anssiz) ? anssiz : resplen);
1137 goto retry;
1138 }
1139 if (!(statp->options & RES_INSECURE1) &&
1140 !res_ourserver_p(statp, (struct sockaddr*) (void*) &from)) {
1141 /*
1142 * response from wrong server? ignore it.
1143 * XXX - potential security hazard could
1144 * be detected here.
1145 */
1146 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
1147 (stdout, ";; not our server:\n"), ans, (resplen > anssiz) ? anssiz : resplen);
1148 goto retry;
1149 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001150#ifdef RES_USE_EDNS0
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001151 if (anhp->rcode == FORMERR && (statp->options & RES_USE_EDNS0) != 0U) {
1152 /*
1153 * Do not retry if the server do not understand EDNS0.
1154 * The case has to be captured here, as FORMERR packet do not
1155 * carry query section, hence res_queriesmatch() returns 0.
1156 */
1157 DprintQ(statp->options & RES_DEBUG, (stdout, "server rejected query with EDNS0:\n"), ans,
1158 (resplen > anssiz) ? anssiz : resplen);
1159 /* record the error */
1160 statp->_flags |= RES_F_EDNS0ERR;
1161 res_nclose(statp);
1162 return (0);
1163 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001164#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001165 if (!(statp->options & RES_INSECURE2) &&
1166 !res_queriesmatch(buf, buf + buflen, ans, ans + anssiz)) {
1167 /*
1168 * response contains wrong query? ignore it.
1169 * XXX - potential security hazard could
1170 * be detected here.
1171 */
1172 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
1173 (stdout, ";; wrong query name:\n"), ans, (resplen > anssiz) ? anssiz : resplen);
1174 goto retry;
1175 ;
1176 }
1177 done = evNowTime();
1178 *delay = _res_stats_calculate_rtt(&done, &now);
1179 if (anhp->rcode == SERVFAIL || anhp->rcode == NOTIMP || anhp->rcode == REFUSED) {
1180 DprintQ(statp->options & RES_DEBUG, (stdout, "server rejected query:\n"), ans,
1181 (resplen > anssiz) ? anssiz : resplen);
1182 res_nclose(statp);
1183 /* don't retry if called from dig */
1184 if (!statp->pfcode) {
1185 *rcode = anhp->rcode;
1186 return (0);
1187 }
1188 }
1189 if (!(statp->options & RES_IGNTC) && anhp->tc) {
1190 /*
1191 * To get the rest of answer,
1192 * use TCP with same server.
1193 */
1194 Dprint(statp->options & RES_DEBUG, (stdout, ";; truncated answer\n"));
1195 *v_circuit = 1;
1196 res_nclose(statp);
1197 return (1);
1198 }
1199 /*
1200 * All is well, or the error is fatal. Signal that the
1201 * next nameserver ought not be tried.
1202 */
1203 if (resplen > 0) {
1204 *rcode = anhp->rcode;
1205 }
1206 return (resplen);
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001207}
1208
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001209static void Aerror(const res_state statp, FILE* file, const char* string, int error,
1210 const struct sockaddr* address, int alen) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001211 if (!kVerboseLogging) return;
1212
1213 const int save = errno;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001214 char hbuf[NI_MAXHOST];
1215 char sbuf[NI_MAXSERV];
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001216 constexpr int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001217
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001218 if ((statp->options & RES_DEBUG) != 0U) {
1219 if (getnameinfo(address, (socklen_t) alen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
1220 niflags)) {
1221 strncpy(hbuf, "?", sizeof(hbuf) - 1);
1222 hbuf[sizeof(hbuf) - 1] = '\0';
1223 strncpy(sbuf, "?", sizeof(sbuf) - 1);
1224 sbuf[sizeof(sbuf) - 1] = '\0';
1225 }
1226 fprintf(file, "res_send: %s ([%s].%s): %s\n", string, hbuf, sbuf, strerror(error));
1227 }
1228 errno = save;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001229}
1230
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001231static void Perror(const res_state statp, FILE* file, const char* string, int error) {
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001232 if (!kVerboseLogging) return;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001233
Bernie Innocenti9f05f5e2018-09-12 23:20:10 +09001234 const int save = errno;
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001235 if ((statp->options & RES_DEBUG) != 0U)
1236 fprintf(file, "res_send: %s: %s\n", string, strerror(error));
1237 errno = save;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001238}
1239
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001240static int sock_eq(struct sockaddr* a, struct sockaddr* b) {
1241 struct sockaddr_in *a4, *b4;
1242 struct sockaddr_in6 *a6, *b6;
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001243
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001244 if (a->sa_family != b->sa_family) return 0;
1245 switch (a->sa_family) {
1246 case AF_INET:
1247 a4 = (struct sockaddr_in*) (void*) a;
1248 b4 = (struct sockaddr_in*) (void*) b;
1249 return a4->sin_port == b4->sin_port && a4->sin_addr.s_addr == b4->sin_addr.s_addr;
1250 case AF_INET6:
1251 a6 = (struct sockaddr_in6*) (void*) a;
1252 b6 = (struct sockaddr_in6*) (void*) b;
1253 return a6->sin6_port == b6->sin6_port &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001254#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001255 a6->sin6_scope_id == b6->sin6_scope_id &&
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001256#endif
Bernie Innocenti8ad893f2018-08-31 14:09:46 +09001257 IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
1258 default:
1259 return 0;
1260 }
Bernie Innocenti318ed2d2018-08-30 04:05:20 +09001261}