2 * Copyright (c) 2008-2011 Apple Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
24 * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
26 * Permission to use, copy, modify, and distribute this software for any
27 * purpose with or without fee is hereby granted, provided that the above
28 * copyright notice and this permission notice appear in all copies.
30 * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
31 * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
32 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
33 * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
34 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
35 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
36 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
40 * Copyright (c) 1988, 1993
41 * The Regents of the University of California. All rights reserved.
43 * Redistribution and use in source and binary forms, with or without
44 * modification, are permitted provided that the following conditions
46 * 1. Redistributions of source code must retain the above copyright
47 * notice, this list of conditions and the following disclaimer.
48 * 2. Redistributions in binary form must reproduce the above copyright
49 * notice, this list of conditions and the following disclaimer in the
50 * documentation and/or other materials provided with the distribution.
51 * 4. Neither the name of the University nor the names of its contributors
52 * may be used to endorse or promote products derived from this software
53 * without specific prior written permission.
55 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
56 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
57 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
58 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
59 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
60 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
61 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
62 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
63 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
64 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68 * Portions Copyright (c) 1993 by Digital Equipment Corporation.
70 * Permission to use, copy, modify, and distribute this software for any
71 * purpose with or without fee is hereby granted, provided that the above
72 * copyright notice and this permission notice appear in all copies, and that
73 * the name of Digital Equipment Corporation not be used in advertising or
74 * publicity pertaining to distribution of the document or software without
75 * specific, written prior permission.
77 * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
78 * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
79 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
80 * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
81 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
82 * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
83 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
89 #include "si_module.h"
92 #include <arpa/inet.h>
93 #include <arpa/nameser.h>
94 #include <arpa/nameser_compat.h>
95 #include <libkern/OSAtomic.h>
96 #include <netinet/in.h>
108 #include <sys/event.h>
109 #include <sys/param.h>
110 #include <sys/time.h>
111 #include <sys/types.h>
112 #include <sys/socket.h>
118 #include <dns_util.h>
119 #include <TargetConditionals.h>
120 #include <dispatch/dispatch.h>
122 /* from dns_util.c */
123 #define DNS_MAX_RECEIVE_SIZE 65536
125 #define INET_NTOP_AF_INET_OFFSET 4
126 #define INET_NTOP_AF_INET6_OFFSET 8
128 #define IPPROTO_UNSPEC 0
132 #define SHORT_AAAA_EXTRA 2
133 #define MEDIUM_AAAA_EXTRA 5
134 #define LONG_AAAA_EXTRA 10
136 #define MDNS_DEBUG_FILE "/etc/.mdns_debug"
137 #define MDNS_DEBUG_STDOUT 0x00000001
138 #define MDNS_DEBUG_STDERR 0x00000002
139 #define MDNS_DEBUG_ASL 0x00000004
140 #define MDNS_DEBUG_OUT 0x00000007
141 #define MDNS_DEBUG_MORE 0x00000010
143 static int _mdns_debug
= 0;
145 /* mutex protects DNSServiceProcessResult and DNSServiceRefDeallocate */
146 static pthread_mutex_t _mdns_mutex
= PTHREAD_MUTEX_INITIALIZER
;
156 typedef struct mdns_srv_t mdns_srv_t
;
179 static uint32_t _mdns_generation
= 0;
180 static DNSServiceRef _mdns_sdref
;
181 static DNSServiceRef _mdns_old_sdref
;
183 static void _mdns_hostent_clear(mdns_hostent_t
*h
);
184 static void _mdns_reply_clear(mdns_reply_t
*r
);
185 static int _mdns_search(const char *name
, int class, int type
, const char *interface
, DNSServiceFlags flags
, uint8_t *answer
, uint32_t *anslen
, mdns_reply_t
*reply
);
187 static const char hexchar
[] = "0123456789abcdef";
189 #define BILLION 1000000000
191 /* length of a reverse DNS IPv6 address query name, e.g. "9.4.a.f.c.e.e.f.e.e.1.5.4.1.4.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.e.f.ip6.arpa" */
192 #define IPv6_REVERSE_LEN 72
194 /* index of the trailing char that must be "8", "9", "A", "a", "b", or "B" */
195 #define IPv6_REVERSE_LINK_LOCAL_TRAILING_CHAR 58
197 /* index of low-order nibble of embedded scope id */
198 #define IPv6_REVERSE_LINK_LOCAL_SCOPE_ID_LOW 48
200 const static uint8_t hexval
[128] = {
201 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0 - 15 */
202 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 16 - 31 */
203 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 32 - 47 */
204 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, /* 48 - 63 */
205 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 64 - 79 */
206 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80 - 95 */
207 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 96 - 111 */
208 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* 112 - 127 */
212 _mdns_debug_message(const char *str
, ...)
217 if (str
== NULL
) return;
218 if ((_mdns_debug
& MDNS_DEBUG_OUT
) == 0) return;
221 vasprintf(&out
, str
, v
);
222 if (out
== NULL
) return;
224 if (_mdns_debug
& MDNS_DEBUG_STDOUT
) fprintf(stdout
, "%s", out
);
225 if (_mdns_debug
& MDNS_DEBUG_STDERR
) fprintf(stderr
, "%s", out
);
226 if (_mdns_debug
& MDNS_DEBUG_ASL
) asl_log_message(ASL_LEVEL_NOTICE
, "%s", out
);
233 _mdns_reverse_ipv4(const char *addr
)
242 if (addr
== NULL
) return NULL
;
244 memcpy(&(ab
.a
), addr
, 4);
246 asprintf(&p
, "%u.%u.%u.%u.in-addr.arpa.", ab
.b
[3], ab
.b
[2], ab
.b
[1], ab
.b
[0]);
251 _mdns_reverse_ipv6(const char *addr
)
257 if (addr
== NULL
) return NULL
;
262 for (i
= 0; i
< 16; i
++)
268 x
[j
--] = hexchar
[hi
];
270 x
[j
--] = hexchar
[lo
];
273 asprintf(&p
, "%sip6.arpa.", x
);
280 * Canonicalize the domain name by converting to lower case and removing the
281 * trailing '.' if present.
284 _mdns_canonicalize(const char *s
)
289 if (s
== NULL
) return NULL
;
292 if (t
== NULL
) return NULL
;
294 if (t
[0] == '\0') return t
;
296 for (i
= 0; t
[i
] != '\0'; i
++)
298 if (t
[i
] >= 'A' && t
[i
] <= 'Z') t
[i
] += 32;
301 if (t
[i
-1] == '.') t
[i
-1] = '\0';
307 * _mdns_hostent_append_alias
308 * Appends an alias to the mdns_hostent_t structure.
311 _mdns_hostent_append_alias(mdns_hostent_t
*h
, const char *alias
)
316 if ((h
== NULL
) || (alias
== NULL
)) return 0;
318 name
= _mdns_canonicalize(alias
);
319 if (name
== NULL
) return -1;
321 /* don't add the name if it matches an existing name */
322 if ((h
->host
.h_name
!= NULL
) && string_equal(h
->host
.h_name
, name
))
328 for (i
= 0; i
< h
->alias_count
; ++i
)
330 if (string_equal(h
->host
.h_aliases
[i
], name
))
337 /* add the alias and NULL terminate the list if it is new */
338 h
->host
.h_aliases
= (char **)reallocf(h
->host
.h_aliases
, (h
->alias_count
+ 2) * sizeof(char *));
339 if (h
->host
.h_aliases
== NULL
)
346 h
->host
.h_aliases
[h
->alias_count
] = name
;
349 h
->host
.h_aliases
[h
->alias_count
] = NULL
;
354 * _mdns_hostent_append_addr
355 * Appends an alias to the mdns_hostent_t structure.
358 _mdns_hostent_append_addr(mdns_hostent_t
*h
, const uint8_t *addr
, uint32_t len
)
360 if ((h
== NULL
) || (addr
== NULL
) || (len
== 0)) return 0;
362 /* copy the address buffer */
363 uint8_t *buf
= malloc(len
);
364 if (buf
== NULL
) return -1;
366 memcpy(buf
, addr
, len
);
368 /* add the address and NULL terminate the list if it is new */
369 h
->host
.h_addr_list
= (char **)reallocf(h
->host
.h_addr_list
, (h
->addr_count
+ 2) * sizeof(char *));
371 if (h
->host
.h_addr_list
== NULL
)
377 h
->host
.h_addr_list
[h
->addr_count
] = (char*)buf
;
380 h
->host
.h_addr_list
[h
->addr_count
] = NULL
;
385 _mdns_hostent_clear(mdns_hostent_t
*h
)
387 if (h
== NULL
) return;
389 free(h
->host
.h_name
);
390 h
->host
.h_name
= NULL
;
392 char **aliases
= h
->host
.h_aliases
;
393 while (aliases
&& *aliases
) free(*aliases
++);
395 free(h
->host
.h_aliases
);
396 h
->host
.h_aliases
= NULL
;
399 char **addrs
= h
->host
.h_addr_list
;
400 while (addrs
&& *addrs
) free(*addrs
++);
402 free(h
->host
.h_addr_list
);
403 h
->host
.h_addr_list
= NULL
;
408 _mdns_reply_clear(mdns_reply_t
*r
)
410 if (r
== NULL
) return;
413 _mdns_hostent_clear(r
->h4
);
414 _mdns_hostent_clear(r
->h6
);
415 mdns_srv_t
*srv
= r
->srv
;
420 mdns_srv_t
*next
= srv
->next
;
421 free(srv
->srv
.target
);
428 mdns_hostbyname(si_mod_t
*si
, const char *name
, int af
, const char *interface
, uint32_t *err
)
433 si_item_t
*out
= NULL
;
436 DNSServiceFlags flags
= 0;
438 if (err
!= NULL
) *err
= SI_STATUS_NO_ERROR
;
440 if ((name
== NULL
) || (si
== NULL
))
442 if (err
!= NULL
) *err
= SI_STATUS_H_ERRNO_NO_RECOVERY
;
446 memset(&h
, 0, sizeof(h
));
447 memset(&reply
, 0, sizeof(reply
));
458 h
.host
.h_length
= 16;
462 if (err
!= NULL
) *err
= SI_STATUS_H_ERRNO_NO_RECOVERY
;
466 _mdns_debug_message(";; mdns_hostbyname %s type %u class %u\n", name
, type
, ns_c_in
);
468 h
.host
.h_addrtype
= af
;
470 status
= _mdns_search(name
, ns_c_in
, type
, interface
, flags
, NULL
, NULL
, &reply
);
471 if ((status
!= 0) || (h
.addr_count
== 0))
473 _mdns_reply_clear(&reply
);
474 if (err
!= NULL
) *err
= SI_STATUS_H_ERRNO_HOST_NOT_FOUND
;
478 bb
= reply
.ttl
+ time(NULL
);
483 out
= (si_item_t
*)LI_ils_create("L4488s*44a", (unsigned long)si
, CATEGORY_HOST_IPV4
, 1, bb
, 0LL, h
.host
.h_name
, h
.host
.h_aliases
, h
.host
.h_addrtype
, h
.host
.h_length
, h
.host
.h_addr_list
);
486 out
= (si_item_t
*)LI_ils_create("L4488s*44c", (unsigned long)si
, CATEGORY_HOST_IPV6
, 1, bb
, 0LL, h
.host
.h_name
, h
.host
.h_aliases
, h
.host
.h_addrtype
, h
.host
.h_length
, h
.host
.h_addr_list
);
490 _mdns_reply_clear(&reply
);
492 if ((out
== NULL
) && (err
!= NULL
)) *err
= SI_STATUS_H_ERRNO_NO_RECOVERY
;
498 mdns_hostbyaddr(si_mod_t
*si
, const void *addr
, int af
, const char *interface
, uint32_t *err
)
507 DNSServiceFlags flags
= 0;
509 if (err
!= NULL
) *err
= SI_STATUS_NO_ERROR
;
511 if ((addr
== NULL
) || (si
== NULL
))
513 if (err
!= NULL
) *err
= SI_STATUS_H_ERRNO_NO_RECOVERY
;
517 memset(&h
, 0, sizeof(h
));
518 memset(&reply
, 0, sizeof(reply
));
525 name
= _mdns_reverse_ipv4(addr
);
526 cat
= CATEGORY_HOST_IPV4
;
529 h
.host
.h_length
= 16;
531 name
= _mdns_reverse_ipv6(addr
);
532 cat
= CATEGORY_HOST_IPV6
;
535 if (err
!= NULL
) *err
= SI_STATUS_H_ERRNO_NO_RECOVERY
;
539 h
.host
.h_addrtype
= af
;
541 _mdns_debug_message(";; mdns_hostbyaddr %s type %u class %u\n", name
, ns_t_ptr
, ns_c_in
);
543 status
= _mdns_search(name
, ns_c_in
, ns_t_ptr
, interface
, flags
, NULL
, NULL
, &reply
);
547 _mdns_reply_clear(&reply
);
548 if (err
!= NULL
) *err
= SI_STATUS_H_ERRNO_HOST_NOT_FOUND
;
552 status
= _mdns_hostent_append_addr(&h
, addr
, h
.host
.h_length
);
555 _mdns_hostent_clear(&h
);
556 if (err
!= NULL
) *err
= SI_STATUS_H_ERRNO_NO_RECOVERY
;
560 bb
= reply
.ttl
+ time(NULL
);
561 out
= (si_item_t
*)LI_ils_create("L4488s*44a", (unsigned long)si
, cat
, 1, bb
, 0LL, h
.host
.h_name
, h
.host
.h_aliases
, h
.host
.h_addrtype
, h
.host
.h_length
, h
.host
.h_addr_list
);
563 _mdns_hostent_clear(&h
);
565 if ((out
== NULL
) && (err
!= NULL
)) *err
= SI_STATUS_H_ERRNO_NO_RECOVERY
;
570 mdns_addrinfo(si_mod_t
*si
, const void *node
, const void *serv
, uint32_t family
, uint32_t socktype
, uint32_t proto
, uint32_t flags
, const char *interface
, uint32_t *err
)
584 if (err
!= NULL
) *err
= SI_STATUS_H_ERRNO_NO_RECOVERY
;
588 if (family
== AF_INET6
)
590 if ((flags
& AI_V4MAPPED
) == 0) wantv4
= false;
592 else if (family
== AF_INET
)
596 else if (family
!= AF_UNSPEC
)
601 if (err
!= NULL
) *err
= SI_STATUS_NO_ERROR
;
603 _mdns_debug_message(";; mdns_addrinfo node %s serv %s\n", (const char *)node
, (const char *)serv
);
605 si_list_t
*out
= NULL
;
607 memset(&h4
, 0, sizeof(h4
));
608 memset(&h6
, 0, sizeof(h6
));
609 memset(&reply
, 0, sizeof(reply
));
611 h4
.host
.h_addrtype
= AF_INET
;
612 h4
.host
.h_length
= 4;
613 h6
.host
.h_addrtype
= AF_INET6
;
614 h6
.host
.h_length
= 16;
616 if (wantv4
&& wantv6
)
634 if (err
!= NULL
) *err
= SI_STATUS_H_ERRNO_NO_RECOVERY
;
639 if ((flags
& AI_NUMERICSERV
) != 0)
641 if (serv
== NULL
) port
= 0;
642 else port
= *(uint16_t *)serv
;
646 if (_gai_serv_to_port(serv
, proto
, &port
) != 0)
648 if (err
) *err
= SI_STATUS_EAI_NONAME
;
654 if ((flags
& AI_NUMERICHOST
) != 0)
657 struct in_addr
*p4
= NULL
;
658 struct in6_addr
*p6
= NULL
;
660 if (node
== NULL
) return NULL
;
662 if (family
== AF_INET
)
665 memcpy(p4
, node
, sizeof(a4
));
667 else if (family
== AF_INET6
)
670 memcpy(p6
, node
, sizeof(a6
));
673 out
= si_addrinfo_list(si
, flags
, socktype
, proto
, p4
, p6
, port
, 0, cname
, cname
);
678 DNSServiceFlags dns_flags
= 0;
680 if (node
== NULL
) return NULL
;
682 if (flags
& AI_ADDRCONFIG
)
684 dns_flags
|= kDNSServiceFlagsSuppressUnusable
;
687 res
= _mdns_search(node
, ns_c_in
, type
, interface
, dns_flags
, NULL
, NULL
, &reply
);
688 if ((res
== 0) && ((h4
.addr_count
> 0) || (h6
.addr_count
> 0)))
690 out
= si_addrinfo_list_from_hostent(si
, flags
, socktype
, proto
, port
, 0, (wantv4
? &h4
.host
: NULL
), (wantv6
? &h6
.host
: NULL
));
692 else if (err
!= NULL
)
694 *err
= SI_STATUS_EAI_NONAME
;
697 _mdns_reply_clear(&reply
);
704 mdns_srv_byname(si_mod_t
* si
, const char *qname
, const char *interface
, uint32_t *err
)
706 si_list_t
*out
= NULL
;
710 const uint64_t unused
= 0;
711 DNSServiceFlags flags
= 0;
715 if (err
!= NULL
) *err
= SI_STATUS_H_ERRNO_NO_RECOVERY
;
719 if (err
!= NULL
) *err
= SI_STATUS_NO_ERROR
;
721 _mdns_debug_message(";; mdns_srv_byname %s type %u class %u\n", qname
, ns_t_srv
, ns_c_in
);
723 memset(&reply
, 0, sizeof(reply
));
724 res
= _mdns_search(qname
, ns_c_in
, ns_t_srv
, interface
, flags
, NULL
, NULL
, &reply
);
731 item
= (si_item_t
*)LI_ils_create("L4488222s", (unsigned long)si
, CATEGORY_SRV
, 1, unused
, unused
, srv
->srv
.priority
, srv
->srv
.weight
, srv
->srv
.port
, srv
->srv
.target
);
732 out
= si_list_add(out
, item
);
733 si_item_release(item
);
738 _mdns_reply_clear(&reply
);
743 * We support dns_async_start / cancel / handle_reply using dns_item_call
746 mdns_item_call(si_mod_t
*si
, int call
, const char *name
, const char *ignored
, const char *interface
, uint32_t class, uint32_t type
, uint32_t *err
)
749 uint8_t buf
[DNS_MAX_RECEIVE_SIZE
];
750 uint32_t len
= sizeof(buf
);
755 DNSServiceFlags flags
= 0;
757 if ((si
== NULL
) || (name
== NULL
))
759 if (err
!= NULL
) *err
= SI_STATUS_H_ERRNO_NO_RECOVERY
;
763 if (err
!= NULL
) *err
= SI_STATUS_NO_ERROR
;
765 _mdns_debug_message(";; mdns_item_call %s type %u class %u\n", name
, type
, class);
767 memset(&h4
, 0, sizeof(h4
));
768 memset(&h6
, 0, sizeof(h6
));
769 memset(&reply
, 0, sizeof(reply
));
771 h4
.host
.h_addrtype
= AF_INET
;
772 h4
.host
.h_length
= 4;
773 h6
.host
.h_addrtype
= AF_INET6
;
774 h6
.host
.h_length
= 16;
778 res
= _mdns_search(name
, class, type
, interface
, flags
, buf
, &len
, &reply
);
779 if ((res
!= 0) || (len
<= 0) || (len
> DNS_MAX_RECEIVE_SIZE
))
781 _mdns_reply_clear(&reply
);
782 if (err
!= NULL
) *err
= SI_STATUS_H_ERRNO_HOST_NOT_FOUND
;
786 struct sockaddr_in6 from
;
787 uint32_t fromlen
= sizeof(from
);
788 memset(&from
, 0, fromlen
);
789 from
.sin6_len
= fromlen
;
790 from
.sin6_family
= AF_INET6
;
791 from
.sin6_addr
.__u6_addr
.__u6_addr8
[15] = 1;
793 if (reply
.ifnum
!= 0)
795 from
.sin6_addr
.__u6_addr
.__u6_addr16
[0] = htons(0xfe80);
796 from
.sin6_scope_id
= reply
.ifnum
;
799 out
= (si_item_t
*)LI_ils_create("L4488@@", (unsigned long)si
, CATEGORY_DNSPACKET
, 1, 0LL, 0LL, len
, buf
, fromlen
, &from
);
800 if ((out
== NULL
) && (err
!= NULL
)) *err
= SI_STATUS_H_ERRNO_NO_RECOVERY
;
802 _mdns_reply_clear(&reply
);
808 mdns_is_valid(si_mod_t
*si
, si_item_t
*item
)
814 mdns_close(si_mod_t
*si
)
819 _mdns_atfork_prepare(void)
821 /* acquire our lock so that we know all other threads have "drained" */
822 pthread_mutex_lock(&_mdns_mutex
);
826 _mdns_atfork_parent(void)
828 /* parent can simply resume */
829 pthread_mutex_unlock(&_mdns_mutex
);
833 _mdns_atfork_child(void)
835 /* child needs to force re-initialization */
836 _mdns_old_sdref
= _mdns_sdref
; // for later deallocation
838 pthread_mutex_unlock(&_mdns_mutex
);
844 pthread_atfork(_mdns_atfork_prepare
, _mdns_atfork_parent
, _mdns_atfork_child
);
846 if (getenv("RES_DEBUG") != NULL
) _mdns_debug
|= MDNS_DEBUG_STDOUT
;
847 int fd
= open(MDNS_DEBUG_FILE
, O_RDONLY
, 0);
854 memset(c
, 0, sizeof(c
));
857 for (i
= 0; i
< n
; i
++)
859 if ((c
[i
] == 'o') || (c
[i
] == 'O')) _mdns_debug
|= MDNS_DEBUG_STDOUT
;
860 if ((c
[i
] == 'e') || (c
[i
] == 'E')) _mdns_debug
|= MDNS_DEBUG_STDERR
;
861 if ((c
[i
] == 'a') || (c
[i
] == 'A')) _mdns_debug
|= MDNS_DEBUG_ASL
;
862 if ((c
[i
] == 'm') || (c
[i
] == 'M')) _mdns_debug
|= MDNS_DEBUG_MORE
;
868 si_module_static_mdns(void)
870 static const struct si_mod_vtable_s mdns_vtable
=
872 .sim_close
= &mdns_close
,
873 .sim_is_valid
= &mdns_is_valid
,
874 .sim_host_byname
= &mdns_hostbyname
,
875 .sim_host_byaddr
= &mdns_hostbyaddr
,
876 .sim_item_call
= &mdns_item_call
,
877 .sim_addrinfo
= &mdns_addrinfo
,
878 .sim_srv_byname
= &mdns_srv_byname
,
885 .flags
= SI_MOD_FLAG_STATIC
,
888 .vtable
= &mdns_vtable
,
891 static dispatch_once_t once
;
893 dispatch_once(&once
, ^{
894 si
.name
= strdup("mdns");
898 return (si_mod_t
*)&si
;
902 * _mdns_parse_domain_name
903 * Combine DNS labels to form a string.
904 * DNSService API does not return compressed names.
907 _mdns_parse_domain_name(const uint8_t *data
, uint32_t datalen
)
911 uint32_t domainlen
= 0;
914 if ((data
== NULL
) || (datalen
== 0)) return NULL
;
917 * i: index into input data
918 * j: index into output string
920 while (datalen
-- > 0)
923 domainlen
+= (len
+ 1);
924 domain
= reallocf(domain
, domainlen
);
926 if (domain
== NULL
) return NULL
;
928 if (len
== 0) break; // DNS root (NUL)
932 domain
[j
++] = datalen
? '.' : '\0';
935 while ((len
-- > 0) && (0 != datalen
--))
939 /* special case: escape the '.' with a '\' */
940 domain
= reallocf(domain
, ++domainlen
);
941 if (domain
== NULL
) return NULL
;
946 domain
[j
++] = data
[i
++];
956 * _mdns_pack_domain_name
957 * Format the string as packed DNS labels.
958 * Only used for one string at a time, therefore no need for compression.
961 _mdns_pack_domain_name(const char *str
, uint8_t *buf
, size_t buflen
)
966 if ((str
== NULL
) || (buf
== NULL
)) return -1;
970 /* calculate length to next '.' or '\0' */
971 char *dot
= strchr(str
, '.');
972 if (dot
== NULL
) dot
= strchr(str
, '\0');
975 if (len
> NS_MAXLABEL
) return -1;
977 /* copy data for label */
979 while (str
< dot
&& i
< buflen
)
984 /* skip past '.', break if '\0' */
985 if (*str
++ == '\0') break;
988 if (i
>= buflen
) return -1;
992 /* no trailing dot - add a null label */
994 if (i
>= buflen
) return -1;
1002 _is_rev_link_local(const char *name
)
1006 if (name
== NULL
) return 0;
1009 if (len
== 0) return 0;
1011 /* check for trailing '.' */
1012 if (name
[len
- 1] == '.') len
--;
1014 if (len
!= IPv6_REVERSE_LEN
) return 0;
1016 i
= IPv6_REVERSE_LINK_LOCAL_TRAILING_CHAR
;
1017 if ((name
[i
] != '8') && (name
[i
] != '9') && (name
[i
] != 'A') && (name
[i
] != 'a') && (name
[i
] != 'B') && (name
[i
] != 'b')) return 0;
1019 i
= IPv6_REVERSE_LINK_LOCAL_TRAILING_CHAR
+ 1;
1020 if (strncasecmp(name
+ i
, ".e.f.ip6.arpa", 13)) return 0;
1022 for (i
= 0; i
< IPv6_REVERSE_LINK_LOCAL_TRAILING_CHAR
; i
+= 2)
1024 if (name
[i
] < '0') return 0;
1025 if ((name
[i
] > '9') && (name
[i
] < 'A')) return 0;
1026 if ((name
[i
] > 'F') && (name
[i
] < 'a')) return 0;
1027 if (name
[i
] > 'f') return 0;
1028 if (name
[i
+ 1] != '.') return 0;
1035 * _mdns_ipv6_extract_scope_id
1036 * If the input string is a link local IPv6 address with an encoded scope id,
1037 * the scope id is extracted and a new string is constructed with the scope id removed.
1040 _mdns_ipv6_extract_scope_id(const char *name
, uint32_t *out_ifnum
)
1047 if (out_ifnum
!= NULL
) *out_ifnum
= 0;
1048 if (name
== NULL
) return NULL
;
1050 /* examine the address, extract the scope id if present */
1051 if (_is_rev_link_local(name
))
1053 /* _is_rev_link_local rejects chars > 127 so it's safe to index into hexval */
1054 i
= IPv6_REVERSE_LINK_LOCAL_SCOPE_ID_LOW
;
1055 nibble
= hexval
[(uint32_t)name
[i
]];
1059 nibble
= hexval
[(uint32_t)name
[i
]];
1060 iface
+= (nibble
<< 4);
1063 nibble
= hexval
[(uint32_t)name
[i
]];
1064 iface
+= (nibble
<< 8);
1067 nibble
= hexval
[(uint32_t)name
[i
]];
1068 iface
+= (nibble
<< 12);
1072 qname
= strdup(name
);
1073 if (qname
== NULL
) return NULL
;
1075 i
= IPv6_REVERSE_LINK_LOCAL_SCOPE_ID_LOW
;
1081 if (out_ifnum
) *out_ifnum
= iface
;
1089 _mdns_make_query(const char* name
, int class, int type
, uint8_t *buf
, uint32_t buflen
)
1093 if ((buf
== NULL
) || (buflen
< (NS_HFIXEDSZ
+ NS_QFIXEDSZ
))) return -1;
1095 memset(buf
, 0, NS_HFIXEDSZ
);
1096 HEADER
*hp
= (HEADER
*)buf
;
1099 hp
->id
= arc4random();
1101 hp
->opcode
= ns_o_query
;
1103 hp
->rcode
= ns_r_noerror
;
1104 hp
->qdcount
= htons(1);
1106 int n
= _mdns_pack_domain_name(name
, &buf
[len
], buflen
- len
);
1107 if (n
< 0) return -1;
1112 memcpy(&buf
[len
], &word
, sizeof(word
));
1113 len
+= sizeof(word
);
1114 word
= htons(class);
1115 memcpy(&buf
[len
], &word
, sizeof(word
));
1116 len
+= sizeof(word
);
1123 mdns_reply_t
*reply
;
1124 mdns_hostent_t
*host
;
1125 uint8_t *answer
; // DNS packet buffer
1126 size_t anslen
; // DNS packet buffer current length
1127 size_t ansmaxlen
; // DNS packet buffer maximum length
1128 int type
; // type of query: A, AAAA, PTR, SRV...
1129 uint16_t last_type
; // last type received
1132 DNSServiceFlags flags
;
1133 DNSServiceErrorType error
;
1134 int kq
; // kqueue to notify when callback received
1135 } mdns_query_context_t
;
1138 _mdns_query_callback(DNSServiceRef
, DNSServiceFlags
, uint32_t, DNSServiceErrorType
, const char *, uint16_t, uint16_t, uint16_t, const void *, uint32_t, void *);
1142 * initializes the context and starts a DNS-SD query.
1144 static DNSServiceErrorType
1145 _mdns_query_start(mdns_query_context_t
*ctx
, mdns_reply_t
*reply
, uint8_t *answer
, uint32_t *anslen
, const char* name
, int class, int type
, const char *interface
, DNSServiceFlags flags
, int kq
)
1147 DNSServiceErrorType status
;
1149 flags
|= kDNSServiceFlagsShareConnection
;
1150 flags
|= kDNSServiceFlagsReturnIntermediates
;
1152 /* <rdar://problem/7428439> mDNSResponder is now responsible for timeouts */
1153 flags
|= kDNSServiceFlagsTimeout
;
1155 memset(ctx
, 0, sizeof(mdns_query_context_t
));
1157 if ((answer
!= NULL
) && (anslen
!= NULL
))
1159 /* build a dummy DNS header to return to the caller */
1160 ctx
->answer
= answer
;
1161 ctx
->ansmaxlen
= *anslen
;
1162 ctx
->anslen
= _mdns_make_query(name
, class, type
, answer
, ctx
->ansmaxlen
);
1163 if (ctx
->anslen
<= 0) return -1;
1167 ctx
->sd
= _mdns_sdref
;
1168 ctx
->sd_gen
= _mdns_generation
;
1174 if (type
== ns_t_a
) ctx
->host
= reply
->h4
;
1175 else if (type
== ns_t_aaaa
) ctx
->host
= reply
->h6
;
1176 else if (type
== ns_t_ptr
&& reply
->h4
) ctx
->host
= reply
->h4
;
1177 else if (type
== ns_t_ptr
&& reply
->h6
) ctx
->host
= reply
->h6
;
1178 else if (type
!= ns_t_srv
&& type
!= ns_t_cname
) return -1;
1182 char *qname
= _mdns_ipv6_extract_scope_id(name
, &iface
);
1183 if (qname
== NULL
) qname
= (char *)name
;
1185 if (interface
!= NULL
)
1187 /* get interface number from name */
1188 int iface2
= if_nametoindex(interface
);
1190 /* balk if interface name lookup failed */
1191 if (iface2
== 0) return -1;
1193 /* balk if scope id is set AND interface is given AND they don't match */
1194 if ((iface
!= 0) && (iface2
!= 0) && (iface
!= iface2
)) return -1;
1195 if (iface2
!= 0) iface
= iface2
;
1198 _mdns_debug_message(";; mdns query %s type %d class %d [ctx %p]\n", qname
, type
, class, ctx
);
1200 status
= DNSServiceQueryRecord(&ctx
->sd
, flags
, iface
, qname
, type
, class, _mdns_query_callback
, ctx
);
1201 if (qname
!= name
) free(qname
);
1206 * _mdns_query_is_complete
1207 * Determines whether the specified query has sufficient information to be
1208 * considered complete.
1211 _mdns_query_is_complete(mdns_query_context_t
*ctx
)
1213 bool complete
= false;
1215 /* NULL context is an error, but we call it complete */
1216 if (ctx
== NULL
) return true;
1219 * The default is to ignore kDNSServiceFlagsMoreComing, since it has either
1220 * never been supported or worked correctly. MDNS_DEBUG_MORE makes us honor it.
1222 if (ctx
->flags
& kDNSServiceFlagsMoreComing
)
1224 if (_mdns_debug
& MDNS_DEBUG_MORE
)
1226 _mdns_debug_message(";; mdns is_complete type %d ctx %p more coming - incomplete\n", ctx
->type
, ctx
);
1231 if (ctx
->last_type
!= ctx
->type
)
1233 _mdns_debug_message(";; mdns is_complete ctx %p type mismatch (%d != %d) - incomplete\n", ctx
, ctx
->last_type
, ctx
->type
);
1241 if (ctx
->host
!= NULL
&& ctx
->host
->addr_count
> 0) complete
= true;
1244 if (ctx
->host
!= NULL
&& ctx
->host
->host
.h_name
!= NULL
) complete
= true;
1247 if (ctx
->reply
!= NULL
&& ctx
->reply
->srv
!= NULL
) complete
= true;
1250 _mdns_debug_message(";; mdns is_complete unexpected type %d ctx %p\n", ctx
->type
, ctx
);
1253 _mdns_debug_message(";; mdns is_complete type %d ctx %p %s%scomplete\n", ctx
->type
, ctx
, (ctx
->flags
& kDNSServiceFlagsMoreComing
) ? "(more coming flag ignored)" : "", complete
? " - " : " - in");
1260 * Clear out the temporary fields of the context, and clear any result
1261 * structures that are incomplete. Retrns 1 if the query was complete.
1264 _mdns_query_clear(mdns_query_context_t
*ctx
)
1266 bool complete
= _mdns_query_is_complete(ctx
);
1268 if (ctx
== NULL
) return complete
;
1270 if (ctx
->sd
!= NULL
)
1272 /* only dealloc this DNSServiceRef if the "main" _mdns_sdref has not been deallocated */
1273 if (ctx
->sd
!= NULL
&& ctx
->sd_gen
== _mdns_generation
)
1275 DNSServiceRefDeallocate(ctx
->sd
);
1286 _mdns_hostent_clear(ctx
->host
);
1294 _mdns_query_callback(DNSServiceRef sdRef
, DNSServiceFlags flags
, uint32_t ifIndex
, DNSServiceErrorType errorCode
, const char *fullname
, uint16_t rrtype
, uint16_t rrclass
, uint16_t rdlen
, const void *rdata
, uint32_t ttl
, void *ctx
)
1296 mdns_query_context_t
*context
;
1299 context
= (mdns_query_context_t
*)ctx
;
1301 context
->flags
= flags
;
1302 context
->error
= errorCode
;
1303 context
->last_type
= rrtype
;
1305 if (errorCode
!= kDNSServiceErr_NoError
)
1307 _mdns_debug_message(";; [%s type %hu class %hu]: error %d [ctx %p]\n", fullname
, rrtype
, rrclass
, errorCode
, context
);
1311 /* embed the scope ID into link-local IPv6 addresses */
1312 if ((rrtype
== ns_t_aaaa
) && (rdlen
== sizeof(struct in6_addr
)) && IN6_IS_ADDR_LINKLOCAL((struct in6_addr
*)rdata
))
1314 memcpy(&a6
, rdata
, rdlen
);
1315 a6
.__u6_addr
.__u6_addr16
[1] = htons(ifIndex
);
1319 if (context
->reply
!= NULL
)
1323 mdns_reply_t
*reply
= context
->reply
;
1325 if (reply
->ifnum
== 0) reply
->ifnum
= ifIndex
;
1327 _mdns_hostent_append_alias(context
->host
, fullname
);
1328 if ((reply
->ttl
== 0) || (ttl
< reply
->ttl
)) reply
->ttl
= ttl
;
1335 if ((context
->host
!= NULL
) &&
1336 ((((rrtype
== ns_t_a
) && (context
->host
->host
.h_addrtype
== AF_INET
)) || ((rrtype
== ns_t_aaaa
) && (context
->host
->host
.h_addrtype
== AF_INET6
))) &&
1337 (rdlen
>= context
->host
->host
.h_length
)))
1339 if (context
->host
->host
.h_name
== NULL
)
1342 mdns_hostent_t
*h
= context
->host
;
1343 char *h_name
= _mdns_canonicalize(fullname
);
1344 context
->host
->host
.h_name
= h_name
;
1346 /* 6863416 remove h_name from h_aliases */
1347 for (i
= 0; i
< h
->alias_count
; ++i
)
1349 if (h_name
== NULL
) break;
1351 if (string_equal(h
->host
.h_aliases
[i
], h_name
))
1353 /* includes trailing NULL pointer */
1354 int sz
= sizeof(char *) * (h
->alias_count
- i
);
1355 free(h
->host
.h_aliases
[i
]);
1356 memmove(&h
->host
.h_aliases
[i
], &h
->host
.h_aliases
[i
+1], sz
);
1357 h
->alias_count
-= 1;
1363 _mdns_hostent_append_addr(context
->host
, rdata
, context
->host
->host
.h_length
);
1374 name
= _mdns_parse_domain_name(rdata
, rdlen
);
1375 if (name
== NULL
) malformed
= 1;
1377 _mdns_hostent_append_alias(context
->host
, name
);
1378 _mdns_debug_message(";; [%s type %hu class %hu] cname %s [ctx %p]\n", fullname
, rrtype
, rrclass
, name
, context
);
1384 name
= _mdns_parse_domain_name(rdata
, rdlen
);
1385 if (name
== NULL
) malformed
= 1;
1387 if ((context
->host
!= NULL
) && (context
->host
->host
.h_name
== NULL
))
1389 context
->host
->host
.h_name
= _mdns_canonicalize(name
);
1392 _mdns_hostent_append_alias(context
->host
, name
);
1398 mdns_rr_srv_t
*p
= (mdns_rr_srv_t
*)rdata
;
1399 mdns_srv_t
*srv
= calloc(1, sizeof(mdns_srv_t
));
1400 if (srv
== NULL
) break;
1402 if (rdlen
< sizeof(mdns_rr_srv_t
))
1408 srv
->srv
.priority
= ntohs(p
->priority
);
1409 srv
->srv
.weight
= ntohs(p
->weight
);
1410 srv
->srv
.port
= ntohs(p
->port
);
1411 srv
->srv
.target
= _mdns_parse_domain_name(&p
->target
[0], rdlen
- 3*sizeof(uint16_t));
1413 if (srv
->srv
.target
== NULL
)
1419 /* append to the end of the list */
1420 if (reply
->srv
== NULL
)
1426 mdns_srv_t
*iter
= reply
->srv
;
1427 while (iter
->next
) iter
= iter
->next
;
1435 malformed
= _mdns_debug
;
1442 _mdns_debug_message(";; [%s type %hu class %hu]: malformed reply [ctx %p]\n", fullname
, rrtype
, rrclass
, context
);
1447 if (context
->answer
!= NULL
)
1452 size_t buflen
= context
->ansmaxlen
- context
->anslen
;
1454 if (buflen
< NS_HFIXEDSZ
)
1456 _mdns_debug_message(";; [%s type %hu class %hu]: malformed reply (too small) [ctx %p]\n", fullname
, rrtype
, rrclass
, context
);
1460 cp
= context
->answer
+ context
->anslen
;
1462 n
= _mdns_pack_domain_name(fullname
, cp
, buflen
);
1465 _mdns_debug_message(";; [%s type %hu class %hu]: name mismatch [ctx %p]\n", fullname
, rrtype
, rrclass
, context
);
1470 * check that there is enough space in the buffer for the
1471 * resource name (n), the resource record data (rdlen) and
1472 * the resource record header (10).
1474 if (buflen
< (n
+ rdlen
+ 10))
1476 _mdns_debug_message(";; [%s type %hu class %hu]: insufficient buffer space for reply [ctx %p]\n", fullname
, rrtype
, rrclass
, context
);
1486 word
= htons(rrtype
);
1487 memcpy(cp
, &word
, sizeof(word
));
1490 word
= htons(rrclass
);
1491 memcpy(cp
, &word
, sizeof(word
));
1494 longword
= htonl(ttl
);
1495 memcpy(cp
, &longword
, sizeof(longword
));
1496 cp
+= sizeof(longword
);
1498 word
= htons(rdlen
);
1499 memcpy(cp
, &word
, sizeof(word
));
1502 memcpy(cp
, rdata
, rdlen
);
1505 ans
= (HEADER
*)context
->answer
;
1506 ans
->ancount
= htons(ntohs(ans
->ancount
) + 1);
1508 context
->anslen
= (size_t)(cp
- context
->answer
);
1511 _mdns_debug_message(";; [%s type %hu class %hu] reply [ctx %p]\n", fullname
, rrtype
, rrclass
, context
);
1515 /* Ping the waiting thread in case this callback was invoked on another */
1516 if (context
->kq
!= -1)
1519 EV_SET(&ev
, 1, EVFILT_USER
, 0, NOTE_TRIGGER
, 0, 0);
1520 int res
= kevent(context
->kq
, &ev
, 1, NULL
, 0, NULL
);
1521 if (res
!= 0) _mdns_debug_message(";; kevent EV_TRIGGER: %s [ctx %p]\n", strerror(errno
), context
);
1526 _mdns_now(struct timespec
*now
)
1529 gettimeofday(&tv
, NULL
);
1530 now
->tv_sec
= tv
.tv_sec
;
1531 now
->tv_nsec
= tv
.tv_usec
* 1000;
1535 _mdns_add_time(struct timespec
*sum
, const struct timespec
*a
, const struct timespec
*b
)
1537 sum
->tv_sec
= a
->tv_sec
+ b
->tv_sec
;
1538 sum
->tv_nsec
= a
->tv_nsec
+ b
->tv_nsec
;
1540 if (sum
->tv_nsec
> 1000000000)
1542 sum
->tv_sec
+= (sum
->tv_nsec
/ 1000000000);
1543 sum
->tv_nsec
%= 1000000000;
1547 /* calculate a deadline from the current time based on the desired timeout */
1549 _mdns_deadline(struct timespec
*deadline
, const struct timespec
*delta
)
1551 struct timespec now
;
1553 _mdns_add_time(deadline
, &now
, delta
);
1557 _mdns_sub_time(struct timespec
*delta
, const struct timespec
*a
, const struct timespec
*b
)
1559 delta
->tv_sec
= a
->tv_sec
- b
->tv_sec
;
1560 delta
->tv_nsec
= a
->tv_nsec
- b
->tv_nsec
;
1562 if (delta
->tv_nsec
< 0)
1564 delta
->tv_nsec
+= 1000000000;
1569 /* calculate a timeout remaining before the given deadline */
1571 _mdns_timeout(struct timespec
*timeout
, const struct timespec
*deadline
)
1573 struct timespec now
;
1575 _mdns_sub_time(timeout
, deadline
, &now
);
1579 _mdns_search(const char *name
, int class, int type
, const char *interface
, DNSServiceFlags flags
, uint8_t *answer
, uint32_t *anslen
, mdns_reply_t
*reply
)
1581 DNSServiceErrorType err
= 0;
1584 struct timespec start
, finish
, delta
, timeout
;
1586 int i
, got_a_response
= 0;
1587 bool complete
, initialize
= true;
1589 uint32_t n_iface_4
= 0;
1591 /* determine number of IPv4 interfaces (ignore loopback) */
1592 si_inet_config(&n_iface_4
, NULL
);
1593 if (n_iface_4
> 0) n_iface_4
--;
1595 /* <rdar://problem/7732497> limit the number of initialization retries */
1596 int initialize_retries
= 3;
1598 /* 2 for A and AAAA parallel queries */
1600 mdns_query_context_t ctx
[2];
1602 if (name
== NULL
) return -1;
1604 #if TARGET_OS_EMBEDDED
1605 /* log a warning for queries from the main thread */
1606 if (pthread_is_threaded_np() && pthread_main_np()) asl_log(NULL
, NULL
, ASL_LEVEL_WARNING
, "Warning: Libinfo call to mDNSResponder on main thread");
1607 #endif /* TARGET_OS_EMBEDDED */
1611 * The kevent(2) API timeout parameter is used to enforce the total
1612 * timeout of the DNS query. Each iteraion recalculates the relative
1613 * timeout based on the desired end time (total timeout from origin).
1615 * In order to workaround some DNS configurations that do not return
1616 * responses for AAAA queries, parallel queries modify the total
1617 * timeout upon receipt of the first response. The new total timeout is
1618 * set to an effective value of 2N where N is the time taken to receive
1619 * the A response (the original total timeout is preserved if 2N would
1620 * have exceeded it). However, since mDNSResponder caches values, a
1621 * minimum value of 50ms for N is enforced in order to give some time
1622 * for the receipt of a AAAA response.
1625 /* determine the maximum time to wait for a result */
1626 delta
.tv_sec
= RES_MAXRETRANS
+ 5;
1628 _mdns_deadline(&finish
, &delta
);
1632 for (i
= 0; i
< 2; ++i
) memset(&ctx
[i
], 0 , sizeof(mdns_query_context_t
));
1634 /* set up the kqueue */
1636 EV_SET(&ev
, 1, EVFILT_USER
, EV_ADD
| EV_CLEAR
, 0, 0, 0);
1637 n
= kevent(kq
, &ev
, 1, NULL
, 0, NULL
);
1638 if (n
!= 0) wait
= false;
1645 pthread_mutex_lock(&_mdns_mutex
);
1647 /* clear any stale contexts */
1648 for (i
= 0; i
< n_ctx
; ++i
) _mdns_query_clear(&ctx
[i
]);
1651 if (_mdns_sdref
== NULL
)
1653 if (_mdns_old_sdref
!= NULL
)
1656 DNSServiceRefDeallocate(_mdns_old_sdref
);
1657 _mdns_old_sdref
= NULL
;
1660 /* (re)initialize the shared connection */
1661 err
= DNSServiceCreateConnection(&_mdns_sdref
);
1663 /* limit the number of retries */
1664 if ((initialize_retries
-- <= 0) && (err
== 0)) err
= kDNSServiceErr_Unknown
;
1668 pthread_mutex_unlock(&_mdns_mutex
);
1674 * issue (or reissue) the queries
1675 * unspecified type: do parallel A and AAAA
1679 err
= _mdns_query_start(&ctx
[n_ctx
++], reply
, answer
, anslen
, name
, class, (type
== 0) ? ns_t_a
: type
, interface
, flags
, kq
);
1682 if ((err
== 0) && (type
== 0))
1684 err
= _mdns_query_start(&ctx
[n_ctx
++], reply
, answer
, anslen
, name
, class, ns_t_aaaa
, interface
, flags
, kq
);
1687 if (err
!= 0) _mdns_debug_message(";; initialization error %d\n", err
);
1689 /* try to reinitialize */
1690 if ((err
== kDNSServiceErr_Unknown
) || (err
== kDNSServiceErr_ServiceNotRunning
) || (err
== kDNSServiceErr_BadReference
))
1692 if (_mdns_sdref
!= NULL
)
1695 DNSServiceRefDeallocate(_mdns_sdref
);
1701 pthread_mutex_unlock(&_mdns_mutex
);
1706 pthread_mutex_unlock(&_mdns_mutex
);
1710 /* (re)register the fd with kqueue */
1711 int fd
= DNSServiceRefSockFD(_mdns_sdref
);
1712 EV_SET(&ev
, fd
, EVFILT_READ
, EV_ADD
, 0, 0, 0);
1713 n
= kevent(kq
, &ev
, 1, NULL
, 0, NULL
);
1714 pthread_mutex_unlock(&_mdns_mutex
);
1715 if (err
!= 0 || n
!= 0) break;
1718 _mdns_debug_message(";; set kevent timeout %ld.%ld [ctx %p %p]\n", timeout
.tv_sec
, timeout
.tv_nsec
, (n_ctx
> 0) ? &(ctx
[0]) : NULL
, (n_ctx
> 1) ? &(ctx
[1]) : NULL
);
1720 n
= kevent(kq
, NULL
, 0, &ev
, 1, &timeout
);
1721 if ((n
< 0) && (errno
!= EINTR
))
1727 pthread_mutex_lock(&_mdns_mutex
);
1730 * DNSServiceProcessResult() is a blocking API
1731 * confirm that there is still data on the socket
1733 const struct timespec notimeout
= { 0, 0 };
1734 int m
= kevent(kq
, NULL
, 0, &ev
, 1, ¬imeout
);
1736 if (_mdns_sdref
== NULL
)
1740 else if (m
> 0 && ev
.filter
== EVFILT_READ
)
1742 err
= DNSServiceProcessResult(_mdns_sdref
);
1743 if ((err
== kDNSServiceErr_ServiceNotRunning
) || (err
== kDNSServiceErr_BadReference
))
1745 _mdns_debug_message(";; DNSServiceProcessResult status %d [ctx %p %p]\n", err
, (n_ctx
> 0) ? &(ctx
[0]) : NULL
, (n_ctx
> 1) ? &(ctx
[1]) : NULL
);
1748 /* re-initialize the shared connection */
1750 DNSServiceRefDeallocate(_mdns_sdref
);
1756 /* Check if all queries are complete (including errors) */
1758 for (i
= 0; i
< n_ctx
; ++i
)
1760 if ((ctx
[i
].error
!= 0) || _mdns_query_is_complete(&ctx
[i
]))
1762 if (ctx
[i
].type
== ns_t_a
)
1764 got_a_response
= GOT_DATA
;
1765 if (ctx
[i
].error
!= 0) got_a_response
= GOT_ERROR
;
1768 _mdns_debug_message(";; [%s type %d class %d] finished processing ctx %p\n", name
, type
, class, &(ctx
[i
]));
1772 _mdns_debug_message(";; [%s type %d class %d] continuing ctx %p\n", name
, type
, class, &(ctx
[i
]));
1777 pthread_mutex_unlock(&_mdns_mutex
);
1781 _mdns_debug_message(";; DNSServiceProcessResult error status %d [ctx %p %p]\n", err
, (n_ctx
> 0) ? &(ctx
[0]) : NULL
, (n_ctx
> 1) ? &(ctx
[1]) : NULL
);
1786 _mdns_debug_message(";; [%s type %d class %d] done [ctx %p %p]\n", name
, type
, class, (n_ctx
> 0) ? &(ctx
[0]) : NULL
, (n_ctx
> 1) ? &(ctx
[1]) : NULL
);
1789 else if (got_a_response
!= 0)
1791 /* got A, adjust deadline for AAAA */
1792 struct timespec now
, tn
, extra
;
1794 /* delta = now - start */
1796 _mdns_sub_time(&delta
, &now
, &start
);
1798 extra
.tv_sec
= SHORT_AAAA_EXTRA
;
1801 /* if delta is small (<= 20 milliseconds), we probably got a result from mDNSResponder's cache */
1802 if ((delta
.tv_sec
== 0) && (delta
.tv_nsec
<= 20000000))
1804 extra
.tv_sec
= MEDIUM_AAAA_EXTRA
;
1806 else if (n_iface_4
== 0)
1808 extra
.tv_sec
= LONG_AAAA_EXTRA
;
1810 else if (got_a_response
== GOT_ERROR
)
1812 extra
.tv_sec
= MEDIUM_AAAA_EXTRA
;
1815 /* tn = 2 * delta */
1816 _mdns_add_time(&tn
, &delta
, &delta
);
1818 /* delta = tn + extra */
1819 _mdns_add_time(&delta
, &tn
, &extra
);
1821 /* check that delta doesn't exceed our total timeout */
1822 _mdns_sub_time(&tn
, &timeout
, &delta
);
1825 _mdns_debug_message(";; new timeout [%s type %d class %d] (waiting for AAAA) %ld.%ld [ctx %p %p]\n", name
, type
, class, delta
.tv_sec
, delta
.tv_nsec
, (n_ctx
> 0) ? &(ctx
[0]) : NULL
, (n_ctx
> 1) ? &(ctx
[1]) : NULL
);
1826 _mdns_deadline(&finish
, &delta
);
1830 /* calculate remaining timeout */
1831 _mdns_timeout(&timeout
, &finish
);
1833 /* check for time remaining */
1834 if (timeout
.tv_sec
< 0)
1836 _mdns_debug_message(";; [%s type %d class %d] timeout [ctx %p %p]\n", name
, type
, class, (n_ctx
> 0) ? &(ctx
[0]) : NULL
, (n_ctx
> 1) ? &(ctx
[1]) : NULL
);
1842 pthread_mutex_lock(&_mdns_mutex
);
1844 for (i
= 0; i
< n_ctx
; ++i
)
1846 if (err
== 0) err
= ctx
[i
].error
;
1847 /* only clears hostents if result is incomplete */
1848 complete
= _mdns_query_clear(&ctx
[i
]) | complete
;
1851 pthread_mutex_unlock(&_mdns_mutex
);
1853 /* everything should be done with the kq by now */
1856 /* return error if everything is incomplete */
1857 if (!complete
) res
= -1;
1859 if (anslen
!= NULL
) *anslen
= ctx
[0].anslen
;