1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-connection.c DBusConnection object
4 * Copyright (C) 2002, 2003 Red Hat Inc.
6 * Licensed under the Academic Free License version 1.2
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-connection.h"
26 #include "dbus-list.h"
27 #include "dbus-timeout.h"
28 #include "dbus-transport.h"
29 #include "dbus-watch.h"
30 #include "dbus-connection-internal.h"
31 #include "dbus-list.h"
32 #include "dbus-hash.h"
33 #include "dbus-message-internal.h"
34 #include "dbus-message-handler.h"
35 #include "dbus-threads.h"
36 #include "dbus-protocol.h"
37 #include "dbus-dataslot.h"
38 #include "dbus-object-registry.h"
39 #include "dbus-string.h"
40 #include "dbus-pending-call.h"
43 #define CONNECTION_LOCK(connection) do { \
44 _dbus_verbose (" LOCK: %s\n", _DBUS_FUNCTION_NAME); \
45 dbus_mutex_lock ((connection)->mutex); \
47 #define CONNECTION_UNLOCK(connection) do { \
48 _dbus_verbose (" UNLOCK: %s\n", _DBUS_FUNCTION_NAME); \
49 dbus_mutex_unlock ((connection)->mutex); \
52 #define CONNECTION_LOCK(connection) dbus_mutex_lock ((connection)->mutex)
53 #define CONNECTION_UNLOCK(connection) dbus_mutex_unlock ((connection)->mutex)
57 * @defgroup DBusConnection DBusConnection
59 * @brief Connection to another application
61 * A DBusConnection represents a connection to another
62 * application. Messages can be sent and received via this connection.
63 * The other application may be a message bus; for convenience, the
64 * function dbus_bus_get() is provided to automatically open a
65 * connection to the well-known message buses.
67 * In brief a DBusConnection is a message queue associated with some
68 * message transport mechanism such as a socket. The connection
69 * maintains a queue of incoming messages and a queue of outgoing
72 * Incoming messages are normally processed by calling
73 * dbus_connection_dispatch(). dbus_connection_dispatch() runs any
74 * handlers registered for the topmost message in the message queue,
75 * then discards the message, then returns.
77 * dbus_connection_get_dispatch_status() indicates whether
78 * messages are currently in the queue that need dispatching.
79 * dbus_connection_set_dispatch_status_function() allows
80 * you to set a function to be used to monitor the dispatch status.
82 * If you're using GLib or Qt add-on libraries for D-BUS, there are
83 * special convenience APIs in those libraries that hide
84 * all the details of dispatch and watch/timeout monitoring.
85 * For example, dbus_connection_setup_with_g_main().
87 * If you aren't using these add-on libraries, you have to manually
88 * call dbus_connection_set_dispatch_status_function(),
89 * dbus_connection_set_watch_functions(),
90 * dbus_connection_set_timeout_functions() providing appropriate
91 * functions to integrate the connection with your application's main
94 * When you use dbus_connection_send() or one of its variants to send
95 * a message, the message is added to the outgoing queue. It's
96 * actually written to the network later; either in
97 * dbus_watch_handle() invoked by your main loop, or in
98 * dbus_connection_flush() which blocks until it can write out the
99 * entire outgoing queue. The GLib/Qt add-on libraries again
100 * handle the details here for you by setting up watch functions.
102 * When a connection is disconnected, you are guaranteed to get a
103 * message with the name #DBUS_MESSAGE_LOCAL_DISCONNECT.
105 * You may not drop the last reference to a #DBusConnection
106 * until that connection has been disconnected.
108 * You may dispatch the unprocessed incoming message queue even if the
109 * connection is disconnected. However, #DBUS_MESSAGE_LOCAL_DISCONNECT
110 * will always be the last message in the queue (obviously no messages
111 * are received after disconnection).
113 * #DBusConnection has thread locks and drops them when invoking user
114 * callbacks, so in general is transparently threadsafe. However,
115 * #DBusMessage does NOT have thread locks; you must not send the same
116 * message to multiple #DBusConnection that will be used from
121 * @defgroup DBusConnectionInternals DBusConnection implementation details
122 * @ingroup DBusInternals
123 * @brief Implementation details of DBusConnection
128 static dbus_bool_t _dbus_modify_sigpipe = TRUE;
131 * Implementation details of DBusConnection. All fields are private.
133 struct DBusConnection
135 DBusAtomic refcount; /**< Reference count. */
137 DBusMutex *mutex; /**< Lock on the entire DBusConnection */
139 dbus_bool_t dispatch_acquired; /**< Protects dispatch() */
140 DBusCondVar *dispatch_cond; /**< Protects dispatch() */
142 dbus_bool_t io_path_acquired; /**< Protects transport io path */
143 DBusCondVar *io_path_cond; /**< Protects transport io path */
145 DBusList *outgoing_messages; /**< Queue of messages we need to send, send the end of the list first. */
146 DBusList *incoming_messages; /**< Queue of messages we have received, end of the list received most recently. */
148 DBusMessage *message_borrowed; /**< True if the first incoming message has been borrowed */
149 DBusCondVar *message_returned_cond; /**< Used with dbus_connection_borrow_message() */
151 int n_outgoing; /**< Length of outgoing queue. */
152 int n_incoming; /**< Length of incoming queue. */
154 DBusCounter *outgoing_counter; /**< Counts size of outgoing messages. */
156 DBusTransport *transport; /**< Object that sends/receives messages over network. */
157 DBusWatchList *watches; /**< Stores active watches. */
158 DBusTimeoutList *timeouts; /**< Stores active timeouts. */
160 DBusList *filter_list; /**< List of filters. */
162 DBusDataSlotList slot_list; /**< Data stored by allocated integer ID */
164 DBusHashTable *pending_replies; /**< Hash of message serials to #DBusPendingCall. */
166 dbus_uint32_t client_serial; /**< Client serial. Increments each time a message is sent */
167 DBusList *disconnect_message_link; /**< Preallocated list node for queueing the disconnection message */
169 DBusWakeupMainFunction wakeup_main_function; /**< Function to wake up the mainloop */
170 void *wakeup_main_data; /**< Application data for wakeup_main_function */
171 DBusFreeFunction free_wakeup_main_data; /**< free wakeup_main_data */
173 DBusDispatchStatusFunction dispatch_status_function; /**< Function on dispatch status changes */
174 void *dispatch_status_data; /**< Application data for dispatch_status_function */
175 DBusFreeFunction free_dispatch_status_data; /**< free dispatch_status_data */
177 DBusDispatchStatus last_dispatch_status; /**< The last dispatch status we reported to the application. */
179 DBusList *link_cache; /**< A cache of linked list links to prevent contention
180 * for the global linked list mempool lock
182 DBusObjectRegistry *objects; /**< Objects registered with this connection */
185 static void _dbus_connection_remove_timeout_locked (DBusConnection *connection,
186 DBusTimeout *timeout);
187 static DBusDispatchStatus _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection);
188 static void _dbus_connection_update_dispatch_status_and_unlock (DBusConnection *connection,
189 DBusDispatchStatus new_status);
190 static void _dbus_connection_last_unref (DBusConnection *connection);
194 * Acquires the connection lock.
196 * @param connection the connection.
199 _dbus_connection_lock (DBusConnection *connection)
201 CONNECTION_LOCK (connection);
205 * Releases the connection lock.
207 * @param connection the connection.
210 _dbus_connection_unlock (DBusConnection *connection)
212 CONNECTION_UNLOCK (connection);
216 * Wakes up the main loop if it is sleeping
217 * Needed if we're e.g. queueing outgoing messages
218 * on a thread while the mainloop sleeps.
220 * @param connection the connection.
223 _dbus_connection_wakeup_mainloop (DBusConnection *connection)
225 if (connection->wakeup_main_function)
226 (*connection->wakeup_main_function) (connection->wakeup_main_data);
229 #ifdef DBUS_BUILD_TESTS
230 /* For now this function isn't used */
232 * Adds a message to the incoming message queue, returning #FALSE
233 * if there's insufficient memory to queue the message.
234 * Does not take over refcount of the message.
236 * @param connection the connection.
237 * @param message the message to queue.
238 * @returns #TRUE on success.
241 _dbus_connection_queue_received_message (DBusConnection *connection,
242 DBusMessage *message)
246 link = _dbus_list_alloc_link (message);
250 dbus_message_ref (message);
251 _dbus_connection_queue_received_message_link (connection, link);
258 * Adds a message-containing list link to the incoming message queue,
259 * taking ownership of the link and the message's current refcount.
260 * Cannot fail due to lack of memory.
262 * @param connection the connection.
263 * @param link the message link to queue.
266 _dbus_connection_queue_received_message_link (DBusConnection *connection,
269 DBusPendingCall *pending;
270 dbus_int32_t reply_serial;
271 DBusMessage *message;
273 _dbus_assert (_dbus_transport_get_is_authenticated (connection->transport));
275 _dbus_list_append_link (&connection->incoming_messages,
277 message = link->data;
279 /* If this is a reply we're waiting on, remove timeout for it */
280 reply_serial = dbus_message_get_reply_serial (message);
281 if (reply_serial != -1)
283 pending = _dbus_hash_table_lookup_int (connection->pending_replies,
287 if (pending->timeout_added)
288 _dbus_connection_remove_timeout_locked (connection,
291 pending->timeout_added = FALSE;
295 connection->n_incoming += 1;
297 _dbus_connection_wakeup_mainloop (connection);
299 _dbus_assert (dbus_message_get_name (message) != NULL);
300 _dbus_verbose ("Message %p (%s) added to incoming queue %p, %d incoming\n",
301 message, dbus_message_get_name (message),
303 connection->n_incoming);
307 * Adds a link + message to the incoming message queue.
308 * Can't fail. Takes ownership of both link and message.
310 * @param connection the connection.
311 * @param link the list node and message to queue.
313 * @todo This needs to wake up the mainloop if it is in
314 * a poll/select and this is a multithreaded app.
317 _dbus_connection_queue_synthesized_message_link (DBusConnection *connection,
320 _dbus_list_append_link (&connection->incoming_messages, link);
322 connection->n_incoming += 1;
324 _dbus_connection_wakeup_mainloop (connection);
326 _dbus_verbose ("Synthesized message %p added to incoming queue %p, %d incoming\n",
327 link->data, connection, connection->n_incoming);
332 * Checks whether there are messages in the outgoing message queue.
334 * @param connection the connection.
335 * @returns #TRUE if the outgoing queue is non-empty.
338 _dbus_connection_have_messages_to_send (DBusConnection *connection)
340 return connection->outgoing_messages != NULL;
344 * Gets the next outgoing message. The message remains in the
345 * queue, and the caller does not own a reference to it.
347 * @param connection the connection.
348 * @returns the message to be sent.
351 _dbus_connection_get_message_to_send (DBusConnection *connection)
353 return _dbus_list_get_last (&connection->outgoing_messages);
357 * Notifies the connection that a message has been sent, so the
358 * message can be removed from the outgoing queue.
359 * Called with the connection lock held.
361 * @param connection the connection.
362 * @param message the message that was sent.
365 _dbus_connection_message_sent (DBusConnection *connection,
366 DBusMessage *message)
370 _dbus_assert (_dbus_transport_get_is_authenticated (connection->transport));
372 link = _dbus_list_get_last_link (&connection->outgoing_messages);
373 _dbus_assert (link != NULL);
374 _dbus_assert (link->data == message);
376 /* Save this link in the link cache */
377 _dbus_list_unlink (&connection->outgoing_messages,
379 _dbus_list_prepend_link (&connection->link_cache, link);
381 connection->n_outgoing -= 1;
383 _dbus_verbose ("Message %p (%s) removed from outgoing queue %p, %d left to send\n",
384 message, dbus_message_get_name (message),
385 connection, connection->n_outgoing);
387 /* Save this link in the link cache also */
388 _dbus_message_remove_size_counter (message, connection->outgoing_counter,
390 _dbus_list_prepend_link (&connection->link_cache, link);
392 dbus_message_unref (message);
394 if (connection->n_outgoing == 0)
395 _dbus_transport_messages_pending (connection->transport,
396 connection->n_outgoing);
400 * Adds a watch using the connection's DBusAddWatchFunction if
401 * available. Otherwise records the watch to be added when said
402 * function is available. Also re-adds the watch if the
403 * DBusAddWatchFunction changes. May fail due to lack of memory.
405 * @param connection the connection.
406 * @param watch the watch to add.
407 * @returns #TRUE on success.
410 _dbus_connection_add_watch (DBusConnection *connection,
413 if (connection->watches) /* null during finalize */
414 return _dbus_watch_list_add_watch (connection->watches,
421 * Removes a watch using the connection's DBusRemoveWatchFunction
422 * if available. It's an error to call this function on a watch
423 * that was not previously added.
425 * @param connection the connection.
426 * @param watch the watch to remove.
429 _dbus_connection_remove_watch (DBusConnection *connection,
432 if (connection->watches) /* null during finalize */
433 _dbus_watch_list_remove_watch (connection->watches,
438 * Toggles a watch and notifies app via connection's
439 * DBusWatchToggledFunction if available. It's an error to call this
440 * function on a watch that was not previously added.
442 * @param connection the connection.
443 * @param watch the watch to toggle.
444 * @param enabled whether to enable or disable
447 _dbus_connection_toggle_watch (DBusConnection *connection,
451 if (connection->watches) /* null during finalize */
452 _dbus_watch_list_toggle_watch (connection->watches,
457 * Adds a timeout using the connection's DBusAddTimeoutFunction if
458 * available. Otherwise records the timeout to be added when said
459 * function is available. Also re-adds the timeout if the
460 * DBusAddTimeoutFunction changes. May fail due to lack of memory.
461 * The timeout will fire repeatedly until removed.
463 * @param connection the connection.
464 * @param timeout the timeout to add.
465 * @returns #TRUE on success.
468 _dbus_connection_add_timeout (DBusConnection *connection,
469 DBusTimeout *timeout)
471 if (connection->timeouts) /* null during finalize */
472 return _dbus_timeout_list_add_timeout (connection->timeouts,
479 * Removes a timeout using the connection's DBusRemoveTimeoutFunction
480 * if available. It's an error to call this function on a timeout
481 * that was not previously added.
483 * @param connection the connection.
484 * @param timeout the timeout to remove.
487 _dbus_connection_remove_timeout (DBusConnection *connection,
488 DBusTimeout *timeout)
490 if (connection->timeouts) /* null during finalize */
491 _dbus_timeout_list_remove_timeout (connection->timeouts,
496 _dbus_connection_remove_timeout_locked (DBusConnection *connection,
497 DBusTimeout *timeout)
499 CONNECTION_LOCK (connection);
500 _dbus_connection_remove_timeout (connection, timeout);
501 CONNECTION_UNLOCK (connection);
505 * Toggles a timeout and notifies app via connection's
506 * DBusTimeoutToggledFunction if available. It's an error to call this
507 * function on a timeout that was not previously added.
509 * @param connection the connection.
510 * @param timeout the timeout to toggle.
511 * @param enabled whether to enable or disable
514 _dbus_connection_toggle_timeout (DBusConnection *connection,
515 DBusTimeout *timeout,
518 if (connection->timeouts) /* null during finalize */
519 _dbus_timeout_list_toggle_timeout (connection->timeouts,
524 * Tells the connection that the transport has been disconnected.
525 * Results in posting a disconnect message on the incoming message
526 * queue. Only has an effect the first time it's called.
528 * @param connection the connection
531 _dbus_connection_notify_disconnected (DBusConnection *connection)
533 if (connection->disconnect_message_link)
535 /* We haven't sent the disconnect message already */
536 _dbus_connection_queue_synthesized_message_link (connection,
537 connection->disconnect_message_link);
538 connection->disconnect_message_link = NULL;
543 _dbus_connection_attach_pending_call_unlocked (DBusConnection *connection,
544 DBusPendingCall *pending)
546 _dbus_assert (pending->reply_serial != 0);
548 if (!_dbus_connection_add_timeout (connection, pending->timeout))
551 if (!_dbus_hash_table_insert_int (connection->pending_replies,
552 pending->reply_serial,
555 _dbus_connection_remove_timeout (connection, pending->timeout);
559 pending->timeout_added = TRUE;
560 pending->connection = connection;
562 dbus_pending_call_ref (pending);
568 free_pending_call_on_hash_removal (void *data)
570 DBusPendingCall *pending;
577 if (pending->connection)
579 if (pending->timeout_added)
581 _dbus_connection_remove_timeout (pending->connection,
583 pending->timeout_added = FALSE;
586 pending->connection = NULL;
588 dbus_pending_call_unref (pending);
593 _dbus_connection_detach_pending_call_and_unlock (DBusConnection *connection,
594 DBusPendingCall *pending)
596 /* The idea here is to avoid finalizing the pending call
597 * with the lock held, since there's a destroy notifier
598 * in pending call that goes out to application code.
600 dbus_pending_call_ref (pending);
601 _dbus_hash_table_remove_int (connection->pending_replies,
602 pending->reply_serial);
603 CONNECTION_UNLOCK (connection);
604 dbus_pending_call_unref (pending);
608 * Removes a pending call from the connection, such that
609 * the pending reply will be ignored. May drop the last
610 * reference to the pending call.
612 * @param connection the connection
613 * @param pending the pending call
616 _dbus_connection_remove_pending_call (DBusConnection *connection,
617 DBusPendingCall *pending)
619 CONNECTION_LOCK (connection);
620 _dbus_connection_detach_pending_call_and_unlock (connection, pending);
624 * Completes a pending call with the given message,
625 * or if the message is #NULL, by timing out the pending call.
627 * @param pending the pending call
628 * @param message the message to complete the call with, or #NULL
629 * to time out the call
632 _dbus_pending_call_complete_and_unlock (DBusPendingCall *pending,
633 DBusMessage *message)
637 message = pending->timeout_link->data;
638 _dbus_list_clear (&pending->timeout_link);
641 _dbus_verbose (" handing message %p to pending call\n", message);
643 _dbus_assert (pending->reply == NULL);
644 pending->reply = message;
645 dbus_message_ref (pending->reply);
647 dbus_pending_call_ref (pending); /* in case there's no app with a ref held */
648 _dbus_connection_detach_pending_call_and_unlock (pending->connection, pending);
650 /* Must be called unlocked since it invokes app callback */
651 _dbus_pending_call_notify (pending);
652 dbus_pending_call_unref (pending);
656 * Acquire the transporter I/O path. This must be done before
657 * doing any I/O in the transporter. May sleep and drop the
658 * connection mutex while waiting for the I/O path.
660 * @param connection the connection.
661 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
662 * @returns TRUE if the I/O path was acquired.
665 _dbus_connection_acquire_io_path (DBusConnection *connection,
666 int timeout_milliseconds)
668 dbus_bool_t res = TRUE;
670 if (connection->io_path_acquired)
672 if (timeout_milliseconds != -1)
673 res = dbus_condvar_wait_timeout (connection->io_path_cond,
675 timeout_milliseconds);
677 dbus_condvar_wait (connection->io_path_cond, connection->mutex);
682 _dbus_assert (!connection->io_path_acquired);
684 connection->io_path_acquired = TRUE;
691 * Release the I/O path when you're done with it. Only call
692 * after you've acquired the I/O. Wakes up at most one thread
693 * currently waiting to acquire the I/O path.
695 * @param connection the connection.
698 _dbus_connection_release_io_path (DBusConnection *connection)
700 _dbus_assert (connection->io_path_acquired);
702 connection->io_path_acquired = FALSE;
703 dbus_condvar_wake_one (connection->io_path_cond);
708 * Queues incoming messages and sends outgoing messages for this
709 * connection, optionally blocking in the process. Each call to
710 * _dbus_connection_do_iteration() will call select() or poll() one
711 * time and then read or write data if possible.
713 * The purpose of this function is to be able to flush outgoing
714 * messages or queue up incoming messages without returning
715 * control to the application and causing reentrancy weirdness.
717 * The flags parameter allows you to specify whether to
718 * read incoming messages, write outgoing messages, or both,
719 * and whether to block if no immediate action is possible.
721 * The timeout_milliseconds parameter does nothing unless the
722 * iteration is blocking.
724 * If there are no outgoing messages and DBUS_ITERATION_DO_READING
725 * wasn't specified, then it's impossible to block, even if
726 * you specify DBUS_ITERATION_BLOCK; in that case the function
727 * returns immediately.
729 * @param connection the connection.
730 * @param flags iteration flags.
731 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
734 _dbus_connection_do_iteration (DBusConnection *connection,
736 int timeout_milliseconds)
738 if (connection->n_outgoing == 0)
739 flags &= ~DBUS_ITERATION_DO_WRITING;
741 if (_dbus_connection_acquire_io_path (connection,
742 (flags & DBUS_ITERATION_BLOCK) ? timeout_milliseconds : 0))
744 _dbus_transport_do_iteration (connection->transport,
745 flags, timeout_milliseconds);
746 _dbus_connection_release_io_path (connection);
751 * Creates a new connection for the given transport. A transport
752 * represents a message stream that uses some concrete mechanism, such
753 * as UNIX domain sockets. May return #NULL if insufficient
754 * memory exists to create the connection.
756 * @param transport the transport.
757 * @returns the new connection, or #NULL on failure.
760 _dbus_connection_new_for_transport (DBusTransport *transport)
762 DBusConnection *connection;
763 DBusWatchList *watch_list;
764 DBusTimeoutList *timeout_list;
765 DBusHashTable *pending_replies;
767 DBusCondVar *message_returned_cond;
768 DBusCondVar *dispatch_cond;
769 DBusCondVar *io_path_cond;
770 DBusList *disconnect_link;
771 DBusMessage *disconnect_message;
772 DBusCounter *outgoing_counter;
773 DBusObjectRegistry *objects;
777 pending_replies = NULL;
780 message_returned_cond = NULL;
781 dispatch_cond = NULL;
783 disconnect_link = NULL;
784 disconnect_message = NULL;
785 outgoing_counter = NULL;
788 watch_list = _dbus_watch_list_new ();
789 if (watch_list == NULL)
792 timeout_list = _dbus_timeout_list_new ();
793 if (timeout_list == NULL)
797 _dbus_hash_table_new (DBUS_HASH_INT,
799 (DBusFreeFunction)free_pending_call_on_hash_removal);
800 if (pending_replies == NULL)
803 connection = dbus_new0 (DBusConnection, 1);
804 if (connection == NULL)
807 mutex = dbus_mutex_new ();
811 message_returned_cond = dbus_condvar_new ();
812 if (message_returned_cond == NULL)
815 dispatch_cond = dbus_condvar_new ();
816 if (dispatch_cond == NULL)
819 io_path_cond = dbus_condvar_new ();
820 if (io_path_cond == NULL)
823 disconnect_message = dbus_message_new_signal (DBUS_MESSAGE_LOCAL_DISCONNECT);
824 if (disconnect_message == NULL)
827 disconnect_link = _dbus_list_alloc_link (disconnect_message);
828 if (disconnect_link == NULL)
831 outgoing_counter = _dbus_counter_new ();
832 if (outgoing_counter == NULL)
835 objects = _dbus_object_registry_new (connection);
839 if (_dbus_modify_sigpipe)
840 _dbus_disable_sigpipe ();
842 connection->refcount.value = 1;
843 connection->mutex = mutex;
844 connection->dispatch_cond = dispatch_cond;
845 connection->io_path_cond = io_path_cond;
846 connection->message_returned_cond = message_returned_cond;
847 connection->transport = transport;
848 connection->watches = watch_list;
849 connection->timeouts = timeout_list;
850 connection->pending_replies = pending_replies;
851 connection->outgoing_counter = outgoing_counter;
852 connection->filter_list = NULL;
853 connection->last_dispatch_status = DBUS_DISPATCH_COMPLETE; /* so we're notified first time there's data */
854 connection->objects = objects;
856 _dbus_data_slot_list_init (&connection->slot_list);
858 connection->client_serial = 1;
860 connection->disconnect_message_link = disconnect_link;
862 if (!_dbus_transport_set_connection (transport, connection))
865 _dbus_transport_ref (transport);
870 if (disconnect_message != NULL)
871 dbus_message_unref (disconnect_message);
873 if (disconnect_link != NULL)
874 _dbus_list_free_link (disconnect_link);
876 if (io_path_cond != NULL)
877 dbus_condvar_free (io_path_cond);
879 if (dispatch_cond != NULL)
880 dbus_condvar_free (dispatch_cond);
882 if (message_returned_cond != NULL)
883 dbus_condvar_free (message_returned_cond);
886 dbus_mutex_free (mutex);
888 if (connection != NULL)
889 dbus_free (connection);
892 _dbus_hash_table_unref (pending_replies);
895 _dbus_watch_list_free (watch_list);
898 _dbus_timeout_list_free (timeout_list);
900 if (outgoing_counter)
901 _dbus_counter_unref (outgoing_counter);
904 _dbus_object_registry_unref (objects);
910 * Increments the reference count of a DBusConnection.
911 * Requires that the caller already holds the connection lock.
913 * @param connection the connection.
916 _dbus_connection_ref_unlocked (DBusConnection *connection)
918 #ifdef DBUS_HAVE_ATOMIC_INT
919 _dbus_atomic_inc (&connection->refcount);
921 _dbus_assert (connection->refcount.value > 0);
922 connection->refcount.value += 1;
927 * Decrements the reference count of a DBusConnection.
928 * Requires that the caller already holds the connection lock.
930 * @param connection the connection.
933 _dbus_connection_unref_unlocked (DBusConnection *connection)
935 dbus_bool_t last_unref;
937 _dbus_return_if_fail (connection != NULL);
939 /* The connection lock is better than the global
940 * lock in the atomic increment fallback
943 #ifdef DBUS_HAVE_ATOMIC_INT
944 last_unref = (_dbus_atomic_dec (&connection->refcount) == 1);
946 _dbus_assert (connection->refcount.value > 0);
948 connection->refcount.value -= 1;
949 last_unref = (connection->refcount.value == 0);
951 printf ("unref_unlocked() connection %p count = %d\n", connection, connection->refcount.value);
956 _dbus_connection_last_unref (connection);
960 _dbus_connection_get_next_client_serial (DBusConnection *connection)
964 serial = connection->client_serial++;
966 if (connection->client_serial < 0)
967 connection->client_serial = 1;
973 * Used to notify a connection when a DBusMessageHandler is
974 * destroyed, so the connection can drop any reference
975 * to the handler. This is a private function, but still
976 * takes the connection lock. Don't call it with the lock held.
978 * @todo needs to check in pending_replies too.
980 * @param connection the connection
981 * @param handler the handler
984 _dbus_connection_handler_destroyed_locked (DBusConnection *connection,
985 DBusMessageHandler *handler)
989 CONNECTION_LOCK (connection);
991 link = _dbus_list_get_first_link (&connection->filter_list);
994 DBusMessageHandler *h = link->data;
995 DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
998 _dbus_list_remove_link (&connection->filter_list,
1003 CONNECTION_UNLOCK (connection);
1007 * A callback for use with dbus_watch_new() to create a DBusWatch.
1009 * @todo This is basically a hack - we could delete _dbus_transport_handle_watch()
1010 * and the virtual handle_watch in DBusTransport if we got rid of it.
1011 * The reason this is some work is threading, see the _dbus_connection_handle_watch()
1014 * @param watch the watch.
1015 * @param condition the current condition of the file descriptors being watched.
1016 * @param data must be a pointer to a #DBusConnection
1017 * @returns #FALSE if the IO condition may not have been fully handled due to lack of memory
1020 _dbus_connection_handle_watch (DBusWatch *watch,
1021 unsigned int condition,
1024 DBusConnection *connection;
1026 DBusDispatchStatus status;
1030 CONNECTION_LOCK (connection);
1031 _dbus_connection_acquire_io_path (connection, -1);
1032 retval = _dbus_transport_handle_watch (connection->transport,
1034 _dbus_connection_release_io_path (connection);
1036 status = _dbus_connection_get_dispatch_status_unlocked (connection);
1038 /* this calls out to user code */
1039 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1045 * Get the server ID to be used in the object ID for an object
1046 * registered with this connection.
1048 * @todo implement this function
1050 * @param connection the connection.
1051 * @returns the portion of the object ID
1054 _dbus_connection_init_id (DBusConnection *connection,
1055 DBusObjectID *object_id)
1058 dbus_object_id_set_server_bits (object_id, 15);
1059 dbus_object_id_set_client_bits (object_id, 31);
1060 dbus_object_id_set_is_server_bit (object_id, FALSE);
1066 * @addtogroup DBusConnection
1072 * Opens a new connection to a remote address.
1074 * @todo specify what the address parameter is. Right now
1075 * it's just the name of a UNIX domain socket. It should be
1076 * something more complex that encodes which transport to use.
1078 * If the open fails, the function returns #NULL, and provides
1079 * a reason for the failure in the result parameter. Pass
1080 * #NULL for the result parameter if you aren't interested
1081 * in the reason for failure.
1083 * @param address the address.
1084 * @param error address where an error can be returned.
1085 * @returns new connection, or #NULL on failure.
1088 dbus_connection_open (const char *address,
1091 DBusConnection *connection;
1092 DBusTransport *transport;
1094 _dbus_return_val_if_fail (address != NULL, NULL);
1095 _dbus_return_val_if_error_is_set (error, NULL);
1097 transport = _dbus_transport_open (address, error);
1098 if (transport == NULL)
1100 _DBUS_ASSERT_ERROR_IS_SET (error);
1104 connection = _dbus_connection_new_for_transport (transport);
1106 _dbus_transport_unref (transport);
1108 if (connection == NULL)
1110 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1118 * Increments the reference count of a DBusConnection.
1120 * @param connection the connection.
1123 dbus_connection_ref (DBusConnection *connection)
1125 _dbus_return_if_fail (connection != NULL);
1127 /* The connection lock is better than the global
1128 * lock in the atomic increment fallback
1131 #ifdef DBUS_HAVE_ATOMIC_INT
1132 _dbus_atomic_inc (&connection->refcount);
1134 CONNECTION_LOCK (connection);
1135 _dbus_assert (connection->refcount.value > 0);
1137 connection->refcount.value += 1;
1138 CONNECTION_UNLOCK (connection);
1143 free_outgoing_message (void *element,
1146 DBusMessage *message = element;
1147 DBusConnection *connection = data;
1149 _dbus_message_remove_size_counter (message,
1150 connection->outgoing_counter,
1152 dbus_message_unref (message);
1155 /* This is run without the mutex held, but after the last reference
1156 * to the connection has been dropped we should have no thread-related
1160 _dbus_connection_last_unref (DBusConnection *connection)
1164 _dbus_verbose ("Finalizing connection %p\n", connection);
1166 _dbus_assert (connection->refcount.value == 0);
1168 /* You have to disconnect the connection before unref:ing it. Otherwise
1169 * you won't get the disconnected message.
1171 _dbus_assert (!_dbus_transport_get_is_connected (connection->transport));
1173 /* ---- We're going to call various application callbacks here, hope it doesn't break anything... */
1174 _dbus_object_registry_free_all_unlocked (connection->objects);
1176 dbus_connection_set_dispatch_status_function (connection, NULL, NULL, NULL);
1177 dbus_connection_set_wakeup_main_function (connection, NULL, NULL, NULL);
1178 dbus_connection_set_unix_user_function (connection, NULL, NULL, NULL);
1180 _dbus_watch_list_free (connection->watches);
1181 connection->watches = NULL;
1183 _dbus_timeout_list_free (connection->timeouts);
1184 connection->timeouts = NULL;
1186 _dbus_data_slot_list_free (&connection->slot_list);
1187 /* ---- Done with stuff that invokes application callbacks */
1189 link = _dbus_list_get_first_link (&connection->filter_list);
1190 while (link != NULL)
1192 DBusMessageHandler *h = link->data;
1193 DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
1195 _dbus_message_handler_remove_connection (h, connection);
1200 _dbus_object_registry_unref (connection->objects);
1202 _dbus_hash_table_unref (connection->pending_replies);
1203 connection->pending_replies = NULL;
1205 _dbus_list_clear (&connection->filter_list);
1207 _dbus_list_foreach (&connection->outgoing_messages,
1208 free_outgoing_message,
1210 _dbus_list_clear (&connection->outgoing_messages);
1212 _dbus_list_foreach (&connection->incoming_messages,
1213 (DBusForeachFunction) dbus_message_unref,
1215 _dbus_list_clear (&connection->incoming_messages);
1217 _dbus_counter_unref (connection->outgoing_counter);
1219 _dbus_transport_unref (connection->transport);
1221 if (connection->disconnect_message_link)
1223 DBusMessage *message = connection->disconnect_message_link->data;
1224 dbus_message_unref (message);
1225 _dbus_list_free_link (connection->disconnect_message_link);
1228 _dbus_list_clear (&connection->link_cache);
1230 dbus_condvar_free (connection->dispatch_cond);
1231 dbus_condvar_free (connection->io_path_cond);
1232 dbus_condvar_free (connection->message_returned_cond);
1234 dbus_mutex_free (connection->mutex);
1236 dbus_free (connection);
1240 * Decrements the reference count of a DBusConnection, and finalizes
1241 * it if the count reaches zero. It is a bug to drop the last reference
1242 * to a connection that has not been disconnected.
1244 * @todo in practice it can be quite tricky to never unref a connection
1245 * that's still connected; maybe there's some way we could avoid
1248 * @param connection the connection.
1251 dbus_connection_unref (DBusConnection *connection)
1253 dbus_bool_t last_unref;
1255 _dbus_return_if_fail (connection != NULL);
1257 /* The connection lock is better than the global
1258 * lock in the atomic increment fallback
1261 #ifdef DBUS_HAVE_ATOMIC_INT
1262 last_unref = (_dbus_atomic_dec (&connection->refcount) == 1);
1264 CONNECTION_LOCK (connection);
1266 _dbus_assert (connection->refcount.value > 0);
1268 connection->refcount.value -= 1;
1269 last_unref = (connection->refcount.value == 0);
1272 printf ("unref() connection %p count = %d\n", connection, connection->refcount.value);
1275 CONNECTION_UNLOCK (connection);
1279 _dbus_connection_last_unref (connection);
1283 * Closes the connection, so no further data can be sent or received.
1284 * Any further attempts to send data will result in errors. This
1285 * function does not affect the connection's reference count. It's
1286 * safe to disconnect a connection more than once; all calls after the
1287 * first do nothing. It's impossible to "reconnect" a connection, a
1288 * new connection must be created.
1290 * @param connection the connection.
1293 dbus_connection_disconnect (DBusConnection *connection)
1295 _dbus_return_if_fail (connection != NULL);
1297 CONNECTION_LOCK (connection);
1298 _dbus_transport_disconnect (connection->transport);
1299 CONNECTION_UNLOCK (connection);
1303 _dbus_connection_get_is_connected_unlocked (DBusConnection *connection)
1305 return _dbus_transport_get_is_connected (connection->transport);
1309 * Gets whether the connection is currently connected. All
1310 * connections are connected when they are opened. A connection may
1311 * become disconnected when the remote application closes its end, or
1312 * exits; a connection may also be disconnected with
1313 * dbus_connection_disconnect().
1315 * @param connection the connection.
1316 * @returns #TRUE if the connection is still alive.
1319 dbus_connection_get_is_connected (DBusConnection *connection)
1323 _dbus_return_val_if_fail (connection != NULL, FALSE);
1325 CONNECTION_LOCK (connection);
1326 res = _dbus_connection_get_is_connected_unlocked (connection);
1327 CONNECTION_UNLOCK (connection);
1333 * Gets whether the connection was authenticated. (Note that
1334 * if the connection was authenticated then disconnected,
1335 * this function still returns #TRUE)
1337 * @param connection the connection
1338 * @returns #TRUE if the connection was ever authenticated
1341 dbus_connection_get_is_authenticated (DBusConnection *connection)
1345 _dbus_return_val_if_fail (connection != NULL, FALSE);
1347 CONNECTION_LOCK (connection);
1348 res = _dbus_transport_get_is_authenticated (connection->transport);
1349 CONNECTION_UNLOCK (connection);
1354 struct DBusPreallocatedSend
1356 DBusConnection *connection;
1357 DBusList *queue_link;
1358 DBusList *counter_link;
1361 static DBusPreallocatedSend*
1362 _dbus_connection_preallocate_send_unlocked (DBusConnection *connection)
1364 DBusPreallocatedSend *preallocated;
1366 _dbus_return_val_if_fail (connection != NULL, NULL);
1368 preallocated = dbus_new (DBusPreallocatedSend, 1);
1369 if (preallocated == NULL)
1372 if (connection->link_cache != NULL)
1374 preallocated->queue_link =
1375 _dbus_list_pop_first_link (&connection->link_cache);
1376 preallocated->queue_link->data = NULL;
1380 preallocated->queue_link = _dbus_list_alloc_link (NULL);
1381 if (preallocated->queue_link == NULL)
1385 if (connection->link_cache != NULL)
1387 preallocated->counter_link =
1388 _dbus_list_pop_first_link (&connection->link_cache);
1389 preallocated->counter_link->data = connection->outgoing_counter;
1393 preallocated->counter_link = _dbus_list_alloc_link (connection->outgoing_counter);
1394 if (preallocated->counter_link == NULL)
1398 _dbus_counter_ref (preallocated->counter_link->data);
1400 preallocated->connection = connection;
1402 return preallocated;
1405 _dbus_list_free_link (preallocated->queue_link);
1407 dbus_free (preallocated);
1413 * Preallocates resources needed to send a message, allowing the message
1414 * to be sent without the possibility of memory allocation failure.
1415 * Allows apps to create a future guarantee that they can send
1416 * a message regardless of memory shortages.
1418 * @param connection the connection we're preallocating for.
1419 * @returns the preallocated resources, or #NULL
1421 DBusPreallocatedSend*
1422 dbus_connection_preallocate_send (DBusConnection *connection)
1424 DBusPreallocatedSend *preallocated;
1426 _dbus_return_val_if_fail (connection != NULL, NULL);
1428 CONNECTION_LOCK (connection);
1431 _dbus_connection_preallocate_send_unlocked (connection);
1433 CONNECTION_UNLOCK (connection);
1435 return preallocated;
1439 * Frees preallocated message-sending resources from
1440 * dbus_connection_preallocate_send(). Should only
1441 * be called if the preallocated resources are not used
1442 * to send a message.
1444 * @param connection the connection
1445 * @param preallocated the resources
1448 dbus_connection_free_preallocated_send (DBusConnection *connection,
1449 DBusPreallocatedSend *preallocated)
1451 _dbus_return_if_fail (connection != NULL);
1452 _dbus_return_if_fail (preallocated != NULL);
1453 _dbus_return_if_fail (connection == preallocated->connection);
1455 _dbus_list_free_link (preallocated->queue_link);
1456 _dbus_counter_unref (preallocated->counter_link->data);
1457 _dbus_list_free_link (preallocated->counter_link);
1458 dbus_free (preallocated);
1462 _dbus_connection_send_preallocated_unlocked (DBusConnection *connection,
1463 DBusPreallocatedSend *preallocated,
1464 DBusMessage *message,
1465 dbus_uint32_t *client_serial)
1467 dbus_uint32_t serial;
1469 preallocated->queue_link->data = message;
1470 _dbus_list_prepend_link (&connection->outgoing_messages,
1471 preallocated->queue_link);
1473 _dbus_message_add_size_counter_link (message,
1474 preallocated->counter_link);
1476 dbus_free (preallocated);
1477 preallocated = NULL;
1479 dbus_message_ref (message);
1481 connection->n_outgoing += 1;
1483 _dbus_verbose ("Message %p (%s) added to outgoing queue %p, %d pending to send\n",
1485 dbus_message_get_name (message),
1487 connection->n_outgoing);
1489 if (dbus_message_get_serial (message) == 0)
1491 serial = _dbus_connection_get_next_client_serial (connection);
1492 _dbus_message_set_serial (message, serial);
1494 *client_serial = serial;
1499 *client_serial = dbus_message_get_serial (message);
1502 _dbus_message_lock (message);
1504 if (connection->n_outgoing == 1)
1505 _dbus_transport_messages_pending (connection->transport,
1506 connection->n_outgoing);
1508 _dbus_connection_wakeup_mainloop (connection);
1512 * Sends a message using preallocated resources. This function cannot fail.
1513 * It works identically to dbus_connection_send() in other respects.
1514 * Preallocated resources comes from dbus_connection_preallocate_send().
1515 * This function "consumes" the preallocated resources, they need not
1516 * be freed separately.
1518 * @param connection the connection
1519 * @param preallocated the preallocated resources
1520 * @param message the message to send
1521 * @param client_serial return location for client serial assigned to the message
1524 dbus_connection_send_preallocated (DBusConnection *connection,
1525 DBusPreallocatedSend *preallocated,
1526 DBusMessage *message,
1527 dbus_uint32_t *client_serial)
1529 _dbus_return_if_fail (connection != NULL);
1530 _dbus_return_if_fail (preallocated != NULL);
1531 _dbus_return_if_fail (message != NULL);
1532 _dbus_return_if_fail (preallocated->connection == connection);
1533 _dbus_return_if_fail (dbus_message_get_name (message) != NULL);
1535 CONNECTION_LOCK (connection);
1536 _dbus_connection_send_preallocated_unlocked (connection,
1538 message, client_serial);
1539 CONNECTION_UNLOCK (connection);
1543 _dbus_connection_send_unlocked (DBusConnection *connection,
1544 DBusMessage *message,
1545 dbus_uint32_t *client_serial)
1547 DBusPreallocatedSend *preallocated;
1549 _dbus_assert (connection != NULL);
1550 _dbus_assert (message != NULL);
1552 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
1553 if (preallocated == NULL)
1557 _dbus_connection_send_preallocated_unlocked (connection,
1565 * Adds a message to the outgoing message queue. Does not block to
1566 * write the message to the network; that happens asynchronously. To
1567 * force the message to be written, call dbus_connection_flush().
1568 * Because this only queues the message, the only reason it can
1569 * fail is lack of memory. Even if the connection is disconnected,
1570 * no error will be returned.
1572 * If the function fails due to lack of memory, it returns #FALSE.
1573 * The function will never fail for other reasons; even if the
1574 * connection is disconnected, you can queue an outgoing message,
1575 * though obviously it won't be sent.
1577 * @param connection the connection.
1578 * @param message the message to write.
1579 * @param client_serial return location for client serial.
1580 * @returns #TRUE on success.
1583 dbus_connection_send (DBusConnection *connection,
1584 DBusMessage *message,
1585 dbus_uint32_t *client_serial)
1587 _dbus_return_val_if_fail (connection != NULL, FALSE);
1588 _dbus_return_val_if_fail (message != NULL, FALSE);
1590 CONNECTION_LOCK (connection);
1592 if (!_dbus_connection_send_unlocked (connection, message, client_serial))
1594 CONNECTION_UNLOCK (connection);
1598 CONNECTION_UNLOCK (connection);
1603 reply_handler_timeout (void *data)
1605 DBusConnection *connection;
1606 DBusDispatchStatus status;
1607 DBusPendingCall *pending = data;
1609 connection = pending->connection;
1611 CONNECTION_LOCK (connection);
1612 if (pending->timeout_link)
1614 _dbus_connection_queue_synthesized_message_link (connection,
1615 pending->timeout_link);
1616 pending->timeout_link = NULL;
1619 _dbus_connection_remove_timeout (connection,
1621 pending->timeout_added = FALSE;
1623 status = _dbus_connection_get_dispatch_status_unlocked (connection);
1625 /* Unlocks, and calls out to user code */
1626 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1632 * Queues a message to send, as with dbus_connection_send_message(),
1633 * but also returns a #DBusPendingCall used to receive a reply to the
1634 * message. If no reply is received in the given timeout_milliseconds,
1635 * this function expires the pending reply and generates a synthetic
1636 * error reply (generated in-process, not by the remote application)
1637 * indicating that a timeout occurred.
1639 * A #DBusPendingCall will see a reply message after any filters, but
1640 * before any object instances or other handlers. A #DBusPendingCall
1641 * will always see exactly one reply message, unless it's cancelled
1642 * with dbus_pending_call_cancel().
1644 * If a filter filters out the reply before the handler sees it, the
1645 * reply is immediately timed out and a timeout error reply is
1646 * generated. If a filter removes the timeout error reply then the
1647 * #DBusPendingCall will get confused. Filtering the timeout error
1648 * is thus considered a bug and will print a warning.
1650 * If #NULL is passed for the pending_return, the #DBusPendingCall
1651 * will still be generated internally, and used to track
1652 * the message reply timeout. This means a timeout error will
1653 * occur if no reply arrives, unlike with dbus_connection_send().
1655 * If -1 is passed for the timeout, a sane default timeout is used. -1
1656 * is typically the best value for the timeout for this reason, unless
1657 * you want a very short or very long timeout. There is no way to
1658 * avoid a timeout entirely, other than passing INT_MAX for the
1659 * timeout to postpone it indefinitely.
1661 * @param connection the connection
1662 * @param message the message to send
1663 * @param pending_return return location for a #DBusPendingCall object, or #NULL
1664 * @param timeout_milliseconds timeout in milliseconds or -1 for default
1665 * @returns #TRUE if the message is successfully queued, #FALSE if no memory.
1669 dbus_connection_send_with_reply (DBusConnection *connection,
1670 DBusMessage *message,
1671 DBusPendingCall **pending_return,
1672 int timeout_milliseconds)
1674 DBusPendingCall *pending;
1676 DBusList *reply_link;
1677 dbus_int32_t serial = -1;
1679 _dbus_return_val_if_fail (connection != NULL, FALSE);
1680 _dbus_return_val_if_fail (message != NULL, FALSE);
1681 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
1684 *pending_return = NULL;
1686 pending = _dbus_pending_call_new (connection,
1687 timeout_milliseconds,
1688 reply_handler_timeout);
1690 if (pending == NULL)
1693 CONNECTION_LOCK (connection);
1695 /* Assign a serial to the message */
1696 if (dbus_message_get_serial (message) == 0)
1698 serial = _dbus_connection_get_next_client_serial (connection);
1699 _dbus_message_set_serial (message, serial);
1702 pending->reply_serial = serial;
1704 reply = dbus_message_new_error (message, DBUS_ERROR_NO_REPLY,
1705 "No reply within specified time");
1708 CONNECTION_UNLOCK (connection);
1709 dbus_pending_call_unref (pending);
1713 reply_link = _dbus_list_alloc_link (reply);
1716 CONNECTION_UNLOCK (connection);
1717 dbus_message_unref (reply);
1718 dbus_pending_call_unref (pending);
1722 pending->timeout_link = reply_link;
1724 /* Insert the serial in the pending replies hash;
1725 * hash takes a refcount on DBusPendingCall.
1726 * Also, add the timeout.
1728 if (!_dbus_connection_attach_pending_call_unlocked (connection,
1731 CONNECTION_UNLOCK (connection);
1732 dbus_pending_call_unref (pending);
1736 if (!_dbus_connection_send_unlocked (connection, message, NULL))
1738 _dbus_connection_detach_pending_call_and_unlock (connection,
1745 dbus_pending_call_ref (pending);
1746 *pending_return = pending;
1749 CONNECTION_UNLOCK (connection);
1755 check_for_reply_unlocked (DBusConnection *connection,
1756 dbus_uint32_t client_serial)
1760 link = _dbus_list_get_first_link (&connection->incoming_messages);
1762 while (link != NULL)
1764 DBusMessage *reply = link->data;
1766 if (dbus_message_get_reply_serial (reply) == client_serial)
1768 _dbus_list_remove_link (&connection->incoming_messages, link);
1769 connection->n_incoming -= 1;
1770 dbus_message_ref (reply);
1773 link = _dbus_list_get_next_link (&connection->incoming_messages, link);
1780 * Blocks a certain time period while waiting for a reply.
1781 * If no reply arrives, returns #NULL.
1783 * @todo could use performance improvements (it keeps scanning
1784 * the whole message queue for example) and has thread issues,
1785 * see comments in source
1787 * @param connection the connection
1788 * @param client_serial the reply serial to wait for
1789 * @param timeout_milliseconds timeout in milliseconds or -1 for default
1790 * @returns the message that is the reply or #NULL if no reply
1793 _dbus_connection_block_for_reply (DBusConnection *connection,
1794 dbus_uint32_t client_serial,
1795 int timeout_milliseconds)
1797 long start_tv_sec, start_tv_usec;
1798 long end_tv_sec, end_tv_usec;
1799 long tv_sec, tv_usec;
1800 DBusDispatchStatus status;
1802 _dbus_return_val_if_fail (connection != NULL, NULL);
1803 _dbus_return_val_if_fail (client_serial != 0, NULL);
1804 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
1806 if (timeout_milliseconds == -1)
1807 timeout_milliseconds = _DBUS_DEFAULT_TIMEOUT_VALUE;
1809 /* it would probably seem logical to pass in _DBUS_INT_MAX
1810 * for infinite timeout, but then math below would get
1811 * all overflow-prone, so smack that down.
1813 if (timeout_milliseconds > _DBUS_ONE_HOUR_IN_MILLISECONDS * 6)
1814 timeout_milliseconds = _DBUS_ONE_HOUR_IN_MILLISECONDS * 6;
1816 /* Flush message queue */
1817 dbus_connection_flush (connection);
1819 CONNECTION_LOCK (connection);
1821 _dbus_get_current_time (&start_tv_sec, &start_tv_usec);
1822 end_tv_sec = start_tv_sec + timeout_milliseconds / 1000;
1823 end_tv_usec = start_tv_usec + (timeout_milliseconds % 1000) * 1000;
1824 end_tv_sec += end_tv_usec / _DBUS_USEC_PER_SECOND;
1825 end_tv_usec = end_tv_usec % _DBUS_USEC_PER_SECOND;
1827 _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",
1828 timeout_milliseconds,
1830 start_tv_sec, start_tv_usec,
1831 end_tv_sec, end_tv_usec);
1833 /* Now we wait... */
1834 /* THREAD TODO: This is busted. What if a dispatch() or pop_message
1835 * gets the message before we do?
1837 /* always block at least once as we know we don't have the reply yet */
1838 _dbus_connection_do_iteration (connection,
1839 DBUS_ITERATION_DO_READING |
1840 DBUS_ITERATION_BLOCK,
1841 timeout_milliseconds);
1845 /* queue messages and get status */
1846 status = _dbus_connection_get_dispatch_status_unlocked (connection);
1848 if (status == DBUS_DISPATCH_DATA_REMAINS)
1852 reply = check_for_reply_unlocked (connection, client_serial);
1855 status = _dbus_connection_get_dispatch_status_unlocked (connection);
1857 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): got reply %s\n",
1858 dbus_message_get_name (reply));
1860 /* Unlocks, and calls out to user code */
1861 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1867 _dbus_get_current_time (&tv_sec, &tv_usec);
1869 if (tv_sec < start_tv_sec)
1870 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): clock set backward\n");
1871 else if (connection->disconnect_message_link == NULL)
1872 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): disconnected\n");
1873 else if (tv_sec < end_tv_sec ||
1874 (tv_sec == end_tv_sec && tv_usec < end_tv_usec))
1876 timeout_milliseconds = (end_tv_sec - tv_sec) * 1000 +
1877 (end_tv_usec - tv_usec) / 1000;
1878 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): %d milliseconds remain\n", timeout_milliseconds);
1879 _dbus_assert (timeout_milliseconds >= 0);
1881 if (status == DBUS_DISPATCH_NEED_MEMORY)
1883 /* Try sleeping a bit, as we aren't sure we need to block for reading,
1884 * we may already have a reply in the buffer and just can't process
1887 _dbus_verbose ("dbus_connection_send_with_reply_and_block() waiting for more memory\n");
1889 if (timeout_milliseconds < 100)
1890 ; /* just busy loop */
1891 else if (timeout_milliseconds <= 1000)
1892 _dbus_sleep_milliseconds (timeout_milliseconds / 3);
1894 _dbus_sleep_milliseconds (1000);
1898 /* block again, we don't have the reply buffered yet. */
1899 _dbus_connection_do_iteration (connection,
1900 DBUS_ITERATION_DO_READING |
1901 DBUS_ITERATION_BLOCK,
1902 timeout_milliseconds);
1905 goto recheck_status;
1908 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): Waited %ld milliseconds and got no reply\n",
1909 (tv_sec - start_tv_sec) * 1000 + (tv_usec - start_tv_usec) / 1000);
1911 /* unlocks and calls out to user code */
1912 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1918 * Sends a message and blocks a certain time period while waiting for
1919 * a reply. This function does not reenter the main loop,
1920 * i.e. messages other than the reply are queued up but not
1921 * processed. This function is used to do non-reentrant "method
1924 * If a normal reply is received, it is returned, and removed from the
1925 * incoming message queue. If it is not received, #NULL is returned
1926 * and the error is set to #DBUS_ERROR_NO_REPLY. If an error reply is
1927 * received, it is converted to a #DBusError and returned as an error,
1928 * then the reply message is deleted. If something else goes wrong,
1929 * result is set to whatever is appropriate, such as
1930 * #DBUS_ERROR_NO_MEMORY or #DBUS_ERROR_DISCONNECTED.
1932 * @param connection the connection
1933 * @param message the message to send
1934 * @param timeout_milliseconds timeout in milliseconds or -1 for default
1935 * @param error return location for error message
1936 * @returns the message that is the reply or #NULL with an error code if the
1940 dbus_connection_send_with_reply_and_block (DBusConnection *connection,
1941 DBusMessage *message,
1942 int timeout_milliseconds,
1945 dbus_uint32_t client_serial;
1948 _dbus_return_val_if_fail (connection != NULL, NULL);
1949 _dbus_return_val_if_fail (message != NULL, NULL);
1950 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
1951 _dbus_return_val_if_error_is_set (error, NULL);
1953 if (!dbus_connection_send (connection, message, &client_serial))
1955 _DBUS_SET_OOM (error);
1959 reply = _dbus_connection_block_for_reply (connection,
1961 timeout_milliseconds);
1965 if (dbus_connection_get_is_connected (connection))
1966 dbus_set_error (error, DBUS_ERROR_NO_REPLY, "Message did not receive a reply");
1968 dbus_set_error (error, DBUS_ERROR_DISCONNECTED, "Disconnected prior to receiving a reply");
1972 else if (dbus_set_error_from_message (error, reply))
1974 dbus_message_unref (reply);
1982 * Blocks until the outgoing message queue is empty.
1984 * @param connection the connection.
1987 dbus_connection_flush (DBusConnection *connection)
1989 /* We have to specify DBUS_ITERATION_DO_READING here because
1990 * otherwise we could have two apps deadlock if they are both doing
1991 * a flush(), and the kernel buffers fill up. This could change the
1994 DBusDispatchStatus status;
1996 _dbus_return_if_fail (connection != NULL);
1998 CONNECTION_LOCK (connection);
1999 while (connection->n_outgoing > 0 &&
2000 _dbus_connection_get_is_connected_unlocked (connection))
2001 _dbus_connection_do_iteration (connection,
2002 DBUS_ITERATION_DO_READING |
2003 DBUS_ITERATION_DO_WRITING |
2004 DBUS_ITERATION_BLOCK,
2007 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2009 /* Unlocks and calls out to user code */
2010 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2013 /* Call with mutex held. Will drop it while waiting and re-acquire
2017 _dbus_connection_wait_for_borrowed (DBusConnection *connection)
2019 _dbus_assert (connection->message_borrowed != NULL);
2021 while (connection->message_borrowed != NULL)
2022 dbus_condvar_wait (connection->message_returned_cond, connection->mutex);
2026 * Returns the first-received message from the incoming message queue,
2027 * leaving it in the queue. If the queue is empty, returns #NULL.
2029 * The caller does not own a reference to the returned message, and
2030 * must either return it using dbus_connection_return_message() or
2031 * keep it after calling dbus_connection_steal_borrowed_message(). No
2032 * one can get at the message while its borrowed, so return it as
2033 * quickly as possible and don't keep a reference to it after
2034 * returning it. If you need to keep the message, make a copy of it.
2036 * @param connection the connection.
2037 * @returns next message in the incoming queue.
2040 dbus_connection_borrow_message (DBusConnection *connection)
2042 DBusMessage *message;
2043 DBusDispatchStatus status;
2045 _dbus_return_val_if_fail (connection != NULL, NULL);
2046 /* can't borrow during dispatch */
2047 _dbus_return_val_if_fail (!connection->dispatch_acquired, NULL);
2049 /* this is called for the side effect that it queues
2050 * up any messages from the transport
2052 status = dbus_connection_get_dispatch_status (connection);
2053 if (status != DBUS_DISPATCH_DATA_REMAINS)
2056 CONNECTION_LOCK (connection);
2058 if (connection->message_borrowed != NULL)
2059 _dbus_connection_wait_for_borrowed (connection);
2061 message = _dbus_list_get_first (&connection->incoming_messages);
2064 connection->message_borrowed = message;
2066 CONNECTION_UNLOCK (connection);
2071 * Used to return a message after peeking at it using
2072 * dbus_connection_borrow_message().
2074 * @param connection the connection
2075 * @param message the message from dbus_connection_borrow_message()
2078 dbus_connection_return_message (DBusConnection *connection,
2079 DBusMessage *message)
2081 _dbus_return_if_fail (connection != NULL);
2082 _dbus_return_if_fail (message != NULL);
2083 /* can't borrow during dispatch */
2084 _dbus_return_if_fail (!connection->dispatch_acquired);
2086 CONNECTION_LOCK (connection);
2088 _dbus_assert (message == connection->message_borrowed);
2090 connection->message_borrowed = NULL;
2091 dbus_condvar_wake_all (connection->message_returned_cond);
2093 CONNECTION_UNLOCK (connection);
2097 * Used to keep a message after peeking at it using
2098 * dbus_connection_borrow_message(). Before using this function, see
2099 * the caveats/warnings in the documentation for
2100 * dbus_connection_pop_message().
2102 * @param connection the connection
2103 * @param message the message from dbus_connection_borrow_message()
2106 dbus_connection_steal_borrowed_message (DBusConnection *connection,
2107 DBusMessage *message)
2109 DBusMessage *pop_message;
2111 _dbus_return_if_fail (connection != NULL);
2112 _dbus_return_if_fail (message != NULL);
2113 /* can't borrow during dispatch */
2114 _dbus_return_if_fail (!connection->dispatch_acquired);
2116 CONNECTION_LOCK (connection);
2118 _dbus_assert (message == connection->message_borrowed);
2120 pop_message = _dbus_list_pop_first (&connection->incoming_messages);
2121 _dbus_assert (message == pop_message);
2123 connection->n_incoming -= 1;
2125 _dbus_verbose ("Incoming message %p stolen from queue, %d incoming\n",
2126 message, connection->n_incoming);
2128 connection->message_borrowed = NULL;
2129 dbus_condvar_wake_all (connection->message_returned_cond);
2131 CONNECTION_UNLOCK (connection);
2134 /* See dbus_connection_pop_message, but requires the caller to own
2135 * the lock before calling. May drop the lock while running.
2138 _dbus_connection_pop_message_link_unlocked (DBusConnection *connection)
2140 if (connection->message_borrowed != NULL)
2141 _dbus_connection_wait_for_borrowed (connection);
2143 if (connection->n_incoming > 0)
2147 link = _dbus_list_pop_first_link (&connection->incoming_messages);
2148 connection->n_incoming -= 1;
2150 _dbus_verbose ("Message %p (%s) removed from incoming queue %p, %d incoming\n",
2151 link->data, dbus_message_get_name (link->data),
2152 connection, connection->n_incoming);
2160 /* See dbus_connection_pop_message, but requires the caller to own
2161 * the lock before calling. May drop the lock while running.
2164 _dbus_connection_pop_message_unlocked (DBusConnection *connection)
2168 link = _dbus_connection_pop_message_link_unlocked (connection);
2172 DBusMessage *message;
2174 message = link->data;
2176 _dbus_list_free_link (link);
2185 _dbus_connection_putback_message_link_unlocked (DBusConnection *connection,
2186 DBusList *message_link)
2188 _dbus_assert (message_link != NULL);
2189 /* You can't borrow a message while a link is outstanding */
2190 _dbus_assert (connection->message_borrowed == NULL);
2192 _dbus_list_prepend_link (&connection->incoming_messages,
2194 connection->n_incoming += 1;
2196 _dbus_verbose ("Message %p (%s) put back into queue %p, %d incoming\n",
2197 message_link->data, dbus_message_get_name (message_link->data),
2198 connection, connection->n_incoming);
2202 * Returns the first-received message from the incoming message queue,
2203 * removing it from the queue. The caller owns a reference to the
2204 * returned message. If the queue is empty, returns #NULL.
2206 * This function bypasses any message handlers that are registered,
2207 * and so using it is usually wrong. Instead, let the main loop invoke
2208 * dbus_connection_dispatch(). Popping messages manually is only
2209 * useful in very simple programs that don't share a #DBusConnection
2210 * with any libraries or other modules.
2212 * @param connection the connection.
2213 * @returns next message in the incoming queue.
2216 dbus_connection_pop_message (DBusConnection *connection)
2218 DBusMessage *message;
2219 DBusDispatchStatus status;
2221 /* this is called for the side effect that it queues
2222 * up any messages from the transport
2224 status = dbus_connection_get_dispatch_status (connection);
2225 if (status != DBUS_DISPATCH_DATA_REMAINS)
2228 CONNECTION_LOCK (connection);
2230 message = _dbus_connection_pop_message_unlocked (connection);
2232 _dbus_verbose ("Returning popped message %p\n", message);
2234 CONNECTION_UNLOCK (connection);
2240 * Acquire the dispatcher. This must be done before dispatching
2241 * messages in order to guarantee the right order of
2242 * message delivery. May sleep and drop the connection mutex
2243 * while waiting for the dispatcher.
2245 * @param connection the connection.
2248 _dbus_connection_acquire_dispatch (DBusConnection *connection)
2250 if (connection->dispatch_acquired)
2251 dbus_condvar_wait (connection->dispatch_cond, connection->mutex);
2252 _dbus_assert (!connection->dispatch_acquired);
2254 connection->dispatch_acquired = TRUE;
2258 * Release the dispatcher when you're done with it. Only call
2259 * after you've acquired the dispatcher. Wakes up at most one
2260 * thread currently waiting to acquire the dispatcher.
2262 * @param connection the connection.
2265 _dbus_connection_release_dispatch (DBusConnection *connection)
2267 _dbus_assert (connection->dispatch_acquired);
2269 connection->dispatch_acquired = FALSE;
2270 dbus_condvar_wake_one (connection->dispatch_cond);
2274 _dbus_connection_failed_pop (DBusConnection *connection,
2275 DBusList *message_link)
2277 _dbus_list_prepend_link (&connection->incoming_messages,
2279 connection->n_incoming += 1;
2282 static DBusDispatchStatus
2283 _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection)
2285 if (connection->n_incoming > 0)
2286 return DBUS_DISPATCH_DATA_REMAINS;
2287 else if (!_dbus_transport_queue_messages (connection->transport))
2288 return DBUS_DISPATCH_NEED_MEMORY;
2291 DBusDispatchStatus status;
2293 status = _dbus_transport_get_dispatch_status (connection->transport);
2295 if (status != DBUS_DISPATCH_COMPLETE)
2297 else if (connection->n_incoming > 0)
2298 return DBUS_DISPATCH_DATA_REMAINS;
2300 return DBUS_DISPATCH_COMPLETE;
2305 _dbus_connection_update_dispatch_status_and_unlock (DBusConnection *connection,
2306 DBusDispatchStatus new_status)
2308 dbus_bool_t changed;
2309 DBusDispatchStatusFunction function;
2312 /* We have the lock */
2314 _dbus_connection_ref_unlocked (connection);
2316 changed = new_status != connection->last_dispatch_status;
2318 connection->last_dispatch_status = new_status;
2320 function = connection->dispatch_status_function;
2321 data = connection->dispatch_status_data;
2323 /* We drop the lock */
2324 CONNECTION_UNLOCK (connection);
2326 if (changed && function)
2328 _dbus_verbose ("Notifying of change to dispatch status of %p now %d (%s)\n",
2329 connection, new_status,
2330 new_status == DBUS_DISPATCH_COMPLETE ? "complete" :
2331 new_status == DBUS_DISPATCH_DATA_REMAINS ? "data remains" :
2332 new_status == DBUS_DISPATCH_NEED_MEMORY ? "need memory" :
2334 (* function) (connection, new_status, data);
2337 dbus_connection_unref (connection);
2341 * Gets the current state (what we would currently return
2342 * from dbus_connection_dispatch()) but doesn't actually
2343 * dispatch any messages.
2345 * @param connection the connection.
2346 * @returns current dispatch status
2349 dbus_connection_get_dispatch_status (DBusConnection *connection)
2351 DBusDispatchStatus status;
2353 _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
2355 CONNECTION_LOCK (connection);
2357 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2359 CONNECTION_UNLOCK (connection);
2365 * Processes data buffered while handling watches, queueing zero or
2366 * more incoming messages. Then pops the first-received message from
2367 * the current incoming message queue, runs any handlers for it, and
2368 * unrefs the message. Returns a status indicating whether messages/data
2369 * remain, more memory is needed, or all data has been processed.
2371 * Even if the dispatch status is #DBUS_DISPATCH_DATA_REMAINS,
2372 * does not necessarily dispatch a message, as the data may
2373 * be part of authentication or the like.
2375 * @todo some FIXME in here about handling DBUS_HANDLER_RESULT_NEED_MEMORY
2377 * @todo right now a message filter gets run on replies to a pending
2378 * call in here, but not in the case where we block without
2379 * entering the main loop.
2381 * @param connection the connection
2382 * @returns dispatch status
2385 dbus_connection_dispatch (DBusConnection *connection)
2387 DBusMessage *message;
2388 DBusList *link, *filter_list_copy, *message_link;
2389 DBusHandlerResult result;
2390 DBusPendingCall *pending;
2391 dbus_int32_t reply_serial;
2392 DBusDispatchStatus status;
2394 _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
2396 CONNECTION_LOCK (connection);
2397 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2398 if (status != DBUS_DISPATCH_DATA_REMAINS)
2400 /* unlocks and calls out to user code */
2401 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2405 /* We need to ref the connection since the callback could potentially
2406 * drop the last ref to it
2408 _dbus_connection_ref_unlocked (connection);
2410 _dbus_connection_acquire_dispatch (connection);
2412 /* This call may drop the lock during the execution (if waiting for
2413 * borrowed messages to be returned) but the order of message
2414 * dispatch if several threads call dispatch() is still
2415 * protected by the lock, since only one will get the lock, and that
2416 * one will finish the message dispatching
2418 message_link = _dbus_connection_pop_message_link_unlocked (connection);
2419 if (message_link == NULL)
2421 /* another thread dispatched our stuff */
2423 _dbus_connection_release_dispatch (connection);
2425 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2427 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2429 dbus_connection_unref (connection);
2434 message = message_link->data;
2436 result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2438 reply_serial = dbus_message_get_reply_serial (message);
2439 pending = _dbus_hash_table_lookup_int (connection->pending_replies,
2442 if (!_dbus_list_copy (&connection->filter_list, &filter_list_copy))
2444 _dbus_connection_release_dispatch (connection);
2446 _dbus_connection_failed_pop (connection, message_link);
2448 /* unlocks and calls user code */
2449 _dbus_connection_update_dispatch_status_and_unlock (connection,
2450 DBUS_DISPATCH_NEED_MEMORY);
2452 dbus_connection_unref (connection);
2454 return DBUS_DISPATCH_NEED_MEMORY;
2457 _dbus_list_foreach (&filter_list_copy,
2458 (DBusForeachFunction)dbus_message_handler_ref,
2461 /* We're still protected from dispatch() reentrancy here
2462 * since we acquired the dispatcher
2464 CONNECTION_UNLOCK (connection);
2466 link = _dbus_list_get_first_link (&filter_list_copy);
2467 while (link != NULL)
2469 DBusMessageHandler *handler = link->data;
2470 DBusList *next = _dbus_list_get_next_link (&filter_list_copy, link);
2472 _dbus_verbose (" running filter on message %p\n", message);
2473 result = _dbus_message_handler_handle_message (handler, connection,
2476 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
2482 _dbus_list_foreach (&filter_list_copy,
2483 (DBusForeachFunction)dbus_message_handler_unref,
2485 _dbus_list_clear (&filter_list_copy);
2487 CONNECTION_LOCK (connection);
2489 if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
2492 /* Did a reply we were waiting on get filtered? */
2493 if (pending && result == DBUS_HANDLER_RESULT_HANDLED)
2495 /* Queue the timeout immediately! */
2496 if (pending->timeout_link)
2498 _dbus_connection_queue_synthesized_message_link (connection,
2499 pending->timeout_link);
2500 pending->timeout_link = NULL;
2504 /* We already queued the timeout? Then it was filtered! */
2505 _dbus_warn ("The timeout error with reply serial %d was filtered, so the DBusPendingCall will never stop pending.\n", reply_serial);
2509 if (result == DBUS_HANDLER_RESULT_HANDLED)
2514 _dbus_pending_call_complete_and_unlock (pending, message);
2518 CONNECTION_LOCK (connection);
2522 /* We're still protected from dispatch() reentrancy here
2523 * since we acquired the dispatcher
2525 _dbus_verbose (" running object handler on message %p (%s)\n",
2526 message, dbus_message_get_name (message));
2528 result = _dbus_object_registry_handle_and_unlock (connection->objects,
2531 CONNECTION_LOCK (connection);
2533 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
2536 if (dbus_message_get_type (message) == DBUS_MESSAGE_TYPE_METHOD_CALL)
2540 DBusPreallocatedSend *preallocated;
2542 _dbus_verbose (" sending error %s\n",
2543 DBUS_ERROR_UNKNOWN_METHOD);
2545 if (!_dbus_string_init (&str))
2547 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
2551 if (!_dbus_string_append_printf (&str,
2552 "Method \"%s\" doesn't exist\n",
2553 dbus_message_get_name (message)))
2555 _dbus_string_free (&str);
2556 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
2560 reply = dbus_message_new_error (message,
2561 DBUS_ERROR_UNKNOWN_METHOD,
2562 _dbus_string_get_const_data (&str));
2563 _dbus_string_free (&str);
2567 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
2571 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
2573 if (preallocated == NULL)
2575 dbus_message_unref (reply);
2576 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
2580 _dbus_connection_send_preallocated_unlocked (connection, preallocated,
2583 dbus_message_unref (reply);
2585 result = DBUS_HANDLER_RESULT_HANDLED;
2588 _dbus_verbose (" done dispatching %p (%s) on connection %p\n", message,
2589 dbus_message_get_name (message), connection);
2592 if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
2594 /* Put message back, and we'll start over.
2595 * Yes this means handlers must be idempotent if they
2596 * don't return HANDLED; c'est la vie.
2598 _dbus_connection_putback_message_link_unlocked (connection,
2603 _dbus_list_free_link (message_link);
2604 dbus_message_unref (message); /* don't want the message to count in max message limits
2605 * in computing dispatch status below
2609 _dbus_connection_release_dispatch (connection);
2611 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2613 /* unlocks and calls user code */
2614 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2616 dbus_connection_unref (connection);
2622 * Sets the watch functions for the connection. These functions are
2623 * responsible for making the application's main loop aware of file
2624 * descriptors that need to be monitored for events, using select() or
2625 * poll(). When using Qt, typically the DBusAddWatchFunction would
2626 * create a QSocketNotifier. When using GLib, the DBusAddWatchFunction
2627 * could call g_io_add_watch(), or could be used as part of a more
2628 * elaborate GSource. Note that when a watch is added, it may
2631 * The DBusWatchToggledFunction notifies the application that the
2632 * watch has been enabled or disabled. Call dbus_watch_get_enabled()
2633 * to check this. A disabled watch should have no effect, and enabled
2634 * watch should be added to the main loop. This feature is used
2635 * instead of simply adding/removing the watch because
2636 * enabling/disabling can be done without memory allocation. The
2637 * toggled function may be NULL if a main loop re-queries
2638 * dbus_watch_get_enabled() every time anyway.
2640 * The DBusWatch can be queried for the file descriptor to watch using
2641 * dbus_watch_get_fd(), and for the events to watch for using
2642 * dbus_watch_get_flags(). The flags returned by
2643 * dbus_watch_get_flags() will only contain DBUS_WATCH_READABLE and
2644 * DBUS_WATCH_WRITABLE, never DBUS_WATCH_HANGUP or DBUS_WATCH_ERROR;
2645 * all watches implicitly include a watch for hangups, errors, and
2646 * other exceptional conditions.
2648 * Once a file descriptor becomes readable or writable, or an exception
2649 * occurs, dbus_watch_handle() should be called to
2650 * notify the connection of the file descriptor's condition.
2652 * dbus_watch_handle() cannot be called during the
2653 * DBusAddWatchFunction, as the connection will not be ready to handle
2656 * It is not allowed to reference a DBusWatch after it has been passed
2657 * to remove_function.
2659 * If #FALSE is returned due to lack of memory, the failure may be due
2660 * to a #FALSE return from the new add_function. If so, the
2661 * add_function may have been called successfully one or more times,
2662 * but the remove_function will also have been called to remove any
2663 * successful adds. i.e. if #FALSE is returned the net result
2664 * should be that dbus_connection_set_watch_functions() has no effect,
2665 * but the add_function and remove_function may have been called.
2667 * @todo We need to drop the lock when we call the
2668 * add/remove/toggled functions which can be a side effect
2669 * of setting the watch functions.
2671 * @param connection the connection.
2672 * @param add_function function to begin monitoring a new descriptor.
2673 * @param remove_function function to stop monitoring a descriptor.
2674 * @param toggled_function function to notify of enable/disable
2675 * @param data data to pass to add_function and remove_function.
2676 * @param free_data_function function to be called to free the data.
2677 * @returns #FALSE on failure (no memory)
2680 dbus_connection_set_watch_functions (DBusConnection *connection,
2681 DBusAddWatchFunction add_function,
2682 DBusRemoveWatchFunction remove_function,
2683 DBusWatchToggledFunction toggled_function,
2685 DBusFreeFunction free_data_function)
2689 _dbus_return_val_if_fail (connection != NULL, FALSE);
2691 CONNECTION_LOCK (connection);
2692 /* ref connection for slightly better reentrancy */
2693 _dbus_connection_ref_unlocked (connection);
2695 /* FIXME this can call back into user code, and we need to drop the
2696 * connection lock when it does.
2698 retval = _dbus_watch_list_set_functions (connection->watches,
2699 add_function, remove_function,
2701 data, free_data_function);
2703 CONNECTION_UNLOCK (connection);
2704 /* drop our paranoid refcount */
2705 dbus_connection_unref (connection);
2711 * Sets the timeout functions for the connection. These functions are
2712 * responsible for making the application's main loop aware of timeouts.
2713 * When using Qt, typically the DBusAddTimeoutFunction would create a
2714 * QTimer. When using GLib, the DBusAddTimeoutFunction would call
2717 * The DBusTimeoutToggledFunction notifies the application that the
2718 * timeout has been enabled or disabled. Call
2719 * dbus_timeout_get_enabled() to check this. A disabled timeout should
2720 * have no effect, and enabled timeout should be added to the main
2721 * loop. This feature is used instead of simply adding/removing the
2722 * timeout because enabling/disabling can be done without memory
2723 * allocation. With Qt, QTimer::start() and QTimer::stop() can be used
2724 * to enable and disable. The toggled function may be NULL if a main
2725 * loop re-queries dbus_timeout_get_enabled() every time anyway.
2726 * Whenever a timeout is toggled, its interval may change.
2728 * The DBusTimeout can be queried for the timer interval using
2729 * dbus_timeout_get_interval(). dbus_timeout_handle() should be called
2730 * repeatedly, each time the interval elapses, starting after it has
2731 * elapsed once. The timeout stops firing when it is removed with the
2732 * given remove_function. The timer interval may change whenever the
2733 * timeout is added, removed, or toggled.
2735 * @param connection the connection.
2736 * @param add_function function to add a timeout.
2737 * @param remove_function function to remove a timeout.
2738 * @param toggled_function function to notify of enable/disable
2739 * @param data data to pass to add_function and remove_function.
2740 * @param free_data_function function to be called to free the data.
2741 * @returns #FALSE on failure (no memory)
2744 dbus_connection_set_timeout_functions (DBusConnection *connection,
2745 DBusAddTimeoutFunction add_function,
2746 DBusRemoveTimeoutFunction remove_function,
2747 DBusTimeoutToggledFunction toggled_function,
2749 DBusFreeFunction free_data_function)
2753 _dbus_return_val_if_fail (connection != NULL, FALSE);
2755 CONNECTION_LOCK (connection);
2756 /* ref connection for slightly better reentrancy */
2757 _dbus_connection_ref_unlocked (connection);
2759 retval = _dbus_timeout_list_set_functions (connection->timeouts,
2760 add_function, remove_function,
2762 data, free_data_function);
2764 CONNECTION_UNLOCK (connection);
2765 /* drop our paranoid refcount */
2766 dbus_connection_unref (connection);
2772 * Sets the mainloop wakeup function for the connection. Thi function is
2773 * responsible for waking up the main loop (if its sleeping) when some some
2774 * change has happened to the connection that the mainloop needs to reconsiders
2775 * (e.g. a message has been queued for writing).
2776 * When using Qt, this typically results in a call to QEventLoop::wakeUp().
2777 * When using GLib, it would call g_main_context_wakeup().
2780 * @param connection the connection.
2781 * @param wakeup_main_function function to wake up the mainloop
2782 * @param data data to pass wakeup_main_function
2783 * @param free_data_function function to be called to free the data.
2786 dbus_connection_set_wakeup_main_function (DBusConnection *connection,
2787 DBusWakeupMainFunction wakeup_main_function,
2789 DBusFreeFunction free_data_function)
2792 DBusFreeFunction old_free_data;
2794 _dbus_return_if_fail (connection != NULL);
2796 CONNECTION_LOCK (connection);
2797 old_data = connection->wakeup_main_data;
2798 old_free_data = connection->free_wakeup_main_data;
2800 connection->wakeup_main_function = wakeup_main_function;
2801 connection->wakeup_main_data = data;
2802 connection->free_wakeup_main_data = free_data_function;
2804 CONNECTION_UNLOCK (connection);
2806 /* Callback outside the lock */
2808 (*old_free_data) (old_data);
2812 * Set a function to be invoked when the dispatch status changes.
2813 * If the dispatch status is #DBUS_DISPATCH_DATA_REMAINS, then
2814 * dbus_connection_dispatch() needs to be called to process incoming
2815 * messages. However, dbus_connection_dispatch() MUST NOT BE CALLED
2816 * from inside the DBusDispatchStatusFunction. Indeed, almost
2817 * any reentrancy in this function is a bad idea. Instead,
2818 * the DBusDispatchStatusFunction should simply save an indication
2819 * that messages should be dispatched later, when the main loop
2822 * @param connection the connection
2823 * @param function function to call on dispatch status changes
2824 * @param data data for function
2825 * @param free_data_function free the function data
2828 dbus_connection_set_dispatch_status_function (DBusConnection *connection,
2829 DBusDispatchStatusFunction function,
2831 DBusFreeFunction free_data_function)
2834 DBusFreeFunction old_free_data;
2836 _dbus_return_if_fail (connection != NULL);
2838 CONNECTION_LOCK (connection);
2839 old_data = connection->dispatch_status_data;
2840 old_free_data = connection->free_dispatch_status_data;
2842 connection->dispatch_status_function = function;
2843 connection->dispatch_status_data = data;
2844 connection->free_dispatch_status_data = free_data_function;
2846 CONNECTION_UNLOCK (connection);
2848 /* Callback outside the lock */
2850 (*old_free_data) (old_data);
2854 * Gets the UNIX user ID of the connection if any.
2855 * Returns #TRUE if the uid is filled in.
2856 * Always returns #FALSE on non-UNIX platforms.
2857 * Always returns #FALSE prior to authenticating the
2860 * @param connection the connection
2861 * @param uid return location for the user ID
2862 * @returns #TRUE if uid is filled in with a valid user ID
2865 dbus_connection_get_unix_user (DBusConnection *connection,
2870 _dbus_return_val_if_fail (connection != NULL, FALSE);
2871 _dbus_return_val_if_fail (uid != NULL, FALSE);
2873 CONNECTION_LOCK (connection);
2875 if (!_dbus_transport_get_is_authenticated (connection->transport))
2878 result = _dbus_transport_get_unix_user (connection->transport,
2880 CONNECTION_UNLOCK (connection);
2886 * Sets a predicate function used to determine whether a given user ID
2887 * is allowed to connect. When an incoming connection has
2888 * authenticated with a particular user ID, this function is called;
2889 * if it returns #TRUE, the connection is allowed to proceed,
2890 * otherwise the connection is disconnected.
2892 * If the function is set to #NULL (as it is by default), then
2893 * only the same UID as the server process will be allowed to
2896 * @param connection the connection
2897 * @param function the predicate
2898 * @param data data to pass to the predicate
2899 * @param free_data_function function to free the data
2902 dbus_connection_set_unix_user_function (DBusConnection *connection,
2903 DBusAllowUnixUserFunction function,
2905 DBusFreeFunction free_data_function)
2907 void *old_data = NULL;
2908 DBusFreeFunction old_free_function = NULL;
2910 _dbus_return_if_fail (connection != NULL);
2912 CONNECTION_LOCK (connection);
2913 _dbus_transport_set_unix_user_function (connection->transport,
2914 function, data, free_data_function,
2915 &old_data, &old_free_function);
2916 CONNECTION_UNLOCK (connection);
2918 if (old_free_function != NULL)
2919 (* old_free_function) (old_data);
2923 * Adds a message filter. Filters are handlers that are run on
2924 * all incoming messages, prior to the objects
2925 * registered with dbus_connection_register_object().
2926 * Filters are run in the order that they were added.
2927 * The same handler can be added as a filter more than once, in
2928 * which case it will be run more than once.
2929 * Filters added during a filter callback won't be run on the
2930 * message being processed.
2932 * The connection does NOT add a reference to the message handler;
2933 * instead, if the message handler is finalized, the connection simply
2934 * forgets about it. Thus the caller of this function must keep a
2935 * reference to the message handler.
2937 * @todo we don't run filters on messages while blocking without
2938 * entering the main loop, since filters are run as part of
2939 * dbus_connection_dispatch().
2941 * @param connection the connection
2942 * @param handler the handler
2943 * @returns #TRUE on success, #FALSE if not enough memory.
2946 dbus_connection_add_filter (DBusConnection *connection,
2947 DBusMessageHandler *handler)
2949 _dbus_return_val_if_fail (connection != NULL, FALSE);
2950 _dbus_return_val_if_fail (handler != NULL, FALSE);
2952 CONNECTION_LOCK (connection);
2953 if (!_dbus_message_handler_add_connection (handler, connection))
2955 CONNECTION_UNLOCK (connection);
2959 if (!_dbus_list_append (&connection->filter_list,
2962 _dbus_message_handler_remove_connection (handler, connection);
2963 CONNECTION_UNLOCK (connection);
2967 CONNECTION_UNLOCK (connection);
2972 * Removes a previously-added message filter. It is a programming
2973 * error to call this function for a handler that has not
2974 * been added as a filter. If the given handler was added
2975 * more than once, only one instance of it will be removed
2976 * (the most recently-added instance).
2978 * @param connection the connection
2979 * @param handler the handler to remove
2983 dbus_connection_remove_filter (DBusConnection *connection,
2984 DBusMessageHandler *handler)
2986 _dbus_return_if_fail (connection != NULL);
2987 _dbus_return_if_fail (handler != NULL);
2989 CONNECTION_LOCK (connection);
2990 if (!_dbus_list_remove_last (&connection->filter_list, handler))
2992 _dbus_warn ("Tried to remove a DBusConnection filter that had not been added\n");
2993 CONNECTION_UNLOCK (connection);
2997 _dbus_message_handler_remove_connection (handler, connection);
2999 CONNECTION_UNLOCK (connection);
3003 * Registers an object with the connection. This object is assigned an
3004 * object ID, and will be visible under this ID and with the provided
3005 * interfaces to the peer application on the other end of the
3006 * connection. The object instance should be passed in as object_impl;
3007 * the instance can be any datatype, as long as it fits in a void*.
3009 * As a side effect of calling this function, the "registered"
3010 * callback in the #DBusObjectVTable will be invoked.
3012 * If the object is deleted, be sure to unregister it with
3013 * dbus_connection_unregister_object() or it will continue to get
3016 * @param connection the connection to register the instance with
3017 * @param interfaces #NULL-terminated array of interface names the instance supports
3018 * @param vtable virtual table of functions for manipulating the instance
3019 * @param object_impl object instance
3020 * @param object_id if non-#NULL, object ID to initialize with the new object's ID
3021 * @returns #FALSE if not enough memory to register the object instance
3024 dbus_connection_register_object (DBusConnection *connection,
3025 const char **interfaces,
3026 const DBusObjectVTable *vtable,
3028 DBusObjectID *object_id)
3030 _dbus_return_val_if_fail (connection != NULL, FALSE);
3031 _dbus_return_val_if_fail (vtable != NULL, FALSE);
3032 _dbus_return_val_if_fail (vtable->dbus_internal_pad1 == NULL, FALSE);
3033 _dbus_return_val_if_fail (vtable->dbus_internal_pad2 == NULL, FALSE);
3034 _dbus_return_val_if_fail (vtable->dbus_internal_pad3 == NULL, FALSE);
3036 CONNECTION_LOCK (connection);
3038 return _dbus_object_registry_add_and_unlock (connection->objects,
3046 * Reverses the effects of dbus_connection_register_object(),
3047 * and invokes the "unregistered" callback in the #DBusObjectVTable
3048 * for the given object. The passed-in object ID must be a valid,
3049 * registered object ID or the results are undefined.
3051 * @param connection the connection to unregister the object ID from
3052 * @param object_id the object ID to unregister
3055 dbus_connection_unregister_object (DBusConnection *connection,
3056 const DBusObjectID *object_id)
3058 _dbus_return_if_fail (connection != NULL);
3060 CONNECTION_LOCK (connection);
3062 return _dbus_object_registry_remove_and_unlock (connection->objects,
3066 static DBusDataSlotAllocator slot_allocator;
3067 _DBUS_DEFINE_GLOBAL_LOCK (connection_slots);
3070 * Allocates an integer ID to be used for storing application-specific
3071 * data on any DBusConnection. The allocated ID may then be used
3072 * with dbus_connection_set_data() and dbus_connection_get_data().
3073 * The passed-in slot must be initialized to -1, and is filled in
3074 * with the slot ID. If the passed-in slot is not -1, it's assumed
3075 * to be already allocated, and its refcount is incremented.
3077 * The allocated slot is global, i.e. all DBusConnection objects will
3078 * have a slot with the given integer ID reserved.
3080 * @param slot_p address of a global variable storing the slot
3081 * @returns #FALSE on failure (no memory)
3084 dbus_connection_allocate_data_slot (dbus_int32_t *slot_p)
3086 return _dbus_data_slot_allocator_alloc (&slot_allocator,
3087 _DBUS_LOCK_NAME (connection_slots),
3092 * Deallocates a global ID for connection data slots.
3093 * dbus_connection_get_data() and dbus_connection_set_data() may no
3094 * longer be used with this slot. Existing data stored on existing
3095 * DBusConnection objects will be freed when the connection is
3096 * finalized, but may not be retrieved (and may only be replaced if
3097 * someone else reallocates the slot). When the refcount on the
3098 * passed-in slot reaches 0, it is set to -1.
3100 * @param slot_p address storing the slot to deallocate
3103 dbus_connection_free_data_slot (dbus_int32_t *slot_p)
3105 _dbus_return_if_fail (*slot_p >= 0);
3107 _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
3111 * Stores a pointer on a DBusConnection, along
3112 * with an optional function to be used for freeing
3113 * the data when the data is set again, or when
3114 * the connection is finalized. The slot number
3115 * must have been allocated with dbus_connection_allocate_data_slot().
3117 * @param connection the connection
3118 * @param slot the slot number
3119 * @param data the data to store
3120 * @param free_data_func finalizer function for the data
3121 * @returns #TRUE if there was enough memory to store the data
3124 dbus_connection_set_data (DBusConnection *connection,
3127 DBusFreeFunction free_data_func)
3129 DBusFreeFunction old_free_func;
3133 _dbus_return_val_if_fail (connection != NULL, FALSE);
3134 _dbus_return_val_if_fail (slot >= 0, FALSE);
3136 CONNECTION_LOCK (connection);
3138 retval = _dbus_data_slot_list_set (&slot_allocator,
3139 &connection->slot_list,
3140 slot, data, free_data_func,
3141 &old_free_func, &old_data);
3143 CONNECTION_UNLOCK (connection);
3147 /* Do the actual free outside the connection lock */
3149 (* old_free_func) (old_data);
3156 * Retrieves data previously set with dbus_connection_set_data().
3157 * The slot must still be allocated (must not have been freed).
3159 * @param connection the connection
3160 * @param slot the slot to get data from
3161 * @returns the data, or #NULL if not found
3164 dbus_connection_get_data (DBusConnection *connection,
3169 _dbus_return_val_if_fail (connection != NULL, NULL);
3171 CONNECTION_LOCK (connection);
3173 res = _dbus_data_slot_list_get (&slot_allocator,
3174 &connection->slot_list,
3177 CONNECTION_UNLOCK (connection);
3183 * This function sets a global flag for whether dbus_connection_new()
3184 * will set SIGPIPE behavior to SIG_IGN.
3186 * @param will_modify_sigpipe #TRUE to allow sigpipe to be set to SIG_IGN
3189 dbus_connection_set_change_sigpipe (dbus_bool_t will_modify_sigpipe)
3191 _dbus_modify_sigpipe = will_modify_sigpipe != FALSE;
3195 * Specifies the maximum size message this connection is allowed to
3196 * receive. Larger messages will result in disconnecting the
3199 * @param connection a #DBusConnection
3200 * @param size maximum message size the connection can receive, in bytes
3203 dbus_connection_set_max_message_size (DBusConnection *connection,
3206 _dbus_return_if_fail (connection != NULL);
3208 CONNECTION_LOCK (connection);
3209 _dbus_transport_set_max_message_size (connection->transport,
3211 CONNECTION_UNLOCK (connection);
3215 * Gets the value set by dbus_connection_set_max_message_size().
3217 * @param connection the connection
3218 * @returns the max size of a single message
3221 dbus_connection_get_max_message_size (DBusConnection *connection)
3225 _dbus_return_val_if_fail (connection != NULL, 0);
3227 CONNECTION_LOCK (connection);
3228 res = _dbus_transport_get_max_message_size (connection->transport);
3229 CONNECTION_UNLOCK (connection);
3234 * Sets the maximum total number of bytes that can be used for all messages
3235 * received on this connection. Messages count toward the maximum until
3236 * they are finalized. When the maximum is reached, the connection will
3237 * not read more data until some messages are finalized.
3239 * The semantics of the maximum are: if outstanding messages are
3240 * already above the maximum, additional messages will not be read.
3241 * The semantics are not: if the next message would cause us to exceed
3242 * the maximum, we don't read it. The reason is that we don't know the
3243 * size of a message until after we read it.
3245 * Thus, the max live messages size can actually be exceeded
3246 * by up to the maximum size of a single message.
3248 * Also, if we read say 1024 bytes off the wire in a single read(),
3249 * and that contains a half-dozen small messages, we may exceed the
3250 * size max by that amount. But this should be inconsequential.
3252 * This does imply that we can't call read() with a buffer larger
3253 * than we're willing to exceed this limit by.
3255 * @param connection the connection
3256 * @param size the maximum size in bytes of all outstanding messages
3259 dbus_connection_set_max_received_size (DBusConnection *connection,
3262 _dbus_return_if_fail (connection != NULL);
3264 CONNECTION_LOCK (connection);
3265 _dbus_transport_set_max_received_size (connection->transport,
3267 CONNECTION_UNLOCK (connection);
3271 * Gets the value set by dbus_connection_set_max_received_size().
3273 * @param connection the connection
3274 * @returns the max size of all live messages
3277 dbus_connection_get_max_received_size (DBusConnection *connection)
3281 _dbus_return_val_if_fail (connection != NULL, 0);
3283 CONNECTION_LOCK (connection);
3284 res = _dbus_transport_get_max_received_size (connection->transport);
3285 CONNECTION_UNLOCK (connection);
3290 * Gets the approximate size in bytes of all messages in the outgoing
3291 * message queue. The size is approximate in that you shouldn't use
3292 * it to decide how many bytes to read off the network or anything
3293 * of that nature, as optimizations may choose to tell small white lies
3294 * to avoid performance overhead.
3296 * @param connection the connection
3297 * @returns the number of bytes that have been queued up but not sent
3300 dbus_connection_get_outgoing_size (DBusConnection *connection)
3304 _dbus_return_val_if_fail (connection != NULL, 0);
3306 CONNECTION_LOCK (connection);
3307 res = _dbus_counter_get_value (connection->outgoing_counter);
3308 CONNECTION_UNLOCK (connection);