* remove a bunch of todo items from the 1.0 list
[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 1.0? 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               /* Always use abstract namespace if possible with tmpdir */
562               
563               server =
564                 _dbus_server_new_for_domain_socket (_dbus_string_get_const_data (&full_path),
565 #ifdef HAVE_ABSTRACT_SOCKETS
566                                                     TRUE,
567 #else
568                                                     FALSE,
569 #endif
570                                                     error);
571
572               _dbus_string_free (&full_path);
573               _dbus_string_free (&filename);
574             }
575           else
576             {
577               if (path)
578                 server = _dbus_server_new_for_domain_socket (path, FALSE, error);
579               else
580                 server = _dbus_server_new_for_domain_socket (abstract, TRUE, error);
581             }
582         }
583       else if (strcmp (method, "tcp") == 0)
584         {
585           const char *host = dbus_address_entry_get_value (entries[i], "host");
586           const char *port = dbus_address_entry_get_value (entries[i], "port");
587           DBusString  str;
588           long lport;
589           dbus_bool_t sresult;
590           
591           if (port == NULL)
592             {
593               address_problem_type = "tcp";
594               address_problem_field = "port";
595               goto bad_address;
596             }
597
598           _dbus_string_init_const (&str, port);
599           sresult = _dbus_string_parse_int (&str, 0, &lport, NULL);
600           _dbus_string_free (&str);
601           
602           if (sresult == FALSE || lport <= 0 || lport > 65535)
603             {
604               address_problem_other = "Port is not an integer between 0 and 65535";
605               goto bad_address;
606             }
607           
608           server = _dbus_server_new_for_tcp_socket (host, lport, error);
609
610           if (server)
611             break;
612         }
613 #ifdef DBUS_BUILD_TESTS
614       else if (strcmp (method, "debug-pipe") == 0)
615         {
616           const char *name = dbus_address_entry_get_value (entries[i], "name");
617
618           if (name == NULL)
619             {
620               address_problem_type = "debug-pipe";
621               address_problem_field = "name";
622               goto bad_address;
623             }
624
625           server = _dbus_server_debug_pipe_new (name, error);
626         }
627 #endif
628       else
629         {
630           address_problem_other = "Unknown address type (examples of valid types are \"unix\" and \"tcp\")";
631           goto bad_address;
632         }
633       
634       if (server)
635         break;
636     }
637
638  out:
639   
640   dbus_address_entries_free (entries);
641   return server;
642
643  bad_address:
644   dbus_address_entries_free (entries);
645   if (address_problem_type != NULL)
646     dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
647                     "Server address of type %s was missing argument %s",
648                     address_problem_type, address_problem_field);
649   else
650     dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
651                     "Could not parse server address: %s",
652                     address_problem_other);
653
654   return NULL;
655 }
656
657 /**
658  * Increments the reference count of a DBusServer.
659  *
660  * @param server the server.
661  * @returns the server
662  */
663 DBusServer *
664 dbus_server_ref (DBusServer *server)
665 {
666   _dbus_return_val_if_fail (server != NULL, NULL);
667   _dbus_return_val_if_fail (server->refcount.value > 0, NULL);
668
669 #ifdef DBUS_HAVE_ATOMIC_INT
670   _dbus_atomic_inc (&server->refcount);
671 #else
672   SERVER_LOCK (server);
673   _dbus_assert (server->refcount.value > 0);
674
675   server->refcount.value += 1;
676   SERVER_UNLOCK (server);
677 #endif
678
679   return server;
680 }
681
682 /**
683  * Decrements the reference count of a DBusServer.  Finalizes the
684  * server if the reference count reaches zero.
685  *
686  * The server must be disconnected before the refcount reaches zero.
687  *
688  * @param server the server.
689  */
690 void
691 dbus_server_unref (DBusServer *server)
692 {
693   dbus_bool_t last_unref;
694   
695   _dbus_return_if_fail (server != NULL);
696   _dbus_return_if_fail (server->refcount.value > 0);
697
698 #ifdef DBUS_HAVE_ATOMIC_INT
699   last_unref = (_dbus_atomic_dec (&server->refcount) == 1);
700 #else
701   SERVER_LOCK (server);
702   
703   _dbus_assert (server->refcount.value > 0);
704
705   server->refcount.value -= 1;
706   last_unref = (server->refcount.value == 0);
707   
708   SERVER_UNLOCK (server);
709 #endif
710   
711   if (last_unref)
712     {
713       /* lock not held! */
714       _dbus_assert (server->disconnected);
715       
716       _dbus_assert (server->vtable->finalize != NULL);
717       
718       (* server->vtable->finalize) (server);
719     }
720 }
721
722 /**
723  * Like dbus_server_ref() but does not acquire the lock (must already be held)
724  *
725  * @param server the server.
726  */
727 void
728 _dbus_server_ref_unlocked (DBusServer *server)
729 {
730   _dbus_assert (server != NULL);
731   _dbus_assert (server->refcount.value > 0);
732   
733   HAVE_LOCK_CHECK (server);
734
735 #ifdef DBUS_HAVE_ATOMIC_INT
736   _dbus_atomic_inc (&server->refcount);
737 #else
738   _dbus_assert (server->refcount.value > 0);
739
740   server->refcount.value += 1;
741 #endif
742 }
743
744 /**
745  * Like dbus_server_unref() but does not acquire the lock (must already be held)
746  *
747  * @param server the server.
748  */
749 void
750 _dbus_server_unref_unlocked (DBusServer *server)
751 {
752   dbus_bool_t last_unref;
753   
754   _dbus_assert (server != NULL);
755   _dbus_assert (server->refcount.value > 0);
756
757   HAVE_LOCK_CHECK (server);
758   
759 #ifdef DBUS_HAVE_ATOMIC_INT
760   last_unref = (_dbus_atomic_dec (&server->refcount) == 1);
761 #else
762   _dbus_assert (server->refcount.value > 0);
763
764   server->refcount.value -= 1;
765   last_unref = (server->refcount.value == 0);
766 #endif
767   
768   if (last_unref)
769     {
770       _dbus_assert (server->disconnected);
771       
772       SERVER_UNLOCK (server);
773       
774       _dbus_assert (server->vtable->finalize != NULL);
775       
776       (* server->vtable->finalize) (server);
777     }
778 }
779
780 /**
781  * Releases the server's address and stops listening for
782  * new clients. If called more than once, only the first
783  * call has an effect. Does not modify the server's
784  * reference count.
785  * 
786  * @param server the server.
787  */
788 void
789 dbus_server_disconnect (DBusServer *server)
790 {
791   _dbus_return_if_fail (server != NULL);
792   _dbus_return_if_fail (server->refcount.value > 0);
793
794   SERVER_LOCK (server);
795   _dbus_server_ref_unlocked (server);
796   
797   _dbus_assert (server->vtable->disconnect != NULL);
798
799   if (!server->disconnected)
800     {
801       /* this has to be first so recursive calls to disconnect don't happen */
802       server->disconnected = TRUE;
803       
804       (* server->vtable->disconnect) (server);
805     }
806
807   SERVER_UNLOCK (server);
808   dbus_server_unref (server);
809 }
810
811 /**
812  * Returns #TRUE if the server is still listening for new connections.
813  *
814  * @param server the server.
815  */
816 dbus_bool_t
817 dbus_server_get_is_connected (DBusServer *server)
818 {
819   dbus_bool_t retval;
820   
821   _dbus_return_val_if_fail (server != NULL, FALSE);
822
823   SERVER_LOCK (server);
824   retval = !server->disconnected;
825   SERVER_UNLOCK (server);
826
827   return retval;
828 }
829
830 /**
831  * Returns the address of the server, as a newly-allocated
832  * string which must be freed by the caller.
833  *
834  * @param server the server
835  * @returns the address or #NULL if no memory
836  */
837 char*
838 dbus_server_get_address (DBusServer *server)
839 {
840   char *retval;
841   
842   _dbus_return_val_if_fail (server != NULL, NULL);
843
844   SERVER_LOCK (server);
845   retval = _dbus_strdup (server->address);
846   SERVER_UNLOCK (server);
847
848   return retval;
849 }
850
851 /**
852  * Sets a function to be used for handling new connections.  The given
853  * function is passed each new connection as the connection is
854  * created. If the new connection function increments the connection's
855  * reference count, the connection will stay alive. Otherwise, the
856  * connection will be unreferenced and closed.
857  *
858  * @param server the server.
859  * @param function a function to handle new connections.
860  * @param data data to pass to the new connection handler.
861  * @param free_data_function function to free the data.
862  */
863 void
864 dbus_server_set_new_connection_function (DBusServer                *server,
865                                          DBusNewConnectionFunction  function,
866                                          void                      *data,
867                                          DBusFreeFunction           free_data_function)
868 {
869   DBusFreeFunction old_free_function;
870   void *old_data;
871   
872   _dbus_return_if_fail (server != NULL);
873
874   SERVER_LOCK (server);
875   old_free_function = server->new_connection_free_data_function;
876   old_data = server->new_connection_data;
877   
878   server->new_connection_function = function;
879   server->new_connection_data = data;
880   server->new_connection_free_data_function = free_data_function;
881   SERVER_UNLOCK (server);
882     
883   if (old_free_function != NULL)
884     (* old_free_function) (old_data);
885 }
886
887 /**
888  * Sets the watch functions for the connection. These functions are
889  * responsible for making the application's main loop aware of file
890  * descriptors that need to be monitored for events.
891  *
892  * This function behaves exactly like dbus_connection_set_watch_functions();
893  * see the documentation for that routine.
894  *
895  * @param server the server.
896  * @param add_function function to begin monitoring a new descriptor.
897  * @param remove_function function to stop monitoring a descriptor.
898  * @param toggled_function function to notify when the watch is enabled/disabled
899  * @param data data to pass to add_function and remove_function.
900  * @param free_data_function function to be called to free the data.
901  * @returns #FALSE on failure (no memory)
902  */
903 dbus_bool_t
904 dbus_server_set_watch_functions (DBusServer              *server,
905                                  DBusAddWatchFunction     add_function,
906                                  DBusRemoveWatchFunction  remove_function,
907                                  DBusWatchToggledFunction toggled_function,
908                                  void                    *data,
909                                  DBusFreeFunction         free_data_function)
910 {
911   dbus_bool_t result;
912   DBusWatchList *watches;
913   
914   _dbus_return_val_if_fail (server != NULL, FALSE);
915
916   SERVER_LOCK (server);
917   watches = server->watches;
918   server->watches = NULL;
919   if (watches)
920     {
921       SERVER_UNLOCK (server);
922       result = _dbus_watch_list_set_functions (watches,
923                                                add_function,
924                                                remove_function,
925                                                toggled_function,
926                                                data,
927                                                free_data_function);
928       SERVER_LOCK (server);
929     }
930   else
931     {
932       _dbus_warn ("Re-entrant call to %s\n", _DBUS_FUNCTION_NAME);
933       result = FALSE;
934     }
935   server->watches = watches;
936   SERVER_UNLOCK (server);
937   
938   return result;
939 }
940
941 /**
942  * Sets the timeout functions for the connection. These functions are
943  * responsible for making the application's main loop aware of timeouts.
944  *
945  * This function behaves exactly like dbus_connection_set_timeout_functions();
946  * see the documentation for that routine.
947  *
948  * @param server the server.
949  * @param add_function function to add a timeout.
950  * @param remove_function function to remove a timeout.
951  * @param toggled_function function to notify when the timeout is enabled/disabled
952  * @param data data to pass to add_function and remove_function.
953  * @param free_data_function function to be called to free the data.
954  * @returns #FALSE on failure (no memory)
955  */
956 dbus_bool_t
957 dbus_server_set_timeout_functions (DBusServer                *server,
958                                    DBusAddTimeoutFunction     add_function,
959                                    DBusRemoveTimeoutFunction  remove_function,
960                                    DBusTimeoutToggledFunction toggled_function,
961                                    void                      *data,
962                                    DBusFreeFunction           free_data_function)
963 {
964   dbus_bool_t result;
965   DBusTimeoutList *timeouts;
966   
967   _dbus_return_val_if_fail (server != NULL, FALSE);
968
969   SERVER_LOCK (server);
970   timeouts = server->timeouts;
971   server->timeouts = NULL;
972   if (timeouts)
973     {
974       SERVER_UNLOCK (server);
975       result = _dbus_timeout_list_set_functions (timeouts,
976                                                  add_function,
977                                                  remove_function,
978                                                  toggled_function,
979                                                  data,
980                                                  free_data_function);
981       SERVER_LOCK (server);
982     }
983   else
984     {
985       _dbus_warn ("Re-entrant call to %s\n", _DBUS_FUNCTION_NAME);
986       result = FALSE;
987     }
988   server->timeouts = timeouts;
989   SERVER_UNLOCK (server);
990   
991   return result;
992 }
993
994 /**
995  * Sets the authentication mechanisms that this server offers
996  * to clients, as a list of SASL mechanisms. This function
997  * only affects connections created *after* it is called.
998  * Pass #NULL instead of an array to use all available mechanisms.
999  *
1000  * @param server the server
1001  * @param mechanisms #NULL-terminated array of mechanisms
1002  * @returns #FALSE if no memory
1003  */
1004 dbus_bool_t
1005 dbus_server_set_auth_mechanisms (DBusServer  *server,
1006                                  const char **mechanisms)
1007 {
1008   char **copy;
1009
1010   _dbus_return_val_if_fail (server != NULL, FALSE);
1011
1012   SERVER_LOCK (server);
1013   
1014   if (mechanisms != NULL)
1015     {
1016       copy = _dbus_dup_string_array (mechanisms);
1017       if (copy == NULL)
1018         return FALSE;
1019     }
1020   else
1021     copy = NULL;
1022
1023   dbus_free_string_array (server->auth_mechanisms);
1024   server->auth_mechanisms = copy;
1025
1026   SERVER_UNLOCK (server);
1027   
1028   return TRUE;
1029 }
1030
1031
1032 static DBusDataSlotAllocator slot_allocator;
1033 _DBUS_DEFINE_GLOBAL_LOCK (server_slots);
1034
1035 /**
1036  * Allocates an integer ID to be used for storing application-specific
1037  * data on any DBusServer. The allocated ID may then be used
1038  * with dbus_server_set_data() and dbus_server_get_data().
1039  * The slot must be initialized with -1. If a nonnegative
1040  * slot is passed in, the refcount is incremented on that
1041  * slot, rather than creating a new slot.
1042  *  
1043  * The allocated slot is global, i.e. all DBusServer objects will have
1044  * a slot with the given integer ID reserved.
1045  *
1046  * @param slot_p address of global variable storing the slot ID
1047  * @returns #FALSE on no memory
1048  */
1049 dbus_bool_t
1050 dbus_server_allocate_data_slot (dbus_int32_t *slot_p)
1051 {
1052   return _dbus_data_slot_allocator_alloc (&slot_allocator,
1053                                           (DBusMutex **)&_DBUS_LOCK_NAME (server_slots),
1054                                           slot_p);
1055 }
1056
1057 /**
1058  * Deallocates a global ID for server data slots.
1059  * dbus_server_get_data() and dbus_server_set_data()
1060  * may no longer be used with this slot.
1061  * Existing data stored on existing DBusServer objects
1062  * will be freed when the server is finalized,
1063  * but may not be retrieved (and may only be replaced
1064  * if someone else reallocates the slot).
1065  *
1066  * @param slot_p address of the slot to deallocate
1067  */
1068 void
1069 dbus_server_free_data_slot (dbus_int32_t *slot_p)
1070 {
1071   _dbus_return_if_fail (*slot_p >= 0);
1072   
1073   _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
1074 }
1075
1076 /**
1077  * Stores a pointer on a DBusServer, along
1078  * with an optional function to be used for freeing
1079  * the data when the data is set again, or when
1080  * the server is finalized. The slot number
1081  * must have been allocated with dbus_server_allocate_data_slot().
1082  *
1083  * @param server the server
1084  * @param slot the slot number
1085  * @param data the data to store
1086  * @param free_data_func finalizer function for the data
1087  * @returns #TRUE if there was enough memory to store the data
1088  */
1089 dbus_bool_t
1090 dbus_server_set_data (DBusServer       *server,
1091                       int               slot,
1092                       void             *data,
1093                       DBusFreeFunction  free_data_func)
1094 {
1095   DBusFreeFunction old_free_func;
1096   void *old_data;
1097   dbus_bool_t retval;
1098
1099   _dbus_return_val_if_fail (server != NULL, FALSE);
1100
1101   SERVER_LOCK (server);
1102   
1103   retval = _dbus_data_slot_list_set (&slot_allocator,
1104                                      &server->slot_list,
1105                                      slot, data, free_data_func,
1106                                      &old_free_func, &old_data);
1107
1108
1109   SERVER_UNLOCK (server);
1110   
1111   if (retval)
1112     {
1113       /* Do the actual free outside the server lock */
1114       if (old_free_func)
1115         (* old_free_func) (old_data);
1116     }
1117
1118   return retval;
1119 }
1120
1121 /**
1122  * Retrieves data previously set with dbus_server_set_data().
1123  * The slot must still be allocated (must not have been freed).
1124  *
1125  * @param server the server
1126  * @param slot the slot to get data from
1127  * @returns the data, or #NULL if not found
1128  */
1129 void*
1130 dbus_server_get_data (DBusServer   *server,
1131                       int           slot)
1132 {
1133   void *res;
1134
1135   _dbus_return_val_if_fail (server != NULL, NULL);
1136   
1137   SERVER_LOCK (server);
1138   
1139   res = _dbus_data_slot_list_get (&slot_allocator,
1140                                   &server->slot_list,
1141                                   slot);
1142
1143   SERVER_UNLOCK (server);
1144   
1145   return res;
1146 }
1147
1148 /** @} */
1149
1150 #ifdef DBUS_BUILD_TESTS
1151 #include "dbus-test.h"
1152
1153 dbus_bool_t
1154 _dbus_server_test (void)
1155 {
1156   const char *valid_addresses[] = {
1157     "tcp:port=1234",
1158     "unix:path=./boogie",
1159     "tcp:host=localhost,port=1234",
1160     "tcp:host=localhost,port=1234;tcp:port=5678",
1161     "tcp:port=1234;unix:path=./boogie",
1162   };
1163
1164   DBusServer *server;
1165   int i;
1166   
1167   for (i = 0; i < _DBUS_N_ELEMENTS (valid_addresses); i++)
1168     {
1169       server = dbus_server_listen (valid_addresses[i], NULL);
1170       if (server == NULL)
1171         _dbus_assert_not_reached ("Failed to listen for valid address.");
1172
1173       dbus_server_disconnect (server);
1174       dbus_server_unref (server);
1175
1176       /* Try disconnecting before unreffing */
1177       server = dbus_server_listen (valid_addresses[i], NULL);
1178       if (server == NULL)
1179         _dbus_assert_not_reached ("Failed to listen for valid address.");
1180
1181       dbus_server_disconnect (server);
1182       dbus_server_unref (server);
1183     }
1184
1185   return TRUE;
1186 }
1187
1188 #endif /* DBUS_BUILD_TESTS */