blob: 24b740a2c2d77b2465768454dfab927f7dab15f5 [file] [log] [blame]
The Android Open Source Projecta27d2ba2008-10-21 07:00:00 -07001/* $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
84/*
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>
95#include <netinet/in6.h>
96#include "arpa_nameser.h"
97#include <arpa/inet.h>
98
99#include <errno.h>
100#include <netdb.h>
101#ifdef ANDROID_CHANGES
102#include "resolv_private.h"
103#else
104#include <resolv.h>
105#endif
106#include <signal.h>
107#include <stdio.h>
108#include <stdlib.h>
109#include <string.h>
110#include <unistd.h>
111
112#include <isc/eventlib.h>
113
114#ifndef DE_CONST
115#define DE_CONST(c,v) v = ((c) ? \
116 strchr((const void *)(c), *(const char *)(const void *)(c)) : NULL)
117#endif
118
119/* Options. Leave them on. */
120#ifndef DEBUG
121#define DEBUG
122#endif
123#include "res_debug.h"
124#include "res_private.h"
125
126#define EXT(res) ((res)->_u._ext)
127
128static const int highestFD = FD_SETSIZE - 1;
129
130/* Forward. */
131
132static int get_salen __P((const struct sockaddr *));
133static struct sockaddr * get_nsaddr __P((res_state, size_t));
134static int send_vc(res_state, const u_char *, int,
135 u_char *, int, int *, int);
136static int send_dg(res_state, const u_char *, int,
137 u_char *, int, int *, int,
138 int *, int *);
139static void Aerror(const res_state, FILE *, const char *, int,
140 const struct sockaddr *, int);
141static void Perror(const res_state, FILE *, const char *, int);
142static int sock_eq(struct sockaddr *, struct sockaddr *);
143#ifdef NEED_PSELECT
144static int pselect(int, void *, void *, void *,
145 struct timespec *,
146 const sigset_t *);
147#endif
148void res_pquery(const res_state, const u_char *, int, FILE *);
149
150
151/* BIONIC-BEGIN: implement source port randomization */
152typedef union {
153 struct sockaddr sa;
154 struct sockaddr_in sin;
155 struct sockaddr_in6 sin6;
156} _sockaddr_union;
157
158static int
159random_bind( int s, int family )
160{
161 _sockaddr_union u;
162 int j;
163 socklen_t slen;
164
165 /* clear all, this also sets the IP4/6 address to 'any' */
166 memset( &u, 0, sizeof u );
167
168 switch (family) {
169 case AF_INET:
170 u.sin.sin_family = family;
171 slen = sizeof u.sin;
172 break;
173 case AF_INET6:
174 u.sin6.sin6_family = family;
175 slen = sizeof u.sin6;
176 break;
177 default:
178 errno = EPROTO;
179 return -1;
180 }
181
182 /* first try to bind to a random source port a few times */
183 for (j = 0; j < 10; j++) {
184 /* find a random port between 1025 .. 65534 */
185 int port = 1025 + (res_randomid() % (65535-1025));
186 if (family == AF_INET)
187 u.sin.sin_port = htons(port);
188 else
189 u.sin6.sin6_port = htons(port);
190
191 if ( !bind( s, &u.sa, slen ) )
192 return 0;
193 }
194
195 /* nothing after 10 tries, our network table is probably busy */
196 /* let the system decide which port is best */
197 if (family == AF_INET)
198 u.sin.sin_port = 0;
199 else
200 u.sin6.sin6_port = 0;
201
202 return bind( s, &u.sa, slen );
203}
204/* BIONIC-END */
205
206static const int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
207
208/* Public. */
209
210/* int
211 * res_isourserver(ina)
212 * looks up "ina" in _res.ns_addr_list[]
213 * returns:
214 * 0 : not found
215 * >0 : found
216 * author:
217 * paul vixie, 29may94
218 */
219int
220res_ourserver_p(const res_state statp, const struct sockaddr *sa) {
221 const struct sockaddr_in *inp, *srv;
222 const struct sockaddr_in6 *in6p, *srv6;
223 int ns;
224
225 switch (sa->sa_family) {
226 case AF_INET:
227 inp = (const struct sockaddr_in *)(const void *)sa;
228 for (ns = 0; ns < statp->nscount; ns++) {
229 srv = (struct sockaddr_in *)(void *)get_nsaddr(statp, (size_t)ns);
230 if (srv->sin_family == inp->sin_family &&
231 srv->sin_port == inp->sin_port &&
232 (srv->sin_addr.s_addr == INADDR_ANY ||
233 srv->sin_addr.s_addr == inp->sin_addr.s_addr))
234 return (1);
235 }
236 break;
237 case AF_INET6:
238 if (EXT(statp).ext == NULL)
239 break;
240 in6p = (const struct sockaddr_in6 *)(const void *)sa;
241 for (ns = 0; ns < statp->nscount; ns++) {
242 srv6 = (struct sockaddr_in6 *)(void *)get_nsaddr(statp, (size_t)ns);
243 if (srv6->sin6_family == in6p->sin6_family &&
244 srv6->sin6_port == in6p->sin6_port &&
245#ifdef HAVE_SIN6_SCOPE_ID
246 (srv6->sin6_scope_id == 0 ||
247 srv6->sin6_scope_id == in6p->sin6_scope_id) &&
248#endif
249 (IN6_IS_ADDR_UNSPECIFIED(&srv6->sin6_addr) ||
250 IN6_ARE_ADDR_EQUAL(&srv6->sin6_addr, &in6p->sin6_addr)))
251 return (1);
252 }
253 break;
254 default:
255 break;
256 }
257 return (0);
258}
259
260/* int
261 * res_nameinquery(name, type, class, buf, eom)
262 * look for (name,type,class) in the query section of packet (buf,eom)
263 * requires:
264 * buf + HFIXEDSZ <= eom
265 * returns:
266 * -1 : format error
267 * 0 : not found
268 * >0 : found
269 * author:
270 * paul vixie, 29may94
271 */
272int
273res_nameinquery(const char *name, int type, int class,
274 const u_char *buf, const u_char *eom)
275{
276 const u_char *cp = buf + HFIXEDSZ;
277 int qdcount = ntohs(((const HEADER*)(const void *)buf)->qdcount);
278
279 while (qdcount-- > 0) {
280 char tname[MAXDNAME+1];
281 int n, ttype, tclass;
282
283 n = dn_expand(buf, eom, cp, tname, sizeof tname);
284 if (n < 0)
285 return (-1);
286 cp += n;
287 if (cp + 2 * INT16SZ > eom)
288 return (-1);
289 ttype = ns_get16(cp); cp += INT16SZ;
290 tclass = ns_get16(cp); cp += INT16SZ;
291 if (ttype == type && tclass == class &&
292 ns_samename(tname, name) == 1)
293 return (1);
294 }
295 return (0);
296}
297
298/* int
299 * res_queriesmatch(buf1, eom1, buf2, eom2)
300 * is there a 1:1 mapping of (name,type,class)
301 * in (buf1,eom1) and (buf2,eom2)?
302 * returns:
303 * -1 : format error
304 * 0 : not a 1:1 mapping
305 * >0 : is a 1:1 mapping
306 * author:
307 * paul vixie, 29may94
308 */
309int
310res_queriesmatch(const u_char *buf1, const u_char *eom1,
311 const u_char *buf2, const u_char *eom2)
312{
313 const u_char *cp = buf1 + HFIXEDSZ;
314 int qdcount = ntohs(((const HEADER*)(const void *)buf1)->qdcount);
315
316 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2)
317 return (-1);
318
319 /*
320 * Only header section present in replies to
321 * dynamic update packets.
322 */
323 if ((((const HEADER *)(const void *)buf1)->opcode == ns_o_update) &&
324 (((const HEADER *)(const void *)buf2)->opcode == ns_o_update))
325 return (1);
326
327 if (qdcount != ntohs(((const HEADER*)(const void *)buf2)->qdcount))
328 return (0);
329 while (qdcount-- > 0) {
330 char tname[MAXDNAME+1];
331 int n, ttype, tclass;
332
333 n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
334 if (n < 0)
335 return (-1);
336 cp += n;
337 if (cp + 2 * INT16SZ > eom1)
338 return (-1);
339 ttype = ns_get16(cp); cp += INT16SZ;
340 tclass = ns_get16(cp); cp += INT16SZ;
341 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2))
342 return (0);
343 }
344 return (1);
345}
346
347int
348res_nsend(res_state statp,
349 const u_char *buf, int buflen, u_char *ans, int anssiz)
350{
351 int gotsomewhere, terrno, try, v_circuit, resplen, ns, n;
352 char abuf[NI_MAXHOST];
353
354 if (statp->nscount == 0) {
355 errno = ESRCH;
356 return (-1);
357 }
358 if (anssiz < HFIXEDSZ) {
359 errno = EINVAL;
360 return (-1);
361 }
362 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_QUERY),
363 (stdout, ";; res_send()\n"), buf, buflen);
364 v_circuit = (statp->options & RES_USEVC) || buflen > PACKETSZ;
365 gotsomewhere = 0;
366 terrno = ETIMEDOUT;
367
368 /*
369 * If the ns_addr_list in the resolver context has changed, then
370 * invalidate our cached copy and the associated timing data.
371 */
372 if (EXT(statp).nscount != 0) {
373 int needclose = 0;
374 struct sockaddr_storage peer;
375 socklen_t peerlen;
376
377 if (EXT(statp).nscount != statp->nscount)
378 needclose++;
379 else
380 for (ns = 0; ns < statp->nscount; ns++) {
381 if (statp->nsaddr_list[ns].sin_family &&
382 !sock_eq((struct sockaddr *)(void *)&statp->nsaddr_list[ns],
383 (struct sockaddr *)(void *)&EXT(statp).ext->nsaddrs[ns])) {
384 needclose++;
385 break;
386 }
387
388 if (EXT(statp).nssocks[ns] == -1)
389 continue;
390 peerlen = sizeof(peer);
391 if (getsockname(EXT(statp).nssocks[ns],
392 (struct sockaddr *)(void *)&peer, &peerlen) < 0) {
393 needclose++;
394 break;
395 }
396 if (!sock_eq((struct sockaddr *)(void *)&peer,
397 get_nsaddr(statp, (size_t)ns))) {
398 needclose++;
399 break;
400 }
401 }
402 if (needclose) {
403 res_nclose(statp);
404 EXT(statp).nscount = 0;
405 }
406 }
407
408 /*
409 * Maybe initialize our private copy of the ns_addr_list.
410 */
411 if (EXT(statp).nscount == 0) {
412 for (ns = 0; ns < statp->nscount; ns++) {
413 EXT(statp).nstimes[ns] = RES_MAXTIME;
414 EXT(statp).nssocks[ns] = -1;
415 if (!statp->nsaddr_list[ns].sin_family)
416 continue;
417 EXT(statp).ext->nsaddrs[ns].sin =
418 statp->nsaddr_list[ns];
419 }
420 EXT(statp).nscount = statp->nscount;
421 }
422
423 /*
424 * Some resolvers want to even out the load on their nameservers.
425 * Note that RES_BLAST overrides RES_ROTATE.
426 */
427 if ((statp->options & RES_ROTATE) != 0U &&
428 (statp->options & RES_BLAST) == 0U) {
429 union res_sockaddr_union inu;
430 struct sockaddr_in ina;
431 int lastns = statp->nscount - 1;
432 int fd;
433 u_int16_t nstime;
434
435 if (EXT(statp).ext != NULL)
436 inu = EXT(statp).ext->nsaddrs[0];
437 ina = statp->nsaddr_list[0];
438 fd = EXT(statp).nssocks[0];
439 nstime = EXT(statp).nstimes[0];
440 for (ns = 0; ns < lastns; ns++) {
441 if (EXT(statp).ext != NULL)
442 EXT(statp).ext->nsaddrs[ns] =
443 EXT(statp).ext->nsaddrs[ns + 1];
444 statp->nsaddr_list[ns] = statp->nsaddr_list[ns + 1];
445 EXT(statp).nssocks[ns] = EXT(statp).nssocks[ns + 1];
446 EXT(statp).nstimes[ns] = EXT(statp).nstimes[ns + 1];
447 }
448 if (EXT(statp).ext != NULL)
449 EXT(statp).ext->nsaddrs[lastns] = inu;
450 statp->nsaddr_list[lastns] = ina;
451 EXT(statp).nssocks[lastns] = fd;
452 EXT(statp).nstimes[lastns] = nstime;
453 }
454
455 /*
456 * Send request, RETRY times, or until successful.
457 */
458 for (try = 0; try < statp->retry; try++) {
459 for (ns = 0; ns < statp->nscount; ns++) {
460 struct sockaddr *nsap;
461 int nsaplen;
462 nsap = get_nsaddr(statp, (size_t)ns);
463 nsaplen = get_salen(nsap);
464 statp->_flags &= ~RES_F_LASTMASK;
465 statp->_flags |= (ns << RES_F_LASTSHIFT);
466 same_ns:
467 if (statp->qhook) {
468 int done = 0, loops = 0;
469
470 do {
471 res_sendhookact act;
472
473 act = (*statp->qhook)(&nsap, &buf, &buflen,
474 ans, anssiz, &resplen);
475 switch (act) {
476 case res_goahead:
477 done = 1;
478 break;
479 case res_nextns:
480 res_nclose(statp);
481 goto next_ns;
482 case res_done:
483 return (resplen);
484 case res_modified:
485 /* give the hook another try */
486 if (++loops < 42) /*doug adams*/
487 break;
488 /*FALLTHROUGH*/
489 case res_error:
490 /*FALLTHROUGH*/
491 default:
492 goto fail;
493 }
494 } while (!done);
495 }
496
497 Dprint(((statp->options & RES_DEBUG) &&
498 getnameinfo(nsap, (socklen_t)nsaplen, abuf, sizeof(abuf),
499 NULL, 0, niflags) == 0),
500 (stdout, ";; Querying server (# %d) address = %s\n",
501 ns + 1, abuf));
502
503
504 if (v_circuit) {
505 /* Use VC; at most one attempt per server. */
506 try = statp->retry;
507 n = send_vc(statp, buf, buflen, ans, anssiz, &terrno,
508 ns);
509 if (n < 0)
510 goto fail;
511 if (n == 0)
512 goto next_ns;
513 resplen = n;
514 } else {
515 /* Use datagrams. */
516 n = send_dg(statp, buf, buflen, ans, anssiz, &terrno,
517 ns, &v_circuit, &gotsomewhere);
518 if (n < 0)
519 goto fail;
520 if (n == 0)
521 goto next_ns;
522 if (v_circuit)
523 goto same_ns;
524 resplen = n;
525 }
526
527 Dprint((statp->options & RES_DEBUG) ||
528 ((statp->pfcode & RES_PRF_REPLY) &&
529 (statp->pfcode & RES_PRF_HEAD1)),
530 (stdout, ";; got answer:\n"));
531
532 DprintQ((statp->options & RES_DEBUG) ||
533 (statp->pfcode & RES_PRF_REPLY),
534 (stdout, "%s", ""),
535 ans, (resplen > anssiz) ? anssiz : resplen);
536
537 /*
538 * If we have temporarily opened a virtual circuit,
539 * or if we haven't been asked to keep a socket open,
540 * close the socket.
541 */
542 if ((v_circuit && (statp->options & RES_USEVC) == 0U) ||
543 (statp->options & RES_STAYOPEN) == 0U) {
544 res_nclose(statp);
545 }
546 if (statp->rhook) {
547 int done = 0, loops = 0;
548
549 do {
550 res_sendhookact act;
551
552 act = (*statp->rhook)(nsap, buf, buflen,
553 ans, anssiz, &resplen);
554 switch (act) {
555 case res_goahead:
556 case res_done:
557 done = 1;
558 break;
559 case res_nextns:
560 res_nclose(statp);
561 goto next_ns;
562 case res_modified:
563 /* give the hook another try */
564 if (++loops < 42) /*doug adams*/
565 break;
566 /*FALLTHROUGH*/
567 case res_error:
568 /*FALLTHROUGH*/
569 default:
570 goto fail;
571 }
572 } while (!done);
573
574 }
575 return (resplen);
576 next_ns: ;
577 } /*foreach ns*/
578 } /*foreach retry*/
579 res_nclose(statp);
580 if (!v_circuit) {
581 if (!gotsomewhere)
582 errno = ECONNREFUSED; /* no nameservers found */
583 else
584 errno = ETIMEDOUT; /* no answer obtained */
585 } else
586 errno = terrno;
587 return (-1);
588 fail:
589 res_nclose(statp);
590 return (-1);
591}
592
593/* Private */
594
595static int
596get_salen(sa)
597 const struct sockaddr *sa;
598{
599
600#ifdef HAVE_SA_LEN
601 /* There are people do not set sa_len. Be forgiving to them. */
602 if (sa->sa_len)
603 return (sa->sa_len);
604#endif
605
606 if (sa->sa_family == AF_INET)
607 return (sizeof(struct sockaddr_in));
608 else if (sa->sa_family == AF_INET6)
609 return (sizeof(struct sockaddr_in6));
610 else
611 return (0); /* unknown, die on connect */
612}
613
614/*
615 * pick appropriate nsaddr_list for use. see res_init() for initialization.
616 */
617static struct sockaddr *
618get_nsaddr(statp, n)
619 res_state statp;
620 size_t n;
621{
622
623 if (!statp->nsaddr_list[n].sin_family && EXT(statp).ext) {
624 /*
625 * - EXT(statp).ext->nsaddrs[n] holds an address that is larger
626 * than struct sockaddr, and
627 * - user code did not update statp->nsaddr_list[n].
628 */
629 return (struct sockaddr *)(void *)&EXT(statp).ext->nsaddrs[n];
630 } else {
631 /*
632 * - user code updated statp->nsaddr_list[n], or
633 * - statp->nsaddr_list[n] has the same content as
634 * EXT(statp).ext->nsaddrs[n].
635 */
636 return (struct sockaddr *)(void *)&statp->nsaddr_list[n];
637 }
638}
639
640static int
641send_vc(res_state statp,
642 const u_char *buf, int buflen, u_char *ans, int anssiz,
643 int *terrno, int ns)
644{
645 const HEADER *hp = (const HEADER *)(const void *)buf;
646 HEADER *anhp = (HEADER *)(void *)ans;
647 struct sockaddr *nsap;
648 int nsaplen;
649 int truncating, connreset, resplen, n;
650 struct iovec iov[2];
651 u_short len;
652 u_char *cp;
653 void *tmp;
654
655 nsap = get_nsaddr(statp, (size_t)ns);
656 nsaplen = get_salen(nsap);
657
658 connreset = 0;
659 same_ns:
660 truncating = 0;
661
662 /* Are we still talking to whom we want to talk to? */
663 if (statp->_vcsock >= 0 && (statp->_flags & RES_F_VC) != 0) {
664 struct sockaddr_storage peer;
665 socklen_t size = sizeof peer;
666
667 if (getpeername(statp->_vcsock,
668 (struct sockaddr *)(void *)&peer, &size) < 0 ||
669 !sock_eq((struct sockaddr *)(void *)&peer, nsap)) {
670 res_nclose(statp);
671 statp->_flags &= ~RES_F_VC;
672 }
673 }
674
675 if (statp->_vcsock < 0 || (statp->_flags & RES_F_VC) == 0) {
676 if (statp->_vcsock >= 0)
677 res_nclose(statp);
678
679 statp->_vcsock = socket(nsap->sa_family, SOCK_STREAM, 0);
680 if (statp->_vcsock > highestFD) {
681 res_nclose(statp);
682 errno = ENOTSOCK;
683 }
684 if (statp->_vcsock < 0) {
685 switch (errno) {
686 case EPROTONOSUPPORT:
687#ifdef EPFNOSUPPORT
688 case EPFNOSUPPORT:
689#endif
690 case EAFNOSUPPORT:
691 Perror(statp, stderr, "socket(vc)", errno);
692 return (0);
693 default:
694 *terrno = errno;
695 Perror(statp, stderr, "socket(vc)", errno);
696 return (-1);
697 }
698 }
699 errno = 0;
700 if (random_bind(statp->_vcsock,nsap->sa_family) < 0) {
701 *terrno = errno;
702 Aerror(statp, stderr, "bind/vc", errno, nsap,
703 nsaplen);
704 res_nclose(statp);
705 return (0);
706 }
707 if (connect(statp->_vcsock, nsap, (socklen_t)nsaplen) < 0) {
708 *terrno = errno;
709 Aerror(statp, stderr, "connect/vc", errno, nsap,
710 nsaplen);
711 res_nclose(statp);
712 return (0);
713 }
714 statp->_flags |= RES_F_VC;
715 }
716
717 /*
718 * Send length & message
719 */
720 ns_put16((u_short)buflen, (u_char*)(void *)&len);
721 iov[0] = evConsIovec(&len, INT16SZ);
722 DE_CONST(buf, tmp);
723 iov[1] = evConsIovec(tmp, (size_t)buflen);
724 if (writev(statp->_vcsock, iov, 2) != (INT16SZ + buflen)) {
725 *terrno = errno;
726 Perror(statp, stderr, "write failed", errno);
727 res_nclose(statp);
728 return (0);
729 }
730 /*
731 * Receive length & response
732 */
733 read_len:
734 cp = ans;
735 len = INT16SZ;
736 while ((n = read(statp->_vcsock, (char *)cp, (size_t)len)) > 0) {
737 cp += n;
738 if ((len -= n) == 0)
739 break;
740 }
741 if (n <= 0) {
742 *terrno = errno;
743 Perror(statp, stderr, "read failed", errno);
744 res_nclose(statp);
745 /*
746 * A long running process might get its TCP
747 * connection reset if the remote server was
748 * restarted. Requery the server instead of
749 * trying a new one. When there is only one
750 * server, this means that a query might work
751 * instead of failing. We only allow one reset
752 * per query to prevent looping.
753 */
754 if (*terrno == ECONNRESET && !connreset) {
755 connreset = 1;
756 res_nclose(statp);
757 goto same_ns;
758 }
759 res_nclose(statp);
760 return (0);
761 }
762 resplen = ns_get16(ans);
763 if (resplen > anssiz) {
764 Dprint(statp->options & RES_DEBUG,
765 (stdout, ";; response truncated\n")
766 );
767 truncating = 1;
768 len = anssiz;
769 } else
770 len = resplen;
771 if (len < HFIXEDSZ) {
772 /*
773 * Undersized message.
774 */
775 Dprint(statp->options & RES_DEBUG,
776 (stdout, ";; undersized: %d\n", len));
777 *terrno = EMSGSIZE;
778 res_nclose(statp);
779 return (0);
780 }
781 cp = ans;
782 while (len != 0 && (n = read(statp->_vcsock, (char *)cp, (size_t)len)) > 0){
783 cp += n;
784 len -= n;
785 }
786 if (n <= 0) {
787 *terrno = errno;
788 Perror(statp, stderr, "read(vc)", errno);
789 res_nclose(statp);
790 return (0);
791 }
792 if (truncating) {
793 /*
794 * Flush rest of answer so connection stays in synch.
795 */
796 anhp->tc = 1;
797 len = resplen - anssiz;
798 while (len != 0) {
799 char junk[PACKETSZ];
800
801 n = read(statp->_vcsock, junk,
802 (len > sizeof junk) ? sizeof junk : len);
803 if (n > 0)
804 len -= n;
805 else
806 break;
807 }
808 }
809 /*
810 * If the calling applicating has bailed out of
811 * a previous call and failed to arrange to have
812 * the circuit closed or the server has got
813 * itself confused, then drop the packet and
814 * wait for the correct one.
815 */
816 if (hp->id != anhp->id) {
817 DprintQ((statp->options & RES_DEBUG) ||
818 (statp->pfcode & RES_PRF_REPLY),
819 (stdout, ";; old answer (unexpected):\n"),
820 ans, (resplen > anssiz) ? anssiz: resplen);
821 goto read_len;
822 }
823
824 /*
825 * All is well, or the error is fatal. Signal that the
826 * next nameserver ought not be tried.
827 */
828 return (resplen);
829}
830
831static int
832send_dg(res_state statp,
833 const u_char *buf, int buflen, u_char *ans, int anssiz,
834 int *terrno, int ns, int *v_circuit, int *gotsomewhere)
835{
836 const HEADER *hp = (const HEADER *)(const void *)buf;
837 HEADER *anhp = (HEADER *)(void *)ans;
838 const struct sockaddr *nsap;
839 int nsaplen;
840 struct timespec now, timeout, finish;
841 fd_set dsmask;
842 struct sockaddr_storage from;
843 socklen_t fromlen;
844 int resplen, seconds, n, s;
845
846 nsap = get_nsaddr(statp, (size_t)ns);
847 nsaplen = get_salen(nsap);
848 if (EXT(statp).nssocks[ns] == -1) {
849 EXT(statp).nssocks[ns] = socket(nsap->sa_family, SOCK_DGRAM, 0);
850 if (EXT(statp).nssocks[ns] > highestFD) {
851 res_nclose(statp);
852 errno = ENOTSOCK;
853 }
854 if (EXT(statp).nssocks[ns] < 0) {
855 switch (errno) {
856 case EPROTONOSUPPORT:
857#ifdef EPFNOSUPPORT
858 case EPFNOSUPPORT:
859#endif
860 case EAFNOSUPPORT:
861 Perror(statp, stderr, "socket(dg)", errno);
862 return (0);
863 default:
864 *terrno = errno;
865 Perror(statp, stderr, "socket(dg)", errno);
866 return (-1);
867 }
868 }
869#ifndef CANNOT_CONNECT_DGRAM
870 /*
871 * On a 4.3BSD+ machine (client and server,
872 * actually), sending to a nameserver datagram
873 * port with no nameserver will cause an
874 * ICMP port unreachable message to be returned.
875 * If our datagram socket is "connected" to the
876 * server, we get an ECONNREFUSED error on the next
877 * socket operation, and select returns if the
878 * error message is received. We can thus detect
879 * the absence of a nameserver without timing out.
880 */
881 if (random_bind(EXT(statp).nssocks[ns], nsap->sa_family) < 0) {
882 Aerror(statp, stderr, "bind(dg)", errno, nsap,
883 nsaplen);
884 res_nclose(statp);
885 return (0);
886 }
887 if (connect(EXT(statp).nssocks[ns], nsap, (socklen_t)nsaplen) < 0) {
888 Aerror(statp, stderr, "connect(dg)", errno, nsap,
889 nsaplen);
890 res_nclose(statp);
891 return (0);
892 }
893#endif /* !CANNOT_CONNECT_DGRAM */
894 Dprint(statp->options & RES_DEBUG,
895 (stdout, ";; new DG socket\n"))
896 }
897 s = EXT(statp).nssocks[ns];
898#ifndef CANNOT_CONNECT_DGRAM
899 if (send(s, (const char*)buf, (size_t)buflen, 0) != buflen) {
900 Perror(statp, stderr, "send", errno);
901 res_nclose(statp);
902 return (0);
903 }
904#else /* !CANNOT_CONNECT_DGRAM */
905 if (sendto(s, (const char*)buf, buflen, 0, nsap, nsaplen) != buflen)
906 {
907 Aerror(statp, stderr, "sendto", errno, nsap, nsaplen);
908 res_nclose(statp);
909 return (0);
910 }
911#endif /* !CANNOT_CONNECT_DGRAM */
912
913 /*
914 * Wait for reply.
915 */
916 seconds = (statp->retrans << ns);
917 if (ns > 0)
918 seconds /= statp->nscount;
919 if (seconds <= 0)
920 seconds = 1;
921 now = evNowTime();
922 timeout = evConsTime((long)seconds, 0L);
923 finish = evAddTime(now, timeout);
924 goto nonow;
925 wait:
926 now = evNowTime();
927 nonow:
928 FD_ZERO(&dsmask);
929 FD_SET(s, &dsmask);
930 if (evCmpTime(finish, now) > 0)
931 timeout = evSubTime(finish, now);
932 else
933 timeout = evConsTime(0L, 0L);
934 n = pselect(s + 1, &dsmask, NULL, NULL, &timeout, NULL);
935 if (n == 0) {
936 Dprint(statp->options & RES_DEBUG, (stdout, ";; timeout\n"));
937 *gotsomewhere = 1;
938 return (0);
939 }
940 if (n < 0) {
941 if (errno == EINTR)
942 goto wait;
943 Perror(statp, stderr, "select", errno);
944 res_nclose(statp);
945 return (0);
946 }
947 errno = 0;
948 fromlen = sizeof(from);
949 resplen = recvfrom(s, (char*)ans, (size_t)anssiz,0,
950 (struct sockaddr *)(void *)&from, &fromlen);
951 if (resplen <= 0) {
952 Perror(statp, stderr, "recvfrom", errno);
953 res_nclose(statp);
954 return (0);
955 }
956 *gotsomewhere = 1;
957 if (resplen < HFIXEDSZ) {
958 /*
959 * Undersized message.
960 */
961 Dprint(statp->options & RES_DEBUG,
962 (stdout, ";; undersized: %d\n",
963 resplen));
964 *terrno = EMSGSIZE;
965 res_nclose(statp);
966 return (0);
967 }
968 if (hp->id != anhp->id) {
969 /*
970 * response from old query, ignore it.
971 * XXX - potential security hazard could
972 * be detected here.
973 */
974 DprintQ((statp->options & RES_DEBUG) ||
975 (statp->pfcode & RES_PRF_REPLY),
976 (stdout, ";; old answer:\n"),
977 ans, (resplen > anssiz) ? anssiz : resplen);
978 goto wait;
979 }
980 if (!(statp->options & RES_INSECURE1) &&
981 !res_ourserver_p(statp, (struct sockaddr *)(void *)&from)) {
982 /*
983 * response from wrong server? ignore it.
984 * XXX - potential security hazard could
985 * be detected here.
986 */
987 DprintQ((statp->options & RES_DEBUG) ||
988 (statp->pfcode & RES_PRF_REPLY),
989 (stdout, ";; not our server:\n"),
990 ans, (resplen > anssiz) ? anssiz : resplen);
991 goto wait;
992 }
993#ifdef RES_USE_EDNS0
994 if (anhp->rcode == FORMERR && (statp->options & RES_USE_EDNS0) != 0U) {
995 /*
996 * Do not retry if the server do not understand EDNS0.
997 * The case has to be captured here, as FORMERR packet do not
998 * carry query section, hence res_queriesmatch() returns 0.
999 */
1000 DprintQ(statp->options & RES_DEBUG,
1001 (stdout, "server rejected query with EDNS0:\n"),
1002 ans, (resplen > anssiz) ? anssiz : resplen);
1003 /* record the error */
1004 statp->_flags |= RES_F_EDNS0ERR;
1005 res_nclose(statp);
1006 return (0);
1007 }
1008#endif
1009 if (!(statp->options & RES_INSECURE2) &&
1010 !res_queriesmatch(buf, buf + buflen,
1011 ans, ans + anssiz)) {
1012 /*
1013 * response contains wrong query? ignore it.
1014 * XXX - potential security hazard could
1015 * be detected here.
1016 */
1017 DprintQ((statp->options & RES_DEBUG) ||
1018 (statp->pfcode & RES_PRF_REPLY),
1019 (stdout, ";; wrong query name:\n"),
1020 ans, (resplen > anssiz) ? anssiz : resplen);
1021 goto wait;
1022 }
1023 if (anhp->rcode == SERVFAIL ||
1024 anhp->rcode == NOTIMP ||
1025 anhp->rcode == REFUSED) {
1026 DprintQ(statp->options & RES_DEBUG,
1027 (stdout, "server rejected query:\n"),
1028 ans, (resplen > anssiz) ? anssiz : resplen);
1029 res_nclose(statp);
1030 /* don't retry if called from dig */
1031 if (!statp->pfcode)
1032 return (0);
1033 }
1034 if (!(statp->options & RES_IGNTC) && anhp->tc) {
1035 /*
1036 * To get the rest of answer,
1037 * use TCP with same server.
1038 */
1039 Dprint(statp->options & RES_DEBUG,
1040 (stdout, ";; truncated answer\n"));
1041 *v_circuit = 1;
1042 res_nclose(statp);
1043 return (1);
1044 }
1045 /*
1046 * All is well, or the error is fatal. Signal that the
1047 * next nameserver ought not be tried.
1048 */
1049 return (resplen);
1050}
1051
1052static void
1053Aerror(const res_state statp, FILE *file, const char *string, int error,
1054 const struct sockaddr *address, int alen)
1055{
1056 int save = errno;
1057 char hbuf[NI_MAXHOST];
1058 char sbuf[NI_MAXSERV];
1059
1060 alen = alen;
1061
1062 if ((statp->options & RES_DEBUG) != 0U) {
1063 if (getnameinfo(address, (socklen_t)alen, hbuf, sizeof(hbuf),
1064 sbuf, sizeof(sbuf), niflags)) {
1065 strncpy(hbuf, "?", sizeof(hbuf) - 1);
1066 hbuf[sizeof(hbuf) - 1] = '\0';
1067 strncpy(sbuf, "?", sizeof(sbuf) - 1);
1068 sbuf[sizeof(sbuf) - 1] = '\0';
1069 }
1070 fprintf(file, "res_send: %s ([%s].%s): %s\n",
1071 string, hbuf, sbuf, strerror(error));
1072 }
1073 errno = save;
1074}
1075
1076static void
1077Perror(const res_state statp, FILE *file, const char *string, int error) {
1078 int save = errno;
1079
1080 if ((statp->options & RES_DEBUG) != 0U)
1081 fprintf(file, "res_send: %s: %s\n",
1082 string, strerror(error));
1083 errno = save;
1084}
1085
1086static int
1087sock_eq(struct sockaddr *a, struct sockaddr *b) {
1088 struct sockaddr_in *a4, *b4;
1089 struct sockaddr_in6 *a6, *b6;
1090
1091 if (a->sa_family != b->sa_family)
1092 return 0;
1093 switch (a->sa_family) {
1094 case AF_INET:
1095 a4 = (struct sockaddr_in *)(void *)a;
1096 b4 = (struct sockaddr_in *)(void *)b;
1097 return a4->sin_port == b4->sin_port &&
1098 a4->sin_addr.s_addr == b4->sin_addr.s_addr;
1099 case AF_INET6:
1100 a6 = (struct sockaddr_in6 *)(void *)a;
1101 b6 = (struct sockaddr_in6 *)(void *)b;
1102 return a6->sin6_port == b6->sin6_port &&
1103#ifdef HAVE_SIN6_SCOPE_ID
1104 a6->sin6_scope_id == b6->sin6_scope_id &&
1105#endif
1106 IN6_ARE_ADDR_EQUAL(&a6->sin6_addr, &b6->sin6_addr);
1107 default:
1108 return 0;
1109 }
1110}
1111
1112#ifdef NEED_PSELECT
1113/* XXX needs to move to the porting library. */
1114static int
1115pselect(int nfds, void *rfds, void *wfds, void *efds,
1116 struct timespec *tsp, const sigset_t *sigmask)
1117{
1118 struct timeval tv, *tvp;
1119 sigset_t sigs;
1120 int n;
1121
1122 if (tsp) {
1123 tvp = &tv;
1124 tv = evTimeVal(*tsp);
1125 } else
1126 tvp = NULL;
1127 if (sigmask)
1128 sigprocmask(SIG_SETMASK, sigmask, &sigs);
1129 n = select(nfds, rfds, wfds, efds, tvp);
1130 if (sigmask)
1131 sigprocmask(SIG_SETMASK, &sigs, NULL);
1132 if (tsp)
1133 *tsp = evTimeSpec(tv);
1134 return (n);
1135}
1136#endif