Incorporated from BIND 4.9.3-BETA24 release.
[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/param.h>
73 #include <sys/time.h>
74 #include <sys/socket.h>
75 #include <sys/uio.h>
76 #include <netinet/in.h>
77 #include <arpa/nameser.h>
78 #include <arpa/inet.h>
79
80 #include <stdio.h>
81 #include <netdb.h>
82 #include <errno.h>
83 #include <resolv.h>
84 #if defined(BSD) && (BSD >= 199306)
85 # include <stdlib.h>
86 # include <string.h>
87 # include <unistd.h>
88 #else
89 # include "../conf/portability.h"
90 #endif
91
92 #if defined(USE_OPTIONS_H)
93 # include <../conf/options.h>
94 #endif
95
96 void _res_close __P((void));
97
98 static int s = -1;      /* socket used for communications */
99 static int connected = 0;       /* is the socket connected */
100 static int vc = 0;      /* is the socket a virtual ciruit? */
101
102 #ifndef FD_SET
103 /* XXX - should be in portability.h */
104 #define NFDBITS         32
105 #define FD_SETSIZE      32
106 #define FD_SET(n, p)    ((p)->fds_bits[(n)/NFDBITS] |= (1 << ((n) % NFDBITS)))
107 #define FD_CLR(n, p)    ((p)->fds_bits[(n)/NFDBITS] &= ~(1 << ((n) % NFDBITS)))
108 #define FD_ISSET(n, p)  ((p)->fds_bits[(n)/NFDBITS] & (1 << ((n) % NFDBITS)))
109 #define FD_ZERO(p)      bzero((char *)(p), sizeof(*(p)))
110 #endif
111
112 #ifndef DEBUG
113 #   define Dprint(cond, args) /*empty*/
114 #   define DprintQ(cond, args, query, size) /*empty*/
115 #   define Aerror(file, string, error, address) /*empty*/
116 #   define Perror(file, string, error) /*empty*/
117 #else
118 #   define Dprint(cond, args) if (cond) {fprintf args;} else {}
119 #   define DprintQ(cond, args, query, size) if (cond) {\
120                         fprintf args;\
121                         __fp_nquery(query, size, stdout);\
122                 } else {}
123     static void
124     Aerror(file, string, error, address)
125         FILE *file;
126         char *string;
127         int error;
128         struct sockaddr_in address;
129     {
130         int save = errno;
131
132         if (_res.options & RES_DEBUG) {
133                 fprintf(file, "res_send: %s ([%s].%u): %s\n",
134                         string,
135                         inet_ntoa(address.sin_addr),
136                         ntohs(address.sin_port),
137                         strerror(error));
138         }
139         errno = save;
140     }
141     static void
142     Perror(file, string, error)
143         FILE *file;
144         char *string;
145         int error;
146     {
147         int save = errno;
148
149         if (_res.options & RES_DEBUG) {
150                 fprintf(file, "res_send: %s: %s\n",
151                         string, strerror(error));
152         }
153         errno = save;
154     }
155 #endif
156
157 static res_send_qhook Qhook = NULL;
158 static res_send_rhook Rhook = NULL;
159
160 void
161 res_send_setqhook(hook)
162         res_send_qhook hook;
163 {
164
165         Qhook = hook;
166 }
167
168 void
169 res_send_setrhook(hook)
170         res_send_rhook hook;
171 {
172
173         Rhook = hook;
174 }
175
176 /* int
177  * res_isourserver(ina)
178  *      looks up "ina" in _res.ns_addr_list[]
179  * returns:
180  *      0  : not found
181  *      >0 : found
182  * author:
183  *      paul vixie, 29may94
184  */
185 int
186 res_isourserver(inp)
187         const struct sockaddr_in *inp;
188 {
189         struct sockaddr_in ina;
190         register int ns, ret;
191
192         ina = *inp;
193         ret = 0;
194         for (ns = 0;  ns < _res.nscount;  ns++) {
195                 register const struct sockaddr_in *srv = &_res.nsaddr_list[ns];
196
197                 if (srv->sin_family == ina.sin_family &&
198                     srv->sin_port == ina.sin_port &&
199                     (srv->sin_addr.s_addr == INADDR_ANY ||
200                      srv->sin_addr.s_addr == ina.sin_addr.s_addr)) {
201                         ret++;
202                         break;
203                 }
204         }
205         return (ret);
206 }
207
208 /* int
209  * res_nameinquery(name, type, class, buf, eom)
210  *      look for (name,type,class) in the query section of packet (buf,eom)
211  * returns:
212  *      -1 : format error
213  *      0  : not found
214  *      >0 : found
215  * author:
216  *      paul vixie, 29may94
217  */
218 int
219 res_nameinquery(name, type, class, buf, eom)
220         const char *name;
221         register int type, class;
222         const u_char *buf, *eom;
223 {
224         register const u_char *cp = buf + HFIXEDSZ;
225         int qdcount = ntohs(((HEADER*)buf)->qdcount);
226
227         while (qdcount-- > 0) {
228                 char tname[MAXDNAME+1];
229                 register int n, ttype, tclass;
230
231                 n = dn_expand(buf, eom, cp, tname, sizeof tname);
232                 if (n < 0)
233                         return (-1);
234                 cp += n;
235                 ttype = _getshort(cp); cp += INT16SZ;
236                 tclass = _getshort(cp); cp += INT16SZ;
237                 if (ttype == type &&
238                     tclass == class &&
239                     strcasecmp(tname, name) == 0)
240                         return (1);
241         }
242         return (0);
243 }
244
245 /* int
246  * res_queriesmatch(buf1, eom1, buf2, eom2)
247  *      is there a 1:1 mapping of (name,type,class)
248  *      in (buf1,eom1) and (buf2,eom2)?
249  * returns:
250  *      -1 : format error
251  *      0  : not a 1:1 mapping
252  *      >0 : is a 1:1 mapping
253  * author:
254  *      paul vixie, 29may94
255  */
256 int
257 res_queriesmatch(buf1, eom1, buf2, eom2)
258         const u_char *buf1, *eom1;
259         const u_char *buf2, *eom2;
260 {
261         register const u_char *cp = buf1 + HFIXEDSZ;
262         int qdcount = ntohs(((HEADER*)buf1)->qdcount);
263
264         if (qdcount != ntohs(((HEADER*)buf2)->qdcount))
265                 return (0);
266         while (qdcount-- > 0) {
267                 char tname[MAXDNAME+1];
268                 register int n, ttype, tclass;
269
270                 n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
271                 if (n < 0)
272                         return (-1);
273                 cp += n;
274                 ttype = _getshort(cp);  cp += INT16SZ;
275                 tclass = _getshort(cp); cp += INT16SZ;
276                 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2))
277                         return (0);
278         }
279         return (1);
280 }
281
282 int
283 res_send(buf, buflen, ans, anssiz)
284         const u_char *buf;
285         int buflen;
286         u_char *ans;
287         int anssiz;
288 {
289         HEADER *hp = (HEADER *) buf;
290         HEADER *anhp = (HEADER *) ans;
291         int gotsomewhere, connreset, terrno, try, v_circuit, resplen, ns;
292         register int n;
293         u_int badns;    /* XXX NSMAX can't exceed #/bits in this var */
294
295         if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
296                 /* errno should have been set by res_init() in this case. */
297                 return (-1);
298         }
299         DprintQ((_res.options & RES_DEBUG) || (_res.pfcode & RES_PRF_QUERY),
300                 (stdout, ";; res_send()\n"), buf, buflen);
301         v_circuit = (_res.options & RES_USEVC) || buflen > PACKETSZ;
302         gotsomewhere = 0;
303         connreset = 0;
304         terrno = ETIMEDOUT;
305         badns = 0;
306
307         /*
308          * Send request, RETRY times, or until successful
309          */
310         for (try = 0; try < _res.retry; try++) {
311             for (ns = 0; ns < _res.nscount; ns++) {
312                 struct sockaddr_in *nsap = &_res.nsaddr_list[ns];
313     same_ns:
314                 if (badns & (1 << ns)) {
315                         _res_close();
316                         goto next_ns;
317                 }
318
319                 if (Qhook) {
320                         int done = 0, loops = 0;
321
322                         do {
323                                 res_sendhookact act;
324
325                                 act = (*Qhook)(&nsap, &buf, &buflen,
326                                                ans, anssiz, &resplen);
327                                 switch (act) {
328                                 case res_goahead:
329                                         done = 1;
330                                         break;
331                                 case res_nextns:
332                                         _res_close();
333                                         goto next_ns;
334                                 case res_done:
335                                         return (resplen);
336                                 case res_modified:
337                                         /* give the hook another try */
338                                         if (++loops < 42) /*doug adams*/
339                                                 break;
340                                         /*FALLTHROUGH*/
341                                 case res_error:
342                                         /*FALLTHROUGH*/
343                                 default:
344                                         return (-1);
345                                 }
346                         } while (!done);
347                 }
348
349                 Dprint(_res.options & RES_DEBUG,
350                        (stdout, ";; Querying server (# %d) address = %s\n",
351                         ns + 1, inet_ntoa(nsap->sin_addr)));
352
353                 if (v_circuit) {
354                         int truncated;
355                         struct iovec iov[2];
356                         u_short len;
357                         u_char *cp;
358
359                         /*
360                          * Use virtual circuit;
361                          * at most one attempt per server.
362                          */
363                         try = _res.retry;
364                         truncated = 0;
365                         if ((s < 0) || (!vc)) {
366                                 if (s >= 0)
367                                         _res_close();
368
369                                 s = socket(PF_INET, SOCK_STREAM, 0);
370                                 if (s < 0) {
371                                         terrno = errno;
372                                         Perror(stderr, "socket(vc)", errno);
373                                         return (-1);
374                                 }
375                                 errno = 0;
376                                 if (connect(s, (struct sockaddr *)nsap,
377                                             sizeof(struct sockaddr)) < 0) {
378                                         terrno = errno;
379                                         Aerror(stderr, "connect/vc",
380                                                errno, *nsap);
381                                         badns |= (1 << ns);
382                                         _res_close();
383                                         goto next_ns;
384                                 }
385                                 vc = 1;
386                         }
387                         /*
388                          * Send length & message
389                          */
390                         putshort((u_short)buflen, (u_char*)&len);
391                         iov[0].iov_base = (caddr_t)&len;
392                         iov[0].iov_len = INT16SZ;
393                         iov[1].iov_base = (caddr_t)buf;
394                         iov[1].iov_len = buflen;
395                         if (writev(s, iov, 2) != (INT16SZ + buflen)) {
396                                 terrno = errno;
397                                 Perror(stderr, "write failed", errno);
398                                 badns |= (1 << ns);
399                                 _res_close();
400                                 goto next_ns;
401                         }
402                         /*
403                          * Receive length & response
404                          */
405                         cp = ans;
406                         len = INT16SZ;
407                         while ((n = read(s, (char *)cp, (int)len)) > 0) {
408                                 cp += n;
409                                 if ((len -= n) <= 0)
410                                         break;
411                         }
412                         if (n <= 0) {
413                                 terrno = errno;
414                                 Perror(stderr, "read failed", errno);
415                                 _res_close();
416                                 /*
417                                  * A long running process might get its TCP
418                                  * connection reset if the remote server was
419                                  * restarted.  Requery the server instead of
420                                  * trying a new one.  When there is only one
421                                  * server, this means that a query might work
422                                  * instead of failing.  We only allow one reset
423                                  * per query to prevent looping.
424                                  */
425                                 if (terrno == ECONNRESET && !connreset) {
426                                         connreset = 1;
427                                         _res_close();
428                                         goto same_ns;
429                                 }
430                                 _res_close();
431                                 goto next_ns;
432                         }
433                         resplen = _getshort(ans);
434                         if (resplen > anssiz) {
435                                 Dprint(_res.options & RES_DEBUG,
436                                        (stdout, ";; response truncated\n")
437                                        );
438                                 truncated = 1;
439                                 len = anssiz;
440                         } else
441                                 len = resplen;
442                         cp = ans;
443                         while (len != 0 &&
444                                (n = read(s, (char *)cp, (int)len)) > 0) {
445                                 cp += n;
446                                 len -= n;
447                         }
448                         if (n <= 0) {
449                                 terrno = errno;
450                                 Perror(stderr, "read(vc)", errno);
451                                 _res_close();
452                                 goto next_ns;
453                         }
454                         if (truncated) {
455                                 /*
456                                  * Flush rest of answer
457                                  * so connection stays in synch.
458                                  */
459                                 anhp->tc = 1;
460                                 len = resplen - anssiz;
461                                 while (len != 0) {
462                                         char junk[PACKETSZ];
463
464                                         n = (len > sizeof(junk)
465                                              ? sizeof(junk)
466                                              : len);
467                                         if ((n = read(s, junk, n)) > 0)
468                                                 len -= n;
469                                         else
470                                                 break;
471                                 }
472                         }
473                 } else {
474                         /*
475                          * Use datagrams.
476                          */
477                         struct timeval timeout;
478                         fd_set dsmask;
479                         struct sockaddr_in from;
480                         int fromlen;
481
482                         if ((s < 0) || vc) {
483                                 if (vc)
484                                         _res_close();
485                                 s = socket(PF_INET, SOCK_DGRAM, 0);
486                                 if (s < 0) {
487 #if !defined(BSD) || (BSD < 199103)
488  bad_dg_sock:
489 #endif
490                                         terrno = errno;
491                                         Perror(stderr, "socket(dg)", errno);
492                                         return (-1);
493                                 }
494                                 connected = 0;
495                         }
496                         /*
497                          * On a 4.3BSD+ machine (client and server,
498                          * actually), sending to a nameserver datagram
499                          * port with no nameserver will cause an
500                          * ICMP port unreachable message to be returned.
501                          * If our datagram socket is "connected" to the
502                          * server, we get an ECONNREFUSED error on the next
503                          * socket operation, and select returns if the
504                          * error message is received.  We can thus detect
505                          * the absence of a nameserver without timing out.
506                          * If we have sent queries to at least two servers,
507                          * however, we don't want to remain connected,
508                          * as we wish to receive answers from the first
509                          * server to respond.
510                          */
511                         if (_res.nscount == 1 || (try == 0 && ns == 0)) {
512                                 /*
513                                  * Connect only if we are sure we won't
514                                  * receive a response from another server.
515                                  */
516                                 if (!connected) {
517                                         if (connect(s, (struct sockaddr *)nsap,
518                                                     sizeof(struct sockaddr)
519                                                     ) < 0) {
520                                                 Aerror(stderr,
521                                                        "connect(dg)",
522                                                        errno, *nsap);
523                                                 badns |= (1 << ns);
524                                                 _res_close();
525                                                 goto next_ns;
526                                         }
527                                         connected = 1;
528                                 }
529                                 if (send(s, (char*)buf, buflen, 0) != buflen) {
530                                         Perror(stderr, "send", errno);
531                                         badns |= (1 << ns);
532                                         _res_close();
533                                         goto next_ns;
534                                 }
535                         } else {
536                                 /*
537                                  * Disconnect if we want to listen
538                                  * for responses from more than one server.
539                                  */
540                                 if (connected) {
541 #if defined(BSD) && (BSD >= 199103)
542                                         struct sockaddr_in no_addr;
543
544                                         no_addr.sin_family = AF_INET;
545                                         no_addr.sin_addr.s_addr = INADDR_ANY;
546                                         no_addr.sin_port = 0;
547                                         (void) connect(s,
548                                                        (struct sockaddr *)
549                                                         &no_addr,
550                                                        sizeof(no_addr));
551 #else
552                                         int s1 = socket(PF_INET, SOCK_DGRAM,0);
553                                         if (s1 < 0)
554                                                 goto bad_dg_sock;
555                                         (void) dup2(s1, s);
556                                         (void) close(s1);
557                                         Dprint(_res.options & RES_DEBUG,
558                                                (stdout, ";; new DG socket\n"))
559 #endif
560                                         connected = 0;
561                                         errno = 0;
562                                 }
563                                 if (sendto(s, (char*)buf, buflen, 0,
564                                            (struct sockaddr *)nsap,
565                                            sizeof(struct sockaddr))
566                                     != buflen) {
567                                         Aerror(stderr, "sendto", errno, *nsap);
568                                         badns |= (1 << ns);
569                                         _res_close();
570                                         goto next_ns;
571                                 }
572                         }
573
574                         /*
575                          * Wait for reply
576                          */
577                         timeout.tv_sec = (_res.retrans << try);
578                         if (try > 0)
579                                 timeout.tv_sec /= _res.nscount;
580                         if ((long) timeout.tv_sec <= 0)
581                                 timeout.tv_sec = 1;
582                         timeout.tv_usec = 0;
583     wait:
584                         FD_ZERO(&dsmask);
585                         FD_SET(s, &dsmask);
586                         n = select(s+1, &dsmask, (fd_set *)NULL,
587                                    (fd_set *)NULL, &timeout);
588                         if (n < 0) {
589                                 Perror(stderr, "select", errno);
590                                 _res_close();
591                                 goto next_ns;
592                         }
593                         if (n == 0) {
594                                 /*
595                                  * timeout
596                                  */
597                                 Dprint(_res.options & RES_DEBUG,
598                                        (stdout, ";; timeout\n"));
599                                 gotsomewhere = 1;
600                                 _res_close();
601                                 goto next_ns;
602                         }
603                         errno = 0;
604                         fromlen = sizeof(struct sockaddr_in);
605                         resplen = recvfrom(s, (char*)ans, anssiz, 0,
606                                            (struct sockaddr *)&from, &fromlen);
607                         if (resplen <= 0) {
608                                 Perror(stderr, "recvfrom", errno);
609                                 _res_close();
610                                 goto next_ns;
611                         }
612                         gotsomewhere = 1;
613                         if (hp->id != anhp->id) {
614                                 /*
615                                  * response from old query, ignore it.
616                                  * XXX - potential security hazard could
617                                  *       be detected here.
618                                  */
619                                 DprintQ((_res.options & RES_DEBUG) ||
620                                         (_res.pfcode & RES_PRF_REPLY),
621                                         (stdout, ";; old answer:\n"),
622                                         ans, resplen);
623                                 goto wait;
624                         }
625 #if CHECK_SRVR_ADDR
626                         if (!(_res.options & RES_INSECURE1) &&
627                             !res_isourserver(&from)) {
628                                 /*
629                                  * response from wrong server? ignore it.
630                                  * XXX - potential security hazard could
631                                  *       be detected here.
632                                  */
633                                 DprintQ((_res.options & RES_DEBUG) ||
634                                         (_res.pfcode & RES_PRF_REPLY),
635                                         (stdout, ";; not our server:\n"),
636                                         ans, resplen);
637                                 goto wait;
638                         }
639 #endif
640                         if (!(_res.options & RES_INSECURE2) &&
641                             !res_queriesmatch(buf, buf + buflen,
642                                               ans, ans + anssiz)) {
643                                 /*
644                                  * response contains wrong query? ignore it.
645                                  * XXX - potential security hazard could
646                                  *       be detected here.
647                                  */
648                                 DprintQ((_res.options & RES_DEBUG) ||
649                                         (_res.pfcode & RES_PRF_REPLY),
650                                         (stdout, ";; wrong query name:\n"),
651                                         ans, resplen);
652                                 goto wait;
653                         }
654                         if (anhp->rcode == SERVFAIL ||
655                             anhp->rcode == NOTIMP ||
656                             anhp->rcode == REFUSED) {
657                                 DprintQ(_res.options & RES_DEBUG,
658                                         (stdout, "server rejected query:\n"),
659                                         ans, resplen);
660                                 badns |= (1 << ns);
661                                 _res_close();
662                                 /* don't retry if called from dig */
663                                 if (!_res.pfcode)
664                                         goto next_ns;
665                         }
666                         if (!(_res.options & RES_IGNTC) && anhp->tc) {
667                                 /*
668                                  * get rest of answer;
669                                  * use TCP with same server.
670                                  */
671                                 Dprint(_res.options & RES_DEBUG,
672                                        (stdout, ";; truncated answer\n"));
673                                 v_circuit = 1;
674                                 _res_close();
675                                 goto same_ns;
676                         }
677                 } /*if vc/dg*/
678                 DprintQ((_res.options & RES_DEBUG) ||
679                         (_res.pfcode & RES_PRF_REPLY),
680                         (stdout, ";; got answer:\n"),
681                         ans, resplen);
682                 /*
683                  * If using virtual circuits, we assume that the first server
684                  * is preferred over the rest (i.e. it is on the local
685                  * machine) and only keep that one open.
686                  * If we have temporarily opened a virtual circuit,
687                  * or if we haven't been asked to keep a socket open,
688                  * close the socket.
689                  */
690                 if ((v_circuit && (!(_res.options & RES_USEVC) || ns != 0)) ||
691                     !(_res.options & RES_STAYOPEN)) {
692                         _res_close();
693                 }
694                 if (Rhook) {
695                         int done = 0, loops = 0;
696
697                         do {
698                                 res_sendhookact act;
699
700                                 act = (*Rhook)(nsap, buf, buflen,
701                                                ans, anssiz, &resplen);
702                                 switch (act) {
703                                 case res_goahead:
704                                 case res_done:
705                                         done = 1;
706                                         break;
707                                 case res_nextns:
708                                         _res_close();
709                                         goto next_ns;
710                                 case res_modified:
711                                         /* give the hook another try */
712                                         if (++loops < 42) /*doug adams*/
713                                                 break;
714                                         /*FALLTHROUGH*/
715                                 case res_error:
716                                         /*FALLTHROUGH*/
717                                 default:
718                                         return (-1);
719                                 }
720                         } while (!done);
721
722                 }
723                 return (resplen);
724     next_ns: ;
725            } /*foreach ns*/
726         } /*foreach retry*/
727         _res_close();
728         if (!v_circuit)
729                 if (!gotsomewhere)
730                         errno = ECONNREFUSED;   /* no nameservers found */
731                 else
732                         errno = ETIMEDOUT;      /* no answer obtained */
733         else
734                 errno = terrno;
735         return (-1);
736 }
737
738 /*
739  * This routine is for closing the socket if a virtual circuit is used and
740  * the program wants to close it.  This provides support for endhostent()
741  * which expects to close the socket.
742  *
743  * This routine is not expected to be user visible.
744  */
745 void
746 _res_close()
747 {
748         if (s >= 0) {
749                 (void) close(s);
750                 s = -1;
751                 connected = 0;
752                 vc = 0;
753         }
754 }