2006-10-19 Havoc Pennington <hp@redhat.com>
[platform/upstream/dbus.git] / dbus / dbus-server.c
1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-server.c DBusServer object
3  *
4  * Copyright (C) 2002, 2003, 2004, 2005 Red Hat Inc.
5  *
6  * Licensed under the Academic Free License version 2.1
7  * 
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  * 
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  *
22  */ 
23
24 #include "dbus-server.h"
25 #include "dbus-server-unix.h"
26 #include "dbus-server-socket.h"
27 #include "dbus-string.h"
28 #ifdef DBUS_BUILD_TESTS
29 #include "dbus-server-debug-pipe.h"
30 #endif
31 #include "dbus-address.h"
32 #include "dbus-protocol.h"
33
34 /**
35  * @defgroup DBusServer DBusServer
36  * @ingroup  DBus
37  * @brief Server that listens for new connections.
38  *
39  * Types and functions related to DBusServer.
40  * A DBusServer represents a server that other applications
41  * can connect to. Each connection from another application
42  * is represented by a DBusConnection.
43  *
44  * @todo Thread safety hasn't been looked at for #DBusServer
45  * @todo Need notification to apps of disconnection, may matter for some transports
46  */
47
48 /**
49  * @defgroup DBusServerInternals DBusServer implementation details
50  * @ingroup  DBusInternals
51  * @brief Implementation details of DBusServer
52  *
53  * @{
54  */
55
56 /* this is a little fragile since it assumes the address doesn't
57  * already have a guid, but it shouldn't
58  */
59 static char*
60 copy_address_with_guid_appended (const DBusString *address,
61                                  const DBusString *guid_hex)
62 {
63   DBusString with_guid;
64   char *retval;
65   
66   if (!_dbus_string_init (&with_guid))
67     return NULL;
68
69   if (!_dbus_string_copy (address, 0, &with_guid,
70                           _dbus_string_get_length (&with_guid)) ||
71       !_dbus_string_append (&with_guid, ",guid=") ||
72       !_dbus_string_copy (guid_hex, 0,
73                           &with_guid, _dbus_string_get_length (&with_guid)))
74     {
75       _dbus_string_free (&with_guid);
76       return NULL;
77     }
78
79   retval = NULL;
80   _dbus_string_steal_data (&with_guid, &retval);
81
82   _dbus_string_free (&with_guid);
83       
84   return retval; /* may be NULL if steal_data failed */
85 }
86
87 /**
88  * Initializes the members of the DBusServer base class.
89  * Chained up to by subclass constructors.
90  *
91  * @param server the server.
92  * @param vtable the vtable for the subclass.
93  * @param address the server's address
94  * @returns #TRUE on success.
95  */
96 dbus_bool_t
97 _dbus_server_init_base (DBusServer             *server,
98                         const DBusServerVTable *vtable,
99                         const DBusString       *address)
100 {
101   server->vtable = vtable;
102   server->refcount.value = 1;
103
104   server->address = NULL;
105   server->watches = NULL;
106   server->timeouts = NULL;
107
108   if (!_dbus_string_init (&server->guid_hex))
109     return FALSE;
110
111   _dbus_generate_uuid (&server->guid);
112
113   if (!_dbus_uuid_encode (&server->guid, &server->guid_hex))
114     goto failed;
115   
116   server->address = copy_address_with_guid_appended (address,
117                                                      &server->guid_hex);
118   if (server->address == NULL)
119     goto failed;
120   
121   _dbus_mutex_new_at_location (&server->mutex);
122   if (server->mutex == NULL)
123     goto failed;
124   
125   server->watches = _dbus_watch_list_new ();
126   if (server->watches == NULL)
127     goto failed;
128
129   server->timeouts = _dbus_timeout_list_new ();
130   if (server->timeouts == NULL)
131     goto failed;
132
133   _dbus_data_slot_list_init (&server->slot_list);
134
135   _dbus_verbose ("Initialized server on address %s\n", server->address);
136   
137   return TRUE;
138
139  failed:
140   _dbus_mutex_free_at_location (&server->mutex);
141   server->mutex = NULL;
142   if (server->watches)
143     {
144       _dbus_watch_list_free (server->watches);
145       server->watches = NULL;
146     }
147   if (server->timeouts)
148     {
149       _dbus_timeout_list_free (server->timeouts);
150       server->timeouts = NULL;
151     }
152   if (server->address)
153     {
154       dbus_free (server->address);
155       server->address = NULL;
156     }
157   _dbus_string_free (&server->guid_hex);
158   
159   return FALSE;
160 }
161
162 /**
163  * Finalizes the members of the DBusServer base class.
164  * Chained up to by subclass finalizers.
165  *
166  * @param server the server.
167  */
168 void
169 _dbus_server_finalize_base (DBusServer *server)
170 {
171   /* We don't have the lock, but nobody should be accessing
172    * concurrently since they don't have a ref
173    */
174 #ifndef DBUS_DISABLE_CHECKS
175   _dbus_assert (!server->have_server_lock);
176 #endif
177   _dbus_assert (server->disconnected);
178   
179   /* calls out to application code... */
180   _dbus_data_slot_list_free (&server->slot_list);
181
182   dbus_server_set_new_connection_function (server, NULL, NULL, NULL);
183
184   _dbus_watch_list_free (server->watches);
185   _dbus_timeout_list_free (server->timeouts);
186
187   _dbus_mutex_free_at_location (&server->mutex);
188   
189   dbus_free (server->address);
190
191   dbus_free_string_array (server->auth_mechanisms);
192
193   _dbus_string_free (&server->guid_hex);
194 }
195
196
197 /** Function to be called in protected_change_watch() with refcount held */
198 typedef dbus_bool_t (* DBusWatchAddFunction)     (DBusWatchList *list,
199                                                   DBusWatch     *watch);
200 /** Function to be called in protected_change_watch() with refcount held */
201 typedef void        (* DBusWatchRemoveFunction)  (DBusWatchList *list,
202                                                   DBusWatch     *watch);
203 /** Function to be called in protected_change_watch() with refcount held */
204 typedef void        (* DBusWatchToggleFunction)  (DBusWatchList *list,
205                                                   DBusWatch     *watch,
206                                                   dbus_bool_t    enabled);
207
208 static dbus_bool_t
209 protected_change_watch (DBusServer             *server,
210                         DBusWatch              *watch,
211                         DBusWatchAddFunction    add_function,
212                         DBusWatchRemoveFunction remove_function,
213                         DBusWatchToggleFunction toggle_function,
214                         dbus_bool_t             enabled)
215 {
216   DBusWatchList *watches;
217   dbus_bool_t retval;
218   
219   HAVE_LOCK_CHECK (server);
220
221   /* This isn't really safe or reasonable; a better pattern is the "do
222    * everything, then drop lock and call out" one; but it has to be
223    * propagated up through all callers
224    */
225   
226   watches = server->watches;
227   if (watches)
228     {
229       server->watches = NULL;
230       _dbus_server_ref_unlocked (server);
231       SERVER_UNLOCK (server);
232
233       if (add_function)
234         retval = (* add_function) (watches, watch);
235       else if (remove_function)
236         {
237           retval = TRUE;
238           (* remove_function) (watches, watch);
239         }
240       else
241         {
242           retval = TRUE;
243           (* toggle_function) (watches, watch, enabled);
244         }
245       
246       SERVER_LOCK (server);
247       server->watches = watches;
248       _dbus_server_unref_unlocked (server);
249
250       return retval;
251     }
252   else
253     return FALSE;
254 }
255
256 /**
257  * Adds a watch for this server, chaining out to application-provided
258  * watch handlers.
259  *
260  * @param server the server.
261  * @param watch the watch to add.
262  */
263 dbus_bool_t
264 _dbus_server_add_watch (DBusServer *server,
265                         DBusWatch  *watch)
266 {
267   HAVE_LOCK_CHECK (server);
268   return protected_change_watch (server, watch,
269                                  _dbus_watch_list_add_watch,
270                                  NULL, NULL, FALSE);
271 }
272
273 /**
274  * Removes a watch previously added with _dbus_server_remove_watch().
275  *
276  * @param server the server.
277  * @param watch the watch to remove.
278  */
279 void
280 _dbus_server_remove_watch  (DBusServer *server,
281                             DBusWatch  *watch)
282 {
283   HAVE_LOCK_CHECK (server);
284   protected_change_watch (server, watch,
285                           NULL,
286                           _dbus_watch_list_remove_watch,
287                           NULL, FALSE);
288 }
289
290 /**
291  * Toggles a watch and notifies app via server's
292  * DBusWatchToggledFunction if available. It's an error to call this
293  * function on a watch that was not previously added.
294  *
295  * @param server the server.
296  * @param watch the watch to toggle.
297  * @param enabled whether to enable or disable
298  */
299 void
300 _dbus_server_toggle_watch (DBusServer  *server,
301                            DBusWatch   *watch,
302                            dbus_bool_t  enabled)
303 {
304   _dbus_assert (watch != NULL);
305
306   HAVE_LOCK_CHECK (server);
307   protected_change_watch (server, watch,
308                           NULL, NULL,
309                           _dbus_watch_list_toggle_watch,
310                           enabled);
311 }
312
313 /** Function to be called in protected_change_timeout() with refcount held */
314 typedef dbus_bool_t (* DBusTimeoutAddFunction)    (DBusTimeoutList *list,
315                                                    DBusTimeout     *timeout);
316 /** Function to be called in protected_change_timeout() with refcount held */
317 typedef void        (* DBusTimeoutRemoveFunction) (DBusTimeoutList *list,
318                                                    DBusTimeout     *timeout);
319 /** Function to be called in protected_change_timeout() with refcount held */
320 typedef void        (* DBusTimeoutToggleFunction) (DBusTimeoutList *list,
321                                                    DBusTimeout     *timeout,
322                                                    dbus_bool_t      enabled);
323
324
325 static dbus_bool_t
326 protected_change_timeout (DBusServer               *server,
327                           DBusTimeout              *timeout,
328                           DBusTimeoutAddFunction    add_function,
329                           DBusTimeoutRemoveFunction remove_function,
330                           DBusTimeoutToggleFunction toggle_function,
331                           dbus_bool_t               enabled)
332 {
333   DBusTimeoutList *timeouts;
334   dbus_bool_t retval;
335   
336   HAVE_LOCK_CHECK (server);
337
338   /* This isn't really safe or reasonable; a better pattern is the "do everything, then
339    * drop lock and call out" one; but it has to be propagated up through all callers
340    */
341   
342   timeouts = server->timeouts;
343   if (timeouts)
344     {
345       server->timeouts = NULL;
346       _dbus_server_ref_unlocked (server);
347       SERVER_UNLOCK (server);
348
349       if (add_function)
350         retval = (* add_function) (timeouts, timeout);
351       else if (remove_function)
352         {
353           retval = TRUE;
354           (* remove_function) (timeouts, timeout);
355         }
356       else
357         {
358           retval = TRUE;
359           (* toggle_function) (timeouts, timeout, enabled);
360         }
361       
362       SERVER_LOCK (server);
363       server->timeouts = timeouts;
364       _dbus_server_unref_unlocked (server);
365
366       return retval;
367     }
368   else
369     return FALSE;
370 }
371
372 /**
373  * Adds a timeout for this server, chaining out to
374  * application-provided timeout handlers. The timeout should be
375  * repeatedly handled with dbus_timeout_handle() at its given interval
376  * until it is removed.
377  *
378  * @param server the server.
379  * @param timeout the timeout to add.
380  */
381 dbus_bool_t
382 _dbus_server_add_timeout (DBusServer  *server,
383                           DBusTimeout *timeout)
384 {
385   return protected_change_timeout (server, timeout,
386                                    _dbus_timeout_list_add_timeout,
387                                    NULL, NULL, FALSE);
388 }
389
390 /**
391  * Removes a timeout previously added with _dbus_server_add_timeout().
392  *
393  * @param server the server.
394  * @param timeout the timeout to remove.
395  */
396 void
397 _dbus_server_remove_timeout (DBusServer  *server,
398                              DBusTimeout *timeout)
399 {
400   protected_change_timeout (server, timeout,
401                             NULL,
402                             _dbus_timeout_list_remove_timeout,
403                             NULL, FALSE);
404 }
405
406 /**
407  * Toggles a timeout and notifies app via server's
408  * DBusTimeoutToggledFunction if available. It's an error to call this
409  * function on a timeout that was not previously added.
410  *
411  * @param server the server.
412  * @param timeout the timeout to toggle.
413  * @param enabled whether to enable or disable
414  */
415 void
416 _dbus_server_toggle_timeout (DBusServer  *server,
417                              DBusTimeout *timeout,
418                              dbus_bool_t  enabled)
419 {
420   protected_change_timeout (server, timeout,
421                             NULL, NULL,
422                             _dbus_timeout_list_toggle_timeout,
423                             enabled);
424 }
425
426 /** @} */
427
428 /**
429  * @addtogroup DBusServer
430  *
431  * @{
432  */
433
434
435 /**
436  * @typedef DBusServer
437  *
438  * An opaque object representing a server that listens for
439  * connections from other applications. Each time a connection
440  * is made, a new DBusConnection is created and made available
441  * via an application-provided DBusNewConnectionFunction.
442  * The DBusNewConnectionFunction is provided with
443  * dbus_server_set_new_connection_function().
444  * 
445  */
446
447 static const struct {
448   DBusServerListenResult (* func) (DBusAddressEntry *entry,
449                                    DBusServer      **server_p,
450                                    DBusError        *error);
451 } listen_funcs[] = {
452   { _dbus_server_listen_socket },
453   { _dbus_server_listen_platform_specific }
454 #ifdef DBUS_BUILD_TESTS
455   , { _dbus_server_listen_debug_pipe }
456 #endif
457 };
458
459 /**
460  * Listens for new connections on the given address.
461  * If there are multiple address entries in the address,
462  * tries each one and listens on the first one that
463  * works.
464  * 
465  * Returns #NULL and sets error if listening fails for any reason.
466  * Otherwise returns a new #DBusServer.
467  * dbus_server_set_new_connection_function() and
468  * dbus_server_set_watch_functions() should be called
469  * immediately to render the server fully functional.
470  * 
471  * @param address the address of this server.
472  * @param error location to store rationale for failure.
473  * @returns a new DBusServer, or #NULL on failure.
474  * 
475  */
476 DBusServer*
477 dbus_server_listen (const char     *address,
478                     DBusError      *error)
479 {
480   DBusServer *server;
481   DBusAddressEntry **entries;
482   int len, i;
483   DBusError first_connect_error;
484   dbus_bool_t handled_once;
485   
486   _dbus_return_val_if_fail (address != NULL, NULL);
487   _dbus_return_val_if_error_is_set (error, NULL);
488   
489   if (!dbus_parse_address (address, &entries, &len, error))
490     return NULL;
491
492   server = NULL;
493   dbus_error_init (&first_connect_error);
494   handled_once = FALSE;
495   
496   for (i = 0; i < len; i++)
497     {
498       int j;
499
500       for (j = 0; j < (int) _DBUS_N_ELEMENTS (listen_funcs); ++j)
501         {
502           DBusServerListenResult result;
503           DBusError tmp_error;
504       
505           dbus_error_init (&tmp_error);
506           result = (* listen_funcs[j].func) (entries[i],
507                                              &server,
508                                              &tmp_error);
509
510           if (result == DBUS_SERVER_LISTEN_OK)
511             {
512               _dbus_assert (server != NULL);
513               _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
514               handled_once = TRUE;
515               goto out;
516             }
517           else if (result == DBUS_SERVER_LISTEN_BAD_ADDRESS)
518             {
519               _dbus_assert (server == NULL);
520               _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
521               dbus_move_error (&tmp_error, error);
522               handled_once = TRUE;
523               goto out;
524             }
525           else if (result == DBUS_SERVER_LISTEN_NOT_HANDLED)
526             {
527               _dbus_assert (server == NULL);
528               _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
529
530               /* keep trying addresses */
531             }
532           else if (result == DBUS_SERVER_LISTEN_DID_NOT_CONNECT)
533             {
534               _dbus_assert (server == NULL);
535               _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
536               if (!dbus_error_is_set (&first_connect_error))
537                 dbus_move_error (&tmp_error, &first_connect_error);
538               else
539                 dbus_error_free (&tmp_error);
540
541               handled_once = TRUE;
542               
543               /* keep trying addresses */
544             }
545         }
546
547       _dbus_assert (server == NULL);
548       _DBUS_ASSERT_ERROR_IS_CLEAR (error);
549     }
550
551  out:
552
553   if (!handled_once)
554     {
555       _DBUS_ASSERT_ERROR_IS_CLEAR (error);
556       if (len > 0)
557         dbus_set_error (error,
558                        DBUS_ERROR_BAD_ADDRESS,
559                        "Unknown address type '%s'",
560                        dbus_address_entry_get_method (entries[0]));
561       else
562         dbus_set_error (error,
563                         DBUS_ERROR_BAD_ADDRESS,
564                         "Empty address '%s'",
565                         address);
566     }
567   
568   dbus_address_entries_free (entries);
569
570   if (server == NULL)
571     {
572       _dbus_assert (error == NULL || dbus_error_is_set (&first_connect_error) ||
573                    dbus_error_is_set (error));
574       
575       if (error && dbus_error_is_set (error))
576         {
577           /* already set the error */
578         }
579       else
580         {
581           /* didn't set the error but either error should be
582            * NULL or first_connect_error should be set.
583            */
584           _dbus_assert (error == NULL || dbus_error_is_set (&first_connect_error));
585           dbus_move_error (&first_connect_error, error);
586         }
587
588       _DBUS_ASSERT_ERROR_IS_CLEAR (&first_connect_error); /* be sure we freed it */
589       _DBUS_ASSERT_ERROR_IS_SET (error);
590
591       return NULL;
592     }
593   else
594     {
595       _DBUS_ASSERT_ERROR_IS_CLEAR (error);
596       return server;
597     }
598 }
599
600 /**
601  * Increments the reference count of a DBusServer.
602  *
603  * @param server the server.
604  * @returns the server
605  */
606 DBusServer *
607 dbus_server_ref (DBusServer *server)
608 {
609   _dbus_return_val_if_fail (server != NULL, NULL);
610   _dbus_return_val_if_fail (server->refcount.value > 0, NULL);
611
612 #ifdef DBUS_HAVE_ATOMIC_INT
613   _dbus_atomic_inc (&server->refcount);
614 #else
615   SERVER_LOCK (server);
616   _dbus_assert (server->refcount.value > 0);
617
618   server->refcount.value += 1;
619   SERVER_UNLOCK (server);
620 #endif
621
622   return server;
623 }
624
625 /**
626  * Decrements the reference count of a DBusServer.  Finalizes the
627  * server if the reference count reaches zero.
628  *
629  * The server must be disconnected before the refcount reaches zero.
630  *
631  * @param server the server.
632  */
633 void
634 dbus_server_unref (DBusServer *server)
635 {
636   dbus_bool_t last_unref;
637   
638   _dbus_return_if_fail (server != NULL);
639   _dbus_return_if_fail (server->refcount.value > 0);
640
641 #ifdef DBUS_HAVE_ATOMIC_INT
642   last_unref = (_dbus_atomic_dec (&server->refcount) == 1);
643 #else
644   SERVER_LOCK (server);
645   
646   _dbus_assert (server->refcount.value > 0);
647
648   server->refcount.value -= 1;
649   last_unref = (server->refcount.value == 0);
650   
651   SERVER_UNLOCK (server);
652 #endif
653   
654   if (last_unref)
655     {
656       /* lock not held! */
657       _dbus_assert (server->disconnected);
658       
659       _dbus_assert (server->vtable->finalize != NULL);
660       
661       (* server->vtable->finalize) (server);
662     }
663 }
664
665 /**
666  * Like dbus_server_ref() but does not acquire the lock (must already be held)
667  *
668  * @param server the server.
669  */
670 void
671 _dbus_server_ref_unlocked (DBusServer *server)
672 {
673   _dbus_assert (server != NULL);
674   _dbus_assert (server->refcount.value > 0);
675   
676   HAVE_LOCK_CHECK (server);
677
678 #ifdef DBUS_HAVE_ATOMIC_INT
679   _dbus_atomic_inc (&server->refcount);
680 #else
681   _dbus_assert (server->refcount.value > 0);
682
683   server->refcount.value += 1;
684 #endif
685 }
686
687 /**
688  * Like dbus_server_unref() but does not acquire the lock (must already be held)
689  *
690  * @param server the server.
691  */
692 void
693 _dbus_server_unref_unlocked (DBusServer *server)
694 {
695   dbus_bool_t last_unref;
696   
697   _dbus_assert (server != NULL);
698   _dbus_assert (server->refcount.value > 0);
699
700   HAVE_LOCK_CHECK (server);
701   
702 #ifdef DBUS_HAVE_ATOMIC_INT
703   last_unref = (_dbus_atomic_dec (&server->refcount) == 1);
704 #else
705   _dbus_assert (server->refcount.value > 0);
706
707   server->refcount.value -= 1;
708   last_unref = (server->refcount.value == 0);
709 #endif
710   
711   if (last_unref)
712     {
713       _dbus_assert (server->disconnected);
714       
715       SERVER_UNLOCK (server);
716       
717       _dbus_assert (server->vtable->finalize != NULL);
718       
719       (* server->vtable->finalize) (server);
720     }
721 }
722
723 /**
724  * Releases the server's address and stops listening for
725  * new clients. If called more than once, only the first
726  * call has an effect. Does not modify the server's
727  * reference count.
728  * 
729  * @param server the server.
730  */
731 void
732 dbus_server_disconnect (DBusServer *server)
733 {
734   _dbus_return_if_fail (server != NULL);
735   _dbus_return_if_fail (server->refcount.value > 0);
736
737   SERVER_LOCK (server);
738   _dbus_server_ref_unlocked (server);
739   
740   _dbus_assert (server->vtable->disconnect != NULL);
741
742   if (!server->disconnected)
743     {
744       /* this has to be first so recursive calls to disconnect don't happen */
745       server->disconnected = TRUE;
746       
747       (* server->vtable->disconnect) (server);
748     }
749
750   SERVER_UNLOCK (server);
751   dbus_server_unref (server);
752 }
753
754 /**
755  * Returns #TRUE if the server is still listening for new connections.
756  *
757  * @param server the server.
758  */
759 dbus_bool_t
760 dbus_server_get_is_connected (DBusServer *server)
761 {
762   dbus_bool_t retval;
763   
764   _dbus_return_val_if_fail (server != NULL, FALSE);
765
766   SERVER_LOCK (server);
767   retval = !server->disconnected;
768   SERVER_UNLOCK (server);
769
770   return retval;
771 }
772
773 /**
774  * Returns the address of the server, as a newly-allocated
775  * string which must be freed by the caller.
776  *
777  * @param server the server
778  * @returns the address or #NULL if no memory
779  */
780 char*
781 dbus_server_get_address (DBusServer *server)
782 {
783   char *retval;
784   
785   _dbus_return_val_if_fail (server != NULL, NULL);
786
787   SERVER_LOCK (server);
788   retval = _dbus_strdup (server->address);
789   SERVER_UNLOCK (server);
790
791   return retval;
792 }
793
794 /**
795  * Sets a function to be used for handling new connections.  The given
796  * function is passed each new connection as the connection is
797  * created. If the new connection function increments the connection's
798  * reference count, the connection will stay alive. Otherwise, the
799  * connection will be unreferenced and closed. The new connection
800  * function may also close the connection itself, which is considered
801  * good form if the connection is not wanted.
802  *
803  * The connection here is private in the sense of
804  * dbus_connection_open_private(), so if the new connection function
805  * keeps a reference it must arrange for the connection to be closed.
806  * i.e. libdbus does not own this connection once the new connection
807  * function takes a reference.
808  *
809  * @param server the server.
810  * @param function a function to handle new connections.
811  * @param data data to pass to the new connection handler.
812  * @param free_data_function function to free the data.
813  */
814 void
815 dbus_server_set_new_connection_function (DBusServer                *server,
816                                          DBusNewConnectionFunction  function,
817                                          void                      *data,
818                                          DBusFreeFunction           free_data_function)
819 {
820   DBusFreeFunction old_free_function;
821   void *old_data;
822   
823   _dbus_return_if_fail (server != NULL);
824
825   SERVER_LOCK (server);
826   old_free_function = server->new_connection_free_data_function;
827   old_data = server->new_connection_data;
828   
829   server->new_connection_function = function;
830   server->new_connection_data = data;
831   server->new_connection_free_data_function = free_data_function;
832   SERVER_UNLOCK (server);
833     
834   if (old_free_function != NULL)
835     (* old_free_function) (old_data);
836 }
837
838 /**
839  * Sets the watch functions for the connection. These functions are
840  * responsible for making the application's main loop aware of file
841  * descriptors that need to be monitored for events.
842  *
843  * This function behaves exactly like dbus_connection_set_watch_functions();
844  * see the documentation for that routine.
845  *
846  * @param server the server.
847  * @param add_function function to begin monitoring a new descriptor.
848  * @param remove_function function to stop monitoring a descriptor.
849  * @param toggled_function function to notify when the watch is enabled/disabled
850  * @param data data to pass to add_function and remove_function.
851  * @param free_data_function function to be called to free the data.
852  * @returns #FALSE on failure (no memory)
853  */
854 dbus_bool_t
855 dbus_server_set_watch_functions (DBusServer              *server,
856                                  DBusAddWatchFunction     add_function,
857                                  DBusRemoveWatchFunction  remove_function,
858                                  DBusWatchToggledFunction toggled_function,
859                                  void                    *data,
860                                  DBusFreeFunction         free_data_function)
861 {
862   dbus_bool_t result;
863   DBusWatchList *watches;
864   
865   _dbus_return_val_if_fail (server != NULL, FALSE);
866
867   SERVER_LOCK (server);
868   watches = server->watches;
869   server->watches = NULL;
870   if (watches)
871     {
872       SERVER_UNLOCK (server);
873       result = _dbus_watch_list_set_functions (watches,
874                                                add_function,
875                                                remove_function,
876                                                toggled_function,
877                                                data,
878                                                free_data_function);
879       SERVER_LOCK (server);
880     }
881   else
882     {
883       _dbus_warn_check_failed ("Re-entrant call to %s\n", _DBUS_FUNCTION_NAME);
884       result = FALSE;
885     }
886   server->watches = watches;
887   SERVER_UNLOCK (server);
888   
889   return result;
890 }
891
892 /**
893  * Sets the timeout functions for the connection. These functions are
894  * responsible for making the application's main loop aware of timeouts.
895  *
896  * This function behaves exactly like dbus_connection_set_timeout_functions();
897  * see the documentation for that routine.
898  *
899  * @param server the server.
900  * @param add_function function to add a timeout.
901  * @param remove_function function to remove a timeout.
902  * @param toggled_function function to notify when the timeout is enabled/disabled
903  * @param data data to pass to add_function and remove_function.
904  * @param free_data_function function to be called to free the data.
905  * @returns #FALSE on failure (no memory)
906  */
907 dbus_bool_t
908 dbus_server_set_timeout_functions (DBusServer                *server,
909                                    DBusAddTimeoutFunction     add_function,
910                                    DBusRemoveTimeoutFunction  remove_function,
911                                    DBusTimeoutToggledFunction toggled_function,
912                                    void                      *data,
913                                    DBusFreeFunction           free_data_function)
914 {
915   dbus_bool_t result;
916   DBusTimeoutList *timeouts;
917   
918   _dbus_return_val_if_fail (server != NULL, FALSE);
919
920   SERVER_LOCK (server);
921   timeouts = server->timeouts;
922   server->timeouts = NULL;
923   if (timeouts)
924     {
925       SERVER_UNLOCK (server);
926       result = _dbus_timeout_list_set_functions (timeouts,
927                                                  add_function,
928                                                  remove_function,
929                                                  toggled_function,
930                                                  data,
931                                                  free_data_function);
932       SERVER_LOCK (server);
933     }
934   else
935     {
936       _dbus_warn_check_failed ("Re-entrant call to %s\n", _DBUS_FUNCTION_NAME);
937       result = FALSE;
938     }
939   server->timeouts = timeouts;
940   SERVER_UNLOCK (server);
941   
942   return result;
943 }
944
945 /**
946  * Sets the authentication mechanisms that this server offers
947  * to clients, as a list of SASL mechanisms. This function
948  * only affects connections created *after* it is called.
949  * Pass #NULL instead of an array to use all available mechanisms.
950  *
951  * @param server the server
952  * @param mechanisms #NULL-terminated array of mechanisms
953  * @returns #FALSE if no memory
954  */
955 dbus_bool_t
956 dbus_server_set_auth_mechanisms (DBusServer  *server,
957                                  const char **mechanisms)
958 {
959   char **copy;
960
961   _dbus_return_val_if_fail (server != NULL, FALSE);
962
963   SERVER_LOCK (server);
964   
965   if (mechanisms != NULL)
966     {
967       copy = _dbus_dup_string_array (mechanisms);
968       if (copy == NULL)
969         return FALSE;
970     }
971   else
972     copy = NULL;
973
974   dbus_free_string_array (server->auth_mechanisms);
975   server->auth_mechanisms = copy;
976
977   SERVER_UNLOCK (server);
978   
979   return TRUE;
980 }
981
982
983 static DBusDataSlotAllocator slot_allocator;
984 _DBUS_DEFINE_GLOBAL_LOCK (server_slots);
985
986 /**
987  * Allocates an integer ID to be used for storing application-specific
988  * data on any DBusServer. The allocated ID may then be used
989  * with dbus_server_set_data() and dbus_server_get_data().
990  * The slot must be initialized with -1. If a nonnegative
991  * slot is passed in, the refcount is incremented on that
992  * slot, rather than creating a new slot.
993  *  
994  * The allocated slot is global, i.e. all DBusServer objects will have
995  * a slot with the given integer ID reserved.
996  *
997  * @param slot_p address of global variable storing the slot ID
998  * @returns #FALSE on no memory
999  */
1000 dbus_bool_t
1001 dbus_server_allocate_data_slot (dbus_int32_t *slot_p)
1002 {
1003   return _dbus_data_slot_allocator_alloc (&slot_allocator,
1004                                           (DBusMutex **)&_DBUS_LOCK_NAME (server_slots),
1005                                           slot_p);
1006 }
1007
1008 /**
1009  * Deallocates a global ID for server data slots.
1010  * dbus_server_get_data() and dbus_server_set_data()
1011  * may no longer be used with this slot.
1012  * Existing data stored on existing DBusServer objects
1013  * will be freed when the server is finalized,
1014  * but may not be retrieved (and may only be replaced
1015  * if someone else reallocates the slot).
1016  *
1017  * @param slot_p address of the slot to deallocate
1018  */
1019 void
1020 dbus_server_free_data_slot (dbus_int32_t *slot_p)
1021 {
1022   _dbus_return_if_fail (*slot_p >= 0);
1023   
1024   _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
1025 }
1026
1027 /**
1028  * Stores a pointer on a DBusServer, along
1029  * with an optional function to be used for freeing
1030  * the data when the data is set again, or when
1031  * the server is finalized. The slot number
1032  * must have been allocated with dbus_server_allocate_data_slot().
1033  *
1034  * @param server the server
1035  * @param slot the slot number
1036  * @param data the data to store
1037  * @param free_data_func finalizer function for the data
1038  * @returns #TRUE if there was enough memory to store the data
1039  */
1040 dbus_bool_t
1041 dbus_server_set_data (DBusServer       *server,
1042                       int               slot,
1043                       void             *data,
1044                       DBusFreeFunction  free_data_func)
1045 {
1046   DBusFreeFunction old_free_func;
1047   void *old_data;
1048   dbus_bool_t retval;
1049
1050   _dbus_return_val_if_fail (server != NULL, FALSE);
1051
1052   SERVER_LOCK (server);
1053   
1054   retval = _dbus_data_slot_list_set (&slot_allocator,
1055                                      &server->slot_list,
1056                                      slot, data, free_data_func,
1057                                      &old_free_func, &old_data);
1058
1059
1060   SERVER_UNLOCK (server);
1061   
1062   if (retval)
1063     {
1064       /* Do the actual free outside the server lock */
1065       if (old_free_func)
1066         (* old_free_func) (old_data);
1067     }
1068
1069   return retval;
1070 }
1071
1072 /**
1073  * Retrieves data previously set with dbus_server_set_data().
1074  * The slot must still be allocated (must not have been freed).
1075  *
1076  * @param server the server
1077  * @param slot the slot to get data from
1078  * @returns the data, or #NULL if not found
1079  */
1080 void*
1081 dbus_server_get_data (DBusServer   *server,
1082                       int           slot)
1083 {
1084   void *res;
1085
1086   _dbus_return_val_if_fail (server != NULL, NULL);
1087   
1088   SERVER_LOCK (server);
1089   
1090   res = _dbus_data_slot_list_get (&slot_allocator,
1091                                   &server->slot_list,
1092                                   slot);
1093
1094   SERVER_UNLOCK (server);
1095   
1096   return res;
1097 }
1098
1099 /** @} */
1100
1101 #ifdef DBUS_BUILD_TESTS
1102 #include "dbus-test.h"
1103
1104 dbus_bool_t
1105 _dbus_server_test (void)
1106 {
1107   const char *valid_addresses[] = {
1108     "tcp:port=1234",
1109     "unix:path=./boogie",
1110     "tcp:host=localhost,port=1234",
1111     "tcp:host=localhost,port=1234;tcp:port=5678",
1112     "tcp:port=1234;unix:path=./boogie",
1113   };
1114
1115   DBusServer *server;
1116   int i;
1117   
1118   for (i = 0; i < _DBUS_N_ELEMENTS (valid_addresses); i++)
1119     {
1120       DBusError error;
1121
1122       /* FIXME um, how are the two tests here different? */
1123       
1124       dbus_error_init (&error);
1125       server = dbus_server_listen (valid_addresses[i], &error);
1126       if (server == NULL)
1127         {
1128           _dbus_warn ("server listen error: %s: %s\n", error.name, error.message);
1129           dbus_error_free (&error);
1130           _dbus_assert_not_reached ("Failed to listen for valid address.");
1131         }
1132
1133       dbus_server_disconnect (server);
1134       dbus_server_unref (server);
1135
1136       /* Try disconnecting before unreffing */
1137       server = dbus_server_listen (valid_addresses[i], &error);
1138       if (server == NULL)
1139         {
1140           _dbus_warn ("server listen error: %s: %s\n", error.name, error.message);
1141           dbus_error_free (&error);          
1142           _dbus_assert_not_reached ("Failed to listen for valid address.");
1143         }
1144
1145       dbus_server_disconnect (server);
1146       dbus_server_unref (server);
1147     }
1148
1149   return TRUE;
1150 }
1151
1152 #endif /* DBUS_BUILD_TESTS */