Update
[glibc.git] / resolv / res_send.c
blobd3dc2ba8e1ce30f56b0935eeb3e589c3de9532b4
1 /*
2 * Copyright (c) 1985, 1989, 1993
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 4. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
31 * Portions Copyright (c) 1993 by Digital Equipment Corporation.
33 * Permission to use, copy, modify, and distribute this software for any
34 * purpose with or without fee is hereby granted, provided that the above
35 * copyright notice and this permission notice appear in all copies, and that
36 * the name of Digital Equipment Corporation not be used in advertising or
37 * publicity pertaining to distribution of the document or software without
38 * specific, written prior permission.
40 * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
41 * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
42 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
43 * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
44 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
45 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
46 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
47 * SOFTWARE.
51 * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
53 * Permission to use, copy, modify, and distribute this software for any
54 * purpose with or without fee is hereby granted, provided that the above
55 * copyright notice and this permission notice appear in all copies.
57 * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
58 * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
59 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
60 * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
61 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
62 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
63 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
64 * SOFTWARE.
67 #if defined(LIBC_SCCS) && !defined(lint)
68 static const char sccsid[] = "@(#)res_send.c 8.1 (Berkeley) 6/4/93";
69 static const char rcsid[] = "$Id$";
70 #endif /* LIBC_SCCS and not lint */
73 * Send query to name server and wait for reply.
76 #include <sys/types.h>
77 #include <sys/param.h>
78 #include <sys/time.h>
79 #include <sys/socket.h>
80 #include <sys/uio.h>
82 #include <netinet/in.h>
83 #include <arpa/nameser.h>
84 #include <arpa/inet.h>
86 #include <errno.h>
87 #include <netdb.h>
88 #include <resolv.h>
89 #include <signal.h>
90 #include <stdio.h>
91 #include <stdlib.h>
92 #include <string.h>
93 #include <unistd.h>
95 #include <sys/poll.h>
97 /* Options. Leave them on. */
98 /* #undef DEBUG */
99 #include "res_debug.h"
101 #ifdef NEED_PSELECT
102 static int pselect(int, void *, void *, void *,
103 struct timespec *,
104 const sigset_t *);
105 #endif
107 #define CHECK_SRVR_ADDR
109 /* From bind lib/isc/ev_timers.c: */
110 #define BILLION 1000000000
111 static struct timespec
112 evTimeSpec(struct timeval tv) {
113 struct timespec ts;
115 ts.tv_sec = tv.tv_sec;
116 ts.tv_nsec = tv.tv_usec * 1000;
117 return (ts);
120 static struct timespec
121 evConsTime(time_t sec, long nsec) {
122 struct timespec x;
124 x.tv_sec = sec;
125 x.tv_nsec = nsec;
126 return (x);
129 static struct timespec
130 evAddTime(struct timespec addend1, struct timespec addend2) {
131 struct timespec x;
133 x.tv_sec = addend1.tv_sec + addend2.tv_sec;
134 x.tv_nsec = addend1.tv_nsec + addend2.tv_nsec;
135 if (x.tv_nsec >= BILLION) {
136 x.tv_sec++;
137 x.tv_nsec -= BILLION;
139 return (x);
142 static struct timespec
143 evSubTime(struct timespec minuend, struct timespec subtrahend) {
144 struct timespec x;
146 x.tv_sec = minuend.tv_sec - subtrahend.tv_sec;
147 if (minuend.tv_nsec >= subtrahend.tv_nsec)
148 x.tv_nsec = minuend.tv_nsec - subtrahend.tv_nsec;
149 else {
150 x.tv_nsec = BILLION - subtrahend.tv_nsec + minuend.tv_nsec;
151 x.tv_sec--;
153 return (x);
156 static int
157 evCmpTime(struct timespec a, struct timespec b) {
158 long x = a.tv_sec - b.tv_sec;
160 if (x == 0L)
161 x = a.tv_nsec - b.tv_nsec;
162 return (x < 0L ? (-1) : x > 0L ? (1) : (0));
165 static struct timespec
166 evNowTime() {
167 struct timeval now;
169 if (gettimeofday(&now, NULL) < 0)
170 return (evConsTime(0, 0));
171 return (evTimeSpec(now));
173 /* End of code from bind lib/isc/ev_timers.c. */
175 #ifdef DEBUG
176 static void
177 Aerror(const res_state statp, FILE *file, const char *string, int error,
178 struct sockaddr_in address)
180 int save = errno;
182 if ((statp->options & RES_DEBUG) != 0) {
183 char tmp[sizeof "255.255.255.255"];
185 fprintf(file, "res_send: %s ([%s].%u): %s\n",
186 string,
187 inet_ntop(address.sin_family, &address.sin_addr,
188 tmp, sizeof tmp),
189 ntohs(address.sin_port),
190 strerror(error));
192 __set_errno (save);
194 static void
195 Perror(const res_state statp, FILE *file, const char *string, int error) {
196 int save = errno;
198 if ((statp->options & RES_DEBUG) != 0)
199 fprintf(file, "res_send: %s: %s\n",
200 string, strerror(error));
201 __set_errno (save);
203 #endif
205 static int cmpsock(struct sockaddr_in *a1, struct sockaddr_in *a2);
206 void res_pquery(const res_state, const u_char *, int, FILE *);
208 /* int
209 * res_isourserver(ina)
210 * looks up "ina" in _res.ns_addr_list[]
211 * returns:
212 * 0 : not found
213 * >0 : found
214 * author:
215 * paul vixie, 29may94
218 res_ourserver_p(const res_state statp, const struct sockaddr_in *inp) {
219 struct sockaddr_in ina;
220 int ns;
222 ina = *inp;
223 for (ns = 0; ns < statp->nscount; ns++) {
224 const struct sockaddr_in *srv = &statp->nsaddr_list[ns];
226 if (srv->sin_family == ina.sin_family &&
227 srv->sin_port == ina.sin_port &&
228 (srv->sin_addr.s_addr == INADDR_ANY ||
229 srv->sin_addr.s_addr == ina.sin_addr.s_addr))
230 return (1);
232 return (0);
235 /* int
236 * res_nameinquery(name, type, class, buf, eom)
237 * look for (name,type,class) in the query section of packet (buf,eom)
238 * requires:
239 * buf + HFIXEDSZ <= eom
240 * returns:
241 * -1 : format error
242 * 0 : not found
243 * >0 : found
244 * author:
245 * paul vixie, 29may94
248 res_nameinquery(const char *name, int type, int class,
249 const u_char *buf, const u_char *eom)
251 const u_char *cp = buf + HFIXEDSZ;
252 int qdcount = ntohs(((HEADER*)buf)->qdcount);
254 while (qdcount-- > 0) {
255 char tname[MAXDNAME+1];
256 int n, ttype, tclass;
258 n = dn_expand(buf, eom, cp, tname, sizeof tname);
259 if (n < 0)
260 return (-1);
261 cp += n;
262 if (cp + 2 * INT16SZ > eom)
263 return (-1);
264 ttype = ns_get16(cp); cp += INT16SZ;
265 tclass = ns_get16(cp); cp += INT16SZ;
266 if (ttype == type && tclass == class &&
267 ns_samename(tname, name) == 1)
268 return (1);
270 return (0);
273 /* int
274 * res_queriesmatch(buf1, eom1, buf2, eom2)
275 * is there a 1:1 mapping of (name,type,class)
276 * in (buf1,eom1) and (buf2,eom2)?
277 * returns:
278 * -1 : format error
279 * 0 : not a 1:1 mapping
280 * >0 : is a 1:1 mapping
281 * author:
282 * paul vixie, 29may94
285 res_queriesmatch(const u_char *buf1, const u_char *eom1,
286 const u_char *buf2, const u_char *eom2)
288 const u_char *cp = buf1 + HFIXEDSZ;
289 int qdcount = ntohs(((HEADER*)buf1)->qdcount);
291 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2)
292 return (-1);
295 * Only header section present in replies to
296 * dynamic update packets.
298 if ( (((HEADER *)buf1)->opcode == ns_o_update) &&
299 (((HEADER *)buf2)->opcode == ns_o_update) )
300 return (1);
302 if (qdcount != ntohs(((HEADER*)buf2)->qdcount))
303 return (0);
304 while (qdcount-- > 0) {
305 char tname[MAXDNAME+1];
306 int n, ttype, tclass;
308 n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
309 if (n < 0)
310 return (-1);
311 cp += n;
312 if (cp + 2 * INT16SZ > eom1)
313 return (-1);
314 ttype = ns_get16(cp); cp += INT16SZ;
315 tclass = ns_get16(cp); cp += INT16SZ;
316 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2))
317 return (0);
319 return (1);
323 res_nsend(res_state statp,
324 const u_char *buf, int buflen, u_char *ans, int anssiz)
326 HEADER *hp = (HEADER *) buf;
327 HEADER *anhp = (HEADER *) ans;
328 int gotsomewhere, connreset, terrno, try, v_circuit, resplen, ns, n;
329 u_int badns; /* XXX NSMAX can't exceed #/bits in this variable */
330 static int highestFD = FD_SETSIZE - 1;
332 if (anssiz < HFIXEDSZ) {
333 __set_errno (EINVAL);
334 return (-1);
336 DprintQ((statp->options & RES_DEBUG) || (statp->pfcode & RES_PRF_QUERY),
337 (stdout, ";; res_send()\n"), buf, buflen);
338 v_circuit = (statp->options & RES_USEVC) || buflen > PACKETSZ;
339 gotsomewhere = 0;
340 connreset = 0;
341 terrno = ETIMEDOUT;
342 badns = 0;
345 * Some callers want to even out the load on their resolver list.
347 if (statp->nscount > 0 && (statp->options & RES_ROTATE) != 0) {
348 struct sockaddr_in ina;
349 int lastns = statp->nscount - 1;
351 ina = statp->nsaddr_list[0];
352 for (ns = 0; ns < lastns; ns++)
353 statp->nsaddr_list[ns] = statp->nsaddr_list[ns + 1];
354 statp->nsaddr_list[lastns] = ina;
358 * Send request, RETRY times, or until successful
360 for (try = 0; try < statp->retry; try++) {
361 for (ns = 0; ns < statp->nscount; ns++) {
362 struct sockaddr_in *nsap = &statp->nsaddr_list[ns];
363 same_ns:
364 if (badns & (1 << ns)) {
365 res_nclose(statp);
366 goto next_ns;
369 if (statp->qhook) {
370 int done = 0, loops = 0;
372 do {
373 res_sendhookact act;
375 act = (*statp->qhook)(&nsap, &buf, &buflen,
376 ans, anssiz, &resplen);
377 switch (act) {
378 case res_goahead:
379 done = 1;
380 break;
381 case res_nextns:
382 res_nclose(statp);
383 goto next_ns;
384 case res_done:
385 return (resplen);
386 case res_modified:
387 /* give the hook another try */
388 if (++loops < 42) /*doug adams*/
389 break;
390 /*FALLTHROUGH*/
391 case res_error:
392 /*FALLTHROUGH*/
393 default:
394 return (-1);
396 } while (!done);
399 Dprint(statp->options & RES_DEBUG,
400 (stdout, ";; Querying server (# %d) address = %s\n",
401 ns + 1, inet_ntoa(nsap->sin_addr)));
403 if (v_circuit) {
404 int truncated;
405 struct iovec iov[2];
406 u_short len;
407 u_char *cp;
409 /* Use VC; at most one attempt per server. */
410 try = statp->retry;
411 truncated = 0;
413 /* Are we still talking to whom we want to talk to? */
414 if (statp->_sock >= 0 &&
415 (statp->_flags & RES_F_VC) != 0) {
416 struct sockaddr_in peer;
417 int size = sizeof(peer);
419 if (getpeername(statp->_sock,
420 (struct sockaddr *)&peer,
421 &size) < 0) {
422 res_nclose(statp);
423 statp->_flags &= ~RES_F_VC;
424 } else if (!cmpsock(&peer, nsap)) {
425 res_nclose(statp);
426 statp->_flags &= ~RES_F_VC;
430 if (statp->_sock < 0 ||
431 (statp->_flags & RES_F_VC) == 0) {
432 if (statp->_sock >= 0)
433 res_nclose(statp);
435 statp->_sock = socket(PF_INET,
436 SOCK_STREAM, 0);
437 if (statp->_sock < 0 ||
438 statp->_sock > highestFD) {
439 terrno = errno;
440 Perror(statp, stderr,
441 "socket(vc)", errno);
442 return (-1);
444 __set_errno (0);
445 if (connect(statp->_sock,
446 (struct sockaddr *)nsap,
447 sizeof *nsap) < 0) {
448 terrno = errno;
449 Aerror(statp, stderr, "connect/vc",
450 errno, *nsap);
451 badns |= (1 << ns);
452 res_nclose(statp);
453 goto next_ns;
455 statp->_flags |= RES_F_VC;
458 * Send length & message
460 putshort((u_short)buflen, (u_char*)&len);
461 iov[0].iov_base = (caddr_t)&len;
462 iov[0].iov_len = INT16SZ;
463 iov[1].iov_base = (caddr_t)buf;
464 iov[1].iov_len = buflen;
465 if (writev(statp->_sock, iov, 2) !=
466 (INT16SZ + buflen)) {
467 terrno = errno;
468 Perror(statp, stderr, "write failed", errno);
469 badns |= (1 << ns);
470 res_nclose(statp);
471 goto next_ns;
474 * Receive length & response
476 read_len:
477 cp = ans;
478 len = INT16SZ;
479 while ((n = read(statp->_sock,
480 (char *)cp, (int)len)) > 0) {
481 cp += n;
482 if ((len -= n) <= 0)
483 break;
485 if (n <= 0) {
486 terrno = errno;
487 Perror(statp, stderr, "read failed", errno);
488 res_nclose(statp);
490 * A long running process might get its TCP
491 * connection reset if the remote server was
492 * restarted. Requery the server instead of
493 * trying a new one. When there is only one
494 * server, this means that a query might work
495 * instead of failing. We only allow one reset
496 * per query to prevent looping.
498 if (terrno == ECONNRESET && !connreset) {
499 connreset = 1;
500 res_nclose(statp);
501 goto same_ns;
503 res_nclose(statp);
504 goto next_ns;
506 resplen = ns_get16(ans);
507 if (resplen > anssiz) {
508 Dprint(statp->options & RES_DEBUG,
509 (stdout, ";; response truncated\n")
511 truncated = 1;
512 len = anssiz;
513 } else
514 len = resplen;
515 if (len < HFIXEDSZ) {
517 * Undersized message.
519 Dprint(statp->options & RES_DEBUG,
520 (stdout, ";; undersized: %d\n", len));
521 terrno = EMSGSIZE;
522 badns |= (1 << ns);
523 res_nclose(statp);
524 goto next_ns;
526 cp = ans;
527 while (len != 0 &&
528 (n = read(statp->_sock, (char *)cp, (int)len))
529 > 0) {
530 cp += n;
531 len -= n;
533 if (n <= 0) {
534 terrno = errno;
535 Perror(statp, stderr, "read(vc)", errno);
536 res_nclose(statp);
537 goto next_ns;
539 if (truncated) {
541 * Flush rest of answer
542 * so connection stays in synch.
544 anhp->tc = 1;
545 len = resplen - anssiz;
546 while (len != 0) {
547 char junk[PACKETSZ];
549 n = ((size_t)len > sizeof(junk)
550 ? sizeof(junk)
551 : len);
552 n = read(statp->_sock, junk, n);
553 if (n > 0)
554 len -= n;
555 else
556 break;
560 * The calling applicating has bailed out of
561 * a previous call and failed to arrange to have
562 * the circuit closed or the server has got
563 * itself confused. Anyway drop the packet and
564 * wait for the correct one.
566 if (hp->id != anhp->id) {
567 DprintQ((statp->options & RES_DEBUG) ||
568 (statp->pfcode & RES_PRF_REPLY),
569 (stdout, ";; old answer (unexpected):\n"),
570 ans, (resplen>anssiz)?anssiz:resplen);
571 goto read_len;
573 } else {
575 * Use datagrams.
577 struct timespec start, timeout, finish;
578 #ifdef _LIBC
579 struct pollfd pfd[1];
580 int ptimeout;
581 #else
582 fd_set dsmask;
583 #endif
584 struct sockaddr_in from;
585 int fromlen, seconds;
587 if (statp->_sock < 0 ||
588 (statp->_flags & RES_F_VC) != 0) {
589 if ((statp->_flags & RES_F_VC) != 0)
590 res_nclose(statp);
591 statp->_sock = socket(PF_INET, SOCK_DGRAM, 0);
592 if (statp->_sock < 0 ||
593 statp->_sock > highestFD) {
594 #ifndef CAN_RECONNECT
595 bad_dg_sock:
596 #endif
597 terrno = errno;
598 Perror(statp, stderr,
599 "socket(dg)", errno);
600 return (-1);
602 statp->_flags &= ~RES_F_CONN;
604 #ifndef CANNOT_CONNECT_DGRAM
606 * On a 4.3BSD+ machine (client and server,
607 * actually), sending to a nameserver datagram
608 * port with no nameserver will cause an
609 * ICMP port unreachable message to be returned.
610 * If our datagram socket is "connected" to the
611 * server, we get an ECONNREFUSED error on the next
612 * socket operation, and select returns if the
613 * error message is received. We can thus detect
614 * the absence of a nameserver without timing out.
615 * If we have sent queries to at least two servers,
616 * however, we don't want to remain connected,
617 * as we wish to receive answers from the first
618 * server to respond.
620 if (statp->nscount == 1 || (try == 0 && ns == 0)) {
622 * Connect only if we are sure we won't
623 * receive a response from another server.
625 if ((statp->_flags & RES_F_CONN) == 0) {
626 if (connect(statp->_sock,
627 (struct sockaddr *)nsap,
628 sizeof *nsap) < 0) {
629 Aerror(statp, stderr,
630 "connect(dg)",
631 errno, *nsap);
632 badns |= (1 << ns);
633 res_nclose(statp);
634 goto next_ns;
636 statp->_flags |= RES_F_CONN;
638 if (send(statp->_sock, (char*)buf, buflen, 0)
639 != buflen) {
640 Perror(statp, stderr, "send", errno);
641 badns |= (1 << ns);
642 res_nclose(statp);
643 goto next_ns;
645 } else {
647 * Disconnect if we want to listen
648 * for responses from more than one server.
650 if ((statp->_flags & RES_F_CONN) != 0) {
651 #ifdef CAN_RECONNECT
652 struct sockaddr_in no_addr;
654 no_addr.sin_family = AF_INET;
655 no_addr.sin_addr.s_addr = INADDR_ANY;
656 no_addr.sin_port = 0;
657 (void) connect(statp->_sock,
658 (struct sockaddr *)
659 &no_addr,
660 sizeof no_addr);
661 #else
662 struct sockaddr_in local_addr;
663 int len, result, s1;
665 len = sizeof(local_addr);
666 s1 = socket(PF_INET, SOCK_DGRAM, 0);
667 result = getsockname(statp->_sock,
668 (struct sockaddr *)&local_addr,
669 &len);
670 if (s1 < 0)
671 goto bad_dg_sock;
672 (void) dup2(s1, statp->_sock);
673 (void) close(s1);
674 if (result == 0) {
676 * Attempt to rebind to old
677 * port. Note connected socket
678 * has an sin_addr set.
680 local_addr.sin_addr.s_addr =
681 htonl(0);
682 (void)bind(statp->_sock,
683 (struct sockaddr *)
684 &local_addr, len);
686 Dprint(statp->options & RES_DEBUG,
687 (stdout, ";; new DG socket\n"))
688 #endif /* CAN_RECONNECT */
689 statp->_flags &= ~RES_F_CONN;
690 __set_errno (0);
692 #endif /* !CANNOT_CONNECT_DGRAM */
693 if (sendto(statp->_sock,
694 (char*)buf, buflen, 0,
695 (struct sockaddr *)nsap,
696 sizeof *nsap)
697 != buflen) {
698 Aerror(statp, stderr, "sendto", errno, *nsap);
699 badns |= (1 << ns);
700 res_nclose(statp);
701 goto next_ns;
703 #ifndef CANNOT_CONNECT_DGRAM
705 #endif /* !CANNOT_CONNECT_DGRAM */
707 if (statp->_sock < 0 || statp->_sock > highestFD) {
708 Perror(statp, stderr,
709 "fd out-of-bounds", EMFILE);
710 res_nclose(statp);
711 goto next_ns;
715 * Wait for reply
717 seconds = (statp->retrans << try);
718 if (try > 0)
719 seconds /= statp->nscount;
720 if (seconds <= 0)
721 seconds = 1;
723 start = evNowTime();
724 timeout = evConsTime(seconds, 0);
725 finish = evAddTime(start, timeout);
726 wait:
727 #ifdef _LIBC
728 /* Convert struct timespec in milliseconds. */
729 ptimeout = timeout.tv_sec * 1000
730 + timeout.tv_nsec / 1000000;
732 pfd[0].fd = statp->_sock;
733 pfd[0].events = POLLIN;
734 n = __poll (pfd, 1, ptimeout);
735 #else
736 FD_ZERO(&dsmask);
737 FD_SET(statp->_sock, &dsmask);
738 n = pselect(statp->_sock + 1,
739 &dsmask, NULL, NULL,
740 &timeout, NULL);
741 #endif
742 if (n == 0) {
743 Dprint(statp->options & RES_DEBUG,
744 (stdout, ";; timeout\n"));
745 gotsomewhere = 1;
746 goto next_ns;
748 if (n < 0) {
749 if (errno == EINTR) {
750 struct timespec now;
752 now = evNowTime();
753 if (evCmpTime(finish, now) >= 0) {
754 timeout = evSubTime(finish,
755 now);
756 goto wait;
759 #ifdef _LIBC
760 Perror(statp, stderr, "poll", errno);
761 #else
762 Perror(statp, stderr, "select", errno);
763 #endif
764 res_nclose(statp);
765 goto next_ns;
767 __set_errno (0);
768 fromlen = sizeof(struct sockaddr_in);
769 resplen = recvfrom(statp->_sock, (char*)ans, anssiz,0,
770 (struct sockaddr *)&from, &fromlen);
771 if (resplen <= 0) {
772 Perror(statp, stderr, "recvfrom", errno);
773 res_nclose(statp);
774 goto next_ns;
776 gotsomewhere = 1;
777 if (resplen < HFIXEDSZ) {
779 * Undersized message.
781 Dprint(statp->options & RES_DEBUG,
782 (stdout, ";; undersized: %d\n",
783 resplen));
784 terrno = EMSGSIZE;
785 badns |= (1 << ns);
786 res_nclose(statp);
787 goto next_ns;
789 if (hp->id != anhp->id) {
791 * response from old query, ignore it.
792 * XXX - potential security hazard could
793 * be detected here.
795 DprintQ((statp->options & RES_DEBUG) ||
796 (statp->pfcode & RES_PRF_REPLY),
797 (stdout, ";; old answer:\n"),
798 ans, (resplen>anssiz)?anssiz:resplen);
799 goto wait;
801 #ifdef CHECK_SRVR_ADDR
802 if (!(statp->options & RES_INSECURE1) &&
803 !res_ourserver_p(statp, &from)) {
805 * response from wrong server? ignore it.
806 * XXX - potential security hazard could
807 * be detected here.
809 DprintQ((statp->options & RES_DEBUG) ||
810 (statp->pfcode & RES_PRF_REPLY),
811 (stdout, ";; not our server:\n"),
812 ans, (resplen>anssiz)?anssiz:resplen);
813 goto wait;
815 #endif
816 if (!(statp->options & RES_INSECURE2) &&
817 !res_queriesmatch(buf, buf + buflen,
818 ans, ans + anssiz)) {
820 * response contains wrong query? ignore it.
821 * XXX - potential security hazard could
822 * be detected here.
824 DprintQ((statp->options & RES_DEBUG) ||
825 (statp->pfcode & RES_PRF_REPLY),
826 (stdout, ";; wrong query name:\n"),
827 ans, (resplen>anssiz)?anssiz:resplen);
828 goto wait;
830 if (anhp->rcode == SERVFAIL ||
831 anhp->rcode == NOTIMP ||
832 anhp->rcode == REFUSED) {
833 DprintQ(statp->options & RES_DEBUG,
834 (stdout, "server rejected query:\n"),
835 ans, (resplen>anssiz)?anssiz:resplen);
836 badns |= (1 << ns);
837 res_nclose(statp);
838 /* don't retry if called from dig */
839 if (!statp->pfcode)
840 goto next_ns;
842 if (!(statp->options & RES_IGNTC) && anhp->tc) {
844 * get rest of answer;
845 * use TCP with same server.
847 Dprint(statp->options & RES_DEBUG,
848 (stdout, ";; truncated answer\n"));
849 v_circuit = 1;
850 res_nclose(statp);
851 goto same_ns;
853 } /*if vc/dg*/
854 Dprint((statp->options & RES_DEBUG) ||
855 ((statp->pfcode & RES_PRF_REPLY) &&
856 (statp->pfcode & RES_PRF_HEAD1)),
857 (stdout, ";; got answer:\n"));
858 DprintQ((statp->options & RES_DEBUG) ||
859 (statp->pfcode & RES_PRF_REPLY),
860 (stdout, ""),
861 ans, (resplen>anssiz)?anssiz:resplen);
863 * If using virtual circuits, we assume that the first server
864 * is preferred over the rest (i.e. it is on the local
865 * machine) and only keep that one open.
866 * If we have temporarily opened a virtual circuit,
867 * or if we haven't been asked to keep a socket open,
868 * close the socket.
870 if ((v_circuit && (!(statp->options & RES_USEVC) || ns != 0)) ||
871 !(statp->options & RES_STAYOPEN)) {
872 res_nclose(statp);
874 if (statp->rhook) {
875 int done = 0, loops = 0;
877 do {
878 res_sendhookact act;
880 act = (*statp->rhook)(nsap, buf, buflen,
881 ans, anssiz, &resplen);
882 switch (act) {
883 case res_goahead:
884 case res_done:
885 done = 1;
886 break;
887 case res_nextns:
888 res_nclose(statp);
889 goto next_ns;
890 case res_modified:
891 /* give the hook another try */
892 if (++loops < 42) /*doug adams*/
893 break;
894 /*FALLTHROUGH*/
895 case res_error:
896 /*FALLTHROUGH*/
897 default:
898 return (-1);
900 } while (!done);
903 return (resplen);
904 next_ns: ;
905 } /*foreach ns*/
906 } /*foreach retry*/
907 res_nclose(statp);
908 if (!v_circuit) {
909 if (!gotsomewhere)
910 __set_errno (ECONNREFUSED); /* no nameservers found */
911 else
912 __set_errno (ETIMEDOUT); /* no answer obtained */
913 } else
914 __set_errno (terrno);
915 return (-1);
919 * This routine is for closing the socket if a virtual circuit is used and
920 * the program wants to close it. This provides support for endhostent()
921 * which expects to close the socket.
923 * This routine is not expected to be user visible.
925 void
926 res_nclose(res_state statp) {
927 if (statp->_sock >= 0) {
928 (void) close(statp->_sock);
929 statp->_sock = -1;
930 statp->_flags &= ~(RES_F_VC | RES_F_CONN);
934 /* Private */
935 static int
936 cmpsock(struct sockaddr_in *a1, struct sockaddr_in *a2) {
937 return ((a1->sin_family == a2->sin_family) &&
938 (a1->sin_port == a2->sin_port) &&
939 (a1->sin_addr.s_addr == a2->sin_addr.s_addr));
942 #ifdef NEED_PSELECT
943 /* XXX needs to move to the porting library. */
944 static int
945 pselect(int nfds, void *rfds, void *wfds, void *efds,
946 struct timespec *tsp,
947 const sigset_t *sigmask)
949 struct timeval tv, *tvp;
950 sigset_t sigs;
951 int n;
953 if (tsp) {
954 tvp = &tv;
955 tv = evTimeVal(*tsp);
956 } else
957 tvp = NULL;
958 if (sigmask)
959 sigprocmask(SIG_SETMASK, sigmask, &sigs);
960 n = select(nfds, rfds, wfds, efds, tvp);
961 if (sigmask)
962 sigprocmask(SIG_SETMASK, &sigs, NULL);
963 if (tsp)
964 *tsp = evTimeSpec(tv);
965 return (n);
967 #endif