]> git.saurik.com Git - apple/libinfo.git/blob - lookup.subproj/mdns_module.c
5c4c120c41bbc439dd37b4e1e6553e32a7b2e844
[apple/libinfo.git] / lookup.subproj / mdns_module.c
1 /*
2 * Copyright (c) 2008-2015 Apple Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
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
11 * file.
12 *
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.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23 /*
24 * Portions Copyright (c) 1996-1999 by Internet Software Consortium.
25 *
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.
29 *
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
37 * SOFTWARE.
38 */
39 /*
40 * Copyright (c) 1988, 1993
41 * The Regents of the University of California. All rights reserved.
42 *
43 * Redistribution and use in source and binary forms, with or without
44 * modification, are permitted provided that the following conditions
45 * are met:
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.
54 *
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
65 * SUCH DAMAGE.
66 */
67 /*
68 * Portions Copyright (c) 1993 by Digital Equipment Corporation.
69 *
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.
76 *
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
84 * SOFTWARE.
85 */
86
87 #include "ils.h"
88 #include "netdb.h"
89 #include "si_module.h"
90
91 #include <assert.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>
97 #include <ctype.h>
98 #include <dns_sd.h>
99 #include <dnsinfo.h>
100 #include <errno.h>
101 #include <nameser.h>
102 #include <notify.h>
103 #include <pthread.h>
104 #include <resolv.h>
105 #include <stdio.h>
106 #include <stdlib.h>
107 #include <string.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>
113 #include <net/if.h>
114 #include <time.h>
115 #include <unistd.h>
116 #include <asl.h>
117 #include <dns.h>
118 #include <dns_util.h>
119 #include <TargetConditionals.h>
120 #include <dispatch/dispatch.h>
121
122 /* from dns_util.c */
123 #define DNS_MAX_RECEIVE_SIZE 65536
124
125 #define INET_NTOP_AF_INET_OFFSET 4
126 #define INET_NTOP_AF_INET6_OFFSET 8
127
128 #define IPPROTO_UNSPEC 0
129
130 #define GOT_DATA 1
131 #define GOT_ERROR 2
132 #define SHORT_AAAA_EXTRA 2
133 #define MEDIUM_AAAA_EXTRA 5
134 #define LONG_AAAA_EXTRA 10
135
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
142 static int _mdns_debug = 0;
143
144 /* mutex protects DNSServiceProcessResult and DNSServiceRefDeallocate */
145 static pthread_mutex_t _mdns_mutex = PTHREAD_MUTEX_INITIALIZER;
146
147 typedef struct
148 {
149 uint16_t priority;
150 uint16_t weight;
151 uint16_t port;
152 uint8_t target[0];
153 } mdns_rr_srv_t;
154
155 typedef struct mdns_srv_t mdns_srv_t;
156 struct mdns_srv_t
157 {
158 si_srv_t srv;
159 mdns_srv_t *next;
160 };
161
162 typedef struct
163 {
164 struct hostent host;
165 int alias_count;
166 int addr_count;
167 } mdns_hostent_t;
168
169 typedef struct
170 {
171 mdns_hostent_t *h4;
172 mdns_hostent_t *h6;
173 mdns_srv_t *srv;
174 uint64_t ttl;
175 uint32_t ifnum;
176 } mdns_reply_t;
177
178 static uint32_t _mdns_generation = 0;
179 static DNSServiceRef _mdns_sdref;
180 static DNSServiceRef _mdns_old_sdref;
181
182 static void _mdns_hostent_clear(mdns_hostent_t *h);
183 static void _mdns_reply_clear(mdns_reply_t *r);
184 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);
185
186 static const char hexchar[] = "0123456789abcdef";
187
188 #define BILLION 1000000000
189
190 /* 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" */
191 #define IPv6_REVERSE_LEN 72
192
193 /* index of the trailing char that must be "8", "9", "A", "a", "b", or "B" */
194 #define IPv6_REVERSE_LINK_LOCAL_TRAILING_CHAR 58
195
196 /* index of low-order nibble of embedded scope id */
197 #define IPv6_REVERSE_LINK_LOCAL_SCOPE_ID_LOW 48
198
199 const static uint8_t hexval[128] = {
200 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0 - 15 */
201 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 16 - 31 */
202 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 32 - 47 */
203 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, /* 48 - 63 */
204 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 64 - 79 */
205 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80 - 95 */
206 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 96 - 111 */
207 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* 112 - 127 */
208 };
209
210 static void
211 _mdns_debug_message(const char *str, ...)
212 {
213 va_list v;
214 char *out = NULL;
215
216 if (str == NULL) return;
217 if ((_mdns_debug & MDNS_DEBUG_OUT) == 0) return;
218
219 va_start(v, str);
220 vasprintf(&out, str, v);
221 if (out == NULL) return;
222
223 if (_mdns_debug & MDNS_DEBUG_STDOUT) fprintf(stdout, "%s", out);
224 if (_mdns_debug & MDNS_DEBUG_STDERR) fprintf(stderr, "%s", out);
225 if (_mdns_debug & MDNS_DEBUG_ASL) asl_log_message(ASL_LEVEL_NOTICE, "%s", out);
226 free(out);
227
228 va_end(v);
229 }
230
231 static char *
232 _mdns_reverse_ipv4(const char *addr)
233 {
234 union
235 {
236 uint32_t a;
237 unsigned char b[4];
238 } ab;
239 char *p;
240
241 if (addr == NULL) return NULL;
242
243 memcpy(&(ab.a), addr, 4);
244
245 asprintf(&p, "%u.%u.%u.%u.in-addr.arpa.", ab.b[3], ab.b[2], ab.b[1], ab.b[0]);
246 return p;
247 }
248
249 static char *
250 _mdns_reverse_ipv6(const char *addr)
251 {
252 char x[65], *p;
253 int i, j;
254 u_int8_t d, hi, lo;
255
256 if (addr == NULL) return NULL;
257
258 x[64] = '\0';
259 j = 63;
260
261 for (i = 0; i < 16; i++)
262 {
263 d = addr[i];
264 lo = d & 0x0f;
265 hi = d >> 4;
266 x[j--] = '.';
267 x[j--] = hexchar[hi];
268 x[j--] = '.';
269 x[j--] = hexchar[lo];
270 }
271
272 asprintf(&p, "%sip6.arpa.", x);
273
274 return p;
275 }
276
277 /*
278 * _mdns_canonicalize
279 * Canonicalize the domain name by converting to lower case and removing the
280 * trailing '.' if present.
281 */
282 static char *
283 _mdns_canonicalize(const char *s)
284 {
285 int i;
286 char *t;
287
288 if (s == NULL) return NULL;
289
290 t = strdup(s);
291 if (t == NULL) return NULL;
292
293 if (t[0] == '\0') return t;
294
295 for (i = 0; t[i] != '\0'; i++)
296 {
297 if (t[i] >= 'A' && t[i] <= 'Z') t[i] += 32;
298 }
299
300 if (t[i-1] == '.') t[i-1] = '\0';
301
302 return t;
303 }
304
305 /*
306 * _mdns_hostent_append_alias
307 * Appends an alias to the mdns_hostent_t structure.
308 */
309 static int
310 _mdns_hostent_append_alias(mdns_hostent_t *h, const char *alias)
311 {
312 int i;
313 char *name;
314
315 _mdns_debug_message(";; _mdns_hostent_append_alias(%p, %s)\n", h, alias);
316 if ((h == NULL) || (alias == NULL)) return 0;
317
318 name = _mdns_canonicalize(alias);
319 if (name == NULL) return -1;
320
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))
323 {
324 free(name);
325 return 0;
326 }
327
328 for (i = 0; i < h->alias_count; ++i)
329 {
330 if (string_equal(h->host.h_aliases[i], name))
331 {
332 free(name);
333 return 0;
334 }
335 }
336
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)
340 {
341 h->alias_count = 0;
342 free(name);
343 return -1;
344 }
345
346 h->host.h_aliases[h->alias_count] = name;
347 h->alias_count++;
348
349 h->host.h_aliases[h->alias_count] = NULL;
350 return 0;
351 }
352
353 /*
354 * _mdns_hostent_append_addr
355 * Appends an alias to the mdns_hostent_t structure.
356 */
357 static int
358 _mdns_hostent_append_addr(mdns_hostent_t *h, const uint8_t *addr, uint32_t len)
359 {
360 _mdns_debug_message(";; _mdns_hostent_append_addr(%p, %p, %u)\n", h, addr, len);
361 if ((h == NULL) || (addr == NULL) || (len == 0)) return 0;
362
363 /* copy the address buffer */
364 uint8_t *buf = malloc(len);
365 if (buf == NULL) return -1;
366
367 memcpy(buf, addr, len);
368
369 /* add the address and NULL terminate the list if it is new */
370 h->host.h_addr_list = (char **)reallocf(h->host.h_addr_list, (h->addr_count + 2) * sizeof(char *));
371
372 if (h->host.h_addr_list == NULL)
373 {
374 h->addr_count = 0;
375 return -1;
376 }
377
378 h->host.h_addr_list[h->addr_count] = (char*)buf;
379 h->addr_count++;
380
381 h->host.h_addr_list[h->addr_count] = NULL;
382 return 0;
383 }
384
385 static void
386 _mdns_hostent_clear(mdns_hostent_t *h)
387 {
388 if (h == NULL) return;
389
390 free(h->host.h_name);
391 h->host.h_name = NULL;
392
393 char **aliases = h->host.h_aliases;
394 while (aliases && *aliases) free(*aliases++);
395
396 free(h->host.h_aliases);
397 h->host.h_aliases = NULL;
398 h->alias_count = 0;
399
400 char **addrs = h->host.h_addr_list;
401 while (addrs && *addrs) free(*addrs++);
402
403 free(h->host.h_addr_list);
404 h->host.h_addr_list = NULL;
405 h->addr_count = 0;
406 }
407
408 static void
409 _mdns_reply_clear(mdns_reply_t *r)
410 {
411 if (r == NULL) return;
412
413 r->ifnum = 0;
414 _mdns_hostent_clear(r->h4);
415 _mdns_hostent_clear(r->h6);
416 mdns_srv_t *srv = r->srv;
417 r->srv = NULL;
418
419 while (srv != NULL)
420 {
421 mdns_srv_t *next = srv->next;
422 free(srv->srv.target);
423 free(srv);
424 srv = next;
425 }
426 }
427
428 static si_item_t *
429 mdns_hostbyname(si_mod_t *si, const char *name, int af, const char *interface, uint32_t *err)
430 {
431 uint32_t type;
432 mdns_hostent_t h;
433 mdns_reply_t reply;
434 si_item_t *out = NULL;
435 uint64_t bb;
436 int status;
437 DNSServiceFlags flags = 0;
438
439 if (err != NULL) *err = SI_STATUS_NO_ERROR;
440
441 if ((name == NULL) || (si == NULL))
442 {
443 if (err != NULL) *err = SI_STATUS_H_ERRNO_NO_RECOVERY;
444 return NULL;
445 }
446
447 memset(&h, 0, sizeof(h));
448 memset(&reply, 0, sizeof(reply));
449
450 switch (af)
451 {
452 case AF_INET:
453 type = ns_t_a;
454 h.host.h_length = 4;
455 reply.h4 = &h;
456 break;
457 case AF_INET6:
458 type = ns_t_aaaa;
459 h.host.h_length = 16;
460 reply.h6 = &h;
461 break;
462 default:
463 if (err != NULL) *err = SI_STATUS_H_ERRNO_NO_RECOVERY;
464 return NULL;
465 }
466
467 _mdns_debug_message(";; mdns_hostbyname %s type %u class %u\n", name, type, ns_c_in);
468
469 h.host.h_addrtype = af;
470
471 status = _mdns_search(name, ns_c_in, type, interface, flags, NULL, NULL, &reply);
472 if ((status != 0) || (h.addr_count == 0))
473 {
474 _mdns_reply_clear(&reply);
475 if (err != NULL) *err = SI_STATUS_H_ERRNO_HOST_NOT_FOUND;
476 return NULL;
477 }
478
479 bb = reply.ttl + time(NULL);
480
481 switch (af)
482 {
483 case AF_INET:
484 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);
485 break;
486 case AF_INET6:
487 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);
488 break;
489 }
490
491 _mdns_reply_clear(&reply);
492
493 if ((out == NULL) && (err != NULL)) *err = SI_STATUS_H_ERRNO_NO_RECOVERY;
494
495 return out;
496 }
497
498 static si_item_t *
499 mdns_hostbyaddr(si_mod_t *si, const void *addr, int af, const char *interface, uint32_t *err)
500 {
501 mdns_hostent_t h;
502 mdns_reply_t reply;
503 char *name;
504 si_item_t *out;
505 uint64_t bb;
506 int cat;
507 int status;
508 DNSServiceFlags flags = 0;
509
510 if (err != NULL) *err = SI_STATUS_NO_ERROR;
511
512 if ((addr == NULL) || (si == NULL))
513 {
514 if (err != NULL) *err = SI_STATUS_H_ERRNO_NO_RECOVERY;
515 return NULL;
516 }
517
518 memset(&h, 0, sizeof(h));
519 memset(&reply, 0, sizeof(reply));
520
521 switch (af)
522 {
523 case AF_INET:
524 h.host.h_length = 4;
525 reply.h4 = &h;
526 name = _mdns_reverse_ipv4(addr);
527 cat = CATEGORY_HOST_IPV4;
528 break;
529 case AF_INET6:
530 h.host.h_length = 16;
531 reply.h6 = &h;
532 name = _mdns_reverse_ipv6(addr);
533 cat = CATEGORY_HOST_IPV6;
534 break;
535 default:
536 if (err != NULL) *err = SI_STATUS_H_ERRNO_NO_RECOVERY;
537 return NULL;
538 }
539
540 h.host.h_addrtype = af;
541
542 _mdns_debug_message(";; mdns_hostbyaddr %s type %u class %u\n", name, ns_t_ptr, ns_c_in);
543
544 status = _mdns_search(name, ns_c_in, ns_t_ptr, interface, flags, NULL, NULL, &reply);
545 free(name);
546 if (status != 0)
547 {
548 _mdns_reply_clear(&reply);
549 if (err != NULL) *err = SI_STATUS_H_ERRNO_HOST_NOT_FOUND;
550 return NULL;
551 }
552
553 status = _mdns_hostent_append_addr(&h, addr, h.host.h_length);
554 if (status != 0)
555 {
556 _mdns_hostent_clear(&h);
557 if (err != NULL) *err = SI_STATUS_H_ERRNO_NO_RECOVERY;
558 return NULL;
559 }
560
561 bb = reply.ttl + time(NULL);
562
563 switch (af)
564 {
565 case AF_INET:
566 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);
567 break;
568 case AF_INET6:
569 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);
570 break;
571 }
572
573 _mdns_hostent_clear(&h);
574
575 if ((out == NULL) && (err != NULL)) *err = SI_STATUS_H_ERRNO_NO_RECOVERY;
576 return out;
577 }
578
579 static si_list_t *
580 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)
581 {
582 bool wantv4 = true;
583 bool wantv6 = true;
584 struct in_addr a4;
585 struct in6_addr a6;
586 mdns_hostent_t h4;
587 mdns_hostent_t h6;
588 mdns_reply_t reply;
589 uint32_t type;
590 uint16_t port;
591
592 if (si == NULL)
593 {
594 if (err != NULL) *err = SI_STATUS_H_ERRNO_NO_RECOVERY;
595 return NULL;
596 }
597
598 if (family == AF_INET6)
599 {
600 if ((flags & AI_V4MAPPED) == 0) wantv4 = false;
601 }
602 else if (family == AF_INET)
603 {
604 wantv6 = false;
605 }
606 else if (family != AF_UNSPEC)
607 {
608 return NULL;
609 }
610
611 if (err != NULL) *err = SI_STATUS_NO_ERROR;
612
613 _mdns_debug_message(";; mdns_addrinfo node %s serv %s\n", (const char *)node, (const char *)serv);
614
615 si_list_t *out = NULL;
616
617 memset(&h4, 0, sizeof(h4));
618 memset(&h6, 0, sizeof(h6));
619 memset(&reply, 0, sizeof(reply));
620
621 h4.host.h_addrtype = AF_INET;
622 h4.host.h_length = 4;
623 h6.host.h_addrtype = AF_INET6;
624 h6.host.h_length = 16;
625
626 if (wantv4 && wantv6)
627 {
628 type = 0;
629 reply.h4 = &h4;
630 reply.h6 = &h6;
631 }
632 else if (wantv4)
633 {
634 reply.h4 = &h4;
635 type = ns_t_a;
636 }
637 else if (wantv6)
638 {
639 type = ns_t_aaaa;
640 reply.h6 = &h6;
641 }
642 else
643 {
644 if (err != NULL) *err = SI_STATUS_H_ERRNO_NO_RECOVERY;
645 return NULL;
646 }
647
648 /* service lookup */
649 if ((flags & AI_NUMERICSERV) != 0)
650 {
651 if (serv == NULL) port = 0;
652 else port = *(uint16_t *)serv;
653 }
654 else
655 {
656 if (_gai_serv_to_port(serv, proto, &port) != 0)
657 {
658 if (err) *err = SI_STATUS_EAI_NONAME;
659 return NULL;
660 }
661 }
662
663 /* host lookup */
664 if ((flags & AI_NUMERICHOST) != 0)
665 {
666 char *cname = NULL;
667 struct in_addr *p4 = NULL;
668 struct in6_addr *p6 = NULL;
669
670 if (node == NULL) return NULL;
671
672 if (family == AF_INET)
673 {
674 p4 = &a4;
675 memcpy(p4, node, sizeof(a4));
676 }
677 else if (family == AF_INET6)
678 {
679 p6 = &a6;
680 memcpy(p6, node, sizeof(a6));
681 }
682
683 out = si_addrinfo_list(si, flags, socktype, proto, p4, p6, port, 0, cname, cname);
684 }
685 else
686 {
687 int res;
688 DNSServiceFlags dns_flags = 0;
689
690 if (node == NULL) return NULL;
691
692 if (flags & AI_ADDRCONFIG)
693 {
694 dns_flags |= kDNSServiceFlagsSuppressUnusable;
695 }
696
697 res = _mdns_search(node, ns_c_in, type, interface, dns_flags, NULL, NULL, &reply);
698 if ((res == 0) && ((h4.addr_count > 0) || (h6.addr_count > 0)))
699 {
700 out = si_addrinfo_list_from_hostent(si, flags, socktype, proto, port, 0, (wantv4 ? &h4.host : NULL), (wantv6 ? &h6.host : NULL));
701 }
702 else if (err != NULL)
703 {
704 *err = SI_STATUS_EAI_NONAME;
705 }
706
707 _mdns_reply_clear(&reply);
708 }
709
710 return out;
711 }
712
713 static si_list_t *
714 mdns_srv_byname(si_mod_t* si, const char *qname, const char *interface, uint32_t *err)
715 {
716 si_list_t *out = NULL;
717 mdns_reply_t reply;
718 mdns_srv_t *srv;
719 int res;
720 const uint64_t unused = 0;
721 DNSServiceFlags flags = 0;
722
723 if (si == NULL)
724 {
725 if (err != NULL) *err = SI_STATUS_H_ERRNO_NO_RECOVERY;
726 return NULL;
727 }
728
729 if (err != NULL) *err = SI_STATUS_NO_ERROR;
730
731 _mdns_debug_message(";; mdns_srv_byname %s type %u class %u\n", qname, ns_t_srv, ns_c_in);
732
733 memset(&reply, 0, sizeof(reply));
734 res = _mdns_search(qname, ns_c_in, ns_t_srv, interface, flags, NULL, NULL, &reply);
735 if (res == 0)
736 {
737 srv = reply.srv;
738 while (srv != NULL)
739 {
740 si_item_t *item;
741 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);
742 out = si_list_add(out, item);
743 si_item_release(item);
744 srv = srv->next;
745 }
746 }
747
748 _mdns_reply_clear(&reply);
749 return out;
750 }
751
752 /*
753 * We support dns_async_start / cancel / handle_reply using dns_item_call
754 */
755 static si_item_t *
756 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)
757 {
758 int res;
759 uint8_t buf[DNS_MAX_RECEIVE_SIZE];
760 uint32_t len = sizeof(buf);
761 mdns_reply_t reply;
762 mdns_hostent_t h4;
763 mdns_hostent_t h6;
764 si_item_t *out;
765 DNSServiceFlags flags = 0;
766
767 if ((si == NULL) || (name == NULL))
768 {
769 if (err != NULL) *err = SI_STATUS_H_ERRNO_NO_RECOVERY;
770 return NULL;
771 }
772
773 if (err != NULL) *err = SI_STATUS_NO_ERROR;
774
775 _mdns_debug_message(";; mdns_item_call %s type %u class %u\n", name, type, class);
776
777 memset(&h4, 0, sizeof(h4));
778 memset(&h6, 0, sizeof(h6));
779 memset(&reply, 0, sizeof(reply));
780
781 h4.host.h_addrtype = AF_INET;
782 h4.host.h_length = 4;
783 h6.host.h_addrtype = AF_INET6;
784 h6.host.h_length = 16;
785 reply.h4 = &h4;
786 reply.h6 = &h6;
787
788 res = _mdns_search(name, class, type, interface, flags, buf, &len, &reply);
789 if ((res != 0) || (len <= 0) || (len > DNS_MAX_RECEIVE_SIZE))
790 {
791 _mdns_reply_clear(&reply);
792 if (err != NULL) *err = SI_STATUS_H_ERRNO_HOST_NOT_FOUND;
793 return NULL;
794 }
795
796 struct sockaddr_in6 from;
797 uint32_t fromlen = sizeof(from);
798 memset(&from, 0, fromlen);
799 from.sin6_len = fromlen;
800 from.sin6_family = AF_INET6;
801 from.sin6_addr.__u6_addr.__u6_addr8[15] = 1;
802
803 if (reply.ifnum != 0)
804 {
805 from.sin6_addr.__u6_addr.__u6_addr16[0] = htons(0xfe80);
806 from.sin6_scope_id = reply.ifnum;
807 }
808
809 out = (si_item_t *)LI_ils_create("L4488@@", (unsigned long)si, CATEGORY_DNSPACKET, 1, 0LL, 0LL, len, buf, fromlen, &from);
810 if ((out == NULL) && (err != NULL)) *err = SI_STATUS_H_ERRNO_NO_RECOVERY;
811
812 _mdns_reply_clear(&reply);
813
814 return out;
815 }
816
817 static int
818 mdns_is_valid(si_mod_t *si, si_item_t *item)
819 {
820 return 0;
821 }
822
823 static void
824 mdns_close(si_mod_t *si)
825 {
826 }
827
828 static void
829 _mdns_atfork_prepare(void)
830 {
831 /* acquire our lock so that we know all other threads have "drained" */
832 pthread_mutex_lock(&_mdns_mutex);
833 }
834
835 static void
836 _mdns_atfork_parent(void)
837 {
838 /* parent can simply resume */
839 pthread_mutex_unlock(&_mdns_mutex);
840 }
841
842 static void
843 _mdns_atfork_child(void)
844 {
845 /* child needs to force re-initialization */
846 _mdns_old_sdref = _mdns_sdref; // for later deallocation
847 _mdns_sdref = NULL;
848 pthread_mutex_unlock(&_mdns_mutex);
849 }
850
851 static void
852 _mdns_init(void)
853 {
854 pthread_atfork(_mdns_atfork_prepare, _mdns_atfork_parent, _mdns_atfork_child);
855
856 if (getenv("RES_DEBUG") != NULL) _mdns_debug |= MDNS_DEBUG_STDOUT;
857 int fd = open(MDNS_DEBUG_FILE, O_RDONLY, 0);
858 errno = 0;
859
860 if (fd >= 0)
861 {
862 int i, n;
863 char c[5];
864 memset(c, 0, sizeof(c));
865 n = read(fd, c, 4);
866
867 for (i = 0; i < n; i++)
868 {
869 if ((c[i] == 'o') || (c[i] == 'O')) _mdns_debug |= MDNS_DEBUG_STDOUT;
870 if ((c[i] == 'e') || (c[i] == 'E')) _mdns_debug |= MDNS_DEBUG_STDERR;
871 if ((c[i] == 'a') || (c[i] == 'A')) _mdns_debug |= MDNS_DEBUG_ASL;
872 }
873 }
874 }
875
876 si_mod_t *
877 si_module_static_mdns(void)
878 {
879 static const struct si_mod_vtable_s mdns_vtable =
880 {
881 .sim_close = &mdns_close,
882 .sim_is_valid = &mdns_is_valid,
883 .sim_host_byname = &mdns_hostbyname,
884 .sim_host_byaddr = &mdns_hostbyaddr,
885 .sim_item_call = &mdns_item_call,
886 .sim_addrinfo = &mdns_addrinfo,
887 .sim_srv_byname = &mdns_srv_byname,
888 };
889
890 static si_mod_t si =
891 {
892 .vers = 1,
893 .refcount = 1,
894 .flags = SI_MOD_FLAG_STATIC,
895
896 .private = NULL,
897 .vtable = &mdns_vtable,
898 };
899
900 static dispatch_once_t once;
901
902 dispatch_once(&once, ^{
903 si.name = strdup("mdns");
904 _mdns_init();
905 });
906
907 return (si_mod_t*)&si;
908 }
909
910 /*
911 * _mdns_parse_domain_name
912 * Combine DNS labels to form a string.
913 * DNSService API does not return compressed names.
914 */
915 static char *
916 _mdns_parse_domain_name(const uint8_t *data, uint32_t datalen)
917 {
918 int i = 0, j = 0;
919 uint32_t len;
920 uint32_t domainlen = 0;
921 char *domain = NULL;
922
923 if ((data == NULL) || (datalen == 0)) return NULL;
924
925 /*
926 * i: index into input data
927 * j: index into output string
928 */
929 while (datalen-- > 0)
930 {
931 len = data[i++];
932 domainlen += (len + 1);
933 domain = reallocf(domain, domainlen);
934
935 if (domain == NULL) return NULL;
936
937 if (len == 0) break; // DNS root (NUL)
938
939 if (j > 0)
940 {
941 domain[j++] = datalen ? '.' : '\0';
942 }
943
944 while ((len-- > 0) && (0 != datalen--))
945 {
946 if (data[i] == '.')
947 {
948 /* special case: escape the '.' with a '\' */
949 domain = reallocf(domain, ++domainlen);
950 if (domain == NULL) return NULL;
951
952 domain[j++] = '\\';
953 }
954
955 domain[j++] = data[i++];
956 }
957 }
958
959 domain[j] = '\0';
960
961 return domain;
962 }
963
964 /*
965 * _mdns_pack_domain_name
966 * Format the string as packed DNS labels.
967 * Only used for one string at a time, therefore no need for compression.
968 */
969 static int
970 _mdns_pack_domain_name(const char *str, uint8_t *buf, size_t buflen)
971 {
972 int i = 0;
973 uintptr_t len = 0;
974
975 if ((str == NULL) || (buf == NULL)) return -1;
976
977 while (i < buflen)
978 {
979 /* calculate length to next '.' or '\0' */
980 char *dot = strchr(str, '.');
981 if (dot == NULL) dot = strchr(str, '\0');
982
983 len = (dot - str);
984 if (len > NS_MAXLABEL) return -1;
985
986 /* copy data for label */
987 buf[i++] = len;
988 while (str < dot && i < buflen)
989 {
990 buf[i++] = *str++;
991 }
992
993 /* skip past '.', break if '\0' */
994 if (*str++ == '\0') break;
995 }
996
997 if (i >= buflen) return -1;
998
999 if (len > 0)
1000 {
1001 /* no trailing dot - add a null label */
1002 buf[i++] = 0;
1003 if (i >= buflen) return -1;
1004 }
1005
1006 buf[i] = '\0';
1007 return i;
1008 }
1009
1010 static int
1011 _is_rev_link_local(const char *name)
1012 {
1013 int len, i;
1014
1015 if (name == NULL) return 0;
1016
1017 len = strlen(name);
1018 if (len == 0) return 0;
1019
1020 /* check for trailing '.' */
1021 if (name[len - 1] == '.') len--;
1022
1023 if (len != IPv6_REVERSE_LEN) return 0;
1024
1025 i = IPv6_REVERSE_LINK_LOCAL_TRAILING_CHAR;
1026 if ((name[i] != '8') && (name[i] != '9') && (name[i] != 'A') && (name[i] != 'a') && (name[i] != 'B') && (name[i] != 'b')) return 0;
1027
1028 i = IPv6_REVERSE_LINK_LOCAL_TRAILING_CHAR + 1;
1029 if (strncasecmp(name + i, ".e.f.ip6.arpa", 13)) return 0;
1030
1031 for (i = 0; i < IPv6_REVERSE_LINK_LOCAL_TRAILING_CHAR; i += 2)
1032 {
1033 if (name[i] < '0') return 0;
1034 if ((name[i] > '9') && (name[i] < 'A')) return 0;
1035 if ((name[i] > 'F') && (name[i] < 'a')) return 0;
1036 if (name[i] > 'f') return 0;
1037 if (name[i + 1] != '.') return 0;
1038 }
1039
1040 return 1;
1041 }
1042
1043 /*
1044 * _mdns_ipv6_extract_scope_id
1045 * If the input string is a link local IPv6 address with an encoded scope id,
1046 * the scope id is extracted and a new string is constructed with the scope id removed.
1047 */
1048 static char *
1049 _mdns_ipv6_extract_scope_id(const char *name, uint32_t *out_ifnum)
1050 {
1051 char *qname = NULL;
1052 uint16_t nibble;
1053 uint32_t iface;
1054 int i;
1055
1056 if (out_ifnum != NULL) *out_ifnum = 0;
1057 if (name == NULL) return NULL;
1058
1059 /* examine the address, extract the scope id if present */
1060 if (_is_rev_link_local(name))
1061 {
1062 /* _is_rev_link_local rejects chars > 127 so it's safe to index into hexval */
1063 i = IPv6_REVERSE_LINK_LOCAL_SCOPE_ID_LOW;
1064 nibble = hexval[(uint32_t)name[i]];
1065 iface = nibble;
1066
1067 i += 2;
1068 nibble = hexval[(uint32_t)name[i]];
1069 iface += (nibble << 4);
1070
1071 i += 2;
1072 nibble = hexval[(uint32_t)name[i]];
1073 iface += (nibble << 8);
1074
1075 i += 2;
1076 nibble = hexval[(uint32_t)name[i]];
1077 iface += (nibble << 12);
1078
1079 if (iface != 0)
1080 {
1081 qname = strdup(name);
1082 if (qname == NULL) return NULL;
1083
1084 i = IPv6_REVERSE_LINK_LOCAL_SCOPE_ID_LOW;
1085 qname[i] = '0';
1086 qname[i + 2] = '0';
1087 qname[i + 4] = '0';
1088 qname[i + 6] = '0';
1089
1090 if (out_ifnum) *out_ifnum = iface;
1091 }
1092 }
1093
1094 return qname;
1095 }
1096
1097 static int
1098 _mdns_make_query(const char* name, int class, int type, uint8_t *buf, uint32_t buflen)
1099 {
1100 uint32_t len = 0;
1101
1102 if ((buf == NULL) || (buflen < (NS_HFIXEDSZ + NS_QFIXEDSZ))) return -1;
1103
1104 memset(buf, 0, NS_HFIXEDSZ);
1105 HEADER *hp = (HEADER *)buf;
1106
1107 len += NS_HFIXEDSZ;
1108 hp->id = arc4random();
1109 hp->qr = 1;
1110 hp->opcode = ns_o_query;
1111 hp->rd = 1;
1112 hp->rcode = ns_r_noerror;
1113 hp->qdcount = htons(1);
1114
1115 int n = _mdns_pack_domain_name(name, &buf[len], buflen - len);
1116 if (n < 0) return -1;
1117
1118 len += n;
1119 uint16_t word;
1120 word = htons(type);
1121 memcpy(&buf[len], &word, sizeof(word));
1122 len += sizeof(word);
1123 word = htons(class);
1124 memcpy(&buf[len], &word, sizeof(word));
1125 len += sizeof(word);
1126
1127 return len;
1128 }
1129
1130 typedef struct mdns_query_context_s
1131 {
1132 mdns_reply_t *reply;
1133 mdns_hostent_t *host;
1134 uint8_t *answer; // DNS packet buffer
1135 size_t anslen; // DNS packet buffer current length
1136 size_t ansmaxlen; // DNS packet buffer maximum length
1137 int type; // type of query: A, AAAA, PTR, SRV...
1138 uint16_t last_type; // last type received
1139 uint32_t sd_gen;
1140 DNSServiceRef sd;
1141 DNSServiceFlags flags;
1142 DNSServiceErrorType error;
1143 int kq; // kqueue to notify when callback received
1144 struct mdns_query_context_s *next; // linked list
1145 } mdns_query_context_t;
1146
1147 static mdns_query_context_t *in_flight;
1148
1149 static void
1150 _mdns_query_callback(DNSServiceRef, DNSServiceFlags, uint32_t, DNSServiceErrorType, const char *, uint16_t, uint16_t, uint16_t, const void *, uint32_t, void *);
1151
1152 /*
1153 * _mdns_query_start
1154 * initializes the context and starts a DNS-SD query.
1155 */
1156 static DNSServiceErrorType
1157 _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)
1158 {
1159 DNSServiceErrorType status;
1160
1161 flags |= kDNSServiceFlagsShareConnection;
1162 flags |= kDNSServiceFlagsReturnIntermediates;
1163
1164 /* <rdar://problem/7428439> mDNSResponder is now responsible for timeouts */
1165 flags |= kDNSServiceFlagsTimeout;
1166
1167 memset(ctx, 0, sizeof(mdns_query_context_t));
1168
1169 if ((answer != NULL) && (anslen != NULL))
1170 {
1171 /* build a dummy DNS header to return to the caller */
1172 ctx->answer = answer;
1173 ctx->ansmaxlen = *anslen;
1174 ctx->anslen = _mdns_make_query(name, class, type, answer, ctx->ansmaxlen);
1175 if (ctx->anslen <= 0) return -1;
1176 }
1177
1178 ctx->type = type;
1179 ctx->sd = _mdns_sdref;
1180 ctx->sd_gen = _mdns_generation;
1181 ctx->kq = kq;
1182
1183 if (reply != NULL)
1184 {
1185 ctx->reply = reply;
1186 if (type == ns_t_a) ctx->host = reply->h4;
1187 else if (type == ns_t_aaaa) ctx->host = reply->h6;
1188 else if (type == ns_t_ptr && reply->h4) ctx->host = reply->h4;
1189 else if (type == ns_t_ptr && reply->h6) ctx->host = reply->h6;
1190 else if (type != ns_t_srv && type != ns_t_cname) return -1;
1191 }
1192
1193 uint32_t iface = 0;
1194 char *qname = _mdns_ipv6_extract_scope_id(name, &iface);
1195 if (qname == NULL) qname = (char *)name;
1196
1197 if (interface != NULL)
1198 {
1199 /* get interface number from name */
1200 int iface2 = if_nametoindex(interface);
1201
1202 /* balk if interface name lookup failed */
1203 if (iface2 == 0) return -1;
1204
1205 /* balk if scope id is set AND interface is given AND they don't match */
1206 if ((iface != 0) && (iface2 != 0) && (iface != iface2)) return -1;
1207 if (iface2 != 0) iface = iface2;
1208 }
1209
1210 _mdns_debug_message(";; mdns query %s type %d class %d [ctx %p]\n", qname, type, class, ctx);
1211
1212 status = DNSServiceQueryRecord(&ctx->sd, flags, iface, qname, type, class, _mdns_query_callback, ctx);
1213 if (qname != name) free(qname);
1214
1215 /* keep a linked list of all in-flight queries */
1216 ctx->next = in_flight;
1217 in_flight = ctx;
1218
1219 return status;
1220 }
1221
1222 /*
1223 * _mdns_query_is_complete
1224 * Determines whether the specified query has sufficient information to be
1225 * considered complete.
1226 */
1227 static bool
1228 _mdns_query_is_complete(mdns_query_context_t *ctx, bool *more)
1229 {
1230 bool complete = false;
1231
1232 /* NULL context is an error, but we call it complete */
1233 if (ctx == NULL) return true;
1234
1235 /* not complete if discoveryd says there is more coming (for some in-flight query - possibly not this one) */
1236 if (ctx->flags & kDNSServiceFlagsMoreComing)
1237 {
1238 if (more != NULL) *more = true;
1239 _mdns_debug_message(";; mdns is_complete type %d ctx %p more coming - incomplete\n", ctx->type, ctx);
1240 return false;
1241 } else {
1242 if (more != NULL) *more = false;
1243 _mdns_debug_message(";; mdns is_complete type %d ctx %p clear more coming - complete\n", ctx->type, ctx);
1244 }
1245
1246 if (ctx->last_type != ctx->type)
1247 {
1248 _mdns_debug_message(";; mdns is_complete ctx %p type mismatch (%d != %d) - incomplete\n", ctx, ctx->last_type, ctx->type);
1249 return false;
1250 }
1251
1252 switch (ctx->type)
1253 {
1254 case ns_t_a:
1255 case ns_t_aaaa:
1256 if (ctx->host != NULL && ctx->host->addr_count > 0)
1257 {
1258 _mdns_debug_message(";; mdns is_complete type %d ctx %p host addr count %d complete -> true\n", ctx->type, ctx, ctx->host->addr_count);
1259 complete = true;
1260 }
1261 break;
1262 case ns_t_ptr:
1263 if (ctx->host != NULL && ctx->host->host.h_name != NULL)
1264 {
1265 complete = true;
1266 _mdns_debug_message(";; mdns is_complete type %d ctx %p host name %s complete -> true\n", ctx->type, ctx, ctx->host->host.h_name);
1267 }
1268 break;
1269 case ns_t_srv:
1270 if (ctx->reply != NULL && ctx->reply->srv != NULL)
1271 {
1272 _mdns_debug_message(";; mdns is_complete type %d ctx %p srv %s complete -> true\n", ctx->type, ctx, ctx->reply->srv);
1273 complete = true;
1274 }
1275 break;
1276 default:
1277 _mdns_debug_message(";; mdns is_complete unexpected type %d ctx %p\n", ctx->type, ctx);
1278 }
1279
1280 _mdns_debug_message(";; mdns is_complete type %d ctx %p %scomplete\n", ctx->type, ctx, complete ? " - " : " - in");
1281
1282 return complete;
1283 }
1284
1285 /*
1286 * _mdns_query_clear
1287 * Clear out the temporary fields of the context, and clear any result
1288 * structures that are incomplete. Returns true if the query was complete.
1289 */
1290 static bool
1291 _mdns_query_clear(mdns_query_context_t *ctx)
1292 {
1293 mdns_query_context_t *p;
1294
1295 if (ctx == NULL) return true;
1296
1297 bool more = false;
1298 bool complete = _mdns_query_is_complete(ctx, &more);
1299
1300 if (ctx->sd != NULL)
1301 {
1302 /* only dealloc this DNSServiceRef if the "main" _mdns_sdref has not been deallocated */
1303 if (ctx->sd != NULL && ctx->sd_gen == _mdns_generation)
1304 {
1305 DNSServiceRefDeallocate(ctx->sd);
1306 }
1307 }
1308
1309 ctx->sd = NULL;
1310 ctx->sd_gen = 0;
1311 ctx->flags = 0;
1312 ctx->kq = -1;
1313
1314 if (in_flight == ctx)
1315 {
1316 in_flight = ctx->next;
1317 }
1318 else
1319 {
1320 p = in_flight;
1321 while ((p != NULL) && (p->next != ctx)) p = p->next;
1322 if (p != NULL) p->next = ctx->next;
1323 }
1324
1325 ctx->next = NULL;
1326
1327 if (!complete && !more)
1328 {
1329 _mdns_hostent_clear(ctx->host);
1330 ctx->anslen = -1;
1331 }
1332
1333 return complete | more;
1334 }
1335
1336 static void
1337 _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)
1338 {
1339 mdns_query_context_t *p, *context;
1340 struct in6_addr a6;
1341
1342 context = (mdns_query_context_t *)ctx;
1343 _mdns_debug_message(";; _mdns_query_callback ctx %p flags=0x%08x%s\n", context, flags, (flags & kDNSServiceFlagsMoreComing) ? " (kDNSServiceFlagsMoreComing is set)" : "");
1344
1345 context->flags = flags;
1346 context->error = errorCode;
1347 context->last_type = rrtype;
1348
1349 /* if kDNSServiceFlagsMoreComing is NOT set, there is no more data coming for ALL in-flight queries */
1350 if (!(flags & kDNSServiceFlagsMoreComing))
1351 {
1352 for (p = in_flight; p != NULL; p = p->next)
1353 {
1354 if (p->flags & kDNSServiceFlagsMoreComing)
1355 {
1356 _mdns_debug_message(";; cleared kDNSServiceFlagsMoreComing flag for ctx %p\n", p);
1357 p->flags &= ~kDNSServiceFlagsMoreComing;
1358 }
1359 }
1360 }
1361
1362 if (errorCode != kDNSServiceErr_NoError)
1363 {
1364 _mdns_debug_message(";; [%s type %hu class %hu]: error %d [ctx %p]\n", fullname, rrtype, rrclass, errorCode, context);
1365 goto wakeup_kevent;
1366 }
1367
1368 /* embed the scope ID into link-local IPv6 addresses */
1369 if ((rrtype == ns_t_aaaa) && (rdlen == sizeof(struct in6_addr)) && IN6_IS_ADDR_LINKLOCAL((struct in6_addr *)rdata))
1370 {
1371 memcpy(&a6, rdata, rdlen);
1372 a6.__u6_addr.__u6_addr16[1] = htons(ifIndex);
1373 rdata = &a6;
1374 }
1375
1376 if (context->reply != NULL)
1377 {
1378 char *name;
1379 int malformed = 0;
1380 mdns_reply_t *reply = context->reply;
1381
1382 if (reply->ifnum == 0) reply->ifnum = ifIndex;
1383
1384 _mdns_hostent_append_alias(context->host, fullname);
1385 if ((reply->ttl == 0) || (ttl < reply->ttl)) reply->ttl = ttl;
1386
1387 switch (rrtype)
1388 {
1389 case ns_t_a:
1390 case ns_t_aaaa:
1391 {
1392 if ((context->host != NULL) &&
1393 ((((rrtype == ns_t_a) && (context->host->host.h_addrtype == AF_INET)) || ((rrtype == ns_t_aaaa) && (context->host->host.h_addrtype == AF_INET6))) &&
1394 (rdlen >= context->host->host.h_length)))
1395 {
1396 if (context->host->host.h_name == NULL)
1397 {
1398 int i;
1399 mdns_hostent_t *h = context->host;
1400 char *h_name = _mdns_canonicalize(fullname);
1401 context->host->host.h_name = h_name;
1402
1403 /* 6863416 remove h_name from h_aliases */
1404 for (i = 0; i < h->alias_count; ++i)
1405 {
1406 if (h_name == NULL) break;
1407
1408 if (string_equal(h->host.h_aliases[i], h_name))
1409 {
1410 /* includes trailing NULL pointer */
1411 int sz = sizeof(char *) * (h->alias_count - i);
1412 free(h->host.h_aliases[i]);
1413 memmove(&h->host.h_aliases[i], &h->host.h_aliases[i+1], sz);
1414 h->alias_count -= 1;
1415 break;
1416 }
1417 }
1418 }
1419
1420 _mdns_hostent_append_addr(context->host, rdata, context->host->host.h_length);
1421 }
1422 else
1423 {
1424 malformed = 1;
1425 }
1426
1427 break;
1428 }
1429 case ns_t_cname:
1430 {
1431 name = _mdns_parse_domain_name(rdata, rdlen);
1432 if (name == NULL) malformed = 1;
1433
1434 _mdns_hostent_append_alias(context->host, name);
1435 _mdns_debug_message(";; [%s type %hu class %hu] cname %s [ctx %p]\n", fullname, rrtype, rrclass, name, context);
1436 free(name);
1437 break;
1438 }
1439 case ns_t_ptr:
1440 {
1441 name = _mdns_parse_domain_name(rdata, rdlen);
1442 if (name == NULL) malformed = 1;
1443
1444 if ((context->host != NULL) && (context->host->host.h_name == NULL))
1445 {
1446 context->host->host.h_name = _mdns_canonicalize(name);
1447 }
1448
1449 _mdns_hostent_append_alias(context->host, name);
1450 free(name);
1451 break;
1452 }
1453 case ns_t_srv:
1454 {
1455 mdns_rr_srv_t *p = (mdns_rr_srv_t *)rdata;
1456 mdns_srv_t *srv = calloc(1, sizeof(mdns_srv_t));
1457 if (srv == NULL) break;
1458
1459 if (rdlen < sizeof(mdns_rr_srv_t))
1460 {
1461 malformed = 1;
1462 break;
1463 }
1464
1465 srv->srv.priority = ntohs(p->priority);
1466 srv->srv.weight = ntohs(p->weight);
1467 srv->srv.port = ntohs(p->port);
1468 srv->srv.target = _mdns_parse_domain_name(&p->target[0], rdlen - 3*sizeof(uint16_t));
1469
1470 if (srv->srv.target == NULL)
1471 {
1472 malformed = 1;
1473 break;
1474 }
1475
1476 /* append to the end of the list */
1477 if (reply->srv == NULL)
1478 {
1479 reply->srv = srv;
1480 }
1481 else
1482 {
1483 mdns_srv_t *iter = reply->srv;
1484 while (iter->next) iter = iter->next;
1485 iter->next = srv;
1486 }
1487
1488 break;
1489 }
1490 default:
1491 {
1492 malformed = _mdns_debug;
1493 break;
1494 }
1495 }
1496
1497 if (malformed != 0)
1498 {
1499 _mdns_debug_message(";; [%s type %hu class %hu]: malformed reply [ctx %p]\n", fullname, rrtype, rrclass, context);
1500 goto wakeup_kevent;
1501 }
1502 }
1503
1504 if (context->answer != NULL)
1505 {
1506 int n;
1507 uint8_t *cp;
1508 HEADER *ans;
1509 size_t buflen = context->ansmaxlen - context->anslen;
1510
1511 if (buflen < NS_HFIXEDSZ)
1512 {
1513 _mdns_debug_message(";; [%s type %hu class %hu]: malformed reply (too small) [ctx %p]\n", fullname, rrtype, rrclass, context);
1514 goto wakeup_kevent;
1515 }
1516
1517 cp = context->answer + context->anslen;
1518
1519 n = _mdns_pack_domain_name(fullname, cp, buflen);
1520 if (n < 0)
1521 {
1522 _mdns_debug_message(";; [%s type %hu class %hu]: name mismatch [ctx %p]\n", fullname, rrtype, rrclass, context);
1523 goto wakeup_kevent;
1524 }
1525
1526 /*
1527 * check that there is enough space in the buffer for the
1528 * resource name (n), the resource record data (rdlen) and
1529 * the resource record header (10).
1530 */
1531 if (buflen < (n + rdlen + 10))
1532 {
1533 _mdns_debug_message(";; [%s type %hu class %hu]: insufficient buffer space for reply [ctx %p]\n", fullname, rrtype, rrclass, context);
1534 goto wakeup_kevent;
1535 }
1536
1537 cp += n;
1538 buflen -= n;
1539
1540 uint16_t word;
1541 uint32_t longword;
1542
1543 word = htons(rrtype);
1544 memcpy(cp, &word, sizeof(word));
1545 cp += sizeof(word);
1546
1547 word = htons(rrclass);
1548 memcpy(cp, &word, sizeof(word));
1549 cp += sizeof(word);
1550
1551 longword = htonl(ttl);
1552 memcpy(cp, &longword, sizeof(longword));
1553 cp += sizeof(longword);
1554
1555 word = htons(rdlen);
1556 memcpy(cp, &word, sizeof(word));
1557 cp += sizeof(word);
1558
1559 memcpy(cp, rdata, rdlen);
1560 cp += rdlen;
1561
1562 ans = (HEADER *)context->answer;
1563 ans->ancount = htons(ntohs(ans->ancount) + 1);
1564
1565 context->anslen = (size_t)(cp - context->answer);
1566 }
1567
1568 _mdns_debug_message(";; [%s type %hu class %hu] reply [ctx %p]\n", fullname, rrtype, rrclass, context);
1569
1570 wakeup_kevent:
1571
1572 /* Ping the waiting thread in case this callback was invoked on another */
1573 if (context->kq != -1)
1574 {
1575 _mdns_debug_message(";; _mdns_query_callback sending kevent wakeup\n");
1576 struct kevent ev;
1577 EV_SET(&ev, 1, EVFILT_USER, 0, NOTE_TRIGGER, 0, 0);
1578 int res = kevent(context->kq, &ev, 1, NULL, 0, NULL);
1579 if (res != 0) _mdns_debug_message(";; kevent EV_TRIGGER: %s [ctx %p]\n", strerror(errno), context);
1580 }
1581 }
1582
1583 static void
1584 _mdns_now(struct timespec *now)
1585 {
1586 struct timeval tv;
1587 gettimeofday(&tv, NULL);
1588 now->tv_sec = tv.tv_sec;
1589 now->tv_nsec = tv.tv_usec * 1000;
1590 }
1591
1592 static void
1593 _mdns_add_time(struct timespec *sum, const struct timespec *a, const struct timespec *b)
1594 {
1595 sum->tv_sec = a->tv_sec + b->tv_sec;
1596 sum->tv_nsec = a->tv_nsec + b->tv_nsec;
1597
1598 if (sum->tv_nsec > 1000000000)
1599 {
1600 sum->tv_sec += (sum->tv_nsec / 1000000000);
1601 sum->tv_nsec %= 1000000000;
1602 }
1603 }
1604
1605 /* calculate a deadline from the current time based on the desired timeout */
1606 static void
1607 _mdns_deadline(struct timespec *deadline, const struct timespec *delta)
1608 {
1609 struct timespec now;
1610 _mdns_now(&now);
1611 _mdns_add_time(deadline, &now, delta);
1612 }
1613
1614 static void
1615 _mdns_sub_time(struct timespec *delta, const struct timespec *a, const struct timespec *b)
1616 {
1617 delta->tv_sec = a->tv_sec - b->tv_sec;
1618 delta->tv_nsec = a->tv_nsec - b->tv_nsec;
1619
1620 if (delta->tv_nsec < 0)
1621 {
1622 delta->tv_nsec += 1000000000;
1623 delta->tv_sec -= 1;
1624 }
1625 }
1626
1627 /* calculate a timeout remaining before the given deadline */
1628 static void
1629 _mdns_timeout(struct timespec *timeout, const struct timespec *deadline)
1630 {
1631 struct timespec now;
1632 _mdns_now(&now);
1633 _mdns_sub_time(timeout, deadline, &now);
1634 }
1635
1636 int
1637 _mdns_search(const char *name, int class, int type, const char *interface, DNSServiceFlags flags, uint8_t *answer, uint32_t *anslen, mdns_reply_t *reply)
1638 {
1639 DNSServiceErrorType err = 0;
1640 int kq, n;
1641 struct kevent ev;
1642 struct timespec start, finish, delta, timeout;
1643 int res = 0;
1644 int i, got_a_response = 0;
1645 bool complete, initialize = true;
1646 bool wait = true;
1647 uint32_t n_iface_4 = 0;
1648
1649 /* determine number of IPv4 interfaces (ignore loopback) */
1650 si_inet_config(&n_iface_4, NULL);
1651 if (n_iface_4 > 0) n_iface_4--;
1652
1653 /* <rdar://problem/7732497> limit the number of initialization retries */
1654 int initialize_retries = 3;
1655
1656 /* 2 for A and AAAA parallel queries */
1657 int n_ctx = 0;
1658 mdns_query_context_t ctx[2];
1659 bool more_coming[2];
1660
1661 if (name == NULL) return -1;
1662
1663 #if TARGET_OS_EMBEDDED
1664 /* log a warning for queries from the main thread */
1665 if (pthread_is_threaded_np() && pthread_main_np()) asl_log(NULL, NULL, ASL_LEVEL_WARNING, "Warning: Libinfo call to mDNSResponder on main thread");
1666 #endif /* TARGET_OS_EMBEDDED */
1667
1668 /*
1669 * Timeout Logic
1670 * The kevent(2) API timeout parameter is used to enforce the total
1671 * timeout of the DNS query. Each iteraion recalculates the relative
1672 * timeout based on the desired end time (total timeout from origin).
1673 *
1674 * In order to workaround some DNS configurations that do not return
1675 * responses for AAAA queries, parallel queries modify the total
1676 * timeout upon receipt of the first response. The new total timeout is
1677 * set to an effective value of 2N where N is the time taken to receive
1678 * the A response (the original total timeout is preserved if 2N would
1679 * have exceeded it). However, since mDNSResponder caches values, a
1680 * minimum value of 50ms for N is enforced in order to give some time
1681 * for the receipt of a AAAA response.
1682 */
1683
1684 /* determine the maximum time to wait for a result */
1685 delta.tv_sec = RES_MAXRETRANS + 5;
1686 delta.tv_nsec = 0;
1687 _mdns_deadline(&finish, &delta);
1688 timeout = delta;
1689 _mdns_now(&start);
1690
1691
1692 for (i = 0; i < 2; ++i) {
1693 memset(&ctx[i], 0 , sizeof(mdns_query_context_t));
1694 more_coming[i] = false;
1695 }
1696 /* set up the kqueue */
1697 kq = kqueue();
1698 EV_SET(&ev, 1, EVFILT_USER, EV_ADD | EV_CLEAR, 0, 0, 0);
1699 n = kevent(kq, &ev, 1, NULL, 0, NULL);
1700 if (n != 0) wait = false;
1701
1702 while (wait)
1703 {
1704 _mdns_debug_message(";; _mdns_search wait loop\n");
1705
1706 if (initialize)
1707 {
1708 initialize = false;
1709 pthread_mutex_lock(&_mdns_mutex);
1710
1711 /* clear any stale contexts */
1712 for (i = 0; i < n_ctx; ++i) _mdns_query_clear(&ctx[i]);
1713 n_ctx = 0;
1714
1715 if (_mdns_sdref == NULL)
1716 {
1717 if (_mdns_old_sdref != NULL)
1718 {
1719 _mdns_generation++;
1720 DNSServiceRefDeallocate(_mdns_old_sdref);
1721 _mdns_old_sdref = NULL;
1722 }
1723
1724 /* (re)initialize the shared connection */
1725 err = DNSServiceCreateConnection(&_mdns_sdref);
1726
1727 /* limit the number of retries */
1728 if ((initialize_retries-- <= 0) && (err == 0)) err = kDNSServiceErr_Unknown;
1729 if (err != 0)
1730 {
1731 wait = false;
1732 pthread_mutex_unlock(&_mdns_mutex);
1733 break;
1734 }
1735 }
1736
1737 /*
1738 * issue (or reissue) the queries
1739 * unspecified type: do parallel A and AAAA
1740 */
1741 if (err == 0)
1742 {
1743 err = _mdns_query_start(&ctx[n_ctx++], reply, answer, anslen, name, class, (type == 0) ? ns_t_a : type, interface, flags, kq);
1744 }
1745
1746 if ((err == 0) && (type == 0))
1747 {
1748 err = _mdns_query_start(&ctx[n_ctx++], reply, answer, anslen, name, class, ns_t_aaaa, interface, flags, kq);
1749 }
1750
1751 if (err != 0) _mdns_debug_message(";; initialization error %d\n", err);
1752
1753 /* try to reinitialize */
1754 if ((err == kDNSServiceErr_Unknown) || (err == kDNSServiceErr_ServiceNotRunning) || (err == kDNSServiceErr_BadReference))
1755 {
1756 if (_mdns_sdref != NULL)
1757 {
1758 _mdns_generation++;
1759 DNSServiceRefDeallocate(_mdns_sdref);
1760 _mdns_sdref = NULL;
1761 }
1762
1763 err = 0;
1764 initialize = true;
1765 pthread_mutex_unlock(&_mdns_mutex);
1766 continue;
1767 }
1768 else if (err != 0)
1769 {
1770 pthread_mutex_unlock(&_mdns_mutex);
1771 break;
1772 }
1773
1774 /* (re)register the fd with kqueue */
1775 int fd = DNSServiceRefSockFD(_mdns_sdref);
1776 EV_SET(&ev, fd, EVFILT_READ, EV_ADD, 0, 0, 0);
1777 n = kevent(kq, &ev, 1, NULL, 0, NULL);
1778 pthread_mutex_unlock(&_mdns_mutex);
1779 if (err != 0 || n != 0) break;
1780 }
1781
1782 _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);
1783
1784 errno = 0;
1785 n = kevent(kq, NULL, 0, &ev, 1, &timeout);
1786 if ((n < 0) && (errno != EINTR))
1787 {
1788 res = -1;
1789 break;
1790 }
1791
1792 pthread_mutex_lock(&_mdns_mutex);
1793
1794 /*
1795 * DNSServiceProcessResult() is a blocking API
1796 * confirm that there is still data on the socket
1797 */
1798 const struct timespec notimeout = { 0, 0 };
1799 int m = kevent(kq, NULL, 0, &ev, 1, &notimeout);
1800
1801 if (_mdns_sdref == NULL)
1802 {
1803 initialize = true;
1804 _mdns_debug_message(";; _mdns_sdref is NULL, initialize = true\n");
1805 }
1806 else if (m > 0 && ev.filter == EVFILT_READ)
1807 {
1808 _mdns_debug_message(";; _mdns_search calling DNSServiceProcessResult\n", err);
1809 err = DNSServiceProcessResult(_mdns_sdref);
1810 _mdns_debug_message(";; DNSServiceProcessResult -> %s\n", err);
1811 if ((err == kDNSServiceErr_ServiceNotRunning) || (err == kDNSServiceErr_BadReference))
1812 {
1813 _mdns_debug_message(";; DNSServiceProcessResult status %d [ctx %p %p]\n", err, (n_ctx > 0) ? &(ctx[0]) : NULL, (n_ctx > 1) ? &(ctx[1]) : NULL);
1814 err = 0;
1815
1816 /* re-initialize the shared connection */
1817 _mdns_generation++;
1818 DNSServiceRefDeallocate(_mdns_sdref);
1819 _mdns_sdref = NULL;
1820 initialize = true;
1821 }
1822 }
1823 else if (m == 0 && ev.filter == EVFILT_USER)
1824 {
1825 _mdns_debug_message(";; kevent wakeup\n", m, (int)ev.filter);
1826 }
1827 else
1828 {
1829 _mdns_debug_message(";; kevent m=%d ev.filter=0x%08x\n", m, ev.filter);
1830 }
1831
1832 /* Check if all queries are complete (including errors) */
1833 complete = true;
1834 for (i = 0; i < n_ctx; ++i)
1835 {
1836 bool qc = _mdns_query_is_complete(&ctx[i], &more_coming[i]);
1837 _mdns_debug_message(";; ctx %d %p error=%d complete=%s\n", i, &(ctx[i]), ctx[i].error, qc ? "true" : "false");
1838
1839 if ((ctx[i].error != 0) || qc)
1840 {
1841 if (ctx[i].type == ns_t_a)
1842 {
1843 got_a_response = GOT_DATA;
1844 if (ctx[i].error != 0) got_a_response = GOT_ERROR;
1845 _mdns_debug_message(";; type ns_t_a got_a_response=%s ctx %p\n", (got_a_response == GOT_DATA) ? "GOT_DATA" : "GOT_ERROR", &(ctx[i]));
1846 }
1847
1848 _mdns_debug_message(";; [%s type %d class %d] finished processing ctx %p\n", name, type, class, &(ctx[i]));
1849 }
1850 else
1851 {
1852 _mdns_debug_message(";; [%s type %d class %d] continuing ctx %p\n", name, type, class, &(ctx[i]));
1853 complete = false;
1854 }
1855 }
1856
1857 pthread_mutex_unlock(&_mdns_mutex);
1858
1859 if (err != 0)
1860 {
1861 _mdns_debug_message(";; DNSServiceProcessResult error status %d [ctx %p %p]\n", err, (n_ctx > 0) ? &(ctx[0]) : NULL, (n_ctx > 1) ? &(ctx[1]) : NULL);
1862 break;
1863 }
1864 else if (complete)
1865 {
1866 _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);
1867 break;
1868 }
1869 else if (more_coming[0] || more_coming[1])
1870 {
1871 /* got partial data - probably from cache - reduce wait time */
1872 struct timespec now, tmp, extra;
1873
1874 /* tmp = now - start */
1875 _mdns_now(&now);
1876 _mdns_sub_time(&tmp, &now, &start);
1877
1878 extra.tv_sec = MEDIUM_AAAA_EXTRA;
1879 extra.tv_nsec = 0;
1880
1881 /* delta = tmp + extra */
1882 _mdns_add_time(&delta, &tmp, &extra);
1883
1884 /* check that delta doesn't exceed our total timeout */
1885 _mdns_sub_time(&tmp, &timeout, &delta);
1886 if (tmp.tv_sec >= 0)
1887 {
1888 _mdns_debug_message(";; new timeout [%s type %d class %d] (waiting for more) %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);
1889 _mdns_deadline(&finish, &delta);
1890 }
1891 }
1892 else if (got_a_response == GOT_DATA)
1893 {
1894 /* got A, adjust deadline for AAAA */
1895 struct timespec now, tn, extra;
1896
1897 /* delta = now - start */
1898 _mdns_now(&now);
1899 _mdns_sub_time(&delta, &now, &start);
1900
1901 extra.tv_sec = SHORT_AAAA_EXTRA;
1902 extra.tv_nsec = 0;
1903
1904 /* if delta is small (<= 20 milliseconds), we probably got a result from cache */
1905 if ((delta.tv_sec == 0) && (delta.tv_nsec <= 20000000))
1906 {
1907 extra.tv_sec = MEDIUM_AAAA_EXTRA;
1908 }
1909 else if (n_iface_4 == 0)
1910 {
1911 extra.tv_sec = LONG_AAAA_EXTRA;
1912 }
1913 else if (got_a_response == GOT_ERROR)
1914 {
1915 extra.tv_sec = MEDIUM_AAAA_EXTRA;
1916 }
1917
1918 /* tn = 2 * delta */
1919 _mdns_add_time(&tn, &delta, &delta);
1920
1921 /* delta = tn + extra */
1922 _mdns_add_time(&delta, &tn, &extra);
1923
1924 /* check that delta doesn't exceed our total timeout */
1925 _mdns_sub_time(&tn, &timeout, &delta);
1926 if (tn.tv_sec >= 0)
1927 {
1928 _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);
1929 _mdns_deadline(&finish, &delta);
1930 }
1931 }
1932
1933 /* calculate remaining timeout */
1934 _mdns_timeout(&timeout, &finish);
1935
1936 /* check for time remaining */
1937 if (timeout.tv_sec < 0)
1938 {
1939 _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);
1940 break;
1941 }
1942 }
1943
1944 _mdns_debug_message(";; finished _mdns_search loop [ctx %p %p]\n", (n_ctx > 0) ? &(ctx[0]) : NULL, (n_ctx > 1) ? &(ctx[1]) : NULL);
1945
1946 complete = false;
1947 pthread_mutex_lock(&_mdns_mutex);
1948
1949 for (i = 0; i < n_ctx; ++i)
1950 {
1951 /* only clears hostents if result is incomplete */
1952 bool cc = _mdns_query_clear(&ctx[i]);
1953 complete = cc | complete;
1954 _mdns_debug_message(";; _mdns_search ctx %p %scomplete\n", &ctx[i], cc ? "" : "in");
1955 }
1956
1957 if (more_coming[0] || more_coming[1]) complete = false;
1958
1959 _mdns_debug_message(";; _mdns_search overall %scomplete\n", complete ? "" : "in");
1960 pthread_mutex_unlock(&_mdns_mutex);
1961
1962 /* everything should be done with the kq by now */
1963 close(kq);
1964
1965 /* return error if everything is incomplete */
1966 if (!complete) res = -1;
1967
1968 if (anslen != NULL) *anslen = ctx[0].anslen;
1969 _mdns_debug_message(";; _mdns_search exit res %d\n", res);
1970 return res;
1971 }