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