1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-connection.c DBusConnection object
4 * Copyright (C) 2002, 2003, 2004, 2005 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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-threads.h"
37 #include "dbus-protocol.h"
38 #include "dbus-dataslot.h"
39 #include "dbus-string.h"
40 #include "dbus-pending-call.h"
41 #include "dbus-object-tree.h"
42 #include "dbus-threads-internal.h"
45 #ifdef DBUS_DISABLE_CHECKS
46 #define TOOK_LOCK_CHECK(connection)
47 #define RELEASING_LOCK_CHECK(connection)
48 #define HAVE_LOCK_CHECK(connection)
50 #define TOOK_LOCK_CHECK(connection) do { \
51 _dbus_assert (!(connection)->have_connection_lock); \
52 (connection)->have_connection_lock = TRUE; \
54 #define RELEASING_LOCK_CHECK(connection) do { \
55 _dbus_assert ((connection)->have_connection_lock); \
56 (connection)->have_connection_lock = FALSE; \
58 #define HAVE_LOCK_CHECK(connection) _dbus_assert ((connection)->have_connection_lock)
59 /* A "DO_NOT_HAVE_LOCK_CHECK" is impossible since we need the lock to check the flag */
64 #define CONNECTION_LOCK(connection) do { \
65 if (TRACE_LOCKS) { _dbus_verbose (" LOCK: %s\n", _DBUS_FUNCTION_NAME); } \
66 _dbus_mutex_lock ((connection)->mutex); \
67 TOOK_LOCK_CHECK (connection); \
70 #define CONNECTION_UNLOCK(connection) do { \
71 if (TRACE_LOCKS) { _dbus_verbose (" UNLOCK: %s\n", _DBUS_FUNCTION_NAME); } \
72 RELEASING_LOCK_CHECK (connection); \
73 _dbus_mutex_unlock ((connection)->mutex); \
76 #define DISPATCH_STATUS_NAME(s) \
77 ((s) == DBUS_DISPATCH_COMPLETE ? "complete" : \
78 (s) == DBUS_DISPATCH_DATA_REMAINS ? "data remains" : \
79 (s) == DBUS_DISPATCH_NEED_MEMORY ? "need memory" : \
83 * @defgroup DBusConnection DBusConnection
85 * @brief Connection to another application
87 * A DBusConnection represents a connection to another
88 * application. Messages can be sent and received via this connection.
89 * The other application may be a message bus; for convenience, the
90 * function dbus_bus_get() is provided to automatically open a
91 * connection to the well-known message buses.
93 * In brief a DBusConnection is a message queue associated with some
94 * message transport mechanism such as a socket. The connection
95 * maintains a queue of incoming messages and a queue of outgoing
98 * Incoming messages are normally processed by calling
99 * dbus_connection_dispatch(). dbus_connection_dispatch() runs any
100 * handlers registered for the topmost message in the message queue,
101 * then discards the message, then returns.
103 * dbus_connection_get_dispatch_status() indicates whether
104 * messages are currently in the queue that need dispatching.
105 * dbus_connection_set_dispatch_status_function() allows
106 * you to set a function to be used to monitor the dispatch status.
108 * If you're using GLib or Qt add-on libraries for D-Bus, there are
109 * special convenience APIs in those libraries that hide
110 * all the details of dispatch and watch/timeout monitoring.
111 * For example, dbus_connection_setup_with_g_main().
113 * If you aren't using these add-on libraries, you have to manually
114 * call dbus_connection_set_dispatch_status_function(),
115 * dbus_connection_set_watch_functions(),
116 * dbus_connection_set_timeout_functions() providing appropriate
117 * functions to integrate the connection with your application's main
120 * When you use dbus_connection_send() or one of its variants to send
121 * a message, the message is added to the outgoing queue. It's
122 * actually written to the network later; either in
123 * dbus_watch_handle() invoked by your main loop, or in
124 * dbus_connection_flush() which blocks until it can write out the
125 * entire outgoing queue. The GLib/Qt add-on libraries again
126 * handle the details here for you by setting up watch functions.
128 * When a connection is disconnected, you are guaranteed to get a
129 * signal "Disconnected" from the interface
130 * #DBUS_INTERFACE_LOCAL, path
133 * You may not drop the last reference to a #DBusConnection
134 * until that connection has been disconnected.
136 * You may dispatch the unprocessed incoming message queue even if the
137 * connection is disconnected. However, "Disconnected" will always be
138 * the last message in the queue (obviously no messages are received
139 * after disconnection).
141 * #DBusConnection has thread locks and drops them when invoking user
142 * callbacks, so in general is transparently threadsafe. However,
143 * #DBusMessage does NOT have thread locks; you must not send the same
144 * message to multiple #DBusConnection that will be used from
149 * @defgroup DBusConnectionInternals DBusConnection implementation details
150 * @ingroup DBusInternals
151 * @brief Implementation details of DBusConnection
157 * Internal struct representing a message filter function
159 typedef struct DBusMessageFilter DBusMessageFilter;
162 * Internal struct representing a message filter function
164 struct DBusMessageFilter
166 DBusAtomic refcount; /**< Reference count */
167 DBusHandleMessageFunction function; /**< Function to call to filter */
168 void *user_data; /**< User data for the function */
169 DBusFreeFunction free_user_data_function; /**< Function to free the user data */
174 * Internals of DBusPreallocatedSend
176 struct DBusPreallocatedSend
178 DBusConnection *connection; /**< Connection we'd send the message to */
179 DBusList *queue_link; /**< Preallocated link in the queue */
180 DBusList *counter_link; /**< Preallocated link in the resource counter */
183 static dbus_bool_t _dbus_modify_sigpipe = TRUE;
186 * Implementation details of DBusConnection. All fields are private.
188 struct DBusConnection
190 DBusAtomic refcount; /**< Reference count. */
192 DBusMutex *mutex; /**< Lock on the entire DBusConnection */
194 DBusMutex *dispatch_mutex; /**< Protects dispatch_acquired */
195 DBusCondVar *dispatch_cond; /**< Notify when dispatch_acquired is available */
196 DBusMutex *io_path_mutex; /**< Protects io_path_acquired */
197 DBusCondVar *io_path_cond; /**< Notify when io_path_acquired is available */
199 DBusList *outgoing_messages; /**< Queue of messages we need to send, send the end of the list first. */
200 DBusList *incoming_messages; /**< Queue of messages we have received, end of the list received most recently. */
202 DBusMessage *message_borrowed; /**< Filled in if the first incoming message has been borrowed;
203 * dispatch_acquired will be set by the borrower
206 int n_outgoing; /**< Length of outgoing queue. */
207 int n_incoming; /**< Length of incoming queue. */
209 DBusCounter *outgoing_counter; /**< Counts size of outgoing messages. */
211 DBusTransport *transport; /**< Object that sends/receives messages over network. */
212 DBusWatchList *watches; /**< Stores active watches. */
213 DBusTimeoutList *timeouts; /**< Stores active timeouts. */
215 DBusList *filter_list; /**< List of filters. */
217 DBusDataSlotList slot_list; /**< Data stored by allocated integer ID */
219 DBusHashTable *pending_replies; /**< Hash of message serials to #DBusPendingCall. */
221 dbus_uint32_t client_serial; /**< Client serial. Increments each time a message is sent */
222 DBusList *disconnect_message_link; /**< Preallocated list node for queueing the disconnection message */
224 DBusWakeupMainFunction wakeup_main_function; /**< Function to wake up the mainloop */
225 void *wakeup_main_data; /**< Application data for wakeup_main_function */
226 DBusFreeFunction free_wakeup_main_data; /**< free wakeup_main_data */
228 DBusDispatchStatusFunction dispatch_status_function; /**< Function on dispatch status changes */
229 void *dispatch_status_data; /**< Application data for dispatch_status_function */
230 DBusFreeFunction free_dispatch_status_data; /**< free dispatch_status_data */
232 DBusDispatchStatus last_dispatch_status; /**< The last dispatch status we reported to the application. */
234 DBusList *link_cache; /**< A cache of linked list links to prevent contention
235 * for the global linked list mempool lock
237 DBusObjectTree *objects; /**< Object path handlers registered with this connection */
239 char *server_guid; /**< GUID of server if we are in shared_connections, #NULL if server GUID is unknown or connection is private */
241 unsigned int shareable : 1; /**< #TRUE if connection can go in shared_connections once we know the GUID */
243 unsigned int shared : 1; /** < #TRUE if connection is shared and we hold a ref to it */
245 unsigned int dispatch_acquired : 1; /**< Someone has dispatch path (can drain incoming queue) */
246 unsigned int io_path_acquired : 1; /**< Someone has transport io path (can use the transport to read/write messages) */
248 unsigned int exit_on_disconnect : 1; /**< If #TRUE, exit after handling disconnect signal */
250 #ifndef DBUS_DISABLE_CHECKS
251 unsigned int have_connection_lock : 1; /**< Used to check locking */
254 #ifndef DBUS_DISABLE_CHECKS
255 int generation; /**< _dbus_current_generation that should correspond to this connection */
259 static DBusDispatchStatus _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection);
260 static void _dbus_connection_update_dispatch_status_and_unlock (DBusConnection *connection,
261 DBusDispatchStatus new_status);
262 static void _dbus_connection_last_unref (DBusConnection *connection);
263 static void _dbus_connection_acquire_dispatch (DBusConnection *connection);
264 static void _dbus_connection_release_dispatch (DBusConnection *connection);
265 static DBusDispatchStatus _dbus_connection_flush_unlocked (DBusConnection *connection);
267 static DBusMessageFilter *
268 _dbus_message_filter_ref (DBusMessageFilter *filter)
270 _dbus_assert (filter->refcount.value > 0);
271 _dbus_atomic_inc (&filter->refcount);
277 _dbus_message_filter_unref (DBusMessageFilter *filter)
279 _dbus_assert (filter->refcount.value > 0);
281 if (_dbus_atomic_dec (&filter->refcount) == 1)
283 if (filter->free_user_data_function)
284 (* filter->free_user_data_function) (filter->user_data);
291 * Acquires the connection lock.
293 * @param connection the connection.
296 _dbus_connection_lock (DBusConnection *connection)
298 CONNECTION_LOCK (connection);
302 * Releases the connection lock.
304 * @param connection the connection.
307 _dbus_connection_unlock (DBusConnection *connection)
309 CONNECTION_UNLOCK (connection);
313 * Wakes up the main loop if it is sleeping
314 * Needed if we're e.g. queueing outgoing messages
315 * on a thread while the mainloop sleeps.
317 * @param connection the connection.
320 _dbus_connection_wakeup_mainloop (DBusConnection *connection)
322 if (connection->wakeup_main_function)
323 (*connection->wakeup_main_function) (connection->wakeup_main_data);
326 #ifdef DBUS_BUILD_TESTS
327 /* For now this function isn't used */
329 * Adds a message to the incoming message queue, returning #FALSE
330 * if there's insufficient memory to queue the message.
331 * Does not take over refcount of the message.
333 * @param connection the connection.
334 * @param message the message to queue.
335 * @returns #TRUE on success.
338 _dbus_connection_queue_received_message (DBusConnection *connection,
339 DBusMessage *message)
343 link = _dbus_list_alloc_link (message);
347 dbus_message_ref (message);
348 _dbus_connection_queue_received_message_link (connection, link);
354 * Gets the locks so we can examine them
356 * @param connection the connection.
357 * @param mutex_loc return for the location of the main mutex pointer
358 * @param dispatch_mutex_loc return location of the dispatch mutex pointer
359 * @param io_path_mutex_loc return location of the io_path mutex pointer
360 * @param dispatch_cond_loc return location of the dispatch conditional
362 * @param io_path_cond_loc return location of the io_path conditional
366 _dbus_connection_test_get_locks (DBusConnection *conn,
367 DBusMutex **mutex_loc,
368 DBusMutex **dispatch_mutex_loc,
369 DBusMutex **io_path_mutex_loc,
370 DBusCondVar **dispatch_cond_loc,
371 DBusCondVar **io_path_cond_loc)
373 *mutex_loc = conn->mutex;
374 *dispatch_mutex_loc = conn->dispatch_mutex;
375 *io_path_mutex_loc = conn->io_path_mutex;
376 *dispatch_cond_loc = conn->dispatch_cond;
377 *io_path_cond_loc = conn->io_path_cond;
382 * Adds a message-containing list link to the incoming message queue,
383 * taking ownership of the link and the message's current refcount.
384 * Cannot fail due to lack of memory.
386 * @param connection the connection.
387 * @param link the message link to queue.
390 _dbus_connection_queue_received_message_link (DBusConnection *connection,
393 DBusPendingCall *pending;
394 dbus_int32_t reply_serial;
395 DBusMessage *message;
397 _dbus_assert (_dbus_transport_get_is_authenticated (connection->transport));
399 _dbus_list_append_link (&connection->incoming_messages,
401 message = link->data;
403 /* If this is a reply we're waiting on, remove timeout for it */
404 reply_serial = dbus_message_get_reply_serial (message);
405 if (reply_serial != -1)
407 pending = _dbus_hash_table_lookup_int (connection->pending_replies,
411 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
412 _dbus_connection_remove_timeout_unlocked (connection,
413 _dbus_pending_call_get_timeout_unlocked (pending));
415 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
421 connection->n_incoming += 1;
423 _dbus_connection_wakeup_mainloop (connection);
425 _dbus_verbose ("Message %p (%d %s %s %s '%s' reply to %u) added to incoming queue %p, %d incoming\n",
427 dbus_message_get_type (message),
428 dbus_message_get_path (message) ?
429 dbus_message_get_path (message) :
431 dbus_message_get_interface (message) ?
432 dbus_message_get_interface (message) :
434 dbus_message_get_member (message) ?
435 dbus_message_get_member (message) :
437 dbus_message_get_signature (message),
438 dbus_message_get_reply_serial (message),
440 connection->n_incoming);}
443 * Adds a link + message to the incoming message queue.
444 * Can't fail. Takes ownership of both link and message.
446 * @param connection the connection.
447 * @param link the list node and message to queue.
449 * @todo 1.0? This needs to wake up the mainloop if it is in
450 * a poll/select and this is a multithreaded app.
453 _dbus_connection_queue_synthesized_message_link (DBusConnection *connection,
456 HAVE_LOCK_CHECK (connection);
458 _dbus_list_append_link (&connection->incoming_messages, link);
460 connection->n_incoming += 1;
462 _dbus_connection_wakeup_mainloop (connection);
464 _dbus_verbose ("Synthesized message %p added to incoming queue %p, %d incoming\n",
465 link->data, connection, connection->n_incoming);
470 * Checks whether there are messages in the outgoing message queue.
471 * Called with connection lock held.
473 * @param connection the connection.
474 * @returns #TRUE if the outgoing queue is non-empty.
477 _dbus_connection_has_messages_to_send_unlocked (DBusConnection *connection)
479 HAVE_LOCK_CHECK (connection);
480 return connection->outgoing_messages != NULL;
484 * Checks whether there are messages in the outgoing message queue.
486 * @param connection the connection.
487 * @returns #TRUE if the outgoing queue is non-empty.
490 dbus_connection_has_messages_to_send (DBusConnection *connection)
494 _dbus_return_val_if_fail (connection != NULL, FALSE);
496 CONNECTION_LOCK (connection);
497 v = _dbus_connection_has_messages_to_send_unlocked (connection);
498 CONNECTION_UNLOCK (connection);
504 * Gets the next outgoing message. The message remains in the
505 * queue, and the caller does not own a reference to it.
507 * @param connection the connection.
508 * @returns the message to be sent.
511 _dbus_connection_get_message_to_send (DBusConnection *connection)
513 HAVE_LOCK_CHECK (connection);
515 return _dbus_list_get_last (&connection->outgoing_messages);
519 * Notifies the connection that a message has been sent, so the
520 * message can be removed from the outgoing queue.
521 * Called with the connection lock held.
523 * @param connection the connection.
524 * @param message the message that was sent.
527 _dbus_connection_message_sent (DBusConnection *connection,
528 DBusMessage *message)
532 HAVE_LOCK_CHECK (connection);
534 /* This can be called before we even complete authentication, since
535 * it's called on disconnect to clean up the outgoing queue.
536 * It's also called as we successfully send each message.
539 link = _dbus_list_get_last_link (&connection->outgoing_messages);
540 _dbus_assert (link != NULL);
541 _dbus_assert (link->data == message);
543 /* Save this link in the link cache */
544 _dbus_list_unlink (&connection->outgoing_messages,
546 _dbus_list_prepend_link (&connection->link_cache, link);
548 connection->n_outgoing -= 1;
550 _dbus_verbose ("Message %p (%d %s %s %s '%s') removed from outgoing queue %p, %d left to send\n",
552 dbus_message_get_type (message),
553 dbus_message_get_path (message) ?
554 dbus_message_get_path (message) :
556 dbus_message_get_interface (message) ?
557 dbus_message_get_interface (message) :
559 dbus_message_get_member (message) ?
560 dbus_message_get_member (message) :
562 dbus_message_get_signature (message),
563 connection, connection->n_outgoing);
565 /* Save this link in the link cache also */
566 _dbus_message_remove_size_counter (message, connection->outgoing_counter,
568 _dbus_list_prepend_link (&connection->link_cache, link);
570 dbus_message_unref (message);
573 typedef dbus_bool_t (* DBusWatchAddFunction) (DBusWatchList *list,
575 typedef void (* DBusWatchRemoveFunction) (DBusWatchList *list,
577 typedef void (* DBusWatchToggleFunction) (DBusWatchList *list,
579 dbus_bool_t enabled);
582 protected_change_watch (DBusConnection *connection,
584 DBusWatchAddFunction add_function,
585 DBusWatchRemoveFunction remove_function,
586 DBusWatchToggleFunction toggle_function,
589 DBusWatchList *watches;
592 HAVE_LOCK_CHECK (connection);
594 /* This isn't really safe or reasonable; a better pattern is the "do everything, then
595 * drop lock and call out" one; but it has to be propagated up through all callers
598 watches = connection->watches;
601 connection->watches = NULL;
602 _dbus_connection_ref_unlocked (connection);
603 CONNECTION_UNLOCK (connection);
606 retval = (* add_function) (watches, watch);
607 else if (remove_function)
610 (* remove_function) (watches, watch);
615 (* toggle_function) (watches, watch, enabled);
618 CONNECTION_LOCK (connection);
619 connection->watches = watches;
620 _dbus_connection_unref_unlocked (connection);
630 * Adds a watch using the connection's DBusAddWatchFunction if
631 * available. Otherwise records the watch to be added when said
632 * function is available. Also re-adds the watch if the
633 * DBusAddWatchFunction changes. May fail due to lack of memory.
634 * Connection lock should be held when calling this.
636 * @param connection the connection.
637 * @param watch the watch to add.
638 * @returns #TRUE on success.
641 _dbus_connection_add_watch_unlocked (DBusConnection *connection,
644 return protected_change_watch (connection, watch,
645 _dbus_watch_list_add_watch,
650 * Removes a watch using the connection's DBusRemoveWatchFunction
651 * if available. It's an error to call this function on a watch
652 * that was not previously added.
653 * Connection lock should be held when calling this.
655 * @param connection the connection.
656 * @param watch the watch to remove.
659 _dbus_connection_remove_watch_unlocked (DBusConnection *connection,
662 protected_change_watch (connection, watch,
664 _dbus_watch_list_remove_watch,
669 * Toggles a watch and notifies app via connection's
670 * DBusWatchToggledFunction if available. It's an error to call this
671 * function on a watch that was not previously added.
672 * Connection lock should be held when calling this.
674 * @param connection the connection.
675 * @param watch the watch to toggle.
676 * @param enabled whether to enable or disable
679 _dbus_connection_toggle_watch_unlocked (DBusConnection *connection,
683 _dbus_assert (watch != NULL);
685 protected_change_watch (connection, watch,
687 _dbus_watch_list_toggle_watch,
691 typedef dbus_bool_t (* DBusTimeoutAddFunction) (DBusTimeoutList *list,
692 DBusTimeout *timeout);
693 typedef void (* DBusTimeoutRemoveFunction) (DBusTimeoutList *list,
694 DBusTimeout *timeout);
695 typedef void (* DBusTimeoutToggleFunction) (DBusTimeoutList *list,
696 DBusTimeout *timeout,
697 dbus_bool_t enabled);
700 protected_change_timeout (DBusConnection *connection,
701 DBusTimeout *timeout,
702 DBusTimeoutAddFunction add_function,
703 DBusTimeoutRemoveFunction remove_function,
704 DBusTimeoutToggleFunction toggle_function,
707 DBusTimeoutList *timeouts;
710 HAVE_LOCK_CHECK (connection);
712 /* This isn't really safe or reasonable; a better pattern is the "do everything, then
713 * drop lock and call out" one; but it has to be propagated up through all callers
716 timeouts = connection->timeouts;
719 connection->timeouts = NULL;
720 _dbus_connection_ref_unlocked (connection);
721 CONNECTION_UNLOCK (connection);
724 retval = (* add_function) (timeouts, timeout);
725 else if (remove_function)
728 (* remove_function) (timeouts, timeout);
733 (* toggle_function) (timeouts, timeout, enabled);
736 CONNECTION_LOCK (connection);
737 connection->timeouts = timeouts;
738 _dbus_connection_unref_unlocked (connection);
747 * Adds a timeout using the connection's DBusAddTimeoutFunction if
748 * available. Otherwise records the timeout to be added when said
749 * function is available. Also re-adds the timeout if the
750 * DBusAddTimeoutFunction changes. May fail due to lack of memory.
751 * The timeout will fire repeatedly until removed.
752 * Connection lock should be held when calling this.
754 * @param connection the connection.
755 * @param timeout the timeout to add.
756 * @returns #TRUE on success.
759 _dbus_connection_add_timeout_unlocked (DBusConnection *connection,
760 DBusTimeout *timeout)
762 return protected_change_timeout (connection, timeout,
763 _dbus_timeout_list_add_timeout,
768 * Removes a timeout using the connection's DBusRemoveTimeoutFunction
769 * if available. It's an error to call this function on a timeout
770 * that was not previously added.
771 * Connection lock should be held when calling this.
773 * @param connection the connection.
774 * @param timeout the timeout to remove.
777 _dbus_connection_remove_timeout_unlocked (DBusConnection *connection,
778 DBusTimeout *timeout)
780 protected_change_timeout (connection, timeout,
782 _dbus_timeout_list_remove_timeout,
787 * Toggles a timeout and notifies app via connection's
788 * DBusTimeoutToggledFunction if available. It's an error to call this
789 * function on a timeout that was not previously added.
790 * Connection lock should be held when calling this.
792 * @param connection the connection.
793 * @param timeout the timeout to toggle.
794 * @param enabled whether to enable or disable
797 _dbus_connection_toggle_timeout_unlocked (DBusConnection *connection,
798 DBusTimeout *timeout,
801 protected_change_timeout (connection, timeout,
803 _dbus_timeout_list_toggle_timeout,
808 _dbus_connection_attach_pending_call_unlocked (DBusConnection *connection,
809 DBusPendingCall *pending)
811 dbus_uint32_t reply_serial;
812 DBusTimeout *timeout;
814 HAVE_LOCK_CHECK (connection);
816 reply_serial = _dbus_pending_call_get_reply_serial_unlocked (pending);
818 _dbus_assert (reply_serial != 0);
820 timeout = _dbus_pending_call_get_timeout_unlocked (pending);
822 if (!_dbus_connection_add_timeout_unlocked (connection, timeout))
825 if (!_dbus_hash_table_insert_int (connection->pending_replies,
829 _dbus_connection_remove_timeout_unlocked (connection, timeout);
831 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
832 HAVE_LOCK_CHECK (connection);
836 _dbus_pending_call_set_timeout_added_unlocked (pending, TRUE);
838 _dbus_pending_call_ref_unlocked (pending);
840 HAVE_LOCK_CHECK (connection);
846 free_pending_call_on_hash_removal (void *data)
848 DBusPendingCall *pending;
849 DBusConnection *connection;
856 connection = _dbus_pending_call_get_connection_unlocked (pending);
858 HAVE_LOCK_CHECK (connection);
860 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
862 _dbus_connection_remove_timeout_unlocked (connection,
863 _dbus_pending_call_get_timeout_unlocked (pending));
865 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
868 /* FIXME 1.0? this is sort of dangerous and undesirable to drop the lock
869 * here, but the pending call finalizer could in principle call out to
870 * application code so we pretty much have to... some larger code reorg
873 _dbus_connection_ref_unlocked (connection);
874 _dbus_pending_call_unref_and_unlock (pending);
875 CONNECTION_LOCK (connection);
876 _dbus_connection_unref_unlocked (connection);
880 _dbus_connection_detach_pending_call_unlocked (DBusConnection *connection,
881 DBusPendingCall *pending)
883 /* This ends up unlocking to call the pending call finalizer, which is unexpected to
886 _dbus_hash_table_remove_int (connection->pending_replies,
887 _dbus_pending_call_get_reply_serial_unlocked (pending));
891 _dbus_connection_detach_pending_call_and_unlock (DBusConnection *connection,
892 DBusPendingCall *pending)
894 /* The idea here is to avoid finalizing the pending call
895 * with the lock held, since there's a destroy notifier
896 * in pending call that goes out to application code.
898 * There's an extra unlock inside the hash table
899 * "free pending call" function FIXME...
901 _dbus_pending_call_ref_unlocked (pending);
902 _dbus_hash_table_remove_int (connection->pending_replies,
903 _dbus_pending_call_get_reply_serial_unlocked (pending));
904 _dbus_pending_call_unref_and_unlock (pending);
908 * Removes a pending call from the connection, such that
909 * the pending reply will be ignored. May drop the last
910 * reference to the pending call.
912 * @param connection the connection
913 * @param pending the pending call
916 _dbus_connection_remove_pending_call (DBusConnection *connection,
917 DBusPendingCall *pending)
919 CONNECTION_LOCK (connection);
920 _dbus_connection_detach_pending_call_and_unlock (connection, pending);
924 * Acquire the transporter I/O path. This must be done before
925 * doing any I/O in the transporter. May sleep and drop the
926 * IO path mutex while waiting for the I/O path.
928 * @param connection the connection.
929 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
930 * @returns TRUE if the I/O path was acquired.
933 _dbus_connection_acquire_io_path (DBusConnection *connection,
934 int timeout_milliseconds)
936 dbus_bool_t we_acquired;
938 HAVE_LOCK_CHECK (connection);
940 /* We don't want the connection to vanish */
941 _dbus_connection_ref_unlocked (connection);
943 /* We will only touch io_path_acquired which is protected by our mutex */
944 CONNECTION_UNLOCK (connection);
946 _dbus_verbose ("%s locking io_path_mutex\n", _DBUS_FUNCTION_NAME);
947 _dbus_mutex_lock (connection->io_path_mutex);
949 _dbus_verbose ("%s start connection->io_path_acquired = %d timeout = %d\n",
950 _DBUS_FUNCTION_NAME, connection->io_path_acquired, timeout_milliseconds);
954 if (connection->io_path_acquired)
956 if (timeout_milliseconds != -1)
958 _dbus_verbose ("%s waiting %d for IO path to be acquirable\n",
959 _DBUS_FUNCTION_NAME, timeout_milliseconds);
960 _dbus_condvar_wait_timeout (connection->io_path_cond,
961 connection->io_path_mutex,
962 timeout_milliseconds);
966 while (connection->io_path_acquired)
968 _dbus_verbose ("%s waiting for IO path to be acquirable\n", _DBUS_FUNCTION_NAME);
969 _dbus_condvar_wait (connection->io_path_cond,
970 connection->io_path_mutex);
975 if (!connection->io_path_acquired)
978 connection->io_path_acquired = TRUE;
981 _dbus_verbose ("%s end connection->io_path_acquired = %d we_acquired = %d\n",
982 _DBUS_FUNCTION_NAME, connection->io_path_acquired, we_acquired);
984 _dbus_verbose ("%s unlocking io_path_mutex\n", _DBUS_FUNCTION_NAME);
985 _dbus_mutex_unlock (connection->io_path_mutex);
987 CONNECTION_LOCK (connection);
989 HAVE_LOCK_CHECK (connection);
991 _dbus_connection_unref_unlocked (connection);
997 * Release the I/O path when you're done with it. Only call
998 * after you've acquired the I/O. Wakes up at most one thread
999 * currently waiting to acquire the I/O path.
1001 * @param connection the connection.
1004 _dbus_connection_release_io_path (DBusConnection *connection)
1006 HAVE_LOCK_CHECK (connection);
1008 _dbus_verbose ("%s locking io_path_mutex\n", _DBUS_FUNCTION_NAME);
1009 _dbus_mutex_lock (connection->io_path_mutex);
1011 _dbus_assert (connection->io_path_acquired);
1013 _dbus_verbose ("%s start connection->io_path_acquired = %d\n",
1014 _DBUS_FUNCTION_NAME, connection->io_path_acquired);
1016 connection->io_path_acquired = FALSE;
1017 _dbus_condvar_wake_one (connection->io_path_cond);
1019 _dbus_verbose ("%s unlocking io_path_mutex\n", _DBUS_FUNCTION_NAME);
1020 _dbus_mutex_unlock (connection->io_path_mutex);
1024 * Queues incoming messages and sends outgoing messages for this
1025 * connection, optionally blocking in the process. Each call to
1026 * _dbus_connection_do_iteration_unlocked() will call select() or poll() one
1027 * time and then read or write data if possible.
1029 * The purpose of this function is to be able to flush outgoing
1030 * messages or queue up incoming messages without returning
1031 * control to the application and causing reentrancy weirdness.
1033 * The flags parameter allows you to specify whether to
1034 * read incoming messages, write outgoing messages, or both,
1035 * and whether to block if no immediate action is possible.
1037 * The timeout_milliseconds parameter does nothing unless the
1038 * iteration is blocking.
1040 * If there are no outgoing messages and DBUS_ITERATION_DO_READING
1041 * wasn't specified, then it's impossible to block, even if
1042 * you specify DBUS_ITERATION_BLOCK; in that case the function
1043 * returns immediately.
1045 * Called with connection lock held.
1047 * @param connection the connection.
1048 * @param flags iteration flags.
1049 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
1052 _dbus_connection_do_iteration_unlocked (DBusConnection *connection,
1054 int timeout_milliseconds)
1056 _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
1058 HAVE_LOCK_CHECK (connection);
1060 if (connection->n_outgoing == 0)
1061 flags &= ~DBUS_ITERATION_DO_WRITING;
1063 if (_dbus_connection_acquire_io_path (connection,
1064 (flags & DBUS_ITERATION_BLOCK) ? timeout_milliseconds : 0))
1066 HAVE_LOCK_CHECK (connection);
1068 _dbus_transport_do_iteration (connection->transport,
1069 flags, timeout_milliseconds);
1070 _dbus_connection_release_io_path (connection);
1073 HAVE_LOCK_CHECK (connection);
1075 _dbus_verbose ("%s end\n", _DBUS_FUNCTION_NAME);
1079 * Creates a new connection for the given transport. A transport
1080 * represents a message stream that uses some concrete mechanism, such
1081 * as UNIX domain sockets. May return #NULL if insufficient
1082 * memory exists to create the connection.
1084 * @param transport the transport.
1085 * @returns the new connection, or #NULL on failure.
1088 _dbus_connection_new_for_transport (DBusTransport *transport)
1090 DBusConnection *connection;
1091 DBusWatchList *watch_list;
1092 DBusTimeoutList *timeout_list;
1093 DBusHashTable *pending_replies;
1094 DBusList *disconnect_link;
1095 DBusMessage *disconnect_message;
1096 DBusCounter *outgoing_counter;
1097 DBusObjectTree *objects;
1101 pending_replies = NULL;
1102 timeout_list = NULL;
1103 disconnect_link = NULL;
1104 disconnect_message = NULL;
1105 outgoing_counter = NULL;
1108 watch_list = _dbus_watch_list_new ();
1109 if (watch_list == NULL)
1112 timeout_list = _dbus_timeout_list_new ();
1113 if (timeout_list == NULL)
1117 _dbus_hash_table_new (DBUS_HASH_INT,
1119 (DBusFreeFunction)free_pending_call_on_hash_removal);
1120 if (pending_replies == NULL)
1123 connection = dbus_new0 (DBusConnection, 1);
1124 if (connection == NULL)
1127 _dbus_mutex_new_at_location (&connection->mutex);
1128 if (connection->mutex == NULL)
1131 _dbus_mutex_new_at_location (&connection->io_path_mutex);
1132 if (connection->io_path_mutex == NULL)
1135 _dbus_mutex_new_at_location (&connection->dispatch_mutex);
1136 if (connection->dispatch_mutex == NULL)
1139 _dbus_condvar_new_at_location (&connection->dispatch_cond);
1140 if (connection->dispatch_cond == NULL)
1143 _dbus_condvar_new_at_location (&connection->io_path_cond);
1144 if (connection->io_path_cond == NULL)
1147 disconnect_message = dbus_message_new_signal (DBUS_PATH_LOCAL,
1148 DBUS_INTERFACE_LOCAL,
1151 if (disconnect_message == NULL)
1154 disconnect_link = _dbus_list_alloc_link (disconnect_message);
1155 if (disconnect_link == NULL)
1158 outgoing_counter = _dbus_counter_new ();
1159 if (outgoing_counter == NULL)
1162 objects = _dbus_object_tree_new (connection);
1163 if (objects == NULL)
1166 if (_dbus_modify_sigpipe)
1167 _dbus_disable_sigpipe ();
1169 connection->refcount.value = 1;
1170 connection->transport = transport;
1171 connection->watches = watch_list;
1172 connection->timeouts = timeout_list;
1173 connection->pending_replies = pending_replies;
1174 connection->outgoing_counter = outgoing_counter;
1175 connection->filter_list = NULL;
1176 connection->last_dispatch_status = DBUS_DISPATCH_COMPLETE; /* so we're notified first time there's data */
1177 connection->objects = objects;
1178 connection->exit_on_disconnect = FALSE;
1179 connection->shareable = FALSE;
1180 #ifndef DBUS_DISABLE_CHECKS
1181 connection->generation = _dbus_current_generation;
1184 _dbus_data_slot_list_init (&connection->slot_list);
1186 connection->client_serial = 1;
1188 connection->disconnect_message_link = disconnect_link;
1190 CONNECTION_LOCK (connection);
1192 if (!_dbus_transport_set_connection (transport, connection))
1195 _dbus_transport_ref (transport);
1197 CONNECTION_UNLOCK (connection);
1202 if (disconnect_message != NULL)
1203 dbus_message_unref (disconnect_message);
1205 if (disconnect_link != NULL)
1206 _dbus_list_free_link (disconnect_link);
1208 if (connection != NULL)
1210 _dbus_condvar_free_at_location (&connection->io_path_cond);
1211 _dbus_condvar_free_at_location (&connection->dispatch_cond);
1212 _dbus_mutex_free_at_location (&connection->mutex);
1213 _dbus_mutex_free_at_location (&connection->io_path_mutex);
1214 _dbus_mutex_free_at_location (&connection->dispatch_mutex);
1215 dbus_free (connection);
1217 if (pending_replies)
1218 _dbus_hash_table_unref (pending_replies);
1221 _dbus_watch_list_free (watch_list);
1224 _dbus_timeout_list_free (timeout_list);
1226 if (outgoing_counter)
1227 _dbus_counter_unref (outgoing_counter);
1230 _dbus_object_tree_unref (objects);
1236 * Increments the reference count of a DBusConnection.
1237 * Requires that the caller already holds the connection lock.
1239 * @param connection the connection.
1240 * @returns the connection.
1243 _dbus_connection_ref_unlocked (DBusConnection *connection)
1245 _dbus_assert (connection != NULL);
1246 _dbus_assert (connection->generation == _dbus_current_generation);
1248 HAVE_LOCK_CHECK (connection);
1250 #ifdef DBUS_HAVE_ATOMIC_INT
1251 _dbus_atomic_inc (&connection->refcount);
1253 _dbus_assert (connection->refcount.value > 0);
1254 connection->refcount.value += 1;
1261 * Decrements the reference count of a DBusConnection.
1262 * Requires that the caller already holds the connection lock.
1264 * @param connection the connection.
1267 _dbus_connection_unref_unlocked (DBusConnection *connection)
1269 dbus_bool_t last_unref;
1271 HAVE_LOCK_CHECK (connection);
1273 _dbus_assert (connection != NULL);
1275 /* The connection lock is better than the global
1276 * lock in the atomic increment fallback
1279 #ifdef DBUS_HAVE_ATOMIC_INT
1280 last_unref = (_dbus_atomic_dec (&connection->refcount) == 1);
1282 _dbus_assert (connection->refcount.value > 0);
1284 connection->refcount.value -= 1;
1285 last_unref = (connection->refcount.value == 0);
1287 printf ("unref_unlocked() connection %p count = %d\n", connection, connection->refcount.value);
1292 _dbus_connection_last_unref (connection);
1295 static dbus_uint32_t
1296 _dbus_connection_get_next_client_serial (DBusConnection *connection)
1300 serial = connection->client_serial++;
1302 if (connection->client_serial < 0)
1303 connection->client_serial = 1;
1309 * A callback for use with dbus_watch_new() to create a DBusWatch.
1311 * @todo This is basically a hack - we could delete _dbus_transport_handle_watch()
1312 * and the virtual handle_watch in DBusTransport if we got rid of it.
1313 * The reason this is some work is threading, see the _dbus_connection_handle_watch()
1316 * @param watch the watch.
1317 * @param condition the current condition of the file descriptors being watched.
1318 * @param data must be a pointer to a #DBusConnection
1319 * @returns #FALSE if the IO condition may not have been fully handled due to lack of memory
1322 _dbus_connection_handle_watch (DBusWatch *watch,
1323 unsigned int condition,
1326 DBusConnection *connection;
1328 DBusDispatchStatus status;
1332 _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
1334 CONNECTION_LOCK (connection);
1335 _dbus_connection_acquire_io_path (connection, -1);
1336 HAVE_LOCK_CHECK (connection);
1337 retval = _dbus_transport_handle_watch (connection->transport,
1340 _dbus_connection_release_io_path (connection);
1342 HAVE_LOCK_CHECK (connection);
1344 _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
1346 status = _dbus_connection_get_dispatch_status_unlocked (connection);
1348 /* this calls out to user code */
1349 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1351 _dbus_verbose ("%s end\n", _DBUS_FUNCTION_NAME);
1356 _DBUS_DEFINE_GLOBAL_LOCK (shared_connections);
1357 static DBusHashTable *shared_connections = NULL;
1360 shared_connections_shutdown (void *data)
1362 _DBUS_LOCK (shared_connections);
1364 _dbus_assert (_dbus_hash_table_get_n_entries (shared_connections) == 0);
1366 _dbus_hash_table_unref (shared_connections);
1367 shared_connections = NULL;
1369 _DBUS_UNLOCK (shared_connections);
1373 connection_lookup_shared (DBusAddressEntry *entry,
1374 DBusConnection **result)
1376 _dbus_verbose ("checking for existing connection\n");
1380 _DBUS_LOCK (shared_connections);
1382 if (shared_connections == NULL)
1384 _dbus_verbose ("creating shared_connections hash table\n");
1386 shared_connections = _dbus_hash_table_new (DBUS_HASH_STRING,
1389 if (shared_connections == NULL)
1391 _DBUS_UNLOCK (shared_connections);
1395 if (!_dbus_register_shutdown_func (shared_connections_shutdown, NULL))
1397 _dbus_hash_table_unref (shared_connections);
1398 shared_connections = NULL;
1399 _DBUS_UNLOCK (shared_connections);
1403 _dbus_verbose (" successfully created shared_connections\n");
1405 _DBUS_UNLOCK (shared_connections);
1406 return TRUE; /* no point looking up in the hash we just made */
1412 guid = dbus_address_entry_get_value (entry, "guid");
1416 *result = _dbus_hash_table_lookup_string (shared_connections,
1421 /* The DBusConnection can't have been disconnected
1422 * between the lookup and this code, because the
1423 * disconnection will take the shared_connections lock to
1424 * remove the connection. It can't have been finalized
1425 * since you have to disconnect prior to finalize.
1427 * Thus it's safe to ref the connection.
1429 dbus_connection_ref (*result);
1431 _dbus_verbose ("looked up existing connection to server guid %s\n",
1436 _DBUS_UNLOCK (shared_connections);
1442 connection_record_shared_unlocked (DBusConnection *connection,
1446 char *guid_in_connection;
1448 /* A separate copy of the key is required in the hash table, because
1449 * we don't have a lock on the connection when we are doing a hash
1453 _dbus_assert (connection->server_guid == NULL);
1454 _dbus_assert (connection->shareable);
1456 guid_key = _dbus_strdup (guid);
1457 if (guid_key == NULL)
1460 guid_in_connection = _dbus_strdup (guid);
1461 if (guid_in_connection == NULL)
1463 dbus_free (guid_key);
1467 _DBUS_LOCK (shared_connections);
1468 _dbus_assert (shared_connections != NULL);
1470 if (!_dbus_hash_table_insert_string (shared_connections,
1471 guid_key, connection))
1473 dbus_free (guid_key);
1474 dbus_free (guid_in_connection);
1475 _DBUS_UNLOCK (shared_connections);
1479 connection->server_guid = guid_in_connection;
1480 connection->shared = TRUE;
1482 /* get a hard ref on this connection */
1483 dbus_connection_ref (connection);
1485 _dbus_verbose ("stored connection to %s to be shared\n",
1486 connection->server_guid);
1488 _DBUS_UNLOCK (shared_connections);
1490 _dbus_assert (connection->server_guid != NULL);
1496 connection_forget_shared_unlocked (DBusConnection *connection)
1498 HAVE_LOCK_CHECK (connection);
1500 if (connection->server_guid == NULL)
1503 _dbus_verbose ("dropping connection to %s out of the shared table\n",
1504 connection->server_guid);
1506 _DBUS_LOCK (shared_connections);
1508 if (!_dbus_hash_table_remove_string (shared_connections,
1509 connection->server_guid))
1510 _dbus_assert_not_reached ("connection was not in the shared table");
1512 dbus_free (connection->server_guid);
1513 connection->server_guid = NULL;
1515 /* remove the hash ref */
1516 _dbus_connection_unref_unlocked (connection);
1517 _DBUS_UNLOCK (shared_connections);
1520 static DBusConnection*
1521 connection_try_from_address_entry (DBusAddressEntry *entry,
1524 DBusTransport *transport;
1525 DBusConnection *connection;
1527 transport = _dbus_transport_open (entry, error);
1529 if (transport == NULL)
1531 _DBUS_ASSERT_ERROR_IS_SET (error);
1535 connection = _dbus_connection_new_for_transport (transport);
1537 _dbus_transport_unref (transport);
1539 if (connection == NULL)
1541 _DBUS_SET_OOM (error);
1545 #ifndef DBUS_DISABLE_CHECKS
1546 _dbus_assert (!connection->have_connection_lock);
1552 * If the shared parameter is true, then any existing connection will
1553 * be used (and if a new connection is created, it will be available
1554 * for use by others). If the shared parameter is false, a new
1555 * connection will always be created, and the new connection will
1556 * never be returned to other callers.
1558 * @param address the address
1559 * @param shared whether the connection is shared or private
1560 * @param error error return
1561 * @returns the connection or #NULL on error
1563 static DBusConnection*
1564 _dbus_connection_open_internal (const char *address,
1568 DBusConnection *connection;
1569 DBusAddressEntry **entries;
1570 DBusError tmp_error;
1571 DBusError first_error;
1574 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1576 _dbus_verbose ("opening %s connection to: %s\n",
1577 shared ? "shared" : "private", address);
1579 if (!dbus_parse_address (address, &entries, &len, error))
1582 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1586 dbus_error_init (&tmp_error);
1587 dbus_error_init (&first_error);
1588 for (i = 0; i < len; i++)
1592 if (!connection_lookup_shared (entries[i], &connection))
1593 _DBUS_SET_OOM (&tmp_error);
1596 if (connection == NULL)
1598 connection = connection_try_from_address_entry (entries[i],
1601 if (connection != NULL && shared)
1605 connection->shareable = TRUE;
1607 guid = dbus_address_entry_get_value (entries[i], "guid");
1609 /* we don't have a connection lock but we know nobody
1610 * else has a handle to the connection
1614 !connection_record_shared_unlocked (connection, guid))
1616 _DBUS_SET_OOM (&tmp_error);
1617 _dbus_connection_close_internal (connection);
1618 dbus_connection_unref (connection);
1622 /* but as of now the connection is possibly shared
1623 * since another thread could have pulled it from the table
1631 _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
1634 dbus_move_error (&tmp_error, &first_error);
1636 dbus_error_free (&tmp_error);
1639 /* NOTE we don't have a lock on a possibly-shared connection object */
1641 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1642 _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
1644 if (connection == NULL)
1646 _DBUS_ASSERT_ERROR_IS_SET (&first_error);
1647 dbus_move_error (&first_error, error);
1651 dbus_error_free (&first_error);
1654 dbus_address_entries_free (entries);
1661 * @addtogroup DBusConnection
1667 * Gets a connection to a remote address. If a connection to the given
1668 * address already exists, returns the existing connection with its
1669 * reference count incremented. Otherwise, returns a new connection
1670 * and saves the new connection for possible re-use if a future call
1671 * to dbus_connection_open() asks to connect to the same server.
1673 * Use dbus_connection_open_private() to get a dedicated connection
1674 * not shared with other callers of dbus_connection_open().
1676 * If the open fails, the function returns #NULL, and provides a
1677 * reason for the failure in the error parameter. Pass #NULL for the
1678 * error parameter if you aren't interested in the reason for
1681 * @param address the address.
1682 * @param error address where an error can be returned.
1683 * @returns new connection, or #NULL on failure.
1686 dbus_connection_open (const char *address,
1689 DBusConnection *connection;
1691 _dbus_return_val_if_fail (address != NULL, NULL);
1692 _dbus_return_val_if_error_is_set (error, NULL);
1694 connection = _dbus_connection_open_internal (address,
1702 * Opens a new, dedicated connection to a remote address. Unlike
1703 * dbus_connection_open(), always creates a new connection.
1704 * This connection will not be saved or recycled by libdbus.
1706 * If the open fails, the function returns #NULL, and provides a
1707 * reason for the failure in the error parameter. Pass #NULL for the
1708 * error parameter if you aren't interested in the reason for
1711 * @param address the address.
1712 * @param error address where an error can be returned.
1713 * @returns new connection, or #NULL on failure.
1716 dbus_connection_open_private (const char *address,
1719 DBusConnection *connection;
1721 _dbus_return_val_if_fail (address != NULL, NULL);
1722 _dbus_return_val_if_error_is_set (error, NULL);
1724 connection = _dbus_connection_open_internal (address,
1732 * Increments the reference count of a DBusConnection.
1734 * @param connection the connection.
1735 * @returns the connection.
1738 dbus_connection_ref (DBusConnection *connection)
1740 _dbus_return_val_if_fail (connection != NULL, NULL);
1741 _dbus_return_val_if_fail (connection->generation == _dbus_current_generation, NULL);
1743 /* The connection lock is better than the global
1744 * lock in the atomic increment fallback
1747 #ifdef DBUS_HAVE_ATOMIC_INT
1748 _dbus_atomic_inc (&connection->refcount);
1750 CONNECTION_LOCK (connection);
1751 _dbus_assert (connection->refcount.value > 0);
1753 connection->refcount.value += 1;
1754 CONNECTION_UNLOCK (connection);
1761 free_outgoing_message (void *element,
1764 DBusMessage *message = element;
1765 DBusConnection *connection = data;
1767 _dbus_message_remove_size_counter (message,
1768 connection->outgoing_counter,
1770 dbus_message_unref (message);
1773 /* This is run without the mutex held, but after the last reference
1774 * to the connection has been dropped we should have no thread-related
1778 _dbus_connection_last_unref (DBusConnection *connection)
1782 _dbus_verbose ("Finalizing connection %p\n", connection);
1784 _dbus_assert (connection->refcount.value == 0);
1786 /* You have to disconnect the connection before unref:ing it. Otherwise
1787 * you won't get the disconnected message.
1789 _dbus_assert (!_dbus_transport_get_is_connected (connection->transport));
1790 _dbus_assert (connection->server_guid == NULL);
1792 /* ---- We're going to call various application callbacks here, hope it doesn't break anything... */
1793 _dbus_object_tree_free_all_unlocked (connection->objects);
1795 dbus_connection_set_dispatch_status_function (connection, NULL, NULL, NULL);
1796 dbus_connection_set_wakeup_main_function (connection, NULL, NULL, NULL);
1797 dbus_connection_set_unix_user_function (connection, NULL, NULL, NULL);
1799 _dbus_watch_list_free (connection->watches);
1800 connection->watches = NULL;
1802 _dbus_timeout_list_free (connection->timeouts);
1803 connection->timeouts = NULL;
1805 _dbus_data_slot_list_free (&connection->slot_list);
1807 link = _dbus_list_get_first_link (&connection->filter_list);
1808 while (link != NULL)
1810 DBusMessageFilter *filter = link->data;
1811 DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
1813 filter->function = NULL;
1814 _dbus_message_filter_unref (filter); /* calls app callback */
1819 _dbus_list_clear (&connection->filter_list);
1821 /* ---- Done with stuff that invokes application callbacks */
1823 _dbus_object_tree_unref (connection->objects);
1825 _dbus_hash_table_unref (connection->pending_replies);
1826 connection->pending_replies = NULL;
1828 _dbus_list_clear (&connection->filter_list);
1830 _dbus_list_foreach (&connection->outgoing_messages,
1831 free_outgoing_message,
1833 _dbus_list_clear (&connection->outgoing_messages);
1835 _dbus_list_foreach (&connection->incoming_messages,
1836 (DBusForeachFunction) dbus_message_unref,
1838 _dbus_list_clear (&connection->incoming_messages);
1840 _dbus_counter_unref (connection->outgoing_counter);
1842 _dbus_transport_unref (connection->transport);
1844 if (connection->disconnect_message_link)
1846 DBusMessage *message = connection->disconnect_message_link->data;
1847 dbus_message_unref (message);
1848 _dbus_list_free_link (connection->disconnect_message_link);
1851 _dbus_list_clear (&connection->link_cache);
1853 _dbus_condvar_free_at_location (&connection->dispatch_cond);
1854 _dbus_condvar_free_at_location (&connection->io_path_cond);
1856 _dbus_mutex_free_at_location (&connection->io_path_mutex);
1857 _dbus_mutex_free_at_location (&connection->dispatch_mutex);
1859 _dbus_mutex_free_at_location (&connection->mutex);
1861 dbus_free (connection);
1865 * Decrements the reference count of a DBusConnection, and finalizes
1866 * it if the count reaches zero. It is a bug to drop the last reference
1867 * to a connection that has not been disconnected.
1869 * @todo in practice it can be quite tricky to never unref a connection
1870 * that's still connected; maybe there's some way we could avoid
1873 * @param connection the connection.
1876 dbus_connection_unref (DBusConnection *connection)
1878 dbus_bool_t last_unref;
1880 _dbus_return_if_fail (connection != NULL);
1881 _dbus_return_if_fail (connection->generation == _dbus_current_generation);
1883 /* The connection lock is better than the global
1884 * lock in the atomic increment fallback
1887 #ifdef DBUS_HAVE_ATOMIC_INT
1888 last_unref = (_dbus_atomic_dec (&connection->refcount) == 1);
1890 CONNECTION_LOCK (connection);
1892 _dbus_assert (connection->refcount.value > 0);
1894 connection->refcount.value -= 1;
1895 last_unref = (connection->refcount.value == 0);
1898 printf ("unref() connection %p count = %d\n", connection, connection->refcount.value);
1901 CONNECTION_UNLOCK (connection);
1905 _dbus_connection_last_unref (connection);
1909 _dbus_connection_close_internal_and_unlock (DBusConnection *connection)
1911 DBusDispatchStatus status;
1913 _dbus_verbose ("Disconnecting %p\n", connection);
1915 _dbus_transport_disconnect (connection->transport);
1917 _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
1918 status = _dbus_connection_get_dispatch_status_unlocked (connection);
1920 /* this calls out to user code */
1921 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1925 _dbus_connection_close_internal (DBusConnection *connection)
1927 _dbus_assert (connection != NULL);
1928 _dbus_assert (connection->generation == _dbus_current_generation);
1930 CONNECTION_LOCK (connection);
1931 _dbus_connection_close_internal_and_unlock (connection);
1935 * Closes the connection, so no further data can be sent or received.
1936 * Any further attempts to send data will result in errors. This
1937 * function does not affect the connection's reference count. It's
1938 * safe to disconnect a connection more than once; all calls after the
1939 * first do nothing. It's impossible to "reopen" a connection, a
1940 * new connection must be created. This function may result in a call
1941 * to the DBusDispatchStatusFunction set with
1942 * dbus_connection_set_dispatch_status_function(), as the disconnect
1943 * message it generates needs to be dispatched.
1945 * If the connection is a shared connection we print out a warning that
1946 * you can not close shared connection and we return. Internal calls
1947 * should use _dbus_connection_close_internal() to close shared connections.
1949 * @param connection the connection.
1952 dbus_connection_close (DBusConnection *connection)
1954 _dbus_return_if_fail (connection != NULL);
1955 _dbus_return_if_fail (connection->generation == _dbus_current_generation);
1957 CONNECTION_LOCK (connection);
1959 if (connection->shared)
1961 CONNECTION_UNLOCK (connection);
1963 _dbus_warn ("Applications can not close shared connections. Please fix this in your app. Ignoring close request and continuing.");
1967 _dbus_connection_close_internal_and_unlock (connection);
1971 _dbus_connection_get_is_connected_unlocked (DBusConnection *connection)
1973 HAVE_LOCK_CHECK (connection);
1974 return _dbus_transport_get_is_connected (connection->transport);
1978 * Gets whether the connection is currently connected. All
1979 * connections are connected when they are opened. A connection may
1980 * become disconnected when the remote application closes its end, or
1981 * exits; a connection may also be disconnected with
1982 * dbus_connection_close().
1984 * @param connection the connection.
1985 * @returns #TRUE if the connection is still alive.
1988 dbus_connection_get_is_connected (DBusConnection *connection)
1992 _dbus_return_val_if_fail (connection != NULL, FALSE);
1994 CONNECTION_LOCK (connection);
1995 res = _dbus_connection_get_is_connected_unlocked (connection);
1996 CONNECTION_UNLOCK (connection);
2002 * Gets whether the connection was authenticated. (Note that
2003 * if the connection was authenticated then disconnected,
2004 * this function still returns #TRUE)
2006 * @param connection the connection
2007 * @returns #TRUE if the connection was ever authenticated
2010 dbus_connection_get_is_authenticated (DBusConnection *connection)
2014 _dbus_return_val_if_fail (connection != NULL, FALSE);
2016 CONNECTION_LOCK (connection);
2017 res = _dbus_transport_get_is_authenticated (connection->transport);
2018 CONNECTION_UNLOCK (connection);
2024 * Set whether _exit() should be called when the connection receives a
2025 * disconnect signal. The call to _exit() comes after any handlers for
2026 * the disconnect signal run; handlers can cancel the exit by calling
2029 * By default, exit_on_disconnect is #FALSE; but for message bus
2030 * connections returned from dbus_bus_get() it will be toggled on
2033 * @param connection the connection
2034 * @param exit_on_disconnect #TRUE if _exit() should be called after a disconnect signal
2037 dbus_connection_set_exit_on_disconnect (DBusConnection *connection,
2038 dbus_bool_t exit_on_disconnect)
2040 _dbus_return_if_fail (connection != NULL);
2042 CONNECTION_LOCK (connection);
2043 connection->exit_on_disconnect = exit_on_disconnect != FALSE;
2044 CONNECTION_UNLOCK (connection);
2047 static DBusPreallocatedSend*
2048 _dbus_connection_preallocate_send_unlocked (DBusConnection *connection)
2050 DBusPreallocatedSend *preallocated;
2052 HAVE_LOCK_CHECK (connection);
2054 _dbus_assert (connection != NULL);
2056 preallocated = dbus_new (DBusPreallocatedSend, 1);
2057 if (preallocated == NULL)
2060 if (connection->link_cache != NULL)
2062 preallocated->queue_link =
2063 _dbus_list_pop_first_link (&connection->link_cache);
2064 preallocated->queue_link->data = NULL;
2068 preallocated->queue_link = _dbus_list_alloc_link (NULL);
2069 if (preallocated->queue_link == NULL)
2073 if (connection->link_cache != NULL)
2075 preallocated->counter_link =
2076 _dbus_list_pop_first_link (&connection->link_cache);
2077 preallocated->counter_link->data = connection->outgoing_counter;
2081 preallocated->counter_link = _dbus_list_alloc_link (connection->outgoing_counter);
2082 if (preallocated->counter_link == NULL)
2086 _dbus_counter_ref (preallocated->counter_link->data);
2088 preallocated->connection = connection;
2090 return preallocated;
2093 _dbus_list_free_link (preallocated->queue_link);
2095 dbus_free (preallocated);
2101 * Preallocates resources needed to send a message, allowing the message
2102 * to be sent without the possibility of memory allocation failure.
2103 * Allows apps to create a future guarantee that they can send
2104 * a message regardless of memory shortages.
2106 * @param connection the connection we're preallocating for.
2107 * @returns the preallocated resources, or #NULL
2109 DBusPreallocatedSend*
2110 dbus_connection_preallocate_send (DBusConnection *connection)
2112 DBusPreallocatedSend *preallocated;
2114 _dbus_return_val_if_fail (connection != NULL, NULL);
2116 CONNECTION_LOCK (connection);
2119 _dbus_connection_preallocate_send_unlocked (connection);
2121 CONNECTION_UNLOCK (connection);
2123 return preallocated;
2127 * Frees preallocated message-sending resources from
2128 * dbus_connection_preallocate_send(). Should only
2129 * be called if the preallocated resources are not used
2130 * to send a message.
2132 * @param connection the connection
2133 * @param preallocated the resources
2136 dbus_connection_free_preallocated_send (DBusConnection *connection,
2137 DBusPreallocatedSend *preallocated)
2139 _dbus_return_if_fail (connection != NULL);
2140 _dbus_return_if_fail (preallocated != NULL);
2141 _dbus_return_if_fail (connection == preallocated->connection);
2143 _dbus_list_free_link (preallocated->queue_link);
2144 _dbus_counter_unref (preallocated->counter_link->data);
2145 _dbus_list_free_link (preallocated->counter_link);
2146 dbus_free (preallocated);
2149 /* Called with lock held, does not update dispatch status */
2151 _dbus_connection_send_preallocated_unlocked_no_update (DBusConnection *connection,
2152 DBusPreallocatedSend *preallocated,
2153 DBusMessage *message,
2154 dbus_uint32_t *client_serial)
2156 dbus_uint32_t serial;
2159 preallocated->queue_link->data = message;
2160 _dbus_list_prepend_link (&connection->outgoing_messages,
2161 preallocated->queue_link);
2163 _dbus_message_add_size_counter_link (message,
2164 preallocated->counter_link);
2166 dbus_free (preallocated);
2167 preallocated = NULL;
2169 dbus_message_ref (message);
2171 connection->n_outgoing += 1;
2173 sig = dbus_message_get_signature (message);
2175 _dbus_verbose ("Message %p (%d %s %s %s '%s') for %s added to outgoing queue %p, %d pending to send\n",
2177 dbus_message_get_type (message),
2178 dbus_message_get_path (message) ?
2179 dbus_message_get_path (message) :
2181 dbus_message_get_interface (message) ?
2182 dbus_message_get_interface (message) :
2184 dbus_message_get_member (message) ?
2185 dbus_message_get_member (message) :
2188 dbus_message_get_destination (message) ?
2189 dbus_message_get_destination (message) :
2192 connection->n_outgoing);
2194 if (dbus_message_get_serial (message) == 0)
2196 serial = _dbus_connection_get_next_client_serial (connection);
2197 _dbus_message_set_serial (message, serial);
2199 *client_serial = serial;
2204 *client_serial = dbus_message_get_serial (message);
2207 _dbus_verbose ("Message %p serial is %u\n",
2208 message, dbus_message_get_serial (message));
2210 _dbus_message_lock (message);
2212 /* Now we need to run an iteration to hopefully just write the messages
2213 * out immediately, and otherwise get them queued up
2215 _dbus_connection_do_iteration_unlocked (connection,
2216 DBUS_ITERATION_DO_WRITING,
2219 /* If stuff is still queued up, be sure we wake up the main loop */
2220 if (connection->n_outgoing > 0)
2221 _dbus_connection_wakeup_mainloop (connection);
2225 _dbus_connection_send_preallocated_and_unlock (DBusConnection *connection,
2226 DBusPreallocatedSend *preallocated,
2227 DBusMessage *message,
2228 dbus_uint32_t *client_serial)
2230 DBusDispatchStatus status;
2232 HAVE_LOCK_CHECK (connection);
2234 _dbus_connection_send_preallocated_unlocked_no_update (connection,
2236 message, client_serial);
2238 _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
2239 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2241 /* this calls out to user code */
2242 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2246 * Sends a message using preallocated resources. This function cannot fail.
2247 * It works identically to dbus_connection_send() in other respects.
2248 * Preallocated resources comes from dbus_connection_preallocate_send().
2249 * This function "consumes" the preallocated resources, they need not
2250 * be freed separately.
2252 * @param connection the connection
2253 * @param preallocated the preallocated resources
2254 * @param message the message to send
2255 * @param client_serial return location for client serial assigned to the message
2258 dbus_connection_send_preallocated (DBusConnection *connection,
2259 DBusPreallocatedSend *preallocated,
2260 DBusMessage *message,
2261 dbus_uint32_t *client_serial)
2263 _dbus_return_if_fail (connection != NULL);
2264 _dbus_return_if_fail (preallocated != NULL);
2265 _dbus_return_if_fail (message != NULL);
2266 _dbus_return_if_fail (preallocated->connection == connection);
2267 _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_METHOD_CALL ||
2268 dbus_message_get_member (message) != NULL);
2269 _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL ||
2270 (dbus_message_get_interface (message) != NULL &&
2271 dbus_message_get_member (message) != NULL));
2273 CONNECTION_LOCK (connection);
2274 _dbus_connection_send_preallocated_and_unlock (connection,
2276 message, client_serial);
2280 _dbus_connection_send_unlocked_no_update (DBusConnection *connection,
2281 DBusMessage *message,
2282 dbus_uint32_t *client_serial)
2284 DBusPreallocatedSend *preallocated;
2286 _dbus_assert (connection != NULL);
2287 _dbus_assert (message != NULL);
2289 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
2290 if (preallocated == NULL)
2293 _dbus_connection_send_preallocated_unlocked_no_update (connection,
2301 _dbus_connection_send_and_unlock (DBusConnection *connection,
2302 DBusMessage *message,
2303 dbus_uint32_t *client_serial)
2305 DBusPreallocatedSend *preallocated;
2307 _dbus_assert (connection != NULL);
2308 _dbus_assert (message != NULL);
2310 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
2311 if (preallocated == NULL)
2313 CONNECTION_UNLOCK (connection);
2317 _dbus_connection_send_preallocated_and_unlock (connection,
2325 * Adds a message to the outgoing message queue. Does not block to
2326 * write the message to the network; that happens asynchronously. To
2327 * force the message to be written, call dbus_connection_flush().
2328 * Because this only queues the message, the only reason it can
2329 * fail is lack of memory. Even if the connection is disconnected,
2330 * no error will be returned.
2332 * If the function fails due to lack of memory, it returns #FALSE.
2333 * The function will never fail for other reasons; even if the
2334 * connection is disconnected, you can queue an outgoing message,
2335 * though obviously it won't be sent.
2337 * @param connection the connection.
2338 * @param message the message to write.
2339 * @param client_serial return location for client serial.
2340 * @returns #TRUE on success.
2343 dbus_connection_send (DBusConnection *connection,
2344 DBusMessage *message,
2345 dbus_uint32_t *client_serial)
2347 _dbus_return_val_if_fail (connection != NULL, FALSE);
2348 _dbus_return_val_if_fail (message != NULL, FALSE);
2350 CONNECTION_LOCK (connection);
2352 return _dbus_connection_send_and_unlock (connection,
2358 reply_handler_timeout (void *data)
2360 DBusConnection *connection;
2361 DBusDispatchStatus status;
2362 DBusPendingCall *pending = data;
2364 connection = _dbus_pending_call_get_connection_and_lock (pending);
2366 _dbus_pending_call_queue_timeout_error_unlocked (pending,
2368 _dbus_connection_remove_timeout_unlocked (connection,
2369 _dbus_pending_call_get_timeout_unlocked (pending));
2370 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
2372 _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
2373 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2375 /* Unlocks, and calls out to user code */
2376 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2382 * Queues a message to send, as with dbus_connection_send_message(),
2383 * but also returns a #DBusPendingCall used to receive a reply to the
2384 * message. If no reply is received in the given timeout_milliseconds,
2385 * this function expires the pending reply and generates a synthetic
2386 * error reply (generated in-process, not by the remote application)
2387 * indicating that a timeout occurred.
2389 * A #DBusPendingCall will see a reply message after any filters, but
2390 * before any object instances or other handlers. A #DBusPendingCall
2391 * will always see exactly one reply message, unless it's cancelled
2392 * with dbus_pending_call_cancel().
2394 * If a filter filters out the reply before the handler sees it, the
2395 * reply is immediately timed out and a timeout error reply is
2396 * generated. If a filter removes the timeout error reply then the
2397 * #DBusPendingCall will get confused. Filtering the timeout error
2398 * is thus considered a bug and will print a warning.
2400 * If #NULL is passed for the pending_return, the #DBusPendingCall
2401 * will still be generated internally, and used to track
2402 * the message reply timeout. This means a timeout error will
2403 * occur if no reply arrives, unlike with dbus_connection_send().
2405 * If -1 is passed for the timeout, a sane default timeout is used. -1
2406 * is typically the best value for the timeout for this reason, unless
2407 * you want a very short or very long timeout. There is no way to
2408 * avoid a timeout entirely, other than passing INT_MAX for the
2409 * timeout to postpone it indefinitely.
2411 * @param connection the connection
2412 * @param message the message to send
2413 * @param pending_return return location for a #DBusPendingCall object, or #NULLif connection is disconnected
2414 * @param timeout_milliseconds timeout in milliseconds or -1 for default
2415 * @returns #FALSE if no memory, #TRUE otherwise.
2419 dbus_connection_send_with_reply (DBusConnection *connection,
2420 DBusMessage *message,
2421 DBusPendingCall **pending_return,
2422 int timeout_milliseconds)
2424 DBusPendingCall *pending;
2425 dbus_int32_t serial = -1;
2426 DBusDispatchStatus status;
2428 _dbus_return_val_if_fail (connection != NULL, FALSE);
2429 _dbus_return_val_if_fail (message != NULL, FALSE);
2430 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
2433 *pending_return = NULL;
2435 CONNECTION_LOCK (connection);
2437 if (!_dbus_connection_get_is_connected_unlocked (connection))
2439 CONNECTION_UNLOCK (connection);
2441 *pending_return = NULL;
2446 pending = _dbus_pending_call_new_unlocked (connection,
2447 timeout_milliseconds,
2448 reply_handler_timeout);
2450 if (pending == NULL)
2452 CONNECTION_UNLOCK (connection);
2456 /* Assign a serial to the message */
2457 serial = dbus_message_get_serial (message);
2460 serial = _dbus_connection_get_next_client_serial (connection);
2461 _dbus_message_set_serial (message, serial);
2464 if (!_dbus_pending_call_set_timeout_error_unlocked (pending, message, serial))
2467 /* Insert the serial in the pending replies hash;
2468 * hash takes a refcount on DBusPendingCall.
2469 * Also, add the timeout.
2471 if (!_dbus_connection_attach_pending_call_unlocked (connection,
2475 if (!_dbus_connection_send_unlocked_no_update (connection, message, NULL))
2477 _dbus_connection_detach_pending_call_and_unlock (connection,
2479 goto error_unlocked;
2483 *pending_return = pending; /* hand off refcount */
2486 _dbus_connection_detach_pending_call_unlocked (connection, pending);
2487 /* we still have a ref to the pending call in this case, we unref
2488 * after unlocking, below
2492 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2494 /* this calls out to user code */
2495 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2497 if (pending_return == NULL)
2498 dbus_pending_call_unref (pending);
2503 CONNECTION_UNLOCK (connection);
2505 dbus_pending_call_unref (pending);
2509 /* This is slightly strange since we can pop a message here without
2510 * the dispatch lock.
2513 check_for_reply_unlocked (DBusConnection *connection,
2514 dbus_uint32_t client_serial)
2518 HAVE_LOCK_CHECK (connection);
2520 link = _dbus_list_get_first_link (&connection->incoming_messages);
2522 while (link != NULL)
2524 DBusMessage *reply = link->data;
2526 if (dbus_message_get_reply_serial (reply) == client_serial)
2528 _dbus_list_remove_link (&connection->incoming_messages, link);
2529 connection->n_incoming -= 1;
2532 link = _dbus_list_get_next_link (&connection->incoming_messages, link);
2539 connection_timeout_and_complete_all_pending_calls_unlocked (DBusConnection *connection)
2541 /* We can't iterate over the hash in the normal way since we'll be
2542 * dropping the lock for each item. So we restart the
2543 * iter each time as we drain the hash table.
2546 while (_dbus_hash_table_get_n_entries (connection->pending_replies) > 0)
2548 DBusPendingCall *pending;
2551 _dbus_hash_iter_init (connection->pending_replies, &iter);
2552 _dbus_hash_iter_next (&iter);
2554 pending = (DBusPendingCall *) _dbus_hash_iter_get_value (&iter);
2555 _dbus_pending_call_ref_unlocked (pending);
2557 _dbus_pending_call_queue_timeout_error_unlocked (pending,
2559 _dbus_connection_remove_timeout_unlocked (connection,
2560 _dbus_pending_call_get_timeout_unlocked (pending));
2561 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
2562 _dbus_hash_iter_remove_entry (&iter);
2564 _dbus_pending_call_unref_and_unlock (pending);
2565 CONNECTION_LOCK (connection);
2567 HAVE_LOCK_CHECK (connection);
2571 complete_pending_call_and_unlock (DBusConnection *connection,
2572 DBusPendingCall *pending,
2573 DBusMessage *message)
2575 _dbus_pending_call_set_reply_unlocked (pending, message);
2576 _dbus_pending_call_ref_unlocked (pending); /* in case there's no app with a ref held */
2577 _dbus_connection_detach_pending_call_and_unlock (connection, pending);
2579 /* Must be called unlocked since it invokes app callback */
2580 _dbus_pending_call_complete (pending);
2581 dbus_pending_call_unref (pending);
2585 check_for_reply_and_update_dispatch_unlocked (DBusConnection *connection,
2586 DBusPendingCall *pending)
2589 DBusDispatchStatus status;
2591 reply = check_for_reply_unlocked (connection,
2592 _dbus_pending_call_get_reply_serial_unlocked (pending));
2595 _dbus_verbose ("%s checked for reply\n", _DBUS_FUNCTION_NAME);
2597 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): got reply\n");
2599 complete_pending_call_and_unlock (connection, pending, reply);
2600 dbus_message_unref (reply);
2602 CONNECTION_LOCK (connection);
2603 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2604 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2605 dbus_pending_call_unref (pending);
2614 * When a function that blocks has been called with a timeout, and we
2615 * run out of memory, the time to wait for memory is based on the
2616 * timeout. If the caller was willing to block a long time we wait a
2617 * relatively long time for memory, if they were only willing to block
2618 * briefly then we retry for memory at a rapid rate.
2620 * @timeout_milliseconds the timeout requested for blocking
2623 _dbus_memory_pause_based_on_timeout (int timeout_milliseconds)
2625 if (timeout_milliseconds == -1)
2626 _dbus_sleep_milliseconds (1000);
2627 else if (timeout_milliseconds < 100)
2628 ; /* just busy loop */
2629 else if (timeout_milliseconds <= 1000)
2630 _dbus_sleep_milliseconds (timeout_milliseconds / 3);
2632 _dbus_sleep_milliseconds (1000);
2636 * Blocks until a pending call times out or gets a reply.
2638 * Does not re-enter the main loop or run filter/path-registered
2639 * callbacks. The reply to the message will not be seen by
2642 * Returns immediately if pending call already got a reply.
2644 * @todo could use performance improvements (it keeps scanning
2645 * the whole message queue for example)
2647 * @param pending the pending call we block for a reply on
2650 _dbus_connection_block_pending_call (DBusPendingCall *pending)
2652 long start_tv_sec, start_tv_usec;
2653 long end_tv_sec, end_tv_usec;
2654 long tv_sec, tv_usec;
2655 DBusDispatchStatus status;
2656 DBusConnection *connection;
2657 dbus_uint32_t client_serial;
2658 int timeout_milliseconds;
2660 _dbus_assert (pending != NULL);
2662 if (dbus_pending_call_get_completed (pending))
2665 dbus_pending_call_ref (pending); /* necessary because the call could be canceled */
2667 connection = _dbus_pending_call_get_connection_and_lock (pending);
2669 /* Flush message queue - note, can affect dispatch status */
2670 _dbus_connection_flush_unlocked (connection);
2672 client_serial = _dbus_pending_call_get_reply_serial_unlocked (pending);
2674 /* note that timeout_milliseconds is limited to a smallish value
2675 * in _dbus_pending_call_new() so overflows aren't possible
2678 timeout_milliseconds = dbus_timeout_get_interval (_dbus_pending_call_get_timeout_unlocked (pending));
2680 _dbus_get_current_time (&start_tv_sec, &start_tv_usec);
2681 end_tv_sec = start_tv_sec + timeout_milliseconds / 1000;
2682 end_tv_usec = start_tv_usec + (timeout_milliseconds % 1000) * 1000;
2683 end_tv_sec += end_tv_usec / _DBUS_USEC_PER_SECOND;
2684 end_tv_usec = end_tv_usec % _DBUS_USEC_PER_SECOND;
2686 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): will block %d milliseconds for reply serial %u from %ld sec %ld usec to %ld sec %ld usec\n",
2687 timeout_milliseconds,
2689 start_tv_sec, start_tv_usec,
2690 end_tv_sec, end_tv_usec);
2692 /* check to see if we already got the data off the socket */
2693 /* from another blocked pending call */
2694 if (check_for_reply_and_update_dispatch_unlocked (connection, pending))
2697 /* Now we wait... */
2698 /* always block at least once as we know we don't have the reply yet */
2699 _dbus_connection_do_iteration_unlocked (connection,
2700 DBUS_ITERATION_DO_READING |
2701 DBUS_ITERATION_BLOCK,
2702 timeout_milliseconds);
2706 _dbus_verbose ("%s top of recheck\n", _DBUS_FUNCTION_NAME);
2708 HAVE_LOCK_CHECK (connection);
2710 /* queue messages and get status */
2712 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2714 /* the get_completed() is in case a dispatch() while we were blocking
2715 * got the reply instead of us.
2717 if (_dbus_pending_call_get_completed_unlocked (pending))
2719 _dbus_verbose ("Pending call completed by dispatch in %s\n", _DBUS_FUNCTION_NAME);
2720 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2721 dbus_pending_call_unref (pending);
2725 if (status == DBUS_DISPATCH_DATA_REMAINS) {
2726 if (check_for_reply_and_update_dispatch_unlocked (connection, pending))
2730 _dbus_get_current_time (&tv_sec, &tv_usec);
2732 if (!_dbus_connection_get_is_connected_unlocked (connection))
2734 /* FIXME 1.0 send a "DBUS_ERROR_DISCONNECTED" instead, just to help
2735 * programmers understand what went wrong since the timeout is
2739 complete_pending_call_and_unlock (connection, pending, NULL);
2740 dbus_pending_call_unref (pending);
2743 else if (tv_sec < start_tv_sec)
2744 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): clock set backward\n");
2745 else if (connection->disconnect_message_link == NULL)
2746 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): disconnected\n");
2747 else if (tv_sec < end_tv_sec ||
2748 (tv_sec == end_tv_sec && tv_usec < end_tv_usec))
2750 timeout_milliseconds = (end_tv_sec - tv_sec) * 1000 +
2751 (end_tv_usec - tv_usec) / 1000;
2752 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): %d milliseconds remain\n", timeout_milliseconds);
2753 _dbus_assert (timeout_milliseconds >= 0);
2755 if (status == DBUS_DISPATCH_NEED_MEMORY)
2757 /* Try sleeping a bit, as we aren't sure we need to block for reading,
2758 * we may already have a reply in the buffer and just can't process
2761 _dbus_verbose ("dbus_connection_send_with_reply_and_block() waiting for more memory\n");
2763 _dbus_memory_pause_based_on_timeout (timeout_milliseconds);
2767 /* block again, we don't have the reply buffered yet. */
2768 _dbus_connection_do_iteration_unlocked (connection,
2769 DBUS_ITERATION_DO_READING |
2770 DBUS_ITERATION_BLOCK,
2771 timeout_milliseconds);
2774 goto recheck_status;
2777 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): Waited %ld milliseconds and got no reply\n",
2778 (tv_sec - start_tv_sec) * 1000 + (tv_usec - start_tv_usec) / 1000);
2780 _dbus_assert (!_dbus_pending_call_get_completed_unlocked (pending));
2782 /* unlock and call user code */
2783 complete_pending_call_and_unlock (connection, pending, NULL);
2785 /* update user code on dispatch status */
2786 CONNECTION_LOCK (connection);
2787 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2788 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2789 dbus_pending_call_unref (pending);
2793 * Sends a message and blocks a certain time period while waiting for
2794 * a reply. This function does not reenter the main loop,
2795 * i.e. messages other than the reply are queued up but not
2796 * processed. This function is used to do non-reentrant "method
2799 * If a normal reply is received, it is returned, and removed from the
2800 * incoming message queue. If it is not received, #NULL is returned
2801 * and the error is set to #DBUS_ERROR_NO_REPLY. If an error reply is
2802 * received, it is converted to a #DBusError and returned as an error,
2803 * then the reply message is deleted. If something else goes wrong,
2804 * result is set to whatever is appropriate, such as
2805 * #DBUS_ERROR_NO_MEMORY or #DBUS_ERROR_DISCONNECTED.
2807 * @param connection the connection
2808 * @param message the message to send
2809 * @param timeout_milliseconds timeout in milliseconds or -1 for default
2810 * @param error return location for error message
2811 * @returns the message that is the reply or #NULL with an error code if the
2815 dbus_connection_send_with_reply_and_block (DBusConnection *connection,
2816 DBusMessage *message,
2817 int timeout_milliseconds,
2821 DBusPendingCall *pending;
2823 _dbus_return_val_if_fail (connection != NULL, NULL);
2824 _dbus_return_val_if_fail (message != NULL, NULL);
2825 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, NULL);
2826 _dbus_return_val_if_error_is_set (error, NULL);
2828 if (!dbus_connection_send_with_reply (connection, message,
2829 &pending, timeout_milliseconds))
2831 _DBUS_SET_OOM (error);
2835 _dbus_assert (pending != NULL);
2837 dbus_pending_call_block (pending);
2839 reply = dbus_pending_call_steal_reply (pending);
2840 dbus_pending_call_unref (pending);
2842 /* call_complete_and_unlock() called from pending_call_block() should
2843 * always fill this in.
2845 _dbus_assert (reply != NULL);
2847 if (dbus_set_error_from_message (error, reply))
2849 dbus_message_unref (reply);
2857 * Blocks until the outgoing message queue is empty.
2858 * Assumes connection lock already held.
2860 * If you call this, you MUST call update_dispatch_status afterword...
2862 * @param connection the connection.
2865 _dbus_connection_flush_unlocked (DBusConnection *connection)
2867 /* We have to specify DBUS_ITERATION_DO_READING here because
2868 * otherwise we could have two apps deadlock if they are both doing
2869 * a flush(), and the kernel buffers fill up. This could change the
2872 DBusDispatchStatus status;
2874 HAVE_LOCK_CHECK (connection);
2876 while (connection->n_outgoing > 0 &&
2877 _dbus_connection_get_is_connected_unlocked (connection))
2879 _dbus_verbose ("doing iteration in %s\n", _DBUS_FUNCTION_NAME);
2880 HAVE_LOCK_CHECK (connection);
2881 _dbus_connection_do_iteration_unlocked (connection,
2882 DBUS_ITERATION_DO_READING |
2883 DBUS_ITERATION_DO_WRITING |
2884 DBUS_ITERATION_BLOCK,
2888 HAVE_LOCK_CHECK (connection);
2889 _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
2890 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2892 HAVE_LOCK_CHECK (connection);
2897 * Blocks until the outgoing message queue is empty.
2899 * @param connection the connection.
2902 dbus_connection_flush (DBusConnection *connection)
2904 /* We have to specify DBUS_ITERATION_DO_READING here because
2905 * otherwise we could have two apps deadlock if they are both doing
2906 * a flush(), and the kernel buffers fill up. This could change the
2909 DBusDispatchStatus status;
2911 _dbus_return_if_fail (connection != NULL);
2913 CONNECTION_LOCK (connection);
2915 status = _dbus_connection_flush_unlocked (connection);
2917 HAVE_LOCK_CHECK (connection);
2918 /* Unlocks and calls out to user code */
2919 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2921 _dbus_verbose ("%s end\n", _DBUS_FUNCTION_NAME);
2925 * This function is intended for use with applications that don't want
2926 * to write a main loop and deal with #DBusWatch and #DBusTimeout. An
2927 * example usage would be:
2930 * while (dbus_connection_read_write_dispatch (connection, -1))
2931 * ; // empty loop body
2934 * In this usage you would normally have set up a filter function to look
2935 * at each message as it is dispatched. The loop terminates when the last
2936 * message from the connection (the disconnected signal) is processed.
2938 * If there are messages to dispatch and the dispatch flag is set, this
2939 * function will dbus_connection_dispatch() once, and return. If there are no
2940 * messages to dispatch, this function will block until it can read or write,
2941 * then read or write, then return.
2943 * The way to think of this function is that it either makes some sort
2944 * of progress, or it blocks.
2946 * The return value indicates whether the disconnect message has been
2947 * processed, NOT whether the connection is connected. This is
2948 * important because even after disconnecting, you want to process any
2949 * messages you received prior to the disconnect.
2951 * @param connection the connection
2952 * @param timeout_milliseconds max time to block or -1 for infinite
2953 * @param dispatch dispatch new messages or leave them on the incoming queue
2954 * @returns #TRUE if the disconnect message has not been processed
2957 _dbus_connection_read_write_dispatch (DBusConnection *connection,
2958 int timeout_milliseconds,
2959 dbus_bool_t dispatch)
2961 DBusDispatchStatus dstatus;
2962 dbus_bool_t dispatched_disconnected;
2964 dstatus = dbus_connection_get_dispatch_status (connection);
2966 if (dispatch && dstatus == DBUS_DISPATCH_DATA_REMAINS)
2968 _dbus_verbose ("doing dispatch in %s\n", _DBUS_FUNCTION_NAME);
2969 dbus_connection_dispatch (connection);
2970 CONNECTION_LOCK (connection);
2972 else if (dstatus == DBUS_DISPATCH_NEED_MEMORY)
2974 _dbus_verbose ("pausing for memory in %s\n", _DBUS_FUNCTION_NAME);
2975 _dbus_memory_pause_based_on_timeout (timeout_milliseconds);
2976 CONNECTION_LOCK (connection);
2980 CONNECTION_LOCK (connection);
2981 if (_dbus_connection_get_is_connected_unlocked (connection))
2983 _dbus_verbose ("doing iteration in %s\n", _DBUS_FUNCTION_NAME);
2984 _dbus_connection_do_iteration_unlocked (connection,
2985 DBUS_ITERATION_DO_READING |
2986 DBUS_ITERATION_DO_WRITING |
2987 DBUS_ITERATION_BLOCK,
2988 timeout_milliseconds);
2992 HAVE_LOCK_CHECK (connection);
2993 dispatched_disconnected = connection->n_incoming == 0 &&
2994 connection->disconnect_message_link == NULL;
2995 CONNECTION_UNLOCK (connection);
2996 return !dispatched_disconnected; /* TRUE if we have not processed disconnected */
3001 * This function is intended for use with applications that don't want
3002 * to write a main loop and deal with #DBusWatch and #DBusTimeout. An
3003 * example usage would be:
3006 * while (dbus_connection_read_write_dispatch (connection, -1))
3007 * ; // empty loop body
3010 * In this usage you would normally have set up a filter function to look
3011 * at each message as it is dispatched. The loop terminates when the last
3012 * message from the connection (the disconnected signal) is processed.
3014 * If there are messages to dispatch, this function will
3015 * dbus_connection_dispatch() once, and return. If there are no
3016 * messages to dispatch, this function will block until it can read or
3017 * write, then read or write, then return.
3019 * The way to think of this function is that it either makes some sort
3020 * of progress, or it blocks.
3022 * The return value indicates whether the disconnect message has been
3023 * processed, NOT whether the connection is connected. This is
3024 * important because even after disconnecting, you want to process any
3025 * messages you received prior to the disconnect.
3027 * @param connection the connection
3028 * @param timeout_milliseconds max time to block or -1 for infinite
3029 * @returns #TRUE if the disconnect message has not been processed
3032 dbus_connection_read_write_dispatch (DBusConnection *connection,
3033 int timeout_milliseconds)
3035 _dbus_return_val_if_fail (connection != NULL, FALSE);
3036 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3037 return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, TRUE);
3041 * This function is intended for use with applications that don't want to
3042 * write a main loop and deal with #DBusWatch and #DBusTimeout.
3044 * If there are no messages to dispatch, this function will block until it can
3045 * read or write, then read or write, then return.
3047 * The return value indicates whether the disconnect message has been
3048 * processed, NOT whether the connection is connected. This is important
3049 * because even after disconnecting, you want to process any messages you
3050 * received prior to the disconnect.
3052 * @param connection the connection
3053 * @param timeout_milliseconds max time to block or -1 for infinite
3054 * @returns #TRUE if the disconnect message has not been processed
3057 dbus_connection_read_write (DBusConnection *connection,
3058 int timeout_milliseconds)
3060 _dbus_return_val_if_fail (connection != NULL, FALSE);
3061 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3062 return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, FALSE);
3066 * Returns the first-received message from the incoming message queue,
3067 * leaving it in the queue. If the queue is empty, returns #NULL.
3069 * The caller does not own a reference to the returned message, and
3070 * must either return it using dbus_connection_return_message() or
3071 * keep it after calling dbus_connection_steal_borrowed_message(). No
3072 * one can get at the message while its borrowed, so return it as
3073 * quickly as possible and don't keep a reference to it after
3074 * returning it. If you need to keep the message, make a copy of it.
3076 * dbus_connection_dispatch() will block if called while a borrowed
3077 * message is outstanding; only one piece of code can be playing with
3078 * the incoming queue at a time. This function will block if called
3079 * during a dbus_connection_dispatch().
3081 * @param connection the connection.
3082 * @returns next message in the incoming queue.
3085 dbus_connection_borrow_message (DBusConnection *connection)
3087 DBusDispatchStatus status;
3088 DBusMessage *message;
3090 _dbus_return_val_if_fail (connection != NULL, NULL);
3092 _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
3094 /* this is called for the side effect that it queues
3095 * up any messages from the transport
3097 status = dbus_connection_get_dispatch_status (connection);
3098 if (status != DBUS_DISPATCH_DATA_REMAINS)
3101 CONNECTION_LOCK (connection);
3103 _dbus_connection_acquire_dispatch (connection);
3105 /* While a message is outstanding, the dispatch lock is held */
3106 _dbus_assert (connection->message_borrowed == NULL);
3108 connection->message_borrowed = _dbus_list_get_first (&connection->incoming_messages);
3110 message = connection->message_borrowed;
3112 /* Note that we KEEP the dispatch lock until the message is returned */
3113 if (message == NULL)
3114 _dbus_connection_release_dispatch (connection);
3116 CONNECTION_UNLOCK (connection);
3122 * Used to return a message after peeking at it using
3123 * dbus_connection_borrow_message(). Only called if
3124 * message from dbus_connection_borrow_message() was non-#NULL.
3126 * @param connection the connection
3127 * @param message the message from dbus_connection_borrow_message()
3130 dbus_connection_return_message (DBusConnection *connection,
3131 DBusMessage *message)
3133 _dbus_return_if_fail (connection != NULL);
3134 _dbus_return_if_fail (message != NULL);
3135 _dbus_return_if_fail (message == connection->message_borrowed);
3136 _dbus_return_if_fail (connection->dispatch_acquired);
3138 CONNECTION_LOCK (connection);
3140 _dbus_assert (message == connection->message_borrowed);
3142 connection->message_borrowed = NULL;
3144 _dbus_connection_release_dispatch (connection);
3146 CONNECTION_UNLOCK (connection);
3150 * Used to keep a message after peeking at it using
3151 * dbus_connection_borrow_message(). Before using this function, see
3152 * the caveats/warnings in the documentation for
3153 * dbus_connection_pop_message().
3155 * @param connection the connection
3156 * @param message the message from dbus_connection_borrow_message()
3159 dbus_connection_steal_borrowed_message (DBusConnection *connection,
3160 DBusMessage *message)
3162 DBusMessage *pop_message;
3164 _dbus_return_if_fail (connection != NULL);
3165 _dbus_return_if_fail (message != NULL);
3166 _dbus_return_if_fail (message == connection->message_borrowed);
3167 _dbus_return_if_fail (connection->dispatch_acquired);
3169 CONNECTION_LOCK (connection);
3171 _dbus_assert (message == connection->message_borrowed);
3173 pop_message = _dbus_list_pop_first (&connection->incoming_messages);
3174 _dbus_assert (message == pop_message);
3176 connection->n_incoming -= 1;
3178 _dbus_verbose ("Incoming message %p stolen from queue, %d incoming\n",
3179 message, connection->n_incoming);
3181 connection->message_borrowed = NULL;
3183 _dbus_connection_release_dispatch (connection);
3185 CONNECTION_UNLOCK (connection);
3188 /* See dbus_connection_pop_message, but requires the caller to own
3189 * the lock before calling. May drop the lock while running.
3192 _dbus_connection_pop_message_link_unlocked (DBusConnection *connection)
3194 HAVE_LOCK_CHECK (connection);
3196 _dbus_assert (connection->message_borrowed == NULL);
3198 if (connection->n_incoming > 0)
3202 link = _dbus_list_pop_first_link (&connection->incoming_messages);
3203 connection->n_incoming -= 1;
3205 _dbus_verbose ("Message %p (%d %s %s %s '%s') removed from incoming queue %p, %d incoming\n",
3207 dbus_message_get_type (link->data),
3208 dbus_message_get_path (link->data) ?
3209 dbus_message_get_path (link->data) :
3211 dbus_message_get_interface (link->data) ?
3212 dbus_message_get_interface (link->data) :
3214 dbus_message_get_member (link->data) ?
3215 dbus_message_get_member (link->data) :
3217 dbus_message_get_signature (link->data),
3218 connection, connection->n_incoming);
3226 /* See dbus_connection_pop_message, but requires the caller to own
3227 * the lock before calling. May drop the lock while running.
3230 _dbus_connection_pop_message_unlocked (DBusConnection *connection)
3234 HAVE_LOCK_CHECK (connection);
3236 link = _dbus_connection_pop_message_link_unlocked (connection);
3240 DBusMessage *message;
3242 message = link->data;
3244 _dbus_list_free_link (link);
3253 _dbus_connection_putback_message_link_unlocked (DBusConnection *connection,
3254 DBusList *message_link)
3256 HAVE_LOCK_CHECK (connection);
3258 _dbus_assert (message_link != NULL);
3259 /* You can't borrow a message while a link is outstanding */
3260 _dbus_assert (connection->message_borrowed == NULL);
3261 /* We had to have the dispatch lock across the pop/putback */
3262 _dbus_assert (connection->dispatch_acquired);
3264 _dbus_list_prepend_link (&connection->incoming_messages,
3266 connection->n_incoming += 1;
3268 _dbus_verbose ("Message %p (%d %s %s '%s') put back into queue %p, %d incoming\n",
3270 dbus_message_get_type (message_link->data),
3271 dbus_message_get_interface (message_link->data) ?
3272 dbus_message_get_interface (message_link->data) :
3274 dbus_message_get_member (message_link->data) ?
3275 dbus_message_get_member (message_link->data) :
3277 dbus_message_get_signature (message_link->data),
3278 connection, connection->n_incoming);
3282 * Returns the first-received message from the incoming message queue,
3283 * removing it from the queue. The caller owns a reference to the
3284 * returned message. If the queue is empty, returns #NULL.
3286 * This function bypasses any message handlers that are registered,
3287 * and so using it is usually wrong. Instead, let the main loop invoke
3288 * dbus_connection_dispatch(). Popping messages manually is only
3289 * useful in very simple programs that don't share a #DBusConnection
3290 * with any libraries or other modules.
3292 * There is a lock that covers all ways of accessing the incoming message
3293 * queue, so dbus_connection_dispatch(), dbus_connection_pop_message(),
3294 * dbus_connection_borrow_message(), etc. will all block while one of the others
3295 * in the group is running.
3297 * @param connection the connection.
3298 * @returns next message in the incoming queue.
3301 dbus_connection_pop_message (DBusConnection *connection)
3303 DBusMessage *message;
3304 DBusDispatchStatus status;
3306 _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
3308 /* this is called for the side effect that it queues
3309 * up any messages from the transport
3311 status = dbus_connection_get_dispatch_status (connection);
3312 if (status != DBUS_DISPATCH_DATA_REMAINS)
3315 CONNECTION_LOCK (connection);
3316 _dbus_connection_acquire_dispatch (connection);
3317 HAVE_LOCK_CHECK (connection);
3319 message = _dbus_connection_pop_message_unlocked (connection);
3321 _dbus_verbose ("Returning popped message %p\n", message);
3323 _dbus_connection_release_dispatch (connection);
3324 CONNECTION_UNLOCK (connection);
3330 * Acquire the dispatcher. This is a separate lock so the main
3331 * connection lock can be dropped to call out to application dispatch
3334 * @param connection the connection.
3337 _dbus_connection_acquire_dispatch (DBusConnection *connection)
3339 HAVE_LOCK_CHECK (connection);
3341 _dbus_connection_ref_unlocked (connection);
3342 CONNECTION_UNLOCK (connection);
3344 _dbus_verbose ("%s locking dispatch_mutex\n", _DBUS_FUNCTION_NAME);
3345 _dbus_mutex_lock (connection->dispatch_mutex);
3347 while (connection->dispatch_acquired)
3349 _dbus_verbose ("%s waiting for dispatch to be acquirable\n", _DBUS_FUNCTION_NAME);
3350 _dbus_condvar_wait (connection->dispatch_cond,
3351 connection->dispatch_mutex);
3354 _dbus_assert (!connection->dispatch_acquired);
3356 connection->dispatch_acquired = TRUE;
3358 _dbus_verbose ("%s unlocking dispatch_mutex\n", _DBUS_FUNCTION_NAME);
3359 _dbus_mutex_unlock (connection->dispatch_mutex);
3361 CONNECTION_LOCK (connection);
3362 _dbus_connection_unref_unlocked (connection);
3366 * Release the dispatcher when you're done with it. Only call
3367 * after you've acquired the dispatcher. Wakes up at most one
3368 * thread currently waiting to acquire the dispatcher.
3370 * @param connection the connection.
3373 _dbus_connection_release_dispatch (DBusConnection *connection)
3375 HAVE_LOCK_CHECK (connection);
3377 _dbus_verbose ("%s locking dispatch_mutex\n", _DBUS_FUNCTION_NAME);
3378 _dbus_mutex_lock (connection->dispatch_mutex);
3380 _dbus_assert (connection->dispatch_acquired);
3382 connection->dispatch_acquired = FALSE;
3383 _dbus_condvar_wake_one (connection->dispatch_cond);
3385 _dbus_verbose ("%s unlocking dispatch_mutex\n", _DBUS_FUNCTION_NAME);
3386 _dbus_mutex_unlock (connection->dispatch_mutex);
3390 _dbus_connection_failed_pop (DBusConnection *connection,
3391 DBusList *message_link)
3393 _dbus_list_prepend_link (&connection->incoming_messages,
3395 connection->n_incoming += 1;
3398 static DBusDispatchStatus
3399 _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection)
3401 HAVE_LOCK_CHECK (connection);
3403 if (connection->n_incoming > 0)
3404 return DBUS_DISPATCH_DATA_REMAINS;
3405 else if (!_dbus_transport_queue_messages (connection->transport))
3406 return DBUS_DISPATCH_NEED_MEMORY;
3409 DBusDispatchStatus status;
3410 dbus_bool_t is_connected;
3412 status = _dbus_transport_get_dispatch_status (connection->transport);
3413 is_connected = _dbus_transport_get_is_connected (connection->transport);
3415 _dbus_verbose ("dispatch status = %s is_connected = %d\n",
3416 DISPATCH_STATUS_NAME (status), is_connected);
3420 if (status == DBUS_DISPATCH_COMPLETE &&
3421 connection->disconnect_message_link)
3423 _dbus_verbose ("Sending disconnect message from %s\n",
3424 _DBUS_FUNCTION_NAME);
3426 connection_forget_shared_unlocked (connection);
3428 /* If we have pending calls queued timeouts on disconnect */
3429 connection_timeout_and_complete_all_pending_calls_unlocked (connection);
3431 /* We haven't sent the disconnect message already,
3432 * and all real messages have been queued up.
3434 _dbus_connection_queue_synthesized_message_link (connection,
3435 connection->disconnect_message_link);
3436 connection->disconnect_message_link = NULL;
3438 status = DBUS_DISPATCH_DATA_REMAINS;
3441 /* Dump the outgoing queue, we aren't going to be able to
3442 * send it now, and we'd like accessors like
3443 * dbus_connection_get_outgoing_size() to be accurate.
3445 if (connection->n_outgoing > 0)
3449 _dbus_verbose ("Dropping %d outgoing messages since we're disconnected\n",
3450 connection->n_outgoing);
3452 while ((link = _dbus_list_get_last_link (&connection->outgoing_messages)))
3454 _dbus_connection_message_sent (connection, link->data);
3459 if (status != DBUS_DISPATCH_COMPLETE)
3461 else if (connection->n_incoming > 0)
3462 return DBUS_DISPATCH_DATA_REMAINS;
3464 return DBUS_DISPATCH_COMPLETE;
3469 _dbus_connection_update_dispatch_status_and_unlock (DBusConnection *connection,
3470 DBusDispatchStatus new_status)
3472 dbus_bool_t changed;
3473 DBusDispatchStatusFunction function;
3476 HAVE_LOCK_CHECK (connection);
3478 _dbus_connection_ref_unlocked (connection);
3480 changed = new_status != connection->last_dispatch_status;
3482 connection->last_dispatch_status = new_status;
3484 function = connection->dispatch_status_function;
3485 data = connection->dispatch_status_data;
3487 /* We drop the lock */
3488 CONNECTION_UNLOCK (connection);
3490 if (changed && function)
3492 _dbus_verbose ("Notifying of change to dispatch status of %p now %d (%s)\n",
3493 connection, new_status,
3494 DISPATCH_STATUS_NAME (new_status));
3495 (* function) (connection, new_status, data);
3498 dbus_connection_unref (connection);
3502 * Gets the current state (what we would currently return
3503 * from dbus_connection_dispatch()) but doesn't actually
3504 * dispatch any messages.
3506 * @param connection the connection.
3507 * @returns current dispatch status
3510 dbus_connection_get_dispatch_status (DBusConnection *connection)
3512 DBusDispatchStatus status;
3514 _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
3516 _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
3518 CONNECTION_LOCK (connection);
3520 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3522 CONNECTION_UNLOCK (connection);
3528 * Filter funtion for handling the Peer standard interface
3530 static DBusHandlerResult
3531 _dbus_connection_peer_filter_unlocked_no_update (DBusConnection *connection,
3532 DBusMessage *message)
3534 if (dbus_message_is_method_call (message,
3535 DBUS_INTERFACE_PEER,
3541 ret = dbus_message_new_method_return (message);
3543 return DBUS_HANDLER_RESULT_NEED_MEMORY;
3545 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
3547 dbus_message_unref (ret);
3550 return DBUS_HANDLER_RESULT_NEED_MEMORY;
3552 return DBUS_HANDLER_RESULT_HANDLED;
3556 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
3560 * Processes all builtin filter functions
3562 * If the spec specifies a standard interface
3563 * they should be processed from this method
3565 static DBusHandlerResult
3566 _dbus_connection_run_builtin_filters_unlocked_no_update (DBusConnection *connection,
3567 DBusMessage *message)
3569 /* We just run one filter for now but have the option to run more
3570 if the spec calls for it in the future */
3572 return _dbus_connection_peer_filter_unlocked_no_update (connection, message);
3576 * Processes data buffered while handling watches, queueing zero or
3577 * more incoming messages. Then pops the first-received message from
3578 * the current incoming message queue, runs any handlers for it, and
3579 * unrefs the message. Returns a status indicating whether messages/data
3580 * remain, more memory is needed, or all data has been processed.
3582 * Even if the dispatch status is #DBUS_DISPATCH_DATA_REMAINS,
3583 * does not necessarily dispatch a message, as the data may
3584 * be part of authentication or the like.
3586 * @todo some FIXME in here about handling DBUS_HANDLER_RESULT_NEED_MEMORY
3588 * @todo FIXME what if we call out to application code to handle a
3589 * message, holding the dispatch lock, and the application code runs
3590 * the main loop and dispatches again? Probably deadlocks at the
3591 * moment. Maybe we want a dispatch status of DBUS_DISPATCH_IN_PROGRESS,
3592 * and then the GSource etc. could handle the situation? Right now
3593 * our GSource is NO_RECURSE
3595 * @param connection the connection
3596 * @returns dispatch status
3599 dbus_connection_dispatch (DBusConnection *connection)
3601 DBusMessage *message;
3602 DBusList *link, *filter_list_copy, *message_link;
3603 DBusHandlerResult result;
3604 DBusPendingCall *pending;
3605 dbus_int32_t reply_serial;
3606 DBusDispatchStatus status;
3608 _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
3610 _dbus_verbose ("%s\n", _DBUS_FUNCTION_NAME);
3612 CONNECTION_LOCK (connection);
3613 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3614 if (status != DBUS_DISPATCH_DATA_REMAINS)
3616 /* unlocks and calls out to user code */
3617 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3621 /* We need to ref the connection since the callback could potentially
3622 * drop the last ref to it
3624 _dbus_connection_ref_unlocked (connection);
3626 _dbus_connection_acquire_dispatch (connection);
3627 HAVE_LOCK_CHECK (connection);
3629 message_link = _dbus_connection_pop_message_link_unlocked (connection);
3630 if (message_link == NULL)
3632 /* another thread dispatched our stuff */
3634 _dbus_verbose ("another thread dispatched message (during acquire_dispatch above)\n");
3636 _dbus_connection_release_dispatch (connection);
3638 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3640 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3642 dbus_connection_unref (connection);
3647 message = message_link->data;
3649 _dbus_verbose (" dispatching message %p (%d %s %s '%s')\n",
3651 dbus_message_get_type (message),
3652 dbus_message_get_interface (message) ?
3653 dbus_message_get_interface (message) :
3655 dbus_message_get_member (message) ?
3656 dbus_message_get_member (message) :
3658 dbus_message_get_signature (message));
3660 result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
3662 /* Pending call handling must be first, because if you do
3663 * dbus_connection_send_with_reply_and_block() or
3664 * dbus_pending_call_block() then no handlers/filters will be run on
3665 * the reply. We want consistent semantics in the case where we
3666 * dbus_connection_dispatch() the reply.
3669 reply_serial = dbus_message_get_reply_serial (message);
3670 pending = _dbus_hash_table_lookup_int (connection->pending_replies,
3674 _dbus_verbose ("Dispatching a pending reply\n");
3675 complete_pending_call_and_unlock (connection, pending, message);
3676 pending = NULL; /* it's probably unref'd */
3678 CONNECTION_LOCK (connection);
3679 _dbus_verbose ("pending call completed in dispatch\n");
3680 result = DBUS_HANDLER_RESULT_HANDLED;
3684 result = _dbus_connection_run_builtin_filters_unlocked_no_update (connection, message);
3685 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
3688 if (!_dbus_list_copy (&connection->filter_list, &filter_list_copy))
3690 _dbus_connection_release_dispatch (connection);
3691 HAVE_LOCK_CHECK (connection);
3693 _dbus_connection_failed_pop (connection, message_link);
3695 /* unlocks and calls user code */
3696 _dbus_connection_update_dispatch_status_and_unlock (connection,
3697 DBUS_DISPATCH_NEED_MEMORY);
3700 dbus_pending_call_unref (pending);
3701 dbus_connection_unref (connection);
3703 return DBUS_DISPATCH_NEED_MEMORY;
3706 _dbus_list_foreach (&filter_list_copy,
3707 (DBusForeachFunction)_dbus_message_filter_ref,
3710 /* We're still protected from dispatch() reentrancy here
3711 * since we acquired the dispatcher
3713 CONNECTION_UNLOCK (connection);
3715 link = _dbus_list_get_first_link (&filter_list_copy);
3716 while (link != NULL)
3718 DBusMessageFilter *filter = link->data;
3719 DBusList *next = _dbus_list_get_next_link (&filter_list_copy, link);
3721 if (filter->function == NULL)
3723 _dbus_verbose (" filter was removed in a callback function\n");
3728 _dbus_verbose (" running filter on message %p\n", message);
3729 result = (* filter->function) (connection, message, filter->user_data);
3731 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
3737 _dbus_list_foreach (&filter_list_copy,
3738 (DBusForeachFunction)_dbus_message_filter_unref,
3740 _dbus_list_clear (&filter_list_copy);
3742 CONNECTION_LOCK (connection);
3744 if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
3746 _dbus_verbose ("No memory in %s\n", _DBUS_FUNCTION_NAME);
3749 else if (result == DBUS_HANDLER_RESULT_HANDLED)
3751 _dbus_verbose ("filter handled message in dispatch\n");
3755 /* We're still protected from dispatch() reentrancy here
3756 * since we acquired the dispatcher
3758 _dbus_verbose (" running object path dispatch on message %p (%d %s %s '%s')\n",
3760 dbus_message_get_type (message),
3761 dbus_message_get_interface (message) ?
3762 dbus_message_get_interface (message) :
3764 dbus_message_get_member (message) ?
3765 dbus_message_get_member (message) :
3767 dbus_message_get_signature (message));
3769 HAVE_LOCK_CHECK (connection);
3770 result = _dbus_object_tree_dispatch_and_unlock (connection->objects,
3773 CONNECTION_LOCK (connection);
3775 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
3777 _dbus_verbose ("object tree handled message in dispatch\n");
3781 if (dbus_message_get_type (message) == DBUS_MESSAGE_TYPE_METHOD_CALL)
3785 DBusPreallocatedSend *preallocated;
3787 _dbus_verbose (" sending error %s\n",
3788 DBUS_ERROR_UNKNOWN_METHOD);
3790 if (!_dbus_string_init (&str))
3792 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
3793 _dbus_verbose ("no memory for error string in dispatch\n");
3797 if (!_dbus_string_append_printf (&str,
3798 "Method \"%s\" with signature \"%s\" on interface \"%s\" doesn't exist\n",
3799 dbus_message_get_member (message),
3800 dbus_message_get_signature (message),
3801 dbus_message_get_interface (message)))
3803 _dbus_string_free (&str);
3804 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
3805 _dbus_verbose ("no memory for error string in dispatch\n");
3809 reply = dbus_message_new_error (message,
3810 DBUS_ERROR_UNKNOWN_METHOD,
3811 _dbus_string_get_const_data (&str));
3812 _dbus_string_free (&str);
3816 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
3817 _dbus_verbose ("no memory for error reply in dispatch\n");
3821 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
3823 if (preallocated == NULL)
3825 dbus_message_unref (reply);
3826 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
3827 _dbus_verbose ("no memory for error send in dispatch\n");
3831 _dbus_connection_send_preallocated_unlocked_no_update (connection, preallocated,
3834 dbus_message_unref (reply);
3836 result = DBUS_HANDLER_RESULT_HANDLED;
3839 _dbus_verbose (" done dispatching %p (%d %s %s '%s') on connection %p\n", message,
3840 dbus_message_get_type (message),
3841 dbus_message_get_interface (message) ?
3842 dbus_message_get_interface (message) :
3844 dbus_message_get_member (message) ?
3845 dbus_message_get_member (message) :
3847 dbus_message_get_signature (message),
3851 if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
3853 _dbus_verbose ("out of memory in %s\n", _DBUS_FUNCTION_NAME);
3855 /* Put message back, and we'll start over.
3856 * Yes this means handlers must be idempotent if they
3857 * don't return HANDLED; c'est la vie.
3859 _dbus_connection_putback_message_link_unlocked (connection,
3864 _dbus_verbose (" ... done dispatching in %s\n", _DBUS_FUNCTION_NAME);
3866 if (dbus_message_is_signal (message,
3867 DBUS_INTERFACE_LOCAL,
3870 _dbus_bus_check_connection_and_unref_unlocked (connection);
3872 if (connection->exit_on_disconnect)
3874 CONNECTION_UNLOCK (connection);
3876 _dbus_verbose ("Exiting on Disconnected signal\n");
3878 _dbus_assert_not_reached ("Call to exit() returned");
3882 _dbus_list_free_link (message_link);
3883 dbus_message_unref (message); /* don't want the message to count in max message limits
3884 * in computing dispatch status below
3888 _dbus_connection_release_dispatch (connection);
3889 HAVE_LOCK_CHECK (connection);
3891 _dbus_verbose ("%s before final status update\n", _DBUS_FUNCTION_NAME);
3892 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3894 /* unlocks and calls user code */
3895 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3897 dbus_connection_unref (connection);
3903 * Sets the watch functions for the connection. These functions are
3904 * responsible for making the application's main loop aware of file
3905 * descriptors that need to be monitored for events, using select() or
3906 * poll(). When using Qt, typically the DBusAddWatchFunction would
3907 * create a QSocketNotifier. When using GLib, the DBusAddWatchFunction
3908 * could call g_io_add_watch(), or could be used as part of a more
3909 * elaborate GSource. Note that when a watch is added, it may
3912 * The DBusWatchToggledFunction notifies the application that the
3913 * watch has been enabled or disabled. Call dbus_watch_get_enabled()
3914 * to check this. A disabled watch should have no effect, and enabled
3915 * watch should be added to the main loop. This feature is used
3916 * instead of simply adding/removing the watch because
3917 * enabling/disabling can be done without memory allocation. The
3918 * toggled function may be NULL if a main loop re-queries
3919 * dbus_watch_get_enabled() every time anyway.
3921 * The DBusWatch can be queried for the file descriptor to watch using
3922 * dbus_watch_get_fd(), and for the events to watch for using
3923 * dbus_watch_get_flags(). The flags returned by
3924 * dbus_watch_get_flags() will only contain DBUS_WATCH_READABLE and
3925 * DBUS_WATCH_WRITABLE, never DBUS_WATCH_HANGUP or DBUS_WATCH_ERROR;
3926 * all watches implicitly include a watch for hangups, errors, and
3927 * other exceptional conditions.
3929 * Once a file descriptor becomes readable or writable, or an exception
3930 * occurs, dbus_watch_handle() should be called to
3931 * notify the connection of the file descriptor's condition.
3933 * dbus_watch_handle() cannot be called during the
3934 * DBusAddWatchFunction, as the connection will not be ready to handle
3937 * It is not allowed to reference a DBusWatch after it has been passed
3938 * to remove_function.
3940 * If #FALSE is returned due to lack of memory, the failure may be due
3941 * to a #FALSE return from the new add_function. If so, the
3942 * add_function may have been called successfully one or more times,
3943 * but the remove_function will also have been called to remove any
3944 * successful adds. i.e. if #FALSE is returned the net result
3945 * should be that dbus_connection_set_watch_functions() has no effect,
3946 * but the add_function and remove_function may have been called.
3948 * @todo We need to drop the lock when we call the
3949 * add/remove/toggled functions which can be a side effect
3950 * of setting the watch functions.
3952 * @param connection the connection.
3953 * @param add_function function to begin monitoring a new descriptor.
3954 * @param remove_function function to stop monitoring a descriptor.
3955 * @param toggled_function function to notify of enable/disable
3956 * @param data data to pass to add_function and remove_function.
3957 * @param free_data_function function to be called to free the data.
3958 * @returns #FALSE on failure (no memory)
3961 dbus_connection_set_watch_functions (DBusConnection *connection,
3962 DBusAddWatchFunction add_function,
3963 DBusRemoveWatchFunction remove_function,
3964 DBusWatchToggledFunction toggled_function,
3966 DBusFreeFunction free_data_function)
3969 DBusWatchList *watches;
3971 _dbus_return_val_if_fail (connection != NULL, FALSE);
3973 CONNECTION_LOCK (connection);
3975 #ifndef DBUS_DISABLE_CHECKS
3976 if (connection->watches == NULL)
3978 _dbus_warn ("Re-entrant call to %s is not allowed\n",
3979 _DBUS_FUNCTION_NAME);
3984 /* ref connection for slightly better reentrancy */
3985 _dbus_connection_ref_unlocked (connection);
3987 /* This can call back into user code, and we need to drop the
3988 * connection lock when it does. This is kind of a lame
3991 watches = connection->watches;
3992 connection->watches = NULL;
3993 CONNECTION_UNLOCK (connection);
3995 retval = _dbus_watch_list_set_functions (watches,
3996 add_function, remove_function,
3998 data, free_data_function);
3999 CONNECTION_LOCK (connection);
4000 connection->watches = watches;
4002 CONNECTION_UNLOCK (connection);
4003 /* drop our paranoid refcount */
4004 dbus_connection_unref (connection);
4010 * Sets the timeout functions for the connection. These functions are
4011 * responsible for making the application's main loop aware of timeouts.
4012 * When using Qt, typically the DBusAddTimeoutFunction would create a
4013 * QTimer. When using GLib, the DBusAddTimeoutFunction would call
4016 * The DBusTimeoutToggledFunction notifies the application that the
4017 * timeout has been enabled or disabled. Call
4018 * dbus_timeout_get_enabled() to check this. A disabled timeout should
4019 * have no effect, and enabled timeout should be added to the main
4020 * loop. This feature is used instead of simply adding/removing the
4021 * timeout because enabling/disabling can be done without memory
4022 * allocation. With Qt, QTimer::start() and QTimer::stop() can be used
4023 * to enable and disable. The toggled function may be NULL if a main
4024 * loop re-queries dbus_timeout_get_enabled() every time anyway.
4025 * Whenever a timeout is toggled, its interval may change.
4027 * The DBusTimeout can be queried for the timer interval using
4028 * dbus_timeout_get_interval(). dbus_timeout_handle() should be called
4029 * repeatedly, each time the interval elapses, starting after it has
4030 * elapsed once. The timeout stops firing when it is removed with the
4031 * given remove_function. The timer interval may change whenever the
4032 * timeout is added, removed, or toggled.
4034 * @param connection the connection.
4035 * @param add_function function to add a timeout.
4036 * @param remove_function function to remove a timeout.
4037 * @param toggled_function function to notify of enable/disable
4038 * @param data data to pass to add_function and remove_function.
4039 * @param free_data_function function to be called to free the data.
4040 * @returns #FALSE on failure (no memory)
4043 dbus_connection_set_timeout_functions (DBusConnection *connection,
4044 DBusAddTimeoutFunction add_function,
4045 DBusRemoveTimeoutFunction remove_function,
4046 DBusTimeoutToggledFunction toggled_function,
4048 DBusFreeFunction free_data_function)
4051 DBusTimeoutList *timeouts;
4053 _dbus_return_val_if_fail (connection != NULL, FALSE);
4055 CONNECTION_LOCK (connection);
4057 #ifndef DBUS_DISABLE_CHECKS
4058 if (connection->timeouts == NULL)
4060 _dbus_warn ("Re-entrant call to %s is not allowed\n",
4061 _DBUS_FUNCTION_NAME);
4066 /* ref connection for slightly better reentrancy */
4067 _dbus_connection_ref_unlocked (connection);
4069 timeouts = connection->timeouts;
4070 connection->timeouts = NULL;
4071 CONNECTION_UNLOCK (connection);
4073 retval = _dbus_timeout_list_set_functions (timeouts,
4074 add_function, remove_function,
4076 data, free_data_function);
4077 CONNECTION_LOCK (connection);
4078 connection->timeouts = timeouts;
4080 CONNECTION_UNLOCK (connection);
4081 /* drop our paranoid refcount */
4082 dbus_connection_unref (connection);
4088 * Sets the mainloop wakeup function for the connection. This function is
4089 * responsible for waking up the main loop (if its sleeping) when some some
4090 * change has happened to the connection that the mainloop needs to reconsider
4091 * (e.g. a message has been queued for writing).
4092 * When using Qt, this typically results in a call to QEventLoop::wakeUp().
4093 * When using GLib, it would call g_main_context_wakeup().
4096 * @param connection the connection.
4097 * @param wakeup_main_function function to wake up the mainloop
4098 * @param data data to pass wakeup_main_function
4099 * @param free_data_function function to be called to free the data.
4102 dbus_connection_set_wakeup_main_function (DBusConnection *connection,
4103 DBusWakeupMainFunction wakeup_main_function,
4105 DBusFreeFunction free_data_function)
4108 DBusFreeFunction old_free_data;
4110 _dbus_return_if_fail (connection != NULL);
4112 CONNECTION_LOCK (connection);
4113 old_data = connection->wakeup_main_data;
4114 old_free_data = connection->free_wakeup_main_data;
4116 connection->wakeup_main_function = wakeup_main_function;
4117 connection->wakeup_main_data = data;
4118 connection->free_wakeup_main_data = free_data_function;
4120 CONNECTION_UNLOCK (connection);
4122 /* Callback outside the lock */
4124 (*old_free_data) (old_data);
4128 * Set a function to be invoked when the dispatch status changes.
4129 * If the dispatch status is #DBUS_DISPATCH_DATA_REMAINS, then
4130 * dbus_connection_dispatch() needs to be called to process incoming
4131 * messages. However, dbus_connection_dispatch() MUST NOT BE CALLED
4132 * from inside the DBusDispatchStatusFunction. Indeed, almost
4133 * any reentrancy in this function is a bad idea. Instead,
4134 * the DBusDispatchStatusFunction should simply save an indication
4135 * that messages should be dispatched later, when the main loop
4138 * @param connection the connection
4139 * @param function function to call on dispatch status changes
4140 * @param data data for function
4141 * @param free_data_function free the function data
4144 dbus_connection_set_dispatch_status_function (DBusConnection *connection,
4145 DBusDispatchStatusFunction function,
4147 DBusFreeFunction free_data_function)
4150 DBusFreeFunction old_free_data;
4152 _dbus_return_if_fail (connection != NULL);
4154 CONNECTION_LOCK (connection);
4155 old_data = connection->dispatch_status_data;
4156 old_free_data = connection->free_dispatch_status_data;
4158 connection->dispatch_status_function = function;
4159 connection->dispatch_status_data = data;
4160 connection->free_dispatch_status_data = free_data_function;
4162 CONNECTION_UNLOCK (connection);
4164 /* Callback outside the lock */
4166 (*old_free_data) (old_data);
4170 * Get the UNIX file descriptor of the connection, if any. This can
4171 * be used for SELinux access control checks with getpeercon() for
4172 * example. DO NOT read or write to the file descriptor, or try to
4173 * select() on it; use DBusWatch for main loop integration. Not all
4174 * connections will have a file descriptor. So for adding descriptors
4175 * to the main loop, use dbus_watch_get_fd() and so forth.
4177 * @param connection the connection
4178 * @param fd return location for the file descriptor.
4179 * @returns #TRUE if fd is successfully obtained.
4182 dbus_connection_get_unix_fd (DBusConnection *connection,
4187 _dbus_return_val_if_fail (connection != NULL, FALSE);
4188 _dbus_return_val_if_fail (connection->transport != NULL, FALSE);
4190 CONNECTION_LOCK (connection);
4192 retval = _dbus_transport_get_unix_fd (connection->transport,
4195 CONNECTION_UNLOCK (connection);
4201 * Gets the UNIX user ID of the connection if any.
4202 * Returns #TRUE if the uid is filled in.
4203 * Always returns #FALSE on non-UNIX platforms.
4204 * Always returns #FALSE prior to authenticating the
4207 * @param connection the connection
4208 * @param uid return location for the user ID
4209 * @returns #TRUE if uid is filled in with a valid user ID
4212 dbus_connection_get_unix_user (DBusConnection *connection,
4217 _dbus_return_val_if_fail (connection != NULL, FALSE);
4218 _dbus_return_val_if_fail (uid != NULL, FALSE);
4220 CONNECTION_LOCK (connection);
4222 if (!_dbus_transport_get_is_authenticated (connection->transport))
4225 result = _dbus_transport_get_unix_user (connection->transport,
4227 CONNECTION_UNLOCK (connection);
4233 * Gets the process ID of the connection if any.
4234 * Returns #TRUE if the uid is filled in.
4235 * Always returns #FALSE prior to authenticating the
4238 * @param connection the connection
4239 * @param pid return location for the process ID
4240 * @returns #TRUE if uid is filled in with a valid process ID
4243 dbus_connection_get_unix_process_id (DBusConnection *connection,
4248 _dbus_return_val_if_fail (connection != NULL, FALSE);
4249 _dbus_return_val_if_fail (pid != NULL, FALSE);
4251 CONNECTION_LOCK (connection);
4253 if (!_dbus_transport_get_is_authenticated (connection->transport))
4256 result = _dbus_transport_get_unix_process_id (connection->transport,
4258 CONNECTION_UNLOCK (connection);
4264 * Sets a predicate function used to determine whether a given user ID
4265 * is allowed to connect. When an incoming connection has
4266 * authenticated with a particular user ID, this function is called;
4267 * if it returns #TRUE, the connection is allowed to proceed,
4268 * otherwise the connection is disconnected.
4270 * If the function is set to #NULL (as it is by default), then
4271 * only the same UID as the server process will be allowed to
4274 * @param connection the connection
4275 * @param function the predicate
4276 * @param data data to pass to the predicate
4277 * @param free_data_function function to free the data
4280 dbus_connection_set_unix_user_function (DBusConnection *connection,
4281 DBusAllowUnixUserFunction function,
4283 DBusFreeFunction free_data_function)
4285 void *old_data = NULL;
4286 DBusFreeFunction old_free_function = NULL;
4288 _dbus_return_if_fail (connection != NULL);
4290 CONNECTION_LOCK (connection);
4291 _dbus_transport_set_unix_user_function (connection->transport,
4292 function, data, free_data_function,
4293 &old_data, &old_free_function);
4294 CONNECTION_UNLOCK (connection);
4296 if (old_free_function != NULL)
4297 (* old_free_function) (old_data);
4301 * Adds a message filter. Filters are handlers that are run on all
4302 * incoming messages, prior to the objects registered with
4303 * dbus_connection_register_object_path(). Filters are run in the
4304 * order that they were added. The same handler can be added as a
4305 * filter more than once, in which case it will be run more than once.
4306 * Filters added during a filter callback won't be run on the message
4309 * @todo we don't run filters on messages while blocking without
4310 * entering the main loop, since filters are run as part of
4311 * dbus_connection_dispatch(). This is probably a feature, as filters
4312 * could create arbitrary reentrancy. But kind of sucks if you're
4313 * trying to filter METHOD_RETURN for some reason.
4315 * @param connection the connection
4316 * @param function function to handle messages
4317 * @param user_data user data to pass to the function
4318 * @param free_data_function function to use for freeing user data
4319 * @returns #TRUE on success, #FALSE if not enough memory.
4322 dbus_connection_add_filter (DBusConnection *connection,
4323 DBusHandleMessageFunction function,
4325 DBusFreeFunction free_data_function)
4327 DBusMessageFilter *filter;
4329 _dbus_return_val_if_fail (connection != NULL, FALSE);
4330 _dbus_return_val_if_fail (function != NULL, FALSE);
4332 filter = dbus_new0 (DBusMessageFilter, 1);
4336 filter->refcount.value = 1;
4338 CONNECTION_LOCK (connection);
4340 if (!_dbus_list_append (&connection->filter_list,
4343 _dbus_message_filter_unref (filter);
4344 CONNECTION_UNLOCK (connection);
4348 /* Fill in filter after all memory allocated,
4349 * so we don't run the free_user_data_function
4350 * if the add_filter() fails
4353 filter->function = function;
4354 filter->user_data = user_data;
4355 filter->free_user_data_function = free_data_function;
4357 CONNECTION_UNLOCK (connection);
4362 * Removes a previously-added message filter. It is a programming
4363 * error to call this function for a handler that has not been added
4364 * as a filter. If the given handler was added more than once, only
4365 * one instance of it will be removed (the most recently-added
4368 * @param connection the connection
4369 * @param function the handler to remove
4370 * @param user_data user data for the handler to remove
4374 dbus_connection_remove_filter (DBusConnection *connection,
4375 DBusHandleMessageFunction function,
4379 DBusMessageFilter *filter;
4381 _dbus_return_if_fail (connection != NULL);
4382 _dbus_return_if_fail (function != NULL);
4384 CONNECTION_LOCK (connection);
4388 link = _dbus_list_get_last_link (&connection->filter_list);
4389 while (link != NULL)
4391 filter = link->data;
4393 if (filter->function == function &&
4394 filter->user_data == user_data)
4396 _dbus_list_remove_link (&connection->filter_list, link);
4397 filter->function = NULL;
4402 link = _dbus_list_get_prev_link (&connection->filter_list, link);
4405 CONNECTION_UNLOCK (connection);
4407 #ifndef DBUS_DISABLE_CHECKS
4410 _dbus_warn ("Attempt to remove filter function %p user data %p, but no such filter has been added\n",
4411 function, user_data);
4416 /* Call application code */
4417 if (filter->free_user_data_function)
4418 (* filter->free_user_data_function) (filter->user_data);
4420 filter->free_user_data_function = NULL;
4421 filter->user_data = NULL;
4423 _dbus_message_filter_unref (filter);
4427 * Registers a handler for a given path in the object hierarchy.
4428 * The given vtable handles messages sent to exactly the given path.
4431 * @param connection the connection
4432 * @param path a '/' delimited string of path elements
4433 * @param vtable the virtual table
4434 * @param user_data data to pass to functions in the vtable
4435 * @returns #FALSE if not enough memory
4438 dbus_connection_register_object_path (DBusConnection *connection,
4440 const DBusObjectPathVTable *vtable,
4443 char **decomposed_path;
4446 _dbus_return_val_if_fail (connection != NULL, FALSE);
4447 _dbus_return_val_if_fail (path != NULL, FALSE);
4448 _dbus_return_val_if_fail (path[0] == '/', FALSE);
4449 _dbus_return_val_if_fail (vtable != NULL, FALSE);
4451 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
4454 CONNECTION_LOCK (connection);
4456 retval = _dbus_object_tree_register (connection->objects,
4458 (const char **) decomposed_path, vtable,
4461 CONNECTION_UNLOCK (connection);
4463 dbus_free_string_array (decomposed_path);
4469 * Registers a fallback handler for a given subsection of the object
4470 * hierarchy. The given vtable handles messages at or below the given
4471 * path. You can use this to establish a default message handling
4472 * policy for a whole "subdirectory."
4474 * @param connection the connection
4475 * @param path a '/' delimited string of path elements
4476 * @param vtable the virtual table
4477 * @param user_data data to pass to functions in the vtable
4478 * @returns #FALSE if not enough memory
4481 dbus_connection_register_fallback (DBusConnection *connection,
4483 const DBusObjectPathVTable *vtable,
4486 char **decomposed_path;
4489 _dbus_return_val_if_fail (connection != NULL, FALSE);
4490 _dbus_return_val_if_fail (path != NULL, FALSE);
4491 _dbus_return_val_if_fail (path[0] == '/', FALSE);
4492 _dbus_return_val_if_fail (vtable != NULL, FALSE);
4494 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
4497 CONNECTION_LOCK (connection);
4499 retval = _dbus_object_tree_register (connection->objects,
4501 (const char **) decomposed_path, vtable,
4504 CONNECTION_UNLOCK (connection);
4506 dbus_free_string_array (decomposed_path);
4512 * Unregisters the handler registered with exactly the given path.
4513 * It's a bug to call this function for a path that isn't registered.
4514 * Can unregister both fallback paths and object paths.
4516 * @param connection the connection
4517 * @param path a '/' delimited string of path elements
4518 * @returns #FALSE if not enough memory
4521 dbus_connection_unregister_object_path (DBusConnection *connection,
4524 char **decomposed_path;
4526 _dbus_return_val_if_fail (connection != NULL, FALSE);
4527 _dbus_return_val_if_fail (path != NULL, FALSE);
4528 _dbus_return_val_if_fail (path[0] == '/', FALSE);
4530 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
4533 CONNECTION_LOCK (connection);
4535 _dbus_object_tree_unregister_and_unlock (connection->objects, (const char **) decomposed_path);
4537 dbus_free_string_array (decomposed_path);
4543 * Gets the user data passed to dbus_connection_register_object_path()
4544 * or dbus_connection_register_fallback(). If nothing was registered
4545 * at this path, the data is filled in with #NULL.
4547 * @param connection the connection
4548 * @param path the path you registered with
4549 * @param data_p location to store the user data, or #NULL
4550 * @returns #FALSE if not enough memory
4553 dbus_connection_get_object_path_data (DBusConnection *connection,
4557 char **decomposed_path;
4559 _dbus_return_val_if_fail (connection != NULL, FALSE);
4560 _dbus_return_val_if_fail (path != NULL, FALSE);
4561 _dbus_return_val_if_fail (data_p != NULL, FALSE);
4565 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
4568 CONNECTION_LOCK (connection);
4570 *data_p = _dbus_object_tree_get_user_data_unlocked (connection->objects, (const char**) decomposed_path);
4572 CONNECTION_UNLOCK (connection);
4574 dbus_free_string_array (decomposed_path);
4580 * Lists the registered fallback handlers and object path handlers at
4581 * the given parent_path. The returned array should be freed with
4582 * dbus_free_string_array().
4584 * @param connection the connection
4585 * @param parent_path the path to list the child handlers of
4586 * @param child_entries returns #NULL-terminated array of children
4587 * @returns #FALSE if no memory to allocate the child entries
4590 dbus_connection_list_registered (DBusConnection *connection,
4591 const char *parent_path,
4592 char ***child_entries)
4594 char **decomposed_path;
4596 _dbus_return_val_if_fail (connection != NULL, FALSE);
4597 _dbus_return_val_if_fail (parent_path != NULL, FALSE);
4598 _dbus_return_val_if_fail (parent_path[0] == '/', FALSE);
4599 _dbus_return_val_if_fail (child_entries != NULL, FALSE);
4601 if (!_dbus_decompose_path (parent_path, strlen (parent_path), &decomposed_path, NULL))
4604 CONNECTION_LOCK (connection);
4606 retval = _dbus_object_tree_list_registered_and_unlock (connection->objects,
4607 (const char **) decomposed_path,
4609 dbus_free_string_array (decomposed_path);
4614 static DBusDataSlotAllocator slot_allocator;
4615 _DBUS_DEFINE_GLOBAL_LOCK (connection_slots);
4618 * Allocates an integer ID to be used for storing application-specific
4619 * data on any DBusConnection. The allocated ID may then be used
4620 * with dbus_connection_set_data() and dbus_connection_get_data().
4621 * The passed-in slot must be initialized to -1, and is filled in
4622 * with the slot ID. If the passed-in slot is not -1, it's assumed
4623 * to be already allocated, and its refcount is incremented.
4625 * The allocated slot is global, i.e. all DBusConnection objects will
4626 * have a slot with the given integer ID reserved.
4628 * @param slot_p address of a global variable storing the slot
4629 * @returns #FALSE on failure (no memory)
4632 dbus_connection_allocate_data_slot (dbus_int32_t *slot_p)
4634 return _dbus_data_slot_allocator_alloc (&slot_allocator,
4635 &_DBUS_LOCK_NAME (connection_slots),
4640 * Deallocates a global ID for connection data slots.
4641 * dbus_connection_get_data() and dbus_connection_set_data() may no
4642 * longer be used with this slot. Existing data stored on existing
4643 * DBusConnection objects will be freed when the connection is
4644 * finalized, but may not be retrieved (and may only be replaced if
4645 * someone else reallocates the slot). When the refcount on the
4646 * passed-in slot reaches 0, it is set to -1.
4648 * @param slot_p address storing the slot to deallocate
4651 dbus_connection_free_data_slot (dbus_int32_t *slot_p)
4653 _dbus_return_if_fail (*slot_p >= 0);
4655 _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
4659 * Stores a pointer on a DBusConnection, along
4660 * with an optional function to be used for freeing
4661 * the data when the data is set again, or when
4662 * the connection is finalized. The slot number
4663 * must have been allocated with dbus_connection_allocate_data_slot().
4665 * @param connection the connection
4666 * @param slot the slot number
4667 * @param data the data to store
4668 * @param free_data_func finalizer function for the data
4669 * @returns #TRUE if there was enough memory to store the data
4672 dbus_connection_set_data (DBusConnection *connection,
4675 DBusFreeFunction free_data_func)
4677 DBusFreeFunction old_free_func;
4681 _dbus_return_val_if_fail (connection != NULL, FALSE);
4682 _dbus_return_val_if_fail (slot >= 0, FALSE);
4684 CONNECTION_LOCK (connection);
4686 retval = _dbus_data_slot_list_set (&slot_allocator,
4687 &connection->slot_list,
4688 slot, data, free_data_func,
4689 &old_free_func, &old_data);
4691 CONNECTION_UNLOCK (connection);
4695 /* Do the actual free outside the connection lock */
4697 (* old_free_func) (old_data);
4704 * Retrieves data previously set with dbus_connection_set_data().
4705 * The slot must still be allocated (must not have been freed).
4707 * @param connection the connection
4708 * @param slot the slot to get data from
4709 * @returns the data, or #NULL if not found
4712 dbus_connection_get_data (DBusConnection *connection,
4717 _dbus_return_val_if_fail (connection != NULL, NULL);
4719 CONNECTION_LOCK (connection);
4721 res = _dbus_data_slot_list_get (&slot_allocator,
4722 &connection->slot_list,
4725 CONNECTION_UNLOCK (connection);
4731 * This function sets a global flag for whether dbus_connection_new()
4732 * will set SIGPIPE behavior to SIG_IGN.
4734 * @param will_modify_sigpipe #TRUE to allow sigpipe to be set to SIG_IGN
4737 dbus_connection_set_change_sigpipe (dbus_bool_t will_modify_sigpipe)
4739 _dbus_modify_sigpipe = will_modify_sigpipe != FALSE;
4743 * Specifies the maximum size message this connection is allowed to
4744 * receive. Larger messages will result in disconnecting the
4747 * @param connection a #DBusConnection
4748 * @param size maximum message size the connection can receive, in bytes
4751 dbus_connection_set_max_message_size (DBusConnection *connection,
4754 _dbus_return_if_fail (connection != NULL);
4756 CONNECTION_LOCK (connection);
4757 _dbus_transport_set_max_message_size (connection->transport,
4759 CONNECTION_UNLOCK (connection);
4763 * Gets the value set by dbus_connection_set_max_message_size().
4765 * @param connection the connection
4766 * @returns the max size of a single message
4769 dbus_connection_get_max_message_size (DBusConnection *connection)
4773 _dbus_return_val_if_fail (connection != NULL, 0);
4775 CONNECTION_LOCK (connection);
4776 res = _dbus_transport_get_max_message_size (connection->transport);
4777 CONNECTION_UNLOCK (connection);
4782 * Sets the maximum total number of bytes that can be used for all messages
4783 * received on this connection. Messages count toward the maximum until
4784 * they are finalized. When the maximum is reached, the connection will
4785 * not read more data until some messages are finalized.
4787 * The semantics of the maximum are: if outstanding messages are
4788 * already above the maximum, additional messages will not be read.
4789 * The semantics are not: if the next message would cause us to exceed
4790 * the maximum, we don't read it. The reason is that we don't know the
4791 * size of a message until after we read it.
4793 * Thus, the max live messages size can actually be exceeded
4794 * by up to the maximum size of a single message.
4796 * Also, if we read say 1024 bytes off the wire in a single read(),
4797 * and that contains a half-dozen small messages, we may exceed the
4798 * size max by that amount. But this should be inconsequential.
4800 * This does imply that we can't call read() with a buffer larger
4801 * than we're willing to exceed this limit by.
4803 * @param connection the connection
4804 * @param size the maximum size in bytes of all outstanding messages
4807 dbus_connection_set_max_received_size (DBusConnection *connection,
4810 _dbus_return_if_fail (connection != NULL);
4812 CONNECTION_LOCK (connection);
4813 _dbus_transport_set_max_received_size (connection->transport,
4815 CONNECTION_UNLOCK (connection);
4819 * Gets the value set by dbus_connection_set_max_received_size().
4821 * @param connection the connection
4822 * @returns the max size of all live messages
4825 dbus_connection_get_max_received_size (DBusConnection *connection)
4829 _dbus_return_val_if_fail (connection != NULL, 0);
4831 CONNECTION_LOCK (connection);
4832 res = _dbus_transport_get_max_received_size (connection->transport);
4833 CONNECTION_UNLOCK (connection);
4838 * Gets the approximate size in bytes of all messages in the outgoing
4839 * message queue. The size is approximate in that you shouldn't use
4840 * it to decide how many bytes to read off the network or anything
4841 * of that nature, as optimizations may choose to tell small white lies
4842 * to avoid performance overhead.
4844 * @param connection the connection
4845 * @returns the number of bytes that have been queued up but not sent
4848 dbus_connection_get_outgoing_size (DBusConnection *connection)
4852 _dbus_return_val_if_fail (connection != NULL, 0);
4854 CONNECTION_LOCK (connection);
4855 res = _dbus_counter_get_value (connection->outgoing_counter);
4856 CONNECTION_UNLOCK (connection);