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