1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-server.c DBusServer object
4 * Copyright (C) 2002, 2003 Red Hat Inc.
6 * Licensed under the Academic Free License version 1.2
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 #ifdef DBUS_BUILD_TESTS
27 #include "dbus-server-debug.h"
28 #include "dbus-server-debug-pipe.h"
30 #include "dbus-address.h"
33 * @defgroup DBusServer DBusServer
35 * @brief Server that listens for new connections.
37 * Types and functions related to DBusServer.
38 * A DBusServer represents a server that other applications
39 * can connect to. Each connection from another application
40 * is represented by a DBusConnection.
42 * @todo Thread safety hasn't been looked at for #DBusServer
43 * @todo Need notification to apps of disconnection, may matter for some transports
47 * @defgroup DBusServerInternals DBusServer implementation details
48 * @ingroup DBusInternals
49 * @brief Implementation details of DBusServer
55 * Initializes the members of the DBusServer base class.
56 * Chained up to by subclass constructors.
58 * @param server the server.
59 * @param vtable the vtable for the subclass.
60 * @param address the server's address
61 * @returns #TRUE on success.
64 _dbus_server_init_base (DBusServer *server,
65 const DBusServerVTable *vtable,
66 const DBusString *address)
68 server->vtable = vtable;
71 server->address = NULL;
72 server->watches = NULL;
73 server->timeouts = NULL;
74 server->connection_counter = 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 server->connection_counter = _dbus_counter_new ();
88 if (server->connection_counter == NULL)
91 _dbus_data_slot_list_init (&server->slot_list);
93 _dbus_verbose ("Initialized server on address %s\n", server->address);
100 _dbus_watch_list_free (server->watches);
101 server->watches = NULL;
103 if (server->timeouts)
105 _dbus_timeout_list_free (server->timeouts);
106 server->timeouts = NULL;
108 if (server->connection_counter)
110 _dbus_counter_unref (server->connection_counter);
111 server->connection_counter = NULL;
115 dbus_free (server->address);
116 server->address = NULL;
123 * Finalizes the members of the DBusServer base class.
124 * Chained up to by subclass finalizers.
126 * @param server the server.
129 _dbus_server_finalize_base (DBusServer *server)
131 /* calls out to application code... */
132 _dbus_data_slot_list_free (&server->slot_list);
134 dbus_server_set_new_connection_function (server, NULL, NULL, NULL);
136 if (!server->disconnected)
137 dbus_server_disconnect (server);
139 _dbus_watch_list_free (server->watches);
140 _dbus_timeout_list_free (server->timeouts);
141 _dbus_counter_unref (server->connection_counter);
143 dbus_free (server->address);
145 dbus_free_string_array (server->auth_mechanisms);
149 * Adds a watch for this server, chaining out to application-provided
152 * @param server the server.
153 * @param watch the watch to add.
156 _dbus_server_add_watch (DBusServer *server,
159 return _dbus_watch_list_add_watch (server->watches, watch);
163 * Removes a watch previously added with _dbus_server_remove_watch().
165 * @param server the server.
166 * @param watch the watch to remove.
169 _dbus_server_remove_watch (DBusServer *server,
172 _dbus_watch_list_remove_watch (server->watches, watch);
176 * Toggles a watch and notifies app via server's
177 * DBusWatchToggledFunction if available. It's an error to call this
178 * function on a watch that was not previously added.
180 * @param server the server.
181 * @param watch the watch to toggle.
182 * @param enabled whether to enable or disable
185 _dbus_server_toggle_watch (DBusServer *server,
189 if (server->watches) /* null during finalize */
190 _dbus_watch_list_toggle_watch (server->watches,
195 * Adds a timeout for this server, chaining out to
196 * application-provided timeout handlers. The timeout should be
197 * repeatedly handled with dbus_timeout_handle() at its given interval
198 * until it is removed.
200 * @param server the server.
201 * @param timeout the timeout to add.
204 _dbus_server_add_timeout (DBusServer *server,
205 DBusTimeout *timeout)
207 return _dbus_timeout_list_add_timeout (server->timeouts, timeout);
211 * Removes a timeout previously added with _dbus_server_add_timeout().
213 * @param server the server.
214 * @param timeout the timeout to remove.
217 _dbus_server_remove_timeout (DBusServer *server,
218 DBusTimeout *timeout)
220 _dbus_timeout_list_remove_timeout (server->timeouts, timeout);
224 * Toggles a timeout and notifies app via server's
225 * DBusTimeoutToggledFunction if available. It's an error to call this
226 * function on a timeout that was not previously added.
228 * @param server the server.
229 * @param timeout the timeout to toggle.
230 * @param enabled whether to enable or disable
233 _dbus_server_toggle_timeout (DBusServer *server,
234 DBusTimeout *timeout,
237 if (server->timeouts) /* null during finalize */
238 _dbus_timeout_list_toggle_timeout (server->timeouts,
246 * @addtogroup DBusServer
253 * @typedef DBusServer
255 * An opaque object representing a server that listens for
256 * connections from other applications. Each time a connection
257 * is made, a new DBusConnection is created and made available
258 * via an application-provided DBusNewConnectionFunction.
259 * The DBusNewConnectionFunction is provided with
260 * dbus_server_set_new_connection_function().
265 * Listens for new connections on the given address.
266 * Returns #NULL if listening fails for any reason.
267 * Otherwise returns a new #DBusServer.
268 * dbus_server_set_new_connection_function() and
269 * dbus_server_set_watch_functions() should be called
270 * immediately to render the server fully functional.
272 * @todo error messages on bad address could really be better.
273 * DBusResultCode is a bit limiting here.
275 * @param address the address of this server.
276 * @param error location to store rationale for failure.
277 * @returns a new DBusServer, or #NULL on failure.
281 dbus_server_listen (const char *address,
285 DBusAddressEntry **entries;
287 const char *address_problem_type;
288 const char *address_problem_field;
289 const char *address_problem_other;
291 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
293 if (!dbus_parse_address (address, &entries, &len, error))
297 address_problem_type = NULL;
298 address_problem_field = NULL;
299 address_problem_other = NULL;
301 for (i = 0; i < len; i++)
303 const char *method = dbus_address_entry_get_method (entries[i]);
305 if (strcmp (method, "unix") == 0)
307 const char *path = dbus_address_entry_get_value (entries[i], "path");
308 const char *tmpdir = dbus_address_entry_get_value (entries[i], "tmpdir");
310 if (path == NULL && tmpdir == NULL)
312 address_problem_type = "unix";
313 address_problem_field = "path or tmpdir";
319 address_problem_other = "cannot specify both \"path\" and \"tmpdir\" at the same time";
325 DBusString full_path;
328 if (!_dbus_string_init (&full_path))
330 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
334 if (!_dbus_string_init (&filename))
336 _dbus_string_free (&full_path);
337 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
341 if (!_dbus_string_append (&filename,
343 !_dbus_generate_random_ascii (&filename, 10) ||
344 !_dbus_string_append (&full_path, tmpdir) ||
345 !_dbus_concat_dir_and_file (&full_path, &filename))
347 _dbus_string_free (&full_path);
348 _dbus_string_free (&filename);
349 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
353 /* FIXME - we will unconditionally unlink() the path.
354 * unlink() does not follow symlinks, but would like
355 * independent confirmation this is safe enough. See
356 * also _dbus_listen_unix_socket() and comments therein.
360 _dbus_server_new_for_domain_socket (_dbus_string_get_const_data (&full_path),
363 _dbus_string_free (&full_path);
364 _dbus_string_free (&filename);
368 server = _dbus_server_new_for_domain_socket (path, error);
371 else if (strcmp (method, "tcp") == 0)
373 const char *host = dbus_address_entry_get_value (entries[i], "host");
374 const char *port = dbus_address_entry_get_value (entries[i], "port");
381 address_problem_type = "tcp";
382 address_problem_field = "port";
386 _dbus_string_init_const (&str, port);
387 sresult = _dbus_string_parse_int (&str, 0, &lport, NULL);
388 _dbus_string_free (&str);
390 if (sresult == FALSE || lport <= 0 || lport > 65535)
392 address_problem_other = "Port is not an integer between 0 and 65535";
396 server = _dbus_server_new_for_tcp_socket (host, lport, error);
401 #ifdef DBUS_BUILD_TESTS
402 else if (strcmp (method, "debug") == 0)
404 const char *name = dbus_address_entry_get_value (entries[i], "name");
408 address_problem_type = "debug";
409 address_problem_field = "name";
413 server = _dbus_server_debug_new (name, error);
415 else if (strcmp (method, "debug-pipe") == 0)
417 const char *name = dbus_address_entry_get_value (entries[i], "name");
421 address_problem_type = "debug-pipe";
422 address_problem_field = "name";
426 server = _dbus_server_debug_pipe_new (name, error);
431 address_problem_other = "Unknown address type (examples of valid types are \"unix\" and \"tcp\")";
441 dbus_address_entries_free (entries);
445 dbus_address_entries_free (entries);
446 if (address_problem_type != NULL)
447 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
448 "Server address of type %s was missing argument %s",
449 address_problem_type, address_problem_field);
451 dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
452 "Could not parse server address: %s",
453 address_problem_other);
459 * Increments the reference count of a DBusServer.
461 * @param server the server.
464 dbus_server_ref (DBusServer *server)
466 server->refcount += 1;
470 * Decrements the reference count of a DBusServer. Finalizes the
471 * server if the reference count reaches zero. The server connection
472 * will be closed as with dbus_server_disconnect() when the server is
475 * @param server the server.
478 dbus_server_unref (DBusServer *server)
480 _dbus_assert (server != NULL);
481 _dbus_assert (server->refcount > 0);
483 server->refcount -= 1;
484 if (server->refcount == 0)
486 _dbus_assert (server->vtable->finalize != NULL);
488 (* server->vtable->finalize) (server);
493 * Releases the server's address and stops listening for
494 * new clients. If called more than once, only the first
495 * call has an effect. Does not modify the server's
498 * @param server the server.
501 dbus_server_disconnect (DBusServer *server)
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 return !server->disconnected;
524 * Returns the address of the server, as a newly-allocated
525 * string which must be freed by the caller.
527 * @param server the server
528 * @returns the address or #NULL if no memory
531 dbus_server_get_address (DBusServer *server)
533 return _dbus_strdup (server->address);
537 * Sets a function to be used for handling new connections. The given
538 * function is passed each new connection as the connection is
539 * created. If the new connection function increments the connection's
540 * reference count, the connection will stay alive. Otherwise, the
541 * connection will be unreferenced and closed.
543 * @param server the server.
544 * @param function a function to handle new connections.
545 * @param data data to pass to the new connection handler.
546 * @param free_data_function function to free the data.
549 dbus_server_set_new_connection_function (DBusServer *server,
550 DBusNewConnectionFunction function,
552 DBusFreeFunction free_data_function)
554 if (server->new_connection_free_data_function != NULL)
555 (* server->new_connection_free_data_function) (server->new_connection_data);
557 server->new_connection_function = function;
558 server->new_connection_data = data;
559 server->new_connection_free_data_function = free_data_function;
563 * Sets the watch functions for the connection. These functions are
564 * responsible for making the application's main loop aware of file
565 * descriptors that need to be monitored for events.
567 * This function behaves exactly like dbus_connection_set_watch_functions();
568 * see the documentation for that routine.
570 * @param server the server.
571 * @param add_function function to begin monitoring a new descriptor.
572 * @param remove_function function to stop monitoring a descriptor.
573 * @param toggled_function function to notify when the watch is enabled/disabled
574 * @param data data to pass to add_function and remove_function.
575 * @param free_data_function function to be called to free the data.
576 * @returns #FALSE on failure (no memory)
579 dbus_server_set_watch_functions (DBusServer *server,
580 DBusAddWatchFunction add_function,
581 DBusRemoveWatchFunction remove_function,
582 DBusWatchToggledFunction toggled_function,
584 DBusFreeFunction free_data_function)
586 return _dbus_watch_list_set_functions (server->watches,
595 * Sets the timeout functions for the connection. These functions are
596 * responsible for making the application's main loop aware of timeouts.
598 * This function behaves exactly like dbus_connection_set_timeout_functions();
599 * see the documentation for that routine.
601 * @param server the server.
602 * @param add_function function to add a timeout.
603 * @param remove_function function to remove a timeout.
604 * @param toggled_function function to notify when the timeout is enabled/disabled
605 * @param data data to pass to add_function and remove_function.
606 * @param free_data_function function to be called to free the data.
607 * @returns #FALSE on failure (no memory)
610 dbus_server_set_timeout_functions (DBusServer *server,
611 DBusAddTimeoutFunction add_function,
612 DBusRemoveTimeoutFunction remove_function,
613 DBusTimeoutToggledFunction toggled_function,
615 DBusFreeFunction free_data_function)
617 return _dbus_timeout_list_set_functions (server->timeouts,
618 add_function, remove_function,
620 data, free_data_function);
624 * Called to notify the server when a previously-added watch
625 * is ready for reading or writing, or has an exception such
628 * If this function returns #FALSE, then the file descriptor may still
629 * be ready for reading or writing, but more memory is needed in order
630 * to do the reading or writing. If you ignore the #FALSE return, your
631 * application may spin in a busy loop on the file descriptor until
632 * memory becomes available, but nothing more catastrophic should
635 * @param server the server.
636 * @param watch the watch.
637 * @param condition the current condition of the file descriptors being watched.
640 dbus_server_handle_watch (DBusServer *server,
642 unsigned int condition)
644 _dbus_assert (server->vtable->handle_watch != NULL);
646 _dbus_watch_sanitize_condition (watch, &condition);
648 return (* server->vtable->handle_watch) (server, watch, condition);
652 * Sets the authentication mechanisms that this server offers
653 * to clients, as a list of SASL mechanisms. This function
654 * only affects connections created *after* it is called.
655 * Pass #NULL instead of an array to use all available mechanisms.
657 * @param server the server
658 * @param mechanisms #NULL-terminated array of mechanisms
659 * @returns #FALSE if no memory
662 dbus_server_set_auth_mechanisms (DBusServer *server,
663 const char **mechanisms)
667 if (mechanisms != NULL)
669 copy = _dbus_dup_string_array (mechanisms);
676 dbus_free_string_array (server->auth_mechanisms);
677 server->auth_mechanisms = copy;
683 static DBusDataSlotAllocator slot_allocator;
684 _DBUS_DEFINE_GLOBAL_LOCK (server_slots);
687 * Allocates an integer ID to be used for storing application-specific
688 * data on any DBusServer. The allocated ID may then be used
689 * with dbus_server_set_data() and dbus_server_get_data().
690 * If allocation fails, -1 is returned. Again, the allocated
691 * slot is global, i.e. all DBusServer objects will
692 * have a slot with the given integer ID reserved.
694 * @returns -1 on failure, otherwise the data slot ID
697 dbus_server_allocate_data_slot (void)
699 return _dbus_data_slot_allocator_alloc (&slot_allocator,
700 _DBUS_LOCK_NAME (server_slots));
704 * Deallocates a global ID for server data slots.
705 * dbus_server_get_data() and dbus_server_set_data()
706 * may no longer be used with this slot.
707 * Existing data stored on existing DBusServer objects
708 * will be freed when the server is finalized,
709 * but may not be retrieved (and may only be replaced
710 * if someone else reallocates the slot).
712 * @param slot the slot to deallocate
715 dbus_server_free_data_slot (int slot)
717 _dbus_data_slot_allocator_free (&slot_allocator, slot);
721 * Stores a pointer on a DBusServer, along
722 * with an optional function to be used for freeing
723 * the data when the data is set again, or when
724 * the server is finalized. The slot number
725 * must have been allocated with dbus_server_allocate_data_slot().
727 * @param server the server
728 * @param slot the slot number
729 * @param data the data to store
730 * @param free_data_func finalizer function for the data
731 * @returns #TRUE if there was enough memory to store the data
734 dbus_server_set_data (DBusServer *server,
737 DBusFreeFunction free_data_func)
739 DBusFreeFunction old_free_func;
744 dbus_mutex_lock (server->mutex);
747 retval = _dbus_data_slot_list_set (&slot_allocator,
749 slot, data, free_data_func,
750 &old_free_func, &old_data);
753 dbus_mutex_unlock (server->mutex);
758 /* Do the actual free outside the server lock */
760 (* old_free_func) (old_data);
767 * Retrieves data previously set with dbus_server_set_data().
768 * The slot must still be allocated (must not have been freed).
770 * @param server the server
771 * @param slot the slot to get data from
772 * @returns the data, or #NULL if not found
775 dbus_server_get_data (DBusServer *server,
781 dbus_mutex_lock (server->mutex);
784 res = _dbus_data_slot_list_get (&slot_allocator,
789 dbus_mutex_unlock (server->mutex);