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 */
338 unsigned int is_kdbus; /* Samsung change: to spare comparing address too often. 0 - uninitialized, 1 - not kdbus, 2 - kdbus */
341 static DBusDispatchStatus _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection);
342 static void _dbus_connection_update_dispatch_status_and_unlock (DBusConnection *connection,
343 DBusDispatchStatus new_status);
344 static void _dbus_connection_last_unref (DBusConnection *connection);
345 static void _dbus_connection_acquire_dispatch (DBusConnection *connection);
346 static void _dbus_connection_release_dispatch (DBusConnection *connection);
347 static DBusDispatchStatus _dbus_connection_flush_unlocked (DBusConnection *connection);
348 static void _dbus_connection_close_possibly_shared_and_unlock (DBusConnection *connection);
349 static dbus_bool_t _dbus_connection_get_is_connected_unlocked (DBusConnection *connection);
350 static dbus_bool_t _dbus_connection_peek_for_reply_unlocked (DBusConnection *connection,
351 dbus_uint32_t client_serial);
353 static DBusMessageFilter *
354 _dbus_message_filter_ref (DBusMessageFilter *filter)
356 #ifdef DBUS_DISABLE_ASSERT
357 _dbus_atomic_inc (&filter->refcount);
359 dbus_int32_t old_value;
361 old_value = _dbus_atomic_inc (&filter->refcount);
362 _dbus_assert (old_value > 0);
369 _dbus_message_filter_unref (DBusMessageFilter *filter)
371 dbus_int32_t old_value;
373 old_value = _dbus_atomic_dec (&filter->refcount);
374 _dbus_assert (old_value > 0);
378 if (filter->free_user_data_function)
379 (* filter->free_user_data_function) (filter->user_data);
386 * Acquires the connection lock.
388 * @param connection the connection.
391 _dbus_connection_lock (DBusConnection *connection)
393 CONNECTION_LOCK (connection);
397 * Releases the connection lock.
399 * @param connection the connection.
402 _dbus_connection_unlock (DBusConnection *connection)
404 DBusList *expired_messages;
409 _dbus_verbose ("UNLOCK\n");
412 /* If we had messages that expired (fell off the incoming or outgoing
413 * queues) while we were locked, actually release them now */
414 expired_messages = connection->expired_messages;
415 connection->expired_messages = NULL;
417 RELEASING_LOCK_CHECK (connection);
418 _dbus_rmutex_unlock (connection->mutex);
420 for (iter = _dbus_list_pop_first_link (&expired_messages);
422 iter = _dbus_list_pop_first_link (&expired_messages))
424 DBusMessage *message = iter->data;
426 dbus_message_unref (message);
427 _dbus_list_free_link (iter);
432 * Wakes up the main loop if it is sleeping
433 * Needed if we're e.g. queueing outgoing messages
434 * on a thread while the mainloop sleeps.
436 * @param connection the connection.
439 _dbus_connection_wakeup_mainloop (DBusConnection *connection)
441 if (connection->wakeup_main_function)
442 (*connection->wakeup_main_function) (connection->wakeup_main_data);
445 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
447 * Gets the locks so we can examine them
449 * @param connection the connection.
450 * @param mutex_loc return for the location of the main mutex pointer
451 * @param dispatch_mutex_loc return location of the dispatch mutex pointer
452 * @param io_path_mutex_loc return location of the io_path mutex pointer
453 * @param dispatch_cond_loc return location of the dispatch conditional
455 * @param io_path_cond_loc return location of the io_path conditional
459 _dbus_connection_test_get_locks (DBusConnection *connection,
460 DBusMutex **mutex_loc,
461 DBusMutex **dispatch_mutex_loc,
462 DBusMutex **io_path_mutex_loc,
463 DBusCondVar **dispatch_cond_loc,
464 DBusCondVar **io_path_cond_loc)
466 *mutex_loc = (DBusMutex *) connection->mutex;
467 *dispatch_mutex_loc = (DBusMutex *) connection->dispatch_mutex;
468 *io_path_mutex_loc = (DBusMutex *) connection->io_path_mutex;
469 *dispatch_cond_loc = connection->dispatch_cond;
470 *io_path_cond_loc = connection->io_path_cond;
475 * Adds a message-containing list link to the incoming message queue,
476 * taking ownership of the link and the message's current refcount.
477 * Cannot fail due to lack of memory.
479 * @param connection the connection.
480 * @param link the message link to queue.
483 _dbus_connection_queue_received_message_link (DBusConnection *connection,
486 DBusPendingCall *pending;
487 dbus_uint32_t reply_serial;
488 DBusMessage *message;
490 _dbus_assert (_dbus_transport_peek_is_authenticated (connection->transport));
492 _dbus_list_append_link (&connection->incoming_messages,
494 message = link->data;
496 /* If this is a reply we're waiting on, remove timeout for it */
497 reply_serial = dbus_message_get_reply_serial (message);
498 if (reply_serial != 0)
500 pending = _dbus_hash_table_lookup_int (connection->pending_replies,
504 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
505 _dbus_connection_remove_timeout_unlocked (connection,
506 _dbus_pending_call_get_timeout_unlocked (pending));
508 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
514 connection->n_incoming += 1;
516 _dbus_connection_wakeup_mainloop (connection);
518 _dbus_verbose ("Message %p (%s %s %s %s '%s' reply to %u) added to incoming queue %p, %d incoming\n",
520 dbus_message_type_to_string (dbus_message_get_type (message)),
521 dbus_message_get_path (message) ?
522 dbus_message_get_path (message) :
524 dbus_message_get_interface (message) ?
525 dbus_message_get_interface (message) :
527 dbus_message_get_member (message) ?
528 dbus_message_get_member (message) :
530 dbus_message_get_signature (message),
531 dbus_message_get_reply_serial (message),
533 connection->n_incoming);
535 _dbus_message_trace_ref (message, -1, -1,
536 "_dbus_conection_queue_received_message_link");
540 * Adds a link + message to the incoming message queue.
541 * Can't fail. Takes ownership of both link and message.
543 * @param connection the connection.
544 * @param link the list node and message to queue.
548 _dbus_connection_queue_synthesized_message_link (DBusConnection *connection,
551 HAVE_LOCK_CHECK (connection);
553 _dbus_list_append_link (&connection->incoming_messages, link);
555 connection->n_incoming += 1;
557 _dbus_connection_wakeup_mainloop (connection);
559 _dbus_message_trace_ref (link->data, -1, -1,
560 "_dbus_connection_queue_synthesized_message_link");
562 _dbus_verbose ("Synthesized message %p added to incoming queue %p, %d incoming\n",
563 link->data, connection, connection->n_incoming);
568 * Checks whether there are messages in the outgoing message queue.
569 * Called with connection lock held.
571 * @param connection the connection.
572 * @returns #TRUE if the outgoing queue is non-empty.
575 _dbus_connection_has_messages_to_send_unlocked (DBusConnection *connection)
577 HAVE_LOCK_CHECK (connection);
578 return connection->outgoing_messages != NULL;
582 * Checks whether there are messages in the outgoing message queue.
583 * Use dbus_connection_flush() to block until all outgoing
584 * messages have been written to the underlying transport
585 * (such as a socket).
587 * @param connection the connection.
588 * @returns #TRUE if the outgoing queue is non-empty.
591 dbus_connection_has_messages_to_send (DBusConnection *connection)
595 _dbus_return_val_if_fail (connection != NULL, FALSE);
597 CONNECTION_LOCK (connection);
598 v = _dbus_connection_has_messages_to_send_unlocked (connection);
599 CONNECTION_UNLOCK (connection);
605 * Gets the next outgoing message. The message remains in the
606 * queue, and the caller does not own a reference to it.
608 * @param connection the connection.
609 * @returns the message to be sent.
612 _dbus_connection_get_message_to_send (DBusConnection *connection)
614 HAVE_LOCK_CHECK (connection);
616 return _dbus_list_get_last (&connection->outgoing_messages);
620 * Notifies the connection that a message has been sent, so the
621 * message can be removed from the outgoing queue.
622 * Called with the connection lock held.
624 * @param connection the connection.
625 * @param message the message that was sent.
628 _dbus_connection_message_sent_unlocked (DBusConnection *connection,
629 DBusMessage *message)
633 HAVE_LOCK_CHECK (connection);
635 /* This can be called before we even complete authentication, since
636 * it's called on disconnect to clean up the outgoing queue.
637 * It's also called as we successfully send each message.
640 link = _dbus_list_get_last_link (&connection->outgoing_messages);
641 _dbus_assert (link != NULL);
642 _dbus_assert (link->data == message);
644 _dbus_list_unlink (&connection->outgoing_messages,
646 _dbus_list_prepend_link (&connection->expired_messages, link);
648 connection->n_outgoing -= 1;
650 _dbus_verbose ("Message %p (%s %s %s %s '%s') removed from outgoing queue %p, %d left to send\n",
652 dbus_message_type_to_string (dbus_message_get_type (message)),
653 dbus_message_get_path (message) ?
654 dbus_message_get_path (message) :
656 dbus_message_get_interface (message) ?
657 dbus_message_get_interface (message) :
659 dbus_message_get_member (message) ?
660 dbus_message_get_member (message) :
662 dbus_message_get_signature (message),
663 connection, connection->n_outgoing);
665 /* It's OK that in principle we call the notify function, because for the
666 * outgoing limit, there isn't one */
667 _dbus_message_remove_counter (message, connection->outgoing_counter);
669 /* The message will actually be unreffed when we unlock */
672 /** Function to be called in protected_change_watch() with refcount held */
673 typedef dbus_bool_t (* DBusWatchAddFunction) (DBusWatchList *list,
675 /** Function to be called in protected_change_watch() with refcount held */
676 typedef void (* DBusWatchRemoveFunction) (DBusWatchList *list,
678 /** Function to be called in protected_change_watch() with refcount held */
679 typedef void (* DBusWatchToggleFunction) (DBusWatchList *list,
681 dbus_bool_t enabled);
684 protected_change_watch (DBusConnection *connection,
686 DBusWatchAddFunction add_function,
687 DBusWatchRemoveFunction remove_function,
688 DBusWatchToggleFunction toggle_function,
693 HAVE_LOCK_CHECK (connection);
695 /* The original purpose of protected_change_watch() was to hold a
696 * ref on the connection while dropping the connection lock, then
697 * calling out to the app. This was a broken hack that did not
698 * work, since the connection was in a hosed state (no WatchList
699 * field) while calling out.
701 * So for now we'll just keep the lock while calling out. This means
702 * apps are not allowed to call DBusConnection methods inside a
703 * watch function or they will deadlock.
705 * The "real fix" is to use the _and_unlock() pattern found
706 * elsewhere in the code, to defer calling out to the app until
707 * we're about to drop locks and return flow of control to the app
710 * See http://lists.freedesktop.org/archives/dbus/2007-July/thread.html#8144
713 if (connection->watches)
716 retval = (* add_function) (connection->watches, watch);
717 else if (remove_function)
720 (* remove_function) (connection->watches, watch);
725 (* toggle_function) (connection->watches, watch, enabled);
735 * Adds a watch using the connection's DBusAddWatchFunction if
736 * available. Otherwise records the watch to be added when said
737 * function is available. Also re-adds the watch if the
738 * DBusAddWatchFunction changes. May fail due to lack of memory.
739 * Connection lock should be held when calling this.
741 * @param connection the connection.
742 * @param watch the watch to add.
743 * @returns #TRUE on success.
746 _dbus_connection_add_watch_unlocked (DBusConnection *connection,
749 return protected_change_watch (connection, watch,
750 _dbus_watch_list_add_watch,
755 * Removes a watch using the connection's DBusRemoveWatchFunction
756 * if available. It's an error to call this function on a watch
757 * that was not previously added.
758 * Connection lock should be held when calling this.
760 * @param connection the connection.
761 * @param watch the watch to remove.
764 _dbus_connection_remove_watch_unlocked (DBusConnection *connection,
767 protected_change_watch (connection, watch,
769 _dbus_watch_list_remove_watch,
774 * Toggles a watch and notifies app via connection's
775 * DBusWatchToggledFunction if available. It's an error to call this
776 * function on a watch that was not previously added.
777 * Connection lock should be held when calling this.
779 * @param connection the connection.
780 * @param watch the watch to toggle.
781 * @param enabled whether to enable or disable
784 _dbus_connection_toggle_watch_unlocked (DBusConnection *connection,
788 _dbus_assert (watch != NULL);
790 protected_change_watch (connection, watch,
792 _dbus_watch_list_toggle_watch,
796 /** Function to be called in protected_change_timeout() with refcount held */
797 typedef dbus_bool_t (* DBusTimeoutAddFunction) (DBusTimeoutList *list,
798 DBusTimeout *timeout);
799 /** Function to be called in protected_change_timeout() with refcount held */
800 typedef void (* DBusTimeoutRemoveFunction) (DBusTimeoutList *list,
801 DBusTimeout *timeout);
802 /** Function to be called in protected_change_timeout() with refcount held */
803 typedef void (* DBusTimeoutToggleFunction) (DBusTimeoutList *list,
804 DBusTimeout *timeout,
805 dbus_bool_t enabled);
808 protected_change_timeout (DBusConnection *connection,
809 DBusTimeout *timeout,
810 DBusTimeoutAddFunction add_function,
811 DBusTimeoutRemoveFunction remove_function,
812 DBusTimeoutToggleFunction toggle_function,
817 HAVE_LOCK_CHECK (connection);
819 /* The original purpose of protected_change_timeout() was to hold a
820 * ref on the connection while dropping the connection lock, then
821 * calling out to the app. This was a broken hack that did not
822 * work, since the connection was in a hosed state (no TimeoutList
823 * field) while calling out.
825 * So for now we'll just keep the lock while calling out. This means
826 * apps are not allowed to call DBusConnection methods inside a
827 * timeout function or they will deadlock.
829 * The "real fix" is to use the _and_unlock() pattern found
830 * elsewhere in the code, to defer calling out to the app until
831 * we're about to drop locks and return flow of control to the app
834 * See http://lists.freedesktop.org/archives/dbus/2007-July/thread.html#8144
837 if (connection->timeouts)
840 retval = (* add_function) (connection->timeouts, timeout);
841 else if (remove_function)
844 (* remove_function) (connection->timeouts, timeout);
849 (* toggle_function) (connection->timeouts, timeout, enabled);
858 * Adds a timeout using the connection's DBusAddTimeoutFunction if
859 * available. Otherwise records the timeout to be added when said
860 * function is available. Also re-adds the timeout if the
861 * DBusAddTimeoutFunction changes. May fail due to lack of memory.
862 * The timeout will fire repeatedly until removed.
863 * Connection lock should be held when calling this.
865 * @param connection the connection.
866 * @param timeout the timeout to add.
867 * @returns #TRUE on success.
870 _dbus_connection_add_timeout_unlocked (DBusConnection *connection,
871 DBusTimeout *timeout)
873 return protected_change_timeout (connection, timeout,
874 _dbus_timeout_list_add_timeout,
879 * Removes a timeout using the connection's DBusRemoveTimeoutFunction
880 * if available. It's an error to call this function on a timeout
881 * that was not previously added.
882 * Connection lock should be held when calling this.
884 * @param connection the connection.
885 * @param timeout the timeout to remove.
888 _dbus_connection_remove_timeout_unlocked (DBusConnection *connection,
889 DBusTimeout *timeout)
891 protected_change_timeout (connection, timeout,
893 _dbus_timeout_list_remove_timeout,
898 * Toggles a timeout and notifies app via connection's
899 * DBusTimeoutToggledFunction if available. It's an error to call this
900 * function on a timeout that was not previously added.
901 * Connection lock should be held when calling this.
903 * @param connection the connection.
904 * @param timeout the timeout to toggle.
905 * @param enabled whether to enable or disable
908 _dbus_connection_toggle_timeout_unlocked (DBusConnection *connection,
909 DBusTimeout *timeout,
912 protected_change_timeout (connection, timeout,
914 _dbus_timeout_list_toggle_timeout,
919 _dbus_connection_attach_pending_call_unlocked (DBusConnection *connection,
920 DBusPendingCall *pending)
922 dbus_uint32_t reply_serial;
923 DBusTimeout *timeout;
925 HAVE_LOCK_CHECK (connection);
927 reply_serial = _dbus_pending_call_get_reply_serial_unlocked (pending);
929 _dbus_assert (reply_serial != 0);
931 timeout = _dbus_pending_call_get_timeout_unlocked (pending);
935 if (!_dbus_connection_add_timeout_unlocked (connection, timeout))
938 if (!_dbus_hash_table_insert_int (connection->pending_replies,
942 _dbus_connection_remove_timeout_unlocked (connection, timeout);
944 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
945 HAVE_LOCK_CHECK (connection);
949 _dbus_pending_call_set_timeout_added_unlocked (pending, TRUE);
953 if (!_dbus_hash_table_insert_int (connection->pending_replies,
957 HAVE_LOCK_CHECK (connection);
962 _dbus_pending_call_ref_unlocked (pending);
964 HAVE_LOCK_CHECK (connection);
970 free_pending_call_on_hash_removal (void *data)
972 DBusPendingCall *pending;
973 DBusConnection *connection;
980 connection = _dbus_pending_call_get_connection_unlocked (pending);
982 HAVE_LOCK_CHECK (connection);
984 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
986 _dbus_connection_remove_timeout_unlocked (connection,
987 _dbus_pending_call_get_timeout_unlocked (pending));
989 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
992 /* FIXME 1.0? this is sort of dangerous and undesirable to drop the lock
993 * here, but the pending call finalizer could in principle call out to
994 * application code so we pretty much have to... some larger code reorg
997 _dbus_connection_ref_unlocked (connection);
998 _dbus_pending_call_unref_and_unlock (pending);
999 CONNECTION_LOCK (connection);
1000 _dbus_connection_unref_unlocked (connection);
1004 _dbus_connection_detach_pending_call_unlocked (DBusConnection *connection,
1005 DBusPendingCall *pending)
1007 /* This ends up unlocking to call the pending call finalizer, which is unexpected to
1010 _dbus_hash_table_remove_int (connection->pending_replies,
1011 _dbus_pending_call_get_reply_serial_unlocked (pending));
1015 _dbus_connection_detach_pending_call_and_unlock (DBusConnection *connection,
1016 DBusPendingCall *pending)
1018 /* The idea here is to avoid finalizing the pending call
1019 * with the lock held, since there's a destroy notifier
1020 * in pending call that goes out to application code.
1022 * There's an extra unlock inside the hash table
1023 * "free pending call" function FIXME...
1025 _dbus_pending_call_ref_unlocked (pending);
1026 _dbus_hash_table_remove_int (connection->pending_replies,
1027 _dbus_pending_call_get_reply_serial_unlocked (pending));
1029 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
1030 _dbus_connection_remove_timeout_unlocked (connection,
1031 _dbus_pending_call_get_timeout_unlocked (pending));
1033 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
1035 _dbus_pending_call_unref_and_unlock (pending);
1039 * Removes a pending call from the connection, such that
1040 * the pending reply will be ignored. May drop the last
1041 * reference to the pending call.
1043 * @param connection the connection
1044 * @param pending the pending call
1047 _dbus_connection_remove_pending_call (DBusConnection *connection,
1048 DBusPendingCall *pending)
1050 CONNECTION_LOCK (connection);
1051 _dbus_connection_detach_pending_call_and_unlock (connection, pending);
1055 * Acquire the transporter I/O path. This must be done before
1056 * doing any I/O in the transporter. May sleep and drop the
1057 * IO path mutex while waiting for the I/O path.
1059 * @param connection the connection.
1060 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
1061 * @returns TRUE if the I/O path was acquired.
1064 _dbus_connection_acquire_io_path (DBusConnection *connection,
1065 int timeout_milliseconds)
1067 dbus_bool_t we_acquired;
1069 HAVE_LOCK_CHECK (connection);
1071 /* We don't want the connection to vanish */
1072 _dbus_connection_ref_unlocked (connection);
1074 /* We will only touch io_path_acquired which is protected by our mutex */
1075 CONNECTION_UNLOCK (connection);
1077 _dbus_verbose ("locking io_path_mutex\n");
1078 _dbus_cmutex_lock (connection->io_path_mutex);
1080 _dbus_verbose ("start connection->io_path_acquired = %d timeout = %d\n",
1081 connection->io_path_acquired, timeout_milliseconds);
1083 we_acquired = FALSE;
1085 if (connection->io_path_acquired)
1087 if (timeout_milliseconds != -1)
1089 _dbus_verbose ("waiting %d for IO path to be acquirable\n",
1090 timeout_milliseconds);
1092 if (!_dbus_condvar_wait_timeout (connection->io_path_cond,
1093 connection->io_path_mutex,
1094 timeout_milliseconds))
1096 /* We timed out before anyone signaled. */
1097 /* (writing the loop to handle the !timedout case by
1098 * waiting longer if needed is a pain since dbus
1099 * wraps pthread_cond_timedwait to take a relative
1100 * time instead of absolute, something kind of stupid
1101 * on our part. for now it doesn't matter, we will just
1102 * end up back here eventually.)
1108 while (connection->io_path_acquired)
1110 _dbus_verbose ("waiting for IO path to be acquirable\n");
1111 _dbus_condvar_wait (connection->io_path_cond,
1112 connection->io_path_mutex);
1117 if (!connection->io_path_acquired)
1120 connection->io_path_acquired = TRUE;
1123 _dbus_verbose ("end connection->io_path_acquired = %d we_acquired = %d\n",
1124 connection->io_path_acquired, we_acquired);
1126 _dbus_verbose ("unlocking io_path_mutex\n");
1127 _dbus_cmutex_unlock (connection->io_path_mutex);
1129 CONNECTION_LOCK (connection);
1131 HAVE_LOCK_CHECK (connection);
1133 _dbus_connection_unref_unlocked (connection);
1139 * Release the I/O path when you're done with it. Only call
1140 * after you've acquired the I/O. Wakes up at most one thread
1141 * currently waiting to acquire the I/O path.
1143 * @param connection the connection.
1146 _dbus_connection_release_io_path (DBusConnection *connection)
1148 HAVE_LOCK_CHECK (connection);
1150 _dbus_verbose ("locking io_path_mutex\n");
1151 _dbus_cmutex_lock (connection->io_path_mutex);
1153 _dbus_assert (connection->io_path_acquired);
1155 _dbus_verbose ("start connection->io_path_acquired = %d\n",
1156 connection->io_path_acquired);
1158 connection->io_path_acquired = FALSE;
1159 _dbus_condvar_wake_one (connection->io_path_cond);
1161 _dbus_verbose ("unlocking io_path_mutex\n");
1162 _dbus_cmutex_unlock (connection->io_path_mutex);
1166 * Queues incoming messages and sends outgoing messages for this
1167 * connection, optionally blocking in the process. Each call to
1168 * _dbus_connection_do_iteration_unlocked() will call select() or poll() one
1169 * time and then read or write data if possible.
1171 * The purpose of this function is to be able to flush outgoing
1172 * messages or queue up incoming messages without returning
1173 * control to the application and causing reentrancy weirdness.
1175 * The flags parameter allows you to specify whether to
1176 * read incoming messages, write outgoing messages, or both,
1177 * and whether to block if no immediate action is possible.
1179 * The timeout_milliseconds parameter does nothing unless the
1180 * iteration is blocking.
1182 * If there are no outgoing messages and DBUS_ITERATION_DO_READING
1183 * wasn't specified, then it's impossible to block, even if
1184 * you specify DBUS_ITERATION_BLOCK; in that case the function
1185 * returns immediately.
1187 * If pending is not NULL then a check is made if the pending call
1188 * is completed after the io path has been required. If the call
1189 * has been completed nothing is done. This must be done since
1190 * the _dbus_connection_acquire_io_path releases the connection
1193 * Called with connection lock held.
1195 * @param connection the connection.
1196 * @param pending the pending call that should be checked or NULL
1197 * @param flags iteration flags.
1198 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
1201 _dbus_connection_do_iteration_unlocked (DBusConnection *connection,
1202 DBusPendingCall *pending,
1204 int timeout_milliseconds)
1206 _dbus_verbose ("start\n");
1208 HAVE_LOCK_CHECK (connection);
1210 if (connection->n_outgoing == 0)
1211 flags &= ~DBUS_ITERATION_DO_WRITING;
1213 if (_dbus_connection_acquire_io_path (connection,
1214 (flags & DBUS_ITERATION_BLOCK) ? timeout_milliseconds : 0))
1216 HAVE_LOCK_CHECK (connection);
1218 if ( (pending != NULL) && _dbus_pending_call_get_completed_unlocked(pending))
1220 _dbus_verbose ("pending call completed while acquiring I/O path");
1222 else if ( (pending != NULL) &&
1223 _dbus_connection_peek_for_reply_unlocked (connection,
1224 _dbus_pending_call_get_reply_serial_unlocked (pending)))
1226 _dbus_verbose ("pending call completed while acquiring I/O path (reply found in queue)");
1230 _dbus_transport_do_iteration (connection->transport,
1231 flags, timeout_milliseconds);
1234 _dbus_connection_release_io_path (connection);
1237 HAVE_LOCK_CHECK (connection);
1239 _dbus_verbose ("end\n");
1243 * Creates a new connection for the given transport. A transport
1244 * represents a message stream that uses some concrete mechanism, such
1245 * as UNIX domain sockets. May return #NULL if insufficient
1246 * memory exists to create the connection.
1248 * @param transport the transport.
1249 * @returns the new connection, or #NULL on failure.
1252 _dbus_connection_new_for_transport (DBusTransport *transport)
1254 DBusConnection *connection;
1255 DBusWatchList *watch_list;
1256 DBusTimeoutList *timeout_list;
1257 DBusHashTable *pending_replies;
1258 DBusList *disconnect_link;
1259 DBusMessage *disconnect_message;
1260 DBusCounter *outgoing_counter;
1261 DBusObjectTree *objects;
1265 pending_replies = NULL;
1266 timeout_list = NULL;
1267 disconnect_link = NULL;
1268 disconnect_message = NULL;
1269 outgoing_counter = NULL;
1272 watch_list = _dbus_watch_list_new ();
1273 if (watch_list == NULL)
1276 timeout_list = _dbus_timeout_list_new ();
1277 if (timeout_list == NULL)
1281 _dbus_hash_table_new (DBUS_HASH_INT,
1283 (DBusFreeFunction)free_pending_call_on_hash_removal);
1284 if (pending_replies == NULL)
1287 connection = dbus_new0 (DBusConnection, 1);
1288 if (connection == NULL)
1291 _dbus_rmutex_new_at_location (&connection->mutex);
1292 if (connection->mutex == NULL)
1295 _dbus_cmutex_new_at_location (&connection->io_path_mutex);
1296 if (connection->io_path_mutex == NULL)
1299 _dbus_cmutex_new_at_location (&connection->dispatch_mutex);
1300 if (connection->dispatch_mutex == NULL)
1303 _dbus_condvar_new_at_location (&connection->dispatch_cond);
1304 if (connection->dispatch_cond == NULL)
1307 _dbus_condvar_new_at_location (&connection->io_path_cond);
1308 if (connection->io_path_cond == NULL)
1311 _dbus_rmutex_new_at_location (&connection->slot_mutex);
1312 if (connection->slot_mutex == NULL)
1315 disconnect_message = dbus_message_new_signal (DBUS_PATH_LOCAL,
1316 DBUS_INTERFACE_LOCAL,
1319 if (disconnect_message == NULL)
1322 disconnect_link = _dbus_list_alloc_link (disconnect_message);
1323 if (disconnect_link == NULL)
1326 outgoing_counter = _dbus_counter_new ();
1327 if (outgoing_counter == NULL)
1330 objects = _dbus_object_tree_new (connection);
1331 if (objects == NULL)
1334 if (_dbus_modify_sigpipe)
1335 _dbus_disable_sigpipe ();
1337 /* initialized to 0: use atomic op to avoid mixing atomic and non-atomic */
1338 _dbus_atomic_inc (&connection->refcount);
1339 connection->transport = transport;
1340 connection->watches = watch_list;
1341 connection->timeouts = timeout_list;
1342 connection->pending_replies = pending_replies;
1343 connection->outgoing_counter = outgoing_counter;
1344 connection->filter_list = NULL;
1345 connection->last_dispatch_status = DBUS_DISPATCH_COMPLETE; /* so we're notified first time there's data */
1346 connection->objects = objects;
1347 connection->exit_on_disconnect = FALSE;
1348 connection->shareable = FALSE;
1349 connection->route_peer_messages = FALSE;
1350 connection->disconnected_message_arrived = FALSE;
1351 connection->disconnected_message_processed = FALSE;
1353 #if defined(DBUS_ENABLE_CHECKS) || defined(DBUS_ENABLE_ASSERT)
1354 connection->generation = _dbus_current_generation;
1357 _dbus_data_slot_list_init (&connection->slot_list);
1359 connection->client_serial = 1;
1361 connection->disconnect_message_link = disconnect_link;
1363 CONNECTION_LOCK (connection);
1365 if (!_dbus_transport_set_connection (transport, connection))
1367 CONNECTION_UNLOCK (connection);
1372 _dbus_transport_ref (transport);
1374 CONNECTION_UNLOCK (connection);
1376 _dbus_connection_trace_ref (connection, 0, 1, "new_for_transport");
1380 if (disconnect_message != NULL)
1381 dbus_message_unref (disconnect_message);
1383 if (disconnect_link != NULL)
1384 _dbus_list_free_link (disconnect_link);
1386 if (connection != NULL)
1388 _dbus_condvar_free_at_location (&connection->io_path_cond);
1389 _dbus_condvar_free_at_location (&connection->dispatch_cond);
1390 _dbus_rmutex_free_at_location (&connection->mutex);
1391 _dbus_cmutex_free_at_location (&connection->io_path_mutex);
1392 _dbus_cmutex_free_at_location (&connection->dispatch_mutex);
1393 _dbus_rmutex_free_at_location (&connection->slot_mutex);
1394 dbus_free (connection);
1396 if (pending_replies)
1397 _dbus_hash_table_unref (pending_replies);
1400 _dbus_watch_list_free (watch_list);
1403 _dbus_timeout_list_free (timeout_list);
1405 if (outgoing_counter)
1406 _dbus_counter_unref (outgoing_counter);
1409 _dbus_object_tree_unref (objects);
1415 * Increments the reference count of a DBusConnection.
1416 * Requires that the caller already holds the connection lock.
1418 * @param connection the connection.
1419 * @returns the connection.
1422 _dbus_connection_ref_unlocked (DBusConnection *connection)
1424 dbus_int32_t old_refcount;
1426 _dbus_assert (connection != NULL);
1427 _dbus_assert (connection->generation == _dbus_current_generation);
1429 HAVE_LOCK_CHECK (connection);
1431 old_refcount = _dbus_atomic_inc (&connection->refcount);
1432 _dbus_connection_trace_ref (connection, old_refcount, old_refcount + 1,
1439 * Decrements the reference count of a DBusConnection.
1440 * Requires that the caller already holds the connection lock.
1442 * @param connection the connection.
1445 _dbus_connection_unref_unlocked (DBusConnection *connection)
1447 dbus_int32_t old_refcount;
1449 HAVE_LOCK_CHECK (connection);
1451 _dbus_assert (connection != NULL);
1453 old_refcount = _dbus_atomic_dec (&connection->refcount);
1455 _dbus_connection_trace_ref (connection, old_refcount, old_refcount - 1,
1458 if (old_refcount == 1)
1459 _dbus_connection_last_unref (connection);
1462 static dbus_uint32_t
1463 _dbus_connection_get_next_client_serial (DBusConnection *connection)
1465 dbus_uint32_t serial;
1467 serial = connection->client_serial++;
1469 if (connection->client_serial == 0)
1470 connection->client_serial = 1;
1476 * A callback for use with dbus_watch_new() to create a DBusWatch.
1478 * @todo This is basically a hack - we could delete _dbus_transport_handle_watch()
1479 * and the virtual handle_watch in DBusTransport if we got rid of it.
1480 * The reason this is some work is threading, see the _dbus_connection_handle_watch()
1483 * @param watch the watch.
1484 * @param condition the current condition of the file descriptors being watched.
1485 * @param data must be a pointer to a #DBusConnection
1486 * @returns #FALSE if the IO condition may not have been fully handled due to lack of memory
1489 _dbus_connection_handle_watch (DBusWatch *watch,
1490 unsigned int condition,
1493 DBusConnection *connection;
1495 DBusDispatchStatus status;
1499 _dbus_verbose ("start\n");
1501 CONNECTION_LOCK (connection);
1503 if (!_dbus_connection_acquire_io_path (connection, 1))
1505 /* another thread is handling the message */
1506 CONNECTION_UNLOCK (connection);
1510 HAVE_LOCK_CHECK (connection);
1511 retval = _dbus_transport_handle_watch (connection->transport,
1514 _dbus_connection_release_io_path (connection);
1516 HAVE_LOCK_CHECK (connection);
1518 _dbus_verbose ("middle\n");
1520 status = _dbus_connection_get_dispatch_status_unlocked (connection);
1522 /* this calls out to user code */
1523 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1525 _dbus_verbose ("end\n");
1530 /* Protected by _DBUS_LOCK (shared_connections) */
1531 static DBusHashTable *shared_connections = NULL;
1532 static DBusList *shared_connections_no_guid = NULL;
1535 close_connection_on_shutdown (DBusConnection *connection)
1537 DBusMessage *message;
1539 dbus_connection_ref (connection);
1540 _dbus_connection_close_possibly_shared (connection);
1542 /* Churn through to the Disconnected message */
1543 while ((message = dbus_connection_pop_message (connection)))
1545 dbus_message_unref (message);
1547 dbus_connection_unref (connection);
1551 shared_connections_shutdown (void *data)
1555 if (!_DBUS_LOCK (shared_connections))
1557 /* We'd have initialized locks before adding anything, so there
1558 * can't be anything there. */
1562 /* This is a little bit unpleasant... better ideas? */
1563 while ((n_entries = _dbus_hash_table_get_n_entries (shared_connections)) > 0)
1565 DBusConnection *connection;
1568 _dbus_hash_iter_init (shared_connections, &iter);
1569 _dbus_hash_iter_next (&iter);
1571 connection = _dbus_hash_iter_get_value (&iter);
1573 _DBUS_UNLOCK (shared_connections);
1574 close_connection_on_shutdown (connection);
1575 if (!_DBUS_LOCK (shared_connections))
1576 _dbus_assert_not_reached ("global locks were already initialized");
1578 /* The connection should now be dead and not in our hash ... */
1579 _dbus_assert (_dbus_hash_table_get_n_entries (shared_connections) < n_entries);
1582 _dbus_assert (_dbus_hash_table_get_n_entries (shared_connections) == 0);
1584 _dbus_hash_table_unref (shared_connections);
1585 shared_connections = NULL;
1587 if (shared_connections_no_guid != NULL)
1589 DBusConnection *connection;
1590 connection = _dbus_list_pop_first (&shared_connections_no_guid);
1591 while (connection != NULL)
1593 _DBUS_UNLOCK (shared_connections);
1594 close_connection_on_shutdown (connection);
1595 if (!_DBUS_LOCK (shared_connections))
1596 _dbus_assert_not_reached ("global locks were already initialized");
1597 connection = _dbus_list_pop_first (&shared_connections_no_guid);
1601 shared_connections_no_guid = NULL;
1603 _DBUS_UNLOCK (shared_connections);
1607 connection_lookup_shared (DBusAddressEntry *entry,
1608 DBusConnection **result)
1610 _dbus_verbose ("checking for existing connection\n");
1614 if (!_DBUS_LOCK (shared_connections))
1616 /* If it was shared, we'd have initialized global locks when we put
1617 * it in shared_connections. */
1621 if (shared_connections == NULL)
1623 _dbus_verbose ("creating shared_connections hash table\n");
1625 shared_connections = _dbus_hash_table_new (DBUS_HASH_STRING,
1628 if (shared_connections == NULL)
1630 _DBUS_UNLOCK (shared_connections);
1634 if (!_dbus_register_shutdown_func (shared_connections_shutdown, NULL))
1636 _dbus_hash_table_unref (shared_connections);
1637 shared_connections = NULL;
1638 _DBUS_UNLOCK (shared_connections);
1642 _dbus_verbose (" successfully created shared_connections\n");
1644 _DBUS_UNLOCK (shared_connections);
1645 return TRUE; /* no point looking up in the hash we just made */
1651 guid = dbus_address_entry_get_value (entry, "guid");
1655 DBusConnection *connection;
1657 connection = _dbus_hash_table_lookup_string (shared_connections,
1662 /* The DBusConnection can't be finalized without taking
1663 * the shared_connections lock to remove it from the
1664 * hash. So it's safe to ref the connection here.
1665 * However, it may be disconnected if the Disconnected
1666 * message hasn't been processed yet, in which case we
1667 * want to pretend it isn't in the hash and avoid
1670 * The idea is to avoid ever returning a disconnected connection
1671 * from dbus_connection_open(). We could just synchronously
1672 * drop our shared ref to the connection on connection disconnect,
1673 * and then assert here that the connection is connected, but
1674 * that causes reentrancy headaches.
1676 CONNECTION_LOCK (connection);
1677 if (_dbus_connection_get_is_connected_unlocked (connection))
1679 _dbus_connection_ref_unlocked (connection);
1680 *result = connection;
1681 _dbus_verbose ("looked up existing connection to server guid %s\n",
1686 _dbus_verbose ("looked up existing connection to server guid %s but it was disconnected so ignoring it\n",
1689 CONNECTION_UNLOCK (connection);
1693 _DBUS_UNLOCK (shared_connections);
1699 connection_record_shared_unlocked (DBusConnection *connection,
1703 char *guid_in_connection;
1705 HAVE_LOCK_CHECK (connection);
1706 _dbus_assert (connection->server_guid == NULL);
1707 _dbus_assert (connection->shareable);
1709 /* get a hard ref on this connection, even if
1710 * we won't in fact store it in the hash, we still
1711 * need to hold a ref on it until it's disconnected.
1713 _dbus_connection_ref_unlocked (connection);
1717 if (!_DBUS_LOCK (shared_connections))
1720 if (!_dbus_list_prepend (&shared_connections_no_guid, connection))
1722 _DBUS_UNLOCK (shared_connections);
1726 _DBUS_UNLOCK (shared_connections);
1727 return TRUE; /* don't store in the hash */
1730 /* A separate copy of the key is required in the hash table, because
1731 * we don't have a lock on the connection when we are doing a hash
1735 guid_key = _dbus_strdup (guid);
1736 if (guid_key == NULL)
1739 guid_in_connection = _dbus_strdup (guid);
1740 if (guid_in_connection == NULL)
1742 dbus_free (guid_key);
1746 if (!_DBUS_LOCK (shared_connections))
1748 dbus_free (guid_in_connection);
1749 dbus_free (guid_key);
1753 _dbus_assert (shared_connections != NULL);
1755 if (!_dbus_hash_table_insert_string (shared_connections,
1756 guid_key, connection))
1758 dbus_free (guid_key);
1759 dbus_free (guid_in_connection);
1760 _DBUS_UNLOCK (shared_connections);
1764 connection->server_guid = guid_in_connection;
1766 _dbus_verbose ("stored connection to %s to be shared\n",
1767 connection->server_guid);
1769 _DBUS_UNLOCK (shared_connections);
1771 _dbus_assert (connection->server_guid != NULL);
1777 connection_forget_shared_unlocked (DBusConnection *connection)
1779 HAVE_LOCK_CHECK (connection);
1781 if (!connection->shareable)
1784 if (!_DBUS_LOCK (shared_connections))
1786 /* If it was shared, we'd have initialized global locks when we put
1787 * it in the table; so it can't be there. */
1791 if (connection->server_guid != NULL)
1793 _dbus_verbose ("dropping connection to %s out of the shared table\n",
1794 connection->server_guid);
1796 if (!_dbus_hash_table_remove_string (shared_connections,
1797 connection->server_guid))
1798 _dbus_assert_not_reached ("connection was not in the shared table");
1800 dbus_free (connection->server_guid);
1801 connection->server_guid = NULL;
1805 _dbus_list_remove (&shared_connections_no_guid, connection);
1808 _DBUS_UNLOCK (shared_connections);
1810 /* remove our reference held on all shareable connections */
1811 _dbus_connection_unref_unlocked (connection);
1814 static DBusConnection*
1815 connection_try_from_address_entry (DBusAddressEntry *entry,
1818 DBusTransport *transport;
1819 DBusConnection *connection;
1821 transport = _dbus_transport_open (entry, error);
1823 if (transport == NULL)
1825 _DBUS_ASSERT_ERROR_IS_SET (error);
1829 connection = _dbus_connection_new_for_transport (transport);
1831 _dbus_transport_unref (transport);
1833 if (connection == NULL)
1835 _DBUS_SET_OOM (error);
1839 #ifndef DBUS_DISABLE_CHECKS
1840 _dbus_assert (!connection->have_connection_lock);
1847 * If the shared parameter is true, then any existing connection will
1848 * be used (and if a new connection is created, it will be available
1849 * for use by others). If the shared parameter is false, a new
1850 * connection will always be created, and the new connection will
1851 * never be returned to other callers.
1853 * @param address the address
1854 * @param shared whether the connection is shared or private
1855 * @param error error return
1856 * @returns the connection or #NULL on error
1858 static DBusConnection*
1859 _dbus_connection_open_internal (const char *address,
1863 DBusConnection *connection;
1864 DBusAddressEntry **entries;
1865 DBusError tmp_error = DBUS_ERROR_INIT;
1866 DBusError first_error = DBUS_ERROR_INIT;
1869 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1871 _dbus_verbose ("opening %s connection to: %s\n",
1872 shared ? "shared" : "private", address);
1874 if (!dbus_parse_address (address, &entries, &len, error))
1877 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1881 for (i = 0; i < len; i++)
1885 if (!connection_lookup_shared (entries[i], &connection))
1886 _DBUS_SET_OOM (&tmp_error);
1889 if (connection == NULL)
1891 connection = connection_try_from_address_entry (entries[i],
1894 if (connection != NULL && shared)
1898 connection->shareable = TRUE;
1900 /* guid may be NULL */
1901 guid = dbus_address_entry_get_value (entries[i], "guid");
1903 CONNECTION_LOCK (connection);
1905 if (!connection_record_shared_unlocked (connection, guid))
1907 _DBUS_SET_OOM (&tmp_error);
1908 _dbus_connection_close_possibly_shared_and_unlock (connection);
1909 dbus_connection_unref (connection);
1913 CONNECTION_UNLOCK (connection);
1920 _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
1923 dbus_move_error (&tmp_error, &first_error);
1925 dbus_error_free (&tmp_error);
1928 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1929 _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
1931 if (connection == NULL)
1933 _DBUS_ASSERT_ERROR_IS_SET (&first_error);
1934 dbus_move_error (&first_error, error);
1937 dbus_error_free (&first_error);
1939 dbus_address_entries_free (entries);
1944 * Closes a shared OR private connection, while dbus_connection_close() can
1945 * only be used on private connections. Should only be called by the
1946 * dbus code that owns the connection - an owner must be known,
1947 * the open/close state is like malloc/free, not like ref/unref.
1949 * @param connection the connection
1952 _dbus_connection_close_possibly_shared (DBusConnection *connection)
1954 _dbus_assert (connection != NULL);
1955 _dbus_assert (connection->generation == _dbus_current_generation);
1957 CONNECTION_LOCK (connection);
1958 _dbus_connection_close_possibly_shared_and_unlock (connection);
1961 static DBusPreallocatedSend*
1962 _dbus_connection_preallocate_send_unlocked (DBusConnection *connection)
1964 DBusPreallocatedSend *preallocated;
1966 HAVE_LOCK_CHECK (connection);
1968 _dbus_assert (connection != NULL);
1970 preallocated = dbus_new (DBusPreallocatedSend, 1);
1971 if (preallocated == NULL)
1974 preallocated->queue_link = _dbus_list_alloc_link (NULL);
1975 if (preallocated->queue_link == NULL)
1978 preallocated->counter_link = _dbus_list_alloc_link (connection->outgoing_counter);
1979 if (preallocated->counter_link == NULL)
1982 _dbus_counter_ref (preallocated->counter_link->data);
1984 preallocated->connection = connection;
1986 return preallocated;
1989 _dbus_list_free_link (preallocated->queue_link);
1991 dbus_free (preallocated);
1996 unsigned int dbus_connection_get_is_kdbus(DBusConnection *connection)
1998 return connection->is_kdbus;
2001 void dbus_connection_set_is_kdbus(DBusConnection *connection, unsigned int value)
2003 connection->is_kdbus = value;
2006 /* Called with lock held, does not update dispatch status */
2008 _dbus_connection_send_preallocated_unlocked_no_update (DBusConnection *connection,
2009 DBusPreallocatedSend *preallocated,
2010 DBusMessage *message,
2011 dbus_uint32_t *client_serial)
2013 dbus_uint32_t serial;
2015 preallocated->queue_link->data = message;
2016 _dbus_list_prepend_link (&connection->outgoing_messages,
2017 preallocated->queue_link);
2019 /* It's OK that we'll never call the notify function, because for the
2020 * outgoing limit, there isn't one */
2021 _dbus_message_add_counter_link (message,
2022 preallocated->counter_link);
2024 dbus_free (preallocated);
2025 preallocated = NULL;
2027 dbus_message_ref (message);
2029 connection->n_outgoing += 1;
2031 _dbus_verbose ("Message %p (%s %s %s %s '%s') for %s added to outgoing queue %p, %d pending to send\n",
2033 dbus_message_type_to_string (dbus_message_get_type (message)),
2034 dbus_message_get_path (message) ?
2035 dbus_message_get_path (message) :
2037 dbus_message_get_interface (message) ?
2038 dbus_message_get_interface (message) :
2040 dbus_message_get_member (message) ?
2041 dbus_message_get_member (message) :
2043 dbus_message_get_signature (message),
2044 dbus_message_get_destination (message) ?
2045 dbus_message_get_destination (message) :
2048 connection->n_outgoing);
2050 if (dbus_message_get_serial (message) == 0)
2052 serial = _dbus_connection_get_next_client_serial (connection);
2053 dbus_message_set_serial (message, serial);
2055 *client_serial = serial;
2060 *client_serial = dbus_message_get_serial (message);
2063 _dbus_verbose ("Message %p serial is %u\n",
2064 message, dbus_message_get_serial (message));
2066 if(dbus_transport_is_kdbus(connection))
2071 name = dbus_bus_get_unique_name(connection);
2072 sender = malloc (strlen(name) + 4);
2075 strcpy(sender,":1.");
2076 strcpy(&sender[3], name);
2077 _dbus_verbose ("Message sender: %s\n", sender);
2078 dbus_message_set_sender(message, sender);
2079 free((void*)sender);
2083 dbus_message_lock (message);
2085 /* Now we need to run an iteration to hopefully just write the messages
2086 * out immediately, and otherwise get them queued up
2088 _dbus_connection_do_iteration_unlocked (connection,
2090 DBUS_ITERATION_DO_WRITING,
2093 /* If stuff is still queued up, be sure we wake up the main loop */
2094 if (connection->n_outgoing > 0)
2095 _dbus_connection_wakeup_mainloop (connection);
2099 _dbus_connection_send_preallocated_and_unlock (DBusConnection *connection,
2100 DBusPreallocatedSend *preallocated,
2101 DBusMessage *message,
2102 dbus_uint32_t *client_serial)
2104 DBusDispatchStatus status;
2106 HAVE_LOCK_CHECK (connection);
2108 _dbus_connection_send_preallocated_unlocked_no_update (connection,
2110 message, client_serial);
2112 _dbus_verbose ("middle\n");
2113 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2115 /* this calls out to user code */
2116 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2120 * Like dbus_connection_send(), but assumes the connection
2121 * is already locked on function entry, and unlocks before returning.
2123 * @param connection the connection
2124 * @param message the message to send
2125 * @param client_serial return location for client serial of sent message
2126 * @returns #FALSE on out-of-memory
2129 _dbus_connection_send_and_unlock (DBusConnection *connection,
2130 DBusMessage *message,
2131 dbus_uint32_t *client_serial)
2133 DBusPreallocatedSend *preallocated;
2135 _dbus_assert (connection != NULL);
2136 _dbus_assert (message != NULL);
2138 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
2139 if (preallocated == NULL)
2141 CONNECTION_UNLOCK (connection);
2145 _dbus_connection_send_preallocated_and_unlock (connection,
2153 * Used internally to handle the semantics of dbus_server_set_new_connection_function().
2154 * If the new connection function does not ref the connection, we want to close it.
2156 * A bit of a hack, probably the new connection function should have returned a value
2157 * for whether to close, or should have had to close the connection itself if it
2160 * But, this works OK as long as the new connection function doesn't do anything
2161 * crazy like keep the connection around without ref'ing it.
2163 * We have to lock the connection across refcount check and close in case
2164 * the new connection function spawns a thread that closes and unrefs.
2165 * In that case, if the app thread
2166 * closes and unrefs first, we'll harmlessly close again; if the app thread
2167 * still has the ref, we'll close and then the app will close harmlessly.
2168 * If the app unrefs without closing, the app is broken since if the
2169 * app refs from the new connection function it is supposed to also close.
2171 * If we didn't atomically check the refcount and close with the lock held
2172 * though, we could screw this up.
2174 * @param connection the connection
2177 _dbus_connection_close_if_only_one_ref (DBusConnection *connection)
2179 dbus_int32_t refcount;
2181 CONNECTION_LOCK (connection);
2183 refcount = _dbus_atomic_get (&connection->refcount);
2184 /* The caller should have at least one ref */
2185 _dbus_assert (refcount >= 1);
2188 _dbus_connection_close_possibly_shared_and_unlock (connection);
2190 CONNECTION_UNLOCK (connection);
2195 * When a function that blocks has been called with a timeout, and we
2196 * run out of memory, the time to wait for memory is based on the
2197 * timeout. If the caller was willing to block a long time we wait a
2198 * relatively long time for memory, if they were only willing to block
2199 * briefly then we retry for memory at a rapid rate.
2201 * @param timeout_milliseconds the timeout requested for blocking
2204 _dbus_memory_pause_based_on_timeout (int timeout_milliseconds)
2206 if (timeout_milliseconds == -1)
2207 _dbus_sleep_milliseconds (1000);
2208 else if (timeout_milliseconds < 100)
2209 ; /* just busy loop */
2210 else if (timeout_milliseconds <= 1000)
2211 _dbus_sleep_milliseconds (timeout_milliseconds / 3);
2213 _dbus_sleep_milliseconds (1000);
2217 generate_local_error_message (dbus_uint32_t serial,
2221 DBusMessage *message;
2222 message = dbus_message_new (DBUS_MESSAGE_TYPE_ERROR);
2226 if (!dbus_message_set_error_name (message, error_name))
2228 dbus_message_unref (message);
2233 dbus_message_set_no_reply (message, TRUE);
2235 if (!dbus_message_set_reply_serial (message,
2238 dbus_message_unref (message);
2243 if (error_msg != NULL)
2245 DBusMessageIter iter;
2247 dbus_message_iter_init_append (message, &iter);
2248 if (!dbus_message_iter_append_basic (&iter,
2252 dbus_message_unref (message);
2263 * Peek the incoming queue to see if we got reply for a specific serial
2266 _dbus_connection_peek_for_reply_unlocked (DBusConnection *connection,
2267 dbus_uint32_t client_serial)
2270 HAVE_LOCK_CHECK (connection);
2272 link = _dbus_list_get_first_link (&connection->incoming_messages);
2274 while (link != NULL)
2276 DBusMessage *reply = link->data;
2278 if (dbus_message_get_reply_serial (reply) == client_serial)
2280 _dbus_verbose ("%s reply to %d found in queue\n", _DBUS_FUNCTION_NAME, client_serial);
2283 link = _dbus_list_get_next_link (&connection->incoming_messages, link);
2289 /* This is slightly strange since we can pop a message here without
2290 * the dispatch lock.
2293 check_for_reply_unlocked (DBusConnection *connection,
2294 dbus_uint32_t client_serial)
2298 HAVE_LOCK_CHECK (connection);
2300 link = _dbus_list_get_first_link (&connection->incoming_messages);
2302 while (link != NULL)
2304 DBusMessage *reply = link->data;
2306 if (dbus_message_get_reply_serial (reply) == client_serial)
2308 _dbus_list_remove_link (&connection->incoming_messages, link);
2309 connection->n_incoming -= 1;
2312 link = _dbus_list_get_next_link (&connection->incoming_messages, link);
2319 connection_timeout_and_complete_all_pending_calls_unlocked (DBusConnection *connection)
2321 /* We can't iterate over the hash in the normal way since we'll be
2322 * dropping the lock for each item. So we restart the
2323 * iter each time as we drain the hash table.
2326 while (_dbus_hash_table_get_n_entries (connection->pending_replies) > 0)
2328 DBusPendingCall *pending;
2331 _dbus_hash_iter_init (connection->pending_replies, &iter);
2332 _dbus_hash_iter_next (&iter);
2334 pending = _dbus_hash_iter_get_value (&iter);
2335 _dbus_pending_call_ref_unlocked (pending);
2337 _dbus_pending_call_queue_timeout_error_unlocked (pending,
2340 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
2341 _dbus_connection_remove_timeout_unlocked (connection,
2342 _dbus_pending_call_get_timeout_unlocked (pending));
2343 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
2344 _dbus_hash_iter_remove_entry (&iter);
2346 _dbus_pending_call_unref_and_unlock (pending);
2347 CONNECTION_LOCK (connection);
2349 HAVE_LOCK_CHECK (connection);
2353 complete_pending_call_and_unlock (DBusConnection *connection,
2354 DBusPendingCall *pending,
2355 DBusMessage *message)
2357 _dbus_pending_call_set_reply_unlocked (pending, message);
2358 _dbus_pending_call_ref_unlocked (pending); /* in case there's no app with a ref held */
2359 _dbus_connection_detach_pending_call_and_unlock (connection, pending);
2361 /* Must be called unlocked since it invokes app callback */
2362 _dbus_pending_call_complete (pending);
2363 dbus_pending_call_unref (pending);
2367 check_for_reply_and_update_dispatch_unlocked (DBusConnection *connection,
2368 DBusPendingCall *pending)
2371 DBusDispatchStatus status;
2373 reply = check_for_reply_unlocked (connection,
2374 _dbus_pending_call_get_reply_serial_unlocked (pending));
2377 _dbus_verbose ("checked for reply\n");
2379 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): got reply\n");
2381 complete_pending_call_and_unlock (connection, pending, reply);
2382 dbus_message_unref (reply);
2384 CONNECTION_LOCK (connection);
2385 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2386 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2387 dbus_pending_call_unref (pending);
2396 * Blocks until a pending call times out or gets a reply.
2398 * Does not re-enter the main loop or run filter/path-registered
2399 * callbacks. The reply to the message will not be seen by
2402 * Returns immediately if pending call already got a reply.
2404 * @todo could use performance improvements (it keeps scanning
2405 * the whole message queue for example)
2407 * @param pending the pending call we block for a reply on
2410 _dbus_connection_block_pending_call (DBusPendingCall *pending)
2412 long start_tv_sec, start_tv_usec;
2413 long tv_sec, tv_usec;
2414 DBusDispatchStatus status;
2415 DBusConnection *connection;
2416 dbus_uint32_t client_serial;
2417 DBusTimeout *timeout;
2418 int timeout_milliseconds, elapsed_milliseconds;
2420 _dbus_assert (pending != NULL);
2422 if (dbus_pending_call_get_completed (pending))
2425 dbus_pending_call_ref (pending); /* necessary because the call could be canceled */
2427 connection = _dbus_pending_call_get_connection_and_lock (pending);
2429 /* Flush message queue - note, can affect dispatch status */
2430 _dbus_connection_flush_unlocked (connection);
2432 client_serial = _dbus_pending_call_get_reply_serial_unlocked (pending);
2434 /* note that timeout_milliseconds is limited to a smallish value
2435 * in _dbus_pending_call_new() so overflows aren't possible
2438 timeout = _dbus_pending_call_get_timeout_unlocked (pending);
2439 _dbus_get_monotonic_time (&start_tv_sec, &start_tv_usec);
2442 timeout_milliseconds = dbus_timeout_get_interval (timeout);
2444 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): will block %d milliseconds for reply serial %u from %ld sec %ld usec\n",
2445 timeout_milliseconds,
2447 start_tv_sec, start_tv_usec);
2451 timeout_milliseconds = -1;
2453 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): will block for reply serial %u\n", client_serial);
2456 /* check to see if we already got the data off the socket */
2457 /* from another blocked pending call */
2458 if (check_for_reply_and_update_dispatch_unlocked (connection, pending))
2461 /* Now we wait... */
2462 /* always block at least once as we know we don't have the reply yet */
2463 _dbus_connection_do_iteration_unlocked (connection,
2465 DBUS_ITERATION_DO_READING |
2466 DBUS_ITERATION_BLOCK,
2467 timeout_milliseconds);
2471 _dbus_verbose ("top of recheck\n");
2473 HAVE_LOCK_CHECK (connection);
2475 /* queue messages and get status */
2477 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2479 /* the get_completed() is in case a dispatch() while we were blocking
2480 * got the reply instead of us.
2482 if (_dbus_pending_call_get_completed_unlocked (pending))
2484 _dbus_verbose ("Pending call completed by dispatch\n");
2485 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2486 dbus_pending_call_unref (pending);
2490 if (status == DBUS_DISPATCH_DATA_REMAINS)
2492 if (check_for_reply_and_update_dispatch_unlocked (connection, pending))
2496 _dbus_get_monotonic_time (&tv_sec, &tv_usec);
2497 elapsed_milliseconds = (tv_sec - start_tv_sec) * 1000 +
2498 (tv_usec - start_tv_usec) / 1000;
2500 if (!_dbus_connection_get_is_connected_unlocked (connection))
2502 DBusMessage *error_msg;
2504 error_msg = generate_local_error_message (client_serial,
2505 DBUS_ERROR_DISCONNECTED,
2506 "Connection was disconnected before a reply was received");
2508 /* on OOM error_msg is set to NULL */
2509 complete_pending_call_and_unlock (connection, pending, error_msg);
2510 dbus_pending_call_unref (pending);
2513 else if (connection->disconnect_message_link == NULL)
2514 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): disconnected\n");
2515 else if (timeout == NULL)
2517 if (status == DBUS_DISPATCH_NEED_MEMORY)
2519 /* Try sleeping a bit, as we aren't sure we need to block for reading,
2520 * we may already have a reply in the buffer and just can't process
2523 _dbus_verbose ("dbus_connection_send_with_reply_and_block() waiting for more memory\n");
2525 _dbus_memory_pause_based_on_timeout (timeout_milliseconds - elapsed_milliseconds);
2529 /* block again, we don't have the reply buffered yet. */
2530 _dbus_connection_do_iteration_unlocked (connection,
2532 DBUS_ITERATION_DO_READING |
2533 DBUS_ITERATION_BLOCK,
2534 timeout_milliseconds - elapsed_milliseconds);
2537 goto recheck_status;
2539 else if (tv_sec < start_tv_sec)
2540 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): clock set backward\n");
2541 else if (elapsed_milliseconds < timeout_milliseconds)
2543 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): %d milliseconds remain\n", timeout_milliseconds - elapsed_milliseconds);
2545 if (status == DBUS_DISPATCH_NEED_MEMORY)
2547 /* Try sleeping a bit, as we aren't sure we need to block for reading,
2548 * we may already have a reply in the buffer and just can't process
2551 _dbus_verbose ("dbus_connection_send_with_reply_and_block() waiting for more memory\n");
2553 _dbus_memory_pause_based_on_timeout (timeout_milliseconds - elapsed_milliseconds);
2557 /* block again, we don't have the reply buffered yet. */
2558 _dbus_connection_do_iteration_unlocked (connection,
2560 DBUS_ITERATION_DO_READING |
2561 DBUS_ITERATION_BLOCK,
2562 timeout_milliseconds - elapsed_milliseconds);
2565 goto recheck_status;
2568 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): Waited %d milliseconds and got no reply\n",
2569 elapsed_milliseconds);
2571 _dbus_assert (!_dbus_pending_call_get_completed_unlocked (pending));
2573 /* unlock and call user code */
2574 complete_pending_call_and_unlock (connection, pending, NULL);
2576 /* update user code on dispatch status */
2577 CONNECTION_LOCK (connection);
2578 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2579 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2580 dbus_pending_call_unref (pending);
2586 * @addtogroup DBusConnection
2592 * Gets a connection to a remote address. If a connection to the given
2593 * address already exists, returns the existing connection with its
2594 * reference count incremented. Otherwise, returns a new connection
2595 * and saves the new connection for possible re-use if a future call
2596 * to dbus_connection_open() asks to connect to the same server.
2598 * Use dbus_connection_open_private() to get a dedicated connection
2599 * not shared with other callers of dbus_connection_open().
2601 * If the open fails, the function returns #NULL, and provides a
2602 * reason for the failure in the error parameter. Pass #NULL for the
2603 * error parameter if you aren't interested in the reason for
2606 * Because this connection is shared, no user of the connection
2607 * may call dbus_connection_close(). However, when you are done with the
2608 * connection you should call dbus_connection_unref().
2610 * @note Prefer dbus_connection_open() to dbus_connection_open_private()
2611 * unless you have good reason; connections are expensive enough
2612 * that it's wasteful to create lots of connections to the same
2615 * @param address the address.
2616 * @param error address where an error can be returned.
2617 * @returns new connection, or #NULL on failure.
2620 dbus_connection_open (const char *address,
2623 DBusConnection *connection;
2625 _dbus_return_val_if_fail (address != NULL, NULL);
2626 _dbus_return_val_if_error_is_set (error, NULL);
2628 connection = _dbus_connection_open_internal (address,
2636 * Opens a new, dedicated connection to a remote address. Unlike
2637 * dbus_connection_open(), always creates a new connection.
2638 * This connection will not be saved or recycled by libdbus.
2640 * If the open fails, the function returns #NULL, and provides a
2641 * reason for the failure in the error parameter. Pass #NULL for the
2642 * error parameter if you aren't interested in the reason for
2645 * When you are done with this connection, you must
2646 * dbus_connection_close() to disconnect it,
2647 * and dbus_connection_unref() to free the connection object.
2649 * (The dbus_connection_close() can be skipped if the
2650 * connection is already known to be disconnected, for example
2651 * if you are inside a handler for the Disconnected signal.)
2653 * @note Prefer dbus_connection_open() to dbus_connection_open_private()
2654 * unless you have good reason; connections are expensive enough
2655 * that it's wasteful to create lots of connections to the same
2658 * @param address the address.
2659 * @param error address where an error can be returned.
2660 * @returns new connection, or #NULL on failure.
2663 dbus_connection_open_private (const char *address,
2666 DBusConnection *connection;
2668 _dbus_return_val_if_fail (address != NULL, NULL);
2669 _dbus_return_val_if_error_is_set (error, NULL);
2671 connection = _dbus_connection_open_internal (address,
2679 * Increments the reference count of a DBusConnection.
2681 * @param connection the connection.
2682 * @returns the connection.
2685 dbus_connection_ref (DBusConnection *connection)
2687 dbus_int32_t old_refcount;
2689 _dbus_return_val_if_fail (connection != NULL, NULL);
2690 _dbus_return_val_if_fail (connection->generation == _dbus_current_generation, NULL);
2691 old_refcount = _dbus_atomic_inc (&connection->refcount);
2692 _dbus_connection_trace_ref (connection, old_refcount, old_refcount + 1,
2699 free_outgoing_message (void *element,
2702 DBusMessage *message = element;
2703 DBusConnection *connection = data;
2705 _dbus_message_remove_counter (message, connection->outgoing_counter);
2706 dbus_message_unref (message);
2709 /* This is run without the mutex held, but after the last reference
2710 * to the connection has been dropped we should have no thread-related
2714 _dbus_connection_last_unref (DBusConnection *connection)
2718 _dbus_verbose ("Finalizing connection %p\n", connection);
2720 _dbus_assert (_dbus_atomic_get (&connection->refcount) == 0);
2722 /* You have to disconnect the connection before unref:ing it. Otherwise
2723 * you won't get the disconnected message.
2725 _dbus_assert (!_dbus_transport_get_is_connected (connection->transport));
2726 _dbus_assert (connection->server_guid == NULL);
2728 /* ---- We're going to call various application callbacks here, hope it doesn't break anything... */
2729 _dbus_object_tree_free_all_unlocked (connection->objects);
2731 dbus_connection_set_dispatch_status_function (connection, NULL, NULL, NULL);
2732 dbus_connection_set_wakeup_main_function (connection, NULL, NULL, NULL);
2733 dbus_connection_set_unix_user_function (connection, NULL, NULL, NULL);
2734 dbus_connection_set_windows_user_function (connection, NULL, NULL, NULL);
2736 _dbus_watch_list_free (connection->watches);
2737 connection->watches = NULL;
2739 _dbus_timeout_list_free (connection->timeouts);
2740 connection->timeouts = NULL;
2742 _dbus_data_slot_list_free (&connection->slot_list);
2744 link = _dbus_list_get_first_link (&connection->filter_list);
2745 while (link != NULL)
2747 DBusMessageFilter *filter = link->data;
2748 DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
2750 filter->function = NULL;
2751 _dbus_message_filter_unref (filter); /* calls app callback */
2756 _dbus_list_clear (&connection->filter_list);
2758 /* ---- Done with stuff that invokes application callbacks */
2760 _dbus_object_tree_unref (connection->objects);
2762 _dbus_hash_table_unref (connection->pending_replies);
2763 connection->pending_replies = NULL;
2765 _dbus_list_clear (&connection->filter_list);
2767 _dbus_list_foreach (&connection->outgoing_messages,
2768 free_outgoing_message,
2770 _dbus_list_clear (&connection->outgoing_messages);
2772 _dbus_list_foreach (&connection->incoming_messages,
2773 (DBusForeachFunction) dbus_message_unref,
2775 _dbus_list_clear (&connection->incoming_messages);
2777 _dbus_counter_unref (connection->outgoing_counter);
2779 _dbus_transport_unref (connection->transport);
2781 if (connection->disconnect_message_link)
2783 DBusMessage *message = connection->disconnect_message_link->data;
2784 dbus_message_unref (message);
2785 _dbus_list_free_link (connection->disconnect_message_link);
2788 _dbus_condvar_free_at_location (&connection->dispatch_cond);
2789 _dbus_condvar_free_at_location (&connection->io_path_cond);
2791 _dbus_cmutex_free_at_location (&connection->io_path_mutex);
2792 _dbus_cmutex_free_at_location (&connection->dispatch_mutex);
2794 _dbus_rmutex_free_at_location (&connection->slot_mutex);
2796 _dbus_rmutex_free_at_location (&connection->mutex);
2798 dbus_free (connection);
2802 * Decrements the reference count of a DBusConnection, and finalizes
2803 * it if the count reaches zero.
2805 * Note: it is a bug to drop the last reference to a connection that
2806 * is still connected.
2808 * For shared connections, libdbus will own a reference
2809 * as long as the connection is connected, so you can know that either
2810 * you don't have the last reference, or it's OK to drop the last reference.
2811 * Most connections are shared. dbus_connection_open() and dbus_bus_get()
2812 * return shared connections.
2814 * For private connections, the creator of the connection must arrange for
2815 * dbus_connection_close() to be called prior to dropping the last reference.
2816 * Private connections come from dbus_connection_open_private() or dbus_bus_get_private().
2818 * @param connection the connection.
2821 dbus_connection_unref (DBusConnection *connection)
2823 dbus_int32_t old_refcount;
2825 _dbus_return_if_fail (connection != NULL);
2826 _dbus_return_if_fail (connection->generation == _dbus_current_generation);
2828 old_refcount = _dbus_atomic_dec (&connection->refcount);
2830 _dbus_connection_trace_ref (connection, old_refcount, old_refcount - 1,
2833 if (old_refcount == 1)
2835 #ifndef DBUS_DISABLE_CHECKS
2836 if (_dbus_transport_get_is_connected (connection->transport))
2838 _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",
2839 connection->shareable ?
2840 "Most likely, the application called unref() too many times and removed a reference belonging to libdbus, since this is a shared connection.\n" :
2841 "Most likely, the application was supposed to call dbus_connection_close(), since this is a private connection.\n");
2845 _dbus_connection_last_unref (connection);
2850 * Note that the transport can disconnect itself (other end drops us)
2851 * and in that case this function never runs. So this function must
2852 * not do anything more than disconnect the transport and update the
2855 * If the transport self-disconnects, then we assume someone will
2856 * dispatch the connection to cause the dispatch status update.
2859 _dbus_connection_close_possibly_shared_and_unlock (DBusConnection *connection)
2861 DBusDispatchStatus status;
2863 HAVE_LOCK_CHECK (connection);
2865 _dbus_verbose ("Disconnecting %p\n", connection);
2867 /* We need to ref because update_dispatch_status_and_unlock will unref
2868 * the connection if it was shared and libdbus was the only remaining
2871 _dbus_connection_ref_unlocked (connection);
2873 _dbus_transport_disconnect (connection->transport);
2875 /* This has the side effect of queuing the disconnect message link
2876 * (unless we don't have enough memory, possibly, so don't assert it).
2877 * After the disconnect message link is queued, dbus_bus_get/dbus_connection_open
2878 * should never again return the newly-disconnected connection.
2880 * However, we only unref the shared connection and exit_on_disconnect when
2881 * the disconnect message reaches the head of the message queue,
2882 * NOT when it's first queued.
2884 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2886 /* This calls out to user code */
2887 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2889 /* Could also call out to user code */
2890 dbus_connection_unref (connection);
2894 * Closes a private connection, so no further data can be sent or received.
2895 * This disconnects the transport (such as a socket) underlying the
2898 * Attempts to send messages after closing a connection are safe, but will result in
2899 * error replies generated locally in libdbus.
2901 * This function does not affect the connection's reference count. It's
2902 * safe to close a connection more than once; all calls after the
2903 * first do nothing. It's impossible to "reopen" a connection, a
2904 * new connection must be created. This function may result in a call
2905 * to the DBusDispatchStatusFunction set with
2906 * dbus_connection_set_dispatch_status_function(), as the disconnect
2907 * message it generates needs to be dispatched.
2909 * If a connection is dropped by the remote application, it will
2912 * You must close a connection prior to releasing the last reference to
2913 * the connection. If you dbus_connection_unref() for the last time
2914 * without closing the connection, the results are undefined; it
2915 * is a bug in your program and libdbus will try to print a warning.
2917 * You may not close a shared connection. Connections created with
2918 * dbus_connection_open() or dbus_bus_get() are shared.
2919 * These connections are owned by libdbus, and applications should
2920 * only unref them, never close them. Applications can know it is
2921 * safe to unref these connections because libdbus will be holding a
2922 * reference as long as the connection is open. Thus, either the
2923 * connection is closed and it is OK to drop the last reference,
2924 * or the connection is open and the app knows it does not have the
2927 * Connections created with dbus_connection_open_private() or
2928 * dbus_bus_get_private() are not kept track of or referenced by
2929 * libdbus. The creator of these connections is responsible for
2930 * calling dbus_connection_close() prior to releasing the last
2931 * reference, if the connection is not already disconnected.
2933 * @param connection the private (unshared) connection to close
2936 dbus_connection_close (DBusConnection *connection)
2938 _dbus_return_if_fail (connection != NULL);
2939 _dbus_return_if_fail (connection->generation == _dbus_current_generation);
2941 CONNECTION_LOCK (connection);
2943 #ifndef DBUS_DISABLE_CHECKS
2944 if (connection->shareable)
2946 CONNECTION_UNLOCK (connection);
2948 _dbus_warn_check_failed ("Applications must not close shared connections - see dbus_connection_close() docs. This is a bug in the application.\n");
2953 _dbus_connection_close_possibly_shared_and_unlock (connection);
2957 _dbus_connection_get_is_connected_unlocked (DBusConnection *connection)
2959 HAVE_LOCK_CHECK (connection);
2960 return _dbus_transport_get_is_connected (connection->transport);
2964 * Gets whether the connection is currently open. A connection may
2965 * become disconnected when the remote application closes its end, or
2966 * exits; a connection may also be disconnected with
2967 * dbus_connection_close().
2969 * There are not separate states for "closed" and "disconnected," the two
2970 * terms are synonymous. This function should really be called
2971 * get_is_open() but for historical reasons is not.
2973 * @param connection the connection.
2974 * @returns #TRUE if the connection is still alive.
2977 dbus_connection_get_is_connected (DBusConnection *connection)
2981 _dbus_return_val_if_fail (connection != NULL, FALSE);
2983 CONNECTION_LOCK (connection);
2984 res = _dbus_connection_get_is_connected_unlocked (connection);
2985 CONNECTION_UNLOCK (connection);
2991 * Gets whether the connection was authenticated. (Note that
2992 * if the connection was authenticated then disconnected,
2993 * this function still returns #TRUE)
2995 * @param connection the connection
2996 * @returns #TRUE if the connection was ever authenticated
2999 dbus_connection_get_is_authenticated (DBusConnection *connection)
3003 _dbus_return_val_if_fail (connection != NULL, FALSE);
3005 CONNECTION_LOCK (connection);
3006 res = _dbus_transport_try_to_authenticate (connection->transport);
3007 CONNECTION_UNLOCK (connection);
3013 * Sets authenticated status for connection. Needed for kdbus, where authentication is
3014 * made in different manner.
3016 * @param connection the connection
3019 dbus_connection_set_is_authenticated (DBusConnection *connection)
3021 _dbus_return_val_if_fail (connection != NULL, FALSE);
3023 CONNECTION_LOCK (connection);
3024 connection->transport->authenticated = TRUE;
3025 CONNECTION_UNLOCK (connection);
3031 * Gets whether the connection is not authenticated as a specific
3032 * user. If the connection is not authenticated, this function
3033 * returns #TRUE, and if it is authenticated but as an anonymous user,
3034 * it returns #TRUE. If it is authenticated as a specific user, then
3035 * this returns #FALSE. (Note that if the connection was authenticated
3036 * as anonymous then disconnected, this function still returns #TRUE.)
3038 * If the connection is not anonymous, you can use
3039 * dbus_connection_get_unix_user() and
3040 * dbus_connection_get_windows_user() to see who it's authorized as.
3042 * If you want to prevent non-anonymous authorization, use
3043 * dbus_server_set_auth_mechanisms() to remove the mechanisms that
3044 * allow proving user identity (i.e. only allow the ANONYMOUS
3047 * @param connection the connection
3048 * @returns #TRUE if not authenticated or authenticated as anonymous
3051 dbus_connection_get_is_anonymous (DBusConnection *connection)
3055 _dbus_return_val_if_fail (connection != NULL, FALSE);
3057 CONNECTION_LOCK (connection);
3058 res = _dbus_transport_get_is_anonymous (connection->transport);
3059 CONNECTION_UNLOCK (connection);
3065 * Gets the ID of the server address we are authenticated to, if this
3066 * connection is on the client side. If the connection is on the
3067 * server side, this will always return #NULL - use dbus_server_get_id()
3068 * to get the ID of your own server, if you are the server side.
3070 * If a client-side connection is not authenticated yet, the ID may be
3071 * available if it was included in the server address, but may not be
3072 * available. The only way to be sure the server ID is available
3073 * is to wait for authentication to complete.
3075 * In general, each mode of connecting to a given server will have
3076 * its own ID. So for example, if the session bus daemon is listening
3077 * on UNIX domain sockets and on TCP, then each of those modalities
3078 * will have its own server ID.
3080 * If you want an ID that identifies an entire session bus, look at
3081 * dbus_bus_get_id() instead (which is just a convenience wrapper
3082 * around the org.freedesktop.DBus.GetId method invoked on the bus).
3084 * You can also get a machine ID; see dbus_get_local_machine_id() to
3085 * get the machine you are on. There isn't a convenience wrapper, but
3086 * you can invoke org.freedesktop.DBus.Peer.GetMachineId on any peer
3087 * to get the machine ID on the other end.
3089 * The D-Bus specification describes the server ID and other IDs in a
3092 * @param connection the connection
3093 * @returns the server ID or #NULL if no memory or the connection is server-side
3096 dbus_connection_get_server_id (DBusConnection *connection)
3100 _dbus_return_val_if_fail (connection != NULL, NULL);
3102 CONNECTION_LOCK (connection);
3103 id = _dbus_strdup (_dbus_transport_get_server_id (connection->transport));
3104 CONNECTION_UNLOCK (connection);
3110 * Tests whether a certain type can be send via the connection. This
3111 * will always return TRUE for all types, with the exception of
3112 * DBUS_TYPE_UNIX_FD. The function will return TRUE for
3113 * DBUS_TYPE_UNIX_FD only on systems that know Unix file descriptors
3114 * and can send them via the chosen transport and when the remote side
3117 * This function can be used to do runtime checking for types that
3118 * might be unknown to the specific D-Bus client implementation
3119 * version, i.e. it will return FALSE for all types this
3120 * implementation does not know, including invalid or reserved types.
3122 * @param connection the connection
3123 * @param type the type to check
3124 * @returns TRUE if the type may be send via the connection
3127 dbus_connection_can_send_type(DBusConnection *connection,
3130 _dbus_return_val_if_fail (connection != NULL, FALSE);
3132 if (!dbus_type_is_valid (type))
3135 if (type != DBUS_TYPE_UNIX_FD)
3138 #ifdef HAVE_UNIX_FD_PASSING
3142 CONNECTION_LOCK(connection);
3143 b = _dbus_transport_can_pass_unix_fd(connection->transport);
3144 CONNECTION_UNLOCK(connection);
3154 * Set whether _exit() should be called when the connection receives a
3155 * disconnect signal. The call to _exit() comes after any handlers for
3156 * the disconnect signal run; handlers can cancel the exit by calling
3159 * By default, exit_on_disconnect is #FALSE; but for message bus
3160 * connections returned from dbus_bus_get() it will be toggled on
3163 * @param connection the connection
3164 * @param exit_on_disconnect #TRUE if _exit() should be called after a disconnect signal
3167 dbus_connection_set_exit_on_disconnect (DBusConnection *connection,
3168 dbus_bool_t exit_on_disconnect)
3170 _dbus_return_if_fail (connection != NULL);
3172 CONNECTION_LOCK (connection);
3173 connection->exit_on_disconnect = exit_on_disconnect != FALSE;
3174 CONNECTION_UNLOCK (connection);
3178 * Preallocates resources needed to send a message, allowing the message
3179 * to be sent without the possibility of memory allocation failure.
3180 * Allows apps to create a future guarantee that they can send
3181 * a message regardless of memory shortages.
3183 * @param connection the connection we're preallocating for.
3184 * @returns the preallocated resources, or #NULL
3186 DBusPreallocatedSend*
3187 dbus_connection_preallocate_send (DBusConnection *connection)
3189 DBusPreallocatedSend *preallocated;
3191 _dbus_return_val_if_fail (connection != NULL, NULL);
3193 CONNECTION_LOCK (connection);
3196 _dbus_connection_preallocate_send_unlocked (connection);
3198 CONNECTION_UNLOCK (connection);
3200 return preallocated;
3204 * Frees preallocated message-sending resources from
3205 * dbus_connection_preallocate_send(). Should only
3206 * be called if the preallocated resources are not used
3207 * to send a message.
3209 * @param connection the connection
3210 * @param preallocated the resources
3213 dbus_connection_free_preallocated_send (DBusConnection *connection,
3214 DBusPreallocatedSend *preallocated)
3216 _dbus_return_if_fail (connection != NULL);
3217 _dbus_return_if_fail (preallocated != NULL);
3218 _dbus_return_if_fail (connection == preallocated->connection);
3220 _dbus_list_free_link (preallocated->queue_link);
3221 _dbus_counter_unref (preallocated->counter_link->data);
3222 _dbus_list_free_link (preallocated->counter_link);
3223 dbus_free (preallocated);
3227 * Sends a message using preallocated resources. This function cannot fail.
3228 * It works identically to dbus_connection_send() in other respects.
3229 * Preallocated resources comes from dbus_connection_preallocate_send().
3230 * This function "consumes" the preallocated resources, they need not
3231 * be freed separately.
3233 * @param connection the connection
3234 * @param preallocated the preallocated resources
3235 * @param message the message to send
3236 * @param client_serial return location for client serial assigned to the message
3239 dbus_connection_send_preallocated (DBusConnection *connection,
3240 DBusPreallocatedSend *preallocated,
3241 DBusMessage *message,
3242 dbus_uint32_t *client_serial)
3244 _dbus_return_if_fail (connection != NULL);
3245 _dbus_return_if_fail (preallocated != NULL);
3246 _dbus_return_if_fail (message != NULL);
3247 _dbus_return_if_fail (preallocated->connection == connection);
3248 _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_METHOD_CALL ||
3249 dbus_message_get_member (message) != NULL);
3250 _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL ||
3251 (dbus_message_get_interface (message) != NULL &&
3252 dbus_message_get_member (message) != NULL));
3254 CONNECTION_LOCK (connection);
3256 #ifdef HAVE_UNIX_FD_PASSING
3258 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3259 message->n_unix_fds > 0)
3261 /* Refuse to send fds on a connection that cannot handle
3262 them. Unfortunately we cannot return a proper error here, so
3263 the best we can is just return. */
3264 CONNECTION_UNLOCK (connection);
3270 _dbus_connection_send_preallocated_and_unlock (connection,
3272 message, client_serial);
3276 _dbus_connection_send_unlocked_no_update (DBusConnection *connection,
3277 DBusMessage *message,
3278 dbus_uint32_t *client_serial)
3280 DBusPreallocatedSend *preallocated;
3282 _dbus_assert (connection != NULL);
3283 _dbus_assert (message != NULL);
3285 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
3286 if (preallocated == NULL)
3289 _dbus_connection_send_preallocated_unlocked_no_update (connection,
3297 * Adds a message to the outgoing message queue. Does not block to
3298 * write the message to the network; that happens asynchronously. To
3299 * force the message to be written, call dbus_connection_flush() however
3300 * it is not necessary to call dbus_connection_flush() by hand; the
3301 * message will be sent the next time the main loop is run.
3302 * dbus_connection_flush() should only be used, for example, if
3303 * the application was expected to exit before running the main loop.
3305 * Because this only queues the message, the only reason it can
3306 * fail is lack of memory. Even if the connection is disconnected,
3307 * no error will be returned. If the function fails due to lack of memory,
3308 * it returns #FALSE. The function will never fail for other reasons; even
3309 * if the connection is disconnected, you can queue an outgoing message,
3310 * though obviously it won't be sent.
3312 * The message serial is used by the remote application to send a
3313 * reply; see dbus_message_get_serial() or the D-Bus specification.
3315 * dbus_message_unref() can be called as soon as this method returns
3316 * as the message queue will hold its own ref until the message is sent.
3318 * @param connection the connection.
3319 * @param message the message to write.
3320 * @param serial return location for message serial, or #NULL if you don't care
3321 * @returns #TRUE on success.
3324 dbus_connection_send (DBusConnection *connection,
3325 DBusMessage *message,
3326 dbus_uint32_t *serial)
3328 _dbus_return_val_if_fail (connection != NULL, FALSE);
3329 _dbus_return_val_if_fail (message != NULL, FALSE);
3331 CONNECTION_LOCK (connection);
3333 #ifdef HAVE_UNIX_FD_PASSING
3335 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3336 message->n_unix_fds > 0)
3338 /* Refuse to send fds on a connection that cannot handle
3339 them. Unfortunately we cannot return a proper error here, so
3340 the best we can is just return. */
3341 CONNECTION_UNLOCK (connection);
3347 return _dbus_connection_send_and_unlock (connection,
3353 reply_handler_timeout (void *data)
3355 DBusConnection *connection;
3356 DBusDispatchStatus status;
3357 DBusPendingCall *pending = data;
3359 connection = _dbus_pending_call_get_connection_and_lock (pending);
3360 _dbus_connection_ref_unlocked (connection);
3362 _dbus_pending_call_queue_timeout_error_unlocked (pending,
3364 _dbus_connection_remove_timeout_unlocked (connection,
3365 _dbus_pending_call_get_timeout_unlocked (pending));
3366 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
3368 _dbus_verbose ("middle\n");
3369 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3371 /* Unlocks, and calls out to user code */
3372 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3373 dbus_connection_unref (connection);
3379 * Queues a message to send, as with dbus_connection_send(),
3380 * but also returns a #DBusPendingCall used to receive a reply to the
3381 * message. If no reply is received in the given timeout_milliseconds,
3382 * this function expires the pending reply and generates a synthetic
3383 * error reply (generated in-process, not by the remote application)
3384 * indicating that a timeout occurred.
3386 * A #DBusPendingCall will see a reply message before any filters or
3387 * registered object path handlers. See dbus_connection_dispatch() for
3388 * details on when handlers are run.
3390 * A #DBusPendingCall will always see exactly one reply message,
3391 * unless it's cancelled with dbus_pending_call_cancel().
3393 * If #NULL is passed for the pending_return, the #DBusPendingCall
3394 * will still be generated internally, and used to track
3395 * the message reply timeout. This means a timeout error will
3396 * occur if no reply arrives, unlike with dbus_connection_send().
3398 * If -1 is passed for the timeout, a sane default timeout is used. -1
3399 * is typically the best value for the timeout for this reason, unless
3400 * you want a very short or very long timeout. If #DBUS_TIMEOUT_INFINITE is
3401 * passed for the timeout, no timeout will be set and the call will block
3404 * @warning if the connection is disconnected or you try to send Unix
3405 * file descriptors on a connection that does not support them, the
3406 * #DBusPendingCall will be set to #NULL, so be careful with this.
3408 * @param connection the connection
3409 * @param message the message to send
3410 * @param pending_return return location for a #DBusPendingCall
3411 * object, or #NULL if connection is disconnected or when you try to
3412 * send Unix file descriptors on a connection that does not support
3414 * @param timeout_milliseconds timeout in milliseconds, -1 (or
3415 * #DBUS_TIMEOUT_USE_DEFAULT) for default or #DBUS_TIMEOUT_INFINITE for no
3417 * @returns #FALSE if no memory, #TRUE otherwise.
3421 dbus_connection_send_with_reply (DBusConnection *connection,
3422 DBusMessage *message,
3423 DBusPendingCall **pending_return,
3424 int timeout_milliseconds)
3426 DBusPendingCall *pending;
3427 dbus_int32_t serial = -1;
3428 DBusDispatchStatus status;
3430 _dbus_return_val_if_fail (connection != NULL, FALSE);
3431 _dbus_return_val_if_fail (message != NULL, FALSE);
3432 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3435 *pending_return = NULL;
3437 CONNECTION_LOCK (connection);
3439 #ifdef HAVE_UNIX_FD_PASSING
3441 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3442 message->n_unix_fds > 0)
3444 /* Refuse to send fds on a connection that cannot handle
3445 them. Unfortunately we cannot return a proper error here, so
3446 the best we can do is return TRUE but leave *pending_return
3448 CONNECTION_UNLOCK (connection);
3454 if (!_dbus_connection_get_is_connected_unlocked (connection))
3456 CONNECTION_UNLOCK (connection);
3461 pending = _dbus_pending_call_new_unlocked (connection,
3462 timeout_milliseconds,
3463 reply_handler_timeout);
3465 if (pending == NULL)
3467 CONNECTION_UNLOCK (connection);
3471 /* Assign a serial to the message */
3472 serial = dbus_message_get_serial (message);
3475 serial = _dbus_connection_get_next_client_serial (connection);
3476 dbus_message_set_serial (message, serial);
3479 if (!_dbus_pending_call_set_timeout_error_unlocked (pending, message, serial))
3482 /* Insert the serial in the pending replies hash;
3483 * hash takes a refcount on DBusPendingCall.
3484 * Also, add the timeout.
3486 if (!_dbus_connection_attach_pending_call_unlocked (connection,
3490 if (!_dbus_connection_send_unlocked_no_update (connection, message, NULL))
3492 _dbus_connection_detach_pending_call_and_unlock (connection,
3494 goto error_unlocked;
3498 *pending_return = pending; /* hand off refcount */
3501 _dbus_connection_detach_pending_call_unlocked (connection, pending);
3502 /* we still have a ref to the pending call in this case, we unref
3503 * after unlocking, below
3507 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3509 /* this calls out to user code */
3510 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3512 if (pending_return == NULL)
3513 dbus_pending_call_unref (pending);
3518 CONNECTION_UNLOCK (connection);
3520 dbus_pending_call_unref (pending);
3525 * Sends a message and blocks a certain time period while waiting for
3526 * a reply. This function does not reenter the main loop,
3527 * i.e. messages other than the reply are queued up but not
3528 * processed. This function is used to invoke method calls on a
3531 * If a normal reply is received, it is returned, and removed from the
3532 * incoming message queue. If it is not received, #NULL is returned
3533 * and the error is set to #DBUS_ERROR_NO_REPLY. If an error reply is
3534 * received, it is converted to a #DBusError and returned as an error,
3535 * then the reply message is deleted and #NULL is returned. If
3536 * something else goes wrong, result is set to whatever is
3537 * appropriate, such as #DBUS_ERROR_NO_MEMORY or
3538 * #DBUS_ERROR_DISCONNECTED.
3540 * @warning While this function blocks the calling thread will not be
3541 * processing the incoming message queue. This means you can end up
3542 * deadlocked if the application you're talking to needs you to reply
3543 * to a method. To solve this, either avoid the situation, block in a
3544 * separate thread from the main connection-dispatching thread, or use
3545 * dbus_pending_call_set_notify() to avoid blocking.
3547 * @param connection the connection
3548 * @param message the message to send
3549 * @param timeout_milliseconds timeout in milliseconds, -1 (or
3550 * #DBUS_TIMEOUT_USE_DEFAULT) for default or #DBUS_TIMEOUT_INFINITE for no
3552 * @param error return location for error message
3553 * @returns the message that is the reply or #NULL with an error code if the
3557 dbus_connection_send_with_reply_and_block (DBusConnection *connection,
3558 DBusMessage *message,
3559 int timeout_milliseconds,
3563 DBusPendingCall *pending;
3565 _dbus_return_val_if_fail (connection != NULL, NULL);
3566 _dbus_return_val_if_fail (message != NULL, NULL);
3567 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, NULL);
3568 _dbus_return_val_if_error_is_set (error, NULL);
3570 #ifdef HAVE_UNIX_FD_PASSING
3572 CONNECTION_LOCK (connection);
3573 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3574 message->n_unix_fds > 0)
3576 CONNECTION_UNLOCK (connection);
3577 dbus_set_error(error, DBUS_ERROR_FAILED, "Cannot send file descriptors on this connection.");
3580 CONNECTION_UNLOCK (connection);
3584 if (!dbus_connection_send_with_reply (connection, message,
3585 &pending, timeout_milliseconds))
3587 _DBUS_SET_OOM (error);
3591 if (pending == NULL)
3593 dbus_set_error (error, DBUS_ERROR_DISCONNECTED, "Connection is closed");
3597 dbus_pending_call_block (pending);
3599 reply = dbus_pending_call_steal_reply (pending);
3600 dbus_pending_call_unref (pending);
3602 /* call_complete_and_unlock() called from pending_call_block() should
3603 * always fill this in.
3605 _dbus_assert (reply != NULL);
3607 if (dbus_set_error_from_message (error, reply))
3609 dbus_message_unref (reply);
3617 * Blocks until the outgoing message queue is empty.
3618 * Assumes connection lock already held.
3620 * If you call this, you MUST call update_dispatch_status afterword...
3622 * @param connection the connection.
3624 static DBusDispatchStatus
3625 _dbus_connection_flush_unlocked (DBusConnection *connection)
3627 /* We have to specify DBUS_ITERATION_DO_READING here because
3628 * otherwise we could have two apps deadlock if they are both doing
3629 * a flush(), and the kernel buffers fill up. This could change the
3632 DBusDispatchStatus status;
3634 HAVE_LOCK_CHECK (connection);
3636 while (connection->n_outgoing > 0 &&
3637 _dbus_connection_get_is_connected_unlocked (connection))
3639 _dbus_verbose ("doing iteration in\n");
3640 HAVE_LOCK_CHECK (connection);
3641 _dbus_connection_do_iteration_unlocked (connection,
3643 DBUS_ITERATION_DO_READING |
3644 DBUS_ITERATION_DO_WRITING |
3645 DBUS_ITERATION_BLOCK,
3649 HAVE_LOCK_CHECK (connection);
3650 _dbus_verbose ("middle\n");
3651 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3653 HAVE_LOCK_CHECK (connection);
3658 * Blocks until the outgoing message queue is empty.
3660 * @param connection the connection.
3663 dbus_connection_flush (DBusConnection *connection)
3665 /* We have to specify DBUS_ITERATION_DO_READING here because
3666 * otherwise we could have two apps deadlock if they are both doing
3667 * a flush(), and the kernel buffers fill up. This could change the
3670 DBusDispatchStatus status;
3672 _dbus_return_if_fail (connection != NULL);
3674 CONNECTION_LOCK (connection);
3676 status = _dbus_connection_flush_unlocked (connection);
3678 HAVE_LOCK_CHECK (connection);
3679 /* Unlocks and calls out to user code */
3680 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3682 _dbus_verbose ("end\n");
3686 * This function implements dbus_connection_read_write_dispatch() and
3687 * dbus_connection_read_write() (they pass a different value for the
3688 * dispatch parameter).
3690 * @param connection the connection
3691 * @param timeout_milliseconds max time to block or -1 for infinite
3692 * @param dispatch dispatch new messages or leave them on the incoming queue
3693 * @returns #TRUE if the disconnect message has not been processed
3696 _dbus_connection_read_write_dispatch (DBusConnection *connection,
3697 int timeout_milliseconds,
3698 dbus_bool_t dispatch)
3700 DBusDispatchStatus dstatus;
3701 dbus_bool_t progress_possible;
3703 /* Need to grab a ref here in case we're a private connection and
3704 * the user drops the last ref in a handler we call; see bug
3705 * https://bugs.freedesktop.org/show_bug.cgi?id=15635
3707 dbus_connection_ref (connection);
3708 dstatus = dbus_connection_get_dispatch_status (connection);
3710 if (dispatch && dstatus == DBUS_DISPATCH_DATA_REMAINS)
3712 _dbus_verbose ("doing dispatch\n");
3713 dbus_connection_dispatch (connection);
3714 CONNECTION_LOCK (connection);
3716 else if (dstatus == DBUS_DISPATCH_NEED_MEMORY)
3718 _dbus_verbose ("pausing for memory\n");
3719 _dbus_memory_pause_based_on_timeout (timeout_milliseconds);
3720 CONNECTION_LOCK (connection);
3724 CONNECTION_LOCK (connection);
3725 if (_dbus_connection_get_is_connected_unlocked (connection))
3727 _dbus_verbose ("doing iteration\n");
3728 _dbus_connection_do_iteration_unlocked (connection,
3730 DBUS_ITERATION_DO_READING |
3731 DBUS_ITERATION_DO_WRITING |
3732 DBUS_ITERATION_BLOCK,
3733 timeout_milliseconds);
3737 HAVE_LOCK_CHECK (connection);
3738 /* If we can dispatch, we can make progress until the Disconnected message
3739 * has been processed; if we can only read/write, we can make progress
3740 * as long as the transport is open.
3743 progress_possible = connection->n_incoming != 0 ||
3744 connection->disconnect_message_link != NULL;
3746 progress_possible = _dbus_connection_get_is_connected_unlocked (connection);
3748 CONNECTION_UNLOCK (connection);
3750 dbus_connection_unref (connection);
3752 return progress_possible; /* TRUE if we can make more progress */
3757 * This function is intended for use with applications that don't want
3758 * to write a main loop and deal with #DBusWatch and #DBusTimeout. An
3759 * example usage would be:
3762 * while (dbus_connection_read_write_dispatch (connection, -1))
3763 * ; // empty loop body
3766 * In this usage you would normally have set up a filter function to look
3767 * at each message as it is dispatched. The loop terminates when the last
3768 * message from the connection (the disconnected signal) is processed.
3770 * If there are messages to dispatch, this function will
3771 * dbus_connection_dispatch() once, and return. If there are no
3772 * messages to dispatch, this function will block until it can read or
3773 * write, then read or write, then return.
3775 * The way to think of this function is that it either makes some sort
3776 * of progress, or it blocks. Note that, while it is blocked on I/O, it
3777 * cannot be interrupted (even by other threads), which makes this function
3778 * unsuitable for applications that do more than just react to received
3781 * The return value indicates whether the disconnect message has been
3782 * processed, NOT whether the connection is connected. This is
3783 * important because even after disconnecting, you want to process any
3784 * messages you received prior to the disconnect.
3786 * @param connection the connection
3787 * @param timeout_milliseconds max time to block or -1 for infinite
3788 * @returns #TRUE if the disconnect message has not been processed
3791 dbus_connection_read_write_dispatch (DBusConnection *connection,
3792 int timeout_milliseconds)
3794 _dbus_return_val_if_fail (connection != NULL, FALSE);
3795 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3796 return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, TRUE);
3800 * This function is intended for use with applications that don't want to
3801 * write a main loop and deal with #DBusWatch and #DBusTimeout. See also
3802 * dbus_connection_read_write_dispatch().
3804 * As long as the connection is open, this function will block until it can
3805 * read or write, then read or write, then return #TRUE.
3807 * If the connection is closed, the function returns #FALSE.
3809 * The return value indicates whether reading or writing is still
3810 * possible, i.e. whether the connection is connected.
3812 * Note that even after disconnection, messages may remain in the
3813 * incoming queue that need to be
3814 * processed. dbus_connection_read_write_dispatch() dispatches
3815 * incoming messages for you; with dbus_connection_read_write() you
3816 * have to arrange to drain the incoming queue yourself.
3818 * @param connection the connection
3819 * @param timeout_milliseconds max time to block or -1 for infinite
3820 * @returns #TRUE if still connected
3823 dbus_connection_read_write (DBusConnection *connection,
3824 int timeout_milliseconds)
3826 _dbus_return_val_if_fail (connection != NULL, FALSE);
3827 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3828 return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, FALSE);
3831 /* We need to call this anytime we pop the head of the queue, and then
3832 * update_dispatch_status_and_unlock needs to be called afterward
3833 * which will "process" the disconnected message and set
3834 * disconnected_message_processed.
3837 check_disconnected_message_arrived_unlocked (DBusConnection *connection,
3838 DBusMessage *head_of_queue)
3840 HAVE_LOCK_CHECK (connection);
3842 /* checking that the link is NULL is an optimization to avoid the is_signal call */
3843 if (connection->disconnect_message_link == NULL &&
3844 dbus_message_is_signal (head_of_queue,
3845 DBUS_INTERFACE_LOCAL,
3848 connection->disconnected_message_arrived = TRUE;
3853 * Returns the first-received message from the incoming message queue,
3854 * leaving it in the queue. If the queue is empty, returns #NULL.
3856 * The caller does not own a reference to the returned message, and
3857 * must either return it using dbus_connection_return_message() or
3858 * keep it after calling dbus_connection_steal_borrowed_message(). No
3859 * one can get at the message while its borrowed, so return it as
3860 * quickly as possible and don't keep a reference to it after
3861 * returning it. If you need to keep the message, make a copy of it.
3863 * dbus_connection_dispatch() will block if called while a borrowed
3864 * message is outstanding; only one piece of code can be playing with
3865 * the incoming queue at a time. This function will block if called
3866 * during a dbus_connection_dispatch().
3868 * @param connection the connection.
3869 * @returns next message in the incoming queue.
3872 dbus_connection_borrow_message (DBusConnection *connection)
3874 DBusDispatchStatus status;
3875 DBusMessage *message;
3877 _dbus_return_val_if_fail (connection != NULL, NULL);
3879 _dbus_verbose ("start\n");
3881 /* this is called for the side effect that it queues
3882 * up any messages from the transport
3884 status = dbus_connection_get_dispatch_status (connection);
3885 if (status != DBUS_DISPATCH_DATA_REMAINS)
3888 CONNECTION_LOCK (connection);
3890 _dbus_connection_acquire_dispatch (connection);
3892 /* While a message is outstanding, the dispatch lock is held */
3893 _dbus_assert (connection->message_borrowed == NULL);
3895 connection->message_borrowed = _dbus_list_get_first (&connection->incoming_messages);
3897 message = connection->message_borrowed;
3899 check_disconnected_message_arrived_unlocked (connection, message);
3901 /* Note that we KEEP the dispatch lock until the message is returned */
3902 if (message == NULL)
3903 _dbus_connection_release_dispatch (connection);
3905 CONNECTION_UNLOCK (connection);
3907 _dbus_message_trace_ref (message, -1, -1, "dbus_connection_borrow_message");
3909 /* We don't update dispatch status until it's returned or stolen */
3915 * Used to return a message after peeking at it using
3916 * dbus_connection_borrow_message(). Only called if
3917 * message from dbus_connection_borrow_message() was non-#NULL.
3919 * @param connection the connection
3920 * @param message the message from dbus_connection_borrow_message()
3923 dbus_connection_return_message (DBusConnection *connection,
3924 DBusMessage *message)
3926 DBusDispatchStatus status;
3928 _dbus_return_if_fail (connection != NULL);
3929 _dbus_return_if_fail (message != NULL);
3930 _dbus_return_if_fail (message == connection->message_borrowed);
3931 _dbus_return_if_fail (connection->dispatch_acquired);
3933 CONNECTION_LOCK (connection);
3935 _dbus_assert (message == connection->message_borrowed);
3937 connection->message_borrowed = NULL;
3939 _dbus_connection_release_dispatch (connection);
3941 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3942 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3944 _dbus_message_trace_ref (message, -1, -1, "dbus_connection_return_message");
3948 * Used to keep a message after peeking at it using
3949 * dbus_connection_borrow_message(). Before using this function, see
3950 * the caveats/warnings in the documentation for
3951 * dbus_connection_pop_message().
3953 * @param connection the connection
3954 * @param message the message from dbus_connection_borrow_message()
3957 dbus_connection_steal_borrowed_message (DBusConnection *connection,
3958 DBusMessage *message)
3960 DBusMessage *pop_message;
3961 DBusDispatchStatus status;
3963 _dbus_return_if_fail (connection != NULL);
3964 _dbus_return_if_fail (message != NULL);
3965 _dbus_return_if_fail (message == connection->message_borrowed);
3966 _dbus_return_if_fail (connection->dispatch_acquired);
3968 CONNECTION_LOCK (connection);
3970 _dbus_assert (message == connection->message_borrowed);
3972 pop_message = _dbus_list_pop_first (&connection->incoming_messages);
3973 _dbus_assert (message == pop_message);
3974 (void) pop_message; /* unused unless asserting */
3976 connection->n_incoming -= 1;
3978 _dbus_verbose ("Incoming message %p stolen from queue, %d incoming\n",
3979 message, connection->n_incoming);
3981 connection->message_borrowed = NULL;
3983 _dbus_connection_release_dispatch (connection);
3985 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3986 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3987 _dbus_message_trace_ref (message, -1, -1,
3988 "dbus_connection_steal_borrowed_message");
3991 /* See dbus_connection_pop_message, but requires the caller to own
3992 * the lock before calling. May drop the lock while running.
3995 _dbus_connection_pop_message_link_unlocked (DBusConnection *connection)
3997 HAVE_LOCK_CHECK (connection);
3999 _dbus_assert (connection->message_borrowed == NULL);
4001 if (connection->n_incoming > 0)
4005 link = _dbus_list_pop_first_link (&connection->incoming_messages);
4006 connection->n_incoming -= 1;
4008 _dbus_verbose ("Message %p (%s %s %s %s sig:'%s' serial:%u) removed from incoming queue %p, %d incoming\n",
4010 dbus_message_type_to_string (dbus_message_get_type (link->data)),
4011 dbus_message_get_path (link->data) ?
4012 dbus_message_get_path (link->data) :
4014 dbus_message_get_interface (link->data) ?
4015 dbus_message_get_interface (link->data) :
4017 dbus_message_get_member (link->data) ?
4018 dbus_message_get_member (link->data) :
4020 dbus_message_get_signature (link->data),
4021 dbus_message_get_serial (link->data),
4022 connection, connection->n_incoming);
4024 _dbus_message_trace_ref (link->data, -1, -1,
4025 "_dbus_connection_pop_message_link_unlocked");
4027 check_disconnected_message_arrived_unlocked (connection, link->data);
4035 /* See dbus_connection_pop_message, but requires the caller to own
4036 * the lock before calling. May drop the lock while running.
4039 _dbus_connection_pop_message_unlocked (DBusConnection *connection)
4043 HAVE_LOCK_CHECK (connection);
4045 link = _dbus_connection_pop_message_link_unlocked (connection);
4049 DBusMessage *message;
4051 message = link->data;
4053 _dbus_list_free_link (link);
4062 _dbus_connection_putback_message_link_unlocked (DBusConnection *connection,
4063 DBusList *message_link)
4065 HAVE_LOCK_CHECK (connection);
4067 _dbus_assert (message_link != NULL);
4068 /* You can't borrow a message while a link is outstanding */
4069 _dbus_assert (connection->message_borrowed == NULL);
4070 /* We had to have the dispatch lock across the pop/putback */
4071 _dbus_assert (connection->dispatch_acquired);
4073 _dbus_list_prepend_link (&connection->incoming_messages,
4075 connection->n_incoming += 1;
4077 _dbus_verbose ("Message %p (%s %s %s '%s') put back into queue %p, %d incoming\n",
4079 dbus_message_type_to_string (dbus_message_get_type (message_link->data)),
4080 dbus_message_get_interface (message_link->data) ?
4081 dbus_message_get_interface (message_link->data) :
4083 dbus_message_get_member (message_link->data) ?
4084 dbus_message_get_member (message_link->data) :
4086 dbus_message_get_signature (message_link->data),
4087 connection, connection->n_incoming);
4089 _dbus_message_trace_ref (message_link->data, -1, -1,
4090 "_dbus_connection_putback_message_link_unlocked");
4094 * Returns the first-received message from the incoming message queue,
4095 * removing it from the queue. The caller owns a reference to the
4096 * returned message. If the queue is empty, returns #NULL.
4098 * This function bypasses any message handlers that are registered,
4099 * and so using it is usually wrong. Instead, let the main loop invoke
4100 * dbus_connection_dispatch(). Popping messages manually is only
4101 * useful in very simple programs that don't share a #DBusConnection
4102 * with any libraries or other modules.
4104 * There is a lock that covers all ways of accessing the incoming message
4105 * queue, so dbus_connection_dispatch(), dbus_connection_pop_message(),
4106 * dbus_connection_borrow_message(), etc. will all block while one of the others
4107 * in the group is running.
4109 * @param connection the connection.
4110 * @returns next message in the incoming queue.
4113 dbus_connection_pop_message (DBusConnection *connection)
4115 DBusMessage *message;
4116 DBusDispatchStatus status;
4118 _dbus_verbose ("start\n");
4120 /* this is called for the side effect that it queues
4121 * up any messages from the transport
4123 status = dbus_connection_get_dispatch_status (connection);
4124 if (status != DBUS_DISPATCH_DATA_REMAINS)
4127 CONNECTION_LOCK (connection);
4128 _dbus_connection_acquire_dispatch (connection);
4129 HAVE_LOCK_CHECK (connection);
4131 message = _dbus_connection_pop_message_unlocked (connection);
4133 _dbus_verbose ("Returning popped message %p\n", message);
4135 _dbus_connection_release_dispatch (connection);
4137 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4138 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4144 * Acquire the dispatcher. This is a separate lock so the main
4145 * connection lock can be dropped to call out to application dispatch
4148 * @param connection the connection.
4151 _dbus_connection_acquire_dispatch (DBusConnection *connection)
4153 HAVE_LOCK_CHECK (connection);
4155 _dbus_connection_ref_unlocked (connection);
4156 CONNECTION_UNLOCK (connection);
4158 _dbus_verbose ("locking dispatch_mutex\n");
4159 _dbus_cmutex_lock (connection->dispatch_mutex);
4161 while (connection->dispatch_acquired)
4163 _dbus_verbose ("waiting for dispatch to be acquirable\n");
4164 _dbus_condvar_wait (connection->dispatch_cond,
4165 connection->dispatch_mutex);
4168 _dbus_assert (!connection->dispatch_acquired);
4170 connection->dispatch_acquired = TRUE;
4172 _dbus_verbose ("unlocking dispatch_mutex\n");
4173 _dbus_cmutex_unlock (connection->dispatch_mutex);
4175 CONNECTION_LOCK (connection);
4176 _dbus_connection_unref_unlocked (connection);
4180 * Release the dispatcher when you're done with it. Only call
4181 * after you've acquired the dispatcher. Wakes up at most one
4182 * thread currently waiting to acquire the dispatcher.
4184 * @param connection the connection.
4187 _dbus_connection_release_dispatch (DBusConnection *connection)
4189 HAVE_LOCK_CHECK (connection);
4191 _dbus_verbose ("locking dispatch_mutex\n");
4192 _dbus_cmutex_lock (connection->dispatch_mutex);
4194 _dbus_assert (connection->dispatch_acquired);
4196 connection->dispatch_acquired = FALSE;
4197 _dbus_condvar_wake_one (connection->dispatch_cond);
4199 _dbus_verbose ("unlocking dispatch_mutex\n");
4200 _dbus_cmutex_unlock (connection->dispatch_mutex);
4204 _dbus_connection_failed_pop (DBusConnection *connection,
4205 DBusList *message_link)
4207 _dbus_list_prepend_link (&connection->incoming_messages,
4209 connection->n_incoming += 1;
4212 /* Note this may be called multiple times since we don't track whether we already did it */
4214 notify_disconnected_unlocked (DBusConnection *connection)
4216 HAVE_LOCK_CHECK (connection);
4218 /* Set the weakref in dbus-bus.c to NULL, so nobody will get a disconnected
4219 * connection from dbus_bus_get(). We make the same guarantee for
4220 * dbus_connection_open() but in a different way since we don't want to
4221 * unref right here; we instead check for connectedness before returning
4222 * the connection from the hash.
4224 _dbus_bus_notify_shared_connection_disconnected_unlocked (connection);
4226 /* Dump the outgoing queue, we aren't going to be able to
4227 * send it now, and we'd like accessors like
4228 * dbus_connection_get_outgoing_size() to be accurate.
4230 if (connection->n_outgoing > 0)
4234 _dbus_verbose ("Dropping %d outgoing messages since we're disconnected\n",
4235 connection->n_outgoing);
4237 while ((link = _dbus_list_get_last_link (&connection->outgoing_messages)))
4239 _dbus_connection_message_sent_unlocked (connection, link->data);
4244 /* Note this may be called multiple times since we don't track whether we already did it */
4245 static DBusDispatchStatus
4246 notify_disconnected_and_dispatch_complete_unlocked (DBusConnection *connection)
4248 HAVE_LOCK_CHECK (connection);
4250 if (connection->disconnect_message_link != NULL)
4252 _dbus_verbose ("Sending disconnect message\n");
4254 /* If we have pending calls, queue their timeouts - we want the Disconnected
4255 * to be the last message, after these timeouts.
4257 connection_timeout_and_complete_all_pending_calls_unlocked (connection);
4259 /* We haven't sent the disconnect message already,
4260 * and all real messages have been queued up.
4262 _dbus_connection_queue_synthesized_message_link (connection,
4263 connection->disconnect_message_link);
4264 connection->disconnect_message_link = NULL;
4266 return DBUS_DISPATCH_DATA_REMAINS;
4269 return DBUS_DISPATCH_COMPLETE;
4272 static DBusDispatchStatus
4273 _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection)
4275 HAVE_LOCK_CHECK (connection);
4277 if (connection->n_incoming > 0)
4278 return DBUS_DISPATCH_DATA_REMAINS;
4279 else if (!_dbus_transport_queue_messages (connection->transport))
4280 return DBUS_DISPATCH_NEED_MEMORY;
4283 DBusDispatchStatus status;
4284 dbus_bool_t is_connected;
4286 status = _dbus_transport_get_dispatch_status (connection->transport);
4287 is_connected = _dbus_transport_get_is_connected (connection->transport);
4289 _dbus_verbose ("dispatch status = %s is_connected = %d\n",
4290 DISPATCH_STATUS_NAME (status), is_connected);
4294 /* It's possible this would be better done by having an explicit
4295 * notification from _dbus_transport_disconnect() that would
4296 * synchronously do this, instead of waiting for the next dispatch
4297 * status check. However, probably not good to change until it causes
4300 notify_disconnected_unlocked (connection);
4302 /* I'm not sure this is needed; the idea is that we want to
4303 * queue the Disconnected only after we've read all the
4304 * messages, but if we're disconnected maybe we are guaranteed
4305 * to have read them all ?
4307 if (status == DBUS_DISPATCH_COMPLETE)
4308 status = notify_disconnected_and_dispatch_complete_unlocked (connection);
4311 if (status != DBUS_DISPATCH_COMPLETE)
4313 else if (connection->n_incoming > 0)
4314 return DBUS_DISPATCH_DATA_REMAINS;
4316 return DBUS_DISPATCH_COMPLETE;
4321 _dbus_connection_update_dispatch_status_and_unlock (DBusConnection *connection,
4322 DBusDispatchStatus new_status)
4324 dbus_bool_t changed;
4325 DBusDispatchStatusFunction function;
4328 HAVE_LOCK_CHECK (connection);
4330 _dbus_connection_ref_unlocked (connection);
4332 changed = new_status != connection->last_dispatch_status;
4334 connection->last_dispatch_status = new_status;
4336 function = connection->dispatch_status_function;
4337 data = connection->dispatch_status_data;
4339 if (connection->disconnected_message_arrived &&
4340 !connection->disconnected_message_processed)
4342 connection->disconnected_message_processed = TRUE;
4344 /* this does an unref, but we have a ref
4345 * so we should not run the finalizer here
4348 connection_forget_shared_unlocked (connection);
4350 if (connection->exit_on_disconnect)
4352 CONNECTION_UNLOCK (connection);
4354 _dbus_verbose ("Exiting on Disconnected signal\n");
4356 _dbus_assert_not_reached ("Call to exit() returned");
4360 /* We drop the lock */
4361 CONNECTION_UNLOCK (connection);
4363 if (changed && function)
4365 _dbus_verbose ("Notifying of change to dispatch status of %p now %d (%s)\n",
4366 connection, new_status,
4367 DISPATCH_STATUS_NAME (new_status));
4368 (* function) (connection, new_status, data);
4371 dbus_connection_unref (connection);
4375 * Gets the current state of the incoming message queue.
4376 * #DBUS_DISPATCH_DATA_REMAINS indicates that the message queue
4377 * may contain messages. #DBUS_DISPATCH_COMPLETE indicates that the
4378 * incoming queue is empty. #DBUS_DISPATCH_NEED_MEMORY indicates that
4379 * there could be data, but we can't know for sure without more
4382 * To process the incoming message queue, use dbus_connection_dispatch()
4383 * or (in rare cases) dbus_connection_pop_message().
4385 * Note, #DBUS_DISPATCH_DATA_REMAINS really means that either we
4386 * have messages in the queue, or we have raw bytes buffered up
4387 * that need to be parsed. When these bytes are parsed, they
4388 * may not add up to an entire message. Thus, it's possible
4389 * to see a status of #DBUS_DISPATCH_DATA_REMAINS but not
4390 * have a message yet.
4392 * In particular this happens on initial connection, because all sorts
4393 * of authentication protocol stuff has to be parsed before the
4394 * first message arrives.
4396 * @param connection the connection.
4397 * @returns current dispatch status
4400 dbus_connection_get_dispatch_status (DBusConnection *connection)
4402 DBusDispatchStatus status;
4404 _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
4406 _dbus_verbose ("start\n");
4408 CONNECTION_LOCK (connection);
4410 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4412 CONNECTION_UNLOCK (connection);
4418 * Filter funtion for handling the Peer standard interface.
4420 static DBusHandlerResult
4421 _dbus_connection_peer_filter_unlocked_no_update (DBusConnection *connection,
4422 DBusMessage *message)
4424 dbus_bool_t sent = FALSE;
4425 DBusMessage *ret = NULL;
4426 DBusList *expire_link;
4428 if (connection->route_peer_messages && dbus_message_get_destination (message) != NULL)
4430 /* This means we're letting the bus route this message */
4431 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4434 if (!dbus_message_has_interface (message, DBUS_INTERFACE_PEER))
4436 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4439 /* Preallocate a linked-list link, so that if we need to dispose of a
4440 * message, we can attach it to the expired list */
4441 expire_link = _dbus_list_alloc_link (NULL);
4444 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4446 if (dbus_message_is_method_call (message,
4447 DBUS_INTERFACE_PEER,
4450 ret = dbus_message_new_method_return (message);
4454 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4456 else if (dbus_message_is_method_call (message,
4457 DBUS_INTERFACE_PEER,
4462 ret = dbus_message_new_method_return (message);
4466 _dbus_string_init (&uuid);
4467 if (_dbus_get_local_machine_uuid_encoded (&uuid))
4469 const char *v_STRING = _dbus_string_get_const_data (&uuid);
4470 if (dbus_message_append_args (ret,
4471 DBUS_TYPE_STRING, &v_STRING,
4474 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4477 _dbus_string_free (&uuid);
4481 /* We need to bounce anything else with this interface, otherwise apps
4482 * could start extending the interface and when we added extensions
4483 * here to DBusConnection we'd break those apps.
4485 ret = dbus_message_new_error (message,
4486 DBUS_ERROR_UNKNOWN_METHOD,
4487 "Unknown method invoked on org.freedesktop.DBus.Peer interface");
4491 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4497 _dbus_list_free_link (expire_link);
4501 /* It'll be safe to unref the reply when we unlock */
4502 expire_link->data = ret;
4503 _dbus_list_prepend_link (&connection->expired_messages, expire_link);
4507 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4509 return DBUS_HANDLER_RESULT_HANDLED;
4513 * Processes all builtin filter functions
4515 * If the spec specifies a standard interface
4516 * they should be processed from this method
4518 static DBusHandlerResult
4519 _dbus_connection_run_builtin_filters_unlocked_no_update (DBusConnection *connection,
4520 DBusMessage *message)
4522 /* We just run one filter for now but have the option to run more
4523 if the spec calls for it in the future */
4525 return _dbus_connection_peer_filter_unlocked_no_update (connection, message);
4529 * Processes any incoming data.
4531 * If there's incoming raw data that has not yet been parsed, it is
4532 * parsed, which may or may not result in adding messages to the
4535 * The incoming data buffer is filled when the connection reads from
4536 * its underlying transport (such as a socket). Reading usually
4537 * happens in dbus_watch_handle() or dbus_connection_read_write().
4539 * If there are complete messages in the incoming queue,
4540 * dbus_connection_dispatch() removes one message from the queue and
4541 * processes it. Processing has three steps.
4543 * First, any method replies are passed to #DBusPendingCall or
4544 * dbus_connection_send_with_reply_and_block() in order to
4545 * complete the pending method call.
4547 * Second, any filters registered with dbus_connection_add_filter()
4548 * are run. If any filter returns #DBUS_HANDLER_RESULT_HANDLED
4549 * then processing stops after that filter.
4551 * Third, if the message is a method call it is forwarded to
4552 * any registered object path handlers added with
4553 * dbus_connection_register_object_path() or
4554 * dbus_connection_register_fallback().
4556 * A single call to dbus_connection_dispatch() will process at most
4557 * one message; it will not clear the entire message queue.
4559 * Be careful about calling dbus_connection_dispatch() from inside a
4560 * message handler, i.e. calling dbus_connection_dispatch()
4561 * recursively. If threads have been initialized with a recursive
4562 * mutex function, then this will not deadlock; however, it can
4563 * certainly confuse your application.
4565 * @todo some FIXME in here about handling DBUS_HANDLER_RESULT_NEED_MEMORY
4567 * @param connection the connection
4568 * @returns dispatch status, see dbus_connection_get_dispatch_status()
4571 dbus_connection_dispatch (DBusConnection *connection)
4573 DBusMessage *message;
4574 DBusList *link, *filter_list_copy, *message_link;
4575 DBusHandlerResult result;
4576 DBusPendingCall *pending;
4577 dbus_int32_t reply_serial;
4578 DBusDispatchStatus status;
4579 dbus_bool_t found_object;
4581 _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
4583 _dbus_verbose ("\n");
4585 CONNECTION_LOCK (connection);
4586 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4587 if (status != DBUS_DISPATCH_DATA_REMAINS)
4589 /* unlocks and calls out to user code */
4590 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4594 /* We need to ref the connection since the callback could potentially
4595 * drop the last ref to it
4597 _dbus_connection_ref_unlocked (connection);
4599 _dbus_connection_acquire_dispatch (connection);
4600 HAVE_LOCK_CHECK (connection);
4602 message_link = _dbus_connection_pop_message_link_unlocked (connection);
4603 if (message_link == NULL)
4605 /* another thread dispatched our stuff */
4607 _dbus_verbose ("another thread dispatched message (during acquire_dispatch above)\n");
4609 _dbus_connection_release_dispatch (connection);
4611 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4613 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4615 dbus_connection_unref (connection);
4620 message = message_link->data;
4622 _dbus_verbose (" dispatching message %p (%s %s %s '%s')\n",
4624 dbus_message_type_to_string (dbus_message_get_type (message)),
4625 dbus_message_get_interface (message) ?
4626 dbus_message_get_interface (message) :
4628 dbus_message_get_member (message) ?
4629 dbus_message_get_member (message) :
4631 dbus_message_get_signature (message));
4633 result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4635 /* Pending call handling must be first, because if you do
4636 * dbus_connection_send_with_reply_and_block() or
4637 * dbus_pending_call_block() then no handlers/filters will be run on
4638 * the reply. We want consistent semantics in the case where we
4639 * dbus_connection_dispatch() the reply.
4642 reply_serial = dbus_message_get_reply_serial (message);
4643 pending = _dbus_hash_table_lookup_int (connection->pending_replies,
4647 _dbus_verbose ("Dispatching a pending reply\n");
4648 complete_pending_call_and_unlock (connection, pending, message);
4649 pending = NULL; /* it's probably unref'd */
4651 CONNECTION_LOCK (connection);
4652 _dbus_verbose ("pending call completed in dispatch\n");
4653 result = DBUS_HANDLER_RESULT_HANDLED;
4657 result = _dbus_connection_run_builtin_filters_unlocked_no_update (connection, message);
4658 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4661 if (!_dbus_list_copy (&connection->filter_list, &filter_list_copy))
4663 _dbus_connection_release_dispatch (connection);
4664 HAVE_LOCK_CHECK (connection);
4666 _dbus_connection_failed_pop (connection, message_link);
4668 /* unlocks and calls user code */
4669 _dbus_connection_update_dispatch_status_and_unlock (connection,
4670 DBUS_DISPATCH_NEED_MEMORY);
4671 dbus_connection_unref (connection);
4673 return DBUS_DISPATCH_NEED_MEMORY;
4676 _dbus_list_foreach (&filter_list_copy,
4677 (DBusForeachFunction)_dbus_message_filter_ref,
4680 /* We're still protected from dispatch() reentrancy here
4681 * since we acquired the dispatcher
4683 CONNECTION_UNLOCK (connection);
4685 link = _dbus_list_get_first_link (&filter_list_copy);
4686 while (link != NULL)
4688 DBusMessageFilter *filter = link->data;
4689 DBusList *next = _dbus_list_get_next_link (&filter_list_copy, link);
4691 if (filter->function == NULL)
4693 _dbus_verbose (" filter was removed in a callback function\n");
4698 _dbus_verbose (" running filter on message %p\n", message);
4699 result = (* filter->function) (connection, message, filter->user_data);
4701 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4707 _dbus_list_foreach (&filter_list_copy,
4708 (DBusForeachFunction)_dbus_message_filter_unref,
4710 _dbus_list_clear (&filter_list_copy);
4712 CONNECTION_LOCK (connection);
4714 if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
4716 _dbus_verbose ("No memory\n");
4719 else if (result == DBUS_HANDLER_RESULT_HANDLED)
4721 _dbus_verbose ("filter handled message in dispatch\n");
4725 /* We're still protected from dispatch() reentrancy here
4726 * since we acquired the dispatcher
4728 _dbus_verbose (" running object path dispatch on message %p (%s %s %s '%s')\n",
4730 dbus_message_type_to_string (dbus_message_get_type (message)),
4731 dbus_message_get_interface (message) ?
4732 dbus_message_get_interface (message) :
4734 dbus_message_get_member (message) ?
4735 dbus_message_get_member (message) :
4737 dbus_message_get_signature (message));
4739 HAVE_LOCK_CHECK (connection);
4740 result = _dbus_object_tree_dispatch_and_unlock (connection->objects,
4744 CONNECTION_LOCK (connection);
4746 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4748 _dbus_verbose ("object tree handled message in dispatch\n");
4752 if (dbus_message_get_type (message) == DBUS_MESSAGE_TYPE_METHOD_CALL)
4756 DBusPreallocatedSend *preallocated;
4757 DBusList *expire_link;
4759 _dbus_verbose (" sending error %s\n",
4760 DBUS_ERROR_UNKNOWN_METHOD);
4762 if (!_dbus_string_init (&str))
4764 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4765 _dbus_verbose ("no memory for error string in dispatch\n");
4769 if (!_dbus_string_append_printf (&str,
4770 "Method \"%s\" with signature \"%s\" on interface \"%s\" doesn't exist\n",
4771 dbus_message_get_member (message),
4772 dbus_message_get_signature (message),
4773 dbus_message_get_interface (message)))
4775 _dbus_string_free (&str);
4776 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4777 _dbus_verbose ("no memory for error string in dispatch\n");
4781 reply = dbus_message_new_error (message,
4782 found_object ? DBUS_ERROR_UNKNOWN_METHOD : DBUS_ERROR_UNKNOWN_OBJECT,
4783 _dbus_string_get_const_data (&str));
4784 _dbus_string_free (&str);
4788 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4789 _dbus_verbose ("no memory for error reply in dispatch\n");
4793 expire_link = _dbus_list_alloc_link (reply);
4795 if (expire_link == NULL)
4797 dbus_message_unref (reply);
4798 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4799 _dbus_verbose ("no memory for error send in dispatch\n");
4803 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
4805 if (preallocated == NULL)
4807 _dbus_list_free_link (expire_link);
4808 /* It's OK that this is finalized, because it hasn't been seen by
4809 * anything that could attach user callbacks */
4810 dbus_message_unref (reply);
4811 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4812 _dbus_verbose ("no memory for error send in dispatch\n");
4816 _dbus_connection_send_preallocated_unlocked_no_update (connection, preallocated,
4818 /* reply will be freed when we release the lock */
4819 _dbus_list_prepend_link (&connection->expired_messages, expire_link);
4821 result = DBUS_HANDLER_RESULT_HANDLED;
4824 _dbus_verbose (" done dispatching %p (%s %s %s '%s') on connection %p\n", message,
4825 dbus_message_type_to_string (dbus_message_get_type (message)),
4826 dbus_message_get_interface (message) ?
4827 dbus_message_get_interface (message) :
4829 dbus_message_get_member (message) ?
4830 dbus_message_get_member (message) :
4832 dbus_message_get_signature (message),
4836 if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
4838 _dbus_verbose ("out of memory\n");
4840 /* Put message back, and we'll start over.
4841 * Yes this means handlers must be idempotent if they
4842 * don't return HANDLED; c'est la vie.
4844 _dbus_connection_putback_message_link_unlocked (connection,
4846 /* now we don't want to free them */
4847 message_link = NULL;
4852 _dbus_verbose (" ... done dispatching\n");
4855 _dbus_connection_release_dispatch (connection);
4856 HAVE_LOCK_CHECK (connection);
4858 if (message != NULL)
4860 /* We don't want this message to count in maximum message limits when
4861 * computing the dispatch status, below. We have to drop the lock
4862 * temporarily, because finalizing a message can trigger callbacks.
4864 * We have a reference to the connection, and we don't use any cached
4865 * pointers to the connection's internals below this point, so it should
4866 * be safe to drop the lock and take it back. */
4867 CONNECTION_UNLOCK (connection);
4868 dbus_message_unref (message);
4869 CONNECTION_LOCK (connection);
4872 if (message_link != NULL)
4873 _dbus_list_free_link (message_link);
4875 _dbus_verbose ("before final status update\n");
4876 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4878 /* unlocks and calls user code */
4879 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4881 dbus_connection_unref (connection);
4887 * Sets the watch functions for the connection. These functions are
4888 * responsible for making the application's main loop aware of file
4889 * descriptors that need to be monitored for events, using select() or
4890 * poll(). When using Qt, typically the DBusAddWatchFunction would
4891 * create a QSocketNotifier. When using GLib, the DBusAddWatchFunction
4892 * could call g_io_add_watch(), or could be used as part of a more
4893 * elaborate GSource. Note that when a watch is added, it may
4896 * The DBusWatchToggledFunction notifies the application that the
4897 * watch has been enabled or disabled. Call dbus_watch_get_enabled()
4898 * to check this. A disabled watch should have no effect, and enabled
4899 * watch should be added to the main loop. This feature is used
4900 * instead of simply adding/removing the watch because
4901 * enabling/disabling can be done without memory allocation. The
4902 * toggled function may be NULL if a main loop re-queries
4903 * dbus_watch_get_enabled() every time anyway.
4905 * The DBusWatch can be queried for the file descriptor to watch using
4906 * dbus_watch_get_unix_fd() or dbus_watch_get_socket(), and for the
4907 * events to watch for using dbus_watch_get_flags(). The flags
4908 * returned by dbus_watch_get_flags() will only contain
4909 * DBUS_WATCH_READABLE and DBUS_WATCH_WRITABLE, never
4910 * DBUS_WATCH_HANGUP or DBUS_WATCH_ERROR; all watches implicitly
4911 * include a watch for hangups, errors, and other exceptional
4914 * Once a file descriptor becomes readable or writable, or an exception
4915 * occurs, dbus_watch_handle() should be called to
4916 * notify the connection of the file descriptor's condition.
4918 * dbus_watch_handle() cannot be called during the
4919 * DBusAddWatchFunction, as the connection will not be ready to handle
4922 * It is not allowed to reference a DBusWatch after it has been passed
4923 * to remove_function.
4925 * If #FALSE is returned due to lack of memory, the failure may be due
4926 * to a #FALSE return from the new add_function. If so, the
4927 * add_function may have been called successfully one or more times,
4928 * but the remove_function will also have been called to remove any
4929 * successful adds. i.e. if #FALSE is returned the net result
4930 * should be that dbus_connection_set_watch_functions() has no effect,
4931 * but the add_function and remove_function may have been called.
4933 * @note The thread lock on DBusConnection is held while
4934 * watch functions are invoked, so inside these functions you
4935 * may not invoke any methods on DBusConnection or it will deadlock.
4936 * See the comments in the code or http://lists.freedesktop.org/archives/dbus/2007-July/tread.html#8144
4937 * if you encounter this issue and want to attempt writing a patch.
4939 * @param connection the connection.
4940 * @param add_function function to begin monitoring a new descriptor.
4941 * @param remove_function function to stop monitoring a descriptor.
4942 * @param toggled_function function to notify of enable/disable
4943 * @param data data to pass to add_function and remove_function.
4944 * @param free_data_function function to be called to free the data.
4945 * @returns #FALSE on failure (no memory)
4948 dbus_connection_set_watch_functions (DBusConnection *connection,
4949 DBusAddWatchFunction add_function,
4950 DBusRemoveWatchFunction remove_function,
4951 DBusWatchToggledFunction toggled_function,
4953 DBusFreeFunction free_data_function)
4957 _dbus_return_val_if_fail (connection != NULL, FALSE);
4959 CONNECTION_LOCK (connection);
4961 retval = _dbus_watch_list_set_functions (connection->watches,
4962 add_function, remove_function,
4964 data, free_data_function);
4966 CONNECTION_UNLOCK (connection);
4972 * Sets the timeout functions for the connection. These functions are
4973 * responsible for making the application's main loop aware of timeouts.
4974 * When using Qt, typically the DBusAddTimeoutFunction would create a
4975 * QTimer. When using GLib, the DBusAddTimeoutFunction would call
4978 * The DBusTimeoutToggledFunction notifies the application that the
4979 * timeout has been enabled or disabled. Call
4980 * dbus_timeout_get_enabled() to check this. A disabled timeout should
4981 * have no effect, and enabled timeout should be added to the main
4982 * loop. This feature is used instead of simply adding/removing the
4983 * timeout because enabling/disabling can be done without memory
4984 * allocation. With Qt, QTimer::start() and QTimer::stop() can be used
4985 * to enable and disable. The toggled function may be NULL if a main
4986 * loop re-queries dbus_timeout_get_enabled() every time anyway.
4987 * Whenever a timeout is toggled, its interval may change.
4989 * The DBusTimeout can be queried for the timer interval using
4990 * dbus_timeout_get_interval(). dbus_timeout_handle() should be called
4991 * repeatedly, each time the interval elapses, starting after it has
4992 * elapsed once. The timeout stops firing when it is removed with the
4993 * given remove_function. The timer interval may change whenever the
4994 * timeout is added, removed, or toggled.
4996 * @note The thread lock on DBusConnection is held while
4997 * timeout functions are invoked, so inside these functions you
4998 * may not invoke any methods on DBusConnection or it will deadlock.
4999 * See the comments in the code or http://lists.freedesktop.org/archives/dbus/2007-July/thread.html#8144
5000 * if you encounter this issue and want to attempt writing a patch.
5002 * @param connection the connection.
5003 * @param add_function function to add a timeout.
5004 * @param remove_function function to remove a timeout.
5005 * @param toggled_function function to notify of enable/disable
5006 * @param data data to pass to add_function and remove_function.
5007 * @param free_data_function function to be called to free the data.
5008 * @returns #FALSE on failure (no memory)
5011 dbus_connection_set_timeout_functions (DBusConnection *connection,
5012 DBusAddTimeoutFunction add_function,
5013 DBusRemoveTimeoutFunction remove_function,
5014 DBusTimeoutToggledFunction toggled_function,
5016 DBusFreeFunction free_data_function)
5020 _dbus_return_val_if_fail (connection != NULL, FALSE);
5022 CONNECTION_LOCK (connection);
5024 retval = _dbus_timeout_list_set_functions (connection->timeouts,
5025 add_function, remove_function,
5027 data, free_data_function);
5029 CONNECTION_UNLOCK (connection);
5035 * Sets the mainloop wakeup function for the connection. This function
5036 * is responsible for waking up the main loop (if its sleeping in
5037 * another thread) when some some change has happened to the
5038 * connection that the mainloop needs to reconsider (e.g. a message
5039 * has been queued for writing). When using Qt, this typically
5040 * results in a call to QEventLoop::wakeUp(). When using GLib, it
5041 * would call g_main_context_wakeup().
5043 * @param connection the connection.
5044 * @param wakeup_main_function function to wake up the mainloop
5045 * @param data data to pass wakeup_main_function
5046 * @param free_data_function function to be called to free the data.
5049 dbus_connection_set_wakeup_main_function (DBusConnection *connection,
5050 DBusWakeupMainFunction wakeup_main_function,
5052 DBusFreeFunction free_data_function)
5055 DBusFreeFunction old_free_data;
5057 _dbus_return_if_fail (connection != NULL);
5059 CONNECTION_LOCK (connection);
5060 old_data = connection->wakeup_main_data;
5061 old_free_data = connection->free_wakeup_main_data;
5063 connection->wakeup_main_function = wakeup_main_function;
5064 connection->wakeup_main_data = data;
5065 connection->free_wakeup_main_data = free_data_function;
5067 CONNECTION_UNLOCK (connection);
5069 /* Callback outside the lock */
5071 (*old_free_data) (old_data);
5075 * Set a function to be invoked when the dispatch status changes.
5076 * If the dispatch status is #DBUS_DISPATCH_DATA_REMAINS, then
5077 * dbus_connection_dispatch() needs to be called to process incoming
5078 * messages. However, dbus_connection_dispatch() MUST NOT BE CALLED
5079 * from inside the DBusDispatchStatusFunction. Indeed, almost
5080 * any reentrancy in this function is a bad idea. Instead,
5081 * the DBusDispatchStatusFunction should simply save an indication
5082 * that messages should be dispatched later, when the main loop
5085 * If you don't set a dispatch status function, you have to be sure to
5086 * dispatch on every iteration of your main loop, especially if
5087 * dbus_watch_handle() or dbus_timeout_handle() were called.
5089 * @param connection the connection
5090 * @param function function to call on dispatch status changes
5091 * @param data data for function
5092 * @param free_data_function free the function data
5095 dbus_connection_set_dispatch_status_function (DBusConnection *connection,
5096 DBusDispatchStatusFunction function,
5098 DBusFreeFunction free_data_function)
5101 DBusFreeFunction old_free_data;
5103 _dbus_return_if_fail (connection != NULL);
5105 CONNECTION_LOCK (connection);
5106 old_data = connection->dispatch_status_data;
5107 old_free_data = connection->free_dispatch_status_data;
5109 connection->dispatch_status_function = function;
5110 connection->dispatch_status_data = data;
5111 connection->free_dispatch_status_data = free_data_function;
5113 CONNECTION_UNLOCK (connection);
5115 /* Callback outside the lock */
5117 (*old_free_data) (old_data);
5121 * Get the UNIX file descriptor of the connection, if any. This can
5122 * be used for SELinux access control checks with getpeercon() for
5123 * example. DO NOT read or write to the file descriptor, or try to
5124 * select() on it; use DBusWatch for main loop integration. Not all
5125 * connections will have a file descriptor. So for adding descriptors
5126 * to the main loop, use dbus_watch_get_unix_fd() and so forth.
5128 * If the connection is socket-based, you can also use
5129 * dbus_connection_get_socket(), which will work on Windows too.
5130 * This function always fails on Windows.
5132 * Right now the returned descriptor is always a socket, but
5133 * that is not guaranteed.
5135 * @param connection the connection
5136 * @param fd return location for the file descriptor.
5137 * @returns #TRUE if fd is successfully obtained.
5140 dbus_connection_get_unix_fd (DBusConnection *connection,
5143 _dbus_return_val_if_fail (connection != NULL, FALSE);
5144 _dbus_return_val_if_fail (connection->transport != NULL, FALSE);
5147 /* FIXME do this on a lower level */
5151 return dbus_connection_get_socket(connection, fd);
5155 * Gets the underlying Windows or UNIX socket file descriptor
5156 * of the connection, if any. DO NOT read or write to the file descriptor, or try to
5157 * select() on it; use DBusWatch for main loop integration. Not all
5158 * connections will have a socket. So for adding descriptors
5159 * to the main loop, use dbus_watch_get_socket() and so forth.
5161 * If the connection is not socket-based, this function will return FALSE,
5162 * even if the connection does have a file descriptor of some kind.
5163 * i.e. this function always returns specifically a socket file descriptor.
5165 * @param connection the connection
5166 * @param fd return location for the file descriptor.
5167 * @returns #TRUE if fd is successfully obtained.
5170 dbus_connection_get_socket(DBusConnection *connection,
5175 _dbus_return_val_if_fail (connection != NULL, FALSE);
5176 _dbus_return_val_if_fail (connection->transport != NULL, FALSE);
5178 CONNECTION_LOCK (connection);
5180 retval = _dbus_transport_get_socket_fd (connection->transport,
5183 CONNECTION_UNLOCK (connection);
5190 * Gets the UNIX user ID of the connection if known. Returns #TRUE if
5191 * the uid is filled in. Always returns #FALSE on non-UNIX platforms
5192 * for now, though in theory someone could hook Windows to NIS or
5193 * something. Always returns #FALSE prior to authenticating the
5196 * The UID is only read by servers from clients; clients can't usually
5197 * get the UID of servers, because servers do not authenticate to
5198 * clients. The returned UID is the UID the connection authenticated
5201 * The message bus is a server and the apps connecting to the bus
5204 * You can ask the bus to tell you the UID of another connection though
5205 * if you like; this is done with dbus_bus_get_unix_user().
5207 * @param connection the connection
5208 * @param uid return location for the user ID
5209 * @returns #TRUE if uid is filled in with a valid user ID
5212 dbus_connection_get_unix_user (DBusConnection *connection,
5217 _dbus_return_val_if_fail (connection != NULL, FALSE);
5218 _dbus_return_val_if_fail (uid != NULL, FALSE);
5220 CONNECTION_LOCK (connection);
5222 if (!_dbus_transport_try_to_authenticate (connection->transport))
5225 result = _dbus_transport_get_unix_user (connection->transport,
5229 _dbus_assert (!result);
5232 CONNECTION_UNLOCK (connection);
5238 * Gets the process ID of the connection if any.
5239 * Returns #TRUE if the pid is filled in.
5240 * Always returns #FALSE prior to authenticating the
5243 * @param connection the connection
5244 * @param pid return location for the process ID
5245 * @returns #TRUE if uid is filled in with a valid process ID
5248 dbus_connection_get_unix_process_id (DBusConnection *connection,
5253 _dbus_return_val_if_fail (connection != NULL, FALSE);
5254 _dbus_return_val_if_fail (pid != NULL, FALSE);
5256 CONNECTION_LOCK (connection);
5258 if (!_dbus_transport_try_to_authenticate (connection->transport))
5261 result = _dbus_transport_get_unix_process_id (connection->transport,
5264 CONNECTION_UNLOCK (connection);
5270 * Gets the ADT audit data of the connection if any.
5271 * Returns #TRUE if the structure pointer is returned.
5272 * Always returns #FALSE prior to authenticating the
5275 * @param connection the connection
5276 * @param data return location for audit data
5277 * @param data_size return location for length of audit data
5278 * @returns #TRUE if audit data is filled in with a valid ucred pointer
5281 dbus_connection_get_adt_audit_session_data (DBusConnection *connection,
5283 dbus_int32_t *data_size)
5287 _dbus_return_val_if_fail (connection != NULL, FALSE);
5288 _dbus_return_val_if_fail (data != NULL, FALSE);
5289 _dbus_return_val_if_fail (data_size != NULL, FALSE);
5291 CONNECTION_LOCK (connection);
5293 if (!_dbus_transport_try_to_authenticate (connection->transport))
5296 result = _dbus_transport_get_adt_audit_session_data (connection->transport,
5299 CONNECTION_UNLOCK (connection);
5305 * Sets a predicate function used to determine whether a given user ID
5306 * is allowed to connect. When an incoming connection has
5307 * authenticated with a particular user ID, this function is called;
5308 * if it returns #TRUE, the connection is allowed to proceed,
5309 * otherwise the connection is disconnected.
5311 * If the function is set to #NULL (as it is by default), then
5312 * only the same UID as the server process will be allowed to
5313 * connect. Also, root is always allowed to connect.
5315 * On Windows, the function will be set and its free_data_function will
5316 * be invoked when the connection is freed or a new function is set.
5317 * However, the function will never be called, because there are
5318 * no UNIX user ids to pass to it, or at least none of the existing
5319 * auth protocols would allow authenticating as a UNIX user on Windows.
5321 * @param connection the connection
5322 * @param function the predicate
5323 * @param data data to pass to the predicate
5324 * @param free_data_function function to free the data
5327 dbus_connection_set_unix_user_function (DBusConnection *connection,
5328 DBusAllowUnixUserFunction function,
5330 DBusFreeFunction free_data_function)
5332 void *old_data = NULL;
5333 DBusFreeFunction old_free_function = NULL;
5335 _dbus_return_if_fail (connection != NULL);
5337 CONNECTION_LOCK (connection);
5338 _dbus_transport_set_unix_user_function (connection->transport,
5339 function, data, free_data_function,
5340 &old_data, &old_free_function);
5341 CONNECTION_UNLOCK (connection);
5343 if (old_free_function != NULL)
5344 (* old_free_function) (old_data);
5348 * Gets the Windows user SID of the connection if known. Returns
5349 * #TRUE if the ID is filled in. Always returns #FALSE on non-Windows
5350 * platforms for now, though in theory someone could hook UNIX to
5351 * Active Directory or something. Always returns #FALSE prior to
5352 * authenticating the connection.
5354 * The user is only read by servers from clients; clients can't usually
5355 * get the user of servers, because servers do not authenticate to
5356 * clients. The returned user is the user the connection authenticated
5359 * The message bus is a server and the apps connecting to the bus
5362 * The returned user string has to be freed with dbus_free().
5364 * The return value indicates whether the user SID is available;
5365 * if it's available but we don't have the memory to copy it,
5366 * then the return value is #TRUE and #NULL is given as the SID.
5368 * @todo We would like to be able to say "You can ask the bus to tell
5369 * you the user of another connection though if you like; this is done
5370 * with dbus_bus_get_windows_user()." But this has to be implemented
5371 * in bus/driver.c and dbus/dbus-bus.c, and is pointless anyway
5372 * since on Windows we only use the session bus for now.
5374 * @param connection the connection
5375 * @param windows_sid_p return location for an allocated copy of the user ID, or #NULL if no memory
5376 * @returns #TRUE if user is available (returned value may be #NULL anyway if no memory)
5379 dbus_connection_get_windows_user (DBusConnection *connection,
5380 char **windows_sid_p)
5384 _dbus_return_val_if_fail (connection != NULL, FALSE);
5385 _dbus_return_val_if_fail (windows_sid_p != NULL, FALSE);
5387 CONNECTION_LOCK (connection);
5389 if (!_dbus_transport_try_to_authenticate (connection->transport))
5392 result = _dbus_transport_get_windows_user (connection->transport,
5396 _dbus_assert (!result);
5399 CONNECTION_UNLOCK (connection);
5405 * Sets a predicate function used to determine whether a given user ID
5406 * is allowed to connect. When an incoming connection has
5407 * authenticated with a particular user ID, this function is called;
5408 * if it returns #TRUE, the connection is allowed to proceed,
5409 * otherwise the connection is disconnected.
5411 * If the function is set to #NULL (as it is by default), then
5412 * only the same user owning the server process will be allowed to
5415 * On UNIX, the function will be set and its free_data_function will
5416 * be invoked when the connection is freed or a new function is set.
5417 * However, the function will never be called, because there is no
5418 * way right now to authenticate as a Windows user on UNIX.
5420 * @param connection the connection
5421 * @param function the predicate
5422 * @param data data to pass to the predicate
5423 * @param free_data_function function to free the data
5426 dbus_connection_set_windows_user_function (DBusConnection *connection,
5427 DBusAllowWindowsUserFunction function,
5429 DBusFreeFunction free_data_function)
5431 void *old_data = NULL;
5432 DBusFreeFunction old_free_function = NULL;
5434 _dbus_return_if_fail (connection != NULL);
5436 CONNECTION_LOCK (connection);
5437 _dbus_transport_set_windows_user_function (connection->transport,
5438 function, data, free_data_function,
5439 &old_data, &old_free_function);
5440 CONNECTION_UNLOCK (connection);
5442 if (old_free_function != NULL)
5443 (* old_free_function) (old_data);
5447 * This function must be called on the server side of a connection when the
5448 * connection is first seen in the #DBusNewConnectionFunction. If set to
5449 * #TRUE (the default is #FALSE), then the connection can proceed even if
5450 * the client does not authenticate as some user identity, i.e. clients
5451 * can connect anonymously.
5453 * This setting interacts with the available authorization mechanisms
5454 * (see dbus_server_set_auth_mechanisms()). Namely, an auth mechanism
5455 * such as ANONYMOUS that supports anonymous auth must be included in
5456 * the list of available mechanisms for anonymous login to work.
5458 * This setting also changes the default rule for connections
5459 * authorized as a user; normally, if a connection authorizes as
5460 * a user identity, it is permitted if the user identity is
5461 * root or the user identity matches the user identity of the server
5462 * process. If anonymous connections are allowed, however,
5463 * then any user identity is allowed.
5465 * You can override the rules for connections authorized as a
5466 * user identity with dbus_connection_set_unix_user_function()
5467 * and dbus_connection_set_windows_user_function().
5469 * @param connection the connection
5470 * @param value whether to allow authentication as an anonymous user
5473 dbus_connection_set_allow_anonymous (DBusConnection *connection,
5476 _dbus_return_if_fail (connection != NULL);
5478 CONNECTION_LOCK (connection);
5479 _dbus_transport_set_allow_anonymous (connection->transport, value);
5480 CONNECTION_UNLOCK (connection);
5485 * Normally #DBusConnection automatically handles all messages to the
5486 * org.freedesktop.DBus.Peer interface. However, the message bus wants
5487 * to be able to route methods on that interface through the bus and
5488 * to other applications. If routing peer messages is enabled, then
5489 * messages with the org.freedesktop.DBus.Peer interface that also
5490 * have a bus destination name set will not be automatically
5491 * handled by the #DBusConnection and instead will be dispatched
5492 * normally to the application.
5494 * If a normal application sets this flag, it can break things badly.
5495 * So don't set this unless you are the message bus.
5497 * @param connection the connection
5498 * @param value #TRUE to pass through org.freedesktop.DBus.Peer messages with a bus name set
5501 dbus_connection_set_route_peer_messages (DBusConnection *connection,
5504 _dbus_return_if_fail (connection != NULL);
5506 CONNECTION_LOCK (connection);
5507 connection->route_peer_messages = TRUE;
5508 CONNECTION_UNLOCK (connection);
5512 * Adds a message filter. Filters are handlers that are run on all
5513 * incoming messages, prior to the objects registered with
5514 * dbus_connection_register_object_path(). Filters are run in the
5515 * order that they were added. The same handler can be added as a
5516 * filter more than once, in which case it will be run more than once.
5517 * Filters added during a filter callback won't be run on the message
5520 * @todo we don't run filters on messages while blocking without
5521 * entering the main loop, since filters are run as part of
5522 * dbus_connection_dispatch(). This is probably a feature, as filters
5523 * could create arbitrary reentrancy. But kind of sucks if you're
5524 * trying to filter METHOD_RETURN for some reason.
5526 * @param connection the connection
5527 * @param function function to handle messages
5528 * @param user_data user data to pass to the function
5529 * @param free_data_function function to use for freeing user data
5530 * @returns #TRUE on success, #FALSE if not enough memory.
5533 dbus_connection_add_filter (DBusConnection *connection,
5534 DBusHandleMessageFunction function,
5536 DBusFreeFunction free_data_function)
5538 DBusMessageFilter *filter;
5540 _dbus_return_val_if_fail (connection != NULL, FALSE);
5541 _dbus_return_val_if_fail (function != NULL, FALSE);
5543 filter = dbus_new0 (DBusMessageFilter, 1);
5547 _dbus_atomic_inc (&filter->refcount);
5549 CONNECTION_LOCK (connection);
5551 if (!_dbus_list_append (&connection->filter_list,
5554 _dbus_message_filter_unref (filter);
5555 CONNECTION_UNLOCK (connection);
5559 /* Fill in filter after all memory allocated,
5560 * so we don't run the free_user_data_function
5561 * if the add_filter() fails
5564 filter->function = function;
5565 filter->user_data = user_data;
5566 filter->free_user_data_function = free_data_function;
5568 CONNECTION_UNLOCK (connection);
5573 * Removes a previously-added message filter. It is a programming
5574 * error to call this function for a handler that has not been added
5575 * as a filter. If the given handler was added more than once, only
5576 * one instance of it will be removed (the most recently-added
5579 * @param connection the connection
5580 * @param function the handler to remove
5581 * @param user_data user data for the handler to remove
5585 dbus_connection_remove_filter (DBusConnection *connection,
5586 DBusHandleMessageFunction function,
5590 DBusMessageFilter *filter;
5592 _dbus_return_if_fail (connection != NULL);
5593 _dbus_return_if_fail (function != NULL);
5595 CONNECTION_LOCK (connection);
5599 link = _dbus_list_get_last_link (&connection->filter_list);
5600 while (link != NULL)
5602 filter = link->data;
5604 if (filter->function == function &&
5605 filter->user_data == user_data)
5607 _dbus_list_remove_link (&connection->filter_list, link);
5608 filter->function = NULL;
5613 link = _dbus_list_get_prev_link (&connection->filter_list, link);
5617 CONNECTION_UNLOCK (connection);
5619 #ifndef DBUS_DISABLE_CHECKS
5622 _dbus_warn_check_failed ("Attempt to remove filter function %p user data %p, but no such filter has been added\n",
5623 function, user_data);
5628 /* Call application code */
5629 if (filter->free_user_data_function)
5630 (* filter->free_user_data_function) (filter->user_data);
5632 filter->free_user_data_function = NULL;
5633 filter->user_data = NULL;
5635 _dbus_message_filter_unref (filter);
5639 * Registers a handler for a given path or subsection in the object
5640 * hierarchy. The given vtable handles messages sent to exactly the
5641 * given path or also for paths bellow that, depending on fallback
5644 * @param connection the connection
5645 * @param fallback whether to handle messages also for "subdirectory"
5646 * @param path a '/' delimited string of path elements
5647 * @param vtable the virtual table
5648 * @param user_data data to pass to functions in the vtable
5649 * @param error address where an error can be returned
5650 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5651 * #DBUS_ERROR_OBJECT_PATH_IN_USE) is reported
5654 _dbus_connection_register_object_path (DBusConnection *connection,
5655 dbus_bool_t fallback,
5657 const DBusObjectPathVTable *vtable,
5661 char **decomposed_path;
5664 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5667 CONNECTION_LOCK (connection);
5669 retval = _dbus_object_tree_register (connection->objects,
5671 (const char **) decomposed_path, vtable,
5674 CONNECTION_UNLOCK (connection);
5676 dbus_free_string_array (decomposed_path);
5682 * Registers a handler for a given path in the object hierarchy.
5683 * The given vtable handles messages sent to exactly the given path.
5685 * @param connection the connection
5686 * @param path a '/' delimited string of path elements
5687 * @param vtable the virtual table
5688 * @param user_data data to pass to functions in the vtable
5689 * @param error address where an error can be returned
5690 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5691 * #DBUS_ERROR_OBJECT_PATH_IN_USE) is reported
5694 dbus_connection_try_register_object_path (DBusConnection *connection,
5696 const DBusObjectPathVTable *vtable,
5700 _dbus_return_val_if_fail (connection != NULL, FALSE);
5701 _dbus_return_val_if_fail (path != NULL, FALSE);
5702 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5703 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5705 return _dbus_connection_register_object_path (connection, FALSE, path, vtable, user_data, error);
5709 * Registers a handler for a given path in the object hierarchy.
5710 * The given vtable handles messages sent to exactly the given path.
5712 * It is a bug to call this function for object paths which already
5713 * have a handler. Use dbus_connection_try_register_object_path() if this
5714 * might be the case.
5716 * @param connection the connection
5717 * @param path a '/' delimited string of path elements
5718 * @param vtable the virtual table
5719 * @param user_data data to pass to functions in the vtable
5720 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5721 * #DBUS_ERROR_OBJECT_PATH_IN_USE) ocurred
5724 dbus_connection_register_object_path (DBusConnection *connection,
5726 const DBusObjectPathVTable *vtable,
5730 DBusError error = DBUS_ERROR_INIT;
5732 _dbus_return_val_if_fail (connection != NULL, FALSE);
5733 _dbus_return_val_if_fail (path != NULL, FALSE);
5734 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5735 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5737 retval = _dbus_connection_register_object_path (connection, FALSE, path, vtable, user_data, &error);
5739 if (dbus_error_has_name (&error, DBUS_ERROR_OBJECT_PATH_IN_USE))
5741 _dbus_warn ("%s\n", error.message);
5742 dbus_error_free (&error);
5750 * Registers a fallback handler for a given subsection of the object
5751 * hierarchy. The given vtable handles messages at or below the given
5752 * path. You can use this to establish a default message handling
5753 * policy for a whole "subdirectory."
5755 * @param connection the connection
5756 * @param path a '/' delimited string of path elements
5757 * @param vtable the virtual table
5758 * @param user_data data to pass to functions in the vtable
5759 * @param error address where an error can be returned
5760 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5761 * #DBUS_ERROR_OBJECT_PATH_IN_USE) is reported
5764 dbus_connection_try_register_fallback (DBusConnection *connection,
5766 const DBusObjectPathVTable *vtable,
5770 _dbus_return_val_if_fail (connection != NULL, FALSE);
5771 _dbus_return_val_if_fail (path != NULL, FALSE);
5772 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5773 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5775 return _dbus_connection_register_object_path (connection, TRUE, path, vtable, user_data, error);
5779 * Registers a fallback handler for a given subsection of the object
5780 * hierarchy. The given vtable handles messages at or below the given
5781 * path. You can use this to establish a default message handling
5782 * policy for a whole "subdirectory."
5784 * It is a bug to call this function for object paths which already
5785 * have a handler. Use dbus_connection_try_register_fallback() if this
5786 * might be the case.
5788 * @param connection the connection
5789 * @param path a '/' delimited string of path elements
5790 * @param vtable the virtual table
5791 * @param user_data data to pass to functions in the vtable
5792 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5793 * #DBUS_ERROR_OBJECT_PATH_IN_USE) occured
5796 dbus_connection_register_fallback (DBusConnection *connection,
5798 const DBusObjectPathVTable *vtable,
5802 DBusError error = DBUS_ERROR_INIT;
5804 _dbus_return_val_if_fail (connection != NULL, FALSE);
5805 _dbus_return_val_if_fail (path != NULL, FALSE);
5806 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5807 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5809 retval = _dbus_connection_register_object_path (connection, TRUE, path, vtable, user_data, &error);
5811 if (dbus_error_has_name (&error, DBUS_ERROR_OBJECT_PATH_IN_USE))
5813 _dbus_warn ("%s\n", error.message);
5814 dbus_error_free (&error);
5822 * Unregisters the handler registered with exactly the given path.
5823 * It's a bug to call this function for a path that isn't registered.
5824 * Can unregister both fallback paths and object paths.
5826 * @param connection the connection
5827 * @param path a '/' delimited string of path elements
5828 * @returns #FALSE if not enough memory
5831 dbus_connection_unregister_object_path (DBusConnection *connection,
5834 char **decomposed_path;
5836 _dbus_return_val_if_fail (connection != NULL, FALSE);
5837 _dbus_return_val_if_fail (path != NULL, FALSE);
5838 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5840 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5843 CONNECTION_LOCK (connection);
5845 _dbus_object_tree_unregister_and_unlock (connection->objects, (const char **) decomposed_path);
5847 dbus_free_string_array (decomposed_path);
5853 * Gets the user data passed to dbus_connection_register_object_path()
5854 * or dbus_connection_register_fallback(). If nothing was registered
5855 * at this path, the data is filled in with #NULL.
5857 * @param connection the connection
5858 * @param path the path you registered with
5859 * @param data_p location to store the user data, or #NULL
5860 * @returns #FALSE if not enough memory
5863 dbus_connection_get_object_path_data (DBusConnection *connection,
5867 char **decomposed_path;
5869 _dbus_return_val_if_fail (connection != NULL, FALSE);
5870 _dbus_return_val_if_fail (path != NULL, FALSE);
5871 _dbus_return_val_if_fail (data_p != NULL, FALSE);
5875 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5878 CONNECTION_LOCK (connection);
5880 *data_p = _dbus_object_tree_get_user_data_unlocked (connection->objects, (const char**) decomposed_path);
5882 CONNECTION_UNLOCK (connection);
5884 dbus_free_string_array (decomposed_path);
5890 * Lists the registered fallback handlers and object path handlers at
5891 * the given parent_path. The returned array should be freed with
5892 * dbus_free_string_array().
5894 * @param connection the connection
5895 * @param parent_path the path to list the child handlers of
5896 * @param child_entries returns #NULL-terminated array of children
5897 * @returns #FALSE if no memory to allocate the child entries
5900 dbus_connection_list_registered (DBusConnection *connection,
5901 const char *parent_path,
5902 char ***child_entries)
5904 char **decomposed_path;
5906 _dbus_return_val_if_fail (connection != NULL, FALSE);
5907 _dbus_return_val_if_fail (parent_path != NULL, FALSE);
5908 _dbus_return_val_if_fail (parent_path[0] == '/', FALSE);
5909 _dbus_return_val_if_fail (child_entries != NULL, FALSE);
5911 if (!_dbus_decompose_path (parent_path, strlen (parent_path), &decomposed_path, NULL))
5914 CONNECTION_LOCK (connection);
5916 retval = _dbus_object_tree_list_registered_and_unlock (connection->objects,
5917 (const char **) decomposed_path,
5919 dbus_free_string_array (decomposed_path);
5924 static DBusDataSlotAllocator slot_allocator =
5925 _DBUS_DATA_SLOT_ALLOCATOR_INIT (_DBUS_LOCK_NAME (connection_slots));
5928 * Allocates an integer ID to be used for storing application-specific
5929 * data on any DBusConnection. The allocated ID may then be used
5930 * with dbus_connection_set_data() and dbus_connection_get_data().
5931 * The passed-in slot must be initialized to -1, and is filled in
5932 * with the slot ID. If the passed-in slot is not -1, it's assumed
5933 * to be already allocated, and its refcount is incremented.
5935 * The allocated slot is global, i.e. all DBusConnection objects will
5936 * have a slot with the given integer ID reserved.
5938 * @param slot_p address of a global variable storing the slot
5939 * @returns #FALSE on failure (no memory)
5942 dbus_connection_allocate_data_slot (dbus_int32_t *slot_p)
5944 return _dbus_data_slot_allocator_alloc (&slot_allocator,
5949 * Deallocates a global ID for connection data slots.
5950 * dbus_connection_get_data() and dbus_connection_set_data() may no
5951 * longer be used with this slot. Existing data stored on existing
5952 * DBusConnection objects will be freed when the connection is
5953 * finalized, but may not be retrieved (and may only be replaced if
5954 * someone else reallocates the slot). When the refcount on the
5955 * passed-in slot reaches 0, it is set to -1.
5957 * @param slot_p address storing the slot to deallocate
5960 dbus_connection_free_data_slot (dbus_int32_t *slot_p)
5962 _dbus_return_if_fail (*slot_p >= 0);
5964 _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
5968 * Stores a pointer on a DBusConnection, along
5969 * with an optional function to be used for freeing
5970 * the data when the data is set again, or when
5971 * the connection is finalized. The slot number
5972 * must have been allocated with dbus_connection_allocate_data_slot().
5974 * @note This function does not take the
5975 * main thread lock on DBusConnection, which allows it to be
5976 * used from inside watch and timeout functions. (See the
5977 * note in docs for dbus_connection_set_watch_functions().)
5978 * A side effect of this is that you need to know there's
5979 * a reference held on the connection while invoking
5980 * dbus_connection_set_data(), or the connection could be
5981 * finalized during dbus_connection_set_data().
5983 * @param connection the connection
5984 * @param slot the slot number
5985 * @param data the data to store
5986 * @param free_data_func finalizer function for the data
5987 * @returns #TRUE if there was enough memory to store the data
5990 dbus_connection_set_data (DBusConnection *connection,
5993 DBusFreeFunction free_data_func)
5995 DBusFreeFunction old_free_func;
5999 _dbus_return_val_if_fail (connection != NULL, FALSE);
6000 _dbus_return_val_if_fail (slot >= 0, FALSE);
6002 SLOTS_LOCK (connection);
6004 retval = _dbus_data_slot_list_set (&slot_allocator,
6005 &connection->slot_list,
6006 slot, data, free_data_func,
6007 &old_free_func, &old_data);
6009 SLOTS_UNLOCK (connection);
6013 /* Do the actual free outside the connection lock */
6015 (* old_free_func) (old_data);
6022 * Retrieves data previously set with dbus_connection_set_data().
6023 * The slot must still be allocated (must not have been freed).
6025 * @note This function does not take the
6026 * main thread lock on DBusConnection, which allows it to be
6027 * used from inside watch and timeout functions. (See the
6028 * note in docs for dbus_connection_set_watch_functions().)
6029 * A side effect of this is that you need to know there's
6030 * a reference held on the connection while invoking
6031 * dbus_connection_get_data(), or the connection could be
6032 * finalized during dbus_connection_get_data().
6034 * @param connection the connection
6035 * @param slot the slot to get data from
6036 * @returns the data, or #NULL if not found
6039 dbus_connection_get_data (DBusConnection *connection,
6044 _dbus_return_val_if_fail (connection != NULL, NULL);
6045 _dbus_return_val_if_fail (slot >= 0, NULL);
6047 SLOTS_LOCK (connection);
6049 res = _dbus_data_slot_list_get (&slot_allocator,
6050 &connection->slot_list,
6053 SLOTS_UNLOCK (connection);
6059 * This function sets a global flag for whether dbus_connection_new()
6060 * will set SIGPIPE behavior to SIG_IGN.
6062 * @param will_modify_sigpipe #TRUE to allow sigpipe to be set to SIG_IGN
6065 dbus_connection_set_change_sigpipe (dbus_bool_t will_modify_sigpipe)
6067 _dbus_modify_sigpipe = will_modify_sigpipe != FALSE;
6071 * Specifies the maximum size message this connection is allowed to
6072 * receive. Larger messages will result in disconnecting the
6075 * @param connection a #DBusConnection
6076 * @param size maximum message size the connection can receive, in bytes
6079 dbus_connection_set_max_message_size (DBusConnection *connection,
6082 _dbus_return_if_fail (connection != NULL);
6084 CONNECTION_LOCK (connection);
6085 _dbus_transport_set_max_message_size (connection->transport,
6087 CONNECTION_UNLOCK (connection);
6091 * Gets the value set by dbus_connection_set_max_message_size().
6093 * @param connection the connection
6094 * @returns the max size of a single message
6097 dbus_connection_get_max_message_size (DBusConnection *connection)
6101 _dbus_return_val_if_fail (connection != NULL, 0);
6103 CONNECTION_LOCK (connection);
6104 res = _dbus_transport_get_max_message_size (connection->transport);
6105 CONNECTION_UNLOCK (connection);
6110 * Specifies the maximum number of unix fds a message on this
6111 * connection is allowed to receive. Messages with more unix fds will
6112 * result in disconnecting the connection.
6114 * @param connection a #DBusConnection
6115 * @param n maximum message unix fds the connection can receive
6118 dbus_connection_set_max_message_unix_fds (DBusConnection *connection,
6121 _dbus_return_if_fail (connection != NULL);
6123 CONNECTION_LOCK (connection);
6124 _dbus_transport_set_max_message_unix_fds (connection->transport,
6126 CONNECTION_UNLOCK (connection);
6130 * Gets the value set by dbus_connection_set_max_message_unix_fds().
6132 * @param connection the connection
6133 * @returns the max numer of unix fds of a single message
6136 dbus_connection_get_max_message_unix_fds (DBusConnection *connection)
6140 _dbus_return_val_if_fail (connection != NULL, 0);
6142 CONNECTION_LOCK (connection);
6143 res = _dbus_transport_get_max_message_unix_fds (connection->transport);
6144 CONNECTION_UNLOCK (connection);
6149 * Sets the maximum total number of bytes that can be used for all messages
6150 * received on this connection. Messages count toward the maximum until
6151 * they are finalized. When the maximum is reached, the connection will
6152 * not read more data until some messages are finalized.
6154 * The semantics of the maximum are: if outstanding messages are
6155 * already above the maximum, additional messages will not be read.
6156 * The semantics are not: if the next message would cause us to exceed
6157 * the maximum, we don't read it. The reason is that we don't know the
6158 * size of a message until after we read it.
6160 * Thus, the max live messages size can actually be exceeded
6161 * by up to the maximum size of a single message.
6163 * Also, if we read say 1024 bytes off the wire in a single read(),
6164 * and that contains a half-dozen small messages, we may exceed the
6165 * size max by that amount. But this should be inconsequential.
6167 * This does imply that we can't call read() with a buffer larger
6168 * than we're willing to exceed this limit by.
6170 * @param connection the connection
6171 * @param size the maximum size in bytes of all outstanding messages
6174 dbus_connection_set_max_received_size (DBusConnection *connection,
6177 _dbus_return_if_fail (connection != NULL);
6179 CONNECTION_LOCK (connection);
6180 _dbus_transport_set_max_received_size (connection->transport,
6182 CONNECTION_UNLOCK (connection);
6186 * Gets the value set by dbus_connection_set_max_received_size().
6188 * @param connection the connection
6189 * @returns the max size of all live messages
6192 dbus_connection_get_max_received_size (DBusConnection *connection)
6196 _dbus_return_val_if_fail (connection != NULL, 0);
6198 CONNECTION_LOCK (connection);
6199 res = _dbus_transport_get_max_received_size (connection->transport);
6200 CONNECTION_UNLOCK (connection);
6205 * Sets the maximum total number of unix fds that can be used for all messages
6206 * received on this connection. Messages count toward the maximum until
6207 * they are finalized. When the maximum is reached, the connection will
6208 * not read more data until some messages are finalized.
6210 * The semantics are analogous to those of dbus_connection_set_max_received_size().
6212 * @param connection the connection
6213 * @param n the maximum size in bytes of all outstanding messages
6216 dbus_connection_set_max_received_unix_fds (DBusConnection *connection,
6219 _dbus_return_if_fail (connection != NULL);
6221 CONNECTION_LOCK (connection);
6222 _dbus_transport_set_max_received_unix_fds (connection->transport,
6224 CONNECTION_UNLOCK (connection);
6228 * Gets the value set by dbus_connection_set_max_received_unix_fds().
6230 * @param connection the connection
6231 * @returns the max unix fds of all live messages
6234 dbus_connection_get_max_received_unix_fds (DBusConnection *connection)
6238 _dbus_return_val_if_fail (connection != NULL, 0);
6240 CONNECTION_LOCK (connection);
6241 res = _dbus_transport_get_max_received_unix_fds (connection->transport);
6242 CONNECTION_UNLOCK (connection);
6247 * Gets the approximate size in bytes of all messages in the outgoing
6248 * message queue. The size is approximate in that you shouldn't use
6249 * it to decide how many bytes to read off the network or anything
6250 * of that nature, as optimizations may choose to tell small white lies
6251 * to avoid performance overhead.
6253 * @param connection the connection
6254 * @returns the number of bytes that have been queued up but not sent
6257 dbus_connection_get_outgoing_size (DBusConnection *connection)
6261 _dbus_return_val_if_fail (connection != NULL, 0);
6263 CONNECTION_LOCK (connection);
6264 res = _dbus_counter_get_size_value (connection->outgoing_counter);
6265 CONNECTION_UNLOCK (connection);
6269 #ifdef DBUS_ENABLE_STATS
6271 _dbus_connection_get_stats (DBusConnection *connection,
6272 dbus_uint32_t *in_messages,
6273 dbus_uint32_t *in_bytes,
6274 dbus_uint32_t *in_fds,
6275 dbus_uint32_t *in_peak_bytes,
6276 dbus_uint32_t *in_peak_fds,
6277 dbus_uint32_t *out_messages,
6278 dbus_uint32_t *out_bytes,
6279 dbus_uint32_t *out_fds,
6280 dbus_uint32_t *out_peak_bytes,
6281 dbus_uint32_t *out_peak_fds)
6283 CONNECTION_LOCK (connection);
6285 if (in_messages != NULL)
6286 *in_messages = connection->n_incoming;
6288 _dbus_transport_get_stats (connection->transport,
6289 in_bytes, in_fds, in_peak_bytes, in_peak_fds);
6291 if (out_messages != NULL)
6292 *out_messages = connection->n_outgoing;
6294 if (out_bytes != NULL)
6295 *out_bytes = _dbus_counter_get_size_value (connection->outgoing_counter);
6297 if (out_fds != NULL)
6298 *out_fds = _dbus_counter_get_unix_fd_value (connection->outgoing_counter);
6300 if (out_peak_bytes != NULL)
6301 *out_peak_bytes = _dbus_counter_get_peak_size_value (connection->outgoing_counter);
6303 if (out_peak_fds != NULL)
6304 *out_peak_fds = _dbus_counter_get_peak_unix_fd_value (connection->outgoing_counter);
6306 CONNECTION_UNLOCK (connection);
6308 #endif /* DBUS_ENABLE_STATS */
6311 * Gets the approximate number of uni fds of all messages in the
6312 * outgoing message queue.
6314 * @param connection the connection
6315 * @returns the number of unix fds that have been queued up but not sent
6318 dbus_connection_get_outgoing_unix_fds (DBusConnection *connection)
6322 _dbus_return_val_if_fail (connection != NULL, 0);
6324 CONNECTION_LOCK (connection);
6325 res = _dbus_counter_get_unix_fd_value (connection->outgoing_counter);
6326 CONNECTION_UNLOCK (connection);
6331 * Returns the address of the transport object of this connection
6333 * @param connection the connection
6334 * @returns the address string
6337 _dbus_connection_get_address (DBusConnection *connection)
6339 return _dbus_transport_get_address (connection->transport);
6343 dbus_connection_get_transport(DBusConnection *connection)
6345 _dbus_return_val_if_fail (connection != NULL, NULL);
6347 return connection->transport;