2 * Copyright (c) 1999 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * Portions Copyright (c) 1999 Apple Computer, Inc. All Rights
7 * Reserved. This file contains Original Code and/or Modifications of
8 * Original Code as defined in and that are subject to the Apple Public
9 * Source License Version 1.1 (the "License"). You may not use this file
10 * except in compliance with the License. Please obtain a copy of the
11 * License at http://www.apple.com/publicsource and read it before using
14 * The Original Code and all software distributed under the License are
15 * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
16 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
17 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE OR NON- INFRINGEMENT. Please see the
19 * License for the specific language governing rights and limitations
22 * @APPLE_LICENSE_HEADER_END@
25 * ++Copyright++ 1985, 1989, 1993
27 * Copyright (c) 1985, 1989, 1993
28 * The Regents of the University of California. All rights reserved.
30 * Redistribution and use in source and binary forms, with or without
31 * modification, are permitted provided that the following conditions
33 * 1. Redistributions of source code must retain the above copyright
34 * notice, this list of conditions and the following disclaimer.
35 * 2. Redistributions in binary form must reproduce the above copyright
36 * notice, this list of conditions and the following disclaimer in the
37 * documentation and/or other materials provided with the distribution.
38 * 3. All advertising materials mentioning features or use of this software
39 * must display the following acknowledgement:
40 * This product includes software developed by the University of
41 * California, Berkeley and its contributors.
42 * 4. Neither the name of the University nor the names of its contributors
43 * may be used to endorse or promote products derived from this software
44 * without specific prior written permission.
46 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
47 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
48 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
49 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
50 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
51 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
52 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
53 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
54 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
55 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58 * Portions Copyright (c) 1993 by Digital Equipment Corporation.
60 * Permission to use, copy, modify, and distribute this software for any
61 * purpose with or without fee is hereby granted, provided that the above
62 * copyright notice and this permission notice appear in all copies, and that
63 * the name of Digital Equipment Corporation not be used in advertising or
64 * publicity pertaining to distribution of the document or software without
65 * specific, written prior permission.
67 * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
68 * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
69 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
70 * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
71 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
72 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
73 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
79 #if defined(LIBC_SCCS) && !defined(lint)
80 static char sccsid
[] = "@(#)res_send.c 8.1 (Berkeley) 6/4/93";
81 static char rcsid
[] = "$Id: res_send.c,v 1.6 2003/02/18 17:29:25 majka Exp $";
82 #endif /* LIBC_SCCS and not lint */
85 * if you talk to a lot
86 * of multi-homed SunOS
87 * ("broken") name servers.
89 #define CHECK_SRVR_ADDR 1 /* XXX - should be in options.h */
92 * Send query to name server and wait for reply.
95 #include <sys/param.h>
97 #include <sys/socket.h>
99 #include <netinet/in.h>
100 #include <arpa/nameser8_compat.h>
101 #include <arpa/inet.h>
108 #include <resolv8_compat.h>
109 #if defined(BSD) && (BSD >= 199306)
114 # include "portability.h"
117 #if defined(USE_OPTIONS_H)
118 # include "options.h"
121 void _res_close
__P((void));
123 static int s
= -1; /* socket used for communications */
124 static int connected
= 0; /* is the socket connected */
125 static int vc
= 0; /* is the socket a virtual ciruit? */
128 /* XXX - should be in portability.h */
130 #define FD_SETSIZE 32
131 #define FD_SET(n, p) ((p)->fds_bits[(n)/NFDBITS] |= (1 << ((n) % NFDBITS)))
132 #define FD_CLR(n, p) ((p)->fds_bits[(n)/NFDBITS] &= ~(1 << ((n) % NFDBITS)))
133 #define FD_ISSET(n, p) ((p)->fds_bits[(n)/NFDBITS] & (1 << ((n) % NFDBITS)))
134 #define FD_ZERO(p) bzero((char *)(p), sizeof(*(p)))
137 /* XXX - this should be done in portability.h */
138 #if (defined(BSD) && (BSD >= 199103)) || defined(linux)
139 # define CAN_RECONNECT 1
141 # define CAN_RECONNECT 0
145 # define Dprint(cond, args) /*empty*/
146 # define DprintQ(cond, args, query, size) /*empty*/
147 # define Aerror(file, string, error, address) /*empty*/
148 # define Perror(file, string, error) /*empty*/
150 # define Dprint(cond, args) if (cond) {fprintf args;} else {}
151 # define DprintQ(cond, args, query, size) if (cond) {\
153 __fp_nquery(query, size, stdout);\
156 Aerror(file
, string
, error
, address
)
160 struct sockaddr_in address
;
164 if (_res
.options
& RES_DEBUG
) {
165 fprintf(file
, "res_send: %s ([%s].%u): %s\n",
167 inet_ntoa(address
.sin_addr
),
168 ntohs(address
.sin_port
),
174 Perror(file
, string
, error
)
181 if (_res
.options
& RES_DEBUG
) {
182 fprintf(file
, "res_send: %s: %s\n",
183 string
, strerror(error
));
189 static res_send_qhook Qhook
= NULL
;
190 static res_send_rhook Rhook
= NULL
;
193 res_send_setqhook(hook
)
201 res_send_setrhook(hook
)
209 * res_isourserver(ina)
210 * looks up "ina" in _res.ns_addr_list[]
215 * paul vixie, 29may94
219 const struct sockaddr_in
*inp
;
221 struct sockaddr_in ina
;
222 register int ns
, ret
;
226 for (ns
= 0; ns
< _res
.nscount
; ns
++) {
227 register const struct sockaddr_in
*srv
= &_res
.nsaddr_list
[ns
];
229 if (srv
->sin_family
== ina
.sin_family
&&
230 srv
->sin_port
== ina
.sin_port
&&
231 (srv
->sin_addr
.s_addr
== INADDR_ANY
||
232 srv
->sin_addr
.s_addr
== ina
.sin_addr
.s_addr
)) {
241 * res_nameinquery(name, type, class, buf, eom)
242 * look for (name,type,class) in the query section of packet (buf,eom)
248 * paul vixie, 29may94
251 res_nameinquery(name
, type
, class, buf
, eom
)
253 register int type
, class;
254 const u_char
*buf
, *eom
;
256 register const u_char
*cp
= buf
+ HFIXEDSZ
;
257 int qdcount
= ntohs(((HEADER
*)buf
)->qdcount
);
259 while (qdcount
-- > 0) {
260 char tname
[MAXDNAME
+1];
261 register int n
, ttype
, tclass
;
263 n
= dn_expand(buf
, eom
, cp
, tname
, sizeof tname
);
267 ttype
= _getshort(cp
); cp
+= INT16SZ
;
268 tclass
= _getshort(cp
); cp
+= INT16SZ
;
271 strcasecmp(tname
, name
) == 0)
278 * res_queriesmatch(buf1, eom1, buf2, eom2)
279 * is there a 1:1 mapping of (name,type,class)
280 * in (buf1,eom1) and (buf2,eom2)?
283 * 0 : not a 1:1 mapping
284 * >0 : is a 1:1 mapping
286 * paul vixie, 29may94
289 res_queriesmatch(buf1
, eom1
, buf2
, eom2
)
290 const u_char
*buf1
, *eom1
;
291 const u_char
*buf2
, *eom2
;
293 register const u_char
*cp
= buf1
+ HFIXEDSZ
;
294 int qdcount
= ntohs(((HEADER
*)buf1
)->qdcount
);
296 if (qdcount
!= ntohs(((HEADER
*)buf2
)->qdcount
))
298 while (qdcount
-- > 0) {
299 char tname
[MAXDNAME
+1];
300 register int n
, ttype
, tclass
;
302 n
= dn_expand(buf1
, eom1
, cp
, tname
, sizeof tname
);
306 ttype
= _getshort(cp
); cp
+= INT16SZ
;
307 tclass
= _getshort(cp
); cp
+= INT16SZ
;
308 if (!res_nameinquery(tname
, ttype
, tclass
, buf2
, eom2
))
314 /* Returns whether a dns encoded name should be sent to multicast or not */
315 static int dns_is_local_name(const u_int8_t
*name
)
317 const u_int8_t
*d0
= NULL
; // Top-Level Domain
318 const u_int8_t
*d1
= NULL
; // Second-Level Domain
319 const u_int8_t
*d2
= NULL
; // etc.
320 const u_int8_t
*d3
= NULL
;
322 if (name
== NULL
) return 0;
333 // "local" domains need to be resolved with multicast
335 if (d0
[0] == 5 && strncasecmp((char *)d0
+1, "local", 5) == 0) return 1;
338 if (d1
&& d1
[0] == 5 && strncasecmp((char *)d1
+1, "local", 5) == 0 &&
339 d0
[0] == 4 && strncasecmp((char *)d0
+1, "arpa", 4) == 0) return 1;
342 if (d1
&& d1
[0] == 5 && strncasecmp((char *)d1
+1, "local", 5) == 0 &&
343 d0
[0] == 3 && strncasecmp((char *)d0
+1, "int", 3) == 0) return 1;
345 // The network 169.254/16 is defined to be link-local,
346 // so lookups in 254.169.in-addr.arpa. also need to be resolved with local multicast
347 if (d3
&& d3
[0] == 3 && strncasecmp((char *)d3
+1, "254", 3) == 0 &&
348 d2
&& d2
[0] == 3 && strncasecmp((char *)d2
+1, "169", 3) == 0 &&
349 d1
&& d1
[0] == 7 && strncasecmp((char *)d1
+1, "in-addr", 7) == 0 &&
350 d0
[0] == 4 && strncasecmp((char *)d0
+1, "arpa", 4) == 0) return 1;
355 #define DNS_LOCAL_DOMAIN_SERVICE_PORT 5353
356 #define DNS_HEADER_SIZE 12
358 #if BYTE_ORDER == BIG_ENDIAN
359 #define my_htons(x) (x)
360 #define my_htonl(x) (x)
362 #define my_htons(x) ((((u_int16_t)x) >> 8) | (((u_int16_t)x) << 8))
363 #define my_htonl(x) (((x) >> 24) | (((x) & 0x00FF0000) >> 16) | \
364 (((x) & 0x0000FF00) << 16) | ((x) << 24))
367 static const struct sockaddr_in mDNS_addr
=
371 my_htons(DNS_LOCAL_DOMAIN_SERVICE_PORT
),
372 {my_htonl(0xE00000FB)} /* 224.0.0.251 */
376 res_send(buf
, buflen
, ans
, anssiz
)
382 HEADER
*hp
= (HEADER
*) buf
;
383 HEADER
*anhp
= (HEADER
*) ans
;
384 int gotsomewhere
, connreset
, terrno
, try, v_circuit
, resplen
, ns
;
386 u_int badns
; /* XXX NSMAX can't exceed #/bits in this var */
389 if ((_res
.options
& RES_INIT
) == 0 && res_init() == -1) {
390 /* errno should have been set by res_init() in this case. */
393 DprintQ((_res
.options
& RES_DEBUG
) || (_res
.pfcode
& RES_PRF_QUERY
),
394 (stdout
, ";; res_send()\n"), buf
, buflen
);
395 v_circuit
= (_res
.options
& RES_USEVC
) || buflen
> PACKETSZ
;
401 if (dns_is_local_name((u_int8_t
*)(buf
+ DNS_HEADER_SIZE
))) {
410 * Send request, RETRY times, or until successful
412 for (try = 0; try < _res
.retry
; try++) {
413 for (ns
= 0; (multicast
== 0 && ns
< _res
.nscount
) ||
414 (multicast
== 1 && ns
< 1) ; ns
++) {
415 struct sockaddr_in
*nsap
;
417 nsap
= &_res
.nsaddr_list
[ns
];
419 nsap
= (struct sockaddr_in
*)&mDNS_addr
; /* const cast */
421 if (badns
& (1 << ns
)) {
427 int done
= 0, loops
= 0;
432 act
= (*Qhook
)(&nsap
, &buf
, &buflen
,
433 ans
, anssiz
, &resplen
);
444 /* give the hook another try */
445 if (++loops
< 42) /*doug adams*/
456 Dprint(_res
.options
& RES_DEBUG
,
457 (stdout
, ";; Querying server (# %d) address = %s\n",
458 ns
+ 1, inet_ntoa(nsap
->sin_addr
)));
467 * Use virtual circuit;
468 * at most one attempt per server.
472 if ((s
< 0) || (!vc
)) {
476 s
= socket(PF_INET
, SOCK_STREAM
, 0);
479 Perror(stderr
, "socket(vc)", errno
);
483 if (connect(s
, (struct sockaddr
*)nsap
,
484 sizeof(struct sockaddr
)) < 0) {
486 Aerror(stderr
, "connect/vc",
495 * Send length & message
497 putshort((u_short
)buflen
, (u_char
*)&len
);
498 iov
[0].iov_base
= (caddr_t
)&len
;
499 iov
[0].iov_len
= INT16SZ
;
500 iov
[1].iov_base
= (caddr_t
)buf
;
501 iov
[1].iov_len
= buflen
;
502 if (writev(s
, iov
, 2) != (INT16SZ
+ buflen
)) {
504 Perror(stderr
, "write failed", errno
);
510 * Receive length & response
514 while ((n
= read(s
, (char *)cp
, (int)len
)) > 0) {
521 Perror(stderr
, "read failed", errno
);
524 * A long running process might get its TCP
525 * connection reset if the remote server was
526 * restarted. Requery the server instead of
527 * trying a new one. When there is only one
528 * server, this means that a query might work
529 * instead of failing. We only allow one reset
530 * per query to prevent looping.
532 if (terrno
== ECONNRESET
&& !connreset
) {
540 resplen
= _getshort(ans
);
541 if (resplen
> anssiz
) {
542 Dprint(_res
.options
& RES_DEBUG
,
543 (stdout
, ";; response truncated\n")
551 (n
= read(s
, (char *)cp
, (int)len
)) > 0) {
557 Perror(stderr
, "read(vc)", errno
);
563 * Flush rest of answer
564 * so connection stays in synch.
567 len
= resplen
- anssiz
;
571 n
= (len
> sizeof(junk
)
574 if ((n
= read(s
, junk
, n
)) > 0)
584 struct timeval timeout
;
586 struct sockaddr_in from
;
587 unsigned int fromlen
;
592 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
598 Perror(stderr
, "socket(dg)", errno
);
604 * On a 4.3BSD+ machine (client and server,
605 * actually), sending to a nameserver datagram
606 * port with no nameserver will cause an
607 * ICMP port unreachable message to be returned.
608 * If our datagram socket is "connected" to the
609 * server, we get an ECONNREFUSED error on the next
610 * socket operation, and select returns if the
611 * error message is received. We can thus detect
612 * the absence of a nameserver without timing out.
613 * If we have sent queries to at least two servers,
614 * however, we don't want to remain connected,
615 * as we wish to receive answers from the first
618 if ((_res
.nscount
== 1 || (try == 0 && ns
== 0)) && multicast
== 0) {
620 * Connect only if we are sure we won't
621 * receive a response from another server.
624 if (connect(s
, (struct sockaddr
*)nsap
,
625 sizeof(struct sockaddr
)
636 if (send(s
, (char*)buf
, buflen
, 0) != buflen
) {
637 Perror(stderr
, "send", errno
);
644 * Disconnect if we want to listen
645 * for responses from more than one server.
649 struct sockaddr_in no_addr
;
651 no_addr
.sin_family
= AF_INET
;
652 no_addr
.sin_addr
.s_addr
= INADDR_ANY
;
653 no_addr
.sin_port
= 0;
659 int s1
= socket(PF_INET
, SOCK_DGRAM
,0);
664 Dprint(_res
.options
& RES_DEBUG
,
665 (stdout
, ";; new DG socket\n"))
672 struct ifaddrs
* addrs
;
673 struct ifaddrs
* curAddr
;
674 const int twofivefive
= 255;
676 // multicast packets with TTL 255
677 if(setsockopt(s
, IPPROTO_IP
, IP_MULTICAST_TTL
, &twofivefive
, sizeof(twofivefive
))) {
678 Perror(stderr
, "setsocketopt - IP_MULTICAST_TTL", errno
);
683 if (getifaddrs(&addrs
) != 0)
685 Perror(stderr
, "getifaddrs", errno
);
690 /* multicast should send request on all multicast capable interfaces */
691 for (curAddr
= addrs
; curAddr
!= NULL
; curAddr
= curAddr
->ifa_next
) {
692 if ((curAddr
->ifa_addr
->sa_family
) == AF_INET
&&
693 (curAddr
->ifa_flags
& IFF_MULTICAST
) != 0 &&
694 (curAddr
->ifa_flags
& IFF_POINTOPOINT
) == 0) {
695 struct in_addr
* if_ip_addr
= &((struct sockaddr_in
*)curAddr
->ifa_addr
)->sin_addr
;
697 if (setsockopt(s
, IPPROTO_IP
, IP_MULTICAST_IF
,
698 if_ip_addr
, sizeof(*if_ip_addr
)) != 0) {
700 Perror(stderr
, "setsocketopt - IP_MULTICAST_IF", errno
);
705 if (sendto(s
, (char*)buf
, buflen
, 0,
706 (struct sockaddr
*)nsap
, sizeof *nsap
) != buflen
)
709 Aerror(stderr
, "sendto", errno
, *nsap
);
718 if (sendto(s
, (char*)buf
, buflen
, 0,
719 (struct sockaddr
*)nsap
,
720 sizeof(struct sockaddr
))
722 Aerror(stderr
, "sendto", errno
, *nsap
);
733 timeout
.tv_sec
= (_res
.retrans
<< try);
735 timeout
.tv_sec
/= _res
.nscount
;
736 if ((long) timeout
.tv_sec
<= 0 || multicast
)
742 n
= select(s
+1, &dsmask
, (fd_set
*)NULL
,
743 (fd_set
*)NULL
, &timeout
);
745 Perror(stderr
, "select", errno
);
753 Dprint(_res
.options
& RES_DEBUG
,
754 (stdout
, ";; timeout\n"));
760 fromlen
= sizeof(struct sockaddr_in
);
761 resplen
= recvfrom(s
, (char*)ans
, anssiz
, 0,
762 (struct sockaddr
*)&from
, &fromlen
);
764 Perror(stderr
, "recvfrom", errno
);
769 if (hp
->id
!= anhp
->id
) {
771 * response from old query, ignore it.
772 * XXX - potential security hazard could
775 DprintQ((_res
.options
& RES_DEBUG
) ||
776 (_res
.pfcode
& RES_PRF_REPLY
),
777 (stdout
, ";; old answer:\n"),
782 if (!(_res
.options
& RES_INSECURE1
) &&
783 multicast
== 0 && !res_isourserver(&from
)) {
785 * response from wrong server? ignore it.
786 * XXX - potential security hazard could
789 DprintQ((_res
.options
& RES_DEBUG
) ||
790 (_res
.pfcode
& RES_PRF_REPLY
),
791 (stdout
, ";; not our server:\n"),
796 if (!(_res
.options
& RES_INSECURE2
) &&
797 !res_queriesmatch(buf
, buf
+ buflen
,
798 ans
, ans
+ anssiz
)) {
800 * response contains wrong query? ignore it.
801 * XXX - potential security hazard could
804 DprintQ((_res
.options
& RES_DEBUG
) ||
805 (_res
.pfcode
& RES_PRF_REPLY
),
806 (stdout
, ";; wrong query name:\n"),
810 if (anhp
->rcode
== SERVFAIL
||
811 anhp
->rcode
== NOTIMP
||
812 anhp
->rcode
== REFUSED
) {
813 DprintQ(_res
.options
& RES_DEBUG
,
814 (stdout
, "server rejected query:\n"),
818 /* don't retry if called from dig */
822 if (!(_res
.options
& RES_IGNTC
) && anhp
->tc
) {
824 * get rest of answer;
825 * use TCP with same server.
827 Dprint(_res
.options
& RES_DEBUG
,
828 (stdout
, ";; truncated answer\n"));
834 DprintQ((_res
.options
& RES_DEBUG
) ||
835 (_res
.pfcode
& RES_PRF_REPLY
),
836 (stdout
, ";; got answer:\n"),
839 * If using virtual circuits, we assume that the first server
840 * is preferred over the rest (i.e. it is on the local
841 * machine) and only keep that one open.
842 * If we have temporarily opened a virtual circuit,
843 * or if we haven't been asked to keep a socket open,
846 if ((v_circuit
&& (!(_res
.options
& RES_USEVC
) || ns
!= 0)) ||
847 !(_res
.options
& RES_STAYOPEN
)) {
851 int done
= 0, loops
= 0;
856 act
= (*Rhook
)(nsap
, buf
, buflen
,
857 ans
, anssiz
, &resplen
);
867 /* give the hook another try */
868 if (++loops
< 42) /*doug adams*/
886 errno
= ECONNREFUSED
; /* no nameservers found */
888 errno
= ETIMEDOUT
; /* no answer obtained */
895 * This routine is for closing the socket if a virtual circuit is used and
896 * the program wants to close it. This provides support for endhostent()
897 * which expects to close the socket.
899 * This routine is not expected to be user visible.