blob: f2563fb1c5b09a49d3715c6583b3ec93a96c5f43 [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
73#include <sys/cdefs.h>
74#if defined(LIBC_SCCS) && !defined(lint)
75#ifdef notdef
76static const char sccsid[] = "@(#)res_send.c 8.1 (Berkeley) 6/4/93";
77static const char rcsid[] = "Id: res_send.c,v 1.5.2.2.4.5 2004/08/10 02:19:56 marka Exp";
78#else
79__RCSID("$NetBSD: res_send.c,v 1.9 2006/01/24 17:41:25 christos Exp $");
80#endif
81#endif /* LIBC_SCCS and not lint */
82
83/*
84 * Send query to name server and wait for reply.
85 */
86
Bernie Innocenti55864192018-08-30 04:05:20 +090087#include <sys/param.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090088#include <sys/socket.h>
Bernie Innocentif12d5bb2018-08-31 14:09:46 +090089#include <sys/time.h>
90#include <sys/types.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090091#include <sys/uio.h>
92
Bernie Innocenti55864192018-08-30 04:05:20 +090093#include <arpa/inet.h>
Bernie Innocentif12d5bb2018-08-31 14:09:46 +090094#include <arpa/nameser.h>
95#include <netinet/in.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090096
97#include <errno.h>
98#include <fcntl.h>
99#include <netdb.h>
100#include <poll.h>
101#ifdef ANDROID_CHANGES
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900102#include "private/android_filesystem_config.h"
Bernie Innocenti55864192018-08-30 04:05:20 +0900103#include "resolv_netid.h"
104#include "resolv_private.h"
Bernie Innocenti55864192018-08-30 04:05:20 +0900105#else
106#include <resolv.h>
107#endif
108#include <signal.h>
109#include <stdio.h>
110#include <stdlib.h>
111#include <string.h>
112#include <time.h>
113#include <unistd.h>
114
115#include <isc/eventlib.h>
116
117#include <resolv_cache.h>
118
119#include <async_safe/log.h>
120
121#ifndef DE_CONST
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900122#define DE_CONST(c, v) \
123 v = ((c) ? strchr((const void*) (c), *(const char*) (const void*) (c)) : NULL)
Bernie Innocenti55864192018-08-30 04:05:20 +0900124#endif
125
126/* Options. Leave them on. */
127#ifndef DEBUG
128#define DEBUG
129#endif
130#include "res_debug.h"
131#include "res_private.h"
132#include "resolv_stats.h"
133
134#define EXT(res) ((res)->_u._ext)
135#define DBG 0
136
137/* Forward. */
138
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900139static int get_salen __P((const struct sockaddr*) );
140static struct sockaddr* get_nsaddr __P((res_state, size_t));
141static int send_vc(res_state, struct __res_params* params, const u_char*, int, u_char*, int, int*,
142 int, time_t*, int*, int*);
143static int send_dg(res_state, struct __res_params* params, const u_char*, int, u_char*, int, int*,
144 int, int*, int*, time_t*, int*, int*);
145static void Aerror(const res_state, FILE*, const char*, int, const struct sockaddr*, int);
146static void Perror(const res_state, FILE*, const char*, int);
147static int sock_eq(struct sockaddr*, struct sockaddr*);
148void res_pquery(const res_state, const u_char*, int, FILE*);
149static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
150 const struct timespec timeout);
Bernie Innocenti55864192018-08-30 04:05:20 +0900151static int retrying_poll(const int sock, short events, const struct timespec* finish);
152
153/* BIONIC-BEGIN: implement source port randomization */
154typedef union {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900155 struct sockaddr sa;
156 struct sockaddr_in sin;
157 struct sockaddr_in6 sin6;
Bernie Innocenti55864192018-08-30 04:05:20 +0900158} _sockaddr_union;
159
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900160static int random_bind(int s, int family) {
161 _sockaddr_union u;
162 int j;
163 socklen_t slen;
Bernie Innocenti55864192018-08-30 04:05:20 +0900164
165 /* clear all, this also sets the IP4/6 address to 'any' */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900166 memset(&u, 0, sizeof u);
Bernie Innocenti55864192018-08-30 04:05:20 +0900167
168 switch (family) {
169 case AF_INET:
170 u.sin.sin_family = family;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900171 slen = sizeof u.sin;
Bernie Innocenti55864192018-08-30 04:05:20 +0900172 break;
173 case AF_INET6:
174 u.sin6.sin6_family = family;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900175 slen = sizeof u.sin6;
Bernie Innocenti55864192018-08-30 04:05:20 +0900176 break;
177 default:
178 errno = EPROTO;
179 return -1;
180 }
181
182 /* first try to bind to a random source port a few times */
183 for (j = 0; j < 10; j++) {
184 /* find a random port between 1025 .. 65534 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900185 int port = 1025 + (res_randomid() % (65535 - 1025));
Bernie Innocenti55864192018-08-30 04:05:20 +0900186 if (family == AF_INET)
187 u.sin.sin_port = htons(port);
188 else
189 u.sin6.sin6_port = htons(port);
190
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900191 if (!bind(s, &u.sa, slen)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900192 }
193
194 /* nothing after 10 tries, our network table is probably busy */
195 /* let the system decide which port is best */
196 if (family == AF_INET)
197 u.sin.sin_port = 0;
198 else
199 u.sin6.sin6_port = 0;
200
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900201 return bind(s, &u.sa, slen);
Bernie Innocenti55864192018-08-30 04:05:20 +0900202}
203/* BIONIC-END */
204
205static const int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
206
207/* Public. */
208
209/* int
210 * res_isourserver(ina)
211 * looks up "ina" in _res.ns_addr_list[]
212 * returns:
213 * 0 : not found
214 * >0 : found
215 * author:
216 * paul vixie, 29may94
217 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900218__LIBC_HIDDEN__ int res_ourserver_p(const res_state statp, const struct sockaddr* sa) {
219 const struct sockaddr_in *inp, *srv;
220 const struct sockaddr_in6 *in6p, *srv6;
221 int ns;
Bernie Innocenti55864192018-08-30 04:05:20 +0900222
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900223 switch (sa->sa_family) {
224 case AF_INET:
225 inp = (const struct sockaddr_in*) (const void*) sa;
226 for (ns = 0; ns < statp->nscount; ns++) {
227 srv = (struct sockaddr_in*) (void*) get_nsaddr(statp, (size_t) ns);
228 if (srv->sin_family == inp->sin_family && srv->sin_port == inp->sin_port &&
229 (srv->sin_addr.s_addr == INADDR_ANY ||
230 srv->sin_addr.s_addr == inp->sin_addr.s_addr))
231 return (1);
232 }
233 break;
234 case AF_INET6:
235 if (EXT(statp).ext == NULL) break;
236 in6p = (const struct sockaddr_in6*) (const void*) sa;
237 for (ns = 0; ns < statp->nscount; ns++) {
238 srv6 = (struct sockaddr_in6*) (void*) get_nsaddr(statp, (size_t) ns);
239 if (srv6->sin6_family == in6p->sin6_family && srv6->sin6_port == in6p->sin6_port &&
Bernie Innocenti55864192018-08-30 04:05:20 +0900240#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900241 (srv6->sin6_scope_id == 0 || srv6->sin6_scope_id == in6p->sin6_scope_id) &&
Bernie Innocenti55864192018-08-30 04:05:20 +0900242#endif
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900243 (IN6_IS_ADDR_UNSPECIFIED(&srv6->sin6_addr) ||
244 IN6_ARE_ADDR_EQUAL(&srv6->sin6_addr, &in6p->sin6_addr)))
245 return (1);
246 }
247 break;
248 default:
249 break;
250 }
251 return (0);
Bernie Innocenti55864192018-08-30 04:05:20 +0900252}
253
254/* int
255 * res_nameinquery(name, type, class, buf, eom)
256 * look for (name,type,class) in the query section of packet (buf,eom)
257 * requires:
258 * buf + HFIXEDSZ <= eom
259 * returns:
260 * -1 : format error
261 * 0 : not found
262 * >0 : found
263 * author:
264 * paul vixie, 29may94
265 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900266int res_nameinquery(const char* name, int type, int class, const u_char* buf, const u_char* eom) {
267 const u_char* cp = buf + HFIXEDSZ;
268 int qdcount = ntohs(((const HEADER*) (const void*) buf)->qdcount);
Bernie Innocenti55864192018-08-30 04:05:20 +0900269
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900270 while (qdcount-- > 0) {
271 char tname[MAXDNAME + 1];
272 int n, ttype, tclass;
Bernie Innocenti55864192018-08-30 04:05:20 +0900273
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900274 n = dn_expand(buf, eom, cp, tname, sizeof tname);
275 if (n < 0) return (-1);
276 cp += n;
277 if (cp + 2 * INT16SZ > eom) return (-1);
278 ttype = ns_get16(cp);
279 cp += INT16SZ;
280 tclass = ns_get16(cp);
281 cp += INT16SZ;
282 if (ttype == type && tclass == class && ns_samename(tname, name) == 1) return (1);
283 }
284 return (0);
Bernie Innocenti55864192018-08-30 04:05:20 +0900285}
286
287/* int
288 * res_queriesmatch(buf1, eom1, buf2, eom2)
289 * is there a 1:1 mapping of (name,type,class)
290 * in (buf1,eom1) and (buf2,eom2)?
291 * returns:
292 * -1 : format error
293 * 0 : not a 1:1 mapping
294 * >0 : is a 1:1 mapping
295 * author:
296 * paul vixie, 29may94
297 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900298int res_queriesmatch(const u_char* buf1, const u_char* eom1, const u_char* buf2,
299 const u_char* eom2) {
300 const u_char* cp = buf1 + HFIXEDSZ;
301 int qdcount = ntohs(((const HEADER*) (const void*) buf1)->qdcount);
Bernie Innocenti55864192018-08-30 04:05:20 +0900302
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900303 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2) return (-1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900304
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900305 /*
306 * Only header section present in replies to
307 * dynamic update packets.
308 */
309 if ((((const HEADER*) (const void*) buf1)->opcode == ns_o_update) &&
310 (((const HEADER*) (const void*) buf2)->opcode == ns_o_update))
311 return (1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900312
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900313 if (qdcount != ntohs(((const HEADER*) (const void*) buf2)->qdcount)) return (0);
314 while (qdcount-- > 0) {
315 char tname[MAXDNAME + 1];
316 int n, ttype, tclass;
Bernie Innocenti55864192018-08-30 04:05:20 +0900317
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900318 n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
319 if (n < 0) return (-1);
320 cp += n;
321 if (cp + 2 * INT16SZ > eom1) return (-1);
322 ttype = ns_get16(cp);
323 cp += INT16SZ;
324 tclass = ns_get16(cp);
325 cp += INT16SZ;
326 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2)) return (0);
327 }
328 return (1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900329}
330
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900331int res_nsend(res_state statp, const u_char* buf, int buflen, u_char* ans, int anssiz) {
332 int gotsomewhere, terrno, try
333 , v_circuit, resplen, ns, n;
334 char abuf[NI_MAXHOST];
335 ResolvCacheStatus cache_status = RESOLV_CACHE_UNSUPPORTED;
Bernie Innocenti55864192018-08-30 04:05:20 +0900336
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900337 if (anssiz < HFIXEDSZ) {
338 errno = EINVAL;
339 return (-1);
340 }
341 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_QUERY),
342 (stdout, ";; res_send()\n"), buf, buflen);
343 v_circuit = (statp->options & RES_USEVC) || buflen > PACKETSZ;
344 gotsomewhere = 0;
345 terrno = ETIMEDOUT;
Bernie Innocenti55864192018-08-30 04:05:20 +0900346
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900347 int anslen = 0;
348 cache_status = _resolv_cache_lookup(statp->netid, buf, buflen, ans, anssiz, &anslen);
Bernie Innocenti55864192018-08-30 04:05:20 +0900349
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900350 if (cache_status == RESOLV_CACHE_FOUND) {
351 return anslen;
352 } else if (cache_status != RESOLV_CACHE_UNSUPPORTED) {
353 // had a cache miss for a known network, so populate the thread private
354 // data so the normal resolve path can do its thing
355 _resolv_populate_res_for_net(statp);
356 }
357 if (statp->nscount == 0) {
358 // We have no nameservers configured, so there's no point trying.
359 // Tell the cache the query failed, or any retries and anyone else asking the same
360 // question will block for PENDING_REQUEST_TIMEOUT seconds instead of failing fast.
361 _resolv_cache_query_failed(statp->netid, buf, buflen);
362 errno = ESRCH;
363 return (-1);
364 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900365
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900366 /*
367 * If the ns_addr_list in the resolver context has changed, then
368 * invalidate our cached copy and the associated timing data.
369 */
370 if (EXT(statp).nscount != 0) {
371 int needclose = 0;
372 struct sockaddr_storage peer;
373 socklen_t peerlen;
Bernie Innocenti55864192018-08-30 04:05:20 +0900374
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900375 if (EXT(statp).nscount != statp->nscount) {
376 needclose++;
377 } else {
378 for (ns = 0; ns < statp->nscount; ns++) {
379 if (statp->nsaddr_list[ns].sin_family &&
380 !sock_eq((struct sockaddr*) (void*) &statp->nsaddr_list[ns],
381 (struct sockaddr*) (void*) &EXT(statp).ext->nsaddrs[ns])) {
382 needclose++;
383 break;
384 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900385
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900386 if (EXT(statp).nssocks[ns] == -1) continue;
387 peerlen = sizeof(peer);
388 if (getpeername(EXT(statp).nssocks[ns], (struct sockaddr*) (void*) &peer,
389 &peerlen) < 0) {
390 needclose++;
391 break;
392 }
393 if (!sock_eq((struct sockaddr*) (void*) &peer, get_nsaddr(statp, (size_t) ns))) {
394 needclose++;
395 break;
396 }
397 }
398 }
399 if (needclose) {
400 res_nclose(statp);
401 EXT(statp).nscount = 0;
402 }
403 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900404
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900405 /*
406 * Maybe initialize our private copy of the ns_addr_list.
407 */
408 if (EXT(statp).nscount == 0) {
409 for (ns = 0; ns < statp->nscount; ns++) {
410 EXT(statp).nstimes[ns] = RES_MAXTIME;
411 EXT(statp).nssocks[ns] = -1;
412 if (!statp->nsaddr_list[ns].sin_family) continue;
413 EXT(statp).ext->nsaddrs[ns].sin = statp->nsaddr_list[ns];
414 }
415 EXT(statp).nscount = statp->nscount;
416 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900417
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900418 /*
419 * Some resolvers want to even out the load on their nameservers.
420 * Note that RES_BLAST overrides RES_ROTATE.
421 */
422 if ((statp->options & RES_ROTATE) != 0U && (statp->options & RES_BLAST) == 0U) {
423 union res_sockaddr_union inu;
424 struct sockaddr_in ina;
425 int lastns = statp->nscount - 1;
426 int fd;
427 u_int16_t nstime;
Bernie Innocenti55864192018-08-30 04:05:20 +0900428
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900429 if (EXT(statp).ext != NULL) inu = EXT(statp).ext->nsaddrs[0];
430 ina = statp->nsaddr_list[0];
431 fd = EXT(statp).nssocks[0];
432 nstime = EXT(statp).nstimes[0];
433 for (ns = 0; ns < lastns; ns++) {
434 if (EXT(statp).ext != NULL)
435 EXT(statp).ext->nsaddrs[ns] = EXT(statp).ext->nsaddrs[ns + 1];
436 statp->nsaddr_list[ns] = statp->nsaddr_list[ns + 1];
437 EXT(statp).nssocks[ns] = EXT(statp).nssocks[ns + 1];
438 EXT(statp).nstimes[ns] = EXT(statp).nstimes[ns + 1];
439 }
440 if (EXT(statp).ext != NULL) EXT(statp).ext->nsaddrs[lastns] = inu;
441 statp->nsaddr_list[lastns] = ina;
442 EXT(statp).nssocks[lastns] = fd;
443 EXT(statp).nstimes[lastns] = nstime;
444 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900445
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900446 /*
447 * Send request, RETRY times, or until successful.
448 */
449 for (try = 0; try < statp->retry; try ++) {
450 struct __res_stats stats[MAXNS];
451 struct __res_params params;
452 int revision_id = _resolv_cache_get_resolver_stats(statp->netid, &params, stats);
453 bool usable_servers[MAXNS];
454 android_net_res_stats_get_usable_servers(&params, stats, statp->nscount, usable_servers);
Bernie Innocenti55864192018-08-30 04:05:20 +0900455
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900456 for (ns = 0; ns < statp->nscount; ns++) {
457 if (!usable_servers[ns]) continue;
458 struct sockaddr* nsap;
459 int nsaplen;
460 time_t now = 0;
461 int rcode = RCODE_INTERNAL_ERROR;
462 int delay = 0;
463 nsap = get_nsaddr(statp, (size_t) ns);
464 nsaplen = get_salen(nsap);
465 statp->_flags &= ~RES_F_LASTMASK;
466 statp->_flags |= (ns << RES_F_LASTSHIFT);
Bernie Innocenti55864192018-08-30 04:05:20 +0900467
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900468 same_ns:
469 if (statp->qhook) {
470 int done = 0, loops = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900471
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900472 do {
473 res_sendhookact act;
Bernie Innocenti55864192018-08-30 04:05:20 +0900474
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900475 act = (*statp->qhook)(&nsap, &buf, &buflen, ans, anssiz, &resplen);
476 switch (act) {
477 case res_goahead:
478 done = 1;
479 break;
480 case res_nextns:
481 res_nclose(statp);
482 goto next_ns;
483 case res_done:
484 if (cache_status == RESOLV_CACHE_NOTFOUND) {
485 _resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
486 }
487 return (resplen);
488 case res_modified:
489 /* give the hook another try */
490 if (++loops < 42) /*doug adams*/
491 break;
492 /*FALLTHROUGH*/
493 case res_error:
494 /*FALLTHROUGH*/
495 default:
496 goto fail;
497 }
498 } while (!done);
499 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900500
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900501 Dprint(((statp->options & RES_DEBUG) &&
502 getnameinfo(nsap, (socklen_t) nsaplen, abuf, sizeof(abuf), NULL, 0, niflags) ==
503 0),
504 (stdout, ";; Querying server (# %d) address = %s\n", ns + 1, abuf));
Bernie Innocenti55864192018-08-30 04:05:20 +0900505
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900506 if (v_circuit) {
507 /* Use VC; at most one attempt per server. */
508 try
509 = statp->retry;
Bernie Innocenti55864192018-08-30 04:05:20 +0900510
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900511 n = send_vc(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &now, &rcode,
512 &delay);
Bernie Innocenti55864192018-08-30 04:05:20 +0900513
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900514 /*
515 * Only record stats the first time we try a query. This ensures that
516 * queries that deterministically fail (e.g., a name that always returns
517 * SERVFAIL or times out) do not unduly affect the stats.
518 */
519 if (try == 0) {
520 struct __res_sample sample;
521 _res_stats_set_sample(&sample, now, rcode, delay);
522 _resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, ns, &sample,
523 params.max_samples);
524 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900525
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900526 if (DBG) {
527 async_safe_format_log(ANDROID_LOG_DEBUG, "libc", "used send_vc %d\n", n);
528 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900529
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900530 if (n < 0) goto fail;
531 if (n == 0) goto next_ns;
532 resplen = n;
533 } else {
534 /* Use datagrams. */
535 if (DBG) {
536 async_safe_format_log(ANDROID_LOG_DEBUG, "libc", "using send_dg\n");
537 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900538
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900539 n = send_dg(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &v_circuit,
540 &gotsomewhere, &now, &rcode, &delay);
Bernie Innocenti55864192018-08-30 04:05:20 +0900541
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900542 /* Only record stats the first time we try a query. See above. */
543 if (try == 0) {
544 struct __res_sample sample;
545 _res_stats_set_sample(&sample, now, rcode, delay);
546 _resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, ns, &sample,
547 params.max_samples);
548 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900549
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900550 if (DBG) {
551 async_safe_format_log(ANDROID_LOG_DEBUG, "libc", "used send_dg %d\n", n);
552 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900553
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900554 if (n < 0) goto fail;
555 if (n == 0) goto next_ns;
556 if (DBG) {
557 async_safe_format_log(ANDROID_LOG_DEBUG, "libc", "time=%ld\n", time(NULL));
558 }
559 if (v_circuit) goto same_ns;
560 resplen = n;
561 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900562
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900563 Dprint((statp->options & RES_DEBUG) ||
564 ((statp->pfcode & RES_PRF_REPLY) && (statp->pfcode & RES_PRF_HEAD1)),
565 (stdout, ";; got answer:\n"));
Bernie Innocenti55864192018-08-30 04:05:20 +0900566
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900567 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
568 (stdout, "%s", ""), ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti55864192018-08-30 04:05:20 +0900569
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900570 if (cache_status == RESOLV_CACHE_NOTFOUND) {
571 _resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
572 }
573 /*
574 * If we have temporarily opened a virtual circuit,
575 * or if we haven't been asked to keep a socket open,
576 * close the socket.
577 */
578 if ((v_circuit && (statp->options & RES_USEVC) == 0U) ||
579 (statp->options & RES_STAYOPEN) == 0U) {
580 res_nclose(statp);
581 }
582 if (statp->rhook) {
583 int done = 0, loops = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900584
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900585 do {
586 res_sendhookact act;
Bernie Innocenti55864192018-08-30 04:05:20 +0900587
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900588 act = (*statp->rhook)(nsap, buf, buflen, ans, anssiz, &resplen);
589 switch (act) {
590 case res_goahead:
591 case res_done:
592 done = 1;
593 break;
594 case res_nextns:
595 res_nclose(statp);
596 goto next_ns;
597 case res_modified:
598 /* give the hook another try */
599 if (++loops < 42) /*doug adams*/
600 break;
601 /*FALLTHROUGH*/
602 case res_error:
603 /*FALLTHROUGH*/
604 default:
605 goto fail;
606 }
607 } while (!done);
608 }
609 return (resplen);
610 next_ns:;
611 } /*foreach ns*/
612 } /*foreach retry*/
613 res_nclose(statp);
614 if (!v_circuit) {
615 if (!gotsomewhere)
616 errno = ECONNREFUSED; /* no nameservers found */
617 else
618 errno = ETIMEDOUT; /* no answer obtained */
619 } else
620 errno = terrno;
Bernie Innocenti55864192018-08-30 04:05:20 +0900621
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900622 _resolv_cache_query_failed(statp->netid, buf, buflen);
Bernie Innocenti55864192018-08-30 04:05:20 +0900623
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900624 return (-1);
625fail:
Bernie Innocenti55864192018-08-30 04:05:20 +0900626
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900627 _resolv_cache_query_failed(statp->netid, buf, buflen);
628 res_nclose(statp);
629 return (-1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900630}
631
632/* Private */
633
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900634static int get_salen(sa) const struct sockaddr* sa;
Bernie Innocenti55864192018-08-30 04:05:20 +0900635{
Bernie Innocenti55864192018-08-30 04:05:20 +0900636#ifdef HAVE_SA_LEN
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900637 /* There are people do not set sa_len. Be forgiving to them. */
638 if (sa->sa_len) return (sa->sa_len);
Bernie Innocenti55864192018-08-30 04:05:20 +0900639#endif
640
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900641 if (sa->sa_family == AF_INET)
642 return (sizeof(struct sockaddr_in));
643 else if (sa->sa_family == AF_INET6)
644 return (sizeof(struct sockaddr_in6));
645 else
646 return (0); /* unknown, die on connect */
Bernie Innocenti55864192018-08-30 04:05:20 +0900647}
648
649/*
650 * pick appropriate nsaddr_list for use. see res_init() for initialization.
651 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900652static struct sockaddr* get_nsaddr(statp, n) res_state statp;
653size_t n;
Bernie Innocenti55864192018-08-30 04:05:20 +0900654{
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900655 if (!statp->nsaddr_list[n].sin_family && EXT(statp).ext) {
656 /*
657 * - EXT(statp).ext->nsaddrs[n] holds an address that is larger
658 * than struct sockaddr, and
659 * - user code did not update statp->nsaddr_list[n].
660 */
661 return (struct sockaddr*) (void*) &EXT(statp).ext->nsaddrs[n];
662 } else {
663 /*
664 * - user code updated statp->nsaddr_list[n], or
665 * - statp->nsaddr_list[n] has the same content as
666 * EXT(statp).ext->nsaddrs[n].
667 */
668 return (struct sockaddr*) (void*) &statp->nsaddr_list[n];
669 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900670}
671
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900672static struct timespec get_timeout(const res_state statp, const struct __res_params* params,
673 const int ns) {
674 int msec;
675 if (params->base_timeout_msec != 0) {
676 // TODO: scale the timeout by retry attempt and maybe number of servers
677 msec = params->base_timeout_msec;
678 } else {
679 // Legacy algorithm which scales the timeout by nameserver number.
680 // For instance, with 4 nameservers: 5s, 2.5s, 5s, 10s
681 // This has no effect with 1 or 2 nameservers
682 msec = (statp->retrans * 1000) << ns;
683 if (ns > 0) {
684 msec /= statp->nscount;
685 }
686 if (msec < 1000) {
687 msec = 1000; // Use at least 100ms
688 }
689 }
690 if (DBG) {
691 async_safe_format_log(ANDROID_LOG_DEBUG, "libc", "using timeout of %d msec\n", msec);
692 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900693
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900694 struct timespec result;
695 result.tv_sec = msec / 1000;
696 result.tv_nsec = (msec % 1000) * 1000000;
697 return result;
Bernie Innocenti55864192018-08-30 04:05:20 +0900698}
699
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900700static int send_vc(res_state statp, struct __res_params* params, const u_char* buf, int buflen,
701 u_char* ans, int anssiz, int* terrno, int ns, time_t* at, int* rcode,
702 int* delay) {
703 *at = time(NULL);
704 *rcode = RCODE_INTERNAL_ERROR;
705 *delay = 0;
706 const HEADER* hp = (const HEADER*) (const void*) buf;
707 HEADER* anhp = (HEADER*) (void*) ans;
708 struct sockaddr* nsap;
709 int nsaplen;
710 int truncating, connreset, resplen, n;
711 struct iovec iov[2];
712 u_short len;
713 u_char* cp;
714 void* tmp;
Bernie Innocenti55864192018-08-30 04:05:20 +0900715
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900716 if (DBG) {
717 async_safe_format_log(ANDROID_LOG_DEBUG, "libc", "using send_vc\n");
718 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900719
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900720 nsap = get_nsaddr(statp, (size_t) ns);
721 nsaplen = get_salen(nsap);
Bernie Innocenti55864192018-08-30 04:05:20 +0900722
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900723 connreset = 0;
724same_ns:
725 truncating = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900726
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900727 struct timespec now = evNowTime();
Bernie Innocenti55864192018-08-30 04:05:20 +0900728
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900729 /* Are we still talking to whom we want to talk to? */
730 if (statp->_vcsock >= 0 && (statp->_flags & RES_F_VC) != 0) {
731 struct sockaddr_storage peer;
732 socklen_t size = sizeof peer;
733 unsigned old_mark;
734 socklen_t mark_size = sizeof(old_mark);
735 if (getpeername(statp->_vcsock, (struct sockaddr*) (void*) &peer, &size) < 0 ||
736 !sock_eq((struct sockaddr*) (void*) &peer, nsap) ||
737 getsockopt(statp->_vcsock, SOL_SOCKET, SO_MARK, &old_mark, &mark_size) < 0 ||
738 old_mark != statp->_mark) {
739 res_nclose(statp);
740 statp->_flags &= ~RES_F_VC;
741 }
742 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900743
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900744 if (statp->_vcsock < 0 || (statp->_flags & RES_F_VC) == 0) {
745 if (statp->_vcsock >= 0) res_nclose(statp);
Bernie Innocenti55864192018-08-30 04:05:20 +0900746
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900747 statp->_vcsock = socket(nsap->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0);
748 if (statp->_vcsock < 0) {
749 switch (errno) {
750 case EPROTONOSUPPORT:
Bernie Innocenti55864192018-08-30 04:05:20 +0900751#ifdef EPFNOSUPPORT
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900752 case EPFNOSUPPORT:
Bernie Innocenti55864192018-08-30 04:05:20 +0900753#endif
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900754 case EAFNOSUPPORT:
755 Perror(statp, stderr, "socket(vc)", errno);
756 return (0);
757 default:
758 *terrno = errno;
759 Perror(statp, stderr, "socket(vc)", errno);
760 return (-1);
761 }
762 }
763 fchown(statp->_vcsock, AID_DNS, -1);
764 if (statp->_mark != MARK_UNSET) {
765 if (setsockopt(statp->_vcsock, SOL_SOCKET, SO_MARK, &statp->_mark,
766 sizeof(statp->_mark)) < 0) {
767 *terrno = errno;
768 Perror(statp, stderr, "setsockopt", errno);
769 return -1;
770 }
771 }
772 errno = 0;
773 if (random_bind(statp->_vcsock, nsap->sa_family) < 0) {
774 *terrno = errno;
775 Aerror(statp, stderr, "bind/vc", errno, nsap, nsaplen);
776 res_nclose(statp);
777 return (0);
778 }
779 if (connect_with_timeout(statp->_vcsock, nsap, (socklen_t) nsaplen,
780 get_timeout(statp, params, ns)) < 0) {
781 *terrno = errno;
782 Aerror(statp, stderr, "connect/vc", errno, nsap, nsaplen);
783 res_nclose(statp);
784 /*
785 * The way connect_with_timeout() is implemented prevents us from reliably
786 * determining whether this was really a timeout or e.g. ECONNREFUSED. Since
787 * currently both cases are handled in the same way, there is no need to
788 * change this (yet). If we ever need to reliably distinguish between these
789 * cases, both connect_with_timeout() and retrying_poll() need to be
790 * modified, though.
791 */
792 *rcode = RCODE_TIMEOUT;
793 return (0);
794 }
795 statp->_flags |= RES_F_VC;
796 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900797
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900798 /*
799 * Send length & message
800 */
801 ns_put16((u_short) buflen, (u_char*) (void*) &len);
802 iov[0] = evConsIovec(&len, INT16SZ);
803 DE_CONST(buf, tmp);
804 iov[1] = evConsIovec(tmp, (size_t) buflen);
805 if (writev(statp->_vcsock, iov, 2) != (INT16SZ + buflen)) {
806 *terrno = errno;
807 Perror(statp, stderr, "write failed", errno);
808 res_nclose(statp);
809 return (0);
810 }
811 /*
812 * Receive length & response
813 */
814read_len:
815 cp = ans;
816 len = INT16SZ;
817 while ((n = read(statp->_vcsock, (char*) cp, (size_t) len)) > 0) {
818 cp += n;
819 if ((len -= n) == 0) break;
820 }
821 if (n <= 0) {
822 *terrno = errno;
823 Perror(statp, stderr, "read failed", errno);
824 res_nclose(statp);
825 /*
826 * A long running process might get its TCP
827 * connection reset if the remote server was
828 * restarted. Requery the server instead of
829 * trying a new one. When there is only one
830 * server, this means that a query might work
831 * instead of failing. We only allow one reset
832 * per query to prevent looping.
833 */
834 if (*terrno == ECONNRESET && !connreset) {
835 connreset = 1;
836 res_nclose(statp);
837 goto same_ns;
838 }
839 res_nclose(statp);
840 return (0);
841 }
842 resplen = ns_get16(ans);
843 if (resplen > anssiz) {
844 Dprint(statp->options & RES_DEBUG, (stdout, ";; response truncated\n"));
845 truncating = 1;
846 len = anssiz;
847 } else
848 len = resplen;
849 if (len < HFIXEDSZ) {
850 /*
851 * Undersized message.
852 */
853 Dprint(statp->options & RES_DEBUG, (stdout, ";; undersized: %d\n", len));
854 *terrno = EMSGSIZE;
855 res_nclose(statp);
856 return (0);
857 }
858 cp = ans;
859 while (len != 0 && (n = read(statp->_vcsock, (char*) cp, (size_t) len)) > 0) {
860 cp += n;
861 len -= n;
862 }
863 if (n <= 0) {
864 *terrno = errno;
865 Perror(statp, stderr, "read(vc)", errno);
866 res_nclose(statp);
867 return (0);
868 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900869
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900870 if (truncating) {
871 /*
872 * Flush rest of answer so connection stays in synch.
873 */
874 anhp->tc = 1;
875 len = resplen - anssiz;
876 while (len != 0) {
877 char junk[PACKETSZ];
Bernie Innocenti55864192018-08-30 04:05:20 +0900878
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900879 n = read(statp->_vcsock, junk, (len > sizeof junk) ? sizeof junk : len);
880 if (n > 0)
881 len -= n;
882 else
883 break;
884 }
885 }
886 /*
887 * If the calling applicating has bailed out of
888 * a previous call and failed to arrange to have
889 * the circuit closed or the server has got
890 * itself confused, then drop the packet and
891 * wait for the correct one.
892 */
893 if (hp->id != anhp->id) {
894 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
895 (stdout, ";; old answer (unexpected):\n"), ans,
896 (resplen > anssiz) ? anssiz : resplen);
897 goto read_len;
898 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900899
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900900 /*
901 * All is well, or the error is fatal. Signal that the
902 * next nameserver ought not be tried.
903 */
904 if (resplen > 0) {
905 struct timespec done = evNowTime();
906 *delay = _res_stats_calculate_rtt(&done, &now);
907 *rcode = anhp->rcode;
908 }
909 return (resplen);
Bernie Innocenti55864192018-08-30 04:05:20 +0900910}
911
912/* return -1 on error (errno set), 0 on success */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900913static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
914 const struct timespec timeout) {
915 int res, origflags;
Bernie Innocenti55864192018-08-30 04:05:20 +0900916
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900917 origflags = fcntl(sock, F_GETFL, 0);
918 fcntl(sock, F_SETFL, origflags | O_NONBLOCK);
Bernie Innocenti55864192018-08-30 04:05:20 +0900919
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900920 res = __connect(sock, nsap, salen);
921 if (res < 0 && errno != EINPROGRESS) {
922 res = -1;
923 goto done;
924 }
925 if (res != 0) {
926 struct timespec now = evNowTime();
927 struct timespec finish = evAddTime(now, timeout);
928 if (DBG) {
929 async_safe_format_log(ANDROID_LOG_DEBUG, "libc", " %d send_vc\n", sock);
930 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900931
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900932 res = retrying_poll(sock, POLLIN | POLLOUT, &finish);
933 if (res <= 0) {
934 res = -1;
935 }
936 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900937done:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900938 fcntl(sock, F_SETFL, origflags);
939 if (DBG) {
940 async_safe_format_log(ANDROID_LOG_DEBUG, "libc",
941 " %d connect_with_const timeout returning %d\n", sock, res);
942 }
943 return res;
Bernie Innocenti55864192018-08-30 04:05:20 +0900944}
945
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900946static int retrying_poll(const int sock, const short events, const struct timespec* finish) {
947 struct timespec now, timeout;
Bernie Innocenti55864192018-08-30 04:05:20 +0900948
949retry:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900950 if (DBG) {
951 async_safe_format_log(ANDROID_LOG_DEBUG, "libc", " %d retrying_poll\n", sock);
952 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900953
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900954 now = evNowTime();
955 if (evCmpTime(*finish, now) > 0)
956 timeout = evSubTime(*finish, now);
957 else
958 timeout = evConsTime(0L, 0L);
959 struct pollfd fds = {.fd = sock, .events = events};
960 int n = ppoll(&fds, 1, &timeout, /*sigmask=*/NULL);
961 if (n == 0) {
962 if (DBG) {
963 async_safe_format_log(ANDROID_LOG_DEBUG, "libc", " %d retrying_poll timeout\n", sock);
964 }
965 errno = ETIMEDOUT;
966 return 0;
967 }
968 if (n < 0) {
969 if (errno == EINTR) goto retry;
970 if (DBG) {
971 async_safe_format_log(ANDROID_LOG_DEBUG, "libc", " %d retrying_poll got error %d\n",
972 sock, n);
973 }
974 return n;
975 }
976 if (fds.revents & (POLLIN | POLLOUT | POLLERR)) {
977 int error;
978 socklen_t len = sizeof(error);
979 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error) {
980 errno = error;
981 if (DBG) {
982 async_safe_format_log(ANDROID_LOG_DEBUG, "libc",
983 " %d retrying_poll dot error2 %d\n", sock, errno);
984 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900985
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900986 return -1;
987 }
988 }
989 if (DBG) {
990 async_safe_format_log(ANDROID_LOG_DEBUG, "libc", " %d retrying_poll returning %d\n", sock,
991 n);
992 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900993
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900994 return n;
Bernie Innocenti55864192018-08-30 04:05:20 +0900995}
996
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900997static int send_dg(res_state statp, struct __res_params* params, const u_char* buf, int buflen,
998 u_char* ans, int anssiz, int* terrno, int ns, int* v_circuit, int* gotsomewhere,
999 time_t* at, int* rcode, int* delay) {
1000 *at = time(NULL);
1001 *rcode = RCODE_INTERNAL_ERROR;
1002 *delay = 0;
1003 const HEADER* hp = (const HEADER*) (const void*) buf;
1004 HEADER* anhp = (HEADER*) (void*) ans;
1005 const struct sockaddr* nsap;
1006 int nsaplen;
1007 struct timespec now, timeout, finish, done;
1008 struct sockaddr_storage from;
1009 socklen_t fromlen;
1010 int resplen, n, s;
Bernie Innocenti55864192018-08-30 04:05:20 +09001011
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001012 nsap = get_nsaddr(statp, (size_t) ns);
1013 nsaplen = get_salen(nsap);
1014 if (EXT(statp).nssocks[ns] == -1) {
1015 EXT(statp).nssocks[ns] = socket(nsap->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
1016 if (EXT(statp).nssocks[ns] < 0) {
1017 switch (errno) {
1018 case EPROTONOSUPPORT:
Bernie Innocenti55864192018-08-30 04:05:20 +09001019#ifdef EPFNOSUPPORT
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001020 case EPFNOSUPPORT:
Bernie Innocenti55864192018-08-30 04:05:20 +09001021#endif
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001022 case EAFNOSUPPORT:
1023 Perror(statp, stderr, "socket(dg)", errno);
1024 return (0);
1025 default:
1026 *terrno = errno;
1027 Perror(statp, stderr, "socket(dg)", errno);
1028 return (-1);
1029 }
1030 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001031
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001032 fchown(EXT(statp).nssocks[ns], AID_DNS, -1);
1033 if (statp->_mark != MARK_UNSET) {
1034 if (setsockopt(EXT(statp).nssocks[ns], SOL_SOCKET, SO_MARK, &(statp->_mark),
1035 sizeof(statp->_mark)) < 0) {
1036 res_nclose(statp);
1037 return -1;
1038 }
1039 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001040#ifndef CANNOT_CONNECT_DGRAM
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001041 /*
1042 * On a 4.3BSD+ machine (client and server,
1043 * actually), sending to a nameserver datagram
1044 * port with no nameserver will cause an
1045 * ICMP port unreachable message to be returned.
1046 * If our datagram socket is "connected" to the
1047 * server, we get an ECONNREFUSED error on the next
1048 * socket operation, and select returns if the
1049 * error message is received. We can thus detect
1050 * the absence of a nameserver without timing out.
1051 */
1052 if (random_bind(EXT(statp).nssocks[ns], nsap->sa_family) < 0) {
1053 Aerror(statp, stderr, "bind(dg)", errno, nsap, nsaplen);
1054 res_nclose(statp);
1055 return (0);
1056 }
1057 if (__connect(EXT(statp).nssocks[ns], nsap, (socklen_t) nsaplen) < 0) {
1058 Aerror(statp, stderr, "connect(dg)", errno, nsap, nsaplen);
1059 res_nclose(statp);
1060 return (0);
1061 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001062#endif /* !CANNOT_CONNECT_DGRAM */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001063 Dprint(statp->options & RES_DEBUG, (stdout, ";; new DG socket\n"))
1064 }
1065 s = EXT(statp).nssocks[ns];
Bernie Innocenti55864192018-08-30 04:05:20 +09001066#ifndef CANNOT_CONNECT_DGRAM
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001067 if (send(s, (const char*) buf, (size_t) buflen, 0) != buflen) {
1068 Perror(statp, stderr, "send", errno);
1069 res_nclose(statp);
1070 return (0);
1071 }
1072#else /* !CANNOT_CONNECT_DGRAM */
1073 if (sendto(s, (const char*) buf, buflen, 0, nsap, nsaplen) != buflen) {
1074 Aerror(statp, stderr, "sendto", errno, nsap, nsaplen);
1075 res_nclose(statp);
1076 return (0);
1077 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001078#endif /* !CANNOT_CONNECT_DGRAM */
1079
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001080 /*
1081 * Wait for reply.
1082 */
1083 timeout = get_timeout(statp, params, ns);
1084 now = evNowTime();
1085 finish = evAddTime(now, timeout);
Bernie Innocenti55864192018-08-30 04:05:20 +09001086retry:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001087 n = retrying_poll(s, POLLIN, &finish);
Bernie Innocenti55864192018-08-30 04:05:20 +09001088
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001089 if (n == 0) {
1090 *rcode = RCODE_TIMEOUT;
1091 Dprint(statp->options & RES_DEBUG, (stdout, ";; timeout\n"));
1092 *gotsomewhere = 1;
1093 return (0);
1094 }
1095 if (n < 0) {
1096 Perror(statp, stderr, "poll", errno);
1097 res_nclose(statp);
1098 return (0);
1099 }
1100 errno = 0;
1101 fromlen = sizeof(from);
1102 resplen = recvfrom(s, (char*) ans, (size_t) anssiz, 0, (struct sockaddr*) (void*) &from,
1103 &fromlen);
1104 if (resplen <= 0) {
1105 Perror(statp, stderr, "recvfrom", errno);
1106 res_nclose(statp);
1107 return (0);
1108 }
1109 *gotsomewhere = 1;
1110 if (resplen < HFIXEDSZ) {
1111 /*
1112 * Undersized message.
1113 */
1114 Dprint(statp->options & RES_DEBUG, (stdout, ";; undersized: %d\n", resplen));
1115 *terrno = EMSGSIZE;
1116 res_nclose(statp);
1117 return (0);
1118 }
1119 if (hp->id != anhp->id) {
1120 /*
1121 * response from old query, ignore it.
1122 * XXX - potential security hazard could
1123 * be detected here.
1124 */
1125 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
1126 (stdout, ";; old answer:\n"), ans, (resplen > anssiz) ? anssiz : resplen);
1127 goto retry;
1128 }
1129 if (!(statp->options & RES_INSECURE1) &&
1130 !res_ourserver_p(statp, (struct sockaddr*) (void*) &from)) {
1131 /*
1132 * response from wrong server? ignore it.
1133 * XXX - potential security hazard could
1134 * be detected here.
1135 */
1136 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
1137 (stdout, ";; not our server:\n"), ans, (resplen > anssiz) ? anssiz : resplen);
1138 goto retry;
1139 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001140#ifdef RES_USE_EDNS0
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001141 if (anhp->rcode == FORMERR && (statp->options & RES_USE_EDNS0) != 0U) {
1142 /*
1143 * Do not retry if the server do not understand EDNS0.
1144 * The case has to be captured here, as FORMERR packet do not
1145 * carry query section, hence res_queriesmatch() returns 0.
1146 */
1147 DprintQ(statp->options & RES_DEBUG, (stdout, "server rejected query with EDNS0:\n"), ans,
1148 (resplen > anssiz) ? anssiz : resplen);
1149 /* record the error */
1150 statp->_flags |= RES_F_EDNS0ERR;
1151 res_nclose(statp);
1152 return (0);
1153 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001154#endif
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001155 if (!(statp->options & RES_INSECURE2) &&
1156 !res_queriesmatch(buf, buf + buflen, ans, ans + anssiz)) {
1157 /*
1158 * response contains wrong query? ignore it.
1159 * XXX - potential security hazard could
1160 * be detected here.
1161 */
1162 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
1163 (stdout, ";; wrong query name:\n"), ans, (resplen > anssiz) ? anssiz : resplen);
1164 goto retry;
1165 ;
1166 }
1167 done = evNowTime();
1168 *delay = _res_stats_calculate_rtt(&done, &now);
1169 if (anhp->rcode == SERVFAIL || anhp->rcode == NOTIMP || anhp->rcode == REFUSED) {
1170 DprintQ(statp->options & RES_DEBUG, (stdout, "server rejected query:\n"), ans,
1171 (resplen > anssiz) ? anssiz : resplen);
1172 res_nclose(statp);
1173 /* don't retry if called from dig */
1174 if (!statp->pfcode) {
1175 *rcode = anhp->rcode;
1176 return (0);
1177 }
1178 }
1179 if (!(statp->options & RES_IGNTC) && anhp->tc) {
1180 /*
1181 * To get the rest of answer,
1182 * use TCP with same server.
1183 */
1184 Dprint(statp->options & RES_DEBUG, (stdout, ";; truncated answer\n"));
1185 *v_circuit = 1;
1186 res_nclose(statp);
1187 return (1);
1188 }
1189 /*
1190 * All is well, or the error is fatal. Signal that the
1191 * next nameserver ought not be tried.
1192 */
1193 if (resplen > 0) {
1194 *rcode = anhp->rcode;
1195 }
1196 return (resplen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001197}
1198
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001199static void Aerror(const res_state statp, FILE* file, const char* string, int error,
1200 const struct sockaddr* address, int alen) {
1201 int save = errno;
1202 char hbuf[NI_MAXHOST];
1203 char sbuf[NI_MAXSERV];
Bernie Innocenti55864192018-08-30 04:05:20 +09001204
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001205 if ((statp->options & RES_DEBUG) != 0U) {
1206 if (getnameinfo(address, (socklen_t) alen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
1207 niflags)) {
1208 strncpy(hbuf, "?", sizeof(hbuf) - 1);
1209 hbuf[sizeof(hbuf) - 1] = '\0';
1210 strncpy(sbuf, "?", sizeof(sbuf) - 1);
1211 sbuf[sizeof(sbuf) - 1] = '\0';
1212 }
1213 fprintf(file, "res_send: %s ([%s].%s): %s\n", string, hbuf, sbuf, strerror(error));
1214 }
1215 errno = save;
Bernie Innocenti55864192018-08-30 04:05:20 +09001216}
1217
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001218static void Perror(const res_state statp, FILE* file, const char* string, int error) {
1219 int save = errno;
Bernie Innocenti55864192018-08-30 04:05:20 +09001220
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001221 if ((statp->options & RES_DEBUG) != 0U)
1222 fprintf(file, "res_send: %s: %s\n", string, strerror(error));
1223 errno = save;
Bernie Innocenti55864192018-08-30 04:05:20 +09001224}
1225
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001226static int sock_eq(struct sockaddr* a, struct sockaddr* b) {
1227 struct sockaddr_in *a4, *b4;
1228 struct sockaddr_in6 *a6, *b6;
Bernie Innocenti55864192018-08-30 04:05:20 +09001229
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001230 if (a->sa_family != b->sa_family) return 0;
1231 switch (a->sa_family) {
1232 case AF_INET:
1233 a4 = (struct sockaddr_in*) (void*) a;
1234 b4 = (struct sockaddr_in*) (void*) b;
1235 return a4->sin_port == b4->sin_port && a4->sin_addr.s_addr == b4->sin_addr.s_addr;
1236 case AF_INET6:
1237 a6 = (struct sockaddr_in6*) (void*) a;
1238 b6 = (struct sockaddr_in6*) (void*) b;
1239 return a6->sin6_port == b6->sin6_port &&
Bernie Innocenti55864192018-08-30 04:05:20 +09001240#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001241 a6->sin6_scope_id == b6->sin6_scope_id &&
Bernie Innocenti55864192018-08-30 04:05:20 +09001242#endif
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001243 IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
1244 default:
1245 return 0;
1246 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001247}