1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-connection.c DBusConnection object
4 * Copyright (C) 2002-2006 Red Hat Inc.
6 * Licensed under the Academic Free License version 2.1
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 #include "dbus-shared.h"
26 #include "dbus-connection.h"
27 #include "dbus-list.h"
28 #include "dbus-timeout.h"
29 #include "dbus-transport.h"
30 #include "dbus-watch.h"
31 #include "dbus-connection-internal.h"
32 #include "dbus-pending-call-internal.h"
33 #include "dbus-list.h"
34 #include "dbus-hash.h"
35 #include "dbus-message-internal.h"
36 #include "dbus-message-private.h"
37 #include "dbus-threads.h"
38 #include "dbus-protocol.h"
39 #include "dbus-dataslot.h"
40 #include "dbus-string.h"
41 #include "dbus-signature.h"
42 #include "dbus-pending-call.h"
43 #include "dbus-object-tree.h"
44 #include "dbus-threads-internal.h"
46 #include "dbus-marshal-basic.h"
48 #ifdef DBUS_DISABLE_CHECKS
49 #define TOOK_LOCK_CHECK(connection)
50 #define RELEASING_LOCK_CHECK(connection)
51 #define HAVE_LOCK_CHECK(connection)
53 #define TOOK_LOCK_CHECK(connection) do { \
54 _dbus_assert (!(connection)->have_connection_lock); \
55 (connection)->have_connection_lock = TRUE; \
57 #define RELEASING_LOCK_CHECK(connection) do { \
58 _dbus_assert ((connection)->have_connection_lock); \
59 (connection)->have_connection_lock = FALSE; \
61 #define HAVE_LOCK_CHECK(connection) _dbus_assert ((connection)->have_connection_lock)
62 /* A "DO_NOT_HAVE_LOCK_CHECK" is impossible since we need the lock to check the flag */
67 #define CONNECTION_LOCK(connection) do { \
68 if (TRACE_LOCKS) { _dbus_verbose ("LOCK\n"); } \
69 _dbus_mutex_lock ((connection)->mutex); \
70 TOOK_LOCK_CHECK (connection); \
73 #define CONNECTION_UNLOCK(connection) _dbus_connection_unlock (connection)
75 #define SLOTS_LOCK(connection) do { \
76 _dbus_mutex_lock ((connection)->slot_mutex); \
79 #define SLOTS_UNLOCK(connection) do { \
80 _dbus_mutex_unlock ((connection)->slot_mutex); \
83 #define DISPATCH_STATUS_NAME(s) \
84 ((s) == DBUS_DISPATCH_COMPLETE ? "complete" : \
85 (s) == DBUS_DISPATCH_DATA_REMAINS ? "data remains" : \
86 (s) == DBUS_DISPATCH_NEED_MEMORY ? "need memory" : \
90 * @defgroup DBusConnection DBusConnection
92 * @brief Connection to another application
94 * A DBusConnection represents a connection to another
95 * application. Messages can be sent and received via this connection.
96 * The other application may be a message bus; for convenience, the
97 * function dbus_bus_get() is provided to automatically open a
98 * connection to the well-known message buses.
100 * In brief a DBusConnection is a message queue associated with some
101 * message transport mechanism such as a socket. The connection
102 * maintains a queue of incoming messages and a queue of outgoing
105 * Several functions use the following terms:
107 * <li><b>read</b> means to fill the incoming message queue by reading from the socket</li>
108 * <li><b>write</b> means to drain the outgoing queue by writing to the socket</li>
109 * <li><b>dispatch</b> means to drain the incoming queue by invoking application-provided message handlers</li>
112 * The function dbus_connection_read_write_dispatch() for example does all
113 * three of these things, offering a simple alternative to a main loop.
115 * In an application with a main loop, the read/write/dispatch
116 * operations are usually separate.
118 * The connection provides #DBusWatch and #DBusTimeout objects to
119 * the main loop. These are used to know when reading, writing, or
120 * dispatching should be performed.
122 * Incoming messages are processed
123 * by calling dbus_connection_dispatch(). dbus_connection_dispatch()
124 * runs any handlers registered for the topmost message in the message
125 * queue, then discards the message, then returns.
127 * dbus_connection_get_dispatch_status() indicates whether
128 * messages are currently in the queue that need dispatching.
129 * dbus_connection_set_dispatch_status_function() allows
130 * you to set a function to be used to monitor the dispatch status.
132 * If you're using GLib or Qt add-on libraries for D-Bus, there are
133 * special convenience APIs in those libraries that hide
134 * all the details of dispatch and watch/timeout monitoring.
135 * For example, dbus_connection_setup_with_g_main().
137 * If you aren't using these add-on libraries, but want to process
138 * messages asynchronously, you must manually call
139 * dbus_connection_set_dispatch_status_function(),
140 * dbus_connection_set_watch_functions(),
141 * dbus_connection_set_timeout_functions() providing appropriate
142 * functions to integrate the connection with your application's main
143 * loop. This can be tricky to get right; main loops are not simple.
145 * If you don't need to be asynchronous, you can ignore #DBusWatch,
146 * #DBusTimeout, and dbus_connection_dispatch(). Instead,
147 * dbus_connection_read_write_dispatch() can be used.
149 * Or, in <em>very</em> simple applications,
150 * dbus_connection_pop_message() may be all you need, allowing you to
151 * avoid setting up any handler functions (see
152 * dbus_connection_add_filter(),
153 * dbus_connection_register_object_path() for more on handlers).
155 * When you use dbus_connection_send() or one of its variants to send
156 * a message, the message is added to the outgoing queue. It's
157 * actually written to the network later; either in
158 * dbus_watch_handle() invoked by your main loop, or in
159 * dbus_connection_flush() which blocks until it can write out the
160 * entire outgoing queue. The GLib/Qt add-on libraries again
161 * handle the details here for you by setting up watch functions.
163 * When a connection is disconnected, you are guaranteed to get a
164 * signal "Disconnected" from the interface
165 * #DBUS_INTERFACE_LOCAL, path
168 * You may not drop the last reference to a #DBusConnection
169 * until that connection has been disconnected.
171 * You may dispatch the unprocessed incoming message queue even if the
172 * connection is disconnected. However, "Disconnected" will always be
173 * the last message in the queue (obviously no messages are received
174 * after disconnection).
176 * After calling dbus_threads_init(), #DBusConnection has thread
177 * locks and drops them when invoking user callbacks, so in general is
178 * transparently threadsafe. However, #DBusMessage does NOT have
179 * thread locks; you must not send the same message to multiple
180 * #DBusConnection if those connections will be used from different threads,
183 * Also, if you dispatch or pop messages from multiple threads, it
184 * may work in the sense that it won't crash, but it's tough to imagine
185 * sane results; it will be completely unpredictable which messages
186 * go to which threads.
188 * It's recommended to dispatch from a single thread.
190 * The most useful function to call from multiple threads at once
191 * is dbus_connection_send_with_reply_and_block(). That is,
192 * multiple threads can make method calls at the same time.
194 * If you aren't using threads, you can use a main loop and
195 * dbus_pending_call_set_notify() to achieve a similar result.
199 * @defgroup DBusConnectionInternals DBusConnection implementation details
200 * @ingroup DBusInternals
201 * @brief Implementation details of DBusConnection
207 * Internal struct representing a message filter function
209 typedef struct DBusMessageFilter DBusMessageFilter;
212 * Internal struct representing a message filter function
214 struct DBusMessageFilter
216 DBusAtomic refcount; /**< Reference count */
217 DBusHandleMessageFunction function; /**< Function to call to filter */
218 void *user_data; /**< User data for the function */
219 DBusFreeFunction free_user_data_function; /**< Function to free the user data */
224 * Internals of DBusPreallocatedSend
226 struct DBusPreallocatedSend
228 DBusConnection *connection; /**< Connection we'd send the message to */
229 DBusList *queue_link; /**< Preallocated link in the queue */
230 DBusList *counter_link; /**< Preallocated link in the resource counter */
233 #if HAVE_DECL_MSG_NOSIGNAL
234 static dbus_bool_t _dbus_modify_sigpipe = FALSE;
236 static dbus_bool_t _dbus_modify_sigpipe = TRUE;
240 * Implementation details of DBusConnection. All fields are private.
242 struct DBusConnection
244 DBusAtomic refcount; /**< Reference count. */
246 DBusMutex *mutex; /**< Lock on the entire DBusConnection */
248 DBusMutex *dispatch_mutex; /**< Protects dispatch_acquired */
249 DBusCondVar *dispatch_cond; /**< Notify when dispatch_acquired is available */
250 DBusMutex *io_path_mutex; /**< Protects io_path_acquired */
251 DBusCondVar *io_path_cond; /**< Notify when io_path_acquired is available */
253 DBusList *outgoing_messages; /**< Queue of messages we need to send, send the end of the list first. */
254 DBusList *incoming_messages; /**< Queue of messages we have received, end of the list received most recently. */
256 DBusMessage *message_borrowed; /**< Filled in if the first incoming message has been borrowed;
257 * dispatch_acquired will be set by the borrower
260 int n_outgoing; /**< Length of outgoing queue. */
261 int n_incoming; /**< Length of incoming queue. */
263 DBusCounter *outgoing_counter; /**< Counts size of outgoing messages. */
265 DBusTransport *transport; /**< Object that sends/receives messages over network. */
266 DBusWatchList *watches; /**< Stores active watches. */
267 DBusTimeoutList *timeouts; /**< Stores active timeouts. */
269 DBusList *filter_list; /**< List of filters. */
271 DBusMutex *slot_mutex; /**< Lock on slot_list so overall connection lock need not be taken */
272 DBusDataSlotList slot_list; /**< Data stored by allocated integer ID */
274 DBusHashTable *pending_replies; /**< Hash of message serials to #DBusPendingCall. */
276 dbus_uint32_t client_serial; /**< Client serial. Increments each time a message is sent */
277 DBusList *disconnect_message_link; /**< Preallocated list node for queueing the disconnection message */
279 DBusWakeupMainFunction wakeup_main_function; /**< Function to wake up the mainloop */
280 void *wakeup_main_data; /**< Application data for wakeup_main_function */
281 DBusFreeFunction free_wakeup_main_data; /**< free wakeup_main_data */
283 DBusDispatchStatusFunction dispatch_status_function; /**< Function on dispatch status changes */
284 void *dispatch_status_data; /**< Application data for dispatch_status_function */
285 DBusFreeFunction free_dispatch_status_data; /**< free dispatch_status_data */
287 DBusDispatchStatus last_dispatch_status; /**< The last dispatch status we reported to the application. */
289 DBusList *link_cache; /**< A cache of linked list links to prevent contention
290 * for the global linked list mempool lock
292 DBusObjectTree *objects; /**< Object path handlers registered with this connection */
294 char *server_guid; /**< GUID of server if we are in shared_connections, #NULL if server GUID is unknown or connection is private */
296 /* These two MUST be bools and not bitfields, because they are protected by a separate lock
297 * from connection->mutex and all bitfields in a word have to be read/written together.
298 * So you can't have a different lock for different bitfields in the same word.
300 dbus_bool_t dispatch_acquired; /**< Someone has dispatch path (can drain incoming queue) */
301 dbus_bool_t io_path_acquired; /**< Someone has transport io path (can use the transport to read/write messages) */
303 unsigned int shareable : 1; /**< #TRUE if libdbus owns a reference to the connection and can return it from dbus_connection_open() more than once */
305 unsigned int exit_on_disconnect : 1; /**< If #TRUE, exit after handling disconnect signal */
307 unsigned int route_peer_messages : 1; /**< If #TRUE, if org.freedesktop.DBus.Peer messages have a bus name, don't handle them automatically */
309 unsigned int disconnected_message_arrived : 1; /**< We popped or are dispatching the disconnected message.
310 * if the disconnect_message_link is NULL then we queued it, but
311 * this flag is whether it got to the head of the queue.
313 unsigned int disconnected_message_processed : 1; /**< We did our default handling of the disconnected message,
314 * such as closing the connection.
317 #ifndef DBUS_DISABLE_CHECKS
318 unsigned int have_connection_lock : 1; /**< Used to check locking */
321 #ifndef DBUS_DISABLE_CHECKS
322 int generation; /**< _dbus_current_generation that should correspond to this connection */
326 static DBusDispatchStatus _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection);
327 static void _dbus_connection_update_dispatch_status_and_unlock (DBusConnection *connection,
328 DBusDispatchStatus new_status);
329 static void _dbus_connection_last_unref (DBusConnection *connection);
330 static void _dbus_connection_acquire_dispatch (DBusConnection *connection);
331 static void _dbus_connection_release_dispatch (DBusConnection *connection);
332 static DBusDispatchStatus _dbus_connection_flush_unlocked (DBusConnection *connection);
333 static void _dbus_connection_close_possibly_shared_and_unlock (DBusConnection *connection);
334 static dbus_bool_t _dbus_connection_get_is_connected_unlocked (DBusConnection *connection);
335 static dbus_bool_t _dbus_connection_peek_for_reply_unlocked (DBusConnection *connection,
336 dbus_uint32_t client_serial);
338 static DBusMessageFilter *
339 _dbus_message_filter_ref (DBusMessageFilter *filter)
341 #ifdef DBUS_DISABLE_ASSERT
342 _dbus_atomic_inc (&filter->refcount);
344 dbus_int32_t old_value;
346 old_value = _dbus_atomic_inc (&filter->refcount);
347 _dbus_assert (old_value > 0);
354 _dbus_message_filter_unref (DBusMessageFilter *filter)
356 dbus_int32_t old_value;
358 old_value = _dbus_atomic_dec (&filter->refcount);
359 _dbus_assert (old_value > 0);
363 if (filter->free_user_data_function)
364 (* filter->free_user_data_function) (filter->user_data);
371 * Acquires the connection lock.
373 * @param connection the connection.
376 _dbus_connection_lock (DBusConnection *connection)
378 CONNECTION_LOCK (connection);
382 * Releases the connection lock.
384 * @param connection the connection.
387 _dbus_connection_unlock (DBusConnection *connection)
391 _dbus_verbose ("UNLOCK\n");
394 RELEASING_LOCK_CHECK (connection);
395 _dbus_mutex_unlock (connection->mutex);
399 * Wakes up the main loop if it is sleeping
400 * Needed if we're e.g. queueing outgoing messages
401 * on a thread while the mainloop sleeps.
403 * @param connection the connection.
406 _dbus_connection_wakeup_mainloop (DBusConnection *connection)
408 if (connection->wakeup_main_function)
409 (*connection->wakeup_main_function) (connection->wakeup_main_data);
412 #ifdef DBUS_BUILD_TESTS
413 /* For now this function isn't used */
415 * Adds a message to the incoming message queue, returning #FALSE
416 * if there's insufficient memory to queue the message.
417 * Does not take over refcount of the message.
419 * @param connection the connection.
420 * @param message the message to queue.
421 * @returns #TRUE on success.
424 _dbus_connection_queue_received_message (DBusConnection *connection,
425 DBusMessage *message)
429 link = _dbus_list_alloc_link (message);
433 dbus_message_ref (message);
434 _dbus_connection_queue_received_message_link (connection, link);
440 * Gets the locks so we can examine them
442 * @param connection the connection.
443 * @param mutex_loc return for the location of the main mutex pointer
444 * @param dispatch_mutex_loc return location of the dispatch mutex pointer
445 * @param io_path_mutex_loc return location of the io_path mutex pointer
446 * @param dispatch_cond_loc return location of the dispatch conditional
448 * @param io_path_cond_loc return location of the io_path conditional
452 _dbus_connection_test_get_locks (DBusConnection *connection,
453 DBusMutex **mutex_loc,
454 DBusMutex **dispatch_mutex_loc,
455 DBusMutex **io_path_mutex_loc,
456 DBusCondVar **dispatch_cond_loc,
457 DBusCondVar **io_path_cond_loc)
459 *mutex_loc = connection->mutex;
460 *dispatch_mutex_loc = connection->dispatch_mutex;
461 *io_path_mutex_loc = connection->io_path_mutex;
462 *dispatch_cond_loc = connection->dispatch_cond;
463 *io_path_cond_loc = connection->io_path_cond;
468 * Adds a message-containing list link to the incoming message queue,
469 * taking ownership of the link and the message's current refcount.
470 * Cannot fail due to lack of memory.
472 * @param connection the connection.
473 * @param link the message link to queue.
476 _dbus_connection_queue_received_message_link (DBusConnection *connection,
479 DBusPendingCall *pending;
480 dbus_uint32_t reply_serial;
481 DBusMessage *message;
483 _dbus_assert (_dbus_transport_get_is_authenticated (connection->transport));
485 _dbus_list_append_link (&connection->incoming_messages,
487 message = link->data;
489 /* If this is a reply we're waiting on, remove timeout for it */
490 reply_serial = dbus_message_get_reply_serial (message);
491 if (reply_serial != 0)
493 pending = _dbus_hash_table_lookup_int (connection->pending_replies,
497 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
498 _dbus_connection_remove_timeout_unlocked (connection,
499 _dbus_pending_call_get_timeout_unlocked (pending));
501 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
507 connection->n_incoming += 1;
509 _dbus_connection_wakeup_mainloop (connection);
511 _dbus_verbose ("Message %p (%s %s %s %s '%s' reply to %u) added to incoming queue %p, %d incoming\n",
513 dbus_message_type_to_string (dbus_message_get_type (message)),
514 dbus_message_get_path (message) ?
515 dbus_message_get_path (message) :
517 dbus_message_get_interface (message) ?
518 dbus_message_get_interface (message) :
520 dbus_message_get_member (message) ?
521 dbus_message_get_member (message) :
523 dbus_message_get_signature (message),
524 dbus_message_get_reply_serial (message),
526 connection->n_incoming);}
529 * Adds a link + message to the incoming message queue.
530 * Can't fail. Takes ownership of both link and message.
532 * @param connection the connection.
533 * @param link the list node and message to queue.
537 _dbus_connection_queue_synthesized_message_link (DBusConnection *connection,
540 HAVE_LOCK_CHECK (connection);
542 _dbus_list_append_link (&connection->incoming_messages, link);
544 connection->n_incoming += 1;
546 _dbus_connection_wakeup_mainloop (connection);
548 _dbus_verbose ("Synthesized message %p added to incoming queue %p, %d incoming\n",
549 link->data, connection, connection->n_incoming);
554 * Checks whether there are messages in the outgoing message queue.
555 * Called with connection lock held.
557 * @param connection the connection.
558 * @returns #TRUE if the outgoing queue is non-empty.
561 _dbus_connection_has_messages_to_send_unlocked (DBusConnection *connection)
563 HAVE_LOCK_CHECK (connection);
564 return connection->outgoing_messages != NULL;
568 * Checks whether there are messages in the outgoing message queue.
569 * Use dbus_connection_flush() to block until all outgoing
570 * messages have been written to the underlying transport
571 * (such as a socket).
573 * @param connection the connection.
574 * @returns #TRUE if the outgoing queue is non-empty.
577 dbus_connection_has_messages_to_send (DBusConnection *connection)
581 _dbus_return_val_if_fail (connection != NULL, FALSE);
583 CONNECTION_LOCK (connection);
584 v = _dbus_connection_has_messages_to_send_unlocked (connection);
585 CONNECTION_UNLOCK (connection);
591 * Gets the next outgoing message. The message remains in the
592 * queue, and the caller does not own a reference to it.
594 * @param connection the connection.
595 * @returns the message to be sent.
598 _dbus_connection_get_message_to_send (DBusConnection *connection)
600 HAVE_LOCK_CHECK (connection);
602 return _dbus_list_get_last (&connection->outgoing_messages);
606 * Notifies the connection that a message has been sent, so the
607 * message can be removed from the outgoing queue.
608 * Called with the connection lock held.
610 * @param connection the connection.
611 * @param message the message that was sent.
614 _dbus_connection_message_sent_unlocked (DBusConnection *connection,
615 DBusMessage *message)
619 HAVE_LOCK_CHECK (connection);
621 /* This can be called before we even complete authentication, since
622 * it's called on disconnect to clean up the outgoing queue.
623 * It's also called as we successfully send each message.
626 link = _dbus_list_get_last_link (&connection->outgoing_messages);
627 _dbus_assert (link != NULL);
628 _dbus_assert (link->data == message);
630 /* Save this link in the link cache */
631 _dbus_list_unlink (&connection->outgoing_messages,
633 _dbus_list_prepend_link (&connection->link_cache, link);
635 connection->n_outgoing -= 1;
637 _dbus_verbose ("Message %p (%s %s %s %s '%s') removed from outgoing queue %p, %d left to send\n",
639 dbus_message_type_to_string (dbus_message_get_type (message)),
640 dbus_message_get_path (message) ?
641 dbus_message_get_path (message) :
643 dbus_message_get_interface (message) ?
644 dbus_message_get_interface (message) :
646 dbus_message_get_member (message) ?
647 dbus_message_get_member (message) :
649 dbus_message_get_signature (message),
650 connection, connection->n_outgoing);
652 /* It's OK that in principle we call the notify function, because for the
653 * outgoing limit, there isn't one */
654 _dbus_message_remove_counter (message, connection->outgoing_counter,
657 /* Save this link in the link cache also */
658 _dbus_list_prepend_link (&connection->link_cache, link);
660 dbus_message_unref (message);
663 /** Function to be called in protected_change_watch() with refcount held */
664 typedef dbus_bool_t (* DBusWatchAddFunction) (DBusWatchList *list,
666 /** Function to be called in protected_change_watch() with refcount held */
667 typedef void (* DBusWatchRemoveFunction) (DBusWatchList *list,
669 /** Function to be called in protected_change_watch() with refcount held */
670 typedef void (* DBusWatchToggleFunction) (DBusWatchList *list,
672 dbus_bool_t enabled);
675 protected_change_watch (DBusConnection *connection,
677 DBusWatchAddFunction add_function,
678 DBusWatchRemoveFunction remove_function,
679 DBusWatchToggleFunction toggle_function,
684 HAVE_LOCK_CHECK (connection);
686 /* The original purpose of protected_change_watch() was to hold a
687 * ref on the connection while dropping the connection lock, then
688 * calling out to the app. This was a broken hack that did not
689 * work, since the connection was in a hosed state (no WatchList
690 * field) while calling out.
692 * So for now we'll just keep the lock while calling out. This means
693 * apps are not allowed to call DBusConnection methods inside a
694 * watch function or they will deadlock.
696 * The "real fix" is to use the _and_unlock() pattern found
697 * elsewhere in the code, to defer calling out to the app until
698 * we're about to drop locks and return flow of control to the app
701 * See http://lists.freedesktop.org/archives/dbus/2007-July/thread.html#8144
704 if (connection->watches)
707 retval = (* add_function) (connection->watches, watch);
708 else if (remove_function)
711 (* remove_function) (connection->watches, watch);
716 (* toggle_function) (connection->watches, watch, enabled);
726 * Adds a watch using the connection's DBusAddWatchFunction if
727 * available. Otherwise records the watch to be added when said
728 * function is available. Also re-adds the watch if the
729 * DBusAddWatchFunction changes. May fail due to lack of memory.
730 * Connection lock should be held when calling this.
732 * @param connection the connection.
733 * @param watch the watch to add.
734 * @returns #TRUE on success.
737 _dbus_connection_add_watch_unlocked (DBusConnection *connection,
740 return protected_change_watch (connection, watch,
741 _dbus_watch_list_add_watch,
746 * Removes a watch using the connection's DBusRemoveWatchFunction
747 * if available. It's an error to call this function on a watch
748 * that was not previously added.
749 * Connection lock should be held when calling this.
751 * @param connection the connection.
752 * @param watch the watch to remove.
755 _dbus_connection_remove_watch_unlocked (DBusConnection *connection,
758 protected_change_watch (connection, watch,
760 _dbus_watch_list_remove_watch,
765 * Toggles a watch and notifies app via connection's
766 * DBusWatchToggledFunction if available. It's an error to call this
767 * function on a watch that was not previously added.
768 * Connection lock should be held when calling this.
770 * @param connection the connection.
771 * @param watch the watch to toggle.
772 * @param enabled whether to enable or disable
775 _dbus_connection_toggle_watch_unlocked (DBusConnection *connection,
779 _dbus_assert (watch != NULL);
781 protected_change_watch (connection, watch,
783 _dbus_watch_list_toggle_watch,
787 /** Function to be called in protected_change_timeout() with refcount held */
788 typedef dbus_bool_t (* DBusTimeoutAddFunction) (DBusTimeoutList *list,
789 DBusTimeout *timeout);
790 /** Function to be called in protected_change_timeout() with refcount held */
791 typedef void (* DBusTimeoutRemoveFunction) (DBusTimeoutList *list,
792 DBusTimeout *timeout);
793 /** Function to be called in protected_change_timeout() with refcount held */
794 typedef void (* DBusTimeoutToggleFunction) (DBusTimeoutList *list,
795 DBusTimeout *timeout,
796 dbus_bool_t enabled);
799 protected_change_timeout (DBusConnection *connection,
800 DBusTimeout *timeout,
801 DBusTimeoutAddFunction add_function,
802 DBusTimeoutRemoveFunction remove_function,
803 DBusTimeoutToggleFunction toggle_function,
808 HAVE_LOCK_CHECK (connection);
810 /* The original purpose of protected_change_timeout() was to hold a
811 * ref on the connection while dropping the connection lock, then
812 * calling out to the app. This was a broken hack that did not
813 * work, since the connection was in a hosed state (no TimeoutList
814 * field) while calling out.
816 * So for now we'll just keep the lock while calling out. This means
817 * apps are not allowed to call DBusConnection methods inside a
818 * timeout function or they will deadlock.
820 * The "real fix" is to use the _and_unlock() pattern found
821 * elsewhere in the code, to defer calling out to the app until
822 * we're about to drop locks and return flow of control to the app
825 * See http://lists.freedesktop.org/archives/dbus/2007-July/thread.html#8144
828 if (connection->timeouts)
831 retval = (* add_function) (connection->timeouts, timeout);
832 else if (remove_function)
835 (* remove_function) (connection->timeouts, timeout);
840 (* toggle_function) (connection->timeouts, timeout, enabled);
849 * Adds a timeout using the connection's DBusAddTimeoutFunction if
850 * available. Otherwise records the timeout to be added when said
851 * function is available. Also re-adds the timeout if the
852 * DBusAddTimeoutFunction changes. May fail due to lack of memory.
853 * The timeout will fire repeatedly until removed.
854 * Connection lock should be held when calling this.
856 * @param connection the connection.
857 * @param timeout the timeout to add.
858 * @returns #TRUE on success.
861 _dbus_connection_add_timeout_unlocked (DBusConnection *connection,
862 DBusTimeout *timeout)
864 return protected_change_timeout (connection, timeout,
865 _dbus_timeout_list_add_timeout,
870 * Removes a timeout using the connection's DBusRemoveTimeoutFunction
871 * if available. It's an error to call this function on a timeout
872 * that was not previously added.
873 * Connection lock should be held when calling this.
875 * @param connection the connection.
876 * @param timeout the timeout to remove.
879 _dbus_connection_remove_timeout_unlocked (DBusConnection *connection,
880 DBusTimeout *timeout)
882 protected_change_timeout (connection, timeout,
884 _dbus_timeout_list_remove_timeout,
889 * Toggles a timeout and notifies app via connection's
890 * DBusTimeoutToggledFunction if available. It's an error to call this
891 * function on a timeout that was not previously added.
892 * Connection lock should be held when calling this.
894 * @param connection the connection.
895 * @param timeout the timeout to toggle.
896 * @param enabled whether to enable or disable
899 _dbus_connection_toggle_timeout_unlocked (DBusConnection *connection,
900 DBusTimeout *timeout,
903 protected_change_timeout (connection, timeout,
905 _dbus_timeout_list_toggle_timeout,
910 _dbus_connection_attach_pending_call_unlocked (DBusConnection *connection,
911 DBusPendingCall *pending)
913 dbus_uint32_t reply_serial;
914 DBusTimeout *timeout;
916 HAVE_LOCK_CHECK (connection);
918 reply_serial = _dbus_pending_call_get_reply_serial_unlocked (pending);
920 _dbus_assert (reply_serial != 0);
922 timeout = _dbus_pending_call_get_timeout_unlocked (pending);
926 if (!_dbus_connection_add_timeout_unlocked (connection, timeout))
929 if (!_dbus_hash_table_insert_int (connection->pending_replies,
933 _dbus_connection_remove_timeout_unlocked (connection, timeout);
935 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
936 HAVE_LOCK_CHECK (connection);
940 _dbus_pending_call_set_timeout_added_unlocked (pending, TRUE);
944 if (!_dbus_hash_table_insert_int (connection->pending_replies,
948 HAVE_LOCK_CHECK (connection);
953 _dbus_pending_call_ref_unlocked (pending);
955 HAVE_LOCK_CHECK (connection);
961 free_pending_call_on_hash_removal (void *data)
963 DBusPendingCall *pending;
964 DBusConnection *connection;
971 connection = _dbus_pending_call_get_connection_unlocked (pending);
973 HAVE_LOCK_CHECK (connection);
975 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
977 _dbus_connection_remove_timeout_unlocked (connection,
978 _dbus_pending_call_get_timeout_unlocked (pending));
980 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
983 /* FIXME 1.0? this is sort of dangerous and undesirable to drop the lock
984 * here, but the pending call finalizer could in principle call out to
985 * application code so we pretty much have to... some larger code reorg
988 _dbus_connection_ref_unlocked (connection);
989 _dbus_pending_call_unref_and_unlock (pending);
990 CONNECTION_LOCK (connection);
991 _dbus_connection_unref_unlocked (connection);
995 _dbus_connection_detach_pending_call_unlocked (DBusConnection *connection,
996 DBusPendingCall *pending)
998 /* This ends up unlocking to call the pending call finalizer, which is unexpected to
1001 _dbus_hash_table_remove_int (connection->pending_replies,
1002 _dbus_pending_call_get_reply_serial_unlocked (pending));
1006 _dbus_connection_detach_pending_call_and_unlock (DBusConnection *connection,
1007 DBusPendingCall *pending)
1009 /* The idea here is to avoid finalizing the pending call
1010 * with the lock held, since there's a destroy notifier
1011 * in pending call that goes out to application code.
1013 * There's an extra unlock inside the hash table
1014 * "free pending call" function FIXME...
1016 _dbus_pending_call_ref_unlocked (pending);
1017 _dbus_hash_table_remove_int (connection->pending_replies,
1018 _dbus_pending_call_get_reply_serial_unlocked (pending));
1020 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
1021 _dbus_connection_remove_timeout_unlocked (connection,
1022 _dbus_pending_call_get_timeout_unlocked (pending));
1024 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
1026 _dbus_pending_call_unref_and_unlock (pending);
1030 * Removes a pending call from the connection, such that
1031 * the pending reply will be ignored. May drop the last
1032 * reference to the pending call.
1034 * @param connection the connection
1035 * @param pending the pending call
1038 _dbus_connection_remove_pending_call (DBusConnection *connection,
1039 DBusPendingCall *pending)
1041 CONNECTION_LOCK (connection);
1042 _dbus_connection_detach_pending_call_and_unlock (connection, pending);
1046 * Acquire the transporter I/O path. This must be done before
1047 * doing any I/O in the transporter. May sleep and drop the
1048 * IO path mutex while waiting for the I/O path.
1050 * @param connection the connection.
1051 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
1052 * @returns TRUE if the I/O path was acquired.
1055 _dbus_connection_acquire_io_path (DBusConnection *connection,
1056 int timeout_milliseconds)
1058 dbus_bool_t we_acquired;
1060 HAVE_LOCK_CHECK (connection);
1062 /* We don't want the connection to vanish */
1063 _dbus_connection_ref_unlocked (connection);
1065 /* We will only touch io_path_acquired which is protected by our mutex */
1066 CONNECTION_UNLOCK (connection);
1068 _dbus_verbose ("locking io_path_mutex\n");
1069 _dbus_mutex_lock (connection->io_path_mutex);
1071 _dbus_verbose ("start connection->io_path_acquired = %d timeout = %d\n",
1072 connection->io_path_acquired, timeout_milliseconds);
1074 we_acquired = FALSE;
1076 if (connection->io_path_acquired)
1078 if (timeout_milliseconds != -1)
1080 _dbus_verbose ("waiting %d for IO path to be acquirable\n",
1081 timeout_milliseconds);
1083 if (!_dbus_condvar_wait_timeout (connection->io_path_cond,
1084 connection->io_path_mutex,
1085 timeout_milliseconds))
1087 /* We timed out before anyone signaled. */
1088 /* (writing the loop to handle the !timedout case by
1089 * waiting longer if needed is a pain since dbus
1090 * wraps pthread_cond_timedwait to take a relative
1091 * time instead of absolute, something kind of stupid
1092 * on our part. for now it doesn't matter, we will just
1093 * end up back here eventually.)
1099 while (connection->io_path_acquired)
1101 _dbus_verbose ("waiting for IO path to be acquirable\n");
1102 _dbus_condvar_wait (connection->io_path_cond,
1103 connection->io_path_mutex);
1108 if (!connection->io_path_acquired)
1111 connection->io_path_acquired = TRUE;
1114 _dbus_verbose ("end connection->io_path_acquired = %d we_acquired = %d\n",
1115 connection->io_path_acquired, we_acquired);
1117 _dbus_verbose ("unlocking io_path_mutex\n");
1118 _dbus_mutex_unlock (connection->io_path_mutex);
1120 CONNECTION_LOCK (connection);
1122 HAVE_LOCK_CHECK (connection);
1124 _dbus_connection_unref_unlocked (connection);
1130 * Release the I/O path when you're done with it. Only call
1131 * after you've acquired the I/O. Wakes up at most one thread
1132 * currently waiting to acquire the I/O path.
1134 * @param connection the connection.
1137 _dbus_connection_release_io_path (DBusConnection *connection)
1139 HAVE_LOCK_CHECK (connection);
1141 _dbus_verbose ("locking io_path_mutex\n");
1142 _dbus_mutex_lock (connection->io_path_mutex);
1144 _dbus_assert (connection->io_path_acquired);
1146 _dbus_verbose ("start connection->io_path_acquired = %d\n",
1147 connection->io_path_acquired);
1149 connection->io_path_acquired = FALSE;
1150 _dbus_condvar_wake_one (connection->io_path_cond);
1152 _dbus_verbose ("unlocking io_path_mutex\n");
1153 _dbus_mutex_unlock (connection->io_path_mutex);
1157 * Queues incoming messages and sends outgoing messages for this
1158 * connection, optionally blocking in the process. Each call to
1159 * _dbus_connection_do_iteration_unlocked() will call select() or poll() one
1160 * time and then read or write data if possible.
1162 * The purpose of this function is to be able to flush outgoing
1163 * messages or queue up incoming messages without returning
1164 * control to the application and causing reentrancy weirdness.
1166 * The flags parameter allows you to specify whether to
1167 * read incoming messages, write outgoing messages, or both,
1168 * and whether to block if no immediate action is possible.
1170 * The timeout_milliseconds parameter does nothing unless the
1171 * iteration is blocking.
1173 * If there are no outgoing messages and DBUS_ITERATION_DO_READING
1174 * wasn't specified, then it's impossible to block, even if
1175 * you specify DBUS_ITERATION_BLOCK; in that case the function
1176 * returns immediately.
1178 * If pending is not NULL then a check is made if the pending call
1179 * is completed after the io path has been required. If the call
1180 * has been completed nothing is done. This must be done since
1181 * the _dbus_connection_acquire_io_path releases the connection
1184 * Called with connection lock held.
1186 * @param connection the connection.
1187 * @param pending the pending call that should be checked or NULL
1188 * @param flags iteration flags.
1189 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
1192 _dbus_connection_do_iteration_unlocked (DBusConnection *connection,
1193 DBusPendingCall *pending,
1195 int timeout_milliseconds)
1197 _dbus_verbose ("start\n");
1199 HAVE_LOCK_CHECK (connection);
1201 if (connection->n_outgoing == 0)
1202 flags &= ~DBUS_ITERATION_DO_WRITING;
1204 if (_dbus_connection_acquire_io_path (connection,
1205 (flags & DBUS_ITERATION_BLOCK) ? timeout_milliseconds : 0))
1207 HAVE_LOCK_CHECK (connection);
1209 if ( (pending != NULL) && _dbus_pending_call_get_completed_unlocked(pending))
1211 _dbus_verbose ("pending call completed while acquiring I/O path");
1213 else if ( (pending != NULL) &&
1214 _dbus_connection_peek_for_reply_unlocked (connection,
1215 _dbus_pending_call_get_reply_serial_unlocked (pending)))
1217 _dbus_verbose ("pending call completed while acquiring I/O path (reply found in queue)");
1221 _dbus_transport_do_iteration (connection->transport,
1222 flags, timeout_milliseconds);
1225 _dbus_connection_release_io_path (connection);
1228 HAVE_LOCK_CHECK (connection);
1230 _dbus_verbose ("end\n");
1234 * Creates a new connection for the given transport. A transport
1235 * represents a message stream that uses some concrete mechanism, such
1236 * as UNIX domain sockets. May return #NULL if insufficient
1237 * memory exists to create the connection.
1239 * @param transport the transport.
1240 * @returns the new connection, or #NULL on failure.
1243 _dbus_connection_new_for_transport (DBusTransport *transport)
1245 DBusConnection *connection;
1246 DBusWatchList *watch_list;
1247 DBusTimeoutList *timeout_list;
1248 DBusHashTable *pending_replies;
1249 DBusList *disconnect_link;
1250 DBusMessage *disconnect_message;
1251 DBusCounter *outgoing_counter;
1252 DBusObjectTree *objects;
1256 pending_replies = NULL;
1257 timeout_list = NULL;
1258 disconnect_link = NULL;
1259 disconnect_message = NULL;
1260 outgoing_counter = NULL;
1263 watch_list = _dbus_watch_list_new ();
1264 if (watch_list == NULL)
1267 timeout_list = _dbus_timeout_list_new ();
1268 if (timeout_list == NULL)
1272 _dbus_hash_table_new (DBUS_HASH_INT,
1274 (DBusFreeFunction)free_pending_call_on_hash_removal);
1275 if (pending_replies == NULL)
1278 connection = dbus_new0 (DBusConnection, 1);
1279 if (connection == NULL)
1282 _dbus_mutex_new_at_location (&connection->mutex);
1283 if (connection->mutex == NULL)
1286 _dbus_mutex_new_at_location (&connection->io_path_mutex);
1287 if (connection->io_path_mutex == NULL)
1290 _dbus_mutex_new_at_location (&connection->dispatch_mutex);
1291 if (connection->dispatch_mutex == NULL)
1294 _dbus_condvar_new_at_location (&connection->dispatch_cond);
1295 if (connection->dispatch_cond == NULL)
1298 _dbus_condvar_new_at_location (&connection->io_path_cond);
1299 if (connection->io_path_cond == NULL)
1302 _dbus_mutex_new_at_location (&connection->slot_mutex);
1303 if (connection->slot_mutex == NULL)
1306 disconnect_message = dbus_message_new_signal (DBUS_PATH_LOCAL,
1307 DBUS_INTERFACE_LOCAL,
1310 if (disconnect_message == NULL)
1313 disconnect_link = _dbus_list_alloc_link (disconnect_message);
1314 if (disconnect_link == NULL)
1317 outgoing_counter = _dbus_counter_new ();
1318 if (outgoing_counter == NULL)
1321 objects = _dbus_object_tree_new (connection);
1322 if (objects == NULL)
1325 if (_dbus_modify_sigpipe)
1326 _dbus_disable_sigpipe ();
1328 /* initialized to 0: use atomic op to avoid mixing atomic and non-atomic */
1329 _dbus_atomic_inc (&connection->refcount);
1330 connection->transport = transport;
1331 connection->watches = watch_list;
1332 connection->timeouts = timeout_list;
1333 connection->pending_replies = pending_replies;
1334 connection->outgoing_counter = outgoing_counter;
1335 connection->filter_list = NULL;
1336 connection->last_dispatch_status = DBUS_DISPATCH_COMPLETE; /* so we're notified first time there's data */
1337 connection->objects = objects;
1338 connection->exit_on_disconnect = FALSE;
1339 connection->shareable = FALSE;
1340 connection->route_peer_messages = FALSE;
1341 connection->disconnected_message_arrived = FALSE;
1342 connection->disconnected_message_processed = FALSE;
1344 #ifndef DBUS_DISABLE_CHECKS
1345 connection->generation = _dbus_current_generation;
1348 _dbus_data_slot_list_init (&connection->slot_list);
1350 connection->client_serial = 1;
1352 connection->disconnect_message_link = disconnect_link;
1354 CONNECTION_LOCK (connection);
1356 if (!_dbus_transport_set_connection (transport, connection))
1358 CONNECTION_UNLOCK (connection);
1363 _dbus_transport_ref (transport);
1365 CONNECTION_UNLOCK (connection);
1370 if (disconnect_message != NULL)
1371 dbus_message_unref (disconnect_message);
1373 if (disconnect_link != NULL)
1374 _dbus_list_free_link (disconnect_link);
1376 if (connection != NULL)
1378 _dbus_condvar_free_at_location (&connection->io_path_cond);
1379 _dbus_condvar_free_at_location (&connection->dispatch_cond);
1380 _dbus_mutex_free_at_location (&connection->mutex);
1381 _dbus_mutex_free_at_location (&connection->io_path_mutex);
1382 _dbus_mutex_free_at_location (&connection->dispatch_mutex);
1383 _dbus_mutex_free_at_location (&connection->slot_mutex);
1384 dbus_free (connection);
1386 if (pending_replies)
1387 _dbus_hash_table_unref (pending_replies);
1390 _dbus_watch_list_free (watch_list);
1393 _dbus_timeout_list_free (timeout_list);
1395 if (outgoing_counter)
1396 _dbus_counter_unref (outgoing_counter);
1399 _dbus_object_tree_unref (objects);
1405 * Increments the reference count of a DBusConnection.
1406 * Requires that the caller already holds the connection lock.
1408 * @param connection the connection.
1409 * @returns the connection.
1412 _dbus_connection_ref_unlocked (DBusConnection *connection)
1414 _dbus_assert (connection != NULL);
1415 _dbus_assert (connection->generation == _dbus_current_generation);
1417 HAVE_LOCK_CHECK (connection);
1419 _dbus_atomic_inc (&connection->refcount);
1425 * Decrements the reference count of a DBusConnection.
1426 * Requires that the caller already holds the connection lock.
1428 * @param connection the connection.
1431 _dbus_connection_unref_unlocked (DBusConnection *connection)
1433 dbus_bool_t last_unref;
1435 HAVE_LOCK_CHECK (connection);
1437 _dbus_assert (connection != NULL);
1439 last_unref = (_dbus_atomic_dec (&connection->refcount) == 1);
1442 _dbus_connection_last_unref (connection);
1445 static dbus_uint32_t
1446 _dbus_connection_get_next_client_serial (DBusConnection *connection)
1448 dbus_uint32_t serial;
1450 serial = connection->client_serial++;
1452 if (connection->client_serial == 0)
1453 connection->client_serial = 1;
1459 * A callback for use with dbus_watch_new() to create a DBusWatch.
1461 * @todo This is basically a hack - we could delete _dbus_transport_handle_watch()
1462 * and the virtual handle_watch in DBusTransport if we got rid of it.
1463 * The reason this is some work is threading, see the _dbus_connection_handle_watch()
1466 * @param watch the watch.
1467 * @param condition the current condition of the file descriptors being watched.
1468 * @param data must be a pointer to a #DBusConnection
1469 * @returns #FALSE if the IO condition may not have been fully handled due to lack of memory
1472 _dbus_connection_handle_watch (DBusWatch *watch,
1473 unsigned int condition,
1476 DBusConnection *connection;
1478 DBusDispatchStatus status;
1482 _dbus_verbose ("start\n");
1484 CONNECTION_LOCK (connection);
1486 if (!_dbus_connection_acquire_io_path (connection, 1))
1488 /* another thread is handling the message */
1489 CONNECTION_UNLOCK (connection);
1493 HAVE_LOCK_CHECK (connection);
1494 retval = _dbus_transport_handle_watch (connection->transport,
1497 _dbus_connection_release_io_path (connection);
1499 HAVE_LOCK_CHECK (connection);
1501 _dbus_verbose ("middle\n");
1503 status = _dbus_connection_get_dispatch_status_unlocked (connection);
1505 /* this calls out to user code */
1506 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1508 _dbus_verbose ("end\n");
1513 _DBUS_DEFINE_GLOBAL_LOCK (shared_connections);
1514 static DBusHashTable *shared_connections = NULL;
1515 static DBusList *shared_connections_no_guid = NULL;
1518 close_connection_on_shutdown (DBusConnection *connection)
1520 DBusMessage *message;
1522 dbus_connection_ref (connection);
1523 _dbus_connection_close_possibly_shared (connection);
1525 /* Churn through to the Disconnected message */
1526 while ((message = dbus_connection_pop_message (connection)))
1528 dbus_message_unref (message);
1530 dbus_connection_unref (connection);
1534 shared_connections_shutdown (void *data)
1538 _DBUS_LOCK (shared_connections);
1540 /* This is a little bit unpleasant... better ideas? */
1541 while ((n_entries = _dbus_hash_table_get_n_entries (shared_connections)) > 0)
1543 DBusConnection *connection;
1546 _dbus_hash_iter_init (shared_connections, &iter);
1547 _dbus_hash_iter_next (&iter);
1549 connection = _dbus_hash_iter_get_value (&iter);
1551 _DBUS_UNLOCK (shared_connections);
1552 close_connection_on_shutdown (connection);
1553 _DBUS_LOCK (shared_connections);
1555 /* The connection should now be dead and not in our hash ... */
1556 _dbus_assert (_dbus_hash_table_get_n_entries (shared_connections) < n_entries);
1559 _dbus_assert (_dbus_hash_table_get_n_entries (shared_connections) == 0);
1561 _dbus_hash_table_unref (shared_connections);
1562 shared_connections = NULL;
1564 if (shared_connections_no_guid != NULL)
1566 DBusConnection *connection;
1567 connection = _dbus_list_pop_first (&shared_connections_no_guid);
1568 while (connection != NULL)
1570 _DBUS_UNLOCK (shared_connections);
1571 close_connection_on_shutdown (connection);
1572 _DBUS_LOCK (shared_connections);
1573 connection = _dbus_list_pop_first (&shared_connections_no_guid);
1577 shared_connections_no_guid = NULL;
1579 _DBUS_UNLOCK (shared_connections);
1583 connection_lookup_shared (DBusAddressEntry *entry,
1584 DBusConnection **result)
1586 _dbus_verbose ("checking for existing connection\n");
1590 _DBUS_LOCK (shared_connections);
1592 if (shared_connections == NULL)
1594 _dbus_verbose ("creating shared_connections hash table\n");
1596 shared_connections = _dbus_hash_table_new (DBUS_HASH_STRING,
1599 if (shared_connections == NULL)
1601 _DBUS_UNLOCK (shared_connections);
1605 if (!_dbus_register_shutdown_func (shared_connections_shutdown, NULL))
1607 _dbus_hash_table_unref (shared_connections);
1608 shared_connections = NULL;
1609 _DBUS_UNLOCK (shared_connections);
1613 _dbus_verbose (" successfully created shared_connections\n");
1615 _DBUS_UNLOCK (shared_connections);
1616 return TRUE; /* no point looking up in the hash we just made */
1622 guid = dbus_address_entry_get_value (entry, "guid");
1626 DBusConnection *connection;
1628 connection = _dbus_hash_table_lookup_string (shared_connections,
1633 /* The DBusConnection can't be finalized without taking
1634 * the shared_connections lock to remove it from the
1635 * hash. So it's safe to ref the connection here.
1636 * However, it may be disconnected if the Disconnected
1637 * message hasn't been processed yet, in which case we
1638 * want to pretend it isn't in the hash and avoid
1641 * The idea is to avoid ever returning a disconnected connection
1642 * from dbus_connection_open(). We could just synchronously
1643 * drop our shared ref to the connection on connection disconnect,
1644 * and then assert here that the connection is connected, but
1645 * that causes reentrancy headaches.
1647 CONNECTION_LOCK (connection);
1648 if (_dbus_connection_get_is_connected_unlocked (connection))
1650 _dbus_connection_ref_unlocked (connection);
1651 *result = connection;
1652 _dbus_verbose ("looked up existing connection to server guid %s\n",
1657 _dbus_verbose ("looked up existing connection to server guid %s but it was disconnected so ignoring it\n",
1660 CONNECTION_UNLOCK (connection);
1664 _DBUS_UNLOCK (shared_connections);
1670 connection_record_shared_unlocked (DBusConnection *connection,
1674 char *guid_in_connection;
1676 HAVE_LOCK_CHECK (connection);
1677 _dbus_assert (connection->server_guid == NULL);
1678 _dbus_assert (connection->shareable);
1680 /* get a hard ref on this connection, even if
1681 * we won't in fact store it in the hash, we still
1682 * need to hold a ref on it until it's disconnected.
1684 _dbus_connection_ref_unlocked (connection);
1688 _DBUS_LOCK (shared_connections);
1690 if (!_dbus_list_prepend (&shared_connections_no_guid, connection))
1692 _DBUS_UNLOCK (shared_connections);
1696 _DBUS_UNLOCK (shared_connections);
1697 return TRUE; /* don't store in the hash */
1700 /* A separate copy of the key is required in the hash table, because
1701 * we don't have a lock on the connection when we are doing a hash
1705 guid_key = _dbus_strdup (guid);
1706 if (guid_key == NULL)
1709 guid_in_connection = _dbus_strdup (guid);
1710 if (guid_in_connection == NULL)
1712 dbus_free (guid_key);
1716 _DBUS_LOCK (shared_connections);
1717 _dbus_assert (shared_connections != NULL);
1719 if (!_dbus_hash_table_insert_string (shared_connections,
1720 guid_key, connection))
1722 dbus_free (guid_key);
1723 dbus_free (guid_in_connection);
1724 _DBUS_UNLOCK (shared_connections);
1728 connection->server_guid = guid_in_connection;
1730 _dbus_verbose ("stored connection to %s to be shared\n",
1731 connection->server_guid);
1733 _DBUS_UNLOCK (shared_connections);
1735 _dbus_assert (connection->server_guid != NULL);
1741 connection_forget_shared_unlocked (DBusConnection *connection)
1743 HAVE_LOCK_CHECK (connection);
1745 if (!connection->shareable)
1748 _DBUS_LOCK (shared_connections);
1750 if (connection->server_guid != NULL)
1752 _dbus_verbose ("dropping connection to %s out of the shared table\n",
1753 connection->server_guid);
1755 if (!_dbus_hash_table_remove_string (shared_connections,
1756 connection->server_guid))
1757 _dbus_assert_not_reached ("connection was not in the shared table");
1759 dbus_free (connection->server_guid);
1760 connection->server_guid = NULL;
1764 _dbus_list_remove (&shared_connections_no_guid, connection);
1767 _DBUS_UNLOCK (shared_connections);
1769 /* remove our reference held on all shareable connections */
1770 _dbus_connection_unref_unlocked (connection);
1773 static DBusConnection*
1774 connection_try_from_address_entry (DBusAddressEntry *entry,
1777 DBusTransport *transport;
1778 DBusConnection *connection;
1780 transport = _dbus_transport_open (entry, error);
1782 if (transport == NULL)
1784 _DBUS_ASSERT_ERROR_IS_SET (error);
1788 connection = _dbus_connection_new_for_transport (transport);
1790 _dbus_transport_unref (transport);
1792 if (connection == NULL)
1794 _DBUS_SET_OOM (error);
1798 #ifndef DBUS_DISABLE_CHECKS
1799 _dbus_assert (!connection->have_connection_lock);
1805 * If the shared parameter is true, then any existing connection will
1806 * be used (and if a new connection is created, it will be available
1807 * for use by others). If the shared parameter is false, a new
1808 * connection will always be created, and the new connection will
1809 * never be returned to other callers.
1811 * @param address the address
1812 * @param shared whether the connection is shared or private
1813 * @param error error return
1814 * @returns the connection or #NULL on error
1816 static DBusConnection*
1817 _dbus_connection_open_internal (const char *address,
1821 DBusConnection *connection;
1822 DBusAddressEntry **entries;
1823 DBusError tmp_error = DBUS_ERROR_INIT;
1824 DBusError first_error = DBUS_ERROR_INIT;
1827 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1829 _dbus_verbose ("opening %s connection to: %s\n",
1830 shared ? "shared" : "private", address);
1832 if (!dbus_parse_address (address, &entries, &len, error))
1835 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1839 for (i = 0; i < len; i++)
1843 if (!connection_lookup_shared (entries[i], &connection))
1844 _DBUS_SET_OOM (&tmp_error);
1847 if (connection == NULL)
1849 connection = connection_try_from_address_entry (entries[i],
1852 if (connection != NULL && shared)
1856 connection->shareable = TRUE;
1858 /* guid may be NULL */
1859 guid = dbus_address_entry_get_value (entries[i], "guid");
1861 CONNECTION_LOCK (connection);
1863 if (!connection_record_shared_unlocked (connection, guid))
1865 _DBUS_SET_OOM (&tmp_error);
1866 _dbus_connection_close_possibly_shared_and_unlock (connection);
1867 dbus_connection_unref (connection);
1871 CONNECTION_UNLOCK (connection);
1878 _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
1881 dbus_move_error (&tmp_error, &first_error);
1883 dbus_error_free (&tmp_error);
1886 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1887 _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
1889 if (connection == NULL)
1891 _DBUS_ASSERT_ERROR_IS_SET (&first_error);
1892 dbus_move_error (&first_error, error);
1895 dbus_error_free (&first_error);
1897 dbus_address_entries_free (entries);
1902 * Closes a shared OR private connection, while dbus_connection_close() can
1903 * only be used on private connections. Should only be called by the
1904 * dbus code that owns the connection - an owner must be known,
1905 * the open/close state is like malloc/free, not like ref/unref.
1907 * @param connection the connection
1910 _dbus_connection_close_possibly_shared (DBusConnection *connection)
1912 _dbus_assert (connection != NULL);
1913 _dbus_assert (connection->generation == _dbus_current_generation);
1915 CONNECTION_LOCK (connection);
1916 _dbus_connection_close_possibly_shared_and_unlock (connection);
1919 static DBusPreallocatedSend*
1920 _dbus_connection_preallocate_send_unlocked (DBusConnection *connection)
1922 DBusPreallocatedSend *preallocated;
1924 HAVE_LOCK_CHECK (connection);
1926 _dbus_assert (connection != NULL);
1928 preallocated = dbus_new (DBusPreallocatedSend, 1);
1929 if (preallocated == NULL)
1932 if (connection->link_cache != NULL)
1934 preallocated->queue_link =
1935 _dbus_list_pop_first_link (&connection->link_cache);
1936 preallocated->queue_link->data = NULL;
1940 preallocated->queue_link = _dbus_list_alloc_link (NULL);
1941 if (preallocated->queue_link == NULL)
1945 if (connection->link_cache != NULL)
1947 preallocated->counter_link =
1948 _dbus_list_pop_first_link (&connection->link_cache);
1949 preallocated->counter_link->data = connection->outgoing_counter;
1953 preallocated->counter_link = _dbus_list_alloc_link (connection->outgoing_counter);
1954 if (preallocated->counter_link == NULL)
1958 _dbus_counter_ref (preallocated->counter_link->data);
1960 preallocated->connection = connection;
1962 return preallocated;
1965 _dbus_list_free_link (preallocated->queue_link);
1967 dbus_free (preallocated);
1972 /* Called with lock held, does not update dispatch status */
1974 _dbus_connection_send_preallocated_unlocked_no_update (DBusConnection *connection,
1975 DBusPreallocatedSend *preallocated,
1976 DBusMessage *message,
1977 dbus_uint32_t *client_serial)
1979 dbus_uint32_t serial;
1981 preallocated->queue_link->data = message;
1982 _dbus_list_prepend_link (&connection->outgoing_messages,
1983 preallocated->queue_link);
1985 /* It's OK that we'll never call the notify function, because for the
1986 * outgoing limit, there isn't one */
1987 _dbus_message_add_counter_link (message,
1988 preallocated->counter_link);
1990 dbus_free (preallocated);
1991 preallocated = NULL;
1993 dbus_message_ref (message);
1995 connection->n_outgoing += 1;
1997 _dbus_verbose ("Message %p (%s %s %s %s '%s') for %s added to outgoing queue %p, %d pending to send\n",
1999 dbus_message_type_to_string (dbus_message_get_type (message)),
2000 dbus_message_get_path (message) ?
2001 dbus_message_get_path (message) :
2003 dbus_message_get_interface (message) ?
2004 dbus_message_get_interface (message) :
2006 dbus_message_get_member (message) ?
2007 dbus_message_get_member (message) :
2009 dbus_message_get_signature (message),
2010 dbus_message_get_destination (message) ?
2011 dbus_message_get_destination (message) :
2014 connection->n_outgoing);
2016 if (dbus_message_get_serial (message) == 0)
2018 serial = _dbus_connection_get_next_client_serial (connection);
2019 dbus_message_set_serial (message, serial);
2021 *client_serial = serial;
2026 *client_serial = dbus_message_get_serial (message);
2029 _dbus_verbose ("Message %p serial is %u\n",
2030 message, dbus_message_get_serial (message));
2032 dbus_message_lock (message);
2034 /* Now we need to run an iteration to hopefully just write the messages
2035 * out immediately, and otherwise get them queued up
2037 _dbus_connection_do_iteration_unlocked (connection,
2039 DBUS_ITERATION_DO_WRITING,
2042 /* If stuff is still queued up, be sure we wake up the main loop */
2043 if (connection->n_outgoing > 0)
2044 _dbus_connection_wakeup_mainloop (connection);
2048 _dbus_connection_send_preallocated_and_unlock (DBusConnection *connection,
2049 DBusPreallocatedSend *preallocated,
2050 DBusMessage *message,
2051 dbus_uint32_t *client_serial)
2053 DBusDispatchStatus status;
2055 HAVE_LOCK_CHECK (connection);
2057 _dbus_connection_send_preallocated_unlocked_no_update (connection,
2059 message, client_serial);
2061 _dbus_verbose ("middle\n");
2062 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2064 /* this calls out to user code */
2065 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2069 * Like dbus_connection_send(), but assumes the connection
2070 * is already locked on function entry, and unlocks before returning.
2072 * @param connection the connection
2073 * @param message the message to send
2074 * @param client_serial return location for client serial of sent message
2075 * @returns #FALSE on out-of-memory
2078 _dbus_connection_send_and_unlock (DBusConnection *connection,
2079 DBusMessage *message,
2080 dbus_uint32_t *client_serial)
2082 DBusPreallocatedSend *preallocated;
2084 _dbus_assert (connection != NULL);
2085 _dbus_assert (message != NULL);
2087 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
2088 if (preallocated == NULL)
2090 CONNECTION_UNLOCK (connection);
2094 _dbus_connection_send_preallocated_and_unlock (connection,
2102 * Used internally to handle the semantics of dbus_server_set_new_connection_function().
2103 * If the new connection function does not ref the connection, we want to close it.
2105 * A bit of a hack, probably the new connection function should have returned a value
2106 * for whether to close, or should have had to close the connection itself if it
2109 * But, this works OK as long as the new connection function doesn't do anything
2110 * crazy like keep the connection around without ref'ing it.
2112 * We have to lock the connection across refcount check and close in case
2113 * the new connection function spawns a thread that closes and unrefs.
2114 * In that case, if the app thread
2115 * closes and unrefs first, we'll harmlessly close again; if the app thread
2116 * still has the ref, we'll close and then the app will close harmlessly.
2117 * If the app unrefs without closing, the app is broken since if the
2118 * app refs from the new connection function it is supposed to also close.
2120 * If we didn't atomically check the refcount and close with the lock held
2121 * though, we could screw this up.
2123 * @param connection the connection
2126 _dbus_connection_close_if_only_one_ref (DBusConnection *connection)
2128 dbus_int32_t refcount;
2130 CONNECTION_LOCK (connection);
2132 refcount = _dbus_atomic_get (&connection->refcount);
2133 /* The caller should have at least one ref */
2134 _dbus_assert (refcount >= 1);
2137 _dbus_connection_close_possibly_shared_and_unlock (connection);
2139 CONNECTION_UNLOCK (connection);
2144 * When a function that blocks has been called with a timeout, and we
2145 * run out of memory, the time to wait for memory is based on the
2146 * timeout. If the caller was willing to block a long time we wait a
2147 * relatively long time for memory, if they were only willing to block
2148 * briefly then we retry for memory at a rapid rate.
2150 * @timeout_milliseconds the timeout requested for blocking
2153 _dbus_memory_pause_based_on_timeout (int timeout_milliseconds)
2155 if (timeout_milliseconds == -1)
2156 _dbus_sleep_milliseconds (1000);
2157 else if (timeout_milliseconds < 100)
2158 ; /* just busy loop */
2159 else if (timeout_milliseconds <= 1000)
2160 _dbus_sleep_milliseconds (timeout_milliseconds / 3);
2162 _dbus_sleep_milliseconds (1000);
2165 static DBusMessage *
2166 generate_local_error_message (dbus_uint32_t serial,
2170 DBusMessage *message;
2171 message = dbus_message_new (DBUS_MESSAGE_TYPE_ERROR);
2175 if (!dbus_message_set_error_name (message, error_name))
2177 dbus_message_unref (message);
2182 dbus_message_set_no_reply (message, TRUE);
2184 if (!dbus_message_set_reply_serial (message,
2187 dbus_message_unref (message);
2192 if (error_msg != NULL)
2194 DBusMessageIter iter;
2196 dbus_message_iter_init_append (message, &iter);
2197 if (!dbus_message_iter_append_basic (&iter,
2201 dbus_message_unref (message);
2212 * Peek the incoming queue to see if we got reply for a specific serial
2215 _dbus_connection_peek_for_reply_unlocked (DBusConnection *connection,
2216 dbus_uint32_t client_serial)
2219 HAVE_LOCK_CHECK (connection);
2221 link = _dbus_list_get_first_link (&connection->incoming_messages);
2223 while (link != NULL)
2225 DBusMessage *reply = link->data;
2227 if (dbus_message_get_reply_serial (reply) == client_serial)
2229 _dbus_verbose ("%s reply to %d found in queue\n", _DBUS_FUNCTION_NAME, client_serial);
2232 link = _dbus_list_get_next_link (&connection->incoming_messages, link);
2238 /* This is slightly strange since we can pop a message here without
2239 * the dispatch lock.
2242 check_for_reply_unlocked (DBusConnection *connection,
2243 dbus_uint32_t client_serial)
2247 HAVE_LOCK_CHECK (connection);
2249 link = _dbus_list_get_first_link (&connection->incoming_messages);
2251 while (link != NULL)
2253 DBusMessage *reply = link->data;
2255 if (dbus_message_get_reply_serial (reply) == client_serial)
2257 _dbus_list_remove_link (&connection->incoming_messages, link);
2258 connection->n_incoming -= 1;
2261 link = _dbus_list_get_next_link (&connection->incoming_messages, link);
2268 connection_timeout_and_complete_all_pending_calls_unlocked (DBusConnection *connection)
2270 /* We can't iterate over the hash in the normal way since we'll be
2271 * dropping the lock for each item. So we restart the
2272 * iter each time as we drain the hash table.
2275 while (_dbus_hash_table_get_n_entries (connection->pending_replies) > 0)
2277 DBusPendingCall *pending;
2280 _dbus_hash_iter_init (connection->pending_replies, &iter);
2281 _dbus_hash_iter_next (&iter);
2283 pending = _dbus_hash_iter_get_value (&iter);
2284 _dbus_pending_call_ref_unlocked (pending);
2286 _dbus_pending_call_queue_timeout_error_unlocked (pending,
2289 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
2290 _dbus_connection_remove_timeout_unlocked (connection,
2291 _dbus_pending_call_get_timeout_unlocked (pending));
2292 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
2293 _dbus_hash_iter_remove_entry (&iter);
2295 _dbus_pending_call_unref_and_unlock (pending);
2296 CONNECTION_LOCK (connection);
2298 HAVE_LOCK_CHECK (connection);
2302 complete_pending_call_and_unlock (DBusConnection *connection,
2303 DBusPendingCall *pending,
2304 DBusMessage *message)
2306 _dbus_pending_call_set_reply_unlocked (pending, message);
2307 _dbus_pending_call_ref_unlocked (pending); /* in case there's no app with a ref held */
2308 _dbus_connection_detach_pending_call_and_unlock (connection, pending);
2310 /* Must be called unlocked since it invokes app callback */
2311 _dbus_pending_call_complete (pending);
2312 dbus_pending_call_unref (pending);
2316 check_for_reply_and_update_dispatch_unlocked (DBusConnection *connection,
2317 DBusPendingCall *pending)
2320 DBusDispatchStatus status;
2322 reply = check_for_reply_unlocked (connection,
2323 _dbus_pending_call_get_reply_serial_unlocked (pending));
2326 _dbus_verbose ("checked for reply\n");
2328 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): got reply\n");
2330 complete_pending_call_and_unlock (connection, pending, reply);
2331 dbus_message_unref (reply);
2333 CONNECTION_LOCK (connection);
2334 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2335 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2336 dbus_pending_call_unref (pending);
2345 * Blocks until a pending call times out or gets a reply.
2347 * Does not re-enter the main loop or run filter/path-registered
2348 * callbacks. The reply to the message will not be seen by
2351 * Returns immediately if pending call already got a reply.
2353 * @todo could use performance improvements (it keeps scanning
2354 * the whole message queue for example)
2356 * @param pending the pending call we block for a reply on
2359 _dbus_connection_block_pending_call (DBusPendingCall *pending)
2361 long start_tv_sec, start_tv_usec;
2362 long tv_sec, tv_usec;
2363 DBusDispatchStatus status;
2364 DBusConnection *connection;
2365 dbus_uint32_t client_serial;
2366 DBusTimeout *timeout;
2367 int timeout_milliseconds, elapsed_milliseconds;
2369 _dbus_assert (pending != NULL);
2371 if (dbus_pending_call_get_completed (pending))
2374 dbus_pending_call_ref (pending); /* necessary because the call could be canceled */
2376 connection = _dbus_pending_call_get_connection_and_lock (pending);
2378 /* Flush message queue - note, can affect dispatch status */
2379 _dbus_connection_flush_unlocked (connection);
2381 client_serial = _dbus_pending_call_get_reply_serial_unlocked (pending);
2383 /* note that timeout_milliseconds is limited to a smallish value
2384 * in _dbus_pending_call_new() so overflows aren't possible
2387 timeout = _dbus_pending_call_get_timeout_unlocked (pending);
2388 _dbus_get_current_time (&start_tv_sec, &start_tv_usec);
2391 timeout_milliseconds = dbus_timeout_get_interval (timeout);
2393 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): will block %d milliseconds for reply serial %u from %ld sec %ld usec\n",
2394 timeout_milliseconds,
2396 start_tv_sec, start_tv_usec);
2400 timeout_milliseconds = -1;
2402 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): will block for reply serial %u\n", client_serial);
2405 /* check to see if we already got the data off the socket */
2406 /* from another blocked pending call */
2407 if (check_for_reply_and_update_dispatch_unlocked (connection, pending))
2410 /* Now we wait... */
2411 /* always block at least once as we know we don't have the reply yet */
2412 _dbus_connection_do_iteration_unlocked (connection,
2414 DBUS_ITERATION_DO_READING |
2415 DBUS_ITERATION_BLOCK,
2416 timeout_milliseconds);
2420 _dbus_verbose ("top of recheck\n");
2422 HAVE_LOCK_CHECK (connection);
2424 /* queue messages and get status */
2426 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2428 /* the get_completed() is in case a dispatch() while we were blocking
2429 * got the reply instead of us.
2431 if (_dbus_pending_call_get_completed_unlocked (pending))
2433 _dbus_verbose ("Pending call completed by dispatch\n");
2434 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2435 dbus_pending_call_unref (pending);
2439 if (status == DBUS_DISPATCH_DATA_REMAINS)
2441 if (check_for_reply_and_update_dispatch_unlocked (connection, pending))
2445 _dbus_get_current_time (&tv_sec, &tv_usec);
2446 elapsed_milliseconds = (tv_sec - start_tv_sec) * 1000 +
2447 (tv_usec - start_tv_usec) / 1000;
2449 if (!_dbus_connection_get_is_connected_unlocked (connection))
2451 DBusMessage *error_msg;
2453 error_msg = generate_local_error_message (client_serial,
2454 DBUS_ERROR_DISCONNECTED,
2455 "Connection was disconnected before a reply was received");
2457 /* on OOM error_msg is set to NULL */
2458 complete_pending_call_and_unlock (connection, pending, error_msg);
2459 dbus_pending_call_unref (pending);
2462 else if (connection->disconnect_message_link == NULL)
2463 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): disconnected\n");
2464 else if (timeout == NULL)
2466 if (status == DBUS_DISPATCH_NEED_MEMORY)
2468 /* Try sleeping a bit, as we aren't sure we need to block for reading,
2469 * we may already have a reply in the buffer and just can't process
2472 _dbus_verbose ("dbus_connection_send_with_reply_and_block() waiting for more memory\n");
2474 _dbus_memory_pause_based_on_timeout (timeout_milliseconds - elapsed_milliseconds);
2478 /* block again, we don't have the reply buffered yet. */
2479 _dbus_connection_do_iteration_unlocked (connection,
2481 DBUS_ITERATION_DO_READING |
2482 DBUS_ITERATION_BLOCK,
2483 timeout_milliseconds - elapsed_milliseconds);
2486 goto recheck_status;
2488 else if (tv_sec < start_tv_sec)
2489 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): clock set backward\n");
2490 else if (elapsed_milliseconds < timeout_milliseconds)
2492 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): %d milliseconds remain\n", timeout_milliseconds - elapsed_milliseconds);
2494 if (status == DBUS_DISPATCH_NEED_MEMORY)
2496 /* Try sleeping a bit, as we aren't sure we need to block for reading,
2497 * we may already have a reply in the buffer and just can't process
2500 _dbus_verbose ("dbus_connection_send_with_reply_and_block() waiting for more memory\n");
2502 _dbus_memory_pause_based_on_timeout (timeout_milliseconds - elapsed_milliseconds);
2506 /* block again, we don't have the reply buffered yet. */
2507 _dbus_connection_do_iteration_unlocked (connection,
2509 DBUS_ITERATION_DO_READING |
2510 DBUS_ITERATION_BLOCK,
2511 timeout_milliseconds - elapsed_milliseconds);
2514 goto recheck_status;
2517 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): Waited %d milliseconds and got no reply\n",
2518 elapsed_milliseconds);
2520 _dbus_assert (!_dbus_pending_call_get_completed_unlocked (pending));
2522 /* unlock and call user code */
2523 complete_pending_call_and_unlock (connection, pending, NULL);
2525 /* update user code on dispatch status */
2526 CONNECTION_LOCK (connection);
2527 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2528 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2529 dbus_pending_call_unref (pending);
2535 * @addtogroup DBusConnection
2541 * Gets a connection to a remote address. If a connection to the given
2542 * address already exists, returns the existing connection with its
2543 * reference count incremented. Otherwise, returns a new connection
2544 * and saves the new connection for possible re-use if a future call
2545 * to dbus_connection_open() asks to connect to the same server.
2547 * Use dbus_connection_open_private() to get a dedicated connection
2548 * not shared with other callers of dbus_connection_open().
2550 * If the open fails, the function returns #NULL, and provides a
2551 * reason for the failure in the error parameter. Pass #NULL for the
2552 * error parameter if you aren't interested in the reason for
2555 * Because this connection is shared, no user of the connection
2556 * may call dbus_connection_close(). However, when you are done with the
2557 * connection you should call dbus_connection_unref().
2559 * @note Prefer dbus_connection_open() to dbus_connection_open_private()
2560 * unless you have good reason; connections are expensive enough
2561 * that it's wasteful to create lots of connections to the same
2564 * @param address the address.
2565 * @param error address where an error can be returned.
2566 * @returns new connection, or #NULL on failure.
2569 dbus_connection_open (const char *address,
2572 DBusConnection *connection;
2574 _dbus_return_val_if_fail (address != NULL, NULL);
2575 _dbus_return_val_if_error_is_set (error, NULL);
2577 connection = _dbus_connection_open_internal (address,
2585 * Opens a new, dedicated connection to a remote address. Unlike
2586 * dbus_connection_open(), always creates a new connection.
2587 * This connection will not be saved or recycled by libdbus.
2589 * If the open fails, the function returns #NULL, and provides a
2590 * reason for the failure in the error parameter. Pass #NULL for the
2591 * error parameter if you aren't interested in the reason for
2594 * When you are done with this connection, you must
2595 * dbus_connection_close() to disconnect it,
2596 * and dbus_connection_unref() to free the connection object.
2598 * (The dbus_connection_close() can be skipped if the
2599 * connection is already known to be disconnected, for example
2600 * if you are inside a handler for the Disconnected signal.)
2602 * @note Prefer dbus_connection_open() to dbus_connection_open_private()
2603 * unless you have good reason; connections are expensive enough
2604 * that it's wasteful to create lots of connections to the same
2607 * @param address the address.
2608 * @param error address where an error can be returned.
2609 * @returns new connection, or #NULL on failure.
2612 dbus_connection_open_private (const char *address,
2615 DBusConnection *connection;
2617 _dbus_return_val_if_fail (address != NULL, NULL);
2618 _dbus_return_val_if_error_is_set (error, NULL);
2620 connection = _dbus_connection_open_internal (address,
2628 * Increments the reference count of a DBusConnection.
2630 * @param connection the connection.
2631 * @returns the connection.
2634 dbus_connection_ref (DBusConnection *connection)
2636 _dbus_return_val_if_fail (connection != NULL, NULL);
2637 _dbus_return_val_if_fail (connection->generation == _dbus_current_generation, NULL);
2639 _dbus_atomic_inc (&connection->refcount);
2645 free_outgoing_message (void *element,
2648 DBusMessage *message = element;
2649 DBusConnection *connection = data;
2651 _dbus_message_remove_counter (message,
2652 connection->outgoing_counter,
2654 dbus_message_unref (message);
2657 /* This is run without the mutex held, but after the last reference
2658 * to the connection has been dropped we should have no thread-related
2662 _dbus_connection_last_unref (DBusConnection *connection)
2666 _dbus_verbose ("Finalizing connection %p\n", connection);
2668 _dbus_assert (_dbus_atomic_get (&connection->refcount) == 0);
2670 /* You have to disconnect the connection before unref:ing it. Otherwise
2671 * you won't get the disconnected message.
2673 _dbus_assert (!_dbus_transport_get_is_connected (connection->transport));
2674 _dbus_assert (connection->server_guid == NULL);
2676 /* ---- We're going to call various application callbacks here, hope it doesn't break anything... */
2677 _dbus_object_tree_free_all_unlocked (connection->objects);
2679 dbus_connection_set_dispatch_status_function (connection, NULL, NULL, NULL);
2680 dbus_connection_set_wakeup_main_function (connection, NULL, NULL, NULL);
2681 dbus_connection_set_unix_user_function (connection, NULL, NULL, NULL);
2683 _dbus_watch_list_free (connection->watches);
2684 connection->watches = NULL;
2686 _dbus_timeout_list_free (connection->timeouts);
2687 connection->timeouts = NULL;
2689 _dbus_data_slot_list_free (&connection->slot_list);
2691 link = _dbus_list_get_first_link (&connection->filter_list);
2692 while (link != NULL)
2694 DBusMessageFilter *filter = link->data;
2695 DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
2697 filter->function = NULL;
2698 _dbus_message_filter_unref (filter); /* calls app callback */
2703 _dbus_list_clear (&connection->filter_list);
2705 /* ---- Done with stuff that invokes application callbacks */
2707 _dbus_object_tree_unref (connection->objects);
2709 _dbus_hash_table_unref (connection->pending_replies);
2710 connection->pending_replies = NULL;
2712 _dbus_list_clear (&connection->filter_list);
2714 _dbus_list_foreach (&connection->outgoing_messages,
2715 free_outgoing_message,
2717 _dbus_list_clear (&connection->outgoing_messages);
2719 _dbus_list_foreach (&connection->incoming_messages,
2720 (DBusForeachFunction) dbus_message_unref,
2722 _dbus_list_clear (&connection->incoming_messages);
2724 _dbus_counter_unref (connection->outgoing_counter);
2726 _dbus_transport_unref (connection->transport);
2728 if (connection->disconnect_message_link)
2730 DBusMessage *message = connection->disconnect_message_link->data;
2731 dbus_message_unref (message);
2732 _dbus_list_free_link (connection->disconnect_message_link);
2735 _dbus_list_clear (&connection->link_cache);
2737 _dbus_condvar_free_at_location (&connection->dispatch_cond);
2738 _dbus_condvar_free_at_location (&connection->io_path_cond);
2740 _dbus_mutex_free_at_location (&connection->io_path_mutex);
2741 _dbus_mutex_free_at_location (&connection->dispatch_mutex);
2743 _dbus_mutex_free_at_location (&connection->slot_mutex);
2745 _dbus_mutex_free_at_location (&connection->mutex);
2747 dbus_free (connection);
2751 * Decrements the reference count of a DBusConnection, and finalizes
2752 * it if the count reaches zero.
2754 * Note: it is a bug to drop the last reference to a connection that
2755 * is still connected.
2757 * For shared connections, libdbus will own a reference
2758 * as long as the connection is connected, so you can know that either
2759 * you don't have the last reference, or it's OK to drop the last reference.
2760 * Most connections are shared. dbus_connection_open() and dbus_bus_get()
2761 * return shared connections.
2763 * For private connections, the creator of the connection must arrange for
2764 * dbus_connection_close() to be called prior to dropping the last reference.
2765 * Private connections come from dbus_connection_open_private() or dbus_bus_get_private().
2767 * @param connection the connection.
2770 dbus_connection_unref (DBusConnection *connection)
2772 dbus_bool_t last_unref;
2774 _dbus_return_if_fail (connection != NULL);
2775 _dbus_return_if_fail (connection->generation == _dbus_current_generation);
2777 last_unref = (_dbus_atomic_dec (&connection->refcount) == 1);
2781 #ifndef DBUS_DISABLE_CHECKS
2782 if (_dbus_transport_get_is_connected (connection->transport))
2784 _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",
2785 connection->shareable ?
2786 "Most likely, the application called unref() too many times and removed a reference belonging to libdbus, since this is a shared connection.\n" :
2787 "Most likely, the application was supposed to call dbus_connection_close(), since this is a private connection.\n");
2791 _dbus_connection_last_unref (connection);
2796 * Note that the transport can disconnect itself (other end drops us)
2797 * and in that case this function never runs. So this function must
2798 * not do anything more than disconnect the transport and update the
2801 * If the transport self-disconnects, then we assume someone will
2802 * dispatch the connection to cause the dispatch status update.
2805 _dbus_connection_close_possibly_shared_and_unlock (DBusConnection *connection)
2807 DBusDispatchStatus status;
2809 HAVE_LOCK_CHECK (connection);
2811 _dbus_verbose ("Disconnecting %p\n", connection);
2813 /* We need to ref because update_dispatch_status_and_unlock will unref
2814 * the connection if it was shared and libdbus was the only remaining
2817 _dbus_connection_ref_unlocked (connection);
2819 _dbus_transport_disconnect (connection->transport);
2821 /* This has the side effect of queuing the disconnect message link
2822 * (unless we don't have enough memory, possibly, so don't assert it).
2823 * After the disconnect message link is queued, dbus_bus_get/dbus_connection_open
2824 * should never again return the newly-disconnected connection.
2826 * However, we only unref the shared connection and exit_on_disconnect when
2827 * the disconnect message reaches the head of the message queue,
2828 * NOT when it's first queued.
2830 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2832 /* This calls out to user code */
2833 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2835 /* Could also call out to user code */
2836 dbus_connection_unref (connection);
2840 * Closes a private connection, so no further data can be sent or received.
2841 * This disconnects the transport (such as a socket) underlying the
2844 * Attempts to send messages after closing a connection are safe, but will result in
2845 * error replies generated locally in libdbus.
2847 * This function does not affect the connection's reference count. It's
2848 * safe to close a connection more than once; all calls after the
2849 * first do nothing. It's impossible to "reopen" a connection, a
2850 * new connection must be created. This function may result in a call
2851 * to the DBusDispatchStatusFunction set with
2852 * dbus_connection_set_dispatch_status_function(), as the disconnect
2853 * message it generates needs to be dispatched.
2855 * If a connection is dropped by the remote application, it will
2858 * You must close a connection prior to releasing the last reference to
2859 * the connection. If you dbus_connection_unref() for the last time
2860 * without closing the connection, the results are undefined; it
2861 * is a bug in your program and libdbus will try to print a warning.
2863 * You may not close a shared connection. Connections created with
2864 * dbus_connection_open() or dbus_bus_get() are shared.
2865 * These connections are owned by libdbus, and applications should
2866 * only unref them, never close them. Applications can know it is
2867 * safe to unref these connections because libdbus will be holding a
2868 * reference as long as the connection is open. Thus, either the
2869 * connection is closed and it is OK to drop the last reference,
2870 * or the connection is open and the app knows it does not have the
2873 * Connections created with dbus_connection_open_private() or
2874 * dbus_bus_get_private() are not kept track of or referenced by
2875 * libdbus. The creator of these connections is responsible for
2876 * calling dbus_connection_close() prior to releasing the last
2877 * reference, if the connection is not already disconnected.
2879 * @param connection the private (unshared) connection to close
2882 dbus_connection_close (DBusConnection *connection)
2884 _dbus_return_if_fail (connection != NULL);
2885 _dbus_return_if_fail (connection->generation == _dbus_current_generation);
2887 CONNECTION_LOCK (connection);
2889 #ifndef DBUS_DISABLE_CHECKS
2890 if (connection->shareable)
2892 CONNECTION_UNLOCK (connection);
2894 _dbus_warn_check_failed ("Applications must not close shared connections - see dbus_connection_close() docs. This is a bug in the application.\n");
2899 _dbus_connection_close_possibly_shared_and_unlock (connection);
2903 _dbus_connection_get_is_connected_unlocked (DBusConnection *connection)
2905 HAVE_LOCK_CHECK (connection);
2906 return _dbus_transport_get_is_connected (connection->transport);
2910 * Gets whether the connection is currently open. A connection may
2911 * become disconnected when the remote application closes its end, or
2912 * exits; a connection may also be disconnected with
2913 * dbus_connection_close().
2915 * There are not separate states for "closed" and "disconnected," the two
2916 * terms are synonymous. This function should really be called
2917 * get_is_open() but for historical reasons is not.
2919 * @param connection the connection.
2920 * @returns #TRUE if the connection is still alive.
2923 dbus_connection_get_is_connected (DBusConnection *connection)
2927 _dbus_return_val_if_fail (connection != NULL, FALSE);
2929 CONNECTION_LOCK (connection);
2930 res = _dbus_connection_get_is_connected_unlocked (connection);
2931 CONNECTION_UNLOCK (connection);
2937 * Gets whether the connection was authenticated. (Note that
2938 * if the connection was authenticated then disconnected,
2939 * this function still returns #TRUE)
2941 * @param connection the connection
2942 * @returns #TRUE if the connection was ever authenticated
2945 dbus_connection_get_is_authenticated (DBusConnection *connection)
2949 _dbus_return_val_if_fail (connection != NULL, FALSE);
2951 CONNECTION_LOCK (connection);
2952 res = _dbus_transport_get_is_authenticated (connection->transport);
2953 CONNECTION_UNLOCK (connection);
2959 * Gets whether the connection is not authenticated as a specific
2960 * user. If the connection is not authenticated, this function
2961 * returns #TRUE, and if it is authenticated but as an anonymous user,
2962 * it returns #TRUE. If it is authenticated as a specific user, then
2963 * this returns #FALSE. (Note that if the connection was authenticated
2964 * as anonymous then disconnected, this function still returns #TRUE.)
2966 * If the connection is not anonymous, you can use
2967 * dbus_connection_get_unix_user() and
2968 * dbus_connection_get_windows_user() to see who it's authorized as.
2970 * If you want to prevent non-anonymous authorization, use
2971 * dbus_server_set_auth_mechanisms() to remove the mechanisms that
2972 * allow proving user identity (i.e. only allow the ANONYMOUS
2975 * @param connection the connection
2976 * @returns #TRUE if not authenticated or authenticated as anonymous
2979 dbus_connection_get_is_anonymous (DBusConnection *connection)
2983 _dbus_return_val_if_fail (connection != NULL, FALSE);
2985 CONNECTION_LOCK (connection);
2986 res = _dbus_transport_get_is_anonymous (connection->transport);
2987 CONNECTION_UNLOCK (connection);
2993 * Gets the ID of the server address we are authenticated to, if this
2994 * connection is on the client side. If the connection is on the
2995 * server side, this will always return #NULL - use dbus_server_get_id()
2996 * to get the ID of your own server, if you are the server side.
2998 * If a client-side connection is not authenticated yet, the ID may be
2999 * available if it was included in the server address, but may not be
3000 * available. The only way to be sure the server ID is available
3001 * is to wait for authentication to complete.
3003 * In general, each mode of connecting to a given server will have
3004 * its own ID. So for example, if the session bus daemon is listening
3005 * on UNIX domain sockets and on TCP, then each of those modalities
3006 * will have its own server ID.
3008 * If you want an ID that identifies an entire session bus, look at
3009 * dbus_bus_get_id() instead (which is just a convenience wrapper
3010 * around the org.freedesktop.DBus.GetId method invoked on the bus).
3012 * You can also get a machine ID; see dbus_get_local_machine_id() to
3013 * get the machine you are on. There isn't a convenience wrapper, but
3014 * you can invoke org.freedesktop.DBus.Peer.GetMachineId on any peer
3015 * to get the machine ID on the other end.
3017 * The D-Bus specification describes the server ID and other IDs in a
3020 * @param connection the connection
3021 * @returns the server ID or #NULL if no memory or the connection is server-side
3024 dbus_connection_get_server_id (DBusConnection *connection)
3028 _dbus_return_val_if_fail (connection != NULL, NULL);
3030 CONNECTION_LOCK (connection);
3031 id = _dbus_strdup (_dbus_transport_get_server_id (connection->transport));
3032 CONNECTION_UNLOCK (connection);
3038 * Tests whether a certain type can be send via the connection. This
3039 * will always return TRUE for all types, with the exception of
3040 * DBUS_TYPE_UNIX_FD. The function will return TRUE for
3041 * DBUS_TYPE_UNIX_FD only on systems that know Unix file descriptors
3042 * and can send them via the chosen transport and when the remote side
3045 * This function can be used to do runtime checking for types that
3046 * might be unknown to the specific D-Bus client implementation
3047 * version, i.e. it will return FALSE for all types this
3048 * implementation does not know, including invalid or reserved types.
3050 * @param connection the connection
3051 * @param type the type to check
3052 * @returns TRUE if the type may be send via the connection
3055 dbus_connection_can_send_type(DBusConnection *connection,
3058 _dbus_return_val_if_fail (connection != NULL, FALSE);
3060 if (!dbus_type_is_valid (type))
3063 if (type != DBUS_TYPE_UNIX_FD)
3066 #ifdef HAVE_UNIX_FD_PASSING
3070 CONNECTION_LOCK(connection);
3071 b = _dbus_transport_can_pass_unix_fd(connection->transport);
3072 CONNECTION_UNLOCK(connection);
3082 * Set whether _exit() should be called when the connection receives a
3083 * disconnect signal. The call to _exit() comes after any handlers for
3084 * the disconnect signal run; handlers can cancel the exit by calling
3087 * By default, exit_on_disconnect is #FALSE; but for message bus
3088 * connections returned from dbus_bus_get() it will be toggled on
3091 * @param connection the connection
3092 * @param exit_on_disconnect #TRUE if _exit() should be called after a disconnect signal
3095 dbus_connection_set_exit_on_disconnect (DBusConnection *connection,
3096 dbus_bool_t exit_on_disconnect)
3098 _dbus_return_if_fail (connection != NULL);
3100 CONNECTION_LOCK (connection);
3101 connection->exit_on_disconnect = exit_on_disconnect != FALSE;
3102 CONNECTION_UNLOCK (connection);
3106 * Preallocates resources needed to send a message, allowing the message
3107 * to be sent without the possibility of memory allocation failure.
3108 * Allows apps to create a future guarantee that they can send
3109 * a message regardless of memory shortages.
3111 * @param connection the connection we're preallocating for.
3112 * @returns the preallocated resources, or #NULL
3114 DBusPreallocatedSend*
3115 dbus_connection_preallocate_send (DBusConnection *connection)
3117 DBusPreallocatedSend *preallocated;
3119 _dbus_return_val_if_fail (connection != NULL, NULL);
3121 CONNECTION_LOCK (connection);
3124 _dbus_connection_preallocate_send_unlocked (connection);
3126 CONNECTION_UNLOCK (connection);
3128 return preallocated;
3132 * Frees preallocated message-sending resources from
3133 * dbus_connection_preallocate_send(). Should only
3134 * be called if the preallocated resources are not used
3135 * to send a message.
3137 * @param connection the connection
3138 * @param preallocated the resources
3141 dbus_connection_free_preallocated_send (DBusConnection *connection,
3142 DBusPreallocatedSend *preallocated)
3144 _dbus_return_if_fail (connection != NULL);
3145 _dbus_return_if_fail (preallocated != NULL);
3146 _dbus_return_if_fail (connection == preallocated->connection);
3148 _dbus_list_free_link (preallocated->queue_link);
3149 _dbus_counter_unref (preallocated->counter_link->data);
3150 _dbus_list_free_link (preallocated->counter_link);
3151 dbus_free (preallocated);
3155 * Sends a message using preallocated resources. This function cannot fail.
3156 * It works identically to dbus_connection_send() in other respects.
3157 * Preallocated resources comes from dbus_connection_preallocate_send().
3158 * This function "consumes" the preallocated resources, they need not
3159 * be freed separately.
3161 * @param connection the connection
3162 * @param preallocated the preallocated resources
3163 * @param message the message to send
3164 * @param client_serial return location for client serial assigned to the message
3167 dbus_connection_send_preallocated (DBusConnection *connection,
3168 DBusPreallocatedSend *preallocated,
3169 DBusMessage *message,
3170 dbus_uint32_t *client_serial)
3172 _dbus_return_if_fail (connection != NULL);
3173 _dbus_return_if_fail (preallocated != NULL);
3174 _dbus_return_if_fail (message != NULL);
3175 _dbus_return_if_fail (preallocated->connection == connection);
3176 _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_METHOD_CALL ||
3177 dbus_message_get_member (message) != NULL);
3178 _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL ||
3179 (dbus_message_get_interface (message) != NULL &&
3180 dbus_message_get_member (message) != NULL));
3182 CONNECTION_LOCK (connection);
3184 #ifdef HAVE_UNIX_FD_PASSING
3186 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3187 message->n_unix_fds > 0)
3189 /* Refuse to send fds on a connection that cannot handle
3190 them. Unfortunately we cannot return a proper error here, so
3191 the best we can is just return. */
3192 CONNECTION_UNLOCK (connection);
3198 _dbus_connection_send_preallocated_and_unlock (connection,
3200 message, client_serial);
3204 _dbus_connection_send_unlocked_no_update (DBusConnection *connection,
3205 DBusMessage *message,
3206 dbus_uint32_t *client_serial)
3208 DBusPreallocatedSend *preallocated;
3210 _dbus_assert (connection != NULL);
3211 _dbus_assert (message != NULL);
3213 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
3214 if (preallocated == NULL)
3217 _dbus_connection_send_preallocated_unlocked_no_update (connection,
3225 * Adds a message to the outgoing message queue. Does not block to
3226 * write the message to the network; that happens asynchronously. To
3227 * force the message to be written, call dbus_connection_flush() however
3228 * it is not necessary to call dbus_connection_flush() by hand; the
3229 * message will be sent the next time the main loop is run.
3230 * dbus_connection_flush() should only be used, for example, if
3231 * the application was expected to exit before running the main loop.
3233 * Because this only queues the message, the only reason it can
3234 * fail is lack of memory. Even if the connection is disconnected,
3235 * no error will be returned. If the function fails due to lack of memory,
3236 * it returns #FALSE. The function will never fail for other reasons; even
3237 * if the connection is disconnected, you can queue an outgoing message,
3238 * though obviously it won't be sent.
3240 * The message serial is used by the remote application to send a
3241 * reply; see dbus_message_get_serial() or the D-Bus specification.
3243 * dbus_message_unref() can be called as soon as this method returns
3244 * as the message queue will hold its own ref until the message is sent.
3246 * @param connection the connection.
3247 * @param message the message to write.
3248 * @param serial return location for message serial, or #NULL if you don't care
3249 * @returns #TRUE on success.
3252 dbus_connection_send (DBusConnection *connection,
3253 DBusMessage *message,
3254 dbus_uint32_t *serial)
3256 _dbus_return_val_if_fail (connection != NULL, FALSE);
3257 _dbus_return_val_if_fail (message != NULL, FALSE);
3259 CONNECTION_LOCK (connection);
3261 #ifdef HAVE_UNIX_FD_PASSING
3263 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3264 message->n_unix_fds > 0)
3266 /* Refuse to send fds on a connection that cannot handle
3267 them. Unfortunately we cannot return a proper error here, so
3268 the best we can is just return. */
3269 CONNECTION_UNLOCK (connection);
3275 return _dbus_connection_send_and_unlock (connection,
3281 reply_handler_timeout (void *data)
3283 DBusConnection *connection;
3284 DBusDispatchStatus status;
3285 DBusPendingCall *pending = data;
3287 connection = _dbus_pending_call_get_connection_and_lock (pending);
3288 _dbus_connection_ref_unlocked (connection);
3290 _dbus_pending_call_queue_timeout_error_unlocked (pending,
3292 _dbus_connection_remove_timeout_unlocked (connection,
3293 _dbus_pending_call_get_timeout_unlocked (pending));
3294 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
3296 _dbus_verbose ("middle\n");
3297 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3299 /* Unlocks, and calls out to user code */
3300 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3301 dbus_connection_unref (connection);
3307 * Queues a message to send, as with dbus_connection_send(),
3308 * but also returns a #DBusPendingCall used to receive a reply to the
3309 * message. If no reply is received in the given timeout_milliseconds,
3310 * this function expires the pending reply and generates a synthetic
3311 * error reply (generated in-process, not by the remote application)
3312 * indicating that a timeout occurred.
3314 * A #DBusPendingCall will see a reply message before any filters or
3315 * registered object path handlers. See dbus_connection_dispatch() for
3316 * details on when handlers are run.
3318 * A #DBusPendingCall will always see exactly one reply message,
3319 * unless it's cancelled with dbus_pending_call_cancel().
3321 * If #NULL is passed for the pending_return, the #DBusPendingCall
3322 * will still be generated internally, and used to track
3323 * the message reply timeout. This means a timeout error will
3324 * occur if no reply arrives, unlike with dbus_connection_send().
3326 * If -1 is passed for the timeout, a sane default timeout is used. -1
3327 * is typically the best value for the timeout for this reason, unless
3328 * you want a very short or very long timeout. If #DBUS_TIMEOUT_INFINITE is
3329 * passed for the timeout, no timeout will be set and the call will block
3332 * @warning if the connection is disconnected or you try to send Unix
3333 * file descriptors on a connection that does not support them, the
3334 * #DBusPendingCall will be set to #NULL, so be careful with this.
3336 * @param connection the connection
3337 * @param message the message to send
3338 * @param pending_return return location for a #DBusPendingCall
3339 * object, or #NULL if connection is disconnected or when you try to
3340 * send Unix file descriptors on a connection that does not support
3342 * @param timeout_milliseconds timeout in milliseconds, -1 (or
3343 * #DBUS_TIMEOUT_USE_DEFAULT) for default or #DBUS_TIMEOUT_INFINITE for no
3345 * @returns #FALSE if no memory, #TRUE otherwise.
3349 dbus_connection_send_with_reply (DBusConnection *connection,
3350 DBusMessage *message,
3351 DBusPendingCall **pending_return,
3352 int timeout_milliseconds)
3354 DBusPendingCall *pending;
3355 dbus_int32_t serial = -1;
3356 DBusDispatchStatus status;
3358 _dbus_return_val_if_fail (connection != NULL, FALSE);
3359 _dbus_return_val_if_fail (message != NULL, FALSE);
3360 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3363 *pending_return = NULL;
3365 CONNECTION_LOCK (connection);
3367 #ifdef HAVE_UNIX_FD_PASSING
3369 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3370 message->n_unix_fds > 0)
3372 /* Refuse to send fds on a connection that cannot handle
3373 them. Unfortunately we cannot return a proper error here, so
3374 the best we can do is return TRUE but leave *pending_return
3376 CONNECTION_UNLOCK (connection);
3382 if (!_dbus_connection_get_is_connected_unlocked (connection))
3384 CONNECTION_UNLOCK (connection);
3389 pending = _dbus_pending_call_new_unlocked (connection,
3390 timeout_milliseconds,
3391 reply_handler_timeout);
3393 if (pending == NULL)
3395 CONNECTION_UNLOCK (connection);
3399 /* Assign a serial to the message */
3400 serial = dbus_message_get_serial (message);
3403 serial = _dbus_connection_get_next_client_serial (connection);
3404 dbus_message_set_serial (message, serial);
3407 if (!_dbus_pending_call_set_timeout_error_unlocked (pending, message, serial))
3410 /* Insert the serial in the pending replies hash;
3411 * hash takes a refcount on DBusPendingCall.
3412 * Also, add the timeout.
3414 if (!_dbus_connection_attach_pending_call_unlocked (connection,
3418 if (!_dbus_connection_send_unlocked_no_update (connection, message, NULL))
3420 _dbus_connection_detach_pending_call_and_unlock (connection,
3422 goto error_unlocked;
3426 *pending_return = pending; /* hand off refcount */
3429 _dbus_connection_detach_pending_call_unlocked (connection, pending);
3430 /* we still have a ref to the pending call in this case, we unref
3431 * after unlocking, below
3435 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3437 /* this calls out to user code */
3438 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3440 if (pending_return == NULL)
3441 dbus_pending_call_unref (pending);
3446 CONNECTION_UNLOCK (connection);
3448 dbus_pending_call_unref (pending);
3453 * Sends a message and blocks a certain time period while waiting for
3454 * a reply. This function does not reenter the main loop,
3455 * i.e. messages other than the reply are queued up but not
3456 * processed. This function is used to invoke method calls on a
3459 * If a normal reply is received, it is returned, and removed from the
3460 * incoming message queue. If it is not received, #NULL is returned
3461 * and the error is set to #DBUS_ERROR_NO_REPLY. If an error reply is
3462 * received, it is converted to a #DBusError and returned as an error,
3463 * then the reply message is deleted and #NULL is returned. If
3464 * something else goes wrong, result is set to whatever is
3465 * appropriate, such as #DBUS_ERROR_NO_MEMORY or
3466 * #DBUS_ERROR_DISCONNECTED.
3468 * @warning While this function blocks the calling thread will not be
3469 * processing the incoming message queue. This means you can end up
3470 * deadlocked if the application you're talking to needs you to reply
3471 * to a method. To solve this, either avoid the situation, block in a
3472 * separate thread from the main connection-dispatching thread, or use
3473 * dbus_pending_call_set_notify() to avoid blocking.
3475 * @param connection the connection
3476 * @param message the message to send
3477 * @param timeout_milliseconds timeout in milliseconds, -1 (or
3478 * #DBUS_TIMEOUT_USE_DEFAULT) for default or #DBUS_TIMEOUT_INFINITE for no
3480 * @param error return location for error message
3481 * @returns the message that is the reply or #NULL with an error code if the
3485 dbus_connection_send_with_reply_and_block (DBusConnection *connection,
3486 DBusMessage *message,
3487 int timeout_milliseconds,
3491 DBusPendingCall *pending;
3493 _dbus_return_val_if_fail (connection != NULL, NULL);
3494 _dbus_return_val_if_fail (message != NULL, NULL);
3495 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, NULL);
3496 _dbus_return_val_if_error_is_set (error, NULL);
3498 #ifdef HAVE_UNIX_FD_PASSING
3500 CONNECTION_LOCK (connection);
3501 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3502 message->n_unix_fds > 0)
3504 CONNECTION_UNLOCK (connection);
3505 dbus_set_error(error, DBUS_ERROR_FAILED, "Cannot send file descriptors on this connection.");
3508 CONNECTION_UNLOCK (connection);
3512 if (!dbus_connection_send_with_reply (connection, message,
3513 &pending, timeout_milliseconds))
3515 _DBUS_SET_OOM (error);
3519 if (pending == NULL)
3521 dbus_set_error (error, DBUS_ERROR_DISCONNECTED, "Connection is closed");
3525 dbus_pending_call_block (pending);
3527 reply = dbus_pending_call_steal_reply (pending);
3528 dbus_pending_call_unref (pending);
3530 /* call_complete_and_unlock() called from pending_call_block() should
3531 * always fill this in.
3533 _dbus_assert (reply != NULL);
3535 if (dbus_set_error_from_message (error, reply))
3537 dbus_message_unref (reply);
3545 * Blocks until the outgoing message queue is empty.
3546 * Assumes connection lock already held.
3548 * If you call this, you MUST call update_dispatch_status afterword...
3550 * @param connection the connection.
3552 static DBusDispatchStatus
3553 _dbus_connection_flush_unlocked (DBusConnection *connection)
3555 /* We have to specify DBUS_ITERATION_DO_READING here because
3556 * otherwise we could have two apps deadlock if they are both doing
3557 * a flush(), and the kernel buffers fill up. This could change the
3560 DBusDispatchStatus status;
3562 HAVE_LOCK_CHECK (connection);
3564 while (connection->n_outgoing > 0 &&
3565 _dbus_connection_get_is_connected_unlocked (connection))
3567 _dbus_verbose ("doing iteration in\n");
3568 HAVE_LOCK_CHECK (connection);
3569 _dbus_connection_do_iteration_unlocked (connection,
3571 DBUS_ITERATION_DO_READING |
3572 DBUS_ITERATION_DO_WRITING |
3573 DBUS_ITERATION_BLOCK,
3577 HAVE_LOCK_CHECK (connection);
3578 _dbus_verbose ("middle\n");
3579 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3581 HAVE_LOCK_CHECK (connection);
3586 * Blocks until the outgoing message queue is empty.
3588 * @param connection the connection.
3591 dbus_connection_flush (DBusConnection *connection)
3593 /* We have to specify DBUS_ITERATION_DO_READING here because
3594 * otherwise we could have two apps deadlock if they are both doing
3595 * a flush(), and the kernel buffers fill up. This could change the
3598 DBusDispatchStatus status;
3600 _dbus_return_if_fail (connection != NULL);
3602 CONNECTION_LOCK (connection);
3604 status = _dbus_connection_flush_unlocked (connection);
3606 HAVE_LOCK_CHECK (connection);
3607 /* Unlocks and calls out to user code */
3608 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3610 _dbus_verbose ("end\n");
3614 * This function implements dbus_connection_read_write_dispatch() and
3615 * dbus_connection_read_write() (they pass a different value for the
3616 * dispatch parameter).
3618 * @param connection the connection
3619 * @param timeout_milliseconds max time to block or -1 for infinite
3620 * @param dispatch dispatch new messages or leave them on the incoming queue
3621 * @returns #TRUE if the disconnect message has not been processed
3624 _dbus_connection_read_write_dispatch (DBusConnection *connection,
3625 int timeout_milliseconds,
3626 dbus_bool_t dispatch)
3628 DBusDispatchStatus dstatus;
3629 dbus_bool_t progress_possible;
3631 /* Need to grab a ref here in case we're a private connection and
3632 * the user drops the last ref in a handler we call; see bug
3633 * https://bugs.freedesktop.org/show_bug.cgi?id=15635
3635 dbus_connection_ref (connection);
3636 dstatus = dbus_connection_get_dispatch_status (connection);
3638 if (dispatch && dstatus == DBUS_DISPATCH_DATA_REMAINS)
3640 _dbus_verbose ("doing dispatch\n");
3641 dbus_connection_dispatch (connection);
3642 CONNECTION_LOCK (connection);
3644 else if (dstatus == DBUS_DISPATCH_NEED_MEMORY)
3646 _dbus_verbose ("pausing for memory\n");
3647 _dbus_memory_pause_based_on_timeout (timeout_milliseconds);
3648 CONNECTION_LOCK (connection);
3652 CONNECTION_LOCK (connection);
3653 if (_dbus_connection_get_is_connected_unlocked (connection))
3655 _dbus_verbose ("doing iteration\n");
3656 _dbus_connection_do_iteration_unlocked (connection,
3658 DBUS_ITERATION_DO_READING |
3659 DBUS_ITERATION_DO_WRITING |
3660 DBUS_ITERATION_BLOCK,
3661 timeout_milliseconds);
3665 HAVE_LOCK_CHECK (connection);
3666 /* If we can dispatch, we can make progress until the Disconnected message
3667 * has been processed; if we can only read/write, we can make progress
3668 * as long as the transport is open.
3671 progress_possible = connection->n_incoming != 0 ||
3672 connection->disconnect_message_link != NULL;
3674 progress_possible = _dbus_connection_get_is_connected_unlocked (connection);
3676 CONNECTION_UNLOCK (connection);
3678 dbus_connection_unref (connection);
3680 return progress_possible; /* TRUE if we can make more progress */
3685 * This function is intended for use with applications that don't want
3686 * to write a main loop and deal with #DBusWatch and #DBusTimeout. An
3687 * example usage would be:
3690 * while (dbus_connection_read_write_dispatch (connection, -1))
3691 * ; // empty loop body
3694 * In this usage you would normally have set up a filter function to look
3695 * at each message as it is dispatched. The loop terminates when the last
3696 * message from the connection (the disconnected signal) is processed.
3698 * If there are messages to dispatch, this function will
3699 * dbus_connection_dispatch() once, and return. If there are no
3700 * messages to dispatch, this function will block until it can read or
3701 * write, then read or write, then return.
3703 * The way to think of this function is that it either makes some sort
3704 * of progress, or it blocks. Note that, while it is blocked on I/O, it
3705 * cannot be interrupted (even by other threads), which makes this function
3706 * unsuitable for applications that do more than just react to received
3709 * The return value indicates whether the disconnect message has been
3710 * processed, NOT whether the connection is connected. This is
3711 * important because even after disconnecting, you want to process any
3712 * messages you received prior to the disconnect.
3714 * @param connection the connection
3715 * @param timeout_milliseconds max time to block or -1 for infinite
3716 * @returns #TRUE if the disconnect message has not been processed
3719 dbus_connection_read_write_dispatch (DBusConnection *connection,
3720 int timeout_milliseconds)
3722 _dbus_return_val_if_fail (connection != NULL, FALSE);
3723 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3724 return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, TRUE);
3728 * This function is intended for use with applications that don't want to
3729 * write a main loop and deal with #DBusWatch and #DBusTimeout. See also
3730 * dbus_connection_read_write_dispatch().
3732 * As long as the connection is open, this function will block until it can
3733 * read or write, then read or write, then return #TRUE.
3735 * If the connection is closed, the function returns #FALSE.
3737 * The return value indicates whether reading or writing is still
3738 * possible, i.e. whether the connection is connected.
3740 * Note that even after disconnection, messages may remain in the
3741 * incoming queue that need to be
3742 * processed. dbus_connection_read_write_dispatch() dispatches
3743 * incoming messages for you; with dbus_connection_read_write() you
3744 * have to arrange to drain the incoming queue yourself.
3746 * @param connection the connection
3747 * @param timeout_milliseconds max time to block or -1 for infinite
3748 * @returns #TRUE if still connected
3751 dbus_connection_read_write (DBusConnection *connection,
3752 int timeout_milliseconds)
3754 _dbus_return_val_if_fail (connection != NULL, FALSE);
3755 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3756 return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, FALSE);
3759 /* We need to call this anytime we pop the head of the queue, and then
3760 * update_dispatch_status_and_unlock needs to be called afterward
3761 * which will "process" the disconnected message and set
3762 * disconnected_message_processed.
3765 check_disconnected_message_arrived_unlocked (DBusConnection *connection,
3766 DBusMessage *head_of_queue)
3768 HAVE_LOCK_CHECK (connection);
3770 /* checking that the link is NULL is an optimization to avoid the is_signal call */
3771 if (connection->disconnect_message_link == NULL &&
3772 dbus_message_is_signal (head_of_queue,
3773 DBUS_INTERFACE_LOCAL,
3776 connection->disconnected_message_arrived = TRUE;
3781 * Returns the first-received message from the incoming message queue,
3782 * leaving it in the queue. If the queue is empty, returns #NULL.
3784 * The caller does not own a reference to the returned message, and
3785 * must either return it using dbus_connection_return_message() or
3786 * keep it after calling dbus_connection_steal_borrowed_message(). No
3787 * one can get at the message while its borrowed, so return it as
3788 * quickly as possible and don't keep a reference to it after
3789 * returning it. If you need to keep the message, make a copy of it.
3791 * dbus_connection_dispatch() will block if called while a borrowed
3792 * message is outstanding; only one piece of code can be playing with
3793 * the incoming queue at a time. This function will block if called
3794 * during a dbus_connection_dispatch().
3796 * @param connection the connection.
3797 * @returns next message in the incoming queue.
3800 dbus_connection_borrow_message (DBusConnection *connection)
3802 DBusDispatchStatus status;
3803 DBusMessage *message;
3805 _dbus_return_val_if_fail (connection != NULL, NULL);
3807 _dbus_verbose ("start\n");
3809 /* this is called for the side effect that it queues
3810 * up any messages from the transport
3812 status = dbus_connection_get_dispatch_status (connection);
3813 if (status != DBUS_DISPATCH_DATA_REMAINS)
3816 CONNECTION_LOCK (connection);
3818 _dbus_connection_acquire_dispatch (connection);
3820 /* While a message is outstanding, the dispatch lock is held */
3821 _dbus_assert (connection->message_borrowed == NULL);
3823 connection->message_borrowed = _dbus_list_get_first (&connection->incoming_messages);
3825 message = connection->message_borrowed;
3827 check_disconnected_message_arrived_unlocked (connection, message);
3829 /* Note that we KEEP the dispatch lock until the message is returned */
3830 if (message == NULL)
3831 _dbus_connection_release_dispatch (connection);
3833 CONNECTION_UNLOCK (connection);
3835 /* We don't update dispatch status until it's returned or stolen */
3841 * Used to return a message after peeking at it using
3842 * dbus_connection_borrow_message(). Only called if
3843 * message from dbus_connection_borrow_message() was non-#NULL.
3845 * @param connection the connection
3846 * @param message the message from dbus_connection_borrow_message()
3849 dbus_connection_return_message (DBusConnection *connection,
3850 DBusMessage *message)
3852 DBusDispatchStatus status;
3854 _dbus_return_if_fail (connection != NULL);
3855 _dbus_return_if_fail (message != NULL);
3856 _dbus_return_if_fail (message == connection->message_borrowed);
3857 _dbus_return_if_fail (connection->dispatch_acquired);
3859 CONNECTION_LOCK (connection);
3861 _dbus_assert (message == connection->message_borrowed);
3863 connection->message_borrowed = NULL;
3865 _dbus_connection_release_dispatch (connection);
3867 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3868 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3872 * Used to keep a message after peeking at it using
3873 * dbus_connection_borrow_message(). Before using this function, see
3874 * the caveats/warnings in the documentation for
3875 * dbus_connection_pop_message().
3877 * @param connection the connection
3878 * @param message the message from dbus_connection_borrow_message()
3881 dbus_connection_steal_borrowed_message (DBusConnection *connection,
3882 DBusMessage *message)
3884 DBusMessage *pop_message;
3885 DBusDispatchStatus status;
3887 _dbus_return_if_fail (connection != NULL);
3888 _dbus_return_if_fail (message != NULL);
3889 _dbus_return_if_fail (message == connection->message_borrowed);
3890 _dbus_return_if_fail (connection->dispatch_acquired);
3892 CONNECTION_LOCK (connection);
3894 _dbus_assert (message == connection->message_borrowed);
3896 pop_message = _dbus_list_pop_first (&connection->incoming_messages);
3897 _dbus_assert (message == pop_message);
3899 connection->n_incoming -= 1;
3901 _dbus_verbose ("Incoming message %p stolen from queue, %d incoming\n",
3902 message, connection->n_incoming);
3904 connection->message_borrowed = NULL;
3906 _dbus_connection_release_dispatch (connection);
3908 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3909 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3912 /* See dbus_connection_pop_message, but requires the caller to own
3913 * the lock before calling. May drop the lock while running.
3916 _dbus_connection_pop_message_link_unlocked (DBusConnection *connection)
3918 HAVE_LOCK_CHECK (connection);
3920 _dbus_assert (connection->message_borrowed == NULL);
3922 if (connection->n_incoming > 0)
3926 link = _dbus_list_pop_first_link (&connection->incoming_messages);
3927 connection->n_incoming -= 1;
3929 _dbus_verbose ("Message %p (%s %s %s %s '%s') removed from incoming queue %p, %d incoming\n",
3931 dbus_message_type_to_string (dbus_message_get_type (link->data)),
3932 dbus_message_get_path (link->data) ?
3933 dbus_message_get_path (link->data) :
3935 dbus_message_get_interface (link->data) ?
3936 dbus_message_get_interface (link->data) :
3938 dbus_message_get_member (link->data) ?
3939 dbus_message_get_member (link->data) :
3941 dbus_message_get_signature (link->data),
3942 connection, connection->n_incoming);
3944 check_disconnected_message_arrived_unlocked (connection, link->data);
3952 /* See dbus_connection_pop_message, but requires the caller to own
3953 * the lock before calling. May drop the lock while running.
3956 _dbus_connection_pop_message_unlocked (DBusConnection *connection)
3960 HAVE_LOCK_CHECK (connection);
3962 link = _dbus_connection_pop_message_link_unlocked (connection);
3966 DBusMessage *message;
3968 message = link->data;
3970 _dbus_list_free_link (link);
3979 _dbus_connection_putback_message_link_unlocked (DBusConnection *connection,
3980 DBusList *message_link)
3982 HAVE_LOCK_CHECK (connection);
3984 _dbus_assert (message_link != NULL);
3985 /* You can't borrow a message while a link is outstanding */
3986 _dbus_assert (connection->message_borrowed == NULL);
3987 /* We had to have the dispatch lock across the pop/putback */
3988 _dbus_assert (connection->dispatch_acquired);
3990 _dbus_list_prepend_link (&connection->incoming_messages,
3992 connection->n_incoming += 1;
3994 _dbus_verbose ("Message %p (%s %s %s '%s') put back into queue %p, %d incoming\n",
3996 dbus_message_type_to_string (dbus_message_get_type (message_link->data)),
3997 dbus_message_get_interface (message_link->data) ?
3998 dbus_message_get_interface (message_link->data) :
4000 dbus_message_get_member (message_link->data) ?
4001 dbus_message_get_member (message_link->data) :
4003 dbus_message_get_signature (message_link->data),
4004 connection, connection->n_incoming);
4008 * Returns the first-received message from the incoming message queue,
4009 * removing it from the queue. The caller owns a reference to the
4010 * returned message. If the queue is empty, returns #NULL.
4012 * This function bypasses any message handlers that are registered,
4013 * and so using it is usually wrong. Instead, let the main loop invoke
4014 * dbus_connection_dispatch(). Popping messages manually is only
4015 * useful in very simple programs that don't share a #DBusConnection
4016 * with any libraries or other modules.
4018 * There is a lock that covers all ways of accessing the incoming message
4019 * queue, so dbus_connection_dispatch(), dbus_connection_pop_message(),
4020 * dbus_connection_borrow_message(), etc. will all block while one of the others
4021 * in the group is running.
4023 * @param connection the connection.
4024 * @returns next message in the incoming queue.
4027 dbus_connection_pop_message (DBusConnection *connection)
4029 DBusMessage *message;
4030 DBusDispatchStatus status;
4032 _dbus_verbose ("start\n");
4034 /* this is called for the side effect that it queues
4035 * up any messages from the transport
4037 status = dbus_connection_get_dispatch_status (connection);
4038 if (status != DBUS_DISPATCH_DATA_REMAINS)
4041 CONNECTION_LOCK (connection);
4042 _dbus_connection_acquire_dispatch (connection);
4043 HAVE_LOCK_CHECK (connection);
4045 message = _dbus_connection_pop_message_unlocked (connection);
4047 _dbus_verbose ("Returning popped message %p\n", message);
4049 _dbus_connection_release_dispatch (connection);
4051 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4052 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4058 * Acquire the dispatcher. This is a separate lock so the main
4059 * connection lock can be dropped to call out to application dispatch
4062 * @param connection the connection.
4065 _dbus_connection_acquire_dispatch (DBusConnection *connection)
4067 HAVE_LOCK_CHECK (connection);
4069 _dbus_connection_ref_unlocked (connection);
4070 CONNECTION_UNLOCK (connection);
4072 _dbus_verbose ("locking dispatch_mutex\n");
4073 _dbus_mutex_lock (connection->dispatch_mutex);
4075 while (connection->dispatch_acquired)
4077 _dbus_verbose ("waiting for dispatch to be acquirable\n");
4078 _dbus_condvar_wait (connection->dispatch_cond,
4079 connection->dispatch_mutex);
4082 _dbus_assert (!connection->dispatch_acquired);
4084 connection->dispatch_acquired = TRUE;
4086 _dbus_verbose ("unlocking dispatch_mutex\n");
4087 _dbus_mutex_unlock (connection->dispatch_mutex);
4089 CONNECTION_LOCK (connection);
4090 _dbus_connection_unref_unlocked (connection);
4094 * Release the dispatcher when you're done with it. Only call
4095 * after you've acquired the dispatcher. Wakes up at most one
4096 * thread currently waiting to acquire the dispatcher.
4098 * @param connection the connection.
4101 _dbus_connection_release_dispatch (DBusConnection *connection)
4103 HAVE_LOCK_CHECK (connection);
4105 _dbus_verbose ("locking dispatch_mutex\n");
4106 _dbus_mutex_lock (connection->dispatch_mutex);
4108 _dbus_assert (connection->dispatch_acquired);
4110 connection->dispatch_acquired = FALSE;
4111 _dbus_condvar_wake_one (connection->dispatch_cond);
4113 _dbus_verbose ("unlocking dispatch_mutex\n");
4114 _dbus_mutex_unlock (connection->dispatch_mutex);
4118 _dbus_connection_failed_pop (DBusConnection *connection,
4119 DBusList *message_link)
4121 _dbus_list_prepend_link (&connection->incoming_messages,
4123 connection->n_incoming += 1;
4126 /* Note this may be called multiple times since we don't track whether we already did it */
4128 notify_disconnected_unlocked (DBusConnection *connection)
4130 HAVE_LOCK_CHECK (connection);
4132 /* Set the weakref in dbus-bus.c to NULL, so nobody will get a disconnected
4133 * connection from dbus_bus_get(). We make the same guarantee for
4134 * dbus_connection_open() but in a different way since we don't want to
4135 * unref right here; we instead check for connectedness before returning
4136 * the connection from the hash.
4138 _dbus_bus_notify_shared_connection_disconnected_unlocked (connection);
4140 /* Dump the outgoing queue, we aren't going to be able to
4141 * send it now, and we'd like accessors like
4142 * dbus_connection_get_outgoing_size() to be accurate.
4144 if (connection->n_outgoing > 0)
4148 _dbus_verbose ("Dropping %d outgoing messages since we're disconnected\n",
4149 connection->n_outgoing);
4151 while ((link = _dbus_list_get_last_link (&connection->outgoing_messages)))
4153 _dbus_connection_message_sent_unlocked (connection, link->data);
4158 /* Note this may be called multiple times since we don't track whether we already did it */
4159 static DBusDispatchStatus
4160 notify_disconnected_and_dispatch_complete_unlocked (DBusConnection *connection)
4162 HAVE_LOCK_CHECK (connection);
4164 if (connection->disconnect_message_link != NULL)
4166 _dbus_verbose ("Sending disconnect message\n");
4168 /* If we have pending calls, queue their timeouts - we want the Disconnected
4169 * to be the last message, after these timeouts.
4171 connection_timeout_and_complete_all_pending_calls_unlocked (connection);
4173 /* We haven't sent the disconnect message already,
4174 * and all real messages have been queued up.
4176 _dbus_connection_queue_synthesized_message_link (connection,
4177 connection->disconnect_message_link);
4178 connection->disconnect_message_link = NULL;
4180 return DBUS_DISPATCH_DATA_REMAINS;
4183 return DBUS_DISPATCH_COMPLETE;
4186 static DBusDispatchStatus
4187 _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection)
4189 HAVE_LOCK_CHECK (connection);
4191 if (connection->n_incoming > 0)
4192 return DBUS_DISPATCH_DATA_REMAINS;
4193 else if (!_dbus_transport_queue_messages (connection->transport))
4194 return DBUS_DISPATCH_NEED_MEMORY;
4197 DBusDispatchStatus status;
4198 dbus_bool_t is_connected;
4200 status = _dbus_transport_get_dispatch_status (connection->transport);
4201 is_connected = _dbus_transport_get_is_connected (connection->transport);
4203 _dbus_verbose ("dispatch status = %s is_connected = %d\n",
4204 DISPATCH_STATUS_NAME (status), is_connected);
4208 /* It's possible this would be better done by having an explicit
4209 * notification from _dbus_transport_disconnect() that would
4210 * synchronously do this, instead of waiting for the next dispatch
4211 * status check. However, probably not good to change until it causes
4214 notify_disconnected_unlocked (connection);
4216 /* I'm not sure this is needed; the idea is that we want to
4217 * queue the Disconnected only after we've read all the
4218 * messages, but if we're disconnected maybe we are guaranteed
4219 * to have read them all ?
4221 if (status == DBUS_DISPATCH_COMPLETE)
4222 status = notify_disconnected_and_dispatch_complete_unlocked (connection);
4225 if (status != DBUS_DISPATCH_COMPLETE)
4227 else if (connection->n_incoming > 0)
4228 return DBUS_DISPATCH_DATA_REMAINS;
4230 return DBUS_DISPATCH_COMPLETE;
4235 _dbus_connection_update_dispatch_status_and_unlock (DBusConnection *connection,
4236 DBusDispatchStatus new_status)
4238 dbus_bool_t changed;
4239 DBusDispatchStatusFunction function;
4242 HAVE_LOCK_CHECK (connection);
4244 _dbus_connection_ref_unlocked (connection);
4246 changed = new_status != connection->last_dispatch_status;
4248 connection->last_dispatch_status = new_status;
4250 function = connection->dispatch_status_function;
4251 data = connection->dispatch_status_data;
4253 if (connection->disconnected_message_arrived &&
4254 !connection->disconnected_message_processed)
4256 connection->disconnected_message_processed = TRUE;
4258 /* this does an unref, but we have a ref
4259 * so we should not run the finalizer here
4262 connection_forget_shared_unlocked (connection);
4264 if (connection->exit_on_disconnect)
4266 CONNECTION_UNLOCK (connection);
4268 _dbus_verbose ("Exiting on Disconnected signal\n");
4270 _dbus_assert_not_reached ("Call to exit() returned");
4274 /* We drop the lock */
4275 CONNECTION_UNLOCK (connection);
4277 if (changed && function)
4279 _dbus_verbose ("Notifying of change to dispatch status of %p now %d (%s)\n",
4280 connection, new_status,
4281 DISPATCH_STATUS_NAME (new_status));
4282 (* function) (connection, new_status, data);
4285 dbus_connection_unref (connection);
4289 * Gets the current state of the incoming message queue.
4290 * #DBUS_DISPATCH_DATA_REMAINS indicates that the message queue
4291 * may contain messages. #DBUS_DISPATCH_COMPLETE indicates that the
4292 * incoming queue is empty. #DBUS_DISPATCH_NEED_MEMORY indicates that
4293 * there could be data, but we can't know for sure without more
4296 * To process the incoming message queue, use dbus_connection_dispatch()
4297 * or (in rare cases) dbus_connection_pop_message().
4299 * Note, #DBUS_DISPATCH_DATA_REMAINS really means that either we
4300 * have messages in the queue, or we have raw bytes buffered up
4301 * that need to be parsed. When these bytes are parsed, they
4302 * may not add up to an entire message. Thus, it's possible
4303 * to see a status of #DBUS_DISPATCH_DATA_REMAINS but not
4304 * have a message yet.
4306 * In particular this happens on initial connection, because all sorts
4307 * of authentication protocol stuff has to be parsed before the
4308 * first message arrives.
4310 * @param connection the connection.
4311 * @returns current dispatch status
4314 dbus_connection_get_dispatch_status (DBusConnection *connection)
4316 DBusDispatchStatus status;
4318 _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
4320 _dbus_verbose ("start\n");
4322 CONNECTION_LOCK (connection);
4324 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4326 CONNECTION_UNLOCK (connection);
4332 * Filter funtion for handling the Peer standard interface.
4334 static DBusHandlerResult
4335 _dbus_connection_peer_filter_unlocked_no_update (DBusConnection *connection,
4336 DBusMessage *message)
4338 if (connection->route_peer_messages && dbus_message_get_destination (message) != NULL)
4340 /* This means we're letting the bus route this message */
4341 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4343 else if (dbus_message_is_method_call (message,
4344 DBUS_INTERFACE_PEER,
4350 ret = dbus_message_new_method_return (message);
4352 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4354 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4356 dbus_message_unref (ret);
4359 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4361 return DBUS_HANDLER_RESULT_HANDLED;
4363 else if (dbus_message_is_method_call (message,
4364 DBUS_INTERFACE_PEER,
4371 ret = dbus_message_new_method_return (message);
4373 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4376 _dbus_string_init (&uuid);
4377 if (_dbus_get_local_machine_uuid_encoded (&uuid))
4379 const char *v_STRING = _dbus_string_get_const_data (&uuid);
4380 if (dbus_message_append_args (ret,
4381 DBUS_TYPE_STRING, &v_STRING,
4384 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4387 _dbus_string_free (&uuid);
4389 dbus_message_unref (ret);
4392 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4394 return DBUS_HANDLER_RESULT_HANDLED;
4396 else if (dbus_message_has_interface (message, DBUS_INTERFACE_PEER))
4398 /* We need to bounce anything else with this interface, otherwise apps
4399 * could start extending the interface and when we added extensions
4400 * here to DBusConnection we'd break those apps.
4406 ret = dbus_message_new_error (message,
4407 DBUS_ERROR_UNKNOWN_METHOD,
4408 "Unknown method invoked on org.freedesktop.DBus.Peer interface");
4410 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4412 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4414 dbus_message_unref (ret);
4417 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4419 return DBUS_HANDLER_RESULT_HANDLED;
4423 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4428 * Processes all builtin filter functions
4430 * If the spec specifies a standard interface
4431 * they should be processed from this method
4433 static DBusHandlerResult
4434 _dbus_connection_run_builtin_filters_unlocked_no_update (DBusConnection *connection,
4435 DBusMessage *message)
4437 /* We just run one filter for now but have the option to run more
4438 if the spec calls for it in the future */
4440 return _dbus_connection_peer_filter_unlocked_no_update (connection, message);
4444 * Processes any incoming data.
4446 * If there's incoming raw data that has not yet been parsed, it is
4447 * parsed, which may or may not result in adding messages to the
4450 * The incoming data buffer is filled when the connection reads from
4451 * its underlying transport (such as a socket). Reading usually
4452 * happens in dbus_watch_handle() or dbus_connection_read_write().
4454 * If there are complete messages in the incoming queue,
4455 * dbus_connection_dispatch() removes one message from the queue and
4456 * processes it. Processing has three steps.
4458 * First, any method replies are passed to #DBusPendingCall or
4459 * dbus_connection_send_with_reply_and_block() in order to
4460 * complete the pending method call.
4462 * Second, any filters registered with dbus_connection_add_filter()
4463 * are run. If any filter returns #DBUS_HANDLER_RESULT_HANDLED
4464 * then processing stops after that filter.
4466 * Third, if the message is a method call it is forwarded to
4467 * any registered object path handlers added with
4468 * dbus_connection_register_object_path() or
4469 * dbus_connection_register_fallback().
4471 * A single call to dbus_connection_dispatch() will process at most
4472 * one message; it will not clear the entire message queue.
4474 * Be careful about calling dbus_connection_dispatch() from inside a
4475 * message handler, i.e. calling dbus_connection_dispatch()
4476 * recursively. If threads have been initialized with a recursive
4477 * mutex function, then this will not deadlock; however, it can
4478 * certainly confuse your application.
4480 * @todo some FIXME in here about handling DBUS_HANDLER_RESULT_NEED_MEMORY
4482 * @param connection the connection
4483 * @returns dispatch status, see dbus_connection_get_dispatch_status()
4486 dbus_connection_dispatch (DBusConnection *connection)
4488 DBusMessage *message;
4489 DBusList *link, *filter_list_copy, *message_link;
4490 DBusHandlerResult result;
4491 DBusPendingCall *pending;
4492 dbus_int32_t reply_serial;
4493 DBusDispatchStatus status;
4494 dbus_bool_t found_object;
4496 _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
4498 _dbus_verbose ("\n");
4500 CONNECTION_LOCK (connection);
4501 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4502 if (status != DBUS_DISPATCH_DATA_REMAINS)
4504 /* unlocks and calls out to user code */
4505 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4509 /* We need to ref the connection since the callback could potentially
4510 * drop the last ref to it
4512 _dbus_connection_ref_unlocked (connection);
4514 _dbus_connection_acquire_dispatch (connection);
4515 HAVE_LOCK_CHECK (connection);
4517 message_link = _dbus_connection_pop_message_link_unlocked (connection);
4518 if (message_link == NULL)
4520 /* another thread dispatched our stuff */
4522 _dbus_verbose ("another thread dispatched message (during acquire_dispatch above)\n");
4524 _dbus_connection_release_dispatch (connection);
4526 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4528 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4530 dbus_connection_unref (connection);
4535 message = message_link->data;
4537 _dbus_verbose (" dispatching message %p (%s %s %s '%s')\n",
4539 dbus_message_type_to_string (dbus_message_get_type (message)),
4540 dbus_message_get_interface (message) ?
4541 dbus_message_get_interface (message) :
4543 dbus_message_get_member (message) ?
4544 dbus_message_get_member (message) :
4546 dbus_message_get_signature (message));
4548 result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4550 /* Pending call handling must be first, because if you do
4551 * dbus_connection_send_with_reply_and_block() or
4552 * dbus_pending_call_block() then no handlers/filters will be run on
4553 * the reply. We want consistent semantics in the case where we
4554 * dbus_connection_dispatch() the reply.
4557 reply_serial = dbus_message_get_reply_serial (message);
4558 pending = _dbus_hash_table_lookup_int (connection->pending_replies,
4562 _dbus_verbose ("Dispatching a pending reply\n");
4563 complete_pending_call_and_unlock (connection, pending, message);
4564 pending = NULL; /* it's probably unref'd */
4566 CONNECTION_LOCK (connection);
4567 _dbus_verbose ("pending call completed in dispatch\n");
4568 result = DBUS_HANDLER_RESULT_HANDLED;
4572 result = _dbus_connection_run_builtin_filters_unlocked_no_update (connection, message);
4573 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4576 if (!_dbus_list_copy (&connection->filter_list, &filter_list_copy))
4578 _dbus_connection_release_dispatch (connection);
4579 HAVE_LOCK_CHECK (connection);
4581 _dbus_connection_failed_pop (connection, message_link);
4583 /* unlocks and calls user code */
4584 _dbus_connection_update_dispatch_status_and_unlock (connection,
4585 DBUS_DISPATCH_NEED_MEMORY);
4586 dbus_connection_unref (connection);
4588 return DBUS_DISPATCH_NEED_MEMORY;
4591 _dbus_list_foreach (&filter_list_copy,
4592 (DBusForeachFunction)_dbus_message_filter_ref,
4595 /* We're still protected from dispatch() reentrancy here
4596 * since we acquired the dispatcher
4598 CONNECTION_UNLOCK (connection);
4600 link = _dbus_list_get_first_link (&filter_list_copy);
4601 while (link != NULL)
4603 DBusMessageFilter *filter = link->data;
4604 DBusList *next = _dbus_list_get_next_link (&filter_list_copy, link);
4606 if (filter->function == NULL)
4608 _dbus_verbose (" filter was removed in a callback function\n");
4613 _dbus_verbose (" running filter on message %p\n", message);
4614 result = (* filter->function) (connection, message, filter->user_data);
4616 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4622 _dbus_list_foreach (&filter_list_copy,
4623 (DBusForeachFunction)_dbus_message_filter_unref,
4625 _dbus_list_clear (&filter_list_copy);
4627 CONNECTION_LOCK (connection);
4629 if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
4631 _dbus_verbose ("No memory\n");
4634 else if (result == DBUS_HANDLER_RESULT_HANDLED)
4636 _dbus_verbose ("filter handled message in dispatch\n");
4640 /* We're still protected from dispatch() reentrancy here
4641 * since we acquired the dispatcher
4643 _dbus_verbose (" running object path dispatch on message %p (%s %s %s '%s')\n",
4645 dbus_message_type_to_string (dbus_message_get_type (message)),
4646 dbus_message_get_interface (message) ?
4647 dbus_message_get_interface (message) :
4649 dbus_message_get_member (message) ?
4650 dbus_message_get_member (message) :
4652 dbus_message_get_signature (message));
4654 HAVE_LOCK_CHECK (connection);
4655 result = _dbus_object_tree_dispatch_and_unlock (connection->objects,
4659 CONNECTION_LOCK (connection);
4661 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4663 _dbus_verbose ("object tree handled message in dispatch\n");
4667 if (dbus_message_get_type (message) == DBUS_MESSAGE_TYPE_METHOD_CALL)
4671 DBusPreallocatedSend *preallocated;
4673 _dbus_verbose (" sending error %s\n",
4674 DBUS_ERROR_UNKNOWN_METHOD);
4676 if (!_dbus_string_init (&str))
4678 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4679 _dbus_verbose ("no memory for error string in dispatch\n");
4683 if (!_dbus_string_append_printf (&str,
4684 "Method \"%s\" with signature \"%s\" on interface \"%s\" doesn't exist\n",
4685 dbus_message_get_member (message),
4686 dbus_message_get_signature (message),
4687 dbus_message_get_interface (message)))
4689 _dbus_string_free (&str);
4690 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4691 _dbus_verbose ("no memory for error string in dispatch\n");
4695 reply = dbus_message_new_error (message,
4696 found_object ? DBUS_ERROR_UNKNOWN_METHOD : DBUS_ERROR_UNKNOWN_OBJECT,
4697 _dbus_string_get_const_data (&str));
4698 _dbus_string_free (&str);
4702 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4703 _dbus_verbose ("no memory for error reply in dispatch\n");
4707 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
4709 if (preallocated == NULL)
4711 /* It's OK that this is finalized, because it hasn't been seen by
4712 * anything that could attach user callbacks */
4713 dbus_message_unref (reply);
4714 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4715 _dbus_verbose ("no memory for error send in dispatch\n");
4719 _dbus_connection_send_preallocated_unlocked_no_update (connection, preallocated,
4722 dbus_message_unref (reply);
4724 result = DBUS_HANDLER_RESULT_HANDLED;
4727 _dbus_verbose (" done dispatching %p (%s %s %s '%s') on connection %p\n", message,
4728 dbus_message_type_to_string (dbus_message_get_type (message)),
4729 dbus_message_get_interface (message) ?
4730 dbus_message_get_interface (message) :
4732 dbus_message_get_member (message) ?
4733 dbus_message_get_member (message) :
4735 dbus_message_get_signature (message),
4739 if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
4741 _dbus_verbose ("out of memory\n");
4743 /* Put message back, and we'll start over.
4744 * Yes this means handlers must be idempotent if they
4745 * don't return HANDLED; c'est la vie.
4747 _dbus_connection_putback_message_link_unlocked (connection,
4752 _dbus_verbose (" ... done dispatching\n");
4754 _dbus_list_free_link (message_link);
4755 dbus_message_unref (message); /* don't want the message to count in max message limits
4756 * in computing dispatch status below
4760 _dbus_connection_release_dispatch (connection);
4761 HAVE_LOCK_CHECK (connection);
4763 _dbus_verbose ("before final status update\n");
4764 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4766 /* unlocks and calls user code */
4767 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4769 dbus_connection_unref (connection);
4775 * Sets the watch functions for the connection. These functions are
4776 * responsible for making the application's main loop aware of file
4777 * descriptors that need to be monitored for events, using select() or
4778 * poll(). When using Qt, typically the DBusAddWatchFunction would
4779 * create a QSocketNotifier. When using GLib, the DBusAddWatchFunction
4780 * could call g_io_add_watch(), or could be used as part of a more
4781 * elaborate GSource. Note that when a watch is added, it may
4784 * The DBusWatchToggledFunction notifies the application that the
4785 * watch has been enabled or disabled. Call dbus_watch_get_enabled()
4786 * to check this. A disabled watch should have no effect, and enabled
4787 * watch should be added to the main loop. This feature is used
4788 * instead of simply adding/removing the watch because
4789 * enabling/disabling can be done without memory allocation. The
4790 * toggled function may be NULL if a main loop re-queries
4791 * dbus_watch_get_enabled() every time anyway.
4793 * The DBusWatch can be queried for the file descriptor to watch using
4794 * dbus_watch_get_unix_fd() or dbus_watch_get_socket(), and for the
4795 * events to watch for using dbus_watch_get_flags(). The flags
4796 * returned by dbus_watch_get_flags() will only contain
4797 * DBUS_WATCH_READABLE and DBUS_WATCH_WRITABLE, never
4798 * DBUS_WATCH_HANGUP or DBUS_WATCH_ERROR; all watches implicitly
4799 * include a watch for hangups, errors, and other exceptional
4802 * Once a file descriptor becomes readable or writable, or an exception
4803 * occurs, dbus_watch_handle() should be called to
4804 * notify the connection of the file descriptor's condition.
4806 * dbus_watch_handle() cannot be called during the
4807 * DBusAddWatchFunction, as the connection will not be ready to handle
4810 * It is not allowed to reference a DBusWatch after it has been passed
4811 * to remove_function.
4813 * If #FALSE is returned due to lack of memory, the failure may be due
4814 * to a #FALSE return from the new add_function. If so, the
4815 * add_function may have been called successfully one or more times,
4816 * but the remove_function will also have been called to remove any
4817 * successful adds. i.e. if #FALSE is returned the net result
4818 * should be that dbus_connection_set_watch_functions() has no effect,
4819 * but the add_function and remove_function may have been called.
4821 * @note The thread lock on DBusConnection is held while
4822 * watch functions are invoked, so inside these functions you
4823 * may not invoke any methods on DBusConnection or it will deadlock.
4824 * See the comments in the code or http://lists.freedesktop.org/archives/dbus/2007-July/tread.html#8144
4825 * if you encounter this issue and want to attempt writing a patch.
4827 * @param connection the connection.
4828 * @param add_function function to begin monitoring a new descriptor.
4829 * @param remove_function function to stop monitoring a descriptor.
4830 * @param toggled_function function to notify of enable/disable
4831 * @param data data to pass to add_function and remove_function.
4832 * @param free_data_function function to be called to free the data.
4833 * @returns #FALSE on failure (no memory)
4836 dbus_connection_set_watch_functions (DBusConnection *connection,
4837 DBusAddWatchFunction add_function,
4838 DBusRemoveWatchFunction remove_function,
4839 DBusWatchToggledFunction toggled_function,
4841 DBusFreeFunction free_data_function)
4845 _dbus_return_val_if_fail (connection != NULL, FALSE);
4847 CONNECTION_LOCK (connection);
4849 retval = _dbus_watch_list_set_functions (connection->watches,
4850 add_function, remove_function,
4852 data, free_data_function);
4854 CONNECTION_UNLOCK (connection);
4860 * Sets the timeout functions for the connection. These functions are
4861 * responsible for making the application's main loop aware of timeouts.
4862 * When using Qt, typically the DBusAddTimeoutFunction would create a
4863 * QTimer. When using GLib, the DBusAddTimeoutFunction would call
4866 * The DBusTimeoutToggledFunction notifies the application that the
4867 * timeout has been enabled or disabled. Call
4868 * dbus_timeout_get_enabled() to check this. A disabled timeout should
4869 * have no effect, and enabled timeout should be added to the main
4870 * loop. This feature is used instead of simply adding/removing the
4871 * timeout because enabling/disabling can be done without memory
4872 * allocation. With Qt, QTimer::start() and QTimer::stop() can be used
4873 * to enable and disable. The toggled function may be NULL if a main
4874 * loop re-queries dbus_timeout_get_enabled() every time anyway.
4875 * Whenever a timeout is toggled, its interval may change.
4877 * The DBusTimeout can be queried for the timer interval using
4878 * dbus_timeout_get_interval(). dbus_timeout_handle() should be called
4879 * repeatedly, each time the interval elapses, starting after it has
4880 * elapsed once. The timeout stops firing when it is removed with the
4881 * given remove_function. The timer interval may change whenever the
4882 * timeout is added, removed, or toggled.
4884 * @note The thread lock on DBusConnection is held while
4885 * timeout functions are invoked, so inside these functions you
4886 * may not invoke any methods on DBusConnection or it will deadlock.
4887 * See the comments in the code or http://lists.freedesktop.org/archives/dbus/2007-July/thread.html#8144
4888 * if you encounter this issue and want to attempt writing a patch.
4890 * @param connection the connection.
4891 * @param add_function function to add a timeout.
4892 * @param remove_function function to remove a timeout.
4893 * @param toggled_function function to notify of enable/disable
4894 * @param data data to pass to add_function and remove_function.
4895 * @param free_data_function function to be called to free the data.
4896 * @returns #FALSE on failure (no memory)
4899 dbus_connection_set_timeout_functions (DBusConnection *connection,
4900 DBusAddTimeoutFunction add_function,
4901 DBusRemoveTimeoutFunction remove_function,
4902 DBusTimeoutToggledFunction toggled_function,
4904 DBusFreeFunction free_data_function)
4908 _dbus_return_val_if_fail (connection != NULL, FALSE);
4910 CONNECTION_LOCK (connection);
4912 retval = _dbus_timeout_list_set_functions (connection->timeouts,
4913 add_function, remove_function,
4915 data, free_data_function);
4917 CONNECTION_UNLOCK (connection);
4923 * Sets the mainloop wakeup function for the connection. This function
4924 * is responsible for waking up the main loop (if its sleeping in
4925 * another thread) when some some change has happened to the
4926 * connection that the mainloop needs to reconsider (e.g. a message
4927 * has been queued for writing). When using Qt, this typically
4928 * results in a call to QEventLoop::wakeUp(). When using GLib, it
4929 * would call g_main_context_wakeup().
4931 * @param connection the connection.
4932 * @param wakeup_main_function function to wake up the mainloop
4933 * @param data data to pass wakeup_main_function
4934 * @param free_data_function function to be called to free the data.
4937 dbus_connection_set_wakeup_main_function (DBusConnection *connection,
4938 DBusWakeupMainFunction wakeup_main_function,
4940 DBusFreeFunction free_data_function)
4943 DBusFreeFunction old_free_data;
4945 _dbus_return_if_fail (connection != NULL);
4947 CONNECTION_LOCK (connection);
4948 old_data = connection->wakeup_main_data;
4949 old_free_data = connection->free_wakeup_main_data;
4951 connection->wakeup_main_function = wakeup_main_function;
4952 connection->wakeup_main_data = data;
4953 connection->free_wakeup_main_data = free_data_function;
4955 CONNECTION_UNLOCK (connection);
4957 /* Callback outside the lock */
4959 (*old_free_data) (old_data);
4963 * Set a function to be invoked when the dispatch status changes.
4964 * If the dispatch status is #DBUS_DISPATCH_DATA_REMAINS, then
4965 * dbus_connection_dispatch() needs to be called to process incoming
4966 * messages. However, dbus_connection_dispatch() MUST NOT BE CALLED
4967 * from inside the DBusDispatchStatusFunction. Indeed, almost
4968 * any reentrancy in this function is a bad idea. Instead,
4969 * the DBusDispatchStatusFunction should simply save an indication
4970 * that messages should be dispatched later, when the main loop
4973 * If you don't set a dispatch status function, you have to be sure to
4974 * dispatch on every iteration of your main loop, especially if
4975 * dbus_watch_handle() or dbus_timeout_handle() were called.
4977 * @param connection the connection
4978 * @param function function to call on dispatch status changes
4979 * @param data data for function
4980 * @param free_data_function free the function data
4983 dbus_connection_set_dispatch_status_function (DBusConnection *connection,
4984 DBusDispatchStatusFunction function,
4986 DBusFreeFunction free_data_function)
4989 DBusFreeFunction old_free_data;
4991 _dbus_return_if_fail (connection != NULL);
4993 CONNECTION_LOCK (connection);
4994 old_data = connection->dispatch_status_data;
4995 old_free_data = connection->free_dispatch_status_data;
4997 connection->dispatch_status_function = function;
4998 connection->dispatch_status_data = data;
4999 connection->free_dispatch_status_data = free_data_function;
5001 CONNECTION_UNLOCK (connection);
5003 /* Callback outside the lock */
5005 (*old_free_data) (old_data);
5009 * Get the UNIX file descriptor of the connection, if any. This can
5010 * be used for SELinux access control checks with getpeercon() for
5011 * example. DO NOT read or write to the file descriptor, or try to
5012 * select() on it; use DBusWatch for main loop integration. Not all
5013 * connections will have a file descriptor. So for adding descriptors
5014 * to the main loop, use dbus_watch_get_unix_fd() and so forth.
5016 * If the connection is socket-based, you can also use
5017 * dbus_connection_get_socket(), which will work on Windows too.
5018 * This function always fails on Windows.
5020 * Right now the returned descriptor is always a socket, but
5021 * that is not guaranteed.
5023 * @param connection the connection
5024 * @param fd return location for the file descriptor.
5025 * @returns #TRUE if fd is successfully obtained.
5028 dbus_connection_get_unix_fd (DBusConnection *connection,
5031 _dbus_return_val_if_fail (connection != NULL, FALSE);
5032 _dbus_return_val_if_fail (connection->transport != NULL, FALSE);
5035 /* FIXME do this on a lower level */
5039 return dbus_connection_get_socket(connection, fd);
5043 * Gets the underlying Windows or UNIX socket file descriptor
5044 * of the connection, if any. DO NOT read or write to the file descriptor, or try to
5045 * select() on it; use DBusWatch for main loop integration. Not all
5046 * connections will have a socket. So for adding descriptors
5047 * to the main loop, use dbus_watch_get_socket() and so forth.
5049 * If the connection is not socket-based, this function will return FALSE,
5050 * even if the connection does have a file descriptor of some kind.
5051 * i.e. this function always returns specifically a socket file descriptor.
5053 * @param connection the connection
5054 * @param fd return location for the file descriptor.
5055 * @returns #TRUE if fd is successfully obtained.
5058 dbus_connection_get_socket(DBusConnection *connection,
5063 _dbus_return_val_if_fail (connection != NULL, FALSE);
5064 _dbus_return_val_if_fail (connection->transport != NULL, FALSE);
5066 CONNECTION_LOCK (connection);
5068 retval = _dbus_transport_get_socket_fd (connection->transport,
5071 CONNECTION_UNLOCK (connection);
5078 * Gets the UNIX user ID of the connection if known. Returns #TRUE if
5079 * the uid is filled in. Always returns #FALSE on non-UNIX platforms
5080 * for now, though in theory someone could hook Windows to NIS or
5081 * something. Always returns #FALSE prior to authenticating the
5084 * The UID is only read by servers from clients; clients can't usually
5085 * get the UID of servers, because servers do not authenticate to
5086 * clients. The returned UID is the UID the connection authenticated
5089 * The message bus is a server and the apps connecting to the bus
5092 * You can ask the bus to tell you the UID of another connection though
5093 * if you like; this is done with dbus_bus_get_unix_user().
5095 * @param connection the connection
5096 * @param uid return location for the user ID
5097 * @returns #TRUE if uid is filled in with a valid user ID
5100 dbus_connection_get_unix_user (DBusConnection *connection,
5105 _dbus_return_val_if_fail (connection != NULL, FALSE);
5106 _dbus_return_val_if_fail (uid != NULL, FALSE);
5108 CONNECTION_LOCK (connection);
5110 if (!_dbus_transport_get_is_authenticated (connection->transport))
5113 result = _dbus_transport_get_unix_user (connection->transport,
5117 _dbus_assert (!result);
5120 CONNECTION_UNLOCK (connection);
5126 * Gets the process ID of the connection if any.
5127 * Returns #TRUE if the pid is filled in.
5128 * Always returns #FALSE prior to authenticating the
5131 * @param connection the connection
5132 * @param pid return location for the process ID
5133 * @returns #TRUE if uid is filled in with a valid process ID
5136 dbus_connection_get_unix_process_id (DBusConnection *connection,
5141 _dbus_return_val_if_fail (connection != NULL, FALSE);
5142 _dbus_return_val_if_fail (pid != NULL, FALSE);
5144 CONNECTION_LOCK (connection);
5146 if (!_dbus_transport_get_is_authenticated (connection->transport))
5149 result = _dbus_transport_get_unix_process_id (connection->transport,
5152 CONNECTION_UNLOCK (connection);
5158 * Gets the ADT audit data of the connection if any.
5159 * Returns #TRUE if the structure pointer is returned.
5160 * Always returns #FALSE prior to authenticating the
5163 * @param connection the connection
5164 * @param data return location for audit data
5165 * @returns #TRUE if audit data is filled in with a valid ucred pointer
5168 dbus_connection_get_adt_audit_session_data (DBusConnection *connection,
5170 dbus_int32_t *data_size)
5174 _dbus_return_val_if_fail (connection != NULL, FALSE);
5175 _dbus_return_val_if_fail (data != NULL, FALSE);
5176 _dbus_return_val_if_fail (data_size != NULL, FALSE);
5178 CONNECTION_LOCK (connection);
5180 if (!_dbus_transport_get_is_authenticated (connection->transport))
5183 result = _dbus_transport_get_adt_audit_session_data (connection->transport,
5186 CONNECTION_UNLOCK (connection);
5192 * Sets a predicate function used to determine whether a given user ID
5193 * is allowed to connect. When an incoming connection has
5194 * authenticated with a particular user ID, this function is called;
5195 * if it returns #TRUE, the connection is allowed to proceed,
5196 * otherwise the connection is disconnected.
5198 * If the function is set to #NULL (as it is by default), then
5199 * only the same UID as the server process will be allowed to
5200 * connect. Also, root is always allowed to connect.
5202 * On Windows, the function will be set and its free_data_function will
5203 * be invoked when the connection is freed or a new function is set.
5204 * However, the function will never be called, because there are
5205 * no UNIX user ids to pass to it, or at least none of the existing
5206 * auth protocols would allow authenticating as a UNIX user on Windows.
5208 * @param connection the connection
5209 * @param function the predicate
5210 * @param data data to pass to the predicate
5211 * @param free_data_function function to free the data
5214 dbus_connection_set_unix_user_function (DBusConnection *connection,
5215 DBusAllowUnixUserFunction function,
5217 DBusFreeFunction free_data_function)
5219 void *old_data = NULL;
5220 DBusFreeFunction old_free_function = NULL;
5222 _dbus_return_if_fail (connection != NULL);
5224 CONNECTION_LOCK (connection);
5225 _dbus_transport_set_unix_user_function (connection->transport,
5226 function, data, free_data_function,
5227 &old_data, &old_free_function);
5228 CONNECTION_UNLOCK (connection);
5230 if (old_free_function != NULL)
5231 (* old_free_function) (old_data);
5235 * Gets the Windows user SID of the connection if known. Returns
5236 * #TRUE if the ID is filled in. Always returns #FALSE on non-Windows
5237 * platforms for now, though in theory someone could hook UNIX to
5238 * Active Directory or something. Always returns #FALSE prior to
5239 * authenticating the connection.
5241 * The user is only read by servers from clients; clients can't usually
5242 * get the user of servers, because servers do not authenticate to
5243 * clients. The returned user is the user the connection authenticated
5246 * The message bus is a server and the apps connecting to the bus
5249 * The returned user string has to be freed with dbus_free().
5251 * The return value indicates whether the user SID is available;
5252 * if it's available but we don't have the memory to copy it,
5253 * then the return value is #TRUE and #NULL is given as the SID.
5255 * @todo We would like to be able to say "You can ask the bus to tell
5256 * you the user of another connection though if you like; this is done
5257 * with dbus_bus_get_windows_user()." But this has to be implemented
5258 * in bus/driver.c and dbus/dbus-bus.c, and is pointless anyway
5259 * since on Windows we only use the session bus for now.
5261 * @param connection the connection
5262 * @param windows_sid_p return location for an allocated copy of the user ID, or #NULL if no memory
5263 * @returns #TRUE if user is available (returned value may be #NULL anyway if no memory)
5266 dbus_connection_get_windows_user (DBusConnection *connection,
5267 char **windows_sid_p)
5271 _dbus_return_val_if_fail (connection != NULL, FALSE);
5272 _dbus_return_val_if_fail (windows_sid_p != NULL, FALSE);
5274 CONNECTION_LOCK (connection);
5276 if (!_dbus_transport_get_is_authenticated (connection->transport))
5279 result = _dbus_transport_get_windows_user (connection->transport,
5283 _dbus_assert (!result);
5286 CONNECTION_UNLOCK (connection);
5292 * Sets a predicate function used to determine whether a given user ID
5293 * is allowed to connect. When an incoming connection has
5294 * authenticated with a particular user ID, this function is called;
5295 * if it returns #TRUE, the connection is allowed to proceed,
5296 * otherwise the connection is disconnected.
5298 * If the function is set to #NULL (as it is by default), then
5299 * only the same user owning the server process will be allowed to
5302 * On UNIX, the function will be set and its free_data_function will
5303 * be invoked when the connection is freed or a new function is set.
5304 * However, the function will never be called, because there is no
5305 * way right now to authenticate as a Windows user on UNIX.
5307 * @param connection the connection
5308 * @param function the predicate
5309 * @param data data to pass to the predicate
5310 * @param free_data_function function to free the data
5313 dbus_connection_set_windows_user_function (DBusConnection *connection,
5314 DBusAllowWindowsUserFunction function,
5316 DBusFreeFunction free_data_function)
5318 void *old_data = NULL;
5319 DBusFreeFunction old_free_function = NULL;
5321 _dbus_return_if_fail (connection != NULL);
5323 CONNECTION_LOCK (connection);
5324 _dbus_transport_set_windows_user_function (connection->transport,
5325 function, data, free_data_function,
5326 &old_data, &old_free_function);
5327 CONNECTION_UNLOCK (connection);
5329 if (old_free_function != NULL)
5330 (* old_free_function) (old_data);
5334 * This function must be called on the server side of a connection when the
5335 * connection is first seen in the #DBusNewConnectionFunction. If set to
5336 * #TRUE (the default is #FALSE), then the connection can proceed even if
5337 * the client does not authenticate as some user identity, i.e. clients
5338 * can connect anonymously.
5340 * This setting interacts with the available authorization mechanisms
5341 * (see dbus_server_set_auth_mechanisms()). Namely, an auth mechanism
5342 * such as ANONYMOUS that supports anonymous auth must be included in
5343 * the list of available mechanisms for anonymous login to work.
5345 * This setting also changes the default rule for connections
5346 * authorized as a user; normally, if a connection authorizes as
5347 * a user identity, it is permitted if the user identity is
5348 * root or the user identity matches the user identity of the server
5349 * process. If anonymous connections are allowed, however,
5350 * then any user identity is allowed.
5352 * You can override the rules for connections authorized as a
5353 * user identity with dbus_connection_set_unix_user_function()
5354 * and dbus_connection_set_windows_user_function().
5356 * @param connection the connection
5357 * @param value whether to allow authentication as an anonymous user
5360 dbus_connection_set_allow_anonymous (DBusConnection *connection,
5363 _dbus_return_if_fail (connection != NULL);
5365 CONNECTION_LOCK (connection);
5366 _dbus_transport_set_allow_anonymous (connection->transport, value);
5367 CONNECTION_UNLOCK (connection);
5372 * Normally #DBusConnection automatically handles all messages to the
5373 * org.freedesktop.DBus.Peer interface. However, the message bus wants
5374 * to be able to route methods on that interface through the bus and
5375 * to other applications. If routing peer messages is enabled, then
5376 * messages with the org.freedesktop.DBus.Peer interface that also
5377 * have a bus destination name set will not be automatically
5378 * handled by the #DBusConnection and instead will be dispatched
5379 * normally to the application.
5381 * If a normal application sets this flag, it can break things badly.
5382 * So don't set this unless you are the message bus.
5384 * @param connection the connection
5385 * @param value #TRUE to pass through org.freedesktop.DBus.Peer messages with a bus name set
5388 dbus_connection_set_route_peer_messages (DBusConnection *connection,
5391 _dbus_return_if_fail (connection != NULL);
5393 CONNECTION_LOCK (connection);
5394 connection->route_peer_messages = TRUE;
5395 CONNECTION_UNLOCK (connection);
5399 * Adds a message filter. Filters are handlers that are run on all
5400 * incoming messages, prior to the objects registered with
5401 * dbus_connection_register_object_path(). Filters are run in the
5402 * order that they were added. The same handler can be added as a
5403 * filter more than once, in which case it will be run more than once.
5404 * Filters added during a filter callback won't be run on the message
5407 * @todo we don't run filters on messages while blocking without
5408 * entering the main loop, since filters are run as part of
5409 * dbus_connection_dispatch(). This is probably a feature, as filters
5410 * could create arbitrary reentrancy. But kind of sucks if you're
5411 * trying to filter METHOD_RETURN for some reason.
5413 * @param connection the connection
5414 * @param function function to handle messages
5415 * @param user_data user data to pass to the function
5416 * @param free_data_function function to use for freeing user data
5417 * @returns #TRUE on success, #FALSE if not enough memory.
5420 dbus_connection_add_filter (DBusConnection *connection,
5421 DBusHandleMessageFunction function,
5423 DBusFreeFunction free_data_function)
5425 DBusMessageFilter *filter;
5427 _dbus_return_val_if_fail (connection != NULL, FALSE);
5428 _dbus_return_val_if_fail (function != NULL, FALSE);
5430 filter = dbus_new0 (DBusMessageFilter, 1);
5434 _dbus_atomic_inc (&filter->refcount);
5436 CONNECTION_LOCK (connection);
5438 if (!_dbus_list_append (&connection->filter_list,
5441 _dbus_message_filter_unref (filter);
5442 CONNECTION_UNLOCK (connection);
5446 /* Fill in filter after all memory allocated,
5447 * so we don't run the free_user_data_function
5448 * if the add_filter() fails
5451 filter->function = function;
5452 filter->user_data = user_data;
5453 filter->free_user_data_function = free_data_function;
5455 CONNECTION_UNLOCK (connection);
5460 * Removes a previously-added message filter. It is a programming
5461 * error to call this function for a handler that has not been added
5462 * as a filter. If the given handler was added more than once, only
5463 * one instance of it will be removed (the most recently-added
5466 * @param connection the connection
5467 * @param function the handler to remove
5468 * @param user_data user data for the handler to remove
5472 dbus_connection_remove_filter (DBusConnection *connection,
5473 DBusHandleMessageFunction function,
5477 DBusMessageFilter *filter;
5479 _dbus_return_if_fail (connection != NULL);
5480 _dbus_return_if_fail (function != NULL);
5482 CONNECTION_LOCK (connection);
5486 link = _dbus_list_get_last_link (&connection->filter_list);
5487 while (link != NULL)
5489 filter = link->data;
5491 if (filter->function == function &&
5492 filter->user_data == user_data)
5494 _dbus_list_remove_link (&connection->filter_list, link);
5495 filter->function = NULL;
5500 link = _dbus_list_get_prev_link (&connection->filter_list, link);
5504 CONNECTION_UNLOCK (connection);
5506 #ifndef DBUS_DISABLE_CHECKS
5509 _dbus_warn_check_failed ("Attempt to remove filter function %p user data %p, but no such filter has been added\n",
5510 function, user_data);
5515 /* Call application code */
5516 if (filter->free_user_data_function)
5517 (* filter->free_user_data_function) (filter->user_data);
5519 filter->free_user_data_function = NULL;
5520 filter->user_data = NULL;
5522 _dbus_message_filter_unref (filter);
5526 * Registers a handler for a given path or subsection in the object
5527 * hierarchy. The given vtable handles messages sent to exactly the
5528 * given path or also for paths bellow that, depending on fallback
5531 * @param connection the connection
5532 * @param fallback whether to handle messages also for "subdirectory"
5533 * @param path a '/' delimited string of path elements
5534 * @param vtable the virtual table
5535 * @param user_data data to pass to functions in the vtable
5536 * @param error address where an error can be returned
5537 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5538 * #DBUS_ERROR_OBJECT_PATH_IN_USE) is reported
5541 _dbus_connection_register_object_path (DBusConnection *connection,
5542 dbus_bool_t fallback,
5544 const DBusObjectPathVTable *vtable,
5548 char **decomposed_path;
5551 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5554 CONNECTION_LOCK (connection);
5556 retval = _dbus_object_tree_register (connection->objects,
5558 (const char **) decomposed_path, vtable,
5561 CONNECTION_UNLOCK (connection);
5563 dbus_free_string_array (decomposed_path);
5569 * Registers a handler for a given path in the object hierarchy.
5570 * The given vtable handles messages sent to exactly the given path.
5572 * @param connection the connection
5573 * @param path a '/' delimited string of path elements
5574 * @param vtable the virtual table
5575 * @param user_data data to pass to functions in the vtable
5576 * @param error address where an error can be returned
5577 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5578 * #DBUS_ERROR_OBJECT_PATH_IN_USE) is reported
5581 dbus_connection_try_register_object_path (DBusConnection *connection,
5583 const DBusObjectPathVTable *vtable,
5587 _dbus_return_val_if_fail (connection != NULL, FALSE);
5588 _dbus_return_val_if_fail (path != NULL, FALSE);
5589 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5590 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5592 return _dbus_connection_register_object_path (connection, FALSE, path, vtable, user_data, error);
5596 * Registers a handler for a given path in the object hierarchy.
5597 * The given vtable handles messages sent to exactly the given path.
5599 * It is a bug to call this function for object paths which already
5600 * have a handler. Use dbus_connection_try_register_object_path() if this
5601 * might be the case.
5603 * @param connection the connection
5604 * @param path a '/' delimited string of path elements
5605 * @param vtable the virtual table
5606 * @param user_data data to pass to functions in the vtable
5607 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5608 * #DBUS_ERROR_OBJECT_PATH_IN_USE) ocurred
5611 dbus_connection_register_object_path (DBusConnection *connection,
5613 const DBusObjectPathVTable *vtable,
5617 DBusError error = DBUS_ERROR_INIT;
5619 _dbus_return_val_if_fail (connection != NULL, FALSE);
5620 _dbus_return_val_if_fail (path != NULL, FALSE);
5621 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5622 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5624 retval = _dbus_connection_register_object_path (connection, FALSE, path, vtable, user_data, &error);
5626 if (dbus_error_has_name (&error, DBUS_ERROR_OBJECT_PATH_IN_USE))
5628 _dbus_warn ("%s\n", error.message);
5629 dbus_error_free (&error);
5637 * Registers a fallback handler for a given subsection of the object
5638 * hierarchy. The given vtable handles messages at or below the given
5639 * path. You can use this to establish a default message handling
5640 * policy for a whole "subdirectory."
5642 * @param connection the connection
5643 * @param path a '/' delimited string of path elements
5644 * @param vtable the virtual table
5645 * @param user_data data to pass to functions in the vtable
5646 * @param error address where an error can be returned
5647 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5648 * #DBUS_ERROR_OBJECT_PATH_IN_USE) is reported
5651 dbus_connection_try_register_fallback (DBusConnection *connection,
5653 const DBusObjectPathVTable *vtable,
5657 _dbus_return_val_if_fail (connection != NULL, FALSE);
5658 _dbus_return_val_if_fail (path != NULL, FALSE);
5659 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5660 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5662 return _dbus_connection_register_object_path (connection, TRUE, path, vtable, user_data, error);
5666 * Registers a fallback handler for a given subsection of the object
5667 * hierarchy. The given vtable handles messages at or below the given
5668 * path. You can use this to establish a default message handling
5669 * policy for a whole "subdirectory."
5671 * It is a bug to call this function for object paths which already
5672 * have a handler. Use dbus_connection_try_register_fallback() if this
5673 * might be the case.
5675 * @param connection the connection
5676 * @param path a '/' delimited string of path elements
5677 * @param vtable the virtual table
5678 * @param user_data data to pass to functions in the vtable
5679 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5680 * #DBUS_ERROR_OBJECT_PATH_IN_USE) occured
5683 dbus_connection_register_fallback (DBusConnection *connection,
5685 const DBusObjectPathVTable *vtable,
5689 DBusError error = DBUS_ERROR_INIT;
5691 _dbus_return_val_if_fail (connection != NULL, FALSE);
5692 _dbus_return_val_if_fail (path != NULL, FALSE);
5693 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5694 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5696 retval = _dbus_connection_register_object_path (connection, TRUE, path, vtable, user_data, &error);
5698 if (dbus_error_has_name (&error, DBUS_ERROR_OBJECT_PATH_IN_USE))
5700 _dbus_warn ("%s\n", error.message);
5701 dbus_error_free (&error);
5709 * Unregisters the handler registered with exactly the given path.
5710 * It's a bug to call this function for a path that isn't registered.
5711 * Can unregister both fallback paths and object paths.
5713 * @param connection the connection
5714 * @param path a '/' delimited string of path elements
5715 * @returns #FALSE if not enough memory
5718 dbus_connection_unregister_object_path (DBusConnection *connection,
5721 char **decomposed_path;
5723 _dbus_return_val_if_fail (connection != NULL, FALSE);
5724 _dbus_return_val_if_fail (path != NULL, FALSE);
5725 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5727 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5730 CONNECTION_LOCK (connection);
5732 _dbus_object_tree_unregister_and_unlock (connection->objects, (const char **) decomposed_path);
5734 dbus_free_string_array (decomposed_path);
5740 * Gets the user data passed to dbus_connection_register_object_path()
5741 * or dbus_connection_register_fallback(). If nothing was registered
5742 * at this path, the data is filled in with #NULL.
5744 * @param connection the connection
5745 * @param path the path you registered with
5746 * @param data_p location to store the user data, or #NULL
5747 * @returns #FALSE if not enough memory
5750 dbus_connection_get_object_path_data (DBusConnection *connection,
5754 char **decomposed_path;
5756 _dbus_return_val_if_fail (connection != NULL, FALSE);
5757 _dbus_return_val_if_fail (path != NULL, FALSE);
5758 _dbus_return_val_if_fail (data_p != NULL, FALSE);
5762 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5765 CONNECTION_LOCK (connection);
5767 *data_p = _dbus_object_tree_get_user_data_unlocked (connection->objects, (const char**) decomposed_path);
5769 CONNECTION_UNLOCK (connection);
5771 dbus_free_string_array (decomposed_path);
5777 * Lists the registered fallback handlers and object path handlers at
5778 * the given parent_path. The returned array should be freed with
5779 * dbus_free_string_array().
5781 * @param connection the connection
5782 * @param parent_path the path to list the child handlers of
5783 * @param child_entries returns #NULL-terminated array of children
5784 * @returns #FALSE if no memory to allocate the child entries
5787 dbus_connection_list_registered (DBusConnection *connection,
5788 const char *parent_path,
5789 char ***child_entries)
5791 char **decomposed_path;
5793 _dbus_return_val_if_fail (connection != NULL, FALSE);
5794 _dbus_return_val_if_fail (parent_path != NULL, FALSE);
5795 _dbus_return_val_if_fail (parent_path[0] == '/', FALSE);
5796 _dbus_return_val_if_fail (child_entries != NULL, FALSE);
5798 if (!_dbus_decompose_path (parent_path, strlen (parent_path), &decomposed_path, NULL))
5801 CONNECTION_LOCK (connection);
5803 retval = _dbus_object_tree_list_registered_and_unlock (connection->objects,
5804 (const char **) decomposed_path,
5806 dbus_free_string_array (decomposed_path);
5811 static DBusDataSlotAllocator slot_allocator;
5812 _DBUS_DEFINE_GLOBAL_LOCK (connection_slots);
5815 * Allocates an integer ID to be used for storing application-specific
5816 * data on any DBusConnection. The allocated ID may then be used
5817 * with dbus_connection_set_data() and dbus_connection_get_data().
5818 * The passed-in slot must be initialized to -1, and is filled in
5819 * with the slot ID. If the passed-in slot is not -1, it's assumed
5820 * to be already allocated, and its refcount is incremented.
5822 * The allocated slot is global, i.e. all DBusConnection objects will
5823 * have a slot with the given integer ID reserved.
5825 * @param slot_p address of a global variable storing the slot
5826 * @returns #FALSE on failure (no memory)
5829 dbus_connection_allocate_data_slot (dbus_int32_t *slot_p)
5831 return _dbus_data_slot_allocator_alloc (&slot_allocator,
5832 &_DBUS_LOCK_NAME (connection_slots),
5837 * Deallocates a global ID for connection data slots.
5838 * dbus_connection_get_data() and dbus_connection_set_data() may no
5839 * longer be used with this slot. Existing data stored on existing
5840 * DBusConnection objects will be freed when the connection is
5841 * finalized, but may not be retrieved (and may only be replaced if
5842 * someone else reallocates the slot). When the refcount on the
5843 * passed-in slot reaches 0, it is set to -1.
5845 * @param slot_p address storing the slot to deallocate
5848 dbus_connection_free_data_slot (dbus_int32_t *slot_p)
5850 _dbus_return_if_fail (*slot_p >= 0);
5852 _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
5856 * Stores a pointer on a DBusConnection, along
5857 * with an optional function to be used for freeing
5858 * the data when the data is set again, or when
5859 * the connection is finalized. The slot number
5860 * must have been allocated with dbus_connection_allocate_data_slot().
5862 * @note This function does not take the
5863 * main thread lock on DBusConnection, which allows it to be
5864 * used from inside watch and timeout functions. (See the
5865 * note in docs for dbus_connection_set_watch_functions().)
5866 * A side effect of this is that you need to know there's
5867 * a reference held on the connection while invoking
5868 * dbus_connection_set_data(), or the connection could be
5869 * finalized during dbus_connection_set_data().
5871 * @param connection the connection
5872 * @param slot the slot number
5873 * @param data the data to store
5874 * @param free_data_func finalizer function for the data
5875 * @returns #TRUE if there was enough memory to store the data
5878 dbus_connection_set_data (DBusConnection *connection,
5881 DBusFreeFunction free_data_func)
5883 DBusFreeFunction old_free_func;
5887 _dbus_return_val_if_fail (connection != NULL, FALSE);
5888 _dbus_return_val_if_fail (slot >= 0, FALSE);
5890 SLOTS_LOCK (connection);
5892 retval = _dbus_data_slot_list_set (&slot_allocator,
5893 &connection->slot_list,
5894 slot, data, free_data_func,
5895 &old_free_func, &old_data);
5897 SLOTS_UNLOCK (connection);
5901 /* Do the actual free outside the connection lock */
5903 (* old_free_func) (old_data);
5910 * Retrieves data previously set with dbus_connection_set_data().
5911 * The slot must still be allocated (must not have been freed).
5913 * @note This function does not take the
5914 * main thread lock on DBusConnection, which allows it to be
5915 * used from inside watch and timeout functions. (See the
5916 * note in docs for dbus_connection_set_watch_functions().)
5917 * A side effect of this is that you need to know there's
5918 * a reference held on the connection while invoking
5919 * dbus_connection_get_data(), or the connection could be
5920 * finalized during dbus_connection_get_data().
5922 * @param connection the connection
5923 * @param slot the slot to get data from
5924 * @returns the data, or #NULL if not found
5927 dbus_connection_get_data (DBusConnection *connection,
5932 _dbus_return_val_if_fail (connection != NULL, NULL);
5934 SLOTS_LOCK (connection);
5936 res = _dbus_data_slot_list_get (&slot_allocator,
5937 &connection->slot_list,
5940 SLOTS_UNLOCK (connection);
5946 * This function sets a global flag for whether dbus_connection_new()
5947 * will set SIGPIPE behavior to SIG_IGN.
5949 * @param will_modify_sigpipe #TRUE to allow sigpipe to be set to SIG_IGN
5952 dbus_connection_set_change_sigpipe (dbus_bool_t will_modify_sigpipe)
5954 _dbus_modify_sigpipe = will_modify_sigpipe != FALSE;
5958 * Specifies the maximum size message this connection is allowed to
5959 * receive. Larger messages will result in disconnecting the
5962 * @param connection a #DBusConnection
5963 * @param size maximum message size the connection can receive, in bytes
5966 dbus_connection_set_max_message_size (DBusConnection *connection,
5969 _dbus_return_if_fail (connection != NULL);
5971 CONNECTION_LOCK (connection);
5972 _dbus_transport_set_max_message_size (connection->transport,
5974 CONNECTION_UNLOCK (connection);
5978 * Gets the value set by dbus_connection_set_max_message_size().
5980 * @param connection the connection
5981 * @returns the max size of a single message
5984 dbus_connection_get_max_message_size (DBusConnection *connection)
5988 _dbus_return_val_if_fail (connection != NULL, 0);
5990 CONNECTION_LOCK (connection);
5991 res = _dbus_transport_get_max_message_size (connection->transport);
5992 CONNECTION_UNLOCK (connection);
5997 * Specifies the maximum number of unix fds a message on this
5998 * connection is allowed to receive. Messages with more unix fds will
5999 * result in disconnecting the connection.
6001 * @param connection a #DBusConnection
6002 * @param size maximum message unix fds the connection can receive
6005 dbus_connection_set_max_message_unix_fds (DBusConnection *connection,
6008 _dbus_return_if_fail (connection != NULL);
6010 CONNECTION_LOCK (connection);
6011 _dbus_transport_set_max_message_unix_fds (connection->transport,
6013 CONNECTION_UNLOCK (connection);
6017 * Gets the value set by dbus_connection_set_max_message_unix_fds().
6019 * @param connection the connection
6020 * @returns the max numer of unix fds of a single message
6023 dbus_connection_get_max_message_unix_fds (DBusConnection *connection)
6027 _dbus_return_val_if_fail (connection != NULL, 0);
6029 CONNECTION_LOCK (connection);
6030 res = _dbus_transport_get_max_message_unix_fds (connection->transport);
6031 CONNECTION_UNLOCK (connection);
6036 * Sets the maximum total number of bytes that can be used for all messages
6037 * received on this connection. Messages count toward the maximum until
6038 * they are finalized. When the maximum is reached, the connection will
6039 * not read more data until some messages are finalized.
6041 * The semantics of the maximum are: if outstanding messages are
6042 * already above the maximum, additional messages will not be read.
6043 * The semantics are not: if the next message would cause us to exceed
6044 * the maximum, we don't read it. The reason is that we don't know the
6045 * size of a message until after we read it.
6047 * Thus, the max live messages size can actually be exceeded
6048 * by up to the maximum size of a single message.
6050 * Also, if we read say 1024 bytes off the wire in a single read(),
6051 * and that contains a half-dozen small messages, we may exceed the
6052 * size max by that amount. But this should be inconsequential.
6054 * This does imply that we can't call read() with a buffer larger
6055 * than we're willing to exceed this limit by.
6057 * @param connection the connection
6058 * @param size the maximum size in bytes of all outstanding messages
6061 dbus_connection_set_max_received_size (DBusConnection *connection,
6064 _dbus_return_if_fail (connection != NULL);
6066 CONNECTION_LOCK (connection);
6067 _dbus_transport_set_max_received_size (connection->transport,
6069 CONNECTION_UNLOCK (connection);
6073 * Gets the value set by dbus_connection_set_max_received_size().
6075 * @param connection the connection
6076 * @returns the max size of all live messages
6079 dbus_connection_get_max_received_size (DBusConnection *connection)
6083 _dbus_return_val_if_fail (connection != NULL, 0);
6085 CONNECTION_LOCK (connection);
6086 res = _dbus_transport_get_max_received_size (connection->transport);
6087 CONNECTION_UNLOCK (connection);
6092 * Sets the maximum total number of unix fds that can be used for all messages
6093 * received on this connection. Messages count toward the maximum until
6094 * they are finalized. When the maximum is reached, the connection will
6095 * not read more data until some messages are finalized.
6097 * The semantics are analogous to those of dbus_connection_set_max_received_size().
6099 * @param connection the connection
6100 * @param size the maximum size in bytes of all outstanding messages
6103 dbus_connection_set_max_received_unix_fds (DBusConnection *connection,
6106 _dbus_return_if_fail (connection != NULL);
6108 CONNECTION_LOCK (connection);
6109 _dbus_transport_set_max_received_unix_fds (connection->transport,
6111 CONNECTION_UNLOCK (connection);
6115 * Gets the value set by dbus_connection_set_max_received_unix_fds().
6117 * @param connection the connection
6118 * @returns the max unix fds of all live messages
6121 dbus_connection_get_max_received_unix_fds (DBusConnection *connection)
6125 _dbus_return_val_if_fail (connection != NULL, 0);
6127 CONNECTION_LOCK (connection);
6128 res = _dbus_transport_get_max_received_unix_fds (connection->transport);
6129 CONNECTION_UNLOCK (connection);
6134 * Gets the approximate size in bytes of all messages in the outgoing
6135 * message queue. The size is approximate in that you shouldn't use
6136 * it to decide how many bytes to read off the network or anything
6137 * of that nature, as optimizations may choose to tell small white lies
6138 * to avoid performance overhead.
6140 * @param connection the connection
6141 * @returns the number of bytes that have been queued up but not sent
6144 dbus_connection_get_outgoing_size (DBusConnection *connection)
6148 _dbus_return_val_if_fail (connection != NULL, 0);
6150 CONNECTION_LOCK (connection);
6151 res = _dbus_counter_get_size_value (connection->outgoing_counter);
6152 CONNECTION_UNLOCK (connection);
6156 #ifdef DBUS_ENABLE_STATS
6158 _dbus_connection_get_stats (DBusConnection *connection,
6159 dbus_uint32_t *in_messages,
6160 dbus_uint32_t *in_bytes,
6161 dbus_uint32_t *in_fds,
6162 dbus_uint32_t *in_peak_bytes,
6163 dbus_uint32_t *in_peak_fds,
6164 dbus_uint32_t *out_messages,
6165 dbus_uint32_t *out_bytes,
6166 dbus_uint32_t *out_fds,
6167 dbus_uint32_t *out_peak_bytes,
6168 dbus_uint32_t *out_peak_fds,
6169 dbus_uint32_t *link_cache_size)
6171 CONNECTION_LOCK (connection);
6173 if (in_messages != NULL)
6174 *in_messages = connection->n_incoming;
6176 _dbus_transport_get_stats (connection->transport,
6177 in_bytes, in_fds, in_peak_bytes, in_peak_fds);
6179 if (out_messages != NULL)
6180 *out_messages = connection->n_outgoing;
6182 if (out_bytes != NULL)
6183 *out_bytes = _dbus_counter_get_size_value (connection->outgoing_counter);
6185 if (out_fds != NULL)
6186 *out_fds = _dbus_counter_get_unix_fd_value (connection->outgoing_counter);
6188 if (out_peak_bytes != NULL)
6189 *out_peak_bytes = _dbus_counter_get_peak_size_value (connection->outgoing_counter);
6191 if (out_peak_fds != NULL)
6192 *out_peak_fds = _dbus_counter_get_peak_unix_fd_value (connection->outgoing_counter);
6194 if (link_cache_size != NULL)
6196 *link_cache_size = _dbus_list_get_length (&connection->link_cache) * sizeof (DBusList);
6199 CONNECTION_UNLOCK (connection);
6201 #endif /* DBUS_ENABLE_STATS */
6204 * Gets the approximate number of uni fds of all messages in the
6205 * outgoing message queue.
6207 * @param connection the connection
6208 * @returns the number of unix fds that have been queued up but not sent
6211 dbus_connection_get_outgoing_unix_fds (DBusConnection *connection)
6215 _dbus_return_val_if_fail (connection != NULL, 0);
6217 CONNECTION_LOCK (connection);
6218 res = _dbus_counter_get_unix_fd_value (connection->outgoing_counter);
6219 CONNECTION_UNLOCK (connection);