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