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