2 * Copyright (c) 1985, 1989, 1993
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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
33 * @(#)res_send.c 8.1 (Berkeley) 6/4/93
34 * $From: Id: res_send.c,v 8.20 1998/04/06 23:27:51 halley Exp $
35 * $FreeBSD: src/lib/libc/net/res_send.c,v 1.31.2.9 2002/04/11 17:30:24 ume Exp $
36 * $DragonFly: src/lib/libc/net/res_send.c,v 1.3 2003/11/12 20:21:24 eirikn Exp $
40 * Portions Copyright (c) 1993 by Digital Equipment Corporation.
42 * Permission to use, copy, modify, and distribute this software for any
43 * purpose with or without fee is hereby granted, provided that the above
44 * copyright notice and this permission notice appear in all copies, and that
45 * the name of Digital Equipment Corporation not be used in advertising or
46 * publicity pertaining to distribution of the document or software without
47 * specific, written prior permission.
49 * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
50 * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
51 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
52 * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
53 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
54 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
55 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
60 * Portions Copyright (c) 1996 by Internet Software Consortium.
62 * Permission to use, copy, modify, and distribute this software for any
63 * purpose with or without fee is hereby granted, provided that the above
64 * copyright notice and this permission notice appear in all copies.
66 * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
67 * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
68 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
69 * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
70 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
71 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
72 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
77 * Send query to name server and wait for reply.
80 #include <sys/types.h>
81 #include <sys/event.h>
82 #include <sys/param.h>
84 #include <sys/socket.h>
87 #include <netinet/in.h>
88 #include <arpa/nameser.h>
89 #include <arpa/inet.h>
99 #include "res_config.h"
101 static int s = -1; /* socket used for communications */
102 static int connected = 0; /* is the socket connected */
103 static int vc = 0; /* is the socket a virtual circuit? */
104 static int af = 0; /* address family of socket */
105 static res_send_qhook Qhook = NULL;
106 static res_send_rhook Rhook = NULL;
109 #define CAN_RECONNECT 1
112 # define Dprint(cond, args) /*empty*/
113 # define DprintQ(cond, args, query, size) /*empty*/
114 # define Aerror(file, string, error, address) /*empty*/
115 # define Perror(file, string, error) /*empty*/
117 # define Dprint(cond, args) if (cond) {fprintf args;} else {}
118 # define DprintQ(cond, args, query, size) if (cond) {\
120 __fp_nquery(query, size, stdout);\
122 static char abuf[NI_MAXHOST];
123 static char pbuf[NI_MAXSERV];
124 static void Aerror (FILE *, char *, int, struct sockaddr *);
125 static void Perror (FILE *, char *, int);
128 Aerror(file, string, error, address)
132 struct sockaddr *address;
136 if (_res.options & RES_DEBUG) {
137 if (getnameinfo(address, address->sa_len, abuf, sizeof(abuf),
139 NI_NUMERICHOST|NI_NUMERICSERV|NI_WITHSCOPEID) != 0) {
140 strncpy(abuf, "?", sizeof(abuf));
141 strncpy(pbuf, "?", sizeof(pbuf));
143 fprintf(file, "res_send: %s ([%s].%s): %s\n",
144 string, abuf, pbuf, strerror(error));
149 Perror(file, string, error)
156 if (_res.options & RES_DEBUG) {
157 fprintf(file, "res_send: %s: %s\n",
158 string, strerror(error));
165 res_send_setqhook(hook)
173 res_send_setrhook(hook)
180 static struct sockaddr * get_nsaddr (size_t);
183 * pick appropriate nsaddr_list for use. see res_init() for initialization.
185 static struct sockaddr *
190 if (!_res.nsaddr_list[n].sin_family) {
192 * - _res_ext.nsaddr_list[n] holds an address that is larger
193 * than struct sockaddr, and
194 * - user code did not update _res.nsaddr_list[n].
196 return (struct sockaddr *)&_res_ext.nsaddr_list[n];
199 * - user code updated _res.nsaddr_list[n], or
200 * - _res.nsaddr_list[n] has the same content as
201 * _res_ext.nsaddr_list[n].
203 return (struct sockaddr *)&_res.nsaddr_list[n];
208 * res_isourserver(ina)
209 * looks up "ina" in _res.ns_addr_list[]
214 * paul vixie, 29may94
218 const struct sockaddr_in *inp;
220 const struct sockaddr_in6 *in6p = (const struct sockaddr_in6 *)inp;
221 const struct sockaddr_in6 *srv6;
222 const struct sockaddr_in *srv;
226 switch (inp->sin_family) {
228 for (ns = 0; ns < _res.nscount; ns++) {
229 srv6 = (struct sockaddr_in6 *)get_nsaddr(ns);
230 if (srv6->sin6_family == in6p->sin6_family &&
231 srv6->sin6_port == in6p->sin6_port &&
232 srv6->sin6_scope_id == in6p->sin6_scope_id &&
233 (IN6_IS_ADDR_UNSPECIFIED(&srv6->sin6_addr) ||
234 IN6_ARE_ADDR_EQUAL(&srv6->sin6_addr,
235 &in6p->sin6_addr))) {
242 for (ns = 0; ns < _res.nscount; ns++) {
243 srv = (struct sockaddr_in *)get_nsaddr(ns);
244 if (srv->sin_family == inp->sin_family &&
245 srv->sin_port == inp->sin_port &&
246 (srv->sin_addr.s_addr == INADDR_ANY ||
247 srv->sin_addr.s_addr == inp->sin_addr.s_addr)) {
258 * res_nameinquery(name, type, class, buf, eom)
259 * look for (name,type,class) in the query section of packet (buf,eom)
261 * buf + HFIXEDSZ <= eom
267 * paul vixie, 29may94
270 res_nameinquery(name, type, class, buf, eom)
273 const u_char *buf, *eom;
275 const u_char *cp = buf + HFIXEDSZ;
276 int qdcount = ntohs(((HEADER*)buf)->qdcount);
278 while (qdcount-- > 0) {
279 char tname[MAXDNAME+1];
280 int n, ttype, tclass;
282 n = dn_expand(buf, eom, cp, tname, sizeof tname);
286 if (cp + 2 * INT16SZ > eom)
288 ttype = ns_get16(cp); cp += INT16SZ;
289 tclass = ns_get16(cp); cp += INT16SZ;
292 strcasecmp(tname, name) == 0)
299 * res_queriesmatch(buf1, eom1, buf2, eom2)
300 * is there a 1:1 mapping of (name,type,class)
301 * in (buf1,eom1) and (buf2,eom2)?
304 * 0 : not a 1:1 mapping
305 * >0 : is a 1:1 mapping
307 * paul vixie, 29may94
310 res_queriesmatch(buf1, eom1, buf2, eom2)
311 const u_char *buf1, *eom1;
312 const u_char *buf2, *eom2;
314 const u_char *cp = buf1 + HFIXEDSZ;
315 int qdcount = ntohs(((HEADER*)buf1)->qdcount);
317 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2)
321 * Only header section present in replies to
322 * dynamic update packets.
324 if ( (((HEADER *)buf1)->opcode == ns_o_update) &&
325 (((HEADER *)buf2)->opcode == ns_o_update) )
328 if (qdcount != ntohs(((HEADER*)buf2)->qdcount))
330 while (qdcount-- > 0) {
331 char tname[MAXDNAME+1];
332 int n, ttype, tclass;
334 n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
338 if (cp + 2 * INT16SZ > eom1)
340 ttype = ns_get16(cp); cp += INT16SZ;
341 tclass = ns_get16(cp); cp += INT16SZ;
342 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2))
349 res_send(buf, buflen, ans, anssiz)
355 HEADER *hp = (HEADER *) buf;
356 HEADER *anhp = (HEADER *) ans;
357 int gotsomewhere, connreset, terrno, try, v_circuit, resplen, ns, n;
359 u_int badns; /* XXX NSMAX can't exceed #/bits in this variable */
361 if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
362 /* errno should have been set by res_init() in this case. */
365 if (anssiz < HFIXEDSZ) {
369 DprintQ((_res.options & RES_DEBUG) || (_res.pfcode & RES_PRF_QUERY),
370 (stdout, ";; res_send()\n"), buf, buflen);
371 v_circuit = (_res.options & RES_USEVC) || buflen > PACKETSZ;
377 if ((kq = kqueue()) < 0) {
378 Perror(stderr, "kqueue", errno);
383 * Send request, RETRY times, or until successful
385 for (try = 0; try < _res.retry; try++) {
386 for (ns = 0; ns < _res.nscount; ns++) {
387 struct sockaddr *nsap = get_nsaddr(ns);
391 salen = nsap->sa_len;
392 else if (nsap->sa_family == AF_INET6)
393 salen = sizeof(struct sockaddr_in6);
394 else if (nsap->sa_family == AF_INET)
395 salen = sizeof(struct sockaddr_in);
397 salen = 0; /*unknown, die on connect*/
400 if (badns & (1 << ns)) {
406 int done = 0, loops = 0;
411 act = (*Qhook)((struct sockaddr_in **)&nsap,
413 ans, anssiz, &resplen);
425 /* give the hook another try */
426 if (++loops < 42) /*doug adams*/
438 Dprint((_res.options & RES_DEBUG) &&
439 getnameinfo(nsap, salen, abuf, sizeof(abuf),
440 NULL, 0, NI_NUMERICHOST | NI_WITHSCOPEID) == 0,
441 (stdout, ";; Querying server (# %d) address = %s\n",
451 * Use virtual circuit;
452 * at most one attempt per server.
456 if (s < 0 || !vc || hp->opcode == ns_o_update ||
457 af != nsap->sa_family) {
461 af = nsap->sa_family;
462 s = socket(af, SOCK_STREAM, 0);
465 Perror(stderr, "socket(vc)", errno);
471 if (connect(s, nsap, salen) < 0) {
473 Aerror(stderr, "connect/vc",
482 * Send length & message
484 putshort((u_short)buflen, (u_char*)&len);
485 iov[0].iov_base = (caddr_t)&len;
486 iov[0].iov_len = INT16SZ;
487 iov[1].iov_base = (caddr_t)buf;
488 iov[1].iov_len = buflen;
489 if (writev(s, iov, 2) != (INT16SZ + buflen)) {
491 Perror(stderr, "write failed", errno);
497 * Receive length & response
502 while ((n = _read(s, (char *)cp, (int)len)) > 0) {
509 Perror(stderr, "read failed", errno);
512 * A long running process might get its TCP
513 * connection reset if the remote server was
514 * restarted. Requery the server instead of
515 * trying a new one. When there is only one
516 * server, this means that a query might work
517 * instead of failing. We only allow one reset
518 * per query to prevent looping.
520 if (terrno == ECONNRESET && !connreset) {
528 resplen = ns_get16(ans);
529 if (resplen > anssiz) {
530 Dprint(_res.options & RES_DEBUG,
531 (stdout, ";; response truncated\n")
537 if (len < HFIXEDSZ) {
539 * Undersized message.
541 Dprint(_res.options & RES_DEBUG,
542 (stdout, ";; undersized: %d\n", len));
550 (n = _read(s, (char *)cp, (int)len)) > 0) {
556 Perror(stderr, "read(vc)", errno);
562 * Flush rest of answer
563 * so connection stays in synch.
566 len = resplen - anssiz;
570 n = (len > sizeof(junk)
573 if ((n = _read(s, junk, n)) > 0)
580 * The calling applicating has bailed out of
581 * a previous call and failed to arrange to have
582 * the circuit closed or the server has got
583 * itself confused. Anyway drop the packet and
584 * wait for the correct one.
586 if (hp->id != anhp->id) {
587 DprintQ((_res.options & RES_DEBUG) ||
588 (_res.pfcode & RES_PRF_REPLY),
589 (stdout, ";; old answer (unexpected):\n"),
590 ans, (resplen>anssiz)?anssiz:resplen);
599 struct timeval timeout, ctv;
600 struct sockaddr_storage from;
603 if (s < 0 || vc || af != nsap->sa_family) {
606 af = nsap->sa_family;
607 s = socket(af, SOCK_DGRAM, 0);
609 #ifndef CAN_RECONNECT
613 Perror(stderr, "socket(dg)", errno);
620 #ifndef CANNOT_CONNECT_DGRAM
622 * On a 4.3BSD+ machine (client and server,
623 * actually), sending to a nameserver datagram
624 * port with no nameserver will cause an
625 * ICMP port unreachable message to be returned.
626 * If our datagram socket is "connected" to the
627 * server, we get an ECONNREFUSED error on the next
628 * socket operation, and select returns if the
629 * error message is received. We can thus detect
630 * the absence of a nameserver without timing out.
631 * If we have sent queries to at least two servers,
632 * however, we don't want to remain connected,
633 * as we wish to receive answers from the first
636 * When the option "insecure1" is specified, we'd
637 * rather expect to see responses from an "unknown"
638 * address. In order to let the kernel accept such
639 * responses, do not connect the socket here.
640 * XXX: or do we need an explicit option to disable
643 if (!(_res.options & RES_INSECURE1) &&
644 (_res.nscount == 1 || (try == 0 && ns == 0))) {
646 * Connect only if we are sure we won't
647 * receive a response from another server.
650 if (connect(s, nsap, salen) < 0) {
660 if (send(s, (char*)buf, buflen, 0) != buflen) {
661 Perror(stderr, "send", errno);
668 * Disconnect if we want to listen
669 * for responses from more than one server.
673 /* XXX: any errornous address */
674 struct sockaddr_in no_addr;
676 no_addr.sin_family = AF_INET;
677 no_addr.sin_addr.s_addr = INADDR_ANY;
678 no_addr.sin_port = 0;
684 int s1 = socket(af, SOCK_DGRAM,0);
689 Dprint(_res.options & RES_DEBUG,
690 (stdout, ";; new DG socket\n"))
691 #endif /* CAN_RECONNECT */
695 #endif /* !CANNOT_CONNECT_DGRAM */
696 if (sendto(s, (char*)buf, buflen, 0,
697 nsap, salen) != buflen) {
698 Aerror(stderr, "sendto", errno, nsap);
703 #ifndef CANNOT_CONNECT_DGRAM
705 #endif /* !CANNOT_CONNECT_DGRAM */
711 timeout.tv_sec = (_res.retrans << try);
713 timeout.tv_sec /= _res.nscount;
714 if ((long) timeout.tv_sec <= 0)
717 TIMEVAL_TO_TIMESPEC(&timeout, &ts);
718 (void) gettimeofday(&ctv, NULL);
719 timeradd(&timeout, &ctv, &timeout);
722 Perror(stderr, "s out-of-bounds", EMFILE);
727 EV_SET(&kv, s, EVFILT_READ, EV_ADD | EV_ONESHOT, 0,0,0);
729 n = kevent(kq, &kv, 1, &kv, 1, &ts);
731 if (errno == EINTR) {
732 (void) gettimeofday(&ctv, NULL);
733 if (timercmp(&ctv, &timeout, <)) {
734 timersub(&timeout, &ctv, &ctv);
735 TIMEVAL_TO_TIMESPEC(&ctv, &ts);
739 Perror(stderr, "kevent", errno);
748 Dprint(_res.options & RES_DEBUG,
749 (stdout, ";; timeout\n"));
755 fromlen = sizeof(from);
756 resplen = recvfrom(s, (char*)ans, anssiz, 0,
757 (struct sockaddr *)&from, &fromlen);
759 Perror(stderr, "recvfrom", errno);
764 if (resplen < HFIXEDSZ) {
766 * Undersized message.
768 Dprint(_res.options & RES_DEBUG,
769 (stdout, ";; undersized: %d\n",
776 if (hp->id != anhp->id) {
778 * response from old query, ignore it.
779 * XXX - potential security hazard could
782 DprintQ((_res.options & RES_DEBUG) ||
783 (_res.pfcode & RES_PRF_REPLY),
784 (stdout, ";; old answer:\n"),
785 ans, (resplen>anssiz)?anssiz:resplen);
788 #ifdef CHECK_SRVR_ADDR
789 if (!(_res.options & RES_INSECURE1) &&
790 !res_isourserver((struct sockaddr_in *)&from)) {
792 * response from wrong server? ignore it.
793 * XXX - potential security hazard could
796 DprintQ((_res.options & RES_DEBUG) ||
797 (_res.pfcode & RES_PRF_REPLY),
798 (stdout, ";; not our server:\n"),
799 ans, (resplen>anssiz)?anssiz:resplen);
803 if (!(_res.options & RES_INSECURE2) &&
804 !res_queriesmatch(buf, buf + buflen,
805 ans, ans + anssiz)) {
807 * response contains wrong query? ignore it.
808 * XXX - potential security hazard could
811 DprintQ((_res.options & RES_DEBUG) ||
812 (_res.pfcode & RES_PRF_REPLY),
813 (stdout, ";; wrong query name:\n"),
814 ans, (resplen>anssiz)?anssiz:resplen);
817 if (anhp->rcode == SERVFAIL ||
818 anhp->rcode == NOTIMP ||
819 anhp->rcode == REFUSED) {
820 DprintQ(_res.options & RES_DEBUG,
821 (stdout, "server rejected query:\n"),
822 ans, (resplen>anssiz)?anssiz:resplen);
825 /* don't retry if called from dig */
829 if (!(_res.options & RES_IGNTC) && anhp->tc) {
831 * get rest of answer;
832 * use TCP with same server.
834 Dprint(_res.options & RES_DEBUG,
835 (stdout, ";; truncated answer\n"));
841 Dprint((_res.options & RES_DEBUG) ||
842 ((_res.pfcode & RES_PRF_REPLY) &&
843 (_res.pfcode & RES_PRF_HEAD1)),
844 (stdout, ";; got answer:\n"));
845 DprintQ((_res.options & RES_DEBUG) ||
846 (_res.pfcode & RES_PRF_REPLY),
848 ans, (resplen>anssiz)?anssiz:resplen);
850 * If using virtual circuits, we assume that the first server
851 * is preferred over the rest (i.e. it is on the local
852 * machine) and only keep that one open.
853 * If we have temporarily opened a virtual circuit,
854 * or if we haven't been asked to keep a socket open,
857 if ((v_circuit && (!(_res.options & RES_USEVC) || ns != 0)) ||
858 !(_res.options & RES_STAYOPEN)) {
862 int done = 0, loops = 0;
867 act = (*Rhook)((struct sockaddr_in *)nsap,
869 ans, anssiz, &resplen);
879 /* give the hook another try */
880 if (++loops < 42) /*doug adams*/
901 errno = ECONNREFUSED; /* no nameservers found */
903 errno = ETIMEDOUT; /* no answer obtained */
910 * This routine is for closing the socket if a virtual circuit is used and
911 * the program wants to close it. This provides support for endhostent()
912 * which expects to close the socket.
914 * This routine is not expected to be user visible.
929 * Weak aliases for applications that use certain private entry points,
930 * and fail to include <resolv.h>.
933 __weak_reference(__res_close, _res_close);
935 __weak_reference(__res_send, res_send);