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/inet.h>
108 #include "nameser8_compat.h"
109 #include "resolv8_compat.h"
111 #if defined(BSD) && (BSD >= 199306)
116 # include "portability.h"
119 #if defined(USE_OPTIONS_H)
120 # include "options.h"
123 void _res_close
__P((void));
125 static int s
= -1; /* socket used for communications */
126 static int connected
= 0; /* is the socket connected */
127 static int vc
= 0; /* is the socket a virtual ciruit? */
130 /* XXX - should be in portability.h */
132 #define FD_SETSIZE 32
133 #define FD_SET(n, p) ((p)->fds_bits[(n)/NFDBITS] |= (1 << ((n) % NFDBITS)))
134 #define FD_CLR(n, p) ((p)->fds_bits[(n)/NFDBITS] &= ~(1 << ((n) % NFDBITS)))
135 #define FD_ISSET(n, p) ((p)->fds_bits[(n)/NFDBITS] & (1 << ((n) % NFDBITS)))
136 #define FD_ZERO(p) bzero((char *)(p), sizeof(*(p)))
139 /* XXX - this should be done in portability.h */
140 #if (defined(BSD) && (BSD >= 199103)) || defined(linux)
141 # define CAN_RECONNECT 1
143 # define CAN_RECONNECT 0
147 # define Dprint(cond, args) /*empty*/
148 # define DprintQ(cond, args, query, size) /*empty*/
149 # define Aerror(file, string, error, address) /*empty*/
150 # define Perror(file, string, error) /*empty*/
152 # define Dprint(cond, args) if (cond) {fprintf args;} else {}
153 # define DprintQ(cond, args, query, size) if (cond) {\
155 __fp_nquery(query, size, stdout);\
158 Aerror(file
, string
, error
, address
)
162 struct sockaddr_in address
;
166 if (_res
.options
& RES_DEBUG
) {
167 fprintf(file
, "res_send: %s ([%s].%u): %s\n",
169 inet_ntoa(address
.sin_addr
),
170 ntohs(address
.sin_port
),
176 Perror(file
, string
, error
)
183 if (_res
.options
& RES_DEBUG
) {
184 fprintf(file
, "res_send: %s: %s\n",
185 string
, strerror(error
));
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 /* Returns whether a dns encoded name should be sent to multicast or not */
317 static int dns_is_local_name(const u_int8_t
*name
)
319 const u_int8_t
*d0
= NULL
; // Top-Level Domain
320 const u_int8_t
*d1
= NULL
; // Second-Level Domain
321 const u_int8_t
*d2
= NULL
; // etc.
322 const u_int8_t
*d3
= NULL
;
324 if (name
== NULL
|| *name
== 0) return 0;
335 // "local" domains need to be resolved with multicast
337 if (d0
[0] == 5 && strncasecmp((char *)d0
+1, "local", 5) == 0) return 1;
340 if (d1
&& d1
[0] == 5 && strncasecmp((char *)d1
+1, "local", 5) == 0 &&
341 d0
[0] == 4 && strncasecmp((char *)d0
+1, "arpa", 4) == 0) return 1;
344 if (d1
&& d1
[0] == 5 && strncasecmp((char *)d1
+1, "local", 5) == 0 &&
345 d0
[0] == 3 && strncasecmp((char *)d0
+1, "int", 3) == 0) return 1;
347 // The network 169.254/16 is defined to be link-local,
348 // so lookups in 254.169.in-addr.arpa. also need to be resolved with local multicast
349 if (d3
&& d3
[0] == 3 && strncasecmp((char *)d3
+1, "254", 3) == 0 &&
350 d2
&& d2
[0] == 3 && strncasecmp((char *)d2
+1, "169", 3) == 0 &&
351 d1
&& d1
[0] == 7 && strncasecmp((char *)d1
+1, "in-addr", 7) == 0 &&
352 d0
[0] == 4 && strncasecmp((char *)d0
+1, "arpa", 4) == 0) return 1;
357 #define DNS_LOCAL_DOMAIN_SERVICE_PORT 5353
358 #define DNS_HEADER_SIZE 12
360 static const struct sockaddr_in mDNS_addr
=
364 htons(DNS_LOCAL_DOMAIN_SERVICE_PORT
),
365 {htonl(0xE00000FB)} /* 224.0.0.251 */
369 res_send(buf
, buflen
, ans
, anssiz
)
375 HEADER
*hp
= (HEADER
*) buf
;
376 HEADER
*anhp
= (HEADER
*) ans
;
377 int gotsomewhere
, connreset
, terrno
, try, v_circuit
, resplen
, ns
;
379 u_int badns
; /* XXX NSMAX can't exceed #/bits in this var */
382 if ((_res
.options
& RES_INIT
) == 0 && res_init() == -1) {
383 /* errno should have been set by res_init() in this case. */
386 DprintQ((_res
.options
& RES_DEBUG
) || (_res
.pfcode
& RES_PRF_QUERY
),
387 (stdout
, ";; res_send()\n"), buf
, buflen
);
388 v_circuit
= (_res
.options
& RES_USEVC
) || buflen
> PACKETSZ
;
394 if (dns_is_local_name((u_int8_t
*)(buf
+ DNS_HEADER_SIZE
))) {
403 * Send request, RETRY times, or until successful
405 for (try = 0; try < _res
.retry
; try++) {
406 for (ns
= 0; (multicast
== 0 && ns
< _res
.nscount
) ||
407 (multicast
== 1 && ns
< 1) ; ns
++) {
408 struct sockaddr_in
*nsap
;
410 nsap
= &_res
.nsaddr_list
[ns
];
412 nsap
= (struct sockaddr_in
*)&mDNS_addr
; /* const cast */
414 if (badns
& (1 << ns
)) {
420 int done
= 0, loops
= 0;
425 act
= (*Qhook
)(&nsap
, &buf
, &buflen
,
426 ans
, anssiz
, &resplen
);
437 /* give the hook another try */
438 if (++loops
< 42) /*doug adams*/
449 Dprint(_res
.options
& RES_DEBUG
,
450 (stdout
, ";; Querying server (# %d) address = %s\n",
451 ns
+ 1, inet_ntoa(nsap
->sin_addr
)));
460 * Use virtual circuit;
461 * at most one attempt per server.
465 if ((s
< 0) || (!vc
)) {
469 s
= socket(PF_INET
, SOCK_STREAM
, 0);
472 Perror(stderr
, "socket(vc)", errno
);
476 if (connect(s
, (struct sockaddr
*)nsap
,
477 sizeof(struct sockaddr
)) < 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
507 while ((n
= read(s
, (char *)cp
, (int)len
)) > 0) {
514 Perror(stderr
, "read failed", errno
);
517 * A long running process might get its TCP
518 * connection reset if the remote server was
519 * restarted. Requery the server instead of
520 * trying a new one. When there is only one
521 * server, this means that a query might work
522 * instead of failing. We only allow one reset
523 * per query to prevent looping.
525 if (terrno
== ECONNRESET
&& !connreset
) {
533 resplen
= _getshort(ans
);
534 if (resplen
> anssiz
) {
535 Dprint(_res
.options
& RES_DEBUG
,
536 (stdout
, ";; response truncated\n")
544 (n
= read(s
, (char *)cp
, (int)len
)) > 0) {
550 Perror(stderr
, "read(vc)", errno
);
556 * Flush rest of answer
557 * so connection stays in synch.
560 len
= resplen
- anssiz
;
564 n
= (len
> sizeof(junk
)
567 if ((n
= read(s
, junk
, n
)) > 0)
577 struct timeval timeout
;
579 struct sockaddr_in from
;
580 unsigned int fromlen
;
585 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
591 Perror(stderr
, "socket(dg)", errno
);
597 * On a 4.3BSD+ machine (client and server,
598 * actually), sending to a nameserver datagram
599 * port with no nameserver will cause an
600 * ICMP port unreachable message to be returned.
601 * If our datagram socket is "connected" to the
602 * server, we get an ECONNREFUSED error on the next
603 * socket operation, and select returns if the
604 * error message is received. We can thus detect
605 * the absence of a nameserver without timing out.
606 * If we have sent queries to at least two servers,
607 * however, we don't want to remain connected,
608 * as we wish to receive answers from the first
611 if ((_res
.nscount
== 1 || (try == 0 && ns
== 0)) && multicast
== 0) {
613 * Connect only if we are sure we won't
614 * receive a response from another server.
617 if (connect(s
, (struct sockaddr
*)nsap
,
618 sizeof(struct sockaddr
)
629 if (send(s
, (char*)buf
, buflen
, 0) != buflen
) {
630 Perror(stderr
, "send", errno
);
637 * Disconnect if we want to listen
638 * for responses from more than one server.
642 struct sockaddr_in no_addr
;
644 no_addr
.sin_family
= AF_INET
;
645 no_addr
.sin_addr
.s_addr
= INADDR_ANY
;
646 no_addr
.sin_port
= 0;
652 int s1
= socket(PF_INET
, SOCK_DGRAM
,0);
657 Dprint(_res
.options
& RES_DEBUG
,
658 (stdout
, ";; new DG socket\n"))
665 struct ifaddrs
* addrs
;
666 struct ifaddrs
* curAddr
;
667 const int twofivefive
= 255;
669 // multicast packets with TTL 255
670 if(setsockopt(s
, IPPROTO_IP
, IP_MULTICAST_TTL
, &twofivefive
, sizeof(twofivefive
))) {
671 Perror(stderr
, "setsocketopt - IP_MULTICAST_TTL", errno
);
676 if (getifaddrs(&addrs
) != 0)
678 Perror(stderr
, "getifaddrs", errno
);
683 /* multicast should send request on all multicast capable interfaces */
684 for (curAddr
= addrs
; curAddr
!= NULL
; curAddr
= curAddr
->ifa_next
) {
685 if ((curAddr
->ifa_addr
->sa_family
) == AF_INET
&&
686 (curAddr
->ifa_flags
& IFF_MULTICAST
) != 0 &&
687 (curAddr
->ifa_flags
& IFF_POINTOPOINT
) == 0) {
688 struct in_addr
* if_ip_addr
= &((struct sockaddr_in
*)curAddr
->ifa_addr
)->sin_addr
;
690 if (setsockopt(s
, IPPROTO_IP
, IP_MULTICAST_IF
,
691 if_ip_addr
, sizeof(*if_ip_addr
)) != 0) {
693 Perror(stderr
, "setsocketopt - IP_MULTICAST_IF", errno
);
698 if (sendto(s
, (char*)buf
, buflen
, 0,
699 (struct sockaddr
*)nsap
, sizeof *nsap
) != buflen
)
702 Aerror(stderr
, "sendto", errno
, *nsap
);
711 if (sendto(s
, (char*)buf
, buflen
, 0,
712 (struct sockaddr
*)nsap
,
713 sizeof(struct sockaddr
))
715 Aerror(stderr
, "sendto", errno
, *nsap
);
726 timeout
.tv_sec
= (_res
.retrans
<< try);
728 timeout
.tv_sec
/= _res
.nscount
;
729 if ((long) timeout
.tv_sec
<= 0 || multicast
)
735 n
= select(s
+1, &dsmask
, (fd_set
*)NULL
,
736 (fd_set
*)NULL
, &timeout
);
738 Perror(stderr
, "select", errno
);
746 Dprint(_res
.options
& RES_DEBUG
,
747 (stdout
, ";; timeout\n"));
753 fromlen
= sizeof(struct sockaddr_in
);
754 resplen
= recvfrom(s
, (char*)ans
, anssiz
, 0,
755 (struct sockaddr
*)&from
, &fromlen
);
757 Perror(stderr
, "recvfrom", errno
);
762 if (hp
->id
!= anhp
->id
) {
764 * response from old query, ignore it.
765 * XXX - potential security hazard could
768 DprintQ((_res
.options
& RES_DEBUG
) ||
769 (_res
.pfcode
& RES_PRF_REPLY
),
770 (stdout
, ";; old answer:\n"),
775 if (!(_res
.options
& RES_INSECURE1
) &&
776 multicast
== 0 && !res_isourserver(&from
)) {
778 * response from wrong server? ignore it.
779 * XXX - potential security hazard could
782 DprintQ((_res
.options
& RES_DEBUG
) ||
783 (_res
.pfcode
& RES_PRF_REPLY
),
784 (stdout
, ";; not our server:\n"),
789 if (!(_res
.options
& RES_INSECURE2
) &&
790 !res_queriesmatch(buf
, buf
+ buflen
,
791 ans
, ans
+ anssiz
)) {
793 * response contains wrong query? ignore it.
794 * XXX - potential security hazard could
797 DprintQ((_res
.options
& RES_DEBUG
) ||
798 (_res
.pfcode
& RES_PRF_REPLY
),
799 (stdout
, ";; wrong query name:\n"),
803 if (anhp
->rcode
== SERVFAIL
||
804 anhp
->rcode
== NOTIMP
||
805 anhp
->rcode
== REFUSED
) {
806 DprintQ(_res
.options
& RES_DEBUG
,
807 (stdout
, "server rejected query:\n"),
811 /* don't retry if called from dig */
815 if (!(_res
.options
& RES_IGNTC
) && anhp
->tc
) {
817 * get rest of answer;
818 * use TCP with same server.
820 Dprint(_res
.options
& RES_DEBUG
,
821 (stdout
, ";; truncated answer\n"));
827 DprintQ((_res
.options
& RES_DEBUG
) ||
828 (_res
.pfcode
& RES_PRF_REPLY
),
829 (stdout
, ";; got answer:\n"),
832 * If using virtual circuits, we assume that the first server
833 * is preferred over the rest (i.e. it is on the local
834 * machine) and only keep that one open.
835 * If we have temporarily opened a virtual circuit,
836 * or if we haven't been asked to keep a socket open,
839 if ((v_circuit
&& (!(_res
.options
& RES_USEVC
) || ns
!= 0)) ||
840 !(_res
.options
& RES_STAYOPEN
)) {
844 int done
= 0, loops
= 0;
849 act
= (*Rhook
)(nsap
, buf
, buflen
,
850 ans
, anssiz
, &resplen
);
860 /* give the hook another try */
861 if (++loops
< 42) /*doug adams*/
879 errno
= ECONNREFUSED
; /* no nameservers found */
881 errno
= ETIMEDOUT
; /* no answer obtained */
888 * This routine is for closing the socket if a virtual circuit is used and
889 * the program wants to close it. This provides support for endhostent()
890 * which expects to close the socket.
892 * This routine is not expected to be user visible.