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
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
55 * Portions Copyright (c) 1996 by Internet Software Consortium.
57 * Permission to use, copy, modify, and distribute this software for any
58 * purpose with or without fee is hereby granted, provided that the above
59 * copyright notice and this permission notice appear in all copies.
61 * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
62 * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
63 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
64 * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
65 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
66 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
67 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
71 #if defined(LIBC_SCCS) && !defined(lint)
72 static char sccsid[] = "@(#)res_send.c 8.1 (Berkeley) 6/4/93";
73 static char orig_rcsid[] = "From: Id: res_send.c,v 8.20 1998/04/06 23:27:51 halley Exp $";
74 #endif /* LIBC_SCCS and not lint */
75 #include <sys/cdefs.h>
76 __FBSDID("$FreeBSD$");
79 * Send query to name server and wait for reply.
82 #include "namespace.h"
83 #include <sys/types.h>
84 #include <sys/event.h>
85 #include <sys/param.h>
87 #include <sys/socket.h>
90 #include <netinet/in.h>
91 #include <arpa/nameser.h>
92 #include <arpa/inet.h>
101 #include "un-namespace.h"
103 #include "res_config.h"
104 #include "res_send_private.h"
107 #define s ___res_send_private()->s
108 #define connected ___res_send_private()->connected
109 #define vc ___res_send_private()->vc
110 #define af ___res_send_private()->af
111 #define Qhook ___res_send_private()->Qhook
112 #define Rhook ___res_send_private()->Rhook
114 #define CAN_RECONNECT 1
117 # define Dprint(cond, args) /*empty*/
118 # define DprintQ(cond, args, query, size) /*empty*/
119 # define Aerror(file, string, error, address) /*empty*/
120 # define Perror(file, string, error) /*empty*/
122 # define Dprint(cond, args) if (cond) {fprintf args;} else {}
123 # define DprintQ(cond, args, query, size) if (cond) {\
125 __fp_nquery(query, size, stdout);\
127 static void Aerror(FILE *, char *, int, struct sockaddr *);
128 static void Perror(FILE *, char *, int);
131 Aerror(file, string, error, address)
135 struct sockaddr *address;
139 if (_res.options & RES_DEBUG) {
140 char abuf[NI_MAXHOST];
141 char pbuf[NI_MAXSERV];
143 if (getnameinfo(address, address->sa_len, abuf, sizeof(abuf),
144 pbuf, sizeof(pbuf), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
145 strncpy(abuf, "?", sizeof(abuf));
146 strncpy(pbuf, "?", sizeof(pbuf));
148 fprintf(file, "res_send: %s ([%s].%s): %s\n",
149 string, abuf, pbuf, strerror(error));
154 Perror(file, string, error)
161 if (_res.options & RES_DEBUG) {
162 fprintf(file, "res_send: %s: %s\n",
163 string, strerror(error));
170 res_send_setqhook(hook)
178 res_send_setrhook(hook)
185 static struct sockaddr * get_nsaddr(size_t);
188 * pick appropriate nsaddr_list for use. see res_init() for initialization.
190 static struct sockaddr *
195 if (!_res.nsaddr_list[n].sin_family) {
197 * - _res_ext.nsaddr_list[n] holds an address that is larger
198 * than struct sockaddr, and
199 * - user code did not update _res.nsaddr_list[n].
201 return (struct sockaddr *)&_res_ext.nsaddr_list[n];
204 * - user code updated _res.nsaddr_list[n], or
205 * - _res.nsaddr_list[n] has the same content as
206 * _res_ext.nsaddr_list[n].
208 return (struct sockaddr *)&_res.nsaddr_list[n];
213 * res_isourserver(ina)
214 * looks up "ina" in _res.ns_addr_list[]
219 * paul vixie, 29may94
223 const struct sockaddr_in *inp;
225 const struct sockaddr_in6 *in6p = (const struct sockaddr_in6 *)inp;
226 const struct sockaddr_in6 *srv6;
227 const struct sockaddr_in *srv;
231 switch (inp->sin_family) {
233 for (ns = 0; ns < _res.nscount; ns++) {
234 srv6 = (struct sockaddr_in6 *)get_nsaddr(ns);
235 if (srv6->sin6_family == in6p->sin6_family &&
236 srv6->sin6_port == in6p->sin6_port &&
237 srv6->sin6_scope_id == in6p->sin6_scope_id &&
238 (IN6_IS_ADDR_UNSPECIFIED(&srv6->sin6_addr) ||
239 IN6_ARE_ADDR_EQUAL(&srv6->sin6_addr,
240 &in6p->sin6_addr))) {
247 for (ns = 0; ns < _res.nscount; ns++) {
248 srv = (struct sockaddr_in *)get_nsaddr(ns);
249 if (srv->sin_family == inp->sin_family &&
250 srv->sin_port == inp->sin_port &&
251 (srv->sin_addr.s_addr == INADDR_ANY ||
252 srv->sin_addr.s_addr == inp->sin_addr.s_addr)) {
263 * res_nameinquery(name, type, class, buf, eom)
264 * look for (name,type,class) in the query section of packet (buf,eom)
266 * buf + HFIXEDSZ <= eom
272 * paul vixie, 29may94
275 res_nameinquery(name, type, class, buf, eom)
278 const u_char *buf, *eom;
280 const u_char *cp = buf + HFIXEDSZ;
281 int qdcount = ntohs(((HEADER*)buf)->qdcount);
283 while (qdcount-- > 0) {
284 char tname[MAXDNAME+1];
285 int n, ttype, tclass;
287 n = dn_expand(buf, eom, cp, tname, sizeof tname);
291 if (cp + 2 * INT16SZ > eom)
293 ttype = ns_get16(cp); cp += INT16SZ;
294 tclass = ns_get16(cp); cp += INT16SZ;
297 strcasecmp(tname, name) == 0)
304 * res_queriesmatch(buf1, eom1, buf2, eom2)
305 * is there a 1:1 mapping of (name,type,class)
306 * in (buf1,eom1) and (buf2,eom2)?
309 * 0 : not a 1:1 mapping
310 * >0 : is a 1:1 mapping
312 * paul vixie, 29may94
315 res_queriesmatch(buf1, eom1, buf2, eom2)
316 const u_char *buf1, *eom1;
317 const u_char *buf2, *eom2;
319 const u_char *cp = buf1 + HFIXEDSZ;
320 int qdcount = ntohs(((HEADER*)buf1)->qdcount);
322 if (buf1 + HFIXEDSZ > eom1 || buf2 + HFIXEDSZ > eom2)
326 * Only header section present in replies to
327 * dynamic update packets.
329 if ( (((HEADER *)buf1)->opcode == ns_o_update) &&
330 (((HEADER *)buf2)->opcode == ns_o_update) )
333 if (qdcount != ntohs(((HEADER*)buf2)->qdcount))
335 while (qdcount-- > 0) {
336 char tname[MAXDNAME+1];
337 int n, ttype, tclass;
339 n = dn_expand(buf1, eom1, cp, tname, sizeof tname);
343 if (cp + 2 * INT16SZ > eom1)
345 ttype = ns_get16(cp); cp += INT16SZ;
346 tclass = ns_get16(cp); cp += INT16SZ;
347 if (!res_nameinquery(tname, ttype, tclass, buf2, eom2))
354 res_send(buf, buflen, ans, anssiz)
360 HEADER *hp = (HEADER *) buf;
361 HEADER *anhp = (HEADER *) ans;
362 int gotsomewhere, connreset, terrno, try, v_circuit, resplen, ns, n;
364 u_int badns; /* XXX NSMAX can't exceed #/bits in this variable */
366 if ((_res.options & RES_INIT) == 0 && res_init() == -1) {
367 /* errno should have been set by res_init() in this case. */
370 if (anssiz < HFIXEDSZ) {
374 DprintQ((_res.options & RES_DEBUG) || (_res.pfcode & RES_PRF_QUERY),
375 (stdout, ";; res_send()\n"), buf, buflen);
376 v_circuit = (_res.options & RES_USEVC) || buflen > PACKETSZ;
382 if ((kq = kqueue()) < 0) {
383 Perror(stderr, "kqueue", errno);
388 * Send request, RETRY times, or until successful
390 for (try = 0; try < _res.retry; try++) {
391 for (ns = 0; ns < _res.nscount; ns++) {
392 char abuf[NI_MAXHOST];
393 struct sockaddr *nsap = get_nsaddr(ns);
397 salen = nsap->sa_len;
398 else if (nsap->sa_family == AF_INET6)
399 salen = sizeof(struct sockaddr_in6);
400 else if (nsap->sa_family == AF_INET)
401 salen = sizeof(struct sockaddr_in);
403 salen = 0; /*unknown, die on connect*/
406 if (badns & (1 << ns)) {
412 int done = 0, loops = 0;
417 act = (*Qhook)(&nsap,
419 ans, anssiz, &resplen);
431 /* give the hook another try */
432 if (++loops < 42) /*doug adams*/
444 Dprint((_res.options & RES_DEBUG) &&
445 getnameinfo(nsap, salen, abuf, sizeof(abuf),
446 NULL, 0, NI_NUMERICHOST) == 0,
447 (stdout, ";; Querying server (# %d) address = %s\n",
457 * Use virtual circuit;
458 * at most one attempt per server.
462 if (s < 0 || !vc || hp->opcode == ns_o_update ||
463 af != nsap->sa_family) {
467 af = nsap->sa_family;
468 s = _socket(af, SOCK_STREAM, 0);
471 Perror(stderr, "socket(vc)", errno);
477 if (_connect(s, nsap, salen) < 0) {
479 Aerror(stderr, "connect/vc",
488 * Send length & message
490 putshort((u_short)buflen, (u_char*)&len);
491 iov[0].iov_base = (caddr_t)&len;
492 iov[0].iov_len = INT16SZ;
493 iov[1].iov_base = (caddr_t)buf;
494 iov[1].iov_len = buflen;
495 if (_writev(s, iov, 2) != (INT16SZ + buflen)) {
497 Perror(stderr, "write failed", errno);
503 * Receive length & response
508 while ((n = _read(s, (char *)cp, (int)len)) > 0) {
515 Perror(stderr, "read failed", errno);
518 * A long running process might get its TCP
519 * connection reset if the remote server was
520 * restarted. Requery the server instead of
521 * trying a new one. When there is only one
522 * server, this means that a query might work
523 * instead of failing. We only allow one reset
524 * per query to prevent looping.
526 if (terrno == ECONNRESET && !connreset) {
534 resplen = ns_get16(ans);
535 if (resplen > anssiz) {
536 Dprint(_res.options & RES_DEBUG,
537 (stdout, ";; response truncated\n")
543 if (len < HFIXEDSZ) {
545 * Undersized message.
547 Dprint(_res.options & RES_DEBUG,
548 (stdout, ";; undersized: %d\n", len));
556 (n = _read(s, (char *)cp, (int)len)) > 0) {
562 Perror(stderr, "read(vc)", errno);
568 * Flush rest of answer
569 * so connection stays in synch.
572 len = resplen - anssiz;
576 n = (len > sizeof(junk)
579 if ((n = _read(s, junk, n)) > 0)
586 * The calling applicating has bailed out of
587 * a previous call and failed to arrange to have
588 * the circuit closed or the server has got
589 * itself confused. Anyway drop the packet and
590 * wait for the correct one.
592 if (hp->id != anhp->id) {
593 DprintQ((_res.options & RES_DEBUG) ||
594 (_res.pfcode & RES_PRF_REPLY),
595 (stdout, ";; old answer (unexpected):\n"),
596 ans, (resplen>anssiz)?anssiz:resplen);
605 struct timeval timeout, ctv;
606 struct sockaddr_storage from;
609 if (s < 0 || vc || af != nsap->sa_family) {
612 af = nsap->sa_family;
613 s = _socket(af, SOCK_DGRAM, 0);
615 #ifndef CAN_RECONNECT
619 Perror(stderr, "socket(dg)", errno);
626 #ifndef CANNOT_CONNECT_DGRAM
628 * On a 4.3BSD+ machine (client and server,
629 * actually), sending to a nameserver datagram
630 * port with no nameserver will cause an
631 * ICMP port unreachable message to be returned.
632 * If our datagram socket is "connected" to the
633 * server, we get an ECONNREFUSED error on the next
634 * socket operation, and select returns if the
635 * error message is received. We can thus detect
636 * the absence of a nameserver without timing out.
637 * If we have sent queries to at least two servers,
638 * however, we don't want to remain connected,
639 * as we wish to receive answers from the first
642 * When the option "insecure1" is specified, we'd
643 * rather expect to see responses from an "unknown"
644 * address. In order to let the kernel accept such
645 * responses, do not connect the socket here.
646 * XXX: or do we need an explicit option to disable
649 if (!(_res.options & RES_INSECURE1) &&
650 (_res.nscount == 1 || (try == 0 && ns == 0))) {
652 * Connect only if we are sure we won't
653 * receive a response from another server.
656 if (_connect(s, nsap, salen) < 0) {
666 if (send(s, (char*)buf, buflen, 0) != buflen) {
667 Perror(stderr, "send", errno);
674 * Disconnect if we want to listen
675 * for responses from more than one server.
679 /* XXX: any errornous address */
680 struct sockaddr_in no_addr;
682 no_addr.sin_family = AF_INET;
683 no_addr.sin_addr.s_addr = INADDR_ANY;
684 no_addr.sin_port = 0;
690 int s1 = _socket(af, SOCK_DGRAM,0);
695 Dprint(_res.options & RES_DEBUG,
696 (stdout, ";; new DG socket\n"))
697 #endif /* CAN_RECONNECT */
701 #endif /* !CANNOT_CONNECT_DGRAM */
702 if (_sendto(s, (char*)buf, buflen, 0,
703 nsap, salen) != buflen) {
704 Aerror(stderr, "sendto", errno, nsap);
709 #ifndef CANNOT_CONNECT_DGRAM
711 #endif /* !CANNOT_CONNECT_DGRAM */
717 timeout.tv_sec = (_res.retrans << try);
719 timeout.tv_sec /= _res.nscount;
720 if ((long) timeout.tv_sec <= 0)
723 TIMEVAL_TO_TIMESPEC(&timeout, &ts);
724 (void) gettimeofday(&ctv, NULL);
725 timeradd(&timeout, &ctv, &timeout);
728 Perror(stderr, "s out-of-bounds", EMFILE);
733 EV_SET(&kv, s, EVFILT_READ, EV_ADD | EV_ONESHOT, 0,0,0);
735 n = _kevent(kq, &kv, 1, &kv, 1, &ts);
737 if (errno == EINTR) {
738 (void) gettimeofday(&ctv, NULL);
739 if (timercmp(&ctv, &timeout, <)) {
740 timersub(&timeout, &ctv, &ctv);
741 TIMEVAL_TO_TIMESPEC(&ctv, &ts);
745 Perror(stderr, "kevent", errno);
754 Dprint(_res.options & RES_DEBUG,
755 (stdout, ";; timeout\n"));
761 fromlen = sizeof(from);
762 resplen = _recvfrom(s, (char*)ans, anssiz, 0,
763 (struct sockaddr *)&from, &fromlen);
765 Perror(stderr, "recvfrom", errno);
770 if (resplen < HFIXEDSZ) {
772 * Undersized message.
774 Dprint(_res.options & RES_DEBUG,
775 (stdout, ";; undersized: %d\n",
782 if (hp->id != anhp->id) {
784 * response from old query, ignore it.
785 * XXX - potential security hazard could
788 DprintQ((_res.options & RES_DEBUG) ||
789 (_res.pfcode & RES_PRF_REPLY),
790 (stdout, ";; old answer:\n"),
791 ans, (resplen>anssiz)?anssiz:resplen);
794 #ifdef CHECK_SRVR_ADDR
795 if (!(_res.options & RES_INSECURE1) &&
796 !res_isourserver((struct sockaddr_in *)&from)) {
798 * response from wrong server? ignore it.
799 * XXX - potential security hazard could
802 DprintQ((_res.options & RES_DEBUG) ||
803 (_res.pfcode & RES_PRF_REPLY),
804 (stdout, ";; not our server:\n"),
805 ans, (resplen>anssiz)?anssiz:resplen);
809 if (!(_res.options & RES_INSECURE2) &&
810 !res_queriesmatch(buf, buf + buflen,
811 ans, ans + anssiz)) {
813 * response contains wrong query? ignore it.
814 * XXX - potential security hazard could
817 DprintQ((_res.options & RES_DEBUG) ||
818 (_res.pfcode & RES_PRF_REPLY),
819 (stdout, ";; wrong query name:\n"),
820 ans, (resplen>anssiz)?anssiz:resplen);
823 if (anhp->rcode == SERVFAIL ||
824 anhp->rcode == NOTIMP ||
825 anhp->rcode == REFUSED) {
826 DprintQ(_res.options & RES_DEBUG,
827 (stdout, "server rejected query:\n"),
828 ans, (resplen>anssiz)?anssiz:resplen);
831 /* don't retry if called from dig */
835 if (!(_res.options & RES_IGNTC) && anhp->tc) {
837 * get rest of answer;
838 * use TCP with same server.
840 Dprint(_res.options & RES_DEBUG,
841 (stdout, ";; truncated answer\n"));
847 Dprint((_res.options & RES_DEBUG) ||
848 ((_res.pfcode & RES_PRF_REPLY) &&
849 (_res.pfcode & RES_PRF_HEAD1)),
850 (stdout, ";; got answer:\n"));
851 DprintQ((_res.options & RES_DEBUG) ||
852 (_res.pfcode & RES_PRF_REPLY),
853 (stdout, "%.*s", 0, ""),
854 ans, (resplen>anssiz)?anssiz:resplen);
856 * If using virtual circuits, we assume that the first server
857 * is preferred over the rest (i.e. it is on the local
858 * machine) and only keep that one open.
859 * If we have temporarily opened a virtual circuit,
860 * or if we haven't been asked to keep a socket open,
863 if ((v_circuit && (!(_res.options & RES_USEVC) || ns != 0)) ||
864 !(_res.options & RES_STAYOPEN)) {
868 int done = 0, loops = 0;
875 ans, anssiz, &resplen);
885 /* give the hook another try */
886 if (++loops < 42) /*doug adams*/
907 errno = ECONNREFUSED; /* no nameservers found */
909 errno = ETIMEDOUT; /* no answer obtained */
916 * This routine is for closing the socket if a virtual circuit is used and
917 * the program wants to close it. This provides support for endhostent()
918 * which expects to close the socket.
920 * This routine is not expected to be user visible.
935 * Weak aliases for applications that use certain private entry points,
936 * and fail to include <resolv.h>.
939 __weak_reference(__res_close, _res_close);
941 __weak_reference(__res_send, res_send);