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
209 _dbus_connection_trace_ref (DBusConnection *connection,
214 #ifdef DBUS_ENABLE_VERBOSE_MODE
215 static int enabled = -1;
217 _dbus_trace_ref ("DBusConnection", connection, old_refcount, new_refcount,
218 why, "DBUS_CONNECTION_TRACE", &enabled);
223 * Internal struct representing a message filter function
225 typedef struct DBusMessageFilter DBusMessageFilter;
228 * Internal struct representing a message filter function
230 struct DBusMessageFilter
232 DBusAtomic refcount; /**< Reference count */
233 DBusHandleMessageFunction function; /**< Function to call to filter */
234 void *user_data; /**< User data for the function */
235 DBusFreeFunction free_user_data_function; /**< Function to free the user data */
240 * Internals of DBusPreallocatedSend
242 struct DBusPreallocatedSend
244 DBusConnection *connection; /**< Connection we'd send the message to */
245 DBusList *queue_link; /**< Preallocated link in the queue */
246 DBusList *counter_link; /**< Preallocated link in the resource counter */
249 #if HAVE_DECL_MSG_NOSIGNAL
250 static dbus_bool_t _dbus_modify_sigpipe = FALSE;
252 static dbus_bool_t _dbus_modify_sigpipe = TRUE;
256 * Implementation details of DBusConnection. All fields are private.
258 struct DBusConnection
260 DBusAtomic refcount; /**< Reference count. */
262 DBusRMutex *mutex; /**< Lock on the entire DBusConnection */
264 DBusCMutex *dispatch_mutex; /**< Protects dispatch_acquired */
265 DBusCondVar *dispatch_cond; /**< Notify when dispatch_acquired is available */
266 DBusCMutex *io_path_mutex; /**< Protects io_path_acquired */
267 DBusCondVar *io_path_cond; /**< Notify when io_path_acquired is available */
269 DBusList *outgoing_messages; /**< Queue of messages we need to send, send the end of the list first. */
270 DBusList *incoming_messages; /**< Queue of messages we have received, end of the list received most recently. */
271 DBusList *expired_messages; /**< Messages that will be released when we next unlock. */
273 DBusMessage *message_borrowed; /**< Filled in if the first incoming message has been borrowed;
274 * dispatch_acquired will be set by the borrower
277 int n_outgoing; /**< Length of outgoing queue. */
278 int n_incoming; /**< Length of incoming queue. */
280 DBusCounter *outgoing_counter; /**< Counts size of outgoing messages. */
282 DBusTransport *transport; /**< Object that sends/receives messages over network. */
283 DBusWatchList *watches; /**< Stores active watches. */
284 DBusTimeoutList *timeouts; /**< Stores active timeouts. */
286 DBusList *filter_list; /**< List of filters. */
288 DBusRMutex *slot_mutex; /**< Lock on slot_list so overall connection lock need not be taken */
289 DBusDataSlotList slot_list; /**< Data stored by allocated integer ID */
291 DBusHashTable *pending_replies; /**< Hash of message serials to #DBusPendingCall. */
293 dbus_uint32_t client_serial; /**< Client serial. Increments each time a message is sent */
294 DBusList *disconnect_message_link; /**< Preallocated list node for queueing the disconnection message */
296 DBusWakeupMainFunction wakeup_main_function; /**< Function to wake up the mainloop */
297 void *wakeup_main_data; /**< Application data for wakeup_main_function */
298 DBusFreeFunction free_wakeup_main_data; /**< free wakeup_main_data */
300 DBusDispatchStatusFunction dispatch_status_function; /**< Function on dispatch status changes */
301 void *dispatch_status_data; /**< Application data for dispatch_status_function */
302 DBusFreeFunction free_dispatch_status_data; /**< free dispatch_status_data */
304 DBusDispatchStatus last_dispatch_status; /**< The last dispatch status we reported to the application. */
306 DBusObjectTree *objects; /**< Object path handlers registered with this connection */
308 char *server_guid; /**< GUID of server if we are in shared_connections, #NULL if server GUID is unknown or connection is private */
310 /* These two MUST be bools and not bitfields, because they are protected by a separate lock
311 * from connection->mutex and all bitfields in a word have to be read/written together.
312 * So you can't have a different lock for different bitfields in the same word.
314 dbus_bool_t dispatch_acquired; /**< Someone has dispatch path (can drain incoming queue) */
315 dbus_bool_t io_path_acquired; /**< Someone has transport io path (can use the transport to read/write messages) */
317 unsigned int shareable : 1; /**< #TRUE if libdbus owns a reference to the connection and can return it from dbus_connection_open() more than once */
319 unsigned int exit_on_disconnect : 1; /**< If #TRUE, exit after handling disconnect signal */
321 unsigned int route_peer_messages : 1; /**< If #TRUE, if org.freedesktop.DBus.Peer messages have a bus name, don't handle them automatically */
323 unsigned int disconnected_message_arrived : 1; /**< We popped or are dispatching the disconnected message.
324 * if the disconnect_message_link is NULL then we queued it, but
325 * this flag is whether it got to the head of the queue.
327 unsigned int disconnected_message_processed : 1; /**< We did our default handling of the disconnected message,
328 * such as closing the connection.
331 #ifndef DBUS_DISABLE_CHECKS
332 unsigned int have_connection_lock : 1; /**< Used to check locking */
335 #if defined(DBUS_ENABLE_CHECKS) || defined(DBUS_ENABLE_ASSERT)
336 int generation; /**< _dbus_current_generation that should correspond to this connection */
340 static DBusDispatchStatus _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection);
341 static void _dbus_connection_update_dispatch_status_and_unlock (DBusConnection *connection,
342 DBusDispatchStatus new_status);
343 static void _dbus_connection_last_unref (DBusConnection *connection);
344 static void _dbus_connection_acquire_dispatch (DBusConnection *connection);
345 static void _dbus_connection_release_dispatch (DBusConnection *connection);
346 static DBusDispatchStatus _dbus_connection_flush_unlocked (DBusConnection *connection);
347 static void _dbus_connection_close_possibly_shared_and_unlock (DBusConnection *connection);
348 static dbus_bool_t _dbus_connection_get_is_connected_unlocked (DBusConnection *connection);
349 static dbus_bool_t _dbus_connection_peek_for_reply_unlocked (DBusConnection *connection,
350 dbus_uint32_t client_serial);
352 static DBusMessageFilter *
353 _dbus_message_filter_ref (DBusMessageFilter *filter)
355 #ifdef DBUS_DISABLE_ASSERT
356 _dbus_atomic_inc (&filter->refcount);
358 dbus_int32_t old_value;
360 old_value = _dbus_atomic_inc (&filter->refcount);
361 _dbus_assert (old_value > 0);
368 _dbus_message_filter_unref (DBusMessageFilter *filter)
370 dbus_int32_t old_value;
372 old_value = _dbus_atomic_dec (&filter->refcount);
373 _dbus_assert (old_value > 0);
377 if (filter->free_user_data_function)
378 (* filter->free_user_data_function) (filter->user_data);
385 * Acquires the connection lock.
387 * @param connection the connection.
390 _dbus_connection_lock (DBusConnection *connection)
392 CONNECTION_LOCK (connection);
396 * Releases the connection lock.
398 * @param connection the connection.
401 _dbus_connection_unlock (DBusConnection *connection)
403 DBusList *expired_messages;
408 _dbus_verbose ("UNLOCK\n");
411 /* If we had messages that expired (fell off the incoming or outgoing
412 * queues) while we were locked, actually release them now */
413 expired_messages = connection->expired_messages;
414 connection->expired_messages = NULL;
416 RELEASING_LOCK_CHECK (connection);
417 _dbus_rmutex_unlock (connection->mutex);
419 for (iter = _dbus_list_pop_first_link (&expired_messages);
421 iter = _dbus_list_pop_first_link (&expired_messages))
423 DBusMessage *message = iter->data;
425 dbus_message_unref (message);
426 _dbus_list_free_link (iter);
431 * Wakes up the main loop if it is sleeping
432 * Needed if we're e.g. queueing outgoing messages
433 * on a thread while the mainloop sleeps.
435 * @param connection the connection.
438 _dbus_connection_wakeup_mainloop (DBusConnection *connection)
440 if (connection->wakeup_main_function)
441 (*connection->wakeup_main_function) (connection->wakeup_main_data);
444 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
446 * Gets the locks so we can examine them
448 * @param connection the connection.
449 * @param mutex_loc return for the location of the main mutex pointer
450 * @param dispatch_mutex_loc return location of the dispatch mutex pointer
451 * @param io_path_mutex_loc return location of the io_path mutex pointer
452 * @param dispatch_cond_loc return location of the dispatch conditional
454 * @param io_path_cond_loc return location of the io_path conditional
458 _dbus_connection_test_get_locks (DBusConnection *connection,
459 DBusMutex **mutex_loc,
460 DBusMutex **dispatch_mutex_loc,
461 DBusMutex **io_path_mutex_loc,
462 DBusCondVar **dispatch_cond_loc,
463 DBusCondVar **io_path_cond_loc)
465 *mutex_loc = (DBusMutex *) connection->mutex;
466 *dispatch_mutex_loc = (DBusMutex *) connection->dispatch_mutex;
467 *io_path_mutex_loc = (DBusMutex *) connection->io_path_mutex;
468 *dispatch_cond_loc = connection->dispatch_cond;
469 *io_path_cond_loc = connection->io_path_cond;
474 * Adds a message-containing list link to the incoming message queue,
475 * taking ownership of the link and the message's current refcount.
476 * Cannot fail due to lack of memory.
478 * @param connection the connection.
479 * @param link the message link to queue.
482 _dbus_connection_queue_received_message_link (DBusConnection *connection,
485 DBusPendingCall *pending;
486 dbus_uint32_t reply_serial;
487 DBusMessage *message;
489 _dbus_assert (_dbus_transport_peek_is_authenticated (connection->transport));
491 _dbus_list_append_link (&connection->incoming_messages,
493 message = link->data;
495 /* If this is a reply we're waiting on, remove timeout for it */
496 reply_serial = dbus_message_get_reply_serial (message);
497 if (reply_serial != 0)
499 pending = _dbus_hash_table_lookup_int (connection->pending_replies,
503 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
504 _dbus_connection_remove_timeout_unlocked (connection,
505 _dbus_pending_call_get_timeout_unlocked (pending));
507 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
513 connection->n_incoming += 1;
515 _dbus_connection_wakeup_mainloop (connection);
517 _dbus_verbose ("Message %p (%s %s %s %s '%s' reply to %u) added to incoming queue %p, %d incoming\n",
519 dbus_message_type_to_string (dbus_message_get_type (message)),
520 dbus_message_get_path (message) ?
521 dbus_message_get_path (message) :
523 dbus_message_get_interface (message) ?
524 dbus_message_get_interface (message) :
526 dbus_message_get_member (message) ?
527 dbus_message_get_member (message) :
529 dbus_message_get_signature (message),
530 dbus_message_get_reply_serial (message),
532 connection->n_incoming);
534 _dbus_message_trace_ref (message, -1, -1,
535 "_dbus_conection_queue_received_message_link");
539 * Adds a link + message to the incoming message queue.
540 * Can't fail. Takes ownership of both link and message.
542 * @param connection the connection.
543 * @param link the list node and message to queue.
547 _dbus_connection_queue_synthesized_message_link (DBusConnection *connection,
550 HAVE_LOCK_CHECK (connection);
552 _dbus_list_append_link (&connection->incoming_messages, link);
554 connection->n_incoming += 1;
556 _dbus_connection_wakeup_mainloop (connection);
558 _dbus_message_trace_ref (link->data, -1, -1,
559 "_dbus_connection_queue_synthesized_message_link");
561 _dbus_verbose ("Synthesized message %p added to incoming queue %p, %d incoming\n",
562 link->data, connection, connection->n_incoming);
567 * Checks whether there are messages in the outgoing message queue.
568 * Called with connection lock held.
570 * @param connection the connection.
571 * @returns #TRUE if the outgoing queue is non-empty.
574 _dbus_connection_has_messages_to_send_unlocked (DBusConnection *connection)
576 HAVE_LOCK_CHECK (connection);
577 return connection->outgoing_messages != NULL;
581 * Checks whether there are messages in the outgoing message queue.
582 * Use dbus_connection_flush() to block until all outgoing
583 * messages have been written to the underlying transport
584 * (such as a socket).
586 * @param connection the connection.
587 * @returns #TRUE if the outgoing queue is non-empty.
590 dbus_connection_has_messages_to_send (DBusConnection *connection)
594 _dbus_return_val_if_fail (connection != NULL, FALSE);
596 CONNECTION_LOCK (connection);
597 v = _dbus_connection_has_messages_to_send_unlocked (connection);
598 CONNECTION_UNLOCK (connection);
604 * Gets the next outgoing message. The message remains in the
605 * queue, and the caller does not own a reference to it.
607 * @param connection the connection.
608 * @returns the message to be sent.
611 _dbus_connection_get_message_to_send (DBusConnection *connection)
613 HAVE_LOCK_CHECK (connection);
615 return _dbus_list_get_last (&connection->outgoing_messages);
619 * Notifies the connection that a message has been sent, so the
620 * message can be removed from the outgoing queue.
621 * Called with the connection lock held.
623 * @param connection the connection.
624 * @param message the message that was sent.
627 _dbus_connection_message_sent_unlocked (DBusConnection *connection,
628 DBusMessage *message)
632 HAVE_LOCK_CHECK (connection);
634 /* This can be called before we even complete authentication, since
635 * it's called on disconnect to clean up the outgoing queue.
636 * It's also called as we successfully send each message.
639 link = _dbus_list_get_last_link (&connection->outgoing_messages);
640 _dbus_assert (link != NULL);
641 _dbus_assert (link->data == message);
643 _dbus_list_unlink (&connection->outgoing_messages,
645 _dbus_list_prepend_link (&connection->expired_messages, link);
647 connection->n_outgoing -= 1;
649 _dbus_verbose ("Message %p (%s %s %s %s '%s') removed from outgoing queue %p, %d left to send\n",
651 dbus_message_type_to_string (dbus_message_get_type (message)),
652 dbus_message_get_path (message) ?
653 dbus_message_get_path (message) :
655 dbus_message_get_interface (message) ?
656 dbus_message_get_interface (message) :
658 dbus_message_get_member (message) ?
659 dbus_message_get_member (message) :
661 dbus_message_get_signature (message),
662 connection, connection->n_outgoing);
664 /* It's OK that in principle we call the notify function, because for the
665 * outgoing limit, there isn't one */
666 _dbus_message_remove_counter (message, connection->outgoing_counter);
668 /* The message will actually be unreffed when we unlock */
671 /** Function to be called in protected_change_watch() with refcount held */
672 typedef dbus_bool_t (* DBusWatchAddFunction) (DBusWatchList *list,
674 /** Function to be called in protected_change_watch() with refcount held */
675 typedef void (* DBusWatchRemoveFunction) (DBusWatchList *list,
677 /** Function to be called in protected_change_watch() with refcount held */
678 typedef void (* DBusWatchToggleFunction) (DBusWatchList *list,
680 dbus_bool_t enabled);
683 protected_change_watch (DBusConnection *connection,
685 DBusWatchAddFunction add_function,
686 DBusWatchRemoveFunction remove_function,
687 DBusWatchToggleFunction toggle_function,
692 HAVE_LOCK_CHECK (connection);
694 /* The original purpose of protected_change_watch() was to hold a
695 * ref on the connection while dropping the connection lock, then
696 * calling out to the app. This was a broken hack that did not
697 * work, since the connection was in a hosed state (no WatchList
698 * field) while calling out.
700 * So for now we'll just keep the lock while calling out. This means
701 * apps are not allowed to call DBusConnection methods inside a
702 * watch function or they will deadlock.
704 * The "real fix" is to use the _and_unlock() pattern found
705 * elsewhere in the code, to defer calling out to the app until
706 * we're about to drop locks and return flow of control to the app
709 * See http://lists.freedesktop.org/archives/dbus/2007-July/thread.html#8144
712 if (connection->watches)
715 retval = (* add_function) (connection->watches, watch);
716 else if (remove_function)
719 (* remove_function) (connection->watches, watch);
724 (* toggle_function) (connection->watches, watch, enabled);
734 * Adds a watch using the connection's DBusAddWatchFunction if
735 * available. Otherwise records the watch to be added when said
736 * function is available. Also re-adds the watch if the
737 * DBusAddWatchFunction changes. May fail due to lack of memory.
738 * Connection lock should be held when calling this.
740 * @param connection the connection.
741 * @param watch the watch to add.
742 * @returns #TRUE on success.
745 _dbus_connection_add_watch_unlocked (DBusConnection *connection,
748 return protected_change_watch (connection, watch,
749 _dbus_watch_list_add_watch,
754 * Removes a watch using the connection's DBusRemoveWatchFunction
755 * if available. It's an error to call this function on a watch
756 * that was not previously added.
757 * Connection lock should be held when calling this.
759 * @param connection the connection.
760 * @param watch the watch to remove.
763 _dbus_connection_remove_watch_unlocked (DBusConnection *connection,
766 protected_change_watch (connection, watch,
768 _dbus_watch_list_remove_watch,
773 * Toggles a watch and notifies app via connection's
774 * DBusWatchToggledFunction if available. It's an error to call this
775 * function on a watch that was not previously added.
776 * Connection lock should be held when calling this.
778 * @param connection the connection.
779 * @param watch the watch to toggle.
780 * @param enabled whether to enable or disable
783 _dbus_connection_toggle_watch_unlocked (DBusConnection *connection,
787 _dbus_assert (watch != NULL);
789 protected_change_watch (connection, watch,
791 _dbus_watch_list_toggle_watch,
795 /** Function to be called in protected_change_timeout() with refcount held */
796 typedef dbus_bool_t (* DBusTimeoutAddFunction) (DBusTimeoutList *list,
797 DBusTimeout *timeout);
798 /** Function to be called in protected_change_timeout() with refcount held */
799 typedef void (* DBusTimeoutRemoveFunction) (DBusTimeoutList *list,
800 DBusTimeout *timeout);
801 /** Function to be called in protected_change_timeout() with refcount held */
802 typedef void (* DBusTimeoutToggleFunction) (DBusTimeoutList *list,
803 DBusTimeout *timeout,
804 dbus_bool_t enabled);
807 protected_change_timeout (DBusConnection *connection,
808 DBusTimeout *timeout,
809 DBusTimeoutAddFunction add_function,
810 DBusTimeoutRemoveFunction remove_function,
811 DBusTimeoutToggleFunction toggle_function,
816 HAVE_LOCK_CHECK (connection);
818 /* The original purpose of protected_change_timeout() was to hold a
819 * ref on the connection while dropping the connection lock, then
820 * calling out to the app. This was a broken hack that did not
821 * work, since the connection was in a hosed state (no TimeoutList
822 * field) while calling out.
824 * So for now we'll just keep the lock while calling out. This means
825 * apps are not allowed to call DBusConnection methods inside a
826 * timeout function or they will deadlock.
828 * The "real fix" is to use the _and_unlock() pattern found
829 * elsewhere in the code, to defer calling out to the app until
830 * we're about to drop locks and return flow of control to the app
833 * See http://lists.freedesktop.org/archives/dbus/2007-July/thread.html#8144
836 if (connection->timeouts)
839 retval = (* add_function) (connection->timeouts, timeout);
840 else if (remove_function)
843 (* remove_function) (connection->timeouts, timeout);
848 (* toggle_function) (connection->timeouts, timeout, enabled);
857 * Adds a timeout using the connection's DBusAddTimeoutFunction if
858 * available. Otherwise records the timeout to be added when said
859 * function is available. Also re-adds the timeout if the
860 * DBusAddTimeoutFunction changes. May fail due to lack of memory.
861 * The timeout will fire repeatedly until removed.
862 * Connection lock should be held when calling this.
864 * @param connection the connection.
865 * @param timeout the timeout to add.
866 * @returns #TRUE on success.
869 _dbus_connection_add_timeout_unlocked (DBusConnection *connection,
870 DBusTimeout *timeout)
872 return protected_change_timeout (connection, timeout,
873 _dbus_timeout_list_add_timeout,
878 * Removes a timeout using the connection's DBusRemoveTimeoutFunction
879 * if available. It's an error to call this function on a timeout
880 * that was not previously added.
881 * Connection lock should be held when calling this.
883 * @param connection the connection.
884 * @param timeout the timeout to remove.
887 _dbus_connection_remove_timeout_unlocked (DBusConnection *connection,
888 DBusTimeout *timeout)
890 protected_change_timeout (connection, timeout,
892 _dbus_timeout_list_remove_timeout,
897 * Toggles a timeout and notifies app via connection's
898 * DBusTimeoutToggledFunction if available. It's an error to call this
899 * function on a timeout that was not previously added.
900 * Connection lock should be held when calling this.
902 * @param connection the connection.
903 * @param timeout the timeout to toggle.
904 * @param enabled whether to enable or disable
907 _dbus_connection_toggle_timeout_unlocked (DBusConnection *connection,
908 DBusTimeout *timeout,
911 protected_change_timeout (connection, timeout,
913 _dbus_timeout_list_toggle_timeout,
918 _dbus_connection_attach_pending_call_unlocked (DBusConnection *connection,
919 DBusPendingCall *pending)
921 dbus_uint32_t reply_serial;
922 DBusTimeout *timeout;
924 HAVE_LOCK_CHECK (connection);
926 reply_serial = _dbus_pending_call_get_reply_serial_unlocked (pending);
928 _dbus_assert (reply_serial != 0);
930 timeout = _dbus_pending_call_get_timeout_unlocked (pending);
934 if (!_dbus_connection_add_timeout_unlocked (connection, timeout))
937 if (!_dbus_hash_table_insert_int (connection->pending_replies,
941 _dbus_connection_remove_timeout_unlocked (connection, timeout);
943 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
944 HAVE_LOCK_CHECK (connection);
948 _dbus_pending_call_set_timeout_added_unlocked (pending, TRUE);
952 if (!_dbus_hash_table_insert_int (connection->pending_replies,
956 HAVE_LOCK_CHECK (connection);
961 _dbus_pending_call_ref_unlocked (pending);
963 HAVE_LOCK_CHECK (connection);
969 free_pending_call_on_hash_removal (void *data)
971 DBusPendingCall *pending;
972 DBusConnection *connection;
979 connection = _dbus_pending_call_get_connection_unlocked (pending);
981 HAVE_LOCK_CHECK (connection);
983 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
985 _dbus_connection_remove_timeout_unlocked (connection,
986 _dbus_pending_call_get_timeout_unlocked (pending));
988 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
991 /* FIXME 1.0? this is sort of dangerous and undesirable to drop the lock
992 * here, but the pending call finalizer could in principle call out to
993 * application code so we pretty much have to... some larger code reorg
996 _dbus_connection_ref_unlocked (connection);
997 _dbus_pending_call_unref_and_unlock (pending);
998 CONNECTION_LOCK (connection);
999 _dbus_connection_unref_unlocked (connection);
1003 _dbus_connection_detach_pending_call_unlocked (DBusConnection *connection,
1004 DBusPendingCall *pending)
1006 /* This ends up unlocking to call the pending call finalizer, which is unexpected to
1009 _dbus_hash_table_remove_int (connection->pending_replies,
1010 _dbus_pending_call_get_reply_serial_unlocked (pending));
1014 _dbus_connection_detach_pending_call_and_unlock (DBusConnection *connection,
1015 DBusPendingCall *pending)
1017 /* The idea here is to avoid finalizing the pending call
1018 * with the lock held, since there's a destroy notifier
1019 * in pending call that goes out to application code.
1021 * There's an extra unlock inside the hash table
1022 * "free pending call" function FIXME...
1024 _dbus_pending_call_ref_unlocked (pending);
1025 _dbus_hash_table_remove_int (connection->pending_replies,
1026 _dbus_pending_call_get_reply_serial_unlocked (pending));
1028 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
1029 _dbus_connection_remove_timeout_unlocked (connection,
1030 _dbus_pending_call_get_timeout_unlocked (pending));
1032 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
1034 _dbus_pending_call_unref_and_unlock (pending);
1038 * Removes a pending call from the connection, such that
1039 * the pending reply will be ignored. May drop the last
1040 * reference to the pending call.
1042 * @param connection the connection
1043 * @param pending the pending call
1046 _dbus_connection_remove_pending_call (DBusConnection *connection,
1047 DBusPendingCall *pending)
1049 CONNECTION_LOCK (connection);
1050 _dbus_connection_detach_pending_call_and_unlock (connection, pending);
1054 * Acquire the transporter I/O path. This must be done before
1055 * doing any I/O in the transporter. May sleep and drop the
1056 * IO path mutex while waiting for the I/O path.
1058 * @param connection the connection.
1059 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
1060 * @returns TRUE if the I/O path was acquired.
1063 _dbus_connection_acquire_io_path (DBusConnection *connection,
1064 int timeout_milliseconds)
1066 dbus_bool_t we_acquired;
1068 HAVE_LOCK_CHECK (connection);
1070 /* We don't want the connection to vanish */
1071 _dbus_connection_ref_unlocked (connection);
1073 /* We will only touch io_path_acquired which is protected by our mutex */
1074 CONNECTION_UNLOCK (connection);
1076 _dbus_verbose ("locking io_path_mutex\n");
1077 _dbus_cmutex_lock (connection->io_path_mutex);
1079 _dbus_verbose ("start connection->io_path_acquired = %d timeout = %d\n",
1080 connection->io_path_acquired, timeout_milliseconds);
1082 we_acquired = FALSE;
1084 if (connection->io_path_acquired)
1086 if (timeout_milliseconds != -1)
1088 _dbus_verbose ("waiting %d for IO path to be acquirable\n",
1089 timeout_milliseconds);
1091 if (!_dbus_condvar_wait_timeout (connection->io_path_cond,
1092 connection->io_path_mutex,
1093 timeout_milliseconds))
1095 /* We timed out before anyone signaled. */
1096 /* (writing the loop to handle the !timedout case by
1097 * waiting longer if needed is a pain since dbus
1098 * wraps pthread_cond_timedwait to take a relative
1099 * time instead of absolute, something kind of stupid
1100 * on our part. for now it doesn't matter, we will just
1101 * end up back here eventually.)
1107 while (connection->io_path_acquired)
1109 _dbus_verbose ("waiting for IO path to be acquirable\n");
1110 _dbus_condvar_wait (connection->io_path_cond,
1111 connection->io_path_mutex);
1116 if (!connection->io_path_acquired)
1119 connection->io_path_acquired = TRUE;
1122 _dbus_verbose ("end connection->io_path_acquired = %d we_acquired = %d\n",
1123 connection->io_path_acquired, we_acquired);
1125 _dbus_verbose ("unlocking io_path_mutex\n");
1126 _dbus_cmutex_unlock (connection->io_path_mutex);
1128 CONNECTION_LOCK (connection);
1130 HAVE_LOCK_CHECK (connection);
1132 _dbus_connection_unref_unlocked (connection);
1138 * Release the I/O path when you're done with it. Only call
1139 * after you've acquired the I/O. Wakes up at most one thread
1140 * currently waiting to acquire the I/O path.
1142 * @param connection the connection.
1145 _dbus_connection_release_io_path (DBusConnection *connection)
1147 HAVE_LOCK_CHECK (connection);
1149 _dbus_verbose ("locking io_path_mutex\n");
1150 _dbus_cmutex_lock (connection->io_path_mutex);
1152 _dbus_assert (connection->io_path_acquired);
1154 _dbus_verbose ("start connection->io_path_acquired = %d\n",
1155 connection->io_path_acquired);
1157 connection->io_path_acquired = FALSE;
1158 _dbus_condvar_wake_one (connection->io_path_cond);
1160 _dbus_verbose ("unlocking io_path_mutex\n");
1161 _dbus_cmutex_unlock (connection->io_path_mutex);
1165 * Queues incoming messages and sends outgoing messages for this
1166 * connection, optionally blocking in the process. Each call to
1167 * _dbus_connection_do_iteration_unlocked() will call select() or poll() one
1168 * time and then read or write data if possible.
1170 * The purpose of this function is to be able to flush outgoing
1171 * messages or queue up incoming messages without returning
1172 * control to the application and causing reentrancy weirdness.
1174 * The flags parameter allows you to specify whether to
1175 * read incoming messages, write outgoing messages, or both,
1176 * and whether to block if no immediate action is possible.
1178 * The timeout_milliseconds parameter does nothing unless the
1179 * iteration is blocking.
1181 * If there are no outgoing messages and DBUS_ITERATION_DO_READING
1182 * wasn't specified, then it's impossible to block, even if
1183 * you specify DBUS_ITERATION_BLOCK; in that case the function
1184 * returns immediately.
1186 * If pending is not NULL then a check is made if the pending call
1187 * is completed after the io path has been required. If the call
1188 * has been completed nothing is done. This must be done since
1189 * the _dbus_connection_acquire_io_path releases the connection
1192 * Called with connection lock held.
1194 * @param connection the connection.
1195 * @param pending the pending call that should be checked or NULL
1196 * @param flags iteration flags.
1197 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
1200 _dbus_connection_do_iteration_unlocked (DBusConnection *connection,
1201 DBusPendingCall *pending,
1203 int timeout_milliseconds)
1205 _dbus_verbose ("start\n");
1207 HAVE_LOCK_CHECK (connection);
1209 if (connection->n_outgoing == 0)
1210 flags &= ~DBUS_ITERATION_DO_WRITING;
1212 if (_dbus_connection_acquire_io_path (connection,
1213 (flags & DBUS_ITERATION_BLOCK) ? timeout_milliseconds : 0))
1215 HAVE_LOCK_CHECK (connection);
1217 if ( (pending != NULL) && _dbus_pending_call_get_completed_unlocked(pending))
1219 _dbus_verbose ("pending call completed while acquiring I/O path");
1221 else if ( (pending != NULL) &&
1222 _dbus_connection_peek_for_reply_unlocked (connection,
1223 _dbus_pending_call_get_reply_serial_unlocked (pending)))
1225 _dbus_verbose ("pending call completed while acquiring I/O path (reply found in queue)");
1229 _dbus_transport_do_iteration (connection->transport,
1230 flags, timeout_milliseconds);
1233 _dbus_connection_release_io_path (connection);
1236 HAVE_LOCK_CHECK (connection);
1238 _dbus_verbose ("end\n");
1242 * Creates a new connection for the given transport. A transport
1243 * represents a message stream that uses some concrete mechanism, such
1244 * as UNIX domain sockets. May return #NULL if insufficient
1245 * memory exists to create the connection.
1247 * @param transport the transport.
1248 * @returns the new connection, or #NULL on failure.
1250 static DBusConnection*
1251 _dbus_connection_new_for_transport_internal (DBusTransport *transport, dbus_bool_t exists)
1253 DBusConnection *connection;
1254 DBusWatchList *watch_list;
1255 DBusTimeoutList *timeout_list;
1256 DBusHashTable *pending_replies;
1257 DBusList *disconnect_link;
1258 DBusMessage *disconnect_message;
1259 DBusCounter *outgoing_counter;
1260 DBusObjectTree *objects;
1264 pending_replies = NULL;
1265 timeout_list = NULL;
1266 disconnect_link = NULL;
1267 disconnect_message = NULL;
1268 outgoing_counter = NULL;
1271 watch_list = _dbus_watch_list_new ();
1272 if (watch_list == NULL)
1275 timeout_list = _dbus_timeout_list_new ();
1276 if (timeout_list == NULL)
1280 _dbus_hash_table_new (DBUS_HASH_INT,
1282 (DBusFreeFunction)free_pending_call_on_hash_removal);
1283 if (pending_replies == NULL)
1286 connection = dbus_new0 (DBusConnection, 1);
1287 if (connection == NULL)
1290 _dbus_rmutex_new_at_location (&connection->mutex);
1291 if (connection->mutex == NULL)
1294 _dbus_cmutex_new_at_location (&connection->io_path_mutex);
1295 if (connection->io_path_mutex == NULL)
1298 _dbus_cmutex_new_at_location (&connection->dispatch_mutex);
1299 if (connection->dispatch_mutex == NULL)
1302 _dbus_condvar_new_at_location (&connection->dispatch_cond);
1303 if (connection->dispatch_cond == NULL)
1306 _dbus_condvar_new_at_location (&connection->io_path_cond);
1307 if (connection->io_path_cond == NULL)
1310 _dbus_rmutex_new_at_location (&connection->slot_mutex);
1311 if (connection->slot_mutex == NULL)
1314 disconnect_message = dbus_message_new_signal (DBUS_PATH_LOCAL,
1315 DBUS_INTERFACE_LOCAL,
1318 if (disconnect_message == NULL)
1321 disconnect_link = _dbus_list_alloc_link (disconnect_message);
1322 if (disconnect_link == NULL)
1325 outgoing_counter = _dbus_counter_new ();
1326 if (outgoing_counter == NULL)
1329 objects = _dbus_object_tree_new (connection);
1330 if (objects == NULL)
1333 if (_dbus_modify_sigpipe)
1334 _dbus_disable_sigpipe ();
1336 /* initialized to 0: use atomic op to avoid mixing atomic and non-atomic */
1337 _dbus_atomic_inc (&connection->refcount);
1338 connection->transport = transport;
1339 connection->watches = watch_list;
1340 connection->timeouts = timeout_list;
1341 connection->pending_replies = pending_replies;
1342 connection->outgoing_counter = outgoing_counter;
1343 connection->filter_list = NULL;
1344 connection->last_dispatch_status = DBUS_DISPATCH_COMPLETE; /* so we're notified first time there's data */
1345 connection->objects = objects;
1346 connection->exit_on_disconnect = FALSE;
1347 connection->shareable = FALSE;
1348 connection->route_peer_messages = FALSE;
1349 connection->disconnected_message_arrived = FALSE;
1350 connection->disconnected_message_processed = FALSE;
1352 #if defined(DBUS_ENABLE_CHECKS) || defined(DBUS_ENABLE_ASSERT)
1353 connection->generation = _dbus_current_generation;
1356 _dbus_data_slot_list_init (&connection->slot_list);
1358 connection->client_serial = 1;
1360 connection->disconnect_message_link = disconnect_link;
1364 CONNECTION_LOCK (connection);
1366 if (!_dbus_transport_set_connection (transport, connection))
1368 CONNECTION_UNLOCK (connection);
1373 _dbus_transport_ref (transport);
1375 CONNECTION_UNLOCK (connection);
1378 _dbus_connection_trace_ref (connection, 0, 1, "new_for_transport");
1382 if (disconnect_message != NULL)
1383 dbus_message_unref (disconnect_message);
1385 if (disconnect_link != NULL)
1386 _dbus_list_free_link (disconnect_link);
1388 if (connection != NULL)
1390 _dbus_condvar_free_at_location (&connection->io_path_cond);
1391 _dbus_condvar_free_at_location (&connection->dispatch_cond);
1392 _dbus_rmutex_free_at_location (&connection->mutex);
1393 _dbus_cmutex_free_at_location (&connection->io_path_mutex);
1394 _dbus_cmutex_free_at_location (&connection->dispatch_mutex);
1395 _dbus_rmutex_free_at_location (&connection->slot_mutex);
1396 dbus_free (connection);
1398 if (pending_replies)
1399 _dbus_hash_table_unref (pending_replies);
1402 _dbus_watch_list_free (watch_list);
1405 _dbus_timeout_list_free (timeout_list);
1407 if (outgoing_counter)
1408 _dbus_counter_unref (outgoing_counter);
1411 _dbus_object_tree_unref (objects);
1417 * Creates a new connection for the given transport. A transport
1418 * represents a message stream that uses some concrete mechanism, such
1419 * as UNIX domain sockets. May return #NULL if insufficient
1420 * memory exists to create the connection.
1422 * @param transport the transport.
1423 * @returns the new connection, or #NULL on failure.
1426 _dbus_connection_new_for_transport (DBusTransport *transport)
1428 return _dbus_connection_new_for_transport_internal(transport, FALSE);
1432 _dbus_connection_new_for_used_transport (DBusTransport *transport)
1434 return _dbus_connection_new_for_transport_internal(transport, TRUE);
1438 * Increments the reference count of a DBusConnection.
1439 * Requires that the caller already holds the connection lock.
1441 * @param connection the connection.
1442 * @returns the connection.
1445 _dbus_connection_ref_unlocked (DBusConnection *connection)
1447 dbus_int32_t old_refcount;
1449 _dbus_assert (connection != NULL);
1450 _dbus_assert (connection->generation == _dbus_current_generation);
1452 HAVE_LOCK_CHECK (connection);
1454 old_refcount = _dbus_atomic_inc (&connection->refcount);
1455 _dbus_connection_trace_ref (connection, old_refcount, old_refcount + 1,
1462 * Decrements the reference count of a DBusConnection.
1463 * Requires that the caller already holds the connection lock.
1465 * @param connection the connection.
1468 _dbus_connection_unref_unlocked (DBusConnection *connection)
1470 dbus_int32_t old_refcount;
1472 HAVE_LOCK_CHECK (connection);
1474 _dbus_assert (connection != NULL);
1476 old_refcount = _dbus_atomic_dec (&connection->refcount);
1478 _dbus_connection_trace_ref (connection, old_refcount, old_refcount - 1,
1481 if (old_refcount == 1)
1482 _dbus_connection_last_unref (connection);
1485 static dbus_uint32_t
1486 _dbus_connection_get_next_client_serial (DBusConnection *connection)
1488 dbus_uint32_t serial;
1490 serial = connection->client_serial++;
1492 if (connection->client_serial == 0)
1493 connection->client_serial = 1;
1499 * A callback for use with dbus_watch_new() to create a DBusWatch.
1501 * @todo This is basically a hack - we could delete _dbus_transport_handle_watch()
1502 * and the virtual handle_watch in DBusTransport if we got rid of it.
1503 * The reason this is some work is threading, see the _dbus_connection_handle_watch()
1506 * @param watch the watch.
1507 * @param condition the current condition of the file descriptors being watched.
1508 * @param data must be a pointer to a #DBusConnection
1509 * @returns #FALSE if the IO condition may not have been fully handled due to lack of memory
1512 _dbus_connection_handle_watch (DBusWatch *watch,
1513 unsigned int condition,
1516 DBusConnection *connection;
1518 DBusDispatchStatus status;
1522 _dbus_verbose ("start\n");
1524 CONNECTION_LOCK (connection);
1526 if (!_dbus_connection_acquire_io_path (connection, 1))
1528 /* another thread is handling the message */
1529 CONNECTION_UNLOCK (connection);
1533 HAVE_LOCK_CHECK (connection);
1534 retval = _dbus_transport_handle_watch (connection->transport,
1537 _dbus_connection_release_io_path (connection);
1539 HAVE_LOCK_CHECK (connection);
1541 _dbus_verbose ("middle\n");
1543 status = _dbus_connection_get_dispatch_status_unlocked (connection);
1545 /* this calls out to user code */
1546 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1548 _dbus_verbose ("end\n");
1553 /* Protected by _DBUS_LOCK (shared_connections) */
1554 static DBusHashTable *shared_connections = NULL;
1555 static DBusList *shared_connections_no_guid = NULL;
1558 close_connection_on_shutdown (DBusConnection *connection)
1560 DBusMessage *message;
1562 dbus_connection_ref (connection);
1563 _dbus_connection_close_possibly_shared (connection);
1565 /* Churn through to the Disconnected message */
1566 while ((message = dbus_connection_pop_message (connection)))
1568 dbus_message_unref (message);
1570 dbus_connection_unref (connection);
1574 shared_connections_shutdown (void *data)
1578 if (!_DBUS_LOCK (shared_connections))
1580 /* We'd have initialized locks before adding anything, so there
1581 * can't be anything there. */
1585 /* This is a little bit unpleasant... better ideas? */
1586 while ((n_entries = _dbus_hash_table_get_n_entries (shared_connections)) > 0)
1588 DBusConnection *connection;
1591 _dbus_hash_iter_init (shared_connections, &iter);
1592 _dbus_hash_iter_next (&iter);
1594 connection = _dbus_hash_iter_get_value (&iter);
1596 _DBUS_UNLOCK (shared_connections);
1597 close_connection_on_shutdown (connection);
1598 if (!_DBUS_LOCK (shared_connections))
1599 _dbus_assert_not_reached ("global locks were already initialized");
1601 /* The connection should now be dead and not in our hash ... */
1602 _dbus_assert (_dbus_hash_table_get_n_entries (shared_connections) < n_entries);
1605 _dbus_assert (_dbus_hash_table_get_n_entries (shared_connections) == 0);
1607 _dbus_hash_table_unref (shared_connections);
1608 shared_connections = NULL;
1610 if (shared_connections_no_guid != NULL)
1612 DBusConnection *connection;
1613 connection = _dbus_list_pop_first (&shared_connections_no_guid);
1614 while (connection != NULL)
1616 _DBUS_UNLOCK (shared_connections);
1617 close_connection_on_shutdown (connection);
1618 if (!_DBUS_LOCK (shared_connections))
1619 _dbus_assert_not_reached ("global locks were already initialized");
1620 connection = _dbus_list_pop_first (&shared_connections_no_guid);
1624 shared_connections_no_guid = NULL;
1626 _DBUS_UNLOCK (shared_connections);
1630 connection_lookup_shared (DBusAddressEntry *entry,
1631 DBusConnection **result)
1633 _dbus_verbose ("checking for existing connection\n");
1637 if (!_DBUS_LOCK (shared_connections))
1639 /* If it was shared, we'd have initialized global locks when we put
1640 * it in shared_connections. */
1644 if (shared_connections == NULL)
1646 _dbus_verbose ("creating shared_connections hash table\n");
1648 shared_connections = _dbus_hash_table_new (DBUS_HASH_STRING,
1651 if (shared_connections == NULL)
1653 _DBUS_UNLOCK (shared_connections);
1657 if (!_dbus_register_shutdown_func (shared_connections_shutdown, NULL))
1659 _dbus_hash_table_unref (shared_connections);
1660 shared_connections = NULL;
1661 _DBUS_UNLOCK (shared_connections);
1665 _dbus_verbose (" successfully created shared_connections\n");
1667 _DBUS_UNLOCK (shared_connections);
1668 return TRUE; /* no point looking up in the hash we just made */
1674 guid = dbus_address_entry_get_value (entry, "guid");
1678 DBusConnection *connection;
1680 connection = _dbus_hash_table_lookup_string (shared_connections,
1685 /* The DBusConnection can't be finalized without taking
1686 * the shared_connections lock to remove it from the
1687 * hash. So it's safe to ref the connection here.
1688 * However, it may be disconnected if the Disconnected
1689 * message hasn't been processed yet, in which case we
1690 * want to pretend it isn't in the hash and avoid
1693 * The idea is to avoid ever returning a disconnected connection
1694 * from dbus_connection_open(). We could just synchronously
1695 * drop our shared ref to the connection on connection disconnect,
1696 * and then assert here that the connection is connected, but
1697 * that causes reentrancy headaches.
1699 CONNECTION_LOCK (connection);
1700 if (_dbus_connection_get_is_connected_unlocked (connection))
1702 _dbus_connection_ref_unlocked (connection);
1703 *result = connection;
1704 _dbus_verbose ("looked up existing connection to server guid %s\n",
1709 _dbus_verbose ("looked up existing connection to server guid %s but it was disconnected so ignoring it\n",
1712 CONNECTION_UNLOCK (connection);
1716 _DBUS_UNLOCK (shared_connections);
1722 connection_record_shared_unlocked (DBusConnection *connection,
1726 char *guid_in_connection;
1728 HAVE_LOCK_CHECK (connection);
1729 _dbus_assert (connection->server_guid == NULL);
1730 _dbus_assert (connection->shareable);
1732 /* get a hard ref on this connection, even if
1733 * we won't in fact store it in the hash, we still
1734 * need to hold a ref on it until it's disconnected.
1736 _dbus_connection_ref_unlocked (connection);
1740 if (!_DBUS_LOCK (shared_connections))
1743 if (!_dbus_list_prepend (&shared_connections_no_guid, connection))
1745 _DBUS_UNLOCK (shared_connections);
1749 _DBUS_UNLOCK (shared_connections);
1750 return TRUE; /* don't store in the hash */
1753 /* A separate copy of the key is required in the hash table, because
1754 * we don't have a lock on the connection when we are doing a hash
1758 guid_key = _dbus_strdup (guid);
1759 if (guid_key == NULL)
1762 guid_in_connection = _dbus_strdup (guid);
1763 if (guid_in_connection == NULL)
1765 dbus_free (guid_key);
1769 if (!_DBUS_LOCK (shared_connections))
1771 dbus_free (guid_in_connection);
1772 dbus_free (guid_key);
1776 _dbus_assert (shared_connections != NULL);
1778 if (!_dbus_hash_table_insert_string (shared_connections,
1779 guid_key, connection))
1781 dbus_free (guid_key);
1782 dbus_free (guid_in_connection);
1783 _DBUS_UNLOCK (shared_connections);
1787 connection->server_guid = guid_in_connection;
1789 _dbus_verbose ("stored connection to %s to be shared\n",
1790 connection->server_guid);
1792 _DBUS_UNLOCK (shared_connections);
1794 _dbus_assert (connection->server_guid != NULL);
1800 connection_forget_shared_unlocked (DBusConnection *connection)
1802 HAVE_LOCK_CHECK (connection);
1804 if (!connection->shareable)
1807 if (!_DBUS_LOCK (shared_connections))
1809 /* If it was shared, we'd have initialized global locks when we put
1810 * it in the table; so it can't be there. */
1814 if (connection->server_guid != NULL)
1816 _dbus_verbose ("dropping connection to %s out of the shared table\n",
1817 connection->server_guid);
1819 if (!_dbus_hash_table_remove_string (shared_connections,
1820 connection->server_guid))
1821 _dbus_assert_not_reached ("connection was not in the shared table");
1823 dbus_free (connection->server_guid);
1824 connection->server_guid = NULL;
1828 _dbus_list_remove (&shared_connections_no_guid, connection);
1831 _DBUS_UNLOCK (shared_connections);
1833 /* remove our reference held on all shareable connections */
1834 _dbus_connection_unref_unlocked (connection);
1837 static DBusConnection*
1838 connection_try_from_address_entry (DBusAddressEntry *entry,
1841 DBusTransport *transport;
1842 DBusConnection *connection;
1844 transport = _dbus_transport_open (entry, error);
1846 if (transport == NULL)
1848 _DBUS_ASSERT_ERROR_IS_SET (error);
1852 connection = _dbus_connection_new_for_transport (transport);
1854 _dbus_transport_unref (transport);
1856 if (connection == NULL)
1858 _DBUS_SET_OOM (error);
1862 #ifndef DBUS_DISABLE_CHECKS
1863 _dbus_assert (!connection->have_connection_lock);
1870 * If the shared parameter is true, then any existing connection will
1871 * be used (and if a new connection is created, it will be available
1872 * for use by others). If the shared parameter is false, a new
1873 * connection will always be created, and the new connection will
1874 * never be returned to other callers.
1876 * @param address the address
1877 * @param shared whether the connection is shared or private
1878 * @param error error return
1879 * @returns the connection or #NULL on error
1881 static DBusConnection*
1882 _dbus_connection_open_internal (const char *address,
1886 DBusConnection *connection;
1887 DBusAddressEntry **entries;
1888 DBusError tmp_error = DBUS_ERROR_INIT;
1889 DBusError first_error = DBUS_ERROR_INIT;
1892 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1894 _dbus_verbose ("opening %s connection to: %s\n",
1895 shared ? "shared" : "private", address);
1897 if (!dbus_parse_address (address, &entries, &len, error))
1900 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1904 for (i = 0; i < len; i++)
1908 if (!connection_lookup_shared (entries[i], &connection))
1909 _DBUS_SET_OOM (&tmp_error);
1912 if (connection == NULL)
1914 connection = connection_try_from_address_entry (entries[i],
1917 if (connection != NULL && shared)
1921 connection->shareable = TRUE;
1923 /* guid may be NULL */
1924 guid = dbus_address_entry_get_value (entries[i], "guid");
1926 CONNECTION_LOCK (connection);
1928 if (!connection_record_shared_unlocked (connection, guid))
1930 _DBUS_SET_OOM (&tmp_error);
1931 _dbus_connection_close_possibly_shared_and_unlock (connection);
1932 dbus_connection_unref (connection);
1936 CONNECTION_UNLOCK (connection);
1943 _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
1946 dbus_move_error (&tmp_error, &first_error);
1948 dbus_error_free (&tmp_error);
1951 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1952 _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
1954 if (connection == NULL)
1956 _DBUS_ASSERT_ERROR_IS_SET (&first_error);
1957 dbus_move_error (&first_error, error);
1960 dbus_error_free (&first_error);
1962 dbus_address_entries_free (entries);
1967 * Closes a shared OR private connection, while dbus_connection_close() can
1968 * only be used on private connections. Should only be called by the
1969 * dbus code that owns the connection - an owner must be known,
1970 * the open/close state is like malloc/free, not like ref/unref.
1972 * @param connection the connection
1975 _dbus_connection_close_possibly_shared (DBusConnection *connection)
1977 _dbus_assert (connection != NULL);
1978 _dbus_assert (connection->generation == _dbus_current_generation);
1980 CONNECTION_LOCK (connection);
1981 _dbus_connection_close_possibly_shared_and_unlock (connection);
1984 static DBusPreallocatedSend*
1985 _dbus_connection_preallocate_send_unlocked (DBusConnection *connection)
1987 DBusPreallocatedSend *preallocated;
1989 HAVE_LOCK_CHECK (connection);
1991 _dbus_assert (connection != NULL);
1993 preallocated = dbus_new (DBusPreallocatedSend, 1);
1994 if (preallocated == NULL)
1997 preallocated->queue_link = _dbus_list_alloc_link (NULL);
1998 if (preallocated->queue_link == NULL)
2001 preallocated->counter_link = _dbus_list_alloc_link (connection->outgoing_counter);
2002 if (preallocated->counter_link == NULL)
2005 _dbus_counter_ref (preallocated->counter_link->data);
2007 preallocated->connection = connection;
2009 return preallocated;
2012 _dbus_list_free_link (preallocated->queue_link);
2014 dbus_free (preallocated);
2019 /* Called with lock held, does not update dispatch status */
2021 _dbus_connection_send_preallocated_unlocked_no_update (DBusConnection *connection,
2022 DBusPreallocatedSend *preallocated,
2023 DBusMessage *message,
2024 dbus_uint32_t *client_serial)
2026 dbus_uint32_t serial;
2028 preallocated->queue_link->data = message;
2029 _dbus_list_prepend_link (&connection->outgoing_messages,
2030 preallocated->queue_link);
2032 /* It's OK that we'll never call the notify function, because for the
2033 * outgoing limit, there isn't one */
2034 _dbus_message_add_counter_link (message,
2035 preallocated->counter_link);
2037 dbus_free (preallocated);
2038 preallocated = NULL;
2040 dbus_message_ref (message);
2042 connection->n_outgoing += 1;
2044 _dbus_verbose ("Message %p (%s %s %s %s '%s') for %s added to outgoing queue %p, %d pending to send\n",
2046 dbus_message_type_to_string (dbus_message_get_type (message)),
2047 dbus_message_get_path (message) ?
2048 dbus_message_get_path (message) :
2050 dbus_message_get_interface (message) ?
2051 dbus_message_get_interface (message) :
2053 dbus_message_get_member (message) ?
2054 dbus_message_get_member (message) :
2056 dbus_message_get_signature (message),
2057 dbus_message_get_destination (message) ?
2058 dbus_message_get_destination (message) :
2061 connection->n_outgoing);
2063 if (dbus_message_get_serial (message) == 0)
2065 serial = _dbus_connection_get_next_client_serial (connection);
2066 dbus_message_set_serial (message, serial);
2068 *client_serial = serial;
2073 *client_serial = dbus_message_get_serial (message);
2076 _dbus_verbose ("Message %p serial is %u\n",
2077 message, dbus_message_get_serial (message));
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 * @param 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);
2730 dbus_connection_set_windows_user_function (connection, NULL, NULL, NULL);
2732 _dbus_watch_list_free (connection->watches);
2733 connection->watches = NULL;
2735 _dbus_timeout_list_free (connection->timeouts);
2736 connection->timeouts = NULL;
2738 _dbus_data_slot_list_free (&connection->slot_list);
2740 link = _dbus_list_get_first_link (&connection->filter_list);
2741 while (link != NULL)
2743 DBusMessageFilter *filter = link->data;
2744 DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
2746 filter->function = NULL;
2747 _dbus_message_filter_unref (filter); /* calls app callback */
2752 _dbus_list_clear (&connection->filter_list);
2754 /* ---- Done with stuff that invokes application callbacks */
2756 _dbus_object_tree_unref (connection->objects);
2758 _dbus_hash_table_unref (connection->pending_replies);
2759 connection->pending_replies = NULL;
2761 _dbus_list_clear (&connection->filter_list);
2763 _dbus_list_foreach (&connection->outgoing_messages,
2764 free_outgoing_message,
2766 _dbus_list_clear (&connection->outgoing_messages);
2768 _dbus_list_foreach (&connection->incoming_messages,
2769 (DBusForeachFunction) dbus_message_unref,
2771 _dbus_list_clear (&connection->incoming_messages);
2773 _dbus_counter_unref (connection->outgoing_counter);
2775 _dbus_transport_unref (connection->transport);
2777 if (connection->disconnect_message_link)
2779 DBusMessage *message = connection->disconnect_message_link->data;
2780 dbus_message_unref (message);
2781 _dbus_list_free_link (connection->disconnect_message_link);
2784 _dbus_condvar_free_at_location (&connection->dispatch_cond);
2785 _dbus_condvar_free_at_location (&connection->io_path_cond);
2787 _dbus_cmutex_free_at_location (&connection->io_path_mutex);
2788 _dbus_cmutex_free_at_location (&connection->dispatch_mutex);
2790 _dbus_rmutex_free_at_location (&connection->slot_mutex);
2792 _dbus_rmutex_free_at_location (&connection->mutex);
2794 dbus_free (connection);
2798 * Decrements the reference count of a DBusConnection, and finalizes
2799 * it if the count reaches zero.
2801 * Note: it is a bug to drop the last reference to a connection that
2802 * is still connected.
2804 * For shared connections, libdbus will own a reference
2805 * as long as the connection is connected, so you can know that either
2806 * you don't have the last reference, or it's OK to drop the last reference.
2807 * Most connections are shared. dbus_connection_open() and dbus_bus_get()
2808 * return shared connections.
2810 * For private connections, the creator of the connection must arrange for
2811 * dbus_connection_close() to be called prior to dropping the last reference.
2812 * Private connections come from dbus_connection_open_private() or dbus_bus_get_private().
2814 * @param connection the connection.
2817 dbus_connection_unref (DBusConnection *connection)
2819 dbus_int32_t old_refcount;
2821 _dbus_return_if_fail (connection != NULL);
2822 _dbus_return_if_fail (connection->generation == _dbus_current_generation);
2824 old_refcount = _dbus_atomic_dec (&connection->refcount);
2826 _dbus_connection_trace_ref (connection, old_refcount, old_refcount - 1,
2829 if (old_refcount == 1)
2831 #ifndef DBUS_DISABLE_CHECKS
2832 if (_dbus_transport_get_is_connected (connection->transport))
2834 _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",
2835 connection->shareable ?
2836 "Most likely, the application called unref() too many times and removed a reference belonging to libdbus, since this is a shared connection.\n" :
2837 "Most likely, the application was supposed to call dbus_connection_close(), since this is a private connection.\n");
2841 _dbus_connection_last_unref (connection);
2846 * Note that the transport can disconnect itself (other end drops us)
2847 * and in that case this function never runs. So this function must
2848 * not do anything more than disconnect the transport and update the
2851 * If the transport self-disconnects, then we assume someone will
2852 * dispatch the connection to cause the dispatch status update.
2855 _dbus_connection_close_possibly_shared_and_unlock (DBusConnection *connection)
2857 DBusDispatchStatus status;
2859 HAVE_LOCK_CHECK (connection);
2861 _dbus_verbose ("Disconnecting %p\n", connection);
2863 /* We need to ref because update_dispatch_status_and_unlock will unref
2864 * the connection if it was shared and libdbus was the only remaining
2867 _dbus_connection_ref_unlocked (connection);
2869 _dbus_transport_disconnect (connection->transport);
2871 /* This has the side effect of queuing the disconnect message link
2872 * (unless we don't have enough memory, possibly, so don't assert it).
2873 * After the disconnect message link is queued, dbus_bus_get/dbus_connection_open
2874 * should never again return the newly-disconnected connection.
2876 * However, we only unref the shared connection and exit_on_disconnect when
2877 * the disconnect message reaches the head of the message queue,
2878 * NOT when it's first queued.
2880 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2882 /* This calls out to user code */
2883 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2885 /* Could also call out to user code */
2886 dbus_connection_unref (connection);
2890 * Closes a private connection, so no further data can be sent or received.
2891 * This disconnects the transport (such as a socket) underlying the
2894 * Attempts to send messages after closing a connection are safe, but will result in
2895 * error replies generated locally in libdbus.
2897 * This function does not affect the connection's reference count. It's
2898 * safe to close a connection more than once; all calls after the
2899 * first do nothing. It's impossible to "reopen" a connection, a
2900 * new connection must be created. This function may result in a call
2901 * to the DBusDispatchStatusFunction set with
2902 * dbus_connection_set_dispatch_status_function(), as the disconnect
2903 * message it generates needs to be dispatched.
2905 * If a connection is dropped by the remote application, it will
2908 * You must close a connection prior to releasing the last reference to
2909 * the connection. If you dbus_connection_unref() for the last time
2910 * without closing the connection, the results are undefined; it
2911 * is a bug in your program and libdbus will try to print a warning.
2913 * You may not close a shared connection. Connections created with
2914 * dbus_connection_open() or dbus_bus_get() are shared.
2915 * These connections are owned by libdbus, and applications should
2916 * only unref them, never close them. Applications can know it is
2917 * safe to unref these connections because libdbus will be holding a
2918 * reference as long as the connection is open. Thus, either the
2919 * connection is closed and it is OK to drop the last reference,
2920 * or the connection is open and the app knows it does not have the
2923 * Connections created with dbus_connection_open_private() or
2924 * dbus_bus_get_private() are not kept track of or referenced by
2925 * libdbus. The creator of these connections is responsible for
2926 * calling dbus_connection_close() prior to releasing the last
2927 * reference, if the connection is not already disconnected.
2929 * @param connection the private (unshared) connection to close
2932 dbus_connection_close (DBusConnection *connection)
2934 _dbus_return_if_fail (connection != NULL);
2935 _dbus_return_if_fail (connection->generation == _dbus_current_generation);
2937 CONNECTION_LOCK (connection);
2939 #ifndef DBUS_DISABLE_CHECKS
2940 if (connection->shareable)
2942 CONNECTION_UNLOCK (connection);
2944 _dbus_warn_check_failed ("Applications must not close shared connections - see dbus_connection_close() docs. This is a bug in the application.\n");
2949 _dbus_connection_close_possibly_shared_and_unlock (connection);
2953 _dbus_connection_get_is_connected_unlocked (DBusConnection *connection)
2955 HAVE_LOCK_CHECK (connection);
2956 return _dbus_transport_get_is_connected (connection->transport);
2960 * Gets whether the connection is currently open. A connection may
2961 * become disconnected when the remote application closes its end, or
2962 * exits; a connection may also be disconnected with
2963 * dbus_connection_close().
2965 * There are not separate states for "closed" and "disconnected," the two
2966 * terms are synonymous. This function should really be called
2967 * get_is_open() but for historical reasons is not.
2969 * @param connection the connection.
2970 * @returns #TRUE if the connection is still alive.
2973 dbus_connection_get_is_connected (DBusConnection *connection)
2977 _dbus_return_val_if_fail (connection != NULL, FALSE);
2979 CONNECTION_LOCK (connection);
2980 res = _dbus_connection_get_is_connected_unlocked (connection);
2981 CONNECTION_UNLOCK (connection);
2987 * Gets whether the connection was authenticated. (Note that
2988 * if the connection was authenticated then disconnected,
2989 * this function still returns #TRUE)
2991 * @param connection the connection
2992 * @returns #TRUE if the connection was ever authenticated
2995 dbus_connection_get_is_authenticated (DBusConnection *connection)
2999 _dbus_return_val_if_fail (connection != NULL, FALSE);
3001 CONNECTION_LOCK (connection);
3002 res = _dbus_transport_try_to_authenticate (connection->transport);
3003 CONNECTION_UNLOCK (connection);
3009 * Sets authenticated status for connection. Needed for kdbus, where authentication is
3010 * made in different manner.
3011 * LOCK commented out because called with lock already set
3012 * @param connection the connection
3015 dbus_connection_set_is_authenticated (DBusConnection *connection)
3017 _dbus_return_val_if_fail (connection != NULL, FALSE);
3019 // CONNECTION_LOCK (connection);
3020 connection->transport->authenticated = TRUE;
3021 // CONNECTION_UNLOCK (connection);
3027 * Gets whether the connection is not authenticated as a specific
3028 * user. If the connection is not authenticated, this function
3029 * returns #TRUE, and if it is authenticated but as an anonymous user,
3030 * it returns #TRUE. If it is authenticated as a specific user, then
3031 * this returns #FALSE. (Note that if the connection was authenticated
3032 * as anonymous then disconnected, this function still returns #TRUE.)
3034 * If the connection is not anonymous, you can use
3035 * dbus_connection_get_unix_user() and
3036 * dbus_connection_get_windows_user() to see who it's authorized as.
3038 * If you want to prevent non-anonymous authorization, use
3039 * dbus_server_set_auth_mechanisms() to remove the mechanisms that
3040 * allow proving user identity (i.e. only allow the ANONYMOUS
3043 * @param connection the connection
3044 * @returns #TRUE if not authenticated or authenticated as anonymous
3047 dbus_connection_get_is_anonymous (DBusConnection *connection)
3051 _dbus_return_val_if_fail (connection != NULL, FALSE);
3053 CONNECTION_LOCK (connection);
3054 res = _dbus_transport_get_is_anonymous (connection->transport);
3055 CONNECTION_UNLOCK (connection);
3061 * Gets the ID of the server address we are authenticated to, if this
3062 * connection is on the client side. If the connection is on the
3063 * server side, this will always return #NULL - use dbus_server_get_id()
3064 * to get the ID of your own server, if you are the server side.
3066 * If a client-side connection is not authenticated yet, the ID may be
3067 * available if it was included in the server address, but may not be
3068 * available. The only way to be sure the server ID is available
3069 * is to wait for authentication to complete.
3071 * In general, each mode of connecting to a given server will have
3072 * its own ID. So for example, if the session bus daemon is listening
3073 * on UNIX domain sockets and on TCP, then each of those modalities
3074 * will have its own server ID.
3076 * If you want an ID that identifies an entire session bus, look at
3077 * dbus_bus_get_id() instead (which is just a convenience wrapper
3078 * around the org.freedesktop.DBus.GetId method invoked on the bus).
3080 * You can also get a machine ID; see dbus_get_local_machine_id() to
3081 * get the machine you are on. There isn't a convenience wrapper, but
3082 * you can invoke org.freedesktop.DBus.Peer.GetMachineId on any peer
3083 * to get the machine ID on the other end.
3085 * The D-Bus specification describes the server ID and other IDs in a
3088 * @param connection the connection
3089 * @returns the server ID or #NULL if no memory or the connection is server-side
3092 dbus_connection_get_server_id (DBusConnection *connection)
3096 _dbus_return_val_if_fail (connection != NULL, NULL);
3098 CONNECTION_LOCK (connection);
3099 id = _dbus_strdup (_dbus_transport_get_server_id (connection->transport));
3100 CONNECTION_UNLOCK (connection);
3106 * Tests whether a certain type can be send via the connection. This
3107 * will always return TRUE for all types, with the exception of
3108 * DBUS_TYPE_UNIX_FD. The function will return TRUE for
3109 * DBUS_TYPE_UNIX_FD only on systems that know Unix file descriptors
3110 * and can send them via the chosen transport and when the remote side
3113 * This function can be used to do runtime checking for types that
3114 * might be unknown to the specific D-Bus client implementation
3115 * version, i.e. it will return FALSE for all types this
3116 * implementation does not know, including invalid or reserved types.
3118 * @param connection the connection
3119 * @param type the type to check
3120 * @returns TRUE if the type may be send via the connection
3123 dbus_connection_can_send_type(DBusConnection *connection,
3126 _dbus_return_val_if_fail (connection != NULL, FALSE);
3128 if (!dbus_type_is_valid (type))
3131 if (type != DBUS_TYPE_UNIX_FD)
3134 #ifdef HAVE_UNIX_FD_PASSING
3138 CONNECTION_LOCK(connection);
3139 b = _dbus_transport_can_pass_unix_fd(connection->transport);
3140 CONNECTION_UNLOCK(connection);
3150 * Set whether _exit() should be called when the connection receives a
3151 * disconnect signal. The call to _exit() comes after any handlers for
3152 * the disconnect signal run; handlers can cancel the exit by calling
3155 * By default, exit_on_disconnect is #FALSE; but for message bus
3156 * connections returned from dbus_bus_get() it will be toggled on
3159 * @param connection the connection
3160 * @param exit_on_disconnect #TRUE if _exit() should be called after a disconnect signal
3163 dbus_connection_set_exit_on_disconnect (DBusConnection *connection,
3164 dbus_bool_t exit_on_disconnect)
3166 _dbus_return_if_fail (connection != NULL);
3168 CONNECTION_LOCK (connection);
3169 connection->exit_on_disconnect = exit_on_disconnect != FALSE;
3170 CONNECTION_UNLOCK (connection);
3174 * Preallocates resources needed to send a message, allowing the message
3175 * to be sent without the possibility of memory allocation failure.
3176 * Allows apps to create a future guarantee that they can send
3177 * a message regardless of memory shortages.
3179 * @param connection the connection we're preallocating for.
3180 * @returns the preallocated resources, or #NULL
3182 DBusPreallocatedSend*
3183 dbus_connection_preallocate_send (DBusConnection *connection)
3185 DBusPreallocatedSend *preallocated;
3187 _dbus_return_val_if_fail (connection != NULL, NULL);
3189 CONNECTION_LOCK (connection);
3192 _dbus_connection_preallocate_send_unlocked (connection);
3194 CONNECTION_UNLOCK (connection);
3196 return preallocated;
3200 * Frees preallocated message-sending resources from
3201 * dbus_connection_preallocate_send(). Should only
3202 * be called if the preallocated resources are not used
3203 * to send a message.
3205 * @param connection the connection
3206 * @param preallocated the resources
3209 dbus_connection_free_preallocated_send (DBusConnection *connection,
3210 DBusPreallocatedSend *preallocated)
3212 _dbus_return_if_fail (connection != NULL);
3213 _dbus_return_if_fail (preallocated != NULL);
3214 _dbus_return_if_fail (connection == preallocated->connection);
3216 _dbus_list_free_link (preallocated->queue_link);
3217 _dbus_counter_unref (preallocated->counter_link->data);
3218 _dbus_list_free_link (preallocated->counter_link);
3219 dbus_free (preallocated);
3223 * Sends a message using preallocated resources. This function cannot fail.
3224 * It works identically to dbus_connection_send() in other respects.
3225 * Preallocated resources comes from dbus_connection_preallocate_send().
3226 * This function "consumes" the preallocated resources, they need not
3227 * be freed separately.
3229 * @param connection the connection
3230 * @param preallocated the preallocated resources
3231 * @param message the message to send
3232 * @param client_serial return location for client serial assigned to the message
3235 dbus_connection_send_preallocated (DBusConnection *connection,
3236 DBusPreallocatedSend *preallocated,
3237 DBusMessage *message,
3238 dbus_uint32_t *client_serial)
3240 _dbus_return_if_fail (connection != NULL);
3241 _dbus_return_if_fail (preallocated != NULL);
3242 _dbus_return_if_fail (message != NULL);
3243 _dbus_return_if_fail (preallocated->connection == connection);
3244 _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_METHOD_CALL ||
3245 dbus_message_get_member (message) != NULL);
3246 _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL ||
3247 (dbus_message_get_interface (message) != NULL &&
3248 dbus_message_get_member (message) != NULL));
3250 CONNECTION_LOCK (connection);
3252 #ifdef HAVE_UNIX_FD_PASSING
3254 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3255 message->n_unix_fds > 0)
3257 /* Refuse to send fds on a connection that cannot handle
3258 them. Unfortunately we cannot return a proper error here, so
3259 the best we can is just return. */
3260 CONNECTION_UNLOCK (connection);
3265 _dbus_verbose ("Reply sender: %s, destination: %s\n", dbus_message_get_sender(message), dbus_message_get_destination(message)); //todo kdbus temp addon
3266 _dbus_connection_send_preallocated_and_unlock (connection,
3268 message, client_serial);
3272 _dbus_connection_send_unlocked_no_update (DBusConnection *connection,
3273 DBusMessage *message,
3274 dbus_uint32_t *client_serial)
3276 DBusPreallocatedSend *preallocated;
3278 _dbus_assert (connection != NULL);
3279 _dbus_assert (message != NULL);
3281 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
3282 if (preallocated == NULL)
3285 _dbus_connection_send_preallocated_unlocked_no_update (connection,
3293 * Adds a message to the outgoing message queue. Does not block to
3294 * write the message to the network; that happens asynchronously. To
3295 * force the message to be written, call dbus_connection_flush() however
3296 * it is not necessary to call dbus_connection_flush() by hand; the
3297 * message will be sent the next time the main loop is run.
3298 * dbus_connection_flush() should only be used, for example, if
3299 * the application was expected to exit before running the main loop.
3301 * Because this only queues the message, the only reason it can
3302 * fail is lack of memory. Even if the connection is disconnected,
3303 * no error will be returned. If the function fails due to lack of memory,
3304 * it returns #FALSE. The function will never fail for other reasons; even
3305 * if the connection is disconnected, you can queue an outgoing message,
3306 * though obviously it won't be sent.
3308 * The message serial is used by the remote application to send a
3309 * reply; see dbus_message_get_serial() or the D-Bus specification.
3311 * dbus_message_unref() can be called as soon as this method returns
3312 * as the message queue will hold its own ref until the message is sent.
3314 * @param connection the connection.
3315 * @param message the message to write.
3316 * @param serial return location for message serial, or #NULL if you don't care
3317 * @returns #TRUE on success.
3320 dbus_connection_send (DBusConnection *connection,
3321 DBusMessage *message,
3322 dbus_uint32_t *serial)
3324 _dbus_return_val_if_fail (connection != NULL, FALSE);
3325 _dbus_return_val_if_fail (message != NULL, FALSE);
3327 CONNECTION_LOCK (connection);
3329 #ifdef HAVE_UNIX_FD_PASSING
3331 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3332 message->n_unix_fds > 0)
3334 /* Refuse to send fds on a connection that cannot handle
3335 them. Unfortunately we cannot return a proper error here, so
3336 the best we can is just return. */
3337 CONNECTION_UNLOCK (connection);
3343 return _dbus_connection_send_and_unlock (connection,
3349 reply_handler_timeout (void *data)
3351 DBusConnection *connection;
3352 DBusDispatchStatus status;
3353 DBusPendingCall *pending = data;
3355 connection = _dbus_pending_call_get_connection_and_lock (pending);
3356 _dbus_connection_ref_unlocked (connection);
3358 _dbus_pending_call_queue_timeout_error_unlocked (pending,
3360 _dbus_connection_remove_timeout_unlocked (connection,
3361 _dbus_pending_call_get_timeout_unlocked (pending));
3362 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
3364 _dbus_verbose ("middle\n");
3365 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3367 /* Unlocks, and calls out to user code */
3368 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3369 dbus_connection_unref (connection);
3375 * Queues a message to send, as with dbus_connection_send(),
3376 * but also returns a #DBusPendingCall used to receive a reply to the
3377 * message. If no reply is received in the given timeout_milliseconds,
3378 * this function expires the pending reply and generates a synthetic
3379 * error reply (generated in-process, not by the remote application)
3380 * indicating that a timeout occurred.
3382 * A #DBusPendingCall will see a reply message before any filters or
3383 * registered object path handlers. See dbus_connection_dispatch() for
3384 * details on when handlers are run.
3386 * A #DBusPendingCall will always see exactly one reply message,
3387 * unless it's cancelled with dbus_pending_call_cancel().
3389 * If #NULL is passed for the pending_return, the #DBusPendingCall
3390 * will still be generated internally, and used to track
3391 * the message reply timeout. This means a timeout error will
3392 * occur if no reply arrives, unlike with dbus_connection_send().
3394 * If -1 is passed for the timeout, a sane default timeout is used. -1
3395 * is typically the best value for the timeout for this reason, unless
3396 * you want a very short or very long timeout. If #DBUS_TIMEOUT_INFINITE is
3397 * passed for the timeout, no timeout will be set and the call will block
3400 * @warning if the connection is disconnected or you try to send Unix
3401 * file descriptors on a connection that does not support them, the
3402 * #DBusPendingCall will be set to #NULL, so be careful with this.
3404 * @param connection the connection
3405 * @param message the message to send
3406 * @param pending_return return location for a #DBusPendingCall
3407 * object, or #NULL if connection is disconnected or when you try to
3408 * send Unix file descriptors on a connection that does not support
3410 * @param timeout_milliseconds timeout in milliseconds, -1 (or
3411 * #DBUS_TIMEOUT_USE_DEFAULT) for default or #DBUS_TIMEOUT_INFINITE for no
3413 * @returns #FALSE if no memory, #TRUE otherwise.
3417 dbus_connection_send_with_reply (DBusConnection *connection,
3418 DBusMessage *message,
3419 DBusPendingCall **pending_return,
3420 int timeout_milliseconds)
3422 DBusPendingCall *pending;
3423 dbus_int32_t serial = -1;
3424 DBusDispatchStatus status;
3426 _dbus_return_val_if_fail (connection != NULL, FALSE);
3427 _dbus_return_val_if_fail (message != NULL, FALSE);
3428 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3431 *pending_return = NULL;
3433 CONNECTION_LOCK (connection);
3435 #ifdef HAVE_UNIX_FD_PASSING
3437 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3438 message->n_unix_fds > 0)
3440 /* Refuse to send fds on a connection that cannot handle
3441 them. Unfortunately we cannot return a proper error here, so
3442 the best we can do is return TRUE but leave *pending_return
3444 CONNECTION_UNLOCK (connection);
3450 if (!_dbus_connection_get_is_connected_unlocked (connection))
3452 CONNECTION_UNLOCK (connection);
3457 pending = _dbus_pending_call_new_unlocked (connection,
3458 timeout_milliseconds,
3459 reply_handler_timeout);
3461 if (pending == NULL)
3463 CONNECTION_UNLOCK (connection);
3467 /* Assign a serial to the message */
3468 serial = dbus_message_get_serial (message);
3471 serial = _dbus_connection_get_next_client_serial (connection);
3472 dbus_message_set_serial (message, serial);
3475 if (!_dbus_pending_call_set_timeout_error_unlocked (pending, message, serial))
3478 /* Insert the serial in the pending replies hash;
3479 * hash takes a refcount on DBusPendingCall.
3480 * Also, add the timeout.
3482 if (!_dbus_connection_attach_pending_call_unlocked (connection,
3486 if (!_dbus_connection_send_unlocked_no_update (connection, message, NULL))
3488 _dbus_connection_detach_pending_call_and_unlock (connection,
3490 goto error_unlocked;
3494 *pending_return = pending; /* hand off refcount */
3497 _dbus_connection_detach_pending_call_unlocked (connection, pending);
3498 /* we still have a ref to the pending call in this case, we unref
3499 * after unlocking, below
3503 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3505 /* this calls out to user code */
3506 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3508 if (pending_return == NULL)
3509 dbus_pending_call_unref (pending);
3514 CONNECTION_UNLOCK (connection);
3516 dbus_pending_call_unref (pending);
3521 * Sends a message and blocks a certain time period while waiting for
3522 * a reply. This function does not reenter the main loop,
3523 * i.e. messages other than the reply are queued up but not
3524 * processed. This function is used to invoke method calls on a
3527 * If a normal reply is received, it is returned, and removed from the
3528 * incoming message queue. If it is not received, #NULL is returned
3529 * and the error is set to #DBUS_ERROR_NO_REPLY. If an error reply is
3530 * received, it is converted to a #DBusError and returned as an error,
3531 * then the reply message is deleted and #NULL is returned. If
3532 * something else goes wrong, result is set to whatever is
3533 * appropriate, such as #DBUS_ERROR_NO_MEMORY or
3534 * #DBUS_ERROR_DISCONNECTED.
3536 * @warning While this function blocks the calling thread will not be
3537 * processing the incoming message queue. This means you can end up
3538 * deadlocked if the application you're talking to needs you to reply
3539 * to a method. To solve this, either avoid the situation, block in a
3540 * separate thread from the main connection-dispatching thread, or use
3541 * dbus_pending_call_set_notify() to avoid blocking.
3543 * @param connection the connection
3544 * @param message the message to send
3545 * @param timeout_milliseconds timeout in milliseconds, -1 (or
3546 * #DBUS_TIMEOUT_USE_DEFAULT) for default or #DBUS_TIMEOUT_INFINITE for no
3548 * @param error return location for error message
3549 * @returns the message that is the reply or #NULL with an error code if the
3553 dbus_connection_send_with_reply_and_block (DBusConnection *connection,
3554 DBusMessage *message,
3555 int timeout_milliseconds,
3559 DBusPendingCall *pending;
3561 _dbus_return_val_if_fail (connection != NULL, NULL);
3562 _dbus_return_val_if_fail (message != NULL, NULL);
3563 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, NULL);
3564 _dbus_return_val_if_error_is_set (error, NULL);
3566 #ifdef HAVE_UNIX_FD_PASSING
3568 CONNECTION_LOCK (connection);
3569 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3570 message->n_unix_fds > 0)
3572 CONNECTION_UNLOCK (connection);
3573 dbus_set_error(error, DBUS_ERROR_FAILED, "Cannot send file descriptors on this connection.");
3576 CONNECTION_UNLOCK (connection);
3580 if (!dbus_connection_send_with_reply (connection, message,
3581 &pending, timeout_milliseconds))
3583 _DBUS_SET_OOM (error);
3587 if (pending == NULL)
3589 dbus_set_error (error, DBUS_ERROR_DISCONNECTED, "Connection is closed");
3593 dbus_pending_call_block (pending);
3595 reply = dbus_pending_call_steal_reply (pending);
3596 dbus_pending_call_unref (pending);
3598 /* call_complete_and_unlock() called from pending_call_block() should
3599 * always fill this in.
3601 _dbus_assert (reply != NULL);
3603 if (dbus_set_error_from_message (error, reply))
3605 dbus_message_unref (reply);
3613 * Blocks until the outgoing message queue is empty.
3614 * Assumes connection lock already held.
3616 * If you call this, you MUST call update_dispatch_status afterword...
3618 * @param connection the connection.
3620 static DBusDispatchStatus
3621 _dbus_connection_flush_unlocked (DBusConnection *connection)
3623 /* We have to specify DBUS_ITERATION_DO_READING here because
3624 * otherwise we could have two apps deadlock if they are both doing
3625 * a flush(), and the kernel buffers fill up. This could change the
3628 DBusDispatchStatus status;
3630 HAVE_LOCK_CHECK (connection);
3632 while (connection->n_outgoing > 0 &&
3633 _dbus_connection_get_is_connected_unlocked (connection))
3635 _dbus_verbose ("doing iteration in\n");
3636 HAVE_LOCK_CHECK (connection);
3637 _dbus_connection_do_iteration_unlocked (connection,
3639 DBUS_ITERATION_DO_READING |
3640 DBUS_ITERATION_DO_WRITING |
3641 DBUS_ITERATION_BLOCK,
3645 HAVE_LOCK_CHECK (connection);
3646 _dbus_verbose ("middle\n");
3647 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3649 HAVE_LOCK_CHECK (connection);
3654 * Blocks until the outgoing message queue is empty.
3656 * @param connection the connection.
3659 dbus_connection_flush (DBusConnection *connection)
3661 /* We have to specify DBUS_ITERATION_DO_READING here because
3662 * otherwise we could have two apps deadlock if they are both doing
3663 * a flush(), and the kernel buffers fill up. This could change the
3666 DBusDispatchStatus status;
3668 _dbus_return_if_fail (connection != NULL);
3670 CONNECTION_LOCK (connection);
3672 status = _dbus_connection_flush_unlocked (connection);
3674 HAVE_LOCK_CHECK (connection);
3675 /* Unlocks and calls out to user code */
3676 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3678 _dbus_verbose ("end\n");
3682 * This function implements dbus_connection_read_write_dispatch() and
3683 * dbus_connection_read_write() (they pass a different value for the
3684 * dispatch parameter).
3686 * @param connection the connection
3687 * @param timeout_milliseconds max time to block or -1 for infinite
3688 * @param dispatch dispatch new messages or leave them on the incoming queue
3689 * @returns #TRUE if the disconnect message has not been processed
3692 _dbus_connection_read_write_dispatch (DBusConnection *connection,
3693 int timeout_milliseconds,
3694 dbus_bool_t dispatch)
3696 DBusDispatchStatus dstatus;
3697 dbus_bool_t progress_possible;
3699 /* Need to grab a ref here in case we're a private connection and
3700 * the user drops the last ref in a handler we call; see bug
3701 * https://bugs.freedesktop.org/show_bug.cgi?id=15635
3703 dbus_connection_ref (connection);
3704 dstatus = dbus_connection_get_dispatch_status (connection);
3706 if (dispatch && dstatus == DBUS_DISPATCH_DATA_REMAINS)
3708 _dbus_verbose ("doing dispatch\n");
3709 dbus_connection_dispatch (connection);
3710 CONNECTION_LOCK (connection);
3712 else if (dstatus == DBUS_DISPATCH_NEED_MEMORY)
3714 _dbus_verbose ("pausing for memory\n");
3715 _dbus_memory_pause_based_on_timeout (timeout_milliseconds);
3716 CONNECTION_LOCK (connection);
3720 CONNECTION_LOCK (connection);
3721 if (_dbus_connection_get_is_connected_unlocked (connection))
3723 _dbus_verbose ("doing iteration\n");
3724 _dbus_connection_do_iteration_unlocked (connection,
3726 DBUS_ITERATION_DO_READING |
3727 DBUS_ITERATION_DO_WRITING |
3728 DBUS_ITERATION_BLOCK,
3729 timeout_milliseconds);
3733 HAVE_LOCK_CHECK (connection);
3734 /* If we can dispatch, we can make progress until the Disconnected message
3735 * has been processed; if we can only read/write, we can make progress
3736 * as long as the transport is open.
3739 progress_possible = connection->n_incoming != 0 ||
3740 connection->disconnect_message_link != NULL;
3742 progress_possible = _dbus_connection_get_is_connected_unlocked (connection);
3744 CONNECTION_UNLOCK (connection);
3746 dbus_connection_unref (connection);
3748 return progress_possible; /* TRUE if we can make more progress */
3753 * This function is intended for use with applications that don't want
3754 * to write a main loop and deal with #DBusWatch and #DBusTimeout. An
3755 * example usage would be:
3758 * while (dbus_connection_read_write_dispatch (connection, -1))
3759 * ; // empty loop body
3762 * In this usage you would normally have set up a filter function to look
3763 * at each message as it is dispatched. The loop terminates when the last
3764 * message from the connection (the disconnected signal) is processed.
3766 * If there are messages to dispatch, this function will
3767 * dbus_connection_dispatch() once, and return. If there are no
3768 * messages to dispatch, this function will block until it can read or
3769 * write, then read or write, then return.
3771 * The way to think of this function is that it either makes some sort
3772 * of progress, or it blocks. Note that, while it is blocked on I/O, it
3773 * cannot be interrupted (even by other threads), which makes this function
3774 * unsuitable for applications that do more than just react to received
3777 * The return value indicates whether the disconnect message has been
3778 * processed, NOT whether the connection is connected. This is
3779 * important because even after disconnecting, you want to process any
3780 * messages you received prior to the disconnect.
3782 * @param connection the connection
3783 * @param timeout_milliseconds max time to block or -1 for infinite
3784 * @returns #TRUE if the disconnect message has not been processed
3787 dbus_connection_read_write_dispatch (DBusConnection *connection,
3788 int timeout_milliseconds)
3790 _dbus_return_val_if_fail (connection != NULL, FALSE);
3791 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3792 return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, TRUE);
3796 * This function is intended for use with applications that don't want to
3797 * write a main loop and deal with #DBusWatch and #DBusTimeout. See also
3798 * dbus_connection_read_write_dispatch().
3800 * As long as the connection is open, this function will block until it can
3801 * read or write, then read or write, then return #TRUE.
3803 * If the connection is closed, the function returns #FALSE.
3805 * The return value indicates whether reading or writing is still
3806 * possible, i.e. whether the connection is connected.
3808 * Note that even after disconnection, messages may remain in the
3809 * incoming queue that need to be
3810 * processed. dbus_connection_read_write_dispatch() dispatches
3811 * incoming messages for you; with dbus_connection_read_write() you
3812 * have to arrange to drain the incoming queue yourself.
3814 * @param connection the connection
3815 * @param timeout_milliseconds max time to block or -1 for infinite
3816 * @returns #TRUE if still connected
3819 dbus_connection_read_write (DBusConnection *connection,
3820 int timeout_milliseconds)
3822 _dbus_return_val_if_fail (connection != NULL, FALSE);
3823 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3824 return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, FALSE);
3827 /* We need to call this anytime we pop the head of the queue, and then
3828 * update_dispatch_status_and_unlock needs to be called afterward
3829 * which will "process" the disconnected message and set
3830 * disconnected_message_processed.
3833 check_disconnected_message_arrived_unlocked (DBusConnection *connection,
3834 DBusMessage *head_of_queue)
3836 HAVE_LOCK_CHECK (connection);
3838 /* checking that the link is NULL is an optimization to avoid the is_signal call */
3839 if (connection->disconnect_message_link == NULL &&
3840 dbus_message_is_signal (head_of_queue,
3841 DBUS_INTERFACE_LOCAL,
3844 connection->disconnected_message_arrived = TRUE;
3849 * Returns the first-received message from the incoming message queue,
3850 * leaving it in the queue. If the queue is empty, returns #NULL.
3852 * The caller does not own a reference to the returned message, and
3853 * must either return it using dbus_connection_return_message() or
3854 * keep it after calling dbus_connection_steal_borrowed_message(). No
3855 * one can get at the message while its borrowed, so return it as
3856 * quickly as possible and don't keep a reference to it after
3857 * returning it. If you need to keep the message, make a copy of it.
3859 * dbus_connection_dispatch() will block if called while a borrowed
3860 * message is outstanding; only one piece of code can be playing with
3861 * the incoming queue at a time. This function will block if called
3862 * during a dbus_connection_dispatch().
3864 * @param connection the connection.
3865 * @returns next message in the incoming queue.
3868 dbus_connection_borrow_message (DBusConnection *connection)
3870 DBusDispatchStatus status;
3871 DBusMessage *message;
3873 _dbus_return_val_if_fail (connection != NULL, NULL);
3875 _dbus_verbose ("start\n");
3877 /* this is called for the side effect that it queues
3878 * up any messages from the transport
3880 status = dbus_connection_get_dispatch_status (connection);
3881 if (status != DBUS_DISPATCH_DATA_REMAINS)
3884 CONNECTION_LOCK (connection);
3886 _dbus_connection_acquire_dispatch (connection);
3888 /* While a message is outstanding, the dispatch lock is held */
3889 _dbus_assert (connection->message_borrowed == NULL);
3891 connection->message_borrowed = _dbus_list_get_first (&connection->incoming_messages);
3893 message = connection->message_borrowed;
3895 check_disconnected_message_arrived_unlocked (connection, message);
3897 /* Note that we KEEP the dispatch lock until the message is returned */
3898 if (message == NULL)
3899 _dbus_connection_release_dispatch (connection);
3901 CONNECTION_UNLOCK (connection);
3903 _dbus_message_trace_ref (message, -1, -1, "dbus_connection_borrow_message");
3905 /* We don't update dispatch status until it's returned or stolen */
3911 * Used to return a message after peeking at it using
3912 * dbus_connection_borrow_message(). Only called if
3913 * message from dbus_connection_borrow_message() was non-#NULL.
3915 * @param connection the connection
3916 * @param message the message from dbus_connection_borrow_message()
3919 dbus_connection_return_message (DBusConnection *connection,
3920 DBusMessage *message)
3922 DBusDispatchStatus status;
3924 _dbus_return_if_fail (connection != NULL);
3925 _dbus_return_if_fail (message != NULL);
3926 _dbus_return_if_fail (message == connection->message_borrowed);
3927 _dbus_return_if_fail (connection->dispatch_acquired);
3929 CONNECTION_LOCK (connection);
3931 _dbus_assert (message == connection->message_borrowed);
3933 connection->message_borrowed = NULL;
3935 _dbus_connection_release_dispatch (connection);
3937 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3938 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3940 _dbus_message_trace_ref (message, -1, -1, "dbus_connection_return_message");
3944 * Used to keep a message after peeking at it using
3945 * dbus_connection_borrow_message(). Before using this function, see
3946 * the caveats/warnings in the documentation for
3947 * dbus_connection_pop_message().
3949 * @param connection the connection
3950 * @param message the message from dbus_connection_borrow_message()
3953 dbus_connection_steal_borrowed_message (DBusConnection *connection,
3954 DBusMessage *message)
3956 DBusMessage *pop_message;
3957 DBusDispatchStatus status;
3959 _dbus_return_if_fail (connection != NULL);
3960 _dbus_return_if_fail (message != NULL);
3961 _dbus_return_if_fail (message == connection->message_borrowed);
3962 _dbus_return_if_fail (connection->dispatch_acquired);
3964 CONNECTION_LOCK (connection);
3966 _dbus_assert (message == connection->message_borrowed);
3968 pop_message = _dbus_list_pop_first (&connection->incoming_messages);
3969 _dbus_assert (message == pop_message);
3970 (void) pop_message; /* unused unless asserting */
3972 connection->n_incoming -= 1;
3974 _dbus_verbose ("Incoming message %p stolen from queue, %d incoming\n",
3975 message, connection->n_incoming);
3977 connection->message_borrowed = NULL;
3979 _dbus_connection_release_dispatch (connection);
3981 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3982 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3983 _dbus_message_trace_ref (message, -1, -1,
3984 "dbus_connection_steal_borrowed_message");
3987 /* See dbus_connection_pop_message, but requires the caller to own
3988 * the lock before calling. May drop the lock while running.
3991 _dbus_connection_pop_message_link_unlocked (DBusConnection *connection)
3993 HAVE_LOCK_CHECK (connection);
3995 _dbus_assert (connection->message_borrowed == NULL);
3997 if (connection->n_incoming > 0)
4001 link = _dbus_list_pop_first_link (&connection->incoming_messages);
4002 connection->n_incoming -= 1;
4004 _dbus_verbose ("Message %p (%s %s %s %s sig:'%s' serial:%u) removed from incoming queue %p, %d incoming\n",
4006 dbus_message_type_to_string (dbus_message_get_type (link->data)),
4007 dbus_message_get_path (link->data) ?
4008 dbus_message_get_path (link->data) :
4010 dbus_message_get_interface (link->data) ?
4011 dbus_message_get_interface (link->data) :
4013 dbus_message_get_member (link->data) ?
4014 dbus_message_get_member (link->data) :
4016 dbus_message_get_signature (link->data),
4017 dbus_message_get_serial (link->data),
4018 connection, connection->n_incoming);
4020 _dbus_message_trace_ref (link->data, -1, -1,
4021 "_dbus_connection_pop_message_link_unlocked");
4023 check_disconnected_message_arrived_unlocked (connection, link->data);
4031 /* See dbus_connection_pop_message, but requires the caller to own
4032 * the lock before calling. May drop the lock while running.
4035 _dbus_connection_pop_message_unlocked (DBusConnection *connection)
4039 HAVE_LOCK_CHECK (connection);
4041 link = _dbus_connection_pop_message_link_unlocked (connection);
4045 DBusMessage *message;
4047 message = link->data;
4049 _dbus_list_free_link (link);
4058 _dbus_connection_putback_message_link_unlocked (DBusConnection *connection,
4059 DBusList *message_link)
4061 HAVE_LOCK_CHECK (connection);
4063 _dbus_assert (message_link != NULL);
4064 /* You can't borrow a message while a link is outstanding */
4065 _dbus_assert (connection->message_borrowed == NULL);
4066 /* We had to have the dispatch lock across the pop/putback */
4067 _dbus_assert (connection->dispatch_acquired);
4069 _dbus_list_prepend_link (&connection->incoming_messages,
4071 connection->n_incoming += 1;
4073 _dbus_verbose ("Message %p (%s %s %s '%s') put back into queue %p, %d incoming\n",
4075 dbus_message_type_to_string (dbus_message_get_type (message_link->data)),
4076 dbus_message_get_interface (message_link->data) ?
4077 dbus_message_get_interface (message_link->data) :
4079 dbus_message_get_member (message_link->data) ?
4080 dbus_message_get_member (message_link->data) :
4082 dbus_message_get_signature (message_link->data),
4083 connection, connection->n_incoming);
4085 _dbus_message_trace_ref (message_link->data, -1, -1,
4086 "_dbus_connection_putback_message_link_unlocked");
4090 * Returns the first-received message from the incoming message queue,
4091 * removing it from the queue. The caller owns a reference to the
4092 * returned message. If the queue is empty, returns #NULL.
4094 * This function bypasses any message handlers that are registered,
4095 * and so using it is usually wrong. Instead, let the main loop invoke
4096 * dbus_connection_dispatch(). Popping messages manually is only
4097 * useful in very simple programs that don't share a #DBusConnection
4098 * with any libraries or other modules.
4100 * There is a lock that covers all ways of accessing the incoming message
4101 * queue, so dbus_connection_dispatch(), dbus_connection_pop_message(),
4102 * dbus_connection_borrow_message(), etc. will all block while one of the others
4103 * in the group is running.
4105 * @param connection the connection.
4106 * @returns next message in the incoming queue.
4109 dbus_connection_pop_message (DBusConnection *connection)
4111 DBusMessage *message;
4112 DBusDispatchStatus status;
4114 _dbus_verbose ("start\n");
4116 /* this is called for the side effect that it queues
4117 * up any messages from the transport
4119 status = dbus_connection_get_dispatch_status (connection);
4120 if (status != DBUS_DISPATCH_DATA_REMAINS)
4123 CONNECTION_LOCK (connection);
4124 _dbus_connection_acquire_dispatch (connection);
4125 HAVE_LOCK_CHECK (connection);
4127 message = _dbus_connection_pop_message_unlocked (connection);
4129 _dbus_verbose ("Returning popped message %p\n", message);
4131 _dbus_connection_release_dispatch (connection);
4133 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4134 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4140 * Acquire the dispatcher. This is a separate lock so the main
4141 * connection lock can be dropped to call out to application dispatch
4144 * @param connection the connection.
4147 _dbus_connection_acquire_dispatch (DBusConnection *connection)
4149 HAVE_LOCK_CHECK (connection);
4151 _dbus_connection_ref_unlocked (connection);
4152 CONNECTION_UNLOCK (connection);
4154 _dbus_verbose ("locking dispatch_mutex\n");
4155 _dbus_cmutex_lock (connection->dispatch_mutex);
4157 while (connection->dispatch_acquired)
4159 _dbus_verbose ("waiting for dispatch to be acquirable\n");
4160 _dbus_condvar_wait (connection->dispatch_cond,
4161 connection->dispatch_mutex);
4164 _dbus_assert (!connection->dispatch_acquired);
4166 connection->dispatch_acquired = TRUE;
4168 _dbus_verbose ("unlocking dispatch_mutex\n");
4169 _dbus_cmutex_unlock (connection->dispatch_mutex);
4171 CONNECTION_LOCK (connection);
4172 _dbus_connection_unref_unlocked (connection);
4176 * Release the dispatcher when you're done with it. Only call
4177 * after you've acquired the dispatcher. Wakes up at most one
4178 * thread currently waiting to acquire the dispatcher.
4180 * @param connection the connection.
4183 _dbus_connection_release_dispatch (DBusConnection *connection)
4185 HAVE_LOCK_CHECK (connection);
4187 _dbus_verbose ("locking dispatch_mutex\n");
4188 _dbus_cmutex_lock (connection->dispatch_mutex);
4190 _dbus_assert (connection->dispatch_acquired);
4192 connection->dispatch_acquired = FALSE;
4193 _dbus_condvar_wake_one (connection->dispatch_cond);
4195 _dbus_verbose ("unlocking dispatch_mutex\n");
4196 _dbus_cmutex_unlock (connection->dispatch_mutex);
4200 _dbus_connection_failed_pop (DBusConnection *connection,
4201 DBusList *message_link)
4203 _dbus_list_prepend_link (&connection->incoming_messages,
4205 connection->n_incoming += 1;
4208 /* Note this may be called multiple times since we don't track whether we already did it */
4210 notify_disconnected_unlocked (DBusConnection *connection)
4212 HAVE_LOCK_CHECK (connection);
4214 /* Set the weakref in dbus-bus.c to NULL, so nobody will get a disconnected
4215 * connection from dbus_bus_get(). We make the same guarantee for
4216 * dbus_connection_open() but in a different way since we don't want to
4217 * unref right here; we instead check for connectedness before returning
4218 * the connection from the hash.
4220 _dbus_bus_notify_shared_connection_disconnected_unlocked (connection);
4222 /* Dump the outgoing queue, we aren't going to be able to
4223 * send it now, and we'd like accessors like
4224 * dbus_connection_get_outgoing_size() to be accurate.
4226 if (connection->n_outgoing > 0)
4230 _dbus_verbose ("Dropping %d outgoing messages since we're disconnected\n",
4231 connection->n_outgoing);
4233 while ((link = _dbus_list_get_last_link (&connection->outgoing_messages)))
4235 _dbus_connection_message_sent_unlocked (connection, link->data);
4240 /* Note this may be called multiple times since we don't track whether we already did it */
4241 static DBusDispatchStatus
4242 notify_disconnected_and_dispatch_complete_unlocked (DBusConnection *connection)
4244 HAVE_LOCK_CHECK (connection);
4246 if (connection->disconnect_message_link != NULL)
4248 _dbus_verbose ("Sending disconnect message\n");
4250 /* If we have pending calls, queue their timeouts - we want the Disconnected
4251 * to be the last message, after these timeouts.
4253 connection_timeout_and_complete_all_pending_calls_unlocked (connection);
4255 /* We haven't sent the disconnect message already,
4256 * and all real messages have been queued up.
4258 _dbus_connection_queue_synthesized_message_link (connection,
4259 connection->disconnect_message_link);
4260 connection->disconnect_message_link = NULL;
4262 return DBUS_DISPATCH_DATA_REMAINS;
4265 return DBUS_DISPATCH_COMPLETE;
4268 static DBusDispatchStatus
4269 _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection)
4271 HAVE_LOCK_CHECK (connection);
4273 if (connection->n_incoming > 0)
4274 return DBUS_DISPATCH_DATA_REMAINS;
4275 else if (!_dbus_transport_queue_messages (connection->transport))
4276 return DBUS_DISPATCH_NEED_MEMORY;
4279 DBusDispatchStatus status;
4280 dbus_bool_t is_connected;
4282 status = _dbus_transport_get_dispatch_status (connection->transport);
4283 is_connected = _dbus_transport_get_is_connected (connection->transport);
4285 _dbus_verbose ("dispatch status = %s is_connected = %d\n",
4286 DISPATCH_STATUS_NAME (status), is_connected);
4290 /* It's possible this would be better done by having an explicit
4291 * notification from _dbus_transport_disconnect() that would
4292 * synchronously do this, instead of waiting for the next dispatch
4293 * status check. However, probably not good to change until it causes
4296 notify_disconnected_unlocked (connection);
4298 /* I'm not sure this is needed; the idea is that we want to
4299 * queue the Disconnected only after we've read all the
4300 * messages, but if we're disconnected maybe we are guaranteed
4301 * to have read them all ?
4303 if (status == DBUS_DISPATCH_COMPLETE)
4304 status = notify_disconnected_and_dispatch_complete_unlocked (connection);
4307 if (status != DBUS_DISPATCH_COMPLETE)
4309 else if (connection->n_incoming > 0)
4310 return DBUS_DISPATCH_DATA_REMAINS;
4312 return DBUS_DISPATCH_COMPLETE;
4317 _dbus_connection_update_dispatch_status_and_unlock (DBusConnection *connection,
4318 DBusDispatchStatus new_status)
4320 dbus_bool_t changed;
4321 DBusDispatchStatusFunction function;
4324 HAVE_LOCK_CHECK (connection);
4326 _dbus_connection_ref_unlocked (connection);
4328 changed = new_status != connection->last_dispatch_status;
4330 connection->last_dispatch_status = new_status;
4332 function = connection->dispatch_status_function;
4333 data = connection->dispatch_status_data;
4335 if (connection->disconnected_message_arrived &&
4336 !connection->disconnected_message_processed)
4338 connection->disconnected_message_processed = TRUE;
4340 /* this does an unref, but we have a ref
4341 * so we should not run the finalizer here
4344 connection_forget_shared_unlocked (connection);
4346 if (connection->exit_on_disconnect)
4348 CONNECTION_UNLOCK (connection);
4350 _dbus_verbose ("Exiting on Disconnected signal\n");
4352 _dbus_assert_not_reached ("Call to exit() returned");
4356 /* We drop the lock */
4357 CONNECTION_UNLOCK (connection);
4359 if (changed && function)
4361 _dbus_verbose ("Notifying of change to dispatch status of %p now %d (%s)\n",
4362 connection, new_status,
4363 DISPATCH_STATUS_NAME (new_status));
4364 (* function) (connection, new_status, data);
4367 dbus_connection_unref (connection);
4371 * Gets the current state of the incoming message queue.
4372 * #DBUS_DISPATCH_DATA_REMAINS indicates that the message queue
4373 * may contain messages. #DBUS_DISPATCH_COMPLETE indicates that the
4374 * incoming queue is empty. #DBUS_DISPATCH_NEED_MEMORY indicates that
4375 * there could be data, but we can't know for sure without more
4378 * To process the incoming message queue, use dbus_connection_dispatch()
4379 * or (in rare cases) dbus_connection_pop_message().
4381 * Note, #DBUS_DISPATCH_DATA_REMAINS really means that either we
4382 * have messages in the queue, or we have raw bytes buffered up
4383 * that need to be parsed. When these bytes are parsed, they
4384 * may not add up to an entire message. Thus, it's possible
4385 * to see a status of #DBUS_DISPATCH_DATA_REMAINS but not
4386 * have a message yet.
4388 * In particular this happens on initial connection, because all sorts
4389 * of authentication protocol stuff has to be parsed before the
4390 * first message arrives.
4392 * @param connection the connection.
4393 * @returns current dispatch status
4396 dbus_connection_get_dispatch_status (DBusConnection *connection)
4398 DBusDispatchStatus status;
4400 _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
4402 _dbus_verbose ("start\n");
4404 CONNECTION_LOCK (connection);
4406 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4408 CONNECTION_UNLOCK (connection);
4414 * Filter funtion for handling the Peer standard interface.
4416 static DBusHandlerResult
4417 _dbus_connection_peer_filter_unlocked_no_update (DBusConnection *connection,
4418 DBusMessage *message)
4420 dbus_bool_t sent = FALSE;
4421 DBusMessage *ret = NULL;
4422 DBusList *expire_link;
4424 if (connection->route_peer_messages && dbus_message_get_destination (message) != NULL)
4426 /* This means we're letting the bus route this message */
4427 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4430 if (!dbus_message_has_interface (message, DBUS_INTERFACE_PEER))
4432 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4435 /* Preallocate a linked-list link, so that if we need to dispose of a
4436 * message, we can attach it to the expired list */
4437 expire_link = _dbus_list_alloc_link (NULL);
4440 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4442 if (dbus_message_is_method_call (message,
4443 DBUS_INTERFACE_PEER,
4446 ret = dbus_message_new_method_return (message);
4450 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4452 else if (dbus_message_is_method_call (message,
4453 DBUS_INTERFACE_PEER,
4458 ret = dbus_message_new_method_return (message);
4462 _dbus_string_init (&uuid);
4463 if (_dbus_get_local_machine_uuid_encoded (&uuid))
4465 const char *v_STRING = _dbus_string_get_const_data (&uuid);
4466 if (dbus_message_append_args (ret,
4467 DBUS_TYPE_STRING, &v_STRING,
4470 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4473 _dbus_string_free (&uuid);
4477 /* We need to bounce anything else with this interface, otherwise apps
4478 * could start extending the interface and when we added extensions
4479 * here to DBusConnection we'd break those apps.
4481 ret = dbus_message_new_error (message,
4482 DBUS_ERROR_UNKNOWN_METHOD,
4483 "Unknown method invoked on org.freedesktop.DBus.Peer interface");
4487 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4493 _dbus_list_free_link (expire_link);
4497 /* It'll be safe to unref the reply when we unlock */
4498 expire_link->data = ret;
4499 _dbus_list_prepend_link (&connection->expired_messages, expire_link);
4503 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4505 return DBUS_HANDLER_RESULT_HANDLED;
4509 * Processes all builtin filter functions
4511 * If the spec specifies a standard interface
4512 * they should be processed from this method
4514 static DBusHandlerResult
4515 _dbus_connection_run_builtin_filters_unlocked_no_update (DBusConnection *connection,
4516 DBusMessage *message)
4518 /* We just run one filter for now but have the option to run more
4519 if the spec calls for it in the future */
4521 return _dbus_connection_peer_filter_unlocked_no_update (connection, message);
4525 * Processes any incoming data.
4527 * If there's incoming raw data that has not yet been parsed, it is
4528 * parsed, which may or may not result in adding messages to the
4531 * The incoming data buffer is filled when the connection reads from
4532 * its underlying transport (such as a socket). Reading usually
4533 * happens in dbus_watch_handle() or dbus_connection_read_write().
4535 * If there are complete messages in the incoming queue,
4536 * dbus_connection_dispatch() removes one message from the queue and
4537 * processes it. Processing has three steps.
4539 * First, any method replies are passed to #DBusPendingCall or
4540 * dbus_connection_send_with_reply_and_block() in order to
4541 * complete the pending method call.
4543 * Second, any filters registered with dbus_connection_add_filter()
4544 * are run. If any filter returns #DBUS_HANDLER_RESULT_HANDLED
4545 * then processing stops after that filter.
4547 * Third, if the message is a method call it is forwarded to
4548 * any registered object path handlers added with
4549 * dbus_connection_register_object_path() or
4550 * dbus_connection_register_fallback().
4552 * A single call to dbus_connection_dispatch() will process at most
4553 * one message; it will not clear the entire message queue.
4555 * Be careful about calling dbus_connection_dispatch() from inside a
4556 * message handler, i.e. calling dbus_connection_dispatch()
4557 * recursively. If threads have been initialized with a recursive
4558 * mutex function, then this will not deadlock; however, it can
4559 * certainly confuse your application.
4561 * @todo some FIXME in here about handling DBUS_HANDLER_RESULT_NEED_MEMORY
4563 * @param connection the connection
4564 * @returns dispatch status, see dbus_connection_get_dispatch_status()
4567 dbus_connection_dispatch (DBusConnection *connection)
4569 DBusMessage *message;
4570 DBusList *link, *filter_list_copy, *message_link;
4571 DBusHandlerResult result;
4572 DBusPendingCall *pending;
4573 dbus_int32_t reply_serial;
4574 DBusDispatchStatus status;
4575 dbus_bool_t found_object;
4577 _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
4579 _dbus_verbose ("\n");
4581 CONNECTION_LOCK (connection);
4582 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4583 if (status != DBUS_DISPATCH_DATA_REMAINS)
4585 /* unlocks and calls out to user code */
4586 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4590 /* We need to ref the connection since the callback could potentially
4591 * drop the last ref to it
4593 _dbus_connection_ref_unlocked (connection);
4595 _dbus_connection_acquire_dispatch (connection);
4596 HAVE_LOCK_CHECK (connection);
4598 message_link = _dbus_connection_pop_message_link_unlocked (connection);
4599 if (message_link == NULL)
4601 /* another thread dispatched our stuff */
4603 _dbus_verbose ("another thread dispatched message (during acquire_dispatch above)\n");
4605 _dbus_connection_release_dispatch (connection);
4607 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4609 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4611 dbus_connection_unref (connection);
4616 message = message_link->data;
4618 _dbus_verbose (" dispatching message %p (%s %s %s '%s')\n",
4620 dbus_message_type_to_string (dbus_message_get_type (message)),
4621 dbus_message_get_interface (message) ?
4622 dbus_message_get_interface (message) :
4624 dbus_message_get_member (message) ?
4625 dbus_message_get_member (message) :
4627 dbus_message_get_signature (message));
4629 result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4631 /* Pending call handling must be first, because if you do
4632 * dbus_connection_send_with_reply_and_block() or
4633 * dbus_pending_call_block() then no handlers/filters will be run on
4634 * the reply. We want consistent semantics in the case where we
4635 * dbus_connection_dispatch() the reply.
4638 reply_serial = dbus_message_get_reply_serial (message);
4639 pending = _dbus_hash_table_lookup_int (connection->pending_replies,
4643 _dbus_verbose ("Dispatching a pending reply\n");
4644 complete_pending_call_and_unlock (connection, pending, message);
4645 pending = NULL; /* it's probably unref'd */
4647 CONNECTION_LOCK (connection);
4648 _dbus_verbose ("pending call completed in dispatch\n");
4649 result = DBUS_HANDLER_RESULT_HANDLED;
4653 result = _dbus_connection_run_builtin_filters_unlocked_no_update (connection, message);
4654 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4657 if (!_dbus_list_copy (&connection->filter_list, &filter_list_copy))
4659 _dbus_connection_release_dispatch (connection);
4660 HAVE_LOCK_CHECK (connection);
4662 _dbus_connection_failed_pop (connection, message_link);
4664 /* unlocks and calls user code */
4665 _dbus_connection_update_dispatch_status_and_unlock (connection,
4666 DBUS_DISPATCH_NEED_MEMORY);
4667 dbus_connection_unref (connection);
4669 return DBUS_DISPATCH_NEED_MEMORY;
4672 _dbus_list_foreach (&filter_list_copy,
4673 (DBusForeachFunction)_dbus_message_filter_ref,
4676 /* We're still protected from dispatch() reentrancy here
4677 * since we acquired the dispatcher
4679 CONNECTION_UNLOCK (connection);
4681 link = _dbus_list_get_first_link (&filter_list_copy);
4682 while (link != NULL)
4684 DBusMessageFilter *filter = link->data;
4685 DBusList *next = _dbus_list_get_next_link (&filter_list_copy, link);
4687 if (filter->function == NULL)
4689 _dbus_verbose (" filter was removed in a callback function\n");
4694 _dbus_verbose (" running filter on message %p\n", message);
4695 result = (* filter->function) (connection, message, filter->user_data);
4697 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4703 _dbus_list_foreach (&filter_list_copy,
4704 (DBusForeachFunction)_dbus_message_filter_unref,
4706 _dbus_list_clear (&filter_list_copy);
4708 CONNECTION_LOCK (connection);
4710 if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
4712 _dbus_verbose ("No memory\n");
4715 else if (result == DBUS_HANDLER_RESULT_HANDLED)
4717 _dbus_verbose ("filter handled message in dispatch\n");
4721 /* We're still protected from dispatch() reentrancy here
4722 * since we acquired the dispatcher
4724 _dbus_verbose (" running object path dispatch on message %p (%s %s %s '%s')\n",
4726 dbus_message_type_to_string (dbus_message_get_type (message)),
4727 dbus_message_get_interface (message) ?
4728 dbus_message_get_interface (message) :
4730 dbus_message_get_member (message) ?
4731 dbus_message_get_member (message) :
4733 dbus_message_get_signature (message));
4735 HAVE_LOCK_CHECK (connection);
4736 result = _dbus_object_tree_dispatch_and_unlock (connection->objects,
4740 CONNECTION_LOCK (connection);
4742 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4744 _dbus_verbose ("object tree handled message in dispatch\n");
4748 if (dbus_message_get_type (message) == DBUS_MESSAGE_TYPE_METHOD_CALL)
4752 DBusPreallocatedSend *preallocated;
4753 DBusList *expire_link;
4755 _dbus_verbose (" sending error %s\n",
4756 DBUS_ERROR_UNKNOWN_METHOD);
4758 if (!_dbus_string_init (&str))
4760 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4761 _dbus_verbose ("no memory for error string in dispatch\n");
4765 if (!_dbus_string_append_printf (&str,
4766 "Method \"%s\" with signature \"%s\" on interface \"%s\" doesn't exist\n",
4767 dbus_message_get_member (message),
4768 dbus_message_get_signature (message),
4769 dbus_message_get_interface (message)))
4771 _dbus_string_free (&str);
4772 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4773 _dbus_verbose ("no memory for error string in dispatch\n");
4777 reply = dbus_message_new_error (message,
4778 found_object ? DBUS_ERROR_UNKNOWN_METHOD : DBUS_ERROR_UNKNOWN_OBJECT,
4779 _dbus_string_get_const_data (&str));
4780 _dbus_string_free (&str);
4784 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4785 _dbus_verbose ("no memory for error reply in dispatch\n");
4789 expire_link = _dbus_list_alloc_link (reply);
4791 if (expire_link == NULL)
4793 dbus_message_unref (reply);
4794 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4795 _dbus_verbose ("no memory for error send in dispatch\n");
4799 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
4801 if (preallocated == NULL)
4803 _dbus_list_free_link (expire_link);
4804 /* It's OK that this is finalized, because it hasn't been seen by
4805 * anything that could attach user callbacks */
4806 dbus_message_unref (reply);
4807 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4808 _dbus_verbose ("no memory for error send in dispatch\n");
4812 _dbus_connection_send_preallocated_unlocked_no_update (connection, preallocated,
4814 /* reply will be freed when we release the lock */
4815 _dbus_list_prepend_link (&connection->expired_messages, expire_link);
4817 result = DBUS_HANDLER_RESULT_HANDLED;
4820 _dbus_verbose (" done dispatching %p (%s %s %s '%s') on connection %p\n", message,
4821 dbus_message_type_to_string (dbus_message_get_type (message)),
4822 dbus_message_get_interface (message) ?
4823 dbus_message_get_interface (message) :
4825 dbus_message_get_member (message) ?
4826 dbus_message_get_member (message) :
4828 dbus_message_get_signature (message),
4832 if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
4834 _dbus_verbose ("out of memory\n");
4836 /* Put message back, and we'll start over.
4837 * Yes this means handlers must be idempotent if they
4838 * don't return HANDLED; c'est la vie.
4840 _dbus_connection_putback_message_link_unlocked (connection,
4842 /* now we don't want to free them */
4843 message_link = NULL;
4848 _dbus_verbose (" ... done dispatching\n");
4851 _dbus_connection_release_dispatch (connection);
4852 HAVE_LOCK_CHECK (connection);
4854 if (message != NULL)
4856 /* We don't want this message to count in maximum message limits when
4857 * computing the dispatch status, below. We have to drop the lock
4858 * temporarily, because finalizing a message can trigger callbacks.
4860 * We have a reference to the connection, and we don't use any cached
4861 * pointers to the connection's internals below this point, so it should
4862 * be safe to drop the lock and take it back. */
4863 CONNECTION_UNLOCK (connection);
4864 dbus_message_unref (message);
4865 CONNECTION_LOCK (connection);
4868 if (message_link != NULL)
4869 _dbus_list_free_link (message_link);
4871 _dbus_verbose ("before final status update\n");
4872 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4874 /* unlocks and calls user code */
4875 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4877 dbus_connection_unref (connection);
4883 * Sets the watch functions for the connection. These functions are
4884 * responsible for making the application's main loop aware of file
4885 * descriptors that need to be monitored for events, using select() or
4886 * poll(). When using Qt, typically the DBusAddWatchFunction would
4887 * create a QSocketNotifier. When using GLib, the DBusAddWatchFunction
4888 * could call g_io_add_watch(), or could be used as part of a more
4889 * elaborate GSource. Note that when a watch is added, it may
4892 * The DBusWatchToggledFunction notifies the application that the
4893 * watch has been enabled or disabled. Call dbus_watch_get_enabled()
4894 * to check this. A disabled watch should have no effect, and enabled
4895 * watch should be added to the main loop. This feature is used
4896 * instead of simply adding/removing the watch because
4897 * enabling/disabling can be done without memory allocation. The
4898 * toggled function may be NULL if a main loop re-queries
4899 * dbus_watch_get_enabled() every time anyway.
4901 * The DBusWatch can be queried for the file descriptor to watch using
4902 * dbus_watch_get_unix_fd() or dbus_watch_get_socket(), and for the
4903 * events to watch for using dbus_watch_get_flags(). The flags
4904 * returned by dbus_watch_get_flags() will only contain
4905 * DBUS_WATCH_READABLE and DBUS_WATCH_WRITABLE, never
4906 * DBUS_WATCH_HANGUP or DBUS_WATCH_ERROR; all watches implicitly
4907 * include a watch for hangups, errors, and other exceptional
4910 * Once a file descriptor becomes readable or writable, or an exception
4911 * occurs, dbus_watch_handle() should be called to
4912 * notify the connection of the file descriptor's condition.
4914 * dbus_watch_handle() cannot be called during the
4915 * DBusAddWatchFunction, as the connection will not be ready to handle
4918 * It is not allowed to reference a DBusWatch after it has been passed
4919 * to remove_function.
4921 * If #FALSE is returned due to lack of memory, the failure may be due
4922 * to a #FALSE return from the new add_function. If so, the
4923 * add_function may have been called successfully one or more times,
4924 * but the remove_function will also have been called to remove any
4925 * successful adds. i.e. if #FALSE is returned the net result
4926 * should be that dbus_connection_set_watch_functions() has no effect,
4927 * but the add_function and remove_function may have been called.
4929 * @note The thread lock on DBusConnection is held while
4930 * watch functions are invoked, so inside these functions you
4931 * may not invoke any methods on DBusConnection or it will deadlock.
4932 * See the comments in the code or http://lists.freedesktop.org/archives/dbus/2007-July/tread.html#8144
4933 * if you encounter this issue and want to attempt writing a patch.
4935 * @param connection the connection.
4936 * @param add_function function to begin monitoring a new descriptor.
4937 * @param remove_function function to stop monitoring a descriptor.
4938 * @param toggled_function function to notify of enable/disable
4939 * @param data data to pass to add_function and remove_function.
4940 * @param free_data_function function to be called to free the data.
4941 * @returns #FALSE on failure (no memory)
4944 dbus_connection_set_watch_functions (DBusConnection *connection,
4945 DBusAddWatchFunction add_function,
4946 DBusRemoveWatchFunction remove_function,
4947 DBusWatchToggledFunction toggled_function,
4949 DBusFreeFunction free_data_function)
4953 _dbus_return_val_if_fail (connection != NULL, FALSE);
4955 CONNECTION_LOCK (connection);
4957 retval = _dbus_watch_list_set_functions (connection->watches,
4958 add_function, remove_function,
4960 data, free_data_function);
4962 CONNECTION_UNLOCK (connection);
4968 * Sets the timeout functions for the connection. These functions are
4969 * responsible for making the application's main loop aware of timeouts.
4970 * When using Qt, typically the DBusAddTimeoutFunction would create a
4971 * QTimer. When using GLib, the DBusAddTimeoutFunction would call
4974 * The DBusTimeoutToggledFunction notifies the application that the
4975 * timeout has been enabled or disabled. Call
4976 * dbus_timeout_get_enabled() to check this. A disabled timeout should
4977 * have no effect, and enabled timeout should be added to the main
4978 * loop. This feature is used instead of simply adding/removing the
4979 * timeout because enabling/disabling can be done without memory
4980 * allocation. With Qt, QTimer::start() and QTimer::stop() can be used
4981 * to enable and disable. The toggled function may be NULL if a main
4982 * loop re-queries dbus_timeout_get_enabled() every time anyway.
4983 * Whenever a timeout is toggled, its interval may change.
4985 * The DBusTimeout can be queried for the timer interval using
4986 * dbus_timeout_get_interval(). dbus_timeout_handle() should be called
4987 * repeatedly, each time the interval elapses, starting after it has
4988 * elapsed once. The timeout stops firing when it is removed with the
4989 * given remove_function. The timer interval may change whenever the
4990 * timeout is added, removed, or toggled.
4992 * @note The thread lock on DBusConnection is held while
4993 * timeout functions are invoked, so inside these functions you
4994 * may not invoke any methods on DBusConnection or it will deadlock.
4995 * See the comments in the code or http://lists.freedesktop.org/archives/dbus/2007-July/thread.html#8144
4996 * if you encounter this issue and want to attempt writing a patch.
4998 * @param connection the connection.
4999 * @param add_function function to add a timeout.
5000 * @param remove_function function to remove a timeout.
5001 * @param toggled_function function to notify of enable/disable
5002 * @param data data to pass to add_function and remove_function.
5003 * @param free_data_function function to be called to free the data.
5004 * @returns #FALSE on failure (no memory)
5007 dbus_connection_set_timeout_functions (DBusConnection *connection,
5008 DBusAddTimeoutFunction add_function,
5009 DBusRemoveTimeoutFunction remove_function,
5010 DBusTimeoutToggledFunction toggled_function,
5012 DBusFreeFunction free_data_function)
5016 _dbus_return_val_if_fail (connection != NULL, FALSE);
5018 CONNECTION_LOCK (connection);
5020 retval = _dbus_timeout_list_set_functions (connection->timeouts,
5021 add_function, remove_function,
5023 data, free_data_function);
5025 CONNECTION_UNLOCK (connection);
5031 * Sets the mainloop wakeup function for the connection. This function
5032 * is responsible for waking up the main loop (if its sleeping in
5033 * another thread) when some some change has happened to the
5034 * connection that the mainloop needs to reconsider (e.g. a message
5035 * has been queued for writing). When using Qt, this typically
5036 * results in a call to QEventLoop::wakeUp(). When using GLib, it
5037 * would call g_main_context_wakeup().
5039 * @param connection the connection.
5040 * @param wakeup_main_function function to wake up the mainloop
5041 * @param data data to pass wakeup_main_function
5042 * @param free_data_function function to be called to free the data.
5045 dbus_connection_set_wakeup_main_function (DBusConnection *connection,
5046 DBusWakeupMainFunction wakeup_main_function,
5048 DBusFreeFunction free_data_function)
5051 DBusFreeFunction old_free_data;
5053 _dbus_return_if_fail (connection != NULL);
5055 CONNECTION_LOCK (connection);
5056 old_data = connection->wakeup_main_data;
5057 old_free_data = connection->free_wakeup_main_data;
5059 connection->wakeup_main_function = wakeup_main_function;
5060 connection->wakeup_main_data = data;
5061 connection->free_wakeup_main_data = free_data_function;
5063 CONNECTION_UNLOCK (connection);
5065 /* Callback outside the lock */
5067 (*old_free_data) (old_data);
5071 * Set a function to be invoked when the dispatch status changes.
5072 * If the dispatch status is #DBUS_DISPATCH_DATA_REMAINS, then
5073 * dbus_connection_dispatch() needs to be called to process incoming
5074 * messages. However, dbus_connection_dispatch() MUST NOT BE CALLED
5075 * from inside the DBusDispatchStatusFunction. Indeed, almost
5076 * any reentrancy in this function is a bad idea. Instead,
5077 * the DBusDispatchStatusFunction should simply save an indication
5078 * that messages should be dispatched later, when the main loop
5081 * If you don't set a dispatch status function, you have to be sure to
5082 * dispatch on every iteration of your main loop, especially if
5083 * dbus_watch_handle() or dbus_timeout_handle() were called.
5085 * @param connection the connection
5086 * @param function function to call on dispatch status changes
5087 * @param data data for function
5088 * @param free_data_function free the function data
5091 dbus_connection_set_dispatch_status_function (DBusConnection *connection,
5092 DBusDispatchStatusFunction function,
5094 DBusFreeFunction free_data_function)
5097 DBusFreeFunction old_free_data;
5099 _dbus_return_if_fail (connection != NULL);
5101 CONNECTION_LOCK (connection);
5102 old_data = connection->dispatch_status_data;
5103 old_free_data = connection->free_dispatch_status_data;
5105 connection->dispatch_status_function = function;
5106 connection->dispatch_status_data = data;
5107 connection->free_dispatch_status_data = free_data_function;
5109 CONNECTION_UNLOCK (connection);
5111 /* Callback outside the lock */
5113 (*old_free_data) (old_data);
5117 * Get the UNIX file descriptor of the connection, if any. This can
5118 * be used for SELinux access control checks with getpeercon() for
5119 * example. DO NOT read or write to the file descriptor, or try to
5120 * select() on it; use DBusWatch for main loop integration. Not all
5121 * connections will have a file descriptor. So for adding descriptors
5122 * to the main loop, use dbus_watch_get_unix_fd() and so forth.
5124 * If the connection is socket-based, you can also use
5125 * dbus_connection_get_socket(), which will work on Windows too.
5126 * This function always fails on Windows.
5128 * Right now the returned descriptor is always a socket, but
5129 * that is not guaranteed.
5131 * @param connection the connection
5132 * @param fd return location for the file descriptor.
5133 * @returns #TRUE if fd is successfully obtained.
5136 dbus_connection_get_unix_fd (DBusConnection *connection,
5139 _dbus_return_val_if_fail (connection != NULL, FALSE);
5140 _dbus_return_val_if_fail (connection->transport != NULL, FALSE);
5143 /* FIXME do this on a lower level */
5147 return dbus_connection_get_socket(connection, fd);
5151 * Gets the underlying Windows or UNIX socket file descriptor
5152 * of the connection, if any. DO NOT read or write to the file descriptor, or try to
5153 * select() on it; use DBusWatch for main loop integration. Not all
5154 * connections will have a socket. So for adding descriptors
5155 * to the main loop, use dbus_watch_get_socket() and so forth.
5157 * If the connection is not socket-based, this function will return FALSE,
5158 * even if the connection does have a file descriptor of some kind.
5159 * i.e. this function always returns specifically a socket file descriptor.
5161 * @param connection the connection
5162 * @param fd return location for the file descriptor.
5163 * @returns #TRUE if fd is successfully obtained.
5166 dbus_connection_get_socket(DBusConnection *connection,
5171 _dbus_return_val_if_fail (connection != NULL, FALSE);
5172 _dbus_return_val_if_fail (connection->transport != NULL, FALSE);
5174 CONNECTION_LOCK (connection);
5176 retval = _dbus_transport_get_socket_fd (connection->transport,
5179 CONNECTION_UNLOCK (connection);
5186 * Gets the UNIX user ID of the connection if known. Returns #TRUE if
5187 * the uid is filled in. Always returns #FALSE on non-UNIX platforms
5188 * for now, though in theory someone could hook Windows to NIS or
5189 * something. Always returns #FALSE prior to authenticating the
5192 * The UID is only read by servers from clients; clients can't usually
5193 * get the UID of servers, because servers do not authenticate to
5194 * clients. The returned UID is the UID the connection authenticated
5197 * The message bus is a server and the apps connecting to the bus
5200 * You can ask the bus to tell you the UID of another connection though
5201 * if you like; this is done with dbus_bus_get_unix_user().
5203 * @param connection the connection
5204 * @param uid return location for the user ID
5205 * @returns #TRUE if uid is filled in with a valid user ID
5208 dbus_connection_get_unix_user (DBusConnection *connection,
5213 _dbus_return_val_if_fail (connection != NULL, FALSE);
5214 _dbus_return_val_if_fail (uid != NULL, FALSE);
5216 CONNECTION_LOCK (connection);
5218 if (!_dbus_transport_try_to_authenticate (connection->transport))
5221 result = _dbus_transport_get_unix_user (connection->transport,
5225 _dbus_assert (!result);
5228 CONNECTION_UNLOCK (connection);
5234 * Gets the process ID of the connection if any.
5235 * Returns #TRUE if the pid is filled in.
5236 * Always returns #FALSE prior to authenticating the
5239 * @param connection the connection
5240 * @param pid return location for the process ID
5241 * @returns #TRUE if uid is filled in with a valid process ID
5244 dbus_connection_get_unix_process_id (DBusConnection *connection,
5249 _dbus_return_val_if_fail (connection != NULL, FALSE);
5250 _dbus_return_val_if_fail (pid != NULL, FALSE);
5252 CONNECTION_LOCK (connection);
5254 if (!_dbus_transport_try_to_authenticate (connection->transport))
5257 result = _dbus_transport_get_unix_process_id (connection->transport,
5260 CONNECTION_UNLOCK (connection);
5266 * Gets the ADT audit data of the connection if any.
5267 * Returns #TRUE if the structure pointer is returned.
5268 * Always returns #FALSE prior to authenticating the
5271 * @param connection the connection
5272 * @param data return location for audit data
5273 * @param data_size return location for length of audit data
5274 * @returns #TRUE if audit data is filled in with a valid ucred pointer
5277 dbus_connection_get_adt_audit_session_data (DBusConnection *connection,
5279 dbus_int32_t *data_size)
5283 _dbus_return_val_if_fail (connection != NULL, FALSE);
5284 _dbus_return_val_if_fail (data != NULL, FALSE);
5285 _dbus_return_val_if_fail (data_size != NULL, FALSE);
5287 CONNECTION_LOCK (connection);
5289 if (!_dbus_transport_try_to_authenticate (connection->transport))
5292 result = _dbus_transport_get_adt_audit_session_data (connection->transport,
5295 CONNECTION_UNLOCK (connection);
5301 * Sets a predicate function used to determine whether a given user ID
5302 * is allowed to connect. When an incoming connection has
5303 * authenticated with a particular user ID, this function is called;
5304 * if it returns #TRUE, the connection is allowed to proceed,
5305 * otherwise the connection is disconnected.
5307 * If the function is set to #NULL (as it is by default), then
5308 * only the same UID as the server process will be allowed to
5309 * connect. Also, root is always allowed to connect.
5311 * On Windows, the function will be set and its free_data_function will
5312 * be invoked when the connection is freed or a new function is set.
5313 * However, the function will never be called, because there are
5314 * no UNIX user ids to pass to it, or at least none of the existing
5315 * auth protocols would allow authenticating as a UNIX user on Windows.
5317 * @param connection the connection
5318 * @param function the predicate
5319 * @param data data to pass to the predicate
5320 * @param free_data_function function to free the data
5323 dbus_connection_set_unix_user_function (DBusConnection *connection,
5324 DBusAllowUnixUserFunction function,
5326 DBusFreeFunction free_data_function)
5328 void *old_data = NULL;
5329 DBusFreeFunction old_free_function = NULL;
5331 _dbus_return_if_fail (connection != NULL);
5333 CONNECTION_LOCK (connection);
5334 _dbus_transport_set_unix_user_function (connection->transport,
5335 function, data, free_data_function,
5336 &old_data, &old_free_function);
5337 CONNECTION_UNLOCK (connection);
5339 if (old_free_function != NULL)
5340 (* old_free_function) (old_data);
5344 * Gets the Windows user SID of the connection if known. Returns
5345 * #TRUE if the ID is filled in. Always returns #FALSE on non-Windows
5346 * platforms for now, though in theory someone could hook UNIX to
5347 * Active Directory or something. Always returns #FALSE prior to
5348 * authenticating the connection.
5350 * The user is only read by servers from clients; clients can't usually
5351 * get the user of servers, because servers do not authenticate to
5352 * clients. The returned user is the user the connection authenticated
5355 * The message bus is a server and the apps connecting to the bus
5358 * The returned user string has to be freed with dbus_free().
5360 * The return value indicates whether the user SID is available;
5361 * if it's available but we don't have the memory to copy it,
5362 * then the return value is #TRUE and #NULL is given as the SID.
5364 * @todo We would like to be able to say "You can ask the bus to tell
5365 * you the user of another connection though if you like; this is done
5366 * with dbus_bus_get_windows_user()." But this has to be implemented
5367 * in bus/driver.c and dbus/dbus-bus.c, and is pointless anyway
5368 * since on Windows we only use the session bus for now.
5370 * @param connection the connection
5371 * @param windows_sid_p return location for an allocated copy of the user ID, or #NULL if no memory
5372 * @returns #TRUE if user is available (returned value may be #NULL anyway if no memory)
5375 dbus_connection_get_windows_user (DBusConnection *connection,
5376 char **windows_sid_p)
5380 _dbus_return_val_if_fail (connection != NULL, FALSE);
5381 _dbus_return_val_if_fail (windows_sid_p != NULL, FALSE);
5383 CONNECTION_LOCK (connection);
5385 if (!_dbus_transport_try_to_authenticate (connection->transport))
5388 result = _dbus_transport_get_windows_user (connection->transport,
5392 _dbus_assert (!result);
5395 CONNECTION_UNLOCK (connection);
5401 * Sets a predicate function used to determine whether a given user ID
5402 * is allowed to connect. When an incoming connection has
5403 * authenticated with a particular user ID, this function is called;
5404 * if it returns #TRUE, the connection is allowed to proceed,
5405 * otherwise the connection is disconnected.
5407 * If the function is set to #NULL (as it is by default), then
5408 * only the same user owning the server process will be allowed to
5411 * On UNIX, the function will be set and its free_data_function will
5412 * be invoked when the connection is freed or a new function is set.
5413 * However, the function will never be called, because there is no
5414 * way right now to authenticate as a Windows user on UNIX.
5416 * @param connection the connection
5417 * @param function the predicate
5418 * @param data data to pass to the predicate
5419 * @param free_data_function function to free the data
5422 dbus_connection_set_windows_user_function (DBusConnection *connection,
5423 DBusAllowWindowsUserFunction function,
5425 DBusFreeFunction free_data_function)
5427 void *old_data = NULL;
5428 DBusFreeFunction old_free_function = NULL;
5430 _dbus_return_if_fail (connection != NULL);
5432 CONNECTION_LOCK (connection);
5433 _dbus_transport_set_windows_user_function (connection->transport,
5434 function, data, free_data_function,
5435 &old_data, &old_free_function);
5436 CONNECTION_UNLOCK (connection);
5438 if (old_free_function != NULL)
5439 (* old_free_function) (old_data);
5443 * This function must be called on the server side of a connection when the
5444 * connection is first seen in the #DBusNewConnectionFunction. If set to
5445 * #TRUE (the default is #FALSE), then the connection can proceed even if
5446 * the client does not authenticate as some user identity, i.e. clients
5447 * can connect anonymously.
5449 * This setting interacts with the available authorization mechanisms
5450 * (see dbus_server_set_auth_mechanisms()). Namely, an auth mechanism
5451 * such as ANONYMOUS that supports anonymous auth must be included in
5452 * the list of available mechanisms for anonymous login to work.
5454 * This setting also changes the default rule for connections
5455 * authorized as a user; normally, if a connection authorizes as
5456 * a user identity, it is permitted if the user identity is
5457 * root or the user identity matches the user identity of the server
5458 * process. If anonymous connections are allowed, however,
5459 * then any user identity is allowed.
5461 * You can override the rules for connections authorized as a
5462 * user identity with dbus_connection_set_unix_user_function()
5463 * and dbus_connection_set_windows_user_function().
5465 * @param connection the connection
5466 * @param value whether to allow authentication as an anonymous user
5469 dbus_connection_set_allow_anonymous (DBusConnection *connection,
5472 _dbus_return_if_fail (connection != NULL);
5474 CONNECTION_LOCK (connection);
5475 _dbus_transport_set_allow_anonymous (connection->transport, value);
5476 CONNECTION_UNLOCK (connection);
5481 * Normally #DBusConnection automatically handles all messages to the
5482 * org.freedesktop.DBus.Peer interface. However, the message bus wants
5483 * to be able to route methods on that interface through the bus and
5484 * to other applications. If routing peer messages is enabled, then
5485 * messages with the org.freedesktop.DBus.Peer interface that also
5486 * have a bus destination name set will not be automatically
5487 * handled by the #DBusConnection and instead will be dispatched
5488 * normally to the application.
5490 * If a normal application sets this flag, it can break things badly.
5491 * So don't set this unless you are the message bus.
5493 * @param connection the connection
5494 * @param value #TRUE to pass through org.freedesktop.DBus.Peer messages with a bus name set
5497 dbus_connection_set_route_peer_messages (DBusConnection *connection,
5500 _dbus_return_if_fail (connection != NULL);
5502 CONNECTION_LOCK (connection);
5503 connection->route_peer_messages = TRUE;
5504 CONNECTION_UNLOCK (connection);
5508 * Adds a message filter. Filters are handlers that are run on all
5509 * incoming messages, prior to the objects registered with
5510 * dbus_connection_register_object_path(). Filters are run in the
5511 * order that they were added. The same handler can be added as a
5512 * filter more than once, in which case it will be run more than once.
5513 * Filters added during a filter callback won't be run on the message
5516 * @todo we don't run filters on messages while blocking without
5517 * entering the main loop, since filters are run as part of
5518 * dbus_connection_dispatch(). This is probably a feature, as filters
5519 * could create arbitrary reentrancy. But kind of sucks if you're
5520 * trying to filter METHOD_RETURN for some reason.
5522 * @param connection the connection
5523 * @param function function to handle messages
5524 * @param user_data user data to pass to the function
5525 * @param free_data_function function to use for freeing user data
5526 * @returns #TRUE on success, #FALSE if not enough memory.
5529 dbus_connection_add_filter (DBusConnection *connection,
5530 DBusHandleMessageFunction function,
5532 DBusFreeFunction free_data_function)
5534 DBusMessageFilter *filter;
5536 _dbus_return_val_if_fail (connection != NULL, FALSE);
5537 _dbus_return_val_if_fail (function != NULL, FALSE);
5539 filter = dbus_new0 (DBusMessageFilter, 1);
5543 _dbus_atomic_inc (&filter->refcount);
5545 CONNECTION_LOCK (connection);
5547 if (!_dbus_list_append (&connection->filter_list,
5550 _dbus_message_filter_unref (filter);
5551 CONNECTION_UNLOCK (connection);
5555 /* Fill in filter after all memory allocated,
5556 * so we don't run the free_user_data_function
5557 * if the add_filter() fails
5560 filter->function = function;
5561 filter->user_data = user_data;
5562 filter->free_user_data_function = free_data_function;
5564 CONNECTION_UNLOCK (connection);
5569 * Removes a previously-added message filter. It is a programming
5570 * error to call this function for a handler that has not been added
5571 * as a filter. If the given handler was added more than once, only
5572 * one instance of it will be removed (the most recently-added
5575 * @param connection the connection
5576 * @param function the handler to remove
5577 * @param user_data user data for the handler to remove
5581 dbus_connection_remove_filter (DBusConnection *connection,
5582 DBusHandleMessageFunction function,
5586 DBusMessageFilter *filter;
5588 _dbus_return_if_fail (connection != NULL);
5589 _dbus_return_if_fail (function != NULL);
5591 CONNECTION_LOCK (connection);
5595 link = _dbus_list_get_last_link (&connection->filter_list);
5596 while (link != NULL)
5598 filter = link->data;
5600 if (filter->function == function &&
5601 filter->user_data == user_data)
5603 _dbus_list_remove_link (&connection->filter_list, link);
5604 filter->function = NULL;
5609 link = _dbus_list_get_prev_link (&connection->filter_list, link);
5613 CONNECTION_UNLOCK (connection);
5615 #ifndef DBUS_DISABLE_CHECKS
5618 _dbus_warn_check_failed ("Attempt to remove filter function %p user data %p, but no such filter has been added\n",
5619 function, user_data);
5624 /* Call application code */
5625 if (filter->free_user_data_function)
5626 (* filter->free_user_data_function) (filter->user_data);
5628 filter->free_user_data_function = NULL;
5629 filter->user_data = NULL;
5631 _dbus_message_filter_unref (filter);
5635 * Registers a handler for a given path or subsection in the object
5636 * hierarchy. The given vtable handles messages sent to exactly the
5637 * given path or also for paths bellow that, depending on fallback
5640 * @param connection the connection
5641 * @param fallback whether to handle messages also for "subdirectory"
5642 * @param path a '/' delimited string of path elements
5643 * @param vtable the virtual table
5644 * @param user_data data to pass to functions in the vtable
5645 * @param error address where an error can be returned
5646 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5647 * #DBUS_ERROR_OBJECT_PATH_IN_USE) is reported
5650 _dbus_connection_register_object_path (DBusConnection *connection,
5651 dbus_bool_t fallback,
5653 const DBusObjectPathVTable *vtable,
5657 char **decomposed_path;
5660 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5663 CONNECTION_LOCK (connection);
5665 retval = _dbus_object_tree_register (connection->objects,
5667 (const char **) decomposed_path, vtable,
5670 CONNECTION_UNLOCK (connection);
5672 dbus_free_string_array (decomposed_path);
5678 * Registers a handler for a given path in the object hierarchy.
5679 * The given vtable handles messages sent to exactly the given path.
5681 * @param connection the connection
5682 * @param path a '/' delimited string of path elements
5683 * @param vtable the virtual table
5684 * @param user_data data to pass to functions in the vtable
5685 * @param error address where an error can be returned
5686 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5687 * #DBUS_ERROR_OBJECT_PATH_IN_USE) is reported
5690 dbus_connection_try_register_object_path (DBusConnection *connection,
5692 const DBusObjectPathVTable *vtable,
5696 _dbus_return_val_if_fail (connection != NULL, FALSE);
5697 _dbus_return_val_if_fail (path != NULL, FALSE);
5698 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5699 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5701 return _dbus_connection_register_object_path (connection, FALSE, path, vtable, user_data, error);
5705 * Registers a handler for a given path in the object hierarchy.
5706 * The given vtable handles messages sent to exactly the given path.
5708 * It is a bug to call this function for object paths which already
5709 * have a handler. Use dbus_connection_try_register_object_path() if this
5710 * might be the case.
5712 * @param connection the connection
5713 * @param path a '/' delimited string of path elements
5714 * @param vtable the virtual table
5715 * @param user_data data to pass to functions in the vtable
5716 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5717 * #DBUS_ERROR_OBJECT_PATH_IN_USE) ocurred
5720 dbus_connection_register_object_path (DBusConnection *connection,
5722 const DBusObjectPathVTable *vtable,
5726 DBusError error = DBUS_ERROR_INIT;
5728 _dbus_return_val_if_fail (connection != NULL, FALSE);
5729 _dbus_return_val_if_fail (path != NULL, FALSE);
5730 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5731 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5733 retval = _dbus_connection_register_object_path (connection, FALSE, path, vtable, user_data, &error);
5735 if (dbus_error_has_name (&error, DBUS_ERROR_OBJECT_PATH_IN_USE))
5737 _dbus_warn ("%s\n", error.message);
5738 dbus_error_free (&error);
5746 * Registers a fallback handler for a given subsection of the object
5747 * hierarchy. The given vtable handles messages at or below the given
5748 * path. You can use this to establish a default message handling
5749 * policy for a whole "subdirectory."
5751 * @param connection the connection
5752 * @param path a '/' delimited string of path elements
5753 * @param vtable the virtual table
5754 * @param user_data data to pass to functions in the vtable
5755 * @param error address where an error can be returned
5756 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5757 * #DBUS_ERROR_OBJECT_PATH_IN_USE) is reported
5760 dbus_connection_try_register_fallback (DBusConnection *connection,
5762 const DBusObjectPathVTable *vtable,
5766 _dbus_return_val_if_fail (connection != NULL, FALSE);
5767 _dbus_return_val_if_fail (path != NULL, FALSE);
5768 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5769 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5771 return _dbus_connection_register_object_path (connection, TRUE, path, vtable, user_data, error);
5775 * Registers a fallback handler for a given subsection of the object
5776 * hierarchy. The given vtable handles messages at or below the given
5777 * path. You can use this to establish a default message handling
5778 * policy for a whole "subdirectory."
5780 * It is a bug to call this function for object paths which already
5781 * have a handler. Use dbus_connection_try_register_fallback() if this
5782 * might be the case.
5784 * @param connection the connection
5785 * @param path a '/' delimited string of path elements
5786 * @param vtable the virtual table
5787 * @param user_data data to pass to functions in the vtable
5788 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5789 * #DBUS_ERROR_OBJECT_PATH_IN_USE) occured
5792 dbus_connection_register_fallback (DBusConnection *connection,
5794 const DBusObjectPathVTable *vtable,
5798 DBusError error = DBUS_ERROR_INIT;
5800 _dbus_return_val_if_fail (connection != NULL, FALSE);
5801 _dbus_return_val_if_fail (path != NULL, FALSE);
5802 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5803 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5805 retval = _dbus_connection_register_object_path (connection, TRUE, path, vtable, user_data, &error);
5807 if (dbus_error_has_name (&error, DBUS_ERROR_OBJECT_PATH_IN_USE))
5809 _dbus_warn ("%s\n", error.message);
5810 dbus_error_free (&error);
5818 * Unregisters the handler registered with exactly the given path.
5819 * It's a bug to call this function for a path that isn't registered.
5820 * Can unregister both fallback paths and object paths.
5822 * @param connection the connection
5823 * @param path a '/' delimited string of path elements
5824 * @returns #FALSE if not enough memory
5827 dbus_connection_unregister_object_path (DBusConnection *connection,
5830 char **decomposed_path;
5832 _dbus_return_val_if_fail (connection != NULL, FALSE);
5833 _dbus_return_val_if_fail (path != NULL, FALSE);
5834 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5836 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5839 CONNECTION_LOCK (connection);
5841 _dbus_object_tree_unregister_and_unlock (connection->objects, (const char **) decomposed_path);
5843 dbus_free_string_array (decomposed_path);
5849 * Gets the user data passed to dbus_connection_register_object_path()
5850 * or dbus_connection_register_fallback(). If nothing was registered
5851 * at this path, the data is filled in with #NULL.
5853 * @param connection the connection
5854 * @param path the path you registered with
5855 * @param data_p location to store the user data, or #NULL
5856 * @returns #FALSE if not enough memory
5859 dbus_connection_get_object_path_data (DBusConnection *connection,
5863 char **decomposed_path;
5865 _dbus_return_val_if_fail (connection != NULL, FALSE);
5866 _dbus_return_val_if_fail (path != NULL, FALSE);
5867 _dbus_return_val_if_fail (data_p != NULL, FALSE);
5871 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5874 CONNECTION_LOCK (connection);
5876 *data_p = _dbus_object_tree_get_user_data_unlocked (connection->objects, (const char**) decomposed_path);
5878 CONNECTION_UNLOCK (connection);
5880 dbus_free_string_array (decomposed_path);
5886 * Lists the registered fallback handlers and object path handlers at
5887 * the given parent_path. The returned array should be freed with
5888 * dbus_free_string_array().
5890 * @param connection the connection
5891 * @param parent_path the path to list the child handlers of
5892 * @param child_entries returns #NULL-terminated array of children
5893 * @returns #FALSE if no memory to allocate the child entries
5896 dbus_connection_list_registered (DBusConnection *connection,
5897 const char *parent_path,
5898 char ***child_entries)
5900 char **decomposed_path;
5902 _dbus_return_val_if_fail (connection != NULL, FALSE);
5903 _dbus_return_val_if_fail (parent_path != NULL, FALSE);
5904 _dbus_return_val_if_fail (parent_path[0] == '/', FALSE);
5905 _dbus_return_val_if_fail (child_entries != NULL, FALSE);
5907 if (!_dbus_decompose_path (parent_path, strlen (parent_path), &decomposed_path, NULL))
5910 CONNECTION_LOCK (connection);
5912 retval = _dbus_object_tree_list_registered_and_unlock (connection->objects,
5913 (const char **) decomposed_path,
5915 dbus_free_string_array (decomposed_path);
5920 static DBusDataSlotAllocator slot_allocator =
5921 _DBUS_DATA_SLOT_ALLOCATOR_INIT (_DBUS_LOCK_NAME (connection_slots));
5924 * Allocates an integer ID to be used for storing application-specific
5925 * data on any DBusConnection. The allocated ID may then be used
5926 * with dbus_connection_set_data() and dbus_connection_get_data().
5927 * The passed-in slot must be initialized to -1, and is filled in
5928 * with the slot ID. If the passed-in slot is not -1, it's assumed
5929 * to be already allocated, and its refcount is incremented.
5931 * The allocated slot is global, i.e. all DBusConnection objects will
5932 * have a slot with the given integer ID reserved.
5934 * @param slot_p address of a global variable storing the slot
5935 * @returns #FALSE on failure (no memory)
5938 dbus_connection_allocate_data_slot (dbus_int32_t *slot_p)
5940 return _dbus_data_slot_allocator_alloc (&slot_allocator,
5945 * Deallocates a global ID for connection data slots.
5946 * dbus_connection_get_data() and dbus_connection_set_data() may no
5947 * longer be used with this slot. Existing data stored on existing
5948 * DBusConnection objects will be freed when the connection is
5949 * finalized, but may not be retrieved (and may only be replaced if
5950 * someone else reallocates the slot). When the refcount on the
5951 * passed-in slot reaches 0, it is set to -1.
5953 * @param slot_p address storing the slot to deallocate
5956 dbus_connection_free_data_slot (dbus_int32_t *slot_p)
5958 _dbus_return_if_fail (*slot_p >= 0);
5960 _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
5964 * Stores a pointer on a DBusConnection, along
5965 * with an optional function to be used for freeing
5966 * the data when the data is set again, or when
5967 * the connection is finalized. The slot number
5968 * must have been allocated with dbus_connection_allocate_data_slot().
5970 * @note This function does not take the
5971 * main thread lock on DBusConnection, which allows it to be
5972 * used from inside watch and timeout functions. (See the
5973 * note in docs for dbus_connection_set_watch_functions().)
5974 * A side effect of this is that you need to know there's
5975 * a reference held on the connection while invoking
5976 * dbus_connection_set_data(), or the connection could be
5977 * finalized during dbus_connection_set_data().
5979 * @param connection the connection
5980 * @param slot the slot number
5981 * @param data the data to store
5982 * @param free_data_func finalizer function for the data
5983 * @returns #TRUE if there was enough memory to store the data
5986 dbus_connection_set_data (DBusConnection *connection,
5989 DBusFreeFunction free_data_func)
5991 DBusFreeFunction old_free_func;
5995 _dbus_return_val_if_fail (connection != NULL, FALSE);
5996 _dbus_return_val_if_fail (slot >= 0, FALSE);
5998 SLOTS_LOCK (connection);
6000 retval = _dbus_data_slot_list_set (&slot_allocator,
6001 &connection->slot_list,
6002 slot, data, free_data_func,
6003 &old_free_func, &old_data);
6005 SLOTS_UNLOCK (connection);
6009 /* Do the actual free outside the connection lock */
6011 (* old_free_func) (old_data);
6018 * Retrieves data previously set with dbus_connection_set_data().
6019 * The slot must still be allocated (must not have been freed).
6021 * @note This function does not take the
6022 * main thread lock on DBusConnection, which allows it to be
6023 * used from inside watch and timeout functions. (See the
6024 * note in docs for dbus_connection_set_watch_functions().)
6025 * A side effect of this is that you need to know there's
6026 * a reference held on the connection while invoking
6027 * dbus_connection_get_data(), or the connection could be
6028 * finalized during dbus_connection_get_data().
6030 * @param connection the connection
6031 * @param slot the slot to get data from
6032 * @returns the data, or #NULL if not found
6035 dbus_connection_get_data (DBusConnection *connection,
6040 _dbus_return_val_if_fail (connection != NULL, NULL);
6041 _dbus_return_val_if_fail (slot >= 0, NULL);
6043 SLOTS_LOCK (connection);
6045 res = _dbus_data_slot_list_get (&slot_allocator,
6046 &connection->slot_list,
6049 SLOTS_UNLOCK (connection);
6055 * This function sets a global flag for whether dbus_connection_new()
6056 * will set SIGPIPE behavior to SIG_IGN.
6058 * @param will_modify_sigpipe #TRUE to allow sigpipe to be set to SIG_IGN
6061 dbus_connection_set_change_sigpipe (dbus_bool_t will_modify_sigpipe)
6063 _dbus_modify_sigpipe = will_modify_sigpipe != FALSE;
6067 * Specifies the maximum size message this connection is allowed to
6068 * receive. Larger messages will result in disconnecting the
6071 * @param connection a #DBusConnection
6072 * @param size maximum message size the connection can receive, in bytes
6075 dbus_connection_set_max_message_size (DBusConnection *connection,
6078 _dbus_return_if_fail (connection != NULL);
6080 CONNECTION_LOCK (connection);
6081 _dbus_transport_set_max_message_size (connection->transport,
6083 CONNECTION_UNLOCK (connection);
6087 * Gets the value set by dbus_connection_set_max_message_size().
6089 * @param connection the connection
6090 * @returns the max size of a single message
6093 dbus_connection_get_max_message_size (DBusConnection *connection)
6097 _dbus_return_val_if_fail (connection != NULL, 0);
6099 CONNECTION_LOCK (connection);
6100 res = _dbus_transport_get_max_message_size (connection->transport);
6101 CONNECTION_UNLOCK (connection);
6106 * Specifies the maximum number of unix fds a message on this
6107 * connection is allowed to receive. Messages with more unix fds will
6108 * result in disconnecting the connection.
6110 * @param connection a #DBusConnection
6111 * @param n maximum message unix fds the connection can receive
6114 dbus_connection_set_max_message_unix_fds (DBusConnection *connection,
6117 _dbus_return_if_fail (connection != NULL);
6119 CONNECTION_LOCK (connection);
6120 _dbus_transport_set_max_message_unix_fds (connection->transport,
6122 CONNECTION_UNLOCK (connection);
6126 * Gets the value set by dbus_connection_set_max_message_unix_fds().
6128 * @param connection the connection
6129 * @returns the max numer of unix fds of a single message
6132 dbus_connection_get_max_message_unix_fds (DBusConnection *connection)
6136 _dbus_return_val_if_fail (connection != NULL, 0);
6138 CONNECTION_LOCK (connection);
6139 res = _dbus_transport_get_max_message_unix_fds (connection->transport);
6140 CONNECTION_UNLOCK (connection);
6145 * Sets the maximum total number of bytes that can be used for all messages
6146 * received on this connection. Messages count toward the maximum until
6147 * they are finalized. When the maximum is reached, the connection will
6148 * not read more data until some messages are finalized.
6150 * The semantics of the maximum are: if outstanding messages are
6151 * already above the maximum, additional messages will not be read.
6152 * The semantics are not: if the next message would cause us to exceed
6153 * the maximum, we don't read it. The reason is that we don't know the
6154 * size of a message until after we read it.
6156 * Thus, the max live messages size can actually be exceeded
6157 * by up to the maximum size of a single message.
6159 * Also, if we read say 1024 bytes off the wire in a single read(),
6160 * and that contains a half-dozen small messages, we may exceed the
6161 * size max by that amount. But this should be inconsequential.
6163 * This does imply that we can't call read() with a buffer larger
6164 * than we're willing to exceed this limit by.
6166 * @param connection the connection
6167 * @param size the maximum size in bytes of all outstanding messages
6170 dbus_connection_set_max_received_size (DBusConnection *connection,
6173 _dbus_return_if_fail (connection != NULL);
6175 CONNECTION_LOCK (connection);
6176 _dbus_transport_set_max_received_size (connection->transport,
6178 CONNECTION_UNLOCK (connection);
6182 * Gets the value set by dbus_connection_set_max_received_size().
6184 * @param connection the connection
6185 * @returns the max size of all live messages
6188 dbus_connection_get_max_received_size (DBusConnection *connection)
6192 _dbus_return_val_if_fail (connection != NULL, 0);
6194 CONNECTION_LOCK (connection);
6195 res = _dbus_transport_get_max_received_size (connection->transport);
6196 CONNECTION_UNLOCK (connection);
6201 * Sets the maximum total number of unix fds that can be used for all messages
6202 * received on this connection. Messages count toward the maximum until
6203 * they are finalized. When the maximum is reached, the connection will
6204 * not read more data until some messages are finalized.
6206 * The semantics are analogous to those of dbus_connection_set_max_received_size().
6208 * @param connection the connection
6209 * @param n the maximum size in bytes of all outstanding messages
6212 dbus_connection_set_max_received_unix_fds (DBusConnection *connection,
6215 _dbus_return_if_fail (connection != NULL);
6217 CONNECTION_LOCK (connection);
6218 _dbus_transport_set_max_received_unix_fds (connection->transport,
6220 CONNECTION_UNLOCK (connection);
6224 * Gets the value set by dbus_connection_set_max_received_unix_fds().
6226 * @param connection the connection
6227 * @returns the max unix fds of all live messages
6230 dbus_connection_get_max_received_unix_fds (DBusConnection *connection)
6234 _dbus_return_val_if_fail (connection != NULL, 0);
6236 CONNECTION_LOCK (connection);
6237 res = _dbus_transport_get_max_received_unix_fds (connection->transport);
6238 CONNECTION_UNLOCK (connection);
6243 * Gets the approximate size in bytes of all messages in the outgoing
6244 * message queue. The size is approximate in that you shouldn't use
6245 * it to decide how many bytes to read off the network or anything
6246 * of that nature, as optimizations may choose to tell small white lies
6247 * to avoid performance overhead.
6249 * @param connection the connection
6250 * @returns the number of bytes that have been queued up but not sent
6253 dbus_connection_get_outgoing_size (DBusConnection *connection)
6257 _dbus_return_val_if_fail (connection != NULL, 0);
6259 CONNECTION_LOCK (connection);
6260 res = _dbus_counter_get_size_value (connection->outgoing_counter);
6261 CONNECTION_UNLOCK (connection);
6265 #ifdef DBUS_ENABLE_STATS
6267 _dbus_connection_get_stats (DBusConnection *connection,
6268 dbus_uint32_t *in_messages,
6269 dbus_uint32_t *in_bytes,
6270 dbus_uint32_t *in_fds,
6271 dbus_uint32_t *in_peak_bytes,
6272 dbus_uint32_t *in_peak_fds,
6273 dbus_uint32_t *out_messages,
6274 dbus_uint32_t *out_bytes,
6275 dbus_uint32_t *out_fds,
6276 dbus_uint32_t *out_peak_bytes,
6277 dbus_uint32_t *out_peak_fds)
6279 CONNECTION_LOCK (connection);
6281 if (in_messages != NULL)
6282 *in_messages = connection->n_incoming;
6284 _dbus_transport_get_stats (connection->transport,
6285 in_bytes, in_fds, in_peak_bytes, in_peak_fds);
6287 if (out_messages != NULL)
6288 *out_messages = connection->n_outgoing;
6290 if (out_bytes != NULL)
6291 *out_bytes = _dbus_counter_get_size_value (connection->outgoing_counter);
6293 if (out_fds != NULL)
6294 *out_fds = _dbus_counter_get_unix_fd_value (connection->outgoing_counter);
6296 if (out_peak_bytes != NULL)
6297 *out_peak_bytes = _dbus_counter_get_peak_size_value (connection->outgoing_counter);
6299 if (out_peak_fds != NULL)
6300 *out_peak_fds = _dbus_counter_get_peak_unix_fd_value (connection->outgoing_counter);
6302 CONNECTION_UNLOCK (connection);
6304 #endif /* DBUS_ENABLE_STATS */
6307 * Gets the approximate number of uni fds of all messages in the
6308 * outgoing message queue.
6310 * @param connection the connection
6311 * @returns the number of unix fds that have been queued up but not sent
6314 dbus_connection_get_outgoing_unix_fds (DBusConnection *connection)
6318 _dbus_return_val_if_fail (connection != NULL, 0);
6320 CONNECTION_LOCK (connection);
6321 res = _dbus_counter_get_unix_fd_value (connection->outgoing_counter);
6322 CONNECTION_UNLOCK (connection);
6327 * Returns the address of the transport object of this connection
6329 * @param connection the connection
6330 * @returns the address string
6333 _dbus_connection_get_address (DBusConnection *connection)
6335 return _dbus_transport_get_address (connection->transport);
6339 dbus_connection_get_transport(DBusConnection *connection)
6341 _dbus_return_val_if_fail (connection != NULL, NULL);
6343 return connection->transport;