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.2.202.1 2002/11/06 17:30:17 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/nameser.h>
101 #include <arpa/inet.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 extern struct __res_state _res_shadow
;
191 static res_send_qhook Qhook
= NULL
;
192 static res_send_rhook Rhook
= NULL
;
195 res_send_setqhook(hook
)
203 res_send_setrhook(hook
)
211 * res_isourserver(ina)
212 * looks up "ina" in _res.ns_addr_list[]
217 * paul vixie, 29may94
221 const struct sockaddr_in
*inp
;
223 struct sockaddr_in ina
;
224 register int ns
, ret
;
228 for (ns
= 0; ns
< _res
.nscount
; ns
++) {
229 register const struct sockaddr_in
*srv
= &_res
.nsaddr_list
[ns
];
231 if (srv
->sin_family
== ina
.sin_family
&&
232 srv
->sin_port
== ina
.sin_port
&&
233 (srv
->sin_addr
.s_addr
== INADDR_ANY
||
234 srv
->sin_addr
.s_addr
== ina
.sin_addr
.s_addr
)) {
243 * res_nameinquery(name, type, class, buf, eom)
244 * look for (name,type,class) in the query section of packet (buf,eom)
250 * paul vixie, 29may94
253 res_nameinquery(name
, type
, class, buf
, eom
)
255 register int type
, class;
256 const u_char
*buf
, *eom
;
258 register const u_char
*cp
= buf
+ HFIXEDSZ
;
259 int qdcount
= ntohs(((HEADER
*)buf
)->qdcount
);
261 while (qdcount
-- > 0) {
262 char tname
[MAXDNAME
+1];
263 register int n
, ttype
, tclass
;
265 n
= dn_expand(buf
, eom
, cp
, tname
, sizeof tname
);
269 ttype
= _getshort(cp
); cp
+= INT16SZ
;
270 tclass
= _getshort(cp
); cp
+= INT16SZ
;
273 strcasecmp(tname
, name
) == 0)
280 * res_queriesmatch(buf1, eom1, buf2, eom2)
281 * is there a 1:1 mapping of (name,type,class)
282 * in (buf1,eom1) and (buf2,eom2)?
285 * 0 : not a 1:1 mapping
286 * >0 : is a 1:1 mapping
288 * paul vixie, 29may94
291 res_queriesmatch(buf1
, eom1
, buf2
, eom2
)
292 const u_char
*buf1
, *eom1
;
293 const u_char
*buf2
, *eom2
;
295 register const u_char
*cp
= buf1
+ HFIXEDSZ
;
296 int qdcount
= ntohs(((HEADER
*)buf1
)->qdcount
);
298 if (qdcount
!= ntohs(((HEADER
*)buf2
)->qdcount
))
300 while (qdcount
-- > 0) {
301 char tname
[MAXDNAME
+1];
302 register int n
, ttype
, tclass
;
304 n
= dn_expand(buf1
, eom1
, cp
, tname
, sizeof tname
);
308 ttype
= _getshort(cp
); cp
+= INT16SZ
;
309 tclass
= _getshort(cp
); cp
+= INT16SZ
;
310 if (!res_nameinquery(tname
, ttype
, tclass
, buf2
, eom2
))
316 static int res_using_defaults()
320 if (_res
.nscount
!= _res_shadow
.nscount
)
323 for (i
= 0; i
< _res
.nscount
; i
++) {
324 /* Check that the address and port have not changed */
325 if ((_res
.nsaddr_list
[i
].sin_addr
.s_addr
!=
326 _res_shadow
.nsaddr_list
[i
].sin_addr
.s_addr
) ||
327 (_res
.nsaddr_list
[i
].sin_port
!=
328 _res_shadow
.nsaddr_list
[i
].sin_port
)) {
336 /* Returns whether a dns encoded name should be sent to multicast or not */
337 static int dns_is_local_name(const u_int8_t
*name
)
339 const u_int8_t
*d0
= NULL
; // Top-Level Domain
340 const u_int8_t
*d1
= NULL
; // Second-Level Domain
341 const u_int8_t
*d2
= NULL
; // etc.
342 const u_int8_t
*d3
= NULL
;
353 // "local" domains need to be resolved with multicast
355 if (d0
[0] == 5 && strncasecmp((char *)d0
+1, "local", 5) == 0) return 1;
358 if (d1
&& d1
[0] == 5 && strncasecmp((char *)d1
+1, "local", 5) == 0 &&
359 d0
[0] == 4 && strncasecmp((char *)d0
+1, "arpa", 4) == 0) return 1;
362 if (d1
&& d1
[0] == 5 && strncasecmp((char *)d1
+1, "local", 5) == 0 &&
363 d0
[0] == 3 && strncasecmp((char *)d0
+1, "int", 3) == 0) return 1;
365 // The network 169.254/16 is defined to be link-local,
366 // so lookups in 254.169.in-addr.arpa. also need to be resolved with local multicast
367 if (d3
&& d3
[0] == 3 && strncasecmp((char *)d3
+1, "254", 3) == 0 &&
368 d2
&& d2
[0] == 3 && strncasecmp((char *)d2
+1, "169", 3) == 0 &&
369 d1
&& d1
[0] == 7 && strncasecmp((char *)d1
+1, "in-addr", 7) == 0 &&
370 d0
[0] == 4 && strncasecmp((char *)d0
+1, "arpa", 4) == 0) return 1;
375 #define DNS_LOCAL_DOMAIN_SERVICE_PORT 5353
376 #define DNS_HEADER_SIZE 12
378 #if BYTE_ORDER == BIG_ENDIAN
379 #define my_htons(x) (x)
380 #define my_htonl(x) (x)
382 #define my_htons(x) ((((u_int16_t)x) >> 8) | (((u_int16_t)x) << 8))
383 #define my_htonl(x) (((x) >> 24) | (((x) & 0x00FF0000) >> 16) | \
384 (((x) & 0x0000FF00) << 16) | ((x) << 24))
387 static const struct sockaddr_in mDNS_addr
=
391 my_htons(DNS_LOCAL_DOMAIN_SERVICE_PORT
),
392 {my_htonl(0xE00000FB)} /* 224.0.0.251 */
396 res_send(buf
, buflen
, ans
, anssiz
)
402 HEADER
*hp
= (HEADER
*) buf
;
403 HEADER
*anhp
= (HEADER
*) ans
;
404 int gotsomewhere
, connreset
, terrno
, try, v_circuit
, resplen
, ns
;
406 u_int badns
; /* XXX NSMAX can't exceed #/bits in this var */
409 if ((_res
.options
& RES_INIT
) == 0 && res_init() == -1) {
410 /* errno should have been set by res_init() in this case. */
413 DprintQ((_res
.options
& RES_DEBUG
) || (_res
.pfcode
& RES_PRF_QUERY
),
414 (stdout
, ";; res_send()\n"), buf
, buflen
);
415 v_circuit
= (_res
.options
& RES_USEVC
) || buflen
> PACKETSZ
;
421 if (res_using_defaults() &&
422 dns_is_local_name((u_int8_t
*)(buf
+ DNS_HEADER_SIZE
))) {
431 * Send request, RETRY times, or until successful
433 for (try = 0; try < _res
.retry
; try++) {
434 for (ns
= 0; (multicast
== 0 && ns
< _res
.nscount
) ||
435 (multicast
== 1 && ns
< 1) ; ns
++) {
436 struct sockaddr_in
*nsap
;
438 nsap
= &_res
.nsaddr_list
[ns
];
440 nsap
= (struct sockaddr_in
*)&mDNS_addr
; /* const cast */
442 if (badns
& (1 << ns
)) {
448 int done
= 0, loops
= 0;
453 act
= (*Qhook
)(&nsap
, &buf
, &buflen
,
454 ans
, anssiz
, &resplen
);
465 /* give the hook another try */
466 if (++loops
< 42) /*doug adams*/
477 Dprint(_res
.options
& RES_DEBUG
,
478 (stdout
, ";; Querying server (# %d) address = %s\n",
479 ns
+ 1, inet_ntoa(nsap
->sin_addr
)));
488 * Use virtual circuit;
489 * at most one attempt per server.
493 if ((s
< 0) || (!vc
)) {
497 s
= socket(PF_INET
, SOCK_STREAM
, 0);
500 Perror(stderr
, "socket(vc)", errno
);
504 if (connect(s
, (struct sockaddr
*)nsap
,
505 sizeof(struct sockaddr
)) < 0) {
507 Aerror(stderr
, "connect/vc",
516 * Send length & message
518 putshort((u_short
)buflen
, (u_char
*)&len
);
519 iov
[0].iov_base
= (caddr_t
)&len
;
520 iov
[0].iov_len
= INT16SZ
;
521 iov
[1].iov_base
= (caddr_t
)buf
;
522 iov
[1].iov_len
= buflen
;
523 if (writev(s
, iov
, 2) != (INT16SZ
+ buflen
)) {
525 Perror(stderr
, "write failed", errno
);
531 * Receive length & response
535 while ((n
= read(s
, (char *)cp
, (int)len
)) > 0) {
542 Perror(stderr
, "read failed", errno
);
545 * A long running process might get its TCP
546 * connection reset if the remote server was
547 * restarted. Requery the server instead of
548 * trying a new one. When there is only one
549 * server, this means that a query might work
550 * instead of failing. We only allow one reset
551 * per query to prevent looping.
553 if (terrno
== ECONNRESET
&& !connreset
) {
561 resplen
= _getshort(ans
);
562 if (resplen
> anssiz
) {
563 Dprint(_res
.options
& RES_DEBUG
,
564 (stdout
, ";; response truncated\n")
572 (n
= read(s
, (char *)cp
, (int)len
)) > 0) {
578 Perror(stderr
, "read(vc)", errno
);
584 * Flush rest of answer
585 * so connection stays in synch.
588 len
= resplen
- anssiz
;
592 n
= (len
> sizeof(junk
)
595 if ((n
= read(s
, junk
, n
)) > 0)
605 struct timeval timeout
;
607 struct sockaddr_in from
;
613 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
619 Perror(stderr
, "socket(dg)", errno
);
625 * On a 4.3BSD+ machine (client and server,
626 * actually), sending to a nameserver datagram
627 * port with no nameserver will cause an
628 * ICMP port unreachable message to be returned.
629 * If our datagram socket is "connected" to the
630 * server, we get an ECONNREFUSED error on the next
631 * socket operation, and select returns if the
632 * error message is received. We can thus detect
633 * the absence of a nameserver without timing out.
634 * If we have sent queries to at least two servers,
635 * however, we don't want to remain connected,
636 * as we wish to receive answers from the first
639 if ((_res
.nscount
== 1 || (try == 0 && ns
== 0)) && multicast
== 0) {
641 * Connect only if we are sure we won't
642 * receive a response from another server.
645 if (connect(s
, (struct sockaddr
*)nsap
,
646 sizeof(struct sockaddr
)
657 if (send(s
, (char*)buf
, buflen
, 0) != buflen
) {
658 Perror(stderr
, "send", errno
);
665 * Disconnect if we want to listen
666 * for responses from more than one server.
670 struct sockaddr_in no_addr
;
672 no_addr
.sin_family
= AF_INET
;
673 no_addr
.sin_addr
.s_addr
= INADDR_ANY
;
674 no_addr
.sin_port
= 0;
680 int s1
= socket(PF_INET
, SOCK_DGRAM
,0);
685 Dprint(_res
.options
& RES_DEBUG
,
686 (stdout
, ";; new DG socket\n"))
693 struct ifaddrs
* addrs
;
694 struct ifaddrs
* curAddr
;
695 const int twofivefive
= 255;
697 // multicast packets with TTL 255
698 if(setsockopt(s
, IPPROTO_IP
, IP_MULTICAST_TTL
, &twofivefive
, sizeof(twofivefive
))) {
699 Perror(stderr
, "setsocketopt - IP_MULTICAST_TTL", errno
);
704 if (getifaddrs(&addrs
) != 0)
706 Perror(stderr
, "getifaddrs", errno
);
711 /* multicast should send request on all multicast capable interfaces */
712 for (curAddr
= addrs
; curAddr
!= NULL
; curAddr
= curAddr
->ifa_next
) {
713 if ((curAddr
->ifa_addr
->sa_family
) == AF_INET
&&
714 (curAddr
->ifa_flags
& IFF_MULTICAST
) != 0 &&
715 (curAddr
->ifa_flags
& IFF_POINTOPOINT
) == 0) {
716 struct in_addr
* if_ip_addr
= &((struct sockaddr_in
*)curAddr
->ifa_addr
)->sin_addr
;
718 if (setsockopt(s
, IPPROTO_IP
, IP_MULTICAST_IF
,
719 if_ip_addr
, sizeof(*if_ip_addr
)) != 0) {
721 Perror(stderr
, "setsocketopt - IP_MULTICAST_IF", errno
);
726 if (sendto(s
, (char*)buf
, buflen
, 0,
727 (struct sockaddr
*)nsap
, sizeof *nsap
) != buflen
)
730 Aerror(stderr
, "sendto", errno
, *nsap
);
739 if (sendto(s
, (char*)buf
, buflen
, 0,
740 (struct sockaddr
*)nsap
,
741 sizeof(struct sockaddr
))
743 Aerror(stderr
, "sendto", errno
, *nsap
);
754 timeout
.tv_sec
= (_res
.retrans
<< try);
756 timeout
.tv_sec
/= _res
.nscount
;
757 if ((long) timeout
.tv_sec
<= 0 || multicast
)
763 n
= select(s
+1, &dsmask
, (fd_set
*)NULL
,
764 (fd_set
*)NULL
, &timeout
);
766 Perror(stderr
, "select", errno
);
774 Dprint(_res
.options
& RES_DEBUG
,
775 (stdout
, ";; timeout\n"));
781 fromlen
= sizeof(struct sockaddr_in
);
782 resplen
= recvfrom(s
, (char*)ans
, anssiz
, 0,
783 (struct sockaddr
*)&from
, &fromlen
);
785 Perror(stderr
, "recvfrom", errno
);
790 if (hp
->id
!= anhp
->id
) {
792 * response from old query, ignore it.
793 * XXX - potential security hazard could
796 DprintQ((_res
.options
& RES_DEBUG
) ||
797 (_res
.pfcode
& RES_PRF_REPLY
),
798 (stdout
, ";; old answer:\n"),
803 if (!(_res
.options
& RES_INSECURE1
) &&
804 multicast
== 0 && !res_isourserver(&from
)) {
806 * response from wrong server? ignore it.
807 * XXX - potential security hazard could
810 DprintQ((_res
.options
& RES_DEBUG
) ||
811 (_res
.pfcode
& RES_PRF_REPLY
),
812 (stdout
, ";; not our server:\n"),
817 if (!(_res
.options
& RES_INSECURE2
) &&
818 !res_queriesmatch(buf
, buf
+ buflen
,
819 ans
, ans
+ anssiz
)) {
821 * response contains wrong query? ignore it.
822 * XXX - potential security hazard could
825 DprintQ((_res
.options
& RES_DEBUG
) ||
826 (_res
.pfcode
& RES_PRF_REPLY
),
827 (stdout
, ";; wrong query name:\n"),
831 if (anhp
->rcode
== SERVFAIL
||
832 anhp
->rcode
== NOTIMP
||
833 anhp
->rcode
== REFUSED
) {
834 DprintQ(_res
.options
& RES_DEBUG
,
835 (stdout
, "server rejected query:\n"),
839 /* don't retry if called from dig */
843 if (!(_res
.options
& RES_IGNTC
) && anhp
->tc
) {
845 * get rest of answer;
846 * use TCP with same server.
848 Dprint(_res
.options
& RES_DEBUG
,
849 (stdout
, ";; truncated answer\n"));
855 DprintQ((_res
.options
& RES_DEBUG
) ||
856 (_res
.pfcode
& RES_PRF_REPLY
),
857 (stdout
, ";; got answer:\n"),
860 * If using virtual circuits, we assume that the first server
861 * is preferred over the rest (i.e. it is on the local
862 * machine) and only keep that one open.
863 * If we have temporarily opened a virtual circuit,
864 * or if we haven't been asked to keep a socket open,
867 if ((v_circuit
&& (!(_res
.options
& RES_USEVC
) || ns
!= 0)) ||
868 !(_res
.options
& RES_STAYOPEN
)) {
872 int done
= 0, loops
= 0;
877 act
= (*Rhook
)(nsap
, buf
, buflen
,
878 ans
, anssiz
, &resplen
);
888 /* give the hook another try */
889 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.