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