]> git.meshlink.io Git - catta/blob - avahi-compat-libdns_sd/compat.c
* Rename AVAHI_ERR_NOT_CONNECTED to AVAHI_ERR_DISCONNECTED
[catta] / avahi-compat-libdns_sd / compat.c
1 /* $Id$ */
2
3 /***
4   This file is part of avahi.
5  
6   avahi is free software; you can redistribute it and/or modify it
7   under the terms of the GNU Lesser General Public License as
8   published by the Free Software Foundation; either version 2.1 of the
9   License, or (at your option) any later version.
10  
11   avahi is distributed in the hope that it will be useful, but WITHOUT
12   ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13   or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
14   Public License for more details.
15  
16   You should have received a copy of the GNU Lesser General Public
17   License along with avahi; if not, write to the Free Software
18   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19   USA.
20 ***/
21
22 #ifdef HAVE_CONFIG_H
23 #include <config.h>
24 #endif
25
26 #include <pthread.h>
27 #include <assert.h>
28 #include <unistd.h>
29 #include <stdio.h>
30 #include <errno.h>
31 #include <string.h>
32 #include <signal.h>
33 #include <netinet/in.h>
34 #include <fcntl.h>
35
36 #include <sys/types.h>
37 #include <sys/socket.h>
38
39 #include <avahi-common/simple-watch.h>
40 #include <avahi-common/malloc.h>
41 #include <avahi-common/error.h>
42 #include <avahi-common/domain.h>
43 #include <avahi-common/alternative.h>
44
45 #include <avahi-client/client.h>
46 #include <avahi-client/publish.h>
47 #include <avahi-client/lookup.h>
48
49 #include "warn.h"
50 #include "dns_sd.h"
51
52 enum {
53     COMMAND_POLL = 'p',
54     COMMAND_QUIT = 'q',
55     COMMAND_POLL_DONE = 'P',
56     COMMAND_POLL_FAILED = 'F'
57 };
58
59 struct _DNSServiceRef_t {
60     int n_ref;
61     
62     AvahiSimplePoll *simple_poll;
63
64     int thread_fd, main_fd;
65
66     pthread_t thread;
67     int thread_running;
68
69     pthread_mutex_t mutex;
70     
71     void *context;
72     DNSServiceBrowseReply service_browser_callback;
73     DNSServiceResolveReply service_resolver_callback;
74     DNSServiceDomainEnumReply domain_browser_callback;
75     DNSServiceRegisterReply service_register_callback;
76
77     AvahiClient *client;
78     AvahiServiceBrowser *service_browser;
79     AvahiServiceResolver *service_resolver;
80     AvahiDomainBrowser *domain_browser;
81
82     char *service_name, *service_name_chosen, *service_regtype, *service_domain, *service_host;
83     uint16_t service_port;
84     AvahiIfIndex service_interface;
85     AvahiStringList *service_txt;
86
87     AvahiEntryGroup *entry_group;
88 };
89
90 #define ASSERT_SUCCESS(r) { int __ret = (r); assert(__ret == 0); }
91
92 static DNSServiceErrorType map_error(int error) {
93     switch (error) {
94         case AVAHI_OK :
95             return kDNSServiceErr_NoError;
96             
97         case AVAHI_ERR_BAD_STATE :
98             return kDNSServiceErr_BadState;
99             
100         case AVAHI_ERR_INVALID_HOST_NAME:
101         case AVAHI_ERR_INVALID_DOMAIN_NAME:
102         case AVAHI_ERR_INVALID_TTL:
103         case AVAHI_ERR_IS_PATTERN:
104         case AVAHI_ERR_INVALID_RECORD:
105         case AVAHI_ERR_INVALID_SERVICE_NAME:
106         case AVAHI_ERR_INVALID_SERVICE_TYPE:
107         case AVAHI_ERR_INVALID_PORT:
108         case AVAHI_ERR_INVALID_KEY:
109         case AVAHI_ERR_INVALID_ADDRESS:
110         case AVAHI_ERR_INVALID_SERVICE_SUBTYPE:
111             return kDNSServiceErr_BadParam;
112
113
114         case AVAHI_ERR_COLLISION:
115             return kDNSServiceErr_NameConflict;
116
117         case AVAHI_ERR_TOO_MANY_CLIENTS:
118         case AVAHI_ERR_TOO_MANY_OBJECTS:
119         case AVAHI_ERR_TOO_MANY_ENTRIES:
120         case AVAHI_ERR_ACCESS_DENIED:
121             return kDNSServiceErr_Refused;
122
123         case AVAHI_ERR_INVALID_OPERATION:
124         case AVAHI_ERR_INVALID_OBJECT:
125             return kDNSServiceErr_Invalid;
126
127         case AVAHI_ERR_NO_MEMORY:
128             return kDNSServiceErr_NoMemory;
129
130         case AVAHI_ERR_INVALID_INTERFACE:
131         case AVAHI_ERR_INVALID_PROTOCOL:
132             return kDNSServiceErr_BadInterfaceIndex;
133         
134         case AVAHI_ERR_INVALID_FLAGS:
135             return kDNSServiceErr_BadFlags;
136             
137         case AVAHI_ERR_NOT_FOUND:
138             return kDNSServiceErr_NoSuchName;
139             
140         case AVAHI_ERR_VERSION_MISMATCH:
141             return kDNSServiceErr_Incompatible;
142
143         case AVAHI_ERR_NO_NETWORK:
144         case AVAHI_ERR_OS:
145         case AVAHI_ERR_INVALID_CONFIG:
146         case AVAHI_ERR_TIMEOUT:
147         case AVAHI_ERR_DBUS_ERROR:
148         case AVAHI_ERR_DISCONNECTED:
149         case AVAHI_ERR_NO_DAEMON:
150             break;
151
152     }
153
154     return kDNSServiceErr_Unknown;
155 }
156
157 static const char *add_trailing_dot(const char *s, char *buf, size_t buf_len) {
158     if (!s)
159         return NULL;
160
161     if (*s == 0)
162         return s;
163
164     if (s[strlen(s)-1] == '.')
165         return s;
166
167     snprintf(buf, buf_len, "%s.", s);
168     return buf;
169 }
170
171 static int read_command(int fd) {
172     ssize_t r;
173     char command;
174
175     assert(fd >= 0);
176     
177     if ((r = read(fd, &command, 1)) != 1) {
178         fprintf(stderr, __FILE__": read() failed: %s\n", r < 0 ? strerror(errno) : "EOF");
179         return -1;
180     }
181
182     return command;
183 }
184
185 static int write_command(int fd, char reply) {
186     assert(fd >= 0);
187
188     if (write(fd, &reply, 1) != 1) {
189         fprintf(stderr, __FILE__": write() failed: %s\n", strerror(errno));
190         return -1;
191     }
192
193     return 0;
194 }
195
196 static int poll_func(struct pollfd *ufds, unsigned int nfds, int timeout, void *userdata) {
197     DNSServiceRef sdref = userdata;
198     int ret;
199     
200     assert(sdref);
201     
202     ASSERT_SUCCESS(pthread_mutex_unlock(&sdref->mutex));
203
204 /*     fprintf(stderr, "pre-syscall\n"); */
205     ret = poll(ufds, nfds, timeout);
206 /*     fprintf(stderr, "post-syscall\n"); */
207     
208     ASSERT_SUCCESS(pthread_mutex_lock(&sdref->mutex));
209
210     return ret;
211 }
212
213 static void * thread_func(void *data) {
214     DNSServiceRef sdref = data;
215     sigset_t mask;
216
217     sigfillset(&mask);
218     pthread_sigmask(SIG_BLOCK, &mask, NULL);
219     
220     sdref->thread = pthread_self();
221     sdref->thread_running = 1;
222
223     for (;;) {
224         char command;
225
226         if ((command = read_command(sdref->thread_fd)) < 0)
227             break;
228
229 /*         fprintf(stderr, "Command: %c\n", command); */
230         
231         switch (command) {
232
233             case COMMAND_POLL: {
234                 int ret;
235
236                 ASSERT_SUCCESS(pthread_mutex_lock(&sdref->mutex));
237
238                 for (;;) {
239                     errno = 0;
240                     
241                     if ((ret = avahi_simple_poll_run(sdref->simple_poll)) < 0) {
242
243                         if (errno == EINTR)
244                             continue;
245                         
246                         fprintf(stderr, __FILE__": avahi_simple_poll_run() failed: %s\n", strerror(errno));
247                     }
248
249                     break;
250                 }
251
252                 ASSERT_SUCCESS(pthread_mutex_unlock(&sdref->mutex));
253
254                 if (write_command(sdref->thread_fd, ret < 0 ? COMMAND_POLL_FAILED : COMMAND_POLL_DONE) < 0)
255                     break;
256                 
257                 break;
258             }
259
260             case COMMAND_QUIT:
261                 return NULL;
262         }
263         
264     }
265
266     return NULL;
267 }
268
269 static DNSServiceRef sdref_new(void) {
270     int fd[2] = { -1, -1 };
271     DNSServiceRef sdref = NULL;
272     pthread_mutexattr_t mutex_attr;
273
274     if (socketpair(AF_UNIX, SOCK_STREAM, 0, fd) < 0)
275         goto fail;
276
277     if (!(sdref = avahi_new(struct _DNSServiceRef_t, 1)))
278         goto fail;
279
280     sdref->n_ref = 1;
281     sdref->thread_fd = fd[0];
282     sdref->main_fd = fd[1];
283
284     sdref->client = NULL;
285     sdref->service_browser = NULL;
286     sdref->service_resolver = NULL;
287     sdref->domain_browser = NULL;
288     sdref->entry_group = NULL;
289
290     sdref->service_name = sdref->service_name_chosen = sdref->service_regtype = sdref->service_domain = sdref->service_host = NULL;
291     sdref->service_txt = NULL;
292
293     ASSERT_SUCCESS(pthread_mutexattr_init(&mutex_attr));
294     pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_RECURSIVE);
295     ASSERT_SUCCESS(pthread_mutex_init(&sdref->mutex, &mutex_attr));
296
297     sdref->thread_running = 0;
298
299     if (!(sdref->simple_poll = avahi_simple_poll_new()))
300         goto fail;
301
302     avahi_simple_poll_set_func(sdref->simple_poll, poll_func, sdref);
303
304     /* Start simple poll */
305     if (avahi_simple_poll_prepare(sdref->simple_poll, -1) < 0)
306         goto fail;
307
308     /* Queue an initial POLL command for the thread */
309     if (write_command(sdref->main_fd, COMMAND_POLL) < 0)
310         goto fail;
311     
312     if (pthread_create(&sdref->thread, NULL, thread_func, sdref) != 0)
313         goto fail;
314
315     sdref->thread_running = 1;
316     
317     return sdref;
318
319 fail:
320
321     if (sdref)
322         DNSServiceRefDeallocate(sdref);
323
324     return NULL;
325 }
326
327 static void sdref_free(DNSServiceRef sdref) {
328     assert(sdref);
329     
330     if (sdref->thread_running) {
331         ASSERT_SUCCESS(write_command(sdref->main_fd, COMMAND_QUIT));
332         avahi_simple_poll_wakeup(sdref->simple_poll);
333         ASSERT_SUCCESS(pthread_join(sdref->thread, NULL));
334     }
335
336     if (sdref->client)
337         avahi_client_free(sdref->client);
338
339     if (sdref->simple_poll)
340         avahi_simple_poll_free(sdref->simple_poll);
341
342     if (sdref->thread_fd >= 0)
343         close(sdref->thread_fd);
344
345     if (sdref->main_fd >= 0)
346         close(sdref->main_fd);
347
348     ASSERT_SUCCESS(pthread_mutex_destroy(&sdref->mutex));
349
350     avahi_free(sdref->service_name);
351     avahi_free(sdref->service_name_chosen);
352     avahi_free(sdref->service_regtype);
353     avahi_free(sdref->service_domain);
354     avahi_free(sdref->service_host);
355
356     avahi_string_list_free(sdref->service_txt);
357     
358     avahi_free(sdref);
359 }
360
361 static void sdref_ref(DNSServiceRef sdref) {
362     assert(sdref);
363     assert(sdref->n_ref >= 1);
364
365     sdref->n_ref++;
366 }
367
368 static void sdref_unref(DNSServiceRef sdref) {
369     assert(sdref);
370     assert(sdref->n_ref >= 1);
371
372     if (--(sdref->n_ref) <= 0)
373         sdref_free(sdref);
374 }
375
376 int DNSSD_API DNSServiceRefSockFD(DNSServiceRef sdref) {
377     assert(sdref);
378     assert(sdref->n_ref >= 1);
379
380     AVAHI_WARN_LINKAGE;
381     
382     return sdref->main_fd;
383 }
384
385 DNSServiceErrorType DNSSD_API DNSServiceProcessResult(DNSServiceRef sdref) {
386     DNSServiceErrorType ret = kDNSServiceErr_Unknown;
387
388     assert(sdref);
389     assert(sdref->n_ref >= 1);
390     
391     AVAHI_WARN_LINKAGE;
392
393     ASSERT_SUCCESS(pthread_mutex_lock(&sdref->mutex));
394
395     sdref_ref(sdref);
396     
397     /* Cleanup notification socket */
398     if (read_command(sdref->main_fd) != COMMAND_POLL_DONE)
399         goto finish;
400     
401     if (avahi_simple_poll_dispatch(sdref->simple_poll) < 0)
402         goto finish;
403
404     if (sdref->n_ref > 1) /* Perhaps we should die */
405
406         /* Dispatch events */
407         if (avahi_simple_poll_prepare(sdref->simple_poll, -1) < 0)
408             goto finish;
409
410     if (sdref->n_ref > 1)
411
412         /* Request the poll */
413         if (write_command(sdref->main_fd, COMMAND_POLL) < 0)
414             goto finish;
415     
416     ret = kDNSServiceErr_NoError;
417     
418 finish:
419
420     sdref_unref(sdref);
421
422     ASSERT_SUCCESS(pthread_mutex_unlock(&sdref->mutex));
423     
424     return ret;
425 }
426
427 void DNSSD_API DNSServiceRefDeallocate(DNSServiceRef sdref) {
428     AVAHI_WARN_LINKAGE;
429
430     if (sdref)
431         sdref_unref(sdref);
432 }
433
434 static void service_browser_callback(
435     AvahiServiceBrowser *b,
436     AvahiIfIndex interface,
437     AVAHI_GCC_UNUSED AvahiProtocol protocol,
438     AvahiBrowserEvent event,
439     const char *name,
440     const char *type,
441     const char *domain,
442     AVAHI_GCC_UNUSED AvahiLookupResultFlags flags,
443     void *userdata) {
444
445     DNSServiceRef sdref = userdata;
446     char type_fixed[AVAHI_DOMAIN_NAME_MAX], domain_fixed[AVAHI_DOMAIN_NAME_MAX];
447     assert(b);
448     assert(sdref);
449     assert(sdref->n_ref >= 1);
450
451     type = add_trailing_dot(type, type_fixed, sizeof(type_fixed));
452     domain  = add_trailing_dot(domain, domain_fixed, sizeof(domain_fixed));
453     
454     switch (event) {
455         case AVAHI_BROWSER_NEW:
456             sdref->service_browser_callback(sdref, kDNSServiceFlagsAdd, interface, kDNSServiceErr_NoError, name, type, domain, sdref->context);
457             break;
458
459         case AVAHI_BROWSER_REMOVE:
460             sdref->service_browser_callback(sdref, 0, interface, kDNSServiceErr_NoError, name, type, domain, sdref->context);
461             break;
462
463         case AVAHI_BROWSER_FAILURE:
464             sdref->service_browser_callback(sdref, 0, interface, map_error(avahi_client_errno(sdref->client)), NULL, NULL, NULL, sdref->context);
465             break;
466             
467         case AVAHI_BROWSER_CACHE_EXHAUSTED:
468         case AVAHI_BROWSER_ALL_FOR_NOW:
469             break;
470     }
471 }
472
473 static void generic_client_callback(AvahiClient *s, AvahiClientState state, void* userdata) {
474     DNSServiceRef sdref = userdata;
475     int error = kDNSServiceErr_Unknown;
476         
477     assert(s);
478     assert(sdref);
479     assert(sdref->n_ref >= 1);
480
481     switch (state) {
482
483         case AVAHI_CLIENT_FAILURE:
484
485             if (sdref->service_browser_callback)
486                 sdref->service_browser_callback(sdref, 0, 0, error, NULL, NULL, NULL, sdref->context);
487             else if (sdref->service_resolver_callback)
488                 sdref->service_resolver_callback(sdref, 0, 0, error, NULL, NULL, 0, 0, NULL, sdref->context);
489             else if (sdref->domain_browser_callback)
490                 sdref->domain_browser_callback(sdref, 0, 0, error, NULL, sdref->context);
491
492             break;
493
494         case AVAHI_CLIENT_S_RUNNING:
495         case AVAHI_CLIENT_S_COLLISION:
496         case AVAHI_CLIENT_S_REGISTERING:
497             break;
498     }
499 }
500
501 DNSServiceErrorType DNSSD_API DNSServiceBrowse(
502     DNSServiceRef *ret_sdref,
503     DNSServiceFlags flags,
504     uint32_t interface,
505     const char *regtype,
506     const char *domain,
507     DNSServiceBrowseReply callback,
508     void *context) {
509
510     DNSServiceErrorType ret = kDNSServiceErr_Unknown;
511     int error;
512     DNSServiceRef sdref = NULL;
513     AvahiIfIndex ifindex;
514     
515     AVAHI_WARN_LINKAGE;
516     
517     assert(ret_sdref);
518     assert(regtype);
519     assert(domain);
520     assert(callback);
521
522     if (interface == kDNSServiceInterfaceIndexLocalOnly || flags != 0) {
523         AVAHI_WARN_UNSUPPORTED;
524         return kDNSServiceErr_Unsupported;
525     }
526
527     if (!(sdref = sdref_new()))
528         return kDNSServiceErr_Unknown;
529
530     sdref->context = context;
531     sdref->service_browser_callback = callback;
532
533     ASSERT_SUCCESS(pthread_mutex_lock(&sdref->mutex));
534     
535     if (!(sdref->client = avahi_client_new(avahi_simple_poll_get(sdref->simple_poll), generic_client_callback, sdref, &error))) {
536         ret =  map_error(error);
537         goto finish;
538     }
539
540     ifindex = interface == kDNSServiceInterfaceIndexAny ? AVAHI_IF_UNSPEC : (AvahiIfIndex) interface;
541     
542     if (!(sdref->service_browser = avahi_service_browser_new(sdref->client, ifindex, AVAHI_PROTO_UNSPEC, regtype, domain, 0, service_browser_callback, sdref))) {
543         ret = map_error(avahi_client_errno(sdref->client));
544         goto finish;
545     }
546     
547     ret = kDNSServiceErr_NoError;
548     *ret_sdref = sdref;
549                                                               
550 finish:
551
552     ASSERT_SUCCESS(pthread_mutex_unlock(&sdref->mutex));
553     
554     if (ret != kDNSServiceErr_NoError)
555         DNSServiceRefDeallocate(sdref);
556
557     return ret;
558 }
559
560 static void service_resolver_callback(
561     AvahiServiceResolver *r,
562     AvahiIfIndex interface,
563     AVAHI_GCC_UNUSED AvahiProtocol protocol,
564     AvahiResolverEvent event,
565     const char *name,
566     const char *type,
567     const char *domain,
568     const char *host_name,
569     AVAHI_GCC_UNUSED const AvahiAddress *a,
570     uint16_t port,
571     AvahiStringList *txt,
572     AVAHI_GCC_UNUSED AvahiLookupResultFlags flags,
573     void *userdata) {
574
575     DNSServiceRef sdref = userdata;
576
577     assert(r);
578     assert(sdref);
579     assert(sdref->n_ref >= 1);
580
581     switch (event) {
582         case AVAHI_RESOLVER_FOUND: {
583
584             char host_name_fixed[AVAHI_DOMAIN_NAME_MAX];
585             char full_name[AVAHI_DOMAIN_NAME_MAX];
586             int ret;
587             char *p = NULL;
588             size_t l = 0;
589
590             host_name = add_trailing_dot(host_name, host_name_fixed, sizeof(host_name_fixed));
591
592             if ((p = avahi_new0(char, (l = avahi_string_list_serialize(txt, NULL, 0))+1)))
593                 avahi_string_list_serialize(txt, p, l);
594
595             ret = avahi_service_name_join(full_name, sizeof(full_name), name, type, domain);
596             assert(ret == AVAHI_OK);
597
598             strcat(full_name, ".");
599             
600             sdref->service_resolver_callback(sdref, 0, interface, kDNSServiceErr_NoError, full_name, host_name, htons(port), l, p, sdref->context);
601
602             avahi_free(p);
603             break;
604         }
605
606         case AVAHI_RESOLVER_FAILURE:
607             sdref->service_resolver_callback(sdref, 0, interface, map_error(avahi_client_errno(sdref->client)), NULL, NULL, 0, 0, NULL, sdref->context);
608             break;
609     }
610 }
611
612 DNSServiceErrorType DNSSD_API DNSServiceResolve(
613     DNSServiceRef *ret_sdref,
614     DNSServiceFlags flags,
615     uint32_t interface,
616     const char *name,
617     const char *regtype,
618     const char *domain,
619     DNSServiceResolveReply callback,
620     void *context) {
621
622     DNSServiceErrorType ret = kDNSServiceErr_Unknown;
623     int error;
624     DNSServiceRef sdref = NULL;
625     AvahiIfIndex ifindex;
626
627     AVAHI_WARN_LINKAGE;
628
629     assert(ret_sdref);
630     assert(name);
631     assert(regtype);
632     assert(domain);
633     assert(callback);
634
635     if (interface == kDNSServiceInterfaceIndexLocalOnly || flags != 0) {
636         AVAHI_WARN_UNSUPPORTED;
637         return kDNSServiceErr_Unsupported;
638     }
639
640     if (!(sdref = sdref_new()))
641         return kDNSServiceErr_Unknown;
642
643     sdref->context = context;
644     sdref->service_resolver_callback = callback;
645
646     ASSERT_SUCCESS(pthread_mutex_lock(&sdref->mutex));
647     
648     if (!(sdref->client = avahi_client_new(avahi_simple_poll_get(sdref->simple_poll), generic_client_callback, sdref, &error))) {
649         ret =  map_error(error);
650         goto finish;
651     }
652
653     ifindex = interface == kDNSServiceInterfaceIndexAny ? AVAHI_IF_UNSPEC : (AvahiIfIndex) interface;
654     
655     if (!(sdref->service_resolver = avahi_service_resolver_new(sdref->client, ifindex, AVAHI_PROTO_UNSPEC, name, regtype, domain, AVAHI_PROTO_UNSPEC, 0, service_resolver_callback, sdref))) {
656         ret = map_error(avahi_client_errno(sdref->client));
657         goto finish;
658     }
659     
660
661     ret = kDNSServiceErr_NoError;
662     *ret_sdref = sdref;
663                                                               
664 finish:
665
666     ASSERT_SUCCESS(pthread_mutex_unlock(&sdref->mutex));
667     
668     if (ret != kDNSServiceErr_NoError)
669         DNSServiceRefDeallocate(sdref);
670
671     return ret;
672 }
673
674 int DNSSD_API DNSServiceConstructFullName (
675     char *fullName,
676     const char *service,   
677     const char *regtype,
678     const char *domain) {
679
680     AVAHI_WARN_LINKAGE;
681
682     assert(fullName);
683     assert(regtype);
684     assert(domain);
685
686     if (avahi_service_name_join(fullName, kDNSServiceMaxDomainName, service, regtype, domain) < 0)
687         return -1;
688     
689     return 0;
690 }
691
692 static void domain_browser_callback(
693     AvahiDomainBrowser *b,
694     AvahiIfIndex interface,
695     AVAHI_GCC_UNUSED AvahiProtocol protocol,
696     AvahiBrowserEvent event,
697     const char *domain,
698     AVAHI_GCC_UNUSED AvahiLookupResultFlags flags,
699     void *userdata) {
700
701     DNSServiceRef sdref = userdata;
702     static char domain_fixed[AVAHI_DOMAIN_NAME_MAX];
703
704     assert(b);
705     assert(sdref);
706     assert(sdref->n_ref >= 1);
707
708     domain  = add_trailing_dot(domain, domain_fixed, sizeof(domain_fixed));
709
710     switch (event) {
711         case AVAHI_BROWSER_NEW:
712             sdref->domain_browser_callback(sdref, kDNSServiceFlagsAdd, interface, kDNSServiceErr_NoError, domain, sdref->context);
713             break;
714
715         case AVAHI_BROWSER_REMOVE:
716             sdref->domain_browser_callback(sdref, 0, interface, kDNSServiceErr_NoError, domain, sdref->context);
717             break;
718
719         case AVAHI_BROWSER_FAILURE:
720             sdref->domain_browser_callback(sdref, 0, interface, map_error(avahi_client_errno(sdref->client)), domain, sdref->context);
721             break;
722             
723         case AVAHI_BROWSER_CACHE_EXHAUSTED:
724         case AVAHI_BROWSER_ALL_FOR_NOW:
725             break;
726     }
727 }
728
729 DNSServiceErrorType DNSSD_API DNSServiceEnumerateDomains(
730     DNSServiceRef *ret_sdref,
731     DNSServiceFlags flags,
732     uint32_t interface,
733     DNSServiceDomainEnumReply callback,
734     void *context) {
735
736     DNSServiceErrorType ret = kDNSServiceErr_Unknown;
737     int error;
738     DNSServiceRef sdref = NULL;
739     AvahiIfIndex ifindex;
740
741     AVAHI_WARN_LINKAGE;
742
743     assert(ret_sdref);
744     assert(callback);
745
746     if (interface == kDNSServiceInterfaceIndexLocalOnly ||
747         (flags != kDNSServiceFlagsBrowseDomains &&  flags != kDNSServiceFlagsRegistrationDomains)) {
748         AVAHI_WARN_UNSUPPORTED;
749         return kDNSServiceErr_Unsupported;
750     }
751
752     if (!(sdref = sdref_new()))
753         return kDNSServiceErr_Unknown;
754
755     sdref->context = context;
756     sdref->domain_browser_callback = callback;
757
758     ASSERT_SUCCESS(pthread_mutex_lock(&sdref->mutex));
759     
760     if (!(sdref->client = avahi_client_new(avahi_simple_poll_get(sdref->simple_poll), generic_client_callback, sdref, &error))) {
761         ret =  map_error(error);
762         goto finish;
763     }
764
765     ifindex = interface == kDNSServiceInterfaceIndexAny ? AVAHI_IF_UNSPEC : (AvahiIfIndex) interface;
766     
767     if (!(sdref->domain_browser = avahi_domain_browser_new(sdref->client, ifindex, AVAHI_PROTO_UNSPEC, "local",
768                                                            flags == kDNSServiceFlagsRegistrationDomains ? AVAHI_DOMAIN_BROWSER_REGISTER : AVAHI_DOMAIN_BROWSER_BROWSE,
769                                                            0, domain_browser_callback, sdref))) {
770         ret = map_error(avahi_client_errno(sdref->client));
771         goto finish;
772     }
773     
774     ret = kDNSServiceErr_NoError;
775     *ret_sdref = sdref;
776                                                               
777 finish:
778
779     ASSERT_SUCCESS(pthread_mutex_unlock(&sdref->mutex));
780     
781     if (ret != kDNSServiceErr_NoError)
782         DNSServiceRefDeallocate(sdref);
783
784     return ret;
785 }
786
787 static void reg_report_error(DNSServiceRef sdref, DNSServiceErrorType error) {
788     char regtype_fixed[AVAHI_DOMAIN_NAME_MAX], domain_fixed[AVAHI_DOMAIN_NAME_MAX];
789     const char *regtype, *domain;
790     assert(sdref);
791     assert(sdref->n_ref >= 1);
792
793     assert(sdref->service_register_callback);
794
795     regtype = add_trailing_dot(sdref->service_regtype, regtype_fixed, sizeof(regtype_fixed));
796     domain = add_trailing_dot(sdref->service_domain, domain_fixed, sizeof(domain_fixed));
797     
798     sdref->service_register_callback(
799         sdref, 0, error,
800         sdref->service_name_chosen ? sdref->service_name_chosen : sdref->service_name,
801         regtype,
802         domain,
803         sdref->context);
804 }
805
806 static int reg_create_service(DNSServiceRef sdref) {
807     int ret;
808     const char *real_type;
809     
810     assert(sdref);
811     assert(sdref->n_ref >= 1);
812
813     real_type = avahi_get_type_from_subtype(sdref->service_regtype);
814     
815     if ((ret = avahi_entry_group_add_service_strlst(
816         sdref->entry_group,
817         sdref->service_interface,
818         AVAHI_PROTO_UNSPEC,
819         0,
820         sdref->service_name_chosen,
821         real_type ? real_type : sdref->service_regtype,
822         sdref->service_domain,
823         sdref->service_host,
824         sdref->service_port,
825         sdref->service_txt)) < 0)
826         return ret;
827
828     
829     if (real_type) {
830         /* Create a subtype entry */
831
832         if (avahi_entry_group_add_service_subtype(
833                 sdref->entry_group,
834                 sdref->service_interface,
835                 AVAHI_PROTO_UNSPEC,
836                 0,
837                 sdref->service_name_chosen,
838                 real_type,
839                 sdref->service_domain,
840                 sdref->service_regtype) < 0)
841             return ret;
842
843     }
844
845     if ((ret = avahi_entry_group_commit(sdref->entry_group)) < 0)
846         return ret;
847
848     return 0;
849 }
850
851 static void reg_client_callback(AvahiClient *s, AvahiClientState state, void* userdata) {
852     DNSServiceRef sdref = userdata;
853
854     assert(s);
855     assert(sdref);
856     assert(sdref->n_ref >= 1);
857
858     /* We've not been setup completely */
859     if (!sdref->entry_group)
860         return;
861     
862     switch (state) {
863         case AVAHI_CLIENT_FAILURE:
864             reg_report_error(sdref, kDNSServiceErr_Unknown);
865             break;
866
867         case AVAHI_CLIENT_S_RUNNING: {
868             int ret;
869
870             if (!sdref->service_name) {
871                 const char *n;
872                 /* If the service name is taken from the host name, copy that */
873
874                 avahi_free(sdref->service_name_chosen);
875                 sdref->service_name_chosen = NULL;
876
877                 if (!(n = avahi_client_get_host_name(sdref->client))) {
878                     reg_report_error(sdref, map_error(avahi_client_errno(sdref->client)));
879                     return;
880                 }
881
882                 if (!(sdref->service_name_chosen = avahi_strdup(n))) {
883                     reg_report_error(sdref, kDNSServiceErr_NoMemory);
884                     return;
885                 }
886             }
887             
888             /* Register the service */
889
890             if ((ret = reg_create_service(sdref)) < 0) {
891                 reg_report_error(sdref, map_error(ret));
892                 return;
893             }
894             
895             break;
896         }
897             
898         case AVAHI_CLIENT_S_COLLISION:
899
900             /* Remove our entry */
901             avahi_entry_group_reset(sdref->entry_group);
902             
903             break;
904
905         case AVAHI_CLIENT_S_REGISTERING:
906             /* Ignore */
907             break;
908     }
909
910 }
911
912 static void reg_entry_group_callback(AvahiEntryGroup *g, AvahiEntryGroupState state, void *userdata) {
913     DNSServiceRef sdref = userdata;
914
915     assert(g);
916
917     switch (state) {
918         case AVAHI_ENTRY_GROUP_ESTABLISHED:
919             /* Inform the user */
920             reg_report_error(sdref, kDNSServiceErr_NoError);
921
922             break;
923
924         case AVAHI_ENTRY_GROUP_COLLISION: {
925             char *n;
926             int ret;
927             
928             /* Remove our entry */
929             avahi_entry_group_reset(sdref->entry_group);
930
931             assert(sdref->service_name_chosen);
932
933             /* Pick a new name */
934             if (!(n = avahi_alternative_service_name(sdref->service_name_chosen))) {
935                 reg_report_error(sdref, kDNSServiceErr_NoMemory);
936                 return;
937             }
938             avahi_free(sdref->service_name_chosen);
939             sdref->service_name_chosen = n;
940
941             /* Register the service with that new name */
942             if ((ret = reg_create_service(sdref)) < 0) {
943                 reg_report_error(sdref, map_error(ret));
944                 return;
945             }
946             
947             break;
948         }
949
950         case AVAHI_ENTRY_GROUP_REGISTERING:
951         case AVAHI_ENTRY_GROUP_UNCOMMITED:
952             /* Ignore */
953             break;
954
955         case AVAHI_ENTRY_GROUP_FAILURE:
956             /* Inform the user */
957             reg_report_error(sdref, map_error(avahi_client_errno(sdref->client)));
958             break;
959             
960     }
961 }
962
963 DNSServiceErrorType DNSSD_API DNSServiceRegister (
964     DNSServiceRef *ret_sdref,
965     DNSServiceFlags flags,
966     uint32_t interface,
967     const char *name,        
968     const char *regtype,
969     const char *domain,      
970     const char *host,        
971     uint16_t port,
972     uint16_t txtLen,
973     const void *txtRecord,   
974     DNSServiceRegisterReply callback,    
975     void *context) {
976
977     DNSServiceErrorType ret = kDNSServiceErr_Unknown;
978     int error;
979     DNSServiceRef sdref = NULL;
980     AvahiStringList *txt = NULL;
981
982     AVAHI_WARN_LINKAGE;
983
984     assert(ret_sdref);
985     assert(callback);
986     assert(regtype);
987
988     if (interface == kDNSServiceInterfaceIndexLocalOnly || flags) {
989         AVAHI_WARN_UNSUPPORTED;
990         return kDNSServiceErr_Unsupported;
991     }
992
993     if (txtRecord && txtLen > 0) 
994         if (avahi_string_list_parse(txtRecord, txtLen, &txt) < 0)
995             return kDNSServiceErr_Invalid;
996     
997     if (!(sdref = sdref_new())) {
998         avahi_string_list_free(txt);
999         return kDNSServiceErr_Unknown;
1000     }
1001
1002     sdref->context = context;
1003     sdref->service_register_callback = callback;
1004
1005     sdref->service_name = avahi_strdup(name);
1006     sdref->service_regtype = regtype ? avahi_normalize_name_strdup(regtype) : NULL;
1007     sdref->service_domain = domain ? avahi_normalize_name_strdup(domain) : NULL;
1008     sdref->service_host = host ? avahi_normalize_name_strdup(host) : NULL;
1009     sdref->service_interface = interface == kDNSServiceInterfaceIndexAny ? AVAHI_IF_UNSPEC : (AvahiIfIndex) interface;
1010     sdref->service_port = ntohs(port);
1011     sdref->service_txt = txt;
1012
1013     /* Some OOM checking would be cool here */
1014     
1015     ASSERT_SUCCESS(pthread_mutex_lock(&sdref->mutex));
1016     
1017     if (!(sdref->client = avahi_client_new(avahi_simple_poll_get(sdref->simple_poll), reg_client_callback, sdref, &error))) {
1018         ret =  map_error(error);
1019         goto finish;
1020     }
1021
1022     if (!sdref->service_domain) {
1023         const char *d;
1024
1025         if (!(d = avahi_client_get_domain_name(sdref->client))) {
1026             ret = map_error(avahi_client_errno(sdref->client));
1027             goto finish;
1028         }
1029
1030         if (!(sdref->service_domain = avahi_strdup(d))) {
1031             ret = kDNSServiceErr_NoMemory;
1032             goto finish;
1033         }
1034     }
1035
1036     if (!(sdref->entry_group = avahi_entry_group_new(sdref->client, reg_entry_group_callback, sdref))) {
1037         ret = map_error(avahi_client_errno(sdref->client));
1038         goto finish;
1039     }
1040
1041     if (avahi_client_get_state(sdref->client) == AVAHI_CLIENT_S_RUNNING) {
1042         const char *n;
1043
1044         if (sdref->service_name)
1045             n = sdref->service_name;
1046         else {
1047             if (!(n = avahi_client_get_host_name(sdref->client))) {
1048                 ret = map_error(avahi_client_errno(sdref->client));
1049                 goto finish;
1050             }
1051         }
1052
1053         if (!(sdref->service_name_chosen = avahi_strdup(n))) {
1054             ret = kDNSServiceErr_NoMemory;
1055             goto finish;
1056         }
1057
1058             
1059         if ((error = reg_create_service(sdref)) < 0) {
1060             ret = map_error(error);
1061             goto finish;
1062         }
1063     }
1064     
1065     ret = kDNSServiceErr_NoError;
1066     *ret_sdref = sdref;
1067                                                               
1068 finish:
1069
1070     ASSERT_SUCCESS(pthread_mutex_unlock(&sdref->mutex));
1071     
1072     if (ret != kDNSServiceErr_NoError)
1073         DNSServiceRefDeallocate(sdref);
1074
1075     return ret;
1076 }
1077