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.
5 * Copyright (C) 2013 Samsung Electronics
7 * Licensed under the Academic Free License version 2.1
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 #include "dbus-shared.h"
27 #include "dbus-connection.h"
28 #include "dbus-list.h"
29 #include "dbus-timeout.h"
30 #include "dbus-transport.h"
31 #include "dbus-watch.h"
32 #include "dbus-connection-internal.h"
33 #include "dbus-pending-call-internal.h"
34 #include "dbus-list.h"
35 #include "dbus-hash.h"
36 #include "dbus-message-internal.h"
37 #include "dbus-message-private.h"
38 #include "dbus-threads.h"
39 #include "dbus-protocol.h"
40 #include "dbus-dataslot.h"
41 #include "dbus-string.h"
42 #include "dbus-signature.h"
43 #include "dbus-pending-call.h"
44 #include "dbus-object-tree.h"
45 #include "dbus-threads-internal.h"
47 #include "dbus-marshal-basic.h"
48 #ifdef ENABLE_KDBUS_TRANSPORT
49 #include "dbus-transport-kdbus.h"
50 #include "kdbus-common.h"
54 #ifdef DBUS_DISABLE_CHECKS
55 #define TOOK_LOCK_CHECK(connection)
56 #define RELEASING_LOCK_CHECK(connection)
57 #define HAVE_LOCK_CHECK(connection)
59 #define TOOK_LOCK_CHECK(connection) do { \
60 _dbus_assert (!(connection)->have_connection_lock); \
61 (connection)->have_connection_lock = TRUE; \
63 #define RELEASING_LOCK_CHECK(connection) do { \
64 _dbus_assert ((connection)->have_connection_lock); \
65 (connection)->have_connection_lock = FALSE; \
67 #define HAVE_LOCK_CHECK(connection) _dbus_assert ((connection)->have_connection_lock)
68 /* A "DO_NOT_HAVE_LOCK_CHECK" is impossible since we need the lock to check the flag */
73 #define CONNECTION_LOCK(connection) do { \
74 if (TRACE_LOCKS) { _dbus_verbose ("LOCK\n"); } \
75 _dbus_rmutex_lock ((connection)->mutex); \
76 TOOK_LOCK_CHECK (connection); \
79 #define CONNECTION_UNLOCK(connection) _dbus_connection_unlock (connection)
81 #define SLOTS_LOCK(connection) do { \
82 _dbus_rmutex_lock ((connection)->slot_mutex); \
85 #define SLOTS_UNLOCK(connection) do { \
86 _dbus_rmutex_unlock ((connection)->slot_mutex); \
89 #define DISPATCH_STATUS_NAME(s) \
90 ((s) == DBUS_DISPATCH_COMPLETE ? "complete" : \
91 (s) == DBUS_DISPATCH_DATA_REMAINS ? "data remains" : \
92 (s) == DBUS_DISPATCH_NEED_MEMORY ? "need memory" : \
96 * @defgroup DBusConnection DBusConnection
98 * @brief Connection to another application
100 * A DBusConnection represents a connection to another
101 * application. Messages can be sent and received via this connection.
102 * The other application may be a message bus; for convenience, the
103 * function dbus_bus_get() is provided to automatically open a
104 * connection to the well-known message buses.
106 * In brief a DBusConnection is a message queue associated with some
107 * message transport mechanism such as a socket. The connection
108 * maintains a queue of incoming messages and a queue of outgoing
111 * Several functions use the following terms:
113 * <li><b>read</b> means to fill the incoming message queue by reading from the socket</li>
114 * <li><b>write</b> means to drain the outgoing queue by writing to the socket</li>
115 * <li><b>dispatch</b> means to drain the incoming queue by invoking application-provided message handlers</li>
118 * The function dbus_connection_read_write_dispatch() for example does all
119 * three of these things, offering a simple alternative to a main loop.
121 * In an application with a main loop, the read/write/dispatch
122 * operations are usually separate.
124 * The connection provides #DBusWatch and #DBusTimeout objects to
125 * the main loop. These are used to know when reading, writing, or
126 * dispatching should be performed.
128 * Incoming messages are processed
129 * by calling dbus_connection_dispatch(). dbus_connection_dispatch()
130 * runs any handlers registered for the topmost message in the message
131 * queue, then discards the message, then returns.
133 * dbus_connection_get_dispatch_status() indicates whether
134 * messages are currently in the queue that need dispatching.
135 * dbus_connection_set_dispatch_status_function() allows
136 * you to set a function to be used to monitor the dispatch status.
138 * If you're using GLib or Qt add-on libraries for D-Bus, there are
139 * special convenience APIs in those libraries that hide
140 * all the details of dispatch and watch/timeout monitoring.
141 * For example, dbus_connection_setup_with_g_main().
143 * If you aren't using these add-on libraries, but want to process
144 * messages asynchronously, you must manually call
145 * dbus_connection_set_dispatch_status_function(),
146 * dbus_connection_set_watch_functions(),
147 * dbus_connection_set_timeout_functions() providing appropriate
148 * functions to integrate the connection with your application's main
149 * loop. This can be tricky to get right; main loops are not simple.
151 * If you don't need to be asynchronous, you can ignore #DBusWatch,
152 * #DBusTimeout, and dbus_connection_dispatch(). Instead,
153 * dbus_connection_read_write_dispatch() can be used.
155 * Or, in <em>very</em> simple applications,
156 * dbus_connection_pop_message() may be all you need, allowing you to
157 * avoid setting up any handler functions (see
158 * dbus_connection_add_filter(),
159 * dbus_connection_register_object_path() for more on handlers).
161 * When you use dbus_connection_send() or one of its variants to send
162 * a message, the message is added to the outgoing queue. It's
163 * actually written to the network later; either in
164 * dbus_watch_handle() invoked by your main loop, or in
165 * dbus_connection_flush() which blocks until it can write out the
166 * entire outgoing queue. The GLib/Qt add-on libraries again
167 * handle the details here for you by setting up watch functions.
169 * When a connection is disconnected, you are guaranteed to get a
170 * signal "Disconnected" from the interface
171 * #DBUS_INTERFACE_LOCAL, path
174 * You may not drop the last reference to a #DBusConnection
175 * until that connection has been disconnected.
177 * You may dispatch the unprocessed incoming message queue even if the
178 * connection is disconnected. However, "Disconnected" will always be
179 * the last message in the queue (obviously no messages are received
180 * after disconnection).
182 * After calling dbus_threads_init(), #DBusConnection has thread
183 * locks and drops them when invoking user callbacks, so in general is
184 * transparently threadsafe. However, #DBusMessage does NOT have
185 * thread locks; you must not send the same message to multiple
186 * #DBusConnection if those connections will be used from different threads,
189 * Also, if you dispatch or pop messages from multiple threads, it
190 * may work in the sense that it won't crash, but it's tough to imagine
191 * sane results; it will be completely unpredictable which messages
192 * go to which threads.
194 * It's recommended to dispatch from a single thread.
196 * The most useful function to call from multiple threads at once
197 * is dbus_connection_send_with_reply_and_block(). That is,
198 * multiple threads can make method calls at the same time.
200 * If you aren't using threads, you can use a main loop and
201 * dbus_pending_call_set_notify() to achieve a similar result.
205 * @defgroup DBusConnectionInternals DBusConnection implementation details
206 * @ingroup DBusInternals
207 * @brief Implementation details of DBusConnection
213 _dbus_connection_trace_ref (DBusConnection *connection,
218 #ifdef DBUS_ENABLE_VERBOSE_MODE
219 static int enabled = -1;
221 _dbus_trace_ref ("DBusConnection", connection, old_refcount, new_refcount,
222 why, "DBUS_CONNECTION_TRACE", &enabled);
227 * Internal struct representing a message filter function
229 typedef struct DBusMessageFilter DBusMessageFilter;
232 * Internal struct representing a message filter function
234 struct DBusMessageFilter
236 DBusAtomic refcount; /**< Reference count */
237 DBusHandleMessageFunction function; /**< Function to call to filter */
238 void *user_data; /**< User data for the function */
239 DBusFreeFunction free_user_data_function; /**< Function to free the user data */
244 * Internals of DBusPreallocatedSend
246 struct DBusPreallocatedSend
248 DBusConnection *connection; /**< Connection we'd send the message to */
249 DBusList *queue_link; /**< Preallocated link in the queue */
250 DBusList *counter_link; /**< Preallocated link in the resource counter */
253 #if HAVE_DECL_MSG_NOSIGNAL
254 static dbus_bool_t _dbus_modify_sigpipe = FALSE;
256 static dbus_bool_t _dbus_modify_sigpipe = TRUE;
260 * Implementation details of DBusConnection. All fields are private.
262 struct DBusConnection
264 DBusAtomic refcount; /**< Reference count. */
266 DBusRMutex *mutex; /**< Lock on the entire DBusConnection */
268 DBusCMutex *dispatch_mutex; /**< Protects dispatch_acquired */
269 DBusCondVar *dispatch_cond; /**< Notify when dispatch_acquired is available */
270 DBusCMutex *io_path_mutex; /**< Protects io_path_acquired */
271 DBusCondVar *io_path_cond; /**< Notify when io_path_acquired is available */
273 DBusList *outgoing_messages; /**< Queue of messages we need to send, send the end of the list first. */
274 DBusList *incoming_messages; /**< Queue of messages we have received, end of the list received most recently. */
275 DBusList *expired_messages; /**< Messages that will be released when we next unlock. */
277 DBusMessage *message_borrowed; /**< Filled in if the first incoming message has been borrowed;
278 * dispatch_acquired will be set by the borrower
281 int n_outgoing; /**< Length of outgoing queue. */
282 int n_incoming; /**< Length of incoming queue. */
284 DBusCounter *outgoing_counter; /**< Counts size of outgoing messages. */
286 DBusTransport *transport; /**< Object that sends/receives messages over network. */
287 DBusWatchList *watches; /**< Stores active watches. */
288 DBusTimeoutList *timeouts; /**< Stores active timeouts. */
290 DBusList *filter_list; /**< List of filters. */
292 DBusRMutex *slot_mutex; /**< Lock on slot_list so overall connection lock need not be taken */
293 DBusDataSlotList slot_list; /**< Data stored by allocated integer ID */
295 DBusHashTable *pending_replies; /**< Hash of message serials to #DBusPendingCall. */
297 dbus_uint32_t client_serial; /**< Client serial. Increments each time a message is sent */
298 DBusList *disconnect_message_link; /**< Preallocated list node for queueing the disconnection message */
300 DBusWakeupMainFunction wakeup_main_function; /**< Function to wake up the mainloop */
301 void *wakeup_main_data; /**< Application data for wakeup_main_function */
302 DBusFreeFunction free_wakeup_main_data; /**< free wakeup_main_data */
304 DBusDispatchStatusFunction dispatch_status_function; /**< Function on dispatch status changes */
305 void *dispatch_status_data; /**< Application data for dispatch_status_function */
306 DBusFreeFunction free_dispatch_status_data; /**< free dispatch_status_data */
308 DBusDispatchStatus last_dispatch_status; /**< The last dispatch status we reported to the application. */
310 DBusObjectTree *objects; /**< Object path handlers registered with this connection */
312 char *server_guid; /**< GUID of server if we are in shared_connections, #NULL if server GUID is unknown or connection is private */
314 /* These two MUST be bools and not bitfields, because they are protected by a separate lock
315 * from connection->mutex and all bitfields in a word have to be read/written together.
316 * So you can't have a different lock for different bitfields in the same word.
318 dbus_bool_t dispatch_acquired; /**< Someone has dispatch path (can drain incoming queue) */
319 dbus_bool_t io_path_acquired; /**< Someone has transport io path (can use the transport to read/write messages) */
321 unsigned int shareable : 1; /**< #TRUE if libdbus owns a reference to the connection and can return it from dbus_connection_open() more than once */
323 unsigned int exit_on_disconnect : 1; /**< If #TRUE, exit after handling disconnect signal */
325 unsigned int route_peer_messages : 1; /**< If #TRUE, if org.freedesktop.DBus.Peer messages have a bus name, don't handle them automatically */
327 unsigned int disconnected_message_arrived : 1; /**< We popped or are dispatching the disconnected message.
328 * if the disconnect_message_link is NULL then we queued it, but
329 * this flag is whether it got to the head of the queue.
331 unsigned int disconnected_message_processed : 1; /**< We did our default handling of the disconnected message,
332 * such as closing the connection.
335 #ifndef DBUS_DISABLE_CHECKS
336 unsigned int have_connection_lock : 1; /**< Used to check locking */
339 #if defined(DBUS_ENABLE_CHECKS) || defined(DBUS_ENABLE_ASSERT)
340 int generation; /**< _dbus_current_generation that should correspond to this connection */
344 static DBusDispatchStatus _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection);
345 static void _dbus_connection_update_dispatch_status_and_unlock (DBusConnection *connection,
346 DBusDispatchStatus new_status);
347 static void _dbus_connection_last_unref (DBusConnection *connection);
348 static void _dbus_connection_acquire_dispatch (DBusConnection *connection);
349 static void _dbus_connection_release_dispatch (DBusConnection *connection);
350 static DBusDispatchStatus _dbus_connection_flush_unlocked (DBusConnection *connection);
351 static void _dbus_connection_close_possibly_shared_and_unlock (DBusConnection *connection);
352 static dbus_bool_t _dbus_connection_get_is_connected_unlocked (DBusConnection *connection);
353 static dbus_bool_t _dbus_connection_peek_for_reply_unlocked (DBusConnection *connection,
354 dbus_uint32_t client_serial);
356 static DBusMessageFilter *
357 _dbus_message_filter_ref (DBusMessageFilter *filter)
359 #ifdef DBUS_DISABLE_ASSERT
360 _dbus_atomic_inc (&filter->refcount);
362 dbus_int32_t old_value;
364 old_value = _dbus_atomic_inc (&filter->refcount);
365 _dbus_assert (old_value > 0);
372 _dbus_message_filter_unref (DBusMessageFilter *filter)
374 dbus_int32_t old_value;
376 old_value = _dbus_atomic_dec (&filter->refcount);
377 _dbus_assert (old_value > 0);
381 if (filter->free_user_data_function)
382 (* filter->free_user_data_function) (filter->user_data);
389 * Acquires the connection lock.
391 * @param connection the connection.
394 _dbus_connection_lock (DBusConnection *connection)
396 CONNECTION_LOCK (connection);
400 * Releases the connection lock.
402 * @param connection the connection.
405 _dbus_connection_unlock (DBusConnection *connection)
407 DBusList *expired_messages;
412 _dbus_verbose ("UNLOCK\n");
415 /* If we had messages that expired (fell off the incoming or outgoing
416 * queues) while we were locked, actually release them now */
417 expired_messages = connection->expired_messages;
418 connection->expired_messages = NULL;
420 RELEASING_LOCK_CHECK (connection);
421 _dbus_rmutex_unlock (connection->mutex);
423 for (iter = _dbus_list_pop_first_link (&expired_messages);
425 iter = _dbus_list_pop_first_link (&expired_messages))
427 DBusMessage *message = iter->data;
429 dbus_message_unref (message);
430 _dbus_list_free_link (iter);
435 * Wakes up the main loop if it is sleeping
436 * Needed if we're e.g. queueing outgoing messages
437 * on a thread while the mainloop sleeps.
439 * @param connection the connection.
442 _dbus_connection_wakeup_mainloop (DBusConnection *connection)
444 if (connection->wakeup_main_function)
445 (*connection->wakeup_main_function) (connection->wakeup_main_data);
448 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
450 * Gets the locks so we can examine them
452 * @param connection the connection.
453 * @param mutex_loc return for the location of the main mutex pointer
454 * @param dispatch_mutex_loc return location of the dispatch mutex pointer
455 * @param io_path_mutex_loc return location of the io_path mutex pointer
456 * @param dispatch_cond_loc return location of the dispatch conditional
458 * @param io_path_cond_loc return location of the io_path conditional
462 _dbus_connection_test_get_locks (DBusConnection *connection,
463 DBusMutex **mutex_loc,
464 DBusMutex **dispatch_mutex_loc,
465 DBusMutex **io_path_mutex_loc,
466 DBusCondVar **dispatch_cond_loc,
467 DBusCondVar **io_path_cond_loc)
469 *mutex_loc = (DBusMutex *) connection->mutex;
470 *dispatch_mutex_loc = (DBusMutex *) connection->dispatch_mutex;
471 *io_path_mutex_loc = (DBusMutex *) connection->io_path_mutex;
472 *dispatch_cond_loc = connection->dispatch_cond;
473 *io_path_cond_loc = connection->io_path_cond;
478 * Adds a message-containing list link to the incoming message queue,
479 * taking ownership of the link and the message's current refcount.
480 * Cannot fail due to lack of memory.
482 * @param connection the connection.
483 * @param link the message link to queue.
486 _dbus_connection_queue_received_message_link (DBusConnection *connection,
489 DBusPendingCall *pending;
490 dbus_uint32_t reply_serial;
491 DBusMessage *message;
493 _dbus_assert (_dbus_transport_peek_is_authenticated (connection->transport));
495 _dbus_list_append_link (&connection->incoming_messages,
497 message = link->data;
499 /* If this is a reply we're waiting on, remove timeout for it */
500 reply_serial = dbus_message_get_reply_serial (message);
501 if (reply_serial != 0)
503 pending = _dbus_hash_table_lookup_int (connection->pending_replies,
507 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
508 _dbus_connection_remove_timeout_unlocked (connection,
509 _dbus_pending_call_get_timeout_unlocked (pending));
511 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
517 connection->n_incoming += 1;
519 _dbus_connection_wakeup_mainloop (connection);
521 _dbus_verbose ("Message %p (%s %s %s %s '%s' reply to %u) added to incoming queue %p, %d incoming\n",
523 dbus_message_type_to_string (dbus_message_get_type (message)),
524 dbus_message_get_path (message) ?
525 dbus_message_get_path (message) :
527 dbus_message_get_interface (message) ?
528 dbus_message_get_interface (message) :
530 dbus_message_get_member (message) ?
531 dbus_message_get_member (message) :
533 dbus_message_get_signature (message),
534 dbus_message_get_reply_serial (message),
536 connection->n_incoming);
538 _dbus_message_trace_ref (message, -1, -1,
539 "_dbus_conection_queue_received_message_link");
543 * Adds a link + message to the incoming message queue.
544 * Can't fail. Takes ownership of both link and message.
546 * @param connection the connection.
547 * @param link the list node and message to queue.
551 _dbus_connection_queue_synthesized_message_link (DBusConnection *connection,
554 HAVE_LOCK_CHECK (connection);
556 _dbus_list_append_link (&connection->incoming_messages, link);
558 connection->n_incoming += 1;
560 _dbus_connection_wakeup_mainloop (connection);
562 _dbus_message_trace_ref (link->data, -1, -1,
563 "_dbus_connection_queue_synthesized_message_link");
565 _dbus_verbose ("Synthesized message %p added to incoming queue %p, %d incoming\n",
566 link->data, connection, connection->n_incoming);
571 * Checks whether there are messages in the outgoing message queue.
572 * Called with connection lock held.
574 * @param connection the connection.
575 * @returns #TRUE if the outgoing queue is non-empty.
578 _dbus_connection_has_messages_to_send_unlocked (DBusConnection *connection)
580 HAVE_LOCK_CHECK (connection);
581 return connection->outgoing_messages != NULL;
585 * Checks whether there are messages in the outgoing message queue.
586 * Use dbus_connection_flush() to block until all outgoing
587 * messages have been written to the underlying transport
588 * (such as a socket).
590 * @param connection the connection.
591 * @returns #TRUE if the outgoing queue is non-empty.
594 dbus_connection_has_messages_to_send (DBusConnection *connection)
598 _dbus_return_val_if_fail (connection != NULL, FALSE);
600 CONNECTION_LOCK (connection);
601 v = _dbus_connection_has_messages_to_send_unlocked (connection);
602 CONNECTION_UNLOCK (connection);
608 * Gets the next outgoing message. The message remains in the
609 * queue, and the caller does not own a reference to it.
611 * @param connection the connection.
612 * @returns the message to be sent.
615 _dbus_connection_get_message_to_send (DBusConnection *connection)
617 HAVE_LOCK_CHECK (connection);
619 return _dbus_list_get_last (&connection->outgoing_messages);
623 * Notifies the connection that a message has been sent, so the
624 * message can be removed from the outgoing queue.
625 * Called with the connection lock held.
627 * @param connection the connection.
628 * @param message the message that was sent.
631 _dbus_connection_message_sent_unlocked (DBusConnection *connection,
632 DBusMessage *message)
636 HAVE_LOCK_CHECK (connection);
638 /* This can be called before we even complete authentication, since
639 * it's called on disconnect to clean up the outgoing queue.
640 * It's also called as we successfully send each message.
643 link = _dbus_list_get_last_link (&connection->outgoing_messages);
644 _dbus_assert (link != NULL);
645 _dbus_assert (link->data == message);
647 _dbus_list_unlink (&connection->outgoing_messages,
649 _dbus_list_prepend_link (&connection->expired_messages, link);
651 connection->n_outgoing -= 1;
653 _dbus_verbose ("Message %p (%s %s %s %s '%s') removed from outgoing queue %p, %d left to send\n",
655 dbus_message_type_to_string (dbus_message_get_type (message)),
656 dbus_message_get_path (message) ?
657 dbus_message_get_path (message) :
659 dbus_message_get_interface (message) ?
660 dbus_message_get_interface (message) :
662 dbus_message_get_member (message) ?
663 dbus_message_get_member (message) :
665 dbus_message_get_signature (message),
666 connection, connection->n_outgoing);
668 /* It's OK that in principle we call the notify function, because for the
669 * outgoing limit, there isn't one */
670 _dbus_message_remove_counter (message, connection->outgoing_counter);
672 /* The message will actually be unreffed when we unlock */
675 /** Function to be called in protected_change_watch() with refcount held */
676 typedef dbus_bool_t (* DBusWatchAddFunction) (DBusWatchList *list,
678 /** Function to be called in protected_change_watch() with refcount held */
679 typedef void (* DBusWatchRemoveFunction) (DBusWatchList *list,
681 /** Function to be called in protected_change_watch() with refcount held */
682 typedef void (* DBusWatchToggleFunction) (DBusWatchList *list,
684 dbus_bool_t enabled);
687 protected_change_watch (DBusConnection *connection,
689 DBusWatchAddFunction add_function,
690 DBusWatchRemoveFunction remove_function,
691 DBusWatchToggleFunction toggle_function,
696 HAVE_LOCK_CHECK (connection);
698 /* The original purpose of protected_change_watch() was to hold a
699 * ref on the connection while dropping the connection lock, then
700 * calling out to the app. This was a broken hack that did not
701 * work, since the connection was in a hosed state (no WatchList
702 * field) while calling out.
704 * So for now we'll just keep the lock while calling out. This means
705 * apps are not allowed to call DBusConnection methods inside a
706 * watch function or they will deadlock.
708 * The "real fix" is to use the _and_unlock() pattern found
709 * elsewhere in the code, to defer calling out to the app until
710 * we're about to drop locks and return flow of control to the app
713 * See http://lists.freedesktop.org/archives/dbus/2007-July/thread.html#8144
716 if (connection->watches)
719 retval = (* add_function) (connection->watches, watch);
720 else if (remove_function)
723 (* remove_function) (connection->watches, watch);
728 (* toggle_function) (connection->watches, watch, enabled);
738 * Adds a watch using the connection's DBusAddWatchFunction if
739 * available. Otherwise records the watch to be added when said
740 * function is available. Also re-adds the watch if the
741 * DBusAddWatchFunction changes. May fail due to lack of memory.
742 * Connection lock should be held when calling this.
744 * @param connection the connection.
745 * @param watch the watch to add.
746 * @returns #TRUE on success.
749 _dbus_connection_add_watch_unlocked (DBusConnection *connection,
752 return protected_change_watch (connection, watch,
753 _dbus_watch_list_add_watch,
758 * Removes a watch using the connection's DBusRemoveWatchFunction
759 * if available. It's an error to call this function on a watch
760 * that was not previously added.
761 * Connection lock should be held when calling this.
763 * @param connection the connection.
764 * @param watch the watch to remove.
767 _dbus_connection_remove_watch_unlocked (DBusConnection *connection,
770 protected_change_watch (connection, watch,
772 _dbus_watch_list_remove_watch,
777 * Toggles a watch and notifies app via connection's
778 * DBusWatchToggledFunction if available. It's an error to call this
779 * function on a watch that was not previously added.
780 * Connection lock should be held when calling this.
782 * @param connection the connection.
783 * @param watch the watch to toggle.
784 * @param enabled whether to enable or disable
787 _dbus_connection_toggle_watch_unlocked (DBusConnection *connection,
791 _dbus_assert (watch != NULL);
793 protected_change_watch (connection, watch,
795 _dbus_watch_list_toggle_watch,
799 /** Function to be called in protected_change_timeout() with refcount held */
800 typedef dbus_bool_t (* DBusTimeoutAddFunction) (DBusTimeoutList *list,
801 DBusTimeout *timeout);
802 /** Function to be called in protected_change_timeout() with refcount held */
803 typedef void (* DBusTimeoutRemoveFunction) (DBusTimeoutList *list,
804 DBusTimeout *timeout);
805 /** Function to be called in protected_change_timeout() with refcount held */
806 typedef void (* DBusTimeoutToggleFunction) (DBusTimeoutList *list,
807 DBusTimeout *timeout,
808 dbus_bool_t enabled);
811 protected_change_timeout (DBusConnection *connection,
812 DBusTimeout *timeout,
813 DBusTimeoutAddFunction add_function,
814 DBusTimeoutRemoveFunction remove_function,
815 DBusTimeoutToggleFunction toggle_function,
820 HAVE_LOCK_CHECK (connection);
822 /* The original purpose of protected_change_timeout() was to hold a
823 * ref on the connection while dropping the connection lock, then
824 * calling out to the app. This was a broken hack that did not
825 * work, since the connection was in a hosed state (no TimeoutList
826 * field) while calling out.
828 * So for now we'll just keep the lock while calling out. This means
829 * apps are not allowed to call DBusConnection methods inside a
830 * timeout function or they will deadlock.
832 * The "real fix" is to use the _and_unlock() pattern found
833 * elsewhere in the code, to defer calling out to the app until
834 * we're about to drop locks and return flow of control to the app
837 * See http://lists.freedesktop.org/archives/dbus/2007-July/thread.html#8144
840 if (connection->timeouts)
843 retval = (* add_function) (connection->timeouts, timeout);
844 else if (remove_function)
847 (* remove_function) (connection->timeouts, timeout);
852 (* toggle_function) (connection->timeouts, timeout, enabled);
861 * Adds a timeout using the connection's DBusAddTimeoutFunction if
862 * available. Otherwise records the timeout to be added when said
863 * function is available. Also re-adds the timeout if the
864 * DBusAddTimeoutFunction changes. May fail due to lack of memory.
865 * The timeout will fire repeatedly until removed.
866 * Connection lock should be held when calling this.
868 * @param connection the connection.
869 * @param timeout the timeout to add.
870 * @returns #TRUE on success.
873 _dbus_connection_add_timeout_unlocked (DBusConnection *connection,
874 DBusTimeout *timeout)
876 return protected_change_timeout (connection, timeout,
877 _dbus_timeout_list_add_timeout,
882 * Removes a timeout using the connection's DBusRemoveTimeoutFunction
883 * if available. It's an error to call this function on a timeout
884 * that was not previously added.
885 * Connection lock should be held when calling this.
887 * @param connection the connection.
888 * @param timeout the timeout to remove.
891 _dbus_connection_remove_timeout_unlocked (DBusConnection *connection,
892 DBusTimeout *timeout)
894 protected_change_timeout (connection, timeout,
896 _dbus_timeout_list_remove_timeout,
901 * Toggles a timeout and notifies app via connection's
902 * DBusTimeoutToggledFunction if available. It's an error to call this
903 * function on a timeout that was not previously added.
904 * Connection lock should be held when calling this.
906 * @param connection the connection.
907 * @param timeout the timeout to toggle.
908 * @param enabled whether to enable or disable
911 _dbus_connection_toggle_timeout_unlocked (DBusConnection *connection,
912 DBusTimeout *timeout,
915 protected_change_timeout (connection, timeout,
917 _dbus_timeout_list_toggle_timeout,
922 _dbus_connection_attach_pending_call_unlocked (DBusConnection *connection,
923 DBusPendingCall *pending)
925 dbus_uint32_t reply_serial;
926 DBusTimeout *timeout;
928 HAVE_LOCK_CHECK (connection);
930 reply_serial = _dbus_pending_call_get_reply_serial_unlocked (pending);
932 _dbus_assert (reply_serial != 0);
934 timeout = _dbus_pending_call_get_timeout_unlocked (pending);
938 if (!_dbus_connection_add_timeout_unlocked (connection, timeout))
941 if (!_dbus_hash_table_insert_int (connection->pending_replies,
945 _dbus_connection_remove_timeout_unlocked (connection, timeout);
947 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
948 HAVE_LOCK_CHECK (connection);
952 _dbus_pending_call_set_timeout_added_unlocked (pending, TRUE);
956 if (!_dbus_hash_table_insert_int (connection->pending_replies,
960 HAVE_LOCK_CHECK (connection);
965 _dbus_pending_call_ref_unlocked (pending);
967 HAVE_LOCK_CHECK (connection);
973 free_pending_call_on_hash_removal (void *data)
975 DBusPendingCall *pending;
976 DBusConnection *connection;
983 connection = _dbus_pending_call_get_connection_unlocked (pending);
985 HAVE_LOCK_CHECK (connection);
987 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
989 _dbus_connection_remove_timeout_unlocked (connection,
990 _dbus_pending_call_get_timeout_unlocked (pending));
992 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
995 /* FIXME 1.0? this is sort of dangerous and undesirable to drop the lock
996 * here, but the pending call finalizer could in principle call out to
997 * application code so we pretty much have to... some larger code reorg
1000 _dbus_connection_ref_unlocked (connection);
1001 _dbus_pending_call_unref_and_unlock (pending);
1002 CONNECTION_LOCK (connection);
1003 _dbus_connection_unref_unlocked (connection);
1007 _dbus_connection_detach_pending_call_unlocked (DBusConnection *connection,
1008 DBusPendingCall *pending)
1010 /* This ends up unlocking to call the pending call finalizer, which is unexpected to
1013 _dbus_hash_table_remove_int (connection->pending_replies,
1014 _dbus_pending_call_get_reply_serial_unlocked (pending));
1018 _dbus_connection_detach_pending_call_and_unlock (DBusConnection *connection,
1019 DBusPendingCall *pending)
1021 /* The idea here is to avoid finalizing the pending call
1022 * with the lock held, since there's a destroy notifier
1023 * in pending call that goes out to application code.
1025 * There's an extra unlock inside the hash table
1026 * "free pending call" function FIXME...
1028 _dbus_pending_call_ref_unlocked (pending);
1029 _dbus_hash_table_remove_int (connection->pending_replies,
1030 _dbus_pending_call_get_reply_serial_unlocked (pending));
1032 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
1033 _dbus_connection_remove_timeout_unlocked (connection,
1034 _dbus_pending_call_get_timeout_unlocked (pending));
1036 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
1038 _dbus_pending_call_unref_and_unlock (pending);
1042 * Removes a pending call from the connection, such that
1043 * the pending reply will be ignored. May drop the last
1044 * reference to the pending call.
1046 * @param connection the connection
1047 * @param pending the pending call
1050 _dbus_connection_remove_pending_call (DBusConnection *connection,
1051 DBusPendingCall *pending)
1053 CONNECTION_LOCK (connection);
1054 _dbus_connection_detach_pending_call_and_unlock (connection, pending);
1058 * Acquire the transporter I/O path. This must be done before
1059 * doing any I/O in the transporter. May sleep and drop the
1060 * IO path mutex while waiting for the I/O path.
1062 * @param connection the connection.
1063 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
1064 * @returns TRUE if the I/O path was acquired.
1067 _dbus_connection_acquire_io_path (DBusConnection *connection,
1068 int timeout_milliseconds)
1070 dbus_bool_t we_acquired;
1072 HAVE_LOCK_CHECK (connection);
1074 /* We don't want the connection to vanish */
1075 _dbus_connection_ref_unlocked (connection);
1077 /* We will only touch io_path_acquired which is protected by our mutex */
1078 CONNECTION_UNLOCK (connection);
1080 _dbus_verbose ("locking io_path_mutex\n");
1081 _dbus_cmutex_lock (connection->io_path_mutex);
1083 _dbus_verbose ("start connection->io_path_acquired = %d timeout = %d\n",
1084 connection->io_path_acquired, timeout_milliseconds);
1086 we_acquired = FALSE;
1088 if (connection->io_path_acquired)
1090 if (timeout_milliseconds != -1)
1092 _dbus_verbose ("waiting %d for IO path to be acquirable\n",
1093 timeout_milliseconds);
1095 if (!_dbus_condvar_wait_timeout (connection->io_path_cond,
1096 connection->io_path_mutex,
1097 timeout_milliseconds))
1099 /* We timed out before anyone signaled. */
1100 /* (writing the loop to handle the !timedout case by
1101 * waiting longer if needed is a pain since dbus
1102 * wraps pthread_cond_timedwait to take a relative
1103 * time instead of absolute, something kind of stupid
1104 * on our part. for now it doesn't matter, we will just
1105 * end up back here eventually.)
1111 while (connection->io_path_acquired)
1113 _dbus_verbose ("waiting for IO path to be acquirable\n");
1114 _dbus_condvar_wait (connection->io_path_cond,
1115 connection->io_path_mutex);
1120 if (!connection->io_path_acquired)
1123 connection->io_path_acquired = TRUE;
1126 _dbus_verbose ("end connection->io_path_acquired = %d we_acquired = %d\n",
1127 connection->io_path_acquired, we_acquired);
1129 _dbus_verbose ("unlocking io_path_mutex\n");
1130 _dbus_cmutex_unlock (connection->io_path_mutex);
1132 CONNECTION_LOCK (connection);
1134 HAVE_LOCK_CHECK (connection);
1136 _dbus_connection_unref_unlocked (connection);
1142 * Release the I/O path when you're done with it. Only call
1143 * after you've acquired the I/O. Wakes up at most one thread
1144 * currently waiting to acquire the I/O path.
1146 * @param connection the connection.
1149 _dbus_connection_release_io_path (DBusConnection *connection)
1151 HAVE_LOCK_CHECK (connection);
1153 _dbus_verbose ("locking io_path_mutex\n");
1154 _dbus_cmutex_lock (connection->io_path_mutex);
1156 _dbus_assert (connection->io_path_acquired);
1158 _dbus_verbose ("start connection->io_path_acquired = %d\n",
1159 connection->io_path_acquired);
1161 connection->io_path_acquired = FALSE;
1162 _dbus_condvar_wake_one (connection->io_path_cond);
1164 _dbus_verbose ("unlocking io_path_mutex\n");
1165 _dbus_cmutex_unlock (connection->io_path_mutex);
1169 * Queues incoming messages and sends outgoing messages for this
1170 * connection, optionally blocking in the process. Each call to
1171 * _dbus_connection_do_iteration_unlocked() will call select() or poll() one
1172 * time and then read or write data if possible.
1174 * The purpose of this function is to be able to flush outgoing
1175 * messages or queue up incoming messages without returning
1176 * control to the application and causing reentrancy weirdness.
1178 * The flags parameter allows you to specify whether to
1179 * read incoming messages, write outgoing messages, or both,
1180 * and whether to block if no immediate action is possible.
1182 * The timeout_milliseconds parameter does nothing unless the
1183 * iteration is blocking.
1185 * If there are no outgoing messages and DBUS_ITERATION_DO_READING
1186 * wasn't specified, then it's impossible to block, even if
1187 * you specify DBUS_ITERATION_BLOCK; in that case the function
1188 * returns immediately.
1190 * If pending is not NULL then a check is made if the pending call
1191 * is completed after the io path has been required. If the call
1192 * has been completed nothing is done. This must be done since
1193 * the _dbus_connection_acquire_io_path releases the connection
1196 * Called with connection lock held.
1198 * @param connection the connection.
1199 * @param pending the pending call that should be checked or NULL
1200 * @param flags iteration flags.
1201 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
1204 _dbus_connection_do_iteration_unlocked (DBusConnection *connection,
1205 DBusPendingCall *pending,
1207 int timeout_milliseconds)
1209 _dbus_verbose ("start\n");
1211 HAVE_LOCK_CHECK (connection);
1213 if (connection->n_outgoing == 0)
1214 flags &= ~DBUS_ITERATION_DO_WRITING;
1216 if (_dbus_connection_acquire_io_path (connection,
1217 (flags & DBUS_ITERATION_BLOCK) ? timeout_milliseconds : 0))
1219 HAVE_LOCK_CHECK (connection);
1221 if ( (pending != NULL) && _dbus_pending_call_get_completed_unlocked(pending))
1223 _dbus_verbose ("pending call completed while acquiring I/O path");
1225 else if ( (pending != NULL) &&
1226 _dbus_connection_peek_for_reply_unlocked (connection,
1227 _dbus_pending_call_get_reply_serial_unlocked (pending)))
1229 _dbus_verbose ("pending call completed while acquiring I/O path (reply found in queue)");
1233 _dbus_transport_do_iteration (connection->transport,
1234 flags, timeout_milliseconds);
1237 _dbus_connection_release_io_path (connection);
1240 HAVE_LOCK_CHECK (connection);
1242 _dbus_verbose ("end\n");
1246 * Creates a new connection for the given transport. A transport
1247 * represents a message stream that uses some concrete mechanism, such
1248 * as UNIX domain sockets. May return #NULL if insufficient
1249 * memory exists to create the connection.
1251 * @param transport the transport.
1252 * @returns the new connection, or #NULL on failure.
1254 #ifdef ENABLE_KDBUS_TRANSPORT
1255 static DBusConnection*
1256 _dbus_connection_new_for_transport_internal (DBusTransport *transport, dbus_bool_t exists)
1259 _dbus_connection_new_for_transport (DBusTransport *transport)
1262 DBusConnection *connection;
1263 DBusWatchList *watch_list;
1264 DBusTimeoutList *timeout_list;
1265 DBusHashTable *pending_replies;
1266 DBusList *disconnect_link;
1267 DBusMessage *disconnect_message;
1268 DBusCounter *outgoing_counter;
1269 DBusObjectTree *objects;
1273 pending_replies = NULL;
1274 timeout_list = NULL;
1275 disconnect_link = NULL;
1276 disconnect_message = NULL;
1277 outgoing_counter = NULL;
1280 watch_list = _dbus_watch_list_new ();
1281 if (watch_list == NULL)
1284 timeout_list = _dbus_timeout_list_new ();
1285 if (timeout_list == NULL)
1289 _dbus_hash_table_new (DBUS_HASH_INT,
1291 (DBusFreeFunction)free_pending_call_on_hash_removal);
1292 if (pending_replies == NULL)
1295 connection = dbus_new0 (DBusConnection, 1);
1296 if (connection == NULL)
1299 _dbus_rmutex_new_at_location (&connection->mutex);
1300 if (connection->mutex == NULL)
1303 _dbus_cmutex_new_at_location (&connection->io_path_mutex);
1304 if (connection->io_path_mutex == NULL)
1307 _dbus_cmutex_new_at_location (&connection->dispatch_mutex);
1308 if (connection->dispatch_mutex == NULL)
1311 _dbus_condvar_new_at_location (&connection->dispatch_cond);
1312 if (connection->dispatch_cond == NULL)
1315 _dbus_condvar_new_at_location (&connection->io_path_cond);
1316 if (connection->io_path_cond == NULL)
1319 _dbus_rmutex_new_at_location (&connection->slot_mutex);
1320 if (connection->slot_mutex == NULL)
1323 disconnect_message = dbus_message_new_signal (DBUS_PATH_LOCAL,
1324 DBUS_INTERFACE_LOCAL,
1327 if (disconnect_message == NULL)
1330 disconnect_link = _dbus_list_alloc_link (disconnect_message);
1331 if (disconnect_link == NULL)
1334 outgoing_counter = _dbus_counter_new ();
1335 if (outgoing_counter == NULL)
1338 objects = _dbus_object_tree_new (connection);
1339 if (objects == NULL)
1342 if (_dbus_modify_sigpipe)
1343 _dbus_disable_sigpipe ();
1345 /* initialized to 0: use atomic op to avoid mixing atomic and non-atomic */
1346 _dbus_atomic_inc (&connection->refcount);
1347 connection->transport = transport;
1348 connection->watches = watch_list;
1349 connection->timeouts = timeout_list;
1350 connection->pending_replies = pending_replies;
1351 connection->outgoing_counter = outgoing_counter;
1352 connection->filter_list = NULL;
1353 connection->last_dispatch_status = DBUS_DISPATCH_COMPLETE; /* so we're notified first time there's data */
1354 connection->objects = objects;
1355 connection->exit_on_disconnect = FALSE;
1356 connection->shareable = FALSE;
1357 connection->route_peer_messages = FALSE;
1358 connection->disconnected_message_arrived = FALSE;
1359 connection->disconnected_message_processed = FALSE;
1361 #if defined(DBUS_ENABLE_CHECKS) || defined(DBUS_ENABLE_ASSERT)
1362 connection->generation = _dbus_current_generation;
1365 _dbus_data_slot_list_init (&connection->slot_list);
1367 connection->client_serial = 1;
1369 connection->disconnect_message_link = disconnect_link;
1371 #ifdef ENABLE_KDBUS_TRANSPORT
1375 CONNECTION_LOCK (connection);
1377 if (!_dbus_transport_set_connection (transport, connection))
1379 CONNECTION_UNLOCK (connection);
1384 _dbus_transport_ref (transport);
1386 CONNECTION_UNLOCK (connection);
1389 _dbus_connection_trace_ref (connection, 0, 1, "new_for_transport");
1393 if (disconnect_message != NULL)
1394 dbus_message_unref (disconnect_message);
1396 if (disconnect_link != NULL)
1397 _dbus_list_free_link (disconnect_link);
1399 if (connection != NULL)
1401 _dbus_condvar_free_at_location (&connection->io_path_cond);
1402 _dbus_condvar_free_at_location (&connection->dispatch_cond);
1403 _dbus_rmutex_free_at_location (&connection->mutex);
1404 _dbus_cmutex_free_at_location (&connection->io_path_mutex);
1405 _dbus_cmutex_free_at_location (&connection->dispatch_mutex);
1406 _dbus_rmutex_free_at_location (&connection->slot_mutex);
1407 dbus_free (connection);
1409 if (pending_replies)
1410 _dbus_hash_table_unref (pending_replies);
1413 _dbus_watch_list_free (watch_list);
1416 _dbus_timeout_list_free (timeout_list);
1418 if (outgoing_counter)
1419 _dbus_counter_unref (outgoing_counter);
1422 _dbus_object_tree_unref (objects);
1427 #ifdef ENABLE_KDBUS_TRANSPORT
1429 * Creates a new connection for the given transport. A transport
1430 * represents a message stream that uses some concrete mechanism, such
1431 * as UNIX domain sockets. May return #NULL if insufficient
1432 * memory exists to create the connection.
1434 * @param transport the transport.
1435 * @returns the new connection, or #NULL on failure.
1438 _dbus_connection_new_for_transport (DBusTransport *transport)
1440 return _dbus_connection_new_for_transport_internal(transport, FALSE);
1444 _dbus_connection_new_for_used_transport (DBusTransport *transport)
1446 return _dbus_connection_new_for_transport_internal(transport, TRUE);
1451 * Increments the reference count of a DBusConnection.
1452 * Requires that the caller already holds the connection lock.
1454 * @param connection the connection.
1455 * @returns the connection.
1458 _dbus_connection_ref_unlocked (DBusConnection *connection)
1460 dbus_int32_t old_refcount;
1462 _dbus_assert (connection != NULL);
1463 _dbus_assert (connection->generation == _dbus_current_generation);
1465 HAVE_LOCK_CHECK (connection);
1467 old_refcount = _dbus_atomic_inc (&connection->refcount);
1468 _dbus_connection_trace_ref (connection, old_refcount, old_refcount + 1,
1475 * Decrements the reference count of a DBusConnection.
1476 * Requires that the caller already holds the connection lock.
1478 * @param connection the connection.
1481 _dbus_connection_unref_unlocked (DBusConnection *connection)
1483 dbus_int32_t old_refcount;
1485 HAVE_LOCK_CHECK (connection);
1487 _dbus_assert (connection != NULL);
1489 old_refcount = _dbus_atomic_dec (&connection->refcount);
1491 _dbus_connection_trace_ref (connection, old_refcount, old_refcount - 1,
1494 if (old_refcount == 1)
1495 _dbus_connection_last_unref (connection);
1498 static dbus_uint32_t
1499 _dbus_connection_get_next_client_serial (DBusConnection *connection)
1501 dbus_uint32_t serial;
1503 serial = connection->client_serial++;
1505 if (connection->client_serial == 0)
1506 connection->client_serial = 1;
1512 * A callback for use with dbus_watch_new() to create a DBusWatch.
1514 * @todo This is basically a hack - we could delete _dbus_transport_handle_watch()
1515 * and the virtual handle_watch in DBusTransport if we got rid of it.
1516 * The reason this is some work is threading, see the _dbus_connection_handle_watch()
1519 * @param watch the watch.
1520 * @param condition the current condition of the file descriptors being watched.
1521 * @param data must be a pointer to a #DBusConnection
1522 * @returns #FALSE if the IO condition may not have been fully handled due to lack of memory
1525 _dbus_connection_handle_watch (DBusWatch *watch,
1526 unsigned int condition,
1529 DBusConnection *connection;
1531 DBusDispatchStatus status;
1535 _dbus_verbose ("start\n");
1537 CONNECTION_LOCK (connection);
1539 if (!_dbus_connection_acquire_io_path (connection, 1))
1541 /* another thread is handling the message */
1542 CONNECTION_UNLOCK (connection);
1546 HAVE_LOCK_CHECK (connection);
1547 retval = _dbus_transport_handle_watch (connection->transport,
1550 _dbus_connection_release_io_path (connection);
1552 HAVE_LOCK_CHECK (connection);
1554 _dbus_verbose ("middle\n");
1556 status = _dbus_connection_get_dispatch_status_unlocked (connection);
1558 /* this calls out to user code */
1559 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1561 _dbus_verbose ("end\n");
1566 /* Protected by _DBUS_LOCK (shared_connections) */
1567 static DBusHashTable *shared_connections = NULL;
1568 static DBusList *shared_connections_no_guid = NULL;
1571 close_connection_on_shutdown (DBusConnection *connection)
1573 DBusMessage *message;
1575 dbus_connection_ref (connection);
1576 _dbus_connection_close_possibly_shared (connection);
1578 /* Churn through to the Disconnected message */
1579 while ((message = dbus_connection_pop_message (connection)))
1581 dbus_message_unref (message);
1583 dbus_connection_unref (connection);
1587 shared_connections_shutdown (void *data)
1591 if (!_DBUS_LOCK (shared_connections))
1593 /* We'd have initialized locks before adding anything, so there
1594 * can't be anything there. */
1598 /* This is a little bit unpleasant... better ideas? */
1599 while ((n_entries = _dbus_hash_table_get_n_entries (shared_connections)) > 0)
1601 DBusConnection *connection;
1604 _dbus_hash_iter_init (shared_connections, &iter);
1605 _dbus_hash_iter_next (&iter);
1607 connection = _dbus_hash_iter_get_value (&iter);
1609 _DBUS_UNLOCK (shared_connections);
1610 close_connection_on_shutdown (connection);
1611 if (!_DBUS_LOCK (shared_connections))
1612 _dbus_assert_not_reached ("global locks were already initialized");
1614 /* The connection should now be dead and not in our hash ... */
1615 _dbus_assert (_dbus_hash_table_get_n_entries (shared_connections) < n_entries);
1618 _dbus_assert (_dbus_hash_table_get_n_entries (shared_connections) == 0);
1620 _dbus_hash_table_unref (shared_connections);
1621 shared_connections = NULL;
1623 if (shared_connections_no_guid != NULL)
1625 DBusConnection *connection;
1626 connection = _dbus_list_pop_first (&shared_connections_no_guid);
1627 while (connection != NULL)
1629 _DBUS_UNLOCK (shared_connections);
1630 close_connection_on_shutdown (connection);
1631 if (!_DBUS_LOCK (shared_connections))
1632 _dbus_assert_not_reached ("global locks were already initialized");
1633 connection = _dbus_list_pop_first (&shared_connections_no_guid);
1637 shared_connections_no_guid = NULL;
1639 _DBUS_UNLOCK (shared_connections);
1643 connection_lookup_shared (DBusAddressEntry *entry,
1644 DBusConnection **result)
1646 _dbus_verbose ("checking for existing connection\n");
1650 if (!_DBUS_LOCK (shared_connections))
1652 /* If it was shared, we'd have initialized global locks when we put
1653 * it in shared_connections. */
1657 if (shared_connections == NULL)
1659 _dbus_verbose ("creating shared_connections hash table\n");
1661 shared_connections = _dbus_hash_table_new (DBUS_HASH_STRING,
1664 if (shared_connections == NULL)
1666 _DBUS_UNLOCK (shared_connections);
1670 if (!_dbus_register_shutdown_func (shared_connections_shutdown, NULL))
1672 _dbus_hash_table_unref (shared_connections);
1673 shared_connections = NULL;
1674 _DBUS_UNLOCK (shared_connections);
1678 _dbus_verbose (" successfully created shared_connections\n");
1680 _DBUS_UNLOCK (shared_connections);
1681 return TRUE; /* no point looking up in the hash we just made */
1687 guid = dbus_address_entry_get_value (entry, "guid");
1691 DBusConnection *connection;
1693 connection = _dbus_hash_table_lookup_string (shared_connections,
1698 /* The DBusConnection can't be finalized without taking
1699 * the shared_connections lock to remove it from the
1700 * hash. So it's safe to ref the connection here.
1701 * However, it may be disconnected if the Disconnected
1702 * message hasn't been processed yet, in which case we
1703 * want to pretend it isn't in the hash and avoid
1706 * The idea is to avoid ever returning a disconnected connection
1707 * from dbus_connection_open(). We could just synchronously
1708 * drop our shared ref to the connection on connection disconnect,
1709 * and then assert here that the connection is connected, but
1710 * that causes reentrancy headaches.
1712 CONNECTION_LOCK (connection);
1713 if (_dbus_connection_get_is_connected_unlocked (connection))
1715 _dbus_connection_ref_unlocked (connection);
1716 *result = connection;
1717 _dbus_verbose ("looked up existing connection to server guid %s\n",
1722 _dbus_verbose ("looked up existing connection to server guid %s but it was disconnected so ignoring it\n",
1725 CONNECTION_UNLOCK (connection);
1729 _DBUS_UNLOCK (shared_connections);
1735 connection_record_shared_unlocked (DBusConnection *connection,
1739 char *guid_in_connection;
1741 HAVE_LOCK_CHECK (connection);
1742 _dbus_assert (connection->server_guid == NULL);
1743 _dbus_assert (connection->shareable);
1745 /* get a hard ref on this connection, even if
1746 * we won't in fact store it in the hash, we still
1747 * need to hold a ref on it until it's disconnected.
1749 _dbus_connection_ref_unlocked (connection);
1753 if (!_DBUS_LOCK (shared_connections))
1756 if (!_dbus_list_prepend (&shared_connections_no_guid, connection))
1758 _DBUS_UNLOCK (shared_connections);
1762 _DBUS_UNLOCK (shared_connections);
1763 return TRUE; /* don't store in the hash */
1766 /* A separate copy of the key is required in the hash table, because
1767 * we don't have a lock on the connection when we are doing a hash
1771 guid_key = _dbus_strdup (guid);
1772 if (guid_key == NULL)
1775 guid_in_connection = _dbus_strdup (guid);
1776 if (guid_in_connection == NULL)
1778 dbus_free (guid_key);
1782 if (!_DBUS_LOCK (shared_connections))
1784 dbus_free (guid_in_connection);
1785 dbus_free (guid_key);
1789 _dbus_assert (shared_connections != NULL);
1791 if (!_dbus_hash_table_insert_string (shared_connections,
1792 guid_key, connection))
1794 dbus_free (guid_key);
1795 dbus_free (guid_in_connection);
1796 _DBUS_UNLOCK (shared_connections);
1800 connection->server_guid = guid_in_connection;
1802 _dbus_verbose ("stored connection to %s to be shared\n",
1803 connection->server_guid);
1805 _DBUS_UNLOCK (shared_connections);
1807 _dbus_assert (connection->server_guid != NULL);
1813 connection_forget_shared_unlocked (DBusConnection *connection)
1815 HAVE_LOCK_CHECK (connection);
1817 if (!connection->shareable)
1820 if (!_DBUS_LOCK (shared_connections))
1822 /* If it was shared, we'd have initialized global locks when we put
1823 * it in the table; so it can't be there. */
1827 if (connection->server_guid != NULL)
1829 _dbus_verbose ("dropping connection to %s out of the shared table\n",
1830 connection->server_guid);
1832 if (!_dbus_hash_table_remove_string (shared_connections,
1833 connection->server_guid))
1834 _dbus_assert_not_reached ("connection was not in the shared table");
1836 dbus_free (connection->server_guid);
1837 connection->server_guid = NULL;
1841 _dbus_list_remove (&shared_connections_no_guid, connection);
1844 _DBUS_UNLOCK (shared_connections);
1846 /* remove our reference held on all shareable connections */
1847 _dbus_connection_unref_unlocked (connection);
1850 static DBusConnection*
1851 connection_try_from_address_entry (DBusAddressEntry *entry,
1854 DBusTransport *transport;
1855 DBusConnection *connection;
1857 transport = _dbus_transport_open (entry, error);
1859 if (transport == NULL)
1861 _DBUS_ASSERT_ERROR_IS_SET (error);
1865 connection = _dbus_connection_new_for_transport (transport);
1867 _dbus_transport_unref (transport);
1869 if (connection == NULL)
1871 _DBUS_SET_OOM (error);
1875 #ifndef DBUS_DISABLE_CHECKS
1876 _dbus_assert (!connection->have_connection_lock);
1883 * If the shared parameter is true, then any existing connection will
1884 * be used (and if a new connection is created, it will be available
1885 * for use by others). If the shared parameter is false, a new
1886 * connection will always be created, and the new connection will
1887 * never be returned to other callers.
1889 * @param address the address
1890 * @param shared whether the connection is shared or private
1891 * @param error error return
1892 * @returns the connection or #NULL on error
1894 static DBusConnection*
1895 _dbus_connection_open_internal (const char *address,
1899 DBusConnection *connection;
1900 DBusAddressEntry **entries;
1901 DBusError tmp_error = DBUS_ERROR_INIT;
1902 DBusError first_error = DBUS_ERROR_INIT;
1905 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1907 _dbus_verbose ("opening %s connection to: %s\n",
1908 shared ? "shared" : "private", address);
1910 if (!dbus_parse_address (address, &entries, &len, error))
1913 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1917 for (i = 0; i < len; i++)
1921 if (!connection_lookup_shared (entries[i], &connection))
1922 _DBUS_SET_OOM (&tmp_error);
1925 if (connection == NULL)
1927 connection = connection_try_from_address_entry (entries[i],
1930 if (connection != NULL && shared)
1934 connection->shareable = TRUE;
1936 /* guid may be NULL */
1937 guid = dbus_address_entry_get_value (entries[i], "guid");
1939 CONNECTION_LOCK (connection);
1941 if (!connection_record_shared_unlocked (connection, guid))
1943 _DBUS_SET_OOM (&tmp_error);
1944 _dbus_connection_close_possibly_shared_and_unlock (connection);
1945 dbus_connection_unref (connection);
1949 CONNECTION_UNLOCK (connection);
1956 _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
1959 dbus_move_error (&tmp_error, &first_error);
1961 dbus_error_free (&tmp_error);
1964 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1965 _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
1967 if (connection == NULL)
1969 _DBUS_ASSERT_ERROR_IS_SET (&first_error);
1970 dbus_move_error (&first_error, error);
1973 dbus_error_free (&first_error);
1975 dbus_address_entries_free (entries);
1980 * Closes a shared OR private connection, while dbus_connection_close() can
1981 * only be used on private connections. Should only be called by the
1982 * dbus code that owns the connection - an owner must be known,
1983 * the open/close state is like malloc/free, not like ref/unref.
1985 * @param connection the connection
1988 _dbus_connection_close_possibly_shared (DBusConnection *connection)
1990 _dbus_assert (connection != NULL);
1991 _dbus_assert (connection->generation == _dbus_current_generation);
1993 CONNECTION_LOCK (connection);
1994 _dbus_connection_close_possibly_shared_and_unlock (connection);
1997 static DBusPreallocatedSend*
1998 _dbus_connection_preallocate_send_unlocked (DBusConnection *connection)
2000 DBusPreallocatedSend *preallocated;
2002 HAVE_LOCK_CHECK (connection);
2004 _dbus_assert (connection != NULL);
2006 preallocated = dbus_new (DBusPreallocatedSend, 1);
2007 if (preallocated == NULL)
2010 preallocated->queue_link = _dbus_list_alloc_link (NULL);
2011 if (preallocated->queue_link == NULL)
2014 preallocated->counter_link = _dbus_list_alloc_link (connection->outgoing_counter);
2015 if (preallocated->counter_link == NULL)
2018 _dbus_counter_ref (preallocated->counter_link->data);
2020 preallocated->connection = connection;
2022 return preallocated;
2025 _dbus_list_free_link (preallocated->queue_link);
2027 dbus_free (preallocated);
2032 /* Called with lock held, does not update dispatch status */
2034 _dbus_connection_send_preallocated_unlocked_no_update (DBusConnection *connection,
2035 DBusPreallocatedSend *preallocated,
2036 DBusMessage *message,
2037 dbus_uint32_t *client_serial)
2039 dbus_uint32_t serial;
2041 preallocated->queue_link->data = message;
2042 _dbus_list_prepend_link (&connection->outgoing_messages,
2043 preallocated->queue_link);
2045 /* It's OK that we'll never call the notify function, because for the
2046 * outgoing limit, there isn't one */
2047 _dbus_message_add_counter_link (message,
2048 preallocated->counter_link);
2050 dbus_free (preallocated);
2051 preallocated = NULL;
2053 dbus_message_ref (message);
2055 connection->n_outgoing += 1;
2057 _dbus_verbose ("Message %p (%s %s %s %s '%s') for %s added to outgoing queue %p, %d pending to send\n",
2059 dbus_message_type_to_string (dbus_message_get_type (message)),
2060 dbus_message_get_path (message) ?
2061 dbus_message_get_path (message) :
2063 dbus_message_get_interface (message) ?
2064 dbus_message_get_interface (message) :
2066 dbus_message_get_member (message) ?
2067 dbus_message_get_member (message) :
2069 dbus_message_get_signature (message),
2070 dbus_message_get_destination (message) ?
2071 dbus_message_get_destination (message) :
2074 connection->n_outgoing);
2076 if (dbus_message_get_serial (message) == 0)
2078 serial = _dbus_connection_get_next_client_serial (connection);
2079 dbus_message_set_serial (message, serial);
2081 *client_serial = serial;
2086 *client_serial = dbus_message_get_serial (message);
2089 _dbus_verbose ("Message %p serial is %u\n",
2090 message, dbus_message_get_serial (message));
2092 dbus_message_lock (message);
2094 /* Now we need to run an iteration to hopefully just write the messages
2095 * out immediately, and otherwise get them queued up
2097 _dbus_connection_do_iteration_unlocked (connection,
2099 DBUS_ITERATION_DO_WRITING,
2102 /* If stuff is still queued up, be sure we wake up the main loop */
2103 if (connection->n_outgoing > 0)
2104 _dbus_connection_wakeup_mainloop (connection);
2108 _dbus_connection_send_preallocated_and_unlock (DBusConnection *connection,
2109 DBusPreallocatedSend *preallocated,
2110 DBusMessage *message,
2111 dbus_uint32_t *client_serial)
2113 DBusDispatchStatus status;
2115 HAVE_LOCK_CHECK (connection);
2117 _dbus_connection_send_preallocated_unlocked_no_update (connection,
2119 message, client_serial);
2121 _dbus_verbose ("middle\n");
2122 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2124 /* this calls out to user code */
2125 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2129 * Like dbus_connection_send(), but assumes the connection
2130 * is already locked on function entry, and unlocks before returning.
2132 * @param connection the connection
2133 * @param message the message to send
2134 * @param client_serial return location for client serial of sent message
2135 * @returns #FALSE on out-of-memory
2138 _dbus_connection_send_and_unlock (DBusConnection *connection,
2139 DBusMessage *message,
2140 dbus_uint32_t *client_serial)
2142 DBusPreallocatedSend *preallocated;
2144 _dbus_assert (connection != NULL);
2145 _dbus_assert (message != NULL);
2147 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
2148 if (preallocated == NULL)
2150 CONNECTION_UNLOCK (connection);
2154 _dbus_connection_send_preallocated_and_unlock (connection,
2162 * Used internally to handle the semantics of dbus_server_set_new_connection_function().
2163 * If the new connection function does not ref the connection, we want to close it.
2165 * A bit of a hack, probably the new connection function should have returned a value
2166 * for whether to close, or should have had to close the connection itself if it
2169 * But, this works OK as long as the new connection function doesn't do anything
2170 * crazy like keep the connection around without ref'ing it.
2172 * We have to lock the connection across refcount check and close in case
2173 * the new connection function spawns a thread that closes and unrefs.
2174 * In that case, if the app thread
2175 * closes and unrefs first, we'll harmlessly close again; if the app thread
2176 * still has the ref, we'll close and then the app will close harmlessly.
2177 * If the app unrefs without closing, the app is broken since if the
2178 * app refs from the new connection function it is supposed to also close.
2180 * If we didn't atomically check the refcount and close with the lock held
2181 * though, we could screw this up.
2183 * @param connection the connection
2186 _dbus_connection_close_if_only_one_ref (DBusConnection *connection)
2188 dbus_int32_t refcount;
2190 CONNECTION_LOCK (connection);
2192 refcount = _dbus_atomic_get (&connection->refcount);
2193 /* The caller should have at least one ref */
2194 _dbus_assert (refcount >= 1);
2197 _dbus_connection_close_possibly_shared_and_unlock (connection);
2199 CONNECTION_UNLOCK (connection);
2204 * When a function that blocks has been called with a timeout, and we
2205 * run out of memory, the time to wait for memory is based on the
2206 * timeout. If the caller was willing to block a long time we wait a
2207 * relatively long time for memory, if they were only willing to block
2208 * briefly then we retry for memory at a rapid rate.
2210 * @param timeout_milliseconds the timeout requested for blocking
2213 _dbus_memory_pause_based_on_timeout (int timeout_milliseconds)
2215 if (timeout_milliseconds == -1)
2216 _dbus_sleep_milliseconds (1000);
2217 else if (timeout_milliseconds < 100)
2218 ; /* just busy loop */
2219 else if (timeout_milliseconds <= 1000)
2220 _dbus_sleep_milliseconds (timeout_milliseconds / 3);
2222 _dbus_sleep_milliseconds (1000);
2226 generate_local_error_message (dbus_uint32_t serial,
2230 DBusMessage *message;
2231 message = dbus_message_new (DBUS_MESSAGE_TYPE_ERROR);
2235 if (!dbus_message_set_error_name (message, error_name))
2237 dbus_message_unref (message);
2242 dbus_message_set_no_reply (message, TRUE);
2244 if (!dbus_message_set_reply_serial (message,
2247 dbus_message_unref (message);
2252 if (error_msg != NULL)
2254 DBusMessageIter iter;
2256 dbus_message_iter_init_append (message, &iter);
2257 if (!dbus_message_iter_append_basic (&iter,
2261 dbus_message_unref (message);
2272 * Peek the incoming queue to see if we got reply for a specific serial
2275 _dbus_connection_peek_for_reply_unlocked (DBusConnection *connection,
2276 dbus_uint32_t client_serial)
2279 HAVE_LOCK_CHECK (connection);
2281 link = _dbus_list_get_first_link (&connection->incoming_messages);
2283 while (link != NULL)
2285 DBusMessage *reply = link->data;
2287 if (dbus_message_get_reply_serial (reply) == client_serial)
2289 _dbus_verbose ("%s reply to %d found in queue\n", _DBUS_FUNCTION_NAME, client_serial);
2292 link = _dbus_list_get_next_link (&connection->incoming_messages, link);
2298 /* This is slightly strange since we can pop a message here without
2299 * the dispatch lock.
2302 check_for_reply_unlocked (DBusConnection *connection,
2303 dbus_uint32_t client_serial)
2307 HAVE_LOCK_CHECK (connection);
2309 link = _dbus_list_get_first_link (&connection->incoming_messages);
2311 while (link != NULL)
2313 DBusMessage *reply = link->data;
2315 if (dbus_message_get_reply_serial (reply) == client_serial)
2317 _dbus_list_remove_link (&connection->incoming_messages, link);
2318 connection->n_incoming -= 1;
2321 link = _dbus_list_get_next_link (&connection->incoming_messages, link);
2328 connection_timeout_and_complete_all_pending_calls_unlocked (DBusConnection *connection)
2330 /* We can't iterate over the hash in the normal way since we'll be
2331 * dropping the lock for each item. So we restart the
2332 * iter each time as we drain the hash table.
2335 while (_dbus_hash_table_get_n_entries (connection->pending_replies) > 0)
2337 DBusPendingCall *pending;
2340 _dbus_hash_iter_init (connection->pending_replies, &iter);
2341 _dbus_hash_iter_next (&iter);
2343 pending = _dbus_hash_iter_get_value (&iter);
2344 _dbus_pending_call_ref_unlocked (pending);
2346 _dbus_pending_call_queue_timeout_error_unlocked (pending,
2349 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
2350 _dbus_connection_remove_timeout_unlocked (connection,
2351 _dbus_pending_call_get_timeout_unlocked (pending));
2352 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
2353 _dbus_hash_iter_remove_entry (&iter);
2355 _dbus_pending_call_unref_and_unlock (pending);
2356 CONNECTION_LOCK (connection);
2358 HAVE_LOCK_CHECK (connection);
2362 complete_pending_call_and_unlock (DBusConnection *connection,
2363 DBusPendingCall *pending,
2364 DBusMessage *message)
2366 _dbus_pending_call_set_reply_unlocked (pending, message);
2367 _dbus_pending_call_ref_unlocked (pending); /* in case there's no app with a ref held */
2368 _dbus_connection_detach_pending_call_and_unlock (connection, pending);
2370 /* Must be called unlocked since it invokes app callback */
2371 _dbus_pending_call_complete (pending);
2372 dbus_pending_call_unref (pending);
2376 check_for_reply_and_update_dispatch_unlocked (DBusConnection *connection,
2377 DBusPendingCall *pending)
2380 DBusDispatchStatus status;
2382 reply = check_for_reply_unlocked (connection,
2383 _dbus_pending_call_get_reply_serial_unlocked (pending));
2386 _dbus_verbose ("checked for reply\n");
2388 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): got reply\n");
2390 complete_pending_call_and_unlock (connection, pending, reply);
2391 dbus_message_unref (reply);
2393 CONNECTION_LOCK (connection);
2394 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2395 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2396 dbus_pending_call_unref (pending);
2405 * Blocks until a pending call times out or gets a reply.
2407 * Does not re-enter the main loop or run filter/path-registered
2408 * callbacks. The reply to the message will not be seen by
2411 * Returns immediately if pending call already got a reply.
2413 * @todo could use performance improvements (it keeps scanning
2414 * the whole message queue for example)
2416 * @param pending the pending call we block for a reply on
2419 _dbus_connection_block_pending_call (DBusPendingCall *pending)
2421 long start_tv_sec, start_tv_usec;
2422 long tv_sec, tv_usec;
2423 DBusDispatchStatus status;
2424 DBusConnection *connection;
2425 dbus_uint32_t client_serial;
2426 DBusTimeout *timeout;
2427 int timeout_milliseconds, elapsed_milliseconds;
2429 _dbus_assert (pending != NULL);
2431 if (dbus_pending_call_get_completed (pending))
2434 dbus_pending_call_ref (pending); /* necessary because the call could be canceled */
2436 connection = _dbus_pending_call_get_connection_and_lock (pending);
2438 /* Flush message queue - note, can affect dispatch status */
2439 _dbus_connection_flush_unlocked (connection);
2441 client_serial = _dbus_pending_call_get_reply_serial_unlocked (pending);
2443 /* note that timeout_milliseconds is limited to a smallish value
2444 * in _dbus_pending_call_new() so overflows aren't possible
2447 timeout = _dbus_pending_call_get_timeout_unlocked (pending);
2448 _dbus_get_monotonic_time (&start_tv_sec, &start_tv_usec);
2451 timeout_milliseconds = dbus_timeout_get_interval (timeout);
2453 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): will block %d milliseconds for reply serial %u from %ld sec %ld usec\n",
2454 timeout_milliseconds,
2456 start_tv_sec, start_tv_usec);
2460 timeout_milliseconds = -1;
2462 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): will block for reply serial %u\n", client_serial);
2465 /* check to see if we already got the data off the socket */
2466 /* from another blocked pending call */
2467 if (check_for_reply_and_update_dispatch_unlocked (connection, pending))
2470 /* Now we wait... */
2471 /* always block at least once as we know we don't have the reply yet */
2472 _dbus_connection_do_iteration_unlocked (connection,
2474 DBUS_ITERATION_DO_READING |
2475 DBUS_ITERATION_BLOCK,
2476 timeout_milliseconds);
2480 _dbus_verbose ("top of recheck\n");
2482 HAVE_LOCK_CHECK (connection);
2484 /* queue messages and get status */
2486 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2488 /* the get_completed() is in case a dispatch() while we were blocking
2489 * got the reply instead of us.
2491 if (_dbus_pending_call_get_completed_unlocked (pending))
2493 _dbus_verbose ("Pending call completed by dispatch\n");
2494 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2495 dbus_pending_call_unref (pending);
2499 if (status == DBUS_DISPATCH_DATA_REMAINS)
2501 if (check_for_reply_and_update_dispatch_unlocked (connection, pending))
2505 _dbus_get_monotonic_time (&tv_sec, &tv_usec);
2506 elapsed_milliseconds = (tv_sec - start_tv_sec) * 1000 +
2507 (tv_usec - start_tv_usec) / 1000;
2509 if (!_dbus_connection_get_is_connected_unlocked (connection))
2511 DBusMessage *error_msg;
2513 error_msg = generate_local_error_message (client_serial,
2514 DBUS_ERROR_DISCONNECTED,
2515 "Connection was disconnected before a reply was received");
2517 /* on OOM error_msg is set to NULL */
2518 complete_pending_call_and_unlock (connection, pending, error_msg);
2519 dbus_pending_call_unref (pending);
2522 else if (connection->disconnect_message_link == NULL)
2523 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): disconnected\n");
2524 else if (timeout == NULL)
2526 if (status == DBUS_DISPATCH_NEED_MEMORY)
2528 /* Try sleeping a bit, as we aren't sure we need to block for reading,
2529 * we may already have a reply in the buffer and just can't process
2532 _dbus_verbose ("dbus_connection_send_with_reply_and_block() waiting for more memory\n");
2534 _dbus_memory_pause_based_on_timeout (timeout_milliseconds - elapsed_milliseconds);
2538 /* block again, we don't have the reply buffered yet. */
2539 _dbus_connection_do_iteration_unlocked (connection,
2541 DBUS_ITERATION_DO_READING |
2542 DBUS_ITERATION_BLOCK,
2543 timeout_milliseconds - elapsed_milliseconds);
2546 goto recheck_status;
2548 else if (tv_sec < start_tv_sec)
2549 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): clock set backward\n");
2550 else if (elapsed_milliseconds < timeout_milliseconds)
2552 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): %d milliseconds remain\n", timeout_milliseconds - elapsed_milliseconds);
2554 if (status == DBUS_DISPATCH_NEED_MEMORY)
2556 /* Try sleeping a bit, as we aren't sure we need to block for reading,
2557 * we may already have a reply in the buffer and just can't process
2560 _dbus_verbose ("dbus_connection_send_with_reply_and_block() waiting for more memory\n");
2562 _dbus_memory_pause_based_on_timeout (timeout_milliseconds - elapsed_milliseconds);
2566 /* block again, we don't have the reply buffered yet. */
2567 _dbus_connection_do_iteration_unlocked (connection,
2569 DBUS_ITERATION_DO_READING |
2570 DBUS_ITERATION_BLOCK,
2571 timeout_milliseconds - elapsed_milliseconds);
2574 goto recheck_status;
2577 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): Waited %d milliseconds and got no reply\n",
2578 elapsed_milliseconds);
2580 _dbus_assert (!_dbus_pending_call_get_completed_unlocked (pending));
2582 /* unlock and call user code */
2583 complete_pending_call_and_unlock (connection, pending, NULL);
2585 /* update user code on dispatch status */
2586 CONNECTION_LOCK (connection);
2587 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2588 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2589 dbus_pending_call_unref (pending);
2595 * @addtogroup DBusConnection
2601 * Gets a connection to a remote address. If a connection to the given
2602 * address already exists, returns the existing connection with its
2603 * reference count incremented. Otherwise, returns a new connection
2604 * and saves the new connection for possible re-use if a future call
2605 * to dbus_connection_open() asks to connect to the same server.
2607 * Use dbus_connection_open_private() to get a dedicated connection
2608 * not shared with other callers of dbus_connection_open().
2610 * If the open fails, the function returns #NULL, and provides a
2611 * reason for the failure in the error parameter. Pass #NULL for the
2612 * error parameter if you aren't interested in the reason for
2615 * Because this connection is shared, no user of the connection
2616 * may call dbus_connection_close(). However, when you are done with the
2617 * connection you should call dbus_connection_unref().
2619 * @note Prefer dbus_connection_open() to dbus_connection_open_private()
2620 * unless you have good reason; connections are expensive enough
2621 * that it's wasteful to create lots of connections to the same
2624 * @param address the address.
2625 * @param error address where an error can be returned.
2626 * @returns new connection, or #NULL on failure.
2629 dbus_connection_open (const char *address,
2632 DBusConnection *connection;
2634 _dbus_return_val_if_fail (address != NULL, NULL);
2635 _dbus_return_val_if_error_is_set (error, NULL);
2637 connection = _dbus_connection_open_internal (address,
2645 * Opens a new, dedicated connection to a remote address. Unlike
2646 * dbus_connection_open(), always creates a new connection.
2647 * This connection will not be saved or recycled by libdbus.
2649 * If the open fails, the function returns #NULL, and provides a
2650 * reason for the failure in the error parameter. Pass #NULL for the
2651 * error parameter if you aren't interested in the reason for
2654 * When you are done with this connection, you must
2655 * dbus_connection_close() to disconnect it,
2656 * and dbus_connection_unref() to free the connection object.
2658 * (The dbus_connection_close() can be skipped if the
2659 * connection is already known to be disconnected, for example
2660 * if you are inside a handler for the Disconnected signal.)
2662 * @note Prefer dbus_connection_open() to dbus_connection_open_private()
2663 * unless you have good reason; connections are expensive enough
2664 * that it's wasteful to create lots of connections to the same
2667 * @param address the address.
2668 * @param error address where an error can be returned.
2669 * @returns new connection, or #NULL on failure.
2672 dbus_connection_open_private (const char *address,
2675 DBusConnection *connection;
2677 _dbus_return_val_if_fail (address != NULL, NULL);
2678 _dbus_return_val_if_error_is_set (error, NULL);
2680 connection = _dbus_connection_open_internal (address,
2688 * Increments the reference count of a DBusConnection.
2690 * @param connection the connection.
2691 * @returns the connection.
2694 dbus_connection_ref (DBusConnection *connection)
2696 dbus_int32_t old_refcount;
2698 _dbus_return_val_if_fail (connection != NULL, NULL);
2699 _dbus_return_val_if_fail (connection->generation == _dbus_current_generation, NULL);
2700 old_refcount = _dbus_atomic_inc (&connection->refcount);
2701 _dbus_connection_trace_ref (connection, old_refcount, old_refcount + 1,
2708 free_outgoing_message (void *element,
2711 DBusMessage *message = element;
2712 DBusConnection *connection = data;
2714 _dbus_message_remove_counter (message, connection->outgoing_counter);
2715 dbus_message_unref (message);
2718 #ifdef ENABLE_KDBUS_TRANSPORT
2720 _dbus_connection_last_unref_internal (DBusConnection *connection, dbus_bool_t unref_transport)
2723 _dbus_connection_last_unref (DBusConnection *connection)
2728 _dbus_verbose ("Finalizing connection %p\n", connection);
2730 _dbus_assert (_dbus_atomic_get (&connection->refcount) == 0);
2732 /* You have to disconnect the connection before unref:ing it. Otherwise
2733 * you won't get the disconnected message.
2735 #ifdef ENABLE_KDBUS_TRANSPORT
2738 _dbus_assert (!_dbus_transport_get_is_connected (connection->transport));
2739 _dbus_assert (connection->server_guid == NULL);
2741 /* ---- We're going to call various application callbacks here, hope it doesn't break anything... */
2742 _dbus_object_tree_free_all_unlocked (connection->objects);
2744 dbus_connection_set_dispatch_status_function (connection, NULL, NULL, NULL);
2745 dbus_connection_set_wakeup_main_function (connection, NULL, NULL, NULL);
2746 dbus_connection_set_unix_user_function (connection, NULL, NULL, NULL);
2747 dbus_connection_set_windows_user_function (connection, NULL, NULL, NULL);
2749 _dbus_watch_list_free (connection->watches);
2750 connection->watches = NULL;
2752 _dbus_timeout_list_free (connection->timeouts);
2753 connection->timeouts = NULL;
2755 _dbus_data_slot_list_free (&connection->slot_list);
2757 link = _dbus_list_get_first_link (&connection->filter_list);
2758 while (link != NULL)
2760 DBusMessageFilter *filter = link->data;
2761 DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
2763 filter->function = NULL;
2764 _dbus_message_filter_unref (filter); /* calls app callback */
2769 _dbus_list_clear (&connection->filter_list);
2771 /* ---- Done with stuff that invokes application callbacks */
2773 _dbus_object_tree_unref (connection->objects);
2775 _dbus_hash_table_unref (connection->pending_replies);
2776 connection->pending_replies = NULL;
2778 _dbus_list_clear (&connection->filter_list);
2780 _dbus_list_foreach (&connection->outgoing_messages,
2781 free_outgoing_message,
2783 _dbus_list_clear (&connection->outgoing_messages);
2785 _dbus_list_foreach (&connection->incoming_messages,
2786 (DBusForeachFunction) dbus_message_unref,
2788 _dbus_list_clear (&connection->incoming_messages);
2790 _dbus_counter_unref (connection->outgoing_counter);
2792 #ifdef ENABLE_KDBUS_TRANSPORT
2795 _dbus_transport_unref (connection->transport);
2797 if (connection->disconnect_message_link)
2799 DBusMessage *message = connection->disconnect_message_link->data;
2800 dbus_message_unref (message);
2801 _dbus_list_free_link (connection->disconnect_message_link);
2804 _dbus_condvar_free_at_location (&connection->dispatch_cond);
2805 _dbus_condvar_free_at_location (&connection->io_path_cond);
2807 _dbus_cmutex_free_at_location (&connection->io_path_mutex);
2808 _dbus_cmutex_free_at_location (&connection->dispatch_mutex);
2810 _dbus_rmutex_free_at_location (&connection->slot_mutex);
2812 _dbus_rmutex_free_at_location (&connection->mutex);
2814 dbus_free (connection);
2817 #ifdef ENABLE_KDBUS_TRANSPORT
2818 /* This is run without the mutex held, but after the last reference
2819 * to the connection has been dropped we should have no thread-related
2823 _dbus_connection_last_unref (DBusConnection *connection)
2825 _dbus_connection_last_unref_internal(connection, TRUE);
2830 * Decrements the reference count of a DBusConnection, and finalizes
2831 * it if the count reaches zero.
2833 * Note: it is a bug to drop the last reference to a connection that
2834 * is still connected.
2836 * For shared connections, libdbus will own a reference
2837 * as long as the connection is connected, so you can know that either
2838 * you don't have the last reference, or it's OK to drop the last reference.
2839 * Most connections are shared. dbus_connection_open() and dbus_bus_get()
2840 * return shared connections.
2842 * For private connections, the creator of the connection must arrange for
2843 * dbus_connection_close() to be called prior to dropping the last reference.
2844 * Private connections come from dbus_connection_open_private() or dbus_bus_get_private().
2846 * @param connection the connection.
2849 dbus_connection_unref (DBusConnection *connection)
2851 dbus_int32_t old_refcount;
2853 _dbus_return_if_fail (connection != NULL);
2854 _dbus_return_if_fail (connection->generation == _dbus_current_generation);
2856 old_refcount = _dbus_atomic_dec (&connection->refcount);
2858 _dbus_connection_trace_ref (connection, old_refcount, old_refcount - 1,
2861 if (old_refcount == 1)
2863 #ifndef DBUS_DISABLE_CHECKS
2864 if (_dbus_transport_get_is_connected (connection->transport))
2866 _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",
2867 connection->shareable ?
2868 "Most likely, the application called unref() too many times and removed a reference belonging to libdbus, since this is a shared connection.\n" :
2869 "Most likely, the application was supposed to call dbus_connection_close(), since this is a private connection.\n");
2873 _dbus_connection_last_unref (connection);
2877 #ifdef ENABLE_KDBUS_TRANSPORT
2879 dbus_connection_unref_phantom (DBusConnection *connection)
2881 dbus_int32_t old_refcount;
2883 _dbus_return_if_fail (connection != NULL);
2884 _dbus_return_if_fail (connection->generation == _dbus_current_generation);
2886 old_refcount = _dbus_atomic_dec (&connection->refcount);
2888 _dbus_connection_trace_ref (connection, old_refcount, old_refcount - 1, "unref");
2890 if (old_refcount == 1)
2891 _dbus_connection_last_unref_internal(connection, FALSE);
2896 * Note that the transport can disconnect itself (other end drops us)
2897 * and in that case this function never runs. So this function must
2898 * not do anything more than disconnect the transport and update the
2901 * If the transport self-disconnects, then we assume someone will
2902 * dispatch the connection to cause the dispatch status update.
2905 _dbus_connection_close_possibly_shared_and_unlock (DBusConnection *connection)
2907 DBusDispatchStatus status;
2909 HAVE_LOCK_CHECK (connection);
2911 _dbus_verbose ("Disconnecting %p\n", connection);
2913 /* We need to ref because update_dispatch_status_and_unlock will unref
2914 * the connection if it was shared and libdbus was the only remaining
2917 _dbus_connection_ref_unlocked (connection);
2919 _dbus_transport_disconnect (connection->transport);
2921 /* This has the side effect of queuing the disconnect message link
2922 * (unless we don't have enough memory, possibly, so don't assert it).
2923 * After the disconnect message link is queued, dbus_bus_get/dbus_connection_open
2924 * should never again return the newly-disconnected connection.
2926 * However, we only unref the shared connection and exit_on_disconnect when
2927 * the disconnect message reaches the head of the message queue,
2928 * NOT when it's first queued.
2930 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2932 /* This calls out to user code */
2933 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2935 /* Could also call out to user code */
2936 dbus_connection_unref (connection);
2940 * Closes a private connection, so no further data can be sent or received.
2941 * This disconnects the transport (such as a socket) underlying the
2944 * Attempts to send messages after closing a connection are safe, but will result in
2945 * error replies generated locally in libdbus.
2947 * This function does not affect the connection's reference count. It's
2948 * safe to close a connection more than once; all calls after the
2949 * first do nothing. It's impossible to "reopen" a connection, a
2950 * new connection must be created. This function may result in a call
2951 * to the DBusDispatchStatusFunction set with
2952 * dbus_connection_set_dispatch_status_function(), as the disconnect
2953 * message it generates needs to be dispatched.
2955 * If a connection is dropped by the remote application, it will
2958 * You must close a connection prior to releasing the last reference to
2959 * the connection. If you dbus_connection_unref() for the last time
2960 * without closing the connection, the results are undefined; it
2961 * is a bug in your program and libdbus will try to print a warning.
2963 * You may not close a shared connection. Connections created with
2964 * dbus_connection_open() or dbus_bus_get() are shared.
2965 * These connections are owned by libdbus, and applications should
2966 * only unref them, never close them. Applications can know it is
2967 * safe to unref these connections because libdbus will be holding a
2968 * reference as long as the connection is open. Thus, either the
2969 * connection is closed and it is OK to drop the last reference,
2970 * or the connection is open and the app knows it does not have the
2973 * Connections created with dbus_connection_open_private() or
2974 * dbus_bus_get_private() are not kept track of or referenced by
2975 * libdbus. The creator of these connections is responsible for
2976 * calling dbus_connection_close() prior to releasing the last
2977 * reference, if the connection is not already disconnected.
2979 * @param connection the private (unshared) connection to close
2982 dbus_connection_close (DBusConnection *connection)
2984 _dbus_return_if_fail (connection != NULL);
2985 _dbus_return_if_fail (connection->generation == _dbus_current_generation);
2987 CONNECTION_LOCK (connection);
2989 #ifndef DBUS_DISABLE_CHECKS
2990 if (connection->shareable)
2992 CONNECTION_UNLOCK (connection);
2994 _dbus_warn_check_failed ("Applications must not close shared connections - see dbus_connection_close() docs. This is a bug in the application.\n");
2999 _dbus_connection_close_possibly_shared_and_unlock (connection);
3003 _dbus_connection_get_is_connected_unlocked (DBusConnection *connection)
3005 HAVE_LOCK_CHECK (connection);
3006 return _dbus_transport_get_is_connected (connection->transport);
3010 * Gets whether the connection is currently open. A connection may
3011 * become disconnected when the remote application closes its end, or
3012 * exits; a connection may also be disconnected with
3013 * dbus_connection_close().
3015 * There are not separate states for "closed" and "disconnected," the two
3016 * terms are synonymous. This function should really be called
3017 * get_is_open() but for historical reasons is not.
3019 * @param connection the connection.
3020 * @returns #TRUE if the connection is still alive.
3023 dbus_connection_get_is_connected (DBusConnection *connection)
3027 _dbus_return_val_if_fail (connection != NULL, FALSE);
3029 CONNECTION_LOCK (connection);
3030 res = _dbus_connection_get_is_connected_unlocked (connection);
3031 CONNECTION_UNLOCK (connection);
3037 * Gets whether the connection was authenticated. (Note that
3038 * if the connection was authenticated then disconnected,
3039 * this function still returns #TRUE)
3041 * @param connection the connection
3042 * @returns #TRUE if the connection was ever authenticated
3045 dbus_connection_get_is_authenticated (DBusConnection *connection)
3049 _dbus_return_val_if_fail (connection != NULL, FALSE);
3051 CONNECTION_LOCK (connection);
3052 res = _dbus_transport_try_to_authenticate (connection->transport);
3053 CONNECTION_UNLOCK (connection);
3058 #ifdef ENABLE_KDBUS_TRANSPORT
3060 * Sets authenticated status for connection. Needed for kdbus, where authentication is
3061 * made in different manner.
3062 * LOCK commented out because called with lock already set
3063 * @param connection the connection
3066 dbus_connection_set_is_authenticated (DBusConnection *connection)
3068 _dbus_return_val_if_fail (connection != NULL, FALSE);
3070 // CONNECTION_LOCK (connection);
3071 connection->transport->authenticated = TRUE;
3072 // CONNECTION_UNLOCK (connection);
3079 * Gets whether the connection is not authenticated as a specific
3080 * user. If the connection is not authenticated, this function
3081 * returns #TRUE, and if it is authenticated but as an anonymous user,
3082 * it returns #TRUE. If it is authenticated as a specific user, then
3083 * this returns #FALSE. (Note that if the connection was authenticated
3084 * as anonymous then disconnected, this function still returns #TRUE.)
3086 * If the connection is not anonymous, you can use
3087 * dbus_connection_get_unix_user() and
3088 * dbus_connection_get_windows_user() to see who it's authorized as.
3090 * If you want to prevent non-anonymous authorization, use
3091 * dbus_server_set_auth_mechanisms() to remove the mechanisms that
3092 * allow proving user identity (i.e. only allow the ANONYMOUS
3095 * @param connection the connection
3096 * @returns #TRUE if not authenticated or authenticated as anonymous
3099 dbus_connection_get_is_anonymous (DBusConnection *connection)
3103 _dbus_return_val_if_fail (connection != NULL, FALSE);
3105 CONNECTION_LOCK (connection);
3106 res = _dbus_transport_get_is_anonymous (connection->transport);
3107 CONNECTION_UNLOCK (connection);
3113 * Gets the ID of the server address we are authenticated to, if this
3114 * connection is on the client side. If the connection is on the
3115 * server side, this will always return #NULL - use dbus_server_get_id()
3116 * to get the ID of your own server, if you are the server side.
3118 * If a client-side connection is not authenticated yet, the ID may be
3119 * available if it was included in the server address, but may not be
3120 * available. The only way to be sure the server ID is available
3121 * is to wait for authentication to complete.
3123 * In general, each mode of connecting to a given server will have
3124 * its own ID. So for example, if the session bus daemon is listening
3125 * on UNIX domain sockets and on TCP, then each of those modalities
3126 * will have its own server ID.
3128 * If you want an ID that identifies an entire session bus, look at
3129 * dbus_bus_get_id() instead (which is just a convenience wrapper
3130 * around the org.freedesktop.DBus.GetId method invoked on the bus).
3132 * You can also get a machine ID; see dbus_get_local_machine_id() to
3133 * get the machine you are on. There isn't a convenience wrapper, but
3134 * you can invoke org.freedesktop.DBus.Peer.GetMachineId on any peer
3135 * to get the machine ID on the other end.
3137 * The D-Bus specification describes the server ID and other IDs in a
3140 * @param connection the connection
3141 * @returns the server ID or #NULL if no memory or the connection is server-side
3144 dbus_connection_get_server_id (DBusConnection *connection)
3148 _dbus_return_val_if_fail (connection != NULL, NULL);
3150 CONNECTION_LOCK (connection);
3151 id = _dbus_strdup (_dbus_transport_get_server_id (connection->transport));
3152 CONNECTION_UNLOCK (connection);
3158 * Tests whether a certain type can be send via the connection. This
3159 * will always return TRUE for all types, with the exception of
3160 * DBUS_TYPE_UNIX_FD. The function will return TRUE for
3161 * DBUS_TYPE_UNIX_FD only on systems that know Unix file descriptors
3162 * and can send them via the chosen transport and when the remote side
3165 * This function can be used to do runtime checking for types that
3166 * might be unknown to the specific D-Bus client implementation
3167 * version, i.e. it will return FALSE for all types this
3168 * implementation does not know, including invalid or reserved types.
3170 * @param connection the connection
3171 * @param type the type to check
3172 * @returns TRUE if the type may be send via the connection
3175 dbus_connection_can_send_type(DBusConnection *connection,
3178 _dbus_return_val_if_fail (connection != NULL, FALSE);
3180 if (!dbus_type_is_valid (type))
3183 if (type != DBUS_TYPE_UNIX_FD)
3186 #ifdef HAVE_UNIX_FD_PASSING
3190 CONNECTION_LOCK(connection);
3191 b = _dbus_transport_can_pass_unix_fd(connection->transport);
3192 CONNECTION_UNLOCK(connection);
3202 * Set whether _exit() should be called when the connection receives a
3203 * disconnect signal. The call to _exit() comes after any handlers for
3204 * the disconnect signal run; handlers can cancel the exit by calling
3207 * By default, exit_on_disconnect is #FALSE; but for message bus
3208 * connections returned from dbus_bus_get() it will be toggled on
3211 * @param connection the connection
3212 * @param exit_on_disconnect #TRUE if _exit() should be called after a disconnect signal
3215 dbus_connection_set_exit_on_disconnect (DBusConnection *connection,
3216 dbus_bool_t exit_on_disconnect)
3218 _dbus_return_if_fail (connection != NULL);
3220 CONNECTION_LOCK (connection);
3221 connection->exit_on_disconnect = exit_on_disconnect != FALSE;
3222 CONNECTION_UNLOCK (connection);
3226 * Preallocates resources needed to send a message, allowing the message
3227 * to be sent without the possibility of memory allocation failure.
3228 * Allows apps to create a future guarantee that they can send
3229 * a message regardless of memory shortages.
3231 * @param connection the connection we're preallocating for.
3232 * @returns the preallocated resources, or #NULL
3234 DBusPreallocatedSend*
3235 dbus_connection_preallocate_send (DBusConnection *connection)
3237 DBusPreallocatedSend *preallocated;
3239 _dbus_return_val_if_fail (connection != NULL, NULL);
3241 CONNECTION_LOCK (connection);
3244 _dbus_connection_preallocate_send_unlocked (connection);
3246 CONNECTION_UNLOCK (connection);
3248 return preallocated;
3252 * Frees preallocated message-sending resources from
3253 * dbus_connection_preallocate_send(). Should only
3254 * be called if the preallocated resources are not used
3255 * to send a message.
3257 * @param connection the connection
3258 * @param preallocated the resources
3261 dbus_connection_free_preallocated_send (DBusConnection *connection,
3262 DBusPreallocatedSend *preallocated)
3264 _dbus_return_if_fail (connection != NULL);
3265 _dbus_return_if_fail (preallocated != NULL);
3266 _dbus_return_if_fail (connection == preallocated->connection);
3268 _dbus_list_free_link (preallocated->queue_link);
3269 _dbus_counter_unref (preallocated->counter_link->data);
3270 _dbus_list_free_link (preallocated->counter_link);
3271 dbus_free (preallocated);
3275 * Sends a message using preallocated resources. This function cannot fail.
3276 * It works identically to dbus_connection_send() in other respects.
3277 * Preallocated resources comes from dbus_connection_preallocate_send().
3278 * This function "consumes" the preallocated resources, they need not
3279 * be freed separately.
3281 * @param connection the connection
3282 * @param preallocated the preallocated resources
3283 * @param message the message to send
3284 * @param client_serial return location for client serial assigned to the message
3287 dbus_connection_send_preallocated (DBusConnection *connection,
3288 DBusPreallocatedSend *preallocated,
3289 DBusMessage *message,
3290 dbus_uint32_t *client_serial)
3292 _dbus_return_if_fail (connection != NULL);
3293 _dbus_return_if_fail (preallocated != NULL);
3294 _dbus_return_if_fail (message != NULL);
3295 _dbus_return_if_fail (preallocated->connection == connection);
3296 _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_METHOD_CALL ||
3297 dbus_message_get_member (message) != NULL);
3298 _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL ||
3299 (dbus_message_get_interface (message) != NULL &&
3300 dbus_message_get_member (message) != NULL));
3302 CONNECTION_LOCK (connection);
3304 #ifdef HAVE_UNIX_FD_PASSING
3306 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3307 message->n_unix_fds > 0)
3309 /* Refuse to send fds on a connection that cannot handle
3310 them. Unfortunately we cannot return a proper error here, so
3311 the best we can is just return. */
3312 CONNECTION_UNLOCK (connection);
3318 _dbus_connection_send_preallocated_and_unlock (connection,
3320 message, client_serial);
3324 _dbus_connection_send_unlocked_no_update (DBusConnection *connection,
3325 DBusMessage *message,
3326 dbus_uint32_t *client_serial)
3328 DBusPreallocatedSend *preallocated;
3330 _dbus_assert (connection != NULL);
3331 _dbus_assert (message != NULL);
3333 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
3334 if (preallocated == NULL)
3337 _dbus_connection_send_preallocated_unlocked_no_update (connection,
3345 * Adds a message to the outgoing message queue. Does not block to
3346 * write the message to the network; that happens asynchronously. To
3347 * force the message to be written, call dbus_connection_flush() however
3348 * it is not necessary to call dbus_connection_flush() by hand; the
3349 * message will be sent the next time the main loop is run.
3350 * dbus_connection_flush() should only be used, for example, if
3351 * the application was expected to exit before running the main loop.
3353 * Because this only queues the message, the only reason it can
3354 * fail is lack of memory. Even if the connection is disconnected,
3355 * no error will be returned. If the function fails due to lack of memory,
3356 * it returns #FALSE. The function will never fail for other reasons; even
3357 * if the connection is disconnected, you can queue an outgoing message,
3358 * though obviously it won't be sent.
3360 * The message serial is used by the remote application to send a
3361 * reply; see dbus_message_get_serial() or the D-Bus specification.
3363 * dbus_message_unref() can be called as soon as this method returns
3364 * as the message queue will hold its own ref until the message is sent.
3366 * @param connection the connection.
3367 * @param message the message to write.
3368 * @param serial return location for message serial, or #NULL if you don't care
3369 * @returns #TRUE on success.
3372 dbus_connection_send (DBusConnection *connection,
3373 DBusMessage *message,
3374 dbus_uint32_t *serial)
3376 _dbus_return_val_if_fail (connection != NULL, FALSE);
3377 _dbus_return_val_if_fail (message != NULL, FALSE);
3379 CONNECTION_LOCK (connection);
3381 #ifdef HAVE_UNIX_FD_PASSING
3383 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3384 message->n_unix_fds > 0)
3386 /* Refuse to send fds on a connection that cannot handle
3387 them. Unfortunately we cannot return a proper error here, so
3388 the best we can is just return. */
3389 CONNECTION_UNLOCK (connection);
3395 return _dbus_connection_send_and_unlock (connection,
3401 reply_handler_timeout (void *data)
3403 DBusConnection *connection;
3404 DBusDispatchStatus status;
3405 DBusPendingCall *pending = data;
3407 connection = _dbus_pending_call_get_connection_and_lock (pending);
3408 _dbus_connection_ref_unlocked (connection);
3410 _dbus_pending_call_queue_timeout_error_unlocked (pending,
3412 _dbus_connection_remove_timeout_unlocked (connection,
3413 _dbus_pending_call_get_timeout_unlocked (pending));
3414 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
3416 _dbus_verbose ("middle\n");
3417 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3419 /* Unlocks, and calls out to user code */
3420 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3421 dbus_connection_unref (connection);
3427 * Queues a message to send, as with dbus_connection_send(),
3428 * but also returns a #DBusPendingCall used to receive a reply to the
3429 * message. If no reply is received in the given timeout_milliseconds,
3430 * this function expires the pending reply and generates a synthetic
3431 * error reply (generated in-process, not by the remote application)
3432 * indicating that a timeout occurred.
3434 * A #DBusPendingCall will see a reply message before any filters or
3435 * registered object path handlers. See dbus_connection_dispatch() for
3436 * details on when handlers are run.
3438 * A #DBusPendingCall will always see exactly one reply message,
3439 * unless it's cancelled with dbus_pending_call_cancel().
3441 * If #NULL is passed for the pending_return, the #DBusPendingCall
3442 * will still be generated internally, and used to track
3443 * the message reply timeout. This means a timeout error will
3444 * occur if no reply arrives, unlike with dbus_connection_send().
3446 * If -1 is passed for the timeout, a sane default timeout is used. -1
3447 * is typically the best value for the timeout for this reason, unless
3448 * you want a very short or very long timeout. If #DBUS_TIMEOUT_INFINITE is
3449 * passed for the timeout, no timeout will be set and the call will block
3452 * @warning if the connection is disconnected or you try to send Unix
3453 * file descriptors on a connection that does not support them, the
3454 * #DBusPendingCall will be set to #NULL, so be careful with this.
3456 * @param connection the connection
3457 * @param message the message to send
3458 * @param pending_return return location for a #DBusPendingCall
3459 * object, or #NULL if connection is disconnected or when you try to
3460 * send Unix file descriptors on a connection that does not support
3462 * @param timeout_milliseconds timeout in milliseconds, -1 (or
3463 * #DBUS_TIMEOUT_USE_DEFAULT) for default or #DBUS_TIMEOUT_INFINITE for no
3465 * @returns #FALSE if no memory, #TRUE otherwise.
3469 dbus_connection_send_with_reply (DBusConnection *connection,
3470 DBusMessage *message,
3471 DBusPendingCall **pending_return,
3472 int timeout_milliseconds)
3474 DBusPendingCall *pending;
3475 dbus_int32_t serial = -1;
3476 DBusDispatchStatus status;
3478 _dbus_return_val_if_fail (connection != NULL, FALSE);
3479 _dbus_return_val_if_fail (message != NULL, FALSE);
3480 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3483 *pending_return = NULL;
3485 CONNECTION_LOCK (connection);
3487 #ifdef HAVE_UNIX_FD_PASSING
3489 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3490 message->n_unix_fds > 0)
3492 /* Refuse to send fds on a connection that cannot handle
3493 them. Unfortunately we cannot return a proper error here, so
3494 the best we can do is return TRUE but leave *pending_return
3496 CONNECTION_UNLOCK (connection);
3502 if (!_dbus_connection_get_is_connected_unlocked (connection))
3504 CONNECTION_UNLOCK (connection);
3509 pending = _dbus_pending_call_new_unlocked (connection,
3510 timeout_milliseconds,
3511 reply_handler_timeout);
3513 if (pending == NULL)
3515 CONNECTION_UNLOCK (connection);
3519 /* Assign a serial to the message */
3520 serial = dbus_message_get_serial (message);
3523 serial = _dbus_connection_get_next_client_serial (connection);
3524 dbus_message_set_serial (message, serial);
3527 if (!_dbus_pending_call_set_timeout_error_unlocked (pending, message, serial))
3530 /* Insert the serial in the pending replies hash;
3531 * hash takes a refcount on DBusPendingCall.
3532 * Also, add the timeout.
3534 if (!_dbus_connection_attach_pending_call_unlocked (connection,
3538 if (!_dbus_connection_send_unlocked_no_update (connection, message, NULL))
3540 _dbus_connection_detach_pending_call_and_unlock (connection,
3542 goto error_unlocked;
3546 *pending_return = pending; /* hand off refcount */
3549 _dbus_connection_detach_pending_call_unlocked (connection, pending);
3550 /* we still have a ref to the pending call in this case, we unref
3551 * after unlocking, below
3555 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3557 /* this calls out to user code */
3558 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3560 if (pending_return == NULL)
3561 dbus_pending_call_unref (pending);
3566 CONNECTION_UNLOCK (connection);
3568 dbus_pending_call_unref (pending);
3573 * Sends a message and blocks a certain time period while waiting for
3574 * a reply. This function does not reenter the main loop,
3575 * i.e. messages other than the reply are queued up but not
3576 * processed. This function is used to invoke method calls on a
3579 * If a normal reply is received, it is returned, and removed from the
3580 * incoming message queue. If it is not received, #NULL is returned
3581 * and the error is set to #DBUS_ERROR_NO_REPLY. If an error reply is
3582 * received, it is converted to a #DBusError and returned as an error,
3583 * then the reply message is deleted and #NULL is returned. If
3584 * something else goes wrong, result is set to whatever is
3585 * appropriate, such as #DBUS_ERROR_NO_MEMORY or
3586 * #DBUS_ERROR_DISCONNECTED.
3588 * @warning While this function blocks the calling thread will not be
3589 * processing the incoming message queue. This means you can end up
3590 * deadlocked if the application you're talking to needs you to reply
3591 * to a method. To solve this, either avoid the situation, block in a
3592 * separate thread from the main connection-dispatching thread, or use
3593 * dbus_pending_call_set_notify() to avoid blocking.
3595 * @param connection the connection
3596 * @param message the message to send
3597 * @param timeout_milliseconds timeout in milliseconds, -1 (or
3598 * #DBUS_TIMEOUT_USE_DEFAULT) for default or #DBUS_TIMEOUT_INFINITE for no
3600 * @param error return location for error message
3601 * @returns the message that is the reply or #NULL with an error code if the
3605 dbus_connection_send_with_reply_and_block (DBusConnection *connection,
3606 DBusMessage *message,
3607 int timeout_milliseconds,
3611 DBusPendingCall *pending;
3613 _dbus_return_val_if_fail (connection != NULL, NULL);
3614 _dbus_return_val_if_fail (message != NULL, NULL);
3615 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, NULL);
3616 _dbus_return_val_if_error_is_set (error, NULL);
3618 #ifdef HAVE_UNIX_FD_PASSING
3620 CONNECTION_LOCK (connection);
3621 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3622 message->n_unix_fds > 0)
3624 CONNECTION_UNLOCK (connection);
3625 dbus_set_error(error, DBUS_ERROR_FAILED, "Cannot send file descriptors on this connection.");
3628 CONNECTION_UNLOCK (connection);
3632 if (!dbus_connection_send_with_reply (connection, message,
3633 &pending, timeout_milliseconds))
3635 _DBUS_SET_OOM (error);
3639 if (pending == NULL)
3641 dbus_set_error (error, DBUS_ERROR_DISCONNECTED, "Connection is closed");
3645 dbus_pending_call_block (pending);
3647 reply = dbus_pending_call_steal_reply (pending);
3648 dbus_pending_call_unref (pending);
3650 /* call_complete_and_unlock() called from pending_call_block() should
3651 * always fill this in.
3653 _dbus_assert (reply != NULL);
3655 if (dbus_set_error_from_message (error, reply))
3657 dbus_message_unref (reply);
3665 * Blocks until the outgoing message queue is empty.
3666 * Assumes connection lock already held.
3668 * If you call this, you MUST call update_dispatch_status afterword...
3670 * @param connection the connection.
3672 static DBusDispatchStatus
3673 _dbus_connection_flush_unlocked (DBusConnection *connection)
3675 /* We have to specify DBUS_ITERATION_DO_READING here because
3676 * otherwise we could have two apps deadlock if they are both doing
3677 * a flush(), and the kernel buffers fill up. This could change the
3680 DBusDispatchStatus status;
3682 HAVE_LOCK_CHECK (connection);
3684 while (connection->n_outgoing > 0 &&
3685 _dbus_connection_get_is_connected_unlocked (connection))
3687 _dbus_verbose ("doing iteration in\n");
3688 HAVE_LOCK_CHECK (connection);
3689 _dbus_connection_do_iteration_unlocked (connection,
3691 DBUS_ITERATION_DO_READING |
3692 DBUS_ITERATION_DO_WRITING |
3693 DBUS_ITERATION_BLOCK,
3697 HAVE_LOCK_CHECK (connection);
3698 _dbus_verbose ("middle\n");
3699 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3701 HAVE_LOCK_CHECK (connection);
3706 * Blocks until the outgoing message queue is empty.
3708 * @param connection the connection.
3711 dbus_connection_flush (DBusConnection *connection)
3713 /* We have to specify DBUS_ITERATION_DO_READING here because
3714 * otherwise we could have two apps deadlock if they are both doing
3715 * a flush(), and the kernel buffers fill up. This could change the
3718 DBusDispatchStatus status;
3720 _dbus_return_if_fail (connection != NULL);
3722 CONNECTION_LOCK (connection);
3724 status = _dbus_connection_flush_unlocked (connection);
3726 HAVE_LOCK_CHECK (connection);
3727 /* Unlocks and calls out to user code */
3728 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3730 _dbus_verbose ("end\n");
3734 * This function implements dbus_connection_read_write_dispatch() and
3735 * dbus_connection_read_write() (they pass a different value for the
3736 * dispatch parameter).
3738 * @param connection the connection
3739 * @param timeout_milliseconds max time to block or -1 for infinite
3740 * @param dispatch dispatch new messages or leave them on the incoming queue
3741 * @returns #TRUE if the disconnect message has not been processed
3744 _dbus_connection_read_write_dispatch (DBusConnection *connection,
3745 int timeout_milliseconds,
3746 dbus_bool_t dispatch)
3748 DBusDispatchStatus dstatus;
3749 dbus_bool_t progress_possible;
3751 /* Need to grab a ref here in case we're a private connection and
3752 * the user drops the last ref in a handler we call; see bug
3753 * https://bugs.freedesktop.org/show_bug.cgi?id=15635
3755 dbus_connection_ref (connection);
3756 dstatus = dbus_connection_get_dispatch_status (connection);
3758 if (dispatch && dstatus == DBUS_DISPATCH_DATA_REMAINS)
3760 _dbus_verbose ("doing dispatch\n");
3761 dbus_connection_dispatch (connection);
3762 CONNECTION_LOCK (connection);
3764 else if (dstatus == DBUS_DISPATCH_NEED_MEMORY)
3766 _dbus_verbose ("pausing for memory\n");
3767 _dbus_memory_pause_based_on_timeout (timeout_milliseconds);
3768 CONNECTION_LOCK (connection);
3772 CONNECTION_LOCK (connection);
3773 if (_dbus_connection_get_is_connected_unlocked (connection))
3775 _dbus_verbose ("doing iteration\n");
3776 _dbus_connection_do_iteration_unlocked (connection,
3778 DBUS_ITERATION_DO_READING |
3779 DBUS_ITERATION_DO_WRITING |
3780 DBUS_ITERATION_BLOCK,
3781 timeout_milliseconds);
3785 HAVE_LOCK_CHECK (connection);
3786 /* If we can dispatch, we can make progress until the Disconnected message
3787 * has been processed; if we can only read/write, we can make progress
3788 * as long as the transport is open.
3791 progress_possible = connection->n_incoming != 0 ||
3792 connection->disconnect_message_link != NULL;
3794 progress_possible = _dbus_connection_get_is_connected_unlocked (connection);
3796 CONNECTION_UNLOCK (connection);
3798 dbus_connection_unref (connection);
3800 return progress_possible; /* TRUE if we can make more progress */
3805 * This function is intended for use with applications that don't want
3806 * to write a main loop and deal with #DBusWatch and #DBusTimeout. An
3807 * example usage would be:
3810 * while (dbus_connection_read_write_dispatch (connection, -1))
3811 * ; // empty loop body
3814 * In this usage you would normally have set up a filter function to look
3815 * at each message as it is dispatched. The loop terminates when the last
3816 * message from the connection (the disconnected signal) is processed.
3818 * If there are messages to dispatch, this function will
3819 * dbus_connection_dispatch() once, and return. If there are no
3820 * messages to dispatch, this function will block until it can read or
3821 * write, then read or write, then return.
3823 * The way to think of this function is that it either makes some sort
3824 * of progress, or it blocks. Note that, while it is blocked on I/O, it
3825 * cannot be interrupted (even by other threads), which makes this function
3826 * unsuitable for applications that do more than just react to received
3829 * The return value indicates whether the disconnect message has been
3830 * processed, NOT whether the connection is connected. This is
3831 * important because even after disconnecting, you want to process any
3832 * messages you received prior to the disconnect.
3834 * @param connection the connection
3835 * @param timeout_milliseconds max time to block or -1 for infinite
3836 * @returns #TRUE if the disconnect message has not been processed
3839 dbus_connection_read_write_dispatch (DBusConnection *connection,
3840 int timeout_milliseconds)
3842 _dbus_return_val_if_fail (connection != NULL, FALSE);
3843 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3844 return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, TRUE);
3848 * This function is intended for use with applications that don't want to
3849 * write a main loop and deal with #DBusWatch and #DBusTimeout. See also
3850 * dbus_connection_read_write_dispatch().
3852 * As long as the connection is open, this function will block until it can
3853 * read or write, then read or write, then return #TRUE.
3855 * If the connection is closed, the function returns #FALSE.
3857 * The return value indicates whether reading or writing is still
3858 * possible, i.e. whether the connection is connected.
3860 * Note that even after disconnection, messages may remain in the
3861 * incoming queue that need to be
3862 * processed. dbus_connection_read_write_dispatch() dispatches
3863 * incoming messages for you; with dbus_connection_read_write() you
3864 * have to arrange to drain the incoming queue yourself.
3866 * @param connection the connection
3867 * @param timeout_milliseconds max time to block or -1 for infinite
3868 * @returns #TRUE if still connected
3871 dbus_connection_read_write (DBusConnection *connection,
3872 int timeout_milliseconds)
3874 _dbus_return_val_if_fail (connection != NULL, FALSE);
3875 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3876 return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, FALSE);
3879 /* We need to call this anytime we pop the head of the queue, and then
3880 * update_dispatch_status_and_unlock needs to be called afterward
3881 * which will "process" the disconnected message and set
3882 * disconnected_message_processed.
3885 check_disconnected_message_arrived_unlocked (DBusConnection *connection,
3886 DBusMessage *head_of_queue)
3888 HAVE_LOCK_CHECK (connection);
3890 /* checking that the link is NULL is an optimization to avoid the is_signal call */
3891 if (connection->disconnect_message_link == NULL &&
3892 dbus_message_is_signal (head_of_queue,
3893 DBUS_INTERFACE_LOCAL,
3896 connection->disconnected_message_arrived = TRUE;
3901 * Returns the first-received message from the incoming message queue,
3902 * leaving it in the queue. If the queue is empty, returns #NULL.
3904 * The caller does not own a reference to the returned message, and
3905 * must either return it using dbus_connection_return_message() or
3906 * keep it after calling dbus_connection_steal_borrowed_message(). No
3907 * one can get at the message while its borrowed, so return it as
3908 * quickly as possible and don't keep a reference to it after
3909 * returning it. If you need to keep the message, make a copy of it.
3911 * dbus_connection_dispatch() will block if called while a borrowed
3912 * message is outstanding; only one piece of code can be playing with
3913 * the incoming queue at a time. This function will block if called
3914 * during a dbus_connection_dispatch().
3916 * @param connection the connection.
3917 * @returns next message in the incoming queue.
3920 dbus_connection_borrow_message (DBusConnection *connection)
3922 DBusDispatchStatus status;
3923 DBusMessage *message;
3925 _dbus_return_val_if_fail (connection != NULL, NULL);
3927 _dbus_verbose ("start\n");
3929 /* this is called for the side effect that it queues
3930 * up any messages from the transport
3932 status = dbus_connection_get_dispatch_status (connection);
3933 if (status != DBUS_DISPATCH_DATA_REMAINS)
3936 CONNECTION_LOCK (connection);
3938 _dbus_connection_acquire_dispatch (connection);
3940 /* While a message is outstanding, the dispatch lock is held */
3941 _dbus_assert (connection->message_borrowed == NULL);
3943 connection->message_borrowed = _dbus_list_get_first (&connection->incoming_messages);
3945 message = connection->message_borrowed;
3947 check_disconnected_message_arrived_unlocked (connection, message);
3949 /* Note that we KEEP the dispatch lock until the message is returned */
3950 if (message == NULL)
3951 _dbus_connection_release_dispatch (connection);
3953 CONNECTION_UNLOCK (connection);
3955 _dbus_message_trace_ref (message, -1, -1, "dbus_connection_borrow_message");
3957 /* We don't update dispatch status until it's returned or stolen */
3963 * Used to return a message after peeking at it using
3964 * dbus_connection_borrow_message(). Only called if
3965 * message from dbus_connection_borrow_message() was non-#NULL.
3967 * @param connection the connection
3968 * @param message the message from dbus_connection_borrow_message()
3971 dbus_connection_return_message (DBusConnection *connection,
3972 DBusMessage *message)
3974 DBusDispatchStatus status;
3976 _dbus_return_if_fail (connection != NULL);
3977 _dbus_return_if_fail (message != NULL);
3978 _dbus_return_if_fail (message == connection->message_borrowed);
3979 _dbus_return_if_fail (connection->dispatch_acquired);
3981 CONNECTION_LOCK (connection);
3983 _dbus_assert (message == connection->message_borrowed);
3985 connection->message_borrowed = NULL;
3987 _dbus_connection_release_dispatch (connection);
3989 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3990 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3992 _dbus_message_trace_ref (message, -1, -1, "dbus_connection_return_message");
3996 * Used to keep a message after peeking at it using
3997 * dbus_connection_borrow_message(). Before using this function, see
3998 * the caveats/warnings in the documentation for
3999 * dbus_connection_pop_message().
4001 * @param connection the connection
4002 * @param message the message from dbus_connection_borrow_message()
4005 dbus_connection_steal_borrowed_message (DBusConnection *connection,
4006 DBusMessage *message)
4008 DBusMessage *pop_message;
4009 DBusDispatchStatus status;
4011 _dbus_return_if_fail (connection != NULL);
4012 _dbus_return_if_fail (message != NULL);
4013 _dbus_return_if_fail (message == connection->message_borrowed);
4014 _dbus_return_if_fail (connection->dispatch_acquired);
4016 CONNECTION_LOCK (connection);
4018 _dbus_assert (message == connection->message_borrowed);
4020 pop_message = _dbus_list_pop_first (&connection->incoming_messages);
4021 _dbus_assert (message == pop_message);
4022 (void) pop_message; /* unused unless asserting */
4024 connection->n_incoming -= 1;
4026 _dbus_verbose ("Incoming message %p stolen from queue, %d incoming\n",
4027 message, connection->n_incoming);
4029 connection->message_borrowed = NULL;
4031 _dbus_connection_release_dispatch (connection);
4033 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4034 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4035 _dbus_message_trace_ref (message, -1, -1,
4036 "dbus_connection_steal_borrowed_message");
4039 /* See dbus_connection_pop_message, but requires the caller to own
4040 * the lock before calling. May drop the lock while running.
4043 _dbus_connection_pop_message_link_unlocked (DBusConnection *connection)
4045 HAVE_LOCK_CHECK (connection);
4047 _dbus_assert (connection->message_borrowed == NULL);
4049 if (connection->n_incoming > 0)
4053 link = _dbus_list_pop_first_link (&connection->incoming_messages);
4054 connection->n_incoming -= 1;
4056 _dbus_verbose ("Message %p (%s %s %s %s sig:'%s' serial:%u) removed from incoming queue %p, %d incoming\n",
4058 dbus_message_type_to_string (dbus_message_get_type (link->data)),
4059 dbus_message_get_path (link->data) ?
4060 dbus_message_get_path (link->data) :
4062 dbus_message_get_interface (link->data) ?
4063 dbus_message_get_interface (link->data) :
4065 dbus_message_get_member (link->data) ?
4066 dbus_message_get_member (link->data) :
4068 dbus_message_get_signature (link->data),
4069 dbus_message_get_serial (link->data),
4070 connection, connection->n_incoming);
4072 _dbus_message_trace_ref (link->data, -1, -1,
4073 "_dbus_connection_pop_message_link_unlocked");
4075 check_disconnected_message_arrived_unlocked (connection, link->data);
4083 /* See dbus_connection_pop_message, but requires the caller to own
4084 * the lock before calling. May drop the lock while running.
4087 _dbus_connection_pop_message_unlocked (DBusConnection *connection)
4091 HAVE_LOCK_CHECK (connection);
4093 link = _dbus_connection_pop_message_link_unlocked (connection);
4097 DBusMessage *message;
4099 message = link->data;
4101 _dbus_list_free_link (link);
4110 _dbus_connection_putback_message_link_unlocked (DBusConnection *connection,
4111 DBusList *message_link)
4113 HAVE_LOCK_CHECK (connection);
4115 _dbus_assert (message_link != NULL);
4116 /* You can't borrow a message while a link is outstanding */
4117 _dbus_assert (connection->message_borrowed == NULL);
4118 /* We had to have the dispatch lock across the pop/putback */
4119 _dbus_assert (connection->dispatch_acquired);
4121 _dbus_list_prepend_link (&connection->incoming_messages,
4123 connection->n_incoming += 1;
4125 _dbus_verbose ("Message %p (%s %s %s '%s') put back into queue %p, %d incoming\n",
4127 dbus_message_type_to_string (dbus_message_get_type (message_link->data)),
4128 dbus_message_get_interface (message_link->data) ?
4129 dbus_message_get_interface (message_link->data) :
4131 dbus_message_get_member (message_link->data) ?
4132 dbus_message_get_member (message_link->data) :
4134 dbus_message_get_signature (message_link->data),
4135 connection, connection->n_incoming);
4137 _dbus_message_trace_ref (message_link->data, -1, -1,
4138 "_dbus_connection_putback_message_link_unlocked");
4142 * Returns the first-received message from the incoming message queue,
4143 * removing it from the queue. The caller owns a reference to the
4144 * returned message. If the queue is empty, returns #NULL.
4146 * This function bypasses any message handlers that are registered,
4147 * and so using it is usually wrong. Instead, let the main loop invoke
4148 * dbus_connection_dispatch(). Popping messages manually is only
4149 * useful in very simple programs that don't share a #DBusConnection
4150 * with any libraries or other modules.
4152 * There is a lock that covers all ways of accessing the incoming message
4153 * queue, so dbus_connection_dispatch(), dbus_connection_pop_message(),
4154 * dbus_connection_borrow_message(), etc. will all block while one of the others
4155 * in the group is running.
4157 * @param connection the connection.
4158 * @returns next message in the incoming queue.
4161 dbus_connection_pop_message (DBusConnection *connection)
4163 DBusMessage *message;
4164 DBusDispatchStatus status;
4166 _dbus_verbose ("start\n");
4168 /* this is called for the side effect that it queues
4169 * up any messages from the transport
4171 status = dbus_connection_get_dispatch_status (connection);
4172 if (status != DBUS_DISPATCH_DATA_REMAINS)
4175 CONNECTION_LOCK (connection);
4176 _dbus_connection_acquire_dispatch (connection);
4177 HAVE_LOCK_CHECK (connection);
4179 message = _dbus_connection_pop_message_unlocked (connection);
4181 _dbus_verbose ("Returning popped message %p\n", message);
4183 _dbus_connection_release_dispatch (connection);
4185 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4186 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4192 * Acquire the dispatcher. This is a separate lock so the main
4193 * connection lock can be dropped to call out to application dispatch
4196 * @param connection the connection.
4199 _dbus_connection_acquire_dispatch (DBusConnection *connection)
4201 HAVE_LOCK_CHECK (connection);
4203 _dbus_connection_ref_unlocked (connection);
4204 CONNECTION_UNLOCK (connection);
4206 _dbus_verbose ("locking dispatch_mutex\n");
4207 _dbus_cmutex_lock (connection->dispatch_mutex);
4209 while (connection->dispatch_acquired)
4211 _dbus_verbose ("waiting for dispatch to be acquirable\n");
4212 _dbus_condvar_wait (connection->dispatch_cond,
4213 connection->dispatch_mutex);
4216 _dbus_assert (!connection->dispatch_acquired);
4218 connection->dispatch_acquired = TRUE;
4220 _dbus_verbose ("unlocking dispatch_mutex\n");
4221 _dbus_cmutex_unlock (connection->dispatch_mutex);
4223 CONNECTION_LOCK (connection);
4224 _dbus_connection_unref_unlocked (connection);
4228 * Release the dispatcher when you're done with it. Only call
4229 * after you've acquired the dispatcher. Wakes up at most one
4230 * thread currently waiting to acquire the dispatcher.
4232 * @param connection the connection.
4235 _dbus_connection_release_dispatch (DBusConnection *connection)
4237 HAVE_LOCK_CHECK (connection);
4239 _dbus_verbose ("locking dispatch_mutex\n");
4240 _dbus_cmutex_lock (connection->dispatch_mutex);
4242 _dbus_assert (connection->dispatch_acquired);
4244 connection->dispatch_acquired = FALSE;
4245 _dbus_condvar_wake_one (connection->dispatch_cond);
4247 _dbus_verbose ("unlocking dispatch_mutex\n");
4248 _dbus_cmutex_unlock (connection->dispatch_mutex);
4252 _dbus_connection_failed_pop (DBusConnection *connection,
4253 DBusList *message_link)
4255 _dbus_list_prepend_link (&connection->incoming_messages,
4257 connection->n_incoming += 1;
4260 /* Note this may be called multiple times since we don't track whether we already did it */
4262 notify_disconnected_unlocked (DBusConnection *connection)
4264 HAVE_LOCK_CHECK (connection);
4266 /* Set the weakref in dbus-bus.c to NULL, so nobody will get a disconnected
4267 * connection from dbus_bus_get(). We make the same guarantee for
4268 * dbus_connection_open() but in a different way since we don't want to
4269 * unref right here; we instead check for connectedness before returning
4270 * the connection from the hash.
4272 _dbus_bus_notify_shared_connection_disconnected_unlocked (connection);
4274 /* Dump the outgoing queue, we aren't going to be able to
4275 * send it now, and we'd like accessors like
4276 * dbus_connection_get_outgoing_size() to be accurate.
4278 if (connection->n_outgoing > 0)
4282 _dbus_verbose ("Dropping %d outgoing messages since we're disconnected\n",
4283 connection->n_outgoing);
4285 while ((link = _dbus_list_get_last_link (&connection->outgoing_messages)))
4287 _dbus_connection_message_sent_unlocked (connection, link->data);
4292 /* Note this may be called multiple times since we don't track whether we already did it */
4293 static DBusDispatchStatus
4294 notify_disconnected_and_dispatch_complete_unlocked (DBusConnection *connection)
4296 HAVE_LOCK_CHECK (connection);
4298 if (connection->disconnect_message_link != NULL)
4300 _dbus_verbose ("Sending disconnect message\n");
4302 /* If we have pending calls, queue their timeouts - we want the Disconnected
4303 * to be the last message, after these timeouts.
4305 connection_timeout_and_complete_all_pending_calls_unlocked (connection);
4307 /* We haven't sent the disconnect message already,
4308 * and all real messages have been queued up.
4310 _dbus_connection_queue_synthesized_message_link (connection,
4311 connection->disconnect_message_link);
4312 connection->disconnect_message_link = NULL;
4314 return DBUS_DISPATCH_DATA_REMAINS;
4317 return DBUS_DISPATCH_COMPLETE;
4320 static DBusDispatchStatus
4321 _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection)
4323 HAVE_LOCK_CHECK (connection);
4325 if (connection->n_incoming > 0)
4326 return DBUS_DISPATCH_DATA_REMAINS;
4327 else if (!_dbus_transport_queue_messages (connection->transport))
4328 return DBUS_DISPATCH_NEED_MEMORY;
4331 DBusDispatchStatus status;
4332 dbus_bool_t is_connected;
4334 status = _dbus_transport_get_dispatch_status (connection->transport);
4335 is_connected = _dbus_transport_get_is_connected (connection->transport);
4337 _dbus_verbose ("dispatch status = %s is_connected = %d\n",
4338 DISPATCH_STATUS_NAME (status), is_connected);
4342 /* It's possible this would be better done by having an explicit
4343 * notification from _dbus_transport_disconnect() that would
4344 * synchronously do this, instead of waiting for the next dispatch
4345 * status check. However, probably not good to change until it causes
4348 notify_disconnected_unlocked (connection);
4350 /* I'm not sure this is needed; the idea is that we want to
4351 * queue the Disconnected only after we've read all the
4352 * messages, but if we're disconnected maybe we are guaranteed
4353 * to have read them all ?
4355 if (status == DBUS_DISPATCH_COMPLETE)
4356 status = notify_disconnected_and_dispatch_complete_unlocked (connection);
4359 if (status != DBUS_DISPATCH_COMPLETE)
4361 else if (connection->n_incoming > 0)
4362 return DBUS_DISPATCH_DATA_REMAINS;
4364 return DBUS_DISPATCH_COMPLETE;
4369 _dbus_connection_update_dispatch_status_and_unlock (DBusConnection *connection,
4370 DBusDispatchStatus new_status)
4372 dbus_bool_t changed;
4373 DBusDispatchStatusFunction function;
4376 HAVE_LOCK_CHECK (connection);
4378 _dbus_connection_ref_unlocked (connection);
4380 changed = new_status != connection->last_dispatch_status;
4382 connection->last_dispatch_status = new_status;
4384 function = connection->dispatch_status_function;
4385 data = connection->dispatch_status_data;
4387 if (connection->disconnected_message_arrived &&
4388 !connection->disconnected_message_processed)
4390 connection->disconnected_message_processed = TRUE;
4392 /* this does an unref, but we have a ref
4393 * so we should not run the finalizer here
4396 connection_forget_shared_unlocked (connection);
4398 if (connection->exit_on_disconnect)
4400 CONNECTION_UNLOCK (connection);
4402 _dbus_verbose ("Exiting on Disconnected signal\n");
4404 _dbus_assert_not_reached ("Call to exit() returned");
4408 /* We drop the lock */
4409 CONNECTION_UNLOCK (connection);
4411 if (changed && function)
4413 _dbus_verbose ("Notifying of change to dispatch status of %p now %d (%s)\n",
4414 connection, new_status,
4415 DISPATCH_STATUS_NAME (new_status));
4416 (* function) (connection, new_status, data);
4419 dbus_connection_unref (connection);
4423 * Gets the current state of the incoming message queue.
4424 * #DBUS_DISPATCH_DATA_REMAINS indicates that the message queue
4425 * may contain messages. #DBUS_DISPATCH_COMPLETE indicates that the
4426 * incoming queue is empty. #DBUS_DISPATCH_NEED_MEMORY indicates that
4427 * there could be data, but we can't know for sure without more
4430 * To process the incoming message queue, use dbus_connection_dispatch()
4431 * or (in rare cases) dbus_connection_pop_message().
4433 * Note, #DBUS_DISPATCH_DATA_REMAINS really means that either we
4434 * have messages in the queue, or we have raw bytes buffered up
4435 * that need to be parsed. When these bytes are parsed, they
4436 * may not add up to an entire message. Thus, it's possible
4437 * to see a status of #DBUS_DISPATCH_DATA_REMAINS but not
4438 * have a message yet.
4440 * In particular this happens on initial connection, because all sorts
4441 * of authentication protocol stuff has to be parsed before the
4442 * first message arrives.
4444 * @param connection the connection.
4445 * @returns current dispatch status
4448 dbus_connection_get_dispatch_status (DBusConnection *connection)
4450 DBusDispatchStatus status;
4452 _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
4454 _dbus_verbose ("start\n");
4456 CONNECTION_LOCK (connection);
4458 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4460 CONNECTION_UNLOCK (connection);
4466 * Filter funtion for handling the Peer standard interface.
4468 static DBusHandlerResult
4469 _dbus_connection_peer_filter_unlocked_no_update (DBusConnection *connection,
4470 DBusMessage *message)
4472 dbus_bool_t sent = FALSE;
4473 DBusMessage *ret = NULL;
4474 DBusList *expire_link;
4476 if (connection->route_peer_messages && dbus_message_get_destination (message) != NULL)
4478 /* This means we're letting the bus route this message */
4479 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4482 if (!dbus_message_has_interface (message, DBUS_INTERFACE_PEER))
4484 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4487 /* Preallocate a linked-list link, so that if we need to dispose of a
4488 * message, we can attach it to the expired list */
4489 expire_link = _dbus_list_alloc_link (NULL);
4492 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4494 if (dbus_message_is_method_call (message,
4495 DBUS_INTERFACE_PEER,
4498 ret = dbus_message_new_method_return (message);
4502 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4504 else if (dbus_message_is_method_call (message,
4505 DBUS_INTERFACE_PEER,
4510 ret = dbus_message_new_method_return (message);
4514 _dbus_string_init (&uuid);
4515 if (_dbus_get_local_machine_uuid_encoded (&uuid))
4517 const char *v_STRING = _dbus_string_get_const_data (&uuid);
4518 if (dbus_message_append_args (ret,
4519 DBUS_TYPE_STRING, &v_STRING,
4522 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4525 _dbus_string_free (&uuid);
4529 /* We need to bounce anything else with this interface, otherwise apps
4530 * could start extending the interface and when we added extensions
4531 * here to DBusConnection we'd break those apps.
4533 ret = dbus_message_new_error (message,
4534 DBUS_ERROR_UNKNOWN_METHOD,
4535 "Unknown method invoked on org.freedesktop.DBus.Peer interface");
4539 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4545 _dbus_list_free_link (expire_link);
4549 /* It'll be safe to unref the reply when we unlock */
4550 expire_link->data = ret;
4551 _dbus_list_prepend_link (&connection->expired_messages, expire_link);
4555 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4557 return DBUS_HANDLER_RESULT_HANDLED;
4561 * Processes all builtin filter functions
4563 * If the spec specifies a standard interface
4564 * they should be processed from this method
4566 static DBusHandlerResult
4567 _dbus_connection_run_builtin_filters_unlocked_no_update (DBusConnection *connection,
4568 DBusMessage *message)
4570 /* We just run one filter for now but have the option to run more
4571 if the spec calls for it in the future */
4573 return _dbus_connection_peer_filter_unlocked_no_update (connection, message);
4577 * Processes any incoming data.
4579 * If there's incoming raw data that has not yet been parsed, it is
4580 * parsed, which may or may not result in adding messages to the
4583 * The incoming data buffer is filled when the connection reads from
4584 * its underlying transport (such as a socket). Reading usually
4585 * happens in dbus_watch_handle() or dbus_connection_read_write().
4587 * If there are complete messages in the incoming queue,
4588 * dbus_connection_dispatch() removes one message from the queue and
4589 * processes it. Processing has three steps.
4591 * First, any method replies are passed to #DBusPendingCall or
4592 * dbus_connection_send_with_reply_and_block() in order to
4593 * complete the pending method call.
4595 * Second, any filters registered with dbus_connection_add_filter()
4596 * are run. If any filter returns #DBUS_HANDLER_RESULT_HANDLED
4597 * then processing stops after that filter.
4599 * Third, if the message is a method call it is forwarded to
4600 * any registered object path handlers added with
4601 * dbus_connection_register_object_path() or
4602 * dbus_connection_register_fallback().
4604 * A single call to dbus_connection_dispatch() will process at most
4605 * one message; it will not clear the entire message queue.
4607 * Be careful about calling dbus_connection_dispatch() from inside a
4608 * message handler, i.e. calling dbus_connection_dispatch()
4609 * recursively. If threads have been initialized with a recursive
4610 * mutex function, then this will not deadlock; however, it can
4611 * certainly confuse your application.
4613 * @todo some FIXME in here about handling DBUS_HANDLER_RESULT_NEED_MEMORY
4615 * @param connection the connection
4616 * @returns dispatch status, see dbus_connection_get_dispatch_status()
4619 dbus_connection_dispatch (DBusConnection *connection)
4621 DBusMessage *message;
4622 DBusList *link, *filter_list_copy, *message_link;
4623 DBusHandlerResult result;
4624 DBusPendingCall *pending;
4625 dbus_int32_t reply_serial;
4626 DBusDispatchStatus status;
4627 dbus_bool_t found_object;
4629 _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
4631 _dbus_verbose ("\n");
4633 CONNECTION_LOCK (connection);
4634 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4635 if (status != DBUS_DISPATCH_DATA_REMAINS)
4637 /* unlocks and calls out to user code */
4638 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4642 /* We need to ref the connection since the callback could potentially
4643 * drop the last ref to it
4645 _dbus_connection_ref_unlocked (connection);
4647 _dbus_connection_acquire_dispatch (connection);
4648 HAVE_LOCK_CHECK (connection);
4650 message_link = _dbus_connection_pop_message_link_unlocked (connection);
4651 if (message_link == NULL)
4653 /* another thread dispatched our stuff */
4655 _dbus_verbose ("another thread dispatched message (during acquire_dispatch above)\n");
4657 _dbus_connection_release_dispatch (connection);
4659 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4661 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4663 dbus_connection_unref (connection);
4668 message = message_link->data;
4670 _dbus_verbose (" dispatching message %p (%s %s %s '%s')\n",
4672 dbus_message_type_to_string (dbus_message_get_type (message)),
4673 dbus_message_get_interface (message) ?
4674 dbus_message_get_interface (message) :
4676 dbus_message_get_member (message) ?
4677 dbus_message_get_member (message) :
4679 dbus_message_get_signature (message));
4681 result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4683 /* Pending call handling must be first, because if you do
4684 * dbus_connection_send_with_reply_and_block() or
4685 * dbus_pending_call_block() then no handlers/filters will be run on
4686 * the reply. We want consistent semantics in the case where we
4687 * dbus_connection_dispatch() the reply.
4690 reply_serial = dbus_message_get_reply_serial (message);
4691 pending = _dbus_hash_table_lookup_int (connection->pending_replies,
4695 _dbus_verbose ("Dispatching a pending reply\n");
4696 complete_pending_call_and_unlock (connection, pending, message);
4697 pending = NULL; /* it's probably unref'd */
4699 CONNECTION_LOCK (connection);
4700 _dbus_verbose ("pending call completed in dispatch\n");
4701 result = DBUS_HANDLER_RESULT_HANDLED;
4705 result = _dbus_connection_run_builtin_filters_unlocked_no_update (connection, message);
4706 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4709 if (!_dbus_list_copy (&connection->filter_list, &filter_list_copy))
4711 _dbus_connection_release_dispatch (connection);
4712 HAVE_LOCK_CHECK (connection);
4714 _dbus_connection_failed_pop (connection, message_link);
4716 /* unlocks and calls user code */
4717 _dbus_connection_update_dispatch_status_and_unlock (connection,
4718 DBUS_DISPATCH_NEED_MEMORY);
4719 dbus_connection_unref (connection);
4721 return DBUS_DISPATCH_NEED_MEMORY;
4724 _dbus_list_foreach (&filter_list_copy,
4725 (DBusForeachFunction)_dbus_message_filter_ref,
4728 /* We're still protected from dispatch() reentrancy here
4729 * since we acquired the dispatcher
4731 CONNECTION_UNLOCK (connection);
4733 link = _dbus_list_get_first_link (&filter_list_copy);
4734 while (link != NULL)
4736 DBusMessageFilter *filter = link->data;
4737 DBusList *next = _dbus_list_get_next_link (&filter_list_copy, link);
4739 if (filter->function == NULL)
4741 _dbus_verbose (" filter was removed in a callback function\n");
4746 _dbus_verbose (" running filter on message %p\n", message);
4747 result = (* filter->function) (connection, message, filter->user_data);
4749 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4755 _dbus_list_foreach (&filter_list_copy,
4756 (DBusForeachFunction)_dbus_message_filter_unref,
4758 _dbus_list_clear (&filter_list_copy);
4760 CONNECTION_LOCK (connection);
4762 if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
4764 _dbus_verbose ("No memory\n");
4767 else if (result == DBUS_HANDLER_RESULT_HANDLED)
4769 _dbus_verbose ("filter handled message in dispatch\n");
4773 /* We're still protected from dispatch() reentrancy here
4774 * since we acquired the dispatcher
4776 _dbus_verbose (" running object path dispatch on message %p (%s %s %s '%s')\n",
4778 dbus_message_type_to_string (dbus_message_get_type (message)),
4779 dbus_message_get_interface (message) ?
4780 dbus_message_get_interface (message) :
4782 dbus_message_get_member (message) ?
4783 dbus_message_get_member (message) :
4785 dbus_message_get_signature (message));
4787 HAVE_LOCK_CHECK (connection);
4788 result = _dbus_object_tree_dispatch_and_unlock (connection->objects,
4792 CONNECTION_LOCK (connection);
4794 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4796 _dbus_verbose ("object tree handled message in dispatch\n");
4800 if (dbus_message_get_type (message) == DBUS_MESSAGE_TYPE_METHOD_CALL)
4804 DBusPreallocatedSend *preallocated;
4805 DBusList *expire_link;
4807 _dbus_verbose (" sending error %s\n",
4808 DBUS_ERROR_UNKNOWN_METHOD);
4810 if (!_dbus_string_init (&str))
4812 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4813 _dbus_verbose ("no memory for error string in dispatch\n");
4817 if (!_dbus_string_append_printf (&str,
4818 "Method \"%s\" with signature \"%s\" on interface \"%s\" doesn't exist\n",
4819 dbus_message_get_member (message),
4820 dbus_message_get_signature (message),
4821 dbus_message_get_interface (message)))
4823 _dbus_string_free (&str);
4824 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4825 _dbus_verbose ("no memory for error string in dispatch\n");
4829 reply = dbus_message_new_error (message,
4830 found_object ? DBUS_ERROR_UNKNOWN_METHOD : DBUS_ERROR_UNKNOWN_OBJECT,
4831 _dbus_string_get_const_data (&str));
4832 _dbus_string_free (&str);
4836 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4837 _dbus_verbose ("no memory for error reply in dispatch\n");
4841 expire_link = _dbus_list_alloc_link (reply);
4843 if (expire_link == NULL)
4845 dbus_message_unref (reply);
4846 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4847 _dbus_verbose ("no memory for error send in dispatch\n");
4851 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
4853 if (preallocated == NULL)
4855 _dbus_list_free_link (expire_link);
4856 /* It's OK that this is finalized, because it hasn't been seen by
4857 * anything that could attach user callbacks */
4858 dbus_message_unref (reply);
4859 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4860 _dbus_verbose ("no memory for error send in dispatch\n");
4864 _dbus_connection_send_preallocated_unlocked_no_update (connection, preallocated,
4866 /* reply will be freed when we release the lock */
4867 _dbus_list_prepend_link (&connection->expired_messages, expire_link);
4869 result = DBUS_HANDLER_RESULT_HANDLED;
4872 _dbus_verbose (" done dispatching %p (%s %s %s '%s') on connection %p\n", message,
4873 dbus_message_type_to_string (dbus_message_get_type (message)),
4874 dbus_message_get_interface (message) ?
4875 dbus_message_get_interface (message) :
4877 dbus_message_get_member (message) ?
4878 dbus_message_get_member (message) :
4880 dbus_message_get_signature (message),
4884 if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
4886 _dbus_verbose ("out of memory\n");
4888 /* Put message back, and we'll start over.
4889 * Yes this means handlers must be idempotent if they
4890 * don't return HANDLED; c'est la vie.
4892 _dbus_connection_putback_message_link_unlocked (connection,
4894 /* now we don't want to free them */
4895 message_link = NULL;
4900 _dbus_verbose (" ... done dispatching\n");
4903 _dbus_connection_release_dispatch (connection);
4904 HAVE_LOCK_CHECK (connection);
4906 if (message != NULL)
4908 /* We don't want this message to count in maximum message limits when
4909 * computing the dispatch status, below. We have to drop the lock
4910 * temporarily, because finalizing a message can trigger callbacks.
4912 * We have a reference to the connection, and we don't use any cached
4913 * pointers to the connection's internals below this point, so it should
4914 * be safe to drop the lock and take it back. */
4915 CONNECTION_UNLOCK (connection);
4916 dbus_message_unref (message);
4917 CONNECTION_LOCK (connection);
4920 if (message_link != NULL)
4921 _dbus_list_free_link (message_link);
4923 _dbus_verbose ("before final status update\n");
4924 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4926 /* unlocks and calls user code */
4927 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4929 dbus_connection_unref (connection);
4935 * Sets the watch functions for the connection. These functions are
4936 * responsible for making the application's main loop aware of file
4937 * descriptors that need to be monitored for events, using select() or
4938 * poll(). When using Qt, typically the DBusAddWatchFunction would
4939 * create a QSocketNotifier. When using GLib, the DBusAddWatchFunction
4940 * could call g_io_add_watch(), or could be used as part of a more
4941 * elaborate GSource. Note that when a watch is added, it may
4944 * The DBusWatchToggledFunction notifies the application that the
4945 * watch has been enabled or disabled. Call dbus_watch_get_enabled()
4946 * to check this. A disabled watch should have no effect, and enabled
4947 * watch should be added to the main loop. This feature is used
4948 * instead of simply adding/removing the watch because
4949 * enabling/disabling can be done without memory allocation. The
4950 * toggled function may be NULL if a main loop re-queries
4951 * dbus_watch_get_enabled() every time anyway.
4953 * The DBusWatch can be queried for the file descriptor to watch using
4954 * dbus_watch_get_unix_fd() or dbus_watch_get_socket(), and for the
4955 * events to watch for using dbus_watch_get_flags(). The flags
4956 * returned by dbus_watch_get_flags() will only contain
4957 * DBUS_WATCH_READABLE and DBUS_WATCH_WRITABLE, never
4958 * DBUS_WATCH_HANGUP or DBUS_WATCH_ERROR; all watches implicitly
4959 * include a watch for hangups, errors, and other exceptional
4962 * Once a file descriptor becomes readable or writable, or an exception
4963 * occurs, dbus_watch_handle() should be called to
4964 * notify the connection of the file descriptor's condition.
4966 * dbus_watch_handle() cannot be called during the
4967 * DBusAddWatchFunction, as the connection will not be ready to handle
4970 * It is not allowed to reference a DBusWatch after it has been passed
4971 * to remove_function.
4973 * If #FALSE is returned due to lack of memory, the failure may be due
4974 * to a #FALSE return from the new add_function. If so, the
4975 * add_function may have been called successfully one or more times,
4976 * but the remove_function will also have been called to remove any
4977 * successful adds. i.e. if #FALSE is returned the net result
4978 * should be that dbus_connection_set_watch_functions() has no effect,
4979 * but the add_function and remove_function may have been called.
4981 * @note The thread lock on DBusConnection is held while
4982 * watch functions are invoked, so inside these functions you
4983 * may not invoke any methods on DBusConnection or it will deadlock.
4984 * See the comments in the code or http://lists.freedesktop.org/archives/dbus/2007-July/tread.html#8144
4985 * if you encounter this issue and want to attempt writing a patch.
4987 * @param connection the connection.
4988 * @param add_function function to begin monitoring a new descriptor.
4989 * @param remove_function function to stop monitoring a descriptor.
4990 * @param toggled_function function to notify of enable/disable
4991 * @param data data to pass to add_function and remove_function.
4992 * @param free_data_function function to be called to free the data.
4993 * @returns #FALSE on failure (no memory)
4996 dbus_connection_set_watch_functions (DBusConnection *connection,
4997 DBusAddWatchFunction add_function,
4998 DBusRemoveWatchFunction remove_function,
4999 DBusWatchToggledFunction toggled_function,
5001 DBusFreeFunction free_data_function)
5005 _dbus_return_val_if_fail (connection != NULL, FALSE);
5007 CONNECTION_LOCK (connection);
5009 retval = _dbus_watch_list_set_functions (connection->watches,
5010 add_function, remove_function,
5012 data, free_data_function);
5014 CONNECTION_UNLOCK (connection);
5020 * Sets the timeout functions for the connection. These functions are
5021 * responsible for making the application's main loop aware of timeouts.
5022 * When using Qt, typically the DBusAddTimeoutFunction would create a
5023 * QTimer. When using GLib, the DBusAddTimeoutFunction would call
5026 * The DBusTimeoutToggledFunction notifies the application that the
5027 * timeout has been enabled or disabled. Call
5028 * dbus_timeout_get_enabled() to check this. A disabled timeout should
5029 * have no effect, and enabled timeout should be added to the main
5030 * loop. This feature is used instead of simply adding/removing the
5031 * timeout because enabling/disabling can be done without memory
5032 * allocation. With Qt, QTimer::start() and QTimer::stop() can be used
5033 * to enable and disable. The toggled function may be NULL if a main
5034 * loop re-queries dbus_timeout_get_enabled() every time anyway.
5035 * Whenever a timeout is toggled, its interval may change.
5037 * The DBusTimeout can be queried for the timer interval using
5038 * dbus_timeout_get_interval(). dbus_timeout_handle() should be called
5039 * repeatedly, each time the interval elapses, starting after it has
5040 * elapsed once. The timeout stops firing when it is removed with the
5041 * given remove_function. The timer interval may change whenever the
5042 * timeout is added, removed, or toggled.
5044 * @note The thread lock on DBusConnection is held while
5045 * timeout functions are invoked, so inside these functions you
5046 * may not invoke any methods on DBusConnection or it will deadlock.
5047 * See the comments in the code or http://lists.freedesktop.org/archives/dbus/2007-July/thread.html#8144
5048 * if you encounter this issue and want to attempt writing a patch.
5050 * @param connection the connection.
5051 * @param add_function function to add a timeout.
5052 * @param remove_function function to remove a timeout.
5053 * @param toggled_function function to notify of enable/disable
5054 * @param data data to pass to add_function and remove_function.
5055 * @param free_data_function function to be called to free the data.
5056 * @returns #FALSE on failure (no memory)
5059 dbus_connection_set_timeout_functions (DBusConnection *connection,
5060 DBusAddTimeoutFunction add_function,
5061 DBusRemoveTimeoutFunction remove_function,
5062 DBusTimeoutToggledFunction toggled_function,
5064 DBusFreeFunction free_data_function)
5068 _dbus_return_val_if_fail (connection != NULL, FALSE);
5070 CONNECTION_LOCK (connection);
5072 retval = _dbus_timeout_list_set_functions (connection->timeouts,
5073 add_function, remove_function,
5075 data, free_data_function);
5077 CONNECTION_UNLOCK (connection);
5083 * Sets the mainloop wakeup function for the connection. This function
5084 * is responsible for waking up the main loop (if its sleeping in
5085 * another thread) when some some change has happened to the
5086 * connection that the mainloop needs to reconsider (e.g. a message
5087 * has been queued for writing). When using Qt, this typically
5088 * results in a call to QEventLoop::wakeUp(). When using GLib, it
5089 * would call g_main_context_wakeup().
5091 * @param connection the connection.
5092 * @param wakeup_main_function function to wake up the mainloop
5093 * @param data data to pass wakeup_main_function
5094 * @param free_data_function function to be called to free the data.
5097 dbus_connection_set_wakeup_main_function (DBusConnection *connection,
5098 DBusWakeupMainFunction wakeup_main_function,
5100 DBusFreeFunction free_data_function)
5103 DBusFreeFunction old_free_data;
5105 _dbus_return_if_fail (connection != NULL);
5107 CONNECTION_LOCK (connection);
5108 old_data = connection->wakeup_main_data;
5109 old_free_data = connection->free_wakeup_main_data;
5111 connection->wakeup_main_function = wakeup_main_function;
5112 connection->wakeup_main_data = data;
5113 connection->free_wakeup_main_data = free_data_function;
5115 CONNECTION_UNLOCK (connection);
5117 /* Callback outside the lock */
5119 (*old_free_data) (old_data);
5123 * Set a function to be invoked when the dispatch status changes.
5124 * If the dispatch status is #DBUS_DISPATCH_DATA_REMAINS, then
5125 * dbus_connection_dispatch() needs to be called to process incoming
5126 * messages. However, dbus_connection_dispatch() MUST NOT BE CALLED
5127 * from inside the DBusDispatchStatusFunction. Indeed, almost
5128 * any reentrancy in this function is a bad idea. Instead,
5129 * the DBusDispatchStatusFunction should simply save an indication
5130 * that messages should be dispatched later, when the main loop
5133 * If you don't set a dispatch status function, you have to be sure to
5134 * dispatch on every iteration of your main loop, especially if
5135 * dbus_watch_handle() or dbus_timeout_handle() were called.
5137 * @param connection the connection
5138 * @param function function to call on dispatch status changes
5139 * @param data data for function
5140 * @param free_data_function free the function data
5143 dbus_connection_set_dispatch_status_function (DBusConnection *connection,
5144 DBusDispatchStatusFunction function,
5146 DBusFreeFunction free_data_function)
5149 DBusFreeFunction old_free_data;
5151 _dbus_return_if_fail (connection != NULL);
5153 CONNECTION_LOCK (connection);
5154 old_data = connection->dispatch_status_data;
5155 old_free_data = connection->free_dispatch_status_data;
5157 connection->dispatch_status_function = function;
5158 connection->dispatch_status_data = data;
5159 connection->free_dispatch_status_data = free_data_function;
5161 CONNECTION_UNLOCK (connection);
5163 /* Callback outside the lock */
5165 (*old_free_data) (old_data);
5169 * Get the UNIX file descriptor of the connection, if any. This can
5170 * be used for SELinux access control checks with getpeercon() for
5171 * example. DO NOT read or write to the file descriptor, or try to
5172 * select() on it; use DBusWatch for main loop integration. Not all
5173 * connections will have a file descriptor. So for adding descriptors
5174 * to the main loop, use dbus_watch_get_unix_fd() and so forth.
5176 * If the connection is socket-based, you can also use
5177 * dbus_connection_get_socket(), which will work on Windows too.
5178 * This function always fails on Windows.
5180 * Right now the returned descriptor is always a socket, but
5181 * that is not guaranteed.
5183 * @param connection the connection
5184 * @param fd return location for the file descriptor.
5185 * @returns #TRUE if fd is successfully obtained.
5188 dbus_connection_get_unix_fd (DBusConnection *connection,
5191 _dbus_return_val_if_fail (connection != NULL, FALSE);
5192 _dbus_return_val_if_fail (connection->transport != NULL, FALSE);
5195 /* FIXME do this on a lower level */
5199 return dbus_connection_get_socket(connection, fd);
5203 * Gets the underlying Windows or UNIX socket file descriptor
5204 * of the connection, if any. DO NOT read or write to the file descriptor, or try to
5205 * select() on it; use DBusWatch for main loop integration. Not all
5206 * connections will have a socket. So for adding descriptors
5207 * to the main loop, use dbus_watch_get_socket() and so forth.
5209 * If the connection is not socket-based, this function will return FALSE,
5210 * even if the connection does have a file descriptor of some kind.
5211 * i.e. this function always returns specifically a socket file descriptor.
5213 * @param connection the connection
5214 * @param fd return location for the file descriptor.
5215 * @returns #TRUE if fd is successfully obtained.
5218 dbus_connection_get_socket(DBusConnection *connection,
5223 _dbus_return_val_if_fail (connection != NULL, FALSE);
5224 _dbus_return_val_if_fail (connection->transport != NULL, FALSE);
5226 CONNECTION_LOCK (connection);
5228 retval = _dbus_transport_get_socket_fd (connection->transport,
5231 CONNECTION_UNLOCK (connection);
5237 * Gets the UNIX user ID of the connection if known. Returns #TRUE if
5238 * the uid is filled in. Always returns #FALSE on non-UNIX platforms
5239 * for now, though in theory someone could hook Windows to NIS or
5240 * something. Always returns #FALSE prior to authenticating the
5243 * The UID is only read by servers from clients; clients can't usually
5244 * get the UID of servers, because servers do not authenticate to
5245 * clients. The returned UID is the UID the connection authenticated
5248 * The message bus is a server and the apps connecting to the bus
5251 * You can ask the bus to tell you the UID of another connection though
5252 * if you like; this is done with dbus_bus_get_unix_user().
5254 * @param connection the connection
5255 * @param uid return location for the user ID
5256 * @returns #TRUE if uid is filled in with a valid user ID
5259 dbus_connection_get_unix_user (DBusConnection *connection,
5264 _dbus_return_val_if_fail (connection != NULL, FALSE);
5265 _dbus_return_val_if_fail (uid != NULL, FALSE);
5267 CONNECTION_LOCK (connection);
5269 #ifdef ENABLE_KDBUS_TRANSPORT
5270 if (_dbus_connection_get_address (connection) != NULL)
5272 if (!strncmp (_dbus_connection_get_address (connection), "kdbus:", strlen("kdbus:")))
5273 result = kdbus_connection_get_unix_user (connection, dbus_bus_get_unique_name (connection), uid, NULL);
5278 if (!_dbus_transport_try_to_authenticate (connection->transport))
5281 result = _dbus_transport_get_unix_user (connection->transport,
5286 _dbus_assert (!result);
5289 CONNECTION_UNLOCK (connection);
5295 * Gets the process ID of the connection if any.
5296 * Returns #TRUE if the pid is filled in.
5297 * Always returns #FALSE prior to authenticating the
5300 * @param connection the connection
5301 * @param pid return location for the process ID
5302 * @returns #TRUE if uid is filled in with a valid process ID
5305 dbus_connection_get_unix_process_id (DBusConnection *connection,
5310 _dbus_return_val_if_fail (connection != NULL, FALSE);
5311 _dbus_return_val_if_fail (pid != NULL, FALSE);
5313 CONNECTION_LOCK (connection);
5315 #ifdef ENABLE_KDBUS_TRANSPORT
5316 if (_dbus_connection_get_address (connection) != NULL)
5318 if (!strncmp (_dbus_connection_get_address (connection), "kdbus:", strlen("kdbus:")))
5319 result = kdbus_connection_get_unix_process_id (connection, dbus_bus_get_unique_name (connection), pid, NULL);
5324 if (!_dbus_transport_try_to_authenticate (connection->transport))
5327 result = _dbus_transport_get_unix_process_id (connection->transport,
5331 CONNECTION_UNLOCK (connection);
5337 * Gets the ADT audit data of the connection if any.
5338 * Returns #TRUE if the structure pointer is returned.
5339 * Always returns #FALSE prior to authenticating the
5342 * @param connection the connection
5343 * @param data return location for audit data
5344 * @param data_size return location for length of audit data
5345 * @returns #TRUE if audit data is filled in with a valid ucred pointer
5348 dbus_connection_get_adt_audit_session_data (DBusConnection *connection,
5350 dbus_int32_t *data_size)
5354 _dbus_return_val_if_fail (connection != NULL, FALSE);
5355 _dbus_return_val_if_fail (data != NULL, FALSE);
5356 _dbus_return_val_if_fail (data_size != NULL, FALSE);
5358 CONNECTION_LOCK (connection);
5360 if (!_dbus_transport_try_to_authenticate (connection->transport))
5363 result = _dbus_transport_get_adt_audit_session_data (connection->transport,
5366 CONNECTION_UNLOCK (connection);
5372 * Sets a predicate function used to determine whether a given user ID
5373 * is allowed to connect. When an incoming connection has
5374 * authenticated with a particular user ID, this function is called;
5375 * if it returns #TRUE, the connection is allowed to proceed,
5376 * otherwise the connection is disconnected.
5378 * If the function is set to #NULL (as it is by default), then
5379 * only the same UID as the server process will be allowed to
5380 * connect. Also, root is always allowed to connect.
5382 * On Windows, the function will be set and its free_data_function will
5383 * be invoked when the connection is freed or a new function is set.
5384 * However, the function will never be called, because there are
5385 * no UNIX user ids to pass to it, or at least none of the existing
5386 * auth protocols would allow authenticating as a UNIX user on Windows.
5388 * @param connection the connection
5389 * @param function the predicate
5390 * @param data data to pass to the predicate
5391 * @param free_data_function function to free the data
5394 dbus_connection_set_unix_user_function (DBusConnection *connection,
5395 DBusAllowUnixUserFunction function,
5397 DBusFreeFunction free_data_function)
5399 void *old_data = NULL;
5400 DBusFreeFunction old_free_function = NULL;
5402 _dbus_return_if_fail (connection != NULL);
5404 CONNECTION_LOCK (connection);
5405 _dbus_transport_set_unix_user_function (connection->transport,
5406 function, data, free_data_function,
5407 &old_data, &old_free_function);
5408 CONNECTION_UNLOCK (connection);
5410 if (old_free_function != NULL)
5411 (* old_free_function) (old_data);
5415 * Gets the Windows user SID of the connection if known. Returns
5416 * #TRUE if the ID is filled in. Always returns #FALSE on non-Windows
5417 * platforms for now, though in theory someone could hook UNIX to
5418 * Active Directory or something. Always returns #FALSE prior to
5419 * authenticating the connection.
5421 * The user is only read by servers from clients; clients can't usually
5422 * get the user of servers, because servers do not authenticate to
5423 * clients. The returned user is the user the connection authenticated
5426 * The message bus is a server and the apps connecting to the bus
5429 * The returned user string has to be freed with dbus_free().
5431 * The return value indicates whether the user SID is available;
5432 * if it's available but we don't have the memory to copy it,
5433 * then the return value is #TRUE and #NULL is given as the SID.
5435 * @todo We would like to be able to say "You can ask the bus to tell
5436 * you the user of another connection though if you like; this is done
5437 * with dbus_bus_get_windows_user()." But this has to be implemented
5438 * in bus/driver.c and dbus/dbus-bus.c, and is pointless anyway
5439 * since on Windows we only use the session bus for now.
5441 * @param connection the connection
5442 * @param windows_sid_p return location for an allocated copy of the user ID, or #NULL if no memory
5443 * @returns #TRUE if user is available (returned value may be #NULL anyway if no memory)
5446 dbus_connection_get_windows_user (DBusConnection *connection,
5447 char **windows_sid_p)
5451 _dbus_return_val_if_fail (connection != NULL, FALSE);
5452 _dbus_return_val_if_fail (windows_sid_p != NULL, FALSE);
5454 CONNECTION_LOCK (connection);
5456 if (!_dbus_transport_try_to_authenticate (connection->transport))
5459 result = _dbus_transport_get_windows_user (connection->transport,
5463 _dbus_assert (!result);
5466 CONNECTION_UNLOCK (connection);
5472 * Sets a predicate function used to determine whether a given user ID
5473 * is allowed to connect. When an incoming connection has
5474 * authenticated with a particular user ID, this function is called;
5475 * if it returns #TRUE, the connection is allowed to proceed,
5476 * otherwise the connection is disconnected.
5478 * If the function is set to #NULL (as it is by default), then
5479 * only the same user owning the server process will be allowed to
5482 * On UNIX, the function will be set and its free_data_function will
5483 * be invoked when the connection is freed or a new function is set.
5484 * However, the function will never be called, because there is no
5485 * way right now to authenticate as a Windows user on UNIX.
5487 * @param connection the connection
5488 * @param function the predicate
5489 * @param data data to pass to the predicate
5490 * @param free_data_function function to free the data
5493 dbus_connection_set_windows_user_function (DBusConnection *connection,
5494 DBusAllowWindowsUserFunction function,
5496 DBusFreeFunction free_data_function)
5498 void *old_data = NULL;
5499 DBusFreeFunction old_free_function = NULL;
5501 _dbus_return_if_fail (connection != NULL);
5503 CONNECTION_LOCK (connection);
5504 _dbus_transport_set_windows_user_function (connection->transport,
5505 function, data, free_data_function,
5506 &old_data, &old_free_function);
5507 CONNECTION_UNLOCK (connection);
5509 if (old_free_function != NULL)
5510 (* old_free_function) (old_data);
5514 * This function must be called on the server side of a connection when the
5515 * connection is first seen in the #DBusNewConnectionFunction. If set to
5516 * #TRUE (the default is #FALSE), then the connection can proceed even if
5517 * the client does not authenticate as some user identity, i.e. clients
5518 * can connect anonymously.
5520 * This setting interacts with the available authorization mechanisms
5521 * (see dbus_server_set_auth_mechanisms()). Namely, an auth mechanism
5522 * such as ANONYMOUS that supports anonymous auth must be included in
5523 * the list of available mechanisms for anonymous login to work.
5525 * This setting also changes the default rule for connections
5526 * authorized as a user; normally, if a connection authorizes as
5527 * a user identity, it is permitted if the user identity is
5528 * root or the user identity matches the user identity of the server
5529 * process. If anonymous connections are allowed, however,
5530 * then any user identity is allowed.
5532 * You can override the rules for connections authorized as a
5533 * user identity with dbus_connection_set_unix_user_function()
5534 * and dbus_connection_set_windows_user_function().
5536 * @param connection the connection
5537 * @param value whether to allow authentication as an anonymous user
5540 dbus_connection_set_allow_anonymous (DBusConnection *connection,
5543 _dbus_return_if_fail (connection != NULL);
5545 CONNECTION_LOCK (connection);
5546 _dbus_transport_set_allow_anonymous (connection->transport, value);
5547 CONNECTION_UNLOCK (connection);
5552 * Normally #DBusConnection automatically handles all messages to the
5553 * org.freedesktop.DBus.Peer interface. However, the message bus wants
5554 * to be able to route methods on that interface through the bus and
5555 * to other applications. If routing peer messages is enabled, then
5556 * messages with the org.freedesktop.DBus.Peer interface that also
5557 * have a bus destination name set will not be automatically
5558 * handled by the #DBusConnection and instead will be dispatched
5559 * normally to the application.
5561 * If a normal application sets this flag, it can break things badly.
5562 * So don't set this unless you are the message bus.
5564 * @param connection the connection
5565 * @param value #TRUE to pass through org.freedesktop.DBus.Peer messages with a bus name set
5568 dbus_connection_set_route_peer_messages (DBusConnection *connection,
5571 _dbus_return_if_fail (connection != NULL);
5573 CONNECTION_LOCK (connection);
5574 connection->route_peer_messages = TRUE;
5575 CONNECTION_UNLOCK (connection);
5579 * Adds a message filter. Filters are handlers that are run on all
5580 * incoming messages, prior to the objects registered with
5581 * dbus_connection_register_object_path(). Filters are run in the
5582 * order that they were added. The same handler can be added as a
5583 * filter more than once, in which case it will be run more than once.
5584 * Filters added during a filter callback won't be run on the message
5587 * @todo we don't run filters on messages while blocking without
5588 * entering the main loop, since filters are run as part of
5589 * dbus_connection_dispatch(). This is probably a feature, as filters
5590 * could create arbitrary reentrancy. But kind of sucks if you're
5591 * trying to filter METHOD_RETURN for some reason.
5593 * @param connection the connection
5594 * @param function function to handle messages
5595 * @param user_data user data to pass to the function
5596 * @param free_data_function function to use for freeing user data
5597 * @returns #TRUE on success, #FALSE if not enough memory.
5600 dbus_connection_add_filter (DBusConnection *connection,
5601 DBusHandleMessageFunction function,
5603 DBusFreeFunction free_data_function)
5605 DBusMessageFilter *filter;
5607 _dbus_return_val_if_fail (connection != NULL, FALSE);
5608 _dbus_return_val_if_fail (function != NULL, FALSE);
5610 filter = dbus_new0 (DBusMessageFilter, 1);
5614 _dbus_atomic_inc (&filter->refcount);
5616 CONNECTION_LOCK (connection);
5618 if (!_dbus_list_append (&connection->filter_list,
5621 _dbus_message_filter_unref (filter);
5622 CONNECTION_UNLOCK (connection);
5626 /* Fill in filter after all memory allocated,
5627 * so we don't run the free_user_data_function
5628 * if the add_filter() fails
5631 filter->function = function;
5632 filter->user_data = user_data;
5633 filter->free_user_data_function = free_data_function;
5635 CONNECTION_UNLOCK (connection);
5640 * Removes a previously-added message filter. It is a programming
5641 * error to call this function for a handler that has not been added
5642 * as a filter. If the given handler was added more than once, only
5643 * one instance of it will be removed (the most recently-added
5646 * @param connection the connection
5647 * @param function the handler to remove
5648 * @param user_data user data for the handler to remove
5652 dbus_connection_remove_filter (DBusConnection *connection,
5653 DBusHandleMessageFunction function,
5657 DBusMessageFilter *filter;
5659 _dbus_return_if_fail (connection != NULL);
5660 _dbus_return_if_fail (function != NULL);
5662 CONNECTION_LOCK (connection);
5666 link = _dbus_list_get_last_link (&connection->filter_list);
5667 while (link != NULL)
5669 filter = link->data;
5671 if (filter->function == function &&
5672 filter->user_data == user_data)
5674 _dbus_list_remove_link (&connection->filter_list, link);
5675 filter->function = NULL;
5680 link = _dbus_list_get_prev_link (&connection->filter_list, link);
5684 CONNECTION_UNLOCK (connection);
5686 #ifndef DBUS_DISABLE_CHECKS
5689 _dbus_warn_check_failed ("Attempt to remove filter function %p user data %p, but no such filter has been added\n",
5690 function, user_data);
5695 /* Call application code */
5696 if (filter->free_user_data_function)
5697 (* filter->free_user_data_function) (filter->user_data);
5699 filter->free_user_data_function = NULL;
5700 filter->user_data = NULL;
5702 _dbus_message_filter_unref (filter);
5706 * Registers a handler for a given path or subsection in the object
5707 * hierarchy. The given vtable handles messages sent to exactly the
5708 * given path or also for paths bellow that, depending on fallback
5711 * @param connection the connection
5712 * @param fallback whether to handle messages also for "subdirectory"
5713 * @param path a '/' delimited string of path elements
5714 * @param vtable the virtual table
5715 * @param user_data data to pass to functions in the vtable
5716 * @param error address where an error can be returned
5717 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5718 * #DBUS_ERROR_OBJECT_PATH_IN_USE) is reported
5721 _dbus_connection_register_object_path (DBusConnection *connection,
5722 dbus_bool_t fallback,
5724 const DBusObjectPathVTable *vtable,
5728 char **decomposed_path;
5731 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5734 CONNECTION_LOCK (connection);
5736 retval = _dbus_object_tree_register (connection->objects,
5738 (const char **) decomposed_path, vtable,
5741 CONNECTION_UNLOCK (connection);
5743 dbus_free_string_array (decomposed_path);
5749 * Registers a handler for a given path in the object hierarchy.
5750 * The given vtable handles messages sent to exactly the given path.
5752 * @param connection the connection
5753 * @param path a '/' delimited string of path elements
5754 * @param vtable the virtual table
5755 * @param user_data data to pass to functions in the vtable
5756 * @param error address where an error can be returned
5757 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5758 * #DBUS_ERROR_OBJECT_PATH_IN_USE) is reported
5761 dbus_connection_try_register_object_path (DBusConnection *connection,
5763 const DBusObjectPathVTable *vtable,
5767 _dbus_return_val_if_fail (connection != NULL, FALSE);
5768 _dbus_return_val_if_fail (path != NULL, FALSE);
5769 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5770 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5772 return _dbus_connection_register_object_path (connection, FALSE, path, vtable, user_data, error);
5776 * Registers a handler for a given path in the object hierarchy.
5777 * The given vtable handles messages sent to exactly the given path.
5779 * It is a bug to call this function for object paths which already
5780 * have a handler. Use dbus_connection_try_register_object_path() if this
5781 * might be the case.
5783 * @param connection the connection
5784 * @param path a '/' delimited string of path elements
5785 * @param vtable the virtual table
5786 * @param user_data data to pass to functions in the vtable
5787 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5788 * #DBUS_ERROR_OBJECT_PATH_IN_USE) ocurred
5791 dbus_connection_register_object_path (DBusConnection *connection,
5793 const DBusObjectPathVTable *vtable,
5797 DBusError error = DBUS_ERROR_INIT;
5799 _dbus_return_val_if_fail (connection != NULL, FALSE);
5800 _dbus_return_val_if_fail (path != NULL, FALSE);
5801 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5802 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5804 retval = _dbus_connection_register_object_path (connection, FALSE, path, vtable, user_data, &error);
5806 if (dbus_error_has_name (&error, DBUS_ERROR_OBJECT_PATH_IN_USE))
5808 _dbus_warn ("%s\n", error.message);
5809 dbus_error_free (&error);
5817 * Registers a fallback handler for a given subsection of the object
5818 * hierarchy. The given vtable handles messages at or below the given
5819 * path. You can use this to establish a default message handling
5820 * policy for a whole "subdirectory."
5822 * @param connection the connection
5823 * @param path a '/' delimited string of path elements
5824 * @param vtable the virtual table
5825 * @param user_data data to pass to functions in the vtable
5826 * @param error address where an error can be returned
5827 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5828 * #DBUS_ERROR_OBJECT_PATH_IN_USE) is reported
5831 dbus_connection_try_register_fallback (DBusConnection *connection,
5833 const DBusObjectPathVTable *vtable,
5837 _dbus_return_val_if_fail (connection != NULL, FALSE);
5838 _dbus_return_val_if_fail (path != NULL, FALSE);
5839 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5840 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5842 return _dbus_connection_register_object_path (connection, TRUE, path, vtable, user_data, error);
5846 * Registers a fallback handler for a given subsection of the object
5847 * hierarchy. The given vtable handles messages at or below the given
5848 * path. You can use this to establish a default message handling
5849 * policy for a whole "subdirectory."
5851 * It is a bug to call this function for object paths which already
5852 * have a handler. Use dbus_connection_try_register_fallback() if this
5853 * might be the case.
5855 * @param connection the connection
5856 * @param path a '/' delimited string of path elements
5857 * @param vtable the virtual table
5858 * @param user_data data to pass to functions in the vtable
5859 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5860 * #DBUS_ERROR_OBJECT_PATH_IN_USE) occured
5863 dbus_connection_register_fallback (DBusConnection *connection,
5865 const DBusObjectPathVTable *vtable,
5869 DBusError error = DBUS_ERROR_INIT;
5871 _dbus_return_val_if_fail (connection != NULL, FALSE);
5872 _dbus_return_val_if_fail (path != NULL, FALSE);
5873 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5874 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5876 retval = _dbus_connection_register_object_path (connection, TRUE, path, vtable, user_data, &error);
5878 if (dbus_error_has_name (&error, DBUS_ERROR_OBJECT_PATH_IN_USE))
5880 _dbus_warn ("%s\n", error.message);
5881 dbus_error_free (&error);
5889 * Unregisters the handler registered with exactly the given path.
5890 * It's a bug to call this function for a path that isn't registered.
5891 * Can unregister both fallback paths and object paths.
5893 * @param connection the connection
5894 * @param path a '/' delimited string of path elements
5895 * @returns #FALSE if not enough memory
5898 dbus_connection_unregister_object_path (DBusConnection *connection,
5901 char **decomposed_path;
5903 _dbus_return_val_if_fail (connection != NULL, FALSE);
5904 _dbus_return_val_if_fail (path != NULL, FALSE);
5905 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5907 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5910 CONNECTION_LOCK (connection);
5912 _dbus_object_tree_unregister_and_unlock (connection->objects, (const char **) decomposed_path);
5914 dbus_free_string_array (decomposed_path);
5920 * Gets the user data passed to dbus_connection_register_object_path()
5921 * or dbus_connection_register_fallback(). If nothing was registered
5922 * at this path, the data is filled in with #NULL.
5924 * @param connection the connection
5925 * @param path the path you registered with
5926 * @param data_p location to store the user data, or #NULL
5927 * @returns #FALSE if not enough memory
5930 dbus_connection_get_object_path_data (DBusConnection *connection,
5934 char **decomposed_path;
5936 _dbus_return_val_if_fail (connection != NULL, FALSE);
5937 _dbus_return_val_if_fail (path != NULL, FALSE);
5938 _dbus_return_val_if_fail (data_p != NULL, FALSE);
5942 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5945 CONNECTION_LOCK (connection);
5947 *data_p = _dbus_object_tree_get_user_data_unlocked (connection->objects, (const char**) decomposed_path);
5949 CONNECTION_UNLOCK (connection);
5951 dbus_free_string_array (decomposed_path);
5957 * Lists the registered fallback handlers and object path handlers at
5958 * the given parent_path. The returned array should be freed with
5959 * dbus_free_string_array().
5961 * @param connection the connection
5962 * @param parent_path the path to list the child handlers of
5963 * @param child_entries returns #NULL-terminated array of children
5964 * @returns #FALSE if no memory to allocate the child entries
5967 dbus_connection_list_registered (DBusConnection *connection,
5968 const char *parent_path,
5969 char ***child_entries)
5971 char **decomposed_path;
5973 _dbus_return_val_if_fail (connection != NULL, FALSE);
5974 _dbus_return_val_if_fail (parent_path != NULL, FALSE);
5975 _dbus_return_val_if_fail (parent_path[0] == '/', FALSE);
5976 _dbus_return_val_if_fail (child_entries != NULL, FALSE);
5978 if (!_dbus_decompose_path (parent_path, strlen (parent_path), &decomposed_path, NULL))
5981 CONNECTION_LOCK (connection);
5983 retval = _dbus_object_tree_list_registered_and_unlock (connection->objects,
5984 (const char **) decomposed_path,
5986 dbus_free_string_array (decomposed_path);
5991 static DBusDataSlotAllocator slot_allocator =
5992 _DBUS_DATA_SLOT_ALLOCATOR_INIT (_DBUS_LOCK_NAME (connection_slots));
5995 * Allocates an integer ID to be used for storing application-specific
5996 * data on any DBusConnection. The allocated ID may then be used
5997 * with dbus_connection_set_data() and dbus_connection_get_data().
5998 * The passed-in slot must be initialized to -1, and is filled in
5999 * with the slot ID. If the passed-in slot is not -1, it's assumed
6000 * to be already allocated, and its refcount is incremented.
6002 * The allocated slot is global, i.e. all DBusConnection objects will
6003 * have a slot with the given integer ID reserved.
6005 * @param slot_p address of a global variable storing the slot
6006 * @returns #FALSE on failure (no memory)
6009 dbus_connection_allocate_data_slot (dbus_int32_t *slot_p)
6011 return _dbus_data_slot_allocator_alloc (&slot_allocator,
6016 * Deallocates a global ID for connection data slots.
6017 * dbus_connection_get_data() and dbus_connection_set_data() may no
6018 * longer be used with this slot. Existing data stored on existing
6019 * DBusConnection objects will be freed when the connection is
6020 * finalized, but may not be retrieved (and may only be replaced if
6021 * someone else reallocates the slot). When the refcount on the
6022 * passed-in slot reaches 0, it is set to -1.
6024 * @param slot_p address storing the slot to deallocate
6027 dbus_connection_free_data_slot (dbus_int32_t *slot_p)
6029 _dbus_return_if_fail (*slot_p >= 0);
6031 _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
6035 * Stores a pointer on a DBusConnection, along
6036 * with an optional function to be used for freeing
6037 * the data when the data is set again, or when
6038 * the connection is finalized. The slot number
6039 * must have been allocated with dbus_connection_allocate_data_slot().
6041 * @note This function does not take the
6042 * main thread lock on DBusConnection, which allows it to be
6043 * used from inside watch and timeout functions. (See the
6044 * note in docs for dbus_connection_set_watch_functions().)
6045 * A side effect of this is that you need to know there's
6046 * a reference held on the connection while invoking
6047 * dbus_connection_set_data(), or the connection could be
6048 * finalized during dbus_connection_set_data().
6050 * @param connection the connection
6051 * @param slot the slot number
6052 * @param data the data to store
6053 * @param free_data_func finalizer function for the data
6054 * @returns #TRUE if there was enough memory to store the data
6057 dbus_connection_set_data (DBusConnection *connection,
6060 DBusFreeFunction free_data_func)
6062 DBusFreeFunction old_free_func;
6066 _dbus_return_val_if_fail (connection != NULL, FALSE);
6067 _dbus_return_val_if_fail (slot >= 0, FALSE);
6069 SLOTS_LOCK (connection);
6071 retval = _dbus_data_slot_list_set (&slot_allocator,
6072 &connection->slot_list,
6073 slot, data, free_data_func,
6074 &old_free_func, &old_data);
6076 SLOTS_UNLOCK (connection);
6080 /* Do the actual free outside the connection lock */
6082 (* old_free_func) (old_data);
6089 * Retrieves data previously set with dbus_connection_set_data().
6090 * The slot must still be allocated (must not have been freed).
6092 * @note This function does not take the
6093 * main thread lock on DBusConnection, which allows it to be
6094 * used from inside watch and timeout functions. (See the
6095 * note in docs for dbus_connection_set_watch_functions().)
6096 * A side effect of this is that you need to know there's
6097 * a reference held on the connection while invoking
6098 * dbus_connection_get_data(), or the connection could be
6099 * finalized during dbus_connection_get_data().
6101 * @param connection the connection
6102 * @param slot the slot to get data from
6103 * @returns the data, or #NULL if not found
6106 dbus_connection_get_data (DBusConnection *connection,
6111 _dbus_return_val_if_fail (connection != NULL, NULL);
6112 _dbus_return_val_if_fail (slot >= 0, NULL);
6114 SLOTS_LOCK (connection);
6116 res = _dbus_data_slot_list_get (&slot_allocator,
6117 &connection->slot_list,
6120 SLOTS_UNLOCK (connection);
6126 * This function sets a global flag for whether dbus_connection_new()
6127 * will set SIGPIPE behavior to SIG_IGN.
6129 * @param will_modify_sigpipe #TRUE to allow sigpipe to be set to SIG_IGN
6132 dbus_connection_set_change_sigpipe (dbus_bool_t will_modify_sigpipe)
6134 _dbus_modify_sigpipe = will_modify_sigpipe != FALSE;
6138 * Specifies the maximum size message this connection is allowed to
6139 * receive. Larger messages will result in disconnecting the
6142 * @param connection a #DBusConnection
6143 * @param size maximum message size the connection can receive, in bytes
6146 dbus_connection_set_max_message_size (DBusConnection *connection,
6149 _dbus_return_if_fail (connection != NULL);
6151 CONNECTION_LOCK (connection);
6152 _dbus_transport_set_max_message_size (connection->transport,
6154 CONNECTION_UNLOCK (connection);
6158 * Gets the value set by dbus_connection_set_max_message_size().
6160 * @param connection the connection
6161 * @returns the max size of a single message
6164 dbus_connection_get_max_message_size (DBusConnection *connection)
6168 _dbus_return_val_if_fail (connection != NULL, 0);
6170 CONNECTION_LOCK (connection);
6171 res = _dbus_transport_get_max_message_size (connection->transport);
6172 CONNECTION_UNLOCK (connection);
6177 * Specifies the maximum number of unix fds a message on this
6178 * connection is allowed to receive. Messages with more unix fds will
6179 * result in disconnecting the connection.
6181 * @param connection a #DBusConnection
6182 * @param n maximum message unix fds the connection can receive
6185 dbus_connection_set_max_message_unix_fds (DBusConnection *connection,
6188 _dbus_return_if_fail (connection != NULL);
6190 CONNECTION_LOCK (connection);
6191 _dbus_transport_set_max_message_unix_fds (connection->transport,
6193 CONNECTION_UNLOCK (connection);
6197 * Gets the value set by dbus_connection_set_max_message_unix_fds().
6199 * @param connection the connection
6200 * @returns the max numer of unix fds of a single message
6203 dbus_connection_get_max_message_unix_fds (DBusConnection *connection)
6207 _dbus_return_val_if_fail (connection != NULL, 0);
6209 CONNECTION_LOCK (connection);
6210 res = _dbus_transport_get_max_message_unix_fds (connection->transport);
6211 CONNECTION_UNLOCK (connection);
6216 * Sets the maximum total number of bytes that can be used for all messages
6217 * received on this connection. Messages count toward the maximum until
6218 * they are finalized. When the maximum is reached, the connection will
6219 * not read more data until some messages are finalized.
6221 * The semantics of the maximum are: if outstanding messages are
6222 * already above the maximum, additional messages will not be read.
6223 * The semantics are not: if the next message would cause us to exceed
6224 * the maximum, we don't read it. The reason is that we don't know the
6225 * size of a message until after we read it.
6227 * Thus, the max live messages size can actually be exceeded
6228 * by up to the maximum size of a single message.
6230 * Also, if we read say 1024 bytes off the wire in a single read(),
6231 * and that contains a half-dozen small messages, we may exceed the
6232 * size max by that amount. But this should be inconsequential.
6234 * This does imply that we can't call read() with a buffer larger
6235 * than we're willing to exceed this limit by.
6237 * @param connection the connection
6238 * @param size the maximum size in bytes of all outstanding messages
6241 dbus_connection_set_max_received_size (DBusConnection *connection,
6244 _dbus_return_if_fail (connection != NULL);
6246 CONNECTION_LOCK (connection);
6247 _dbus_transport_set_max_received_size (connection->transport,
6249 CONNECTION_UNLOCK (connection);
6253 * Gets the value set by dbus_connection_set_max_received_size().
6255 * @param connection the connection
6256 * @returns the max size of all live messages
6259 dbus_connection_get_max_received_size (DBusConnection *connection)
6263 _dbus_return_val_if_fail (connection != NULL, 0);
6265 CONNECTION_LOCK (connection);
6266 res = _dbus_transport_get_max_received_size (connection->transport);
6267 CONNECTION_UNLOCK (connection);
6272 * Sets the maximum total number of unix fds that can be used for all messages
6273 * received on this connection. Messages count toward the maximum until
6274 * they are finalized. When the maximum is reached, the connection will
6275 * not read more data until some messages are finalized.
6277 * The semantics are analogous to those of dbus_connection_set_max_received_size().
6279 * @param connection the connection
6280 * @param n the maximum size in bytes of all outstanding messages
6283 dbus_connection_set_max_received_unix_fds (DBusConnection *connection,
6286 _dbus_return_if_fail (connection != NULL);
6288 CONNECTION_LOCK (connection);
6289 _dbus_transport_set_max_received_unix_fds (connection->transport,
6291 CONNECTION_UNLOCK (connection);
6295 * Gets the value set by dbus_connection_set_max_received_unix_fds().
6297 * @param connection the connection
6298 * @returns the max unix fds of all live messages
6301 dbus_connection_get_max_received_unix_fds (DBusConnection *connection)
6305 _dbus_return_val_if_fail (connection != NULL, 0);
6307 CONNECTION_LOCK (connection);
6308 res = _dbus_transport_get_max_received_unix_fds (connection->transport);
6309 CONNECTION_UNLOCK (connection);
6314 * Gets the approximate size in bytes of all messages in the outgoing
6315 * message queue. The size is approximate in that you shouldn't use
6316 * it to decide how many bytes to read off the network or anything
6317 * of that nature, as optimizations may choose to tell small white lies
6318 * to avoid performance overhead.
6320 * @param connection the connection
6321 * @returns the number of bytes that have been queued up but not sent
6324 dbus_connection_get_outgoing_size (DBusConnection *connection)
6328 _dbus_return_val_if_fail (connection != NULL, 0);
6330 CONNECTION_LOCK (connection);
6331 res = _dbus_counter_get_size_value (connection->outgoing_counter);
6332 CONNECTION_UNLOCK (connection);
6336 #ifdef DBUS_ENABLE_STATS
6338 _dbus_connection_get_stats (DBusConnection *connection,
6339 dbus_uint32_t *in_messages,
6340 dbus_uint32_t *in_bytes,
6341 dbus_uint32_t *in_fds,
6342 dbus_uint32_t *in_peak_bytes,
6343 dbus_uint32_t *in_peak_fds,
6344 dbus_uint32_t *out_messages,
6345 dbus_uint32_t *out_bytes,
6346 dbus_uint32_t *out_fds,
6347 dbus_uint32_t *out_peak_bytes,
6348 dbus_uint32_t *out_peak_fds)
6350 CONNECTION_LOCK (connection);
6352 if (in_messages != NULL)
6353 *in_messages = connection->n_incoming;
6355 _dbus_transport_get_stats (connection->transport,
6356 in_bytes, in_fds, in_peak_bytes, in_peak_fds);
6358 if (out_messages != NULL)
6359 *out_messages = connection->n_outgoing;
6361 if (out_bytes != NULL)
6362 *out_bytes = _dbus_counter_get_size_value (connection->outgoing_counter);
6364 if (out_fds != NULL)
6365 *out_fds = _dbus_counter_get_unix_fd_value (connection->outgoing_counter);
6367 if (out_peak_bytes != NULL)
6368 *out_peak_bytes = _dbus_counter_get_peak_size_value (connection->outgoing_counter);
6370 if (out_peak_fds != NULL)
6371 *out_peak_fds = _dbus_counter_get_peak_unix_fd_value (connection->outgoing_counter);
6373 CONNECTION_UNLOCK (connection);
6375 #endif /* DBUS_ENABLE_STATS */
6378 * Gets the approximate number of uni fds of all messages in the
6379 * outgoing message queue.
6381 * @param connection the connection
6382 * @returns the number of unix fds that have been queued up but not sent
6385 dbus_connection_get_outgoing_unix_fds (DBusConnection *connection)
6389 _dbus_return_val_if_fail (connection != NULL, 0);
6391 CONNECTION_LOCK (connection);
6392 res = _dbus_counter_get_unix_fd_value (connection->outgoing_counter);
6393 CONNECTION_UNLOCK (connection);
6398 * Returns the address of the transport object of this connection
6400 * @param connection the connection
6401 * @returns the address string
6404 _dbus_connection_get_address (DBusConnection *connection)
6406 return _dbus_transport_get_address (connection->transport);
6409 #ifdef ENABLE_KDBUS_TRANSPORT
6411 dbus_connection_get_transport(DBusConnection *connection)
6413 _dbus_return_val_if_fail (connection != NULL, NULL);
6415 return connection->transport;