2 * Copyright (c) 1999 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved.
8 * This file contains Original Code and/or Modifications of Original Code
9 * as defined in and that are subject to the Apple Public Source License
10 * Version 2.0 (the 'License'). You may not use this file except in
11 * compliance with the License. Please obtain a copy of the License at
12 * http://www.opensource.apple.com/apsl/ and read it before using this
15 * The Original Code and all software distributed under the License are
16 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
17 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
18 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
20 * Please see the License for the specific language governing rights and
21 * limitations under the License.
23 * @APPLE_LICENSE_HEADER_END@
26 * ++Copyright++ 1985, 1989, 1993
28 * Copyright (c) 1985, 1989, 1993
29 * The Regents of the University of California. All rights reserved.
31 * Redistribution and use in source and binary forms, with or without
32 * modification, are permitted provided that the following conditions
34 * 1. Redistributions of source code must retain the above copyright
35 * notice, this list of conditions and the following disclaimer.
36 * 2. Redistributions in binary form must reproduce the above copyright
37 * notice, this list of conditions and the following disclaimer in the
38 * documentation and/or other materials provided with the distribution.
39 * 3. All advertising materials mentioning features or use of this software
40 * must display the following acknowledgement:
41 * This product includes software developed by the University of
42 * California, Berkeley and its contributors.
43 * 4. Neither the name of the University nor the names of its contributors
44 * may be used to endorse or promote products derived from this software
45 * without specific prior written permission.
47 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
48 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
49 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
50 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
51 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
52 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
53 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
54 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
55 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
56 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
59 * Portions Copyright (c) 1993 by Digital Equipment Corporation.
61 * Permission to use, copy, modify, and distribute this software for any
62 * purpose with or without fee is hereby granted, provided that the above
63 * copyright notice and this permission notice appear in all copies, and that
64 * the name of Digital Equipment Corporation not be used in advertising or
65 * publicity pertaining to distribution of the document or software without
66 * specific, written prior permission.
68 * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
69 * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
70 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
71 * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
72 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
73 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
74 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
80 #if defined(LIBC_SCCS) && !defined(lint)
81 static char sccsid
[] = "@(#)res_send.c 8.1 (Berkeley) 6/4/93";
82 static char rcsid
[] = "$Id: res_send.c,v 1.6 2003/02/18 17:29:25 majka Exp $";
83 #endif /* LIBC_SCCS and not lint */
86 * if you talk to a lot
87 * of multi-homed SunOS
88 * ("broken") name servers.
90 #define CHECK_SRVR_ADDR 1 /* XXX - should be in options.h */
93 * Send query to name server and wait for reply.
96 #include <sys/param.h>
98 #include <sys/socket.h>
100 #include <netinet/in.h>
101 #include <arpa/nameser8_compat.h>
102 #include <arpa/inet.h>
109 #include <resolv8_compat.h>
110 #if defined(BSD) && (BSD >= 199306)
115 # include "portability.h"
118 #if defined(USE_OPTIONS_H)
119 # include "options.h"
122 void _res_close
__P((void));
124 static int s
= -1; /* socket used for communications */
125 static int connected
= 0; /* is the socket connected */
126 static int vc
= 0; /* is the socket a virtual ciruit? */
129 /* XXX - should be in portability.h */
131 #define FD_SETSIZE 32
132 #define FD_SET(n, p) ((p)->fds_bits[(n)/NFDBITS] |= (1 << ((n) % NFDBITS)))
133 #define FD_CLR(n, p) ((p)->fds_bits[(n)/NFDBITS] &= ~(1 << ((n) % NFDBITS)))
134 #define FD_ISSET(n, p) ((p)->fds_bits[(n)/NFDBITS] & (1 << ((n) % NFDBITS)))
135 #define FD_ZERO(p) bzero((char *)(p), sizeof(*(p)))
138 /* XXX - this should be done in portability.h */
139 #if (defined(BSD) && (BSD >= 199103)) || defined(linux)
140 # define CAN_RECONNECT 1
142 # define CAN_RECONNECT 0
146 # define Dprint(cond, args) /*empty*/
147 # define DprintQ(cond, args, query, size) /*empty*/
148 # define Aerror(file, string, error, address) /*empty*/
149 # define Perror(file, string, error) /*empty*/
151 # define Dprint(cond, args) if (cond) {fprintf args;} else {}
152 # define DprintQ(cond, args, query, size) if (cond) {\
154 __fp_nquery(query, size, stdout);\
157 Aerror(file
, string
, error
, address
)
161 struct sockaddr_in address
;
165 if (_res
.options
& RES_DEBUG
) {
166 fprintf(file
, "res_send: %s ([%s].%u): %s\n",
168 inet_ntoa(address
.sin_addr
),
169 ntohs(address
.sin_port
),
175 Perror(file
, string
, error
)
182 if (_res
.options
& RES_DEBUG
) {
183 fprintf(file
, "res_send: %s: %s\n",
184 string
, strerror(error
));
190 static res_send_qhook Qhook
= NULL
;
191 static res_send_rhook Rhook
= NULL
;
194 res_send_setqhook(hook
)
202 res_send_setrhook(hook
)
210 * res_isourserver(ina)
211 * looks up "ina" in _res.ns_addr_list[]
216 * paul vixie, 29may94
220 const struct sockaddr_in
*inp
;
222 struct sockaddr_in ina
;
223 register int ns
, ret
;
227 for (ns
= 0; ns
< _res
.nscount
; ns
++) {
228 register const struct sockaddr_in
*srv
= &_res
.nsaddr_list
[ns
];
230 if (srv
->sin_family
== ina
.sin_family
&&
231 srv
->sin_port
== ina
.sin_port
&&
232 (srv
->sin_addr
.s_addr
== INADDR_ANY
||
233 srv
->sin_addr
.s_addr
== ina
.sin_addr
.s_addr
)) {
242 * res_nameinquery(name, type, class, buf, eom)
243 * look for (name,type,class) in the query section of packet (buf,eom)
249 * paul vixie, 29may94
252 res_nameinquery(name
, type
, class, buf
, eom
)
254 register int type
, class;
255 const u_char
*buf
, *eom
;
257 register const u_char
*cp
= buf
+ HFIXEDSZ
;
258 int qdcount
= ntohs(((HEADER
*)buf
)->qdcount
);
260 while (qdcount
-- > 0) {
261 char tname
[MAXDNAME
+1];
262 register int n
, ttype
, tclass
;
264 n
= dn_expand(buf
, eom
, cp
, tname
, sizeof tname
);
268 ttype
= _getshort(cp
); cp
+= INT16SZ
;
269 tclass
= _getshort(cp
); cp
+= INT16SZ
;
272 strcasecmp(tname
, name
) == 0)
279 * res_queriesmatch(buf1, eom1, buf2, eom2)
280 * is there a 1:1 mapping of (name,type,class)
281 * in (buf1,eom1) and (buf2,eom2)?
284 * 0 : not a 1:1 mapping
285 * >0 : is a 1:1 mapping
287 * paul vixie, 29may94
290 res_queriesmatch(buf1
, eom1
, buf2
, eom2
)
291 const u_char
*buf1
, *eom1
;
292 const u_char
*buf2
, *eom2
;
294 register const u_char
*cp
= buf1
+ HFIXEDSZ
;
295 int qdcount
= ntohs(((HEADER
*)buf1
)->qdcount
);
297 if (qdcount
!= ntohs(((HEADER
*)buf2
)->qdcount
))
299 while (qdcount
-- > 0) {
300 char tname
[MAXDNAME
+1];
301 register int n
, ttype
, tclass
;
303 n
= dn_expand(buf1
, eom1
, cp
, tname
, sizeof tname
);
307 ttype
= _getshort(cp
); cp
+= INT16SZ
;
308 tclass
= _getshort(cp
); cp
+= INT16SZ
;
309 if (!res_nameinquery(tname
, ttype
, tclass
, buf2
, eom2
))
315 /* Returns whether a dns encoded name should be sent to multicast or not */
316 static int dns_is_local_name(const u_int8_t
*name
)
318 const u_int8_t
*d0
= NULL
; // Top-Level Domain
319 const u_int8_t
*d1
= NULL
; // Second-Level Domain
320 const u_int8_t
*d2
= NULL
; // etc.
321 const u_int8_t
*d3
= NULL
;
323 if (name
== NULL
) return 0;
334 // "local" domains need to be resolved with multicast
336 if (d0
[0] == 5 && strncasecmp((char *)d0
+1, "local", 5) == 0) return 1;
339 if (d1
&& d1
[0] == 5 && strncasecmp((char *)d1
+1, "local", 5) == 0 &&
340 d0
[0] == 4 && strncasecmp((char *)d0
+1, "arpa", 4) == 0) return 1;
343 if (d1
&& d1
[0] == 5 && strncasecmp((char *)d1
+1, "local", 5) == 0 &&
344 d0
[0] == 3 && strncasecmp((char *)d0
+1, "int", 3) == 0) return 1;
346 // The network 169.254/16 is defined to be link-local,
347 // so lookups in 254.169.in-addr.arpa. also need to be resolved with local multicast
348 if (d3
&& d3
[0] == 3 && strncasecmp((char *)d3
+1, "254", 3) == 0 &&
349 d2
&& d2
[0] == 3 && strncasecmp((char *)d2
+1, "169", 3) == 0 &&
350 d1
&& d1
[0] == 7 && strncasecmp((char *)d1
+1, "in-addr", 7) == 0 &&
351 d0
[0] == 4 && strncasecmp((char *)d0
+1, "arpa", 4) == 0) return 1;
356 #define DNS_LOCAL_DOMAIN_SERVICE_PORT 5353
357 #define DNS_HEADER_SIZE 12
359 #if BYTE_ORDER == BIG_ENDIAN
360 #define my_htons(x) (x)
361 #define my_htonl(x) (x)
363 #define my_htons(x) ((((u_int16_t)x) >> 8) | (((u_int16_t)x) << 8))
364 #define my_htonl(x) (((x) >> 24) | (((x) & 0x00FF0000) >> 16) | \
365 (((x) & 0x0000FF00) << 16) | ((x) << 24))
368 static const struct sockaddr_in mDNS_addr
=
372 my_htons(DNS_LOCAL_DOMAIN_SERVICE_PORT
),
373 {my_htonl(0xE00000FB)} /* 224.0.0.251 */
377 res_send(buf
, buflen
, ans
, anssiz
)
383 HEADER
*hp
= (HEADER
*) buf
;
384 HEADER
*anhp
= (HEADER
*) ans
;
385 int gotsomewhere
, connreset
, terrno
, try, v_circuit
, resplen
, ns
;
387 u_int badns
; /* XXX NSMAX can't exceed #/bits in this var */
390 if ((_res
.options
& RES_INIT
) == 0 && res_init() == -1) {
391 /* errno should have been set by res_init() in this case. */
394 DprintQ((_res
.options
& RES_DEBUG
) || (_res
.pfcode
& RES_PRF_QUERY
),
395 (stdout
, ";; res_send()\n"), buf
, buflen
);
396 v_circuit
= (_res
.options
& RES_USEVC
) || buflen
> PACKETSZ
;
402 if (dns_is_local_name((u_int8_t
*)(buf
+ DNS_HEADER_SIZE
))) {
411 * Send request, RETRY times, or until successful
413 for (try = 0; try < _res
.retry
; try++) {
414 for (ns
= 0; (multicast
== 0 && ns
< _res
.nscount
) ||
415 (multicast
== 1 && ns
< 1) ; ns
++) {
416 struct sockaddr_in
*nsap
;
418 nsap
= &_res
.nsaddr_list
[ns
];
420 nsap
= (struct sockaddr_in
*)&mDNS_addr
; /* const cast */
422 if (badns
& (1 << ns
)) {
428 int done
= 0, loops
= 0;
433 act
= (*Qhook
)(&nsap
, &buf
, &buflen
,
434 ans
, anssiz
, &resplen
);
445 /* give the hook another try */
446 if (++loops
< 42) /*doug adams*/
457 Dprint(_res
.options
& RES_DEBUG
,
458 (stdout
, ";; Querying server (# %d) address = %s\n",
459 ns
+ 1, inet_ntoa(nsap
->sin_addr
)));
468 * Use virtual circuit;
469 * at most one attempt per server.
473 if ((s
< 0) || (!vc
)) {
477 s
= socket(PF_INET
, SOCK_STREAM
, 0);
480 Perror(stderr
, "socket(vc)", errno
);
484 if (connect(s
, (struct sockaddr
*)nsap
,
485 sizeof(struct sockaddr
)) < 0) {
487 Aerror(stderr
, "connect/vc",
496 * Send length & message
498 putshort((u_short
)buflen
, (u_char
*)&len
);
499 iov
[0].iov_base
= (caddr_t
)&len
;
500 iov
[0].iov_len
= INT16SZ
;
501 iov
[1].iov_base
= (caddr_t
)buf
;
502 iov
[1].iov_len
= buflen
;
503 if (writev(s
, iov
, 2) != (INT16SZ
+ buflen
)) {
505 Perror(stderr
, "write failed", errno
);
511 * Receive length & response
515 while ((n
= read(s
, (char *)cp
, (int)len
)) > 0) {
522 Perror(stderr
, "read failed", errno
);
525 * A long running process might get its TCP
526 * connection reset if the remote server was
527 * restarted. Requery the server instead of
528 * trying a new one. When there is only one
529 * server, this means that a query might work
530 * instead of failing. We only allow one reset
531 * per query to prevent looping.
533 if (terrno
== ECONNRESET
&& !connreset
) {
541 resplen
= _getshort(ans
);
542 if (resplen
> anssiz
) {
543 Dprint(_res
.options
& RES_DEBUG
,
544 (stdout
, ";; response truncated\n")
552 (n
= read(s
, (char *)cp
, (int)len
)) > 0) {
558 Perror(stderr
, "read(vc)", errno
);
564 * Flush rest of answer
565 * so connection stays in synch.
568 len
= resplen
- anssiz
;
572 n
= (len
> sizeof(junk
)
575 if ((n
= read(s
, junk
, n
)) > 0)
585 struct timeval timeout
;
587 struct sockaddr_in from
;
593 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
599 Perror(stderr
, "socket(dg)", errno
);
605 * On a 4.3BSD+ machine (client and server,
606 * actually), sending to a nameserver datagram
607 * port with no nameserver will cause an
608 * ICMP port unreachable message to be returned.
609 * If our datagram socket is "connected" to the
610 * server, we get an ECONNREFUSED error on the next
611 * socket operation, and select returns if the
612 * error message is received. We can thus detect
613 * the absence of a nameserver without timing out.
614 * If we have sent queries to at least two servers,
615 * however, we don't want to remain connected,
616 * as we wish to receive answers from the first
619 if ((_res
.nscount
== 1 || (try == 0 && ns
== 0)) && multicast
== 0) {
621 * Connect only if we are sure we won't
622 * receive a response from another server.
625 if (connect(s
, (struct sockaddr
*)nsap
,
626 sizeof(struct sockaddr
)
637 if (send(s
, (char*)buf
, buflen
, 0) != buflen
) {
638 Perror(stderr
, "send", errno
);
645 * Disconnect if we want to listen
646 * for responses from more than one server.
650 struct sockaddr_in no_addr
;
652 no_addr
.sin_family
= AF_INET
;
653 no_addr
.sin_addr
.s_addr
= INADDR_ANY
;
654 no_addr
.sin_port
= 0;
660 int s1
= socket(PF_INET
, SOCK_DGRAM
,0);
665 Dprint(_res
.options
& RES_DEBUG
,
666 (stdout
, ";; new DG socket\n"))
673 struct ifaddrs
* addrs
;
674 struct ifaddrs
* curAddr
;
675 const int twofivefive
= 255;
677 // multicast packets with TTL 255
678 if(setsockopt(s
, IPPROTO_IP
, IP_MULTICAST_TTL
, &twofivefive
, sizeof(twofivefive
))) {
679 Perror(stderr
, "setsocketopt - IP_MULTICAST_TTL", errno
);
684 if (getifaddrs(&addrs
) != 0)
686 Perror(stderr
, "getifaddrs", errno
);
691 /* multicast should send request on all multicast capable interfaces */
692 for (curAddr
= addrs
; curAddr
!= NULL
; curAddr
= curAddr
->ifa_next
) {
693 if ((curAddr
->ifa_addr
->sa_family
) == AF_INET
&&
694 (curAddr
->ifa_flags
& IFF_MULTICAST
) != 0 &&
695 (curAddr
->ifa_flags
& IFF_POINTOPOINT
) == 0) {
696 struct in_addr
* if_ip_addr
= &((struct sockaddr_in
*)curAddr
->ifa_addr
)->sin_addr
;
698 if (setsockopt(s
, IPPROTO_IP
, IP_MULTICAST_IF
,
699 if_ip_addr
, sizeof(*if_ip_addr
)) != 0) {
701 Perror(stderr
, "setsocketopt - IP_MULTICAST_IF", errno
);
706 if (sendto(s
, (char*)buf
, buflen
, 0,
707 (struct sockaddr
*)nsap
, sizeof *nsap
) != buflen
)
710 Aerror(stderr
, "sendto", errno
, *nsap
);
719 if (sendto(s
, (char*)buf
, buflen
, 0,
720 (struct sockaddr
*)nsap
,
721 sizeof(struct sockaddr
))
723 Aerror(stderr
, "sendto", errno
, *nsap
);
734 timeout
.tv_sec
= (_res
.retrans
<< try);
736 timeout
.tv_sec
/= _res
.nscount
;
737 if ((long) timeout
.tv_sec
<= 0 || multicast
)
743 n
= select(s
+1, &dsmask
, (fd_set
*)NULL
,
744 (fd_set
*)NULL
, &timeout
);
746 Perror(stderr
, "select", errno
);
754 Dprint(_res
.options
& RES_DEBUG
,
755 (stdout
, ";; timeout\n"));
761 fromlen
= sizeof(struct sockaddr_in
);
762 resplen
= recvfrom(s
, (char*)ans
, anssiz
, 0,
763 (struct sockaddr
*)&from
, &fromlen
);
765 Perror(stderr
, "recvfrom", errno
);
770 if (hp
->id
!= anhp
->id
) {
772 * response from old query, ignore it.
773 * XXX - potential security hazard could
776 DprintQ((_res
.options
& RES_DEBUG
) ||
777 (_res
.pfcode
& RES_PRF_REPLY
),
778 (stdout
, ";; old answer:\n"),
783 if (!(_res
.options
& RES_INSECURE1
) &&
784 multicast
== 0 && !res_isourserver(&from
)) {
786 * response from wrong server? ignore it.
787 * XXX - potential security hazard could
790 DprintQ((_res
.options
& RES_DEBUG
) ||
791 (_res
.pfcode
& RES_PRF_REPLY
),
792 (stdout
, ";; not our server:\n"),
797 if (!(_res
.options
& RES_INSECURE2
) &&
798 !res_queriesmatch(buf
, buf
+ buflen
,
799 ans
, ans
+ anssiz
)) {
801 * response contains wrong query? ignore it.
802 * XXX - potential security hazard could
805 DprintQ((_res
.options
& RES_DEBUG
) ||
806 (_res
.pfcode
& RES_PRF_REPLY
),
807 (stdout
, ";; wrong query name:\n"),
811 if (anhp
->rcode
== SERVFAIL
||
812 anhp
->rcode
== NOTIMP
||
813 anhp
->rcode
== REFUSED
) {
814 DprintQ(_res
.options
& RES_DEBUG
,
815 (stdout
, "server rejected query:\n"),
819 /* don't retry if called from dig */
823 if (!(_res
.options
& RES_IGNTC
) && anhp
->tc
) {
825 * get rest of answer;
826 * use TCP with same server.
828 Dprint(_res
.options
& RES_DEBUG
,
829 (stdout
, ";; truncated answer\n"));
835 DprintQ((_res
.options
& RES_DEBUG
) ||
836 (_res
.pfcode
& RES_PRF_REPLY
),
837 (stdout
, ";; got answer:\n"),
840 * If using virtual circuits, we assume that the first server
841 * is preferred over the rest (i.e. it is on the local
842 * machine) and only keep that one open.
843 * If we have temporarily opened a virtual circuit,
844 * or if we haven't been asked to keep a socket open,
847 if ((v_circuit
&& (!(_res
.options
& RES_USEVC
) || ns
!= 0)) ||
848 !(_res
.options
& RES_STAYOPEN
)) {
852 int done
= 0, loops
= 0;
857 act
= (*Rhook
)(nsap
, buf
, buflen
,
858 ans
, anssiz
, &resplen
);
868 /* give the hook another try */
869 if (++loops
< 42) /*doug adams*/
887 errno
= ECONNREFUSED
; /* no nameservers found */
889 errno
= ETIMEDOUT
; /* no answer obtained */
896 * This routine is for closing the socket if a virtual circuit is used and
897 * the program wants to close it. This provides support for endhostent()
898 * which expects to close the socket.
900 * This routine is not expected to be user visible.