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 dispatch_acquired : 1; /**< Someone has dispatch path (can drain incoming queue) */
244 unsigned int io_path_acquired : 1; /**< Someone has transport io path (can use the transport to read/write messages) */
246 unsigned int exit_on_disconnect : 1; /**< If #TRUE, exit after handling disconnect signal */
248 #ifndef DBUS_DISABLE_CHECKS
249 unsigned int have_connection_lock : 1; /**< Used to check locking */
252 #ifndef DBUS_DISABLE_CHECKS
253 int generation; /**< _dbus_current_generation that should correspond to this connection */
257 static DBusDispatchStatus _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection);
258 static void _dbus_connection_update_dispatch_status_and_unlock (DBusConnection *connection,
259 DBusDispatchStatus new_status);
260 static void _dbus_connection_last_unref (DBusConnection *connection);
261 static void _dbus_connection_acquire_dispatch (DBusConnection *connection);
262 static void _dbus_connection_release_dispatch (DBusConnection *connection);
263 static DBusDispatchStatus _dbus_connection_flush_unlocked (DBusConnection *connection);
265 static DBusMessageFilter *
266 _dbus_message_filter_ref (DBusMessageFilter *filter)
268 _dbus_assert (filter->refcount.value > 0);
269 _dbus_atomic_inc (&filter->refcount);
275 _dbus_message_filter_unref (DBusMessageFilter *filter)
277 _dbus_assert (filter->refcount.value > 0);
279 if (_dbus_atomic_dec (&filter->refcount) == 1)
281 if (filter->free_user_data_function)
282 (* filter->free_user_data_function) (filter->user_data);
289 * Acquires the connection lock.
291 * @param connection the connection.
294 _dbus_connection_lock (DBusConnection *connection)
296 CONNECTION_LOCK (connection);
300 * Releases the connection lock.
302 * @param connection the connection.
305 _dbus_connection_unlock (DBusConnection *connection)
307 CONNECTION_UNLOCK (connection);
311 * Wakes up the main loop if it is sleeping
312 * Needed if we're e.g. queueing outgoing messages
313 * on a thread while the mainloop sleeps.
315 * @param connection the connection.
318 _dbus_connection_wakeup_mainloop (DBusConnection *connection)
320 if (connection->wakeup_main_function)
321 (*connection->wakeup_main_function) (connection->wakeup_main_data);
324 #ifdef DBUS_BUILD_TESTS
325 /* For now this function isn't used */
327 * Adds a message to the incoming message queue, returning #FALSE
328 * if there's insufficient memory to queue the message.
329 * Does not take over refcount of the message.
331 * @param connection the connection.
332 * @param message the message to queue.
333 * @returns #TRUE on success.
336 _dbus_connection_queue_received_message (DBusConnection *connection,
337 DBusMessage *message)
341 link = _dbus_list_alloc_link (message);
345 dbus_message_ref (message);
346 _dbus_connection_queue_received_message_link (connection, link);
353 * Adds a message-containing list link to the incoming message queue,
354 * taking ownership of the link and the message's current refcount.
355 * Cannot fail due to lack of memory.
357 * @param connection the connection.
358 * @param link the message link to queue.
361 _dbus_connection_queue_received_message_link (DBusConnection *connection,
364 DBusPendingCall *pending;
365 dbus_int32_t reply_serial;
366 DBusMessage *message;
368 _dbus_assert (_dbus_transport_get_is_authenticated (connection->transport));
370 _dbus_list_append_link (&connection->incoming_messages,
372 message = link->data;
374 /* If this is a reply we're waiting on, remove timeout for it */
375 reply_serial = dbus_message_get_reply_serial (message);
376 if (reply_serial != -1)
378 pending = _dbus_hash_table_lookup_int (connection->pending_replies,
382 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
383 _dbus_connection_remove_timeout_unlocked (connection,
384 _dbus_pending_call_get_timeout_unlocked (pending));
386 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
392 connection->n_incoming += 1;
394 _dbus_connection_wakeup_mainloop (connection);
396 _dbus_verbose ("Message %p (%d %s %s %s '%s' reply to %u) added to incoming queue %p, %d incoming\n",
398 dbus_message_get_type (message),
399 dbus_message_get_path (message) ?
400 dbus_message_get_path (message) :
402 dbus_message_get_interface (message) ?
403 dbus_message_get_interface (message) :
405 dbus_message_get_member (message) ?
406 dbus_message_get_member (message) :
408 dbus_message_get_signature (message),
409 dbus_message_get_reply_serial (message),
411 connection->n_incoming);}
414 * Adds a link + message to the incoming message queue.
415 * Can't fail. Takes ownership of both link and message.
417 * @param connection the connection.
418 * @param link the list node and message to queue.
420 * @todo This needs to wake up the mainloop if it is in
421 * a poll/select and this is a multithreaded app.
424 _dbus_connection_queue_synthesized_message_link (DBusConnection *connection,
427 HAVE_LOCK_CHECK (connection);
429 _dbus_list_append_link (&connection->incoming_messages, link);
431 connection->n_incoming += 1;
433 _dbus_connection_wakeup_mainloop (connection);
435 _dbus_verbose ("Synthesized message %p added to incoming queue %p, %d incoming\n",
436 link->data, connection, connection->n_incoming);
441 * Checks whether there are messages in the outgoing message queue.
442 * Called with connection lock held.
444 * @param connection the connection.
445 * @returns #TRUE if the outgoing queue is non-empty.
448 _dbus_connection_has_messages_to_send_unlocked (DBusConnection *connection)
450 HAVE_LOCK_CHECK (connection);
451 return connection->outgoing_messages != NULL;
455 * Checks whether there are messages in the outgoing message queue.
457 * @param connection the connection.
458 * @returns #TRUE if the outgoing queue is non-empty.
461 dbus_connection_has_messages_to_send (DBusConnection *connection)
465 _dbus_return_val_if_fail (connection != NULL, FALSE);
467 CONNECTION_LOCK (connection);
468 v = _dbus_connection_has_messages_to_send_unlocked (connection);
469 CONNECTION_UNLOCK (connection);
475 * Gets the next outgoing message. The message remains in the
476 * queue, and the caller does not own a reference to it.
478 * @param connection the connection.
479 * @returns the message to be sent.
482 _dbus_connection_get_message_to_send (DBusConnection *connection)
484 HAVE_LOCK_CHECK (connection);
486 return _dbus_list_get_last (&connection->outgoing_messages);
490 * Notifies the connection that a message has been sent, so the
491 * message can be removed from the outgoing queue.
492 * Called with the connection lock held.
494 * @param connection the connection.
495 * @param message the message that was sent.
498 _dbus_connection_message_sent (DBusConnection *connection,
499 DBusMessage *message)
503 HAVE_LOCK_CHECK (connection);
505 /* This can be called before we even complete authentication, since
506 * it's called on disconnect to clean up the outgoing queue.
507 * It's also called as we successfully send each message.
510 link = _dbus_list_get_last_link (&connection->outgoing_messages);
511 _dbus_assert (link != NULL);
512 _dbus_assert (link->data == message);
514 /* Save this link in the link cache */
515 _dbus_list_unlink (&connection->outgoing_messages,
517 _dbus_list_prepend_link (&connection->link_cache, link);
519 connection->n_outgoing -= 1;
521 _dbus_verbose ("Message %p (%d %s %s %s '%s') removed from outgoing queue %p, %d left to send\n",
523 dbus_message_get_type (message),
524 dbus_message_get_path (message) ?
525 dbus_message_get_path (message) :
527 dbus_message_get_interface (message) ?
528 dbus_message_get_interface (message) :
530 dbus_message_get_member (message) ?
531 dbus_message_get_member (message) :
533 dbus_message_get_signature (message),
534 connection, connection->n_outgoing);
536 /* Save this link in the link cache also */
537 _dbus_message_remove_size_counter (message, connection->outgoing_counter,
539 _dbus_list_prepend_link (&connection->link_cache, link);
541 dbus_message_unref (message);
544 typedef dbus_bool_t (* DBusWatchAddFunction) (DBusWatchList *list,
546 typedef void (* DBusWatchRemoveFunction) (DBusWatchList *list,
548 typedef void (* DBusWatchToggleFunction) (DBusWatchList *list,
550 dbus_bool_t enabled);
553 protected_change_watch (DBusConnection *connection,
555 DBusWatchAddFunction add_function,
556 DBusWatchRemoveFunction remove_function,
557 DBusWatchToggleFunction toggle_function,
560 DBusWatchList *watches;
563 HAVE_LOCK_CHECK (connection);
565 /* This isn't really safe or reasonable; a better pattern is the "do everything, then
566 * drop lock and call out" one; but it has to be propagated up through all callers
569 watches = connection->watches;
572 connection->watches = NULL;
573 _dbus_connection_ref_unlocked (connection);
574 CONNECTION_UNLOCK (connection);
577 retval = (* add_function) (watches, watch);
578 else if (remove_function)
581 (* remove_function) (watches, watch);
586 (* toggle_function) (watches, watch, enabled);
589 CONNECTION_LOCK (connection);
590 connection->watches = watches;
591 _dbus_connection_unref_unlocked (connection);
601 * Adds a watch using the connection's DBusAddWatchFunction if
602 * available. Otherwise records the watch to be added when said
603 * function is available. Also re-adds the watch if the
604 * DBusAddWatchFunction changes. May fail due to lack of memory.
605 * Connection lock should be held when calling this.
607 * @param connection the connection.
608 * @param watch the watch to add.
609 * @returns #TRUE on success.
612 _dbus_connection_add_watch_unlocked (DBusConnection *connection,
615 return protected_change_watch (connection, watch,
616 _dbus_watch_list_add_watch,
621 * Removes a watch using the connection's DBusRemoveWatchFunction
622 * if available. It's an error to call this function on a watch
623 * that was not previously added.
624 * Connection lock should be held when calling this.
626 * @param connection the connection.
627 * @param watch the watch to remove.
630 _dbus_connection_remove_watch_unlocked (DBusConnection *connection,
633 protected_change_watch (connection, watch,
635 _dbus_watch_list_remove_watch,
640 * Toggles a watch and notifies app via connection's
641 * DBusWatchToggledFunction if available. It's an error to call this
642 * function on a watch that was not previously added.
643 * Connection lock should be held when calling this.
645 * @param connection the connection.
646 * @param watch the watch to toggle.
647 * @param enabled whether to enable or disable
650 _dbus_connection_toggle_watch_unlocked (DBusConnection *connection,
654 _dbus_assert (watch != NULL);
656 protected_change_watch (connection, watch,
658 _dbus_watch_list_toggle_watch,
662 typedef dbus_bool_t (* DBusTimeoutAddFunction) (DBusTimeoutList *list,
663 DBusTimeout *timeout);
664 typedef void (* DBusTimeoutRemoveFunction) (DBusTimeoutList *list,
665 DBusTimeout *timeout);
666 typedef void (* DBusTimeoutToggleFunction) (DBusTimeoutList *list,
667 DBusTimeout *timeout,
668 dbus_bool_t enabled);
671 protected_change_timeout (DBusConnection *connection,
672 DBusTimeout *timeout,
673 DBusTimeoutAddFunction add_function,
674 DBusTimeoutRemoveFunction remove_function,
675 DBusTimeoutToggleFunction toggle_function,
678 DBusTimeoutList *timeouts;
681 HAVE_LOCK_CHECK (connection);
683 /* This isn't really safe or reasonable; a better pattern is the "do everything, then
684 * drop lock and call out" one; but it has to be propagated up through all callers
687 timeouts = connection->timeouts;
690 connection->timeouts = NULL;
691 _dbus_connection_ref_unlocked (connection);
692 CONNECTION_UNLOCK (connection);
695 retval = (* add_function) (timeouts, timeout);
696 else if (remove_function)
699 (* remove_function) (timeouts, timeout);
704 (* toggle_function) (timeouts, timeout, enabled);
707 CONNECTION_LOCK (connection);
708 connection->timeouts = timeouts;
709 _dbus_connection_unref_unlocked (connection);
718 * Adds a timeout using the connection's DBusAddTimeoutFunction if
719 * available. Otherwise records the timeout to be added when said
720 * function is available. Also re-adds the timeout if the
721 * DBusAddTimeoutFunction changes. May fail due to lack of memory.
722 * The timeout will fire repeatedly until removed.
723 * Connection lock should be held when calling this.
725 * @param connection the connection.
726 * @param timeout the timeout to add.
727 * @returns #TRUE on success.
730 _dbus_connection_add_timeout_unlocked (DBusConnection *connection,
731 DBusTimeout *timeout)
733 return protected_change_timeout (connection, timeout,
734 _dbus_timeout_list_add_timeout,
739 * Removes a timeout using the connection's DBusRemoveTimeoutFunction
740 * if available. It's an error to call this function on a timeout
741 * that was not previously added.
742 * Connection lock should be held when calling this.
744 * @param connection the connection.
745 * @param timeout the timeout to remove.
748 _dbus_connection_remove_timeout_unlocked (DBusConnection *connection,
749 DBusTimeout *timeout)
751 protected_change_timeout (connection, timeout,
753 _dbus_timeout_list_remove_timeout,
758 * Toggles a timeout and notifies app via connection's
759 * DBusTimeoutToggledFunction if available. It's an error to call this
760 * function on a timeout that was not previously added.
761 * Connection lock should be held when calling this.
763 * @param connection the connection.
764 * @param timeout the timeout to toggle.
765 * @param enabled whether to enable or disable
768 _dbus_connection_toggle_timeout_unlocked (DBusConnection *connection,
769 DBusTimeout *timeout,
772 protected_change_timeout (connection, timeout,
774 _dbus_timeout_list_toggle_timeout,
779 _dbus_connection_attach_pending_call_unlocked (DBusConnection *connection,
780 DBusPendingCall *pending)
782 dbus_uint32_t reply_serial;
783 DBusTimeout *timeout;
785 HAVE_LOCK_CHECK (connection);
787 reply_serial = _dbus_pending_call_get_reply_serial_unlocked (pending);
789 _dbus_assert (reply_serial != 0);
791 timeout = _dbus_pending_call_get_timeout_unlocked (pending);
793 if (!_dbus_connection_add_timeout_unlocked (connection, timeout))
796 if (!_dbus_hash_table_insert_int (connection->pending_replies,
800 _dbus_connection_remove_timeout_unlocked (connection, timeout);
802 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
803 HAVE_LOCK_CHECK (connection);
807 _dbus_pending_call_set_timeout_added_unlocked (pending, TRUE);
809 _dbus_pending_call_ref_unlocked (pending);
811 HAVE_LOCK_CHECK (connection);
817 free_pending_call_on_hash_removal (void *data)
819 DBusPendingCall *pending;
820 DBusConnection *connection;
827 connection = _dbus_pending_call_get_connection_unlocked (pending);
829 HAVE_LOCK_CHECK (connection);
831 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
833 _dbus_connection_remove_timeout_unlocked (connection,
834 _dbus_pending_call_get_timeout_unlocked (pending));
836 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
839 /* FIXME this is sort of dangerous and undesirable to drop the lock here, but
840 * the pending call finalizer could in principle call out to application code
841 * so we pretty much have to... some larger code reorg might be needed.
843 _dbus_connection_ref_unlocked (connection);
844 _dbus_pending_call_unref_and_unlock (pending);
845 CONNECTION_LOCK (connection);
846 _dbus_connection_unref_unlocked (connection);
850 _dbus_connection_detach_pending_call_unlocked (DBusConnection *connection,
851 DBusPendingCall *pending)
853 /* This ends up unlocking to call the pending call finalizer, which is unexpected to
856 _dbus_hash_table_remove_int (connection->pending_replies,
857 _dbus_pending_call_get_reply_serial_unlocked (pending));
861 _dbus_connection_detach_pending_call_and_unlock (DBusConnection *connection,
862 DBusPendingCall *pending)
864 /* The idea here is to avoid finalizing the pending call
865 * with the lock held, since there's a destroy notifier
866 * in pending call that goes out to application code.
868 * There's an extra unlock inside the hash table
869 * "free pending call" function FIXME...
871 _dbus_pending_call_ref_unlocked (pending);
872 _dbus_hash_table_remove_int (connection->pending_replies,
873 _dbus_pending_call_get_reply_serial_unlocked (pending));
874 _dbus_pending_call_unref_and_unlock (pending);
878 * Removes a pending call from the connection, such that
879 * the pending reply will be ignored. May drop the last
880 * reference to the pending call.
882 * @param connection the connection
883 * @param pending the pending call
886 _dbus_connection_remove_pending_call (DBusConnection *connection,
887 DBusPendingCall *pending)
889 CONNECTION_LOCK (connection);
890 _dbus_connection_detach_pending_call_and_unlock (connection, pending);
894 * Acquire the transporter I/O path. This must be done before
895 * doing any I/O in the transporter. May sleep and drop the
896 * IO path mutex while waiting for the I/O path.
898 * @param connection the connection.
899 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
900 * @returns TRUE if the I/O path was acquired.
903 _dbus_connection_acquire_io_path (DBusConnection *connection,
904 int timeout_milliseconds)
906 dbus_bool_t we_acquired;
908 HAVE_LOCK_CHECK (connection);
910 /* We don't want the connection to vanish */
911 _dbus_connection_ref_unlocked (connection);
913 /* We will only touch io_path_acquired which is protected by our mutex */
914 CONNECTION_UNLOCK (connection);
916 _dbus_verbose ("%s locking io_path_mutex\n", _DBUS_FUNCTION_NAME);
917 _dbus_mutex_lock (connection->io_path_mutex);
919 _dbus_verbose ("%s start connection->io_path_acquired = %d timeout = %d\n",
920 _DBUS_FUNCTION_NAME, connection->io_path_acquired, timeout_milliseconds);
924 if (connection->io_path_acquired)
926 if (timeout_milliseconds != -1)
928 _dbus_verbose ("%s waiting %d for IO path to be acquirable\n",
929 _DBUS_FUNCTION_NAME, timeout_milliseconds);
930 _dbus_condvar_wait_timeout (connection->io_path_cond,
931 connection->io_path_mutex,
932 timeout_milliseconds);
936 while (connection->io_path_acquired)
938 _dbus_verbose ("%s waiting for IO path to be acquirable\n", _DBUS_FUNCTION_NAME);
939 _dbus_condvar_wait (connection->io_path_cond, connection->io_path_mutex);
944 if (!connection->io_path_acquired)
947 connection->io_path_acquired = TRUE;
950 _dbus_verbose ("%s end connection->io_path_acquired = %d we_acquired = %d\n",
951 _DBUS_FUNCTION_NAME, connection->io_path_acquired, we_acquired);
953 _dbus_verbose ("%s unlocking io_path_mutex\n", _DBUS_FUNCTION_NAME);
954 _dbus_mutex_unlock (connection->io_path_mutex);
956 CONNECTION_LOCK (connection);
958 HAVE_LOCK_CHECK (connection);
960 _dbus_connection_unref_unlocked (connection);
966 * Release the I/O path when you're done with it. Only call
967 * after you've acquired the I/O. Wakes up at most one thread
968 * currently waiting to acquire the I/O path.
970 * @param connection the connection.
973 _dbus_connection_release_io_path (DBusConnection *connection)
975 HAVE_LOCK_CHECK (connection);
977 _dbus_verbose ("%s locking io_path_mutex\n", _DBUS_FUNCTION_NAME);
978 _dbus_mutex_lock (connection->io_path_mutex);
980 _dbus_assert (connection->io_path_acquired);
982 _dbus_verbose ("%s start connection->io_path_acquired = %d\n",
983 _DBUS_FUNCTION_NAME, connection->io_path_acquired);
985 connection->io_path_acquired = FALSE;
986 _dbus_condvar_wake_one (connection->io_path_cond);
988 _dbus_verbose ("%s unlocking io_path_mutex\n", _DBUS_FUNCTION_NAME);
989 _dbus_mutex_unlock (connection->io_path_mutex);
993 * Queues incoming messages and sends outgoing messages for this
994 * connection, optionally blocking in the process. Each call to
995 * _dbus_connection_do_iteration_unlocked() will call select() or poll() one
996 * time and then read or write data if possible.
998 * The purpose of this function is to be able to flush outgoing
999 * messages or queue up incoming messages without returning
1000 * control to the application and causing reentrancy weirdness.
1002 * The flags parameter allows you to specify whether to
1003 * read incoming messages, write outgoing messages, or both,
1004 * and whether to block if no immediate action is possible.
1006 * The timeout_milliseconds parameter does nothing unless the
1007 * iteration is blocking.
1009 * If there are no outgoing messages and DBUS_ITERATION_DO_READING
1010 * wasn't specified, then it's impossible to block, even if
1011 * you specify DBUS_ITERATION_BLOCK; in that case the function
1012 * returns immediately.
1014 * Called with connection lock held.
1016 * @param connection the connection.
1017 * @param flags iteration flags.
1018 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
1021 _dbus_connection_do_iteration_unlocked (DBusConnection *connection,
1023 int timeout_milliseconds)
1025 _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
1027 HAVE_LOCK_CHECK (connection);
1029 if (connection->n_outgoing == 0)
1030 flags &= ~DBUS_ITERATION_DO_WRITING;
1032 if (_dbus_connection_acquire_io_path (connection,
1033 (flags & DBUS_ITERATION_BLOCK) ? timeout_milliseconds : 0))
1035 HAVE_LOCK_CHECK (connection);
1037 _dbus_transport_do_iteration (connection->transport,
1038 flags, timeout_milliseconds);
1039 _dbus_connection_release_io_path (connection);
1042 HAVE_LOCK_CHECK (connection);
1044 _dbus_verbose ("%s end\n", _DBUS_FUNCTION_NAME);
1048 * Creates a new connection for the given transport. A transport
1049 * represents a message stream that uses some concrete mechanism, such
1050 * as UNIX domain sockets. May return #NULL if insufficient
1051 * memory exists to create the connection.
1053 * @param transport the transport.
1054 * @returns the new connection, or #NULL on failure.
1057 _dbus_connection_new_for_transport (DBusTransport *transport)
1059 DBusConnection *connection;
1060 DBusWatchList *watch_list;
1061 DBusTimeoutList *timeout_list;
1062 DBusHashTable *pending_replies;
1064 DBusMutex *io_path_mutex;
1065 DBusMutex *dispatch_mutex;
1066 DBusCondVar *dispatch_cond;
1067 DBusCondVar *io_path_cond;
1068 DBusList *disconnect_link;
1069 DBusMessage *disconnect_message;
1070 DBusCounter *outgoing_counter;
1071 DBusObjectTree *objects;
1075 pending_replies = NULL;
1076 timeout_list = NULL;
1078 io_path_mutex = NULL;
1079 dispatch_mutex = NULL;
1080 dispatch_cond = NULL;
1081 io_path_cond = NULL;
1082 disconnect_link = NULL;
1083 disconnect_message = NULL;
1084 outgoing_counter = NULL;
1087 watch_list = _dbus_watch_list_new ();
1088 if (watch_list == NULL)
1091 timeout_list = _dbus_timeout_list_new ();
1092 if (timeout_list == NULL)
1096 _dbus_hash_table_new (DBUS_HASH_INT,
1098 (DBusFreeFunction)free_pending_call_on_hash_removal);
1099 if (pending_replies == NULL)
1102 connection = dbus_new0 (DBusConnection, 1);
1103 if (connection == NULL)
1106 mutex = _dbus_mutex_new ();
1110 io_path_mutex = _dbus_mutex_new ();
1111 if (io_path_mutex == NULL)
1114 dispatch_mutex = _dbus_mutex_new ();
1115 if (dispatch_mutex == NULL)
1118 dispatch_cond = _dbus_condvar_new ();
1119 if (dispatch_cond == NULL)
1122 io_path_cond = _dbus_condvar_new ();
1123 if (io_path_cond == NULL)
1126 disconnect_message = dbus_message_new_signal (DBUS_PATH_LOCAL,
1127 DBUS_INTERFACE_LOCAL,
1130 if (disconnect_message == NULL)
1133 disconnect_link = _dbus_list_alloc_link (disconnect_message);
1134 if (disconnect_link == NULL)
1137 outgoing_counter = _dbus_counter_new ();
1138 if (outgoing_counter == NULL)
1141 objects = _dbus_object_tree_new (connection);
1142 if (objects == NULL)
1145 if (_dbus_modify_sigpipe)
1146 _dbus_disable_sigpipe ();
1148 connection->refcount.value = 1;
1149 connection->mutex = mutex;
1150 connection->dispatch_cond = dispatch_cond;
1151 connection->dispatch_mutex = dispatch_mutex;
1152 connection->io_path_cond = io_path_cond;
1153 connection->io_path_mutex = io_path_mutex;
1154 connection->transport = transport;
1155 connection->watches = watch_list;
1156 connection->timeouts = timeout_list;
1157 connection->pending_replies = pending_replies;
1158 connection->outgoing_counter = outgoing_counter;
1159 connection->filter_list = NULL;
1160 connection->last_dispatch_status = DBUS_DISPATCH_COMPLETE; /* so we're notified first time there's data */
1161 connection->objects = objects;
1162 connection->exit_on_disconnect = FALSE;
1163 connection->shareable = FALSE;
1164 #ifndef DBUS_DISABLE_CHECKS
1165 connection->generation = _dbus_current_generation;
1168 _dbus_data_slot_list_init (&connection->slot_list);
1170 connection->client_serial = 1;
1172 connection->disconnect_message_link = disconnect_link;
1174 CONNECTION_LOCK (connection);
1176 if (!_dbus_transport_set_connection (transport, connection))
1179 _dbus_transport_ref (transport);
1181 CONNECTION_UNLOCK (connection);
1186 if (disconnect_message != NULL)
1187 dbus_message_unref (disconnect_message);
1189 if (disconnect_link != NULL)
1190 _dbus_list_free_link (disconnect_link);
1192 if (io_path_cond != NULL)
1193 _dbus_condvar_free (io_path_cond);
1195 if (dispatch_cond != NULL)
1196 _dbus_condvar_free (dispatch_cond);
1199 _dbus_mutex_free (mutex);
1201 if (io_path_mutex != NULL)
1202 _dbus_mutex_free (io_path_mutex);
1204 if (dispatch_mutex != NULL)
1205 _dbus_mutex_free (dispatch_mutex);
1207 if (connection != NULL)
1208 dbus_free (connection);
1210 if (pending_replies)
1211 _dbus_hash_table_unref (pending_replies);
1214 _dbus_watch_list_free (watch_list);
1217 _dbus_timeout_list_free (timeout_list);
1219 if (outgoing_counter)
1220 _dbus_counter_unref (outgoing_counter);
1223 _dbus_object_tree_unref (objects);
1229 * Increments the reference count of a DBusConnection.
1230 * Requires that the caller already holds the connection lock.
1232 * @param connection the connection.
1233 * @returns the connection.
1236 _dbus_connection_ref_unlocked (DBusConnection *connection)
1238 _dbus_assert (connection != NULL);
1239 _dbus_assert (connection->generation == _dbus_current_generation);
1241 HAVE_LOCK_CHECK (connection);
1243 #ifdef DBUS_HAVE_ATOMIC_INT
1244 _dbus_atomic_inc (&connection->refcount);
1246 _dbus_assert (connection->refcount.value > 0);
1247 connection->refcount.value += 1;
1254 * Decrements the reference count of a DBusConnection.
1255 * Requires that the caller already holds the connection lock.
1257 * @param connection the connection.
1260 _dbus_connection_unref_unlocked (DBusConnection *connection)
1262 dbus_bool_t last_unref;
1264 HAVE_LOCK_CHECK (connection);
1266 _dbus_assert (connection != NULL);
1268 /* The connection lock is better than the global
1269 * lock in the atomic increment fallback
1272 #ifdef DBUS_HAVE_ATOMIC_INT
1273 last_unref = (_dbus_atomic_dec (&connection->refcount) == 1);
1275 _dbus_assert (connection->refcount.value > 0);
1277 connection->refcount.value -= 1;
1278 last_unref = (connection->refcount.value == 0);
1280 printf ("unref_unlocked() connection %p count = %d\n", connection, connection->refcount.value);
1285 _dbus_connection_last_unref (connection);
1288 static dbus_uint32_t
1289 _dbus_connection_get_next_client_serial (DBusConnection *connection)
1293 serial = connection->client_serial++;
1295 if (connection->client_serial < 0)
1296 connection->client_serial = 1;
1302 * A callback for use with dbus_watch_new() to create a DBusWatch.
1304 * @todo This is basically a hack - we could delete _dbus_transport_handle_watch()
1305 * and the virtual handle_watch in DBusTransport if we got rid of it.
1306 * The reason this is some work is threading, see the _dbus_connection_handle_watch()
1309 * @param watch the watch.
1310 * @param condition the current condition of the file descriptors being watched.
1311 * @param data must be a pointer to a #DBusConnection
1312 * @returns #FALSE if the IO condition may not have been fully handled due to lack of memory
1315 _dbus_connection_handle_watch (DBusWatch *watch,
1316 unsigned int condition,
1319 DBusConnection *connection;
1321 DBusDispatchStatus status;
1325 _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
1327 CONNECTION_LOCK (connection);
1328 _dbus_connection_acquire_io_path (connection, -1);
1329 HAVE_LOCK_CHECK (connection);
1330 retval = _dbus_transport_handle_watch (connection->transport,
1333 _dbus_connection_release_io_path (connection);
1335 HAVE_LOCK_CHECK (connection);
1337 _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
1339 status = _dbus_connection_get_dispatch_status_unlocked (connection);
1341 /* this calls out to user code */
1342 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1344 _dbus_verbose ("%s end\n", _DBUS_FUNCTION_NAME);
1349 _DBUS_DEFINE_GLOBAL_LOCK (shared_connections);
1350 static DBusHashTable *shared_connections = NULL;
1353 shared_connections_shutdown (void *data)
1355 _DBUS_LOCK (shared_connections);
1357 _dbus_assert (_dbus_hash_table_get_n_entries (shared_connections) == 0);
1358 _dbus_hash_table_unref (shared_connections);
1359 shared_connections = NULL;
1361 _DBUS_UNLOCK (shared_connections);
1365 connection_lookup_shared (DBusAddressEntry *entry,
1366 DBusConnection **result)
1368 _dbus_verbose ("checking for existing connection\n");
1372 _DBUS_LOCK (shared_connections);
1374 if (shared_connections == NULL)
1376 _dbus_verbose ("creating shared_connections hash table\n");
1378 shared_connections = _dbus_hash_table_new (DBUS_HASH_STRING,
1381 if (shared_connections == NULL)
1383 _DBUS_UNLOCK (shared_connections);
1387 if (!_dbus_register_shutdown_func (shared_connections_shutdown, NULL))
1389 _dbus_hash_table_unref (shared_connections);
1390 shared_connections = NULL;
1391 _DBUS_UNLOCK (shared_connections);
1395 _dbus_verbose (" successfully created shared_connections\n");
1397 _DBUS_UNLOCK (shared_connections);
1398 return TRUE; /* no point looking up in the hash we just made */
1404 guid = dbus_address_entry_get_value (entry, "guid");
1408 *result = _dbus_hash_table_lookup_string (shared_connections,
1413 /* The DBusConnection can't have been disconnected
1414 * between the lookup and this code, because the
1415 * disconnection will take the shared_connections lock to
1416 * remove the connection. It can't have been finalized
1417 * since you have to disconnect prior to finalize.
1419 * Thus it's safe to ref the connection.
1421 dbus_connection_ref (*result);
1423 _dbus_verbose ("looked up existing connection to server guid %s\n",
1428 _DBUS_UNLOCK (shared_connections);
1434 connection_record_shared_unlocked (DBusConnection *connection,
1438 char *guid_in_connection;
1440 /* A separate copy of the key is required in the hash table, because
1441 * we don't have a lock on the connection when we are doing a hash
1445 _dbus_assert (connection->server_guid == NULL);
1446 _dbus_assert (connection->shareable);
1448 guid_key = _dbus_strdup (guid);
1449 if (guid_key == NULL)
1452 guid_in_connection = _dbus_strdup (guid);
1453 if (guid_in_connection == NULL)
1455 dbus_free (guid_key);
1459 _DBUS_LOCK (shared_connections);
1460 _dbus_assert (shared_connections != NULL);
1462 if (!_dbus_hash_table_insert_string (shared_connections,
1463 guid_key, connection))
1465 dbus_free (guid_key);
1466 dbus_free (guid_in_connection);
1467 _DBUS_UNLOCK (shared_connections);
1471 connection->server_guid = guid_in_connection;
1473 _dbus_verbose ("stored connection to %s to be shared\n",
1474 connection->server_guid);
1476 _DBUS_UNLOCK (shared_connections);
1478 _dbus_assert (connection->server_guid != NULL);
1484 connection_forget_shared_unlocked (DBusConnection *connection)
1486 HAVE_LOCK_CHECK (connection);
1488 if (connection->server_guid == NULL)
1491 _dbus_verbose ("dropping connection to %s out of the shared table\n",
1492 connection->server_guid);
1494 _DBUS_LOCK (shared_connections);
1496 if (!_dbus_hash_table_remove_string (shared_connections,
1497 connection->server_guid))
1498 _dbus_assert_not_reached ("connection was not in the shared table");
1500 dbus_free (connection->server_guid);
1501 connection->server_guid = NULL;
1503 _DBUS_UNLOCK (shared_connections);
1506 static DBusConnection*
1507 connection_try_from_address_entry (DBusAddressEntry *entry,
1510 DBusTransport *transport;
1511 DBusConnection *connection;
1513 transport = _dbus_transport_open (entry, error);
1515 if (transport == NULL)
1517 _DBUS_ASSERT_ERROR_IS_SET (error);
1521 connection = _dbus_connection_new_for_transport (transport);
1523 _dbus_transport_unref (transport);
1525 if (connection == NULL)
1527 _DBUS_SET_OOM (error);
1531 #ifndef DBUS_DISABLE_CHECKS
1532 _dbus_assert (!connection->have_connection_lock);
1538 * If the shared parameter is true, then any existing connection will
1539 * be used (and if a new connection is created, it will be available
1540 * for use by others). If the shared parameter is false, a new
1541 * connection will always be created, and the new connection will
1542 * never be returned to other callers.
1544 * @param address the address
1545 * @param shared whether the connection is shared or private
1546 * @param error error return
1547 * @returns the connection or #NULL on error
1549 static DBusConnection*
1550 _dbus_connection_open_internal (const char *address,
1554 DBusConnection *connection;
1555 DBusAddressEntry **entries;
1556 DBusError tmp_error;
1557 DBusError first_error;
1560 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1562 _dbus_verbose ("opening %s connection to: %s\n",
1563 shared ? "shared" : "private", address);
1565 if (!dbus_parse_address (address, &entries, &len, error))
1568 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1572 dbus_error_init (&tmp_error);
1573 dbus_error_init (&first_error);
1574 for (i = 0; i < len; i++)
1578 if (!connection_lookup_shared (entries[i], &connection))
1579 _DBUS_SET_OOM (&tmp_error);
1582 if (connection == NULL)
1584 connection = connection_try_from_address_entry (entries[i],
1587 if (connection != NULL && shared)
1591 connection->shareable = TRUE;
1593 guid = dbus_address_entry_get_value (entries[i], "guid");
1595 /* we don't have a connection lock but we know nobody
1596 * else has a handle to the connection
1600 !connection_record_shared_unlocked (connection, guid))
1602 _DBUS_SET_OOM (&tmp_error);
1603 dbus_connection_close (connection);
1604 dbus_connection_unref (connection);
1608 /* but as of now the connection is possibly shared
1609 * since another thread could have pulled it from the table
1617 _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
1620 dbus_move_error (&tmp_error, &first_error);
1622 dbus_error_free (&tmp_error);
1625 /* NOTE we don't have a lock on a possibly-shared connection object */
1627 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1628 _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
1630 if (connection == NULL)
1632 _DBUS_ASSERT_ERROR_IS_SET (&first_error);
1633 dbus_move_error (&first_error, error);
1637 dbus_error_free (&first_error);
1640 dbus_address_entries_free (entries);
1647 * @addtogroup DBusConnection
1653 * Gets a connection to a remote address. If a connection to the given
1654 * address already exists, returns the existing connection with its
1655 * reference count incremented. Otherwise, returns a new connection
1656 * and saves the new connection for possible re-use if a future call
1657 * to dbus_connection_open() asks to connect to the same server.
1659 * Use dbus_connection_open_private() to get a dedicated connection
1660 * not shared with other callers of dbus_connection_open().
1662 * If the open fails, the function returns #NULL, and provides a
1663 * reason for the failure in the error parameter. Pass #NULL for the
1664 * error parameter if you aren't interested in the reason for
1667 * @param address the address.
1668 * @param error address where an error can be returned.
1669 * @returns new connection, or #NULL on failure.
1672 dbus_connection_open (const char *address,
1675 DBusConnection *connection;
1677 _dbus_return_val_if_fail (address != NULL, NULL);
1678 _dbus_return_val_if_error_is_set (error, NULL);
1680 connection = _dbus_connection_open_internal (address,
1688 * Opens a new, dedicated connection to a remote address. Unlike
1689 * dbus_connection_open(), always creates a new connection.
1690 * This connection will not be saved or recycled by libdbus.
1692 * If the open fails, the function returns #NULL, and provides a
1693 * reason for the failure in the error parameter. Pass #NULL for the
1694 * error parameter if you aren't interested in the reason for
1697 * @param address the address.
1698 * @param error address where an error can be returned.
1699 * @returns new connection, or #NULL on failure.
1702 dbus_connection_open_private (const char *address,
1705 DBusConnection *connection;
1707 _dbus_return_val_if_fail (address != NULL, NULL);
1708 _dbus_return_val_if_error_is_set (error, NULL);
1710 connection = _dbus_connection_open_internal (address,
1718 * Increments the reference count of a DBusConnection.
1720 * @param connection the connection.
1721 * @returns the connection.
1724 dbus_connection_ref (DBusConnection *connection)
1726 _dbus_return_val_if_fail (connection != NULL, NULL);
1727 _dbus_return_val_if_fail (connection->generation == _dbus_current_generation, NULL);
1729 /* The connection lock is better than the global
1730 * lock in the atomic increment fallback
1733 #ifdef DBUS_HAVE_ATOMIC_INT
1734 _dbus_atomic_inc (&connection->refcount);
1736 CONNECTION_LOCK (connection);
1737 _dbus_assert (connection->refcount.value > 0);
1739 connection->refcount.value += 1;
1740 CONNECTION_UNLOCK (connection);
1747 free_outgoing_message (void *element,
1750 DBusMessage *message = element;
1751 DBusConnection *connection = data;
1753 _dbus_message_remove_size_counter (message,
1754 connection->outgoing_counter,
1756 dbus_message_unref (message);
1759 /* This is run without the mutex held, but after the last reference
1760 * to the connection has been dropped we should have no thread-related
1764 _dbus_connection_last_unref (DBusConnection *connection)
1768 _dbus_verbose ("Finalizing connection %p\n", connection);
1770 _dbus_assert (connection->refcount.value == 0);
1772 /* You have to disconnect the connection before unref:ing it. Otherwise
1773 * you won't get the disconnected message.
1775 _dbus_assert (!_dbus_transport_get_is_connected (connection->transport));
1776 _dbus_assert (connection->server_guid == NULL);
1778 /* ---- We're going to call various application callbacks here, hope it doesn't break anything... */
1779 _dbus_object_tree_free_all_unlocked (connection->objects);
1781 dbus_connection_set_dispatch_status_function (connection, NULL, NULL, NULL);
1782 dbus_connection_set_wakeup_main_function (connection, NULL, NULL, NULL);
1783 dbus_connection_set_unix_user_function (connection, NULL, NULL, NULL);
1785 _dbus_watch_list_free (connection->watches);
1786 connection->watches = NULL;
1788 _dbus_timeout_list_free (connection->timeouts);
1789 connection->timeouts = NULL;
1791 _dbus_data_slot_list_free (&connection->slot_list);
1793 link = _dbus_list_get_first_link (&connection->filter_list);
1794 while (link != NULL)
1796 DBusMessageFilter *filter = link->data;
1797 DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
1799 filter->function = NULL;
1800 _dbus_message_filter_unref (filter); /* calls app callback */
1805 _dbus_list_clear (&connection->filter_list);
1807 /* ---- Done with stuff that invokes application callbacks */
1809 _dbus_object_tree_unref (connection->objects);
1811 _dbus_hash_table_unref (connection->pending_replies);
1812 connection->pending_replies = NULL;
1814 _dbus_list_clear (&connection->filter_list);
1816 _dbus_list_foreach (&connection->outgoing_messages,
1817 free_outgoing_message,
1819 _dbus_list_clear (&connection->outgoing_messages);
1821 _dbus_list_foreach (&connection->incoming_messages,
1822 (DBusForeachFunction) dbus_message_unref,
1824 _dbus_list_clear (&connection->incoming_messages);
1826 _dbus_counter_unref (connection->outgoing_counter);
1828 _dbus_transport_unref (connection->transport);
1830 if (connection->disconnect_message_link)
1832 DBusMessage *message = connection->disconnect_message_link->data;
1833 dbus_message_unref (message);
1834 _dbus_list_free_link (connection->disconnect_message_link);
1837 _dbus_list_clear (&connection->link_cache);
1839 _dbus_condvar_free (connection->dispatch_cond);
1840 _dbus_condvar_free (connection->io_path_cond);
1842 _dbus_mutex_free (connection->io_path_mutex);
1843 _dbus_mutex_free (connection->dispatch_mutex);
1845 _dbus_mutex_free (connection->mutex);
1847 dbus_free (connection);
1851 * Decrements the reference count of a DBusConnection, and finalizes
1852 * it if the count reaches zero. It is a bug to drop the last reference
1853 * to a connection that has not been disconnected.
1855 * @todo in practice it can be quite tricky to never unref a connection
1856 * that's still connected; maybe there's some way we could avoid
1859 * @param connection the connection.
1862 dbus_connection_unref (DBusConnection *connection)
1864 dbus_bool_t last_unref;
1866 _dbus_return_if_fail (connection != NULL);
1867 _dbus_return_if_fail (connection->generation == _dbus_current_generation);
1869 /* The connection lock is better than the global
1870 * lock in the atomic increment fallback
1873 #ifdef DBUS_HAVE_ATOMIC_INT
1874 last_unref = (_dbus_atomic_dec (&connection->refcount) == 1);
1876 CONNECTION_LOCK (connection);
1878 _dbus_assert (connection->refcount.value > 0);
1880 connection->refcount.value -= 1;
1881 last_unref = (connection->refcount.value == 0);
1884 printf ("unref() connection %p count = %d\n", connection, connection->refcount.value);
1887 CONNECTION_UNLOCK (connection);
1891 _dbus_connection_last_unref (connection);
1895 * Closes the connection, so no further data can be sent or received.
1896 * Any further attempts to send data will result in errors. This
1897 * function does not affect the connection's reference count. It's
1898 * safe to disconnect a connection more than once; all calls after the
1899 * first do nothing. It's impossible to "reopen" a connection, a
1900 * new connection must be created. This function may result in a call
1901 * to the DBusDispatchStatusFunction set with
1902 * dbus_connection_set_dispatch_status_function(), as the disconnect
1903 * message it generates needs to be dispatched.
1905 * @param connection the connection.
1908 dbus_connection_close (DBusConnection *connection)
1910 DBusDispatchStatus status;
1912 _dbus_return_if_fail (connection != NULL);
1913 _dbus_return_if_fail (connection->generation == _dbus_current_generation);
1915 _dbus_verbose ("Disconnecting %p\n", connection);
1917 CONNECTION_LOCK (connection);
1919 _dbus_transport_disconnect (connection->transport);
1921 _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
1922 status = _dbus_connection_get_dispatch_status_unlocked (connection);
1924 /* this calls out to user code */
1925 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1929 _dbus_connection_get_is_connected_unlocked (DBusConnection *connection)
1931 HAVE_LOCK_CHECK (connection);
1932 return _dbus_transport_get_is_connected (connection->transport);
1936 * Gets whether the connection is currently connected. All
1937 * connections are connected when they are opened. A connection may
1938 * become disconnected when the remote application closes its end, or
1939 * exits; a connection may also be disconnected with
1940 * dbus_connection_close().
1942 * @param connection the connection.
1943 * @returns #TRUE if the connection is still alive.
1946 dbus_connection_get_is_connected (DBusConnection *connection)
1950 _dbus_return_val_if_fail (connection != NULL, FALSE);
1952 CONNECTION_LOCK (connection);
1953 res = _dbus_connection_get_is_connected_unlocked (connection);
1954 CONNECTION_UNLOCK (connection);
1960 * Gets whether the connection was authenticated. (Note that
1961 * if the connection was authenticated then disconnected,
1962 * this function still returns #TRUE)
1964 * @param connection the connection
1965 * @returns #TRUE if the connection was ever authenticated
1968 dbus_connection_get_is_authenticated (DBusConnection *connection)
1972 _dbus_return_val_if_fail (connection != NULL, FALSE);
1974 CONNECTION_LOCK (connection);
1975 res = _dbus_transport_get_is_authenticated (connection->transport);
1976 CONNECTION_UNLOCK (connection);
1982 * Set whether _exit() should be called when the connection receives a
1983 * disconnect signal. The call to _exit() comes after any handlers for
1984 * the disconnect signal run; handlers can cancel the exit by calling
1987 * By default, exit_on_disconnect is #FALSE; but for message bus
1988 * connections returned from dbus_bus_get() it will be toggled on
1991 * @param connection the connection
1992 * @param exit_on_disconnect #TRUE if _exit() should be called after a disconnect signal
1995 dbus_connection_set_exit_on_disconnect (DBusConnection *connection,
1996 dbus_bool_t exit_on_disconnect)
1998 _dbus_return_if_fail (connection != NULL);
2000 CONNECTION_LOCK (connection);
2001 connection->exit_on_disconnect = exit_on_disconnect != FALSE;
2002 CONNECTION_UNLOCK (connection);
2005 static DBusPreallocatedSend*
2006 _dbus_connection_preallocate_send_unlocked (DBusConnection *connection)
2008 DBusPreallocatedSend *preallocated;
2010 HAVE_LOCK_CHECK (connection);
2012 _dbus_assert (connection != NULL);
2014 preallocated = dbus_new (DBusPreallocatedSend, 1);
2015 if (preallocated == NULL)
2018 if (connection->link_cache != NULL)
2020 preallocated->queue_link =
2021 _dbus_list_pop_first_link (&connection->link_cache);
2022 preallocated->queue_link->data = NULL;
2026 preallocated->queue_link = _dbus_list_alloc_link (NULL);
2027 if (preallocated->queue_link == NULL)
2031 if (connection->link_cache != NULL)
2033 preallocated->counter_link =
2034 _dbus_list_pop_first_link (&connection->link_cache);
2035 preallocated->counter_link->data = connection->outgoing_counter;
2039 preallocated->counter_link = _dbus_list_alloc_link (connection->outgoing_counter);
2040 if (preallocated->counter_link == NULL)
2044 _dbus_counter_ref (preallocated->counter_link->data);
2046 preallocated->connection = connection;
2048 return preallocated;
2051 _dbus_list_free_link (preallocated->queue_link);
2053 dbus_free (preallocated);
2059 * Preallocates resources needed to send a message, allowing the message
2060 * to be sent without the possibility of memory allocation failure.
2061 * Allows apps to create a future guarantee that they can send
2062 * a message regardless of memory shortages.
2064 * @param connection the connection we're preallocating for.
2065 * @returns the preallocated resources, or #NULL
2067 DBusPreallocatedSend*
2068 dbus_connection_preallocate_send (DBusConnection *connection)
2070 DBusPreallocatedSend *preallocated;
2072 _dbus_return_val_if_fail (connection != NULL, NULL);
2074 CONNECTION_LOCK (connection);
2077 _dbus_connection_preallocate_send_unlocked (connection);
2079 CONNECTION_UNLOCK (connection);
2081 return preallocated;
2085 * Frees preallocated message-sending resources from
2086 * dbus_connection_preallocate_send(). Should only
2087 * be called if the preallocated resources are not used
2088 * to send a message.
2090 * @param connection the connection
2091 * @param preallocated the resources
2094 dbus_connection_free_preallocated_send (DBusConnection *connection,
2095 DBusPreallocatedSend *preallocated)
2097 _dbus_return_if_fail (connection != NULL);
2098 _dbus_return_if_fail (preallocated != NULL);
2099 _dbus_return_if_fail (connection == preallocated->connection);
2101 _dbus_list_free_link (preallocated->queue_link);
2102 _dbus_counter_unref (preallocated->counter_link->data);
2103 _dbus_list_free_link (preallocated->counter_link);
2104 dbus_free (preallocated);
2107 /* Called with lock held, does not update dispatch status */
2109 _dbus_connection_send_preallocated_unlocked_no_update (DBusConnection *connection,
2110 DBusPreallocatedSend *preallocated,
2111 DBusMessage *message,
2112 dbus_uint32_t *client_serial)
2114 dbus_uint32_t serial;
2117 preallocated->queue_link->data = message;
2118 _dbus_list_prepend_link (&connection->outgoing_messages,
2119 preallocated->queue_link);
2121 _dbus_message_add_size_counter_link (message,
2122 preallocated->counter_link);
2124 dbus_free (preallocated);
2125 preallocated = NULL;
2127 dbus_message_ref (message);
2129 connection->n_outgoing += 1;
2131 sig = dbus_message_get_signature (message);
2133 _dbus_verbose ("Message %p (%d %s %s %s '%s') for %s added to outgoing queue %p, %d pending to send\n",
2135 dbus_message_get_type (message),
2136 dbus_message_get_path (message) ?
2137 dbus_message_get_path (message) :
2139 dbus_message_get_interface (message) ?
2140 dbus_message_get_interface (message) :
2142 dbus_message_get_member (message) ?
2143 dbus_message_get_member (message) :
2146 dbus_message_get_destination (message) ?
2147 dbus_message_get_destination (message) :
2150 connection->n_outgoing);
2152 if (dbus_message_get_serial (message) == 0)
2154 serial = _dbus_connection_get_next_client_serial (connection);
2155 _dbus_message_set_serial (message, serial);
2157 *client_serial = serial;
2162 *client_serial = dbus_message_get_serial (message);
2165 _dbus_verbose ("Message %p serial is %u\n",
2166 message, dbus_message_get_serial (message));
2168 _dbus_message_lock (message);
2170 /* Now we need to run an iteration to hopefully just write the messages
2171 * out immediately, and otherwise get them queued up
2173 _dbus_connection_do_iteration_unlocked (connection,
2174 DBUS_ITERATION_DO_WRITING,
2177 /* If stuff is still queued up, be sure we wake up the main loop */
2178 if (connection->n_outgoing > 0)
2179 _dbus_connection_wakeup_mainloop (connection);
2183 _dbus_connection_send_preallocated_and_unlock (DBusConnection *connection,
2184 DBusPreallocatedSend *preallocated,
2185 DBusMessage *message,
2186 dbus_uint32_t *client_serial)
2188 DBusDispatchStatus status;
2190 HAVE_LOCK_CHECK (connection);
2192 _dbus_connection_send_preallocated_unlocked_no_update (connection,
2194 message, client_serial);
2196 _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
2197 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2199 /* this calls out to user code */
2200 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2204 * Sends a message using preallocated resources. This function cannot fail.
2205 * It works identically to dbus_connection_send() in other respects.
2206 * Preallocated resources comes from dbus_connection_preallocate_send().
2207 * This function "consumes" the preallocated resources, they need not
2208 * be freed separately.
2210 * @param connection the connection
2211 * @param preallocated the preallocated resources
2212 * @param message the message to send
2213 * @param client_serial return location for client serial assigned to the message
2216 dbus_connection_send_preallocated (DBusConnection *connection,
2217 DBusPreallocatedSend *preallocated,
2218 DBusMessage *message,
2219 dbus_uint32_t *client_serial)
2221 _dbus_return_if_fail (connection != NULL);
2222 _dbus_return_if_fail (preallocated != NULL);
2223 _dbus_return_if_fail (message != NULL);
2224 _dbus_return_if_fail (preallocated->connection == connection);
2225 _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_METHOD_CALL ||
2226 dbus_message_get_member (message) != NULL);
2227 _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL ||
2228 (dbus_message_get_interface (message) != NULL &&
2229 dbus_message_get_member (message) != NULL));
2231 CONNECTION_LOCK (connection);
2232 _dbus_connection_send_preallocated_and_unlock (connection,
2234 message, client_serial);
2238 _dbus_connection_send_unlocked_no_update (DBusConnection *connection,
2239 DBusMessage *message,
2240 dbus_uint32_t *client_serial)
2242 DBusPreallocatedSend *preallocated;
2244 _dbus_assert (connection != NULL);
2245 _dbus_assert (message != NULL);
2247 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
2248 if (preallocated == NULL)
2251 _dbus_connection_send_preallocated_unlocked_no_update (connection,
2259 _dbus_connection_send_and_unlock (DBusConnection *connection,
2260 DBusMessage *message,
2261 dbus_uint32_t *client_serial)
2263 DBusPreallocatedSend *preallocated;
2265 _dbus_assert (connection != NULL);
2266 _dbus_assert (message != NULL);
2268 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
2269 if (preallocated == NULL)
2271 CONNECTION_UNLOCK (connection);
2275 _dbus_connection_send_preallocated_and_unlock (connection,
2283 * Adds a message to the outgoing message queue. Does not block to
2284 * write the message to the network; that happens asynchronously. To
2285 * force the message to be written, call dbus_connection_flush().
2286 * Because this only queues the message, the only reason it can
2287 * fail is lack of memory. Even if the connection is disconnected,
2288 * no error will be returned.
2290 * If the function fails due to lack of memory, it returns #FALSE.
2291 * The function will never fail for other reasons; even if the
2292 * connection is disconnected, you can queue an outgoing message,
2293 * though obviously it won't be sent.
2295 * @param connection the connection.
2296 * @param message the message to write.
2297 * @param client_serial return location for client serial.
2298 * @returns #TRUE on success.
2301 dbus_connection_send (DBusConnection *connection,
2302 DBusMessage *message,
2303 dbus_uint32_t *client_serial)
2305 _dbus_return_val_if_fail (connection != NULL, FALSE);
2306 _dbus_return_val_if_fail (message != NULL, FALSE);
2308 CONNECTION_LOCK (connection);
2310 return _dbus_connection_send_and_unlock (connection,
2316 reply_handler_timeout (void *data)
2318 DBusConnection *connection;
2319 DBusDispatchStatus status;
2320 DBusPendingCall *pending = data;
2322 connection = _dbus_pending_call_get_connection_and_lock (pending);
2324 _dbus_pending_call_queue_timeout_error_unlocked (pending,
2326 _dbus_connection_remove_timeout_unlocked (connection,
2327 _dbus_pending_call_get_timeout_unlocked (pending));
2328 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
2330 _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
2331 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2333 /* Unlocks, and calls out to user code */
2334 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2340 * Queues a message to send, as with dbus_connection_send_message(),
2341 * but also returns a #DBusPendingCall used to receive a reply to the
2342 * message. If no reply is received in the given timeout_milliseconds,
2343 * this function expires the pending reply and generates a synthetic
2344 * error reply (generated in-process, not by the remote application)
2345 * indicating that a timeout occurred.
2347 * A #DBusPendingCall will see a reply message after any filters, but
2348 * before any object instances or other handlers. A #DBusPendingCall
2349 * will always see exactly one reply message, unless it's cancelled
2350 * with dbus_pending_call_cancel().
2352 * If a filter filters out the reply before the handler sees it, the
2353 * reply is immediately timed out and a timeout error reply is
2354 * generated. If a filter removes the timeout error reply then the
2355 * #DBusPendingCall will get confused. Filtering the timeout error
2356 * is thus considered a bug and will print a warning.
2358 * If #NULL is passed for the pending_return, the #DBusPendingCall
2359 * will still be generated internally, and used to track
2360 * the message reply timeout. This means a timeout error will
2361 * occur if no reply arrives, unlike with dbus_connection_send().
2363 * If -1 is passed for the timeout, a sane default timeout is used. -1
2364 * is typically the best value for the timeout for this reason, unless
2365 * you want a very short or very long timeout. There is no way to
2366 * avoid a timeout entirely, other than passing INT_MAX for the
2367 * timeout to postpone it indefinitely.
2369 * @param connection the connection
2370 * @param message the message to send
2371 * @param pending_return return location for a #DBusPendingCall object, or #NULLif connection is disconnected
2372 * @param timeout_milliseconds timeout in milliseconds or -1 for default
2373 * @returns #FALSE if no memory, #TRUE otherwise.
2377 dbus_connection_send_with_reply (DBusConnection *connection,
2378 DBusMessage *message,
2379 DBusPendingCall **pending_return,
2380 int timeout_milliseconds)
2382 DBusPendingCall *pending;
2383 dbus_int32_t serial = -1;
2384 DBusDispatchStatus status;
2386 _dbus_return_val_if_fail (connection != NULL, FALSE);
2387 _dbus_return_val_if_fail (message != NULL, FALSE);
2388 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
2391 *pending_return = NULL;
2393 CONNECTION_LOCK (connection);
2395 if (!_dbus_connection_get_is_connected_unlocked (connection))
2397 CONNECTION_UNLOCK (connection);
2399 *pending_return = NULL;
2404 pending = _dbus_pending_call_new_unlocked (connection,
2405 timeout_milliseconds,
2406 reply_handler_timeout);
2408 if (pending == NULL)
2410 CONNECTION_UNLOCK (connection);
2414 /* Assign a serial to the message */
2415 serial = dbus_message_get_serial (message);
2418 serial = _dbus_connection_get_next_client_serial (connection);
2419 _dbus_message_set_serial (message, serial);
2422 if (!_dbus_pending_call_set_timeout_error_unlocked (pending, message, serial))
2425 /* Insert the serial in the pending replies hash;
2426 * hash takes a refcount on DBusPendingCall.
2427 * Also, add the timeout.
2429 if (!_dbus_connection_attach_pending_call_unlocked (connection,
2433 if (!_dbus_connection_send_unlocked_no_update (connection, message, NULL))
2435 _dbus_connection_detach_pending_call_and_unlock (connection,
2437 goto error_unlocked;
2441 *pending_return = pending; /* hand off refcount */
2444 _dbus_connection_detach_pending_call_unlocked (connection, pending);
2445 /* we still have a ref to the pending call in this case, we unref
2446 * after unlocking, below
2450 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2452 /* this calls out to user code */
2453 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2455 if (pending_return == NULL)
2456 dbus_pending_call_unref (pending);
2461 CONNECTION_UNLOCK (connection);
2463 dbus_pending_call_unref (pending);
2467 /* This is slightly strange since we can pop a message here without
2468 * the dispatch lock.
2471 check_for_reply_unlocked (DBusConnection *connection,
2472 dbus_uint32_t client_serial)
2476 HAVE_LOCK_CHECK (connection);
2478 link = _dbus_list_get_first_link (&connection->incoming_messages);
2480 while (link != NULL)
2482 DBusMessage *reply = link->data;
2484 if (dbus_message_get_reply_serial (reply) == client_serial)
2486 _dbus_list_remove_link (&connection->incoming_messages, link);
2487 connection->n_incoming -= 1;
2490 link = _dbus_list_get_next_link (&connection->incoming_messages, link);
2497 connection_timeout_and_complete_all_pending_calls_unlocked (DBusConnection *connection)
2499 /* We can't iterate over the hash in the normal way since we'll be
2500 * dropping the lock for each item. So we restart the
2501 * iter each time as we drain the hash table.
2504 while (_dbus_hash_table_get_n_entries (connection->pending_replies) > 0)
2506 DBusPendingCall *pending;
2509 _dbus_hash_iter_init (connection->pending_replies, &iter);
2510 _dbus_hash_iter_next (&iter);
2512 pending = (DBusPendingCall *) _dbus_hash_iter_get_value (&iter);
2513 _dbus_pending_call_ref_unlocked (pending);
2515 _dbus_pending_call_queue_timeout_error_unlocked (pending,
2517 _dbus_connection_remove_timeout_unlocked (connection,
2518 _dbus_pending_call_get_timeout_unlocked (pending));
2519 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
2520 _dbus_hash_iter_remove_entry (&iter);
2522 _dbus_pending_call_unref_and_unlock (pending);
2523 CONNECTION_LOCK (connection);
2525 HAVE_LOCK_CHECK (connection);
2529 complete_pending_call_and_unlock (DBusConnection *connection,
2530 DBusPendingCall *pending,
2531 DBusMessage *message)
2533 _dbus_pending_call_set_reply_unlocked (pending, message);
2534 _dbus_pending_call_ref_unlocked (pending); /* in case there's no app with a ref held */
2535 _dbus_connection_detach_pending_call_and_unlock (connection, pending);
2537 /* Must be called unlocked since it invokes app callback */
2538 _dbus_pending_call_complete (pending);
2539 dbus_pending_call_unref (pending);
2543 check_for_reply_and_update_dispatch_unlocked (DBusConnection *connection,
2544 DBusPendingCall *pending)
2547 DBusDispatchStatus status;
2549 reply = check_for_reply_unlocked (connection,
2550 _dbus_pending_call_get_reply_serial_unlocked (pending));
2553 _dbus_verbose ("%s checked for reply\n", _DBUS_FUNCTION_NAME);
2555 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): got reply\n");
2557 complete_pending_call_and_unlock (connection, pending, reply);
2558 dbus_message_unref (reply);
2560 CONNECTION_LOCK (connection);
2561 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2562 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2563 dbus_pending_call_unref (pending);
2572 * When a function that blocks has been called with a timeout, and we
2573 * run out of memory, the time to wait for memory is based on the
2574 * timeout. If the caller was willing to block a long time we wait a
2575 * relatively long time for memory, if they were only willing to block
2576 * briefly then we retry for memory at a rapid rate.
2578 * @timeout_milliseconds the timeout requested for blocking
2581 _dbus_memory_pause_based_on_timeout (int timeout_milliseconds)
2583 if (timeout_milliseconds == -1)
2584 _dbus_sleep_milliseconds (1000);
2585 else if (timeout_milliseconds < 100)
2586 ; /* just busy loop */
2587 else if (timeout_milliseconds <= 1000)
2588 _dbus_sleep_milliseconds (timeout_milliseconds / 3);
2590 _dbus_sleep_milliseconds (1000);
2594 * Blocks until a pending call times out or gets a reply.
2596 * Does not re-enter the main loop or run filter/path-registered
2597 * callbacks. The reply to the message will not be seen by
2600 * Returns immediately if pending call already got a reply.
2602 * @todo could use performance improvements (it keeps scanning
2603 * the whole message queue for example)
2605 * @param pending the pending call we block for a reply on
2608 _dbus_connection_block_pending_call (DBusPendingCall *pending)
2610 long start_tv_sec, start_tv_usec;
2611 long end_tv_sec, end_tv_usec;
2612 long tv_sec, tv_usec;
2613 DBusDispatchStatus status;
2614 DBusConnection *connection;
2615 dbus_uint32_t client_serial;
2616 int timeout_milliseconds;
2618 _dbus_assert (pending != NULL);
2620 if (dbus_pending_call_get_completed (pending))
2623 dbus_pending_call_ref (pending); /* necessary because the call could be canceled */
2625 connection = _dbus_pending_call_get_connection_and_lock (pending);
2627 /* Flush message queue - note, can affect dispatch status */
2628 _dbus_connection_flush_unlocked (connection);
2630 client_serial = _dbus_pending_call_get_reply_serial_unlocked (pending);
2632 /* note that timeout_milliseconds is limited to a smallish value
2633 * in _dbus_pending_call_new() so overflows aren't possible
2636 timeout_milliseconds = dbus_timeout_get_interval (_dbus_pending_call_get_timeout_unlocked (pending));
2638 _dbus_get_current_time (&start_tv_sec, &start_tv_usec);
2639 end_tv_sec = start_tv_sec + timeout_milliseconds / 1000;
2640 end_tv_usec = start_tv_usec + (timeout_milliseconds % 1000) * 1000;
2641 end_tv_sec += end_tv_usec / _DBUS_USEC_PER_SECOND;
2642 end_tv_usec = end_tv_usec % _DBUS_USEC_PER_SECOND;
2644 _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",
2645 timeout_milliseconds,
2647 start_tv_sec, start_tv_usec,
2648 end_tv_sec, end_tv_usec);
2650 /* check to see if we already got the data off the socket */
2651 /* from another blocked pending call */
2652 if (check_for_reply_and_update_dispatch_unlocked (connection, pending))
2655 /* Now we wait... */
2656 /* always block at least once as we know we don't have the reply yet */
2657 _dbus_connection_do_iteration_unlocked (connection,
2658 DBUS_ITERATION_DO_READING |
2659 DBUS_ITERATION_BLOCK,
2660 timeout_milliseconds);
2664 _dbus_verbose ("%s top of recheck\n", _DBUS_FUNCTION_NAME);
2666 HAVE_LOCK_CHECK (connection);
2668 /* queue messages and get status */
2670 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2672 /* the get_completed() is in case a dispatch() while we were blocking
2673 * got the reply instead of us.
2675 if (_dbus_pending_call_get_completed_unlocked (pending))
2677 _dbus_verbose ("Pending call completed by dispatch in %s\n", _DBUS_FUNCTION_NAME);
2678 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2679 dbus_pending_call_unref (pending);
2683 if (status == DBUS_DISPATCH_DATA_REMAINS) {
2684 if (check_for_reply_and_update_dispatch_unlocked (connection, pending))
2688 _dbus_get_current_time (&tv_sec, &tv_usec);
2690 if (!_dbus_connection_get_is_connected_unlocked (connection))
2692 /* FIXME send a "DBUS_ERROR_DISCONNECTED" instead, just to help
2693 * programmers understand what went wrong since the timeout is
2697 complete_pending_call_and_unlock (connection, pending, NULL);
2698 dbus_pending_call_unref (pending);
2701 else if (tv_sec < start_tv_sec)
2702 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): clock set backward\n");
2703 else if (connection->disconnect_message_link == NULL)
2704 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): disconnected\n");
2705 else if (tv_sec < end_tv_sec ||
2706 (tv_sec == end_tv_sec && tv_usec < end_tv_usec))
2708 timeout_milliseconds = (end_tv_sec - tv_sec) * 1000 +
2709 (end_tv_usec - tv_usec) / 1000;
2710 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): %d milliseconds remain\n", timeout_milliseconds);
2711 _dbus_assert (timeout_milliseconds >= 0);
2713 if (status == DBUS_DISPATCH_NEED_MEMORY)
2715 /* Try sleeping a bit, as we aren't sure we need to block for reading,
2716 * we may already have a reply in the buffer and just can't process
2719 _dbus_verbose ("dbus_connection_send_with_reply_and_block() waiting for more memory\n");
2721 _dbus_memory_pause_based_on_timeout (timeout_milliseconds);
2725 /* block again, we don't have the reply buffered yet. */
2726 _dbus_connection_do_iteration_unlocked (connection,
2727 DBUS_ITERATION_DO_READING |
2728 DBUS_ITERATION_BLOCK,
2729 timeout_milliseconds);
2732 goto recheck_status;
2735 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): Waited %ld milliseconds and got no reply\n",
2736 (tv_sec - start_tv_sec) * 1000 + (tv_usec - start_tv_usec) / 1000);
2738 _dbus_assert (!_dbus_pending_call_get_completed_unlocked (pending));
2740 /* unlock and call user code */
2741 complete_pending_call_and_unlock (connection, pending, NULL);
2743 /* update user code on dispatch status */
2744 CONNECTION_LOCK (connection);
2745 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2746 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2747 dbus_pending_call_unref (pending);
2751 * Sends a message and blocks a certain time period while waiting for
2752 * a reply. This function does not reenter the main loop,
2753 * i.e. messages other than the reply are queued up but not
2754 * processed. This function is used to do non-reentrant "method
2757 * If a normal reply is received, it is returned, and removed from the
2758 * incoming message queue. If it is not received, #NULL is returned
2759 * and the error is set to #DBUS_ERROR_NO_REPLY. If an error reply is
2760 * received, it is converted to a #DBusError and returned as an error,
2761 * then the reply message is deleted. If something else goes wrong,
2762 * result is set to whatever is appropriate, such as
2763 * #DBUS_ERROR_NO_MEMORY or #DBUS_ERROR_DISCONNECTED.
2765 * @param connection the connection
2766 * @param message the message to send
2767 * @param timeout_milliseconds timeout in milliseconds or -1 for default
2768 * @param error return location for error message
2769 * @returns the message that is the reply or #NULL with an error code if the
2773 dbus_connection_send_with_reply_and_block (DBusConnection *connection,
2774 DBusMessage *message,
2775 int timeout_milliseconds,
2779 DBusPendingCall *pending;
2781 _dbus_return_val_if_fail (connection != NULL, NULL);
2782 _dbus_return_val_if_fail (message != NULL, NULL);
2783 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, NULL);
2784 _dbus_return_val_if_error_is_set (error, NULL);
2786 if (!dbus_connection_send_with_reply (connection, message,
2787 &pending, timeout_milliseconds))
2789 _DBUS_SET_OOM (error);
2793 _dbus_assert (pending != NULL);
2795 dbus_pending_call_block (pending);
2797 reply = dbus_pending_call_steal_reply (pending);
2798 dbus_pending_call_unref (pending);
2800 /* call_complete_and_unlock() called from pending_call_block() should
2801 * always fill this in.
2803 _dbus_assert (reply != NULL);
2805 if (dbus_set_error_from_message (error, reply))
2807 dbus_message_unref (reply);
2815 * Blocks until the outgoing message queue is empty.
2816 * Assumes connection lock already held.
2818 * If you call this, you MUST call update_dispatch_status afterword...
2820 * @param connection the connection.
2823 _dbus_connection_flush_unlocked (DBusConnection *connection)
2825 /* We have to specify DBUS_ITERATION_DO_READING here because
2826 * otherwise we could have two apps deadlock if they are both doing
2827 * a flush(), and the kernel buffers fill up. This could change the
2830 DBusDispatchStatus status;
2832 HAVE_LOCK_CHECK (connection);
2834 while (connection->n_outgoing > 0 &&
2835 _dbus_connection_get_is_connected_unlocked (connection))
2837 _dbus_verbose ("doing iteration in %s\n", _DBUS_FUNCTION_NAME);
2838 HAVE_LOCK_CHECK (connection);
2839 _dbus_connection_do_iteration_unlocked (connection,
2840 DBUS_ITERATION_DO_READING |
2841 DBUS_ITERATION_DO_WRITING |
2842 DBUS_ITERATION_BLOCK,
2846 HAVE_LOCK_CHECK (connection);
2847 _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
2848 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2850 HAVE_LOCK_CHECK (connection);
2855 * Blocks until the outgoing message queue is empty.
2857 * @param connection the connection.
2860 dbus_connection_flush (DBusConnection *connection)
2862 /* We have to specify DBUS_ITERATION_DO_READING here because
2863 * otherwise we could have two apps deadlock if they are both doing
2864 * a flush(), and the kernel buffers fill up. This could change the
2867 DBusDispatchStatus status;
2869 _dbus_return_if_fail (connection != NULL);
2871 CONNECTION_LOCK (connection);
2873 status = _dbus_connection_flush_unlocked (connection);
2875 HAVE_LOCK_CHECK (connection);
2876 /* Unlocks and calls out to user code */
2877 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2879 _dbus_verbose ("%s end\n", _DBUS_FUNCTION_NAME);
2883 * This function is intended for use with applications that don't want
2884 * to write a main loop and deal with #DBusWatch and #DBusTimeout. An
2885 * example usage would be:
2888 * while (dbus_connection_read_write_dispatch (connection, -1))
2889 * ; // empty loop body
2892 * In this usage you would normally have set up a filter function to look
2893 * at each message as it is dispatched. The loop terminates when the last
2894 * message from the connection (the disconnected signal) is processed.
2896 * If there are messages to dispatch and the dispatch flag is set, this
2897 * function will dbus_connection_dispatch() once, and return. If there are no
2898 * messages to dispatch, this function will block until it can read or write,
2899 * then read or write, then return.
2901 * The way to think of this function is that it either makes some sort
2902 * of progress, or it blocks.
2904 * The return value indicates whether the disconnect message has been
2905 * processed, NOT whether the connection is connected. This is
2906 * important because even after disconnecting, you want to process any
2907 * messages you received prior to the disconnect.
2909 * @param connection the connection
2910 * @param timeout_milliseconds max time to block or -1 for infinite
2911 * @param dispatch dispatch new messages or leave them on the incoming queue
2912 * @returns #TRUE if the disconnect message has not been processed
2915 _dbus_connection_read_write_dispatch (DBusConnection *connection,
2916 int timeout_milliseconds,
2917 dbus_bool_t dispatch)
2919 DBusDispatchStatus dstatus;
2920 dbus_bool_t dispatched_disconnected;
2922 dstatus = dbus_connection_get_dispatch_status (connection);
2924 if (dispatch && dstatus == DBUS_DISPATCH_DATA_REMAINS)
2926 _dbus_verbose ("doing dispatch in %s\n", _DBUS_FUNCTION_NAME);
2927 dbus_connection_dispatch (connection);
2928 CONNECTION_LOCK (connection);
2930 else if (dstatus == DBUS_DISPATCH_NEED_MEMORY)
2932 _dbus_verbose ("pausing for memory in %s\n", _DBUS_FUNCTION_NAME);
2933 _dbus_memory_pause_based_on_timeout (timeout_milliseconds);
2934 CONNECTION_LOCK (connection);
2938 CONNECTION_LOCK (connection);
2939 if (_dbus_connection_get_is_connected_unlocked (connection))
2941 _dbus_verbose ("doing iteration in %s\n", _DBUS_FUNCTION_NAME);
2942 _dbus_connection_do_iteration_unlocked (connection,
2943 DBUS_ITERATION_DO_READING |
2944 DBUS_ITERATION_DO_WRITING |
2945 DBUS_ITERATION_BLOCK,
2946 timeout_milliseconds);
2950 HAVE_LOCK_CHECK (connection);
2951 dispatched_disconnected = connection->n_incoming == 0 &&
2952 connection->disconnect_message_link == NULL;
2953 CONNECTION_UNLOCK (connection);
2954 return !dispatched_disconnected; /* TRUE if we have not processed disconnected */
2959 * This function is intended for use with applications that don't want
2960 * to write a main loop and deal with #DBusWatch and #DBusTimeout. An
2961 * example usage would be:
2964 * while (dbus_connection_read_write_dispatch (connection, -1))
2965 * ; // empty loop body
2968 * In this usage you would normally have set up a filter function to look
2969 * at each message as it is dispatched. The loop terminates when the last
2970 * message from the connection (the disconnected signal) is processed.
2972 * If there are messages to dispatch, this function will
2973 * dbus_connection_dispatch() once, and return. If there are no
2974 * messages to dispatch, this function will block until it can read or
2975 * write, then read or write, then return.
2977 * The way to think of this function is that it either makes some sort
2978 * of progress, or it blocks.
2980 * The return value indicates whether the disconnect message has been
2981 * processed, NOT whether the connection is connected. This is
2982 * important because even after disconnecting, you want to process any
2983 * messages you received prior to the disconnect.
2985 * @param connection the connection
2986 * @param timeout_milliseconds max time to block or -1 for infinite
2987 * @returns #TRUE if the disconnect message has not been processed
2990 dbus_connection_read_write_dispatch (DBusConnection *connection,
2991 int timeout_milliseconds)
2993 _dbus_return_val_if_fail (connection != NULL, FALSE);
2994 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
2995 return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, TRUE);
2999 * This function is intended for use with applications that don't want to
3000 * write a main loop and deal with #DBusWatch and #DBusTimeout.
3002 * If there are no messages to dispatch, this function will block until it can
3003 * read or write, then read or write, then return.
3005 * The return value indicates whether the disconnect message has been
3006 * processed, NOT whether the connection is connected. This is important
3007 * because even after disconnecting, you want to process any messages you
3008 * received prior to the disconnect.
3010 * @param connection the connection
3011 * @param timeout_milliseconds max time to block or -1 for infinite
3012 * @returns #TRUE if the disconnect message has not been processed
3015 dbus_connection_read_write (DBusConnection *connection,
3016 int timeout_milliseconds)
3018 _dbus_return_val_if_fail (connection != NULL, FALSE);
3019 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3020 return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, FALSE);
3024 * Returns the first-received message from the incoming message queue,
3025 * leaving it in the queue. If the queue is empty, returns #NULL.
3027 * The caller does not own a reference to the returned message, and
3028 * must either return it using dbus_connection_return_message() or
3029 * keep it after calling dbus_connection_steal_borrowed_message(). No
3030 * one can get at the message while its borrowed, so return it as
3031 * quickly as possible and don't keep a reference to it after
3032 * returning it. If you need to keep the message, make a copy of it.
3034 * dbus_connection_dispatch() will block if called while a borrowed
3035 * message is outstanding; only one piece of code can be playing with
3036 * the incoming queue at a time. This function will block if called
3037 * during a dbus_connection_dispatch().
3039 * @param connection the connection.
3040 * @returns next message in the incoming queue.
3043 dbus_connection_borrow_message (DBusConnection *connection)
3045 DBusDispatchStatus status;
3046 DBusMessage *message;
3048 _dbus_return_val_if_fail (connection != NULL, NULL);
3050 _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
3052 /* this is called for the side effect that it queues
3053 * up any messages from the transport
3055 status = dbus_connection_get_dispatch_status (connection);
3056 if (status != DBUS_DISPATCH_DATA_REMAINS)
3059 CONNECTION_LOCK (connection);
3061 _dbus_connection_acquire_dispatch (connection);
3063 /* While a message is outstanding, the dispatch lock is held */
3064 _dbus_assert (connection->message_borrowed == NULL);
3066 connection->message_borrowed = _dbus_list_get_first (&connection->incoming_messages);
3068 message = connection->message_borrowed;
3070 /* Note that we KEEP the dispatch lock until the message is returned */
3071 if (message == NULL)
3072 _dbus_connection_release_dispatch (connection);
3074 CONNECTION_UNLOCK (connection);
3080 * Used to return a message after peeking at it using
3081 * dbus_connection_borrow_message(). Only called if
3082 * message from dbus_connection_borrow_message() was non-#NULL.
3084 * @param connection the connection
3085 * @param message the message from dbus_connection_borrow_message()
3088 dbus_connection_return_message (DBusConnection *connection,
3089 DBusMessage *message)
3091 _dbus_return_if_fail (connection != NULL);
3092 _dbus_return_if_fail (message != NULL);
3093 _dbus_return_if_fail (message == connection->message_borrowed);
3094 _dbus_return_if_fail (connection->dispatch_acquired);
3096 CONNECTION_LOCK (connection);
3098 _dbus_assert (message == connection->message_borrowed);
3100 connection->message_borrowed = NULL;
3102 _dbus_connection_release_dispatch (connection);
3104 CONNECTION_UNLOCK (connection);
3108 * Used to keep a message after peeking at it using
3109 * dbus_connection_borrow_message(). Before using this function, see
3110 * the caveats/warnings in the documentation for
3111 * dbus_connection_pop_message().
3113 * @param connection the connection
3114 * @param message the message from dbus_connection_borrow_message()
3117 dbus_connection_steal_borrowed_message (DBusConnection *connection,
3118 DBusMessage *message)
3120 DBusMessage *pop_message;
3122 _dbus_return_if_fail (connection != NULL);
3123 _dbus_return_if_fail (message != NULL);
3124 _dbus_return_if_fail (message == connection->message_borrowed);
3125 _dbus_return_if_fail (connection->dispatch_acquired);
3127 CONNECTION_LOCK (connection);
3129 _dbus_assert (message == connection->message_borrowed);
3131 pop_message = _dbus_list_pop_first (&connection->incoming_messages);
3132 _dbus_assert (message == pop_message);
3134 connection->n_incoming -= 1;
3136 _dbus_verbose ("Incoming message %p stolen from queue, %d incoming\n",
3137 message, connection->n_incoming);
3139 connection->message_borrowed = NULL;
3141 _dbus_connection_release_dispatch (connection);
3143 CONNECTION_UNLOCK (connection);
3146 /* See dbus_connection_pop_message, but requires the caller to own
3147 * the lock before calling. May drop the lock while running.
3150 _dbus_connection_pop_message_link_unlocked (DBusConnection *connection)
3152 HAVE_LOCK_CHECK (connection);
3154 _dbus_assert (connection->message_borrowed == NULL);
3156 if (connection->n_incoming > 0)
3160 link = _dbus_list_pop_first_link (&connection->incoming_messages);
3161 connection->n_incoming -= 1;
3163 _dbus_verbose ("Message %p (%d %s %s %s '%s') removed from incoming queue %p, %d incoming\n",
3165 dbus_message_get_type (link->data),
3166 dbus_message_get_path (link->data) ?
3167 dbus_message_get_path (link->data) :
3169 dbus_message_get_interface (link->data) ?
3170 dbus_message_get_interface (link->data) :
3172 dbus_message_get_member (link->data) ?
3173 dbus_message_get_member (link->data) :
3175 dbus_message_get_signature (link->data),
3176 connection, connection->n_incoming);
3184 /* See dbus_connection_pop_message, but requires the caller to own
3185 * the lock before calling. May drop the lock while running.
3188 _dbus_connection_pop_message_unlocked (DBusConnection *connection)
3192 HAVE_LOCK_CHECK (connection);
3194 link = _dbus_connection_pop_message_link_unlocked (connection);
3198 DBusMessage *message;
3200 message = link->data;
3202 _dbus_list_free_link (link);
3211 _dbus_connection_putback_message_link_unlocked (DBusConnection *connection,
3212 DBusList *message_link)
3214 HAVE_LOCK_CHECK (connection);
3216 _dbus_assert (message_link != NULL);
3217 /* You can't borrow a message while a link is outstanding */
3218 _dbus_assert (connection->message_borrowed == NULL);
3219 /* We had to have the dispatch lock across the pop/putback */
3220 _dbus_assert (connection->dispatch_acquired);
3222 _dbus_list_prepend_link (&connection->incoming_messages,
3224 connection->n_incoming += 1;
3226 _dbus_verbose ("Message %p (%d %s %s '%s') put back into queue %p, %d incoming\n",
3228 dbus_message_get_type (message_link->data),
3229 dbus_message_get_interface (message_link->data) ?
3230 dbus_message_get_interface (message_link->data) :
3232 dbus_message_get_member (message_link->data) ?
3233 dbus_message_get_member (message_link->data) :
3235 dbus_message_get_signature (message_link->data),
3236 connection, connection->n_incoming);
3240 * Returns the first-received message from the incoming message queue,
3241 * removing it from the queue. The caller owns a reference to the
3242 * returned message. If the queue is empty, returns #NULL.
3244 * This function bypasses any message handlers that are registered,
3245 * and so using it is usually wrong. Instead, let the main loop invoke
3246 * dbus_connection_dispatch(). Popping messages manually is only
3247 * useful in very simple programs that don't share a #DBusConnection
3248 * with any libraries or other modules.
3250 * There is a lock that covers all ways of accessing the incoming message
3251 * queue, so dbus_connection_dispatch(), dbus_connection_pop_message(),
3252 * dbus_connection_borrow_message(), etc. will all block while one of the others
3253 * in the group is running.
3255 * @param connection the connection.
3256 * @returns next message in the incoming queue.
3259 dbus_connection_pop_message (DBusConnection *connection)
3261 DBusMessage *message;
3262 DBusDispatchStatus status;
3264 _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
3266 /* this is called for the side effect that it queues
3267 * up any messages from the transport
3269 status = dbus_connection_get_dispatch_status (connection);
3270 if (status != DBUS_DISPATCH_DATA_REMAINS)
3273 CONNECTION_LOCK (connection);
3274 _dbus_connection_acquire_dispatch (connection);
3275 HAVE_LOCK_CHECK (connection);
3277 message = _dbus_connection_pop_message_unlocked (connection);
3279 _dbus_verbose ("Returning popped message %p\n", message);
3281 _dbus_connection_release_dispatch (connection);
3282 CONNECTION_UNLOCK (connection);
3288 * Acquire the dispatcher. This is a separate lock so the main
3289 * connection lock can be dropped to call out to application dispatch
3292 * @param connection the connection.
3295 _dbus_connection_acquire_dispatch (DBusConnection *connection)
3297 HAVE_LOCK_CHECK (connection);
3299 _dbus_connection_ref_unlocked (connection);
3300 CONNECTION_UNLOCK (connection);
3302 _dbus_verbose ("%s locking dispatch_mutex\n", _DBUS_FUNCTION_NAME);
3303 _dbus_mutex_lock (connection->dispatch_mutex);
3305 while (connection->dispatch_acquired)
3307 _dbus_verbose ("%s waiting for dispatch to be acquirable\n", _DBUS_FUNCTION_NAME);
3308 _dbus_condvar_wait (connection->dispatch_cond, connection->dispatch_mutex);
3311 _dbus_assert (!connection->dispatch_acquired);
3313 connection->dispatch_acquired = TRUE;
3315 _dbus_verbose ("%s unlocking dispatch_mutex\n", _DBUS_FUNCTION_NAME);
3316 _dbus_mutex_unlock (connection->dispatch_mutex);
3318 CONNECTION_LOCK (connection);
3319 _dbus_connection_unref_unlocked (connection);
3323 * Release the dispatcher when you're done with it. Only call
3324 * after you've acquired the dispatcher. Wakes up at most one
3325 * thread currently waiting to acquire the dispatcher.
3327 * @param connection the connection.
3330 _dbus_connection_release_dispatch (DBusConnection *connection)
3332 HAVE_LOCK_CHECK (connection);
3334 _dbus_verbose ("%s locking dispatch_mutex\n", _DBUS_FUNCTION_NAME);
3335 _dbus_mutex_lock (connection->dispatch_mutex);
3337 _dbus_assert (connection->dispatch_acquired);
3339 connection->dispatch_acquired = FALSE;
3340 _dbus_condvar_wake_one (connection->dispatch_cond);
3342 _dbus_verbose ("%s unlocking dispatch_mutex\n", _DBUS_FUNCTION_NAME);
3343 _dbus_mutex_unlock (connection->dispatch_mutex);
3347 _dbus_connection_failed_pop (DBusConnection *connection,
3348 DBusList *message_link)
3350 _dbus_list_prepend_link (&connection->incoming_messages,
3352 connection->n_incoming += 1;
3355 static DBusDispatchStatus
3356 _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection)
3358 HAVE_LOCK_CHECK (connection);
3360 if (connection->n_incoming > 0)
3361 return DBUS_DISPATCH_DATA_REMAINS;
3362 else if (!_dbus_transport_queue_messages (connection->transport))
3363 return DBUS_DISPATCH_NEED_MEMORY;
3366 DBusDispatchStatus status;
3367 dbus_bool_t is_connected;
3369 status = _dbus_transport_get_dispatch_status (connection->transport);
3370 is_connected = _dbus_transport_get_is_connected (connection->transport);
3372 _dbus_verbose ("dispatch status = %s is_connected = %d\n",
3373 DISPATCH_STATUS_NAME (status), is_connected);
3377 if (status == DBUS_DISPATCH_COMPLETE &&
3378 connection->disconnect_message_link)
3380 _dbus_verbose ("Sending disconnect message from %s\n",
3381 _DBUS_FUNCTION_NAME);
3383 connection_forget_shared_unlocked (connection);
3385 /* If we have pending calls queued timeouts on disconnect */
3386 connection_timeout_and_complete_all_pending_calls_unlocked (connection);
3388 /* We haven't sent the disconnect message already,
3389 * and all real messages have been queued up.
3391 _dbus_connection_queue_synthesized_message_link (connection,
3392 connection->disconnect_message_link);
3393 connection->disconnect_message_link = NULL;
3395 status = DBUS_DISPATCH_DATA_REMAINS;
3398 /* Dump the outgoing queue, we aren't going to be able to
3399 * send it now, and we'd like accessors like
3400 * dbus_connection_get_outgoing_size() to be accurate.
3402 if (connection->n_outgoing > 0)
3406 _dbus_verbose ("Dropping %d outgoing messages since we're disconnected\n",
3407 connection->n_outgoing);
3409 while ((link = _dbus_list_get_last_link (&connection->outgoing_messages)))
3411 _dbus_connection_message_sent (connection, link->data);
3416 if (status != DBUS_DISPATCH_COMPLETE)
3418 else if (connection->n_incoming > 0)
3419 return DBUS_DISPATCH_DATA_REMAINS;
3421 return DBUS_DISPATCH_COMPLETE;
3426 _dbus_connection_update_dispatch_status_and_unlock (DBusConnection *connection,
3427 DBusDispatchStatus new_status)
3429 dbus_bool_t changed;
3430 DBusDispatchStatusFunction function;
3433 HAVE_LOCK_CHECK (connection);
3435 _dbus_connection_ref_unlocked (connection);
3437 changed = new_status != connection->last_dispatch_status;
3439 connection->last_dispatch_status = new_status;
3441 function = connection->dispatch_status_function;
3442 data = connection->dispatch_status_data;
3444 /* We drop the lock */
3445 CONNECTION_UNLOCK (connection);
3447 if (changed && function)
3449 _dbus_verbose ("Notifying of change to dispatch status of %p now %d (%s)\n",
3450 connection, new_status,
3451 DISPATCH_STATUS_NAME (new_status));
3452 (* function) (connection, new_status, data);
3455 dbus_connection_unref (connection);
3459 * Gets the current state (what we would currently return
3460 * from dbus_connection_dispatch()) but doesn't actually
3461 * dispatch any messages.
3463 * @param connection the connection.
3464 * @returns current dispatch status
3467 dbus_connection_get_dispatch_status (DBusConnection *connection)
3469 DBusDispatchStatus status;
3471 _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
3473 _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
3475 CONNECTION_LOCK (connection);
3477 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3479 CONNECTION_UNLOCK (connection);
3485 * Filter funtion for handling the Peer standard interface
3487 static DBusHandlerResult
3488 _dbus_connection_peer_filter_unlocked_no_update (DBusConnection *connection,
3489 DBusMessage *message)
3491 if (dbus_message_is_method_call (message,
3492 DBUS_INTERFACE_PEER,
3498 ret = dbus_message_new_method_return (message);
3500 return DBUS_HANDLER_RESULT_NEED_MEMORY;
3502 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
3504 dbus_message_unref (ret);
3507 return DBUS_HANDLER_RESULT_NEED_MEMORY;
3509 return DBUS_HANDLER_RESULT_HANDLED;
3513 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
3517 * Processes all builtin filter functions
3519 * If the spec specifies a standard interface
3520 * they should be processed from this method
3522 static DBusHandlerResult
3523 _dbus_connection_run_builtin_filters_unlocked_no_update (DBusConnection *connection,
3524 DBusMessage *message)
3526 /* We just run one filter for now but have the option to run more
3527 if the spec calls for it in the future */
3529 return _dbus_connection_peer_filter_unlocked_no_update (connection, message);
3533 * Processes data buffered while handling watches, queueing zero or
3534 * more incoming messages. Then pops the first-received message from
3535 * the current incoming message queue, runs any handlers for it, and
3536 * unrefs the message. Returns a status indicating whether messages/data
3537 * remain, more memory is needed, or all data has been processed.
3539 * Even if the dispatch status is #DBUS_DISPATCH_DATA_REMAINS,
3540 * does not necessarily dispatch a message, as the data may
3541 * be part of authentication or the like.
3543 * @todo some FIXME in here about handling DBUS_HANDLER_RESULT_NEED_MEMORY
3545 * @todo FIXME what if we call out to application code to handle a
3546 * message, holding the dispatch lock, and the application code runs
3547 * the main loop and dispatches again? Probably deadlocks at the
3548 * moment. Maybe we want a dispatch status of DBUS_DISPATCH_IN_PROGRESS,
3549 * and then the GSource etc. could handle the situation? Right now
3550 * our GSource is NO_RECURSE
3552 * @param connection the connection
3553 * @returns dispatch status
3556 dbus_connection_dispatch (DBusConnection *connection)
3558 DBusMessage *message;
3559 DBusList *link, *filter_list_copy, *message_link;
3560 DBusHandlerResult result;
3561 DBusPendingCall *pending;
3562 dbus_int32_t reply_serial;
3563 DBusDispatchStatus status;
3565 _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
3567 _dbus_verbose ("%s\n", _DBUS_FUNCTION_NAME);
3569 CONNECTION_LOCK (connection);
3570 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3571 if (status != DBUS_DISPATCH_DATA_REMAINS)
3573 /* unlocks and calls out to user code */
3574 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3578 /* We need to ref the connection since the callback could potentially
3579 * drop the last ref to it
3581 _dbus_connection_ref_unlocked (connection);
3583 _dbus_connection_acquire_dispatch (connection);
3584 HAVE_LOCK_CHECK (connection);
3586 message_link = _dbus_connection_pop_message_link_unlocked (connection);
3587 if (message_link == NULL)
3589 /* another thread dispatched our stuff */
3591 _dbus_verbose ("another thread dispatched message (during acquire_dispatch above)\n");
3593 _dbus_connection_release_dispatch (connection);
3595 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3597 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3599 dbus_connection_unref (connection);
3604 message = message_link->data;
3606 _dbus_verbose (" dispatching message %p (%d %s %s '%s')\n",
3608 dbus_message_get_type (message),
3609 dbus_message_get_interface (message) ?
3610 dbus_message_get_interface (message) :
3612 dbus_message_get_member (message) ?
3613 dbus_message_get_member (message) :
3615 dbus_message_get_signature (message));
3617 result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
3619 /* Pending call handling must be first, because if you do
3620 * dbus_connection_send_with_reply_and_block() or
3621 * dbus_pending_call_block() then no handlers/filters will be run on
3622 * the reply. We want consistent semantics in the case where we
3623 * dbus_connection_dispatch() the reply.
3626 reply_serial = dbus_message_get_reply_serial (message);
3627 pending = _dbus_hash_table_lookup_int (connection->pending_replies,
3631 _dbus_verbose ("Dispatching a pending reply\n");
3632 complete_pending_call_and_unlock (connection, pending, message);
3633 pending = NULL; /* it's probably unref'd */
3635 CONNECTION_LOCK (connection);
3636 _dbus_verbose ("pending call completed in dispatch\n");
3637 result = DBUS_HANDLER_RESULT_HANDLED;
3641 result = _dbus_connection_run_builtin_filters_unlocked_no_update (connection, message);
3642 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
3645 if (!_dbus_list_copy (&connection->filter_list, &filter_list_copy))
3647 _dbus_connection_release_dispatch (connection);
3648 HAVE_LOCK_CHECK (connection);
3650 _dbus_connection_failed_pop (connection, message_link);
3652 /* unlocks and calls user code */
3653 _dbus_connection_update_dispatch_status_and_unlock (connection,
3654 DBUS_DISPATCH_NEED_MEMORY);
3657 dbus_pending_call_unref (pending);
3658 dbus_connection_unref (connection);
3660 return DBUS_DISPATCH_NEED_MEMORY;
3663 _dbus_list_foreach (&filter_list_copy,
3664 (DBusForeachFunction)_dbus_message_filter_ref,
3667 /* We're still protected from dispatch() reentrancy here
3668 * since we acquired the dispatcher
3670 CONNECTION_UNLOCK (connection);
3672 link = _dbus_list_get_first_link (&filter_list_copy);
3673 while (link != NULL)
3675 DBusMessageFilter *filter = link->data;
3676 DBusList *next = _dbus_list_get_next_link (&filter_list_copy, link);
3678 _dbus_verbose (" running filter on message %p\n", message);
3679 result = (* filter->function) (connection, message, filter->user_data);
3681 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
3687 _dbus_list_foreach (&filter_list_copy,
3688 (DBusForeachFunction)_dbus_message_filter_unref,
3690 _dbus_list_clear (&filter_list_copy);
3692 CONNECTION_LOCK (connection);
3694 if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
3696 _dbus_verbose ("No memory in %s\n", _DBUS_FUNCTION_NAME);
3699 else if (result == DBUS_HANDLER_RESULT_HANDLED)
3701 _dbus_verbose ("filter handled message in dispatch\n");
3705 /* We're still protected from dispatch() reentrancy here
3706 * since we acquired the dispatcher
3708 _dbus_verbose (" running object path dispatch on message %p (%d %s %s '%s')\n",
3710 dbus_message_get_type (message),
3711 dbus_message_get_interface (message) ?
3712 dbus_message_get_interface (message) :
3714 dbus_message_get_member (message) ?
3715 dbus_message_get_member (message) :
3717 dbus_message_get_signature (message));
3719 HAVE_LOCK_CHECK (connection);
3720 result = _dbus_object_tree_dispatch_and_unlock (connection->objects,
3723 CONNECTION_LOCK (connection);
3725 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
3727 _dbus_verbose ("object tree handled message in dispatch\n");
3731 if (dbus_message_get_type (message) == DBUS_MESSAGE_TYPE_METHOD_CALL)
3735 DBusPreallocatedSend *preallocated;
3737 _dbus_verbose (" sending error %s\n",
3738 DBUS_ERROR_UNKNOWN_METHOD);
3740 if (!_dbus_string_init (&str))
3742 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
3743 _dbus_verbose ("no memory for error string in dispatch\n");
3747 if (!_dbus_string_append_printf (&str,
3748 "Method \"%s\" with signature \"%s\" on interface \"%s\" doesn't exist\n",
3749 dbus_message_get_member (message),
3750 dbus_message_get_signature (message),
3751 dbus_message_get_interface (message)))
3753 _dbus_string_free (&str);
3754 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
3755 _dbus_verbose ("no memory for error string in dispatch\n");
3759 reply = dbus_message_new_error (message,
3760 DBUS_ERROR_UNKNOWN_METHOD,
3761 _dbus_string_get_const_data (&str));
3762 _dbus_string_free (&str);
3766 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
3767 _dbus_verbose ("no memory for error reply in dispatch\n");
3771 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
3773 if (preallocated == NULL)
3775 dbus_message_unref (reply);
3776 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
3777 _dbus_verbose ("no memory for error send in dispatch\n");
3781 _dbus_connection_send_preallocated_unlocked_no_update (connection, preallocated,
3784 dbus_message_unref (reply);
3786 result = DBUS_HANDLER_RESULT_HANDLED;
3789 _dbus_verbose (" done dispatching %p (%d %s %s '%s') on connection %p\n", message,
3790 dbus_message_get_type (message),
3791 dbus_message_get_interface (message) ?
3792 dbus_message_get_interface (message) :
3794 dbus_message_get_member (message) ?
3795 dbus_message_get_member (message) :
3797 dbus_message_get_signature (message),
3801 if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
3803 _dbus_verbose ("out of memory in %s\n", _DBUS_FUNCTION_NAME);
3805 /* Put message back, and we'll start over.
3806 * Yes this means handlers must be idempotent if they
3807 * don't return HANDLED; c'est la vie.
3809 _dbus_connection_putback_message_link_unlocked (connection,
3814 _dbus_verbose (" ... done dispatching in %s\n", _DBUS_FUNCTION_NAME);
3816 if (dbus_message_is_signal (message,
3817 DBUS_INTERFACE_LOCAL,
3820 _dbus_bus_check_connection_and_unref (connection);
3822 if (connection->exit_on_disconnect)
3824 CONNECTION_UNLOCK (connection);
3826 _dbus_verbose ("Exiting on Disconnected signal\n");
3828 _dbus_assert_not_reached ("Call to exit() returned");
3832 _dbus_list_free_link (message_link);
3833 dbus_message_unref (message); /* don't want the message to count in max message limits
3834 * in computing dispatch status below
3838 _dbus_connection_release_dispatch (connection);
3839 HAVE_LOCK_CHECK (connection);
3841 _dbus_verbose ("%s before final status update\n", _DBUS_FUNCTION_NAME);
3842 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3844 /* unlocks and calls user code */
3845 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3847 dbus_connection_unref (connection);
3853 * Sets the watch functions for the connection. These functions are
3854 * responsible for making the application's main loop aware of file
3855 * descriptors that need to be monitored for events, using select() or
3856 * poll(). When using Qt, typically the DBusAddWatchFunction would
3857 * create a QSocketNotifier. When using GLib, the DBusAddWatchFunction
3858 * could call g_io_add_watch(), or could be used as part of a more
3859 * elaborate GSource. Note that when a watch is added, it may
3862 * The DBusWatchToggledFunction notifies the application that the
3863 * watch has been enabled or disabled. Call dbus_watch_get_enabled()
3864 * to check this. A disabled watch should have no effect, and enabled
3865 * watch should be added to the main loop. This feature is used
3866 * instead of simply adding/removing the watch because
3867 * enabling/disabling can be done without memory allocation. The
3868 * toggled function may be NULL if a main loop re-queries
3869 * dbus_watch_get_enabled() every time anyway.
3871 * The DBusWatch can be queried for the file descriptor to watch using
3872 * dbus_watch_get_fd(), and for the events to watch for using
3873 * dbus_watch_get_flags(). The flags returned by
3874 * dbus_watch_get_flags() will only contain DBUS_WATCH_READABLE and
3875 * DBUS_WATCH_WRITABLE, never DBUS_WATCH_HANGUP or DBUS_WATCH_ERROR;
3876 * all watches implicitly include a watch for hangups, errors, and
3877 * other exceptional conditions.
3879 * Once a file descriptor becomes readable or writable, or an exception
3880 * occurs, dbus_watch_handle() should be called to
3881 * notify the connection of the file descriptor's condition.
3883 * dbus_watch_handle() cannot be called during the
3884 * DBusAddWatchFunction, as the connection will not be ready to handle
3887 * It is not allowed to reference a DBusWatch after it has been passed
3888 * to remove_function.
3890 * If #FALSE is returned due to lack of memory, the failure may be due
3891 * to a #FALSE return from the new add_function. If so, the
3892 * add_function may have been called successfully one or more times,
3893 * but the remove_function will also have been called to remove any
3894 * successful adds. i.e. if #FALSE is returned the net result
3895 * should be that dbus_connection_set_watch_functions() has no effect,
3896 * but the add_function and remove_function may have been called.
3898 * @todo We need to drop the lock when we call the
3899 * add/remove/toggled functions which can be a side effect
3900 * of setting the watch functions.
3902 * @param connection the connection.
3903 * @param add_function function to begin monitoring a new descriptor.
3904 * @param remove_function function to stop monitoring a descriptor.
3905 * @param toggled_function function to notify of enable/disable
3906 * @param data data to pass to add_function and remove_function.
3907 * @param free_data_function function to be called to free the data.
3908 * @returns #FALSE on failure (no memory)
3911 dbus_connection_set_watch_functions (DBusConnection *connection,
3912 DBusAddWatchFunction add_function,
3913 DBusRemoveWatchFunction remove_function,
3914 DBusWatchToggledFunction toggled_function,
3916 DBusFreeFunction free_data_function)
3919 DBusWatchList *watches;
3921 _dbus_return_val_if_fail (connection != NULL, FALSE);
3923 CONNECTION_LOCK (connection);
3925 #ifndef DBUS_DISABLE_CHECKS
3926 if (connection->watches == NULL)
3928 _dbus_warn ("Re-entrant call to %s is not allowed\n",
3929 _DBUS_FUNCTION_NAME);
3934 /* ref connection for slightly better reentrancy */
3935 _dbus_connection_ref_unlocked (connection);
3937 /* This can call back into user code, and we need to drop the
3938 * connection lock when it does. This is kind of a lame
3941 watches = connection->watches;
3942 connection->watches = NULL;
3943 CONNECTION_UNLOCK (connection);
3945 retval = _dbus_watch_list_set_functions (watches,
3946 add_function, remove_function,
3948 data, free_data_function);
3949 CONNECTION_LOCK (connection);
3950 connection->watches = watches;
3952 CONNECTION_UNLOCK (connection);
3953 /* drop our paranoid refcount */
3954 dbus_connection_unref (connection);
3960 * Sets the timeout functions for the connection. These functions are
3961 * responsible for making the application's main loop aware of timeouts.
3962 * When using Qt, typically the DBusAddTimeoutFunction would create a
3963 * QTimer. When using GLib, the DBusAddTimeoutFunction would call
3966 * The DBusTimeoutToggledFunction notifies the application that the
3967 * timeout has been enabled or disabled. Call
3968 * dbus_timeout_get_enabled() to check this. A disabled timeout should
3969 * have no effect, and enabled timeout should be added to the main
3970 * loop. This feature is used instead of simply adding/removing the
3971 * timeout because enabling/disabling can be done without memory
3972 * allocation. With Qt, QTimer::start() and QTimer::stop() can be used
3973 * to enable and disable. The toggled function may be NULL if a main
3974 * loop re-queries dbus_timeout_get_enabled() every time anyway.
3975 * Whenever a timeout is toggled, its interval may change.
3977 * The DBusTimeout can be queried for the timer interval using
3978 * dbus_timeout_get_interval(). dbus_timeout_handle() should be called
3979 * repeatedly, each time the interval elapses, starting after it has
3980 * elapsed once. The timeout stops firing when it is removed with the
3981 * given remove_function. The timer interval may change whenever the
3982 * timeout is added, removed, or toggled.
3984 * @param connection the connection.
3985 * @param add_function function to add a timeout.
3986 * @param remove_function function to remove a timeout.
3987 * @param toggled_function function to notify of enable/disable
3988 * @param data data to pass to add_function and remove_function.
3989 * @param free_data_function function to be called to free the data.
3990 * @returns #FALSE on failure (no memory)
3993 dbus_connection_set_timeout_functions (DBusConnection *connection,
3994 DBusAddTimeoutFunction add_function,
3995 DBusRemoveTimeoutFunction remove_function,
3996 DBusTimeoutToggledFunction toggled_function,
3998 DBusFreeFunction free_data_function)
4001 DBusTimeoutList *timeouts;
4003 _dbus_return_val_if_fail (connection != NULL, FALSE);
4005 CONNECTION_LOCK (connection);
4007 #ifndef DBUS_DISABLE_CHECKS
4008 if (connection->timeouts == NULL)
4010 _dbus_warn ("Re-entrant call to %s is not allowed\n",
4011 _DBUS_FUNCTION_NAME);
4016 /* ref connection for slightly better reentrancy */
4017 _dbus_connection_ref_unlocked (connection);
4019 timeouts = connection->timeouts;
4020 connection->timeouts = NULL;
4021 CONNECTION_UNLOCK (connection);
4023 retval = _dbus_timeout_list_set_functions (timeouts,
4024 add_function, remove_function,
4026 data, free_data_function);
4027 CONNECTION_LOCK (connection);
4028 connection->timeouts = timeouts;
4030 CONNECTION_UNLOCK (connection);
4031 /* drop our paranoid refcount */
4032 dbus_connection_unref (connection);
4038 * Sets the mainloop wakeup function for the connection. This function is
4039 * responsible for waking up the main loop (if its sleeping) when some some
4040 * change has happened to the connection that the mainloop needs to reconsider
4041 * (e.g. a message has been queued for writing).
4042 * When using Qt, this typically results in a call to QEventLoop::wakeUp().
4043 * When using GLib, it would call g_main_context_wakeup().
4046 * @param connection the connection.
4047 * @param wakeup_main_function function to wake up the mainloop
4048 * @param data data to pass wakeup_main_function
4049 * @param free_data_function function to be called to free the data.
4052 dbus_connection_set_wakeup_main_function (DBusConnection *connection,
4053 DBusWakeupMainFunction wakeup_main_function,
4055 DBusFreeFunction free_data_function)
4058 DBusFreeFunction old_free_data;
4060 _dbus_return_if_fail (connection != NULL);
4062 CONNECTION_LOCK (connection);
4063 old_data = connection->wakeup_main_data;
4064 old_free_data = connection->free_wakeup_main_data;
4066 connection->wakeup_main_function = wakeup_main_function;
4067 connection->wakeup_main_data = data;
4068 connection->free_wakeup_main_data = free_data_function;
4070 CONNECTION_UNLOCK (connection);
4072 /* Callback outside the lock */
4074 (*old_free_data) (old_data);
4078 * Set a function to be invoked when the dispatch status changes.
4079 * If the dispatch status is #DBUS_DISPATCH_DATA_REMAINS, then
4080 * dbus_connection_dispatch() needs to be called to process incoming
4081 * messages. However, dbus_connection_dispatch() MUST NOT BE CALLED
4082 * from inside the DBusDispatchStatusFunction. Indeed, almost
4083 * any reentrancy in this function is a bad idea. Instead,
4084 * the DBusDispatchStatusFunction should simply save an indication
4085 * that messages should be dispatched later, when the main loop
4088 * @param connection the connection
4089 * @param function function to call on dispatch status changes
4090 * @param data data for function
4091 * @param free_data_function free the function data
4094 dbus_connection_set_dispatch_status_function (DBusConnection *connection,
4095 DBusDispatchStatusFunction function,
4097 DBusFreeFunction free_data_function)
4100 DBusFreeFunction old_free_data;
4102 _dbus_return_if_fail (connection != NULL);
4104 CONNECTION_LOCK (connection);
4105 old_data = connection->dispatch_status_data;
4106 old_free_data = connection->free_dispatch_status_data;
4108 connection->dispatch_status_function = function;
4109 connection->dispatch_status_data = data;
4110 connection->free_dispatch_status_data = free_data_function;
4112 CONNECTION_UNLOCK (connection);
4114 /* Callback outside the lock */
4116 (*old_free_data) (old_data);
4120 * Get the UNIX file descriptor of the connection, if any. This can
4121 * be used for SELinux access control checks with getpeercon() for
4122 * example. DO NOT read or write to the file descriptor, or try to
4123 * select() on it; use DBusWatch for main loop integration. Not all
4124 * connections will have a file descriptor. So for adding descriptors
4125 * to the main loop, use dbus_watch_get_fd() and so forth.
4127 * @param connection the connection
4128 * @param fd return location for the file descriptor.
4129 * @returns #TRUE if fd is successfully obtained.
4132 dbus_connection_get_unix_fd (DBusConnection *connection,
4137 _dbus_return_val_if_fail (connection != NULL, FALSE);
4138 _dbus_return_val_if_fail (connection->transport != NULL, FALSE);
4140 CONNECTION_LOCK (connection);
4142 retval = _dbus_transport_get_unix_fd (connection->transport,
4145 CONNECTION_UNLOCK (connection);
4151 * Gets the UNIX user ID of the connection if any.
4152 * Returns #TRUE if the uid is filled in.
4153 * Always returns #FALSE on non-UNIX platforms.
4154 * Always returns #FALSE prior to authenticating the
4157 * @param connection the connection
4158 * @param uid return location for the user ID
4159 * @returns #TRUE if uid is filled in with a valid user ID
4162 dbus_connection_get_unix_user (DBusConnection *connection,
4167 _dbus_return_val_if_fail (connection != NULL, FALSE);
4168 _dbus_return_val_if_fail (uid != NULL, FALSE);
4170 CONNECTION_LOCK (connection);
4172 if (!_dbus_transport_get_is_authenticated (connection->transport))
4175 result = _dbus_transport_get_unix_user (connection->transport,
4177 CONNECTION_UNLOCK (connection);
4183 * Gets the process ID of the connection if any.
4184 * Returns #TRUE if the uid is filled in.
4185 * Always returns #FALSE prior to authenticating the
4188 * @param connection the connection
4189 * @param pid return location for the process ID
4190 * @returns #TRUE if uid is filled in with a valid process ID
4193 dbus_connection_get_unix_process_id (DBusConnection *connection,
4198 _dbus_return_val_if_fail (connection != NULL, FALSE);
4199 _dbus_return_val_if_fail (pid != NULL, FALSE);
4201 CONNECTION_LOCK (connection);
4203 if (!_dbus_transport_get_is_authenticated (connection->transport))
4206 result = _dbus_transport_get_unix_process_id (connection->transport,
4208 CONNECTION_UNLOCK (connection);
4214 * Sets a predicate function used to determine whether a given user ID
4215 * is allowed to connect. When an incoming connection has
4216 * authenticated with a particular user ID, this function is called;
4217 * if it returns #TRUE, the connection is allowed to proceed,
4218 * otherwise the connection is disconnected.
4220 * If the function is set to #NULL (as it is by default), then
4221 * only the same UID as the server process will be allowed to
4224 * @param connection the connection
4225 * @param function the predicate
4226 * @param data data to pass to the predicate
4227 * @param free_data_function function to free the data
4230 dbus_connection_set_unix_user_function (DBusConnection *connection,
4231 DBusAllowUnixUserFunction function,
4233 DBusFreeFunction free_data_function)
4235 void *old_data = NULL;
4236 DBusFreeFunction old_free_function = NULL;
4238 _dbus_return_if_fail (connection != NULL);
4240 CONNECTION_LOCK (connection);
4241 _dbus_transport_set_unix_user_function (connection->transport,
4242 function, data, free_data_function,
4243 &old_data, &old_free_function);
4244 CONNECTION_UNLOCK (connection);
4246 if (old_free_function != NULL)
4247 (* old_free_function) (old_data);
4251 * Adds a message filter. Filters are handlers that are run on all
4252 * incoming messages, prior to the objects registered with
4253 * dbus_connection_register_object_path(). Filters are run in the
4254 * order that they were added. The same handler can be added as a
4255 * filter more than once, in which case it will be run more than once.
4256 * Filters added during a filter callback won't be run on the message
4259 * @todo we don't run filters on messages while blocking without
4260 * entering the main loop, since filters are run as part of
4261 * dbus_connection_dispatch(). This is probably a feature, as filters
4262 * could create arbitrary reentrancy. But kind of sucks if you're
4263 * trying to filter METHOD_RETURN for some reason.
4265 * @param connection the connection
4266 * @param function function to handle messages
4267 * @param user_data user data to pass to the function
4268 * @param free_data_function function to use for freeing user data
4269 * @returns #TRUE on success, #FALSE if not enough memory.
4272 dbus_connection_add_filter (DBusConnection *connection,
4273 DBusHandleMessageFunction function,
4275 DBusFreeFunction free_data_function)
4277 DBusMessageFilter *filter;
4279 _dbus_return_val_if_fail (connection != NULL, FALSE);
4280 _dbus_return_val_if_fail (function != NULL, FALSE);
4282 filter = dbus_new0 (DBusMessageFilter, 1);
4286 filter->refcount.value = 1;
4288 CONNECTION_LOCK (connection);
4290 if (!_dbus_list_append (&connection->filter_list,
4293 _dbus_message_filter_unref (filter);
4294 CONNECTION_UNLOCK (connection);
4298 /* Fill in filter after all memory allocated,
4299 * so we don't run the free_user_data_function
4300 * if the add_filter() fails
4303 filter->function = function;
4304 filter->user_data = user_data;
4305 filter->free_user_data_function = free_data_function;
4307 CONNECTION_UNLOCK (connection);
4312 * Removes a previously-added message filter. It is a programming
4313 * error to call this function for a handler that has not been added
4314 * as a filter. If the given handler was added more than once, only
4315 * one instance of it will be removed (the most recently-added
4318 * @param connection the connection
4319 * @param function the handler to remove
4320 * @param user_data user data for the handler to remove
4324 dbus_connection_remove_filter (DBusConnection *connection,
4325 DBusHandleMessageFunction function,
4329 DBusMessageFilter *filter;
4331 _dbus_return_if_fail (connection != NULL);
4332 _dbus_return_if_fail (function != NULL);
4334 CONNECTION_LOCK (connection);
4338 link = _dbus_list_get_last_link (&connection->filter_list);
4339 while (link != NULL)
4341 filter = link->data;
4343 if (filter->function == function &&
4344 filter->user_data == user_data)
4346 _dbus_list_remove_link (&connection->filter_list, link);
4347 filter->function = NULL;
4352 link = _dbus_list_get_prev_link (&connection->filter_list, link);
4355 CONNECTION_UNLOCK (connection);
4357 #ifndef DBUS_DISABLE_CHECKS
4360 _dbus_warn ("Attempt to remove filter function %p user data %p, but no such filter has been added\n",
4361 function, user_data);
4366 /* Call application code */
4367 if (filter->free_user_data_function)
4368 (* filter->free_user_data_function) (filter->user_data);
4370 filter->free_user_data_function = NULL;
4371 filter->user_data = NULL;
4373 _dbus_message_filter_unref (filter);
4377 * Registers a handler for a given path in the object hierarchy.
4378 * The given vtable handles messages sent to exactly the given path.
4381 * @param connection the connection
4382 * @param path a '/' delimited string of path elements
4383 * @param vtable the virtual table
4384 * @param user_data data to pass to functions in the vtable
4385 * @returns #FALSE if not enough memory
4388 dbus_connection_register_object_path (DBusConnection *connection,
4390 const DBusObjectPathVTable *vtable,
4393 char **decomposed_path;
4396 _dbus_return_val_if_fail (connection != NULL, FALSE);
4397 _dbus_return_val_if_fail (path != NULL, FALSE);
4398 _dbus_return_val_if_fail (path[0] == '/', FALSE);
4399 _dbus_return_val_if_fail (vtable != NULL, FALSE);
4401 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
4404 CONNECTION_LOCK (connection);
4406 retval = _dbus_object_tree_register (connection->objects,
4408 (const char **) decomposed_path, vtable,
4411 CONNECTION_UNLOCK (connection);
4413 dbus_free_string_array (decomposed_path);
4419 * Registers a fallback handler for a given subsection of the object
4420 * hierarchy. The given vtable handles messages at or below the given
4421 * path. You can use this to establish a default message handling
4422 * policy for a whole "subdirectory."
4424 * @param connection the connection
4425 * @param path a '/' delimited string of path elements
4426 * @param vtable the virtual table
4427 * @param user_data data to pass to functions in the vtable
4428 * @returns #FALSE if not enough memory
4431 dbus_connection_register_fallback (DBusConnection *connection,
4433 const DBusObjectPathVTable *vtable,
4436 char **decomposed_path;
4439 _dbus_return_val_if_fail (connection != NULL, FALSE);
4440 _dbus_return_val_if_fail (path != NULL, FALSE);
4441 _dbus_return_val_if_fail (path[0] == '/', FALSE);
4442 _dbus_return_val_if_fail (vtable != NULL, FALSE);
4444 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
4447 CONNECTION_LOCK (connection);
4449 retval = _dbus_object_tree_register (connection->objects,
4451 (const char **) decomposed_path, vtable,
4454 CONNECTION_UNLOCK (connection);
4456 dbus_free_string_array (decomposed_path);
4462 * Unregisters the handler registered with exactly the given path.
4463 * It's a bug to call this function for a path that isn't registered.
4464 * Can unregister both fallback paths and object paths.
4466 * @param connection the connection
4467 * @param path a '/' delimited string of path elements
4468 * @returns #FALSE if not enough memory
4471 dbus_connection_unregister_object_path (DBusConnection *connection,
4474 char **decomposed_path;
4476 _dbus_return_val_if_fail (connection != NULL, FALSE);
4477 _dbus_return_val_if_fail (path != NULL, FALSE);
4478 _dbus_return_val_if_fail (path[0] == '/', FALSE);
4480 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
4483 CONNECTION_LOCK (connection);
4485 _dbus_object_tree_unregister_and_unlock (connection->objects, (const char **) decomposed_path);
4487 dbus_free_string_array (decomposed_path);
4493 * Gets the user data passed to dbus_connection_register_object_path()
4494 * or dbus_connection_register_fallback(). If nothing was registered
4495 * at this path, the data is filled in with #NULL.
4497 * @param connection the connection
4498 * @param path the path you registered with
4499 * @param data_p location to store the user data, or #NULL
4500 * @returns #FALSE if not enough memory
4503 dbus_connection_get_object_path_data (DBusConnection *connection,
4507 char **decomposed_path;
4509 _dbus_return_val_if_fail (connection != NULL, FALSE);
4510 _dbus_return_val_if_fail (path != NULL, FALSE);
4511 _dbus_return_val_if_fail (data_p != NULL, FALSE);
4515 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
4518 CONNECTION_LOCK (connection);
4520 *data_p = _dbus_object_tree_get_user_data_unlocked (connection->objects, (const char**) decomposed_path);
4522 CONNECTION_UNLOCK (connection);
4524 dbus_free_string_array (decomposed_path);
4530 * Lists the registered fallback handlers and object path handlers at
4531 * the given parent_path. The returned array should be freed with
4532 * dbus_free_string_array().
4534 * @param connection the connection
4535 * @param parent_path the path to list the child handlers of
4536 * @param child_entries returns #NULL-terminated array of children
4537 * @returns #FALSE if no memory to allocate the child entries
4540 dbus_connection_list_registered (DBusConnection *connection,
4541 const char *parent_path,
4542 char ***child_entries)
4544 char **decomposed_path;
4546 _dbus_return_val_if_fail (connection != NULL, FALSE);
4547 _dbus_return_val_if_fail (parent_path != NULL, FALSE);
4548 _dbus_return_val_if_fail (parent_path[0] == '/', FALSE);
4549 _dbus_return_val_if_fail (child_entries != NULL, FALSE);
4551 if (!_dbus_decompose_path (parent_path, strlen (parent_path), &decomposed_path, NULL))
4554 CONNECTION_LOCK (connection);
4556 retval = _dbus_object_tree_list_registered_and_unlock (connection->objects,
4557 (const char **) decomposed_path,
4559 dbus_free_string_array (decomposed_path);
4564 static DBusDataSlotAllocator slot_allocator;
4565 _DBUS_DEFINE_GLOBAL_LOCK (connection_slots);
4568 * Allocates an integer ID to be used for storing application-specific
4569 * data on any DBusConnection. The allocated ID may then be used
4570 * with dbus_connection_set_data() and dbus_connection_get_data().
4571 * The passed-in slot must be initialized to -1, and is filled in
4572 * with the slot ID. If the passed-in slot is not -1, it's assumed
4573 * to be already allocated, and its refcount is incremented.
4575 * The allocated slot is global, i.e. all DBusConnection objects will
4576 * have a slot with the given integer ID reserved.
4578 * @param slot_p address of a global variable storing the slot
4579 * @returns #FALSE on failure (no memory)
4582 dbus_connection_allocate_data_slot (dbus_int32_t *slot_p)
4584 return _dbus_data_slot_allocator_alloc (&slot_allocator,
4585 _DBUS_LOCK_NAME (connection_slots),
4590 * Deallocates a global ID for connection data slots.
4591 * dbus_connection_get_data() and dbus_connection_set_data() may no
4592 * longer be used with this slot. Existing data stored on existing
4593 * DBusConnection objects will be freed when the connection is
4594 * finalized, but may not be retrieved (and may only be replaced if
4595 * someone else reallocates the slot). When the refcount on the
4596 * passed-in slot reaches 0, it is set to -1.
4598 * @param slot_p address storing the slot to deallocate
4601 dbus_connection_free_data_slot (dbus_int32_t *slot_p)
4603 _dbus_return_if_fail (*slot_p >= 0);
4605 _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
4609 * Stores a pointer on a DBusConnection, along
4610 * with an optional function to be used for freeing
4611 * the data when the data is set again, or when
4612 * the connection is finalized. The slot number
4613 * must have been allocated with dbus_connection_allocate_data_slot().
4615 * @param connection the connection
4616 * @param slot the slot number
4617 * @param data the data to store
4618 * @param free_data_func finalizer function for the data
4619 * @returns #TRUE if there was enough memory to store the data
4622 dbus_connection_set_data (DBusConnection *connection,
4625 DBusFreeFunction free_data_func)
4627 DBusFreeFunction old_free_func;
4631 _dbus_return_val_if_fail (connection != NULL, FALSE);
4632 _dbus_return_val_if_fail (slot >= 0, FALSE);
4634 CONNECTION_LOCK (connection);
4636 retval = _dbus_data_slot_list_set (&slot_allocator,
4637 &connection->slot_list,
4638 slot, data, free_data_func,
4639 &old_free_func, &old_data);
4641 CONNECTION_UNLOCK (connection);
4645 /* Do the actual free outside the connection lock */
4647 (* old_free_func) (old_data);
4654 * Retrieves data previously set with dbus_connection_set_data().
4655 * The slot must still be allocated (must not have been freed).
4657 * @param connection the connection
4658 * @param slot the slot to get data from
4659 * @returns the data, or #NULL if not found
4662 dbus_connection_get_data (DBusConnection *connection,
4667 _dbus_return_val_if_fail (connection != NULL, NULL);
4669 CONNECTION_LOCK (connection);
4671 res = _dbus_data_slot_list_get (&slot_allocator,
4672 &connection->slot_list,
4675 CONNECTION_UNLOCK (connection);
4681 * This function sets a global flag for whether dbus_connection_new()
4682 * will set SIGPIPE behavior to SIG_IGN.
4684 * @param will_modify_sigpipe #TRUE to allow sigpipe to be set to SIG_IGN
4687 dbus_connection_set_change_sigpipe (dbus_bool_t will_modify_sigpipe)
4689 _dbus_modify_sigpipe = will_modify_sigpipe != FALSE;
4693 * Specifies the maximum size message this connection is allowed to
4694 * receive. Larger messages will result in disconnecting the
4697 * @param connection a #DBusConnection
4698 * @param size maximum message size the connection can receive, in bytes
4701 dbus_connection_set_max_message_size (DBusConnection *connection,
4704 _dbus_return_if_fail (connection != NULL);
4706 CONNECTION_LOCK (connection);
4707 _dbus_transport_set_max_message_size (connection->transport,
4709 CONNECTION_UNLOCK (connection);
4713 * Gets the value set by dbus_connection_set_max_message_size().
4715 * @param connection the connection
4716 * @returns the max size of a single message
4719 dbus_connection_get_max_message_size (DBusConnection *connection)
4723 _dbus_return_val_if_fail (connection != NULL, 0);
4725 CONNECTION_LOCK (connection);
4726 res = _dbus_transport_get_max_message_size (connection->transport);
4727 CONNECTION_UNLOCK (connection);
4732 * Sets the maximum total number of bytes that can be used for all messages
4733 * received on this connection. Messages count toward the maximum until
4734 * they are finalized. When the maximum is reached, the connection will
4735 * not read more data until some messages are finalized.
4737 * The semantics of the maximum are: if outstanding messages are
4738 * already above the maximum, additional messages will not be read.
4739 * The semantics are not: if the next message would cause us to exceed
4740 * the maximum, we don't read it. The reason is that we don't know the
4741 * size of a message until after we read it.
4743 * Thus, the max live messages size can actually be exceeded
4744 * by up to the maximum size of a single message.
4746 * Also, if we read say 1024 bytes off the wire in a single read(),
4747 * and that contains a half-dozen small messages, we may exceed the
4748 * size max by that amount. But this should be inconsequential.
4750 * This does imply that we can't call read() with a buffer larger
4751 * than we're willing to exceed this limit by.
4753 * @param connection the connection
4754 * @param size the maximum size in bytes of all outstanding messages
4757 dbus_connection_set_max_received_size (DBusConnection *connection,
4760 _dbus_return_if_fail (connection != NULL);
4762 CONNECTION_LOCK (connection);
4763 _dbus_transport_set_max_received_size (connection->transport,
4765 CONNECTION_UNLOCK (connection);
4769 * Gets the value set by dbus_connection_set_max_received_size().
4771 * @param connection the connection
4772 * @returns the max size of all live messages
4775 dbus_connection_get_max_received_size (DBusConnection *connection)
4779 _dbus_return_val_if_fail (connection != NULL, 0);
4781 CONNECTION_LOCK (connection);
4782 res = _dbus_transport_get_max_received_size (connection->transport);
4783 CONNECTION_UNLOCK (connection);
4788 * Gets the approximate size in bytes of all messages in the outgoing
4789 * message queue. The size is approximate in that you shouldn't use
4790 * it to decide how many bytes to read off the network or anything
4791 * of that nature, as optimizations may choose to tell small white lies
4792 * to avoid performance overhead.
4794 * @param connection the connection
4795 * @returns the number of bytes that have been queued up but not sent
4798 dbus_connection_get_outgoing_size (DBusConnection *connection)
4802 _dbus_return_val_if_fail (connection != NULL, 0);
4804 CONNECTION_LOCK (connection);
4805 res = _dbus_counter_get_value (connection->outgoing_counter);
4806 CONNECTION_UNLOCK (connection);