Initial revision 6759
[qball-mpd.git] / src / .svn / text-base / zeroconf.c.svn-base
blob539f482c7879f9eb635f8c3ba04e75c25724018c
1 /* the Music Player Daemon (MPD)
2  * Copyright (C) 2003-2007 by Warren Dukes (warren.dukes@gmail.com)
3  * This project's homepage is: http://www.musicpd.org
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17  */
19 #include <stdlib.h>
20 #include <assert.h>
21 #include <string.h>
22 #include <arpa/inet.h>
24 #include "zeroconf.h"
25 #include "conf.h"
26 #include "log.h"
27 #include "listen.h"
28 #include "ioops.h"
29 #include "utils.h"
31 /* The dns-sd service type qualifier to publish */
32 #define SERVICE_TYPE            "_mpd._tcp"
34 /* The default service name to publish 
35  * (overridden by 'zeroconf_name' config parameter)
36  */
37 #define SERVICE_NAME            "Music Player"
39 #define DEFAULT_ZEROCONF_ENABLED 1
41 static int zeroconfEnabled;
43 #ifdef HAVE_ZEROCONF
44 static struct ioOps zeroConfIo = {
46 #endif
48 #ifdef HAVE_BONJOUR
49 #include <dns_sd.h>
51 static DNSServiceRef dnsReference;
52 #endif
54 /* Here is the implementation for Avahi (http://avahi.org) Zeroconf support */
55 #ifdef HAVE_AVAHI
57 #include <avahi-client/client.h>
58 #include <avahi-client/publish.h>
60 #include <avahi-common/alternative.h>
61 #include <avahi-common/domain.h>
62 #include <avahi-common/malloc.h>
63 #include <avahi-common/error.h>
65 /* Static avahi data */
66 static AvahiEntryGroup *avahiGroup;
67 static char *avahiName;
68 static AvahiClient* avahiClient;
69 static AvahiPoll avahiPoll;
70 static int avahiRunning;
72 static int avahiFdset( fd_set* rfds, fd_set* wfds, fd_set* efds );
73 static int avahiFdconsume( int fdCount, fd_set* rfds, fd_set* wfds, fd_set* efds );
75 /* Forward Declaration */
76 static void avahiRegisterService(AvahiClient *c);
78 struct AvahiWatch {
79         struct AvahiWatch* prev;
80         struct AvahiWatch* next;
81         int fd;
82         AvahiWatchEvent requestedEvent;
83         AvahiWatchEvent observedEvent;
84         AvahiWatchCallback callback;
85         void* userdata;
88 struct AvahiTimeout {
89         struct AvahiTimeout* prev;
90         struct AvahiTimeout* next;
91         struct timeval expiry;
92         int enabled;
93         AvahiTimeoutCallback callback;
94         void* userdata;
97 static AvahiWatch* avahiWatchList;
98 static AvahiTimeout* avahiTimeoutList;
100 static AvahiWatch* avahiWatchNew( const AvahiPoll *api, int fd, AvahiWatchEvent event, AvahiWatchCallback callback, void *userdata )
102         struct AvahiWatch* newWatch = xmalloc( sizeof(struct AvahiWatch) );
104         newWatch->fd = fd;
105         newWatch->requestedEvent = event;
106         newWatch->observedEvent = 0;
107         newWatch->callback = callback;
108         newWatch->userdata = userdata;
110         /* Insert at front of list */
111         newWatch->next = avahiWatchList;
112         avahiWatchList = newWatch;
113         newWatch->prev = NULL;
114         if( newWatch->next )
115                 newWatch->next->prev = newWatch;
117         return newWatch;
120 static void avahiWatchUpdate( AvahiWatch *w, AvahiWatchEvent event )
122         assert( w != NULL );
123         w->requestedEvent = event;
126 static AvahiWatchEvent avahiWatchGetEvents( AvahiWatch *w )
128         assert( w != NULL );
129         return w->observedEvent;
132 static void avahiWatchFree( AvahiWatch *w )
134         assert( w != NULL );
136         if( avahiWatchList == w )
137                 avahiWatchList = w->next;
138         else if( w->prev != NULL )
139                 w->prev->next = w->next;
141         free( w );
144 static void avahiCheckExpiry( AvahiTimeout *t )
146         assert( t != NULL );
147         if( t->enabled ) {
148                 struct timeval now;
149                 gettimeofday( &now, NULL );
150                 if( timercmp( &now, &(t->expiry), > ) ) {
151                         t->enabled = 0;
152                         t->callback( t, t->userdata );
153                 }
154         }
157 static void avahiTimeoutUpdate( AvahiTimeout *t, const struct timeval *tv )
159         assert( t != NULL );
160         if( tv ) {
161                 t->enabled = 1;
162                 t->expiry.tv_sec = tv->tv_sec;
163                 t->expiry.tv_usec = tv->tv_usec;
164         } else {
165                 t->enabled = 0;
166         }
169 static void avahiTimeoutFree( AvahiTimeout *t )
171         assert( t != NULL );
173         if( avahiTimeoutList == t )
174                 avahiTimeoutList = t->next;
175         else if( t->prev != NULL )
176                 t->prev->next = t->next;
178         free( t );
181 static AvahiTimeout* avahiTimeoutNew( const AvahiPoll *api, const struct timeval *tv, AvahiTimeoutCallback callback, void *userdata )
183         struct AvahiTimeout* newTimeout = xmalloc( sizeof(struct AvahiTimeout) );
185         newTimeout->callback = callback;
186         newTimeout->userdata = userdata;
188         avahiTimeoutUpdate( newTimeout, tv );
190         /* Insert at front of list */
191         newTimeout->next = avahiTimeoutList;
192         avahiTimeoutList = newTimeout;
193         newTimeout->prev = NULL;
194         if( newTimeout->next )
195                 newTimeout->next->prev = newTimeout;
196         
197         return newTimeout;
200 /* Callback when the EntryGroup changes state */
201 static void avahiGroupCallback(
202                 AvahiEntryGroup *g,
203                 AvahiEntryGroupState state,
204                 void *userdata)
206         assert(g);
208         DEBUG( "Avahi: Service group changed to state %d\n", state );
210         switch (state) {
211                 case AVAHI_ENTRY_GROUP_ESTABLISHED :
212                         /* The entry group has been established successfully */
213                         LOG( "Avahi: Service '%s' successfully established.\n", avahiName );
214                         break;
216                 case AVAHI_ENTRY_GROUP_COLLISION : {
217                         char *n;
218                         
219                         /* A service name collision happened. Let's pick a new name */
220                         n = avahi_alternative_service_name(avahiName);
221                         avahi_free(avahiName);
222                         avahiName = n;
223                         
224                         LOG( "Avahi: Service name collision, renaming service to '%s'\n", avahiName );
226                         /* And recreate the services */
227                         avahiRegisterService(avahi_entry_group_get_client(g));
228                         break;
229                 }
231                 case AVAHI_ENTRY_GROUP_FAILURE :
232                         ERROR( "Avahi: Entry group failure: %s\n",
233                                         avahi_strerror(avahi_client_errno(avahi_entry_group_get_client(g))) );
234                         /* Some kind of failure happened while we were registering our services */
235                         avahiRunning = 0;
236                         break;
238                 case AVAHI_ENTRY_GROUP_UNCOMMITED:
239                         DEBUG( "Avahi: Service group is UNCOMMITED\n" );
240                         break;
241                 case AVAHI_ENTRY_GROUP_REGISTERING:
242                         DEBUG( "Avahi: Service group is REGISTERING\n" );
243                         ;
244         }
247 /* Registers a new service with avahi */
248 static void avahiRegisterService(AvahiClient *c)
250         int ret;
251         assert(c);
252         DEBUG( "Avahi: Registering service %s/%s\n", SERVICE_TYPE, avahiName );
254         /* If this is the first time we're called, let's create a new entry group */
255         if (!avahiGroup) {
256                 avahiGroup = avahi_entry_group_new(c, avahiGroupCallback, NULL);
257                 if( !avahiGroup ) {
258                         ERROR( "Avahi: Failed to create avahi EntryGroup: %s\n", avahi_strerror(avahi_client_errno(c)) );
259                         goto fail;
260                 }
261         }
263         /* Add the service */
264         /* TODO: This currently binds to ALL interfaces.
265          *       We could maybe add a service per actual bound interface, if that's better. */
266         ret = avahi_entry_group_add_service(avahiGroup,
267                                         AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, 0,
268                                         avahiName, SERVICE_TYPE,
269                                         NULL, NULL,
270                                         boundPort,
271                                         NULL);
272         if( ret < 0 ) {
273                 ERROR( "Avahi: Failed to add service %s: %s\n", SERVICE_TYPE, avahi_strerror(ret) );
274                 goto fail;
275         }
277         /* Tell the server to register the service group */
278         ret = avahi_entry_group_commit(avahiGroup);
279         if( ret < 0 ) {
280                 ERROR( "Avahi: Failed to commit service group: %s\n", avahi_strerror(ret) );
281                 goto fail;
282         }
283         return;
285 fail:
286         avahiRunning = 0;
289 /* Callback when avahi changes state */
290 static void avahiClientCallback(AvahiClient *c, AvahiClientState state, void *userdata)
292         assert(c);
294         /* Called whenever the client or server state changes */
295         DEBUG( "Avahi: Client changed to state %d\n", state );
297         switch (state) {
298                 case AVAHI_CLIENT_S_RUNNING:
299                         DEBUG( "Avahi: Client is RUNNING\n" );
300                 
301                         /* The server has startup successfully and registered its host
302                          * name on the network, so it's time to create our services */
303                         if (!avahiGroup)
304                                 avahiRegisterService(c);
305                         break;
307                 case AVAHI_CLIENT_FAILURE:
308                         {
309                                 int reason = avahi_client_errno(c);
310                                 if( reason == AVAHI_ERR_DISCONNECTED ) {
311                                         LOG( "Avahi: Client Disconnected, will reconnect shortly\n");
312                                         avahi_entry_group_free( avahiGroup );
313                                         avahiGroup = NULL;
314                                         avahi_client_free( avahiClient );
315                                         avahiClient = NULL;
316                                         avahiClient = avahi_client_new( &avahiPoll, AVAHI_CLIENT_NO_FAIL,
317                                                 avahiClientCallback, NULL, &reason );
318                                         if( !avahiClient ) {
319                                                 ERROR( "Avahi: Could not reconnect: %s\n", avahi_strerror(reason) );
320                                                 avahiRunning = 0;
321                                         }
322                                 } else {
323                                         ERROR( "Avahi: Client failure: %s (terminal)\n", avahi_strerror(reason));
324                                         avahiRunning = 0;
325                                 }
326                         }
327                         break;
329                 case AVAHI_CLIENT_S_COLLISION:
330                         DEBUG( "Avahi: Client is COLLISION\n" );
331                         /* Let's drop our registered services. When the server is back
332                          * in AVAHI_SERVER_RUNNING state we will register them
333                          * again with the new host name. */
334                         if (avahiGroup) {
335                                 DEBUG( "Avahi: Resetting group\n" );
336                                 avahi_entry_group_reset(avahiGroup);
337                         }
338                         
339                 case AVAHI_CLIENT_S_REGISTERING:
340                         DEBUG( "Avahi: Client is REGISTERING\n" );
341                         /* The server records are now being established. This
342                          * might be caused by a host name change. We need to wait
343                          * for our own records to register until the host name is
344                          * properly esatblished. */
345                         
346                         if (avahiGroup) {
347                                 DEBUG( "Avahi: Resetting group\n" );
348                                 avahi_entry_group_reset(avahiGroup);
349                         }
350                         
351                         break;
353                 case AVAHI_CLIENT_CONNECTING:
354                         DEBUG( "Avahi: Client is CONNECTING\n" );
355                         ;
356         }
359 static int avahiFdset( fd_set* rfds, fd_set* wfds, fd_set* efds )
361         AvahiWatch* w;
362         int maxfd = -1;
363         if( !avahiRunning )
364                 return maxfd;
365         for( w = avahiWatchList; w != NULL; w = w->next ) {
366                 if( w->requestedEvent & AVAHI_WATCH_IN ) {
367                         FD_SET( w->fd, rfds );
368                 } 
369                 if( w->requestedEvent & AVAHI_WATCH_OUT ) {
370                         FD_SET( w->fd, wfds );
371                 }
372                 if( w->requestedEvent & AVAHI_WATCH_ERR ) {
373                         FD_SET( w->fd, efds );
374                 }
375                 if( w->requestedEvent & AVAHI_WATCH_HUP ) {
376                         ERROR( "Avahi: No support for HUP events! (ignoring)\n" );
377                 }
379                 if( w->fd > maxfd )
380                         maxfd = w->fd;
381         }
382         return maxfd; 
385 static int avahiFdconsume( int fdCount, fd_set* rfds, fd_set* wfds, fd_set* efds )
387         int retval = fdCount;
388         AvahiTimeout* t;
389         AvahiWatch* w = avahiWatchList;
391         while( w != NULL && retval > 0 ) {
392                 AvahiWatch* current = w;
393                 current->observedEvent = 0;
394                 if( FD_ISSET( current->fd, rfds ) ) {
395                         current->observedEvent |= AVAHI_WATCH_IN;
396                         FD_CLR( current->fd, rfds );
397                         retval--;
398                 }
399                 if( FD_ISSET( current->fd, wfds ) ) {
400                         current->observedEvent |= AVAHI_WATCH_OUT;
401                         FD_CLR( current->fd, wfds );
402                         retval--;
403                 }
404                 if( FD_ISSET( current->fd, efds ) ) {
405                         current->observedEvent |= AVAHI_WATCH_ERR;
406                         FD_CLR( current->fd, efds );
407                         retval--;
408                 }
410                 /* Advance to the next one right now, in case the callback
411                  * removes itself
412                  */
413                 w = w->next;
415                 if( current->observedEvent && avahiRunning ) {
416                         current->callback( current, current->fd,
417                                         current->observedEvent, current->userdata );
418                 }
419         }
421         t = avahiTimeoutList;
422         while( t != NULL && avahiRunning ) {
423                 AvahiTimeout* current = t;
425                 /* Advance to the next one right now, in case the callback
426                  * removes itself
427                  */
428                 t = t->next;
429                 avahiCheckExpiry( current );
430         }
432         return retval;
435 static void init_avahi(const char *serviceName)
437         int error;
438         DEBUG( "Avahi: Initializing interface\n" );
440         if( avahi_is_valid_service_name( serviceName ) ) {
441                 avahiName = avahi_strdup( serviceName );
442         } else {
443                 ERROR( "Invalid zeroconf_name \"%s\", defaulting to \"%s\" instead.\n", serviceName, SERVICE_NAME );
444                 avahiName = avahi_strdup( SERVICE_NAME );
445         }
447         avahiRunning = 1;
449         avahiPoll.userdata = NULL;
450         avahiPoll.watch_new = avahiWatchNew;
451         avahiPoll.watch_update = avahiWatchUpdate;
452         avahiPoll.watch_get_events = avahiWatchGetEvents;
453         avahiPoll.watch_free = avahiWatchFree;
454         avahiPoll.timeout_new = avahiTimeoutNew;
455         avahiPoll.timeout_update = avahiTimeoutUpdate;
456         avahiPoll.timeout_free = avahiTimeoutFree;
458         avahiClient = avahi_client_new( &avahiPoll, AVAHI_CLIENT_NO_FAIL,
459                         avahiClientCallback, NULL, &error );
461         if( !avahiClient ) {
462                 ERROR( "Avahi: Failed to create client: %s\n", avahi_strerror(error) );
463                 goto fail;
464         }
466         zeroConfIo.fdset = avahiFdset;
467         zeroConfIo.consume = avahiFdconsume;
468         registerIO( &zeroConfIo );
470         return;
472 fail:
473         finishZeroconf();
475 #endif /* HAVE_AVAHI */
477 #ifdef HAVE_BONJOUR
478 static int dnsRegisterFdset(fd_set* rfds, fd_set* wfds, fd_set* efds)
480         int fd;
482         if (dnsReference == NULL)
483                 return -1;
485         fd = DNSServiceRefSockFD(dnsReference);
486         if (fd == -1)
487                 return -1;
489         FD_SET(fd, rfds);
491         return fd;
494 static int dnsRegisterFdconsume(int fdCount, fd_set* rfds, fd_set* wfds,
495                                 fd_set* efds)
497         int fd;
499         if (dnsReference == NULL)
500                 return -1;
502         fd = DNSServiceRefSockFD(dnsReference);
503         if (fd == -1)
504                 return -1;
506         if (FD_ISSET(fd, rfds)) {
507                 FD_CLR(fd, rfds);
509                 DNSServiceProcessResult(dnsReference);
511                 return fdCount - 1;
512         }
514         return fdCount;
517 static void dnsRegisterCallback (DNSServiceRef sdRef, DNSServiceFlags flags,
518                                     DNSServiceErrorType errorCode, const char *name,
519                                         const char *regtype, const char *domain, void *context)
521         if (errorCode != kDNSServiceErr_NoError) {
522                 ERROR("Failed to register zeroconf service.\n");
524                 DNSServiceRefDeallocate(dnsReference);
525                 dnsReference = NULL;
526                 deregisterIO( &zeroConfIo );
527         } else {
528                 DEBUG("Registered zeroconf service with name '%s'\n", name);
529         }
532 static void init_zeroconf_osx(const char *serviceName)
534         DNSServiceErrorType error = DNSServiceRegister(&dnsReference,
535                         0, 0, serviceName, SERVICE_TYPE, NULL, NULL, htons(boundPort), 0,
536                         NULL, dnsRegisterCallback, NULL);
538         if (error != kDNSServiceErr_NoError) {
539                 ERROR("Failed to register zeroconf service.\n");
541                 if (dnsReference) {
542                         DNSServiceRefDeallocate(dnsReference);
543                         dnsReference = NULL;
544                 }
545                 return;
546         }
548         zeroConfIo.fdset = dnsRegisterFdset;
549         zeroConfIo.consume = dnsRegisterFdconsume;
550         registerIO( &zeroConfIo );
552 #endif
554 void initZeroconf(void)
556         const char *serviceName = SERVICE_NAME;
557         ConfigParam *param;
559         zeroconfEnabled = getBoolConfigParam(CONF_ZEROCONF_ENABLED);
560         if (zeroconfEnabled == -1)
561                 zeroconfEnabled = DEFAULT_ZEROCONF_ENABLED;
562         else if (zeroconfEnabled < 0)
563                 exit(EXIT_FAILURE);
565         if (!zeroconfEnabled)
566                 return;
568         param = getConfigParam(CONF_ZEROCONF_NAME);
570         if (param && strlen(param->value) > 0)
571                 serviceName = param->value;
573 #ifdef HAVE_AVAHI
574         init_avahi(serviceName);
575 #endif
577 #ifdef HAVE_BONJOUR
578         init_zeroconf_osx(serviceName);
579 #endif
582 void finishZeroconf(void)
584         if (!zeroconfEnabled)
585                 return;
587 #ifdef HAVE_AVAHI
588         DEBUG( "Avahi: Shutting down interface\n" );
589         deregisterIO( &zeroConfIo );
591         if( avahiGroup ) {
592                 avahi_entry_group_free( avahiGroup );
593                 avahiGroup = NULL;
594         }
596         if( avahiClient ) {
597                 avahi_client_free( avahiClient );
598                 avahiClient = NULL;
599         }
601         avahi_free( avahiName );
602         avahiName = NULL;
603 #endif /* HAVE_AVAHI */
605 #ifdef HAVE_BONJOUR
606         deregisterIO( &zeroConfIo );
607         if (dnsReference != NULL) {
608                 DNSServiceRefDeallocate(dnsReference);
609                 dnsReference = NULL;
610                 DEBUG("Deregistered Zeroconf service.\n");
611         }
612 #endif