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