blob: ebac86219be4351c413e922b830f1c7ade48a9d3 [file] [log] [blame]
Bernie Innocenti55864192018-08-30 04:05:20 +09001/* $NetBSD: res_send.c,v 1.9 2006/01/24 17:41:25 christos Exp $ */
2
3/*
4 * Copyright (c) 1985, 1989, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. All advertising materials mentioning features or use of this software
16 * must display the following acknowledgement:
17 * This product includes software developed by the University of
18 * California, Berkeley and its contributors.
19 * 4. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 */
35
36/*
37 * Portions Copyright (c) 1993 by Digital Equipment Corporation.
38 *
39 * Permission to use, copy, modify, and distribute this software for any
40 * purpose with or without fee is hereby granted, provided that the above
41 * copyright notice and this permission notice appear in all copies, and that
42 * the name of Digital Equipment Corporation not be used in advertising or
43 * publicity pertaining to distribution of the document or software without
44 * specific, written prior permission.
45 *
46 * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
47 * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
48 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
49 * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
50 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
51 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
52 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
53 * SOFTWARE.
54 */
55
56/*
57 * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
58 * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
59 *
60 * Permission to use, copy, modify, and distribute this software for any
61 * purpose with or without fee is hereby granted, provided that the above
62 * copyright notice and this permission notice appear in all copies.
63 *
64 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
65 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
66 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR
67 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
68 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
69 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
70 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
71 */
72
Bernie Innocenti55864192018-08-30 04:05:20 +090073/*
74 * Send query to name server and wait for reply.
75 */
76
Bernie Innocenti55864192018-08-30 04:05:20 +090077#include <sys/param.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090078#include <sys/socket.h>
Bernie Innocentif12d5bb2018-08-31 14:09:46 +090079#include <sys/time.h>
80#include <sys/types.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090081#include <sys/uio.h>
82
Bernie Innocenti55864192018-08-30 04:05:20 +090083#include <arpa/inet.h>
Bernie Innocentif12d5bb2018-08-31 14:09:46 +090084#include <arpa/nameser.h>
85#include <netinet/in.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090086
87#include <errno.h>
88#include <fcntl.h>
89#include <netdb.h>
90#include <poll.h>
Bernie Innocenti55864192018-08-30 04:05:20 +090091#include <signal.h>
92#include <stdio.h>
93#include <stdlib.h>
94#include <string.h>
95#include <time.h>
96#include <unistd.h>
97
Bernie Innocenti55864192018-08-30 04:05:20 +090098#include <async_safe/log.h>
99
Bernie Innocenti2fd418e2018-08-30 12:04:03 +0900100#include "private/android_filesystem_config.h"
101#include "res_private.h"
102#include "resolv_cache.h"
103#include "resolv_netid.h"
104#include "resolv_private.h"
105#include "resolv_stats.h"
106
Bernie Innocenti55864192018-08-30 04:05:20 +0900107#ifndef DE_CONST
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900108#define DE_CONST(c, v) \
109 v = ((c) ? strchr((const void*) (c), *(const char*) (const void*) (c)) : NULL)
Bernie Innocenti55864192018-08-30 04:05:20 +0900110#endif
111
112/* Options. Leave them on. */
113#ifndef DEBUG
114#define DEBUG
115#endif
Bernie Innocenti2fd418e2018-08-30 12:04:03 +0900116
Bernie Innocenti55864192018-08-30 04:05:20 +0900117#include "res_debug.h"
Bernie Innocenti55864192018-08-30 04:05:20 +0900118
119#define EXT(res) ((res)->_u._ext)
120#define DBG 0
121
122/* Forward. */
123
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900124static int get_salen __P((const struct sockaddr*) );
125static struct sockaddr* get_nsaddr __P((res_state, size_t));
126static int send_vc(res_state, struct __res_params* params, const u_char*, int, u_char*, int, int*,
127 int, time_t*, int*, int*);
128static int send_dg(res_state, struct __res_params* params, const u_char*, int, u_char*, int, int*,
129 int, int*, int*, time_t*, int*, int*);
130static void Aerror(const res_state, FILE*, const char*, int, const struct sockaddr*, int);
131static void Perror(const res_state, FILE*, const char*, int);
132static int sock_eq(struct sockaddr*, struct sockaddr*);
133void res_pquery(const res_state, const u_char*, int, FILE*);
134static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
135 const struct timespec timeout);
Bernie Innocenti55864192018-08-30 04:05:20 +0900136static int retrying_poll(const int sock, short events, const struct timespec* finish);
137
138/* BIONIC-BEGIN: implement source port randomization */
139typedef union {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900140 struct sockaddr sa;
141 struct sockaddr_in sin;
142 struct sockaddr_in6 sin6;
Bernie Innocenti55864192018-08-30 04:05:20 +0900143} _sockaddr_union;
144
Bernie Innocentif89b3512018-08-30 07:34:37 +0900145// BEGIN: Code copied from ISC eventlib
146// TODO: move away from this code
147
148#define BILLION 1000000000
149
150static struct timespec evConsTime(time_t sec, long nsec) {
151 struct timespec x;
152
153 x.tv_sec = sec;
154 x.tv_nsec = nsec;
155 return (x);
156}
157
158static struct timespec evAddTime(struct timespec addend1, struct timespec addend2) {
159 struct timespec x;
160
161 x.tv_sec = addend1.tv_sec + addend2.tv_sec;
162 x.tv_nsec = addend1.tv_nsec + addend2.tv_nsec;
163 if (x.tv_nsec >= BILLION) {
164 x.tv_sec++;
165 x.tv_nsec -= BILLION;
166 }
167 return (x);
168}
169
170static struct timespec evSubTime(struct timespec minuend, struct timespec subtrahend) {
171 struct timespec x;
172
173 x.tv_sec = minuend.tv_sec - subtrahend.tv_sec;
174 if (minuend.tv_nsec >= subtrahend.tv_nsec)
175 x.tv_nsec = minuend.tv_nsec - subtrahend.tv_nsec;
176 else {
177 x.tv_nsec = BILLION - subtrahend.tv_nsec + minuend.tv_nsec;
178 x.tv_sec--;
179 }
180 return (x);
181}
182
183static int evCmpTime(struct timespec a, struct timespec b) {
184#define SGN(x) ((x) < 0 ? (-1) : (x) > 0 ? (1) : (0));
185 time_t s = a.tv_sec - b.tv_sec;
186 long n;
187
188 if (s != 0) return SGN(s);
189
190 n = a.tv_nsec - b.tv_nsec;
191 return SGN(n);
192}
193
Bernie Innocentif89b3512018-08-30 07:34:37 +0900194static struct timespec evNowTime(void) {
Bernie Innocentif89b3512018-08-30 07:34:37 +0900195 struct timespec tsnow;
Bernie Innocenti357339c2018-08-31 16:11:41 +0900196 clock_gettime(CLOCK_REALTIME, &tsnow);
197 return tsnow;
Bernie Innocentif89b3512018-08-30 07:34:37 +0900198}
199
200static struct iovec evConsIovec(void* buf, size_t cnt) {
201 struct iovec ret;
202
203 memset(&ret, 0xf5, sizeof ret);
204 ret.iov_base = buf;
205 ret.iov_len = cnt;
Bernie Innocenti357339c2018-08-31 16:11:41 +0900206 return ret;
Bernie Innocentif89b3512018-08-30 07:34:37 +0900207}
208
209// END: Code copied from ISC eventlib
210
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900211static int random_bind(int s, int family) {
212 _sockaddr_union u;
213 int j;
214 socklen_t slen;
Bernie Innocenti55864192018-08-30 04:05:20 +0900215
216 /* clear all, this also sets the IP4/6 address to 'any' */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900217 memset(&u, 0, sizeof u);
Bernie Innocenti55864192018-08-30 04:05:20 +0900218
219 switch (family) {
220 case AF_INET:
221 u.sin.sin_family = family;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900222 slen = sizeof u.sin;
Bernie Innocenti55864192018-08-30 04:05:20 +0900223 break;
224 case AF_INET6:
225 u.sin6.sin6_family = family;
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900226 slen = sizeof u.sin6;
Bernie Innocenti55864192018-08-30 04:05:20 +0900227 break;
228 default:
229 errno = EPROTO;
230 return -1;
231 }
232
233 /* first try to bind to a random source port a few times */
234 for (j = 0; j < 10; j++) {
235 /* find a random port between 1025 .. 65534 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900236 int port = 1025 + (res_randomid() % (65535 - 1025));
Bernie Innocenti55864192018-08-30 04:05:20 +0900237 if (family == AF_INET)
238 u.sin.sin_port = htons(port);
239 else
240 u.sin6.sin6_port = htons(port);
241
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900242 if (!bind(s, &u.sa, slen)) return 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900243 }
244
245 /* nothing after 10 tries, our network table is probably busy */
246 /* let the system decide which port is best */
247 if (family == AF_INET)
248 u.sin.sin_port = 0;
249 else
250 u.sin6.sin6_port = 0;
251
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900252 return bind(s, &u.sa, slen);
Bernie Innocenti55864192018-08-30 04:05:20 +0900253}
254/* BIONIC-END */
255
256static const int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
257
258/* Public. */
259
260/* int
261 * res_isourserver(ina)
262 * looks up "ina" in _res.ns_addr_list[]
263 * returns:
264 * 0 : not found
265 * >0 : found
266 * author:
267 * paul vixie, 29may94
268 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900269__LIBC_HIDDEN__ int res_ourserver_p(const res_state statp, const struct sockaddr* sa) {
270 const struct sockaddr_in *inp, *srv;
271 const struct sockaddr_in6 *in6p, *srv6;
272 int ns;
Bernie Innocenti55864192018-08-30 04:05:20 +0900273
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900274 switch (sa->sa_family) {
275 case AF_INET:
276 inp = (const struct sockaddr_in*) (const void*) sa;
277 for (ns = 0; ns < statp->nscount; ns++) {
278 srv = (struct sockaddr_in*) (void*) get_nsaddr(statp, (size_t) ns);
279 if (srv->sin_family == inp->sin_family && srv->sin_port == inp->sin_port &&
280 (srv->sin_addr.s_addr == INADDR_ANY ||
281 srv->sin_addr.s_addr == inp->sin_addr.s_addr))
282 return (1);
283 }
284 break;
285 case AF_INET6:
286 if (EXT(statp).ext == NULL) break;
287 in6p = (const struct sockaddr_in6*) (const void*) sa;
288 for (ns = 0; ns < statp->nscount; ns++) {
289 srv6 = (struct sockaddr_in6*) (void*) get_nsaddr(statp, (size_t) ns);
290 if (srv6->sin6_family == in6p->sin6_family && srv6->sin6_port == in6p->sin6_port &&
Bernie Innocenti55864192018-08-30 04:05:20 +0900291#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900292 (srv6->sin6_scope_id == 0 || srv6->sin6_scope_id == in6p->sin6_scope_id) &&
Bernie Innocenti55864192018-08-30 04:05:20 +0900293#endif
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900294 (IN6_IS_ADDR_UNSPECIFIED(&srv6->sin6_addr) ||
295 IN6_ARE_ADDR_EQUAL(&srv6->sin6_addr, &in6p->sin6_addr)))
296 return (1);
297 }
298 break;
299 default:
300 break;
301 }
302 return (0);
Bernie Innocenti55864192018-08-30 04:05:20 +0900303}
304
305/* int
306 * res_nameinquery(name, type, class, buf, eom)
307 * look for (name,type,class) in the query section of packet (buf,eom)
308 * requires:
309 * buf + HFIXEDSZ <= eom
310 * returns:
311 * -1 : format error
312 * 0 : not found
313 * >0 : found
314 * author:
315 * paul vixie, 29may94
316 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900317int res_nameinquery(const char* name, int type, int class, const u_char* buf, const u_char* eom) {
318 const u_char* cp = buf + HFIXEDSZ;
319 int qdcount = ntohs(((const HEADER*) (const void*) buf)->qdcount);
Bernie Innocenti55864192018-08-30 04:05:20 +0900320
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900321 while (qdcount-- > 0) {
322 char tname[MAXDNAME + 1];
323 int n, ttype, tclass;
Bernie Innocenti55864192018-08-30 04:05:20 +0900324
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900325 n = dn_expand(buf, eom, cp, tname, sizeof tname);
326 if (n < 0) return (-1);
327 cp += n;
328 if (cp + 2 * INT16SZ > eom) return (-1);
329 ttype = ns_get16(cp);
330 cp += INT16SZ;
331 tclass = ns_get16(cp);
332 cp += INT16SZ;
333 if (ttype == type && tclass == class && ns_samename(tname, name) == 1) return (1);
334 }
335 return (0);
Bernie Innocenti55864192018-08-30 04:05:20 +0900336}
337
338/* int
339 * res_queriesmatch(buf1, eom1, buf2, eom2)
340 * is there a 1:1 mapping of (name,type,class)
341 * in (buf1,eom1) and (buf2,eom2)?
342 * returns:
343 * -1 : format error
344 * 0 : not a 1:1 mapping
345 * >0 : is a 1:1 mapping
346 * author:
347 * paul vixie, 29may94
348 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900349int res_queriesmatch(const u_char* buf1, const u_char* eom1, const u_char* buf2,
350 const u_char* eom2) {
351 const u_char* cp = buf1 + HFIXEDSZ;
352 int qdcount = ntohs(((const HEADER*) (const void*) buf1)->qdcount);
Bernie Innocenti55864192018-08-30 04:05:20 +0900353
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900354 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2) return (-1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900355
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900356 /*
357 * Only header section present in replies to
358 * dynamic update packets.
359 */
360 if ((((const HEADER*) (const void*) buf1)->opcode == ns_o_update) &&
361 (((const HEADER*) (const void*) buf2)->opcode == ns_o_update))
362 return (1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900363
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900364 if (qdcount != ntohs(((const HEADER*) (const void*) buf2)->qdcount)) return (0);
365 while (qdcount-- > 0) {
366 char tname[MAXDNAME + 1];
367 int n, ttype, tclass;
Bernie Innocenti55864192018-08-30 04:05:20 +0900368
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900369 n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
370 if (n < 0) return (-1);
371 cp += n;
372 if (cp + 2 * INT16SZ > eom1) return (-1);
373 ttype = ns_get16(cp);
374 cp += INT16SZ;
375 tclass = ns_get16(cp);
376 cp += INT16SZ;
377 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2)) return (0);
378 }
379 return (1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900380}
381
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900382int res_nsend(res_state statp, const u_char* buf, int buflen, u_char* ans, int anssiz) {
383 int gotsomewhere, terrno, try
384 , v_circuit, resplen, ns, n;
385 char abuf[NI_MAXHOST];
386 ResolvCacheStatus cache_status = RESOLV_CACHE_UNSUPPORTED;
Bernie Innocenti55864192018-08-30 04:05:20 +0900387
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900388 if (anssiz < HFIXEDSZ) {
389 errno = EINVAL;
390 return (-1);
391 }
392 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_QUERY),
393 (stdout, ";; res_send()\n"), buf, buflen);
394 v_circuit = (statp->options & RES_USEVC) || buflen > PACKETSZ;
395 gotsomewhere = 0;
396 terrno = ETIMEDOUT;
Bernie Innocenti55864192018-08-30 04:05:20 +0900397
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900398 int anslen = 0;
399 cache_status = _resolv_cache_lookup(statp->netid, buf, buflen, ans, anssiz, &anslen);
Bernie Innocenti55864192018-08-30 04:05:20 +0900400
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900401 if (cache_status == RESOLV_CACHE_FOUND) {
402 return anslen;
403 } else if (cache_status != RESOLV_CACHE_UNSUPPORTED) {
404 // had a cache miss for a known network, so populate the thread private
405 // data so the normal resolve path can do its thing
406 _resolv_populate_res_for_net(statp);
407 }
408 if (statp->nscount == 0) {
409 // We have no nameservers configured, so there's no point trying.
410 // Tell the cache the query failed, or any retries and anyone else asking the same
411 // question will block for PENDING_REQUEST_TIMEOUT seconds instead of failing fast.
412 _resolv_cache_query_failed(statp->netid, buf, buflen);
413 errno = ESRCH;
414 return (-1);
415 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900416
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900417 /*
418 * If the ns_addr_list in the resolver context has changed, then
419 * invalidate our cached copy and the associated timing data.
420 */
421 if (EXT(statp).nscount != 0) {
422 int needclose = 0;
423 struct sockaddr_storage peer;
424 socklen_t peerlen;
Bernie Innocenti55864192018-08-30 04:05:20 +0900425
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900426 if (EXT(statp).nscount != statp->nscount) {
427 needclose++;
428 } else {
429 for (ns = 0; ns < statp->nscount; ns++) {
430 if (statp->nsaddr_list[ns].sin_family &&
431 !sock_eq((struct sockaddr*) (void*) &statp->nsaddr_list[ns],
432 (struct sockaddr*) (void*) &EXT(statp).ext->nsaddrs[ns])) {
433 needclose++;
434 break;
435 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900436
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900437 if (EXT(statp).nssocks[ns] == -1) continue;
438 peerlen = sizeof(peer);
439 if (getpeername(EXT(statp).nssocks[ns], (struct sockaddr*) (void*) &peer,
440 &peerlen) < 0) {
441 needclose++;
442 break;
443 }
444 if (!sock_eq((struct sockaddr*) (void*) &peer, get_nsaddr(statp, (size_t) ns))) {
445 needclose++;
446 break;
447 }
448 }
449 }
450 if (needclose) {
451 res_nclose(statp);
452 EXT(statp).nscount = 0;
453 }
454 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900455
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900456 /*
457 * Maybe initialize our private copy of the ns_addr_list.
458 */
459 if (EXT(statp).nscount == 0) {
460 for (ns = 0; ns < statp->nscount; ns++) {
461 EXT(statp).nstimes[ns] = RES_MAXTIME;
462 EXT(statp).nssocks[ns] = -1;
463 if (!statp->nsaddr_list[ns].sin_family) continue;
464 EXT(statp).ext->nsaddrs[ns].sin = statp->nsaddr_list[ns];
465 }
466 EXT(statp).nscount = statp->nscount;
467 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900468
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900469 /*
470 * Some resolvers want to even out the load on their nameservers.
471 * Note that RES_BLAST overrides RES_ROTATE.
472 */
473 if ((statp->options & RES_ROTATE) != 0U && (statp->options & RES_BLAST) == 0U) {
474 union res_sockaddr_union inu;
475 struct sockaddr_in ina;
476 int lastns = statp->nscount - 1;
477 int fd;
478 u_int16_t nstime;
Bernie Innocenti55864192018-08-30 04:05:20 +0900479
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900480 if (EXT(statp).ext != NULL) inu = EXT(statp).ext->nsaddrs[0];
481 ina = statp->nsaddr_list[0];
482 fd = EXT(statp).nssocks[0];
483 nstime = EXT(statp).nstimes[0];
484 for (ns = 0; ns < lastns; ns++) {
485 if (EXT(statp).ext != NULL)
486 EXT(statp).ext->nsaddrs[ns] = EXT(statp).ext->nsaddrs[ns + 1];
487 statp->nsaddr_list[ns] = statp->nsaddr_list[ns + 1];
488 EXT(statp).nssocks[ns] = EXT(statp).nssocks[ns + 1];
489 EXT(statp).nstimes[ns] = EXT(statp).nstimes[ns + 1];
490 }
491 if (EXT(statp).ext != NULL) EXT(statp).ext->nsaddrs[lastns] = inu;
492 statp->nsaddr_list[lastns] = ina;
493 EXT(statp).nssocks[lastns] = fd;
494 EXT(statp).nstimes[lastns] = nstime;
495 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900496
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900497 /*
498 * Send request, RETRY times, or until successful.
499 */
500 for (try = 0; try < statp->retry; try ++) {
501 struct __res_stats stats[MAXNS];
502 struct __res_params params;
503 int revision_id = _resolv_cache_get_resolver_stats(statp->netid, &params, stats);
504 bool usable_servers[MAXNS];
505 android_net_res_stats_get_usable_servers(&params, stats, statp->nscount, usable_servers);
Bernie Innocenti55864192018-08-30 04:05:20 +0900506
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900507 for (ns = 0; ns < statp->nscount; ns++) {
508 if (!usable_servers[ns]) continue;
509 struct sockaddr* nsap;
510 int nsaplen;
511 time_t now = 0;
512 int rcode = RCODE_INTERNAL_ERROR;
513 int delay = 0;
514 nsap = get_nsaddr(statp, (size_t) ns);
515 nsaplen = get_salen(nsap);
516 statp->_flags &= ~RES_F_LASTMASK;
517 statp->_flags |= (ns << RES_F_LASTSHIFT);
Bernie Innocenti55864192018-08-30 04:05:20 +0900518
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900519 same_ns:
520 if (statp->qhook) {
521 int done = 0, loops = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900522
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900523 do {
524 res_sendhookact act;
Bernie Innocenti55864192018-08-30 04:05:20 +0900525
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900526 act = (*statp->qhook)(&nsap, &buf, &buflen, ans, anssiz, &resplen);
527 switch (act) {
528 case res_goahead:
529 done = 1;
530 break;
531 case res_nextns:
532 res_nclose(statp);
533 goto next_ns;
534 case res_done:
535 if (cache_status == RESOLV_CACHE_NOTFOUND) {
536 _resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
537 }
538 return (resplen);
539 case res_modified:
540 /* give the hook another try */
541 if (++loops < 42) /*doug adams*/
542 break;
543 /*FALLTHROUGH*/
544 case res_error:
545 /*FALLTHROUGH*/
546 default:
547 goto fail;
548 }
549 } while (!done);
550 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900551
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900552 Dprint(((statp->options & RES_DEBUG) &&
553 getnameinfo(nsap, (socklen_t) nsaplen, abuf, sizeof(abuf), NULL, 0, niflags) ==
554 0),
555 (stdout, ";; Querying server (# %d) address = %s\n", ns + 1, abuf));
Bernie Innocenti55864192018-08-30 04:05:20 +0900556
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900557 if (v_circuit) {
558 /* Use VC; at most one attempt per server. */
559 try
560 = statp->retry;
Bernie Innocenti55864192018-08-30 04:05:20 +0900561
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900562 n = send_vc(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &now, &rcode,
563 &delay);
Bernie Innocenti55864192018-08-30 04:05:20 +0900564
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900565 /*
566 * Only record stats the first time we try a query. This ensures that
567 * queries that deterministically fail (e.g., a name that always returns
568 * SERVFAIL or times out) do not unduly affect the stats.
569 */
570 if (try == 0) {
571 struct __res_sample sample;
572 _res_stats_set_sample(&sample, now, rcode, delay);
573 _resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, ns, &sample,
574 params.max_samples);
575 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900576
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900577 if (DBG) {
578 async_safe_format_log(ANDROID_LOG_DEBUG, "libc", "used send_vc %d\n", n);
579 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900580
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900581 if (n < 0) goto fail;
582 if (n == 0) goto next_ns;
583 resplen = n;
584 } else {
585 /* Use datagrams. */
586 if (DBG) {
587 async_safe_format_log(ANDROID_LOG_DEBUG, "libc", "using send_dg\n");
588 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900589
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900590 n = send_dg(statp, &params, buf, buflen, ans, anssiz, &terrno, ns, &v_circuit,
591 &gotsomewhere, &now, &rcode, &delay);
Bernie Innocenti55864192018-08-30 04:05:20 +0900592
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900593 /* Only record stats the first time we try a query. See above. */
594 if (try == 0) {
595 struct __res_sample sample;
596 _res_stats_set_sample(&sample, now, rcode, delay);
597 _resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, ns, &sample,
598 params.max_samples);
599 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900600
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900601 if (DBG) {
602 async_safe_format_log(ANDROID_LOG_DEBUG, "libc", "used send_dg %d\n", n);
603 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900604
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900605 if (n < 0) goto fail;
606 if (n == 0) goto next_ns;
607 if (DBG) {
608 async_safe_format_log(ANDROID_LOG_DEBUG, "libc", "time=%ld\n", time(NULL));
609 }
610 if (v_circuit) goto same_ns;
611 resplen = n;
612 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900613
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900614 Dprint((statp->options & RES_DEBUG) ||
615 ((statp->pfcode & RES_PRF_REPLY) && (statp->pfcode & RES_PRF_HEAD1)),
616 (stdout, ";; got answer:\n"));
Bernie Innocenti55864192018-08-30 04:05:20 +0900617
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900618 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
619 (stdout, "%s", ""), ans, (resplen > anssiz) ? anssiz : resplen);
Bernie Innocenti55864192018-08-30 04:05:20 +0900620
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900621 if (cache_status == RESOLV_CACHE_NOTFOUND) {
622 _resolv_cache_add(statp->netid, buf, buflen, ans, resplen);
623 }
624 /*
625 * If we have temporarily opened a virtual circuit,
626 * or if we haven't been asked to keep a socket open,
627 * close the socket.
628 */
629 if ((v_circuit && (statp->options & RES_USEVC) == 0U) ||
630 (statp->options & RES_STAYOPEN) == 0U) {
631 res_nclose(statp);
632 }
633 if (statp->rhook) {
634 int done = 0, loops = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900635
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900636 do {
637 res_sendhookact act;
Bernie Innocenti55864192018-08-30 04:05:20 +0900638
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900639 act = (*statp->rhook)(nsap, buf, buflen, ans, anssiz, &resplen);
640 switch (act) {
641 case res_goahead:
642 case res_done:
643 done = 1;
644 break;
645 case res_nextns:
646 res_nclose(statp);
647 goto next_ns;
648 case res_modified:
649 /* give the hook another try */
650 if (++loops < 42) /*doug adams*/
651 break;
652 /*FALLTHROUGH*/
653 case res_error:
654 /*FALLTHROUGH*/
655 default:
656 goto fail;
657 }
658 } while (!done);
659 }
660 return (resplen);
661 next_ns:;
662 } /*foreach ns*/
663 } /*foreach retry*/
664 res_nclose(statp);
665 if (!v_circuit) {
666 if (!gotsomewhere)
667 errno = ECONNREFUSED; /* no nameservers found */
668 else
669 errno = ETIMEDOUT; /* no answer obtained */
670 } else
671 errno = terrno;
Bernie Innocenti55864192018-08-30 04:05:20 +0900672
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900673 _resolv_cache_query_failed(statp->netid, buf, buflen);
Bernie Innocenti55864192018-08-30 04:05:20 +0900674
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900675 return (-1);
676fail:
Bernie Innocenti55864192018-08-30 04:05:20 +0900677
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900678 _resolv_cache_query_failed(statp->netid, buf, buflen);
679 res_nclose(statp);
680 return (-1);
Bernie Innocenti55864192018-08-30 04:05:20 +0900681}
682
683/* Private */
684
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900685static int get_salen(sa) const struct sockaddr* sa;
Bernie Innocenti55864192018-08-30 04:05:20 +0900686{
Bernie Innocenti55864192018-08-30 04:05:20 +0900687#ifdef HAVE_SA_LEN
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900688 /* There are people do not set sa_len. Be forgiving to them. */
689 if (sa->sa_len) return (sa->sa_len);
Bernie Innocenti55864192018-08-30 04:05:20 +0900690#endif
691
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900692 if (sa->sa_family == AF_INET)
693 return (sizeof(struct sockaddr_in));
694 else if (sa->sa_family == AF_INET6)
695 return (sizeof(struct sockaddr_in6));
696 else
697 return (0); /* unknown, die on connect */
Bernie Innocenti55864192018-08-30 04:05:20 +0900698}
699
700/*
701 * pick appropriate nsaddr_list for use. see res_init() for initialization.
702 */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900703static struct sockaddr* get_nsaddr(statp, n) res_state statp;
704size_t n;
Bernie Innocenti55864192018-08-30 04:05:20 +0900705{
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900706 if (!statp->nsaddr_list[n].sin_family && EXT(statp).ext) {
707 /*
708 * - EXT(statp).ext->nsaddrs[n] holds an address that is larger
709 * than struct sockaddr, and
710 * - user code did not update statp->nsaddr_list[n].
711 */
712 return (struct sockaddr*) (void*) &EXT(statp).ext->nsaddrs[n];
713 } else {
714 /*
715 * - user code updated statp->nsaddr_list[n], or
716 * - statp->nsaddr_list[n] has the same content as
717 * EXT(statp).ext->nsaddrs[n].
718 */
719 return (struct sockaddr*) (void*) &statp->nsaddr_list[n];
720 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900721}
722
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900723static struct timespec get_timeout(const res_state statp, const struct __res_params* params,
724 const int ns) {
725 int msec;
726 if (params->base_timeout_msec != 0) {
727 // TODO: scale the timeout by retry attempt and maybe number of servers
728 msec = params->base_timeout_msec;
729 } else {
730 // Legacy algorithm which scales the timeout by nameserver number.
731 // For instance, with 4 nameservers: 5s, 2.5s, 5s, 10s
732 // This has no effect with 1 or 2 nameservers
733 msec = (statp->retrans * 1000) << ns;
734 if (ns > 0) {
735 msec /= statp->nscount;
736 }
737 if (msec < 1000) {
738 msec = 1000; // Use at least 100ms
739 }
740 }
741 if (DBG) {
742 async_safe_format_log(ANDROID_LOG_DEBUG, "libc", "using timeout of %d msec\n", msec);
743 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900744
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900745 struct timespec result;
746 result.tv_sec = msec / 1000;
747 result.tv_nsec = (msec % 1000) * 1000000;
748 return result;
Bernie Innocenti55864192018-08-30 04:05:20 +0900749}
750
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900751static int send_vc(res_state statp, struct __res_params* params, const u_char* buf, int buflen,
752 u_char* ans, int anssiz, int* terrno, int ns, time_t* at, int* rcode,
753 int* delay) {
754 *at = time(NULL);
755 *rcode = RCODE_INTERNAL_ERROR;
756 *delay = 0;
757 const HEADER* hp = (const HEADER*) (const void*) buf;
758 HEADER* anhp = (HEADER*) (void*) ans;
759 struct sockaddr* nsap;
760 int nsaplen;
761 int truncating, connreset, resplen, n;
762 struct iovec iov[2];
763 u_short len;
764 u_char* cp;
765 void* tmp;
Bernie Innocenti55864192018-08-30 04:05:20 +0900766
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900767 if (DBG) {
768 async_safe_format_log(ANDROID_LOG_DEBUG, "libc", "using send_vc\n");
769 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900770
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900771 nsap = get_nsaddr(statp, (size_t) ns);
772 nsaplen = get_salen(nsap);
Bernie Innocenti55864192018-08-30 04:05:20 +0900773
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900774 connreset = 0;
775same_ns:
776 truncating = 0;
Bernie Innocenti55864192018-08-30 04:05:20 +0900777
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900778 struct timespec now = evNowTime();
Bernie Innocenti55864192018-08-30 04:05:20 +0900779
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900780 /* Are we still talking to whom we want to talk to? */
781 if (statp->_vcsock >= 0 && (statp->_flags & RES_F_VC) != 0) {
782 struct sockaddr_storage peer;
783 socklen_t size = sizeof peer;
784 unsigned old_mark;
785 socklen_t mark_size = sizeof(old_mark);
786 if (getpeername(statp->_vcsock, (struct sockaddr*) (void*) &peer, &size) < 0 ||
787 !sock_eq((struct sockaddr*) (void*) &peer, nsap) ||
788 getsockopt(statp->_vcsock, SOL_SOCKET, SO_MARK, &old_mark, &mark_size) < 0 ||
789 old_mark != statp->_mark) {
790 res_nclose(statp);
791 statp->_flags &= ~RES_F_VC;
792 }
793 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900794
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900795 if (statp->_vcsock < 0 || (statp->_flags & RES_F_VC) == 0) {
796 if (statp->_vcsock >= 0) res_nclose(statp);
Bernie Innocenti55864192018-08-30 04:05:20 +0900797
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900798 statp->_vcsock = socket(nsap->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0);
799 if (statp->_vcsock < 0) {
800 switch (errno) {
801 case EPROTONOSUPPORT:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900802 case EPFNOSUPPORT:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900803 case EAFNOSUPPORT:
804 Perror(statp, stderr, "socket(vc)", errno);
805 return (0);
806 default:
807 *terrno = errno;
808 Perror(statp, stderr, "socket(vc)", errno);
809 return (-1);
810 }
811 }
812 fchown(statp->_vcsock, AID_DNS, -1);
813 if (statp->_mark != MARK_UNSET) {
814 if (setsockopt(statp->_vcsock, SOL_SOCKET, SO_MARK, &statp->_mark,
815 sizeof(statp->_mark)) < 0) {
816 *terrno = errno;
817 Perror(statp, stderr, "setsockopt", errno);
818 return -1;
819 }
820 }
821 errno = 0;
822 if (random_bind(statp->_vcsock, nsap->sa_family) < 0) {
823 *terrno = errno;
824 Aerror(statp, stderr, "bind/vc", errno, nsap, nsaplen);
825 res_nclose(statp);
826 return (0);
827 }
828 if (connect_with_timeout(statp->_vcsock, nsap, (socklen_t) nsaplen,
829 get_timeout(statp, params, ns)) < 0) {
830 *terrno = errno;
831 Aerror(statp, stderr, "connect/vc", errno, nsap, nsaplen);
832 res_nclose(statp);
833 /*
834 * The way connect_with_timeout() is implemented prevents us from reliably
835 * determining whether this was really a timeout or e.g. ECONNREFUSED. Since
836 * currently both cases are handled in the same way, there is no need to
837 * change this (yet). If we ever need to reliably distinguish between these
838 * cases, both connect_with_timeout() and retrying_poll() need to be
839 * modified, though.
840 */
841 *rcode = RCODE_TIMEOUT;
842 return (0);
843 }
844 statp->_flags |= RES_F_VC;
845 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900846
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900847 /*
848 * Send length & message
849 */
850 ns_put16((u_short) buflen, (u_char*) (void*) &len);
851 iov[0] = evConsIovec(&len, INT16SZ);
852 DE_CONST(buf, tmp);
853 iov[1] = evConsIovec(tmp, (size_t) buflen);
854 if (writev(statp->_vcsock, iov, 2) != (INT16SZ + buflen)) {
855 *terrno = errno;
856 Perror(statp, stderr, "write failed", errno);
857 res_nclose(statp);
858 return (0);
859 }
860 /*
861 * Receive length & response
862 */
863read_len:
864 cp = ans;
865 len = INT16SZ;
866 while ((n = read(statp->_vcsock, (char*) cp, (size_t) len)) > 0) {
867 cp += n;
868 if ((len -= n) == 0) break;
869 }
870 if (n <= 0) {
871 *terrno = errno;
872 Perror(statp, stderr, "read failed", errno);
873 res_nclose(statp);
874 /*
875 * A long running process might get its TCP
876 * connection reset if the remote server was
877 * restarted. Requery the server instead of
878 * trying a new one. When there is only one
879 * server, this means that a query might work
880 * instead of failing. We only allow one reset
881 * per query to prevent looping.
882 */
883 if (*terrno == ECONNRESET && !connreset) {
884 connreset = 1;
885 res_nclose(statp);
886 goto same_ns;
887 }
888 res_nclose(statp);
889 return (0);
890 }
891 resplen = ns_get16(ans);
892 if (resplen > anssiz) {
893 Dprint(statp->options & RES_DEBUG, (stdout, ";; response truncated\n"));
894 truncating = 1;
895 len = anssiz;
896 } else
897 len = resplen;
898 if (len < HFIXEDSZ) {
899 /*
900 * Undersized message.
901 */
902 Dprint(statp->options & RES_DEBUG, (stdout, ";; undersized: %d\n", len));
903 *terrno = EMSGSIZE;
904 res_nclose(statp);
905 return (0);
906 }
907 cp = ans;
908 while (len != 0 && (n = read(statp->_vcsock, (char*) cp, (size_t) len)) > 0) {
909 cp += n;
910 len -= n;
911 }
912 if (n <= 0) {
913 *terrno = errno;
914 Perror(statp, stderr, "read(vc)", errno);
915 res_nclose(statp);
916 return (0);
917 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900918
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900919 if (truncating) {
920 /*
921 * Flush rest of answer so connection stays in synch.
922 */
923 anhp->tc = 1;
924 len = resplen - anssiz;
925 while (len != 0) {
926 char junk[PACKETSZ];
Bernie Innocenti55864192018-08-30 04:05:20 +0900927
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900928 n = read(statp->_vcsock, junk, (len > sizeof junk) ? sizeof junk : len);
929 if (n > 0)
930 len -= n;
931 else
932 break;
933 }
934 }
935 /*
936 * If the calling applicating has bailed out of
937 * a previous call and failed to arrange to have
938 * the circuit closed or the server has got
939 * itself confused, then drop the packet and
940 * wait for the correct one.
941 */
942 if (hp->id != anhp->id) {
943 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
944 (stdout, ";; old answer (unexpected):\n"), ans,
945 (resplen > anssiz) ? anssiz : resplen);
946 goto read_len;
947 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900948
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900949 /*
950 * All is well, or the error is fatal. Signal that the
951 * next nameserver ought not be tried.
952 */
953 if (resplen > 0) {
954 struct timespec done = evNowTime();
955 *delay = _res_stats_calculate_rtt(&done, &now);
956 *rcode = anhp->rcode;
957 }
958 return (resplen);
Bernie Innocenti55864192018-08-30 04:05:20 +0900959}
960
961/* return -1 on error (errno set), 0 on success */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900962static int connect_with_timeout(int sock, const struct sockaddr* nsap, socklen_t salen,
963 const struct timespec timeout) {
964 int res, origflags;
Bernie Innocenti55864192018-08-30 04:05:20 +0900965
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900966 origflags = fcntl(sock, F_GETFL, 0);
967 fcntl(sock, F_SETFL, origflags | O_NONBLOCK);
Bernie Innocenti55864192018-08-30 04:05:20 +0900968
Bernie Innocentif89b3512018-08-30 07:34:37 +0900969 res = connect(sock, nsap, salen);
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900970 if (res < 0 && errno != EINPROGRESS) {
971 res = -1;
972 goto done;
973 }
974 if (res != 0) {
975 struct timespec now = evNowTime();
976 struct timespec finish = evAddTime(now, timeout);
977 if (DBG) {
978 async_safe_format_log(ANDROID_LOG_DEBUG, "libc", " %d send_vc\n", sock);
979 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900980
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900981 res = retrying_poll(sock, POLLIN | POLLOUT, &finish);
982 if (res <= 0) {
983 res = -1;
984 }
985 }
Bernie Innocenti55864192018-08-30 04:05:20 +0900986done:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900987 fcntl(sock, F_SETFL, origflags);
988 if (DBG) {
989 async_safe_format_log(ANDROID_LOG_DEBUG, "libc",
990 " %d connect_with_const timeout returning %d\n", sock, res);
991 }
992 return res;
Bernie Innocenti55864192018-08-30 04:05:20 +0900993}
994
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900995static int retrying_poll(const int sock, const short events, const struct timespec* finish) {
996 struct timespec now, timeout;
Bernie Innocenti55864192018-08-30 04:05:20 +0900997
998retry:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +0900999 if (DBG) {
1000 async_safe_format_log(ANDROID_LOG_DEBUG, "libc", " %d retrying_poll\n", sock);
1001 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001002
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001003 now = evNowTime();
1004 if (evCmpTime(*finish, now) > 0)
1005 timeout = evSubTime(*finish, now);
1006 else
1007 timeout = evConsTime(0L, 0L);
1008 struct pollfd fds = {.fd = sock, .events = events};
1009 int n = ppoll(&fds, 1, &timeout, /*sigmask=*/NULL);
1010 if (n == 0) {
1011 if (DBG) {
1012 async_safe_format_log(ANDROID_LOG_DEBUG, "libc", " %d retrying_poll timeout\n", sock);
1013 }
1014 errno = ETIMEDOUT;
1015 return 0;
1016 }
1017 if (n < 0) {
1018 if (errno == EINTR) goto retry;
1019 if (DBG) {
1020 async_safe_format_log(ANDROID_LOG_DEBUG, "libc", " %d retrying_poll got error %d\n",
1021 sock, n);
1022 }
1023 return n;
1024 }
1025 if (fds.revents & (POLLIN | POLLOUT | POLLERR)) {
1026 int error;
1027 socklen_t len = sizeof(error);
1028 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error) {
1029 errno = error;
1030 if (DBG) {
1031 async_safe_format_log(ANDROID_LOG_DEBUG, "libc",
1032 " %d retrying_poll dot error2 %d\n", sock, errno);
1033 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001034
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001035 return -1;
1036 }
1037 }
1038 if (DBG) {
1039 async_safe_format_log(ANDROID_LOG_DEBUG, "libc", " %d retrying_poll returning %d\n", sock,
1040 n);
1041 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001042
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001043 return n;
Bernie Innocenti55864192018-08-30 04:05:20 +09001044}
1045
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001046static int send_dg(res_state statp, struct __res_params* params, const u_char* buf, int buflen,
1047 u_char* ans, int anssiz, int* terrno, int ns, int* v_circuit, int* gotsomewhere,
1048 time_t* at, int* rcode, int* delay) {
1049 *at = time(NULL);
1050 *rcode = RCODE_INTERNAL_ERROR;
1051 *delay = 0;
1052 const HEADER* hp = (const HEADER*) (const void*) buf;
1053 HEADER* anhp = (HEADER*) (void*) ans;
1054 const struct sockaddr* nsap;
1055 int nsaplen;
1056 struct timespec now, timeout, finish, done;
1057 struct sockaddr_storage from;
1058 socklen_t fromlen;
1059 int resplen, n, s;
Bernie Innocenti55864192018-08-30 04:05:20 +09001060
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001061 nsap = get_nsaddr(statp, (size_t) ns);
1062 nsaplen = get_salen(nsap);
1063 if (EXT(statp).nssocks[ns] == -1) {
1064 EXT(statp).nssocks[ns] = socket(nsap->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
1065 if (EXT(statp).nssocks[ns] < 0) {
1066 switch (errno) {
1067 case EPROTONOSUPPORT:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001068 case EPFNOSUPPORT:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001069 case EAFNOSUPPORT:
1070 Perror(statp, stderr, "socket(dg)", errno);
1071 return (0);
1072 default:
1073 *terrno = errno;
1074 Perror(statp, stderr, "socket(dg)", errno);
1075 return (-1);
1076 }
1077 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001078
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001079 fchown(EXT(statp).nssocks[ns], AID_DNS, -1);
1080 if (statp->_mark != MARK_UNSET) {
1081 if (setsockopt(EXT(statp).nssocks[ns], SOL_SOCKET, SO_MARK, &(statp->_mark),
1082 sizeof(statp->_mark)) < 0) {
1083 res_nclose(statp);
1084 return -1;
1085 }
1086 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001087#ifndef CANNOT_CONNECT_DGRAM
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001088 /*
1089 * On a 4.3BSD+ machine (client and server,
1090 * actually), sending to a nameserver datagram
1091 * port with no nameserver will cause an
1092 * ICMP port unreachable message to be returned.
1093 * If our datagram socket is "connected" to the
1094 * server, we get an ECONNREFUSED error on the next
1095 * socket operation, and select returns if the
1096 * error message is received. We can thus detect
1097 * the absence of a nameserver without timing out.
1098 */
1099 if (random_bind(EXT(statp).nssocks[ns], nsap->sa_family) < 0) {
1100 Aerror(statp, stderr, "bind(dg)", errno, nsap, nsaplen);
1101 res_nclose(statp);
1102 return (0);
1103 }
Bernie Innocentif89b3512018-08-30 07:34:37 +09001104 if (connect(EXT(statp).nssocks[ns], nsap, (socklen_t) nsaplen) < 0) {
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001105 Aerror(statp, stderr, "connect(dg)", errno, nsap, nsaplen);
1106 res_nclose(statp);
1107 return (0);
1108 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001109#endif /* !CANNOT_CONNECT_DGRAM */
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001110 Dprint(statp->options & RES_DEBUG, (stdout, ";; new DG socket\n"))
1111 }
1112 s = EXT(statp).nssocks[ns];
Bernie Innocenti55864192018-08-30 04:05:20 +09001113#ifndef CANNOT_CONNECT_DGRAM
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001114 if (send(s, (const char*) buf, (size_t) buflen, 0) != buflen) {
1115 Perror(statp, stderr, "send", errno);
1116 res_nclose(statp);
1117 return (0);
1118 }
1119#else /* !CANNOT_CONNECT_DGRAM */
1120 if (sendto(s, (const char*) buf, buflen, 0, nsap, nsaplen) != buflen) {
1121 Aerror(statp, stderr, "sendto", errno, nsap, nsaplen);
1122 res_nclose(statp);
1123 return (0);
1124 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001125#endif /* !CANNOT_CONNECT_DGRAM */
1126
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001127 /*
1128 * Wait for reply.
1129 */
1130 timeout = get_timeout(statp, params, ns);
1131 now = evNowTime();
1132 finish = evAddTime(now, timeout);
Bernie Innocenti55864192018-08-30 04:05:20 +09001133retry:
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001134 n = retrying_poll(s, POLLIN, &finish);
Bernie Innocenti55864192018-08-30 04:05:20 +09001135
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001136 if (n == 0) {
1137 *rcode = RCODE_TIMEOUT;
1138 Dprint(statp->options & RES_DEBUG, (stdout, ";; timeout\n"));
1139 *gotsomewhere = 1;
1140 return (0);
1141 }
1142 if (n < 0) {
1143 Perror(statp, stderr, "poll", errno);
1144 res_nclose(statp);
1145 return (0);
1146 }
1147 errno = 0;
1148 fromlen = sizeof(from);
1149 resplen = recvfrom(s, (char*) ans, (size_t) anssiz, 0, (struct sockaddr*) (void*) &from,
1150 &fromlen);
1151 if (resplen <= 0) {
1152 Perror(statp, stderr, "recvfrom", errno);
1153 res_nclose(statp);
1154 return (0);
1155 }
1156 *gotsomewhere = 1;
1157 if (resplen < HFIXEDSZ) {
1158 /*
1159 * Undersized message.
1160 */
1161 Dprint(statp->options & RES_DEBUG, (stdout, ";; undersized: %d\n", resplen));
1162 *terrno = EMSGSIZE;
1163 res_nclose(statp);
1164 return (0);
1165 }
1166 if (hp->id != anhp->id) {
1167 /*
1168 * response from old 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, ";; old answer:\n"), ans, (resplen > anssiz) ? anssiz : resplen);
1174 goto retry;
1175 }
1176 if (!(statp->options & RES_INSECURE1) &&
1177 !res_ourserver_p(statp, (struct sockaddr*) (void*) &from)) {
1178 /*
1179 * response from wrong server? ignore it.
1180 * XXX - potential security hazard could
1181 * be detected here.
1182 */
1183 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
1184 (stdout, ";; not our server:\n"), ans, (resplen > anssiz) ? anssiz : resplen);
1185 goto retry;
1186 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001187#ifdef RES_USE_EDNS0
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001188 if (anhp->rcode == FORMERR && (statp->options & RES_USE_EDNS0) != 0U) {
1189 /*
1190 * Do not retry if the server do not understand EDNS0.
1191 * The case has to be captured here, as FORMERR packet do not
1192 * carry query section, hence res_queriesmatch() returns 0.
1193 */
1194 DprintQ(statp->options & RES_DEBUG, (stdout, "server rejected query with EDNS0:\n"), ans,
1195 (resplen > anssiz) ? anssiz : resplen);
1196 /* record the error */
1197 statp->_flags |= RES_F_EDNS0ERR;
1198 res_nclose(statp);
1199 return (0);
1200 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001201#endif
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001202 if (!(statp->options & RES_INSECURE2) &&
1203 !res_queriesmatch(buf, buf + buflen, ans, ans + anssiz)) {
1204 /*
1205 * response contains wrong query? ignore it.
1206 * XXX - potential security hazard could
1207 * be detected here.
1208 */
1209 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_REPLY),
1210 (stdout, ";; wrong query name:\n"), ans, (resplen > anssiz) ? anssiz : resplen);
1211 goto retry;
1212 ;
1213 }
1214 done = evNowTime();
1215 *delay = _res_stats_calculate_rtt(&done, &now);
1216 if (anhp->rcode == SERVFAIL || anhp->rcode == NOTIMP || anhp->rcode == REFUSED) {
1217 DprintQ(statp->options & RES_DEBUG, (stdout, "server rejected query:\n"), ans,
1218 (resplen > anssiz) ? anssiz : resplen);
1219 res_nclose(statp);
1220 /* don't retry if called from dig */
1221 if (!statp->pfcode) {
1222 *rcode = anhp->rcode;
1223 return (0);
1224 }
1225 }
1226 if (!(statp->options & RES_IGNTC) && anhp->tc) {
1227 /*
1228 * To get the rest of answer,
1229 * use TCP with same server.
1230 */
1231 Dprint(statp->options & RES_DEBUG, (stdout, ";; truncated answer\n"));
1232 *v_circuit = 1;
1233 res_nclose(statp);
1234 return (1);
1235 }
1236 /*
1237 * All is well, or the error is fatal. Signal that the
1238 * next nameserver ought not be tried.
1239 */
1240 if (resplen > 0) {
1241 *rcode = anhp->rcode;
1242 }
1243 return (resplen);
Bernie Innocenti55864192018-08-30 04:05:20 +09001244}
1245
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001246static void Aerror(const res_state statp, FILE* file, const char* string, int error,
1247 const struct sockaddr* address, int alen) {
1248 int save = errno;
1249 char hbuf[NI_MAXHOST];
1250 char sbuf[NI_MAXSERV];
Bernie Innocenti55864192018-08-30 04:05:20 +09001251
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001252 if ((statp->options & RES_DEBUG) != 0U) {
1253 if (getnameinfo(address, (socklen_t) alen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
1254 niflags)) {
1255 strncpy(hbuf, "?", sizeof(hbuf) - 1);
1256 hbuf[sizeof(hbuf) - 1] = '\0';
1257 strncpy(sbuf, "?", sizeof(sbuf) - 1);
1258 sbuf[sizeof(sbuf) - 1] = '\0';
1259 }
1260 fprintf(file, "res_send: %s ([%s].%s): %s\n", string, hbuf, sbuf, strerror(error));
1261 }
1262 errno = save;
Bernie Innocenti55864192018-08-30 04:05:20 +09001263}
1264
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001265static void Perror(const res_state statp, FILE* file, const char* string, int error) {
1266 int save = errno;
Bernie Innocenti55864192018-08-30 04:05:20 +09001267
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001268 if ((statp->options & RES_DEBUG) != 0U)
1269 fprintf(file, "res_send: %s: %s\n", string, strerror(error));
1270 errno = save;
Bernie Innocenti55864192018-08-30 04:05:20 +09001271}
1272
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001273static int sock_eq(struct sockaddr* a, struct sockaddr* b) {
1274 struct sockaddr_in *a4, *b4;
1275 struct sockaddr_in6 *a6, *b6;
Bernie Innocenti55864192018-08-30 04:05:20 +09001276
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001277 if (a->sa_family != b->sa_family) return 0;
1278 switch (a->sa_family) {
1279 case AF_INET:
1280 a4 = (struct sockaddr_in*) (void*) a;
1281 b4 = (struct sockaddr_in*) (void*) b;
1282 return a4->sin_port == b4->sin_port && a4->sin_addr.s_addr == b4->sin_addr.s_addr;
1283 case AF_INET6:
1284 a6 = (struct sockaddr_in6*) (void*) a;
1285 b6 = (struct sockaddr_in6*) (void*) b;
1286 return a6->sin6_port == b6->sin6_port &&
Bernie Innocenti55864192018-08-30 04:05:20 +09001287#ifdef HAVE_SIN6_SCOPE_ID
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001288 a6->sin6_scope_id == b6->sin6_scope_id &&
Bernie Innocenti55864192018-08-30 04:05:20 +09001289#endif
Bernie Innocentif12d5bb2018-08-31 14:09:46 +09001290 IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
1291 default:
1292 return 0;
1293 }
Bernie Innocenti55864192018-08-30 04:05:20 +09001294}