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