1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-server.c DBusServer object
4 * Copyright (C) 2002, 2003, 2004 Red Hat Inc.
6 * Licensed under the Academic Free License version 2.0
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.
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.
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
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"
30 #include "dbus-address.h"
31 #include "dbus-protocol.h"
34 * @defgroup DBusServer DBusServer
36 * @brief Server that listens for new connections.
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.
43 * @todo Thread safety hasn't been looked at for #DBusServer
44 * @todo Need notification to apps of disconnection, may matter for some transports
48 * @defgroup DBusServerInternals DBusServer implementation details
49 * @ingroup DBusInternals
50 * @brief Implementation details of DBusServer
56 * Initializes the members of the DBusServer base class.
57 * Chained up to by subclass constructors.
59 * @param server the server.
60 * @param vtable the vtable for the subclass.
61 * @param address the server's address
62 * @returns #TRUE on success.
65 _dbus_server_init_base (DBusServer *server,
66 const DBusServerVTable *vtable,
67 const DBusString *address)
69 server->vtable = vtable;
72 server->address = NULL;
73 server->watches = NULL;
74 server->timeouts = NULL;
76 if (!_dbus_string_copy_data (address, &server->address))
79 server->watches = _dbus_watch_list_new ();
80 if (server->watches == NULL)
83 server->timeouts = _dbus_timeout_list_new ();
84 if (server->timeouts == NULL)
87 _dbus_data_slot_list_init (&server->slot_list);
89 _dbus_verbose ("Initialized server on address %s\n", server->address);
96 _dbus_watch_list_free (server->watches);
97 server->watches = NULL;
101 _dbus_timeout_list_free (server->timeouts);
102 server->timeouts = NULL;
106 dbus_free (server->address);
107 server->address = NULL;
114 * Finalizes the members of the DBusServer base class.
115 * Chained up to by subclass finalizers.
117 * @param server the server.
120 _dbus_server_finalize_base (DBusServer *server)
122 /* calls out to application code... */
123 _dbus_data_slot_list_free (&server->slot_list);
125 dbus_server_set_new_connection_function (server, NULL, NULL, NULL);
127 if (!server->disconnected)
128 dbus_server_disconnect (server);
130 _dbus_watch_list_free (server->watches);
131 _dbus_timeout_list_free (server->timeouts);
133 dbus_free (server->address);
135 dbus_free_string_array (server->auth_mechanisms);
139 * Adds a watch for this server, chaining out to application-provided
142 * @param server the server.
143 * @param watch the watch to add.
146 _dbus_server_add_watch (DBusServer *server,
149 return _dbus_watch_list_add_watch (server->watches, watch);
153 * Removes a watch previously added with _dbus_server_remove_watch().
155 * @param server the server.
156 * @param watch the watch to remove.
159 _dbus_server_remove_watch (DBusServer *server,
162 _dbus_watch_list_remove_watch (server->watches, watch);
166 * Toggles a watch and notifies app via server's
167 * DBusWatchToggledFunction if available. It's an error to call this
168 * function on a watch that was not previously added.
170 * @param server the server.
171 * @param watch the watch to toggle.
172 * @param enabled whether to enable or disable
175 _dbus_server_toggle_watch (DBusServer *server,
179 if (server->watches) /* null during finalize */
180 _dbus_watch_list_toggle_watch (server->watches,
185 * Adds a timeout for this server, chaining out to
186 * application-provided timeout handlers. The timeout should be
187 * repeatedly handled with dbus_timeout_handle() at its given interval
188 * until it is removed.
190 * @param server the server.
191 * @param timeout the timeout to add.
194 _dbus_server_add_timeout (DBusServer *server,
195 DBusTimeout *timeout)
197 return _dbus_timeout_list_add_timeout (server->timeouts, timeout);
201 * Removes a timeout previously added with _dbus_server_add_timeout().
203 * @param server the server.
204 * @param timeout the timeout to remove.
207 _dbus_server_remove_timeout (DBusServer *server,
208 DBusTimeout *timeout)
210 _dbus_timeout_list_remove_timeout (server->timeouts, timeout);
214 * Toggles a timeout and notifies app via server's
215 * DBusTimeoutToggledFunction if available. It's an error to call this
216 * function on a timeout that was not previously added.
218 * @param server the server.
219 * @param timeout the timeout to toggle.
220 * @param enabled whether to enable or disable
223 _dbus_server_toggle_timeout (DBusServer *server,
224 DBusTimeout *timeout,
227 if (server->timeouts) /* null during finalize */
228 _dbus_timeout_list_toggle_timeout (server->timeouts,
236 * @addtogroup DBusServer
243 * @typedef DBusServer
245 * An opaque object representing a server that listens for
246 * connections from other applications. Each time a connection
247 * is made, a new DBusConnection is created and made available
248 * via an application-provided DBusNewConnectionFunction.
249 * The DBusNewConnectionFunction is provided with
250 * dbus_server_set_new_connection_function().
255 * Listens for new connections on the given address.
256 * Returns #NULL if listening fails for any reason.
257 * Otherwise returns a new #DBusServer.
258 * dbus_server_set_new_connection_function() and
259 * dbus_server_set_watch_functions() should be called
260 * immediately to render the server fully functional.
262 * @todo error messages on bad address could really be better.
263 * DBusResultCode is a bit limiting here.
265 * @param address the address of this server.
266 * @param error location to store rationale for failure.
267 * @returns a new DBusServer, or #NULL on failure.
271 dbus_server_listen (const char *address,
275 DBusAddressEntry **entries;
277 const char *address_problem_type;
278 const char *address_problem_field;
279 const char *address_problem_other;
281 _dbus_return_val_if_fail (address != NULL, NULL);
282 _dbus_return_val_if_error_is_set (error, NULL);
284 if (!dbus_parse_address (address, &entries, &len, error))
288 address_problem_type = NULL;
289 address_problem_field = NULL;
290 address_problem_other = NULL;
292 for (i = 0; i < len; i++)
294 const char *method = dbus_address_entry_get_method (entries[i]);
296 if (strcmp (method, "unix") == 0)
298 const char *path = dbus_address_entry_get_value (entries[i], "path");
299 const char *tmpdir = dbus_address_entry_get_value (entries[i], "tmpdir");
300 const char *abstract = dbus_address_entry_get_value (entries[i], "abstract");
302 if (path == NULL && tmpdir == NULL && abstract == NULL)
304 address_problem_type = "unix";
305 address_problem_field = "path or tmpdir or abstract";
309 if ((path && tmpdir) ||
310 (path && abstract) ||
311 (tmpdir && abstract))
313 address_problem_other = "cannot specify two of \"path\" and \"tmpdir\" and \"abstract\" at the same time";
319 DBusString full_path;
322 if (!_dbus_string_init (&full_path))
324 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
328 if (!_dbus_string_init (&filename))
330 _dbus_string_free (&full_path);
331 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
335 if (!_dbus_string_append (&filename,
337 !_dbus_generate_random_ascii (&filename, 10) ||
338 !_dbus_string_append (&full_path, tmpdir) ||
339 !_dbus_concat_dir_and_file (&full_path, &filename))
341 _dbus_string_free (&full_path);
342 _dbus_string_free (&filename);
343 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
347 /* FIXME - we will unconditionally unlink() the path if
348 * we don't support abstract namespace. unlink() does
349 * not follow symlinks, but would like independent
350 * confirmation this is safe enough. See also
351 * _dbus_listen_unix_socket() and comments therein.
354 /* Always use abstract namespace if possible with tmpdir */
357 _dbus_server_new_for_domain_socket (_dbus_string_get_const_data (&full_path),
358 #ifdef HAVE_ABSTRACT_SOCKETS
365 _dbus_string_free (&full_path);
366 _dbus_string_free (&filename);
371 server = _dbus_server_new_for_domain_socket (path, FALSE, error);
373 server = _dbus_server_new_for_domain_socket (abstract, TRUE, error);
376 else if (strcmp (method, "tcp") == 0)
378 const char *host = dbus_address_entry_get_value (entries[i], "host");
379 const char *port = dbus_address_entry_get_value (entries[i], "port");
386 address_problem_type = "tcp";
387 address_problem_field = "port";
391 _dbus_string_init_const (&str, port);
392 sresult = _dbus_string_parse_int (&str, 0, &lport, NULL);
393 _dbus_string_free (&str);
395 if (sresult == FALSE || lport <= 0 || lport > 65535)
397 address_problem_other = "Port is not an integer between 0 and 65535";
401 server = _dbus_server_new_for_tcp_socket (host, lport, error);
406 #ifdef DBUS_BUILD_TESTS
407 else if (strcmp (method, "debug-pipe") == 0)
409 const char *name = dbus_address_entry_get_value (entries[i], "name");
413 address_problem_type = "debug-pipe";
414 address_problem_field = "name";
418 server = _dbus_server_debug_pipe_new (name, error);
423 address_problem_other = "Unknown address type (examples of valid types are \"unix\" and \"tcp\")";
433 dbus_address_entries_free (entries);
437 dbus_address_entries_free (entries);
438 if (address_problem_type != NULL)
439 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
440 "Server address of type %s was missing argument %s",
441 address_problem_type, address_problem_field);
443 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
444 "Could not parse server address: %s",
445 address_problem_other);
451 * Increments the reference count of a DBusServer.
453 * @param server the server.
454 * @returns the server
457 dbus_server_ref (DBusServer *server)
459 _dbus_return_val_if_fail (server != NULL, NULL);
461 server->refcount += 1;
467 * Decrements the reference count of a DBusServer. Finalizes the
468 * server if the reference count reaches zero. The server connection
469 * will be closed as with dbus_server_disconnect() when the server is
472 * @param server the server.
475 dbus_server_unref (DBusServer *server)
477 _dbus_return_if_fail (server != NULL);
479 _dbus_assert (server->refcount > 0);
481 server->refcount -= 1;
482 if (server->refcount == 0)
484 _dbus_assert (server->vtable->finalize != NULL);
486 (* server->vtable->finalize) (server);
491 * Releases the server's address and stops listening for
492 * new clients. If called more than once, only the first
493 * call has an effect. Does not modify the server's
496 * @param server the server.
499 dbus_server_disconnect (DBusServer *server)
501 _dbus_return_if_fail (server != NULL);
503 _dbus_assert (server->vtable->disconnect != NULL);
505 if (server->disconnected)
508 (* server->vtable->disconnect) (server);
509 server->disconnected = TRUE;
513 * Returns #TRUE if the server is still listening for new connections.
515 * @param server the server.
518 dbus_server_get_is_connected (DBusServer *server)
520 _dbus_return_val_if_fail (server != NULL, FALSE);
522 return !server->disconnected;
526 * Returns the address of the server, as a newly-allocated
527 * string which must be freed by the caller.
529 * @param server the server
530 * @returns the address or #NULL if no memory
533 dbus_server_get_address (DBusServer *server)
535 _dbus_return_val_if_fail (server != NULL, NULL);
537 return _dbus_strdup (server->address);
541 * Sets a function to be used for handling new connections. The given
542 * function is passed each new connection as the connection is
543 * created. If the new connection function increments the connection's
544 * reference count, the connection will stay alive. Otherwise, the
545 * connection will be unreferenced and closed.
547 * @param server the server.
548 * @param function a function to handle new connections.
549 * @param data data to pass to the new connection handler.
550 * @param free_data_function function to free the data.
553 dbus_server_set_new_connection_function (DBusServer *server,
554 DBusNewConnectionFunction function,
556 DBusFreeFunction free_data_function)
558 _dbus_return_if_fail (server != NULL);
560 if (server->new_connection_free_data_function != NULL)
561 (* server->new_connection_free_data_function) (server->new_connection_data);
563 server->new_connection_function = function;
564 server->new_connection_data = data;
565 server->new_connection_free_data_function = free_data_function;
569 * Sets the watch functions for the connection. These functions are
570 * responsible for making the application's main loop aware of file
571 * descriptors that need to be monitored for events.
573 * This function behaves exactly like dbus_connection_set_watch_functions();
574 * see the documentation for that routine.
576 * @param server the server.
577 * @param add_function function to begin monitoring a new descriptor.
578 * @param remove_function function to stop monitoring a descriptor.
579 * @param toggled_function function to notify when the watch is enabled/disabled
580 * @param data data to pass to add_function and remove_function.
581 * @param free_data_function function to be called to free the data.
582 * @returns #FALSE on failure (no memory)
585 dbus_server_set_watch_functions (DBusServer *server,
586 DBusAddWatchFunction add_function,
587 DBusRemoveWatchFunction remove_function,
588 DBusWatchToggledFunction toggled_function,
590 DBusFreeFunction free_data_function)
592 _dbus_return_val_if_fail (server != NULL, FALSE);
594 return _dbus_watch_list_set_functions (server->watches,
603 * Sets the timeout functions for the connection. These functions are
604 * responsible for making the application's main loop aware of timeouts.
606 * This function behaves exactly like dbus_connection_set_timeout_functions();
607 * see the documentation for that routine.
609 * @param server the server.
610 * @param add_function function to add a timeout.
611 * @param remove_function function to remove a timeout.
612 * @param toggled_function function to notify when the timeout is enabled/disabled
613 * @param data data to pass to add_function and remove_function.
614 * @param free_data_function function to be called to free the data.
615 * @returns #FALSE on failure (no memory)
618 dbus_server_set_timeout_functions (DBusServer *server,
619 DBusAddTimeoutFunction add_function,
620 DBusRemoveTimeoutFunction remove_function,
621 DBusTimeoutToggledFunction toggled_function,
623 DBusFreeFunction free_data_function)
625 _dbus_return_val_if_fail (server != NULL, FALSE);
627 return _dbus_timeout_list_set_functions (server->timeouts,
628 add_function, remove_function,
630 data, free_data_function);
634 * Sets the authentication mechanisms that this server offers
635 * to clients, as a list of SASL mechanisms. This function
636 * only affects connections created *after* it is called.
637 * Pass #NULL instead of an array to use all available mechanisms.
639 * @param server the server
640 * @param mechanisms #NULL-terminated array of mechanisms
641 * @returns #FALSE if no memory
644 dbus_server_set_auth_mechanisms (DBusServer *server,
645 const char **mechanisms)
649 _dbus_return_val_if_fail (server != NULL, FALSE);
651 if (mechanisms != NULL)
653 copy = _dbus_dup_string_array (mechanisms);
660 dbus_free_string_array (server->auth_mechanisms);
661 server->auth_mechanisms = copy;
667 static DBusDataSlotAllocator slot_allocator;
668 _DBUS_DEFINE_GLOBAL_LOCK (server_slots);
671 * Allocates an integer ID to be used for storing application-specific
672 * data on any DBusServer. The allocated ID may then be used
673 * with dbus_server_set_data() and dbus_server_get_data().
674 * The slot must be initialized with -1. If a nonnegative
675 * slot is passed in, the refcount is incremented on that
676 * slot, rather than creating a new slot.
678 * The allocated slot is global, i.e. all DBusServer objects will have
679 * a slot with the given integer ID reserved.
681 * @param slot_p address of global variable storing the slot ID
682 * @returns #FALSE on no memory
685 dbus_server_allocate_data_slot (dbus_int32_t *slot_p)
687 return _dbus_data_slot_allocator_alloc (&slot_allocator,
688 _DBUS_LOCK_NAME (server_slots),
693 * Deallocates a global ID for server data slots.
694 * dbus_server_get_data() and dbus_server_set_data()
695 * may no longer be used with this slot.
696 * Existing data stored on existing DBusServer objects
697 * will be freed when the server is finalized,
698 * but may not be retrieved (and may only be replaced
699 * if someone else reallocates the slot).
701 * @param slot_p address of the slot to deallocate
704 dbus_server_free_data_slot (dbus_int32_t *slot_p)
706 _dbus_return_if_fail (*slot_p >= 0);
708 _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
712 * Stores a pointer on a DBusServer, along
713 * with an optional function to be used for freeing
714 * the data when the data is set again, or when
715 * the server is finalized. The slot number
716 * must have been allocated with dbus_server_allocate_data_slot().
718 * @param server the server
719 * @param slot the slot number
720 * @param data the data to store
721 * @param free_data_func finalizer function for the data
722 * @returns #TRUE if there was enough memory to store the data
725 dbus_server_set_data (DBusServer *server,
728 DBusFreeFunction free_data_func)
730 DBusFreeFunction old_free_func;
734 _dbus_return_val_if_fail (server != NULL, FALSE);
737 dbus_mutex_lock (server->mutex);
740 retval = _dbus_data_slot_list_set (&slot_allocator,
742 slot, data, free_data_func,
743 &old_free_func, &old_data);
746 dbus_mutex_unlock (server->mutex);
751 /* Do the actual free outside the server lock */
753 (* old_free_func) (old_data);
760 * Retrieves data previously set with dbus_server_set_data().
761 * The slot must still be allocated (must not have been freed).
763 * @param server the server
764 * @param slot the slot to get data from
765 * @returns the data, or #NULL if not found
768 dbus_server_get_data (DBusServer *server,
773 _dbus_return_val_if_fail (server != NULL, NULL);
776 dbus_mutex_lock (server->mutex);
779 res = _dbus_data_slot_list_get (&slot_allocator,
784 dbus_mutex_unlock (server->mutex);
792 #ifdef DBUS_BUILD_TESTS
793 #include "dbus-test.h"
796 _dbus_server_test (void)
798 const char *valid_addresses[] = {
800 "unix:path=./boogie",
801 "tcp:host=localhost,port=1234",
802 "tcp:host=localhost,port=1234;tcp:port=5678",
803 "tcp:port=1234;unix:path=./boogie",
809 for (i = 0; i < _DBUS_N_ELEMENTS (valid_addresses); i++)
811 server = dbus_server_listen (valid_addresses[i], NULL);
813 _dbus_assert_not_reached ("Failed to listen for valid address.");
815 dbus_server_unref (server);
817 /* Try disconnecting before unreffing */
818 server = dbus_server_listen (valid_addresses[i], NULL);
820 _dbus_assert_not_reached ("Failed to listen for valid address.");
822 dbus_server_disconnect (server);
824 dbus_server_unref (server);
830 #endif /* DBUS_BUILD_TESTS */