blob: bfc6e1a8be6e070af4f616dcb97fc1ce06a09325 [file] [log] [blame]
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001/* $NetBSD: res_send.c,v 1.9 2006/01/24 17:41:25 christos Exp $ */
2
3/*
4 * Copyright 2008 Android Open Source Project (source port randomization)
5 * Copyright (c) 1985, 1989, 1993
6 * The Regents of the University of California. All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 */
36
37/*
38 * Portions Copyright (c) 1993 by Digital Equipment Corporation.
39 *
40 * Permission to use, copy, modify, and distribute this software for any
41 * purpose with or without fee is hereby granted, provided that the above
42 * copyright notice and this permission notice appear in all copies, and that
43 * the name of Digital Equipment Corporation not be used in advertising or
44 * publicity pertaining to distribution of the document or software without
45 * specific, written prior permission.
46 *
47 * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
48 * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
49 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
50 * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
51 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
52 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
53 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
54 * SOFTWARE.
55 */
56
57/*
58 * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
59 * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
60 *
61 * Permission to use, copy, modify, and distribute this software for any
62 * purpose with or without fee is hereby granted, provided that the above
63 * copyright notice and this permission notice appear in all copies.
64 *
65 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
66 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
67 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR
68 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
69 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
70 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
71 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
72 */
73
74#include <sys/cdefs.h>
75#if defined(LIBC_SCCS) && !defined(lint)
76#ifdef notdef
77static const char sccsid[] = "@(#)res_send.c 8.1 (Berkeley) 6/4/93";
78static const char rcsid[] = "Id: res_send.c,v 1.5.2.2.4.5 2004/08/10 02:19:56 marka Exp";
79#else
80__RCSID("$NetBSD: res_send.c,v 1.9 2006/01/24 17:41:25 christos Exp $");
81#endif
82#endif /* LIBC_SCCS and not lint */
83
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080084/*
85 * Send query to name server and wait for reply.
86 */
87
88#include <sys/types.h>
89#include <sys/param.h>
90#include <sys/time.h>
91#include <sys/socket.h>
92#include <sys/uio.h>
93
94#include <netinet/in.h>
Calin Juravle569fb982014-03-04 15:01:29 +000095#include <arpa/nameser.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080096#include <arpa/inet.h>
97
98#include <errno.h>
Robert Greenwaltecd0e952012-01-11 10:04:48 -080099#include <fcntl.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800100#include <netdb.h>
101#ifdef ANDROID_CHANGES
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500102#include "resolv_netid.h"
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800103#include "resolv_private.h"
104#else
105#include <resolv.h>
106#endif
107#include <signal.h>
108#include <stdio.h>
109#include <stdlib.h>
110#include <string.h>
Robert Greenwaltecd0e952012-01-11 10:04:48 -0800111#include <time.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800112#include <unistd.h>
113
114#include <isc/eventlib.h>
115
Pierre Imai6b3f0d62016-02-22 17:50:41 +0900116#include <resolv_cache.h>
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800117
Elliott Hugheseb847bc2013-10-09 15:50:50 -0700118#include "private/libc_logging.h"
Robert Greenwaltecd0e952012-01-11 10:04:48 -0800119
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800120#ifndef DE_CONST
121#define DE_CONST(c,v) v = ((c) ? \
122 strchr((const void *)(c), *(const char *)(const void *)(c)) : NULL)
123#endif
124
125/* Options. Leave them on. */
126#ifndef DEBUG
127#define DEBUG
128#endif
129#include "res_debug.h"
130#include "res_private.h"
Pierre Imai6b3f0d62016-02-22 17:50:41 +0900131#include "resolv_stats.h"
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800132
133#define EXT(res) ((res)->_u._ext)
Robert Greenwaltecd0e952012-01-11 10:04:48 -0800134#define DBG 0
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800135
136static const int highestFD = FD_SETSIZE - 1;
137
138/* Forward. */
139
140static int get_salen __P((const struct sockaddr *));
141static struct sockaddr * get_nsaddr __P((res_state, size_t));
142static int send_vc(res_state, const u_char *, int,
Pierre Imai6b3f0d62016-02-22 17:50:41 +0900143 u_char *, int, int *, int,
144 time_t *, int *, int *);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800145static int send_dg(res_state, const u_char *, int,
146 u_char *, int, int *, int,
Pierre Imai6b3f0d62016-02-22 17:50:41 +0900147 int *, int *,
148 time_t *, int *, int *);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800149static void Aerror(const res_state, FILE *, const char *, int,
150 const struct sockaddr *, int);
151static void Perror(const res_state, FILE *, const char *, int);
152static int sock_eq(struct sockaddr *, struct sockaddr *);
153#ifdef NEED_PSELECT
154static int pselect(int, void *, void *, void *,
155 struct timespec *,
156 const sigset_t *);
157#endif
158void res_pquery(const res_state, const u_char *, int, FILE *);
Robert Greenwaltecd0e952012-01-11 10:04:48 -0800159static int connect_with_timeout(int sock, const struct sockaddr *nsap,
160 socklen_t salen, int sec);
161static int retrying_select(const int sock, fd_set *readset, fd_set *writeset,
162 const struct timespec *finish);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800163
164/* BIONIC-BEGIN: implement source port randomization */
165typedef union {
166 struct sockaddr sa;
167 struct sockaddr_in sin;
168 struct sockaddr_in6 sin6;
169} _sockaddr_union;
170
171static int
172random_bind( int s, int family )
173{
174 _sockaddr_union u;
175 int j;
176 socklen_t slen;
177
178 /* clear all, this also sets the IP4/6 address to 'any' */
179 memset( &u, 0, sizeof u );
180
181 switch (family) {
182 case AF_INET:
183 u.sin.sin_family = family;
184 slen = sizeof u.sin;
185 break;
186 case AF_INET6:
187 u.sin6.sin6_family = family;
188 slen = sizeof u.sin6;
189 break;
190 default:
191 errno = EPROTO;
192 return -1;
193 }
194
195 /* first try to bind to a random source port a few times */
196 for (j = 0; j < 10; j++) {
197 /* find a random port between 1025 .. 65534 */
198 int port = 1025 + (res_randomid() % (65535-1025));
199 if (family == AF_INET)
200 u.sin.sin_port = htons(port);
201 else
202 u.sin6.sin6_port = htons(port);
203
204 if ( !bind( s, &u.sa, slen ) )
205 return 0;
206 }
207
208 /* nothing after 10 tries, our network table is probably busy */
209 /* let the system decide which port is best */
210 if (family == AF_INET)
211 u.sin.sin_port = 0;
212 else
213 u.sin6.sin6_port = 0;
214
215 return bind( s, &u.sa, slen );
216}
217/* BIONIC-END */
218
219static const int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
220
221/* Public. */
222
223/* int
224 * res_isourserver(ina)
225 * looks up "ina" in _res.ns_addr_list[]
226 * returns:
227 * 0 : not found
228 * >0 : found
229 * author:
230 * paul vixie, 29may94
231 */
Jim Huang7cc56662010-10-15 02:02:57 +0800232__LIBC_HIDDEN__ int
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800233res_ourserver_p(const res_state statp, const struct sockaddr *sa) {
234 const struct sockaddr_in *inp, *srv;
235 const struct sockaddr_in6 *in6p, *srv6;
236 int ns;
237
238 switch (sa->sa_family) {
239 case AF_INET:
240 inp = (const struct sockaddr_in *)(const void *)sa;
241 for (ns = 0; ns < statp->nscount; ns++) {
242 srv = (struct sockaddr_in *)(void *)get_nsaddr(statp, (size_t)ns);
243 if (srv->sin_family == inp->sin_family &&
244 srv->sin_port == inp->sin_port &&
245 (srv->sin_addr.s_addr == INADDR_ANY ||
246 srv->sin_addr.s_addr == inp->sin_addr.s_addr))
247 return (1);
248 }
249 break;
250 case AF_INET6:
251 if (EXT(statp).ext == NULL)
252 break;
253 in6p = (const struct sockaddr_in6 *)(const void *)sa;
254 for (ns = 0; ns < statp->nscount; ns++) {
255 srv6 = (struct sockaddr_in6 *)(void *)get_nsaddr(statp, (size_t)ns);
256 if (srv6->sin6_family == in6p->sin6_family &&
257 srv6->sin6_port == in6p->sin6_port &&
258#ifdef HAVE_SIN6_SCOPE_ID
259 (srv6->sin6_scope_id == 0 ||
260 srv6->sin6_scope_id == in6p->sin6_scope_id) &&
261#endif
262 (IN6_IS_ADDR_UNSPECIFIED(&srv6->sin6_addr) ||
263 IN6_ARE_ADDR_EQUAL(&srv6->sin6_addr, &in6p->sin6_addr)))
264 return (1);
265 }
266 break;
267 default:
268 break;
269 }
270 return (0);
271}
272
273/* int
274 * res_nameinquery(name, type, class, buf, eom)
275 * look for (name,type,class) in the query section of packet (buf,eom)
276 * requires:
277 * buf + HFIXEDSZ <= eom
278 * returns:
279 * -1 : format error
280 * 0 : not found
281 * >0 : found
282 * author:
283 * paul vixie, 29may94
284 */
285int
286res_nameinquery(const char *name, int type, int class,
287 const u_char *buf, const u_char *eom)
288{
289 const u_char *cp = buf + HFIXEDSZ;
290 int qdcount = ntohs(((const HEADER*)(const void *)buf)->qdcount);
291
292 while (qdcount-- > 0) {
293 char tname[MAXDNAME+1];
294 int n, ttype, tclass;
295
296 n = dn_expand(buf, eom, cp, tname, sizeof tname);
297 if (n < 0)
298 return (-1);
299 cp += n;
300 if (cp + 2 * INT16SZ > eom)
301 return (-1);
302 ttype = ns_get16(cp); cp += INT16SZ;
303 tclass = ns_get16(cp); cp += INT16SZ;
304 if (ttype == type && tclass == class &&
305 ns_samename(tname, name) == 1)
306 return (1);
307 }
308 return (0);
309}
310
311/* int
312 * res_queriesmatch(buf1, eom1, buf2, eom2)
313 * is there a 1:1 mapping of (name,type,class)
314 * in (buf1,eom1) and (buf2,eom2)?
315 * returns:
316 * -1 : format error
317 * 0 : not a 1:1 mapping
318 * >0 : is a 1:1 mapping
319 * author:
320 * paul vixie, 29may94
321 */
322int
323res_queriesmatch(const u_char *buf1, const u_char *eom1,
324 const u_char *buf2, const u_char *eom2)
325{
326 const u_char *cp = buf1 + HFIXEDSZ;
327 int qdcount = ntohs(((const HEADER*)(const void *)buf1)->qdcount);
328
329 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2)
330 return (-1);
331
332 /*
333 * Only header section present in replies to
334 * dynamic update packets.
335 */
336 if ((((const HEADER *)(const void *)buf1)->opcode == ns_o_update) &&
337 (((const HEADER *)(const void *)buf2)->opcode == ns_o_update))
338 return (1);
339
340 if (qdcount != ntohs(((const HEADER*)(const void *)buf2)->qdcount))
341 return (0);
342 while (qdcount-- > 0) {
343 char tname[MAXDNAME+1];
344 int n, ttype, tclass;
345
346 n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
347 if (n < 0)
348 return (-1);
349 cp += n;
350 if (cp + 2 * INT16SZ > eom1)
351 return (-1);
352 ttype = ns_get16(cp); cp += INT16SZ;
353 tclass = ns_get16(cp); cp += INT16SZ;
354 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2))
355 return (0);
356 }
357 return (1);
358}
359
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800360int
361res_nsend(res_state statp,
362 const u_char *buf, int buflen, u_char *ans, int anssiz)
363{
364 int gotsomewhere, terrno, try, v_circuit, resplen, ns, n;
365 char abuf[NI_MAXHOST];
Pierre Imai6b3f0d62016-02-22 17:50:41 +0900366 ResolvCacheStatus cache_status = RESOLV_CACHE_UNSUPPORTED;
Mattias Falkc63e5902011-08-23 14:34:14 +0200367
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800368 if (anssiz < HFIXEDSZ) {
369 errno = EINVAL;
370 return (-1);
371 }
372 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_QUERY),
373 (stdout, ";; res_send()\n"), buf, buflen);
374 v_circuit = (statp->options & RES_USEVC) || buflen > PACKETSZ;
375 gotsomewhere = 0;
376 terrno = ETIMEDOUT;
377
Paul Jensen41d9a502014-04-08 15:43:41 -0400378 int anslen = 0;
379 cache_status = _resolv_cache_lookup(
380 statp->netid, buf, buflen,
381 ans, anssiz, &anslen);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800382
Paul Jensen41d9a502014-04-08 15:43:41 -0400383 if (cache_status == RESOLV_CACHE_FOUND) {
384 return anslen;
385 } else if (cache_status != RESOLV_CACHE_UNSUPPORTED) {
386 // had a cache miss for a known network, so populate the thread private
387 // data so the normal resolve path can do its thing
388 _resolv_populate_res_for_net(statp);
Mattias Falkc63e5902011-08-23 14:34:14 +0200389 }
Mattias Falkc63e5902011-08-23 14:34:14 +0200390 if (statp->nscount == 0) {
Lorenzo Colittie5477f82014-11-28 20:03:23 +0900391 // We have no nameservers configured, so there's no point trying.
392 // Tell the cache the query failed, or any retries and anyone else asking the same
393 // question will block for PENDING_REQUEST_TIMEOUT seconds instead of failing fast.
394 _resolv_cache_query_failed(statp->netid, buf, buflen);
Mattias Falkc63e5902011-08-23 14:34:14 +0200395 errno = ESRCH;
396 return (-1);
397 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800398
399 /*
400 * If the ns_addr_list in the resolver context has changed, then
401 * invalidate our cached copy and the associated timing data.
402 */
403 if (EXT(statp).nscount != 0) {
404 int needclose = 0;
405 struct sockaddr_storage peer;
406 socklen_t peerlen;
407
Pierre Imai6b3f0d62016-02-22 17:50:41 +0900408 if (EXT(statp).nscount != statp->nscount) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800409 needclose++;
Pierre Imai6b3f0d62016-02-22 17:50:41 +0900410 } else {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800411 for (ns = 0; ns < statp->nscount; ns++) {
412 if (statp->nsaddr_list[ns].sin_family &&
413 !sock_eq((struct sockaddr *)(void *)&statp->nsaddr_list[ns],
414 (struct sockaddr *)(void *)&EXT(statp).ext->nsaddrs[ns])) {
415 needclose++;
416 break;
417 }
418
419 if (EXT(statp).nssocks[ns] == -1)
420 continue;
421 peerlen = sizeof(peer);
Jim Huang87043f92011-12-12 16:32:56 +0800422 if (getpeername(EXT(statp).nssocks[ns],
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800423 (struct sockaddr *)(void *)&peer, &peerlen) < 0) {
424 needclose++;
425 break;
426 }
427 if (!sock_eq((struct sockaddr *)(void *)&peer,
428 get_nsaddr(statp, (size_t)ns))) {
429 needclose++;
430 break;
431 }
432 }
Pierre Imai6b3f0d62016-02-22 17:50:41 +0900433 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800434 if (needclose) {
435 res_nclose(statp);
436 EXT(statp).nscount = 0;
437 }
438 }
439
440 /*
441 * Maybe initialize our private copy of the ns_addr_list.
442 */
443 if (EXT(statp).nscount == 0) {
444 for (ns = 0; ns < statp->nscount; ns++) {
445 EXT(statp).nstimes[ns] = RES_MAXTIME;
446 EXT(statp).nssocks[ns] = -1;
447 if (!statp->nsaddr_list[ns].sin_family)
448 continue;
449 EXT(statp).ext->nsaddrs[ns].sin =
450 statp->nsaddr_list[ns];
451 }
452 EXT(statp).nscount = statp->nscount;
453 }
454
455 /*
456 * Some resolvers want to even out the load on their nameservers.
457 * Note that RES_BLAST overrides RES_ROTATE.
458 */
459 if ((statp->options & RES_ROTATE) != 0U &&
460 (statp->options & RES_BLAST) == 0U) {
461 union res_sockaddr_union inu;
462 struct sockaddr_in ina;
463 int lastns = statp->nscount - 1;
464 int fd;
465 u_int16_t nstime;
466
467 if (EXT(statp).ext != NULL)
468 inu = EXT(statp).ext->nsaddrs[0];
469 ina = statp->nsaddr_list[0];
470 fd = EXT(statp).nssocks[0];
471 nstime = EXT(statp).nstimes[0];
472 for (ns = 0; ns < lastns; ns++) {
473 if (EXT(statp).ext != NULL)
Pierre Imai6b3f0d62016-02-22 17:50:41 +0900474 EXT(statp).ext->nsaddrs[ns] =
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800475 EXT(statp).ext->nsaddrs[ns + 1];
476 statp->nsaddr_list[ns] = statp->nsaddr_list[ns + 1];
477 EXT(statp).nssocks[ns] = EXT(statp).nssocks[ns + 1];
478 EXT(statp).nstimes[ns] = EXT(statp).nstimes[ns + 1];
479 }
480 if (EXT(statp).ext != NULL)
481 EXT(statp).ext->nsaddrs[lastns] = inu;
482 statp->nsaddr_list[lastns] = ina;
483 EXT(statp).nssocks[lastns] = fd;
484 EXT(statp).nstimes[lastns] = nstime;
485 }
486
487 /*
488 * Send request, RETRY times, or until successful.
489 */
490 for (try = 0; try < statp->retry; try++) {
Pierre Imaifff35672016-04-18 11:42:14 +0900491 struct __res_stats stats[MAXNS];
Pierre Imai6b3f0d62016-02-22 17:50:41 +0900492 struct __res_params params;
493 int revision_id = _resolv_cache_get_resolver_stats(statp->netid, &params, stats);
Pierre Imaifff35672016-04-18 11:42:14 +0900494 bool usable_servers[MAXNS];
Pierre Imai6b3f0d62016-02-22 17:50:41 +0900495 _res_stats_get_usable_servers(&params, stats, statp->nscount, usable_servers);
496
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800497 for (ns = 0; ns < statp->nscount; ns++) {
Pierre Imai6b3f0d62016-02-22 17:50:41 +0900498 if (!usable_servers[ns]) continue;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800499 struct sockaddr *nsap;
500 int nsaplen;
Pierre Imai6b3f0d62016-02-22 17:50:41 +0900501 time_t now = 0;
502 int rcode = RCODE_INTERNAL_ERROR;
503 int delay = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800504 nsap = get_nsaddr(statp, (size_t)ns);
505 nsaplen = get_salen(nsap);
506 statp->_flags &= ~RES_F_LASTMASK;
507 statp->_flags |= (ns << RES_F_LASTSHIFT);
Pierre Imai6b3f0d62016-02-22 17:50:41 +0900508
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800509 same_ns:
510 if (statp->qhook) {
511 int done = 0, loops = 0;
512
513 do {
514 res_sendhookact act;
515
516 act = (*statp->qhook)(&nsap, &buf, &buflen,
517 ans, anssiz, &resplen);
518 switch (act) {
519 case res_goahead:
520 done = 1;
521 break;
522 case res_nextns:
523 res_nclose(statp);
524 goto next_ns;
525 case res_done:
526 return (resplen);
527 case res_modified:
528 /* give the hook another try */
529 if (++loops < 42) /*doug adams*/
530 break;
531 /*FALLTHROUGH*/
532 case res_error:
533 /*FALLTHROUGH*/
534 default:
535 goto fail;
536 }
537 } while (!done);
538 }
539
540 Dprint(((statp->options & RES_DEBUG) &&
541 getnameinfo(nsap, (socklen_t)nsaplen, abuf, sizeof(abuf),
Robert Greenwaltecd0e952012-01-11 10:04:48 -0800542 NULL, 0, niflags) == 0),
543 (stdout, ";; Querying server (# %d) address = %s\n",
544 ns + 1, abuf));
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800545
546
547 if (v_circuit) {
548 /* Use VC; at most one attempt per server. */
549 try = statp->retry;
Robert Greenwaltecd0e952012-01-11 10:04:48 -0800550
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800551 n = send_vc(statp, buf, buflen, ans, anssiz, &terrno,
Pierre Imai6b3f0d62016-02-22 17:50:41 +0900552 ns, &now, &rcode, &delay);
553
554 struct __res_sample sample;
555 _res_stats_set_sample(&sample, now, rcode, delay);
556 _resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, ns,
557 &sample, params.max_samples);
Robert Greenwaltecd0e952012-01-11 10:04:48 -0800558
559 if (DBG) {
Elliott Hughes8f2a5a02013-03-15 15:30:25 -0700560 __libc_format_log(ANDROID_LOG_DEBUG, "libc",
Robert Greenwaltecd0e952012-01-11 10:04:48 -0800561 "used send_vc %d\n", n);
562 }
563
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800564 if (n < 0)
565 goto fail;
566 if (n == 0)
567 goto next_ns;
568 resplen = n;
569 } else {
570 /* Use datagrams. */
Robert Greenwaltecd0e952012-01-11 10:04:48 -0800571 if (DBG) {
Elliott Hughes8f2a5a02013-03-15 15:30:25 -0700572 __libc_format_log(ANDROID_LOG_DEBUG, "libc", "using send_dg\n");
Robert Greenwaltecd0e952012-01-11 10:04:48 -0800573 }
574
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800575 n = send_dg(statp, buf, buflen, ans, anssiz, &terrno,
Pierre Imai6b3f0d62016-02-22 17:50:41 +0900576 ns, &v_circuit, &gotsomewhere, &now, &rcode, &delay);
577
578 struct __res_sample sample;
579 _res_stats_set_sample(&sample, now, rcode, delay);
580 _resolv_cache_add_resolver_stats_sample(statp->netid, revision_id, ns,
581 &sample, params.max_samples);
582
Robert Greenwaltecd0e952012-01-11 10:04:48 -0800583 if (DBG) {
Elliott Hughes8f2a5a02013-03-15 15:30:25 -0700584 __libc_format_log(ANDROID_LOG_DEBUG, "libc", "used send_dg %d\n",n);
Robert Greenwaltecd0e952012-01-11 10:04:48 -0800585 }
586
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800587 if (n < 0)
588 goto fail;
589 if (n == 0)
590 goto next_ns;
Robert Greenwaltecd0e952012-01-11 10:04:48 -0800591 if (DBG) {
Kito Chengbb0b09c2013-05-11 17:48:48 +0800592 __libc_format_log(ANDROID_LOG_DEBUG, "libc", "time=%ld\n",
Pierre Imai6b3f0d62016-02-22 17:50:41 +0900593 time(NULL));
Robert Greenwaltecd0e952012-01-11 10:04:48 -0800594 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800595 if (v_circuit)
596 goto same_ns;
597 resplen = n;
598 }
599
600 Dprint((statp->options & RES_DEBUG) ||
601 ((statp->pfcode & RES_PRF_REPLY) &&
602 (statp->pfcode & RES_PRF_HEAD1)),
603 (stdout, ";; got answer:\n"));
604
605 DprintQ((statp->options & RES_DEBUG) ||
606 (statp->pfcode & RES_PRF_REPLY),
607 (stdout, "%s", ""),
608 ans, (resplen > anssiz) ? anssiz : resplen);
609
Pierre Imai6b3f0d62016-02-22 17:50:41 +0900610 if (cache_status == RESOLV_CACHE_NOTFOUND) {
611 _resolv_cache_add(statp->netid, buf, buflen,
612 ans, resplen);
613 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800614 /*
615 * If we have temporarily opened a virtual circuit,
616 * or if we haven't been asked to keep a socket open,
617 * close the socket.
618 */
619 if ((v_circuit && (statp->options & RES_USEVC) == 0U) ||
620 (statp->options & RES_STAYOPEN) == 0U) {
621 res_nclose(statp);
622 }
623 if (statp->rhook) {
624 int done = 0, loops = 0;
625
626 do {
627 res_sendhookact act;
628
629 act = (*statp->rhook)(nsap, buf, buflen,
630 ans, anssiz, &resplen);
631 switch (act) {
632 case res_goahead:
633 case res_done:
634 done = 1;
635 break;
636 case res_nextns:
637 res_nclose(statp);
638 goto next_ns;
639 case res_modified:
640 /* give the hook another try */
641 if (++loops < 42) /*doug adams*/
642 break;
643 /*FALLTHROUGH*/
644 case res_error:
645 /*FALLTHROUGH*/
646 default:
647 goto fail;
648 }
649 } while (!done);
650
651 }
652 return (resplen);
653 next_ns: ;
654 } /*foreach ns*/
655 } /*foreach retry*/
656 res_nclose(statp);
657 if (!v_circuit) {
658 if (!gotsomewhere)
659 errno = ECONNREFUSED; /* no nameservers found */
660 else
661 errno = ETIMEDOUT; /* no answer obtained */
662 } else
663 errno = terrno;
Henrik Engströmce5ba8b2012-06-20 08:47:52 +0200664
Pierre Imai6b3f0d62016-02-22 17:50:41 +0900665 _resolv_cache_query_failed(statp->netid, buf, buflen);
Henrik Engströmce5ba8b2012-06-20 08:47:52 +0200666
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800667 return (-1);
668 fail:
Pierre Imai6b3f0d62016-02-22 17:50:41 +0900669
Paul Jensen41d9a502014-04-08 15:43:41 -0400670 _resolv_cache_query_failed(statp->netid, buf, buflen);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800671 res_nclose(statp);
672 return (-1);
673}
674
675/* Private */
676
677static int
678get_salen(sa)
679 const struct sockaddr *sa;
680{
681
682#ifdef HAVE_SA_LEN
683 /* There are people do not set sa_len. Be forgiving to them. */
684 if (sa->sa_len)
685 return (sa->sa_len);
686#endif
687
688 if (sa->sa_family == AF_INET)
689 return (sizeof(struct sockaddr_in));
690 else if (sa->sa_family == AF_INET6)
691 return (sizeof(struct sockaddr_in6));
692 else
693 return (0); /* unknown, die on connect */
694}
695
696/*
697 * pick appropriate nsaddr_list for use. see res_init() for initialization.
698 */
699static struct sockaddr *
700get_nsaddr(statp, n)
701 res_state statp;
702 size_t n;
703{
704
705 if (!statp->nsaddr_list[n].sin_family && EXT(statp).ext) {
706 /*
707 * - EXT(statp).ext->nsaddrs[n] holds an address that is larger
708 * than struct sockaddr, and
709 * - user code did not update statp->nsaddr_list[n].
710 */
711 return (struct sockaddr *)(void *)&EXT(statp).ext->nsaddrs[n];
712 } else {
713 /*
714 * - user code updated statp->nsaddr_list[n], or
715 * - statp->nsaddr_list[n] has the same content as
716 * EXT(statp).ext->nsaddrs[n].
717 */
718 return (struct sockaddr *)(void *)&statp->nsaddr_list[n];
719 }
720}
721
Robert Greenwaltecd0e952012-01-11 10:04:48 -0800722static int get_timeout(const res_state statp, const int ns)
723{
724 int timeout = (statp->retrans << ns);
725 if (ns > 0) {
726 timeout /= statp->nscount;
727 }
728 if (timeout <= 0) {
729 timeout = 1;
730 }
731 if (DBG) {
Elliott Hughes8f2a5a02013-03-15 15:30:25 -0700732 __libc_format_log(ANDROID_LOG_DEBUG, "libc", "using timeout of %d sec\n", timeout);
Robert Greenwaltecd0e952012-01-11 10:04:48 -0800733 }
734
735 return timeout;
736}
737
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800738static int
739send_vc(res_state statp,
740 const u_char *buf, int buflen, u_char *ans, int anssiz,
Pierre Imai6b3f0d62016-02-22 17:50:41 +0900741 int *terrno, int ns, time_t* at, int* rcode, int* delay)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800742{
Pierre Imai6b3f0d62016-02-22 17:50:41 +0900743 *at = 0;
744 *rcode = RCODE_INTERNAL_ERROR;
745 *delay = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800746 const HEADER *hp = (const HEADER *)(const void *)buf;
747 HEADER *anhp = (HEADER *)(void *)ans;
748 struct sockaddr *nsap;
749 int nsaplen;
750 int truncating, connreset, resplen, n;
751 struct iovec iov[2];
752 u_short len;
753 u_char *cp;
754 void *tmp;
755
Robert Greenwaltecd0e952012-01-11 10:04:48 -0800756 if (DBG) {
Elliott Hughes8f2a5a02013-03-15 15:30:25 -0700757 __libc_format_log(ANDROID_LOG_DEBUG, "libc", "using send_vc\n");
Robert Greenwaltecd0e952012-01-11 10:04:48 -0800758 }
759
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800760 nsap = get_nsaddr(statp, (size_t)ns);
761 nsaplen = get_salen(nsap);
762
763 connreset = 0;
764 same_ns:
765 truncating = 0;
766
Pierre Imai6b3f0d62016-02-22 17:50:41 +0900767 struct timespec now = evNowTime();
768
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800769 /* Are we still talking to whom we want to talk to? */
770 if (statp->_vcsock >= 0 && (statp->_flags & RES_F_VC) != 0) {
771 struct sockaddr_storage peer;
772 socklen_t size = sizeof peer;
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500773 unsigned old_mark;
Elliott Hughes37b1b5b2014-07-02 16:27:20 -0700774 socklen_t mark_size = sizeof(old_mark);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800775 if (getpeername(statp->_vcsock,
776 (struct sockaddr *)(void *)&peer, &size) < 0 ||
Chad Brubakerc39214e2013-06-20 10:36:56 -0700777 !sock_eq((struct sockaddr *)(void *)&peer, nsap) ||
778 getsockopt(statp->_vcsock, SOL_SOCKET, SO_MARK, &old_mark, &mark_size) < 0 ||
779 old_mark != statp->_mark) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800780 res_nclose(statp);
781 statp->_flags &= ~RES_F_VC;
782 }
783 }
784
785 if (statp->_vcsock < 0 || (statp->_flags & RES_F_VC) == 0) {
786 if (statp->_vcsock >= 0)
787 res_nclose(statp);
788
Nick Kralevich1781ed72014-06-29 20:46:17 -0700789 statp->_vcsock = socket(nsap->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800790 if (statp->_vcsock > highestFD) {
791 res_nclose(statp);
792 errno = ENOTSOCK;
793 }
794 if (statp->_vcsock < 0) {
795 switch (errno) {
796 case EPROTONOSUPPORT:
797#ifdef EPFNOSUPPORT
798 case EPFNOSUPPORT:
799#endif
800 case EAFNOSUPPORT:
801 Perror(statp, stderr, "socket(vc)", errno);
802 return (0);
803 default:
804 *terrno = errno;
805 Perror(statp, stderr, "socket(vc)", errno);
806 return (-1);
807 }
808 }
Szymon Jakubczakea9bf672014-02-14 17:07:23 -0500809 if (statp->_mark != MARK_UNSET) {
Chad Brubakerc39214e2013-06-20 10:36:56 -0700810 if (setsockopt(statp->_vcsock, SOL_SOCKET,
Pierre Imai6b3f0d62016-02-22 17:50:41 +0900811 SO_MARK, &statp->_mark, sizeof(statp->_mark)) < 0) {
Chad Brubakerc39214e2013-06-20 10:36:56 -0700812 *terrno = errno;
813 Perror(statp, stderr, "setsockopt", errno);
814 return -1;
815 }
816 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800817 errno = 0;
818 if (random_bind(statp->_vcsock,nsap->sa_family) < 0) {
819 *terrno = errno;
820 Aerror(statp, stderr, "bind/vc", errno, nsap,
821 nsaplen);
822 res_nclose(statp);
823 return (0);
824 }
Robert Greenwaltecd0e952012-01-11 10:04:48 -0800825 if (connect_with_timeout(statp->_vcsock, nsap, (socklen_t)nsaplen,
826 get_timeout(statp, ns)) < 0) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800827 *terrno = errno;
828 Aerror(statp, stderr, "connect/vc", errno, nsap,
829 nsaplen);
830 res_nclose(statp);
Pierre Imai6b3f0d62016-02-22 17:50:41 +0900831 /*
832 * The way connect_with_timeout() is implemented prevents us from reliably
833 * determining whether this was really a timeout or e.g. ECONNREFUSED. Since
834 * currently both cases are handled in the same way, there is no need to
835 * change this (yet). If we ever need to reliably distinguish between these
836 * cases, both connect_with_timeout() and retrying_select() need to be
837 * modified, though.
838 */
839 *rcode = RCODE_TIMEOUT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800840 return (0);
841 }
842 statp->_flags |= RES_F_VC;
843 }
844
845 /*
846 * Send length & message
847 */
848 ns_put16((u_short)buflen, (u_char*)(void *)&len);
849 iov[0] = evConsIovec(&len, INT16SZ);
850 DE_CONST(buf, tmp);
851 iov[1] = evConsIovec(tmp, (size_t)buflen);
852 if (writev(statp->_vcsock, iov, 2) != (INT16SZ + buflen)) {
853 *terrno = errno;
854 Perror(statp, stderr, "write failed", errno);
855 res_nclose(statp);
856 return (0);
857 }
858 /*
859 * Receive length & response
860 */
861 read_len:
862 cp = ans;
863 len = INT16SZ;
864 while ((n = read(statp->_vcsock, (char *)cp, (size_t)len)) > 0) {
865 cp += n;
866 if ((len -= n) == 0)
867 break;
868 }
869 if (n <= 0) {
870 *terrno = errno;
871 Perror(statp, stderr, "read failed", errno);
872 res_nclose(statp);
873 /*
874 * A long running process might get its TCP
875 * connection reset if the remote server was
876 * restarted. Requery the server instead of
877 * trying a new one. When there is only one
878 * server, this means that a query might work
879 * instead of failing. We only allow one reset
880 * per query to prevent looping.
881 */
882 if (*terrno == ECONNRESET && !connreset) {
883 connreset = 1;
884 res_nclose(statp);
885 goto same_ns;
886 }
887 res_nclose(statp);
888 return (0);
889 }
890 resplen = ns_get16(ans);
891 if (resplen > anssiz) {
892 Dprint(statp->options & RES_DEBUG,
893 (stdout, ";; response truncated\n")
894 );
895 truncating = 1;
896 len = anssiz;
897 } else
898 len = resplen;
899 if (len < HFIXEDSZ) {
900 /*
901 * Undersized message.
902 */
903 Dprint(statp->options & RES_DEBUG,
904 (stdout, ";; undersized: %d\n", len));
905 *terrno = EMSGSIZE;
906 res_nclose(statp);
907 return (0);
908 }
909 cp = ans;
910 while (len != 0 && (n = read(statp->_vcsock, (char *)cp, (size_t)len)) > 0){
911 cp += n;
912 len -= n;
913 }
914 if (n <= 0) {
915 *terrno = errno;
916 Perror(statp, stderr, "read(vc)", errno);
917 res_nclose(statp);
918 return (0);
919 }
Pierre Imai6b3f0d62016-02-22 17:50:41 +0900920
921 struct timespec done = evNowTime();
922 *at = done.tv_sec;
923
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800924 if (truncating) {
925 /*
926 * Flush rest of answer so connection stays in synch.
927 */
928 anhp->tc = 1;
929 len = resplen - anssiz;
930 while (len != 0) {
931 char junk[PACKETSZ];
932
933 n = read(statp->_vcsock, junk,
934 (len > sizeof junk) ? sizeof junk : len);
935 if (n > 0)
936 len -= n;
937 else
938 break;
939 }
940 }
941 /*
942 * If the calling applicating has bailed out of
943 * a previous call and failed to arrange to have
944 * the circuit closed or the server has got
945 * itself confused, then drop the packet and
946 * wait for the correct one.
947 */
948 if (hp->id != anhp->id) {
949 DprintQ((statp->options & RES_DEBUG) ||
950 (statp->pfcode & RES_PRF_REPLY),
951 (stdout, ";; old answer (unexpected):\n"),
952 ans, (resplen > anssiz) ? anssiz: resplen);
953 goto read_len;
954 }
955
956 /*
957 * All is well, or the error is fatal. Signal that the
958 * next nameserver ought not be tried.
959 */
Pierre Imai6b3f0d62016-02-22 17:50:41 +0900960 if (resplen > 0) {
961 *delay = _res_stats_calculate_rtt(&done, &now);
962 *rcode = anhp->rcode;
963 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800964 return (resplen);
965}
966
Robert Greenwaltecd0e952012-01-11 10:04:48 -0800967/* return -1 on error (errno set), 0 on success */
968static int
969connect_with_timeout(int sock, const struct sockaddr *nsap, socklen_t salen, int sec)
970{
971 int res, origflags;
972 fd_set rset, wset;
973 struct timespec now, timeout, finish;
974
975 origflags = fcntl(sock, F_GETFL, 0);
976 fcntl(sock, F_SETFL, origflags | O_NONBLOCK);
977
Paul Jensen31ad0372014-05-29 16:28:30 -0400978 res = __connect(sock, nsap, salen);
Robert Greenwaltecd0e952012-01-11 10:04:48 -0800979 if (res < 0 && errno != EINPROGRESS) {
Pierre Imai6b3f0d62016-02-22 17:50:41 +0900980 res = -1;
981 goto done;
Robert Greenwaltecd0e952012-01-11 10:04:48 -0800982 }
983 if (res != 0) {
984 now = evNowTime();
985 timeout = evConsTime((long)sec, 0L);
986 finish = evAddTime(now, timeout);
987 if (DBG) {
Elliott Hughes8f2a5a02013-03-15 15:30:25 -0700988 __libc_format_log(ANDROID_LOG_DEBUG, "libc", " %d send_vc\n", sock);
Robert Greenwaltecd0e952012-01-11 10:04:48 -0800989 }
990
991 res = retrying_select(sock, &rset, &wset, &finish);
992 if (res <= 0) {
Pierre Imai6b3f0d62016-02-22 17:50:41 +0900993 res = -1;
Robert Greenwaltecd0e952012-01-11 10:04:48 -0800994 }
995 }
996done:
997 fcntl(sock, F_SETFL, origflags);
998 if (DBG) {
Elliott Hughes8f2a5a02013-03-15 15:30:25 -0700999 __libc_format_log(ANDROID_LOG_DEBUG, "libc",
Kito Chengbb0b09c2013-05-11 17:48:48 +08001000 " %d connect_with_timeout returning %d\n", sock, res);
Robert Greenwaltecd0e952012-01-11 10:04:48 -08001001 }
1002 return res;
1003}
1004
1005static int
1006retrying_select(const int sock, fd_set *readset, fd_set *writeset, const struct timespec *finish)
1007{
1008 struct timespec now, timeout;
1009 int n, error;
1010 socklen_t len;
1011
1012
1013retry:
1014 if (DBG) {
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001015 __libc_format_log(ANDROID_LOG_DEBUG, "libc", " %d retrying_select\n", sock);
Robert Greenwaltecd0e952012-01-11 10:04:48 -08001016 }
1017
1018 now = evNowTime();
1019 if (readset) {
1020 FD_ZERO(readset);
1021 FD_SET(sock, readset);
1022 }
1023 if (writeset) {
1024 FD_ZERO(writeset);
1025 FD_SET(sock, writeset);
1026 }
1027 if (evCmpTime(*finish, now) > 0)
1028 timeout = evSubTime(*finish, now);
1029 else
1030 timeout = evConsTime(0L, 0L);
1031
1032 n = pselect(sock + 1, readset, writeset, NULL, &timeout, NULL);
1033 if (n == 0) {
1034 if (DBG) {
Elliott Hughes8f2a5a02013-03-15 15:30:25 -07001035 __libc_format_log(ANDROID_LOG_DEBUG, " libc",
Robert Greenwaltecd0e952012-01-11 10:04:48 -08001036 " %d retrying_select timeout\n", sock);
1037 }
1038 errno = ETIMEDOUT;
1039 return 0;
1040 }
1041 if (n < 0) {
1042 if (errno == EINTR)
1043 goto retry;
1044 if (DBG) {
Elliott Hughes8f2a5a02013-03-15 15:30:25 -07001045 __libc_format_log(ANDROID_LOG_DEBUG, "libc",
Robert Greenwaltecd0e952012-01-11 10:04:48 -08001046 " %d retrying_select got error %d\n",sock, n);
1047 }
1048 return n;
1049 }
1050 if ((readset && FD_ISSET(sock, readset)) || (writeset && FD_ISSET(sock, writeset))) {
1051 len = sizeof(error);
1052 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &len) < 0 || error) {
1053 errno = error;
1054 if (DBG) {
Elliott Hughes8f2a5a02013-03-15 15:30:25 -07001055 __libc_format_log(ANDROID_LOG_DEBUG, "libc",
Robert Greenwaltecd0e952012-01-11 10:04:48 -08001056 " %d retrying_select dot error2 %d\n", sock, errno);
1057 }
1058
1059 return -1;
1060 }
1061 }
1062 if (DBG) {
Elliott Hughes8f2a5a02013-03-15 15:30:25 -07001063 __libc_format_log(ANDROID_LOG_DEBUG, "libc",
Kito Chengbb0b09c2013-05-11 17:48:48 +08001064 " %d retrying_select returning %d\n",sock, n);
Robert Greenwaltecd0e952012-01-11 10:04:48 -08001065 }
1066
1067 return n;
1068}
1069
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001070static int
1071send_dg(res_state statp,
1072 const u_char *buf, int buflen, u_char *ans, int anssiz,
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001073 int *terrno, int ns, int *v_circuit, int *gotsomewhere,
1074 time_t *at, int *rcode, int* delay)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001075{
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001076 *at = 0;
1077 *rcode = RCODE_INTERNAL_ERROR;
1078 *delay = 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001079 const HEADER *hp = (const HEADER *)(const void *)buf;
1080 HEADER *anhp = (HEADER *)(void *)ans;
1081 const struct sockaddr *nsap;
1082 int nsaplen;
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001083 struct timespec now, timeout, finish, done;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001084 fd_set dsmask;
1085 struct sockaddr_storage from;
1086 socklen_t fromlen;
1087 int resplen, seconds, n, s;
1088
1089 nsap = get_nsaddr(statp, (size_t)ns);
1090 nsaplen = get_salen(nsap);
1091 if (EXT(statp).nssocks[ns] == -1) {
Nick Kralevich1781ed72014-06-29 20:46:17 -07001092 EXT(statp).nssocks[ns] = socket(nsap->sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001093 if (EXT(statp).nssocks[ns] > highestFD) {
1094 res_nclose(statp);
1095 errno = ENOTSOCK;
1096 }
1097 if (EXT(statp).nssocks[ns] < 0) {
1098 switch (errno) {
1099 case EPROTONOSUPPORT:
1100#ifdef EPFNOSUPPORT
1101 case EPFNOSUPPORT:
1102#endif
1103 case EAFNOSUPPORT:
1104 Perror(statp, stderr, "socket(dg)", errno);
1105 return (0);
1106 default:
1107 *terrno = errno;
1108 Perror(statp, stderr, "socket(dg)", errno);
1109 return (-1);
1110 }
1111 }
Chad Brubakerc39214e2013-06-20 10:36:56 -07001112
Szymon Jakubczakea9bf672014-02-14 17:07:23 -05001113 if (statp->_mark != MARK_UNSET) {
Chad Brubakerc39214e2013-06-20 10:36:56 -07001114 if (setsockopt(EXT(statp).nssocks[ns], SOL_SOCKET,
1115 SO_MARK, &(statp->_mark), sizeof(statp->_mark)) < 0) {
1116 res_nclose(statp);
1117 return -1;
1118 }
1119 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001120#ifndef CANNOT_CONNECT_DGRAM
1121 /*
1122 * On a 4.3BSD+ machine (client and server,
1123 * actually), sending to a nameserver datagram
1124 * port with no nameserver will cause an
1125 * ICMP port unreachable message to be returned.
1126 * If our datagram socket is "connected" to the
1127 * server, we get an ECONNREFUSED error on the next
1128 * socket operation, and select returns if the
1129 * error message is received. We can thus detect
1130 * the absence of a nameserver without timing out.
1131 */
1132 if (random_bind(EXT(statp).nssocks[ns], nsap->sa_family) < 0) {
1133 Aerror(statp, stderr, "bind(dg)", errno, nsap,
1134 nsaplen);
1135 res_nclose(statp);
1136 return (0);
1137 }
Paul Jensen31ad0372014-05-29 16:28:30 -04001138 if (__connect(EXT(statp).nssocks[ns], nsap, (socklen_t)nsaplen) < 0) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001139 Aerror(statp, stderr, "connect(dg)", errno, nsap,
1140 nsaplen);
1141 res_nclose(statp);
1142 return (0);
1143 }
1144#endif /* !CANNOT_CONNECT_DGRAM */
1145 Dprint(statp->options & RES_DEBUG,
1146 (stdout, ";; new DG socket\n"))
Chad Brubakerc39214e2013-06-20 10:36:56 -07001147
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001148 }
1149 s = EXT(statp).nssocks[ns];
1150#ifndef CANNOT_CONNECT_DGRAM
1151 if (send(s, (const char*)buf, (size_t)buflen, 0) != buflen) {
1152 Perror(statp, stderr, "send", errno);
1153 res_nclose(statp);
1154 return (0);
1155 }
1156#else /* !CANNOT_CONNECT_DGRAM */
1157 if (sendto(s, (const char*)buf, buflen, 0, nsap, nsaplen) != buflen)
1158 {
1159 Aerror(statp, stderr, "sendto", errno, nsap, nsaplen);
1160 res_nclose(statp);
1161 return (0);
1162 }
1163#endif /* !CANNOT_CONNECT_DGRAM */
1164
1165 /*
1166 * Wait for reply.
1167 */
Robert Greenwaltecd0e952012-01-11 10:04:48 -08001168 seconds = get_timeout(statp, ns);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001169 now = evNowTime();
1170 timeout = evConsTime((long)seconds, 0L);
1171 finish = evAddTime(now, timeout);
Robert Greenwaltecd0e952012-01-11 10:04:48 -08001172retry:
1173 n = retrying_select(s, &dsmask, NULL, &finish);
1174
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001175 if (n == 0) {
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001176 *rcode = RCODE_TIMEOUT;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001177 Dprint(statp->options & RES_DEBUG, (stdout, ";; timeout\n"));
1178 *gotsomewhere = 1;
1179 return (0);
1180 }
1181 if (n < 0) {
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001182 Perror(statp, stderr, "select", errno);
1183 res_nclose(statp);
1184 return (0);
1185 }
1186 errno = 0;
1187 fromlen = sizeof(from);
1188 resplen = recvfrom(s, (char*)ans, (size_t)anssiz,0,
1189 (struct sockaddr *)(void *)&from, &fromlen);
1190 if (resplen <= 0) {
1191 Perror(statp, stderr, "recvfrom", errno);
1192 res_nclose(statp);
1193 return (0);
1194 }
1195 *gotsomewhere = 1;
1196 if (resplen < HFIXEDSZ) {
1197 /*
1198 * Undersized message.
1199 */
1200 Dprint(statp->options & RES_DEBUG,
1201 (stdout, ";; undersized: %d\n",
1202 resplen));
1203 *terrno = EMSGSIZE;
1204 res_nclose(statp);
1205 return (0);
1206 }
1207 if (hp->id != anhp->id) {
1208 /*
1209 * response from old query, ignore it.
1210 * XXX - potential security hazard could
1211 * be detected here.
1212 */
1213 DprintQ((statp->options & RES_DEBUG) ||
1214 (statp->pfcode & RES_PRF_REPLY),
1215 (stdout, ";; old answer:\n"),
1216 ans, (resplen > anssiz) ? anssiz : resplen);
Robert Greenwaltecd0e952012-01-11 10:04:48 -08001217 goto retry;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001218 }
1219 if (!(statp->options & RES_INSECURE1) &&
1220 !res_ourserver_p(statp, (struct sockaddr *)(void *)&from)) {
1221 /*
1222 * response from wrong server? ignore it.
1223 * XXX - potential security hazard could
1224 * be detected here.
1225 */
1226 DprintQ((statp->options & RES_DEBUG) ||
1227 (statp->pfcode & RES_PRF_REPLY),
1228 (stdout, ";; not our server:\n"),
1229 ans, (resplen > anssiz) ? anssiz : resplen);
Robert Greenwaltecd0e952012-01-11 10:04:48 -08001230 goto retry;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001231 }
1232#ifdef RES_USE_EDNS0
1233 if (anhp->rcode == FORMERR && (statp->options & RES_USE_EDNS0) != 0U) {
1234 /*
1235 * Do not retry if the server do not understand EDNS0.
1236 * The case has to be captured here, as FORMERR packet do not
1237 * carry query section, hence res_queriesmatch() returns 0.
1238 */
1239 DprintQ(statp->options & RES_DEBUG,
1240 (stdout, "server rejected query with EDNS0:\n"),
1241 ans, (resplen > anssiz) ? anssiz : resplen);
1242 /* record the error */
1243 statp->_flags |= RES_F_EDNS0ERR;
1244 res_nclose(statp);
1245 return (0);
1246 }
1247#endif
1248 if (!(statp->options & RES_INSECURE2) &&
1249 !res_queriesmatch(buf, buf + buflen,
1250 ans, ans + anssiz)) {
1251 /*
1252 * response contains wrong query? ignore it.
1253 * XXX - potential security hazard could
1254 * be detected here.
1255 */
1256 DprintQ((statp->options & RES_DEBUG) ||
1257 (statp->pfcode & RES_PRF_REPLY),
1258 (stdout, ";; wrong query name:\n"),
1259 ans, (resplen > anssiz) ? anssiz : resplen);
Robert Greenwaltecd0e952012-01-11 10:04:48 -08001260 goto retry;;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001261 }
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001262 done = evNowTime();
1263 *at = done.tv_sec;
1264 *delay = _res_stats_calculate_rtt(&done, &now);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001265 if (anhp->rcode == SERVFAIL ||
1266 anhp->rcode == NOTIMP ||
1267 anhp->rcode == REFUSED) {
1268 DprintQ(statp->options & RES_DEBUG,
1269 (stdout, "server rejected query:\n"),
1270 ans, (resplen > anssiz) ? anssiz : resplen);
1271 res_nclose(statp);
1272 /* don't retry if called from dig */
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001273 if (!statp->pfcode) {
1274 *rcode = anhp->rcode;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001275 return (0);
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001276 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001277 }
1278 if (!(statp->options & RES_IGNTC) && anhp->tc) {
1279 /*
1280 * To get the rest of answer,
1281 * use TCP with same server.
1282 */
1283 Dprint(statp->options & RES_DEBUG,
1284 (stdout, ";; truncated answer\n"));
1285 *v_circuit = 1;
1286 res_nclose(statp);
1287 return (1);
1288 }
1289 /*
1290 * All is well, or the error is fatal. Signal that the
1291 * next nameserver ought not be tried.
1292 */
Pierre Imai6b3f0d62016-02-22 17:50:41 +09001293 if (resplen > 0) {
1294 *rcode = anhp->rcode;
1295 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001296 return (resplen);
1297}
1298
1299static void
1300Aerror(const res_state statp, FILE *file, const char *string, int error,
1301 const struct sockaddr *address, int alen)
1302{
1303 int save = errno;
1304 char hbuf[NI_MAXHOST];
1305 char sbuf[NI_MAXSERV];
1306
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001307 if ((statp->options & RES_DEBUG) != 0U) {
1308 if (getnameinfo(address, (socklen_t)alen, hbuf, sizeof(hbuf),
1309 sbuf, sizeof(sbuf), niflags)) {
1310 strncpy(hbuf, "?", sizeof(hbuf) - 1);
1311 hbuf[sizeof(hbuf) - 1] = '\0';
1312 strncpy(sbuf, "?", sizeof(sbuf) - 1);
1313 sbuf[sizeof(sbuf) - 1] = '\0';
1314 }
1315 fprintf(file, "res_send: %s ([%s].%s): %s\n",
1316 string, hbuf, sbuf, strerror(error));
1317 }
1318 errno = save;
1319}
1320
1321static void
1322Perror(const res_state statp, FILE *file, const char *string, int error) {
1323 int save = errno;
1324
1325 if ((statp->options & RES_DEBUG) != 0U)
1326 fprintf(file, "res_send: %s: %s\n",
1327 string, strerror(error));
1328 errno = save;
1329}
1330
1331static int
1332sock_eq(struct sockaddr *a, struct sockaddr *b) {
1333 struct sockaddr_in *a4, *b4;
1334 struct sockaddr_in6 *a6, *b6;
1335
1336 if (a->sa_family != b->sa_family)
1337 return 0;
1338 switch (a->sa_family) {
1339 case AF_INET:
1340 a4 = (struct sockaddr_in *)(void *)a;
1341 b4 = (struct sockaddr_in *)(void *)b;
1342 return a4->sin_port == b4->sin_port &&
1343 a4->sin_addr.s_addr == b4->sin_addr.s_addr;
1344 case AF_INET6:
1345 a6 = (struct sockaddr_in6 *)(void *)a;
1346 b6 = (struct sockaddr_in6 *)(void *)b;
1347 return a6->sin6_port == b6->sin6_port &&
1348#ifdef HAVE_SIN6_SCOPE_ID
1349 a6->sin6_scope_id == b6->sin6_scope_id &&
1350#endif
1351 IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
1352 default:
1353 return 0;
1354 }
1355}
1356
1357#ifdef NEED_PSELECT
1358/* XXX needs to move to the porting library. */
1359static int
1360pselect(int nfds, void *rfds, void *wfds, void *efds,
1361 struct timespec *tsp, const sigset_t *sigmask)
1362{
1363 struct timeval tv, *tvp;
1364 sigset_t sigs;
1365 int n;
1366
1367 if (tsp) {
1368 tvp = &tv;
1369 tv = evTimeVal(*tsp);
1370 } else
1371 tvp = NULL;
1372 if (sigmask)
1373 sigprocmask(SIG_SETMASK, sigmask, &sigs);
1374 n = select(nfds, rfds, wfds, efds, tvp);
1375 if (sigmask)
1376 sigprocmask(SIG_SETMASK, &sigs, NULL);
1377 if (tsp)
1378 *tsp = evTimeSpec(tv);
1379 return (n);
1380}
1381#endif