Libinfo-459.40.1.tar.gz
[apple/libinfo.git] / lookup.subproj / mdns_module.c
1 /*
2 * Copyright (c) 2008-2011 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 #define MDNS_DEBUG_MORE 0x00000010
142
143 static int _mdns_debug = 0;
144
145 /* mutex protects DNSServiceProcessResult and DNSServiceRefDeallocate */
146 static pthread_mutex_t _mdns_mutex = PTHREAD_MUTEX_INITIALIZER;
147
148 typedef struct
149 {
150 uint16_t priority;
151 uint16_t weight;
152 uint16_t port;
153 uint8_t target[0];
154 } mdns_rr_srv_t;
155
156 typedef struct mdns_srv_t mdns_srv_t;
157 struct mdns_srv_t
158 {
159 si_srv_t srv;
160 mdns_srv_t *next;
161 };
162
163 typedef struct
164 {
165 struct hostent host;
166 int alias_count;
167 int addr_count;
168 } mdns_hostent_t;
169
170 typedef struct
171 {
172 mdns_hostent_t *h4;
173 mdns_hostent_t *h6;
174 mdns_srv_t *srv;
175 uint64_t ttl;
176 uint32_t ifnum;
177 } mdns_reply_t;
178
179 static uint32_t _mdns_generation = 0;
180 static DNSServiceRef _mdns_sdref;
181 static DNSServiceRef _mdns_old_sdref;
182
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);
186
187 static const char hexchar[] = "0123456789abcdef";
188
189 #define BILLION 1000000000
190
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
193
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
196
197 /* index of low-order nibble of embedded scope id */
198 #define IPv6_REVERSE_LINK_LOCAL_SCOPE_ID_LOW 48
199
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 */
209 };
210
211 static void
212 _mdns_debug_message(const char *str, ...)
213 {
214 va_list v;
215 char *out = NULL;
216
217 if (str == NULL) return;
218 if ((_mdns_debug & MDNS_DEBUG_OUT) == 0) return;
219
220 va_start(v, str);
221 vasprintf(&out, str, v);
222 if (out == NULL) return;
223
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);
227 free(out);
228
229 va_end(v);
230 }
231
232 static char *
233 _mdns_reverse_ipv4(const char *addr)
234 {
235 union
236 {
237 uint32_t a;
238 unsigned char b[4];
239 } ab;
240 char *p;
241
242 if (addr == NULL) return NULL;
243
244 memcpy(&(ab.a), addr, 4);
245
246 asprintf(&p, "%u.%u.%u.%u.in-addr.arpa.", ab.b[3], ab.b[2], ab.b[1], ab.b[0]);
247 return p;
248 }
249
250 static char *
251 _mdns_reverse_ipv6(const char *addr)
252 {
253 char x[65], *p;
254 int i, j;
255 u_int8_t d, hi, lo;
256
257 if (addr == NULL) return NULL;
258
259 x[64] = '\0';
260 j = 63;
261
262 for (i = 0; i < 16; i++)
263 {
264 d = addr[i];
265 lo = d & 0x0f;
266 hi = d >> 4;
267 x[j--] = '.';
268 x[j--] = hexchar[hi];
269 x[j--] = '.';
270 x[j--] = hexchar[lo];
271 }
272
273 asprintf(&p, "%sip6.arpa.", x);
274
275 return p;
276 }
277
278 /*
279 * _mdns_canonicalize
280 * Canonicalize the domain name by converting to lower case and removing the
281 * trailing '.' if present.
282 */
283 static char *
284 _mdns_canonicalize(const char *s)
285 {
286 int i;
287 char *t;
288
289 if (s == NULL) return NULL;
290
291 t = strdup(s);
292 if (t == NULL) return NULL;
293
294 if (t[0] == '\0') return t;
295
296 for (i = 0; t[i] != '\0'; i++)
297 {
298 if (t[i] >= 'A' && t[i] <= 'Z') t[i] += 32;
299 }
300
301 if (t[i-1] == '.') t[i-1] = '\0';
302
303 return t;
304 }
305
306 /*
307 * _mdns_hostent_append_alias
308 * Appends an alias to the mdns_hostent_t structure.
309 */
310 static int
311 _mdns_hostent_append_alias(mdns_hostent_t *h, const char *alias)
312 {
313 int i;
314 char *name;
315
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 if ((h == NULL) || (addr == NULL) || (len == 0)) return 0;
361
362 /* copy the address buffer */
363 uint8_t *buf = malloc(len);
364 if (buf == NULL) return -1;
365
366 memcpy(buf, addr, len);
367
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 *));
370
371 if (h->host.h_addr_list == NULL)
372 {
373 h->addr_count = 0;
374 return -1;
375 }
376
377 h->host.h_addr_list[h->addr_count] = (char*)buf;
378 h->addr_count++;
379
380 h->host.h_addr_list[h->addr_count] = NULL;
381 return 0;
382 }
383
384 static void
385 _mdns_hostent_clear(mdns_hostent_t *h)
386 {
387 if (h == NULL) return;
388
389 free(h->host.h_name);
390 h->host.h_name = NULL;
391
392 char **aliases = h->host.h_aliases;
393 while (aliases && *aliases) free(*aliases++);
394
395 free(h->host.h_aliases);
396 h->host.h_aliases = NULL;
397 h->alias_count = 0;
398
399 char **addrs = h->host.h_addr_list;
400 while (addrs && *addrs) free(*addrs++);
401
402 free(h->host.h_addr_list);
403 h->host.h_addr_list = NULL;
404 h->addr_count = 0;
405 }
406
407 static void
408 _mdns_reply_clear(mdns_reply_t *r)
409 {
410 if (r == NULL) return;
411
412 r->ifnum = 0;
413 _mdns_hostent_clear(r->h4);
414 _mdns_hostent_clear(r->h6);
415 mdns_srv_t *srv = r->srv;
416 r->srv = NULL;
417
418 while (srv != NULL)
419 {
420 mdns_srv_t *next = srv->next;
421 free(srv->srv.target);
422 free(srv);
423 srv = next;
424 }
425 }
426
427 static si_item_t *
428 mdns_hostbyname(si_mod_t *si, const char *name, int af, const char *interface, uint32_t *err)
429 {
430 uint32_t type;
431 mdns_hostent_t h;
432 mdns_reply_t reply;
433 si_item_t *out = NULL;
434 uint64_t bb;
435 int status;
436 DNSServiceFlags flags = 0;
437
438 if (err != NULL) *err = SI_STATUS_NO_ERROR;
439
440 if ((name == NULL) || (si == NULL))
441 {
442 if (err != NULL) *err = SI_STATUS_H_ERRNO_NO_RECOVERY;
443 return NULL;
444 }
445
446 memset(&h, 0, sizeof(h));
447 memset(&reply, 0, sizeof(reply));
448
449 switch (af)
450 {
451 case AF_INET:
452 type = ns_t_a;
453 h.host.h_length = 4;
454 reply.h4 = &h;
455 break;
456 case AF_INET6:
457 type = ns_t_aaaa;
458 h.host.h_length = 16;
459 reply.h6 = &h;
460 break;
461 default:
462 if (err != NULL) *err = SI_STATUS_H_ERRNO_NO_RECOVERY;
463 return NULL;
464 }
465
466 _mdns_debug_message(";; mdns_hostbyname %s type %u class %u\n", name, type, ns_c_in);
467
468 h.host.h_addrtype = af;
469
470 status = _mdns_search(name, ns_c_in, type, interface, flags, NULL, NULL, &reply);
471 if ((status != 0) || (h.addr_count == 0))
472 {
473 _mdns_reply_clear(&reply);
474 if (err != NULL) *err = SI_STATUS_H_ERRNO_HOST_NOT_FOUND;
475 return NULL;
476 }
477
478 bb = reply.ttl + time(NULL);
479
480 switch (af)
481 {
482 case AF_INET:
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);
484 break;
485 case AF_INET6:
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);
487 break;
488 }
489
490 _mdns_reply_clear(&reply);
491
492 if ((out == NULL) && (err != NULL)) *err = SI_STATUS_H_ERRNO_NO_RECOVERY;
493
494 return out;
495 }
496
497 static si_item_t *
498 mdns_hostbyaddr(si_mod_t *si, const void *addr, int af, const char *interface, uint32_t *err)
499 {
500 mdns_hostent_t h;
501 mdns_reply_t reply;
502 char *name;
503 si_item_t *out;
504 uint64_t bb;
505 int cat;
506 int status;
507 DNSServiceFlags flags = 0;
508
509 if (err != NULL) *err = SI_STATUS_NO_ERROR;
510
511 if ((addr == NULL) || (si == NULL))
512 {
513 if (err != NULL) *err = SI_STATUS_H_ERRNO_NO_RECOVERY;
514 return NULL;
515 }
516
517 memset(&h, 0, sizeof(h));
518 memset(&reply, 0, sizeof(reply));
519
520 switch (af)
521 {
522 case AF_INET:
523 h.host.h_length = 4;
524 reply.h4 = &h;
525 name = _mdns_reverse_ipv4(addr);
526 cat = CATEGORY_HOST_IPV4;
527 break;
528 case AF_INET6:
529 h.host.h_length = 16;
530 reply.h6 = &h;
531 name = _mdns_reverse_ipv6(addr);
532 cat = CATEGORY_HOST_IPV6;
533 break;
534 default:
535 if (err != NULL) *err = SI_STATUS_H_ERRNO_NO_RECOVERY;
536 return NULL;
537 }
538
539 h.host.h_addrtype = af;
540
541 _mdns_debug_message(";; mdns_hostbyaddr %s type %u class %u\n", name, ns_t_ptr, ns_c_in);
542
543 status = _mdns_search(name, ns_c_in, ns_t_ptr, interface, flags, NULL, NULL, &reply);
544 free(name);
545 if (status != 0)
546 {
547 _mdns_reply_clear(&reply);
548 if (err != NULL) *err = SI_STATUS_H_ERRNO_HOST_NOT_FOUND;
549 return NULL;
550 }
551
552 status = _mdns_hostent_append_addr(&h, addr, h.host.h_length);
553 if (status != 0)
554 {
555 _mdns_hostent_clear(&h);
556 if (err != NULL) *err = SI_STATUS_H_ERRNO_NO_RECOVERY;
557 return NULL;
558 }
559
560 bb = reply.ttl + time(NULL);
561
562 switch (af)
563 {
564 case AF_INET:
565 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);
566 break;
567 case AF_INET6:
568 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);
569 break;
570 }
571
572 _mdns_hostent_clear(&h);
573
574 if ((out == NULL) && (err != NULL)) *err = SI_STATUS_H_ERRNO_NO_RECOVERY;
575 return out;
576 }
577
578 static si_list_t *
579 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)
580 {
581 bool wantv4 = true;
582 bool wantv6 = true;
583 struct in_addr a4;
584 struct in6_addr a6;
585 mdns_hostent_t h4;
586 mdns_hostent_t h6;
587 mdns_reply_t reply;
588 uint32_t type;
589 uint16_t port;
590
591 if (si == NULL)
592 {
593 if (err != NULL) *err = SI_STATUS_H_ERRNO_NO_RECOVERY;
594 return NULL;
595 }
596
597 if (family == AF_INET6)
598 {
599 if ((flags & AI_V4MAPPED) == 0) wantv4 = false;
600 }
601 else if (family == AF_INET)
602 {
603 wantv6 = false;
604 }
605 else if (family != AF_UNSPEC)
606 {
607 return NULL;
608 }
609
610 if (err != NULL) *err = SI_STATUS_NO_ERROR;
611
612 _mdns_debug_message(";; mdns_addrinfo node %s serv %s\n", (const char *)node, (const char *)serv);
613
614 si_list_t *out = NULL;
615
616 memset(&h4, 0, sizeof(h4));
617 memset(&h6, 0, sizeof(h6));
618 memset(&reply, 0, sizeof(reply));
619
620 h4.host.h_addrtype = AF_INET;
621 h4.host.h_length = 4;
622 h6.host.h_addrtype = AF_INET6;
623 h6.host.h_length = 16;
624
625 if (wantv4 && wantv6)
626 {
627 type = 0;
628 reply.h4 = &h4;
629 reply.h6 = &h6;
630 }
631 else if (wantv4)
632 {
633 reply.h4 = &h4;
634 type = ns_t_a;
635 }
636 else if (wantv6)
637 {
638 type = ns_t_aaaa;
639 reply.h6 = &h6;
640 }
641 else
642 {
643 if (err != NULL) *err = SI_STATUS_H_ERRNO_NO_RECOVERY;
644 return NULL;
645 }
646
647 /* service lookup */
648 if ((flags & AI_NUMERICSERV) != 0)
649 {
650 if (serv == NULL) port = 0;
651 else port = *(uint16_t *)serv;
652 }
653 else
654 {
655 if (_gai_serv_to_port(serv, proto, &port) != 0)
656 {
657 if (err) *err = SI_STATUS_EAI_NONAME;
658 return NULL;
659 }
660 }
661
662 /* host lookup */
663 if ((flags & AI_NUMERICHOST) != 0)
664 {
665 char *cname = NULL;
666 struct in_addr *p4 = NULL;
667 struct in6_addr *p6 = NULL;
668
669 if (node == NULL) return NULL;
670
671 if (family == AF_INET)
672 {
673 p4 = &a4;
674 memcpy(p4, node, sizeof(a4));
675 }
676 else if (family == AF_INET6)
677 {
678 p6 = &a6;
679 memcpy(p6, node, sizeof(a6));
680 }
681
682 out = si_addrinfo_list(si, flags, socktype, proto, p4, p6, port, 0, cname, cname);
683 }
684 else
685 {
686 int res;
687 DNSServiceFlags dns_flags = 0;
688
689 if (node == NULL) return NULL;
690
691 if (flags & AI_ADDRCONFIG)
692 {
693 dns_flags |= kDNSServiceFlagsSuppressUnusable;
694 }
695
696 res = _mdns_search(node, ns_c_in, type, interface, dns_flags, NULL, NULL, &reply);
697 if ((res == 0) && ((h4.addr_count > 0) || (h6.addr_count > 0)))
698 {
699 out = si_addrinfo_list_from_hostent(si, flags, socktype, proto, port, 0, (wantv4 ? &h4.host : NULL), (wantv6 ? &h6.host : NULL));
700 }
701 else if (err != NULL)
702 {
703 *err = SI_STATUS_EAI_NONAME;
704 }
705
706 _mdns_reply_clear(&reply);
707 }
708
709 return out;
710 }
711
712 static si_list_t *
713 mdns_srv_byname(si_mod_t* si, const char *qname, const char *interface, uint32_t *err)
714 {
715 si_list_t *out = NULL;
716 mdns_reply_t reply;
717 mdns_srv_t *srv;
718 int res;
719 const uint64_t unused = 0;
720 DNSServiceFlags flags = 0;
721
722 if (si == NULL)
723 {
724 if (err != NULL) *err = SI_STATUS_H_ERRNO_NO_RECOVERY;
725 return NULL;
726 }
727
728 if (err != NULL) *err = SI_STATUS_NO_ERROR;
729
730 _mdns_debug_message(";; mdns_srv_byname %s type %u class %u\n", qname, ns_t_srv, ns_c_in);
731
732 memset(&reply, 0, sizeof(reply));
733 res = _mdns_search(qname, ns_c_in, ns_t_srv, interface, flags, NULL, NULL, &reply);
734 if (res == 0)
735 {
736 srv = reply.srv;
737 while (srv != NULL)
738 {
739 si_item_t *item;
740 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);
741 out = si_list_add(out, item);
742 si_item_release(item);
743 srv = srv->next;
744 }
745 }
746
747 _mdns_reply_clear(&reply);
748 return out;
749 }
750
751 /*
752 * We support dns_async_start / cancel / handle_reply using dns_item_call
753 */
754 static si_item_t *
755 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)
756 {
757 int res;
758 uint8_t buf[DNS_MAX_RECEIVE_SIZE];
759 uint32_t len = sizeof(buf);
760 mdns_reply_t reply;
761 mdns_hostent_t h4;
762 mdns_hostent_t h6;
763 si_item_t *out;
764 DNSServiceFlags flags = 0;
765
766 if ((si == NULL) || (name == NULL))
767 {
768 if (err != NULL) *err = SI_STATUS_H_ERRNO_NO_RECOVERY;
769 return NULL;
770 }
771
772 if (err != NULL) *err = SI_STATUS_NO_ERROR;
773
774 _mdns_debug_message(";; mdns_item_call %s type %u class %u\n", name, type, class);
775
776 memset(&h4, 0, sizeof(h4));
777 memset(&h6, 0, sizeof(h6));
778 memset(&reply, 0, sizeof(reply));
779
780 h4.host.h_addrtype = AF_INET;
781 h4.host.h_length = 4;
782 h6.host.h_addrtype = AF_INET6;
783 h6.host.h_length = 16;
784 reply.h4 = &h4;
785 reply.h6 = &h6;
786
787 res = _mdns_search(name, class, type, interface, flags, buf, &len, &reply);
788 if ((res != 0) || (len <= 0) || (len > DNS_MAX_RECEIVE_SIZE))
789 {
790 _mdns_reply_clear(&reply);
791 if (err != NULL) *err = SI_STATUS_H_ERRNO_HOST_NOT_FOUND;
792 return NULL;
793 }
794
795 struct sockaddr_in6 from;
796 uint32_t fromlen = sizeof(from);
797 memset(&from, 0, fromlen);
798 from.sin6_len = fromlen;
799 from.sin6_family = AF_INET6;
800 from.sin6_addr.__u6_addr.__u6_addr8[15] = 1;
801
802 if (reply.ifnum != 0)
803 {
804 from.sin6_addr.__u6_addr.__u6_addr16[0] = htons(0xfe80);
805 from.sin6_scope_id = reply.ifnum;
806 }
807
808 out = (si_item_t *)LI_ils_create("L4488@@", (unsigned long)si, CATEGORY_DNSPACKET, 1, 0LL, 0LL, len, buf, fromlen, &from);
809 if ((out == NULL) && (err != NULL)) *err = SI_STATUS_H_ERRNO_NO_RECOVERY;
810
811 _mdns_reply_clear(&reply);
812
813 return out;
814 }
815
816 static int
817 mdns_is_valid(si_mod_t *si, si_item_t *item)
818 {
819 return 0;
820 }
821
822 static void
823 mdns_close(si_mod_t *si)
824 {
825 }
826
827 static void
828 _mdns_atfork_prepare(void)
829 {
830 /* acquire our lock so that we know all other threads have "drained" */
831 pthread_mutex_lock(&_mdns_mutex);
832 }
833
834 static void
835 _mdns_atfork_parent(void)
836 {
837 /* parent can simply resume */
838 pthread_mutex_unlock(&_mdns_mutex);
839 }
840
841 static void
842 _mdns_atfork_child(void)
843 {
844 /* child needs to force re-initialization */
845 _mdns_old_sdref = _mdns_sdref; // for later deallocation
846 _mdns_sdref = NULL;
847 pthread_mutex_unlock(&_mdns_mutex);
848 }
849
850 static void
851 _mdns_init(void)
852 {
853 pthread_atfork(_mdns_atfork_prepare, _mdns_atfork_parent, _mdns_atfork_child);
854
855 if (getenv("RES_DEBUG") != NULL) _mdns_debug |= MDNS_DEBUG_STDOUT;
856 int fd = open(MDNS_DEBUG_FILE, O_RDONLY, 0);
857 errno = 0;
858
859 if (fd >= 0)
860 {
861 int i, n;
862 char c[5];
863 memset(c, 0, sizeof(c));
864 n = read(fd, c, 4);
865
866 for (i = 0; i < n; i++)
867 {
868 if ((c[i] == 'o') || (c[i] == 'O')) _mdns_debug |= MDNS_DEBUG_STDOUT;
869 if ((c[i] == 'e') || (c[i] == 'E')) _mdns_debug |= MDNS_DEBUG_STDERR;
870 if ((c[i] == 'a') || (c[i] == 'A')) _mdns_debug |= MDNS_DEBUG_ASL;
871 if ((c[i] == 'm') || (c[i] == 'M')) _mdns_debug |= MDNS_DEBUG_MORE;
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
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 } mdns_query_context_t;
1145
1146 static void
1147 _mdns_query_callback(DNSServiceRef, DNSServiceFlags, uint32_t, DNSServiceErrorType, const char *, uint16_t, uint16_t, uint16_t, const void *, uint32_t, void *);
1148
1149 /*
1150 * _mdns_query_start
1151 * initializes the context and starts a DNS-SD query.
1152 */
1153 static DNSServiceErrorType
1154 _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)
1155 {
1156 DNSServiceErrorType status;
1157
1158 flags |= kDNSServiceFlagsShareConnection;
1159 flags |= kDNSServiceFlagsReturnIntermediates;
1160
1161 /* <rdar://problem/7428439> mDNSResponder is now responsible for timeouts */
1162 flags |= kDNSServiceFlagsTimeout;
1163
1164 memset(ctx, 0, sizeof(mdns_query_context_t));
1165
1166 if ((answer != NULL) && (anslen != NULL))
1167 {
1168 /* build a dummy DNS header to return to the caller */
1169 ctx->answer = answer;
1170 ctx->ansmaxlen = *anslen;
1171 ctx->anslen = _mdns_make_query(name, class, type, answer, ctx->ansmaxlen);
1172 if (ctx->anslen <= 0) return -1;
1173 }
1174
1175 ctx->type = type;
1176 ctx->sd = _mdns_sdref;
1177 ctx->sd_gen = _mdns_generation;
1178 ctx->kq = kq;
1179
1180 if (reply != NULL)
1181 {
1182 ctx->reply = reply;
1183 if (type == ns_t_a) ctx->host = reply->h4;
1184 else if (type == ns_t_aaaa) ctx->host = reply->h6;
1185 else if (type == ns_t_ptr && reply->h4) ctx->host = reply->h4;
1186 else if (type == ns_t_ptr && reply->h6) ctx->host = reply->h6;
1187 else if (type != ns_t_srv && type != ns_t_cname) return -1;
1188 }
1189
1190 uint32_t iface = 0;
1191 char *qname = _mdns_ipv6_extract_scope_id(name, &iface);
1192 if (qname == NULL) qname = (char *)name;
1193
1194 if (interface != NULL)
1195 {
1196 /* get interface number from name */
1197 int iface2 = if_nametoindex(interface);
1198
1199 /* balk if interface name lookup failed */
1200 if (iface2 == 0) return -1;
1201
1202 /* balk if scope id is set AND interface is given AND they don't match */
1203 if ((iface != 0) && (iface2 != 0) && (iface != iface2)) return -1;
1204 if (iface2 != 0) iface = iface2;
1205 }
1206
1207 _mdns_debug_message(";; mdns query %s type %d class %d [ctx %p]\n", qname, type, class, ctx);
1208
1209 status = DNSServiceQueryRecord(&ctx->sd, flags, iface, qname, type, class, _mdns_query_callback, ctx);
1210 if (qname != name) free(qname);
1211 return status;
1212 }
1213
1214 /*
1215 * _mdns_query_is_complete
1216 * Determines whether the specified query has sufficient information to be
1217 * considered complete.
1218 */
1219 static bool
1220 _mdns_query_is_complete(mdns_query_context_t *ctx)
1221 {
1222 bool complete = false;
1223
1224 /* NULL context is an error, but we call it complete */
1225 if (ctx == NULL) return true;
1226
1227 /*
1228 * The default is to ignore kDNSServiceFlagsMoreComing, since it has either
1229 * never been supported or worked correctly. MDNS_DEBUG_MORE makes us honor it.
1230 */
1231 if (ctx->flags & kDNSServiceFlagsMoreComing)
1232 {
1233 if (_mdns_debug & MDNS_DEBUG_MORE)
1234 {
1235 _mdns_debug_message(";; mdns is_complete type %d ctx %p more coming - incomplete\n", ctx->type, ctx);
1236 return false;
1237 }
1238 }
1239
1240 if (ctx->last_type != ctx->type)
1241 {
1242 _mdns_debug_message(";; mdns is_complete ctx %p type mismatch (%d != %d) - incomplete\n", ctx, ctx->last_type, ctx->type);
1243 return false;
1244 }
1245
1246 switch (ctx->type)
1247 {
1248 case ns_t_a:
1249 case ns_t_aaaa:
1250 if (ctx->host != NULL && ctx->host->addr_count > 0) complete = true;
1251 break;
1252 case ns_t_ptr:
1253 if (ctx->host != NULL && ctx->host->host.h_name != NULL) complete = true;
1254 break;
1255 case ns_t_srv:
1256 if (ctx->reply != NULL && ctx->reply->srv != NULL) complete = true;
1257 break;
1258 default:
1259 _mdns_debug_message(";; mdns is_complete unexpected type %d ctx %p\n", ctx->type, ctx);
1260 }
1261
1262 _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");
1263
1264 return complete;
1265 }
1266
1267 /*
1268 * _mdns_query_clear
1269 * Clear out the temporary fields of the context, and clear any result
1270 * structures that are incomplete. Retrns 1 if the query was complete.
1271 */
1272 static bool
1273 _mdns_query_clear(mdns_query_context_t *ctx)
1274 {
1275 bool complete = _mdns_query_is_complete(ctx);
1276
1277 if (ctx == NULL) return complete;
1278
1279 if (ctx->sd != NULL)
1280 {
1281 /* only dealloc this DNSServiceRef if the "main" _mdns_sdref has not been deallocated */
1282 if (ctx->sd != NULL && ctx->sd_gen == _mdns_generation)
1283 {
1284 DNSServiceRefDeallocate(ctx->sd);
1285 }
1286 }
1287
1288 ctx->sd = NULL;
1289 ctx->sd_gen = 0;
1290 ctx->flags = 0;
1291 ctx->kq = -1;
1292
1293 if (!complete)
1294 {
1295 _mdns_hostent_clear(ctx->host);
1296 ctx->anslen = -1;
1297 }
1298
1299 return complete;
1300 }
1301
1302 static void
1303 _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)
1304 {
1305 mdns_query_context_t *context;
1306 struct in6_addr a6;
1307
1308 context = (mdns_query_context_t *)ctx;
1309
1310 context->flags = flags;
1311 context->error = errorCode;
1312 context->last_type = rrtype;
1313
1314 if (errorCode != kDNSServiceErr_NoError)
1315 {
1316 _mdns_debug_message(";; [%s type %hu class %hu]: error %d [ctx %p]\n", fullname, rrtype, rrclass, errorCode, context);
1317 goto wakeup_kevent;
1318 }
1319
1320 /* embed the scope ID into link-local IPv6 addresses */
1321 if ((rrtype == ns_t_aaaa) && (rdlen == sizeof(struct in6_addr)) && IN6_IS_ADDR_LINKLOCAL((struct in6_addr *)rdata))
1322 {
1323 memcpy(&a6, rdata, rdlen);
1324 a6.__u6_addr.__u6_addr16[1] = htons(ifIndex);
1325 rdata = &a6;
1326 }
1327
1328 if (context->reply != NULL)
1329 {
1330 char *name;
1331 int malformed = 0;
1332 mdns_reply_t *reply = context->reply;
1333
1334 if (reply->ifnum == 0) reply->ifnum = ifIndex;
1335
1336 _mdns_hostent_append_alias(context->host, fullname);
1337 if ((reply->ttl == 0) || (ttl < reply->ttl)) reply->ttl = ttl;
1338
1339 switch (rrtype)
1340 {
1341 case ns_t_a:
1342 case ns_t_aaaa:
1343 {
1344 if ((context->host != NULL) &&
1345 ((((rrtype == ns_t_a) && (context->host->host.h_addrtype == AF_INET)) || ((rrtype == ns_t_aaaa) && (context->host->host.h_addrtype == AF_INET6))) &&
1346 (rdlen >= context->host->host.h_length)))
1347 {
1348 if (context->host->host.h_name == NULL)
1349 {
1350 int i;
1351 mdns_hostent_t *h = context->host;
1352 char *h_name = _mdns_canonicalize(fullname);
1353 context->host->host.h_name = h_name;
1354
1355 /* 6863416 remove h_name from h_aliases */
1356 for (i = 0; i < h->alias_count; ++i)
1357 {
1358 if (h_name == NULL) break;
1359
1360 if (string_equal(h->host.h_aliases[i], h_name))
1361 {
1362 /* includes trailing NULL pointer */
1363 int sz = sizeof(char *) * (h->alias_count - i);
1364 free(h->host.h_aliases[i]);
1365 memmove(&h->host.h_aliases[i], &h->host.h_aliases[i+1], sz);
1366 h->alias_count -= 1;
1367 break;
1368 }
1369 }
1370 }
1371
1372 _mdns_hostent_append_addr(context->host, rdata, context->host->host.h_length);
1373 }
1374 else
1375 {
1376 malformed = 1;
1377 }
1378
1379 break;
1380 }
1381 case ns_t_cname:
1382 {
1383 name = _mdns_parse_domain_name(rdata, rdlen);
1384 if (name == NULL) malformed = 1;
1385
1386 _mdns_hostent_append_alias(context->host, name);
1387 _mdns_debug_message(";; [%s type %hu class %hu] cname %s [ctx %p]\n", fullname, rrtype, rrclass, name, context);
1388 free(name);
1389 break;
1390 }
1391 case ns_t_ptr:
1392 {
1393 name = _mdns_parse_domain_name(rdata, rdlen);
1394 if (name == NULL) malformed = 1;
1395
1396 if ((context->host != NULL) && (context->host->host.h_name == NULL))
1397 {
1398 context->host->host.h_name = _mdns_canonicalize(name);
1399 }
1400
1401 _mdns_hostent_append_alias(context->host, name);
1402 free(name);
1403 break;
1404 }
1405 case ns_t_srv:
1406 {
1407 mdns_rr_srv_t *p = (mdns_rr_srv_t *)rdata;
1408 mdns_srv_t *srv = calloc(1, sizeof(mdns_srv_t));
1409 if (srv == NULL) break;
1410
1411 if (rdlen < sizeof(mdns_rr_srv_t))
1412 {
1413 malformed = 1;
1414 break;
1415 }
1416
1417 srv->srv.priority = ntohs(p->priority);
1418 srv->srv.weight = ntohs(p->weight);
1419 srv->srv.port = ntohs(p->port);
1420 srv->srv.target = _mdns_parse_domain_name(&p->target[0], rdlen - 3*sizeof(uint16_t));
1421
1422 if (srv->srv.target == NULL)
1423 {
1424 malformed = 1;
1425 break;
1426 }
1427
1428 /* append to the end of the list */
1429 if (reply->srv == NULL)
1430 {
1431 reply->srv = srv;
1432 }
1433 else
1434 {
1435 mdns_srv_t *iter = reply->srv;
1436 while (iter->next) iter = iter->next;
1437 iter->next = srv;
1438 }
1439
1440 break;
1441 }
1442 default:
1443 {
1444 malformed = _mdns_debug;
1445 break;
1446 }
1447 }
1448
1449 if (malformed != 0)
1450 {
1451 _mdns_debug_message(";; [%s type %hu class %hu]: malformed reply [ctx %p]\n", fullname, rrtype, rrclass, context);
1452 goto wakeup_kevent;
1453 }
1454 }
1455
1456 if (context->answer != NULL)
1457 {
1458 int n;
1459 uint8_t *cp;
1460 HEADER *ans;
1461 size_t buflen = context->ansmaxlen - context->anslen;
1462
1463 if (buflen < NS_HFIXEDSZ)
1464 {
1465 _mdns_debug_message(";; [%s type %hu class %hu]: malformed reply (too small) [ctx %p]\n", fullname, rrtype, rrclass, context);
1466 goto wakeup_kevent;
1467 }
1468
1469 cp = context->answer + context->anslen;
1470
1471 n = _mdns_pack_domain_name(fullname, cp, buflen);
1472 if (n < 0)
1473 {
1474 _mdns_debug_message(";; [%s type %hu class %hu]: name mismatch [ctx %p]\n", fullname, rrtype, rrclass, context);
1475 goto wakeup_kevent;
1476 }
1477
1478 /*
1479 * check that there is enough space in the buffer for the
1480 * resource name (n), the resource record data (rdlen) and
1481 * the resource record header (10).
1482 */
1483 if (buflen < (n + rdlen + 10))
1484 {
1485 _mdns_debug_message(";; [%s type %hu class %hu]: insufficient buffer space for reply [ctx %p]\n", fullname, rrtype, rrclass, context);
1486 goto wakeup_kevent;
1487 }
1488
1489 cp += n;
1490 buflen -= n;
1491
1492 uint16_t word;
1493 uint32_t longword;
1494
1495 word = htons(rrtype);
1496 memcpy(cp, &word, sizeof(word));
1497 cp += sizeof(word);
1498
1499 word = htons(rrclass);
1500 memcpy(cp, &word, sizeof(word));
1501 cp += sizeof(word);
1502
1503 longword = htonl(ttl);
1504 memcpy(cp, &longword, sizeof(longword));
1505 cp += sizeof(longword);
1506
1507 word = htons(rdlen);
1508 memcpy(cp, &word, sizeof(word));
1509 cp += sizeof(word);
1510
1511 memcpy(cp, rdata, rdlen);
1512 cp += rdlen;
1513
1514 ans = (HEADER *)context->answer;
1515 ans->ancount = htons(ntohs(ans->ancount) + 1);
1516
1517 context->anslen = (size_t)(cp - context->answer);
1518 }
1519
1520 _mdns_debug_message(";; [%s type %hu class %hu] reply [ctx %p]\n", fullname, rrtype, rrclass, context);
1521
1522 wakeup_kevent:
1523
1524 /* Ping the waiting thread in case this callback was invoked on another */
1525 if (context->kq != -1)
1526 {
1527 struct kevent ev;
1528 EV_SET(&ev, 1, EVFILT_USER, 0, NOTE_TRIGGER, 0, 0);
1529 int res = kevent(context->kq, &ev, 1, NULL, 0, NULL);
1530 if (res != 0) _mdns_debug_message(";; kevent EV_TRIGGER: %s [ctx %p]\n", strerror(errno), context);
1531 }
1532 }
1533
1534 static void
1535 _mdns_now(struct timespec *now)
1536 {
1537 struct timeval tv;
1538 gettimeofday(&tv, NULL);
1539 now->tv_sec = tv.tv_sec;
1540 now->tv_nsec = tv.tv_usec * 1000;
1541 }
1542
1543 static void
1544 _mdns_add_time(struct timespec *sum, const struct timespec *a, const struct timespec *b)
1545 {
1546 sum->tv_sec = a->tv_sec + b->tv_sec;
1547 sum->tv_nsec = a->tv_nsec + b->tv_nsec;
1548
1549 if (sum->tv_nsec > 1000000000)
1550 {
1551 sum->tv_sec += (sum->tv_nsec / 1000000000);
1552 sum->tv_nsec %= 1000000000;
1553 }
1554 }
1555
1556 /* calculate a deadline from the current time based on the desired timeout */
1557 static void
1558 _mdns_deadline(struct timespec *deadline, const struct timespec *delta)
1559 {
1560 struct timespec now;
1561 _mdns_now(&now);
1562 _mdns_add_time(deadline, &now, delta);
1563 }
1564
1565 static void
1566 _mdns_sub_time(struct timespec *delta, const struct timespec *a, const struct timespec *b)
1567 {
1568 delta->tv_sec = a->tv_sec - b->tv_sec;
1569 delta->tv_nsec = a->tv_nsec - b->tv_nsec;
1570
1571 if (delta->tv_nsec < 0)
1572 {
1573 delta->tv_nsec += 1000000000;
1574 delta->tv_sec -= 1;
1575 }
1576 }
1577
1578 /* calculate a timeout remaining before the given deadline */
1579 static void
1580 _mdns_timeout(struct timespec *timeout, const struct timespec *deadline)
1581 {
1582 struct timespec now;
1583 _mdns_now(&now);
1584 _mdns_sub_time(timeout, deadline, &now);
1585 }
1586
1587 int
1588 _mdns_search(const char *name, int class, int type, const char *interface, DNSServiceFlags flags, uint8_t *answer, uint32_t *anslen, mdns_reply_t *reply)
1589 {
1590 DNSServiceErrorType err = 0;
1591 int kq, n;
1592 struct kevent ev;
1593 struct timespec start, finish, delta, timeout;
1594 int res = 0;
1595 int i, got_a_response = 0;
1596 bool complete, initialize = true;
1597 bool wait = true;
1598 uint32_t n_iface_4 = 0;
1599
1600 /* determine number of IPv4 interfaces (ignore loopback) */
1601 si_inet_config(&n_iface_4, NULL);
1602 if (n_iface_4 > 0) n_iface_4--;
1603
1604 /* <rdar://problem/7732497> limit the number of initialization retries */
1605 int initialize_retries = 3;
1606
1607 /* 2 for A and AAAA parallel queries */
1608 int n_ctx = 0;
1609 mdns_query_context_t ctx[2];
1610
1611 if (name == NULL) return -1;
1612
1613 #if TARGET_OS_EMBEDDED
1614 /* log a warning for queries from the main thread */
1615 if (pthread_is_threaded_np() && pthread_main_np()) asl_log(NULL, NULL, ASL_LEVEL_WARNING, "Warning: Libinfo call to mDNSResponder on main thread");
1616 #endif /* TARGET_OS_EMBEDDED */
1617
1618 /*
1619 * Timeout Logic
1620 * The kevent(2) API timeout parameter is used to enforce the total
1621 * timeout of the DNS query. Each iteraion recalculates the relative
1622 * timeout based on the desired end time (total timeout from origin).
1623 *
1624 * In order to workaround some DNS configurations that do not return
1625 * responses for AAAA queries, parallel queries modify the total
1626 * timeout upon receipt of the first response. The new total timeout is
1627 * set to an effective value of 2N where N is the time taken to receive
1628 * the A response (the original total timeout is preserved if 2N would
1629 * have exceeded it). However, since mDNSResponder caches values, a
1630 * minimum value of 50ms for N is enforced in order to give some time
1631 * for the receipt of a AAAA response.
1632 */
1633
1634 /* determine the maximum time to wait for a result */
1635 delta.tv_sec = RES_MAXRETRANS + 5;
1636 delta.tv_nsec = 0;
1637 _mdns_deadline(&finish, &delta);
1638 timeout = delta;
1639 _mdns_now(&start);
1640
1641 for (i = 0; i < 2; ++i) memset(&ctx[i], 0 , sizeof(mdns_query_context_t));
1642
1643 /* set up the kqueue */
1644 kq = kqueue();
1645 EV_SET(&ev, 1, EVFILT_USER, EV_ADD | EV_CLEAR, 0, 0, 0);
1646 n = kevent(kq, &ev, 1, NULL, 0, NULL);
1647 if (n != 0) wait = false;
1648
1649 while (wait)
1650 {
1651 if (initialize)
1652 {
1653 initialize = false;
1654 pthread_mutex_lock(&_mdns_mutex);
1655
1656 /* clear any stale contexts */
1657 for (i = 0; i < n_ctx; ++i) _mdns_query_clear(&ctx[i]);
1658 n_ctx = 0;
1659
1660 if (_mdns_sdref == NULL)
1661 {
1662 if (_mdns_old_sdref != NULL)
1663 {
1664 _mdns_generation++;
1665 DNSServiceRefDeallocate(_mdns_old_sdref);
1666 _mdns_old_sdref = NULL;
1667 }
1668
1669 /* (re)initialize the shared connection */
1670 err = DNSServiceCreateConnection(&_mdns_sdref);
1671
1672 /* limit the number of retries */
1673 if ((initialize_retries-- <= 0) && (err == 0)) err = kDNSServiceErr_Unknown;
1674 if (err != 0)
1675 {
1676 wait = false;
1677 pthread_mutex_unlock(&_mdns_mutex);
1678 break;
1679 }
1680 }
1681
1682 /*
1683 * issue (or reissue) the queries
1684 * unspecified type: do parallel A and AAAA
1685 */
1686 if (err == 0)
1687 {
1688 err = _mdns_query_start(&ctx[n_ctx++], reply, answer, anslen, name, class, (type == 0) ? ns_t_a : type, interface, flags, kq);
1689 }
1690
1691 if ((err == 0) && (type == 0))
1692 {
1693 err = _mdns_query_start(&ctx[n_ctx++], reply, answer, anslen, name, class, ns_t_aaaa, interface, flags, kq);
1694 }
1695
1696 if (err != 0) _mdns_debug_message(";; initialization error %d\n", err);
1697
1698 /* try to reinitialize */
1699 if ((err == kDNSServiceErr_Unknown) || (err == kDNSServiceErr_ServiceNotRunning) || (err == kDNSServiceErr_BadReference))
1700 {
1701 if (_mdns_sdref != NULL)
1702 {
1703 _mdns_generation++;
1704 DNSServiceRefDeallocate(_mdns_sdref);
1705 _mdns_sdref = NULL;
1706 }
1707
1708 err = 0;
1709 initialize = true;
1710 pthread_mutex_unlock(&_mdns_mutex);
1711 continue;
1712 }
1713 else if (err != 0)
1714 {
1715 pthread_mutex_unlock(&_mdns_mutex);
1716 break;
1717 }
1718
1719 /* (re)register the fd with kqueue */
1720 int fd = DNSServiceRefSockFD(_mdns_sdref);
1721 EV_SET(&ev, fd, EVFILT_READ, EV_ADD, 0, 0, 0);
1722 n = kevent(kq, &ev, 1, NULL, 0, NULL);
1723 pthread_mutex_unlock(&_mdns_mutex);
1724 if (err != 0 || n != 0) break;
1725 }
1726
1727 _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);
1728
1729 n = kevent(kq, NULL, 0, &ev, 1, &timeout);
1730 if ((n < 0) && (errno != EINTR))
1731 {
1732 res = -1;
1733 break;
1734 }
1735
1736 pthread_mutex_lock(&_mdns_mutex);
1737
1738 /*
1739 * DNSServiceProcessResult() is a blocking API
1740 * confirm that there is still data on the socket
1741 */
1742 const struct timespec notimeout = { 0, 0 };
1743 int m = kevent(kq, NULL, 0, &ev, 1, &notimeout);
1744
1745 if (_mdns_sdref == NULL)
1746 {
1747 initialize = true;
1748 }
1749 else if (m > 0 && ev.filter == EVFILT_READ)
1750 {
1751 err = DNSServiceProcessResult(_mdns_sdref);
1752 if ((err == kDNSServiceErr_ServiceNotRunning) || (err == kDNSServiceErr_BadReference))
1753 {
1754 _mdns_debug_message(";; DNSServiceProcessResult status %d [ctx %p %p]\n", err, (n_ctx > 0) ? &(ctx[0]) : NULL, (n_ctx > 1) ? &(ctx[1]) : NULL);
1755 err = 0;
1756
1757 /* re-initialize the shared connection */
1758 _mdns_generation++;
1759 DNSServiceRefDeallocate(_mdns_sdref);
1760 _mdns_sdref = NULL;
1761 initialize = true;
1762 }
1763 }
1764
1765 /* Check if all queries are complete (including errors) */
1766 complete = true;
1767 for (i = 0; i < n_ctx; ++i)
1768 {
1769 if ((ctx[i].error != 0) || _mdns_query_is_complete(&ctx[i]))
1770 {
1771 if (ctx[i].type == ns_t_a)
1772 {
1773 got_a_response = GOT_DATA;
1774 if (ctx[i].error != 0) got_a_response = GOT_ERROR;
1775 }
1776
1777 _mdns_debug_message(";; [%s type %d class %d] finished processing ctx %p\n", name, type, class, &(ctx[i]));
1778 }
1779 else
1780 {
1781 _mdns_debug_message(";; [%s type %d class %d] continuing ctx %p\n", name, type, class, &(ctx[i]));
1782 complete = false;
1783 }
1784 }
1785
1786 pthread_mutex_unlock(&_mdns_mutex);
1787
1788 if (err != 0)
1789 {
1790 _mdns_debug_message(";; DNSServiceProcessResult error status %d [ctx %p %p]\n", err, (n_ctx > 0) ? &(ctx[0]) : NULL, (n_ctx > 1) ? &(ctx[1]) : NULL);
1791 break;
1792 }
1793 else if (complete)
1794 {
1795 _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);
1796 break;
1797 }
1798 else if (got_a_response != 0)
1799 {
1800 /* got A, adjust deadline for AAAA */
1801 struct timespec now, tn, extra;
1802
1803 /* delta = now - start */
1804 _mdns_now(&now);
1805 _mdns_sub_time(&delta, &now, &start);
1806
1807 extra.tv_sec = SHORT_AAAA_EXTRA;
1808 extra.tv_nsec = 0;
1809
1810 /* if delta is small (<= 20 milliseconds), we probably got a result from mDNSResponder's cache */
1811 if ((delta.tv_sec == 0) && (delta.tv_nsec <= 20000000))
1812 {
1813 extra.tv_sec = MEDIUM_AAAA_EXTRA;
1814 }
1815 else if (n_iface_4 == 0)
1816 {
1817 extra.tv_sec = LONG_AAAA_EXTRA;
1818 }
1819 else if (got_a_response == GOT_ERROR)
1820 {
1821 extra.tv_sec = MEDIUM_AAAA_EXTRA;
1822 }
1823
1824 /* tn = 2 * delta */
1825 _mdns_add_time(&tn, &delta, &delta);
1826
1827 /* delta = tn + extra */
1828 _mdns_add_time(&delta, &tn, &extra);
1829
1830 /* check that delta doesn't exceed our total timeout */
1831 _mdns_sub_time(&tn, &timeout, &delta);
1832 if (tn.tv_sec >= 0)
1833 {
1834 _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);
1835 _mdns_deadline(&finish, &delta);
1836 }
1837 }
1838
1839 /* calculate remaining timeout */
1840 _mdns_timeout(&timeout, &finish);
1841
1842 /* check for time remaining */
1843 if (timeout.tv_sec < 0)
1844 {
1845 _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);
1846 break;
1847 }
1848 }
1849
1850 complete = false;
1851 pthread_mutex_lock(&_mdns_mutex);
1852
1853 for (i = 0; i < n_ctx; ++i)
1854 {
1855 if (err == 0) err = ctx[i].error;
1856 /* only clears hostents if result is incomplete */
1857 complete = _mdns_query_clear(&ctx[i]) | complete;
1858 }
1859
1860 pthread_mutex_unlock(&_mdns_mutex);
1861
1862 /* everything should be done with the kq by now */
1863 close(kq);
1864
1865 /* return error if everything is incomplete */
1866 if (!complete) res = -1;
1867
1868 if (anslen != NULL) *anslen = ctx[0].anslen;
1869 return res;
1870 }