]> git.meshlink.io Git - catta/blob - avahi-compat-libdns_sd/compat.c
6fec3c96b40ee8bcfbc406bf478426f5af5d83cc
[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_NOT_CONNECTED:
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         case AVAHI_CLIENT_DISCONNECTED:
485
486             if (sdref->service_browser_callback)
487                 sdref->service_browser_callback(sdref, 0, 0, error, NULL, NULL, NULL, sdref->context);
488             else if (sdref->service_resolver_callback)
489                 sdref->service_resolver_callback(sdref, 0, 0, error, NULL, NULL, 0, 0, NULL, sdref->context);
490             else if (sdref->domain_browser_callback)
491                 sdref->domain_browser_callback(sdref, 0, 0, error, NULL, sdref->context);
492
493             break;
494
495         case AVAHI_CLIENT_S_RUNNING:
496         case AVAHI_CLIENT_S_COLLISION:
497         case AVAHI_CLIENT_S_REGISTERING:
498             break;
499     }
500 }
501
502 DNSServiceErrorType DNSSD_API DNSServiceBrowse(
503     DNSServiceRef *ret_sdref,
504     DNSServiceFlags flags,
505     uint32_t interface,
506     const char *regtype,
507     const char *domain,
508     DNSServiceBrowseReply callback,
509     void *context) {
510
511     DNSServiceErrorType ret = kDNSServiceErr_Unknown;
512     int error;
513     DNSServiceRef sdref = NULL;
514     AvahiIfIndex ifindex;
515     
516     AVAHI_WARN_LINKAGE;
517     
518     assert(ret_sdref);
519     assert(regtype);
520     assert(domain);
521     assert(callback);
522
523     if (interface == kDNSServiceInterfaceIndexLocalOnly || flags != 0) {
524         AVAHI_WARN_UNSUPPORTED;
525         return kDNSServiceErr_Unsupported;
526     }
527
528     if (!(sdref = sdref_new()))
529         return kDNSServiceErr_Unknown;
530
531     sdref->context = context;
532     sdref->service_browser_callback = callback;
533
534     ASSERT_SUCCESS(pthread_mutex_lock(&sdref->mutex));
535     
536     if (!(sdref->client = avahi_client_new(avahi_simple_poll_get(sdref->simple_poll), generic_client_callback, sdref, &error))) {
537         ret =  map_error(error);
538         goto finish;
539     }
540
541     ifindex = interface == kDNSServiceInterfaceIndexAny ? AVAHI_IF_UNSPEC : (AvahiIfIndex) interface;
542     
543     if (!(sdref->service_browser = avahi_service_browser_new(sdref->client, ifindex, AVAHI_PROTO_UNSPEC, regtype, domain, 0, service_browser_callback, sdref))) {
544         ret = map_error(avahi_client_errno(sdref->client));
545         goto finish;
546     }
547     
548     ret = kDNSServiceErr_NoError;
549     *ret_sdref = sdref;
550                                                               
551 finish:
552
553     ASSERT_SUCCESS(pthread_mutex_unlock(&sdref->mutex));
554     
555     if (ret != kDNSServiceErr_NoError)
556         DNSServiceRefDeallocate(sdref);
557
558     return ret;
559 }
560
561 static void service_resolver_callback(
562     AvahiServiceResolver *r,
563     AvahiIfIndex interface,
564     AVAHI_GCC_UNUSED AvahiProtocol protocol,
565     AvahiResolverEvent event,
566     const char *name,
567     const char *type,
568     const char *domain,
569     const char *host_name,
570     AVAHI_GCC_UNUSED const AvahiAddress *a,
571     uint16_t port,
572     AvahiStringList *txt,
573     AVAHI_GCC_UNUSED AvahiLookupResultFlags flags,
574     void *userdata) {
575
576     DNSServiceRef sdref = userdata;
577
578     assert(r);
579     assert(sdref);
580     assert(sdref->n_ref >= 1);
581
582     switch (event) {
583         case AVAHI_RESOLVER_FOUND: {
584
585             char host_name_fixed[AVAHI_DOMAIN_NAME_MAX];
586             char full_name[AVAHI_DOMAIN_NAME_MAX];
587             int ret;
588             char *p = NULL;
589             size_t l = 0;
590
591             host_name = add_trailing_dot(host_name, host_name_fixed, sizeof(host_name_fixed));
592
593             if ((p = avahi_new0(char, (l = avahi_string_list_serialize(txt, NULL, 0))+1)))
594                 avahi_string_list_serialize(txt, p, l);
595
596             ret = avahi_service_name_join(full_name, sizeof(full_name), name, type, domain);
597             assert(ret == AVAHI_OK);
598
599             strcat(full_name, ".");
600             
601             sdref->service_resolver_callback(sdref, 0, interface, kDNSServiceErr_NoError, full_name, host_name, htons(port), l, p, sdref->context);
602
603             avahi_free(p);
604             break;
605         }
606
607         case AVAHI_RESOLVER_FAILURE:
608             sdref->service_resolver_callback(sdref, 0, interface, map_error(avahi_client_errno(sdref->client)), NULL, NULL, 0, 0, NULL, sdref->context);
609             break;
610     }
611 }
612
613 DNSServiceErrorType DNSSD_API DNSServiceResolve(
614     DNSServiceRef *ret_sdref,
615     DNSServiceFlags flags,
616     uint32_t interface,
617     const char *name,
618     const char *regtype,
619     const char *domain,
620     DNSServiceResolveReply callback,
621     void *context) {
622
623     DNSServiceErrorType ret = kDNSServiceErr_Unknown;
624     int error;
625     DNSServiceRef sdref = NULL;
626     AvahiIfIndex ifindex;
627
628     AVAHI_WARN_LINKAGE;
629
630     assert(ret_sdref);
631     assert(name);
632     assert(regtype);
633     assert(domain);
634     assert(callback);
635
636     if (interface == kDNSServiceInterfaceIndexLocalOnly || flags != 0) {
637         AVAHI_WARN_UNSUPPORTED;
638         return kDNSServiceErr_Unsupported;
639     }
640
641     if (!(sdref = sdref_new()))
642         return kDNSServiceErr_Unknown;
643
644     sdref->context = context;
645     sdref->service_resolver_callback = callback;
646
647     ASSERT_SUCCESS(pthread_mutex_lock(&sdref->mutex));
648     
649     if (!(sdref->client = avahi_client_new(avahi_simple_poll_get(sdref->simple_poll), generic_client_callback, sdref, &error))) {
650         ret =  map_error(error);
651         goto finish;
652     }
653
654     ifindex = interface == kDNSServiceInterfaceIndexAny ? AVAHI_IF_UNSPEC : (AvahiIfIndex) interface;
655     
656     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))) {
657         ret = map_error(avahi_client_errno(sdref->client));
658         goto finish;
659     }
660     
661
662     ret = kDNSServiceErr_NoError;
663     *ret_sdref = sdref;
664                                                               
665 finish:
666
667     ASSERT_SUCCESS(pthread_mutex_unlock(&sdref->mutex));
668     
669     if (ret != kDNSServiceErr_NoError)
670         DNSServiceRefDeallocate(sdref);
671
672     return ret;
673 }
674
675 int DNSSD_API DNSServiceConstructFullName (
676     char *fullName,
677     const char *service,   
678     const char *regtype,
679     const char *domain) {
680
681     AVAHI_WARN_LINKAGE;
682
683     assert(fullName);
684     assert(regtype);
685     assert(domain);
686
687     if (avahi_service_name_join(fullName, kDNSServiceMaxDomainName, service, regtype, domain) < 0)
688         return -1;
689     
690     return 0;
691 }
692
693 static void domain_browser_callback(
694     AvahiDomainBrowser *b,
695     AvahiIfIndex interface,
696     AVAHI_GCC_UNUSED AvahiProtocol protocol,
697     AvahiBrowserEvent event,
698     const char *domain,
699     AVAHI_GCC_UNUSED AvahiLookupResultFlags flags,
700     void *userdata) {
701
702     DNSServiceRef sdref = userdata;
703     static char domain_fixed[AVAHI_DOMAIN_NAME_MAX];
704
705     assert(b);
706     assert(sdref);
707     assert(sdref->n_ref >= 1);
708
709     domain  = add_trailing_dot(domain, domain_fixed, sizeof(domain_fixed));
710
711     switch (event) {
712         case AVAHI_BROWSER_NEW:
713             sdref->domain_browser_callback(sdref, kDNSServiceFlagsAdd, interface, kDNSServiceErr_NoError, domain, sdref->context);
714             break;
715
716         case AVAHI_BROWSER_REMOVE:
717             sdref->domain_browser_callback(sdref, 0, interface, kDNSServiceErr_NoError, domain, sdref->context);
718             break;
719
720         case AVAHI_BROWSER_FAILURE:
721             sdref->domain_browser_callback(sdref, 0, interface, map_error(avahi_client_errno(sdref->client)), domain, sdref->context);
722             break;
723             
724         case AVAHI_BROWSER_CACHE_EXHAUSTED:
725         case AVAHI_BROWSER_ALL_FOR_NOW:
726             break;
727     }
728 }
729
730 DNSServiceErrorType DNSSD_API DNSServiceEnumerateDomains(
731     DNSServiceRef *ret_sdref,
732     DNSServiceFlags flags,
733     uint32_t interface,
734     DNSServiceDomainEnumReply callback,
735     void *context) {
736
737     DNSServiceErrorType ret = kDNSServiceErr_Unknown;
738     int error;
739     DNSServiceRef sdref = NULL;
740     AvahiIfIndex ifindex;
741
742     AVAHI_WARN_LINKAGE;
743
744     assert(ret_sdref);
745     assert(callback);
746
747     if (interface == kDNSServiceInterfaceIndexLocalOnly ||
748         (flags != kDNSServiceFlagsBrowseDomains &&  flags != kDNSServiceFlagsRegistrationDomains)) {
749         AVAHI_WARN_UNSUPPORTED;
750         return kDNSServiceErr_Unsupported;
751     }
752
753     if (!(sdref = sdref_new()))
754         return kDNSServiceErr_Unknown;
755
756     sdref->context = context;
757     sdref->domain_browser_callback = callback;
758
759     ASSERT_SUCCESS(pthread_mutex_lock(&sdref->mutex));
760     
761     if (!(sdref->client = avahi_client_new(avahi_simple_poll_get(sdref->simple_poll), generic_client_callback, sdref, &error))) {
762         ret =  map_error(error);
763         goto finish;
764     }
765
766     ifindex = interface == kDNSServiceInterfaceIndexAny ? AVAHI_IF_UNSPEC : (AvahiIfIndex) interface;
767     
768     if (!(sdref->domain_browser = avahi_domain_browser_new(sdref->client, ifindex, AVAHI_PROTO_UNSPEC, "local",
769                                                            flags == kDNSServiceFlagsRegistrationDomains ? AVAHI_DOMAIN_BROWSER_REGISTER : AVAHI_DOMAIN_BROWSER_BROWSE,
770                                                            0, domain_browser_callback, sdref))) {
771         ret = map_error(avahi_client_errno(sdref->client));
772         goto finish;
773     }
774     
775     ret = kDNSServiceErr_NoError;
776     *ret_sdref = sdref;
777                                                               
778 finish:
779
780     ASSERT_SUCCESS(pthread_mutex_unlock(&sdref->mutex));
781     
782     if (ret != kDNSServiceErr_NoError)
783         DNSServiceRefDeallocate(sdref);
784
785     return ret;
786 }
787
788 static void reg_report_error(DNSServiceRef sdref, DNSServiceErrorType error) {
789     char regtype_fixed[AVAHI_DOMAIN_NAME_MAX], domain_fixed[AVAHI_DOMAIN_NAME_MAX];
790     const char *regtype, *domain;
791     assert(sdref);
792     assert(sdref->n_ref >= 1);
793
794     assert(sdref->service_register_callback);
795
796     regtype = add_trailing_dot(sdref->service_regtype, regtype_fixed, sizeof(regtype_fixed));
797     domain = add_trailing_dot(sdref->service_domain, domain_fixed, sizeof(domain_fixed));
798     
799     sdref->service_register_callback(
800         sdref, 0, error,
801         sdref->service_name_chosen ? sdref->service_name_chosen : sdref->service_name,
802         regtype,
803         domain,
804         sdref->context);
805 }
806
807 static int reg_create_service(DNSServiceRef sdref) {
808     int ret;
809     const char *real_type;
810     
811     assert(sdref);
812     assert(sdref->n_ref >= 1);
813
814     real_type = avahi_get_type_from_subtype(sdref->service_regtype);
815     
816     if ((ret = avahi_entry_group_add_service_strlst(
817         sdref->entry_group,
818         sdref->service_interface,
819         AVAHI_PROTO_UNSPEC,
820         0,
821         sdref->service_name_chosen,
822         real_type ? real_type : sdref->service_regtype,
823         sdref->service_domain,
824         sdref->service_host,
825         sdref->service_port,
826         sdref->service_txt)) < 0)
827         return ret;
828
829     
830     if (real_type) {
831         /* Create a subtype entry */
832
833         if (avahi_entry_group_add_service_subtype(
834                 sdref->entry_group,
835                 sdref->service_interface,
836                 AVAHI_PROTO_UNSPEC,
837                 0,
838                 sdref->service_name_chosen,
839                 real_type,
840                 sdref->service_domain,
841                 sdref->service_regtype) < 0)
842             return ret;
843
844     }
845
846     if ((ret = avahi_entry_group_commit(sdref->entry_group)) < 0)
847         return ret;
848
849     return 0;
850 }
851
852 static void reg_client_callback(AvahiClient *s, AvahiClientState state, void* userdata) {
853     DNSServiceRef sdref = userdata;
854
855     assert(s);
856     assert(sdref);
857     assert(sdref->n_ref >= 1);
858
859     /* We've not been setup completely */
860     if (!sdref->entry_group)
861         return;
862     
863     switch (state) {
864         case AVAHI_CLIENT_FAILURE:
865         case AVAHI_CLIENT_DISCONNECTED:
866             reg_report_error(sdref, kDNSServiceErr_Unknown);
867             break;
868
869         case AVAHI_CLIENT_S_RUNNING: {
870             int ret;
871
872             if (!sdref->service_name) {
873                 const char *n;
874                 /* If the service name is taken from the host name, copy that */
875
876                 avahi_free(sdref->service_name_chosen);
877                 sdref->service_name_chosen = NULL;
878
879                 if (!(n = avahi_client_get_host_name(sdref->client))) {
880                     reg_report_error(sdref, map_error(avahi_client_errno(sdref->client)));
881                     return;
882                 }
883
884                 if (!(sdref->service_name_chosen = avahi_strdup(n))) {
885                     reg_report_error(sdref, kDNSServiceErr_NoMemory);
886                     return;
887                 }
888             }
889             
890             /* Register the service */
891
892             if ((ret = reg_create_service(sdref)) < 0) {
893                 reg_report_error(sdref, map_error(ret));
894                 return;
895             }
896             
897             break;
898         }
899             
900         case AVAHI_CLIENT_S_COLLISION:
901
902             /* Remove our entry */
903             avahi_entry_group_reset(sdref->entry_group);
904             
905             break;
906
907         case AVAHI_CLIENT_S_REGISTERING:
908             /* Ignore */
909             break;
910     }
911
912 }
913
914 static void reg_entry_group_callback(AvahiEntryGroup *g, AvahiEntryGroupState state, void *userdata) {
915     DNSServiceRef sdref = userdata;
916
917     assert(g);
918
919     switch (state) {
920         case AVAHI_ENTRY_GROUP_ESTABLISHED:
921             /* Inform the user */
922             reg_report_error(sdref, kDNSServiceErr_NoError);
923
924             break;
925
926         case AVAHI_ENTRY_GROUP_COLLISION: {
927             char *n;
928             int ret;
929             
930             /* Remove our entry */
931             avahi_entry_group_reset(sdref->entry_group);
932
933             assert(sdref->service_name_chosen);
934
935             /* Pick a new name */
936             if (!(n = avahi_alternative_service_name(sdref->service_name_chosen))) {
937                 reg_report_error(sdref, kDNSServiceErr_NoMemory);
938                 return;
939             }
940             avahi_free(sdref->service_name_chosen);
941             sdref->service_name_chosen = n;
942
943             /* Register the service with that new name */
944             if ((ret = reg_create_service(sdref)) < 0) {
945                 reg_report_error(sdref, map_error(ret));
946                 return;
947             }
948             
949             break;
950         }
951
952         case AVAHI_ENTRY_GROUP_REGISTERING:
953         case AVAHI_ENTRY_GROUP_UNCOMMITED:
954             /* Ignore */
955             break;
956
957         case AVAHI_ENTRY_GROUP_FAILURE:
958             /* Inform the user */
959             reg_report_error(sdref, map_error(avahi_client_errno(sdref->client)));
960             break;
961             
962     }
963 }
964
965 DNSServiceErrorType DNSSD_API DNSServiceRegister (
966     DNSServiceRef *ret_sdref,
967     DNSServiceFlags flags,
968     uint32_t interface,
969     const char *name,        
970     const char *regtype,
971     const char *domain,      
972     const char *host,        
973     uint16_t port,
974     uint16_t txtLen,
975     const void *txtRecord,   
976     DNSServiceRegisterReply callback,    
977     void *context) {
978
979     DNSServiceErrorType ret = kDNSServiceErr_Unknown;
980     int error;
981     DNSServiceRef sdref = NULL;
982     AvahiStringList *txt = NULL;
983
984     AVAHI_WARN_LINKAGE;
985
986     assert(ret_sdref);
987     assert(callback);
988     assert(regtype);
989
990     if (interface == kDNSServiceInterfaceIndexLocalOnly || flags) {
991         AVAHI_WARN_UNSUPPORTED;
992         return kDNSServiceErr_Unsupported;
993     }
994
995     if (txtRecord && txtLen > 0) 
996         if (avahi_string_list_parse(txtRecord, txtLen, &txt) < 0)
997             return kDNSServiceErr_Invalid;
998     
999     if (!(sdref = sdref_new())) {
1000         avahi_string_list_free(txt);
1001         return kDNSServiceErr_Unknown;
1002     }
1003
1004     sdref->context = context;
1005     sdref->service_register_callback = callback;
1006
1007     sdref->service_name = avahi_strdup(name);
1008     sdref->service_regtype = regtype ? avahi_normalize_name_strdup(regtype) : NULL;
1009     sdref->service_domain = domain ? avahi_normalize_name_strdup(domain) : NULL;
1010     sdref->service_host = host ? avahi_normalize_name_strdup(host) : NULL;
1011     sdref->service_interface = interface == kDNSServiceInterfaceIndexAny ? AVAHI_IF_UNSPEC : (AvahiIfIndex) interface;
1012     sdref->service_port = ntohs(port);
1013     sdref->service_txt = txt;
1014
1015     /* Some OOM checking would be cool here */
1016     
1017     ASSERT_SUCCESS(pthread_mutex_lock(&sdref->mutex));
1018     
1019     if (!(sdref->client = avahi_client_new(avahi_simple_poll_get(sdref->simple_poll), reg_client_callback, sdref, &error))) {
1020         ret =  map_error(error);
1021         goto finish;
1022     }
1023
1024     if (!sdref->service_domain) {
1025         const char *d;
1026
1027         if (!(d = avahi_client_get_domain_name(sdref->client))) {
1028             ret = map_error(avahi_client_errno(sdref->client));
1029             goto finish;
1030         }
1031
1032         if (!(sdref->service_domain = avahi_strdup(d))) {
1033             ret = kDNSServiceErr_NoMemory;
1034             goto finish;
1035         }
1036     }
1037
1038     if (!(sdref->entry_group = avahi_entry_group_new(sdref->client, reg_entry_group_callback, sdref))) {
1039         ret = map_error(avahi_client_errno(sdref->client));
1040         goto finish;
1041     }
1042
1043     if (avahi_client_get_state(sdref->client) == AVAHI_CLIENT_S_RUNNING) {
1044         const char *n;
1045
1046         if (sdref->service_name)
1047             n = sdref->service_name;
1048         else {
1049             if (!(n = avahi_client_get_host_name(sdref->client))) {
1050                 ret = map_error(avahi_client_errno(sdref->client));
1051                 goto finish;
1052             }
1053         }
1054
1055         if (!(sdref->service_name_chosen = avahi_strdup(n))) {
1056             ret = kDNSServiceErr_NoMemory;
1057             goto finish;
1058         }
1059
1060             
1061         if ((error = reg_create_service(sdref)) < 0) {
1062             ret = map_error(error);
1063             goto finish;
1064         }
1065     }
1066     
1067     ret = kDNSServiceErr_NoError;
1068     *ret_sdref = sdref;
1069                                                               
1070 finish:
1071
1072     ASSERT_SUCCESS(pthread_mutex_unlock(&sdref->mutex));
1073     
1074     if (ret != kDNSServiceErr_NoError)
1075         DNSServiceRefDeallocate(sdref);
1076
1077     return ret;
1078 }
1079