1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-connection.c DBusConnection object
4 * Copyright (C) 2002-2006 Red Hat Inc.
6 * Licensed under the Academic Free License version 2.1
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 #include "dbus-shared.h"
26 #include "dbus-connection.h"
27 #include "dbus-list.h"
28 #include "dbus-timeout.h"
29 #include "dbus-transport.h"
30 #include "dbus-watch.h"
31 #include "dbus-connection-internal.h"
32 #include "dbus-pending-call-internal.h"
33 #include "dbus-list.h"
34 #include "dbus-hash.h"
35 #include "dbus-message-internal.h"
36 #include "dbus-message-private.h"
37 #include "dbus-threads.h"
38 #include "dbus-protocol.h"
39 #include "dbus-dataslot.h"
40 #include "dbus-string.h"
41 #include "dbus-signature.h"
42 #include "dbus-pending-call.h"
43 #include "dbus-object-tree.h"
44 #include "dbus-threads-internal.h"
46 #include "dbus-marshal-basic.h"
47 #include "dbus-transport-kdbus.h"
50 #ifdef DBUS_DISABLE_CHECKS
51 #define TOOK_LOCK_CHECK(connection)
52 #define RELEASING_LOCK_CHECK(connection)
53 #define HAVE_LOCK_CHECK(connection)
55 #define TOOK_LOCK_CHECK(connection) do { \
56 _dbus_assert (!(connection)->have_connection_lock); \
57 (connection)->have_connection_lock = TRUE; \
59 #define RELEASING_LOCK_CHECK(connection) do { \
60 _dbus_assert ((connection)->have_connection_lock); \
61 (connection)->have_connection_lock = FALSE; \
63 #define HAVE_LOCK_CHECK(connection) _dbus_assert ((connection)->have_connection_lock)
64 /* A "DO_NOT_HAVE_LOCK_CHECK" is impossible since we need the lock to check the flag */
69 #define CONNECTION_LOCK(connection) do { \
70 if (TRACE_LOCKS) { _dbus_verbose ("LOCK\n"); } \
71 _dbus_rmutex_lock ((connection)->mutex); \
72 TOOK_LOCK_CHECK (connection); \
75 #define CONNECTION_UNLOCK(connection) _dbus_connection_unlock (connection)
77 #define SLOTS_LOCK(connection) do { \
78 _dbus_rmutex_lock ((connection)->slot_mutex); \
81 #define SLOTS_UNLOCK(connection) do { \
82 _dbus_rmutex_unlock ((connection)->slot_mutex); \
85 #define DISPATCH_STATUS_NAME(s) \
86 ((s) == DBUS_DISPATCH_COMPLETE ? "complete" : \
87 (s) == DBUS_DISPATCH_DATA_REMAINS ? "data remains" : \
88 (s) == DBUS_DISPATCH_NEED_MEMORY ? "need memory" : \
92 * @defgroup DBusConnection DBusConnection
94 * @brief Connection to another application
96 * A DBusConnection represents a connection to another
97 * application. Messages can be sent and received via this connection.
98 * The other application may be a message bus; for convenience, the
99 * function dbus_bus_get() is provided to automatically open a
100 * connection to the well-known message buses.
102 * In brief a DBusConnection is a message queue associated with some
103 * message transport mechanism such as a socket. The connection
104 * maintains a queue of incoming messages and a queue of outgoing
107 * Several functions use the following terms:
109 * <li><b>read</b> means to fill the incoming message queue by reading from the socket</li>
110 * <li><b>write</b> means to drain the outgoing queue by writing to the socket</li>
111 * <li><b>dispatch</b> means to drain the incoming queue by invoking application-provided message handlers</li>
114 * The function dbus_connection_read_write_dispatch() for example does all
115 * three of these things, offering a simple alternative to a main loop.
117 * In an application with a main loop, the read/write/dispatch
118 * operations are usually separate.
120 * The connection provides #DBusWatch and #DBusTimeout objects to
121 * the main loop. These are used to know when reading, writing, or
122 * dispatching should be performed.
124 * Incoming messages are processed
125 * by calling dbus_connection_dispatch(). dbus_connection_dispatch()
126 * runs any handlers registered for the topmost message in the message
127 * queue, then discards the message, then returns.
129 * dbus_connection_get_dispatch_status() indicates whether
130 * messages are currently in the queue that need dispatching.
131 * dbus_connection_set_dispatch_status_function() allows
132 * you to set a function to be used to monitor the dispatch status.
134 * If you're using GLib or Qt add-on libraries for D-Bus, there are
135 * special convenience APIs in those libraries that hide
136 * all the details of dispatch and watch/timeout monitoring.
137 * For example, dbus_connection_setup_with_g_main().
139 * If you aren't using these add-on libraries, but want to process
140 * messages asynchronously, you must manually call
141 * dbus_connection_set_dispatch_status_function(),
142 * dbus_connection_set_watch_functions(),
143 * dbus_connection_set_timeout_functions() providing appropriate
144 * functions to integrate the connection with your application's main
145 * loop. This can be tricky to get right; main loops are not simple.
147 * If you don't need to be asynchronous, you can ignore #DBusWatch,
148 * #DBusTimeout, and dbus_connection_dispatch(). Instead,
149 * dbus_connection_read_write_dispatch() can be used.
151 * Or, in <em>very</em> simple applications,
152 * dbus_connection_pop_message() may be all you need, allowing you to
153 * avoid setting up any handler functions (see
154 * dbus_connection_add_filter(),
155 * dbus_connection_register_object_path() for more on handlers).
157 * When you use dbus_connection_send() or one of its variants to send
158 * a message, the message is added to the outgoing queue. It's
159 * actually written to the network later; either in
160 * dbus_watch_handle() invoked by your main loop, or in
161 * dbus_connection_flush() which blocks until it can write out the
162 * entire outgoing queue. The GLib/Qt add-on libraries again
163 * handle the details here for you by setting up watch functions.
165 * When a connection is disconnected, you are guaranteed to get a
166 * signal "Disconnected" from the interface
167 * #DBUS_INTERFACE_LOCAL, path
170 * You may not drop the last reference to a #DBusConnection
171 * until that connection has been disconnected.
173 * You may dispatch the unprocessed incoming message queue even if the
174 * connection is disconnected. However, "Disconnected" will always be
175 * the last message in the queue (obviously no messages are received
176 * after disconnection).
178 * After calling dbus_threads_init(), #DBusConnection has thread
179 * locks and drops them when invoking user callbacks, so in general is
180 * transparently threadsafe. However, #DBusMessage does NOT have
181 * thread locks; you must not send the same message to multiple
182 * #DBusConnection if those connections will be used from different threads,
185 * Also, if you dispatch or pop messages from multiple threads, it
186 * may work in the sense that it won't crash, but it's tough to imagine
187 * sane results; it will be completely unpredictable which messages
188 * go to which threads.
190 * It's recommended to dispatch from a single thread.
192 * The most useful function to call from multiple threads at once
193 * is dbus_connection_send_with_reply_and_block(). That is,
194 * multiple threads can make method calls at the same time.
196 * If you aren't using threads, you can use a main loop and
197 * dbus_pending_call_set_notify() to achieve a similar result.
201 * @defgroup DBusConnectionInternals DBusConnection implementation details
202 * @ingroup DBusInternals
203 * @brief Implementation details of DBusConnection
208 #ifdef DBUS_ENABLE_VERBOSE_MODE
210 _dbus_connection_trace_ref (DBusConnection *connection,
215 static int enabled = -1;
217 _dbus_trace_ref ("DBusConnection", connection, old_refcount, new_refcount,
218 why, "DBUS_CONNECTION_TRACE", &enabled);
221 #define _dbus_connection_trace_ref(c,o,n,w) \
230 * Internal struct representing a message filter function
232 typedef struct DBusMessageFilter DBusMessageFilter;
235 * Internal struct representing a message filter function
237 struct DBusMessageFilter
239 DBusAtomic refcount; /**< Reference count */
240 DBusHandleMessageFunction function; /**< Function to call to filter */
241 void *user_data; /**< User data for the function */
242 DBusFreeFunction free_user_data_function; /**< Function to free the user data */
247 * Internals of DBusPreallocatedSend
249 struct DBusPreallocatedSend
251 DBusConnection *connection; /**< Connection we'd send the message to */
252 DBusList *queue_link; /**< Preallocated link in the queue */
253 DBusList *counter_link; /**< Preallocated link in the resource counter */
256 #if HAVE_DECL_MSG_NOSIGNAL
257 static dbus_bool_t _dbus_modify_sigpipe = FALSE;
259 static dbus_bool_t _dbus_modify_sigpipe = TRUE;
263 * Implementation details of DBusConnection. All fields are private.
265 struct DBusConnection
267 DBusAtomic refcount; /**< Reference count. */
269 DBusRMutex *mutex; /**< Lock on the entire DBusConnection */
271 DBusCMutex *dispatch_mutex; /**< Protects dispatch_acquired */
272 DBusCondVar *dispatch_cond; /**< Notify when dispatch_acquired is available */
273 DBusCMutex *io_path_mutex; /**< Protects io_path_acquired */
274 DBusCondVar *io_path_cond; /**< Notify when io_path_acquired is available */
276 DBusList *outgoing_messages; /**< Queue of messages we need to send, send the end of the list first. */
277 DBusList *incoming_messages; /**< Queue of messages we have received, end of the list received most recently. */
278 DBusList *expired_messages; /**< Messages that will be released when we next unlock. */
280 DBusMessage *message_borrowed; /**< Filled in if the first incoming message has been borrowed;
281 * dispatch_acquired will be set by the borrower
284 int n_outgoing; /**< Length of outgoing queue. */
285 int n_incoming; /**< Length of incoming queue. */
287 DBusCounter *outgoing_counter; /**< Counts size of outgoing messages. */
289 DBusTransport *transport; /**< Object that sends/receives messages over network. */
290 DBusWatchList *watches; /**< Stores active watches. */
291 DBusTimeoutList *timeouts; /**< Stores active timeouts. */
293 DBusList *filter_list; /**< List of filters. */
295 DBusRMutex *slot_mutex; /**< Lock on slot_list so overall connection lock need not be taken */
296 DBusDataSlotList slot_list; /**< Data stored by allocated integer ID */
298 DBusHashTable *pending_replies; /**< Hash of message serials to #DBusPendingCall. */
300 dbus_uint32_t client_serial; /**< Client serial. Increments each time a message is sent */
301 DBusList *disconnect_message_link; /**< Preallocated list node for queueing the disconnection message */
303 DBusWakeupMainFunction wakeup_main_function; /**< Function to wake up the mainloop */
304 void *wakeup_main_data; /**< Application data for wakeup_main_function */
305 DBusFreeFunction free_wakeup_main_data; /**< free wakeup_main_data */
307 DBusDispatchStatusFunction dispatch_status_function; /**< Function on dispatch status changes */
308 void *dispatch_status_data; /**< Application data for dispatch_status_function */
309 DBusFreeFunction free_dispatch_status_data; /**< free dispatch_status_data */
311 DBusDispatchStatus last_dispatch_status; /**< The last dispatch status we reported to the application. */
313 DBusObjectTree *objects; /**< Object path handlers registered with this connection */
315 char *server_guid; /**< GUID of server if we are in shared_connections, #NULL if server GUID is unknown or connection is private */
317 /* These two MUST be bools and not bitfields, because they are protected by a separate lock
318 * from connection->mutex and all bitfields in a word have to be read/written together.
319 * So you can't have a different lock for different bitfields in the same word.
321 dbus_bool_t dispatch_acquired; /**< Someone has dispatch path (can drain incoming queue) */
322 dbus_bool_t io_path_acquired; /**< Someone has transport io path (can use the transport to read/write messages) */
324 unsigned int shareable : 1; /**< #TRUE if libdbus owns a reference to the connection and can return it from dbus_connection_open() more than once */
326 unsigned int exit_on_disconnect : 1; /**< If #TRUE, exit after handling disconnect signal */
328 unsigned int route_peer_messages : 1; /**< If #TRUE, if org.freedesktop.DBus.Peer messages have a bus name, don't handle them automatically */
330 unsigned int disconnected_message_arrived : 1; /**< We popped or are dispatching the disconnected message.
331 * if the disconnect_message_link is NULL then we queued it, but
332 * this flag is whether it got to the head of the queue.
334 unsigned int disconnected_message_processed : 1; /**< We did our default handling of the disconnected message,
335 * such as closing the connection.
338 #ifndef DBUS_DISABLE_CHECKS
339 unsigned int have_connection_lock : 1; /**< Used to check locking */
342 #ifndef DBUS_DISABLE_CHECKS
343 int generation; /**< _dbus_current_generation that should correspond to this connection */
347 static DBusDispatchStatus _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection);
348 static void _dbus_connection_update_dispatch_status_and_unlock (DBusConnection *connection,
349 DBusDispatchStatus new_status);
350 static void _dbus_connection_last_unref (DBusConnection *connection);
351 static void _dbus_connection_acquire_dispatch (DBusConnection *connection);
352 static void _dbus_connection_release_dispatch (DBusConnection *connection);
353 static DBusDispatchStatus _dbus_connection_flush_unlocked (DBusConnection *connection);
354 static void _dbus_connection_close_possibly_shared_and_unlock (DBusConnection *connection);
355 static dbus_bool_t _dbus_connection_get_is_connected_unlocked (DBusConnection *connection);
356 static dbus_bool_t _dbus_connection_peek_for_reply_unlocked (DBusConnection *connection,
357 dbus_uint32_t client_serial);
359 static DBusMessageFilter *
360 _dbus_message_filter_ref (DBusMessageFilter *filter)
362 #ifdef DBUS_DISABLE_ASSERT
363 _dbus_atomic_inc (&filter->refcount);
365 dbus_int32_t old_value;
367 old_value = _dbus_atomic_inc (&filter->refcount);
368 _dbus_assert (old_value > 0);
375 _dbus_message_filter_unref (DBusMessageFilter *filter)
377 dbus_int32_t old_value;
379 old_value = _dbus_atomic_dec (&filter->refcount);
380 _dbus_assert (old_value > 0);
384 if (filter->free_user_data_function)
385 (* filter->free_user_data_function) (filter->user_data);
392 * Acquires the connection lock.
394 * @param connection the connection.
397 _dbus_connection_lock (DBusConnection *connection)
399 CONNECTION_LOCK (connection);
403 * Releases the connection lock.
405 * @param connection the connection.
408 _dbus_connection_unlock (DBusConnection *connection)
410 DBusList *expired_messages;
415 _dbus_verbose ("UNLOCK\n");
418 /* If we had messages that expired (fell off the incoming or outgoing
419 * queues) while we were locked, actually release them now */
420 expired_messages = connection->expired_messages;
421 connection->expired_messages = NULL;
423 RELEASING_LOCK_CHECK (connection);
424 _dbus_rmutex_unlock (connection->mutex);
426 for (iter = _dbus_list_pop_first_link (&expired_messages);
428 iter = _dbus_list_pop_first_link (&expired_messages))
430 DBusMessage *message = iter->data;
432 dbus_message_unref (message);
433 _dbus_list_free_link (iter);
438 * Wakes up the main loop if it is sleeping
439 * Needed if we're e.g. queueing outgoing messages
440 * on a thread while the mainloop sleeps.
442 * @param connection the connection.
445 _dbus_connection_wakeup_mainloop (DBusConnection *connection)
447 if (connection->wakeup_main_function)
448 (*connection->wakeup_main_function) (connection->wakeup_main_data);
451 #ifdef DBUS_BUILD_TESTS
453 * Gets the locks so we can examine them
455 * @param connection the connection.
456 * @param mutex_loc return for the location of the main mutex pointer
457 * @param dispatch_mutex_loc return location of the dispatch mutex pointer
458 * @param io_path_mutex_loc return location of the io_path mutex pointer
459 * @param dispatch_cond_loc return location of the dispatch conditional
461 * @param io_path_cond_loc return location of the io_path conditional
465 _dbus_connection_test_get_locks (DBusConnection *connection,
466 DBusMutex **mutex_loc,
467 DBusMutex **dispatch_mutex_loc,
468 DBusMutex **io_path_mutex_loc,
469 DBusCondVar **dispatch_cond_loc,
470 DBusCondVar **io_path_cond_loc)
472 *mutex_loc = (DBusMutex *) connection->mutex;
473 *dispatch_mutex_loc = (DBusMutex *) connection->dispatch_mutex;
474 *io_path_mutex_loc = (DBusMutex *) connection->io_path_mutex;
475 *dispatch_cond_loc = connection->dispatch_cond;
476 *io_path_cond_loc = connection->io_path_cond;
481 * Adds a message-containing list link to the incoming message queue,
482 * taking ownership of the link and the message's current refcount.
483 * Cannot fail due to lack of memory.
485 * @param connection the connection.
486 * @param link the message link to queue.
489 _dbus_connection_queue_received_message_link (DBusConnection *connection,
492 DBusPendingCall *pending;
493 dbus_uint32_t reply_serial;
494 DBusMessage *message;
496 _dbus_assert (_dbus_transport_get_is_authenticated (connection->transport));
498 _dbus_list_append_link (&connection->incoming_messages,
500 message = link->data;
502 /* If this is a reply we're waiting on, remove timeout for it */
503 reply_serial = dbus_message_get_reply_serial (message);
504 if (reply_serial != 0)
506 pending = _dbus_hash_table_lookup_int (connection->pending_replies,
510 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
511 _dbus_connection_remove_timeout_unlocked (connection,
512 _dbus_pending_call_get_timeout_unlocked (pending));
514 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
520 connection->n_incoming += 1;
522 _dbus_connection_wakeup_mainloop (connection);
524 _dbus_verbose ("Message %p (%s %s %s %s '%s' reply to %u) added to incoming queue %p, %d incoming\n",
526 dbus_message_type_to_string (dbus_message_get_type (message)),
527 dbus_message_get_path (message) ?
528 dbus_message_get_path (message) :
530 dbus_message_get_interface (message) ?
531 dbus_message_get_interface (message) :
533 dbus_message_get_member (message) ?
534 dbus_message_get_member (message) :
536 dbus_message_get_signature (message),
537 dbus_message_get_reply_serial (message),
539 connection->n_incoming);
541 _dbus_message_trace_ref (message, -1, -1,
542 "_dbus_conection_queue_received_message_link");
546 * Adds a link + message to the incoming message queue.
547 * Can't fail. Takes ownership of both link and message.
549 * @param connection the connection.
550 * @param link the list node and message to queue.
554 _dbus_connection_queue_synthesized_message_link (DBusConnection *connection,
557 HAVE_LOCK_CHECK (connection);
559 _dbus_list_append_link (&connection->incoming_messages, link);
561 connection->n_incoming += 1;
563 _dbus_connection_wakeup_mainloop (connection);
565 _dbus_message_trace_ref (link->data, -1, -1,
566 "_dbus_connection_queue_synthesized_message_link");
568 _dbus_verbose ("Synthesized message %p added to incoming queue %p, %d incoming\n",
569 link->data, connection, connection->n_incoming);
574 * Checks whether there are messages in the outgoing message queue.
575 * Called with connection lock held.
577 * @param connection the connection.
578 * @returns #TRUE if the outgoing queue is non-empty.
581 _dbus_connection_has_messages_to_send_unlocked (DBusConnection *connection)
583 HAVE_LOCK_CHECK (connection);
584 return connection->outgoing_messages != NULL;
588 * Checks whether there are messages in the outgoing message queue.
589 * Use dbus_connection_flush() to block until all outgoing
590 * messages have been written to the underlying transport
591 * (such as a socket).
593 * @param connection the connection.
594 * @returns #TRUE if the outgoing queue is non-empty.
597 dbus_connection_has_messages_to_send (DBusConnection *connection)
601 _dbus_return_val_if_fail (connection != NULL, FALSE);
603 CONNECTION_LOCK (connection);
604 v = _dbus_connection_has_messages_to_send_unlocked (connection);
605 CONNECTION_UNLOCK (connection);
611 * Gets the next outgoing message. The message remains in the
612 * queue, and the caller does not own a reference to it.
614 * @param connection the connection.
615 * @returns the message to be sent.
618 _dbus_connection_get_message_to_send (DBusConnection *connection)
620 HAVE_LOCK_CHECK (connection);
622 return _dbus_list_get_last (&connection->outgoing_messages);
626 * Notifies the connection that a message has been sent, so the
627 * message can be removed from the outgoing queue.
628 * Called with the connection lock held.
630 * @param connection the connection.
631 * @param message the message that was sent.
634 _dbus_connection_message_sent_unlocked (DBusConnection *connection,
635 DBusMessage *message)
639 HAVE_LOCK_CHECK (connection);
641 /* This can be called before we even complete authentication, since
642 * it's called on disconnect to clean up the outgoing queue.
643 * It's also called as we successfully send each message.
646 link = _dbus_list_get_last_link (&connection->outgoing_messages);
647 _dbus_assert (link != NULL);
648 _dbus_assert (link->data == message);
650 _dbus_list_unlink (&connection->outgoing_messages,
652 _dbus_list_prepend_link (&connection->expired_messages, link);
654 connection->n_outgoing -= 1;
656 _dbus_verbose ("Message %p (%s %s %s %s '%s') removed from outgoing queue %p, %d left to send\n",
658 dbus_message_type_to_string (dbus_message_get_type (message)),
659 dbus_message_get_path (message) ?
660 dbus_message_get_path (message) :
662 dbus_message_get_interface (message) ?
663 dbus_message_get_interface (message) :
665 dbus_message_get_member (message) ?
666 dbus_message_get_member (message) :
668 dbus_message_get_signature (message),
669 connection, connection->n_outgoing);
671 /* It's OK that in principle we call the notify function, because for the
672 * outgoing limit, there isn't one */
673 _dbus_message_remove_counter (message, connection->outgoing_counter);
675 /* The message will actually be unreffed when we unlock */
678 /** Function to be called in protected_change_watch() with refcount held */
679 typedef dbus_bool_t (* DBusWatchAddFunction) (DBusWatchList *list,
681 /** Function to be called in protected_change_watch() with refcount held */
682 typedef void (* DBusWatchRemoveFunction) (DBusWatchList *list,
684 /** Function to be called in protected_change_watch() with refcount held */
685 typedef void (* DBusWatchToggleFunction) (DBusWatchList *list,
687 dbus_bool_t enabled);
690 protected_change_watch (DBusConnection *connection,
692 DBusWatchAddFunction add_function,
693 DBusWatchRemoveFunction remove_function,
694 DBusWatchToggleFunction toggle_function,
699 HAVE_LOCK_CHECK (connection);
701 /* The original purpose of protected_change_watch() was to hold a
702 * ref on the connection while dropping the connection lock, then
703 * calling out to the app. This was a broken hack that did not
704 * work, since the connection was in a hosed state (no WatchList
705 * field) while calling out.
707 * So for now we'll just keep the lock while calling out. This means
708 * apps are not allowed to call DBusConnection methods inside a
709 * watch function or they will deadlock.
711 * The "real fix" is to use the _and_unlock() pattern found
712 * elsewhere in the code, to defer calling out to the app until
713 * we're about to drop locks and return flow of control to the app
716 * See http://lists.freedesktop.org/archives/dbus/2007-July/thread.html#8144
719 if (connection->watches)
722 retval = (* add_function) (connection->watches, watch);
723 else if (remove_function)
726 (* remove_function) (connection->watches, watch);
731 (* toggle_function) (connection->watches, watch, enabled);
741 * Adds a watch using the connection's DBusAddWatchFunction if
742 * available. Otherwise records the watch to be added when said
743 * function is available. Also re-adds the watch if the
744 * DBusAddWatchFunction changes. May fail due to lack of memory.
745 * Connection lock should be held when calling this.
747 * @param connection the connection.
748 * @param watch the watch to add.
749 * @returns #TRUE on success.
752 _dbus_connection_add_watch_unlocked (DBusConnection *connection,
755 return protected_change_watch (connection, watch,
756 _dbus_watch_list_add_watch,
761 * Removes a watch using the connection's DBusRemoveWatchFunction
762 * if available. It's an error to call this function on a watch
763 * that was not previously added.
764 * Connection lock should be held when calling this.
766 * @param connection the connection.
767 * @param watch the watch to remove.
770 _dbus_connection_remove_watch_unlocked (DBusConnection *connection,
773 protected_change_watch (connection, watch,
775 _dbus_watch_list_remove_watch,
780 * Toggles a watch and notifies app via connection's
781 * DBusWatchToggledFunction if available. It's an error to call this
782 * function on a watch that was not previously added.
783 * Connection lock should be held when calling this.
785 * @param connection the connection.
786 * @param watch the watch to toggle.
787 * @param enabled whether to enable or disable
790 _dbus_connection_toggle_watch_unlocked (DBusConnection *connection,
794 _dbus_assert (watch != NULL);
796 protected_change_watch (connection, watch,
798 _dbus_watch_list_toggle_watch,
802 /** Function to be called in protected_change_timeout() with refcount held */
803 typedef dbus_bool_t (* DBusTimeoutAddFunction) (DBusTimeoutList *list,
804 DBusTimeout *timeout);
805 /** Function to be called in protected_change_timeout() with refcount held */
806 typedef void (* DBusTimeoutRemoveFunction) (DBusTimeoutList *list,
807 DBusTimeout *timeout);
808 /** Function to be called in protected_change_timeout() with refcount held */
809 typedef void (* DBusTimeoutToggleFunction) (DBusTimeoutList *list,
810 DBusTimeout *timeout,
811 dbus_bool_t enabled);
814 protected_change_timeout (DBusConnection *connection,
815 DBusTimeout *timeout,
816 DBusTimeoutAddFunction add_function,
817 DBusTimeoutRemoveFunction remove_function,
818 DBusTimeoutToggleFunction toggle_function,
823 HAVE_LOCK_CHECK (connection);
825 /* The original purpose of protected_change_timeout() was to hold a
826 * ref on the connection while dropping the connection lock, then
827 * calling out to the app. This was a broken hack that did not
828 * work, since the connection was in a hosed state (no TimeoutList
829 * field) while calling out.
831 * So for now we'll just keep the lock while calling out. This means
832 * apps are not allowed to call DBusConnection methods inside a
833 * timeout function or they will deadlock.
835 * The "real fix" is to use the _and_unlock() pattern found
836 * elsewhere in the code, to defer calling out to the app until
837 * we're about to drop locks and return flow of control to the app
840 * See http://lists.freedesktop.org/archives/dbus/2007-July/thread.html#8144
843 if (connection->timeouts)
846 retval = (* add_function) (connection->timeouts, timeout);
847 else if (remove_function)
850 (* remove_function) (connection->timeouts, timeout);
855 (* toggle_function) (connection->timeouts, timeout, enabled);
864 * Adds a timeout using the connection's DBusAddTimeoutFunction if
865 * available. Otherwise records the timeout to be added when said
866 * function is available. Also re-adds the timeout if the
867 * DBusAddTimeoutFunction changes. May fail due to lack of memory.
868 * The timeout will fire repeatedly until removed.
869 * Connection lock should be held when calling this.
871 * @param connection the connection.
872 * @param timeout the timeout to add.
873 * @returns #TRUE on success.
876 _dbus_connection_add_timeout_unlocked (DBusConnection *connection,
877 DBusTimeout *timeout)
879 return protected_change_timeout (connection, timeout,
880 _dbus_timeout_list_add_timeout,
885 * Removes a timeout using the connection's DBusRemoveTimeoutFunction
886 * if available. It's an error to call this function on a timeout
887 * that was not previously added.
888 * Connection lock should be held when calling this.
890 * @param connection the connection.
891 * @param timeout the timeout to remove.
894 _dbus_connection_remove_timeout_unlocked (DBusConnection *connection,
895 DBusTimeout *timeout)
897 protected_change_timeout (connection, timeout,
899 _dbus_timeout_list_remove_timeout,
904 * Toggles a timeout and notifies app via connection's
905 * DBusTimeoutToggledFunction if available. It's an error to call this
906 * function on a timeout that was not previously added.
907 * Connection lock should be held when calling this.
909 * @param connection the connection.
910 * @param timeout the timeout to toggle.
911 * @param enabled whether to enable or disable
914 _dbus_connection_toggle_timeout_unlocked (DBusConnection *connection,
915 DBusTimeout *timeout,
918 protected_change_timeout (connection, timeout,
920 _dbus_timeout_list_toggle_timeout,
925 _dbus_connection_attach_pending_call_unlocked (DBusConnection *connection,
926 DBusPendingCall *pending)
928 dbus_uint32_t reply_serial;
929 DBusTimeout *timeout;
931 HAVE_LOCK_CHECK (connection);
933 reply_serial = _dbus_pending_call_get_reply_serial_unlocked (pending);
935 _dbus_assert (reply_serial != 0);
937 timeout = _dbus_pending_call_get_timeout_unlocked (pending);
941 if (!_dbus_connection_add_timeout_unlocked (connection, timeout))
944 if (!_dbus_hash_table_insert_int (connection->pending_replies,
948 _dbus_connection_remove_timeout_unlocked (connection, timeout);
950 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
951 HAVE_LOCK_CHECK (connection);
955 _dbus_pending_call_set_timeout_added_unlocked (pending, TRUE);
959 if (!_dbus_hash_table_insert_int (connection->pending_replies,
963 HAVE_LOCK_CHECK (connection);
968 _dbus_pending_call_ref_unlocked (pending);
970 HAVE_LOCK_CHECK (connection);
976 free_pending_call_on_hash_removal (void *data)
978 DBusPendingCall *pending;
979 DBusConnection *connection;
986 connection = _dbus_pending_call_get_connection_unlocked (pending);
988 HAVE_LOCK_CHECK (connection);
990 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
992 _dbus_connection_remove_timeout_unlocked (connection,
993 _dbus_pending_call_get_timeout_unlocked (pending));
995 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
998 /* FIXME 1.0? this is sort of dangerous and undesirable to drop the lock
999 * here, but the pending call finalizer could in principle call out to
1000 * application code so we pretty much have to... some larger code reorg
1003 _dbus_connection_ref_unlocked (connection);
1004 _dbus_pending_call_unref_and_unlock (pending);
1005 CONNECTION_LOCK (connection);
1006 _dbus_connection_unref_unlocked (connection);
1010 _dbus_connection_detach_pending_call_unlocked (DBusConnection *connection,
1011 DBusPendingCall *pending)
1013 /* This ends up unlocking to call the pending call finalizer, which is unexpected to
1016 _dbus_hash_table_remove_int (connection->pending_replies,
1017 _dbus_pending_call_get_reply_serial_unlocked (pending));
1021 _dbus_connection_detach_pending_call_and_unlock (DBusConnection *connection,
1022 DBusPendingCall *pending)
1024 /* The idea here is to avoid finalizing the pending call
1025 * with the lock held, since there's a destroy notifier
1026 * in pending call that goes out to application code.
1028 * There's an extra unlock inside the hash table
1029 * "free pending call" function FIXME...
1031 _dbus_pending_call_ref_unlocked (pending);
1032 _dbus_hash_table_remove_int (connection->pending_replies,
1033 _dbus_pending_call_get_reply_serial_unlocked (pending));
1035 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
1036 _dbus_connection_remove_timeout_unlocked (connection,
1037 _dbus_pending_call_get_timeout_unlocked (pending));
1039 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
1041 _dbus_pending_call_unref_and_unlock (pending);
1045 * Removes a pending call from the connection, such that
1046 * the pending reply will be ignored. May drop the last
1047 * reference to the pending call.
1049 * @param connection the connection
1050 * @param pending the pending call
1053 _dbus_connection_remove_pending_call (DBusConnection *connection,
1054 DBusPendingCall *pending)
1056 CONNECTION_LOCK (connection);
1057 _dbus_connection_detach_pending_call_and_unlock (connection, pending);
1061 * Acquire the transporter I/O path. This must be done before
1062 * doing any I/O in the transporter. May sleep and drop the
1063 * IO path mutex while waiting for the I/O path.
1065 * @param connection the connection.
1066 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
1067 * @returns TRUE if the I/O path was acquired.
1070 _dbus_connection_acquire_io_path (DBusConnection *connection,
1071 int timeout_milliseconds)
1073 dbus_bool_t we_acquired;
1075 HAVE_LOCK_CHECK (connection);
1077 /* We don't want the connection to vanish */
1078 _dbus_connection_ref_unlocked (connection);
1080 /* We will only touch io_path_acquired which is protected by our mutex */
1081 CONNECTION_UNLOCK (connection);
1083 _dbus_verbose ("locking io_path_mutex\n");
1084 _dbus_cmutex_lock (connection->io_path_mutex);
1086 _dbus_verbose ("start connection->io_path_acquired = %d timeout = %d\n",
1087 connection->io_path_acquired, timeout_milliseconds);
1089 we_acquired = FALSE;
1091 if (connection->io_path_acquired)
1093 if (timeout_milliseconds != -1)
1095 _dbus_verbose ("waiting %d for IO path to be acquirable\n",
1096 timeout_milliseconds);
1098 if (!_dbus_condvar_wait_timeout (connection->io_path_cond,
1099 connection->io_path_mutex,
1100 timeout_milliseconds))
1102 /* We timed out before anyone signaled. */
1103 /* (writing the loop to handle the !timedout case by
1104 * waiting longer if needed is a pain since dbus
1105 * wraps pthread_cond_timedwait to take a relative
1106 * time instead of absolute, something kind of stupid
1107 * on our part. for now it doesn't matter, we will just
1108 * end up back here eventually.)
1114 while (connection->io_path_acquired)
1116 _dbus_verbose ("waiting for IO path to be acquirable\n");
1117 _dbus_condvar_wait (connection->io_path_cond,
1118 connection->io_path_mutex);
1123 if (!connection->io_path_acquired)
1126 connection->io_path_acquired = TRUE;
1129 _dbus_verbose ("end connection->io_path_acquired = %d we_acquired = %d\n",
1130 connection->io_path_acquired, we_acquired);
1132 _dbus_verbose ("unlocking io_path_mutex\n");
1133 _dbus_cmutex_unlock (connection->io_path_mutex);
1135 CONNECTION_LOCK (connection);
1137 HAVE_LOCK_CHECK (connection);
1139 _dbus_connection_unref_unlocked (connection);
1145 * Release the I/O path when you're done with it. Only call
1146 * after you've acquired the I/O. Wakes up at most one thread
1147 * currently waiting to acquire the I/O path.
1149 * @param connection the connection.
1152 _dbus_connection_release_io_path (DBusConnection *connection)
1154 HAVE_LOCK_CHECK (connection);
1156 _dbus_verbose ("locking io_path_mutex\n");
1157 _dbus_cmutex_lock (connection->io_path_mutex);
1159 _dbus_assert (connection->io_path_acquired);
1161 _dbus_verbose ("start connection->io_path_acquired = %d\n",
1162 connection->io_path_acquired);
1164 connection->io_path_acquired = FALSE;
1165 _dbus_condvar_wake_one (connection->io_path_cond);
1167 _dbus_verbose ("unlocking io_path_mutex\n");
1168 _dbus_cmutex_unlock (connection->io_path_mutex);
1172 * Queues incoming messages and sends outgoing messages for this
1173 * connection, optionally blocking in the process. Each call to
1174 * _dbus_connection_do_iteration_unlocked() will call select() or poll() one
1175 * time and then read or write data if possible.
1177 * The purpose of this function is to be able to flush outgoing
1178 * messages or queue up incoming messages without returning
1179 * control to the application and causing reentrancy weirdness.
1181 * The flags parameter allows you to specify whether to
1182 * read incoming messages, write outgoing messages, or both,
1183 * and whether to block if no immediate action is possible.
1185 * The timeout_milliseconds parameter does nothing unless the
1186 * iteration is blocking.
1188 * If there are no outgoing messages and DBUS_ITERATION_DO_READING
1189 * wasn't specified, then it's impossible to block, even if
1190 * you specify DBUS_ITERATION_BLOCK; in that case the function
1191 * returns immediately.
1193 * If pending is not NULL then a check is made if the pending call
1194 * is completed after the io path has been required. If the call
1195 * has been completed nothing is done. This must be done since
1196 * the _dbus_connection_acquire_io_path releases the connection
1199 * Called with connection lock held.
1201 * @param connection the connection.
1202 * @param pending the pending call that should be checked or NULL
1203 * @param flags iteration flags.
1204 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
1207 _dbus_connection_do_iteration_unlocked (DBusConnection *connection,
1208 DBusPendingCall *pending,
1210 int timeout_milliseconds)
1212 _dbus_verbose ("start\n");
1214 HAVE_LOCK_CHECK (connection);
1216 if (connection->n_outgoing == 0)
1217 flags &= ~DBUS_ITERATION_DO_WRITING;
1219 if (_dbus_connection_acquire_io_path (connection,
1220 (flags & DBUS_ITERATION_BLOCK) ? timeout_milliseconds : 0))
1222 HAVE_LOCK_CHECK (connection);
1224 if ( (pending != NULL) && _dbus_pending_call_get_completed_unlocked(pending))
1226 _dbus_verbose ("pending call completed while acquiring I/O path");
1228 else if ( (pending != NULL) &&
1229 _dbus_connection_peek_for_reply_unlocked (connection,
1230 _dbus_pending_call_get_reply_serial_unlocked (pending)))
1232 _dbus_verbose ("pending call completed while acquiring I/O path (reply found in queue)");
1236 _dbus_transport_do_iteration (connection->transport,
1237 flags, timeout_milliseconds);
1240 _dbus_connection_release_io_path (connection);
1243 HAVE_LOCK_CHECK (connection);
1245 _dbus_verbose ("end\n");
1249 * Creates a new connection for the given transport. A transport
1250 * represents a message stream that uses some concrete mechanism, such
1251 * as UNIX domain sockets. May return #NULL if insufficient
1252 * memory exists to create the connection.
1254 * @param transport the transport.
1255 * @returns the new connection, or #NULL on failure.
1258 _dbus_connection_new_for_transport (DBusTransport *transport)
1260 DBusConnection *connection;
1261 DBusWatchList *watch_list;
1262 DBusTimeoutList *timeout_list;
1263 DBusHashTable *pending_replies;
1264 DBusList *disconnect_link;
1265 DBusMessage *disconnect_message;
1266 DBusCounter *outgoing_counter;
1267 DBusObjectTree *objects;
1271 pending_replies = NULL;
1272 timeout_list = NULL;
1273 disconnect_link = NULL;
1274 disconnect_message = NULL;
1275 outgoing_counter = NULL;
1278 watch_list = _dbus_watch_list_new ();
1279 if (watch_list == NULL)
1282 timeout_list = _dbus_timeout_list_new ();
1283 if (timeout_list == NULL)
1287 _dbus_hash_table_new (DBUS_HASH_INT,
1289 (DBusFreeFunction)free_pending_call_on_hash_removal);
1290 if (pending_replies == NULL)
1293 connection = dbus_new0 (DBusConnection, 1);
1294 if (connection == NULL)
1297 _dbus_rmutex_new_at_location (&connection->mutex);
1298 if (connection->mutex == NULL)
1301 _dbus_cmutex_new_at_location (&connection->io_path_mutex);
1302 if (connection->io_path_mutex == NULL)
1305 _dbus_cmutex_new_at_location (&connection->dispatch_mutex);
1306 if (connection->dispatch_mutex == NULL)
1309 _dbus_condvar_new_at_location (&connection->dispatch_cond);
1310 if (connection->dispatch_cond == NULL)
1313 _dbus_condvar_new_at_location (&connection->io_path_cond);
1314 if (connection->io_path_cond == NULL)
1317 _dbus_rmutex_new_at_location (&connection->slot_mutex);
1318 if (connection->slot_mutex == NULL)
1321 disconnect_message = dbus_message_new_signal (DBUS_PATH_LOCAL,
1322 DBUS_INTERFACE_LOCAL,
1325 if (disconnect_message == NULL)
1328 disconnect_link = _dbus_list_alloc_link (disconnect_message);
1329 if (disconnect_link == NULL)
1332 outgoing_counter = _dbus_counter_new ();
1333 if (outgoing_counter == NULL)
1336 objects = _dbus_object_tree_new (connection);
1337 if (objects == NULL)
1340 if (_dbus_modify_sigpipe)
1341 _dbus_disable_sigpipe ();
1343 /* initialized to 0: use atomic op to avoid mixing atomic and non-atomic */
1344 _dbus_atomic_inc (&connection->refcount);
1345 connection->transport = transport;
1346 connection->watches = watch_list;
1347 connection->timeouts = timeout_list;
1348 connection->pending_replies = pending_replies;
1349 connection->outgoing_counter = outgoing_counter;
1350 connection->filter_list = NULL;
1351 connection->last_dispatch_status = DBUS_DISPATCH_COMPLETE; /* so we're notified first time there's data */
1352 connection->objects = objects;
1353 connection->exit_on_disconnect = FALSE;
1354 connection->shareable = FALSE;
1355 connection->route_peer_messages = FALSE;
1356 connection->disconnected_message_arrived = FALSE;
1357 connection->disconnected_message_processed = FALSE;
1359 #ifndef DBUS_DISABLE_CHECKS
1360 connection->generation = _dbus_current_generation;
1363 _dbus_data_slot_list_init (&connection->slot_list);
1365 connection->client_serial = 1;
1367 connection->disconnect_message_link = disconnect_link;
1369 CONNECTION_LOCK (connection);
1371 if (!_dbus_transport_set_connection (transport, connection))
1373 CONNECTION_UNLOCK (connection);
1378 _dbus_transport_ref (transport);
1380 CONNECTION_UNLOCK (connection);
1382 _dbus_connection_trace_ref (connection, 0, 1, "new_for_transport");
1386 if (disconnect_message != NULL)
1387 dbus_message_unref (disconnect_message);
1389 if (disconnect_link != NULL)
1390 _dbus_list_free_link (disconnect_link);
1392 if (connection != NULL)
1394 _dbus_condvar_free_at_location (&connection->io_path_cond);
1395 _dbus_condvar_free_at_location (&connection->dispatch_cond);
1396 _dbus_rmutex_free_at_location (&connection->mutex);
1397 _dbus_cmutex_free_at_location (&connection->io_path_mutex);
1398 _dbus_cmutex_free_at_location (&connection->dispatch_mutex);
1399 _dbus_rmutex_free_at_location (&connection->slot_mutex);
1400 dbus_free (connection);
1402 if (pending_replies)
1403 _dbus_hash_table_unref (pending_replies);
1406 _dbus_watch_list_free (watch_list);
1409 _dbus_timeout_list_free (timeout_list);
1411 if (outgoing_counter)
1412 _dbus_counter_unref (outgoing_counter);
1415 _dbus_object_tree_unref (objects);
1421 * Increments the reference count of a DBusConnection.
1422 * Requires that the caller already holds the connection lock.
1424 * @param connection the connection.
1425 * @returns the connection.
1428 _dbus_connection_ref_unlocked (DBusConnection *connection)
1430 dbus_int32_t old_refcount;
1432 _dbus_assert (connection != NULL);
1433 _dbus_assert (connection->generation == _dbus_current_generation);
1435 HAVE_LOCK_CHECK (connection);
1437 old_refcount = _dbus_atomic_inc (&connection->refcount);
1438 _dbus_connection_trace_ref (connection, old_refcount, old_refcount + 1,
1445 * Decrements the reference count of a DBusConnection.
1446 * Requires that the caller already holds the connection lock.
1448 * @param connection the connection.
1451 _dbus_connection_unref_unlocked (DBusConnection *connection)
1453 dbus_int32_t old_refcount;
1455 HAVE_LOCK_CHECK (connection);
1457 _dbus_assert (connection != NULL);
1459 old_refcount = _dbus_atomic_dec (&connection->refcount);
1461 _dbus_connection_trace_ref (connection, old_refcount, old_refcount - 1,
1464 if (old_refcount == 1)
1465 _dbus_connection_last_unref (connection);
1468 static dbus_uint32_t
1469 _dbus_connection_get_next_client_serial (DBusConnection *connection)
1471 dbus_uint32_t serial;
1473 serial = connection->client_serial++;
1475 if (connection->client_serial == 0)
1476 connection->client_serial = 1;
1482 * A callback for use with dbus_watch_new() to create a DBusWatch.
1484 * @todo This is basically a hack - we could delete _dbus_transport_handle_watch()
1485 * and the virtual handle_watch in DBusTransport if we got rid of it.
1486 * The reason this is some work is threading, see the _dbus_connection_handle_watch()
1489 * @param watch the watch.
1490 * @param condition the current condition of the file descriptors being watched.
1491 * @param data must be a pointer to a #DBusConnection
1492 * @returns #FALSE if the IO condition may not have been fully handled due to lack of memory
1495 _dbus_connection_handle_watch (DBusWatch *watch,
1496 unsigned int condition,
1499 DBusConnection *connection;
1501 DBusDispatchStatus status;
1505 _dbus_verbose ("start\n");
1507 CONNECTION_LOCK (connection);
1509 if (!_dbus_connection_acquire_io_path (connection, 1))
1511 /* another thread is handling the message */
1512 CONNECTION_UNLOCK (connection);
1516 HAVE_LOCK_CHECK (connection);
1517 retval = _dbus_transport_handle_watch (connection->transport,
1520 _dbus_connection_release_io_path (connection);
1522 HAVE_LOCK_CHECK (connection);
1524 _dbus_verbose ("middle\n");
1526 status = _dbus_connection_get_dispatch_status_unlocked (connection);
1528 /* this calls out to user code */
1529 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1531 _dbus_verbose ("end\n");
1536 /* Protected by _DBUS_LOCK (shared_connections) */
1537 static DBusHashTable *shared_connections = NULL;
1538 static DBusList *shared_connections_no_guid = NULL;
1541 close_connection_on_shutdown (DBusConnection *connection)
1543 DBusMessage *message;
1545 dbus_connection_ref (connection);
1546 _dbus_connection_close_possibly_shared (connection);
1548 /* Churn through to the Disconnected message */
1549 while ((message = dbus_connection_pop_message (connection)))
1551 dbus_message_unref (message);
1553 dbus_connection_unref (connection);
1557 shared_connections_shutdown (void *data)
1561 if (!_DBUS_LOCK (shared_connections))
1563 /* We'd have initialized locks before adding anything, so there
1564 * can't be anything there. */
1568 /* This is a little bit unpleasant... better ideas? */
1569 while ((n_entries = _dbus_hash_table_get_n_entries (shared_connections)) > 0)
1571 DBusConnection *connection;
1574 _dbus_hash_iter_init (shared_connections, &iter);
1575 _dbus_hash_iter_next (&iter);
1577 connection = _dbus_hash_iter_get_value (&iter);
1579 _DBUS_UNLOCK (shared_connections);
1580 close_connection_on_shutdown (connection);
1581 if (!_DBUS_LOCK (shared_connections))
1582 _dbus_assert_not_reached ("global locks were already initialized");
1584 /* The connection should now be dead and not in our hash ... */
1585 _dbus_assert (_dbus_hash_table_get_n_entries (shared_connections) < n_entries);
1588 _dbus_assert (_dbus_hash_table_get_n_entries (shared_connections) == 0);
1590 _dbus_hash_table_unref (shared_connections);
1591 shared_connections = NULL;
1593 if (shared_connections_no_guid != NULL)
1595 DBusConnection *connection;
1596 connection = _dbus_list_pop_first (&shared_connections_no_guid);
1597 while (connection != NULL)
1599 _DBUS_UNLOCK (shared_connections);
1600 close_connection_on_shutdown (connection);
1601 if (!_DBUS_LOCK (shared_connections))
1602 _dbus_assert_not_reached ("global locks were already initialized");
1603 connection = _dbus_list_pop_first (&shared_connections_no_guid);
1607 shared_connections_no_guid = NULL;
1609 _DBUS_UNLOCK (shared_connections);
1613 connection_lookup_shared (DBusAddressEntry *entry,
1614 DBusConnection **result)
1616 _dbus_verbose ("checking for existing connection\n");
1620 if (!_DBUS_LOCK (shared_connections))
1622 /* If it was shared, we'd have initialized global locks when we put
1623 * it in shared_connections. */
1627 if (shared_connections == NULL)
1629 _dbus_verbose ("creating shared_connections hash table\n");
1631 shared_connections = _dbus_hash_table_new (DBUS_HASH_STRING,
1634 if (shared_connections == NULL)
1636 _DBUS_UNLOCK (shared_connections);
1640 if (!_dbus_register_shutdown_func (shared_connections_shutdown, NULL))
1642 _dbus_hash_table_unref (shared_connections);
1643 shared_connections = NULL;
1644 _DBUS_UNLOCK (shared_connections);
1648 _dbus_verbose (" successfully created shared_connections\n");
1650 _DBUS_UNLOCK (shared_connections);
1651 return TRUE; /* no point looking up in the hash we just made */
1657 guid = dbus_address_entry_get_value (entry, "guid");
1661 DBusConnection *connection;
1663 connection = _dbus_hash_table_lookup_string (shared_connections,
1668 /* The DBusConnection can't be finalized without taking
1669 * the shared_connections lock to remove it from the
1670 * hash. So it's safe to ref the connection here.
1671 * However, it may be disconnected if the Disconnected
1672 * message hasn't been processed yet, in which case we
1673 * want to pretend it isn't in the hash and avoid
1676 * The idea is to avoid ever returning a disconnected connection
1677 * from dbus_connection_open(). We could just synchronously
1678 * drop our shared ref to the connection on connection disconnect,
1679 * and then assert here that the connection is connected, but
1680 * that causes reentrancy headaches.
1682 CONNECTION_LOCK (connection);
1683 if (_dbus_connection_get_is_connected_unlocked (connection))
1685 _dbus_connection_ref_unlocked (connection);
1686 *result = connection;
1687 _dbus_verbose ("looked up existing connection to server guid %s\n",
1692 _dbus_verbose ("looked up existing connection to server guid %s but it was disconnected so ignoring it\n",
1695 CONNECTION_UNLOCK (connection);
1699 _DBUS_UNLOCK (shared_connections);
1705 connection_record_shared_unlocked (DBusConnection *connection,
1709 char *guid_in_connection;
1711 HAVE_LOCK_CHECK (connection);
1712 _dbus_assert (connection->server_guid == NULL);
1713 _dbus_assert (connection->shareable);
1715 /* get a hard ref on this connection, even if
1716 * we won't in fact store it in the hash, we still
1717 * need to hold a ref on it until it's disconnected.
1719 _dbus_connection_ref_unlocked (connection);
1723 if (!_DBUS_LOCK (shared_connections))
1726 if (!_dbus_list_prepend (&shared_connections_no_guid, connection))
1728 _DBUS_UNLOCK (shared_connections);
1732 _DBUS_UNLOCK (shared_connections);
1733 return TRUE; /* don't store in the hash */
1736 /* A separate copy of the key is required in the hash table, because
1737 * we don't have a lock on the connection when we are doing a hash
1741 guid_key = _dbus_strdup (guid);
1742 if (guid_key == NULL)
1745 guid_in_connection = _dbus_strdup (guid);
1746 if (guid_in_connection == NULL)
1748 dbus_free (guid_key);
1752 if (!_DBUS_LOCK (shared_connections))
1754 dbus_free (guid_in_connection);
1755 dbus_free (guid_key);
1759 _dbus_assert (shared_connections != NULL);
1761 if (!_dbus_hash_table_insert_string (shared_connections,
1762 guid_key, connection))
1764 dbus_free (guid_key);
1765 dbus_free (guid_in_connection);
1766 _DBUS_UNLOCK (shared_connections);
1770 connection->server_guid = guid_in_connection;
1772 _dbus_verbose ("stored connection to %s to be shared\n",
1773 connection->server_guid);
1775 _DBUS_UNLOCK (shared_connections);
1777 _dbus_assert (connection->server_guid != NULL);
1783 connection_forget_shared_unlocked (DBusConnection *connection)
1785 HAVE_LOCK_CHECK (connection);
1787 if (!connection->shareable)
1790 if (!_DBUS_LOCK (shared_connections))
1792 /* If it was shared, we'd have initialized global locks when we put
1793 * it in the table; so it can't be there. */
1797 if (connection->server_guid != NULL)
1799 _dbus_verbose ("dropping connection to %s out of the shared table\n",
1800 connection->server_guid);
1802 if (!_dbus_hash_table_remove_string (shared_connections,
1803 connection->server_guid))
1804 _dbus_assert_not_reached ("connection was not in the shared table");
1806 dbus_free (connection->server_guid);
1807 connection->server_guid = NULL;
1811 _dbus_list_remove (&shared_connections_no_guid, connection);
1814 _DBUS_UNLOCK (shared_connections);
1816 /* remove our reference held on all shareable connections */
1817 _dbus_connection_unref_unlocked (connection);
1820 static DBusConnection*
1821 connection_try_from_address_entry (DBusAddressEntry *entry,
1824 DBusTransport *transport;
1825 DBusConnection *connection;
1827 transport = _dbus_transport_open (entry, error);
1829 if (transport == NULL)
1831 _DBUS_ASSERT_ERROR_IS_SET (error);
1835 connection = _dbus_connection_new_for_transport (transport);
1837 _dbus_transport_unref (transport);
1839 if (connection == NULL)
1841 _DBUS_SET_OOM (error);
1845 #ifndef DBUS_DISABLE_CHECKS
1846 _dbus_assert (!connection->have_connection_lock);
1853 * If the shared parameter is true, then any existing connection will
1854 * be used (and if a new connection is created, it will be available
1855 * for use by others). If the shared parameter is false, a new
1856 * connection will always be created, and the new connection will
1857 * never be returned to other callers.
1859 * @param address the address
1860 * @param shared whether the connection is shared or private
1861 * @param error error return
1862 * @returns the connection or #NULL on error
1864 static DBusConnection*
1865 _dbus_connection_open_internal (const char *address,
1869 DBusConnection *connection;
1870 DBusAddressEntry **entries;
1871 DBusError tmp_error = DBUS_ERROR_INIT;
1872 DBusError first_error = DBUS_ERROR_INIT;
1875 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1877 _dbus_verbose ("opening %s connection to: %s\n",
1878 shared ? "shared" : "private", address);
1880 if (!dbus_parse_address (address, &entries, &len, error))
1883 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1887 for (i = 0; i < len; i++)
1891 if (!connection_lookup_shared (entries[i], &connection))
1892 _DBUS_SET_OOM (&tmp_error);
1895 if (connection == NULL)
1897 connection = connection_try_from_address_entry (entries[i],
1900 if (connection != NULL && shared)
1904 connection->shareable = TRUE;
1906 /* guid may be NULL */
1907 guid = dbus_address_entry_get_value (entries[i], "guid");
1909 CONNECTION_LOCK (connection);
1911 if (!connection_record_shared_unlocked (connection, guid))
1913 _DBUS_SET_OOM (&tmp_error);
1914 _dbus_connection_close_possibly_shared_and_unlock (connection);
1915 dbus_connection_unref (connection);
1919 CONNECTION_UNLOCK (connection);
1926 _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
1929 dbus_move_error (&tmp_error, &first_error);
1931 dbus_error_free (&tmp_error);
1934 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1935 _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
1937 if (connection == NULL)
1939 _DBUS_ASSERT_ERROR_IS_SET (&first_error);
1940 dbus_move_error (&first_error, error);
1943 dbus_error_free (&first_error);
1945 dbus_address_entries_free (entries);
1950 * Closes a shared OR private connection, while dbus_connection_close() can
1951 * only be used on private connections. Should only be called by the
1952 * dbus code that owns the connection - an owner must be known,
1953 * the open/close state is like malloc/free, not like ref/unref.
1955 * @param connection the connection
1958 _dbus_connection_close_possibly_shared (DBusConnection *connection)
1960 _dbus_assert (connection != NULL);
1961 _dbus_assert (connection->generation == _dbus_current_generation);
1963 CONNECTION_LOCK (connection);
1964 _dbus_connection_close_possibly_shared_and_unlock (connection);
1967 static DBusPreallocatedSend*
1968 _dbus_connection_preallocate_send_unlocked (DBusConnection *connection)
1970 DBusPreallocatedSend *preallocated;
1972 HAVE_LOCK_CHECK (connection);
1974 _dbus_assert (connection != NULL);
1976 preallocated = dbus_new (DBusPreallocatedSend, 1);
1977 if (preallocated == NULL)
1980 preallocated->queue_link = _dbus_list_alloc_link (NULL);
1981 if (preallocated->queue_link == NULL)
1984 preallocated->counter_link = _dbus_list_alloc_link (connection->outgoing_counter);
1985 if (preallocated->counter_link == NULL)
1988 _dbus_counter_ref (preallocated->counter_link->data);
1990 preallocated->connection = connection;
1992 return preallocated;
1995 _dbus_list_free_link (preallocated->queue_link);
1997 dbus_free (preallocated);
2002 /* Called with lock held, does not update dispatch status */
2004 _dbus_connection_send_preallocated_unlocked_no_update (DBusConnection *connection,
2005 DBusPreallocatedSend *preallocated,
2006 DBusMessage *message,
2007 dbus_uint32_t *client_serial)
2009 dbus_uint32_t serial;
2011 preallocated->queue_link->data = message;
2012 _dbus_list_prepend_link (&connection->outgoing_messages,
2013 preallocated->queue_link);
2015 /* It's OK that we'll never call the notify function, because for the
2016 * outgoing limit, there isn't one */
2017 _dbus_message_add_counter_link (message,
2018 preallocated->counter_link);
2020 dbus_free (preallocated);
2021 preallocated = NULL;
2023 dbus_message_ref (message);
2025 connection->n_outgoing += 1;
2027 _dbus_verbose ("Message %p (%s %s %s %s '%s') for %s added to outgoing queue %p, %d pending to send\n",
2029 dbus_message_type_to_string (dbus_message_get_type (message)),
2030 dbus_message_get_path (message) ?
2031 dbus_message_get_path (message) :
2033 dbus_message_get_interface (message) ?
2034 dbus_message_get_interface (message) :
2036 dbus_message_get_member (message) ?
2037 dbus_message_get_member (message) :
2039 dbus_message_get_signature (message),
2040 dbus_message_get_destination (message) ?
2041 dbus_message_get_destination (message) :
2044 connection->n_outgoing);
2046 if (dbus_message_get_serial (message) == 0)
2048 serial = _dbus_connection_get_next_client_serial (connection);
2049 dbus_message_set_serial (message, serial);
2051 *client_serial = serial;
2056 *client_serial = dbus_message_get_serial (message);
2059 _dbus_verbose ("Message %p serial is %u\n",
2060 message, dbus_message_get_serial (message));
2062 if(dbus_transport_is_kdbus(connection))
2067 name = dbus_bus_get_unique_name(connection);
2068 sender = malloc (strlen(name) + 4);
2071 strcpy(sender,":1.");
2072 strcpy(&sender[3], name);
2073 _dbus_verbose ("Message sender: %s\n", sender);
2074 dbus_message_set_sender(message, sender);
2075 free((void*)sender);
2079 dbus_message_lock (message);
2081 /* Now we need to run an iteration to hopefully just write the messages
2082 * out immediately, and otherwise get them queued up
2084 _dbus_connection_do_iteration_unlocked (connection,
2086 DBUS_ITERATION_DO_WRITING,
2089 /* If stuff is still queued up, be sure we wake up the main loop */
2090 if (connection->n_outgoing > 0)
2091 _dbus_connection_wakeup_mainloop (connection);
2095 _dbus_connection_send_preallocated_and_unlock (DBusConnection *connection,
2096 DBusPreallocatedSend *preallocated,
2097 DBusMessage *message,
2098 dbus_uint32_t *client_serial)
2100 DBusDispatchStatus status;
2102 HAVE_LOCK_CHECK (connection);
2104 _dbus_connection_send_preallocated_unlocked_no_update (connection,
2106 message, client_serial);
2108 _dbus_verbose ("middle\n");
2109 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2111 /* this calls out to user code */
2112 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2116 * Like dbus_connection_send(), but assumes the connection
2117 * is already locked on function entry, and unlocks before returning.
2119 * @param connection the connection
2120 * @param message the message to send
2121 * @param client_serial return location for client serial of sent message
2122 * @returns #FALSE on out-of-memory
2125 _dbus_connection_send_and_unlock (DBusConnection *connection,
2126 DBusMessage *message,
2127 dbus_uint32_t *client_serial)
2129 DBusPreallocatedSend *preallocated;
2131 _dbus_assert (connection != NULL);
2132 _dbus_assert (message != NULL);
2134 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
2135 if (preallocated == NULL)
2137 CONNECTION_UNLOCK (connection);
2141 _dbus_connection_send_preallocated_and_unlock (connection,
2149 * Used internally to handle the semantics of dbus_server_set_new_connection_function().
2150 * If the new connection function does not ref the connection, we want to close it.
2152 * A bit of a hack, probably the new connection function should have returned a value
2153 * for whether to close, or should have had to close the connection itself if it
2156 * But, this works OK as long as the new connection function doesn't do anything
2157 * crazy like keep the connection around without ref'ing it.
2159 * We have to lock the connection across refcount check and close in case
2160 * the new connection function spawns a thread that closes and unrefs.
2161 * In that case, if the app thread
2162 * closes and unrefs first, we'll harmlessly close again; if the app thread
2163 * still has the ref, we'll close and then the app will close harmlessly.
2164 * If the app unrefs without closing, the app is broken since if the
2165 * app refs from the new connection function it is supposed to also close.
2167 * If we didn't atomically check the refcount and close with the lock held
2168 * though, we could screw this up.
2170 * @param connection the connection
2173 _dbus_connection_close_if_only_one_ref (DBusConnection *connection)
2175 dbus_int32_t refcount;
2177 CONNECTION_LOCK (connection);
2179 refcount = _dbus_atomic_get (&connection->refcount);
2180 /* The caller should have at least one ref */
2181 _dbus_assert (refcount >= 1);
2184 _dbus_connection_close_possibly_shared_and_unlock (connection);
2186 CONNECTION_UNLOCK (connection);
2191 * When a function that blocks has been called with a timeout, and we
2192 * run out of memory, the time to wait for memory is based on the
2193 * timeout. If the caller was willing to block a long time we wait a
2194 * relatively long time for memory, if they were only willing to block
2195 * briefly then we retry for memory at a rapid rate.
2197 * @timeout_milliseconds the timeout requested for blocking
2200 _dbus_memory_pause_based_on_timeout (int timeout_milliseconds)
2202 if (timeout_milliseconds == -1)
2203 _dbus_sleep_milliseconds (1000);
2204 else if (timeout_milliseconds < 100)
2205 ; /* just busy loop */
2206 else if (timeout_milliseconds <= 1000)
2207 _dbus_sleep_milliseconds (timeout_milliseconds / 3);
2209 _dbus_sleep_milliseconds (1000);
2213 generate_local_error_message (dbus_uint32_t serial,
2217 DBusMessage *message;
2218 message = dbus_message_new (DBUS_MESSAGE_TYPE_ERROR);
2222 if (!dbus_message_set_error_name (message, error_name))
2224 dbus_message_unref (message);
2229 dbus_message_set_no_reply (message, TRUE);
2231 if (!dbus_message_set_reply_serial (message,
2234 dbus_message_unref (message);
2239 if (error_msg != NULL)
2241 DBusMessageIter iter;
2243 dbus_message_iter_init_append (message, &iter);
2244 if (!dbus_message_iter_append_basic (&iter,
2248 dbus_message_unref (message);
2259 * Peek the incoming queue to see if we got reply for a specific serial
2262 _dbus_connection_peek_for_reply_unlocked (DBusConnection *connection,
2263 dbus_uint32_t client_serial)
2266 HAVE_LOCK_CHECK (connection);
2268 link = _dbus_list_get_first_link (&connection->incoming_messages);
2270 while (link != NULL)
2272 DBusMessage *reply = link->data;
2274 if (dbus_message_get_reply_serial (reply) == client_serial)
2276 _dbus_verbose ("%s reply to %d found in queue\n", _DBUS_FUNCTION_NAME, client_serial);
2279 link = _dbus_list_get_next_link (&connection->incoming_messages, link);
2285 /* This is slightly strange since we can pop a message here without
2286 * the dispatch lock.
2289 check_for_reply_unlocked (DBusConnection *connection,
2290 dbus_uint32_t client_serial)
2294 HAVE_LOCK_CHECK (connection);
2296 link = _dbus_list_get_first_link (&connection->incoming_messages);
2298 while (link != NULL)
2300 DBusMessage *reply = link->data;
2302 if (dbus_message_get_reply_serial (reply) == client_serial)
2304 _dbus_list_remove_link (&connection->incoming_messages, link);
2305 connection->n_incoming -= 1;
2308 link = _dbus_list_get_next_link (&connection->incoming_messages, link);
2315 connection_timeout_and_complete_all_pending_calls_unlocked (DBusConnection *connection)
2317 /* We can't iterate over the hash in the normal way since we'll be
2318 * dropping the lock for each item. So we restart the
2319 * iter each time as we drain the hash table.
2322 while (_dbus_hash_table_get_n_entries (connection->pending_replies) > 0)
2324 DBusPendingCall *pending;
2327 _dbus_hash_iter_init (connection->pending_replies, &iter);
2328 _dbus_hash_iter_next (&iter);
2330 pending = _dbus_hash_iter_get_value (&iter);
2331 _dbus_pending_call_ref_unlocked (pending);
2333 _dbus_pending_call_queue_timeout_error_unlocked (pending,
2336 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
2337 _dbus_connection_remove_timeout_unlocked (connection,
2338 _dbus_pending_call_get_timeout_unlocked (pending));
2339 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
2340 _dbus_hash_iter_remove_entry (&iter);
2342 _dbus_pending_call_unref_and_unlock (pending);
2343 CONNECTION_LOCK (connection);
2345 HAVE_LOCK_CHECK (connection);
2349 complete_pending_call_and_unlock (DBusConnection *connection,
2350 DBusPendingCall *pending,
2351 DBusMessage *message)
2353 _dbus_pending_call_set_reply_unlocked (pending, message);
2354 _dbus_pending_call_ref_unlocked (pending); /* in case there's no app with a ref held */
2355 _dbus_connection_detach_pending_call_and_unlock (connection, pending);
2357 /* Must be called unlocked since it invokes app callback */
2358 _dbus_pending_call_complete (pending);
2359 dbus_pending_call_unref (pending);
2363 check_for_reply_and_update_dispatch_unlocked (DBusConnection *connection,
2364 DBusPendingCall *pending)
2367 DBusDispatchStatus status;
2369 reply = check_for_reply_unlocked (connection,
2370 _dbus_pending_call_get_reply_serial_unlocked (pending));
2373 _dbus_verbose ("checked for reply\n");
2375 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): got reply\n");
2377 complete_pending_call_and_unlock (connection, pending, reply);
2378 dbus_message_unref (reply);
2380 CONNECTION_LOCK (connection);
2381 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2382 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2383 dbus_pending_call_unref (pending);
2392 * Blocks until a pending call times out or gets a reply.
2394 * Does not re-enter the main loop or run filter/path-registered
2395 * callbacks. The reply to the message will not be seen by
2398 * Returns immediately if pending call already got a reply.
2400 * @todo could use performance improvements (it keeps scanning
2401 * the whole message queue for example)
2403 * @param pending the pending call we block for a reply on
2406 _dbus_connection_block_pending_call (DBusPendingCall *pending)
2408 long start_tv_sec, start_tv_usec;
2409 long tv_sec, tv_usec;
2410 DBusDispatchStatus status;
2411 DBusConnection *connection;
2412 dbus_uint32_t client_serial;
2413 DBusTimeout *timeout;
2414 int timeout_milliseconds, elapsed_milliseconds;
2416 _dbus_assert (pending != NULL);
2418 if (dbus_pending_call_get_completed (pending))
2421 dbus_pending_call_ref (pending); /* necessary because the call could be canceled */
2423 connection = _dbus_pending_call_get_connection_and_lock (pending);
2425 /* Flush message queue - note, can affect dispatch status */
2426 _dbus_connection_flush_unlocked (connection);
2428 client_serial = _dbus_pending_call_get_reply_serial_unlocked (pending);
2430 /* note that timeout_milliseconds is limited to a smallish value
2431 * in _dbus_pending_call_new() so overflows aren't possible
2434 timeout = _dbus_pending_call_get_timeout_unlocked (pending);
2435 _dbus_get_monotonic_time (&start_tv_sec, &start_tv_usec);
2438 timeout_milliseconds = dbus_timeout_get_interval (timeout);
2440 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): will block %d milliseconds for reply serial %u from %ld sec %ld usec\n",
2441 timeout_milliseconds,
2443 start_tv_sec, start_tv_usec);
2447 timeout_milliseconds = -1;
2449 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): will block for reply serial %u\n", client_serial);
2452 /* check to see if we already got the data off the socket */
2453 /* from another blocked pending call */
2454 if (check_for_reply_and_update_dispatch_unlocked (connection, pending))
2457 /* Now we wait... */
2458 /* always block at least once as we know we don't have the reply yet */
2459 _dbus_connection_do_iteration_unlocked (connection,
2461 DBUS_ITERATION_DO_READING |
2462 DBUS_ITERATION_BLOCK,
2463 timeout_milliseconds);
2467 _dbus_verbose ("top of recheck\n");
2469 HAVE_LOCK_CHECK (connection);
2471 /* queue messages and get status */
2473 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2475 /* the get_completed() is in case a dispatch() while we were blocking
2476 * got the reply instead of us.
2478 if (_dbus_pending_call_get_completed_unlocked (pending))
2480 _dbus_verbose ("Pending call completed by dispatch\n");
2481 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2482 dbus_pending_call_unref (pending);
2486 if (status == DBUS_DISPATCH_DATA_REMAINS)
2488 if (check_for_reply_and_update_dispatch_unlocked (connection, pending))
2492 _dbus_get_monotonic_time (&tv_sec, &tv_usec);
2493 elapsed_milliseconds = (tv_sec - start_tv_sec) * 1000 +
2494 (tv_usec - start_tv_usec) / 1000;
2496 if (!_dbus_connection_get_is_connected_unlocked (connection))
2498 DBusMessage *error_msg;
2500 error_msg = generate_local_error_message (client_serial,
2501 DBUS_ERROR_DISCONNECTED,
2502 "Connection was disconnected before a reply was received");
2504 /* on OOM error_msg is set to NULL */
2505 complete_pending_call_and_unlock (connection, pending, error_msg);
2506 dbus_pending_call_unref (pending);
2509 else if (connection->disconnect_message_link == NULL)
2510 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): disconnected\n");
2511 else if (timeout == NULL)
2513 if (status == DBUS_DISPATCH_NEED_MEMORY)
2515 /* Try sleeping a bit, as we aren't sure we need to block for reading,
2516 * we may already have a reply in the buffer and just can't process
2519 _dbus_verbose ("dbus_connection_send_with_reply_and_block() waiting for more memory\n");
2521 _dbus_memory_pause_based_on_timeout (timeout_milliseconds - elapsed_milliseconds);
2525 /* block again, we don't have the reply buffered yet. */
2526 _dbus_connection_do_iteration_unlocked (connection,
2528 DBUS_ITERATION_DO_READING |
2529 DBUS_ITERATION_BLOCK,
2530 timeout_milliseconds - elapsed_milliseconds);
2533 goto recheck_status;
2535 else if (tv_sec < start_tv_sec)
2536 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): clock set backward\n");
2537 else if (elapsed_milliseconds < timeout_milliseconds)
2539 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): %d milliseconds remain\n", timeout_milliseconds - elapsed_milliseconds);
2541 if (status == DBUS_DISPATCH_NEED_MEMORY)
2543 /* Try sleeping a bit, as we aren't sure we need to block for reading,
2544 * we may already have a reply in the buffer and just can't process
2547 _dbus_verbose ("dbus_connection_send_with_reply_and_block() waiting for more memory\n");
2549 _dbus_memory_pause_based_on_timeout (timeout_milliseconds - elapsed_milliseconds);
2553 /* block again, we don't have the reply buffered yet. */
2554 _dbus_connection_do_iteration_unlocked (connection,
2556 DBUS_ITERATION_DO_READING |
2557 DBUS_ITERATION_BLOCK,
2558 timeout_milliseconds - elapsed_milliseconds);
2561 goto recheck_status;
2564 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): Waited %d milliseconds and got no reply\n",
2565 elapsed_milliseconds);
2567 _dbus_assert (!_dbus_pending_call_get_completed_unlocked (pending));
2569 /* unlock and call user code */
2570 complete_pending_call_and_unlock (connection, pending, NULL);
2572 /* update user code on dispatch status */
2573 CONNECTION_LOCK (connection);
2574 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2575 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2576 dbus_pending_call_unref (pending);
2582 * @addtogroup DBusConnection
2588 * Gets a connection to a remote address. If a connection to the given
2589 * address already exists, returns the existing connection with its
2590 * reference count incremented. Otherwise, returns a new connection
2591 * and saves the new connection for possible re-use if a future call
2592 * to dbus_connection_open() asks to connect to the same server.
2594 * Use dbus_connection_open_private() to get a dedicated connection
2595 * not shared with other callers of dbus_connection_open().
2597 * If the open fails, the function returns #NULL, and provides a
2598 * reason for the failure in the error parameter. Pass #NULL for the
2599 * error parameter if you aren't interested in the reason for
2602 * Because this connection is shared, no user of the connection
2603 * may call dbus_connection_close(). However, when you are done with the
2604 * connection you should call dbus_connection_unref().
2606 * @note Prefer dbus_connection_open() to dbus_connection_open_private()
2607 * unless you have good reason; connections are expensive enough
2608 * that it's wasteful to create lots of connections to the same
2611 * @param address the address.
2612 * @param error address where an error can be returned.
2613 * @returns new connection, or #NULL on failure.
2616 dbus_connection_open (const char *address,
2619 DBusConnection *connection;
2621 _dbus_return_val_if_fail (address != NULL, NULL);
2622 _dbus_return_val_if_error_is_set (error, NULL);
2624 connection = _dbus_connection_open_internal (address,
2632 * Opens a new, dedicated connection to a remote address. Unlike
2633 * dbus_connection_open(), always creates a new connection.
2634 * This connection will not be saved or recycled by libdbus.
2636 * If the open fails, the function returns #NULL, and provides a
2637 * reason for the failure in the error parameter. Pass #NULL for the
2638 * error parameter if you aren't interested in the reason for
2641 * When you are done with this connection, you must
2642 * dbus_connection_close() to disconnect it,
2643 * and dbus_connection_unref() to free the connection object.
2645 * (The dbus_connection_close() can be skipped if the
2646 * connection is already known to be disconnected, for example
2647 * if you are inside a handler for the Disconnected signal.)
2649 * @note Prefer dbus_connection_open() to dbus_connection_open_private()
2650 * unless you have good reason; connections are expensive enough
2651 * that it's wasteful to create lots of connections to the same
2654 * @param address the address.
2655 * @param error address where an error can be returned.
2656 * @returns new connection, or #NULL on failure.
2659 dbus_connection_open_private (const char *address,
2662 DBusConnection *connection;
2664 _dbus_return_val_if_fail (address != NULL, NULL);
2665 _dbus_return_val_if_error_is_set (error, NULL);
2667 connection = _dbus_connection_open_internal (address,
2675 * Increments the reference count of a DBusConnection.
2677 * @param connection the connection.
2678 * @returns the connection.
2681 dbus_connection_ref (DBusConnection *connection)
2683 dbus_int32_t old_refcount;
2685 _dbus_return_val_if_fail (connection != NULL, NULL);
2686 _dbus_return_val_if_fail (connection->generation == _dbus_current_generation, NULL);
2687 old_refcount = _dbus_atomic_inc (&connection->refcount);
2688 _dbus_connection_trace_ref (connection, old_refcount, old_refcount + 1,
2695 free_outgoing_message (void *element,
2698 DBusMessage *message = element;
2699 DBusConnection *connection = data;
2701 _dbus_message_remove_counter (message, connection->outgoing_counter);
2702 dbus_message_unref (message);
2705 /* This is run without the mutex held, but after the last reference
2706 * to the connection has been dropped we should have no thread-related
2710 _dbus_connection_last_unref (DBusConnection *connection)
2714 _dbus_verbose ("Finalizing connection %p\n", connection);
2716 _dbus_assert (_dbus_atomic_get (&connection->refcount) == 0);
2718 /* You have to disconnect the connection before unref:ing it. Otherwise
2719 * you won't get the disconnected message.
2721 _dbus_assert (!_dbus_transport_get_is_connected (connection->transport));
2722 _dbus_assert (connection->server_guid == NULL);
2724 /* ---- We're going to call various application callbacks here, hope it doesn't break anything... */
2725 _dbus_object_tree_free_all_unlocked (connection->objects);
2727 dbus_connection_set_dispatch_status_function (connection, NULL, NULL, NULL);
2728 dbus_connection_set_wakeup_main_function (connection, NULL, NULL, NULL);
2729 dbus_connection_set_unix_user_function (connection, NULL, NULL, NULL);
2731 _dbus_watch_list_free (connection->watches);
2732 connection->watches = NULL;
2734 _dbus_timeout_list_free (connection->timeouts);
2735 connection->timeouts = NULL;
2737 _dbus_data_slot_list_free (&connection->slot_list);
2739 link = _dbus_list_get_first_link (&connection->filter_list);
2740 while (link != NULL)
2742 DBusMessageFilter *filter = link->data;
2743 DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
2745 filter->function = NULL;
2746 _dbus_message_filter_unref (filter); /* calls app callback */
2751 _dbus_list_clear (&connection->filter_list);
2753 /* ---- Done with stuff that invokes application callbacks */
2755 _dbus_object_tree_unref (connection->objects);
2757 _dbus_hash_table_unref (connection->pending_replies);
2758 connection->pending_replies = NULL;
2760 _dbus_list_clear (&connection->filter_list);
2762 _dbus_list_foreach (&connection->outgoing_messages,
2763 free_outgoing_message,
2765 _dbus_list_clear (&connection->outgoing_messages);
2767 _dbus_list_foreach (&connection->incoming_messages,
2768 (DBusForeachFunction) dbus_message_unref,
2770 _dbus_list_clear (&connection->incoming_messages);
2772 _dbus_counter_unref (connection->outgoing_counter);
2774 _dbus_transport_unref (connection->transport);
2776 if (connection->disconnect_message_link)
2778 DBusMessage *message = connection->disconnect_message_link->data;
2779 dbus_message_unref (message);
2780 _dbus_list_free_link (connection->disconnect_message_link);
2783 _dbus_condvar_free_at_location (&connection->dispatch_cond);
2784 _dbus_condvar_free_at_location (&connection->io_path_cond);
2786 _dbus_cmutex_free_at_location (&connection->io_path_mutex);
2787 _dbus_cmutex_free_at_location (&connection->dispatch_mutex);
2789 _dbus_rmutex_free_at_location (&connection->slot_mutex);
2791 _dbus_rmutex_free_at_location (&connection->mutex);
2793 dbus_free (connection);
2797 * Decrements the reference count of a DBusConnection, and finalizes
2798 * it if the count reaches zero.
2800 * Note: it is a bug to drop the last reference to a connection that
2801 * is still connected.
2803 * For shared connections, libdbus will own a reference
2804 * as long as the connection is connected, so you can know that either
2805 * you don't have the last reference, or it's OK to drop the last reference.
2806 * Most connections are shared. dbus_connection_open() and dbus_bus_get()
2807 * return shared connections.
2809 * For private connections, the creator of the connection must arrange for
2810 * dbus_connection_close() to be called prior to dropping the last reference.
2811 * Private connections come from dbus_connection_open_private() or dbus_bus_get_private().
2813 * @param connection the connection.
2816 dbus_connection_unref (DBusConnection *connection)
2818 dbus_int32_t old_refcount;
2820 _dbus_return_if_fail (connection != NULL);
2821 _dbus_return_if_fail (connection->generation == _dbus_current_generation);
2823 old_refcount = _dbus_atomic_dec (&connection->refcount);
2825 _dbus_connection_trace_ref (connection, old_refcount, old_refcount - 1,
2828 if (old_refcount == 1)
2830 #ifndef DBUS_DISABLE_CHECKS
2831 if (_dbus_transport_get_is_connected (connection->transport))
2833 _dbus_warn_check_failed ("The last reference on a connection was dropped without closing the connection. This is a bug in an application. See dbus_connection_unref() documentation for details.\n%s",
2834 connection->shareable ?
2835 "Most likely, the application called unref() too many times and removed a reference belonging to libdbus, since this is a shared connection.\n" :
2836 "Most likely, the application was supposed to call dbus_connection_close(), since this is a private connection.\n");
2840 _dbus_connection_last_unref (connection);
2845 * Note that the transport can disconnect itself (other end drops us)
2846 * and in that case this function never runs. So this function must
2847 * not do anything more than disconnect the transport and update the
2850 * If the transport self-disconnects, then we assume someone will
2851 * dispatch the connection to cause the dispatch status update.
2854 _dbus_connection_close_possibly_shared_and_unlock (DBusConnection *connection)
2856 DBusDispatchStatus status;
2858 HAVE_LOCK_CHECK (connection);
2860 _dbus_verbose ("Disconnecting %p\n", connection);
2862 /* We need to ref because update_dispatch_status_and_unlock will unref
2863 * the connection if it was shared and libdbus was the only remaining
2866 _dbus_connection_ref_unlocked (connection);
2868 _dbus_transport_disconnect (connection->transport);
2870 /* This has the side effect of queuing the disconnect message link
2871 * (unless we don't have enough memory, possibly, so don't assert it).
2872 * After the disconnect message link is queued, dbus_bus_get/dbus_connection_open
2873 * should never again return the newly-disconnected connection.
2875 * However, we only unref the shared connection and exit_on_disconnect when
2876 * the disconnect message reaches the head of the message queue,
2877 * NOT when it's first queued.
2879 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2881 /* This calls out to user code */
2882 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2884 /* Could also call out to user code */
2885 dbus_connection_unref (connection);
2889 * Closes a private connection, so no further data can be sent or received.
2890 * This disconnects the transport (such as a socket) underlying the
2893 * Attempts to send messages after closing a connection are safe, but will result in
2894 * error replies generated locally in libdbus.
2896 * This function does not affect the connection's reference count. It's
2897 * safe to close a connection more than once; all calls after the
2898 * first do nothing. It's impossible to "reopen" a connection, a
2899 * new connection must be created. This function may result in a call
2900 * to the DBusDispatchStatusFunction set with
2901 * dbus_connection_set_dispatch_status_function(), as the disconnect
2902 * message it generates needs to be dispatched.
2904 * If a connection is dropped by the remote application, it will
2907 * You must close a connection prior to releasing the last reference to
2908 * the connection. If you dbus_connection_unref() for the last time
2909 * without closing the connection, the results are undefined; it
2910 * is a bug in your program and libdbus will try to print a warning.
2912 * You may not close a shared connection. Connections created with
2913 * dbus_connection_open() or dbus_bus_get() are shared.
2914 * These connections are owned by libdbus, and applications should
2915 * only unref them, never close them. Applications can know it is
2916 * safe to unref these connections because libdbus will be holding a
2917 * reference as long as the connection is open. Thus, either the
2918 * connection is closed and it is OK to drop the last reference,
2919 * or the connection is open and the app knows it does not have the
2922 * Connections created with dbus_connection_open_private() or
2923 * dbus_bus_get_private() are not kept track of or referenced by
2924 * libdbus. The creator of these connections is responsible for
2925 * calling dbus_connection_close() prior to releasing the last
2926 * reference, if the connection is not already disconnected.
2928 * @param connection the private (unshared) connection to close
2931 dbus_connection_close (DBusConnection *connection)
2933 _dbus_return_if_fail (connection != NULL);
2934 _dbus_return_if_fail (connection->generation == _dbus_current_generation);
2936 CONNECTION_LOCK (connection);
2938 #ifndef DBUS_DISABLE_CHECKS
2939 if (connection->shareable)
2941 CONNECTION_UNLOCK (connection);
2943 _dbus_warn_check_failed ("Applications must not close shared connections - see dbus_connection_close() docs. This is a bug in the application.\n");
2948 _dbus_connection_close_possibly_shared_and_unlock (connection);
2952 _dbus_connection_get_is_connected_unlocked (DBusConnection *connection)
2954 HAVE_LOCK_CHECK (connection);
2955 return _dbus_transport_get_is_connected (connection->transport);
2959 * Gets whether the connection is currently open. A connection may
2960 * become disconnected when the remote application closes its end, or
2961 * exits; a connection may also be disconnected with
2962 * dbus_connection_close().
2964 * There are not separate states for "closed" and "disconnected," the two
2965 * terms are synonymous. This function should really be called
2966 * get_is_open() but for historical reasons is not.
2968 * @param connection the connection.
2969 * @returns #TRUE if the connection is still alive.
2972 dbus_connection_get_is_connected (DBusConnection *connection)
2976 _dbus_return_val_if_fail (connection != NULL, FALSE);
2978 CONNECTION_LOCK (connection);
2979 res = _dbus_connection_get_is_connected_unlocked (connection);
2980 CONNECTION_UNLOCK (connection);
2986 * Gets whether the connection was authenticated. (Note that
2987 * if the connection was authenticated then disconnected,
2988 * this function still returns #TRUE)
2990 * @param connection the connection
2991 * @returns #TRUE if the connection was ever authenticated
2994 dbus_connection_get_is_authenticated (DBusConnection *connection)
2998 _dbus_return_val_if_fail (connection != NULL, FALSE);
3000 CONNECTION_LOCK (connection);
3001 res = _dbus_transport_get_is_authenticated (connection->transport);
3002 CONNECTION_UNLOCK (connection);
3008 * Sets authenticated status for connection. Needed for kdbus, where authentication is
3009 * made in different manner.
3011 * @param connection the connection
3014 dbus_connection_set_is_authenticated (DBusConnection *connection)
3016 _dbus_return_val_if_fail (connection != NULL, FALSE);
3018 CONNECTION_LOCK (connection);
3019 connection->transport->authenticated = TRUE;
3020 CONNECTION_UNLOCK (connection);
3026 * Gets whether the connection is not authenticated as a specific
3027 * user. If the connection is not authenticated, this function
3028 * returns #TRUE, and if it is authenticated but as an anonymous user,
3029 * it returns #TRUE. If it is authenticated as a specific user, then
3030 * this returns #FALSE. (Note that if the connection was authenticated
3031 * as anonymous then disconnected, this function still returns #TRUE.)
3033 * If the connection is not anonymous, you can use
3034 * dbus_connection_get_unix_user() and
3035 * dbus_connection_get_windows_user() to see who it's authorized as.
3037 * If you want to prevent non-anonymous authorization, use
3038 * dbus_server_set_auth_mechanisms() to remove the mechanisms that
3039 * allow proving user identity (i.e. only allow the ANONYMOUS
3042 * @param connection the connection
3043 * @returns #TRUE if not authenticated or authenticated as anonymous
3046 dbus_connection_get_is_anonymous (DBusConnection *connection)
3050 _dbus_return_val_if_fail (connection != NULL, FALSE);
3052 CONNECTION_LOCK (connection);
3053 res = _dbus_transport_get_is_anonymous (connection->transport);
3054 CONNECTION_UNLOCK (connection);
3060 * Gets the ID of the server address we are authenticated to, if this
3061 * connection is on the client side. If the connection is on the
3062 * server side, this will always return #NULL - use dbus_server_get_id()
3063 * to get the ID of your own server, if you are the server side.
3065 * If a client-side connection is not authenticated yet, the ID may be
3066 * available if it was included in the server address, but may not be
3067 * available. The only way to be sure the server ID is available
3068 * is to wait for authentication to complete.
3070 * In general, each mode of connecting to a given server will have
3071 * its own ID. So for example, if the session bus daemon is listening
3072 * on UNIX domain sockets and on TCP, then each of those modalities
3073 * will have its own server ID.
3075 * If you want an ID that identifies an entire session bus, look at
3076 * dbus_bus_get_id() instead (which is just a convenience wrapper
3077 * around the org.freedesktop.DBus.GetId method invoked on the bus).
3079 * You can also get a machine ID; see dbus_get_local_machine_id() to
3080 * get the machine you are on. There isn't a convenience wrapper, but
3081 * you can invoke org.freedesktop.DBus.Peer.GetMachineId on any peer
3082 * to get the machine ID on the other end.
3084 * The D-Bus specification describes the server ID and other IDs in a
3087 * @param connection the connection
3088 * @returns the server ID or #NULL if no memory or the connection is server-side
3091 dbus_connection_get_server_id (DBusConnection *connection)
3095 _dbus_return_val_if_fail (connection != NULL, NULL);
3097 CONNECTION_LOCK (connection);
3098 id = _dbus_strdup (_dbus_transport_get_server_id (connection->transport));
3099 CONNECTION_UNLOCK (connection);
3105 * Tests whether a certain type can be send via the connection. This
3106 * will always return TRUE for all types, with the exception of
3107 * DBUS_TYPE_UNIX_FD. The function will return TRUE for
3108 * DBUS_TYPE_UNIX_FD only on systems that know Unix file descriptors
3109 * and can send them via the chosen transport and when the remote side
3112 * This function can be used to do runtime checking for types that
3113 * might be unknown to the specific D-Bus client implementation
3114 * version, i.e. it will return FALSE for all types this
3115 * implementation does not know, including invalid or reserved types.
3117 * @param connection the connection
3118 * @param type the type to check
3119 * @returns TRUE if the type may be send via the connection
3122 dbus_connection_can_send_type(DBusConnection *connection,
3125 _dbus_return_val_if_fail (connection != NULL, FALSE);
3127 if (!dbus_type_is_valid (type))
3130 if (type != DBUS_TYPE_UNIX_FD)
3133 #ifdef HAVE_UNIX_FD_PASSING
3137 CONNECTION_LOCK(connection);
3138 b = _dbus_transport_can_pass_unix_fd(connection->transport);
3139 CONNECTION_UNLOCK(connection);
3149 * Set whether _exit() should be called when the connection receives a
3150 * disconnect signal. The call to _exit() comes after any handlers for
3151 * the disconnect signal run; handlers can cancel the exit by calling
3154 * By default, exit_on_disconnect is #FALSE; but for message bus
3155 * connections returned from dbus_bus_get() it will be toggled on
3158 * @param connection the connection
3159 * @param exit_on_disconnect #TRUE if _exit() should be called after a disconnect signal
3162 dbus_connection_set_exit_on_disconnect (DBusConnection *connection,
3163 dbus_bool_t exit_on_disconnect)
3165 _dbus_return_if_fail (connection != NULL);
3167 CONNECTION_LOCK (connection);
3168 connection->exit_on_disconnect = exit_on_disconnect != FALSE;
3169 CONNECTION_UNLOCK (connection);
3173 * Preallocates resources needed to send a message, allowing the message
3174 * to be sent without the possibility of memory allocation failure.
3175 * Allows apps to create a future guarantee that they can send
3176 * a message regardless of memory shortages.
3178 * @param connection the connection we're preallocating for.
3179 * @returns the preallocated resources, or #NULL
3181 DBusPreallocatedSend*
3182 dbus_connection_preallocate_send (DBusConnection *connection)
3184 DBusPreallocatedSend *preallocated;
3186 _dbus_return_val_if_fail (connection != NULL, NULL);
3188 CONNECTION_LOCK (connection);
3191 _dbus_connection_preallocate_send_unlocked (connection);
3193 CONNECTION_UNLOCK (connection);
3195 return preallocated;
3199 * Frees preallocated message-sending resources from
3200 * dbus_connection_preallocate_send(). Should only
3201 * be called if the preallocated resources are not used
3202 * to send a message.
3204 * @param connection the connection
3205 * @param preallocated the resources
3208 dbus_connection_free_preallocated_send (DBusConnection *connection,
3209 DBusPreallocatedSend *preallocated)
3211 _dbus_return_if_fail (connection != NULL);
3212 _dbus_return_if_fail (preallocated != NULL);
3213 _dbus_return_if_fail (connection == preallocated->connection);
3215 _dbus_list_free_link (preallocated->queue_link);
3216 _dbus_counter_unref (preallocated->counter_link->data);
3217 _dbus_list_free_link (preallocated->counter_link);
3218 dbus_free (preallocated);
3222 * Sends a message using preallocated resources. This function cannot fail.
3223 * It works identically to dbus_connection_send() in other respects.
3224 * Preallocated resources comes from dbus_connection_preallocate_send().
3225 * This function "consumes" the preallocated resources, they need not
3226 * be freed separately.
3228 * @param connection the connection
3229 * @param preallocated the preallocated resources
3230 * @param message the message to send
3231 * @param client_serial return location for client serial assigned to the message
3234 dbus_connection_send_preallocated (DBusConnection *connection,
3235 DBusPreallocatedSend *preallocated,
3236 DBusMessage *message,
3237 dbus_uint32_t *client_serial)
3239 _dbus_return_if_fail (connection != NULL);
3240 _dbus_return_if_fail (preallocated != NULL);
3241 _dbus_return_if_fail (message != NULL);
3242 _dbus_return_if_fail (preallocated->connection == connection);
3243 _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_METHOD_CALL ||
3244 dbus_message_get_member (message) != NULL);
3245 _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL ||
3246 (dbus_message_get_interface (message) != NULL &&
3247 dbus_message_get_member (message) != NULL));
3249 CONNECTION_LOCK (connection);
3251 #ifdef HAVE_UNIX_FD_PASSING
3253 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3254 message->n_unix_fds > 0)
3256 /* Refuse to send fds on a connection that cannot handle
3257 them. Unfortunately we cannot return a proper error here, so
3258 the best we can is just return. */
3259 CONNECTION_UNLOCK (connection);
3265 _dbus_connection_send_preallocated_and_unlock (connection,
3267 message, client_serial);
3271 _dbus_connection_send_unlocked_no_update (DBusConnection *connection,
3272 DBusMessage *message,
3273 dbus_uint32_t *client_serial)
3275 DBusPreallocatedSend *preallocated;
3277 _dbus_assert (connection != NULL);
3278 _dbus_assert (message != NULL);
3280 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
3281 if (preallocated == NULL)
3284 _dbus_connection_send_preallocated_unlocked_no_update (connection,
3292 * Adds a message to the outgoing message queue. Does not block to
3293 * write the message to the network; that happens asynchronously. To
3294 * force the message to be written, call dbus_connection_flush() however
3295 * it is not necessary to call dbus_connection_flush() by hand; the
3296 * message will be sent the next time the main loop is run.
3297 * dbus_connection_flush() should only be used, for example, if
3298 * the application was expected to exit before running the main loop.
3300 * Because this only queues the message, the only reason it can
3301 * fail is lack of memory. Even if the connection is disconnected,
3302 * no error will be returned. If the function fails due to lack of memory,
3303 * it returns #FALSE. The function will never fail for other reasons; even
3304 * if the connection is disconnected, you can queue an outgoing message,
3305 * though obviously it won't be sent.
3307 * The message serial is used by the remote application to send a
3308 * reply; see dbus_message_get_serial() or the D-Bus specification.
3310 * dbus_message_unref() can be called as soon as this method returns
3311 * as the message queue will hold its own ref until the message is sent.
3313 * @param connection the connection.
3314 * @param message the message to write.
3315 * @param serial return location for message serial, or #NULL if you don't care
3316 * @returns #TRUE on success.
3319 dbus_connection_send (DBusConnection *connection,
3320 DBusMessage *message,
3321 dbus_uint32_t *serial)
3323 _dbus_return_val_if_fail (connection != NULL, FALSE);
3324 _dbus_return_val_if_fail (message != NULL, FALSE);
3326 CONNECTION_LOCK (connection);
3328 #ifdef HAVE_UNIX_FD_PASSING
3330 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3331 message->n_unix_fds > 0)
3333 /* Refuse to send fds on a connection that cannot handle
3334 them. Unfortunately we cannot return a proper error here, so
3335 the best we can is just return. */
3336 CONNECTION_UNLOCK (connection);
3342 return _dbus_connection_send_and_unlock (connection,
3348 reply_handler_timeout (void *data)
3350 DBusConnection *connection;
3351 DBusDispatchStatus status;
3352 DBusPendingCall *pending = data;
3354 connection = _dbus_pending_call_get_connection_and_lock (pending);
3355 _dbus_connection_ref_unlocked (connection);
3357 _dbus_pending_call_queue_timeout_error_unlocked (pending,
3359 _dbus_connection_remove_timeout_unlocked (connection,
3360 _dbus_pending_call_get_timeout_unlocked (pending));
3361 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
3363 _dbus_verbose ("middle\n");
3364 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3366 /* Unlocks, and calls out to user code */
3367 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3368 dbus_connection_unref (connection);
3374 * Queues a message to send, as with dbus_connection_send(),
3375 * but also returns a #DBusPendingCall used to receive a reply to the
3376 * message. If no reply is received in the given timeout_milliseconds,
3377 * this function expires the pending reply and generates a synthetic
3378 * error reply (generated in-process, not by the remote application)
3379 * indicating that a timeout occurred.
3381 * A #DBusPendingCall will see a reply message before any filters or
3382 * registered object path handlers. See dbus_connection_dispatch() for
3383 * details on when handlers are run.
3385 * A #DBusPendingCall will always see exactly one reply message,
3386 * unless it's cancelled with dbus_pending_call_cancel().
3388 * If #NULL is passed for the pending_return, the #DBusPendingCall
3389 * will still be generated internally, and used to track
3390 * the message reply timeout. This means a timeout error will
3391 * occur if no reply arrives, unlike with dbus_connection_send().
3393 * If -1 is passed for the timeout, a sane default timeout is used. -1
3394 * is typically the best value for the timeout for this reason, unless
3395 * you want a very short or very long timeout. If #DBUS_TIMEOUT_INFINITE is
3396 * passed for the timeout, no timeout will be set and the call will block
3399 * @warning if the connection is disconnected or you try to send Unix
3400 * file descriptors on a connection that does not support them, the
3401 * #DBusPendingCall will be set to #NULL, so be careful with this.
3403 * @param connection the connection
3404 * @param message the message to send
3405 * @param pending_return return location for a #DBusPendingCall
3406 * object, or #NULL if connection is disconnected or when you try to
3407 * send Unix file descriptors on a connection that does not support
3409 * @param timeout_milliseconds timeout in milliseconds, -1 (or
3410 * #DBUS_TIMEOUT_USE_DEFAULT) for default or #DBUS_TIMEOUT_INFINITE for no
3412 * @returns #FALSE if no memory, #TRUE otherwise.
3416 dbus_connection_send_with_reply (DBusConnection *connection,
3417 DBusMessage *message,
3418 DBusPendingCall **pending_return,
3419 int timeout_milliseconds)
3421 DBusPendingCall *pending;
3422 dbus_int32_t serial = -1;
3423 DBusDispatchStatus status;
3425 _dbus_return_val_if_fail (connection != NULL, FALSE);
3426 _dbus_return_val_if_fail (message != NULL, FALSE);
3427 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3430 *pending_return = NULL;
3432 CONNECTION_LOCK (connection);
3434 #ifdef HAVE_UNIX_FD_PASSING
3436 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3437 message->n_unix_fds > 0)
3439 /* Refuse to send fds on a connection that cannot handle
3440 them. Unfortunately we cannot return a proper error here, so
3441 the best we can do is return TRUE but leave *pending_return
3443 CONNECTION_UNLOCK (connection);
3449 if (!_dbus_connection_get_is_connected_unlocked (connection))
3451 CONNECTION_UNLOCK (connection);
3456 pending = _dbus_pending_call_new_unlocked (connection,
3457 timeout_milliseconds,
3458 reply_handler_timeout);
3460 if (pending == NULL)
3462 CONNECTION_UNLOCK (connection);
3466 /* Assign a serial to the message */
3467 serial = dbus_message_get_serial (message);
3470 serial = _dbus_connection_get_next_client_serial (connection);
3471 dbus_message_set_serial (message, serial);
3474 if (!_dbus_pending_call_set_timeout_error_unlocked (pending, message, serial))
3477 /* Insert the serial in the pending replies hash;
3478 * hash takes a refcount on DBusPendingCall.
3479 * Also, add the timeout.
3481 if (!_dbus_connection_attach_pending_call_unlocked (connection,
3485 if (!_dbus_connection_send_unlocked_no_update (connection, message, NULL))
3487 _dbus_connection_detach_pending_call_and_unlock (connection,
3489 goto error_unlocked;
3493 *pending_return = pending; /* hand off refcount */
3496 _dbus_connection_detach_pending_call_unlocked (connection, pending);
3497 /* we still have a ref to the pending call in this case, we unref
3498 * after unlocking, below
3502 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3504 /* this calls out to user code */
3505 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3507 if (pending_return == NULL)
3508 dbus_pending_call_unref (pending);
3513 CONNECTION_UNLOCK (connection);
3515 dbus_pending_call_unref (pending);
3520 * Sends a message and blocks a certain time period while waiting for
3521 * a reply. This function does not reenter the main loop,
3522 * i.e. messages other than the reply are queued up but not
3523 * processed. This function is used to invoke method calls on a
3526 * If a normal reply is received, it is returned, and removed from the
3527 * incoming message queue. If it is not received, #NULL is returned
3528 * and the error is set to #DBUS_ERROR_NO_REPLY. If an error reply is
3529 * received, it is converted to a #DBusError and returned as an error,
3530 * then the reply message is deleted and #NULL is returned. If
3531 * something else goes wrong, result is set to whatever is
3532 * appropriate, such as #DBUS_ERROR_NO_MEMORY or
3533 * #DBUS_ERROR_DISCONNECTED.
3535 * @warning While this function blocks the calling thread will not be
3536 * processing the incoming message queue. This means you can end up
3537 * deadlocked if the application you're talking to needs you to reply
3538 * to a method. To solve this, either avoid the situation, block in a
3539 * separate thread from the main connection-dispatching thread, or use
3540 * dbus_pending_call_set_notify() to avoid blocking.
3542 * @param connection the connection
3543 * @param message the message to send
3544 * @param timeout_milliseconds timeout in milliseconds, -1 (or
3545 * #DBUS_TIMEOUT_USE_DEFAULT) for default or #DBUS_TIMEOUT_INFINITE for no
3547 * @param error return location for error message
3548 * @returns the message that is the reply or #NULL with an error code if the
3552 dbus_connection_send_with_reply_and_block (DBusConnection *connection,
3553 DBusMessage *message,
3554 int timeout_milliseconds,
3558 DBusPendingCall *pending;
3560 _dbus_return_val_if_fail (connection != NULL, NULL);
3561 _dbus_return_val_if_fail (message != NULL, NULL);
3562 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, NULL);
3563 _dbus_return_val_if_error_is_set (error, NULL);
3565 #ifdef HAVE_UNIX_FD_PASSING
3567 CONNECTION_LOCK (connection);
3568 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3569 message->n_unix_fds > 0)
3571 CONNECTION_UNLOCK (connection);
3572 dbus_set_error(error, DBUS_ERROR_FAILED, "Cannot send file descriptors on this connection.");
3575 CONNECTION_UNLOCK (connection);
3579 if (!dbus_connection_send_with_reply (connection, message,
3580 &pending, timeout_milliseconds))
3582 _DBUS_SET_OOM (error);
3586 if (pending == NULL)
3588 dbus_set_error (error, DBUS_ERROR_DISCONNECTED, "Connection is closed");
3592 dbus_pending_call_block (pending);
3594 reply = dbus_pending_call_steal_reply (pending);
3595 dbus_pending_call_unref (pending);
3597 /* call_complete_and_unlock() called from pending_call_block() should
3598 * always fill this in.
3600 _dbus_assert (reply != NULL);
3602 if (dbus_set_error_from_message (error, reply))
3604 dbus_message_unref (reply);
3612 * Blocks until the outgoing message queue is empty.
3613 * Assumes connection lock already held.
3615 * If you call this, you MUST call update_dispatch_status afterword...
3617 * @param connection the connection.
3619 static DBusDispatchStatus
3620 _dbus_connection_flush_unlocked (DBusConnection *connection)
3622 /* We have to specify DBUS_ITERATION_DO_READING here because
3623 * otherwise we could have two apps deadlock if they are both doing
3624 * a flush(), and the kernel buffers fill up. This could change the
3627 DBusDispatchStatus status;
3629 HAVE_LOCK_CHECK (connection);
3631 while (connection->n_outgoing > 0 &&
3632 _dbus_connection_get_is_connected_unlocked (connection))
3634 _dbus_verbose ("doing iteration in\n");
3635 HAVE_LOCK_CHECK (connection);
3636 _dbus_connection_do_iteration_unlocked (connection,
3638 DBUS_ITERATION_DO_READING |
3639 DBUS_ITERATION_DO_WRITING |
3640 DBUS_ITERATION_BLOCK,
3644 HAVE_LOCK_CHECK (connection);
3645 _dbus_verbose ("middle\n");
3646 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3648 HAVE_LOCK_CHECK (connection);
3653 * Blocks until the outgoing message queue is empty.
3655 * @param connection the connection.
3658 dbus_connection_flush (DBusConnection *connection)
3660 /* We have to specify DBUS_ITERATION_DO_READING here because
3661 * otherwise we could have two apps deadlock if they are both doing
3662 * a flush(), and the kernel buffers fill up. This could change the
3665 DBusDispatchStatus status;
3667 _dbus_return_if_fail (connection != NULL);
3669 CONNECTION_LOCK (connection);
3671 status = _dbus_connection_flush_unlocked (connection);
3673 HAVE_LOCK_CHECK (connection);
3674 /* Unlocks and calls out to user code */
3675 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3677 _dbus_verbose ("end\n");
3681 * This function implements dbus_connection_read_write_dispatch() and
3682 * dbus_connection_read_write() (they pass a different value for the
3683 * dispatch parameter).
3685 * @param connection the connection
3686 * @param timeout_milliseconds max time to block or -1 for infinite
3687 * @param dispatch dispatch new messages or leave them on the incoming queue
3688 * @returns #TRUE if the disconnect message has not been processed
3691 _dbus_connection_read_write_dispatch (DBusConnection *connection,
3692 int timeout_milliseconds,
3693 dbus_bool_t dispatch)
3695 DBusDispatchStatus dstatus;
3696 dbus_bool_t progress_possible;
3698 /* Need to grab a ref here in case we're a private connection and
3699 * the user drops the last ref in a handler we call; see bug
3700 * https://bugs.freedesktop.org/show_bug.cgi?id=15635
3702 dbus_connection_ref (connection);
3703 dstatus = dbus_connection_get_dispatch_status (connection);
3705 if (dispatch && dstatus == DBUS_DISPATCH_DATA_REMAINS)
3707 _dbus_verbose ("doing dispatch\n");
3708 dbus_connection_dispatch (connection);
3709 CONNECTION_LOCK (connection);
3711 else if (dstatus == DBUS_DISPATCH_NEED_MEMORY)
3713 _dbus_verbose ("pausing for memory\n");
3714 _dbus_memory_pause_based_on_timeout (timeout_milliseconds);
3715 CONNECTION_LOCK (connection);
3719 CONNECTION_LOCK (connection);
3720 if (_dbus_connection_get_is_connected_unlocked (connection))
3722 _dbus_verbose ("doing iteration\n");
3723 _dbus_connection_do_iteration_unlocked (connection,
3725 DBUS_ITERATION_DO_READING |
3726 DBUS_ITERATION_DO_WRITING |
3727 DBUS_ITERATION_BLOCK,
3728 timeout_milliseconds);
3732 HAVE_LOCK_CHECK (connection);
3733 /* If we can dispatch, we can make progress until the Disconnected message
3734 * has been processed; if we can only read/write, we can make progress
3735 * as long as the transport is open.
3738 progress_possible = connection->n_incoming != 0 ||
3739 connection->disconnect_message_link != NULL;
3741 progress_possible = _dbus_connection_get_is_connected_unlocked (connection);
3743 CONNECTION_UNLOCK (connection);
3745 dbus_connection_unref (connection);
3747 return progress_possible; /* TRUE if we can make more progress */
3752 * This function is intended for use with applications that don't want
3753 * to write a main loop and deal with #DBusWatch and #DBusTimeout. An
3754 * example usage would be:
3757 * while (dbus_connection_read_write_dispatch (connection, -1))
3758 * ; // empty loop body
3761 * In this usage you would normally have set up a filter function to look
3762 * at each message as it is dispatched. The loop terminates when the last
3763 * message from the connection (the disconnected signal) is processed.
3765 * If there are messages to dispatch, this function will
3766 * dbus_connection_dispatch() once, and return. If there are no
3767 * messages to dispatch, this function will block until it can read or
3768 * write, then read or write, then return.
3770 * The way to think of this function is that it either makes some sort
3771 * of progress, or it blocks. Note that, while it is blocked on I/O, it
3772 * cannot be interrupted (even by other threads), which makes this function
3773 * unsuitable for applications that do more than just react to received
3776 * The return value indicates whether the disconnect message has been
3777 * processed, NOT whether the connection is connected. This is
3778 * important because even after disconnecting, you want to process any
3779 * messages you received prior to the disconnect.
3781 * @param connection the connection
3782 * @param timeout_milliseconds max time to block or -1 for infinite
3783 * @returns #TRUE if the disconnect message has not been processed
3786 dbus_connection_read_write_dispatch (DBusConnection *connection,
3787 int timeout_milliseconds)
3789 _dbus_return_val_if_fail (connection != NULL, FALSE);
3790 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3791 return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, TRUE);
3795 * This function is intended for use with applications that don't want to
3796 * write a main loop and deal with #DBusWatch and #DBusTimeout. See also
3797 * dbus_connection_read_write_dispatch().
3799 * As long as the connection is open, this function will block until it can
3800 * read or write, then read or write, then return #TRUE.
3802 * If the connection is closed, the function returns #FALSE.
3804 * The return value indicates whether reading or writing is still
3805 * possible, i.e. whether the connection is connected.
3807 * Note that even after disconnection, messages may remain in the
3808 * incoming queue that need to be
3809 * processed. dbus_connection_read_write_dispatch() dispatches
3810 * incoming messages for you; with dbus_connection_read_write() you
3811 * have to arrange to drain the incoming queue yourself.
3813 * @param connection the connection
3814 * @param timeout_milliseconds max time to block or -1 for infinite
3815 * @returns #TRUE if still connected
3818 dbus_connection_read_write (DBusConnection *connection,
3819 int timeout_milliseconds)
3821 _dbus_return_val_if_fail (connection != NULL, FALSE);
3822 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3823 return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, FALSE);
3826 /* We need to call this anytime we pop the head of the queue, and then
3827 * update_dispatch_status_and_unlock needs to be called afterward
3828 * which will "process" the disconnected message and set
3829 * disconnected_message_processed.
3832 check_disconnected_message_arrived_unlocked (DBusConnection *connection,
3833 DBusMessage *head_of_queue)
3835 HAVE_LOCK_CHECK (connection);
3837 /* checking that the link is NULL is an optimization to avoid the is_signal call */
3838 if (connection->disconnect_message_link == NULL &&
3839 dbus_message_is_signal (head_of_queue,
3840 DBUS_INTERFACE_LOCAL,
3843 connection->disconnected_message_arrived = TRUE;
3848 * Returns the first-received message from the incoming message queue,
3849 * leaving it in the queue. If the queue is empty, returns #NULL.
3851 * The caller does not own a reference to the returned message, and
3852 * must either return it using dbus_connection_return_message() or
3853 * keep it after calling dbus_connection_steal_borrowed_message(). No
3854 * one can get at the message while its borrowed, so return it as
3855 * quickly as possible and don't keep a reference to it after
3856 * returning it. If you need to keep the message, make a copy of it.
3858 * dbus_connection_dispatch() will block if called while a borrowed
3859 * message is outstanding; only one piece of code can be playing with
3860 * the incoming queue at a time. This function will block if called
3861 * during a dbus_connection_dispatch().
3863 * @param connection the connection.
3864 * @returns next message in the incoming queue.
3867 dbus_connection_borrow_message (DBusConnection *connection)
3869 DBusDispatchStatus status;
3870 DBusMessage *message;
3872 _dbus_return_val_if_fail (connection != NULL, NULL);
3874 _dbus_verbose ("start\n");
3876 /* this is called for the side effect that it queues
3877 * up any messages from the transport
3879 status = dbus_connection_get_dispatch_status (connection);
3880 if (status != DBUS_DISPATCH_DATA_REMAINS)
3883 CONNECTION_LOCK (connection);
3885 _dbus_connection_acquire_dispatch (connection);
3887 /* While a message is outstanding, the dispatch lock is held */
3888 _dbus_assert (connection->message_borrowed == NULL);
3890 connection->message_borrowed = _dbus_list_get_first (&connection->incoming_messages);
3892 message = connection->message_borrowed;
3894 check_disconnected_message_arrived_unlocked (connection, message);
3896 /* Note that we KEEP the dispatch lock until the message is returned */
3897 if (message == NULL)
3898 _dbus_connection_release_dispatch (connection);
3900 CONNECTION_UNLOCK (connection);
3902 _dbus_message_trace_ref (message, -1, -1, "dbus_connection_borrow_message");
3904 /* We don't update dispatch status until it's returned or stolen */
3910 * Used to return a message after peeking at it using
3911 * dbus_connection_borrow_message(). Only called if
3912 * message from dbus_connection_borrow_message() was non-#NULL.
3914 * @param connection the connection
3915 * @param message the message from dbus_connection_borrow_message()
3918 dbus_connection_return_message (DBusConnection *connection,
3919 DBusMessage *message)
3921 DBusDispatchStatus status;
3923 _dbus_return_if_fail (connection != NULL);
3924 _dbus_return_if_fail (message != NULL);
3925 _dbus_return_if_fail (message == connection->message_borrowed);
3926 _dbus_return_if_fail (connection->dispatch_acquired);
3928 CONNECTION_LOCK (connection);
3930 _dbus_assert (message == connection->message_borrowed);
3932 connection->message_borrowed = NULL;
3934 _dbus_connection_release_dispatch (connection);
3936 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3937 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3939 _dbus_message_trace_ref (message, -1, -1, "dbus_connection_return_message");
3943 * Used to keep a message after peeking at it using
3944 * dbus_connection_borrow_message(). Before using this function, see
3945 * the caveats/warnings in the documentation for
3946 * dbus_connection_pop_message().
3948 * @param connection the connection
3949 * @param message the message from dbus_connection_borrow_message()
3952 dbus_connection_steal_borrowed_message (DBusConnection *connection,
3953 DBusMessage *message)
3955 DBusMessage *pop_message;
3956 DBusDispatchStatus status;
3958 _dbus_return_if_fail (connection != NULL);
3959 _dbus_return_if_fail (message != NULL);
3960 _dbus_return_if_fail (message == connection->message_borrowed);
3961 _dbus_return_if_fail (connection->dispatch_acquired);
3963 CONNECTION_LOCK (connection);
3965 _dbus_assert (message == connection->message_borrowed);
3967 pop_message = _dbus_list_pop_first (&connection->incoming_messages);
3968 _dbus_assert (message == pop_message);
3969 (void) pop_message; /* unused unless asserting */
3971 connection->n_incoming -= 1;
3973 _dbus_verbose ("Incoming message %p stolen from queue, %d incoming\n",
3974 message, connection->n_incoming);
3976 connection->message_borrowed = NULL;
3978 _dbus_connection_release_dispatch (connection);
3980 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3981 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3982 _dbus_message_trace_ref (message, -1, -1,
3983 "dbus_connection_steal_borrowed_message");
3986 /* See dbus_connection_pop_message, but requires the caller to own
3987 * the lock before calling. May drop the lock while running.
3990 _dbus_connection_pop_message_link_unlocked (DBusConnection *connection)
3992 HAVE_LOCK_CHECK (connection);
3994 _dbus_assert (connection->message_borrowed == NULL);
3996 if (connection->n_incoming > 0)
4000 link = _dbus_list_pop_first_link (&connection->incoming_messages);
4001 connection->n_incoming -= 1;
4003 _dbus_verbose ("Message %p (%s %s %s %s '%s') removed from incoming queue %p, %d incoming\n",
4005 dbus_message_type_to_string (dbus_message_get_type (link->data)),
4006 dbus_message_get_path (link->data) ?
4007 dbus_message_get_path (link->data) :
4009 dbus_message_get_interface (link->data) ?
4010 dbus_message_get_interface (link->data) :
4012 dbus_message_get_member (link->data) ?
4013 dbus_message_get_member (link->data) :
4015 dbus_message_get_signature (link->data),
4016 connection, connection->n_incoming);
4018 _dbus_message_trace_ref (link->data, -1, -1,
4019 "_dbus_connection_pop_message_link_unlocked");
4021 check_disconnected_message_arrived_unlocked (connection, link->data);
4029 /* See dbus_connection_pop_message, but requires the caller to own
4030 * the lock before calling. May drop the lock while running.
4033 _dbus_connection_pop_message_unlocked (DBusConnection *connection)
4037 HAVE_LOCK_CHECK (connection);
4039 link = _dbus_connection_pop_message_link_unlocked (connection);
4043 DBusMessage *message;
4045 message = link->data;
4047 _dbus_list_free_link (link);
4056 _dbus_connection_putback_message_link_unlocked (DBusConnection *connection,
4057 DBusList *message_link)
4059 HAVE_LOCK_CHECK (connection);
4061 _dbus_assert (message_link != NULL);
4062 /* You can't borrow a message while a link is outstanding */
4063 _dbus_assert (connection->message_borrowed == NULL);
4064 /* We had to have the dispatch lock across the pop/putback */
4065 _dbus_assert (connection->dispatch_acquired);
4067 _dbus_list_prepend_link (&connection->incoming_messages,
4069 connection->n_incoming += 1;
4071 _dbus_verbose ("Message %p (%s %s %s '%s') put back into queue %p, %d incoming\n",
4073 dbus_message_type_to_string (dbus_message_get_type (message_link->data)),
4074 dbus_message_get_interface (message_link->data) ?
4075 dbus_message_get_interface (message_link->data) :
4077 dbus_message_get_member (message_link->data) ?
4078 dbus_message_get_member (message_link->data) :
4080 dbus_message_get_signature (message_link->data),
4081 connection, connection->n_incoming);
4083 _dbus_message_trace_ref (message_link->data, -1, -1,
4084 "_dbus_connection_putback_message_link_unlocked");
4088 * Returns the first-received message from the incoming message queue,
4089 * removing it from the queue. The caller owns a reference to the
4090 * returned message. If the queue is empty, returns #NULL.
4092 * This function bypasses any message handlers that are registered,
4093 * and so using it is usually wrong. Instead, let the main loop invoke
4094 * dbus_connection_dispatch(). Popping messages manually is only
4095 * useful in very simple programs that don't share a #DBusConnection
4096 * with any libraries or other modules.
4098 * There is a lock that covers all ways of accessing the incoming message
4099 * queue, so dbus_connection_dispatch(), dbus_connection_pop_message(),
4100 * dbus_connection_borrow_message(), etc. will all block while one of the others
4101 * in the group is running.
4103 * @param connection the connection.
4104 * @returns next message in the incoming queue.
4107 dbus_connection_pop_message (DBusConnection *connection)
4109 DBusMessage *message;
4110 DBusDispatchStatus status;
4112 _dbus_verbose ("start\n");
4114 /* this is called for the side effect that it queues
4115 * up any messages from the transport
4117 status = dbus_connection_get_dispatch_status (connection);
4118 if (status != DBUS_DISPATCH_DATA_REMAINS)
4121 CONNECTION_LOCK (connection);
4122 _dbus_connection_acquire_dispatch (connection);
4123 HAVE_LOCK_CHECK (connection);
4125 message = _dbus_connection_pop_message_unlocked (connection);
4127 _dbus_verbose ("Returning popped message %p\n", message);
4129 _dbus_connection_release_dispatch (connection);
4131 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4132 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4138 * Acquire the dispatcher. This is a separate lock so the main
4139 * connection lock can be dropped to call out to application dispatch
4142 * @param connection the connection.
4145 _dbus_connection_acquire_dispatch (DBusConnection *connection)
4147 HAVE_LOCK_CHECK (connection);
4149 _dbus_connection_ref_unlocked (connection);
4150 CONNECTION_UNLOCK (connection);
4152 _dbus_verbose ("locking dispatch_mutex\n");
4153 _dbus_cmutex_lock (connection->dispatch_mutex);
4155 while (connection->dispatch_acquired)
4157 _dbus_verbose ("waiting for dispatch to be acquirable\n");
4158 _dbus_condvar_wait (connection->dispatch_cond,
4159 connection->dispatch_mutex);
4162 _dbus_assert (!connection->dispatch_acquired);
4164 connection->dispatch_acquired = TRUE;
4166 _dbus_verbose ("unlocking dispatch_mutex\n");
4167 _dbus_cmutex_unlock (connection->dispatch_mutex);
4169 CONNECTION_LOCK (connection);
4170 _dbus_connection_unref_unlocked (connection);
4174 * Release the dispatcher when you're done with it. Only call
4175 * after you've acquired the dispatcher. Wakes up at most one
4176 * thread currently waiting to acquire the dispatcher.
4178 * @param connection the connection.
4181 _dbus_connection_release_dispatch (DBusConnection *connection)
4183 HAVE_LOCK_CHECK (connection);
4185 _dbus_verbose ("locking dispatch_mutex\n");
4186 _dbus_cmutex_lock (connection->dispatch_mutex);
4188 _dbus_assert (connection->dispatch_acquired);
4190 connection->dispatch_acquired = FALSE;
4191 _dbus_condvar_wake_one (connection->dispatch_cond);
4193 _dbus_verbose ("unlocking dispatch_mutex\n");
4194 _dbus_cmutex_unlock (connection->dispatch_mutex);
4198 _dbus_connection_failed_pop (DBusConnection *connection,
4199 DBusList *message_link)
4201 _dbus_list_prepend_link (&connection->incoming_messages,
4203 connection->n_incoming += 1;
4206 /* Note this may be called multiple times since we don't track whether we already did it */
4208 notify_disconnected_unlocked (DBusConnection *connection)
4210 HAVE_LOCK_CHECK (connection);
4212 /* Set the weakref in dbus-bus.c to NULL, so nobody will get a disconnected
4213 * connection from dbus_bus_get(). We make the same guarantee for
4214 * dbus_connection_open() but in a different way since we don't want to
4215 * unref right here; we instead check for connectedness before returning
4216 * the connection from the hash.
4218 _dbus_bus_notify_shared_connection_disconnected_unlocked (connection);
4220 /* Dump the outgoing queue, we aren't going to be able to
4221 * send it now, and we'd like accessors like
4222 * dbus_connection_get_outgoing_size() to be accurate.
4224 if (connection->n_outgoing > 0)
4228 _dbus_verbose ("Dropping %d outgoing messages since we're disconnected\n",
4229 connection->n_outgoing);
4231 while ((link = _dbus_list_get_last_link (&connection->outgoing_messages)))
4233 _dbus_connection_message_sent_unlocked (connection, link->data);
4238 /* Note this may be called multiple times since we don't track whether we already did it */
4239 static DBusDispatchStatus
4240 notify_disconnected_and_dispatch_complete_unlocked (DBusConnection *connection)
4242 HAVE_LOCK_CHECK (connection);
4244 if (connection->disconnect_message_link != NULL)
4246 _dbus_verbose ("Sending disconnect message\n");
4248 /* If we have pending calls, queue their timeouts - we want the Disconnected
4249 * to be the last message, after these timeouts.
4251 connection_timeout_and_complete_all_pending_calls_unlocked (connection);
4253 /* We haven't sent the disconnect message already,
4254 * and all real messages have been queued up.
4256 _dbus_connection_queue_synthesized_message_link (connection,
4257 connection->disconnect_message_link);
4258 connection->disconnect_message_link = NULL;
4260 return DBUS_DISPATCH_DATA_REMAINS;
4263 return DBUS_DISPATCH_COMPLETE;
4266 static DBusDispatchStatus
4267 _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection)
4269 HAVE_LOCK_CHECK (connection);
4271 if (connection->n_incoming > 0)
4272 return DBUS_DISPATCH_DATA_REMAINS;
4273 else if (!_dbus_transport_queue_messages (connection->transport))
4274 return DBUS_DISPATCH_NEED_MEMORY;
4277 DBusDispatchStatus status;
4278 dbus_bool_t is_connected;
4280 status = _dbus_transport_get_dispatch_status (connection->transport);
4281 is_connected = _dbus_transport_get_is_connected (connection->transport);
4283 _dbus_verbose ("dispatch status = %s is_connected = %d\n",
4284 DISPATCH_STATUS_NAME (status), is_connected);
4288 /* It's possible this would be better done by having an explicit
4289 * notification from _dbus_transport_disconnect() that would
4290 * synchronously do this, instead of waiting for the next dispatch
4291 * status check. However, probably not good to change until it causes
4294 notify_disconnected_unlocked (connection);
4296 /* I'm not sure this is needed; the idea is that we want to
4297 * queue the Disconnected only after we've read all the
4298 * messages, but if we're disconnected maybe we are guaranteed
4299 * to have read them all ?
4301 if (status == DBUS_DISPATCH_COMPLETE)
4302 status = notify_disconnected_and_dispatch_complete_unlocked (connection);
4305 if (status != DBUS_DISPATCH_COMPLETE)
4307 else if (connection->n_incoming > 0)
4308 return DBUS_DISPATCH_DATA_REMAINS;
4310 return DBUS_DISPATCH_COMPLETE;
4315 _dbus_connection_update_dispatch_status_and_unlock (DBusConnection *connection,
4316 DBusDispatchStatus new_status)
4318 dbus_bool_t changed;
4319 DBusDispatchStatusFunction function;
4322 HAVE_LOCK_CHECK (connection);
4324 _dbus_connection_ref_unlocked (connection);
4326 changed = new_status != connection->last_dispatch_status;
4328 connection->last_dispatch_status = new_status;
4330 function = connection->dispatch_status_function;
4331 data = connection->dispatch_status_data;
4333 if (connection->disconnected_message_arrived &&
4334 !connection->disconnected_message_processed)
4336 connection->disconnected_message_processed = TRUE;
4338 /* this does an unref, but we have a ref
4339 * so we should not run the finalizer here
4342 connection_forget_shared_unlocked (connection);
4344 if (connection->exit_on_disconnect)
4346 CONNECTION_UNLOCK (connection);
4348 _dbus_verbose ("Exiting on Disconnected signal\n");
4350 _dbus_assert_not_reached ("Call to exit() returned");
4354 /* We drop the lock */
4355 CONNECTION_UNLOCK (connection);
4357 if (changed && function)
4359 _dbus_verbose ("Notifying of change to dispatch status of %p now %d (%s)\n",
4360 connection, new_status,
4361 DISPATCH_STATUS_NAME (new_status));
4362 (* function) (connection, new_status, data);
4365 dbus_connection_unref (connection);
4369 * Gets the current state of the incoming message queue.
4370 * #DBUS_DISPATCH_DATA_REMAINS indicates that the message queue
4371 * may contain messages. #DBUS_DISPATCH_COMPLETE indicates that the
4372 * incoming queue is empty. #DBUS_DISPATCH_NEED_MEMORY indicates that
4373 * there could be data, but we can't know for sure without more
4376 * To process the incoming message queue, use dbus_connection_dispatch()
4377 * or (in rare cases) dbus_connection_pop_message().
4379 * Note, #DBUS_DISPATCH_DATA_REMAINS really means that either we
4380 * have messages in the queue, or we have raw bytes buffered up
4381 * that need to be parsed. When these bytes are parsed, they
4382 * may not add up to an entire message. Thus, it's possible
4383 * to see a status of #DBUS_DISPATCH_DATA_REMAINS but not
4384 * have a message yet.
4386 * In particular this happens on initial connection, because all sorts
4387 * of authentication protocol stuff has to be parsed before the
4388 * first message arrives.
4390 * @param connection the connection.
4391 * @returns current dispatch status
4394 dbus_connection_get_dispatch_status (DBusConnection *connection)
4396 DBusDispatchStatus status;
4398 _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
4400 _dbus_verbose ("start\n");
4402 CONNECTION_LOCK (connection);
4404 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4406 CONNECTION_UNLOCK (connection);
4412 * Filter funtion for handling the Peer standard interface.
4414 static DBusHandlerResult
4415 _dbus_connection_peer_filter_unlocked_no_update (DBusConnection *connection,
4416 DBusMessage *message)
4418 dbus_bool_t sent = FALSE;
4419 DBusMessage *ret = NULL;
4420 DBusList *expire_link;
4422 if (connection->route_peer_messages && dbus_message_get_destination (message) != NULL)
4424 /* This means we're letting the bus route this message */
4425 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4428 if (!dbus_message_has_interface (message, DBUS_INTERFACE_PEER))
4430 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4433 /* Preallocate a linked-list link, so that if we need to dispose of a
4434 * message, we can attach it to the expired list */
4435 expire_link = _dbus_list_alloc_link (NULL);
4438 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4440 if (dbus_message_is_method_call (message,
4441 DBUS_INTERFACE_PEER,
4444 ret = dbus_message_new_method_return (message);
4448 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4450 else if (dbus_message_is_method_call (message,
4451 DBUS_INTERFACE_PEER,
4456 ret = dbus_message_new_method_return (message);
4460 _dbus_string_init (&uuid);
4461 if (_dbus_get_local_machine_uuid_encoded (&uuid))
4463 const char *v_STRING = _dbus_string_get_const_data (&uuid);
4464 if (dbus_message_append_args (ret,
4465 DBUS_TYPE_STRING, &v_STRING,
4468 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4471 _dbus_string_free (&uuid);
4475 /* We need to bounce anything else with this interface, otherwise apps
4476 * could start extending the interface and when we added extensions
4477 * here to DBusConnection we'd break those apps.
4479 ret = dbus_message_new_error (message,
4480 DBUS_ERROR_UNKNOWN_METHOD,
4481 "Unknown method invoked on org.freedesktop.DBus.Peer interface");
4485 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4491 _dbus_list_free_link (expire_link);
4495 /* It'll be safe to unref the reply when we unlock */
4496 expire_link->data = ret;
4497 _dbus_list_prepend_link (&connection->expired_messages, expire_link);
4501 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4503 return DBUS_HANDLER_RESULT_HANDLED;
4507 * Processes all builtin filter functions
4509 * If the spec specifies a standard interface
4510 * they should be processed from this method
4512 static DBusHandlerResult
4513 _dbus_connection_run_builtin_filters_unlocked_no_update (DBusConnection *connection,
4514 DBusMessage *message)
4516 /* We just run one filter for now but have the option to run more
4517 if the spec calls for it in the future */
4519 return _dbus_connection_peer_filter_unlocked_no_update (connection, message);
4523 * Processes any incoming data.
4525 * If there's incoming raw data that has not yet been parsed, it is
4526 * parsed, which may or may not result in adding messages to the
4529 * The incoming data buffer is filled when the connection reads from
4530 * its underlying transport (such as a socket). Reading usually
4531 * happens in dbus_watch_handle() or dbus_connection_read_write().
4533 * If there are complete messages in the incoming queue,
4534 * dbus_connection_dispatch() removes one message from the queue and
4535 * processes it. Processing has three steps.
4537 * First, any method replies are passed to #DBusPendingCall or
4538 * dbus_connection_send_with_reply_and_block() in order to
4539 * complete the pending method call.
4541 * Second, any filters registered with dbus_connection_add_filter()
4542 * are run. If any filter returns #DBUS_HANDLER_RESULT_HANDLED
4543 * then processing stops after that filter.
4545 * Third, if the message is a method call it is forwarded to
4546 * any registered object path handlers added with
4547 * dbus_connection_register_object_path() or
4548 * dbus_connection_register_fallback().
4550 * A single call to dbus_connection_dispatch() will process at most
4551 * one message; it will not clear the entire message queue.
4553 * Be careful about calling dbus_connection_dispatch() from inside a
4554 * message handler, i.e. calling dbus_connection_dispatch()
4555 * recursively. If threads have been initialized with a recursive
4556 * mutex function, then this will not deadlock; however, it can
4557 * certainly confuse your application.
4559 * @todo some FIXME in here about handling DBUS_HANDLER_RESULT_NEED_MEMORY
4561 * @param connection the connection
4562 * @returns dispatch status, see dbus_connection_get_dispatch_status()
4565 dbus_connection_dispatch (DBusConnection *connection)
4567 DBusMessage *message;
4568 DBusList *link, *filter_list_copy, *message_link;
4569 DBusHandlerResult result;
4570 DBusPendingCall *pending;
4571 dbus_int32_t reply_serial;
4572 DBusDispatchStatus status;
4573 dbus_bool_t found_object;
4575 _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
4577 _dbus_verbose ("\n");
4579 CONNECTION_LOCK (connection);
4580 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4581 if (status != DBUS_DISPATCH_DATA_REMAINS)
4583 /* unlocks and calls out to user code */
4584 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4588 /* We need to ref the connection since the callback could potentially
4589 * drop the last ref to it
4591 _dbus_connection_ref_unlocked (connection);
4593 _dbus_connection_acquire_dispatch (connection);
4594 HAVE_LOCK_CHECK (connection);
4596 message_link = _dbus_connection_pop_message_link_unlocked (connection);
4597 if (message_link == NULL)
4599 /* another thread dispatched our stuff */
4601 _dbus_verbose ("another thread dispatched message (during acquire_dispatch above)\n");
4603 _dbus_connection_release_dispatch (connection);
4605 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4607 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4609 dbus_connection_unref (connection);
4614 message = message_link->data;
4616 _dbus_verbose (" dispatching message %p (%s %s %s '%s')\n",
4618 dbus_message_type_to_string (dbus_message_get_type (message)),
4619 dbus_message_get_interface (message) ?
4620 dbus_message_get_interface (message) :
4622 dbus_message_get_member (message) ?
4623 dbus_message_get_member (message) :
4625 dbus_message_get_signature (message));
4627 result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4629 /* Pending call handling must be first, because if you do
4630 * dbus_connection_send_with_reply_and_block() or
4631 * dbus_pending_call_block() then no handlers/filters will be run on
4632 * the reply. We want consistent semantics in the case where we
4633 * dbus_connection_dispatch() the reply.
4636 reply_serial = dbus_message_get_reply_serial (message);
4637 pending = _dbus_hash_table_lookup_int (connection->pending_replies,
4641 _dbus_verbose ("Dispatching a pending reply\n");
4642 complete_pending_call_and_unlock (connection, pending, message);
4643 pending = NULL; /* it's probably unref'd */
4645 CONNECTION_LOCK (connection);
4646 _dbus_verbose ("pending call completed in dispatch\n");
4647 result = DBUS_HANDLER_RESULT_HANDLED;
4651 result = _dbus_connection_run_builtin_filters_unlocked_no_update (connection, message);
4652 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4655 if (!_dbus_list_copy (&connection->filter_list, &filter_list_copy))
4657 _dbus_connection_release_dispatch (connection);
4658 HAVE_LOCK_CHECK (connection);
4660 _dbus_connection_failed_pop (connection, message_link);
4662 /* unlocks and calls user code */
4663 _dbus_connection_update_dispatch_status_and_unlock (connection,
4664 DBUS_DISPATCH_NEED_MEMORY);
4665 dbus_connection_unref (connection);
4667 return DBUS_DISPATCH_NEED_MEMORY;
4670 _dbus_list_foreach (&filter_list_copy,
4671 (DBusForeachFunction)_dbus_message_filter_ref,
4674 /* We're still protected from dispatch() reentrancy here
4675 * since we acquired the dispatcher
4677 CONNECTION_UNLOCK (connection);
4679 link = _dbus_list_get_first_link (&filter_list_copy);
4680 while (link != NULL)
4682 DBusMessageFilter *filter = link->data;
4683 DBusList *next = _dbus_list_get_next_link (&filter_list_copy, link);
4685 if (filter->function == NULL)
4687 _dbus_verbose (" filter was removed in a callback function\n");
4692 _dbus_verbose (" running filter on message %p\n", message);
4693 result = (* filter->function) (connection, message, filter->user_data);
4695 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4701 _dbus_list_foreach (&filter_list_copy,
4702 (DBusForeachFunction)_dbus_message_filter_unref,
4704 _dbus_list_clear (&filter_list_copy);
4706 CONNECTION_LOCK (connection);
4708 if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
4710 _dbus_verbose ("No memory\n");
4713 else if (result == DBUS_HANDLER_RESULT_HANDLED)
4715 _dbus_verbose ("filter handled message in dispatch\n");
4719 /* We're still protected from dispatch() reentrancy here
4720 * since we acquired the dispatcher
4722 _dbus_verbose (" running object path dispatch on message %p (%s %s %s '%s')\n",
4724 dbus_message_type_to_string (dbus_message_get_type (message)),
4725 dbus_message_get_interface (message) ?
4726 dbus_message_get_interface (message) :
4728 dbus_message_get_member (message) ?
4729 dbus_message_get_member (message) :
4731 dbus_message_get_signature (message));
4733 HAVE_LOCK_CHECK (connection);
4734 result = _dbus_object_tree_dispatch_and_unlock (connection->objects,
4738 CONNECTION_LOCK (connection);
4740 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4742 _dbus_verbose ("object tree handled message in dispatch\n");
4746 if (dbus_message_get_type (message) == DBUS_MESSAGE_TYPE_METHOD_CALL)
4750 DBusPreallocatedSend *preallocated;
4751 DBusList *expire_link;
4753 _dbus_verbose (" sending error %s\n",
4754 DBUS_ERROR_UNKNOWN_METHOD);
4756 if (!_dbus_string_init (&str))
4758 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4759 _dbus_verbose ("no memory for error string in dispatch\n");
4763 if (!_dbus_string_append_printf (&str,
4764 "Method \"%s\" with signature \"%s\" on interface \"%s\" doesn't exist\n",
4765 dbus_message_get_member (message),
4766 dbus_message_get_signature (message),
4767 dbus_message_get_interface (message)))
4769 _dbus_string_free (&str);
4770 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4771 _dbus_verbose ("no memory for error string in dispatch\n");
4775 reply = dbus_message_new_error (message,
4776 found_object ? DBUS_ERROR_UNKNOWN_METHOD : DBUS_ERROR_UNKNOWN_OBJECT,
4777 _dbus_string_get_const_data (&str));
4778 _dbus_string_free (&str);
4782 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4783 _dbus_verbose ("no memory for error reply in dispatch\n");
4787 expire_link = _dbus_list_alloc_link (reply);
4789 if (expire_link == NULL)
4791 dbus_message_unref (reply);
4792 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4793 _dbus_verbose ("no memory for error send in dispatch\n");
4797 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
4799 if (preallocated == NULL)
4801 _dbus_list_free_link (expire_link);
4802 /* It's OK that this is finalized, because it hasn't been seen by
4803 * anything that could attach user callbacks */
4804 dbus_message_unref (reply);
4805 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4806 _dbus_verbose ("no memory for error send in dispatch\n");
4810 _dbus_connection_send_preallocated_unlocked_no_update (connection, preallocated,
4812 /* reply will be freed when we release the lock */
4813 _dbus_list_prepend_link (&connection->expired_messages, expire_link);
4815 result = DBUS_HANDLER_RESULT_HANDLED;
4818 _dbus_verbose (" done dispatching %p (%s %s %s '%s') on connection %p\n", message,
4819 dbus_message_type_to_string (dbus_message_get_type (message)),
4820 dbus_message_get_interface (message) ?
4821 dbus_message_get_interface (message) :
4823 dbus_message_get_member (message) ?
4824 dbus_message_get_member (message) :
4826 dbus_message_get_signature (message),
4830 if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
4832 _dbus_verbose ("out of memory\n");
4834 /* Put message back, and we'll start over.
4835 * Yes this means handlers must be idempotent if they
4836 * don't return HANDLED; c'est la vie.
4838 _dbus_connection_putback_message_link_unlocked (connection,
4840 /* now we don't want to free them */
4841 message_link = NULL;
4846 _dbus_verbose (" ... done dispatching\n");
4849 _dbus_connection_release_dispatch (connection);
4850 HAVE_LOCK_CHECK (connection);
4852 if (message != NULL)
4854 /* We don't want this message to count in maximum message limits when
4855 * computing the dispatch status, below. We have to drop the lock
4856 * temporarily, because finalizing a message can trigger callbacks.
4858 * We have a reference to the connection, and we don't use any cached
4859 * pointers to the connection's internals below this point, so it should
4860 * be safe to drop the lock and take it back. */
4861 CONNECTION_UNLOCK (connection);
4862 dbus_message_unref (message);
4863 CONNECTION_LOCK (connection);
4866 if (message_link != NULL)
4867 _dbus_list_free_link (message_link);
4869 _dbus_verbose ("before final status update\n");
4870 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4872 /* unlocks and calls user code */
4873 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4875 dbus_connection_unref (connection);
4881 * Sets the watch functions for the connection. These functions are
4882 * responsible for making the application's main loop aware of file
4883 * descriptors that need to be monitored for events, using select() or
4884 * poll(). When using Qt, typically the DBusAddWatchFunction would
4885 * create a QSocketNotifier. When using GLib, the DBusAddWatchFunction
4886 * could call g_io_add_watch(), or could be used as part of a more
4887 * elaborate GSource. Note that when a watch is added, it may
4890 * The DBusWatchToggledFunction notifies the application that the
4891 * watch has been enabled or disabled. Call dbus_watch_get_enabled()
4892 * to check this. A disabled watch should have no effect, and enabled
4893 * watch should be added to the main loop. This feature is used
4894 * instead of simply adding/removing the watch because
4895 * enabling/disabling can be done without memory allocation. The
4896 * toggled function may be NULL if a main loop re-queries
4897 * dbus_watch_get_enabled() every time anyway.
4899 * The DBusWatch can be queried for the file descriptor to watch using
4900 * dbus_watch_get_unix_fd() or dbus_watch_get_socket(), and for the
4901 * events to watch for using dbus_watch_get_flags(). The flags
4902 * returned by dbus_watch_get_flags() will only contain
4903 * DBUS_WATCH_READABLE and DBUS_WATCH_WRITABLE, never
4904 * DBUS_WATCH_HANGUP or DBUS_WATCH_ERROR; all watches implicitly
4905 * include a watch for hangups, errors, and other exceptional
4908 * Once a file descriptor becomes readable or writable, or an exception
4909 * occurs, dbus_watch_handle() should be called to
4910 * notify the connection of the file descriptor's condition.
4912 * dbus_watch_handle() cannot be called during the
4913 * DBusAddWatchFunction, as the connection will not be ready to handle
4916 * It is not allowed to reference a DBusWatch after it has been passed
4917 * to remove_function.
4919 * If #FALSE is returned due to lack of memory, the failure may be due
4920 * to a #FALSE return from the new add_function. If so, the
4921 * add_function may have been called successfully one or more times,
4922 * but the remove_function will also have been called to remove any
4923 * successful adds. i.e. if #FALSE is returned the net result
4924 * should be that dbus_connection_set_watch_functions() has no effect,
4925 * but the add_function and remove_function may have been called.
4927 * @note The thread lock on DBusConnection is held while
4928 * watch functions are invoked, so inside these functions you
4929 * may not invoke any methods on DBusConnection or it will deadlock.
4930 * See the comments in the code or http://lists.freedesktop.org/archives/dbus/2007-July/tread.html#8144
4931 * if you encounter this issue and want to attempt writing a patch.
4933 * @param connection the connection.
4934 * @param add_function function to begin monitoring a new descriptor.
4935 * @param remove_function function to stop monitoring a descriptor.
4936 * @param toggled_function function to notify of enable/disable
4937 * @param data data to pass to add_function and remove_function.
4938 * @param free_data_function function to be called to free the data.
4939 * @returns #FALSE on failure (no memory)
4942 dbus_connection_set_watch_functions (DBusConnection *connection,
4943 DBusAddWatchFunction add_function,
4944 DBusRemoveWatchFunction remove_function,
4945 DBusWatchToggledFunction toggled_function,
4947 DBusFreeFunction free_data_function)
4951 _dbus_return_val_if_fail (connection != NULL, FALSE);
4953 CONNECTION_LOCK (connection);
4955 retval = _dbus_watch_list_set_functions (connection->watches,
4956 add_function, remove_function,
4958 data, free_data_function);
4960 CONNECTION_UNLOCK (connection);
4966 * Sets the timeout functions for the connection. These functions are
4967 * responsible for making the application's main loop aware of timeouts.
4968 * When using Qt, typically the DBusAddTimeoutFunction would create a
4969 * QTimer. When using GLib, the DBusAddTimeoutFunction would call
4972 * The DBusTimeoutToggledFunction notifies the application that the
4973 * timeout has been enabled or disabled. Call
4974 * dbus_timeout_get_enabled() to check this. A disabled timeout should
4975 * have no effect, and enabled timeout should be added to the main
4976 * loop. This feature is used instead of simply adding/removing the
4977 * timeout because enabling/disabling can be done without memory
4978 * allocation. With Qt, QTimer::start() and QTimer::stop() can be used
4979 * to enable and disable. The toggled function may be NULL if a main
4980 * loop re-queries dbus_timeout_get_enabled() every time anyway.
4981 * Whenever a timeout is toggled, its interval may change.
4983 * The DBusTimeout can be queried for the timer interval using
4984 * dbus_timeout_get_interval(). dbus_timeout_handle() should be called
4985 * repeatedly, each time the interval elapses, starting after it has
4986 * elapsed once. The timeout stops firing when it is removed with the
4987 * given remove_function. The timer interval may change whenever the
4988 * timeout is added, removed, or toggled.
4990 * @note The thread lock on DBusConnection is held while
4991 * timeout functions are invoked, so inside these functions you
4992 * may not invoke any methods on DBusConnection or it will deadlock.
4993 * See the comments in the code or http://lists.freedesktop.org/archives/dbus/2007-July/thread.html#8144
4994 * if you encounter this issue and want to attempt writing a patch.
4996 * @param connection the connection.
4997 * @param add_function function to add a timeout.
4998 * @param remove_function function to remove a timeout.
4999 * @param toggled_function function to notify of enable/disable
5000 * @param data data to pass to add_function and remove_function.
5001 * @param free_data_function function to be called to free the data.
5002 * @returns #FALSE on failure (no memory)
5005 dbus_connection_set_timeout_functions (DBusConnection *connection,
5006 DBusAddTimeoutFunction add_function,
5007 DBusRemoveTimeoutFunction remove_function,
5008 DBusTimeoutToggledFunction toggled_function,
5010 DBusFreeFunction free_data_function)
5014 _dbus_return_val_if_fail (connection != NULL, FALSE);
5016 CONNECTION_LOCK (connection);
5018 retval = _dbus_timeout_list_set_functions (connection->timeouts,
5019 add_function, remove_function,
5021 data, free_data_function);
5023 CONNECTION_UNLOCK (connection);
5029 * Sets the mainloop wakeup function for the connection. This function
5030 * is responsible for waking up the main loop (if its sleeping in
5031 * another thread) when some some change has happened to the
5032 * connection that the mainloop needs to reconsider (e.g. a message
5033 * has been queued for writing). When using Qt, this typically
5034 * results in a call to QEventLoop::wakeUp(). When using GLib, it
5035 * would call g_main_context_wakeup().
5037 * @param connection the connection.
5038 * @param wakeup_main_function function to wake up the mainloop
5039 * @param data data to pass wakeup_main_function
5040 * @param free_data_function function to be called to free the data.
5043 dbus_connection_set_wakeup_main_function (DBusConnection *connection,
5044 DBusWakeupMainFunction wakeup_main_function,
5046 DBusFreeFunction free_data_function)
5049 DBusFreeFunction old_free_data;
5051 _dbus_return_if_fail (connection != NULL);
5053 CONNECTION_LOCK (connection);
5054 old_data = connection->wakeup_main_data;
5055 old_free_data = connection->free_wakeup_main_data;
5057 connection->wakeup_main_function = wakeup_main_function;
5058 connection->wakeup_main_data = data;
5059 connection->free_wakeup_main_data = free_data_function;
5061 CONNECTION_UNLOCK (connection);
5063 /* Callback outside the lock */
5065 (*old_free_data) (old_data);
5069 * Set a function to be invoked when the dispatch status changes.
5070 * If the dispatch status is #DBUS_DISPATCH_DATA_REMAINS, then
5071 * dbus_connection_dispatch() needs to be called to process incoming
5072 * messages. However, dbus_connection_dispatch() MUST NOT BE CALLED
5073 * from inside the DBusDispatchStatusFunction. Indeed, almost
5074 * any reentrancy in this function is a bad idea. Instead,
5075 * the DBusDispatchStatusFunction should simply save an indication
5076 * that messages should be dispatched later, when the main loop
5079 * If you don't set a dispatch status function, you have to be sure to
5080 * dispatch on every iteration of your main loop, especially if
5081 * dbus_watch_handle() or dbus_timeout_handle() were called.
5083 * @param connection the connection
5084 * @param function function to call on dispatch status changes
5085 * @param data data for function
5086 * @param free_data_function free the function data
5089 dbus_connection_set_dispatch_status_function (DBusConnection *connection,
5090 DBusDispatchStatusFunction function,
5092 DBusFreeFunction free_data_function)
5095 DBusFreeFunction old_free_data;
5097 _dbus_return_if_fail (connection != NULL);
5099 CONNECTION_LOCK (connection);
5100 old_data = connection->dispatch_status_data;
5101 old_free_data = connection->free_dispatch_status_data;
5103 connection->dispatch_status_function = function;
5104 connection->dispatch_status_data = data;
5105 connection->free_dispatch_status_data = free_data_function;
5107 CONNECTION_UNLOCK (connection);
5109 /* Callback outside the lock */
5111 (*old_free_data) (old_data);
5115 * Get the UNIX file descriptor of the connection, if any. This can
5116 * be used for SELinux access control checks with getpeercon() for
5117 * example. DO NOT read or write to the file descriptor, or try to
5118 * select() on it; use DBusWatch for main loop integration. Not all
5119 * connections will have a file descriptor. So for adding descriptors
5120 * to the main loop, use dbus_watch_get_unix_fd() and so forth.
5122 * If the connection is socket-based, you can also use
5123 * dbus_connection_get_socket(), which will work on Windows too.
5124 * This function always fails on Windows.
5126 * Right now the returned descriptor is always a socket, but
5127 * that is not guaranteed.
5129 * @param connection the connection
5130 * @param fd return location for the file descriptor.
5131 * @returns #TRUE if fd is successfully obtained.
5134 dbus_connection_get_unix_fd (DBusConnection *connection,
5137 _dbus_return_val_if_fail (connection != NULL, FALSE);
5138 _dbus_return_val_if_fail (connection->transport != NULL, FALSE);
5141 /* FIXME do this on a lower level */
5145 return dbus_connection_get_socket(connection, fd);
5149 * Gets the underlying Windows or UNIX socket file descriptor
5150 * of the connection, if any. DO NOT read or write to the file descriptor, or try to
5151 * select() on it; use DBusWatch for main loop integration. Not all
5152 * connections will have a socket. So for adding descriptors
5153 * to the main loop, use dbus_watch_get_socket() and so forth.
5155 * If the connection is not socket-based, this function will return FALSE,
5156 * even if the connection does have a file descriptor of some kind.
5157 * i.e. this function always returns specifically a socket file descriptor.
5159 * @param connection the connection
5160 * @param fd return location for the file descriptor.
5161 * @returns #TRUE if fd is successfully obtained.
5164 dbus_connection_get_socket(DBusConnection *connection,
5169 _dbus_return_val_if_fail (connection != NULL, FALSE);
5170 _dbus_return_val_if_fail (connection->transport != NULL, FALSE);
5172 CONNECTION_LOCK (connection);
5174 retval = _dbus_transport_get_socket_fd (connection->transport,
5177 CONNECTION_UNLOCK (connection);
5184 * Gets the UNIX user ID of the connection if known. Returns #TRUE if
5185 * the uid is filled in. Always returns #FALSE on non-UNIX platforms
5186 * for now, though in theory someone could hook Windows to NIS or
5187 * something. Always returns #FALSE prior to authenticating the
5190 * The UID is only read by servers from clients; clients can't usually
5191 * get the UID of servers, because servers do not authenticate to
5192 * clients. The returned UID is the UID the connection authenticated
5195 * The message bus is a server and the apps connecting to the bus
5198 * You can ask the bus to tell you the UID of another connection though
5199 * if you like; this is done with dbus_bus_get_unix_user().
5201 * @param connection the connection
5202 * @param uid return location for the user ID
5203 * @returns #TRUE if uid is filled in with a valid user ID
5206 dbus_connection_get_unix_user (DBusConnection *connection,
5211 _dbus_return_val_if_fail (connection != NULL, FALSE);
5212 _dbus_return_val_if_fail (uid != NULL, FALSE);
5214 CONNECTION_LOCK (connection);
5216 if (!_dbus_transport_get_is_authenticated (connection->transport))
5219 result = _dbus_transport_get_unix_user (connection->transport,
5223 _dbus_assert (!result);
5226 CONNECTION_UNLOCK (connection);
5232 * Gets the process ID of the connection if any.
5233 * Returns #TRUE if the pid is filled in.
5234 * Always returns #FALSE prior to authenticating the
5237 * @param connection the connection
5238 * @param pid return location for the process ID
5239 * @returns #TRUE if uid is filled in with a valid process ID
5242 dbus_connection_get_unix_process_id (DBusConnection *connection,
5247 _dbus_return_val_if_fail (connection != NULL, FALSE);
5248 _dbus_return_val_if_fail (pid != NULL, FALSE);
5250 CONNECTION_LOCK (connection);
5252 if (!_dbus_transport_get_is_authenticated (connection->transport))
5255 result = _dbus_transport_get_unix_process_id (connection->transport,
5258 CONNECTION_UNLOCK (connection);
5264 * Gets the ADT audit data of the connection if any.
5265 * Returns #TRUE if the structure pointer is returned.
5266 * Always returns #FALSE prior to authenticating the
5269 * @param connection the connection
5270 * @param data return location for audit data
5271 * @returns #TRUE if audit data is filled in with a valid ucred pointer
5274 dbus_connection_get_adt_audit_session_data (DBusConnection *connection,
5276 dbus_int32_t *data_size)
5280 _dbus_return_val_if_fail (connection != NULL, FALSE);
5281 _dbus_return_val_if_fail (data != NULL, FALSE);
5282 _dbus_return_val_if_fail (data_size != NULL, FALSE);
5284 CONNECTION_LOCK (connection);
5286 if (!_dbus_transport_get_is_authenticated (connection->transport))
5289 result = _dbus_transport_get_adt_audit_session_data (connection->transport,
5292 CONNECTION_UNLOCK (connection);
5298 * Sets a predicate function used to determine whether a given user ID
5299 * is allowed to connect. When an incoming connection has
5300 * authenticated with a particular user ID, this function is called;
5301 * if it returns #TRUE, the connection is allowed to proceed,
5302 * otherwise the connection is disconnected.
5304 * If the function is set to #NULL (as it is by default), then
5305 * only the same UID as the server process will be allowed to
5306 * connect. Also, root is always allowed to connect.
5308 * On Windows, the function will be set and its free_data_function will
5309 * be invoked when the connection is freed or a new function is set.
5310 * However, the function will never be called, because there are
5311 * no UNIX user ids to pass to it, or at least none of the existing
5312 * auth protocols would allow authenticating as a UNIX user on Windows.
5314 * @param connection the connection
5315 * @param function the predicate
5316 * @param data data to pass to the predicate
5317 * @param free_data_function function to free the data
5320 dbus_connection_set_unix_user_function (DBusConnection *connection,
5321 DBusAllowUnixUserFunction function,
5323 DBusFreeFunction free_data_function)
5325 void *old_data = NULL;
5326 DBusFreeFunction old_free_function = NULL;
5328 _dbus_return_if_fail (connection != NULL);
5330 CONNECTION_LOCK (connection);
5331 _dbus_transport_set_unix_user_function (connection->transport,
5332 function, data, free_data_function,
5333 &old_data, &old_free_function);
5334 CONNECTION_UNLOCK (connection);
5336 if (old_free_function != NULL)
5337 (* old_free_function) (old_data);
5341 * Gets the Windows user SID of the connection if known. Returns
5342 * #TRUE if the ID is filled in. Always returns #FALSE on non-Windows
5343 * platforms for now, though in theory someone could hook UNIX to
5344 * Active Directory or something. Always returns #FALSE prior to
5345 * authenticating the connection.
5347 * The user is only read by servers from clients; clients can't usually
5348 * get the user of servers, because servers do not authenticate to
5349 * clients. The returned user is the user the connection authenticated
5352 * The message bus is a server and the apps connecting to the bus
5355 * The returned user string has to be freed with dbus_free().
5357 * The return value indicates whether the user SID is available;
5358 * if it's available but we don't have the memory to copy it,
5359 * then the return value is #TRUE and #NULL is given as the SID.
5361 * @todo We would like to be able to say "You can ask the bus to tell
5362 * you the user of another connection though if you like; this is done
5363 * with dbus_bus_get_windows_user()." But this has to be implemented
5364 * in bus/driver.c and dbus/dbus-bus.c, and is pointless anyway
5365 * since on Windows we only use the session bus for now.
5367 * @param connection the connection
5368 * @param windows_sid_p return location for an allocated copy of the user ID, or #NULL if no memory
5369 * @returns #TRUE if user is available (returned value may be #NULL anyway if no memory)
5372 dbus_connection_get_windows_user (DBusConnection *connection,
5373 char **windows_sid_p)
5377 _dbus_return_val_if_fail (connection != NULL, FALSE);
5378 _dbus_return_val_if_fail (windows_sid_p != NULL, FALSE);
5380 CONNECTION_LOCK (connection);
5382 if (!_dbus_transport_get_is_authenticated (connection->transport))
5385 result = _dbus_transport_get_windows_user (connection->transport,
5389 _dbus_assert (!result);
5392 CONNECTION_UNLOCK (connection);
5398 * Sets a predicate function used to determine whether a given user ID
5399 * is allowed to connect. When an incoming connection has
5400 * authenticated with a particular user ID, this function is called;
5401 * if it returns #TRUE, the connection is allowed to proceed,
5402 * otherwise the connection is disconnected.
5404 * If the function is set to #NULL (as it is by default), then
5405 * only the same user owning the server process will be allowed to
5408 * On UNIX, the function will be set and its free_data_function will
5409 * be invoked when the connection is freed or a new function is set.
5410 * However, the function will never be called, because there is no
5411 * way right now to authenticate as a Windows user on UNIX.
5413 * @param connection the connection
5414 * @param function the predicate
5415 * @param data data to pass to the predicate
5416 * @param free_data_function function to free the data
5419 dbus_connection_set_windows_user_function (DBusConnection *connection,
5420 DBusAllowWindowsUserFunction function,
5422 DBusFreeFunction free_data_function)
5424 void *old_data = NULL;
5425 DBusFreeFunction old_free_function = NULL;
5427 _dbus_return_if_fail (connection != NULL);
5429 CONNECTION_LOCK (connection);
5430 _dbus_transport_set_windows_user_function (connection->transport,
5431 function, data, free_data_function,
5432 &old_data, &old_free_function);
5433 CONNECTION_UNLOCK (connection);
5435 if (old_free_function != NULL)
5436 (* old_free_function) (old_data);
5440 * This function must be called on the server side of a connection when the
5441 * connection is first seen in the #DBusNewConnectionFunction. If set to
5442 * #TRUE (the default is #FALSE), then the connection can proceed even if
5443 * the client does not authenticate as some user identity, i.e. clients
5444 * can connect anonymously.
5446 * This setting interacts with the available authorization mechanisms
5447 * (see dbus_server_set_auth_mechanisms()). Namely, an auth mechanism
5448 * such as ANONYMOUS that supports anonymous auth must be included in
5449 * the list of available mechanisms for anonymous login to work.
5451 * This setting also changes the default rule for connections
5452 * authorized as a user; normally, if a connection authorizes as
5453 * a user identity, it is permitted if the user identity is
5454 * root or the user identity matches the user identity of the server
5455 * process. If anonymous connections are allowed, however,
5456 * then any user identity is allowed.
5458 * You can override the rules for connections authorized as a
5459 * user identity with dbus_connection_set_unix_user_function()
5460 * and dbus_connection_set_windows_user_function().
5462 * @param connection the connection
5463 * @param value whether to allow authentication as an anonymous user
5466 dbus_connection_set_allow_anonymous (DBusConnection *connection,
5469 _dbus_return_if_fail (connection != NULL);
5471 CONNECTION_LOCK (connection);
5472 _dbus_transport_set_allow_anonymous (connection->transport, value);
5473 CONNECTION_UNLOCK (connection);
5478 * Normally #DBusConnection automatically handles all messages to the
5479 * org.freedesktop.DBus.Peer interface. However, the message bus wants
5480 * to be able to route methods on that interface through the bus and
5481 * to other applications. If routing peer messages is enabled, then
5482 * messages with the org.freedesktop.DBus.Peer interface that also
5483 * have a bus destination name set will not be automatically
5484 * handled by the #DBusConnection and instead will be dispatched
5485 * normally to the application.
5487 * If a normal application sets this flag, it can break things badly.
5488 * So don't set this unless you are the message bus.
5490 * @param connection the connection
5491 * @param value #TRUE to pass through org.freedesktop.DBus.Peer messages with a bus name set
5494 dbus_connection_set_route_peer_messages (DBusConnection *connection,
5497 _dbus_return_if_fail (connection != NULL);
5499 CONNECTION_LOCK (connection);
5500 connection->route_peer_messages = TRUE;
5501 CONNECTION_UNLOCK (connection);
5505 * Adds a message filter. Filters are handlers that are run on all
5506 * incoming messages, prior to the objects registered with
5507 * dbus_connection_register_object_path(). Filters are run in the
5508 * order that they were added. The same handler can be added as a
5509 * filter more than once, in which case it will be run more than once.
5510 * Filters added during a filter callback won't be run on the message
5513 * @todo we don't run filters on messages while blocking without
5514 * entering the main loop, since filters are run as part of
5515 * dbus_connection_dispatch(). This is probably a feature, as filters
5516 * could create arbitrary reentrancy. But kind of sucks if you're
5517 * trying to filter METHOD_RETURN for some reason.
5519 * @param connection the connection
5520 * @param function function to handle messages
5521 * @param user_data user data to pass to the function
5522 * @param free_data_function function to use for freeing user data
5523 * @returns #TRUE on success, #FALSE if not enough memory.
5526 dbus_connection_add_filter (DBusConnection *connection,
5527 DBusHandleMessageFunction function,
5529 DBusFreeFunction free_data_function)
5531 DBusMessageFilter *filter;
5533 _dbus_return_val_if_fail (connection != NULL, FALSE);
5534 _dbus_return_val_if_fail (function != NULL, FALSE);
5536 filter = dbus_new0 (DBusMessageFilter, 1);
5540 _dbus_atomic_inc (&filter->refcount);
5542 CONNECTION_LOCK (connection);
5544 if (!_dbus_list_append (&connection->filter_list,
5547 _dbus_message_filter_unref (filter);
5548 CONNECTION_UNLOCK (connection);
5552 /* Fill in filter after all memory allocated,
5553 * so we don't run the free_user_data_function
5554 * if the add_filter() fails
5557 filter->function = function;
5558 filter->user_data = user_data;
5559 filter->free_user_data_function = free_data_function;
5561 CONNECTION_UNLOCK (connection);
5566 * Removes a previously-added message filter. It is a programming
5567 * error to call this function for a handler that has not been added
5568 * as a filter. If the given handler was added more than once, only
5569 * one instance of it will be removed (the most recently-added
5572 * @param connection the connection
5573 * @param function the handler to remove
5574 * @param user_data user data for the handler to remove
5578 dbus_connection_remove_filter (DBusConnection *connection,
5579 DBusHandleMessageFunction function,
5583 DBusMessageFilter *filter;
5585 _dbus_return_if_fail (connection != NULL);
5586 _dbus_return_if_fail (function != NULL);
5588 CONNECTION_LOCK (connection);
5592 link = _dbus_list_get_last_link (&connection->filter_list);
5593 while (link != NULL)
5595 filter = link->data;
5597 if (filter->function == function &&
5598 filter->user_data == user_data)
5600 _dbus_list_remove_link (&connection->filter_list, link);
5601 filter->function = NULL;
5606 link = _dbus_list_get_prev_link (&connection->filter_list, link);
5610 CONNECTION_UNLOCK (connection);
5612 #ifndef DBUS_DISABLE_CHECKS
5615 _dbus_warn_check_failed ("Attempt to remove filter function %p user data %p, but no such filter has been added\n",
5616 function, user_data);
5621 /* Call application code */
5622 if (filter->free_user_data_function)
5623 (* filter->free_user_data_function) (filter->user_data);
5625 filter->free_user_data_function = NULL;
5626 filter->user_data = NULL;
5628 _dbus_message_filter_unref (filter);
5632 * Registers a handler for a given path or subsection in the object
5633 * hierarchy. The given vtable handles messages sent to exactly the
5634 * given path or also for paths bellow that, depending on fallback
5637 * @param connection the connection
5638 * @param fallback whether to handle messages also for "subdirectory"
5639 * @param path a '/' delimited string of path elements
5640 * @param vtable the virtual table
5641 * @param user_data data to pass to functions in the vtable
5642 * @param error address where an error can be returned
5643 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5644 * #DBUS_ERROR_OBJECT_PATH_IN_USE) is reported
5647 _dbus_connection_register_object_path (DBusConnection *connection,
5648 dbus_bool_t fallback,
5650 const DBusObjectPathVTable *vtable,
5654 char **decomposed_path;
5657 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5660 CONNECTION_LOCK (connection);
5662 retval = _dbus_object_tree_register (connection->objects,
5664 (const char **) decomposed_path, vtable,
5667 CONNECTION_UNLOCK (connection);
5669 dbus_free_string_array (decomposed_path);
5675 * Registers a handler for a given path in the object hierarchy.
5676 * The given vtable handles messages sent to exactly the given path.
5678 * @param connection the connection
5679 * @param path a '/' delimited string of path elements
5680 * @param vtable the virtual table
5681 * @param user_data data to pass to functions in the vtable
5682 * @param error address where an error can be returned
5683 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5684 * #DBUS_ERROR_OBJECT_PATH_IN_USE) is reported
5687 dbus_connection_try_register_object_path (DBusConnection *connection,
5689 const DBusObjectPathVTable *vtable,
5693 _dbus_return_val_if_fail (connection != NULL, FALSE);
5694 _dbus_return_val_if_fail (path != NULL, FALSE);
5695 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5696 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5698 return _dbus_connection_register_object_path (connection, FALSE, path, vtable, user_data, error);
5702 * Registers a handler for a given path in the object hierarchy.
5703 * The given vtable handles messages sent to exactly the given path.
5705 * It is a bug to call this function for object paths which already
5706 * have a handler. Use dbus_connection_try_register_object_path() if this
5707 * might be the case.
5709 * @param connection the connection
5710 * @param path a '/' delimited string of path elements
5711 * @param vtable the virtual table
5712 * @param user_data data to pass to functions in the vtable
5713 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5714 * #DBUS_ERROR_OBJECT_PATH_IN_USE) ocurred
5717 dbus_connection_register_object_path (DBusConnection *connection,
5719 const DBusObjectPathVTable *vtable,
5723 DBusError error = DBUS_ERROR_INIT;
5725 _dbus_return_val_if_fail (connection != NULL, FALSE);
5726 _dbus_return_val_if_fail (path != NULL, FALSE);
5727 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5728 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5730 retval = _dbus_connection_register_object_path (connection, FALSE, path, vtable, user_data, &error);
5732 if (dbus_error_has_name (&error, DBUS_ERROR_OBJECT_PATH_IN_USE))
5734 _dbus_warn ("%s\n", error.message);
5735 dbus_error_free (&error);
5743 * Registers a fallback handler for a given subsection of the object
5744 * hierarchy. The given vtable handles messages at or below the given
5745 * path. You can use this to establish a default message handling
5746 * policy for a whole "subdirectory."
5748 * @param connection the connection
5749 * @param path a '/' delimited string of path elements
5750 * @param vtable the virtual table
5751 * @param user_data data to pass to functions in the vtable
5752 * @param error address where an error can be returned
5753 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5754 * #DBUS_ERROR_OBJECT_PATH_IN_USE) is reported
5757 dbus_connection_try_register_fallback (DBusConnection *connection,
5759 const DBusObjectPathVTable *vtable,
5763 _dbus_return_val_if_fail (connection != NULL, FALSE);
5764 _dbus_return_val_if_fail (path != NULL, FALSE);
5765 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5766 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5768 return _dbus_connection_register_object_path (connection, TRUE, path, vtable, user_data, error);
5772 * Registers a fallback handler for a given subsection of the object
5773 * hierarchy. The given vtable handles messages at or below the given
5774 * path. You can use this to establish a default message handling
5775 * policy for a whole "subdirectory."
5777 * It is a bug to call this function for object paths which already
5778 * have a handler. Use dbus_connection_try_register_fallback() if this
5779 * might be the case.
5781 * @param connection the connection
5782 * @param path a '/' delimited string of path elements
5783 * @param vtable the virtual table
5784 * @param user_data data to pass to functions in the vtable
5785 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5786 * #DBUS_ERROR_OBJECT_PATH_IN_USE) occured
5789 dbus_connection_register_fallback (DBusConnection *connection,
5791 const DBusObjectPathVTable *vtable,
5795 DBusError error = DBUS_ERROR_INIT;
5797 _dbus_return_val_if_fail (connection != NULL, FALSE);
5798 _dbus_return_val_if_fail (path != NULL, FALSE);
5799 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5800 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5802 retval = _dbus_connection_register_object_path (connection, TRUE, path, vtable, user_data, &error);
5804 if (dbus_error_has_name (&error, DBUS_ERROR_OBJECT_PATH_IN_USE))
5806 _dbus_warn ("%s\n", error.message);
5807 dbus_error_free (&error);
5815 * Unregisters the handler registered with exactly the given path.
5816 * It's a bug to call this function for a path that isn't registered.
5817 * Can unregister both fallback paths and object paths.
5819 * @param connection the connection
5820 * @param path a '/' delimited string of path elements
5821 * @returns #FALSE if not enough memory
5824 dbus_connection_unregister_object_path (DBusConnection *connection,
5827 char **decomposed_path;
5829 _dbus_return_val_if_fail (connection != NULL, FALSE);
5830 _dbus_return_val_if_fail (path != NULL, FALSE);
5831 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5833 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5836 CONNECTION_LOCK (connection);
5838 _dbus_object_tree_unregister_and_unlock (connection->objects, (const char **) decomposed_path);
5840 dbus_free_string_array (decomposed_path);
5846 * Gets the user data passed to dbus_connection_register_object_path()
5847 * or dbus_connection_register_fallback(). If nothing was registered
5848 * at this path, the data is filled in with #NULL.
5850 * @param connection the connection
5851 * @param path the path you registered with
5852 * @param data_p location to store the user data, or #NULL
5853 * @returns #FALSE if not enough memory
5856 dbus_connection_get_object_path_data (DBusConnection *connection,
5860 char **decomposed_path;
5862 _dbus_return_val_if_fail (connection != NULL, FALSE);
5863 _dbus_return_val_if_fail (path != NULL, FALSE);
5864 _dbus_return_val_if_fail (data_p != NULL, FALSE);
5868 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5871 CONNECTION_LOCK (connection);
5873 *data_p = _dbus_object_tree_get_user_data_unlocked (connection->objects, (const char**) decomposed_path);
5875 CONNECTION_UNLOCK (connection);
5877 dbus_free_string_array (decomposed_path);
5883 * Lists the registered fallback handlers and object path handlers at
5884 * the given parent_path. The returned array should be freed with
5885 * dbus_free_string_array().
5887 * @param connection the connection
5888 * @param parent_path the path to list the child handlers of
5889 * @param child_entries returns #NULL-terminated array of children
5890 * @returns #FALSE if no memory to allocate the child entries
5893 dbus_connection_list_registered (DBusConnection *connection,
5894 const char *parent_path,
5895 char ***child_entries)
5897 char **decomposed_path;
5899 _dbus_return_val_if_fail (connection != NULL, FALSE);
5900 _dbus_return_val_if_fail (parent_path != NULL, FALSE);
5901 _dbus_return_val_if_fail (parent_path[0] == '/', FALSE);
5902 _dbus_return_val_if_fail (child_entries != NULL, FALSE);
5904 if (!_dbus_decompose_path (parent_path, strlen (parent_path), &decomposed_path, NULL))
5907 CONNECTION_LOCK (connection);
5909 retval = _dbus_object_tree_list_registered_and_unlock (connection->objects,
5910 (const char **) decomposed_path,
5912 dbus_free_string_array (decomposed_path);
5917 static DBusDataSlotAllocator slot_allocator =
5918 _DBUS_DATA_SLOT_ALLOCATOR_INIT (_DBUS_LOCK_NAME (connection_slots));
5921 * Allocates an integer ID to be used for storing application-specific
5922 * data on any DBusConnection. The allocated ID may then be used
5923 * with dbus_connection_set_data() and dbus_connection_get_data().
5924 * The passed-in slot must be initialized to -1, and is filled in
5925 * with the slot ID. If the passed-in slot is not -1, it's assumed
5926 * to be already allocated, and its refcount is incremented.
5928 * The allocated slot is global, i.e. all DBusConnection objects will
5929 * have a slot with the given integer ID reserved.
5931 * @param slot_p address of a global variable storing the slot
5932 * @returns #FALSE on failure (no memory)
5935 dbus_connection_allocate_data_slot (dbus_int32_t *slot_p)
5937 return _dbus_data_slot_allocator_alloc (&slot_allocator,
5942 * Deallocates a global ID for connection data slots.
5943 * dbus_connection_get_data() and dbus_connection_set_data() may no
5944 * longer be used with this slot. Existing data stored on existing
5945 * DBusConnection objects will be freed when the connection is
5946 * finalized, but may not be retrieved (and may only be replaced if
5947 * someone else reallocates the slot). When the refcount on the
5948 * passed-in slot reaches 0, it is set to -1.
5950 * @param slot_p address storing the slot to deallocate
5953 dbus_connection_free_data_slot (dbus_int32_t *slot_p)
5955 _dbus_return_if_fail (*slot_p >= 0);
5957 _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
5961 * Stores a pointer on a DBusConnection, along
5962 * with an optional function to be used for freeing
5963 * the data when the data is set again, or when
5964 * the connection is finalized. The slot number
5965 * must have been allocated with dbus_connection_allocate_data_slot().
5967 * @note This function does not take the
5968 * main thread lock on DBusConnection, which allows it to be
5969 * used from inside watch and timeout functions. (See the
5970 * note in docs for dbus_connection_set_watch_functions().)
5971 * A side effect of this is that you need to know there's
5972 * a reference held on the connection while invoking
5973 * dbus_connection_set_data(), or the connection could be
5974 * finalized during dbus_connection_set_data().
5976 * @param connection the connection
5977 * @param slot the slot number
5978 * @param data the data to store
5979 * @param free_data_func finalizer function for the data
5980 * @returns #TRUE if there was enough memory to store the data
5983 dbus_connection_set_data (DBusConnection *connection,
5986 DBusFreeFunction free_data_func)
5988 DBusFreeFunction old_free_func;
5992 _dbus_return_val_if_fail (connection != NULL, FALSE);
5993 _dbus_return_val_if_fail (slot >= 0, FALSE);
5995 SLOTS_LOCK (connection);
5997 retval = _dbus_data_slot_list_set (&slot_allocator,
5998 &connection->slot_list,
5999 slot, data, free_data_func,
6000 &old_free_func, &old_data);
6002 SLOTS_UNLOCK (connection);
6006 /* Do the actual free outside the connection lock */
6008 (* old_free_func) (old_data);
6015 * Retrieves data previously set with dbus_connection_set_data().
6016 * The slot must still be allocated (must not have been freed).
6018 * @note This function does not take the
6019 * main thread lock on DBusConnection, which allows it to be
6020 * used from inside watch and timeout functions. (See the
6021 * note in docs for dbus_connection_set_watch_functions().)
6022 * A side effect of this is that you need to know there's
6023 * a reference held on the connection while invoking
6024 * dbus_connection_get_data(), or the connection could be
6025 * finalized during dbus_connection_get_data().
6027 * @param connection the connection
6028 * @param slot the slot to get data from
6029 * @returns the data, or #NULL if not found
6032 dbus_connection_get_data (DBusConnection *connection,
6037 _dbus_return_val_if_fail (connection != NULL, NULL);
6038 _dbus_return_val_if_fail (slot >= 0, NULL);
6040 SLOTS_LOCK (connection);
6042 res = _dbus_data_slot_list_get (&slot_allocator,
6043 &connection->slot_list,
6046 SLOTS_UNLOCK (connection);
6052 * This function sets a global flag for whether dbus_connection_new()
6053 * will set SIGPIPE behavior to SIG_IGN.
6055 * @param will_modify_sigpipe #TRUE to allow sigpipe to be set to SIG_IGN
6058 dbus_connection_set_change_sigpipe (dbus_bool_t will_modify_sigpipe)
6060 _dbus_modify_sigpipe = will_modify_sigpipe != FALSE;
6064 * Specifies the maximum size message this connection is allowed to
6065 * receive. Larger messages will result in disconnecting the
6068 * @param connection a #DBusConnection
6069 * @param size maximum message size the connection can receive, in bytes
6072 dbus_connection_set_max_message_size (DBusConnection *connection,
6075 _dbus_return_if_fail (connection != NULL);
6077 CONNECTION_LOCK (connection);
6078 _dbus_transport_set_max_message_size (connection->transport,
6080 CONNECTION_UNLOCK (connection);
6084 * Gets the value set by dbus_connection_set_max_message_size().
6086 * @param connection the connection
6087 * @returns the max size of a single message
6090 dbus_connection_get_max_message_size (DBusConnection *connection)
6094 _dbus_return_val_if_fail (connection != NULL, 0);
6096 CONNECTION_LOCK (connection);
6097 res = _dbus_transport_get_max_message_size (connection->transport);
6098 CONNECTION_UNLOCK (connection);
6103 * Specifies the maximum number of unix fds a message on this
6104 * connection is allowed to receive. Messages with more unix fds will
6105 * result in disconnecting the connection.
6107 * @param connection a #DBusConnection
6108 * @param size maximum message unix fds the connection can receive
6111 dbus_connection_set_max_message_unix_fds (DBusConnection *connection,
6114 _dbus_return_if_fail (connection != NULL);
6116 CONNECTION_LOCK (connection);
6117 _dbus_transport_set_max_message_unix_fds (connection->transport,
6119 CONNECTION_UNLOCK (connection);
6123 * Gets the value set by dbus_connection_set_max_message_unix_fds().
6125 * @param connection the connection
6126 * @returns the max numer of unix fds of a single message
6129 dbus_connection_get_max_message_unix_fds (DBusConnection *connection)
6133 _dbus_return_val_if_fail (connection != NULL, 0);
6135 CONNECTION_LOCK (connection);
6136 res = _dbus_transport_get_max_message_unix_fds (connection->transport);
6137 CONNECTION_UNLOCK (connection);
6142 * Sets the maximum total number of bytes that can be used for all messages
6143 * received on this connection. Messages count toward the maximum until
6144 * they are finalized. When the maximum is reached, the connection will
6145 * not read more data until some messages are finalized.
6147 * The semantics of the maximum are: if outstanding messages are
6148 * already above the maximum, additional messages will not be read.
6149 * The semantics are not: if the next message would cause us to exceed
6150 * the maximum, we don't read it. The reason is that we don't know the
6151 * size of a message until after we read it.
6153 * Thus, the max live messages size can actually be exceeded
6154 * by up to the maximum size of a single message.
6156 * Also, if we read say 1024 bytes off the wire in a single read(),
6157 * and that contains a half-dozen small messages, we may exceed the
6158 * size max by that amount. But this should be inconsequential.
6160 * This does imply that we can't call read() with a buffer larger
6161 * than we're willing to exceed this limit by.
6163 * @param connection the connection
6164 * @param size the maximum size in bytes of all outstanding messages
6167 dbus_connection_set_max_received_size (DBusConnection *connection,
6170 _dbus_return_if_fail (connection != NULL);
6172 CONNECTION_LOCK (connection);
6173 _dbus_transport_set_max_received_size (connection->transport,
6175 CONNECTION_UNLOCK (connection);
6179 * Gets the value set by dbus_connection_set_max_received_size().
6181 * @param connection the connection
6182 * @returns the max size of all live messages
6185 dbus_connection_get_max_received_size (DBusConnection *connection)
6189 _dbus_return_val_if_fail (connection != NULL, 0);
6191 CONNECTION_LOCK (connection);
6192 res = _dbus_transport_get_max_received_size (connection->transport);
6193 CONNECTION_UNLOCK (connection);
6198 * Sets the maximum total number of unix fds that can be used for all messages
6199 * received on this connection. Messages count toward the maximum until
6200 * they are finalized. When the maximum is reached, the connection will
6201 * not read more data until some messages are finalized.
6203 * The semantics are analogous to those of dbus_connection_set_max_received_size().
6205 * @param connection the connection
6206 * @param size the maximum size in bytes of all outstanding messages
6209 dbus_connection_set_max_received_unix_fds (DBusConnection *connection,
6212 _dbus_return_if_fail (connection != NULL);
6214 CONNECTION_LOCK (connection);
6215 _dbus_transport_set_max_received_unix_fds (connection->transport,
6217 CONNECTION_UNLOCK (connection);
6221 * Gets the value set by dbus_connection_set_max_received_unix_fds().
6223 * @param connection the connection
6224 * @returns the max unix fds of all live messages
6227 dbus_connection_get_max_received_unix_fds (DBusConnection *connection)
6231 _dbus_return_val_if_fail (connection != NULL, 0);
6233 CONNECTION_LOCK (connection);
6234 res = _dbus_transport_get_max_received_unix_fds (connection->transport);
6235 CONNECTION_UNLOCK (connection);
6240 * Gets the approximate size in bytes of all messages in the outgoing
6241 * message queue. The size is approximate in that you shouldn't use
6242 * it to decide how many bytes to read off the network or anything
6243 * of that nature, as optimizations may choose to tell small white lies
6244 * to avoid performance overhead.
6246 * @param connection the connection
6247 * @returns the number of bytes that have been queued up but not sent
6250 dbus_connection_get_outgoing_size (DBusConnection *connection)
6254 _dbus_return_val_if_fail (connection != NULL, 0);
6256 CONNECTION_LOCK (connection);
6257 res = _dbus_counter_get_size_value (connection->outgoing_counter);
6258 CONNECTION_UNLOCK (connection);
6262 #ifdef DBUS_ENABLE_STATS
6264 _dbus_connection_get_stats (DBusConnection *connection,
6265 dbus_uint32_t *in_messages,
6266 dbus_uint32_t *in_bytes,
6267 dbus_uint32_t *in_fds,
6268 dbus_uint32_t *in_peak_bytes,
6269 dbus_uint32_t *in_peak_fds,
6270 dbus_uint32_t *out_messages,
6271 dbus_uint32_t *out_bytes,
6272 dbus_uint32_t *out_fds,
6273 dbus_uint32_t *out_peak_bytes,
6274 dbus_uint32_t *out_peak_fds)
6276 CONNECTION_LOCK (connection);
6278 if (in_messages != NULL)
6279 *in_messages = connection->n_incoming;
6281 _dbus_transport_get_stats (connection->transport,
6282 in_bytes, in_fds, in_peak_bytes, in_peak_fds);
6284 if (out_messages != NULL)
6285 *out_messages = connection->n_outgoing;
6287 if (out_bytes != NULL)
6288 *out_bytes = _dbus_counter_get_size_value (connection->outgoing_counter);
6290 if (out_fds != NULL)
6291 *out_fds = _dbus_counter_get_unix_fd_value (connection->outgoing_counter);
6293 if (out_peak_bytes != NULL)
6294 *out_peak_bytes = _dbus_counter_get_peak_size_value (connection->outgoing_counter);
6296 if (out_peak_fds != NULL)
6297 *out_peak_fds = _dbus_counter_get_peak_unix_fd_value (connection->outgoing_counter);
6299 CONNECTION_UNLOCK (connection);
6301 #endif /* DBUS_ENABLE_STATS */
6304 * Gets the approximate number of uni fds of all messages in the
6305 * outgoing message queue.
6307 * @param connection the connection
6308 * @returns the number of unix fds that have been queued up but not sent
6311 dbus_connection_get_outgoing_unix_fds (DBusConnection *connection)
6315 _dbus_return_val_if_fail (connection != NULL, 0);
6317 CONNECTION_LOCK (connection);
6318 res = _dbus_counter_get_unix_fd_value (connection->outgoing_counter);
6319 CONNECTION_UNLOCK (connection);
6324 * Returns the address of the transport object of this connection
6326 * @param connection the connection
6327 * @returns the address string
6330 _dbus_connection_get_address (DBusConnection *connection)
6332 return _dbus_transport_get_address (connection->transport);
6336 dbus_connection_get_transport(DBusConnection *connection)
6338 _dbus_return_val_if_fail (connection != NULL, NULL);
6340 return connection->transport;