2 * ++Copyright++ 1985, 1989, 1993
4 * Copyright (c) 1985, 1989, 1993
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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
35 * Portions Copyright (c) 1993 by Digital Equipment Corporation.
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.
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
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 */
62 * if you talk to a lot
63 * of multi-homed SunOS
64 * ("broken") name servers.
66 #define CHECK_SRVR_ADDR 1 /* XXX - should be in options.h */
69 * Send query to name server and wait for reply.
72 #include <sys/param.h>
74 #include <sys/socket.h>
76 #include <netinet/in.h>
77 #include <arpa/nameser.h>
78 #include <arpa/inet.h>
84 #if defined(BSD) && (BSD >= 199306)
89 # include "../conf/portability.h"
92 #if defined(USE_OPTIONS_H)
93 # include <../conf/options.h>
96 void _res_close __P((void));
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? */
103 /* XXX - should be in portability.h */
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)))
112 /* XXX - this should be done in portability.h */
113 #if (defined(BSD) && (BSD >= 199103)) || defined(linux)
114 # define CAN_RECONNECT 1
116 # define CAN_RECONNECT 0
120 # define Dprint(cond, args) /*empty*/
121 # define DprintQ(cond, args, query, size) /*empty*/
122 # define Aerror(file, string, error, address) /*empty*/
123 # define Perror(file, string, error) /*empty*/
125 # define Dprint(cond, args) if (cond) {fprintf args;} else {}
126 # define DprintQ(cond, args, query, size) if (cond) {\
128 __fp_nquery(query, size, stdout);\
131 Aerror(file, string, error, address)
135 struct sockaddr_in address;
139 if (_res.options & RES_DEBUG) {
140 fprintf(file, "res_send: %s ([%s].%u): %s\n",
142 inet_ntoa(address.sin_addr),
143 ntohs(address.sin_port),
149 Perror(file, string, error)
156 if (_res.options & RES_DEBUG) {
157 fprintf(file, "res_send: %s: %s\n",
158 string, strerror(error));
164 static res_send_qhook Qhook = NULL;
165 static res_send_rhook Rhook = NULL;
168 res_send_setqhook(hook)
176 res_send_setrhook(hook)
184 * res_isourserver(ina)
185 * looks up "ina" in _res.ns_addr_list[]
190 * paul vixie, 29may94
194 const struct sockaddr_in *inp;
196 struct sockaddr_in ina;
197 register int ns, ret;
201 for (ns = 0; ns < _res.nscount; ns++) {
202 register const struct sockaddr_in *srv = &_res.nsaddr_list[ns];
204 if (srv->sin_family == ina.sin_family &&
205 srv->sin_port == ina.sin_port &&
206 (srv->sin_addr.s_addr == INADDR_ANY ||
207 srv->sin_addr.s_addr == ina.sin_addr.s_addr)) {
216 * res_nameinquery(name, type, class, buf, eom)
217 * look for (name,type,class) in the query section of packet (buf,eom)
223 * paul vixie, 29may94
226 res_nameinquery(name, type, class, buf, eom)
228 register int type, class;
229 const u_char *buf, *eom;
231 register const u_char *cp = buf + HFIXEDSZ;
232 int qdcount = ntohs(((HEADER*)buf)->qdcount);
234 while (qdcount-- > 0) {
235 char tname[MAXDNAME+1];
236 register int n, ttype, tclass;
238 n = dn_expand(buf, eom, cp, tname, sizeof tname);
242 ttype = _getshort(cp); cp += INT16SZ;
243 tclass = _getshort(cp); cp += INT16SZ;
246 strcasecmp(tname, name) == 0)
253 * res_queriesmatch(buf1, eom1, buf2, eom2)
254 * is there a 1:1 mapping of (name,type,class)
255 * in (buf1,eom1) and (buf2,eom2)?
258 * 0 : not a 1:1 mapping
259 * >0 : is a 1:1 mapping
261 * paul vixie, 29may94
264 res_queriesmatch(buf1, eom1, buf2, eom2)
265 const u_char *buf1, *eom1;
266 const u_char *buf2, *eom2;
268 register const u_char *cp = buf1 + HFIXEDSZ;
269 int qdcount = ntohs(((HEADER*)buf1)->qdcount);
271 if (qdcount != ntohs(((HEADER*)buf2)->qdcount))
273 while (qdcount-- > 0) {
274 char tname[MAXDNAME+1];
275 register int n, ttype, tclass;
277 n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
281 ttype = _getshort(cp); cp += INT16SZ;
282 tclass = _getshort(cp); cp += INT16SZ;
283 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2))
290 res_send(buf, buflen, ans, anssiz)
296 HEADER *hp = (HEADER *) buf;
297 HEADER *anhp = (HEADER *) ans;
298 int gotsomewhere, connreset, terrno, try, v_circuit, resplen, ns;
300 u_int badns; /* XXX NSMAX can't exceed #/bits in this var */
302 if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
303 /* errno should have been set by res_init() in this case. */
306 DprintQ((_res.options & RES_DEBUG) || (_res.pfcode & RES_PRF_QUERY),
307 (stdout, ";; res_send()\n"), buf, buflen);
308 v_circuit = (_res.options & RES_USEVC) || buflen > PACKETSZ;
315 * Send request, RETRY times, or until successful
317 for (try = 0; try < _res.retry; try++) {
318 for (ns = 0; ns < _res.nscount; ns++) {
319 struct sockaddr_in *nsap = &_res.nsaddr_list[ns];
321 if (badns & (1 << ns)) {
327 int done = 0, loops = 0;
332 act = (*Qhook)(&nsap, &buf, &buflen,
333 ans, anssiz, &resplen);
344 /* give the hook another try */
345 if (++loops < 42) /*doug adams*/
356 Dprint(_res.options & RES_DEBUG,
357 (stdout, ";; Querying server (# %d) address = %s\n",
358 ns + 1, inet_ntoa(nsap->sin_addr)));
367 * Use virtual circuit;
368 * at most one attempt per server.
372 if ((s < 0) || (!vc)) {
376 s = socket(PF_INET, SOCK_STREAM, 0);
379 Perror(stderr, "socket(vc)", errno);
383 if (connect(s, (struct sockaddr *)nsap,
384 sizeof(struct sockaddr)) < 0) {
386 Aerror(stderr, "connect/vc",
395 * Send length & message
397 putshort((u_short)buflen, (u_char*)&len);
398 iov[0].iov_base = (caddr_t)&len;
399 iov[0].iov_len = INT16SZ;
400 iov[1].iov_base = (caddr_t)buf;
401 iov[1].iov_len = buflen;
402 if (writev(s, iov, 2) != (INT16SZ + buflen)) {
404 Perror(stderr, "write failed", errno);
410 * Receive length & response
414 while ((n = read(s, (char *)cp, (int)len)) > 0) {
421 Perror(stderr, "read failed", errno);
424 * A long running process might get its TCP
425 * connection reset if the remote server was
426 * restarted. Requery the server instead of
427 * trying a new one. When there is only one
428 * server, this means that a query might work
429 * instead of failing. We only allow one reset
430 * per query to prevent looping.
432 if (terrno == ECONNRESET && !connreset) {
440 resplen = _getshort(ans);
441 if (resplen > anssiz) {
442 Dprint(_res.options & RES_DEBUG,
443 (stdout, ";; response truncated\n")
451 (n = read(s, (char *)cp, (int)len)) > 0) {
457 Perror(stderr, "read(vc)", errno);
463 * Flush rest of answer
464 * so connection stays in synch.
467 len = resplen - anssiz;
471 n = (len > sizeof(junk)
474 if ((n = read(s, junk, n)) > 0)
484 struct timeval timeout;
486 struct sockaddr_in from;
492 s = socket(PF_INET, SOCK_DGRAM, 0);
498 Perror(stderr, "socket(dg)", errno);
504 * On a 4.3BSD+ machine (client and server,
505 * actually), sending to a nameserver datagram
506 * port with no nameserver will cause an
507 * ICMP port unreachable message to be returned.
508 * If our datagram socket is "connected" to the
509 * server, we get an ECONNREFUSED error on the next
510 * socket operation, and select returns if the
511 * error message is received. We can thus detect
512 * the absence of a nameserver without timing out.
513 * If we have sent queries to at least two servers,
514 * however, we don't want to remain connected,
515 * as we wish to receive answers from the first
518 if (_res.nscount == 1 || (try == 0 && ns == 0)) {
520 * Connect only if we are sure we won't
521 * receive a response from another server.
524 if (connect(s, (struct sockaddr *)nsap,
525 sizeof(struct sockaddr)
536 if (send(s, (char*)buf, buflen, 0) != buflen) {
537 Perror(stderr, "send", errno);
544 * Disconnect if we want to listen
545 * for responses from more than one server.
549 struct sockaddr_in no_addr;
551 no_addr.sin_family = AF_INET;
552 no_addr.sin_addr.s_addr = INADDR_ANY;
553 no_addr.sin_port = 0;
559 int s1 = socket(PF_INET, SOCK_DGRAM,0);
564 Dprint(_res.options & RES_DEBUG,
565 (stdout, ";; new DG socket\n"))
570 if (sendto(s, (char*)buf, buflen, 0,
571 (struct sockaddr *)nsap,
572 sizeof(struct sockaddr))
574 Aerror(stderr, "sendto", errno, *nsap);
584 timeout.tv_sec = (_res.retrans << try);
586 timeout.tv_sec /= _res.nscount;
587 if ((long) timeout.tv_sec <= 0)
593 n = select(s+1, &dsmask, (fd_set *)NULL,
594 (fd_set *)NULL, &timeout);
596 Perror(stderr, "select", errno);
604 Dprint(_res.options & RES_DEBUG,
605 (stdout, ";; timeout\n"));
611 fromlen = sizeof(struct sockaddr_in);
612 resplen = recvfrom(s, (char*)ans, anssiz, 0,
613 (struct sockaddr *)&from, &fromlen);
615 Perror(stderr, "recvfrom", errno);
620 if (hp->id != anhp->id) {
622 * response from old query, ignore it.
623 * XXX - potential security hazard could
626 DprintQ((_res.options & RES_DEBUG) ||
627 (_res.pfcode & RES_PRF_REPLY),
628 (stdout, ";; old answer:\n"),
633 if (!(_res.options & RES_INSECURE1) &&
634 !res_isourserver(&from)) {
636 * response from wrong server? ignore it.
637 * XXX - potential security hazard could
640 DprintQ((_res.options & RES_DEBUG) ||
641 (_res.pfcode & RES_PRF_REPLY),
642 (stdout, ";; not our server:\n"),
647 if (!(_res.options & RES_INSECURE2) &&
648 !res_queriesmatch(buf, buf + buflen,
649 ans, ans + anssiz)) {
651 * response contains wrong query? ignore it.
652 * XXX - potential security hazard could
655 DprintQ((_res.options & RES_DEBUG) ||
656 (_res.pfcode & RES_PRF_REPLY),
657 (stdout, ";; wrong query name:\n"),
661 if (anhp->rcode == SERVFAIL ||
662 anhp->rcode == NOTIMP ||
663 anhp->rcode == REFUSED) {
664 DprintQ(_res.options & RES_DEBUG,
665 (stdout, "server rejected query:\n"),
669 /* don't retry if called from dig */
673 if (!(_res.options & RES_IGNTC) && anhp->tc) {
675 * get rest of answer;
676 * use TCP with same server.
678 Dprint(_res.options & RES_DEBUG,
679 (stdout, ";; truncated answer\n"));
685 DprintQ((_res.options & RES_DEBUG) ||
686 (_res.pfcode & RES_PRF_REPLY),
687 (stdout, ";; got answer:\n"),
690 * If using virtual circuits, we assume that the first server
691 * is preferred over the rest (i.e. it is on the local
692 * machine) and only keep that one open.
693 * If we have temporarily opened a virtual circuit,
694 * or if we haven't been asked to keep a socket open,
697 if ((v_circuit && (!(_res.options & RES_USEVC) || ns != 0)) ||
698 !(_res.options & RES_STAYOPEN)) {
702 int done = 0, loops = 0;
707 act = (*Rhook)(nsap, buf, buflen,
708 ans, anssiz, &resplen);
718 /* give the hook another try */
719 if (++loops < 42) /*doug adams*/
737 errno = ECONNREFUSED; /* no nameservers found */
739 errno = ETIMEDOUT; /* no answer obtained */
746 * This routine is for closing the socket if a virtual circuit is used and
747 * the program wants to close it. This provides support for endhostent()
748 * which expects to close the socket.
750 * This routine is not expected to be user visible.