]> git.proxmox.com Git - mirror_edk2.git/blob - StdLib/BsdSocketLib/res_send.c
Add Socket Libraries.
[mirror_edk2.git] / StdLib / BsdSocketLib / res_send.c
1 /*
2 * Copyright (c) 1985, 1989, 1993
3 * The Regents of the University of California. All rights reserved.
4 *
5 * Portions copyright (c) 1999, 2000
6 * Intel Corporation.
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 *
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 *
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 *
20 * 3. All advertising materials mentioning features or use of this software
21 * must display the following acknowledgement:
22 *
23 * This product includes software developed by the University of
24 * California, Berkeley, Intel Corporation, and its contributors.
25 *
26 * 4. Neither the name of University, Intel Corporation, or their respective
27 * contributors may be used to endorse or promote products derived from
28 * this software without specific prior written permission.
29 *
30 * THIS SOFTWARE IS PROVIDED BY THE REGENTS, INTEL CORPORATION AND
31 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
32 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
33 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS,
34 * INTEL CORPORATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
35 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
37 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
38 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
39 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
40 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
41 *
42 */
43
44 /*
45 * Portions Copyright (c) 1993 by Digital Equipment Corporation.
46 *
47 * Permission to use, copy, modify, and distribute this software for any
48 * purpose with or without fee is hereby granted, provided that the above
49 * copyright notice and this permission notice appear in all copies, and that
50 * the name of Digital Equipment Corporation not be used in advertising or
51 * publicity pertaining to distribution of the document or software without
52 * specific, written prior permission.
53 *
54 * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
55 * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
56 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
57 * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
58 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
59 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
60 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
61 * SOFTWARE.
62 */
63
64 /*
65 * Portions Copyright (c) 1996 by Internet Software Consortium.
66 *
67 * Permission to use, copy, modify, and distribute this software for any
68 * purpose with or without fee is hereby granted, provided that the above
69 * copyright notice and this permission notice appear in all copies.
70 *
71 * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
72 * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
73 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
74 * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
75 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
76 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
77 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
78 * SOFTWARE.
79 */
80
81 #if defined(LIBC_SCCS) && !defined(lint)
82 static char sccsid[] = "@(#)res_send.c 8.1 (Berkeley) 6/4/93";
83 static char orig_rcsid[] = "From: Id: res_send.c,v 8.20 1998/04/06 23:27:51 halley Exp $";
84 static char rcsid[] = "$Id: res_send.c,v 1.1.1.1 2003/11/19 01:51:39 kyu3 Exp $";
85 #endif /* LIBC_SCCS and not lint */
86
87 /*
88 * Send query to name server and wait for reply.
89 */
90
91 #include <sys/types.h>
92 #include <sys/param.h>
93 #include <sys/select.h>
94 #include <sys/socket.h>
95 #include <sys/time.h>
96 #include <sys/uio.h>
97
98 #include <netinet/in.h>
99 #include <arpa/nameser.h>
100 #include <arpa/inet.h>
101
102 #include <errno.h>
103 #include <netdb.h>
104 #include <resolv.h>
105 #include <stdio.h>
106 #include <stdlib.h>
107 #include <string.h>
108 #include <unistd.h>
109
110 #include "res_config.h"
111
112 #ifndef _ORG_FREEBSD_
113 #define NOPOLL
114 #endif
115
116 #ifdef NOPOLL /* libc_r doesn't wrap poll yet() */
117 static int use_poll = 0;
118 #else
119 #include <poll.h>
120 static int use_poll = 1; /* adapt to poll() syscall availability */
121 /* 0 = not present, 1 = try it, 2 = exists */
122 #endif
123
124 static int s = -1; /* socket used for communications */
125 static int connected = 0; /* is the socket connected */
126 static int vc = 0; /* is the socket a virtual circuit? */
127 static res_send_qhook Qhook = NULL;
128 static res_send_rhook Rhook = NULL;
129
130
131 #define CAN_RECONNECT 1
132
133 #ifndef DEBUG
134 # define Dprint(cond, args) /*empty*/
135 # define DprintQ(cond, args, query, size) /*empty*/
136 # define Aerror(file, string, error, address) /*empty*/
137 # define Perror(file, string, error) /*empty*/
138 #else
139 # define Dprint(cond, args) if (cond) {fprintf args;} else {}
140 # define DprintQ(cond, args, query, size) if (cond) {\
141 fprintf args;\
142 __fp_nquery(query, size, stdout);\
143 } else {}
144
145 static void
146 Aerror(
147 FILE *file,
148 char *string,
149 int error,
150 struct sockaddr_in address
151 )
152 {
153 int save = errno;
154
155 if (_res.options & RES_DEBUG) {
156 fprintf(file, "res_send: %s ([%s].%u): %s\n",
157 string,
158 inet_ntoa(address.sin_addr),
159 ntohs(address.sin_port),
160 strerror(error));
161 }
162 errno = save;
163 }
164
165
166 static void
167 Perror(
168 FILE *file,
169 char *string,
170 int error
171 )
172 {
173 int save = errno;
174
175 if (_res.options & RES_DEBUG) {
176 fprintf(file, "res_send: %s: %s\n",
177 string, strerror(error));
178 }
179 errno = save;
180 }
181 #endif
182
183 void
184 res_send_setqhook(
185 res_send_qhook hook
186 )
187 {
188
189 Qhook = hook;
190 }
191
192 void
193 res_send_setrhook(
194 res_send_rhook hook
195 )
196 {
197
198 Rhook = hook;
199 }
200
201 /* int
202 * res_isourserver(ina)
203 * looks up "ina" in _res.ns_addr_list[]
204 * returns:
205 * 0 : not found
206 * >0 : found
207 * author:
208 * paul vixie, 29may94
209 */
210 int
211 res_isourserver(
212 const struct sockaddr_in *inp
213 )
214 {
215 struct sockaddr_in ina;
216 int ns, ret;
217
218 ina = *inp;
219 ret = 0;
220 for (ns = 0; ns < _res.nscount; ns++) {
221 const struct sockaddr_in *srv = &_res.nsaddr_list[ns];
222
223 if (srv->sin_family == ina.sin_family &&
224 srv->sin_port == ina.sin_port &&
225 (srv->sin_addr.s_addr == INADDR_ANY ||
226 srv->sin_addr.s_addr == ina.sin_addr.s_addr)) {
227 ret++;
228 break;
229 }
230 }
231 return (ret);
232 }
233
234 /* int
235 * res_nameinquery(name, type, class, buf, eom)
236 * look for (name,type,class) in the query section of packet (buf,eom)
237 * requires:
238 * buf + HFIXEDSZ <= eom
239 * returns:
240 * -1 : format error
241 * 0 : not found
242 * >0 : found
243 * author:
244 * paul vixie, 29may94
245 */
246 int
247 res_nameinquery(
248 const char *name,
249 int type,
250 int class,
251 const u_char *buf,
252 const u_char *eom
253 )
254 {
255 const u_char *cp = buf + HFIXEDSZ;
256 int qdcount = ntohs(((HEADER*)buf)->qdcount);
257
258 while (qdcount-- > 0) {
259 char tname[MAXDNAME+1];
260 int n, ttype, tclass;
261
262 n = dn_expand(buf, eom, cp, tname, sizeof tname);
263 if (n < 0)
264 return (-1);
265 cp += n;
266 if (cp + 2 * INT16SZ > eom)
267 return (-1);
268 ttype = ns_get16(cp); cp += INT16SZ;
269 tclass = ns_get16(cp); cp += INT16SZ;
270 if (ttype == type &&
271 tclass == class &&
272 strcasecmp(tname, name) == 0)
273 return (1);
274 }
275 return (0);
276 }
277
278 /* int
279 * res_queriesmatch(buf1, eom1, buf2, eom2)
280 * is there a 1:1 mapping of (name,type,class)
281 * in (buf1,eom1) and (buf2,eom2)?
282 * returns:
283 * -1 : format error
284 * 0 : not a 1:1 mapping
285 * >0 : is a 1:1 mapping
286 * author:
287 * paul vixie, 29may94
288 */
289 int
290 res_queriesmatch(
291 const u_char *buf1,
292 const u_char *eom1,
293 const u_char *buf2,
294 const u_char *eom2
295 )
296 {
297 const u_char *cp = buf1 + HFIXEDSZ;
298 int qdcount = ntohs(((HEADER*)buf1)->qdcount);
299
300 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2)
301 return (-1);
302
303 /*
304 * Only header section present in replies to
305 * dynamic update packets.
306 */
307 if ( (((HEADER *)buf1)->opcode == ns_o_update) &&
308 (((HEADER *)buf2)->opcode == ns_o_update) )
309 return (1);
310
311 if (qdcount != ntohs(((HEADER*)buf2)->qdcount))
312 return (0);
313 while (qdcount-- > 0) {
314 char tname[MAXDNAME+1];
315 int n, ttype, tclass;
316
317 n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
318 if (n < 0)
319 return (-1);
320 cp += n;
321 if (cp + 2 * INT16SZ > eom1)
322 return (-1);
323 ttype = ns_get16(cp); cp += INT16SZ;
324 tclass = ns_get16(cp); cp += INT16SZ;
325 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2))
326 return (0);
327 }
328 return (1);
329 }
330
331 int
332 res_send(
333 const u_char *buf,
334 int buflen,
335 u_char *ans,
336 int anssiz
337 )
338 {
339 HEADER *hp = (HEADER *) buf;
340 HEADER *anhp = (HEADER *) ans;
341 int gotsomewhere, connreset, terrno, try, v_circuit, resplen, ns;
342 ssize_t n;
343 u_int32_t badns; /* XXX NSMAX can't exceed #/bits in this variable */
344
345 if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
346 /* errno should have been set by res_init() in this case. */
347 return (-1);
348 }
349 if (anssiz < HFIXEDSZ) {
350 errno = EINVAL;
351 return (-1);
352 }
353 DprintQ((_res.options & RES_DEBUG) || (_res.pfcode & RES_PRF_QUERY),
354 (stdout, ";; res_send()\n"), buf, buflen);
355 v_circuit = (_res.options & RES_USEVC) || buflen > PACKETSZ;
356 gotsomewhere = 0;
357 connreset = 0;
358 terrno = ETIMEDOUT;
359 badns = 0;
360
361 /*
362 * Send request, RETRY times, or until successful
363 */
364 for (try = 0; try < _res.retry; try++) {
365 for (ns = 0; ns < _res.nscount; ns++) {
366 struct sockaddr_in *nsap = &_res.nsaddr_list[ns];
367 same_ns:
368 if (badns & (1 << ns)) {
369 res_close();
370 goto next_ns;
371 }
372
373 if (Qhook) {
374 int done = 0, loops = 0;
375
376 do {
377 res_sendhookact act;
378
379 act = (*Qhook)(&nsap, &buf, &buflen,
380 ans, anssiz, &resplen);
381 switch (act) {
382 case res_goahead:
383 done = 1;
384 break;
385 case res_nextns:
386 res_close();
387 goto next_ns;
388 case res_done:
389 return (resplen);
390 case res_modified:
391 /* give the hook another try */
392 if (++loops < 42) /*doug adams*/
393 break;
394 /*FALLTHROUGH*/
395 case res_error:
396 /*FALLTHROUGH*/
397 default:
398 return (-1);
399 }
400 } while (!done);
401 }
402
403 Dprint(_res.options & RES_DEBUG,
404 (stdout, ";; Querying server (# %d) address = %s\n",
405 ns + 1, inet_ntoa(nsap->sin_addr)));
406
407 if (v_circuit) {
408 int truncated;
409 struct iovec iov[2];
410 u_short len;
411 u_char *cp;
412
413 /*
414 * Use virtual circuit;
415 * at most one attempt per server.
416 */
417 try = _res.retry;
418 truncated = 0;
419 if (s < 0 || !vc || hp->opcode == ns_o_update) {
420 if (s >= 0)
421 res_close();
422
423 s = socket(PF_INET, SOCK_STREAM, 0);
424 if (s < 0) {
425 terrno = errno;
426 Perror(stderr, "socket(vc)", errno);
427 return (-1);
428 }
429 errno = 0;
430 nsap->sin_len = sizeof ( *nsap );
431 if (connect(s, (struct sockaddr *)nsap,
432 sizeof *nsap) < 0) {
433 terrno = errno;
434 Aerror(stderr, "connect/vc",
435 errno, *nsap);
436 badns |= (1 << ns);
437 res_close();
438 goto next_ns;
439 }
440 vc = 1;
441 }
442 /*
443 * Send length & message
444 */
445 putshort((u_short)buflen, (u_char*)&len);
446 iov[0].iov_base = (caddr_t)&len;
447 iov[0].iov_len = INT16SZ;
448 iov[1].iov_base = (caddr_t)buf;
449 iov[1].iov_len = buflen;
450 if (writev(s, iov, 2) != (INT16SZ + buflen)) {
451 terrno = errno;
452 Perror(stderr, "write failed", errno);
453 badns |= (1 << ns);
454 res_close();
455 goto next_ns;
456 }
457 /*
458 * Receive length & response
459 */
460 read_len:
461 cp = ans;
462 len = INT16SZ;
463 while ((n = read(s, (char *)cp, (int)len)) > 0) {
464 cp += n;
465 len = (u_short)( len - n );
466 if (len <= 0)
467 break;
468 }
469 if (n <= 0) {
470 terrno = errno;
471 Perror(stderr, "read failed", errno);
472 res_close();
473 /*
474 * A long running process might get its TCP
475 * connection reset if the remote server was
476 * restarted. Requery the server instead of
477 * trying a new one. When there is only one
478 * server, this means that a query might work
479 * instead of failing. We only allow one reset
480 * per query to prevent looping.
481 */
482 if (terrno == ECONNRESET && !connreset) {
483 connreset = 1;
484 res_close();
485 goto same_ns;
486 }
487 res_close();
488 goto next_ns;
489 }
490 resplen = ns_get16(ans);
491 if (resplen > anssiz) {
492 Dprint(_res.options & RES_DEBUG,
493 (stdout, ";; response truncated\n")
494 );
495 truncated = 1;
496 len = (ushort)anssiz;
497 } else
498 len = (ushort)resplen;
499 if (len < HFIXEDSZ) {
500 /*
501 * Undersized message.
502 */
503 Dprint(_res.options & RES_DEBUG,
504 (stdout, ";; undersized: %d\n", len));
505 terrno = EMSGSIZE;
506 badns |= (1 << ns);
507 res_close();
508 goto next_ns;
509 }
510 cp = ans;
511 while (len != 0 &&
512 (n = read(s, (char *)cp, (int)len)) > 0) {
513 cp += n;
514 len = (u_short)( len - n );
515 }
516 if (n <= 0) {
517 terrno = errno;
518 Perror(stderr, "read(vc)", errno);
519 res_close();
520 goto next_ns;
521 }
522 if (truncated) {
523 /*
524 * Flush rest of answer
525 * so connection stays in synch.
526 */
527 anhp->tc = 1;
528 len = (ushort)( resplen - anssiz );
529 while (len != 0) {
530 char junk[PACKETSZ];
531
532 n = (len > sizeof(junk)
533 ? sizeof(junk)
534 : len);
535 if ((n = read(s, junk, n)) > 0)
536 len = (u_short)( len - n );
537 else
538 break;
539 }
540 }
541 /*
542 * The calling applicating has bailed out of
543 * a previous call and failed to arrange to have
544 * the circuit closed or the server has got
545 * itself confused. Anyway drop the packet and
546 * wait for the correct one.
547 */
548 if (hp->id != anhp->id) {
549 DprintQ((_res.options & RES_DEBUG) ||
550 (_res.pfcode & RES_PRF_REPLY),
551 (stdout, ";; old answer (unexpected):\n"),
552 ans, (resplen>anssiz)?anssiz:resplen);
553 goto read_len;
554 }
555 } else {
556 /*
557 * Use datagrams.
558 */
559 #ifndef NOPOLL
560 struct pollfd pfd;
561 int msec;
562 #endif
563 struct timeval timeout;
564 fd_set dsmask, *dsmaskp;
565 int dsmasklen;
566 struct sockaddr_in from;
567 int fromlen;
568
569 if ((s < 0) || vc) {
570 if (vc)
571 res_close();
572 s = socket(PF_INET, SOCK_DGRAM, 0);
573 if (s < 0) {
574 #ifndef CAN_RECONNECT
575 bad_dg_sock:
576 #endif
577 terrno = errno;
578 Perror(stderr, "socket(dg)", errno);
579 return (-1);
580 }
581 connected = 0;
582 }
583 #ifndef CANNOT_CONNECT_DGRAM
584 /*
585 * On a 4.3BSD+ machine (client and server,
586 * actually), sending to a nameserver datagram
587 * port with no nameserver will cause an
588 * ICMP port unreachable message to be returned.
589 * If our datagram socket is "connected" to the
590 * server, we get an ECONNREFUSED error on the next
591 * socket operation, and select returns if the
592 * error message is received. We can thus detect
593 * the absence of a nameserver without timing out.
594 * If we have sent queries to at least two servers,
595 * however, we don't want to remain connected,
596 * as we wish to receive answers from the first
597 * server to respond.
598 */
599 if (_res.nscount == 1 || (try == 0 && ns == 0)) {
600 /*
601 * Connect only if we are sure we won't
602 * receive a response from another server.
603 */
604 if (!connected) {
605 nsap->sin_len = sizeof ( *nsap );
606 if (connect(s, (struct sockaddr *)nsap,
607 sizeof *nsap
608 ) < 0) {
609 Aerror(stderr,
610 "connect(dg)",
611 errno, *nsap);
612 badns |= (1 << ns);
613 res_close();
614 goto next_ns;
615 }
616 connected = 1;
617 }
618 if (send(s, (char*)buf, buflen, 0) != buflen) {
619 Perror(stderr, "send", errno);
620 badns |= (1 << ns);
621 res_close();
622 goto next_ns;
623 }
624 } else {
625 /*
626 * Disconnect if we want to listen
627 * for responses from more than one server.
628 */
629 if (connected) {
630 #ifdef CAN_RECONNECT
631 struct sockaddr_in no_addr;
632
633 no_addr.sin_family = AF_INET;
634 no_addr.sin_addr.s_addr = INADDR_ANY;
635 no_addr.sin_port = 0;
636 (void) connect(s,
637 (struct sockaddr *)
638 &no_addr,
639 sizeof no_addr);
640 #else
641 int s1 = socket(PF_INET, SOCK_DGRAM,0);
642 if (s1 < 0)
643 goto bad_dg_sock;
644 (void) dup2(s1, s);
645 (void) close(s1);
646 Dprint(_res.options & RES_DEBUG,
647 (stdout, ";; new DG socket\n"))
648 #endif /* CAN_RECONNECT */
649 connected = 0;
650 errno = 0;
651 }
652 #endif /* !CANNOT_CONNECT_DGRAM */
653 if (sendto(s, (char*)buf, buflen, 0,
654 (struct sockaddr *)nsap,
655 sizeof *nsap)
656 != buflen) {
657 Aerror(stderr, "sendto", errno, *nsap);
658 badns |= (1 << ns);
659 res_close();
660 goto next_ns;
661 }
662 #ifndef CANNOT_CONNECT_DGRAM
663 }
664 #endif /* !CANNOT_CONNECT_DGRAM */
665
666 /*
667 * Wait for reply
668 */
669 #ifndef NOPOLL
670 othersyscall:
671 if (use_poll) {
672 msec = (_res.retrans << try) * 1000;
673 if (try > 0)
674 msec /= _res.nscount;
675 if (msec <= 0)
676 msec = 1000;
677 } else {
678 #endif
679 timeout.tv_sec = (_res.retrans << try);
680 if (try > 0)
681 timeout.tv_sec /= _res.nscount;
682 if ((long) timeout.tv_sec <= 0)
683 timeout.tv_sec = 1;
684 timeout.tv_usec = 0;
685 #ifndef NOPOLL
686 }
687 #endif
688 wait:
689 if (s < 0) {
690 Perror(stderr, "s out-of-bounds", EMFILE);
691 res_close();
692 goto next_ns;
693 }
694 #ifndef NOPOLL
695 if (use_poll) {
696 struct sigaction sa, osa;
697 int sigsys_installed = 0;
698
699 pfd.fd = s;
700 pfd.events = POLLIN;
701 if (use_poll == 1) {
702 bzero(&sa, sizeof(sa));
703 sa.sa_handler = SIG_IGN;
704 if (sigaction(SIGSYS, &sa, &osa) >= 0)
705 sigsys_installed = 1;
706 }
707 n = poll(&pfd, 1, msec);
708 if (sigsys_installed == 1) {
709 int oerrno = errno;
710 sigaction(SIGSYS, &osa, NULL);
711 errno = oerrno;
712 }
713 /* XXX why does nosys() return EINVAL? */
714 if (n < 0 && (errno == ENOSYS ||
715 errno == EINVAL)) {
716 use_poll = 0;
717 goto othersyscall;
718 } else if (use_poll == 1)
719 use_poll = 2;
720 if (n < 0) {
721 if (errno == EINTR)
722 goto wait;
723 Perror(stderr, "poll", errno);
724 res_close();
725 goto next_ns;
726 }
727 } else {
728 #endif
729 dsmasklen = howmany(s + 1, NFDBITS) *
730 sizeof(fd_mask);
731 if (dsmasklen > sizeof(fd_set)) {
732 dsmaskp = (fd_set *)malloc(dsmasklen);
733 if (dsmaskp == NULL) {
734 res_close();
735 goto next_ns;
736 }
737 } else
738 dsmaskp = &dsmask;
739 /* only zero what we need */
740 memset((char *)dsmaskp, 0, dsmasklen);
741 FD_SET(s, dsmaskp);
742 n = select(s + 1, dsmaskp, (fd_set *)NULL,
743 (fd_set *)NULL, &timeout);
744 if (dsmaskp != &dsmask)
745 free(dsmaskp);
746 if (n < 0) {
747 if (errno == EINTR)
748 goto wait;
749 Perror(stderr, "select", errno);
750 res_close();
751 goto next_ns;
752 }
753 #ifndef NOPOLL
754 }
755 #endif
756
757 if (n == 0) {
758 /*
759 * timeout
760 */
761 Dprint(_res.options & RES_DEBUG,
762 (stdout, ";; timeout\n"));
763 gotsomewhere = 1;
764 res_close();
765 goto next_ns;
766 }
767 errno = 0;
768 fromlen = sizeof(struct sockaddr_in);
769 resplen = (int)recvfrom(s, (char*)ans, anssiz, 0,
770 (struct sockaddr *)&from, &fromlen);
771 if (resplen <= 0) {
772 Perror(stderr, "recvfrom", errno);
773 res_close();
774 goto next_ns;
775 }
776 gotsomewhere = 1;
777 if (resplen < HFIXEDSZ) {
778 /*
779 * Undersized message.
780 */
781 Dprint(_res.options & RES_DEBUG,
782 (stdout, ";; undersized: %d\n",
783 resplen));
784 terrno = EMSGSIZE;
785 badns |= (1 << ns);
786 res_close();
787 goto next_ns;
788 }
789 if (hp->id != anhp->id) {
790 /*
791 * response from old query, ignore it.
792 * XXX - potential security hazard could
793 * be detected here.
794 */
795 DprintQ((_res.options & RES_DEBUG) ||
796 (_res.pfcode & RES_PRF_REPLY),
797 (stdout, ";; old answer:\n"),
798 ans, (resplen>anssiz)?anssiz:resplen);
799 goto wait;
800 }
801 #ifdef CHECK_SRVR_ADDR
802 if (!(_res.options & RES_INSECURE1) &&
803 !res_isourserver(&from)) {
804 /*
805 * response from wrong server? ignore it.
806 * XXX - potential security hazard could
807 * be detected here.
808 */
809 DprintQ((_res.options & RES_DEBUG) ||
810 (_res.pfcode & RES_PRF_REPLY),
811 (stdout, ";; not our server:\n"),
812 ans, (resplen>anssiz)?anssiz:resplen);
813 goto wait;
814 }
815 #endif
816 if (!(_res.options & RES_INSECURE2) &&
817 !res_queriesmatch(buf, buf + buflen,
818 ans, ans + anssiz)) {
819 /*
820 * response contains wrong query? ignore it.
821 * XXX - potential security hazard could
822 * be detected here.
823 */
824 DprintQ((_res.options & RES_DEBUG) ||
825 (_res.pfcode & RES_PRF_REPLY),
826 (stdout, ";; wrong query name:\n"),
827 ans, (resplen>anssiz)?anssiz:resplen);
828 goto wait;
829 }
830 if (anhp->rcode == SERVFAIL ||
831 anhp->rcode == NOTIMP ||
832 anhp->rcode == REFUSED) {
833 DprintQ(_res.options & RES_DEBUG,
834 (stdout, "server rejected query:\n"),
835 ans, (resplen>anssiz)?anssiz:resplen);
836 badns |= (1 << ns);
837 res_close();
838 /* don't retry if called from dig */
839 if (!_res.pfcode)
840 goto next_ns;
841 }
842 if (!(_res.options & RES_IGNTC) && anhp->tc) {
843 /*
844 * get rest of answer;
845 * use TCP with same server.
846 */
847 Dprint(_res.options & RES_DEBUG,
848 (stdout, ";; truncated answer\n"));
849 v_circuit = 1;
850 res_close();
851 goto same_ns;
852 }
853 } /*if vc/dg*/
854 Dprint((_res.options & RES_DEBUG) ||
855 ((_res.pfcode & RES_PRF_REPLY) &&
856 (_res.pfcode & RES_PRF_HEAD1)),
857 (stdout, ";; got answer:\n"));
858 DprintQ((_res.options & RES_DEBUG) ||
859 (_res.pfcode & RES_PRF_REPLY),
860 (stdout, ""),
861 ans, (resplen>anssiz)?anssiz:resplen);
862 /*
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.
869 */
870 if ((v_circuit && (!(_res.options & RES_USEVC) || ns != 0)) ||
871 !(_res.options & RES_STAYOPEN)) {
872 res_close();
873 }
874 if (Rhook) {
875 int done = 0, loops = 0;
876
877 do {
878 res_sendhookact act;
879
880 act = (*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_close();
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);
899 }
900 } while (!done);
901
902 }
903 return (resplen);
904 next_ns: ;
905 } /*foreach ns*/
906 } /*foreach retry*/
907 res_close();
908 if (!v_circuit) {
909 if (!gotsomewhere)
910 errno = ECONNREFUSED; /* no nameservers found */
911 else
912 errno = ETIMEDOUT; /* no answer obtained */
913 } else
914 errno = terrno;
915 return (-1);
916 }
917
918 /*
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.
922 *
923 * This routine is not expected to be user visible.
924 */
925 void
926 res_close()
927 {
928 if (s >= 0) {
929 (void) close(s);
930 s = -1;
931 connected = 0;
932 vc = 0;
933 }
934 }