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