1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-connection.c DBusConnection object
4 * Copyright (C) 2002-2006 Red Hat Inc.
6 * Licensed under the Academic Free License version 2.1
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 #include "dbus-shared.h"
26 #include "dbus-connection.h"
27 #include "dbus-list.h"
28 #include "dbus-timeout.h"
29 #include "dbus-transport.h"
30 #include "dbus-watch.h"
31 #include "dbus-connection-internal.h"
32 #include "dbus-pending-call-internal.h"
33 #include "dbus-list.h"
34 #include "dbus-hash.h"
35 #include "dbus-message-internal.h"
36 #include "dbus-message-private.h"
37 #include "dbus-threads.h"
38 #include "dbus-protocol.h"
39 #include "dbus-dataslot.h"
40 #include "dbus-string.h"
41 #include "dbus-pending-call.h"
42 #include "dbus-object-tree.h"
43 #include "dbus-threads-internal.h"
45 #include "dbus-marshal-basic.h"
47 #ifdef DBUS_DISABLE_CHECKS
48 #define TOOK_LOCK_CHECK(connection)
49 #define RELEASING_LOCK_CHECK(connection)
50 #define HAVE_LOCK_CHECK(connection)
52 #define TOOK_LOCK_CHECK(connection) do { \
53 _dbus_assert (!(connection)->have_connection_lock); \
54 (connection)->have_connection_lock = TRUE; \
56 #define RELEASING_LOCK_CHECK(connection) do { \
57 _dbus_assert ((connection)->have_connection_lock); \
58 (connection)->have_connection_lock = FALSE; \
60 #define HAVE_LOCK_CHECK(connection) _dbus_assert ((connection)->have_connection_lock)
61 /* A "DO_NOT_HAVE_LOCK_CHECK" is impossible since we need the lock to check the flag */
66 #define CONNECTION_LOCK(connection) do { \
67 if (TRACE_LOCKS) { _dbus_verbose ("LOCK\n"); } \
68 _dbus_mutex_lock ((connection)->mutex); \
69 TOOK_LOCK_CHECK (connection); \
72 #define CONNECTION_UNLOCK(connection) do { \
73 if (TRACE_LOCKS) { _dbus_verbose ("UNLOCK\n"); } \
74 RELEASING_LOCK_CHECK (connection); \
75 _dbus_mutex_unlock ((connection)->mutex); \
78 #define SLOTS_LOCK(connection) do { \
79 _dbus_mutex_lock ((connection)->slot_mutex); \
82 #define SLOTS_UNLOCK(connection) do { \
83 _dbus_mutex_unlock ((connection)->slot_mutex); \
86 #define DISPATCH_STATUS_NAME(s) \
87 ((s) == DBUS_DISPATCH_COMPLETE ? "complete" : \
88 (s) == DBUS_DISPATCH_DATA_REMAINS ? "data remains" : \
89 (s) == DBUS_DISPATCH_NEED_MEMORY ? "need memory" : \
93 * @defgroup DBusConnection DBusConnection
95 * @brief Connection to another application
97 * A DBusConnection represents a connection to another
98 * application. Messages can be sent and received via this connection.
99 * The other application may be a message bus; for convenience, the
100 * function dbus_bus_get() is provided to automatically open a
101 * connection to the well-known message buses.
103 * In brief a DBusConnection is a message queue associated with some
104 * message transport mechanism such as a socket. The connection
105 * maintains a queue of incoming messages and a queue of outgoing
108 * Several functions use the following terms:
110 * <li><b>read</b> means to fill the incoming message queue by reading from the socket</li>
111 * <li><b>write</b> means to drain the outgoing queue by writing to the socket</li>
112 * <li><b>dispatch</b> means to drain the incoming queue by invoking application-provided message handlers</li>
115 * The function dbus_connection_read_write_dispatch() for example does all
116 * three of these things, offering a simple alternative to a main loop.
118 * In an application with a main loop, the read/write/dispatch
119 * operations are usually separate.
121 * The connection provides #DBusWatch and #DBusTimeout objects to
122 * the main loop. These are used to know when reading, writing, or
123 * dispatching should be performed.
125 * Incoming messages are processed
126 * by calling dbus_connection_dispatch(). dbus_connection_dispatch()
127 * runs any handlers registered for the topmost message in the message
128 * queue, then discards the message, then returns.
130 * dbus_connection_get_dispatch_status() indicates whether
131 * messages are currently in the queue that need dispatching.
132 * dbus_connection_set_dispatch_status_function() allows
133 * you to set a function to be used to monitor the dispatch status.
135 * If you're using GLib or Qt add-on libraries for D-Bus, there are
136 * special convenience APIs in those libraries that hide
137 * all the details of dispatch and watch/timeout monitoring.
138 * For example, dbus_connection_setup_with_g_main().
140 * If you aren't using these add-on libraries, but want to process
141 * messages asynchronously, you must manually call
142 * dbus_connection_set_dispatch_status_function(),
143 * dbus_connection_set_watch_functions(),
144 * dbus_connection_set_timeout_functions() providing appropriate
145 * functions to integrate the connection with your application's main
146 * loop. This can be tricky to get right; main loops are not simple.
148 * If you don't need to be asynchronous, you can ignore #DBusWatch,
149 * #DBusTimeout, and dbus_connection_dispatch(). Instead,
150 * dbus_connection_read_write_dispatch() can be used.
152 * Or, in <em>very</em> simple applications,
153 * dbus_connection_pop_message() may be all you need, allowing you to
154 * avoid setting up any handler functions (see
155 * dbus_connection_add_filter(),
156 * dbus_connection_register_object_path() for more on handlers).
158 * When you use dbus_connection_send() or one of its variants to send
159 * a message, the message is added to the outgoing queue. It's
160 * actually written to the network later; either in
161 * dbus_watch_handle() invoked by your main loop, or in
162 * dbus_connection_flush() which blocks until it can write out the
163 * entire outgoing queue. The GLib/Qt add-on libraries again
164 * handle the details here for you by setting up watch functions.
166 * When a connection is disconnected, you are guaranteed to get a
167 * signal "Disconnected" from the interface
168 * #DBUS_INTERFACE_LOCAL, path
171 * You may not drop the last reference to a #DBusConnection
172 * until that connection has been disconnected.
174 * You may dispatch the unprocessed incoming message queue even if the
175 * connection is disconnected. However, "Disconnected" will always be
176 * the last message in the queue (obviously no messages are received
177 * after disconnection).
179 * After calling dbus_threads_init(), #DBusConnection has thread
180 * locks and drops them when invoking user callbacks, so in general is
181 * transparently threadsafe. However, #DBusMessage does NOT have
182 * thread locks; you must not send the same message to multiple
183 * #DBusConnection if those connections will be used from different threads,
186 * Also, if you dispatch or pop messages from multiple threads, it
187 * may work in the sense that it won't crash, but it's tough to imagine
188 * sane results; it will be completely unpredictable which messages
189 * go to which threads.
191 * It's recommended to dispatch from a single thread.
193 * The most useful function to call from multiple threads at once
194 * is dbus_connection_send_with_reply_and_block(). That is,
195 * multiple threads can make method calls at the same time.
197 * If you aren't using threads, you can use a main loop and
198 * dbus_pending_call_set_notify() to achieve a similar result.
202 * @defgroup DBusConnectionInternals DBusConnection implementation details
203 * @ingroup DBusInternals
204 * @brief Implementation details of DBusConnection
210 * Internal struct representing a message filter function
212 typedef struct DBusMessageFilter DBusMessageFilter;
215 * Internal struct representing a message filter function
217 struct DBusMessageFilter
219 DBusAtomic refcount; /**< Reference count */
220 DBusHandleMessageFunction function; /**< Function to call to filter */
221 void *user_data; /**< User data for the function */
222 DBusFreeFunction free_user_data_function; /**< Function to free the user data */
227 * Internals of DBusPreallocatedSend
229 struct DBusPreallocatedSend
231 DBusConnection *connection; /**< Connection we'd send the message to */
232 DBusList *queue_link; /**< Preallocated link in the queue */
233 DBusList *counter_link; /**< Preallocated link in the resource counter */
236 #if HAVE_DECL_MSG_NOSIGNAL
237 static dbus_bool_t _dbus_modify_sigpipe = FALSE;
239 static dbus_bool_t _dbus_modify_sigpipe = TRUE;
243 * Implementation details of DBusConnection. All fields are private.
245 struct DBusConnection
247 DBusAtomic refcount; /**< Reference count. */
249 DBusMutex *mutex; /**< Lock on the entire DBusConnection */
251 DBusMutex *dispatch_mutex; /**< Protects dispatch_acquired */
252 DBusCondVar *dispatch_cond; /**< Notify when dispatch_acquired is available */
253 DBusMutex *io_path_mutex; /**< Protects io_path_acquired */
254 DBusCondVar *io_path_cond; /**< Notify when io_path_acquired is available */
256 DBusList *outgoing_messages; /**< Queue of messages we need to send, send the end of the list first. */
257 DBusList *incoming_messages; /**< Queue of messages we have received, end of the list received most recently. */
259 DBusMessage *message_borrowed; /**< Filled in if the first incoming message has been borrowed;
260 * dispatch_acquired will be set by the borrower
263 int n_outgoing; /**< Length of outgoing queue. */
264 int n_incoming; /**< Length of incoming queue. */
266 DBusCounter *outgoing_counter; /**< Counts size of outgoing messages. */
268 DBusTransport *transport; /**< Object that sends/receives messages over network. */
269 DBusWatchList *watches; /**< Stores active watches. */
270 DBusTimeoutList *timeouts; /**< Stores active timeouts. */
272 DBusList *filter_list; /**< List of filters. */
274 DBusMutex *slot_mutex; /**< Lock on slot_list so overall connection lock need not be taken */
275 DBusDataSlotList slot_list; /**< Data stored by allocated integer ID */
277 DBusHashTable *pending_replies; /**< Hash of message serials to #DBusPendingCall. */
279 dbus_uint32_t client_serial; /**< Client serial. Increments each time a message is sent */
280 DBusList *disconnect_message_link; /**< Preallocated list node for queueing the disconnection message */
282 DBusWakeupMainFunction wakeup_main_function; /**< Function to wake up the mainloop */
283 void *wakeup_main_data; /**< Application data for wakeup_main_function */
284 DBusFreeFunction free_wakeup_main_data; /**< free wakeup_main_data */
286 DBusDispatchStatusFunction dispatch_status_function; /**< Function on dispatch status changes */
287 void *dispatch_status_data; /**< Application data for dispatch_status_function */
288 DBusFreeFunction free_dispatch_status_data; /**< free dispatch_status_data */
290 DBusDispatchStatus last_dispatch_status; /**< The last dispatch status we reported to the application. */
292 DBusList *link_cache; /**< A cache of linked list links to prevent contention
293 * for the global linked list mempool lock
295 DBusObjectTree *objects; /**< Object path handlers registered with this connection */
297 char *server_guid; /**< GUID of server if we are in shared_connections, #NULL if server GUID is unknown or connection is private */
299 /* These two MUST be bools and not bitfields, because they are protected by a separate lock
300 * from connection->mutex and all bitfields in a word have to be read/written together.
301 * So you can't have a different lock for different bitfields in the same word.
303 dbus_bool_t dispatch_acquired; /**< Someone has dispatch path (can drain incoming queue) */
304 dbus_bool_t io_path_acquired; /**< Someone has transport io path (can use the transport to read/write messages) */
306 unsigned int shareable : 1; /**< #TRUE if libdbus owns a reference to the connection and can return it from dbus_connection_open() more than once */
308 unsigned int exit_on_disconnect : 1; /**< If #TRUE, exit after handling disconnect signal */
310 unsigned int route_peer_messages : 1; /**< If #TRUE, if org.freedesktop.DBus.Peer messages have a bus name, don't handle them automatically */
312 unsigned int disconnected_message_arrived : 1; /**< We popped or are dispatching the disconnected message.
313 * if the disconnect_message_link is NULL then we queued it, but
314 * this flag is whether it got to the head of the queue.
316 unsigned int disconnected_message_processed : 1; /**< We did our default handling of the disconnected message,
317 * such as closing the connection.
320 #ifndef DBUS_DISABLE_CHECKS
321 unsigned int have_connection_lock : 1; /**< Used to check locking */
324 #ifndef DBUS_DISABLE_CHECKS
325 int generation; /**< _dbus_current_generation that should correspond to this connection */
329 static DBusDispatchStatus _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection);
330 static void _dbus_connection_update_dispatch_status_and_unlock (DBusConnection *connection,
331 DBusDispatchStatus new_status);
332 static void _dbus_connection_last_unref (DBusConnection *connection);
333 static void _dbus_connection_acquire_dispatch (DBusConnection *connection);
334 static void _dbus_connection_release_dispatch (DBusConnection *connection);
335 static DBusDispatchStatus _dbus_connection_flush_unlocked (DBusConnection *connection);
336 static void _dbus_connection_close_possibly_shared_and_unlock (DBusConnection *connection);
337 static dbus_bool_t _dbus_connection_get_is_connected_unlocked (DBusConnection *connection);
338 static dbus_bool_t _dbus_connection_peek_for_reply_unlocked (DBusConnection *connection,
339 dbus_uint32_t client_serial);
341 static DBusMessageFilter *
342 _dbus_message_filter_ref (DBusMessageFilter *filter)
344 #ifdef DBUS_DISABLE_ASSERT
345 _dbus_atomic_inc (&filter->refcount);
347 dbus_int32_t old_value;
349 old_value = _dbus_atomic_inc (&filter->refcount);
350 _dbus_assert (old_value > 0);
357 _dbus_message_filter_unref (DBusMessageFilter *filter)
359 dbus_int32_t old_value;
361 old_value = _dbus_atomic_dec (&filter->refcount);
362 _dbus_assert (old_value > 0);
366 if (filter->free_user_data_function)
367 (* filter->free_user_data_function) (filter->user_data);
374 * Acquires the connection lock.
376 * @param connection the connection.
379 _dbus_connection_lock (DBusConnection *connection)
381 CONNECTION_LOCK (connection);
385 * Releases the connection lock.
387 * @param connection the connection.
390 _dbus_connection_unlock (DBusConnection *connection)
392 CONNECTION_UNLOCK (connection);
396 * Wakes up the main loop if it is sleeping
397 * Needed if we're e.g. queueing outgoing messages
398 * on a thread while the mainloop sleeps.
400 * @param connection the connection.
403 _dbus_connection_wakeup_mainloop (DBusConnection *connection)
405 if (connection->wakeup_main_function)
406 (*connection->wakeup_main_function) (connection->wakeup_main_data);
409 #ifdef DBUS_BUILD_TESTS
410 /* For now this function isn't used */
412 * Adds a message to the incoming message queue, returning #FALSE
413 * if there's insufficient memory to queue the message.
414 * Does not take over refcount of the message.
416 * @param connection the connection.
417 * @param message the message to queue.
418 * @returns #TRUE on success.
421 _dbus_connection_queue_received_message (DBusConnection *connection,
422 DBusMessage *message)
426 link = _dbus_list_alloc_link (message);
430 dbus_message_ref (message);
431 _dbus_connection_queue_received_message_link (connection, link);
437 * Gets the locks so we can examine them
439 * @param connection the connection.
440 * @param mutex_loc return for the location of the main mutex pointer
441 * @param dispatch_mutex_loc return location of the dispatch mutex pointer
442 * @param io_path_mutex_loc return location of the io_path mutex pointer
443 * @param dispatch_cond_loc return location of the dispatch conditional
445 * @param io_path_cond_loc return location of the io_path conditional
449 _dbus_connection_test_get_locks (DBusConnection *connection,
450 DBusMutex **mutex_loc,
451 DBusMutex **dispatch_mutex_loc,
452 DBusMutex **io_path_mutex_loc,
453 DBusCondVar **dispatch_cond_loc,
454 DBusCondVar **io_path_cond_loc)
456 *mutex_loc = connection->mutex;
457 *dispatch_mutex_loc = connection->dispatch_mutex;
458 *io_path_mutex_loc = connection->io_path_mutex;
459 *dispatch_cond_loc = connection->dispatch_cond;
460 *io_path_cond_loc = connection->io_path_cond;
465 * Adds a message-containing list link to the incoming message queue,
466 * taking ownership of the link and the message's current refcount.
467 * Cannot fail due to lack of memory.
469 * @param connection the connection.
470 * @param link the message link to queue.
473 _dbus_connection_queue_received_message_link (DBusConnection *connection,
476 DBusPendingCall *pending;
477 dbus_uint32_t reply_serial;
478 DBusMessage *message;
480 _dbus_assert (_dbus_transport_get_is_authenticated (connection->transport));
482 _dbus_list_append_link (&connection->incoming_messages,
484 message = link->data;
486 /* If this is a reply we're waiting on, remove timeout for it */
487 reply_serial = dbus_message_get_reply_serial (message);
488 if (reply_serial != 0)
490 pending = _dbus_hash_table_lookup_int (connection->pending_replies,
494 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
495 _dbus_connection_remove_timeout_unlocked (connection,
496 _dbus_pending_call_get_timeout_unlocked (pending));
498 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
504 connection->n_incoming += 1;
506 _dbus_connection_wakeup_mainloop (connection);
508 _dbus_verbose ("Message %p (%s %s %s %s '%s' reply to %u) added to incoming queue %p, %d incoming\n",
510 dbus_message_type_to_string (dbus_message_get_type (message)),
511 dbus_message_get_path (message) ?
512 dbus_message_get_path (message) :
514 dbus_message_get_interface (message) ?
515 dbus_message_get_interface (message) :
517 dbus_message_get_member (message) ?
518 dbus_message_get_member (message) :
520 dbus_message_get_signature (message),
521 dbus_message_get_reply_serial (message),
523 connection->n_incoming);}
526 * Adds a link + message to the incoming message queue.
527 * Can't fail. Takes ownership of both link and message.
529 * @param connection the connection.
530 * @param link the list node and message to queue.
534 _dbus_connection_queue_synthesized_message_link (DBusConnection *connection,
537 HAVE_LOCK_CHECK (connection);
539 _dbus_list_append_link (&connection->incoming_messages, link);
541 connection->n_incoming += 1;
543 _dbus_connection_wakeup_mainloop (connection);
545 _dbus_verbose ("Synthesized message %p added to incoming queue %p, %d incoming\n",
546 link->data, connection, connection->n_incoming);
551 * Checks whether there are messages in the outgoing message queue.
552 * Called with connection lock held.
554 * @param connection the connection.
555 * @returns #TRUE if the outgoing queue is non-empty.
558 _dbus_connection_has_messages_to_send_unlocked (DBusConnection *connection)
560 HAVE_LOCK_CHECK (connection);
561 return connection->outgoing_messages != NULL;
565 * Checks whether there are messages in the outgoing message queue.
566 * Use dbus_connection_flush() to block until all outgoing
567 * messages have been written to the underlying transport
568 * (such as a socket).
570 * @param connection the connection.
571 * @returns #TRUE if the outgoing queue is non-empty.
574 dbus_connection_has_messages_to_send (DBusConnection *connection)
578 _dbus_return_val_if_fail (connection != NULL, FALSE);
580 CONNECTION_LOCK (connection);
581 v = _dbus_connection_has_messages_to_send_unlocked (connection);
582 CONNECTION_UNLOCK (connection);
588 * Gets the next outgoing message. The message remains in the
589 * queue, and the caller does not own a reference to it.
591 * @param connection the connection.
592 * @returns the message to be sent.
595 _dbus_connection_get_message_to_send (DBusConnection *connection)
597 HAVE_LOCK_CHECK (connection);
599 return _dbus_list_get_last (&connection->outgoing_messages);
603 * Notifies the connection that a message has been sent, so the
604 * message can be removed from the outgoing queue.
605 * Called with the connection lock held.
607 * @param connection the connection.
608 * @param message the message that was sent.
611 _dbus_connection_message_sent (DBusConnection *connection,
612 DBusMessage *message)
616 HAVE_LOCK_CHECK (connection);
618 /* This can be called before we even complete authentication, since
619 * it's called on disconnect to clean up the outgoing queue.
620 * It's also called as we successfully send each message.
623 link = _dbus_list_get_last_link (&connection->outgoing_messages);
624 _dbus_assert (link != NULL);
625 _dbus_assert (link->data == message);
627 /* Save this link in the link cache */
628 _dbus_list_unlink (&connection->outgoing_messages,
630 _dbus_list_prepend_link (&connection->link_cache, link);
632 connection->n_outgoing -= 1;
634 _dbus_verbose ("Message %p (%s %s %s %s '%s') removed from outgoing queue %p, %d left to send\n",
636 dbus_message_type_to_string (dbus_message_get_type (message)),
637 dbus_message_get_path (message) ?
638 dbus_message_get_path (message) :
640 dbus_message_get_interface (message) ?
641 dbus_message_get_interface (message) :
643 dbus_message_get_member (message) ?
644 dbus_message_get_member (message) :
646 dbus_message_get_signature (message),
647 connection, connection->n_outgoing);
649 /* Save this link in the link cache also */
650 _dbus_message_remove_counter (message, connection->outgoing_counter,
652 _dbus_list_prepend_link (&connection->link_cache, link);
654 dbus_message_unref (message);
657 /** Function to be called in protected_change_watch() with refcount held */
658 typedef dbus_bool_t (* DBusWatchAddFunction) (DBusWatchList *list,
660 /** Function to be called in protected_change_watch() with refcount held */
661 typedef void (* DBusWatchRemoveFunction) (DBusWatchList *list,
663 /** Function to be called in protected_change_watch() with refcount held */
664 typedef void (* DBusWatchToggleFunction) (DBusWatchList *list,
666 dbus_bool_t enabled);
669 protected_change_watch (DBusConnection *connection,
671 DBusWatchAddFunction add_function,
672 DBusWatchRemoveFunction remove_function,
673 DBusWatchToggleFunction toggle_function,
678 HAVE_LOCK_CHECK (connection);
680 /* The original purpose of protected_change_watch() was to hold a
681 * ref on the connection while dropping the connection lock, then
682 * calling out to the app. This was a broken hack that did not
683 * work, since the connection was in a hosed state (no WatchList
684 * field) while calling out.
686 * So for now we'll just keep the lock while calling out. This means
687 * apps are not allowed to call DBusConnection methods inside a
688 * watch function or they will deadlock.
690 * The "real fix" is to use the _and_unlock() pattern found
691 * elsewhere in the code, to defer calling out to the app until
692 * we're about to drop locks and return flow of control to the app
695 * See http://lists.freedesktop.org/archives/dbus/2007-July/thread.html#8144
698 if (connection->watches)
701 retval = (* add_function) (connection->watches, watch);
702 else if (remove_function)
705 (* remove_function) (connection->watches, watch);
710 (* toggle_function) (connection->watches, watch, enabled);
720 * Adds a watch using the connection's DBusAddWatchFunction if
721 * available. Otherwise records the watch to be added when said
722 * function is available. Also re-adds the watch if the
723 * DBusAddWatchFunction changes. May fail due to lack of memory.
724 * Connection lock should be held when calling this.
726 * @param connection the connection.
727 * @param watch the watch to add.
728 * @returns #TRUE on success.
731 _dbus_connection_add_watch_unlocked (DBusConnection *connection,
734 return protected_change_watch (connection, watch,
735 _dbus_watch_list_add_watch,
740 * Removes a watch using the connection's DBusRemoveWatchFunction
741 * if available. It's an error to call this function on a watch
742 * that was not previously added.
743 * Connection lock should be held when calling this.
745 * @param connection the connection.
746 * @param watch the watch to remove.
749 _dbus_connection_remove_watch_unlocked (DBusConnection *connection,
752 protected_change_watch (connection, watch,
754 _dbus_watch_list_remove_watch,
759 * Toggles a watch and notifies app via connection's
760 * DBusWatchToggledFunction if available. It's an error to call this
761 * function on a watch that was not previously added.
762 * Connection lock should be held when calling this.
764 * @param connection the connection.
765 * @param watch the watch to toggle.
766 * @param enabled whether to enable or disable
769 _dbus_connection_toggle_watch_unlocked (DBusConnection *connection,
773 _dbus_assert (watch != NULL);
775 protected_change_watch (connection, watch,
777 _dbus_watch_list_toggle_watch,
781 /** Function to be called in protected_change_timeout() with refcount held */
782 typedef dbus_bool_t (* DBusTimeoutAddFunction) (DBusTimeoutList *list,
783 DBusTimeout *timeout);
784 /** Function to be called in protected_change_timeout() with refcount held */
785 typedef void (* DBusTimeoutRemoveFunction) (DBusTimeoutList *list,
786 DBusTimeout *timeout);
787 /** Function to be called in protected_change_timeout() with refcount held */
788 typedef void (* DBusTimeoutToggleFunction) (DBusTimeoutList *list,
789 DBusTimeout *timeout,
790 dbus_bool_t enabled);
793 protected_change_timeout (DBusConnection *connection,
794 DBusTimeout *timeout,
795 DBusTimeoutAddFunction add_function,
796 DBusTimeoutRemoveFunction remove_function,
797 DBusTimeoutToggleFunction toggle_function,
802 HAVE_LOCK_CHECK (connection);
804 /* The original purpose of protected_change_timeout() was to hold a
805 * ref on the connection while dropping the connection lock, then
806 * calling out to the app. This was a broken hack that did not
807 * work, since the connection was in a hosed state (no TimeoutList
808 * field) while calling out.
810 * So for now we'll just keep the lock while calling out. This means
811 * apps are not allowed to call DBusConnection methods inside a
812 * timeout function or they will deadlock.
814 * The "real fix" is to use the _and_unlock() pattern found
815 * elsewhere in the code, to defer calling out to the app until
816 * we're about to drop locks and return flow of control to the app
819 * See http://lists.freedesktop.org/archives/dbus/2007-July/thread.html#8144
822 if (connection->timeouts)
825 retval = (* add_function) (connection->timeouts, timeout);
826 else if (remove_function)
829 (* remove_function) (connection->timeouts, timeout);
834 (* toggle_function) (connection->timeouts, timeout, enabled);
843 * Adds a timeout using the connection's DBusAddTimeoutFunction if
844 * available. Otherwise records the timeout to be added when said
845 * function is available. Also re-adds the timeout if the
846 * DBusAddTimeoutFunction changes. May fail due to lack of memory.
847 * The timeout will fire repeatedly until removed.
848 * Connection lock should be held when calling this.
850 * @param connection the connection.
851 * @param timeout the timeout to add.
852 * @returns #TRUE on success.
855 _dbus_connection_add_timeout_unlocked (DBusConnection *connection,
856 DBusTimeout *timeout)
858 return protected_change_timeout (connection, timeout,
859 _dbus_timeout_list_add_timeout,
864 * Removes a timeout using the connection's DBusRemoveTimeoutFunction
865 * if available. It's an error to call this function on a timeout
866 * that was not previously added.
867 * Connection lock should be held when calling this.
869 * @param connection the connection.
870 * @param timeout the timeout to remove.
873 _dbus_connection_remove_timeout_unlocked (DBusConnection *connection,
874 DBusTimeout *timeout)
876 protected_change_timeout (connection, timeout,
878 _dbus_timeout_list_remove_timeout,
883 * Toggles a timeout and notifies app via connection's
884 * DBusTimeoutToggledFunction if available. It's an error to call this
885 * function on a timeout that was not previously added.
886 * Connection lock should be held when calling this.
888 * @param connection the connection.
889 * @param timeout the timeout to toggle.
890 * @param enabled whether to enable or disable
893 _dbus_connection_toggle_timeout_unlocked (DBusConnection *connection,
894 DBusTimeout *timeout,
897 protected_change_timeout (connection, timeout,
899 _dbus_timeout_list_toggle_timeout,
904 _dbus_connection_attach_pending_call_unlocked (DBusConnection *connection,
905 DBusPendingCall *pending)
907 dbus_uint32_t reply_serial;
908 DBusTimeout *timeout;
910 HAVE_LOCK_CHECK (connection);
912 reply_serial = _dbus_pending_call_get_reply_serial_unlocked (pending);
914 _dbus_assert (reply_serial != 0);
916 timeout = _dbus_pending_call_get_timeout_unlocked (pending);
920 if (!_dbus_connection_add_timeout_unlocked (connection, timeout))
923 if (!_dbus_hash_table_insert_int (connection->pending_replies,
927 _dbus_connection_remove_timeout_unlocked (connection, timeout);
929 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
930 HAVE_LOCK_CHECK (connection);
934 _dbus_pending_call_set_timeout_added_unlocked (pending, TRUE);
938 if (!_dbus_hash_table_insert_int (connection->pending_replies,
942 HAVE_LOCK_CHECK (connection);
947 _dbus_pending_call_ref_unlocked (pending);
949 HAVE_LOCK_CHECK (connection);
955 free_pending_call_on_hash_removal (void *data)
957 DBusPendingCall *pending;
958 DBusConnection *connection;
965 connection = _dbus_pending_call_get_connection_unlocked (pending);
967 HAVE_LOCK_CHECK (connection);
969 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
971 _dbus_connection_remove_timeout_unlocked (connection,
972 _dbus_pending_call_get_timeout_unlocked (pending));
974 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
977 /* FIXME 1.0? this is sort of dangerous and undesirable to drop the lock
978 * here, but the pending call finalizer could in principle call out to
979 * application code so we pretty much have to... some larger code reorg
982 _dbus_connection_ref_unlocked (connection);
983 _dbus_pending_call_unref_and_unlock (pending);
984 CONNECTION_LOCK (connection);
985 _dbus_connection_unref_unlocked (connection);
989 _dbus_connection_detach_pending_call_unlocked (DBusConnection *connection,
990 DBusPendingCall *pending)
992 /* This ends up unlocking to call the pending call finalizer, which is unexpected to
995 _dbus_hash_table_remove_int (connection->pending_replies,
996 _dbus_pending_call_get_reply_serial_unlocked (pending));
1000 _dbus_connection_detach_pending_call_and_unlock (DBusConnection *connection,
1001 DBusPendingCall *pending)
1003 /* The idea here is to avoid finalizing the pending call
1004 * with the lock held, since there's a destroy notifier
1005 * in pending call that goes out to application code.
1007 * There's an extra unlock inside the hash table
1008 * "free pending call" function FIXME...
1010 _dbus_pending_call_ref_unlocked (pending);
1011 _dbus_hash_table_remove_int (connection->pending_replies,
1012 _dbus_pending_call_get_reply_serial_unlocked (pending));
1014 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
1015 _dbus_connection_remove_timeout_unlocked (connection,
1016 _dbus_pending_call_get_timeout_unlocked (pending));
1018 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
1020 _dbus_pending_call_unref_and_unlock (pending);
1024 * Removes a pending call from the connection, such that
1025 * the pending reply will be ignored. May drop the last
1026 * reference to the pending call.
1028 * @param connection the connection
1029 * @param pending the pending call
1032 _dbus_connection_remove_pending_call (DBusConnection *connection,
1033 DBusPendingCall *pending)
1035 CONNECTION_LOCK (connection);
1036 _dbus_connection_detach_pending_call_and_unlock (connection, pending);
1040 * Acquire the transporter I/O path. This must be done before
1041 * doing any I/O in the transporter. May sleep and drop the
1042 * IO path mutex while waiting for the I/O path.
1044 * @param connection the connection.
1045 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
1046 * @returns TRUE if the I/O path was acquired.
1049 _dbus_connection_acquire_io_path (DBusConnection *connection,
1050 int timeout_milliseconds)
1052 dbus_bool_t we_acquired;
1054 HAVE_LOCK_CHECK (connection);
1056 /* We don't want the connection to vanish */
1057 _dbus_connection_ref_unlocked (connection);
1059 /* We will only touch io_path_acquired which is protected by our mutex */
1060 CONNECTION_UNLOCK (connection);
1062 _dbus_verbose ("locking io_path_mutex\n");
1063 _dbus_mutex_lock (connection->io_path_mutex);
1065 _dbus_verbose ("start connection->io_path_acquired = %d timeout = %d\n",
1066 connection->io_path_acquired, timeout_milliseconds);
1068 we_acquired = FALSE;
1070 if (connection->io_path_acquired)
1072 if (timeout_milliseconds != -1)
1074 _dbus_verbose ("waiting %d for IO path to be acquirable\n",
1075 timeout_milliseconds);
1077 if (!_dbus_condvar_wait_timeout (connection->io_path_cond,
1078 connection->io_path_mutex,
1079 timeout_milliseconds))
1081 /* We timed out before anyone signaled. */
1082 /* (writing the loop to handle the !timedout case by
1083 * waiting longer if needed is a pain since dbus
1084 * wraps pthread_cond_timedwait to take a relative
1085 * time instead of absolute, something kind of stupid
1086 * on our part. for now it doesn't matter, we will just
1087 * end up back here eventually.)
1093 while (connection->io_path_acquired)
1095 _dbus_verbose ("waiting for IO path to be acquirable\n");
1096 _dbus_condvar_wait (connection->io_path_cond,
1097 connection->io_path_mutex);
1102 if (!connection->io_path_acquired)
1105 connection->io_path_acquired = TRUE;
1108 _dbus_verbose ("end connection->io_path_acquired = %d we_acquired = %d\n",
1109 connection->io_path_acquired, we_acquired);
1111 _dbus_verbose ("unlocking io_path_mutex\n");
1112 _dbus_mutex_unlock (connection->io_path_mutex);
1114 CONNECTION_LOCK (connection);
1116 HAVE_LOCK_CHECK (connection);
1118 _dbus_connection_unref_unlocked (connection);
1124 * Release the I/O path when you're done with it. Only call
1125 * after you've acquired the I/O. Wakes up at most one thread
1126 * currently waiting to acquire the I/O path.
1128 * @param connection the connection.
1131 _dbus_connection_release_io_path (DBusConnection *connection)
1133 HAVE_LOCK_CHECK (connection);
1135 _dbus_verbose ("locking io_path_mutex\n");
1136 _dbus_mutex_lock (connection->io_path_mutex);
1138 _dbus_assert (connection->io_path_acquired);
1140 _dbus_verbose ("start connection->io_path_acquired = %d\n",
1141 connection->io_path_acquired);
1143 connection->io_path_acquired = FALSE;
1144 _dbus_condvar_wake_one (connection->io_path_cond);
1146 _dbus_verbose ("unlocking io_path_mutex\n");
1147 _dbus_mutex_unlock (connection->io_path_mutex);
1151 * Queues incoming messages and sends outgoing messages for this
1152 * connection, optionally blocking in the process. Each call to
1153 * _dbus_connection_do_iteration_unlocked() will call select() or poll() one
1154 * time and then read or write data if possible.
1156 * The purpose of this function is to be able to flush outgoing
1157 * messages or queue up incoming messages without returning
1158 * control to the application and causing reentrancy weirdness.
1160 * The flags parameter allows you to specify whether to
1161 * read incoming messages, write outgoing messages, or both,
1162 * and whether to block if no immediate action is possible.
1164 * The timeout_milliseconds parameter does nothing unless the
1165 * iteration is blocking.
1167 * If there are no outgoing messages and DBUS_ITERATION_DO_READING
1168 * wasn't specified, then it's impossible to block, even if
1169 * you specify DBUS_ITERATION_BLOCK; in that case the function
1170 * returns immediately.
1172 * If pending is not NULL then a check is made if the pending call
1173 * is completed after the io path has been required. If the call
1174 * has been completed nothing is done. This must be done since
1175 * the _dbus_connection_acquire_io_path releases the connection
1178 * Called with connection lock held.
1180 * @param connection the connection.
1181 * @param pending the pending call that should be checked or NULL
1182 * @param flags iteration flags.
1183 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
1186 _dbus_connection_do_iteration_unlocked (DBusConnection *connection,
1187 DBusPendingCall *pending,
1189 int timeout_milliseconds)
1191 _dbus_verbose ("start\n");
1193 HAVE_LOCK_CHECK (connection);
1195 if (connection->n_outgoing == 0)
1196 flags &= ~DBUS_ITERATION_DO_WRITING;
1198 if (_dbus_connection_acquire_io_path (connection,
1199 (flags & DBUS_ITERATION_BLOCK) ? timeout_milliseconds : 0))
1201 HAVE_LOCK_CHECK (connection);
1203 if ( (pending != NULL) && _dbus_pending_call_get_completed_unlocked(pending))
1205 _dbus_verbose ("pending call completed while acquiring I/O path");
1207 else if ( (pending != NULL) &&
1208 _dbus_connection_peek_for_reply_unlocked (connection,
1209 _dbus_pending_call_get_reply_serial_unlocked (pending)))
1211 _dbus_verbose ("pending call completed while acquiring I/O path (reply found in queue)");
1215 _dbus_transport_do_iteration (connection->transport,
1216 flags, timeout_milliseconds);
1219 _dbus_connection_release_io_path (connection);
1222 HAVE_LOCK_CHECK (connection);
1224 _dbus_verbose ("end\n");
1228 * Creates a new connection for the given transport. A transport
1229 * represents a message stream that uses some concrete mechanism, such
1230 * as UNIX domain sockets. May return #NULL if insufficient
1231 * memory exists to create the connection.
1233 * @param transport the transport.
1234 * @returns the new connection, or #NULL on failure.
1237 _dbus_connection_new_for_transport (DBusTransport *transport)
1239 DBusConnection *connection;
1240 DBusWatchList *watch_list;
1241 DBusTimeoutList *timeout_list;
1242 DBusHashTable *pending_replies;
1243 DBusList *disconnect_link;
1244 DBusMessage *disconnect_message;
1245 DBusCounter *outgoing_counter;
1246 DBusObjectTree *objects;
1250 pending_replies = NULL;
1251 timeout_list = NULL;
1252 disconnect_link = NULL;
1253 disconnect_message = NULL;
1254 outgoing_counter = NULL;
1257 watch_list = _dbus_watch_list_new ();
1258 if (watch_list == NULL)
1261 timeout_list = _dbus_timeout_list_new ();
1262 if (timeout_list == NULL)
1266 _dbus_hash_table_new (DBUS_HASH_INT,
1268 (DBusFreeFunction)free_pending_call_on_hash_removal);
1269 if (pending_replies == NULL)
1272 connection = dbus_new0 (DBusConnection, 1);
1273 if (connection == NULL)
1276 _dbus_mutex_new_at_location (&connection->mutex);
1277 if (connection->mutex == NULL)
1280 _dbus_mutex_new_at_location (&connection->io_path_mutex);
1281 if (connection->io_path_mutex == NULL)
1284 _dbus_mutex_new_at_location (&connection->dispatch_mutex);
1285 if (connection->dispatch_mutex == NULL)
1288 _dbus_condvar_new_at_location (&connection->dispatch_cond);
1289 if (connection->dispatch_cond == NULL)
1292 _dbus_condvar_new_at_location (&connection->io_path_cond);
1293 if (connection->io_path_cond == NULL)
1296 _dbus_mutex_new_at_location (&connection->slot_mutex);
1297 if (connection->slot_mutex == NULL)
1300 disconnect_message = dbus_message_new_signal (DBUS_PATH_LOCAL,
1301 DBUS_INTERFACE_LOCAL,
1304 if (disconnect_message == NULL)
1307 disconnect_link = _dbus_list_alloc_link (disconnect_message);
1308 if (disconnect_link == NULL)
1311 outgoing_counter = _dbus_counter_new ();
1312 if (outgoing_counter == NULL)
1315 objects = _dbus_object_tree_new (connection);
1316 if (objects == NULL)
1319 if (_dbus_modify_sigpipe)
1320 _dbus_disable_sigpipe ();
1322 /* initialized to 0: use atomic op to avoid mixing atomic and non-atomic */
1323 _dbus_atomic_inc (&connection->refcount);
1324 connection->transport = transport;
1325 connection->watches = watch_list;
1326 connection->timeouts = timeout_list;
1327 connection->pending_replies = pending_replies;
1328 connection->outgoing_counter = outgoing_counter;
1329 connection->filter_list = NULL;
1330 connection->last_dispatch_status = DBUS_DISPATCH_COMPLETE; /* so we're notified first time there's data */
1331 connection->objects = objects;
1332 connection->exit_on_disconnect = FALSE;
1333 connection->shareable = FALSE;
1334 connection->route_peer_messages = FALSE;
1335 connection->disconnected_message_arrived = FALSE;
1336 connection->disconnected_message_processed = FALSE;
1338 #ifndef DBUS_DISABLE_CHECKS
1339 connection->generation = _dbus_current_generation;
1342 _dbus_data_slot_list_init (&connection->slot_list);
1344 connection->client_serial = 1;
1346 connection->disconnect_message_link = disconnect_link;
1348 CONNECTION_LOCK (connection);
1350 if (!_dbus_transport_set_connection (transport, connection))
1352 CONNECTION_UNLOCK (connection);
1357 _dbus_transport_ref (transport);
1359 CONNECTION_UNLOCK (connection);
1364 if (disconnect_message != NULL)
1365 dbus_message_unref (disconnect_message);
1367 if (disconnect_link != NULL)
1368 _dbus_list_free_link (disconnect_link);
1370 if (connection != NULL)
1372 _dbus_condvar_free_at_location (&connection->io_path_cond);
1373 _dbus_condvar_free_at_location (&connection->dispatch_cond);
1374 _dbus_mutex_free_at_location (&connection->mutex);
1375 _dbus_mutex_free_at_location (&connection->io_path_mutex);
1376 _dbus_mutex_free_at_location (&connection->dispatch_mutex);
1377 _dbus_mutex_free_at_location (&connection->slot_mutex);
1378 dbus_free (connection);
1380 if (pending_replies)
1381 _dbus_hash_table_unref (pending_replies);
1384 _dbus_watch_list_free (watch_list);
1387 _dbus_timeout_list_free (timeout_list);
1389 if (outgoing_counter)
1390 _dbus_counter_unref (outgoing_counter);
1393 _dbus_object_tree_unref (objects);
1399 * Increments the reference count of a DBusConnection.
1400 * Requires that the caller already holds the connection lock.
1402 * @param connection the connection.
1403 * @returns the connection.
1406 _dbus_connection_ref_unlocked (DBusConnection *connection)
1408 _dbus_assert (connection != NULL);
1409 _dbus_assert (connection->generation == _dbus_current_generation);
1411 HAVE_LOCK_CHECK (connection);
1413 _dbus_atomic_inc (&connection->refcount);
1419 * Decrements the reference count of a DBusConnection.
1420 * Requires that the caller already holds the connection lock.
1422 * @param connection the connection.
1425 _dbus_connection_unref_unlocked (DBusConnection *connection)
1427 dbus_bool_t last_unref;
1429 HAVE_LOCK_CHECK (connection);
1431 _dbus_assert (connection != NULL);
1433 last_unref = (_dbus_atomic_dec (&connection->refcount) == 1);
1436 _dbus_connection_last_unref (connection);
1439 static dbus_uint32_t
1440 _dbus_connection_get_next_client_serial (DBusConnection *connection)
1442 dbus_uint32_t serial;
1444 serial = connection->client_serial++;
1446 if (connection->client_serial == 0)
1447 connection->client_serial = 1;
1453 * A callback for use with dbus_watch_new() to create a DBusWatch.
1455 * @todo This is basically a hack - we could delete _dbus_transport_handle_watch()
1456 * and the virtual handle_watch in DBusTransport if we got rid of it.
1457 * The reason this is some work is threading, see the _dbus_connection_handle_watch()
1460 * @param watch the watch.
1461 * @param condition the current condition of the file descriptors being watched.
1462 * @param data must be a pointer to a #DBusConnection
1463 * @returns #FALSE if the IO condition may not have been fully handled due to lack of memory
1466 _dbus_connection_handle_watch (DBusWatch *watch,
1467 unsigned int condition,
1470 DBusConnection *connection;
1472 DBusDispatchStatus status;
1476 _dbus_verbose ("start\n");
1478 CONNECTION_LOCK (connection);
1480 if (!_dbus_connection_acquire_io_path (connection, 1))
1482 /* another thread is handling the message */
1483 CONNECTION_UNLOCK (connection);
1487 HAVE_LOCK_CHECK (connection);
1488 retval = _dbus_transport_handle_watch (connection->transport,
1491 _dbus_connection_release_io_path (connection);
1493 HAVE_LOCK_CHECK (connection);
1495 _dbus_verbose ("middle\n");
1497 status = _dbus_connection_get_dispatch_status_unlocked (connection);
1499 /* this calls out to user code */
1500 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1502 _dbus_verbose ("end\n");
1507 _DBUS_DEFINE_GLOBAL_LOCK (shared_connections);
1508 static DBusHashTable *shared_connections = NULL;
1509 static DBusList *shared_connections_no_guid = NULL;
1512 close_connection_on_shutdown (DBusConnection *connection)
1514 DBusMessage *message;
1516 dbus_connection_ref (connection);
1517 _dbus_connection_close_possibly_shared (connection);
1519 /* Churn through to the Disconnected message */
1520 while ((message = dbus_connection_pop_message (connection)))
1522 dbus_message_unref (message);
1524 dbus_connection_unref (connection);
1528 shared_connections_shutdown (void *data)
1532 _DBUS_LOCK (shared_connections);
1534 /* This is a little bit unpleasant... better ideas? */
1535 while ((n_entries = _dbus_hash_table_get_n_entries (shared_connections)) > 0)
1537 DBusConnection *connection;
1540 _dbus_hash_iter_init (shared_connections, &iter);
1541 _dbus_hash_iter_next (&iter);
1543 connection = _dbus_hash_iter_get_value (&iter);
1545 _DBUS_UNLOCK (shared_connections);
1546 close_connection_on_shutdown (connection);
1547 _DBUS_LOCK (shared_connections);
1549 /* The connection should now be dead and not in our hash ... */
1550 _dbus_assert (_dbus_hash_table_get_n_entries (shared_connections) < n_entries);
1553 _dbus_assert (_dbus_hash_table_get_n_entries (shared_connections) == 0);
1555 _dbus_hash_table_unref (shared_connections);
1556 shared_connections = NULL;
1558 if (shared_connections_no_guid != NULL)
1560 DBusConnection *connection;
1561 connection = _dbus_list_pop_first (&shared_connections_no_guid);
1562 while (connection != NULL)
1564 _DBUS_UNLOCK (shared_connections);
1565 close_connection_on_shutdown (connection);
1566 _DBUS_LOCK (shared_connections);
1567 connection = _dbus_list_pop_first (&shared_connections_no_guid);
1571 shared_connections_no_guid = NULL;
1573 _DBUS_UNLOCK (shared_connections);
1577 connection_lookup_shared (DBusAddressEntry *entry,
1578 DBusConnection **result)
1580 _dbus_verbose ("checking for existing connection\n");
1584 _DBUS_LOCK (shared_connections);
1586 if (shared_connections == NULL)
1588 _dbus_verbose ("creating shared_connections hash table\n");
1590 shared_connections = _dbus_hash_table_new (DBUS_HASH_STRING,
1593 if (shared_connections == NULL)
1595 _DBUS_UNLOCK (shared_connections);
1599 if (!_dbus_register_shutdown_func (shared_connections_shutdown, NULL))
1601 _dbus_hash_table_unref (shared_connections);
1602 shared_connections = NULL;
1603 _DBUS_UNLOCK (shared_connections);
1607 _dbus_verbose (" successfully created shared_connections\n");
1609 _DBUS_UNLOCK (shared_connections);
1610 return TRUE; /* no point looking up in the hash we just made */
1616 guid = dbus_address_entry_get_value (entry, "guid");
1620 DBusConnection *connection;
1622 connection = _dbus_hash_table_lookup_string (shared_connections,
1627 /* The DBusConnection can't be finalized without taking
1628 * the shared_connections lock to remove it from the
1629 * hash. So it's safe to ref the connection here.
1630 * However, it may be disconnected if the Disconnected
1631 * message hasn't been processed yet, in which case we
1632 * want to pretend it isn't in the hash and avoid
1635 * The idea is to avoid ever returning a disconnected connection
1636 * from dbus_connection_open(). We could just synchronously
1637 * drop our shared ref to the connection on connection disconnect,
1638 * and then assert here that the connection is connected, but
1639 * that causes reentrancy headaches.
1641 CONNECTION_LOCK (connection);
1642 if (_dbus_connection_get_is_connected_unlocked (connection))
1644 _dbus_connection_ref_unlocked (connection);
1645 *result = connection;
1646 _dbus_verbose ("looked up existing connection to server guid %s\n",
1651 _dbus_verbose ("looked up existing connection to server guid %s but it was disconnected so ignoring it\n",
1654 CONNECTION_UNLOCK (connection);
1658 _DBUS_UNLOCK (shared_connections);
1664 connection_record_shared_unlocked (DBusConnection *connection,
1668 char *guid_in_connection;
1670 HAVE_LOCK_CHECK (connection);
1671 _dbus_assert (connection->server_guid == NULL);
1672 _dbus_assert (connection->shareable);
1674 /* get a hard ref on this connection, even if
1675 * we won't in fact store it in the hash, we still
1676 * need to hold a ref on it until it's disconnected.
1678 _dbus_connection_ref_unlocked (connection);
1682 _DBUS_LOCK (shared_connections);
1684 if (!_dbus_list_prepend (&shared_connections_no_guid, connection))
1686 _DBUS_UNLOCK (shared_connections);
1690 _DBUS_UNLOCK (shared_connections);
1691 return TRUE; /* don't store in the hash */
1694 /* A separate copy of the key is required in the hash table, because
1695 * we don't have a lock on the connection when we are doing a hash
1699 guid_key = _dbus_strdup (guid);
1700 if (guid_key == NULL)
1703 guid_in_connection = _dbus_strdup (guid);
1704 if (guid_in_connection == NULL)
1706 dbus_free (guid_key);
1710 _DBUS_LOCK (shared_connections);
1711 _dbus_assert (shared_connections != NULL);
1713 if (!_dbus_hash_table_insert_string (shared_connections,
1714 guid_key, connection))
1716 dbus_free (guid_key);
1717 dbus_free (guid_in_connection);
1718 _DBUS_UNLOCK (shared_connections);
1722 connection->server_guid = guid_in_connection;
1724 _dbus_verbose ("stored connection to %s to be shared\n",
1725 connection->server_guid);
1727 _DBUS_UNLOCK (shared_connections);
1729 _dbus_assert (connection->server_guid != NULL);
1735 connection_forget_shared_unlocked (DBusConnection *connection)
1737 HAVE_LOCK_CHECK (connection);
1739 if (!connection->shareable)
1742 _DBUS_LOCK (shared_connections);
1744 if (connection->server_guid != NULL)
1746 _dbus_verbose ("dropping connection to %s out of the shared table\n",
1747 connection->server_guid);
1749 if (!_dbus_hash_table_remove_string (shared_connections,
1750 connection->server_guid))
1751 _dbus_assert_not_reached ("connection was not in the shared table");
1753 dbus_free (connection->server_guid);
1754 connection->server_guid = NULL;
1758 _dbus_list_remove (&shared_connections_no_guid, connection);
1761 _DBUS_UNLOCK (shared_connections);
1763 /* remove our reference held on all shareable connections */
1764 _dbus_connection_unref_unlocked (connection);
1767 static DBusConnection*
1768 connection_try_from_address_entry (DBusAddressEntry *entry,
1771 DBusTransport *transport;
1772 DBusConnection *connection;
1774 transport = _dbus_transport_open (entry, error);
1776 if (transport == NULL)
1778 _DBUS_ASSERT_ERROR_IS_SET (error);
1782 connection = _dbus_connection_new_for_transport (transport);
1784 _dbus_transport_unref (transport);
1786 if (connection == NULL)
1788 _DBUS_SET_OOM (error);
1792 #ifndef DBUS_DISABLE_CHECKS
1793 _dbus_assert (!connection->have_connection_lock);
1799 * If the shared parameter is true, then any existing connection will
1800 * be used (and if a new connection is created, it will be available
1801 * for use by others). If the shared parameter is false, a new
1802 * connection will always be created, and the new connection will
1803 * never be returned to other callers.
1805 * @param address the address
1806 * @param shared whether the connection is shared or private
1807 * @param error error return
1808 * @returns the connection or #NULL on error
1810 static DBusConnection*
1811 _dbus_connection_open_internal (const char *address,
1815 DBusConnection *connection;
1816 DBusAddressEntry **entries;
1817 DBusError tmp_error = DBUS_ERROR_INIT;
1818 DBusError first_error = DBUS_ERROR_INIT;
1821 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1823 _dbus_verbose ("opening %s connection to: %s\n",
1824 shared ? "shared" : "private", address);
1826 if (!dbus_parse_address (address, &entries, &len, error))
1829 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1833 for (i = 0; i < len; i++)
1837 if (!connection_lookup_shared (entries[i], &connection))
1838 _DBUS_SET_OOM (&tmp_error);
1841 if (connection == NULL)
1843 connection = connection_try_from_address_entry (entries[i],
1846 if (connection != NULL && shared)
1850 connection->shareable = TRUE;
1852 /* guid may be NULL */
1853 guid = dbus_address_entry_get_value (entries[i], "guid");
1855 CONNECTION_LOCK (connection);
1857 if (!connection_record_shared_unlocked (connection, guid))
1859 _DBUS_SET_OOM (&tmp_error);
1860 _dbus_connection_close_possibly_shared_and_unlock (connection);
1861 dbus_connection_unref (connection);
1865 CONNECTION_UNLOCK (connection);
1872 _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
1875 dbus_move_error (&tmp_error, &first_error);
1877 dbus_error_free (&tmp_error);
1880 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1881 _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
1883 if (connection == NULL)
1885 _DBUS_ASSERT_ERROR_IS_SET (&first_error);
1886 dbus_move_error (&first_error, error);
1889 dbus_error_free (&first_error);
1891 dbus_address_entries_free (entries);
1896 * Closes a shared OR private connection, while dbus_connection_close() can
1897 * only be used on private connections. Should only be called by the
1898 * dbus code that owns the connection - an owner must be known,
1899 * the open/close state is like malloc/free, not like ref/unref.
1901 * @param connection the connection
1904 _dbus_connection_close_possibly_shared (DBusConnection *connection)
1906 _dbus_assert (connection != NULL);
1907 _dbus_assert (connection->generation == _dbus_current_generation);
1909 CONNECTION_LOCK (connection);
1910 _dbus_connection_close_possibly_shared_and_unlock (connection);
1913 static DBusPreallocatedSend*
1914 _dbus_connection_preallocate_send_unlocked (DBusConnection *connection)
1916 DBusPreallocatedSend *preallocated;
1918 HAVE_LOCK_CHECK (connection);
1920 _dbus_assert (connection != NULL);
1922 preallocated = dbus_new (DBusPreallocatedSend, 1);
1923 if (preallocated == NULL)
1926 if (connection->link_cache != NULL)
1928 preallocated->queue_link =
1929 _dbus_list_pop_first_link (&connection->link_cache);
1930 preallocated->queue_link->data = NULL;
1934 preallocated->queue_link = _dbus_list_alloc_link (NULL);
1935 if (preallocated->queue_link == NULL)
1939 if (connection->link_cache != NULL)
1941 preallocated->counter_link =
1942 _dbus_list_pop_first_link (&connection->link_cache);
1943 preallocated->counter_link->data = connection->outgoing_counter;
1947 preallocated->counter_link = _dbus_list_alloc_link (connection->outgoing_counter);
1948 if (preallocated->counter_link == NULL)
1952 _dbus_counter_ref (preallocated->counter_link->data);
1954 preallocated->connection = connection;
1956 return preallocated;
1959 _dbus_list_free_link (preallocated->queue_link);
1961 dbus_free (preallocated);
1966 /* Called with lock held, does not update dispatch status */
1968 _dbus_connection_send_preallocated_unlocked_no_update (DBusConnection *connection,
1969 DBusPreallocatedSend *preallocated,
1970 DBusMessage *message,
1971 dbus_uint32_t *client_serial)
1973 dbus_uint32_t serial;
1975 preallocated->queue_link->data = message;
1976 _dbus_list_prepend_link (&connection->outgoing_messages,
1977 preallocated->queue_link);
1979 _dbus_message_add_counter_link (message,
1980 preallocated->counter_link);
1982 dbus_free (preallocated);
1983 preallocated = NULL;
1985 dbus_message_ref (message);
1987 connection->n_outgoing += 1;
1989 _dbus_verbose ("Message %p (%s %s %s %s '%s') for %s added to outgoing queue %p, %d pending to send\n",
1991 dbus_message_type_to_string (dbus_message_get_type (message)),
1992 dbus_message_get_path (message) ?
1993 dbus_message_get_path (message) :
1995 dbus_message_get_interface (message) ?
1996 dbus_message_get_interface (message) :
1998 dbus_message_get_member (message) ?
1999 dbus_message_get_member (message) :
2001 dbus_message_get_signature (message),
2002 dbus_message_get_destination (message) ?
2003 dbus_message_get_destination (message) :
2006 connection->n_outgoing);
2008 if (dbus_message_get_serial (message) == 0)
2010 serial = _dbus_connection_get_next_client_serial (connection);
2011 dbus_message_set_serial (message, serial);
2013 *client_serial = serial;
2018 *client_serial = dbus_message_get_serial (message);
2021 _dbus_verbose ("Message %p serial is %u\n",
2022 message, dbus_message_get_serial (message));
2024 dbus_message_lock (message);
2026 /* Now we need to run an iteration to hopefully just write the messages
2027 * out immediately, and otherwise get them queued up
2029 _dbus_connection_do_iteration_unlocked (connection,
2031 DBUS_ITERATION_DO_WRITING,
2034 /* If stuff is still queued up, be sure we wake up the main loop */
2035 if (connection->n_outgoing > 0)
2036 _dbus_connection_wakeup_mainloop (connection);
2040 _dbus_connection_send_preallocated_and_unlock (DBusConnection *connection,
2041 DBusPreallocatedSend *preallocated,
2042 DBusMessage *message,
2043 dbus_uint32_t *client_serial)
2045 DBusDispatchStatus status;
2047 HAVE_LOCK_CHECK (connection);
2049 _dbus_connection_send_preallocated_unlocked_no_update (connection,
2051 message, client_serial);
2053 _dbus_verbose ("middle\n");
2054 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2056 /* this calls out to user code */
2057 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2061 * Like dbus_connection_send(), but assumes the connection
2062 * is already locked on function entry, and unlocks before returning.
2064 * @param connection the connection
2065 * @param message the message to send
2066 * @param client_serial return location for client serial of sent message
2067 * @returns #FALSE on out-of-memory
2070 _dbus_connection_send_and_unlock (DBusConnection *connection,
2071 DBusMessage *message,
2072 dbus_uint32_t *client_serial)
2074 DBusPreallocatedSend *preallocated;
2076 _dbus_assert (connection != NULL);
2077 _dbus_assert (message != NULL);
2079 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
2080 if (preallocated == NULL)
2082 CONNECTION_UNLOCK (connection);
2086 _dbus_connection_send_preallocated_and_unlock (connection,
2094 * Used internally to handle the semantics of dbus_server_set_new_connection_function().
2095 * If the new connection function does not ref the connection, we want to close it.
2097 * A bit of a hack, probably the new connection function should have returned a value
2098 * for whether to close, or should have had to close the connection itself if it
2101 * But, this works OK as long as the new connection function doesn't do anything
2102 * crazy like keep the connection around without ref'ing it.
2104 * We have to lock the connection across refcount check and close in case
2105 * the new connection function spawns a thread that closes and unrefs.
2106 * In that case, if the app thread
2107 * closes and unrefs first, we'll harmlessly close again; if the app thread
2108 * still has the ref, we'll close and then the app will close harmlessly.
2109 * If the app unrefs without closing, the app is broken since if the
2110 * app refs from the new connection function it is supposed to also close.
2112 * If we didn't atomically check the refcount and close with the lock held
2113 * though, we could screw this up.
2115 * @param connection the connection
2118 _dbus_connection_close_if_only_one_ref (DBusConnection *connection)
2120 dbus_int32_t refcount;
2122 CONNECTION_LOCK (connection);
2124 refcount = _dbus_atomic_get (&connection->refcount);
2125 /* The caller should have at least one ref */
2126 _dbus_assert (refcount >= 1);
2129 _dbus_connection_close_possibly_shared_and_unlock (connection);
2131 CONNECTION_UNLOCK (connection);
2136 * When a function that blocks has been called with a timeout, and we
2137 * run out of memory, the time to wait for memory is based on the
2138 * timeout. If the caller was willing to block a long time we wait a
2139 * relatively long time for memory, if they were only willing to block
2140 * briefly then we retry for memory at a rapid rate.
2142 * @timeout_milliseconds the timeout requested for blocking
2145 _dbus_memory_pause_based_on_timeout (int timeout_milliseconds)
2147 if (timeout_milliseconds == -1)
2148 _dbus_sleep_milliseconds (1000);
2149 else if (timeout_milliseconds < 100)
2150 ; /* just busy loop */
2151 else if (timeout_milliseconds <= 1000)
2152 _dbus_sleep_milliseconds (timeout_milliseconds / 3);
2154 _dbus_sleep_milliseconds (1000);
2157 static DBusMessage *
2158 generate_local_error_message (dbus_uint32_t serial,
2162 DBusMessage *message;
2163 message = dbus_message_new (DBUS_MESSAGE_TYPE_ERROR);
2167 if (!dbus_message_set_error_name (message, error_name))
2169 dbus_message_unref (message);
2174 dbus_message_set_no_reply (message, TRUE);
2176 if (!dbus_message_set_reply_serial (message,
2179 dbus_message_unref (message);
2184 if (error_msg != NULL)
2186 DBusMessageIter iter;
2188 dbus_message_iter_init_append (message, &iter);
2189 if (!dbus_message_iter_append_basic (&iter,
2193 dbus_message_unref (message);
2204 * Peek the incoming queue to see if we got reply for a specific serial
2207 _dbus_connection_peek_for_reply_unlocked (DBusConnection *connection,
2208 dbus_uint32_t client_serial)
2211 HAVE_LOCK_CHECK (connection);
2213 link = _dbus_list_get_first_link (&connection->incoming_messages);
2215 while (link != NULL)
2217 DBusMessage *reply = link->data;
2219 if (dbus_message_get_reply_serial (reply) == client_serial)
2221 _dbus_verbose ("%s reply to %d found in queue\n", _DBUS_FUNCTION_NAME, client_serial);
2224 link = _dbus_list_get_next_link (&connection->incoming_messages, link);
2230 /* This is slightly strange since we can pop a message here without
2231 * the dispatch lock.
2234 check_for_reply_unlocked (DBusConnection *connection,
2235 dbus_uint32_t client_serial)
2239 HAVE_LOCK_CHECK (connection);
2241 link = _dbus_list_get_first_link (&connection->incoming_messages);
2243 while (link != NULL)
2245 DBusMessage *reply = link->data;
2247 if (dbus_message_get_reply_serial (reply) == client_serial)
2249 _dbus_list_remove_link (&connection->incoming_messages, link);
2250 connection->n_incoming -= 1;
2253 link = _dbus_list_get_next_link (&connection->incoming_messages, link);
2260 connection_timeout_and_complete_all_pending_calls_unlocked (DBusConnection *connection)
2262 /* We can't iterate over the hash in the normal way since we'll be
2263 * dropping the lock for each item. So we restart the
2264 * iter each time as we drain the hash table.
2267 while (_dbus_hash_table_get_n_entries (connection->pending_replies) > 0)
2269 DBusPendingCall *pending;
2272 _dbus_hash_iter_init (connection->pending_replies, &iter);
2273 _dbus_hash_iter_next (&iter);
2275 pending = _dbus_hash_iter_get_value (&iter);
2276 _dbus_pending_call_ref_unlocked (pending);
2278 _dbus_pending_call_queue_timeout_error_unlocked (pending,
2281 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
2282 _dbus_connection_remove_timeout_unlocked (connection,
2283 _dbus_pending_call_get_timeout_unlocked (pending));
2284 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
2285 _dbus_hash_iter_remove_entry (&iter);
2287 _dbus_pending_call_unref_and_unlock (pending);
2288 CONNECTION_LOCK (connection);
2290 HAVE_LOCK_CHECK (connection);
2294 complete_pending_call_and_unlock (DBusConnection *connection,
2295 DBusPendingCall *pending,
2296 DBusMessage *message)
2298 _dbus_pending_call_set_reply_unlocked (pending, message);
2299 _dbus_pending_call_ref_unlocked (pending); /* in case there's no app with a ref held */
2300 _dbus_connection_detach_pending_call_and_unlock (connection, pending);
2302 /* Must be called unlocked since it invokes app callback */
2303 _dbus_pending_call_complete (pending);
2304 dbus_pending_call_unref (pending);
2308 check_for_reply_and_update_dispatch_unlocked (DBusConnection *connection,
2309 DBusPendingCall *pending)
2312 DBusDispatchStatus status;
2314 reply = check_for_reply_unlocked (connection,
2315 _dbus_pending_call_get_reply_serial_unlocked (pending));
2318 _dbus_verbose ("checked for reply\n");
2320 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): got reply\n");
2322 complete_pending_call_and_unlock (connection, pending, reply);
2323 dbus_message_unref (reply);
2325 CONNECTION_LOCK (connection);
2326 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2327 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2328 dbus_pending_call_unref (pending);
2337 * Blocks until a pending call times out or gets a reply.
2339 * Does not re-enter the main loop or run filter/path-registered
2340 * callbacks. The reply to the message will not be seen by
2343 * Returns immediately if pending call already got a reply.
2345 * @todo could use performance improvements (it keeps scanning
2346 * the whole message queue for example)
2348 * @param pending the pending call we block for a reply on
2351 _dbus_connection_block_pending_call (DBusPendingCall *pending)
2353 long start_tv_sec, start_tv_usec;
2354 long tv_sec, tv_usec;
2355 DBusDispatchStatus status;
2356 DBusConnection *connection;
2357 dbus_uint32_t client_serial;
2358 DBusTimeout *timeout;
2359 int timeout_milliseconds, elapsed_milliseconds;
2361 _dbus_assert (pending != NULL);
2363 if (dbus_pending_call_get_completed (pending))
2366 dbus_pending_call_ref (pending); /* necessary because the call could be canceled */
2368 connection = _dbus_pending_call_get_connection_and_lock (pending);
2370 /* Flush message queue - note, can affect dispatch status */
2371 _dbus_connection_flush_unlocked (connection);
2373 client_serial = _dbus_pending_call_get_reply_serial_unlocked (pending);
2375 /* note that timeout_milliseconds is limited to a smallish value
2376 * in _dbus_pending_call_new() so overflows aren't possible
2379 timeout = _dbus_pending_call_get_timeout_unlocked (pending);
2380 _dbus_get_current_time (&start_tv_sec, &start_tv_usec);
2383 timeout_milliseconds = dbus_timeout_get_interval (timeout);
2385 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): will block %d milliseconds for reply serial %u from %ld sec %ld usec\n",
2386 timeout_milliseconds,
2388 start_tv_sec, start_tv_usec);
2392 timeout_milliseconds = -1;
2394 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): will block for reply serial %u\n", client_serial);
2397 /* check to see if we already got the data off the socket */
2398 /* from another blocked pending call */
2399 if (check_for_reply_and_update_dispatch_unlocked (connection, pending))
2402 /* Now we wait... */
2403 /* always block at least once as we know we don't have the reply yet */
2404 _dbus_connection_do_iteration_unlocked (connection,
2406 DBUS_ITERATION_DO_READING |
2407 DBUS_ITERATION_BLOCK,
2408 timeout_milliseconds);
2412 _dbus_verbose ("top of recheck\n");
2414 HAVE_LOCK_CHECK (connection);
2416 /* queue messages and get status */
2418 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2420 /* the get_completed() is in case a dispatch() while we were blocking
2421 * got the reply instead of us.
2423 if (_dbus_pending_call_get_completed_unlocked (pending))
2425 _dbus_verbose ("Pending call completed by dispatch\n");
2426 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2427 dbus_pending_call_unref (pending);
2431 if (status == DBUS_DISPATCH_DATA_REMAINS)
2433 if (check_for_reply_and_update_dispatch_unlocked (connection, pending))
2437 _dbus_get_current_time (&tv_sec, &tv_usec);
2438 elapsed_milliseconds = (tv_sec - start_tv_sec) * 1000 +
2439 (tv_usec - start_tv_usec) / 1000;
2441 if (!_dbus_connection_get_is_connected_unlocked (connection))
2443 DBusMessage *error_msg;
2445 error_msg = generate_local_error_message (client_serial,
2446 DBUS_ERROR_DISCONNECTED,
2447 "Connection was disconnected before a reply was received");
2449 /* on OOM error_msg is set to NULL */
2450 complete_pending_call_and_unlock (connection, pending, error_msg);
2451 dbus_pending_call_unref (pending);
2454 else if (connection->disconnect_message_link == NULL)
2455 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): disconnected\n");
2456 else if (timeout == NULL)
2458 if (status == DBUS_DISPATCH_NEED_MEMORY)
2460 /* Try sleeping a bit, as we aren't sure we need to block for reading,
2461 * we may already have a reply in the buffer and just can't process
2464 _dbus_verbose ("dbus_connection_send_with_reply_and_block() waiting for more memory\n");
2466 _dbus_memory_pause_based_on_timeout (timeout_milliseconds - elapsed_milliseconds);
2470 /* block again, we don't have the reply buffered yet. */
2471 _dbus_connection_do_iteration_unlocked (connection,
2473 DBUS_ITERATION_DO_READING |
2474 DBUS_ITERATION_BLOCK,
2475 timeout_milliseconds - elapsed_milliseconds);
2478 goto recheck_status;
2480 else if (tv_sec < start_tv_sec)
2481 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): clock set backward\n");
2482 else if (elapsed_milliseconds < timeout_milliseconds)
2484 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): %d milliseconds remain\n", timeout_milliseconds - elapsed_milliseconds);
2486 if (status == DBUS_DISPATCH_NEED_MEMORY)
2488 /* Try sleeping a bit, as we aren't sure we need to block for reading,
2489 * we may already have a reply in the buffer and just can't process
2492 _dbus_verbose ("dbus_connection_send_with_reply_and_block() waiting for more memory\n");
2494 _dbus_memory_pause_based_on_timeout (timeout_milliseconds - elapsed_milliseconds);
2498 /* block again, we don't have the reply buffered yet. */
2499 _dbus_connection_do_iteration_unlocked (connection,
2501 DBUS_ITERATION_DO_READING |
2502 DBUS_ITERATION_BLOCK,
2503 timeout_milliseconds - elapsed_milliseconds);
2506 goto recheck_status;
2509 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): Waited %d milliseconds and got no reply\n",
2510 elapsed_milliseconds);
2512 _dbus_assert (!_dbus_pending_call_get_completed_unlocked (pending));
2514 /* unlock and call user code */
2515 complete_pending_call_and_unlock (connection, pending, NULL);
2517 /* update user code on dispatch status */
2518 CONNECTION_LOCK (connection);
2519 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2520 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2521 dbus_pending_call_unref (pending);
2527 * @addtogroup DBusConnection
2533 * Gets a connection to a remote address. If a connection to the given
2534 * address already exists, returns the existing connection with its
2535 * reference count incremented. Otherwise, returns a new connection
2536 * and saves the new connection for possible re-use if a future call
2537 * to dbus_connection_open() asks to connect to the same server.
2539 * Use dbus_connection_open_private() to get a dedicated connection
2540 * not shared with other callers of dbus_connection_open().
2542 * If the open fails, the function returns #NULL, and provides a
2543 * reason for the failure in the error parameter. Pass #NULL for the
2544 * error parameter if you aren't interested in the reason for
2547 * Because this connection is shared, no user of the connection
2548 * may call dbus_connection_close(). However, when you are done with the
2549 * connection you should call dbus_connection_unref().
2551 * @note Prefer dbus_connection_open() to dbus_connection_open_private()
2552 * unless you have good reason; connections are expensive enough
2553 * that it's wasteful to create lots of connections to the same
2556 * @param address the address.
2557 * @param error address where an error can be returned.
2558 * @returns new connection, or #NULL on failure.
2561 dbus_connection_open (const char *address,
2564 DBusConnection *connection;
2566 _dbus_return_val_if_fail (address != NULL, NULL);
2567 _dbus_return_val_if_error_is_set (error, NULL);
2569 connection = _dbus_connection_open_internal (address,
2577 * Opens a new, dedicated connection to a remote address. Unlike
2578 * dbus_connection_open(), always creates a new connection.
2579 * This connection will not be saved or recycled by libdbus.
2581 * If the open fails, the function returns #NULL, and provides a
2582 * reason for the failure in the error parameter. Pass #NULL for the
2583 * error parameter if you aren't interested in the reason for
2586 * When you are done with this connection, you must
2587 * dbus_connection_close() to disconnect it,
2588 * and dbus_connection_unref() to free the connection object.
2590 * (The dbus_connection_close() can be skipped if the
2591 * connection is already known to be disconnected, for example
2592 * if you are inside a handler for the Disconnected signal.)
2594 * @note Prefer dbus_connection_open() to dbus_connection_open_private()
2595 * unless you have good reason; connections are expensive enough
2596 * that it's wasteful to create lots of connections to the same
2599 * @param address the address.
2600 * @param error address where an error can be returned.
2601 * @returns new connection, or #NULL on failure.
2604 dbus_connection_open_private (const char *address,
2607 DBusConnection *connection;
2609 _dbus_return_val_if_fail (address != NULL, NULL);
2610 _dbus_return_val_if_error_is_set (error, NULL);
2612 connection = _dbus_connection_open_internal (address,
2620 * Increments the reference count of a DBusConnection.
2622 * @param connection the connection.
2623 * @returns the connection.
2626 dbus_connection_ref (DBusConnection *connection)
2628 _dbus_return_val_if_fail (connection != NULL, NULL);
2629 _dbus_return_val_if_fail (connection->generation == _dbus_current_generation, NULL);
2631 _dbus_atomic_inc (&connection->refcount);
2637 free_outgoing_message (void *element,
2640 DBusMessage *message = element;
2641 DBusConnection *connection = data;
2643 _dbus_message_remove_counter (message,
2644 connection->outgoing_counter,
2646 dbus_message_unref (message);
2649 /* This is run without the mutex held, but after the last reference
2650 * to the connection has been dropped we should have no thread-related
2654 _dbus_connection_last_unref (DBusConnection *connection)
2658 _dbus_verbose ("Finalizing connection %p\n", connection);
2660 _dbus_assert (_dbus_atomic_get (&connection->refcount) == 0);
2662 /* You have to disconnect the connection before unref:ing it. Otherwise
2663 * you won't get the disconnected message.
2665 _dbus_assert (!_dbus_transport_get_is_connected (connection->transport));
2666 _dbus_assert (connection->server_guid == NULL);
2668 /* ---- We're going to call various application callbacks here, hope it doesn't break anything... */
2669 _dbus_object_tree_free_all_unlocked (connection->objects);
2671 dbus_connection_set_dispatch_status_function (connection, NULL, NULL, NULL);
2672 dbus_connection_set_wakeup_main_function (connection, NULL, NULL, NULL);
2673 dbus_connection_set_unix_user_function (connection, NULL, NULL, NULL);
2675 _dbus_watch_list_free (connection->watches);
2676 connection->watches = NULL;
2678 _dbus_timeout_list_free (connection->timeouts);
2679 connection->timeouts = NULL;
2681 _dbus_data_slot_list_free (&connection->slot_list);
2683 link = _dbus_list_get_first_link (&connection->filter_list);
2684 while (link != NULL)
2686 DBusMessageFilter *filter = link->data;
2687 DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
2689 filter->function = NULL;
2690 _dbus_message_filter_unref (filter); /* calls app callback */
2695 _dbus_list_clear (&connection->filter_list);
2697 /* ---- Done with stuff that invokes application callbacks */
2699 _dbus_object_tree_unref (connection->objects);
2701 _dbus_hash_table_unref (connection->pending_replies);
2702 connection->pending_replies = NULL;
2704 _dbus_list_clear (&connection->filter_list);
2706 _dbus_list_foreach (&connection->outgoing_messages,
2707 free_outgoing_message,
2709 _dbus_list_clear (&connection->outgoing_messages);
2711 _dbus_list_foreach (&connection->incoming_messages,
2712 (DBusForeachFunction) dbus_message_unref,
2714 _dbus_list_clear (&connection->incoming_messages);
2716 _dbus_counter_unref (connection->outgoing_counter);
2718 _dbus_transport_unref (connection->transport);
2720 if (connection->disconnect_message_link)
2722 DBusMessage *message = connection->disconnect_message_link->data;
2723 dbus_message_unref (message);
2724 _dbus_list_free_link (connection->disconnect_message_link);
2727 _dbus_list_clear (&connection->link_cache);
2729 _dbus_condvar_free_at_location (&connection->dispatch_cond);
2730 _dbus_condvar_free_at_location (&connection->io_path_cond);
2732 _dbus_mutex_free_at_location (&connection->io_path_mutex);
2733 _dbus_mutex_free_at_location (&connection->dispatch_mutex);
2735 _dbus_mutex_free_at_location (&connection->slot_mutex);
2737 _dbus_mutex_free_at_location (&connection->mutex);
2739 dbus_free (connection);
2743 * Decrements the reference count of a DBusConnection, and finalizes
2744 * it if the count reaches zero.
2746 * Note: it is a bug to drop the last reference to a connection that
2747 * is still connected.
2749 * For shared connections, libdbus will own a reference
2750 * as long as the connection is connected, so you can know that either
2751 * you don't have the last reference, or it's OK to drop the last reference.
2752 * Most connections are shared. dbus_connection_open() and dbus_bus_get()
2753 * return shared connections.
2755 * For private connections, the creator of the connection must arrange for
2756 * dbus_connection_close() to be called prior to dropping the last reference.
2757 * Private connections come from dbus_connection_open_private() or dbus_bus_get_private().
2759 * @param connection the connection.
2762 dbus_connection_unref (DBusConnection *connection)
2764 dbus_bool_t last_unref;
2766 _dbus_return_if_fail (connection != NULL);
2767 _dbus_return_if_fail (connection->generation == _dbus_current_generation);
2769 last_unref = (_dbus_atomic_dec (&connection->refcount) == 1);
2773 #ifndef DBUS_DISABLE_CHECKS
2774 if (_dbus_transport_get_is_connected (connection->transport))
2776 _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",
2777 connection->shareable ?
2778 "Most likely, the application called unref() too many times and removed a reference belonging to libdbus, since this is a shared connection.\n" :
2779 "Most likely, the application was supposed to call dbus_connection_close(), since this is a private connection.\n");
2783 _dbus_connection_last_unref (connection);
2788 * Note that the transport can disconnect itself (other end drops us)
2789 * and in that case this function never runs. So this function must
2790 * not do anything more than disconnect the transport and update the
2793 * If the transport self-disconnects, then we assume someone will
2794 * dispatch the connection to cause the dispatch status update.
2797 _dbus_connection_close_possibly_shared_and_unlock (DBusConnection *connection)
2799 DBusDispatchStatus status;
2801 HAVE_LOCK_CHECK (connection);
2803 _dbus_verbose ("Disconnecting %p\n", connection);
2805 /* We need to ref because update_dispatch_status_and_unlock will unref
2806 * the connection if it was shared and libdbus was the only remaining
2809 _dbus_connection_ref_unlocked (connection);
2811 _dbus_transport_disconnect (connection->transport);
2813 /* This has the side effect of queuing the disconnect message link
2814 * (unless we don't have enough memory, possibly, so don't assert it).
2815 * After the disconnect message link is queued, dbus_bus_get/dbus_connection_open
2816 * should never again return the newly-disconnected connection.
2818 * However, we only unref the shared connection and exit_on_disconnect when
2819 * the disconnect message reaches the head of the message queue,
2820 * NOT when it's first queued.
2822 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2824 /* This calls out to user code */
2825 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2827 /* Could also call out to user code */
2828 dbus_connection_unref (connection);
2832 * Closes a private connection, so no further data can be sent or received.
2833 * This disconnects the transport (such as a socket) underlying the
2836 * Attempts to send messages after closing a connection are safe, but will result in
2837 * error replies generated locally in libdbus.
2839 * This function does not affect the connection's reference count. It's
2840 * safe to close a connection more than once; all calls after the
2841 * first do nothing. It's impossible to "reopen" a connection, a
2842 * new connection must be created. This function may result in a call
2843 * to the DBusDispatchStatusFunction set with
2844 * dbus_connection_set_dispatch_status_function(), as the disconnect
2845 * message it generates needs to be dispatched.
2847 * If a connection is dropped by the remote application, it will
2850 * You must close a connection prior to releasing the last reference to
2851 * the connection. If you dbus_connection_unref() for the last time
2852 * without closing the connection, the results are undefined; it
2853 * is a bug in your program and libdbus will try to print a warning.
2855 * You may not close a shared connection. Connections created with
2856 * dbus_connection_open() or dbus_bus_get() are shared.
2857 * These connections are owned by libdbus, and applications should
2858 * only unref them, never close them. Applications can know it is
2859 * safe to unref these connections because libdbus will be holding a
2860 * reference as long as the connection is open. Thus, either the
2861 * connection is closed and it is OK to drop the last reference,
2862 * or the connection is open and the app knows it does not have the
2865 * Connections created with dbus_connection_open_private() or
2866 * dbus_bus_get_private() are not kept track of or referenced by
2867 * libdbus. The creator of these connections is responsible for
2868 * calling dbus_connection_close() prior to releasing the last
2869 * reference, if the connection is not already disconnected.
2871 * @param connection the private (unshared) connection to close
2874 dbus_connection_close (DBusConnection *connection)
2876 _dbus_return_if_fail (connection != NULL);
2877 _dbus_return_if_fail (connection->generation == _dbus_current_generation);
2879 CONNECTION_LOCK (connection);
2881 #ifndef DBUS_DISABLE_CHECKS
2882 if (connection->shareable)
2884 CONNECTION_UNLOCK (connection);
2886 _dbus_warn_check_failed ("Applications must not close shared connections - see dbus_connection_close() docs. This is a bug in the application.\n");
2891 _dbus_connection_close_possibly_shared_and_unlock (connection);
2895 _dbus_connection_get_is_connected_unlocked (DBusConnection *connection)
2897 HAVE_LOCK_CHECK (connection);
2898 return _dbus_transport_get_is_connected (connection->transport);
2902 * Gets whether the connection is currently open. A connection may
2903 * become disconnected when the remote application closes its end, or
2904 * exits; a connection may also be disconnected with
2905 * dbus_connection_close().
2907 * There are not separate states for "closed" and "disconnected," the two
2908 * terms are synonymous. This function should really be called
2909 * get_is_open() but for historical reasons is not.
2911 * @param connection the connection.
2912 * @returns #TRUE if the connection is still alive.
2915 dbus_connection_get_is_connected (DBusConnection *connection)
2919 _dbus_return_val_if_fail (connection != NULL, FALSE);
2921 CONNECTION_LOCK (connection);
2922 res = _dbus_connection_get_is_connected_unlocked (connection);
2923 CONNECTION_UNLOCK (connection);
2929 * Gets whether the connection was authenticated. (Note that
2930 * if the connection was authenticated then disconnected,
2931 * this function still returns #TRUE)
2933 * @param connection the connection
2934 * @returns #TRUE if the connection was ever authenticated
2937 dbus_connection_get_is_authenticated (DBusConnection *connection)
2941 _dbus_return_val_if_fail (connection != NULL, FALSE);
2943 CONNECTION_LOCK (connection);
2944 res = _dbus_transport_get_is_authenticated (connection->transport);
2945 CONNECTION_UNLOCK (connection);
2951 * Gets whether the connection is not authenticated as a specific
2952 * user. If the connection is not authenticated, this function
2953 * returns #TRUE, and if it is authenticated but as an anonymous user,
2954 * it returns #TRUE. If it is authenticated as a specific user, then
2955 * this returns #FALSE. (Note that if the connection was authenticated
2956 * as anonymous then disconnected, this function still returns #TRUE.)
2958 * If the connection is not anonymous, you can use
2959 * dbus_connection_get_unix_user() and
2960 * dbus_connection_get_windows_user() to see who it's authorized as.
2962 * If you want to prevent non-anonymous authorization, use
2963 * dbus_server_set_auth_mechanisms() to remove the mechanisms that
2964 * allow proving user identity (i.e. only allow the ANONYMOUS
2967 * @param connection the connection
2968 * @returns #TRUE if not authenticated or authenticated as anonymous
2971 dbus_connection_get_is_anonymous (DBusConnection *connection)
2975 _dbus_return_val_if_fail (connection != NULL, FALSE);
2977 CONNECTION_LOCK (connection);
2978 res = _dbus_transport_get_is_anonymous (connection->transport);
2979 CONNECTION_UNLOCK (connection);
2985 * Gets the ID of the server address we are authenticated to, if this
2986 * connection is on the client side. If the connection is on the
2987 * server side, this will always return #NULL - use dbus_server_get_id()
2988 * to get the ID of your own server, if you are the server side.
2990 * If a client-side connection is not authenticated yet, the ID may be
2991 * available if it was included in the server address, but may not be
2992 * available. The only way to be sure the server ID is available
2993 * is to wait for authentication to complete.
2995 * In general, each mode of connecting to a given server will have
2996 * its own ID. So for example, if the session bus daemon is listening
2997 * on UNIX domain sockets and on TCP, then each of those modalities
2998 * will have its own server ID.
3000 * If you want an ID that identifies an entire session bus, look at
3001 * dbus_bus_get_id() instead (which is just a convenience wrapper
3002 * around the org.freedesktop.DBus.GetId method invoked on the bus).
3004 * You can also get a machine ID; see dbus_get_local_machine_id() to
3005 * get the machine you are on. There isn't a convenience wrapper, but
3006 * you can invoke org.freedesktop.DBus.Peer.GetMachineId on any peer
3007 * to get the machine ID on the other end.
3009 * The D-Bus specification describes the server ID and other IDs in a
3012 * @param connection the connection
3013 * @returns the server ID or #NULL if no memory or the connection is server-side
3016 dbus_connection_get_server_id (DBusConnection *connection)
3020 _dbus_return_val_if_fail (connection != NULL, NULL);
3022 CONNECTION_LOCK (connection);
3023 id = _dbus_strdup (_dbus_transport_get_server_id (connection->transport));
3024 CONNECTION_UNLOCK (connection);
3030 * Tests whether a certain type can be send via the connection. This
3031 * will always return TRUE for all types, with the exception of
3032 * DBUS_TYPE_UNIX_FD. The function will return TRUE for
3033 * DBUS_TYPE_UNIX_FD only on systems that know Unix file descriptors
3034 * and can send them via the chosen transport and when the remote side
3037 * This function can be used to do runtime checking for types that
3038 * might be unknown to the specific D-Bus client implementation
3039 * version, i.e. it will return FALSE for all types this
3040 * implementation does not know, including invalid or reserved types.
3042 * @param connection the connection
3043 * @param type the type to check
3044 * @returns TRUE if the type may be send via the connection
3047 dbus_connection_can_send_type(DBusConnection *connection,
3050 _dbus_return_val_if_fail (connection != NULL, FALSE);
3052 if (!_dbus_type_is_valid(type))
3055 if (type != DBUS_TYPE_UNIX_FD)
3058 #ifdef HAVE_UNIX_FD_PASSING
3062 CONNECTION_LOCK(connection);
3063 b = _dbus_transport_can_pass_unix_fd(connection->transport);
3064 CONNECTION_UNLOCK(connection);
3074 * Set whether _exit() should be called when the connection receives a
3075 * disconnect signal. The call to _exit() comes after any handlers for
3076 * the disconnect signal run; handlers can cancel the exit by calling
3079 * By default, exit_on_disconnect is #FALSE; but for message bus
3080 * connections returned from dbus_bus_get() it will be toggled on
3083 * @param connection the connection
3084 * @param exit_on_disconnect #TRUE if _exit() should be called after a disconnect signal
3087 dbus_connection_set_exit_on_disconnect (DBusConnection *connection,
3088 dbus_bool_t exit_on_disconnect)
3090 _dbus_return_if_fail (connection != NULL);
3092 CONNECTION_LOCK (connection);
3093 connection->exit_on_disconnect = exit_on_disconnect != FALSE;
3094 CONNECTION_UNLOCK (connection);
3098 * Preallocates resources needed to send a message, allowing the message
3099 * to be sent without the possibility of memory allocation failure.
3100 * Allows apps to create a future guarantee that they can send
3101 * a message regardless of memory shortages.
3103 * @param connection the connection we're preallocating for.
3104 * @returns the preallocated resources, or #NULL
3106 DBusPreallocatedSend*
3107 dbus_connection_preallocate_send (DBusConnection *connection)
3109 DBusPreallocatedSend *preallocated;
3111 _dbus_return_val_if_fail (connection != NULL, NULL);
3113 CONNECTION_LOCK (connection);
3116 _dbus_connection_preallocate_send_unlocked (connection);
3118 CONNECTION_UNLOCK (connection);
3120 return preallocated;
3124 * Frees preallocated message-sending resources from
3125 * dbus_connection_preallocate_send(). Should only
3126 * be called if the preallocated resources are not used
3127 * to send a message.
3129 * @param connection the connection
3130 * @param preallocated the resources
3133 dbus_connection_free_preallocated_send (DBusConnection *connection,
3134 DBusPreallocatedSend *preallocated)
3136 _dbus_return_if_fail (connection != NULL);
3137 _dbus_return_if_fail (preallocated != NULL);
3138 _dbus_return_if_fail (connection == preallocated->connection);
3140 _dbus_list_free_link (preallocated->queue_link);
3141 _dbus_counter_unref (preallocated->counter_link->data);
3142 _dbus_list_free_link (preallocated->counter_link);
3143 dbus_free (preallocated);
3147 * Sends a message using preallocated resources. This function cannot fail.
3148 * It works identically to dbus_connection_send() in other respects.
3149 * Preallocated resources comes from dbus_connection_preallocate_send().
3150 * This function "consumes" the preallocated resources, they need not
3151 * be freed separately.
3153 * @param connection the connection
3154 * @param preallocated the preallocated resources
3155 * @param message the message to send
3156 * @param client_serial return location for client serial assigned to the message
3159 dbus_connection_send_preallocated (DBusConnection *connection,
3160 DBusPreallocatedSend *preallocated,
3161 DBusMessage *message,
3162 dbus_uint32_t *client_serial)
3164 _dbus_return_if_fail (connection != NULL);
3165 _dbus_return_if_fail (preallocated != NULL);
3166 _dbus_return_if_fail (message != NULL);
3167 _dbus_return_if_fail (preallocated->connection == connection);
3168 _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_METHOD_CALL ||
3169 dbus_message_get_member (message) != NULL);
3170 _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL ||
3171 (dbus_message_get_interface (message) != NULL &&
3172 dbus_message_get_member (message) != NULL));
3174 CONNECTION_LOCK (connection);
3176 #ifdef HAVE_UNIX_FD_PASSING
3178 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3179 message->n_unix_fds > 0)
3181 /* Refuse to send fds on a connection that cannot handle
3182 them. Unfortunately we cannot return a proper error here, so
3183 the best we can is just return. */
3184 CONNECTION_UNLOCK (connection);
3190 _dbus_connection_send_preallocated_and_unlock (connection,
3192 message, client_serial);
3196 _dbus_connection_send_unlocked_no_update (DBusConnection *connection,
3197 DBusMessage *message,
3198 dbus_uint32_t *client_serial)
3200 DBusPreallocatedSend *preallocated;
3202 _dbus_assert (connection != NULL);
3203 _dbus_assert (message != NULL);
3205 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
3206 if (preallocated == NULL)
3209 _dbus_connection_send_preallocated_unlocked_no_update (connection,
3217 * Adds a message to the outgoing message queue. Does not block to
3218 * write the message to the network; that happens asynchronously. To
3219 * force the message to be written, call dbus_connection_flush() however
3220 * it is not necessary to call dbus_connection_flush() by hand; the
3221 * message will be sent the next time the main loop is run.
3222 * dbus_connection_flush() should only be used, for example, if
3223 * the application was expected to exit before running the main loop.
3225 * Because this only queues the message, the only reason it can
3226 * fail is lack of memory. Even if the connection is disconnected,
3227 * no error will be returned. If the function fails due to lack of memory,
3228 * it returns #FALSE. The function will never fail for other reasons; even
3229 * if the connection is disconnected, you can queue an outgoing message,
3230 * though obviously it won't be sent.
3232 * The message serial is used by the remote application to send a
3233 * reply; see dbus_message_get_serial() or the D-Bus specification.
3235 * dbus_message_unref() can be called as soon as this method returns
3236 * as the message queue will hold its own ref until the message is sent.
3238 * @param connection the connection.
3239 * @param message the message to write.
3240 * @param serial return location for message serial, or #NULL if you don't care
3241 * @returns #TRUE on success.
3244 dbus_connection_send (DBusConnection *connection,
3245 DBusMessage *message,
3246 dbus_uint32_t *serial)
3248 _dbus_return_val_if_fail (connection != NULL, FALSE);
3249 _dbus_return_val_if_fail (message != NULL, FALSE);
3251 CONNECTION_LOCK (connection);
3253 #ifdef HAVE_UNIX_FD_PASSING
3255 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3256 message->n_unix_fds > 0)
3258 /* Refuse to send fds on a connection that cannot handle
3259 them. Unfortunately we cannot return a proper error here, so
3260 the best we can is just return. */
3261 CONNECTION_UNLOCK (connection);
3267 return _dbus_connection_send_and_unlock (connection,
3273 reply_handler_timeout (void *data)
3275 DBusConnection *connection;
3276 DBusDispatchStatus status;
3277 DBusPendingCall *pending = data;
3279 connection = _dbus_pending_call_get_connection_and_lock (pending);
3281 _dbus_pending_call_queue_timeout_error_unlocked (pending,
3283 _dbus_connection_remove_timeout_unlocked (connection,
3284 _dbus_pending_call_get_timeout_unlocked (pending));
3285 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
3287 _dbus_verbose ("middle\n");
3288 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3290 /* Unlocks, and calls out to user code */
3291 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3297 * Queues a message to send, as with dbus_connection_send(),
3298 * but also returns a #DBusPendingCall used to receive a reply to the
3299 * message. If no reply is received in the given timeout_milliseconds,
3300 * this function expires the pending reply and generates a synthetic
3301 * error reply (generated in-process, not by the remote application)
3302 * indicating that a timeout occurred.
3304 * A #DBusPendingCall will see a reply message before any filters or
3305 * registered object path handlers. See dbus_connection_dispatch() for
3306 * details on when handlers are run.
3308 * A #DBusPendingCall will always see exactly one reply message,
3309 * unless it's cancelled with dbus_pending_call_cancel().
3311 * If #NULL is passed for the pending_return, the #DBusPendingCall
3312 * will still be generated internally, and used to track
3313 * the message reply timeout. This means a timeout error will
3314 * occur if no reply arrives, unlike with dbus_connection_send().
3316 * If -1 is passed for the timeout, a sane default timeout is used. -1
3317 * is typically the best value for the timeout for this reason, unless
3318 * you want a very short or very long timeout. If #DBUS_TIMEOUT_INFINITE is
3319 * passed for the timeout, no timeout will be set and the call will block
3322 * @warning if the connection is disconnected or you try to send Unix
3323 * file descriptors on a connection that does not support them, the
3324 * #DBusPendingCall will be set to #NULL, so be careful with this.
3326 * @param connection the connection
3327 * @param message the message to send
3328 * @param pending_return return location for a #DBusPendingCall
3329 * object, or #NULL if connection is disconnected or when you try to
3330 * send Unix file descriptors on a connection that does not support
3332 * @param timeout_milliseconds timeout in milliseconds, -1 (or
3333 * #DBUS_TIMEOUT_USE_DEFAULT) for default or #DBUS_TIMEOUT_INFINITE for no
3335 * @returns #FALSE if no memory, #TRUE otherwise.
3339 dbus_connection_send_with_reply (DBusConnection *connection,
3340 DBusMessage *message,
3341 DBusPendingCall **pending_return,
3342 int timeout_milliseconds)
3344 DBusPendingCall *pending;
3345 dbus_int32_t serial = -1;
3346 DBusDispatchStatus status;
3348 _dbus_return_val_if_fail (connection != NULL, FALSE);
3349 _dbus_return_val_if_fail (message != NULL, FALSE);
3350 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3353 *pending_return = NULL;
3355 CONNECTION_LOCK (connection);
3357 #ifdef HAVE_UNIX_FD_PASSING
3359 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3360 message->n_unix_fds > 0)
3362 /* Refuse to send fds on a connection that cannot handle
3363 them. Unfortunately we cannot return a proper error here, so
3364 the best we can do is return TRUE but leave *pending_return
3366 CONNECTION_UNLOCK (connection);
3372 if (!_dbus_connection_get_is_connected_unlocked (connection))
3374 CONNECTION_UNLOCK (connection);
3379 pending = _dbus_pending_call_new_unlocked (connection,
3380 timeout_milliseconds,
3381 reply_handler_timeout);
3383 if (pending == NULL)
3385 CONNECTION_UNLOCK (connection);
3389 /* Assign a serial to the message */
3390 serial = dbus_message_get_serial (message);
3393 serial = _dbus_connection_get_next_client_serial (connection);
3394 dbus_message_set_serial (message, serial);
3397 if (!_dbus_pending_call_set_timeout_error_unlocked (pending, message, serial))
3400 /* Insert the serial in the pending replies hash;
3401 * hash takes a refcount on DBusPendingCall.
3402 * Also, add the timeout.
3404 if (!_dbus_connection_attach_pending_call_unlocked (connection,
3408 if (!_dbus_connection_send_unlocked_no_update (connection, message, NULL))
3410 _dbus_connection_detach_pending_call_and_unlock (connection,
3412 goto error_unlocked;
3416 *pending_return = pending; /* hand off refcount */
3419 _dbus_connection_detach_pending_call_unlocked (connection, pending);
3420 /* we still have a ref to the pending call in this case, we unref
3421 * after unlocking, below
3425 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3427 /* this calls out to user code */
3428 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3430 if (pending_return == NULL)
3431 dbus_pending_call_unref (pending);
3436 CONNECTION_UNLOCK (connection);
3438 dbus_pending_call_unref (pending);
3443 * Sends a message and blocks a certain time period while waiting for
3444 * a reply. This function does not reenter the main loop,
3445 * i.e. messages other than the reply are queued up but not
3446 * processed. This function is used to invoke method calls on a
3449 * If a normal reply is received, it is returned, and removed from the
3450 * incoming message queue. If it is not received, #NULL is returned
3451 * and the error is set to #DBUS_ERROR_NO_REPLY. If an error reply is
3452 * received, it is converted to a #DBusError and returned as an error,
3453 * then the reply message is deleted and #NULL is returned. If
3454 * something else goes wrong, result is set to whatever is
3455 * appropriate, such as #DBUS_ERROR_NO_MEMORY or
3456 * #DBUS_ERROR_DISCONNECTED.
3458 * @warning While this function blocks the calling thread will not be
3459 * processing the incoming message queue. This means you can end up
3460 * deadlocked if the application you're talking to needs you to reply
3461 * to a method. To solve this, either avoid the situation, block in a
3462 * separate thread from the main connection-dispatching thread, or use
3463 * dbus_pending_call_set_notify() to avoid blocking.
3465 * @param connection the connection
3466 * @param message the message to send
3467 * @param timeout_milliseconds timeout in milliseconds, -1 (or
3468 * #DBUS_TIMEOUT_USE_DEFAULT) for default or #DBUS_TIMEOUT_INFINITE for no
3470 * @param error return location for error message
3471 * @returns the message that is the reply or #NULL with an error code if the
3475 dbus_connection_send_with_reply_and_block (DBusConnection *connection,
3476 DBusMessage *message,
3477 int timeout_milliseconds,
3481 DBusPendingCall *pending;
3483 _dbus_return_val_if_fail (connection != NULL, NULL);
3484 _dbus_return_val_if_fail (message != NULL, NULL);
3485 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, NULL);
3486 _dbus_return_val_if_error_is_set (error, NULL);
3488 #ifdef HAVE_UNIX_FD_PASSING
3490 CONNECTION_LOCK (connection);
3491 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3492 message->n_unix_fds > 0)
3494 CONNECTION_UNLOCK (connection);
3495 dbus_set_error(error, DBUS_ERROR_FAILED, "Cannot send file descriptors on this connection.");
3498 CONNECTION_UNLOCK (connection);
3502 if (!dbus_connection_send_with_reply (connection, message,
3503 &pending, timeout_milliseconds))
3505 _DBUS_SET_OOM (error);
3509 if (pending == NULL)
3511 dbus_set_error (error, DBUS_ERROR_DISCONNECTED, "Connection is closed");
3515 dbus_pending_call_block (pending);
3517 reply = dbus_pending_call_steal_reply (pending);
3518 dbus_pending_call_unref (pending);
3520 /* call_complete_and_unlock() called from pending_call_block() should
3521 * always fill this in.
3523 _dbus_assert (reply != NULL);
3525 if (dbus_set_error_from_message (error, reply))
3527 dbus_message_unref (reply);
3535 * Blocks until the outgoing message queue is empty.
3536 * Assumes connection lock already held.
3538 * If you call this, you MUST call update_dispatch_status afterword...
3540 * @param connection the connection.
3542 static DBusDispatchStatus
3543 _dbus_connection_flush_unlocked (DBusConnection *connection)
3545 /* We have to specify DBUS_ITERATION_DO_READING here because
3546 * otherwise we could have two apps deadlock if they are both doing
3547 * a flush(), and the kernel buffers fill up. This could change the
3550 DBusDispatchStatus status;
3552 HAVE_LOCK_CHECK (connection);
3554 while (connection->n_outgoing > 0 &&
3555 _dbus_connection_get_is_connected_unlocked (connection))
3557 _dbus_verbose ("doing iteration in\n");
3558 HAVE_LOCK_CHECK (connection);
3559 _dbus_connection_do_iteration_unlocked (connection,
3561 DBUS_ITERATION_DO_READING |
3562 DBUS_ITERATION_DO_WRITING |
3563 DBUS_ITERATION_BLOCK,
3567 HAVE_LOCK_CHECK (connection);
3568 _dbus_verbose ("middle\n");
3569 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3571 HAVE_LOCK_CHECK (connection);
3576 * Blocks until the outgoing message queue is empty.
3578 * @param connection the connection.
3581 dbus_connection_flush (DBusConnection *connection)
3583 /* We have to specify DBUS_ITERATION_DO_READING here because
3584 * otherwise we could have two apps deadlock if they are both doing
3585 * a flush(), and the kernel buffers fill up. This could change the
3588 DBusDispatchStatus status;
3590 _dbus_return_if_fail (connection != NULL);
3592 CONNECTION_LOCK (connection);
3594 status = _dbus_connection_flush_unlocked (connection);
3596 HAVE_LOCK_CHECK (connection);
3597 /* Unlocks and calls out to user code */
3598 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3600 _dbus_verbose ("end\n");
3604 * This function implements dbus_connection_read_write_dispatch() and
3605 * dbus_connection_read_write() (they pass a different value for the
3606 * dispatch parameter).
3608 * @param connection the connection
3609 * @param timeout_milliseconds max time to block or -1 for infinite
3610 * @param dispatch dispatch new messages or leave them on the incoming queue
3611 * @returns #TRUE if the disconnect message has not been processed
3614 _dbus_connection_read_write_dispatch (DBusConnection *connection,
3615 int timeout_milliseconds,
3616 dbus_bool_t dispatch)
3618 DBusDispatchStatus dstatus;
3619 dbus_bool_t progress_possible;
3621 /* Need to grab a ref here in case we're a private connection and
3622 * the user drops the last ref in a handler we call; see bug
3623 * https://bugs.freedesktop.org/show_bug.cgi?id=15635
3625 dbus_connection_ref (connection);
3626 dstatus = dbus_connection_get_dispatch_status (connection);
3628 if (dispatch && dstatus == DBUS_DISPATCH_DATA_REMAINS)
3630 _dbus_verbose ("doing dispatch\n");
3631 dbus_connection_dispatch (connection);
3632 CONNECTION_LOCK (connection);
3634 else if (dstatus == DBUS_DISPATCH_NEED_MEMORY)
3636 _dbus_verbose ("pausing for memory\n");
3637 _dbus_memory_pause_based_on_timeout (timeout_milliseconds);
3638 CONNECTION_LOCK (connection);
3642 CONNECTION_LOCK (connection);
3643 if (_dbus_connection_get_is_connected_unlocked (connection))
3645 _dbus_verbose ("doing iteration\n");
3646 _dbus_connection_do_iteration_unlocked (connection,
3648 DBUS_ITERATION_DO_READING |
3649 DBUS_ITERATION_DO_WRITING |
3650 DBUS_ITERATION_BLOCK,
3651 timeout_milliseconds);
3655 HAVE_LOCK_CHECK (connection);
3656 /* If we can dispatch, we can make progress until the Disconnected message
3657 * has been processed; if we can only read/write, we can make progress
3658 * as long as the transport is open.
3661 progress_possible = connection->n_incoming != 0 ||
3662 connection->disconnect_message_link != NULL;
3664 progress_possible = _dbus_connection_get_is_connected_unlocked (connection);
3666 CONNECTION_UNLOCK (connection);
3668 dbus_connection_unref (connection);
3670 return progress_possible; /* TRUE if we can make more progress */
3675 * This function is intended for use with applications that don't want
3676 * to write a main loop and deal with #DBusWatch and #DBusTimeout. An
3677 * example usage would be:
3680 * while (dbus_connection_read_write_dispatch (connection, -1))
3681 * ; // empty loop body
3684 * In this usage you would normally have set up a filter function to look
3685 * at each message as it is dispatched. The loop terminates when the last
3686 * message from the connection (the disconnected signal) is processed.
3688 * If there are messages to dispatch, this function will
3689 * dbus_connection_dispatch() once, and return. If there are no
3690 * messages to dispatch, this function will block until it can read or
3691 * write, then read or write, then return.
3693 * The way to think of this function is that it either makes some sort
3694 * of progress, or it blocks. Note that, while it is blocked on I/O, it
3695 * cannot be interrupted (even by other threads), which makes this function
3696 * unsuitable for applications that do more than just react to received
3699 * The return value indicates whether the disconnect message has been
3700 * processed, NOT whether the connection is connected. This is
3701 * important because even after disconnecting, you want to process any
3702 * messages you received prior to the disconnect.
3704 * @param connection the connection
3705 * @param timeout_milliseconds max time to block or -1 for infinite
3706 * @returns #TRUE if the disconnect message has not been processed
3709 dbus_connection_read_write_dispatch (DBusConnection *connection,
3710 int timeout_milliseconds)
3712 _dbus_return_val_if_fail (connection != NULL, FALSE);
3713 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3714 return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, TRUE);
3718 * This function is intended for use with applications that don't want to
3719 * write a main loop and deal with #DBusWatch and #DBusTimeout. See also
3720 * dbus_connection_read_write_dispatch().
3722 * As long as the connection is open, this function will block until it can
3723 * read or write, then read or write, then return #TRUE.
3725 * If the connection is closed, the function returns #FALSE.
3727 * The return value indicates whether reading or writing is still
3728 * possible, i.e. whether the connection is connected.
3730 * Note that even after disconnection, messages may remain in the
3731 * incoming queue that need to be
3732 * processed. dbus_connection_read_write_dispatch() dispatches
3733 * incoming messages for you; with dbus_connection_read_write() you
3734 * have to arrange to drain the incoming queue yourself.
3736 * @param connection the connection
3737 * @param timeout_milliseconds max time to block or -1 for infinite
3738 * @returns #TRUE if still connected
3741 dbus_connection_read_write (DBusConnection *connection,
3742 int timeout_milliseconds)
3744 _dbus_return_val_if_fail (connection != NULL, FALSE);
3745 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3746 return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, FALSE);
3749 /* We need to call this anytime we pop the head of the queue, and then
3750 * update_dispatch_status_and_unlock needs to be called afterward
3751 * which will "process" the disconnected message and set
3752 * disconnected_message_processed.
3755 check_disconnected_message_arrived_unlocked (DBusConnection *connection,
3756 DBusMessage *head_of_queue)
3758 HAVE_LOCK_CHECK (connection);
3760 /* checking that the link is NULL is an optimization to avoid the is_signal call */
3761 if (connection->disconnect_message_link == NULL &&
3762 dbus_message_is_signal (head_of_queue,
3763 DBUS_INTERFACE_LOCAL,
3766 connection->disconnected_message_arrived = TRUE;
3771 * Returns the first-received message from the incoming message queue,
3772 * leaving it in the queue. If the queue is empty, returns #NULL.
3774 * The caller does not own a reference to the returned message, and
3775 * must either return it using dbus_connection_return_message() or
3776 * keep it after calling dbus_connection_steal_borrowed_message(). No
3777 * one can get at the message while its borrowed, so return it as
3778 * quickly as possible and don't keep a reference to it after
3779 * returning it. If you need to keep the message, make a copy of it.
3781 * dbus_connection_dispatch() will block if called while a borrowed
3782 * message is outstanding; only one piece of code can be playing with
3783 * the incoming queue at a time. This function will block if called
3784 * during a dbus_connection_dispatch().
3786 * @param connection the connection.
3787 * @returns next message in the incoming queue.
3790 dbus_connection_borrow_message (DBusConnection *connection)
3792 DBusDispatchStatus status;
3793 DBusMessage *message;
3795 _dbus_return_val_if_fail (connection != NULL, NULL);
3797 _dbus_verbose ("start\n");
3799 /* this is called for the side effect that it queues
3800 * up any messages from the transport
3802 status = dbus_connection_get_dispatch_status (connection);
3803 if (status != DBUS_DISPATCH_DATA_REMAINS)
3806 CONNECTION_LOCK (connection);
3808 _dbus_connection_acquire_dispatch (connection);
3810 /* While a message is outstanding, the dispatch lock is held */
3811 _dbus_assert (connection->message_borrowed == NULL);
3813 connection->message_borrowed = _dbus_list_get_first (&connection->incoming_messages);
3815 message = connection->message_borrowed;
3817 check_disconnected_message_arrived_unlocked (connection, message);
3819 /* Note that we KEEP the dispatch lock until the message is returned */
3820 if (message == NULL)
3821 _dbus_connection_release_dispatch (connection);
3823 CONNECTION_UNLOCK (connection);
3825 /* We don't update dispatch status until it's returned or stolen */
3831 * Used to return a message after peeking at it using
3832 * dbus_connection_borrow_message(). Only called if
3833 * message from dbus_connection_borrow_message() was non-#NULL.
3835 * @param connection the connection
3836 * @param message the message from dbus_connection_borrow_message()
3839 dbus_connection_return_message (DBusConnection *connection,
3840 DBusMessage *message)
3842 DBusDispatchStatus status;
3844 _dbus_return_if_fail (connection != NULL);
3845 _dbus_return_if_fail (message != NULL);
3846 _dbus_return_if_fail (message == connection->message_borrowed);
3847 _dbus_return_if_fail (connection->dispatch_acquired);
3849 CONNECTION_LOCK (connection);
3851 _dbus_assert (message == connection->message_borrowed);
3853 connection->message_borrowed = NULL;
3855 _dbus_connection_release_dispatch (connection);
3857 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3858 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3862 * Used to keep a message after peeking at it using
3863 * dbus_connection_borrow_message(). Before using this function, see
3864 * the caveats/warnings in the documentation for
3865 * dbus_connection_pop_message().
3867 * @param connection the connection
3868 * @param message the message from dbus_connection_borrow_message()
3871 dbus_connection_steal_borrowed_message (DBusConnection *connection,
3872 DBusMessage *message)
3874 DBusMessage *pop_message;
3875 DBusDispatchStatus status;
3877 _dbus_return_if_fail (connection != NULL);
3878 _dbus_return_if_fail (message != NULL);
3879 _dbus_return_if_fail (message == connection->message_borrowed);
3880 _dbus_return_if_fail (connection->dispatch_acquired);
3882 CONNECTION_LOCK (connection);
3884 _dbus_assert (message == connection->message_borrowed);
3886 pop_message = _dbus_list_pop_first (&connection->incoming_messages);
3887 _dbus_assert (message == pop_message);
3889 connection->n_incoming -= 1;
3891 _dbus_verbose ("Incoming message %p stolen from queue, %d incoming\n",
3892 message, connection->n_incoming);
3894 connection->message_borrowed = NULL;
3896 _dbus_connection_release_dispatch (connection);
3898 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3899 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3902 /* See dbus_connection_pop_message, but requires the caller to own
3903 * the lock before calling. May drop the lock while running.
3906 _dbus_connection_pop_message_link_unlocked (DBusConnection *connection)
3908 HAVE_LOCK_CHECK (connection);
3910 _dbus_assert (connection->message_borrowed == NULL);
3912 if (connection->n_incoming > 0)
3916 link = _dbus_list_pop_first_link (&connection->incoming_messages);
3917 connection->n_incoming -= 1;
3919 _dbus_verbose ("Message %p (%s %s %s %s '%s') removed from incoming queue %p, %d incoming\n",
3921 dbus_message_type_to_string (dbus_message_get_type (link->data)),
3922 dbus_message_get_path (link->data) ?
3923 dbus_message_get_path (link->data) :
3925 dbus_message_get_interface (link->data) ?
3926 dbus_message_get_interface (link->data) :
3928 dbus_message_get_member (link->data) ?
3929 dbus_message_get_member (link->data) :
3931 dbus_message_get_signature (link->data),
3932 connection, connection->n_incoming);
3934 check_disconnected_message_arrived_unlocked (connection, link->data);
3942 /* See dbus_connection_pop_message, but requires the caller to own
3943 * the lock before calling. May drop the lock while running.
3946 _dbus_connection_pop_message_unlocked (DBusConnection *connection)
3950 HAVE_LOCK_CHECK (connection);
3952 link = _dbus_connection_pop_message_link_unlocked (connection);
3956 DBusMessage *message;
3958 message = link->data;
3960 _dbus_list_free_link (link);
3969 _dbus_connection_putback_message_link_unlocked (DBusConnection *connection,
3970 DBusList *message_link)
3972 HAVE_LOCK_CHECK (connection);
3974 _dbus_assert (message_link != NULL);
3975 /* You can't borrow a message while a link is outstanding */
3976 _dbus_assert (connection->message_borrowed == NULL);
3977 /* We had to have the dispatch lock across the pop/putback */
3978 _dbus_assert (connection->dispatch_acquired);
3980 _dbus_list_prepend_link (&connection->incoming_messages,
3982 connection->n_incoming += 1;
3984 _dbus_verbose ("Message %p (%s %s %s '%s') put back into queue %p, %d incoming\n",
3986 dbus_message_type_to_string (dbus_message_get_type (message_link->data)),
3987 dbus_message_get_interface (message_link->data) ?
3988 dbus_message_get_interface (message_link->data) :
3990 dbus_message_get_member (message_link->data) ?
3991 dbus_message_get_member (message_link->data) :
3993 dbus_message_get_signature (message_link->data),
3994 connection, connection->n_incoming);
3998 * Returns the first-received message from the incoming message queue,
3999 * removing it from the queue. The caller owns a reference to the
4000 * returned message. If the queue is empty, returns #NULL.
4002 * This function bypasses any message handlers that are registered,
4003 * and so using it is usually wrong. Instead, let the main loop invoke
4004 * dbus_connection_dispatch(). Popping messages manually is only
4005 * useful in very simple programs that don't share a #DBusConnection
4006 * with any libraries or other modules.
4008 * There is a lock that covers all ways of accessing the incoming message
4009 * queue, so dbus_connection_dispatch(), dbus_connection_pop_message(),
4010 * dbus_connection_borrow_message(), etc. will all block while one of the others
4011 * in the group is running.
4013 * @param connection the connection.
4014 * @returns next message in the incoming queue.
4017 dbus_connection_pop_message (DBusConnection *connection)
4019 DBusMessage *message;
4020 DBusDispatchStatus status;
4022 _dbus_verbose ("start\n");
4024 /* this is called for the side effect that it queues
4025 * up any messages from the transport
4027 status = dbus_connection_get_dispatch_status (connection);
4028 if (status != DBUS_DISPATCH_DATA_REMAINS)
4031 CONNECTION_LOCK (connection);
4032 _dbus_connection_acquire_dispatch (connection);
4033 HAVE_LOCK_CHECK (connection);
4035 message = _dbus_connection_pop_message_unlocked (connection);
4037 _dbus_verbose ("Returning popped message %p\n", message);
4039 _dbus_connection_release_dispatch (connection);
4041 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4042 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4048 * Acquire the dispatcher. This is a separate lock so the main
4049 * connection lock can be dropped to call out to application dispatch
4052 * @param connection the connection.
4055 _dbus_connection_acquire_dispatch (DBusConnection *connection)
4057 HAVE_LOCK_CHECK (connection);
4059 _dbus_connection_ref_unlocked (connection);
4060 CONNECTION_UNLOCK (connection);
4062 _dbus_verbose ("locking dispatch_mutex\n");
4063 _dbus_mutex_lock (connection->dispatch_mutex);
4065 while (connection->dispatch_acquired)
4067 _dbus_verbose ("waiting for dispatch to be acquirable\n");
4068 _dbus_condvar_wait (connection->dispatch_cond,
4069 connection->dispatch_mutex);
4072 _dbus_assert (!connection->dispatch_acquired);
4074 connection->dispatch_acquired = TRUE;
4076 _dbus_verbose ("unlocking dispatch_mutex\n");
4077 _dbus_mutex_unlock (connection->dispatch_mutex);
4079 CONNECTION_LOCK (connection);
4080 _dbus_connection_unref_unlocked (connection);
4084 * Release the dispatcher when you're done with it. Only call
4085 * after you've acquired the dispatcher. Wakes up at most one
4086 * thread currently waiting to acquire the dispatcher.
4088 * @param connection the connection.
4091 _dbus_connection_release_dispatch (DBusConnection *connection)
4093 HAVE_LOCK_CHECK (connection);
4095 _dbus_verbose ("locking dispatch_mutex\n");
4096 _dbus_mutex_lock (connection->dispatch_mutex);
4098 _dbus_assert (connection->dispatch_acquired);
4100 connection->dispatch_acquired = FALSE;
4101 _dbus_condvar_wake_one (connection->dispatch_cond);
4103 _dbus_verbose ("unlocking dispatch_mutex\n");
4104 _dbus_mutex_unlock (connection->dispatch_mutex);
4108 _dbus_connection_failed_pop (DBusConnection *connection,
4109 DBusList *message_link)
4111 _dbus_list_prepend_link (&connection->incoming_messages,
4113 connection->n_incoming += 1;
4116 /* Note this may be called multiple times since we don't track whether we already did it */
4118 notify_disconnected_unlocked (DBusConnection *connection)
4120 HAVE_LOCK_CHECK (connection);
4122 /* Set the weakref in dbus-bus.c to NULL, so nobody will get a disconnected
4123 * connection from dbus_bus_get(). We make the same guarantee for
4124 * dbus_connection_open() but in a different way since we don't want to
4125 * unref right here; we instead check for connectedness before returning
4126 * the connection from the hash.
4128 _dbus_bus_notify_shared_connection_disconnected_unlocked (connection);
4130 /* Dump the outgoing queue, we aren't going to be able to
4131 * send it now, and we'd like accessors like
4132 * dbus_connection_get_outgoing_size() to be accurate.
4134 if (connection->n_outgoing > 0)
4138 _dbus_verbose ("Dropping %d outgoing messages since we're disconnected\n",
4139 connection->n_outgoing);
4141 while ((link = _dbus_list_get_last_link (&connection->outgoing_messages)))
4143 _dbus_connection_message_sent (connection, link->data);
4148 /* Note this may be called multiple times since we don't track whether we already did it */
4149 static DBusDispatchStatus
4150 notify_disconnected_and_dispatch_complete_unlocked (DBusConnection *connection)
4152 HAVE_LOCK_CHECK (connection);
4154 if (connection->disconnect_message_link != NULL)
4156 _dbus_verbose ("Sending disconnect message\n");
4158 /* If we have pending calls, queue their timeouts - we want the Disconnected
4159 * to be the last message, after these timeouts.
4161 connection_timeout_and_complete_all_pending_calls_unlocked (connection);
4163 /* We haven't sent the disconnect message already,
4164 * and all real messages have been queued up.
4166 _dbus_connection_queue_synthesized_message_link (connection,
4167 connection->disconnect_message_link);
4168 connection->disconnect_message_link = NULL;
4170 return DBUS_DISPATCH_DATA_REMAINS;
4173 return DBUS_DISPATCH_COMPLETE;
4176 static DBusDispatchStatus
4177 _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection)
4179 HAVE_LOCK_CHECK (connection);
4181 if (connection->n_incoming > 0)
4182 return DBUS_DISPATCH_DATA_REMAINS;
4183 else if (!_dbus_transport_queue_messages (connection->transport))
4184 return DBUS_DISPATCH_NEED_MEMORY;
4187 DBusDispatchStatus status;
4188 dbus_bool_t is_connected;
4190 status = _dbus_transport_get_dispatch_status (connection->transport);
4191 is_connected = _dbus_transport_get_is_connected (connection->transport);
4193 _dbus_verbose ("dispatch status = %s is_connected = %d\n",
4194 DISPATCH_STATUS_NAME (status), is_connected);
4198 /* It's possible this would be better done by having an explicit
4199 * notification from _dbus_transport_disconnect() that would
4200 * synchronously do this, instead of waiting for the next dispatch
4201 * status check. However, probably not good to change until it causes
4204 notify_disconnected_unlocked (connection);
4206 /* I'm not sure this is needed; the idea is that we want to
4207 * queue the Disconnected only after we've read all the
4208 * messages, but if we're disconnected maybe we are guaranteed
4209 * to have read them all ?
4211 if (status == DBUS_DISPATCH_COMPLETE)
4212 status = notify_disconnected_and_dispatch_complete_unlocked (connection);
4215 if (status != DBUS_DISPATCH_COMPLETE)
4217 else if (connection->n_incoming > 0)
4218 return DBUS_DISPATCH_DATA_REMAINS;
4220 return DBUS_DISPATCH_COMPLETE;
4225 _dbus_connection_update_dispatch_status_and_unlock (DBusConnection *connection,
4226 DBusDispatchStatus new_status)
4228 dbus_bool_t changed;
4229 DBusDispatchStatusFunction function;
4232 HAVE_LOCK_CHECK (connection);
4234 _dbus_connection_ref_unlocked (connection);
4236 changed = new_status != connection->last_dispatch_status;
4238 connection->last_dispatch_status = new_status;
4240 function = connection->dispatch_status_function;
4241 data = connection->dispatch_status_data;
4243 if (connection->disconnected_message_arrived &&
4244 !connection->disconnected_message_processed)
4246 connection->disconnected_message_processed = TRUE;
4248 /* this does an unref, but we have a ref
4249 * so we should not run the finalizer here
4252 connection_forget_shared_unlocked (connection);
4254 if (connection->exit_on_disconnect)
4256 CONNECTION_UNLOCK (connection);
4258 _dbus_verbose ("Exiting on Disconnected signal\n");
4260 _dbus_assert_not_reached ("Call to exit() returned");
4264 /* We drop the lock */
4265 CONNECTION_UNLOCK (connection);
4267 if (changed && function)
4269 _dbus_verbose ("Notifying of change to dispatch status of %p now %d (%s)\n",
4270 connection, new_status,
4271 DISPATCH_STATUS_NAME (new_status));
4272 (* function) (connection, new_status, data);
4275 dbus_connection_unref (connection);
4279 * Gets the current state of the incoming message queue.
4280 * #DBUS_DISPATCH_DATA_REMAINS indicates that the message queue
4281 * may contain messages. #DBUS_DISPATCH_COMPLETE indicates that the
4282 * incoming queue is empty. #DBUS_DISPATCH_NEED_MEMORY indicates that
4283 * there could be data, but we can't know for sure without more
4286 * To process the incoming message queue, use dbus_connection_dispatch()
4287 * or (in rare cases) dbus_connection_pop_message().
4289 * Note, #DBUS_DISPATCH_DATA_REMAINS really means that either we
4290 * have messages in the queue, or we have raw bytes buffered up
4291 * that need to be parsed. When these bytes are parsed, they
4292 * may not add up to an entire message. Thus, it's possible
4293 * to see a status of #DBUS_DISPATCH_DATA_REMAINS but not
4294 * have a message yet.
4296 * In particular this happens on initial connection, because all sorts
4297 * of authentication protocol stuff has to be parsed before the
4298 * first message arrives.
4300 * @param connection the connection.
4301 * @returns current dispatch status
4304 dbus_connection_get_dispatch_status (DBusConnection *connection)
4306 DBusDispatchStatus status;
4308 _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
4310 _dbus_verbose ("start\n");
4312 CONNECTION_LOCK (connection);
4314 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4316 CONNECTION_UNLOCK (connection);
4322 * Filter funtion for handling the Peer standard interface.
4324 static DBusHandlerResult
4325 _dbus_connection_peer_filter_unlocked_no_update (DBusConnection *connection,
4326 DBusMessage *message)
4328 if (connection->route_peer_messages && dbus_message_get_destination (message) != NULL)
4330 /* This means we're letting the bus route this message */
4331 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4333 else if (dbus_message_is_method_call (message,
4334 DBUS_INTERFACE_PEER,
4340 ret = dbus_message_new_method_return (message);
4342 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4344 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4346 dbus_message_unref (ret);
4349 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4351 return DBUS_HANDLER_RESULT_HANDLED;
4353 else if (dbus_message_is_method_call (message,
4354 DBUS_INTERFACE_PEER,
4361 ret = dbus_message_new_method_return (message);
4363 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4366 _dbus_string_init (&uuid);
4367 if (_dbus_get_local_machine_uuid_encoded (&uuid))
4369 const char *v_STRING = _dbus_string_get_const_data (&uuid);
4370 if (dbus_message_append_args (ret,
4371 DBUS_TYPE_STRING, &v_STRING,
4374 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4377 _dbus_string_free (&uuid);
4379 dbus_message_unref (ret);
4382 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4384 return DBUS_HANDLER_RESULT_HANDLED;
4386 else if (dbus_message_has_interface (message, DBUS_INTERFACE_PEER))
4388 /* We need to bounce anything else with this interface, otherwise apps
4389 * could start extending the interface and when we added extensions
4390 * here to DBusConnection we'd break those apps.
4396 ret = dbus_message_new_error (message,
4397 DBUS_ERROR_UNKNOWN_METHOD,
4398 "Unknown method invoked on org.freedesktop.DBus.Peer interface");
4400 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4402 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4404 dbus_message_unref (ret);
4407 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4409 return DBUS_HANDLER_RESULT_HANDLED;
4413 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4418 * Processes all builtin filter functions
4420 * If the spec specifies a standard interface
4421 * they should be processed from this method
4423 static DBusHandlerResult
4424 _dbus_connection_run_builtin_filters_unlocked_no_update (DBusConnection *connection,
4425 DBusMessage *message)
4427 /* We just run one filter for now but have the option to run more
4428 if the spec calls for it in the future */
4430 return _dbus_connection_peer_filter_unlocked_no_update (connection, message);
4434 * Processes any incoming data.
4436 * If there's incoming raw data that has not yet been parsed, it is
4437 * parsed, which may or may not result in adding messages to the
4440 * The incoming data buffer is filled when the connection reads from
4441 * its underlying transport (such as a socket). Reading usually
4442 * happens in dbus_watch_handle() or dbus_connection_read_write().
4444 * If there are complete messages in the incoming queue,
4445 * dbus_connection_dispatch() removes one message from the queue and
4446 * processes it. Processing has three steps.
4448 * First, any method replies are passed to #DBusPendingCall or
4449 * dbus_connection_send_with_reply_and_block() in order to
4450 * complete the pending method call.
4452 * Second, any filters registered with dbus_connection_add_filter()
4453 * are run. If any filter returns #DBUS_HANDLER_RESULT_HANDLED
4454 * then processing stops after that filter.
4456 * Third, if the message is a method call it is forwarded to
4457 * any registered object path handlers added with
4458 * dbus_connection_register_object_path() or
4459 * dbus_connection_register_fallback().
4461 * A single call to dbus_connection_dispatch() will process at most
4462 * one message; it will not clear the entire message queue.
4464 * Be careful about calling dbus_connection_dispatch() from inside a
4465 * message handler, i.e. calling dbus_connection_dispatch()
4466 * recursively. If threads have been initialized with a recursive
4467 * mutex function, then this will not deadlock; however, it can
4468 * certainly confuse your application.
4470 * @todo some FIXME in here about handling DBUS_HANDLER_RESULT_NEED_MEMORY
4472 * @param connection the connection
4473 * @returns dispatch status, see dbus_connection_get_dispatch_status()
4476 dbus_connection_dispatch (DBusConnection *connection)
4478 DBusMessage *message;
4479 DBusList *link, *filter_list_copy, *message_link;
4480 DBusHandlerResult result;
4481 DBusPendingCall *pending;
4482 dbus_int32_t reply_serial;
4483 DBusDispatchStatus status;
4485 _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
4487 _dbus_verbose ("\n");
4489 CONNECTION_LOCK (connection);
4490 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4491 if (status != DBUS_DISPATCH_DATA_REMAINS)
4493 /* unlocks and calls out to user code */
4494 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4498 /* We need to ref the connection since the callback could potentially
4499 * drop the last ref to it
4501 _dbus_connection_ref_unlocked (connection);
4503 _dbus_connection_acquire_dispatch (connection);
4504 HAVE_LOCK_CHECK (connection);
4506 message_link = _dbus_connection_pop_message_link_unlocked (connection);
4507 if (message_link == NULL)
4509 /* another thread dispatched our stuff */
4511 _dbus_verbose ("another thread dispatched message (during acquire_dispatch above)\n");
4513 _dbus_connection_release_dispatch (connection);
4515 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4517 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4519 dbus_connection_unref (connection);
4524 message = message_link->data;
4526 _dbus_verbose (" dispatching message %p (%s %s %s '%s')\n",
4528 dbus_message_type_to_string (dbus_message_get_type (message)),
4529 dbus_message_get_interface (message) ?
4530 dbus_message_get_interface (message) :
4532 dbus_message_get_member (message) ?
4533 dbus_message_get_member (message) :
4535 dbus_message_get_signature (message));
4537 result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4539 /* Pending call handling must be first, because if you do
4540 * dbus_connection_send_with_reply_and_block() or
4541 * dbus_pending_call_block() then no handlers/filters will be run on
4542 * the reply. We want consistent semantics in the case where we
4543 * dbus_connection_dispatch() the reply.
4546 reply_serial = dbus_message_get_reply_serial (message);
4547 pending = _dbus_hash_table_lookup_int (connection->pending_replies,
4551 _dbus_verbose ("Dispatching a pending reply\n");
4552 complete_pending_call_and_unlock (connection, pending, message);
4553 pending = NULL; /* it's probably unref'd */
4555 CONNECTION_LOCK (connection);
4556 _dbus_verbose ("pending call completed in dispatch\n");
4557 result = DBUS_HANDLER_RESULT_HANDLED;
4561 result = _dbus_connection_run_builtin_filters_unlocked_no_update (connection, message);
4562 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4565 if (!_dbus_list_copy (&connection->filter_list, &filter_list_copy))
4567 _dbus_connection_release_dispatch (connection);
4568 HAVE_LOCK_CHECK (connection);
4570 _dbus_connection_failed_pop (connection, message_link);
4572 /* unlocks and calls user code */
4573 _dbus_connection_update_dispatch_status_and_unlock (connection,
4574 DBUS_DISPATCH_NEED_MEMORY);
4575 dbus_connection_unref (connection);
4577 return DBUS_DISPATCH_NEED_MEMORY;
4580 _dbus_list_foreach (&filter_list_copy,
4581 (DBusForeachFunction)_dbus_message_filter_ref,
4584 /* We're still protected from dispatch() reentrancy here
4585 * since we acquired the dispatcher
4587 CONNECTION_UNLOCK (connection);
4589 link = _dbus_list_get_first_link (&filter_list_copy);
4590 while (link != NULL)
4592 DBusMessageFilter *filter = link->data;
4593 DBusList *next = _dbus_list_get_next_link (&filter_list_copy, link);
4595 if (filter->function == NULL)
4597 _dbus_verbose (" filter was removed in a callback function\n");
4602 _dbus_verbose (" running filter on message %p\n", message);
4603 result = (* filter->function) (connection, message, filter->user_data);
4605 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4611 _dbus_list_foreach (&filter_list_copy,
4612 (DBusForeachFunction)_dbus_message_filter_unref,
4614 _dbus_list_clear (&filter_list_copy);
4616 CONNECTION_LOCK (connection);
4618 if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
4620 _dbus_verbose ("No memory\n");
4623 else if (result == DBUS_HANDLER_RESULT_HANDLED)
4625 _dbus_verbose ("filter handled message in dispatch\n");
4629 /* We're still protected from dispatch() reentrancy here
4630 * since we acquired the dispatcher
4632 _dbus_verbose (" running object path dispatch on message %p (%s %s %s '%s')\n",
4634 dbus_message_type_to_string (dbus_message_get_type (message)),
4635 dbus_message_get_interface (message) ?
4636 dbus_message_get_interface (message) :
4638 dbus_message_get_member (message) ?
4639 dbus_message_get_member (message) :
4641 dbus_message_get_signature (message));
4643 HAVE_LOCK_CHECK (connection);
4644 result = _dbus_object_tree_dispatch_and_unlock (connection->objects,
4647 CONNECTION_LOCK (connection);
4649 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4651 _dbus_verbose ("object tree handled message in dispatch\n");
4655 if (dbus_message_get_type (message) == DBUS_MESSAGE_TYPE_METHOD_CALL)
4659 DBusPreallocatedSend *preallocated;
4661 _dbus_verbose (" sending error %s\n",
4662 DBUS_ERROR_UNKNOWN_METHOD);
4664 if (!_dbus_string_init (&str))
4666 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4667 _dbus_verbose ("no memory for error string in dispatch\n");
4671 if (!_dbus_string_append_printf (&str,
4672 "Method \"%s\" with signature \"%s\" on interface \"%s\" doesn't exist\n",
4673 dbus_message_get_member (message),
4674 dbus_message_get_signature (message),
4675 dbus_message_get_interface (message)))
4677 _dbus_string_free (&str);
4678 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4679 _dbus_verbose ("no memory for error string in dispatch\n");
4683 reply = dbus_message_new_error (message,
4684 DBUS_ERROR_UNKNOWN_METHOD,
4685 _dbus_string_get_const_data (&str));
4686 _dbus_string_free (&str);
4690 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4691 _dbus_verbose ("no memory for error reply in dispatch\n");
4695 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
4697 if (preallocated == NULL)
4699 dbus_message_unref (reply);
4700 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4701 _dbus_verbose ("no memory for error send in dispatch\n");
4705 _dbus_connection_send_preallocated_unlocked_no_update (connection, preallocated,
4708 dbus_message_unref (reply);
4710 result = DBUS_HANDLER_RESULT_HANDLED;
4713 _dbus_verbose (" done dispatching %p (%s %s %s '%s') on connection %p\n", message,
4714 dbus_message_type_to_string (dbus_message_get_type (message)),
4715 dbus_message_get_interface (message) ?
4716 dbus_message_get_interface (message) :
4718 dbus_message_get_member (message) ?
4719 dbus_message_get_member (message) :
4721 dbus_message_get_signature (message),
4725 if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
4727 _dbus_verbose ("out of memory\n");
4729 /* Put message back, and we'll start over.
4730 * Yes this means handlers must be idempotent if they
4731 * don't return HANDLED; c'est la vie.
4733 _dbus_connection_putback_message_link_unlocked (connection,
4738 _dbus_verbose (" ... done dispatching\n");
4740 _dbus_list_free_link (message_link);
4741 dbus_message_unref (message); /* don't want the message to count in max message limits
4742 * in computing dispatch status below
4746 _dbus_connection_release_dispatch (connection);
4747 HAVE_LOCK_CHECK (connection);
4749 _dbus_verbose ("before final status update\n");
4750 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4752 /* unlocks and calls user code */
4753 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4755 dbus_connection_unref (connection);
4761 * Sets the watch functions for the connection. These functions are
4762 * responsible for making the application's main loop aware of file
4763 * descriptors that need to be monitored for events, using select() or
4764 * poll(). When using Qt, typically the DBusAddWatchFunction would
4765 * create a QSocketNotifier. When using GLib, the DBusAddWatchFunction
4766 * could call g_io_add_watch(), or could be used as part of a more
4767 * elaborate GSource. Note that when a watch is added, it may
4770 * The DBusWatchToggledFunction notifies the application that the
4771 * watch has been enabled or disabled. Call dbus_watch_get_enabled()
4772 * to check this. A disabled watch should have no effect, and enabled
4773 * watch should be added to the main loop. This feature is used
4774 * instead of simply adding/removing the watch because
4775 * enabling/disabling can be done without memory allocation. The
4776 * toggled function may be NULL if a main loop re-queries
4777 * dbus_watch_get_enabled() every time anyway.
4779 * The DBusWatch can be queried for the file descriptor to watch using
4780 * dbus_watch_get_unix_fd() or dbus_watch_get_socket(), and for the
4781 * events to watch for using dbus_watch_get_flags(). The flags
4782 * returned by dbus_watch_get_flags() will only contain
4783 * DBUS_WATCH_READABLE and DBUS_WATCH_WRITABLE, never
4784 * DBUS_WATCH_HANGUP or DBUS_WATCH_ERROR; all watches implicitly
4785 * include a watch for hangups, errors, and other exceptional
4788 * Once a file descriptor becomes readable or writable, or an exception
4789 * occurs, dbus_watch_handle() should be called to
4790 * notify the connection of the file descriptor's condition.
4792 * dbus_watch_handle() cannot be called during the
4793 * DBusAddWatchFunction, as the connection will not be ready to handle
4796 * It is not allowed to reference a DBusWatch after it has been passed
4797 * to remove_function.
4799 * If #FALSE is returned due to lack of memory, the failure may be due
4800 * to a #FALSE return from the new add_function. If so, the
4801 * add_function may have been called successfully one or more times,
4802 * but the remove_function will also have been called to remove any
4803 * successful adds. i.e. if #FALSE is returned the net result
4804 * should be that dbus_connection_set_watch_functions() has no effect,
4805 * but the add_function and remove_function may have been called.
4807 * @note The thread lock on DBusConnection is held while
4808 * watch functions are invoked, so inside these functions you
4809 * may not invoke any methods on DBusConnection or it will deadlock.
4810 * See the comments in the code or http://lists.freedesktop.org/archives/dbus/2007-July/tread.html#8144
4811 * if you encounter this issue and want to attempt writing a patch.
4813 * @param connection the connection.
4814 * @param add_function function to begin monitoring a new descriptor.
4815 * @param remove_function function to stop monitoring a descriptor.
4816 * @param toggled_function function to notify of enable/disable
4817 * @param data data to pass to add_function and remove_function.
4818 * @param free_data_function function to be called to free the data.
4819 * @returns #FALSE on failure (no memory)
4822 dbus_connection_set_watch_functions (DBusConnection *connection,
4823 DBusAddWatchFunction add_function,
4824 DBusRemoveWatchFunction remove_function,
4825 DBusWatchToggledFunction toggled_function,
4827 DBusFreeFunction free_data_function)
4831 _dbus_return_val_if_fail (connection != NULL, FALSE);
4833 CONNECTION_LOCK (connection);
4835 retval = _dbus_watch_list_set_functions (connection->watches,
4836 add_function, remove_function,
4838 data, free_data_function);
4840 CONNECTION_UNLOCK (connection);
4846 * Sets the timeout functions for the connection. These functions are
4847 * responsible for making the application's main loop aware of timeouts.
4848 * When using Qt, typically the DBusAddTimeoutFunction would create a
4849 * QTimer. When using GLib, the DBusAddTimeoutFunction would call
4852 * The DBusTimeoutToggledFunction notifies the application that the
4853 * timeout has been enabled or disabled. Call
4854 * dbus_timeout_get_enabled() to check this. A disabled timeout should
4855 * have no effect, and enabled timeout should be added to the main
4856 * loop. This feature is used instead of simply adding/removing the
4857 * timeout because enabling/disabling can be done without memory
4858 * allocation. With Qt, QTimer::start() and QTimer::stop() can be used
4859 * to enable and disable. The toggled function may be NULL if a main
4860 * loop re-queries dbus_timeout_get_enabled() every time anyway.
4861 * Whenever a timeout is toggled, its interval may change.
4863 * The DBusTimeout can be queried for the timer interval using
4864 * dbus_timeout_get_interval(). dbus_timeout_handle() should be called
4865 * repeatedly, each time the interval elapses, starting after it has
4866 * elapsed once. The timeout stops firing when it is removed with the
4867 * given remove_function. The timer interval may change whenever the
4868 * timeout is added, removed, or toggled.
4870 * @note The thread lock on DBusConnection is held while
4871 * timeout functions are invoked, so inside these functions you
4872 * may not invoke any methods on DBusConnection or it will deadlock.
4873 * See the comments in the code or http://lists.freedesktop.org/archives/dbus/2007-July/thread.html#8144
4874 * if you encounter this issue and want to attempt writing a patch.
4876 * @param connection the connection.
4877 * @param add_function function to add a timeout.
4878 * @param remove_function function to remove a timeout.
4879 * @param toggled_function function to notify of enable/disable
4880 * @param data data to pass to add_function and remove_function.
4881 * @param free_data_function function to be called to free the data.
4882 * @returns #FALSE on failure (no memory)
4885 dbus_connection_set_timeout_functions (DBusConnection *connection,
4886 DBusAddTimeoutFunction add_function,
4887 DBusRemoveTimeoutFunction remove_function,
4888 DBusTimeoutToggledFunction toggled_function,
4890 DBusFreeFunction free_data_function)
4894 _dbus_return_val_if_fail (connection != NULL, FALSE);
4896 CONNECTION_LOCK (connection);
4898 retval = _dbus_timeout_list_set_functions (connection->timeouts,
4899 add_function, remove_function,
4901 data, free_data_function);
4903 CONNECTION_UNLOCK (connection);
4909 * Sets the mainloop wakeup function for the connection. This function
4910 * is responsible for waking up the main loop (if its sleeping in
4911 * another thread) when some some change has happened to the
4912 * connection that the mainloop needs to reconsider (e.g. a message
4913 * has been queued for writing). When using Qt, this typically
4914 * results in a call to QEventLoop::wakeUp(). When using GLib, it
4915 * would call g_main_context_wakeup().
4917 * @param connection the connection.
4918 * @param wakeup_main_function function to wake up the mainloop
4919 * @param data data to pass wakeup_main_function
4920 * @param free_data_function function to be called to free the data.
4923 dbus_connection_set_wakeup_main_function (DBusConnection *connection,
4924 DBusWakeupMainFunction wakeup_main_function,
4926 DBusFreeFunction free_data_function)
4929 DBusFreeFunction old_free_data;
4931 _dbus_return_if_fail (connection != NULL);
4933 CONNECTION_LOCK (connection);
4934 old_data = connection->wakeup_main_data;
4935 old_free_data = connection->free_wakeup_main_data;
4937 connection->wakeup_main_function = wakeup_main_function;
4938 connection->wakeup_main_data = data;
4939 connection->free_wakeup_main_data = free_data_function;
4941 CONNECTION_UNLOCK (connection);
4943 /* Callback outside the lock */
4945 (*old_free_data) (old_data);
4949 * Set a function to be invoked when the dispatch status changes.
4950 * If the dispatch status is #DBUS_DISPATCH_DATA_REMAINS, then
4951 * dbus_connection_dispatch() needs to be called to process incoming
4952 * messages. However, dbus_connection_dispatch() MUST NOT BE CALLED
4953 * from inside the DBusDispatchStatusFunction. Indeed, almost
4954 * any reentrancy in this function is a bad idea. Instead,
4955 * the DBusDispatchStatusFunction should simply save an indication
4956 * that messages should be dispatched later, when the main loop
4959 * If you don't set a dispatch status function, you have to be sure to
4960 * dispatch on every iteration of your main loop, especially if
4961 * dbus_watch_handle() or dbus_timeout_handle() were called.
4963 * @param connection the connection
4964 * @param function function to call on dispatch status changes
4965 * @param data data for function
4966 * @param free_data_function free the function data
4969 dbus_connection_set_dispatch_status_function (DBusConnection *connection,
4970 DBusDispatchStatusFunction function,
4972 DBusFreeFunction free_data_function)
4975 DBusFreeFunction old_free_data;
4977 _dbus_return_if_fail (connection != NULL);
4979 CONNECTION_LOCK (connection);
4980 old_data = connection->dispatch_status_data;
4981 old_free_data = connection->free_dispatch_status_data;
4983 connection->dispatch_status_function = function;
4984 connection->dispatch_status_data = data;
4985 connection->free_dispatch_status_data = free_data_function;
4987 CONNECTION_UNLOCK (connection);
4989 /* Callback outside the lock */
4991 (*old_free_data) (old_data);
4995 * Get the UNIX file descriptor of the connection, if any. This can
4996 * be used for SELinux access control checks with getpeercon() for
4997 * example. DO NOT read or write to the file descriptor, or try to
4998 * select() on it; use DBusWatch for main loop integration. Not all
4999 * connections will have a file descriptor. So for adding descriptors
5000 * to the main loop, use dbus_watch_get_unix_fd() and so forth.
5002 * If the connection is socket-based, you can also use
5003 * dbus_connection_get_socket(), which will work on Windows too.
5004 * This function always fails on Windows.
5006 * Right now the returned descriptor is always a socket, but
5007 * that is not guaranteed.
5009 * @param connection the connection
5010 * @param fd return location for the file descriptor.
5011 * @returns #TRUE if fd is successfully obtained.
5014 dbus_connection_get_unix_fd (DBusConnection *connection,
5017 _dbus_return_val_if_fail (connection != NULL, FALSE);
5018 _dbus_return_val_if_fail (connection->transport != NULL, FALSE);
5021 /* FIXME do this on a lower level */
5025 return dbus_connection_get_socket(connection, fd);
5029 * Gets the underlying Windows or UNIX socket file descriptor
5030 * of the connection, if any. DO NOT read or write to the file descriptor, or try to
5031 * select() on it; use DBusWatch for main loop integration. Not all
5032 * connections will have a socket. So for adding descriptors
5033 * to the main loop, use dbus_watch_get_socket() and so forth.
5035 * If the connection is not socket-based, this function will return FALSE,
5036 * even if the connection does have a file descriptor of some kind.
5037 * i.e. this function always returns specifically a socket file descriptor.
5039 * @param connection the connection
5040 * @param fd return location for the file descriptor.
5041 * @returns #TRUE if fd is successfully obtained.
5044 dbus_connection_get_socket(DBusConnection *connection,
5049 _dbus_return_val_if_fail (connection != NULL, FALSE);
5050 _dbus_return_val_if_fail (connection->transport != NULL, FALSE);
5052 CONNECTION_LOCK (connection);
5054 retval = _dbus_transport_get_socket_fd (connection->transport,
5057 CONNECTION_UNLOCK (connection);
5064 * Gets the UNIX user ID of the connection if known. Returns #TRUE if
5065 * the uid is filled in. Always returns #FALSE on non-UNIX platforms
5066 * for now, though in theory someone could hook Windows to NIS or
5067 * something. Always returns #FALSE prior to authenticating the
5070 * The UID is only read by servers from clients; clients can't usually
5071 * get the UID of servers, because servers do not authenticate to
5072 * clients. The returned UID is the UID the connection authenticated
5075 * The message bus is a server and the apps connecting to the bus
5078 * You can ask the bus to tell you the UID of another connection though
5079 * if you like; this is done with dbus_bus_get_unix_user().
5081 * @param connection the connection
5082 * @param uid return location for the user ID
5083 * @returns #TRUE if uid is filled in with a valid user ID
5086 dbus_connection_get_unix_user (DBusConnection *connection,
5091 _dbus_return_val_if_fail (connection != NULL, FALSE);
5092 _dbus_return_val_if_fail (uid != NULL, FALSE);
5094 CONNECTION_LOCK (connection);
5096 if (!_dbus_transport_get_is_authenticated (connection->transport))
5099 result = _dbus_transport_get_unix_user (connection->transport,
5103 _dbus_assert (!result);
5106 CONNECTION_UNLOCK (connection);
5112 * Gets the process ID of the connection if any.
5113 * Returns #TRUE if the pid is filled in.
5114 * Always returns #FALSE prior to authenticating the
5117 * @param connection the connection
5118 * @param pid return location for the process ID
5119 * @returns #TRUE if uid is filled in with a valid process ID
5122 dbus_connection_get_unix_process_id (DBusConnection *connection,
5127 _dbus_return_val_if_fail (connection != NULL, FALSE);
5128 _dbus_return_val_if_fail (pid != NULL, FALSE);
5130 CONNECTION_LOCK (connection);
5132 if (!_dbus_transport_get_is_authenticated (connection->transport))
5135 result = _dbus_transport_get_unix_process_id (connection->transport,
5138 CONNECTION_UNLOCK (connection);
5144 * Gets the ADT audit data of the connection if any.
5145 * Returns #TRUE if the structure pointer is returned.
5146 * Always returns #FALSE prior to authenticating the
5149 * @param connection the connection
5150 * @param data return location for audit data
5151 * @returns #TRUE if audit data is filled in with a valid ucred pointer
5154 dbus_connection_get_adt_audit_session_data (DBusConnection *connection,
5156 dbus_int32_t *data_size)
5160 _dbus_return_val_if_fail (connection != NULL, FALSE);
5161 _dbus_return_val_if_fail (data != NULL, FALSE);
5162 _dbus_return_val_if_fail (data_size != NULL, FALSE);
5164 CONNECTION_LOCK (connection);
5166 if (!_dbus_transport_get_is_authenticated (connection->transport))
5169 result = _dbus_transport_get_adt_audit_session_data (connection->transport,
5172 CONNECTION_UNLOCK (connection);
5178 * Sets a predicate function used to determine whether a given user ID
5179 * is allowed to connect. When an incoming connection has
5180 * authenticated with a particular user ID, this function is called;
5181 * if it returns #TRUE, the connection is allowed to proceed,
5182 * otherwise the connection is disconnected.
5184 * If the function is set to #NULL (as it is by default), then
5185 * only the same UID as the server process will be allowed to
5186 * connect. Also, root is always allowed to connect.
5188 * On Windows, the function will be set and its free_data_function will
5189 * be invoked when the connection is freed or a new function is set.
5190 * However, the function will never be called, because there are
5191 * no UNIX user ids to pass to it, or at least none of the existing
5192 * auth protocols would allow authenticating as a UNIX user on Windows.
5194 * @param connection the connection
5195 * @param function the predicate
5196 * @param data data to pass to the predicate
5197 * @param free_data_function function to free the data
5200 dbus_connection_set_unix_user_function (DBusConnection *connection,
5201 DBusAllowUnixUserFunction function,
5203 DBusFreeFunction free_data_function)
5205 void *old_data = NULL;
5206 DBusFreeFunction old_free_function = NULL;
5208 _dbus_return_if_fail (connection != NULL);
5210 CONNECTION_LOCK (connection);
5211 _dbus_transport_set_unix_user_function (connection->transport,
5212 function, data, free_data_function,
5213 &old_data, &old_free_function);
5214 CONNECTION_UNLOCK (connection);
5216 if (old_free_function != NULL)
5217 (* old_free_function) (old_data);
5221 * Gets the Windows user SID of the connection if known. Returns
5222 * #TRUE if the ID is filled in. Always returns #FALSE on non-Windows
5223 * platforms for now, though in theory someone could hook UNIX to
5224 * Active Directory or something. Always returns #FALSE prior to
5225 * authenticating the connection.
5227 * The user is only read by servers from clients; clients can't usually
5228 * get the user of servers, because servers do not authenticate to
5229 * clients. The returned user is the user the connection authenticated
5232 * The message bus is a server and the apps connecting to the bus
5235 * The returned user string has to be freed with dbus_free().
5237 * The return value indicates whether the user SID is available;
5238 * if it's available but we don't have the memory to copy it,
5239 * then the return value is #TRUE and #NULL is given as the SID.
5241 * @todo We would like to be able to say "You can ask the bus to tell
5242 * you the user of another connection though if you like; this is done
5243 * with dbus_bus_get_windows_user()." But this has to be implemented
5244 * in bus/driver.c and dbus/dbus-bus.c, and is pointless anyway
5245 * since on Windows we only use the session bus for now.
5247 * @param connection the connection
5248 * @param windows_sid_p return location for an allocated copy of the user ID, or #NULL if no memory
5249 * @returns #TRUE if user is available (returned value may be #NULL anyway if no memory)
5252 dbus_connection_get_windows_user (DBusConnection *connection,
5253 char **windows_sid_p)
5257 _dbus_return_val_if_fail (connection != NULL, FALSE);
5258 _dbus_return_val_if_fail (windows_sid_p != NULL, FALSE);
5260 CONNECTION_LOCK (connection);
5262 if (!_dbus_transport_get_is_authenticated (connection->transport))
5265 result = _dbus_transport_get_windows_user (connection->transport,
5269 _dbus_assert (!result);
5272 CONNECTION_UNLOCK (connection);
5278 * Sets a predicate function used to determine whether a given user ID
5279 * is allowed to connect. When an incoming connection has
5280 * authenticated with a particular user ID, this function is called;
5281 * if it returns #TRUE, the connection is allowed to proceed,
5282 * otherwise the connection is disconnected.
5284 * If the function is set to #NULL (as it is by default), then
5285 * only the same user owning the server process will be allowed to
5288 * On UNIX, the function will be set and its free_data_function will
5289 * be invoked when the connection is freed or a new function is set.
5290 * However, the function will never be called, because there is no
5291 * way right now to authenticate as a Windows user on UNIX.
5293 * @param connection the connection
5294 * @param function the predicate
5295 * @param data data to pass to the predicate
5296 * @param free_data_function function to free the data
5299 dbus_connection_set_windows_user_function (DBusConnection *connection,
5300 DBusAllowWindowsUserFunction function,
5302 DBusFreeFunction free_data_function)
5304 void *old_data = NULL;
5305 DBusFreeFunction old_free_function = NULL;
5307 _dbus_return_if_fail (connection != NULL);
5309 CONNECTION_LOCK (connection);
5310 _dbus_transport_set_windows_user_function (connection->transport,
5311 function, data, free_data_function,
5312 &old_data, &old_free_function);
5313 CONNECTION_UNLOCK (connection);
5315 if (old_free_function != NULL)
5316 (* old_free_function) (old_data);
5320 * This function must be called on the server side of a connection when the
5321 * connection is first seen in the #DBusNewConnectionFunction. If set to
5322 * #TRUE (the default is #FALSE), then the connection can proceed even if
5323 * the client does not authenticate as some user identity, i.e. clients
5324 * can connect anonymously.
5326 * This setting interacts with the available authorization mechanisms
5327 * (see dbus_server_set_auth_mechanisms()). Namely, an auth mechanism
5328 * such as ANONYMOUS that supports anonymous auth must be included in
5329 * the list of available mechanisms for anonymous login to work.
5331 * This setting also changes the default rule for connections
5332 * authorized as a user; normally, if a connection authorizes as
5333 * a user identity, it is permitted if the user identity is
5334 * root or the user identity matches the user identity of the server
5335 * process. If anonymous connections are allowed, however,
5336 * then any user identity is allowed.
5338 * You can override the rules for connections authorized as a
5339 * user identity with dbus_connection_set_unix_user_function()
5340 * and dbus_connection_set_windows_user_function().
5342 * @param connection the connection
5343 * @param value whether to allow authentication as an anonymous user
5346 dbus_connection_set_allow_anonymous (DBusConnection *connection,
5349 _dbus_return_if_fail (connection != NULL);
5351 CONNECTION_LOCK (connection);
5352 _dbus_transport_set_allow_anonymous (connection->transport, value);
5353 CONNECTION_UNLOCK (connection);
5358 * Normally #DBusConnection automatically handles all messages to the
5359 * org.freedesktop.DBus.Peer interface. However, the message bus wants
5360 * to be able to route methods on that interface through the bus and
5361 * to other applications. If routing peer messages is enabled, then
5362 * messages with the org.freedesktop.DBus.Peer interface that also
5363 * have a bus destination name set will not be automatically
5364 * handled by the #DBusConnection and instead will be dispatched
5365 * normally to the application.
5367 * If a normal application sets this flag, it can break things badly.
5368 * So don't set this unless you are the message bus.
5370 * @param connection the connection
5371 * @param value #TRUE to pass through org.freedesktop.DBus.Peer messages with a bus name set
5374 dbus_connection_set_route_peer_messages (DBusConnection *connection,
5377 _dbus_return_if_fail (connection != NULL);
5379 CONNECTION_LOCK (connection);
5380 connection->route_peer_messages = TRUE;
5381 CONNECTION_UNLOCK (connection);
5385 * Adds a message filter. Filters are handlers that are run on all
5386 * incoming messages, prior to the objects registered with
5387 * dbus_connection_register_object_path(). Filters are run in the
5388 * order that they were added. The same handler can be added as a
5389 * filter more than once, in which case it will be run more than once.
5390 * Filters added during a filter callback won't be run on the message
5393 * @todo we don't run filters on messages while blocking without
5394 * entering the main loop, since filters are run as part of
5395 * dbus_connection_dispatch(). This is probably a feature, as filters
5396 * could create arbitrary reentrancy. But kind of sucks if you're
5397 * trying to filter METHOD_RETURN for some reason.
5399 * @param connection the connection
5400 * @param function function to handle messages
5401 * @param user_data user data to pass to the function
5402 * @param free_data_function function to use for freeing user data
5403 * @returns #TRUE on success, #FALSE if not enough memory.
5406 dbus_connection_add_filter (DBusConnection *connection,
5407 DBusHandleMessageFunction function,
5409 DBusFreeFunction free_data_function)
5411 DBusMessageFilter *filter;
5413 _dbus_return_val_if_fail (connection != NULL, FALSE);
5414 _dbus_return_val_if_fail (function != NULL, FALSE);
5416 filter = dbus_new0 (DBusMessageFilter, 1);
5420 _dbus_atomic_inc (&filter->refcount);
5422 CONNECTION_LOCK (connection);
5424 if (!_dbus_list_append (&connection->filter_list,
5427 _dbus_message_filter_unref (filter);
5428 CONNECTION_UNLOCK (connection);
5432 /* Fill in filter after all memory allocated,
5433 * so we don't run the free_user_data_function
5434 * if the add_filter() fails
5437 filter->function = function;
5438 filter->user_data = user_data;
5439 filter->free_user_data_function = free_data_function;
5441 CONNECTION_UNLOCK (connection);
5446 * Removes a previously-added message filter. It is a programming
5447 * error to call this function for a handler that has not been added
5448 * as a filter. If the given handler was added more than once, only
5449 * one instance of it will be removed (the most recently-added
5452 * @param connection the connection
5453 * @param function the handler to remove
5454 * @param user_data user data for the handler to remove
5458 dbus_connection_remove_filter (DBusConnection *connection,
5459 DBusHandleMessageFunction function,
5463 DBusMessageFilter *filter;
5465 _dbus_return_if_fail (connection != NULL);
5466 _dbus_return_if_fail (function != NULL);
5468 CONNECTION_LOCK (connection);
5472 link = _dbus_list_get_last_link (&connection->filter_list);
5473 while (link != NULL)
5475 filter = link->data;
5477 if (filter->function == function &&
5478 filter->user_data == user_data)
5480 _dbus_list_remove_link (&connection->filter_list, link);
5481 filter->function = NULL;
5486 link = _dbus_list_get_prev_link (&connection->filter_list, link);
5490 CONNECTION_UNLOCK (connection);
5492 #ifndef DBUS_DISABLE_CHECKS
5495 _dbus_warn_check_failed ("Attempt to remove filter function %p user data %p, but no such filter has been added\n",
5496 function, user_data);
5501 /* Call application code */
5502 if (filter->free_user_data_function)
5503 (* filter->free_user_data_function) (filter->user_data);
5505 filter->free_user_data_function = NULL;
5506 filter->user_data = NULL;
5508 _dbus_message_filter_unref (filter);
5512 * Registers a handler for a given path in the object hierarchy.
5513 * The given vtable handles messages sent to exactly the given path.
5515 * @param connection the connection
5516 * @param path a '/' delimited string of path elements
5517 * @param vtable the virtual table
5518 * @param user_data data to pass to functions in the vtable
5519 * @param error address where an error can be returned
5520 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5521 * #DBUS_ERROR_OBJECT_PATH_IN_USE) is reported
5524 dbus_connection_try_register_object_path (DBusConnection *connection,
5526 const DBusObjectPathVTable *vtable,
5530 char **decomposed_path;
5533 _dbus_return_val_if_fail (connection != NULL, FALSE);
5534 _dbus_return_val_if_fail (path != NULL, FALSE);
5535 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5536 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5538 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5541 CONNECTION_LOCK (connection);
5543 retval = _dbus_object_tree_register (connection->objects,
5545 (const char **) decomposed_path, vtable,
5548 CONNECTION_UNLOCK (connection);
5550 dbus_free_string_array (decomposed_path);
5556 * Registers a handler for a given path in the object hierarchy.
5557 * The given vtable handles messages sent to exactly the given path.
5559 * It is a bug to call this function for object paths which already
5560 * have a handler. Use dbus_connection_try_register_object_path() if this
5561 * might be the case.
5563 * @param connection the connection
5564 * @param path a '/' delimited string of path elements
5565 * @param vtable the virtual table
5566 * @param user_data data to pass to functions in the vtable
5567 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5568 * #DBUS_ERROR_OBJECT_PATH_IN_USE) ocurred
5571 dbus_connection_register_object_path (DBusConnection *connection,
5573 const DBusObjectPathVTable *vtable,
5576 char **decomposed_path;
5578 DBusError error = DBUS_ERROR_INIT;
5580 _dbus_return_val_if_fail (connection != NULL, FALSE);
5581 _dbus_return_val_if_fail (path != NULL, FALSE);
5582 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5583 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5585 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5588 CONNECTION_LOCK (connection);
5590 retval = _dbus_object_tree_register (connection->objects,
5592 (const char **) decomposed_path, vtable,
5595 CONNECTION_UNLOCK (connection);
5597 dbus_free_string_array (decomposed_path);
5599 if (dbus_error_has_name (&error, DBUS_ERROR_OBJECT_PATH_IN_USE))
5601 _dbus_warn ("%s\n", error.message);
5602 dbus_error_free (&error);
5610 * Registers a fallback handler for a given subsection of the object
5611 * hierarchy. The given vtable handles messages at or below the given
5612 * path. You can use this to establish a default message handling
5613 * policy for a whole "subdirectory."
5615 * @param connection the connection
5616 * @param path a '/' delimited string of path elements
5617 * @param vtable the virtual table
5618 * @param user_data data to pass to functions in the vtable
5619 * @param error address where an error can be returned
5620 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5621 * #DBUS_ERROR_OBJECT_PATH_IN_USE) is reported
5624 dbus_connection_try_register_fallback (DBusConnection *connection,
5626 const DBusObjectPathVTable *vtable,
5630 char **decomposed_path;
5633 _dbus_return_val_if_fail (connection != NULL, FALSE);
5634 _dbus_return_val_if_fail (path != NULL, FALSE);
5635 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5636 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5638 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5641 CONNECTION_LOCK (connection);
5643 retval = _dbus_object_tree_register (connection->objects,
5645 (const char **) decomposed_path, vtable,
5648 CONNECTION_UNLOCK (connection);
5650 dbus_free_string_array (decomposed_path);
5656 * Registers a fallback handler for a given subsection of the object
5657 * hierarchy. The given vtable handles messages at or below the given
5658 * path. You can use this to establish a default message handling
5659 * policy for a whole "subdirectory."
5661 * It is a bug to call this function for object paths which already
5662 * have a handler. Use dbus_connection_try_register_fallback() if this
5663 * might be the case.
5665 * @param connection the connection
5666 * @param path a '/' delimited string of path elements
5667 * @param vtable the virtual table
5668 * @param user_data data to pass to functions in the vtable
5669 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5670 * #DBUS_ERROR_OBJECT_PATH_IN_USE) occured
5673 dbus_connection_register_fallback (DBusConnection *connection,
5675 const DBusObjectPathVTable *vtable,
5678 char **decomposed_path;
5680 DBusError error = DBUS_ERROR_INIT;
5682 _dbus_return_val_if_fail (connection != NULL, FALSE);
5683 _dbus_return_val_if_fail (path != NULL, FALSE);
5684 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5685 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5687 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5690 CONNECTION_LOCK (connection);
5692 retval = _dbus_object_tree_register (connection->objects,
5694 (const char **) decomposed_path, vtable,
5697 CONNECTION_UNLOCK (connection);
5699 dbus_free_string_array (decomposed_path);
5701 if (dbus_error_has_name (&error, DBUS_ERROR_OBJECT_PATH_IN_USE))
5703 _dbus_warn ("%s\n", error.message);
5704 dbus_error_free (&error);
5712 * Unregisters the handler registered with exactly the given path.
5713 * It's a bug to call this function for a path that isn't registered.
5714 * Can unregister both fallback paths and object paths.
5716 * @param connection the connection
5717 * @param path a '/' delimited string of path elements
5718 * @returns #FALSE if not enough memory
5721 dbus_connection_unregister_object_path (DBusConnection *connection,
5724 char **decomposed_path;
5726 _dbus_return_val_if_fail (connection != NULL, FALSE);
5727 _dbus_return_val_if_fail (path != NULL, FALSE);
5728 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5730 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5733 CONNECTION_LOCK (connection);
5735 _dbus_object_tree_unregister_and_unlock (connection->objects, (const char **) decomposed_path);
5737 dbus_free_string_array (decomposed_path);
5743 * Gets the user data passed to dbus_connection_register_object_path()
5744 * or dbus_connection_register_fallback(). If nothing was registered
5745 * at this path, the data is filled in with #NULL.
5747 * @param connection the connection
5748 * @param path the path you registered with
5749 * @param data_p location to store the user data, or #NULL
5750 * @returns #FALSE if not enough memory
5753 dbus_connection_get_object_path_data (DBusConnection *connection,
5757 char **decomposed_path;
5759 _dbus_return_val_if_fail (connection != NULL, FALSE);
5760 _dbus_return_val_if_fail (path != NULL, FALSE);
5761 _dbus_return_val_if_fail (data_p != NULL, FALSE);
5765 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5768 CONNECTION_LOCK (connection);
5770 *data_p = _dbus_object_tree_get_user_data_unlocked (connection->objects, (const char**) decomposed_path);
5772 CONNECTION_UNLOCK (connection);
5774 dbus_free_string_array (decomposed_path);
5780 * Lists the registered fallback handlers and object path handlers at
5781 * the given parent_path. The returned array should be freed with
5782 * dbus_free_string_array().
5784 * @param connection the connection
5785 * @param parent_path the path to list the child handlers of
5786 * @param child_entries returns #NULL-terminated array of children
5787 * @returns #FALSE if no memory to allocate the child entries
5790 dbus_connection_list_registered (DBusConnection *connection,
5791 const char *parent_path,
5792 char ***child_entries)
5794 char **decomposed_path;
5796 _dbus_return_val_if_fail (connection != NULL, FALSE);
5797 _dbus_return_val_if_fail (parent_path != NULL, FALSE);
5798 _dbus_return_val_if_fail (parent_path[0] == '/', FALSE);
5799 _dbus_return_val_if_fail (child_entries != NULL, FALSE);
5801 if (!_dbus_decompose_path (parent_path, strlen (parent_path), &decomposed_path, NULL))
5804 CONNECTION_LOCK (connection);
5806 retval = _dbus_object_tree_list_registered_and_unlock (connection->objects,
5807 (const char **) decomposed_path,
5809 dbus_free_string_array (decomposed_path);
5814 static DBusDataSlotAllocator slot_allocator;
5815 _DBUS_DEFINE_GLOBAL_LOCK (connection_slots);
5818 * Allocates an integer ID to be used for storing application-specific
5819 * data on any DBusConnection. The allocated ID may then be used
5820 * with dbus_connection_set_data() and dbus_connection_get_data().
5821 * The passed-in slot must be initialized to -1, and is filled in
5822 * with the slot ID. If the passed-in slot is not -1, it's assumed
5823 * to be already allocated, and its refcount is incremented.
5825 * The allocated slot is global, i.e. all DBusConnection objects will
5826 * have a slot with the given integer ID reserved.
5828 * @param slot_p address of a global variable storing the slot
5829 * @returns #FALSE on failure (no memory)
5832 dbus_connection_allocate_data_slot (dbus_int32_t *slot_p)
5834 return _dbus_data_slot_allocator_alloc (&slot_allocator,
5835 &_DBUS_LOCK_NAME (connection_slots),
5840 * Deallocates a global ID for connection data slots.
5841 * dbus_connection_get_data() and dbus_connection_set_data() may no
5842 * longer be used with this slot. Existing data stored on existing
5843 * DBusConnection objects will be freed when the connection is
5844 * finalized, but may not be retrieved (and may only be replaced if
5845 * someone else reallocates the slot). When the refcount on the
5846 * passed-in slot reaches 0, it is set to -1.
5848 * @param slot_p address storing the slot to deallocate
5851 dbus_connection_free_data_slot (dbus_int32_t *slot_p)
5853 _dbus_return_if_fail (*slot_p >= 0);
5855 _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
5859 * Stores a pointer on a DBusConnection, along
5860 * with an optional function to be used for freeing
5861 * the data when the data is set again, or when
5862 * the connection is finalized. The slot number
5863 * must have been allocated with dbus_connection_allocate_data_slot().
5865 * @note This function does not take the
5866 * main thread lock on DBusConnection, which allows it to be
5867 * used from inside watch and timeout functions. (See the
5868 * note in docs for dbus_connection_set_watch_functions().)
5869 * A side effect of this is that you need to know there's
5870 * a reference held on the connection while invoking
5871 * dbus_connection_set_data(), or the connection could be
5872 * finalized during dbus_connection_set_data().
5874 * @param connection the connection
5875 * @param slot the slot number
5876 * @param data the data to store
5877 * @param free_data_func finalizer function for the data
5878 * @returns #TRUE if there was enough memory to store the data
5881 dbus_connection_set_data (DBusConnection *connection,
5884 DBusFreeFunction free_data_func)
5886 DBusFreeFunction old_free_func;
5890 _dbus_return_val_if_fail (connection != NULL, FALSE);
5891 _dbus_return_val_if_fail (slot >= 0, FALSE);
5893 SLOTS_LOCK (connection);
5895 retval = _dbus_data_slot_list_set (&slot_allocator,
5896 &connection->slot_list,
5897 slot, data, free_data_func,
5898 &old_free_func, &old_data);
5900 SLOTS_UNLOCK (connection);
5904 /* Do the actual free outside the connection lock */
5906 (* old_free_func) (old_data);
5913 * Retrieves data previously set with dbus_connection_set_data().
5914 * The slot must still be allocated (must not have been freed).
5916 * @note This function does not take the
5917 * main thread lock on DBusConnection, which allows it to be
5918 * used from inside watch and timeout functions. (See the
5919 * note in docs for dbus_connection_set_watch_functions().)
5920 * A side effect of this is that you need to know there's
5921 * a reference held on the connection while invoking
5922 * dbus_connection_get_data(), or the connection could be
5923 * finalized during dbus_connection_get_data().
5925 * @param connection the connection
5926 * @param slot the slot to get data from
5927 * @returns the data, or #NULL if not found
5930 dbus_connection_get_data (DBusConnection *connection,
5935 _dbus_return_val_if_fail (connection != NULL, NULL);
5937 SLOTS_LOCK (connection);
5939 res = _dbus_data_slot_list_get (&slot_allocator,
5940 &connection->slot_list,
5943 SLOTS_UNLOCK (connection);
5949 * This function sets a global flag for whether dbus_connection_new()
5950 * will set SIGPIPE behavior to SIG_IGN.
5952 * @param will_modify_sigpipe #TRUE to allow sigpipe to be set to SIG_IGN
5955 dbus_connection_set_change_sigpipe (dbus_bool_t will_modify_sigpipe)
5957 _dbus_modify_sigpipe = will_modify_sigpipe != FALSE;
5961 * Specifies the maximum size message this connection is allowed to
5962 * receive. Larger messages will result in disconnecting the
5965 * @param connection a #DBusConnection
5966 * @param size maximum message size the connection can receive, in bytes
5969 dbus_connection_set_max_message_size (DBusConnection *connection,
5972 _dbus_return_if_fail (connection != NULL);
5974 CONNECTION_LOCK (connection);
5975 _dbus_transport_set_max_message_size (connection->transport,
5977 CONNECTION_UNLOCK (connection);
5981 * Gets the value set by dbus_connection_set_max_message_size().
5983 * @param connection the connection
5984 * @returns the max size of a single message
5987 dbus_connection_get_max_message_size (DBusConnection *connection)
5991 _dbus_return_val_if_fail (connection != NULL, 0);
5993 CONNECTION_LOCK (connection);
5994 res = _dbus_transport_get_max_message_size (connection->transport);
5995 CONNECTION_UNLOCK (connection);
6000 * Specifies the maximum number of unix fds a message on this
6001 * connection is allowed to receive. Messages with more unix fds will
6002 * result in disconnecting the connection.
6004 * @param connection a #DBusConnection
6005 * @param size maximum message unix fds the connection can receive
6008 dbus_connection_set_max_message_unix_fds (DBusConnection *connection,
6011 _dbus_return_if_fail (connection != NULL);
6013 CONNECTION_LOCK (connection);
6014 _dbus_transport_set_max_message_unix_fds (connection->transport,
6016 CONNECTION_UNLOCK (connection);
6020 * Gets the value set by dbus_connection_set_max_message_unix_fds().
6022 * @param connection the connection
6023 * @returns the max numer of unix fds of a single message
6026 dbus_connection_get_max_message_unix_fds (DBusConnection *connection)
6030 _dbus_return_val_if_fail (connection != NULL, 0);
6032 CONNECTION_LOCK (connection);
6033 res = _dbus_transport_get_max_message_unix_fds (connection->transport);
6034 CONNECTION_UNLOCK (connection);
6039 * Sets the maximum total number of bytes that can be used for all messages
6040 * received on this connection. Messages count toward the maximum until
6041 * they are finalized. When the maximum is reached, the connection will
6042 * not read more data until some messages are finalized.
6044 * The semantics of the maximum are: if outstanding messages are
6045 * already above the maximum, additional messages will not be read.
6046 * The semantics are not: if the next message would cause us to exceed
6047 * the maximum, we don't read it. The reason is that we don't know the
6048 * size of a message until after we read it.
6050 * Thus, the max live messages size can actually be exceeded
6051 * by up to the maximum size of a single message.
6053 * Also, if we read say 1024 bytes off the wire in a single read(),
6054 * and that contains a half-dozen small messages, we may exceed the
6055 * size max by that amount. But this should be inconsequential.
6057 * This does imply that we can't call read() with a buffer larger
6058 * than we're willing to exceed this limit by.
6060 * @param connection the connection
6061 * @param size the maximum size in bytes of all outstanding messages
6064 dbus_connection_set_max_received_size (DBusConnection *connection,
6067 _dbus_return_if_fail (connection != NULL);
6069 CONNECTION_LOCK (connection);
6070 _dbus_transport_set_max_received_size (connection->transport,
6072 CONNECTION_UNLOCK (connection);
6076 * Gets the value set by dbus_connection_set_max_received_size().
6078 * @param connection the connection
6079 * @returns the max size of all live messages
6082 dbus_connection_get_max_received_size (DBusConnection *connection)
6086 _dbus_return_val_if_fail (connection != NULL, 0);
6088 CONNECTION_LOCK (connection);
6089 res = _dbus_transport_get_max_received_size (connection->transport);
6090 CONNECTION_UNLOCK (connection);
6095 * Sets the maximum total number of unix fds that can be used for all messages
6096 * received on this connection. Messages count toward the maximum until
6097 * they are finalized. When the maximum is reached, the connection will
6098 * not read more data until some messages are finalized.
6100 * The semantics are analogous to those of dbus_connection_set_max_received_size().
6102 * @param connection the connection
6103 * @param size the maximum size in bytes of all outstanding messages
6106 dbus_connection_set_max_received_unix_fds (DBusConnection *connection,
6109 _dbus_return_if_fail (connection != NULL);
6111 CONNECTION_LOCK (connection);
6112 _dbus_transport_set_max_received_unix_fds (connection->transport,
6114 CONNECTION_UNLOCK (connection);
6118 * Gets the value set by dbus_connection_set_max_received_unix_fds().
6120 * @param connection the connection
6121 * @returns the max unix fds of all live messages
6124 dbus_connection_get_max_received_unix_fds (DBusConnection *connection)
6128 _dbus_return_val_if_fail (connection != NULL, 0);
6130 CONNECTION_LOCK (connection);
6131 res = _dbus_transport_get_max_received_unix_fds (connection->transport);
6132 CONNECTION_UNLOCK (connection);
6137 * Gets the approximate size in bytes of all messages in the outgoing
6138 * message queue. The size is approximate in that you shouldn't use
6139 * it to decide how many bytes to read off the network or anything
6140 * of that nature, as optimizations may choose to tell small white lies
6141 * to avoid performance overhead.
6143 * @param connection the connection
6144 * @returns the number of bytes that have been queued up but not sent
6147 dbus_connection_get_outgoing_size (DBusConnection *connection)
6151 _dbus_return_val_if_fail (connection != NULL, 0);
6153 CONNECTION_LOCK (connection);
6154 res = _dbus_counter_get_size_value (connection->outgoing_counter);
6155 CONNECTION_UNLOCK (connection);
6160 * Gets the approximate number of uni fds of all messages in the
6161 * outgoing message queue.
6163 * @param connection the connection
6164 * @returns the number of unix fds that have been queued up but not sent
6167 dbus_connection_get_outgoing_unix_fds (DBusConnection *connection)
6171 _dbus_return_val_if_fail (connection != NULL, 0);
6173 CONNECTION_LOCK (connection);
6174 res = _dbus_counter_get_unix_fd_value (connection->outgoing_counter);
6175 CONNECTION_UNLOCK (connection);