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