2006-09-16 Havoc Pennington <hp@redhat.com>
[platform/upstream/dbus.git] / dbus / dbus-server.c
1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-server.c DBusServer object
3  *
4  * Copyright (C) 2002, 2003, 2004, 2005 Red Hat Inc.
5  *
6  * Licensed under the Academic Free License version 2.1
7  * 
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  * 
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  *
22  */ 
23
24 #include "dbus-server.h"
25 #include "dbus-server-unix.h"
26 #include "dbus-server-socket.h"
27 #include "dbus-string.h"
28 #ifdef DBUS_BUILD_TESTS
29 #include "dbus-server-debug-pipe.h"
30 #endif
31 #include "dbus-address.h"
32 #include "dbus-protocol.h"
33
34 /**
35  * @defgroup DBusServer DBusServer
36  * @ingroup  DBus
37  * @brief Server that listens for new connections.
38  *
39  * Types and functions related to DBusServer.
40  * A DBusServer represents a server that other applications
41  * can connect to. Each connection from another application
42  * is represented by a DBusConnection.
43  *
44  * @todo Thread safety hasn't been looked at for #DBusServer
45  * @todo Need notification to apps of disconnection, may matter for some transports
46  */
47
48 /**
49  * @defgroup DBusServerInternals DBusServer implementation details
50  * @ingroup  DBusInternals
51  * @brief Implementation details of DBusServer
52  *
53  * @{
54  */
55
56 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 /** @} */
446
447 /**
448  * @addtogroup DBusServer
449  *
450  * @{
451  */
452
453
454 /**
455  * @typedef DBusServer
456  *
457  * An opaque object representing a server that listens for
458  * connections from other applications. Each time a connection
459  * is made, a new DBusConnection is created and made available
460  * via an application-provided DBusNewConnectionFunction.
461  * The DBusNewConnectionFunction is provided with
462  * dbus_server_set_new_connection_function().
463  * 
464  */
465
466 static const struct {
467   DBusServerListenResult (* func) (DBusAddressEntry *entry,
468                                    DBusServer      **server_p,
469                                    DBusError        *error);
470 } listen_funcs[] = {
471   { _dbus_server_listen_socket },
472   { _dbus_server_listen_platform_specific }
473 #ifdef DBUS_BUILD_TESTS
474   , { _dbus_server_listen_debug_pipe }
475 #endif
476 };
477
478 /**
479  * Listens for new connections on the given address.
480  * If there are multiple address entries in the address,
481  * tries each one and listens on the first one that
482  * works.
483  * 
484  * Returns #NULL and sets error if listening fails for any reason.
485  * Otherwise returns a new #DBusServer.
486  * dbus_server_set_new_connection_function() and
487  * dbus_server_set_watch_functions() should be called
488  * immediately to render the server fully functional.
489  * 
490  * @param address the address of this server.
491  * @param error location to store rationale for failure.
492  * @returns a new DBusServer, or #NULL on failure.
493  * 
494  */
495 DBusServer*
496 dbus_server_listen (const char     *address,
497                     DBusError      *error)
498 {
499   DBusServer *server;
500   DBusAddressEntry **entries;
501   int len, i;
502   DBusError first_connect_error;
503   dbus_bool_t handled_once;
504   
505   _dbus_return_val_if_fail (address != NULL, NULL);
506   _dbus_return_val_if_error_is_set (error, NULL);
507   
508   if (!dbus_parse_address (address, &entries, &len, error))
509     return NULL;
510
511   server = NULL;
512   dbus_error_init (&first_connect_error);
513   handled_once = FALSE;
514   
515   for (i = 0; i < len; i++)
516     {
517       int j;
518
519       for (j = 0; j < (int) _DBUS_N_ELEMENTS (listen_funcs); ++j)
520         {
521           DBusServerListenResult result;
522           DBusError tmp_error;
523       
524           dbus_error_init (&tmp_error);
525           result = (* listen_funcs[j].func) (entries[i],
526                                              &server,
527                                              &tmp_error);
528
529           if (result == DBUS_SERVER_LISTEN_OK)
530             {
531               _dbus_assert (server != NULL);
532               _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
533               handled_once = TRUE;
534               goto out;
535             }
536           else if (result == DBUS_SERVER_LISTEN_BAD_ADDRESS)
537             {
538               _dbus_assert (server == NULL);
539               _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
540               dbus_move_error (&tmp_error, error);
541               handled_once = TRUE;
542               goto out;
543             }
544           else if (result == DBUS_SERVER_LISTEN_NOT_HANDLED)
545             {
546               _dbus_assert (server == NULL);
547               _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
548
549               /* keep trying addresses */
550             }
551           else if (result == DBUS_SERVER_LISTEN_DID_NOT_CONNECT)
552             {
553               _dbus_assert (server == NULL);
554               _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
555               if (!dbus_error_is_set (&first_connect_error))
556                 dbus_move_error (&tmp_error, &first_connect_error);
557               else
558                 dbus_error_free (&tmp_error);
559
560               handled_once = TRUE;
561               
562               /* keep trying addresses */
563             }
564         }
565
566       _dbus_assert (server == NULL);
567       _DBUS_ASSERT_ERROR_IS_CLEAR (error);
568     }
569
570  out:
571
572   if (!handled_once)
573     {
574       _DBUS_ASSERT_ERROR_IS_CLEAR (error);
575       if (len > 0)
576         dbus_set_error (error,
577                        DBUS_ERROR_BAD_ADDRESS,
578                        "Unknown address type '%s'",
579                        dbus_address_entry_get_method (entries[0]));
580       else
581         dbus_set_error (error,
582                         DBUS_ERROR_BAD_ADDRESS,
583                         "Empty address '%s'",
584                         address);
585     }
586   
587   dbus_address_entries_free (entries);
588
589   if (server == NULL)
590     {
591       _dbus_assert (error == NULL || dbus_error_is_set (&first_connect_error) ||
592                    dbus_error_is_set (error));
593       
594       if (error && dbus_error_is_set (error))
595         {
596           /* already set the error */
597         }
598       else
599         {
600           /* didn't set the error but either error should be
601            * NULL or first_connect_error should be set.
602            */
603           _dbus_assert (error == NULL || dbus_error_is_set (&first_connect_error));
604           dbus_move_error (&first_connect_error, error);
605         }
606
607       _DBUS_ASSERT_ERROR_IS_CLEAR (&first_connect_error); /* be sure we freed it */
608       _DBUS_ASSERT_ERROR_IS_SET (error);
609
610       return NULL;
611     }
612   else
613     {
614       _DBUS_ASSERT_ERROR_IS_CLEAR (error);
615       return server;
616     }
617 }
618
619 /**
620  * Increments the reference count of a DBusServer.
621  *
622  * @param server the server.
623  * @returns the server
624  */
625 DBusServer *
626 dbus_server_ref (DBusServer *server)
627 {
628   _dbus_return_val_if_fail (server != NULL, NULL);
629   _dbus_return_val_if_fail (server->refcount.value > 0, NULL);
630
631 #ifdef DBUS_HAVE_ATOMIC_INT
632   _dbus_atomic_inc (&server->refcount);
633 #else
634   SERVER_LOCK (server);
635   _dbus_assert (server->refcount.value > 0);
636
637   server->refcount.value += 1;
638   SERVER_UNLOCK (server);
639 #endif
640
641   return server;
642 }
643
644 /**
645  * Decrements the reference count of a DBusServer.  Finalizes the
646  * server if the reference count reaches zero.
647  *
648  * The server must be disconnected before the refcount reaches zero.
649  *
650  * @param server the server.
651  */
652 void
653 dbus_server_unref (DBusServer *server)
654 {
655   dbus_bool_t last_unref;
656   
657   _dbus_return_if_fail (server != NULL);
658   _dbus_return_if_fail (server->refcount.value > 0);
659
660 #ifdef DBUS_HAVE_ATOMIC_INT
661   last_unref = (_dbus_atomic_dec (&server->refcount) == 1);
662 #else
663   SERVER_LOCK (server);
664   
665   _dbus_assert (server->refcount.value > 0);
666
667   server->refcount.value -= 1;
668   last_unref = (server->refcount.value == 0);
669   
670   SERVER_UNLOCK (server);
671 #endif
672   
673   if (last_unref)
674     {
675       /* lock not held! */
676       _dbus_assert (server->disconnected);
677       
678       _dbus_assert (server->vtable->finalize != NULL);
679       
680       (* server->vtable->finalize) (server);
681     }
682 }
683
684 /**
685  * Like dbus_server_ref() but does not acquire the lock (must already be held)
686  *
687  * @param server the server.
688  */
689 void
690 _dbus_server_ref_unlocked (DBusServer *server)
691 {
692   _dbus_assert (server != NULL);
693   _dbus_assert (server->refcount.value > 0);
694   
695   HAVE_LOCK_CHECK (server);
696
697 #ifdef DBUS_HAVE_ATOMIC_INT
698   _dbus_atomic_inc (&server->refcount);
699 #else
700   _dbus_assert (server->refcount.value > 0);
701
702   server->refcount.value += 1;
703 #endif
704 }
705
706 /**
707  * Like dbus_server_unref() but does not acquire the lock (must already be held)
708  *
709  * @param server the server.
710  */
711 void
712 _dbus_server_unref_unlocked (DBusServer *server)
713 {
714   dbus_bool_t last_unref;
715   
716   _dbus_assert (server != NULL);
717   _dbus_assert (server->refcount.value > 0);
718
719   HAVE_LOCK_CHECK (server);
720   
721 #ifdef DBUS_HAVE_ATOMIC_INT
722   last_unref = (_dbus_atomic_dec (&server->refcount) == 1);
723 #else
724   _dbus_assert (server->refcount.value > 0);
725
726   server->refcount.value -= 1;
727   last_unref = (server->refcount.value == 0);
728 #endif
729   
730   if (last_unref)
731     {
732       _dbus_assert (server->disconnected);
733       
734       SERVER_UNLOCK (server);
735       
736       _dbus_assert (server->vtable->finalize != NULL);
737       
738       (* server->vtable->finalize) (server);
739     }
740 }
741
742 /**
743  * Releases the server's address and stops listening for
744  * new clients. If called more than once, only the first
745  * call has an effect. Does not modify the server's
746  * reference count.
747  * 
748  * @param server the server.
749  */
750 void
751 dbus_server_disconnect (DBusServer *server)
752 {
753   _dbus_return_if_fail (server != NULL);
754   _dbus_return_if_fail (server->refcount.value > 0);
755
756   SERVER_LOCK (server);
757   _dbus_server_ref_unlocked (server);
758   
759   _dbus_assert (server->vtable->disconnect != NULL);
760
761   if (!server->disconnected)
762     {
763       /* this has to be first so recursive calls to disconnect don't happen */
764       server->disconnected = TRUE;
765       
766       (* server->vtable->disconnect) (server);
767     }
768
769   SERVER_UNLOCK (server);
770   dbus_server_unref (server);
771 }
772
773 /**
774  * Returns #TRUE if the server is still listening for new connections.
775  *
776  * @param server the server.
777  */
778 dbus_bool_t
779 dbus_server_get_is_connected (DBusServer *server)
780 {
781   dbus_bool_t retval;
782   
783   _dbus_return_val_if_fail (server != NULL, FALSE);
784
785   SERVER_LOCK (server);
786   retval = !server->disconnected;
787   SERVER_UNLOCK (server);
788
789   return retval;
790 }
791
792 /**
793  * Returns the address of the server, as a newly-allocated
794  * string which must be freed by the caller.
795  *
796  * @param server the server
797  * @returns the address or #NULL if no memory
798  */
799 char*
800 dbus_server_get_address (DBusServer *server)
801 {
802   char *retval;
803   
804   _dbus_return_val_if_fail (server != NULL, NULL);
805
806   SERVER_LOCK (server);
807   retval = _dbus_strdup (server->address);
808   SERVER_UNLOCK (server);
809
810   return retval;
811 }
812
813 /**
814  * Sets a function to be used for handling new connections.  The given
815  * function is passed each new connection as the connection is
816  * created. If the new connection function increments the connection's
817  * reference count, the connection will stay alive. Otherwise, the
818  * connection will be unreferenced and closed.
819  *
820  * @param server the server.
821  * @param function a function to handle new connections.
822  * @param data data to pass to the new connection handler.
823  * @param free_data_function function to free the data.
824  */
825 void
826 dbus_server_set_new_connection_function (DBusServer                *server,
827                                          DBusNewConnectionFunction  function,
828                                          void                      *data,
829                                          DBusFreeFunction           free_data_function)
830 {
831   DBusFreeFunction old_free_function;
832   void *old_data;
833   
834   _dbus_return_if_fail (server != NULL);
835
836   SERVER_LOCK (server);
837   old_free_function = server->new_connection_free_data_function;
838   old_data = server->new_connection_data;
839   
840   server->new_connection_function = function;
841   server->new_connection_data = data;
842   server->new_connection_free_data_function = free_data_function;
843   SERVER_UNLOCK (server);
844     
845   if (old_free_function != NULL)
846     (* old_free_function) (old_data);
847 }
848
849 /**
850  * Sets the watch functions for the connection. These functions are
851  * responsible for making the application's main loop aware of file
852  * descriptors that need to be monitored for events.
853  *
854  * This function behaves exactly like dbus_connection_set_watch_functions();
855  * see the documentation for that routine.
856  *
857  * @param server the server.
858  * @param add_function function to begin monitoring a new descriptor.
859  * @param remove_function function to stop monitoring a descriptor.
860  * @param toggled_function function to notify when the watch is enabled/disabled
861  * @param data data to pass to add_function and remove_function.
862  * @param free_data_function function to be called to free the data.
863  * @returns #FALSE on failure (no memory)
864  */
865 dbus_bool_t
866 dbus_server_set_watch_functions (DBusServer              *server,
867                                  DBusAddWatchFunction     add_function,
868                                  DBusRemoveWatchFunction  remove_function,
869                                  DBusWatchToggledFunction toggled_function,
870                                  void                    *data,
871                                  DBusFreeFunction         free_data_function)
872 {
873   dbus_bool_t result;
874   DBusWatchList *watches;
875   
876   _dbus_return_val_if_fail (server != NULL, FALSE);
877
878   SERVER_LOCK (server);
879   watches = server->watches;
880   server->watches = NULL;
881   if (watches)
882     {
883       SERVER_UNLOCK (server);
884       result = _dbus_watch_list_set_functions (watches,
885                                                add_function,
886                                                remove_function,
887                                                toggled_function,
888                                                data,
889                                                free_data_function);
890       SERVER_LOCK (server);
891     }
892   else
893     {
894       _dbus_warn ("Re-entrant call to %s\n", _DBUS_FUNCTION_NAME);
895       result = FALSE;
896     }
897   server->watches = watches;
898   SERVER_UNLOCK (server);
899   
900   return result;
901 }
902
903 /**
904  * Sets the timeout functions for the connection. These functions are
905  * responsible for making the application's main loop aware of timeouts.
906  *
907  * This function behaves exactly like dbus_connection_set_timeout_functions();
908  * see the documentation for that routine.
909  *
910  * @param server the server.
911  * @param add_function function to add a timeout.
912  * @param remove_function function to remove a timeout.
913  * @param toggled_function function to notify when the timeout is enabled/disabled
914  * @param data data to pass to add_function and remove_function.
915  * @param free_data_function function to be called to free the data.
916  * @returns #FALSE on failure (no memory)
917  */
918 dbus_bool_t
919 dbus_server_set_timeout_functions (DBusServer                *server,
920                                    DBusAddTimeoutFunction     add_function,
921                                    DBusRemoveTimeoutFunction  remove_function,
922                                    DBusTimeoutToggledFunction toggled_function,
923                                    void                      *data,
924                                    DBusFreeFunction           free_data_function)
925 {
926   dbus_bool_t result;
927   DBusTimeoutList *timeouts;
928   
929   _dbus_return_val_if_fail (server != NULL, FALSE);
930
931   SERVER_LOCK (server);
932   timeouts = server->timeouts;
933   server->timeouts = NULL;
934   if (timeouts)
935     {
936       SERVER_UNLOCK (server);
937       result = _dbus_timeout_list_set_functions (timeouts,
938                                                  add_function,
939                                                  remove_function,
940                                                  toggled_function,
941                                                  data,
942                                                  free_data_function);
943       SERVER_LOCK (server);
944     }
945   else
946     {
947       _dbus_warn ("Re-entrant call to %s\n", _DBUS_FUNCTION_NAME);
948       result = FALSE;
949     }
950   server->timeouts = timeouts;
951   SERVER_UNLOCK (server);
952   
953   return result;
954 }
955
956 /**
957  * Sets the authentication mechanisms that this server offers
958  * to clients, as a list of SASL mechanisms. This function
959  * only affects connections created *after* it is called.
960  * Pass #NULL instead of an array to use all available mechanisms.
961  *
962  * @param server the server
963  * @param mechanisms #NULL-terminated array of mechanisms
964  * @returns #FALSE if no memory
965  */
966 dbus_bool_t
967 dbus_server_set_auth_mechanisms (DBusServer  *server,
968                                  const char **mechanisms)
969 {
970   char **copy;
971
972   _dbus_return_val_if_fail (server != NULL, FALSE);
973
974   SERVER_LOCK (server);
975   
976   if (mechanisms != NULL)
977     {
978       copy = _dbus_dup_string_array (mechanisms);
979       if (copy == NULL)
980         return FALSE;
981     }
982   else
983     copy = NULL;
984
985   dbus_free_string_array (server->auth_mechanisms);
986   server->auth_mechanisms = copy;
987
988   SERVER_UNLOCK (server);
989   
990   return TRUE;
991 }
992
993
994 static DBusDataSlotAllocator slot_allocator;
995 _DBUS_DEFINE_GLOBAL_LOCK (server_slots);
996
997 /**
998  * Allocates an integer ID to be used for storing application-specific
999  * data on any DBusServer. The allocated ID may then be used
1000  * with dbus_server_set_data() and dbus_server_get_data().
1001  * The slot must be initialized with -1. If a nonnegative
1002  * slot is passed in, the refcount is incremented on that
1003  * slot, rather than creating a new slot.
1004  *  
1005  * The allocated slot is global, i.e. all DBusServer objects will have
1006  * a slot with the given integer ID reserved.
1007  *
1008  * @param slot_p address of global variable storing the slot ID
1009  * @returns #FALSE on no memory
1010  */
1011 dbus_bool_t
1012 dbus_server_allocate_data_slot (dbus_int32_t *slot_p)
1013 {
1014   return _dbus_data_slot_allocator_alloc (&slot_allocator,
1015                                           (DBusMutex **)&_DBUS_LOCK_NAME (server_slots),
1016                                           slot_p);
1017 }
1018
1019 /**
1020  * Deallocates a global ID for server data slots.
1021  * dbus_server_get_data() and dbus_server_set_data()
1022  * may no longer be used with this slot.
1023  * Existing data stored on existing DBusServer objects
1024  * will be freed when the server is finalized,
1025  * but may not be retrieved (and may only be replaced
1026  * if someone else reallocates the slot).
1027  *
1028  * @param slot_p address of the slot to deallocate
1029  */
1030 void
1031 dbus_server_free_data_slot (dbus_int32_t *slot_p)
1032 {
1033   _dbus_return_if_fail (*slot_p >= 0);
1034   
1035   _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
1036 }
1037
1038 /**
1039  * Stores a pointer on a DBusServer, along
1040  * with an optional function to be used for freeing
1041  * the data when the data is set again, or when
1042  * the server is finalized. The slot number
1043  * must have been allocated with dbus_server_allocate_data_slot().
1044  *
1045  * @param server the server
1046  * @param slot the slot number
1047  * @param data the data to store
1048  * @param free_data_func finalizer function for the data
1049  * @returns #TRUE if there was enough memory to store the data
1050  */
1051 dbus_bool_t
1052 dbus_server_set_data (DBusServer       *server,
1053                       int               slot,
1054                       void             *data,
1055                       DBusFreeFunction  free_data_func)
1056 {
1057   DBusFreeFunction old_free_func;
1058   void *old_data;
1059   dbus_bool_t retval;
1060
1061   _dbus_return_val_if_fail (server != NULL, FALSE);
1062
1063   SERVER_LOCK (server);
1064   
1065   retval = _dbus_data_slot_list_set (&slot_allocator,
1066                                      &server->slot_list,
1067                                      slot, data, free_data_func,
1068                                      &old_free_func, &old_data);
1069
1070
1071   SERVER_UNLOCK (server);
1072   
1073   if (retval)
1074     {
1075       /* Do the actual free outside the server lock */
1076       if (old_free_func)
1077         (* old_free_func) (old_data);
1078     }
1079
1080   return retval;
1081 }
1082
1083 /**
1084  * Retrieves data previously set with dbus_server_set_data().
1085  * The slot must still be allocated (must not have been freed).
1086  *
1087  * @param server the server
1088  * @param slot the slot to get data from
1089  * @returns the data, or #NULL if not found
1090  */
1091 void*
1092 dbus_server_get_data (DBusServer   *server,
1093                       int           slot)
1094 {
1095   void *res;
1096
1097   _dbus_return_val_if_fail (server != NULL, NULL);
1098   
1099   SERVER_LOCK (server);
1100   
1101   res = _dbus_data_slot_list_get (&slot_allocator,
1102                                   &server->slot_list,
1103                                   slot);
1104
1105   SERVER_UNLOCK (server);
1106   
1107   return res;
1108 }
1109
1110 /** @} */
1111
1112 #ifdef DBUS_BUILD_TESTS
1113 #include "dbus-test.h"
1114
1115 dbus_bool_t
1116 _dbus_server_test (void)
1117 {
1118   const char *valid_addresses[] = {
1119     "tcp:port=1234",
1120     "unix:path=./boogie",
1121     "tcp:host=localhost,port=1234",
1122     "tcp:host=localhost,port=1234;tcp:port=5678",
1123     "tcp:port=1234;unix:path=./boogie",
1124   };
1125
1126   DBusServer *server;
1127   int i;
1128   
1129   for (i = 0; i < _DBUS_N_ELEMENTS (valid_addresses); i++)
1130     {
1131       DBusError error;
1132
1133       /* FIXME um, how are the two tests here different? */
1134       
1135       dbus_error_init (&error);
1136       server = dbus_server_listen (valid_addresses[i], &error);
1137       if (server == NULL)
1138         {
1139           _dbus_warn ("server listen error: %s: %s\n", error.name, error.message);
1140           dbus_error_free (&error);
1141           _dbus_assert_not_reached ("Failed to listen for valid address.");
1142         }
1143
1144       dbus_server_disconnect (server);
1145       dbus_server_unref (server);
1146
1147       /* Try disconnecting before unreffing */
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
1160   return TRUE;
1161 }
1162
1163 #endif /* DBUS_BUILD_TESTS */