1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-connection.c DBusConnection object
4 * Copyright (C) 2002, 2003, 2004, 2005 Red Hat Inc.
6 * Licensed under the Academic Free License version 2.1
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 #include "dbus-shared.h"
26 #include "dbus-connection.h"
27 #include "dbus-list.h"
28 #include "dbus-timeout.h"
29 #include "dbus-transport.h"
30 #include "dbus-watch.h"
31 #include "dbus-connection-internal.h"
32 #include "dbus-pending-call-internal.h"
33 #include "dbus-list.h"
34 #include "dbus-hash.h"
35 #include "dbus-message-internal.h"
36 #include "dbus-threads.h"
37 #include "dbus-protocol.h"
38 #include "dbus-dataslot.h"
39 #include "dbus-string.h"
40 #include "dbus-pending-call.h"
41 #include "dbus-object-tree.h"
42 #include "dbus-threads-internal.h"
45 #ifdef DBUS_DISABLE_CHECKS
46 #define TOOK_LOCK_CHECK(connection)
47 #define RELEASING_LOCK_CHECK(connection)
48 #define HAVE_LOCK_CHECK(connection)
50 #define TOOK_LOCK_CHECK(connection) do { \
51 _dbus_assert (!(connection)->have_connection_lock); \
52 (connection)->have_connection_lock = TRUE; \
54 #define RELEASING_LOCK_CHECK(connection) do { \
55 _dbus_assert ((connection)->have_connection_lock); \
56 (connection)->have_connection_lock = FALSE; \
58 #define HAVE_LOCK_CHECK(connection) _dbus_assert ((connection)->have_connection_lock)
59 /* A "DO_NOT_HAVE_LOCK_CHECK" is impossible since we need the lock to check the flag */
64 #define CONNECTION_LOCK(connection) do { \
65 if (TRACE_LOCKS) { _dbus_verbose (" LOCK: %s\n", _DBUS_FUNCTION_NAME); } \
66 _dbus_mutex_lock ((connection)->mutex); \
67 TOOK_LOCK_CHECK (connection); \
70 #define CONNECTION_UNLOCK(connection) do { \
71 if (TRACE_LOCKS) { _dbus_verbose (" UNLOCK: %s\n", _DBUS_FUNCTION_NAME); } \
72 RELEASING_LOCK_CHECK (connection); \
73 _dbus_mutex_unlock ((connection)->mutex); \
76 #define DISPATCH_STATUS_NAME(s) \
77 ((s) == DBUS_DISPATCH_COMPLETE ? "complete" : \
78 (s) == DBUS_DISPATCH_DATA_REMAINS ? "data remains" : \
79 (s) == DBUS_DISPATCH_NEED_MEMORY ? "need memory" : \
83 * @defgroup DBusConnection DBusConnection
85 * @brief Connection to another application
87 * A DBusConnection represents a connection to another
88 * application. Messages can be sent and received via this connection.
89 * The other application may be a message bus; for convenience, the
90 * function dbus_bus_get() is provided to automatically open a
91 * connection to the well-known message buses.
93 * In brief a DBusConnection is a message queue associated with some
94 * message transport mechanism such as a socket. The connection
95 * maintains a queue of incoming messages and a queue of outgoing
98 * Incoming messages are normally processed by calling
99 * dbus_connection_dispatch(). dbus_connection_dispatch() runs any
100 * handlers registered for the topmost message in the message queue,
101 * then discards the message, then returns.
103 * dbus_connection_get_dispatch_status() indicates whether
104 * messages are currently in the queue that need dispatching.
105 * dbus_connection_set_dispatch_status_function() allows
106 * you to set a function to be used to monitor the dispatch status.
108 * If you're using GLib or Qt add-on libraries for D-BUS, there are
109 * special convenience APIs in those libraries that hide
110 * all the details of dispatch and watch/timeout monitoring.
111 * For example, dbus_connection_setup_with_g_main().
113 * If you aren't using these add-on libraries, you have to manually
114 * call dbus_connection_set_dispatch_status_function(),
115 * dbus_connection_set_watch_functions(),
116 * dbus_connection_set_timeout_functions() providing appropriate
117 * functions to integrate the connection with your application's main
120 * When you use dbus_connection_send() or one of its variants to send
121 * a message, the message is added to the outgoing queue. It's
122 * actually written to the network later; either in
123 * dbus_watch_handle() invoked by your main loop, or in
124 * dbus_connection_flush() which blocks until it can write out the
125 * entire outgoing queue. The GLib/Qt add-on libraries again
126 * handle the details here for you by setting up watch functions.
128 * When a connection is disconnected, you are guaranteed to get a
129 * signal "Disconnected" from the interface
130 * #DBUS_INTERFACE_LOCAL, path
133 * You may not drop the last reference to a #DBusConnection
134 * until that connection has been disconnected.
136 * You may dispatch the unprocessed incoming message queue even if the
137 * connection is disconnected. However, "Disconnected" will always be
138 * the last message in the queue (obviously no messages are received
139 * after disconnection).
141 * #DBusConnection has thread locks and drops them when invoking user
142 * callbacks, so in general is transparently threadsafe. However,
143 * #DBusMessage does NOT have thread locks; you must not send the same
144 * message to multiple #DBusConnection that will be used from
149 * @defgroup DBusConnectionInternals DBusConnection implementation details
150 * @ingroup DBusInternals
151 * @brief Implementation details of DBusConnection
157 * Internal struct representing a message filter function
159 typedef struct DBusMessageFilter DBusMessageFilter;
162 * Internal struct representing a message filter function
164 struct DBusMessageFilter
166 DBusAtomic refcount; /**< Reference count */
167 DBusHandleMessageFunction function; /**< Function to call to filter */
168 void *user_data; /**< User data for the function */
169 DBusFreeFunction free_user_data_function; /**< Function to free the user data */
174 * Internals of DBusPreallocatedSend
176 struct DBusPreallocatedSend
178 DBusConnection *connection; /**< Connection we'd send the message to */
179 DBusList *queue_link; /**< Preallocated link in the queue */
180 DBusList *counter_link; /**< Preallocated link in the resource counter */
183 static dbus_bool_t _dbus_modify_sigpipe = TRUE;
186 * Implementation details of DBusConnection. All fields are private.
188 struct DBusConnection
190 DBusAtomic refcount; /**< Reference count. */
192 DBusMutex *mutex; /**< Lock on the entire DBusConnection */
194 DBusMutex *dispatch_mutex; /**< Protects dispatch_acquired */
195 DBusCondVar *dispatch_cond; /**< Notify when dispatch_acquired is available */
196 DBusMutex *io_path_mutex; /**< Protects io_path_acquired */
197 DBusCondVar *io_path_cond; /**< Notify when io_path_acquired is available */
199 DBusList *outgoing_messages; /**< Queue of messages we need to send, send the end of the list first. */
200 DBusList *incoming_messages; /**< Queue of messages we have received, end of the list received most recently. */
202 DBusMessage *message_borrowed; /**< Filled in if the first incoming message has been borrowed;
203 * dispatch_acquired will be set by the borrower
206 int n_outgoing; /**< Length of outgoing queue. */
207 int n_incoming; /**< Length of incoming queue. */
209 DBusCounter *outgoing_counter; /**< Counts size of outgoing messages. */
211 DBusTransport *transport; /**< Object that sends/receives messages over network. */
212 DBusWatchList *watches; /**< Stores active watches. */
213 DBusTimeoutList *timeouts; /**< Stores active timeouts. */
215 DBusList *filter_list; /**< List of filters. */
217 DBusDataSlotList slot_list; /**< Data stored by allocated integer ID */
219 DBusHashTable *pending_replies; /**< Hash of message serials to #DBusPendingCall. */
221 dbus_uint32_t client_serial; /**< Client serial. Increments each time a message is sent */
222 DBusList *disconnect_message_link; /**< Preallocated list node for queueing the disconnection message */
224 DBusWakeupMainFunction wakeup_main_function; /**< Function to wake up the mainloop */
225 void *wakeup_main_data; /**< Application data for wakeup_main_function */
226 DBusFreeFunction free_wakeup_main_data; /**< free wakeup_main_data */
228 DBusDispatchStatusFunction dispatch_status_function; /**< Function on dispatch status changes */
229 void *dispatch_status_data; /**< Application data for dispatch_status_function */
230 DBusFreeFunction free_dispatch_status_data; /**< free dispatch_status_data */
232 DBusDispatchStatus last_dispatch_status; /**< The last dispatch status we reported to the application. */
234 DBusList *link_cache; /**< A cache of linked list links to prevent contention
235 * for the global linked list mempool lock
237 DBusObjectTree *objects; /**< Object path handlers registered with this connection */
239 char *server_guid; /**< GUID of server if we are in shared_connections, #NULL if server GUID is unknown or connection is private */
241 unsigned int shareable : 1; /**< #TRUE if connection can go in shared_connections once we know the GUID */
243 unsigned int dispatch_acquired : 1; /**< Someone has dispatch path (can drain incoming queue) */
244 unsigned int io_path_acquired : 1; /**< Someone has transport io path (can use the transport to read/write messages) */
246 unsigned int exit_on_disconnect : 1; /**< If #TRUE, exit after handling disconnect signal */
248 #ifndef DBUS_DISABLE_CHECKS
249 unsigned int have_connection_lock : 1; /**< Used to check locking */
252 #ifndef DBUS_DISABLE_CHECKS
253 int generation; /**< _dbus_current_generation that should correspond to this connection */
257 static DBusDispatchStatus _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection);
258 static void _dbus_connection_update_dispatch_status_and_unlock (DBusConnection *connection,
259 DBusDispatchStatus new_status);
260 static void _dbus_connection_last_unref (DBusConnection *connection);
261 static void _dbus_connection_acquire_dispatch (DBusConnection *connection);
262 static void _dbus_connection_release_dispatch (DBusConnection *connection);
264 static DBusMessageFilter *
265 _dbus_message_filter_ref (DBusMessageFilter *filter)
267 _dbus_assert (filter->refcount.value > 0);
268 _dbus_atomic_inc (&filter->refcount);
274 _dbus_message_filter_unref (DBusMessageFilter *filter)
276 _dbus_assert (filter->refcount.value > 0);
278 if (_dbus_atomic_dec (&filter->refcount) == 1)
280 if (filter->free_user_data_function)
281 (* filter->free_user_data_function) (filter->user_data);
288 * Acquires the connection lock.
290 * @param connection the connection.
293 _dbus_connection_lock (DBusConnection *connection)
295 CONNECTION_LOCK (connection);
299 * Releases the connection lock.
301 * @param connection the connection.
304 _dbus_connection_unlock (DBusConnection *connection)
306 CONNECTION_UNLOCK (connection);
310 * Wakes up the main loop if it is sleeping
311 * Needed if we're e.g. queueing outgoing messages
312 * on a thread while the mainloop sleeps.
314 * @param connection the connection.
317 _dbus_connection_wakeup_mainloop (DBusConnection *connection)
319 if (connection->wakeup_main_function)
320 (*connection->wakeup_main_function) (connection->wakeup_main_data);
323 #ifdef DBUS_BUILD_TESTS
324 /* For now this function isn't used */
326 * Adds a message to the incoming message queue, returning #FALSE
327 * if there's insufficient memory to queue the message.
328 * Does not take over refcount of the message.
330 * @param connection the connection.
331 * @param message the message to queue.
332 * @returns #TRUE on success.
335 _dbus_connection_queue_received_message (DBusConnection *connection,
336 DBusMessage *message)
340 link = _dbus_list_alloc_link (message);
344 dbus_message_ref (message);
345 _dbus_connection_queue_received_message_link (connection, link);
352 * Adds a message-containing list link to the incoming message queue,
353 * taking ownership of the link and the message's current refcount.
354 * Cannot fail due to lack of memory.
356 * @param connection the connection.
357 * @param link the message link to queue.
360 _dbus_connection_queue_received_message_link (DBusConnection *connection,
363 DBusPendingCall *pending;
364 dbus_int32_t reply_serial;
365 DBusMessage *message;
367 _dbus_assert (_dbus_transport_get_is_authenticated (connection->transport));
369 _dbus_list_append_link (&connection->incoming_messages,
371 message = link->data;
373 /* If this is a reply we're waiting on, remove timeout for it */
374 reply_serial = dbus_message_get_reply_serial (message);
375 if (reply_serial != -1)
377 pending = _dbus_hash_table_lookup_int (connection->pending_replies,
381 if (_dbus_pending_call_is_timeout_added (pending))
382 _dbus_connection_remove_timeout_unlocked (connection,
383 _dbus_pending_call_get_timeout (pending));
385 _dbus_pending_call_set_timeout_added (pending, FALSE);
391 connection->n_incoming += 1;
393 _dbus_connection_wakeup_mainloop (connection);
395 _dbus_verbose ("Message %p (%d %s %s %s '%s' reply to %u) added to incoming queue %p, %d incoming\n",
397 dbus_message_get_type (message),
398 dbus_message_get_path (message) ?
399 dbus_message_get_path (message) :
401 dbus_message_get_interface (message) ?
402 dbus_message_get_interface (message) :
404 dbus_message_get_member (message) ?
405 dbus_message_get_member (message) :
407 dbus_message_get_signature (message),
408 dbus_message_get_reply_serial (message),
410 connection->n_incoming);}
413 * Adds a link + message to the incoming message queue.
414 * Can't fail. Takes ownership of both link and message.
416 * @param connection the connection.
417 * @param link the list node and message to queue.
419 * @todo This needs to wake up the mainloop if it is in
420 * a poll/select and this is a multithreaded app.
423 _dbus_connection_queue_synthesized_message_link (DBusConnection *connection,
426 HAVE_LOCK_CHECK (connection);
428 _dbus_list_append_link (&connection->incoming_messages, link);
430 connection->n_incoming += 1;
432 _dbus_connection_wakeup_mainloop (connection);
434 _dbus_verbose ("Synthesized message %p added to incoming queue %p, %d incoming\n",
435 link->data, connection, connection->n_incoming);
440 * Checks whether there are messages in the outgoing message queue.
441 * Called with connection lock held.
443 * @param connection the connection.
444 * @returns #TRUE if the outgoing queue is non-empty.
447 _dbus_connection_has_messages_to_send_unlocked (DBusConnection *connection)
449 HAVE_LOCK_CHECK (connection);
450 return connection->outgoing_messages != NULL;
454 * Checks whether there are messages in the outgoing message queue.
456 * @param connection the connection.
457 * @returns #TRUE if the outgoing queue is non-empty.
460 dbus_connection_has_messages_to_send (DBusConnection *connection)
464 _dbus_return_val_if_fail (connection != NULL, FALSE);
466 CONNECTION_LOCK (connection);
467 v = _dbus_connection_has_messages_to_send_unlocked (connection);
468 CONNECTION_UNLOCK (connection);
474 * Gets the next outgoing message. The message remains in the
475 * queue, and the caller does not own a reference to it.
477 * @param connection the connection.
478 * @returns the message to be sent.
481 _dbus_connection_get_message_to_send (DBusConnection *connection)
483 HAVE_LOCK_CHECK (connection);
485 return _dbus_list_get_last (&connection->outgoing_messages);
489 * Notifies the connection that a message has been sent, so the
490 * message can be removed from the outgoing queue.
491 * Called with the connection lock held.
493 * @param connection the connection.
494 * @param message the message that was sent.
497 _dbus_connection_message_sent (DBusConnection *connection,
498 DBusMessage *message)
502 HAVE_LOCK_CHECK (connection);
504 /* This can be called before we even complete authentication, since
505 * it's called on disconnect to clean up the outgoing queue.
506 * It's also called as we successfully send each message.
509 link = _dbus_list_get_last_link (&connection->outgoing_messages);
510 _dbus_assert (link != NULL);
511 _dbus_assert (link->data == message);
513 /* Save this link in the link cache */
514 _dbus_list_unlink (&connection->outgoing_messages,
516 _dbus_list_prepend_link (&connection->link_cache, link);
518 connection->n_outgoing -= 1;
520 _dbus_verbose ("Message %p (%d %s %s %s '%s') removed from outgoing queue %p, %d left to send\n",
522 dbus_message_get_type (message),
523 dbus_message_get_path (message) ?
524 dbus_message_get_path (message) :
526 dbus_message_get_interface (message) ?
527 dbus_message_get_interface (message) :
529 dbus_message_get_member (message) ?
530 dbus_message_get_member (message) :
532 dbus_message_get_signature (message),
533 connection, connection->n_outgoing);
535 /* Save this link in the link cache also */
536 _dbus_message_remove_size_counter (message, connection->outgoing_counter,
538 _dbus_list_prepend_link (&connection->link_cache, link);
540 dbus_message_unref (message);
543 typedef dbus_bool_t (* DBusWatchAddFunction) (DBusWatchList *list,
545 typedef void (* DBusWatchRemoveFunction) (DBusWatchList *list,
547 typedef void (* DBusWatchToggleFunction) (DBusWatchList *list,
549 dbus_bool_t enabled);
552 protected_change_watch (DBusConnection *connection,
554 DBusWatchAddFunction add_function,
555 DBusWatchRemoveFunction remove_function,
556 DBusWatchToggleFunction toggle_function,
559 DBusWatchList *watches;
562 HAVE_LOCK_CHECK (connection);
564 /* This isn't really safe or reasonable; a better pattern is the "do everything, then
565 * drop lock and call out" one; but it has to be propagated up through all callers
568 watches = connection->watches;
571 connection->watches = NULL;
572 _dbus_connection_ref_unlocked (connection);
573 CONNECTION_UNLOCK (connection);
576 retval = (* add_function) (watches, watch);
577 else if (remove_function)
580 (* remove_function) (watches, watch);
585 (* toggle_function) (watches, watch, enabled);
588 CONNECTION_LOCK (connection);
589 connection->watches = watches;
590 _dbus_connection_unref_unlocked (connection);
600 * Adds a watch using the connection's DBusAddWatchFunction if
601 * available. Otherwise records the watch to be added when said
602 * function is available. Also re-adds the watch if the
603 * DBusAddWatchFunction changes. May fail due to lack of memory.
604 * Connection lock should be held when calling this.
606 * @param connection the connection.
607 * @param watch the watch to add.
608 * @returns #TRUE on success.
611 _dbus_connection_add_watch_unlocked (DBusConnection *connection,
614 return protected_change_watch (connection, watch,
615 _dbus_watch_list_add_watch,
620 * Removes a watch using the connection's DBusRemoveWatchFunction
621 * if available. It's an error to call this function on a watch
622 * that was not previously added.
623 * Connection lock should be held when calling this.
625 * @param connection the connection.
626 * @param watch the watch to remove.
629 _dbus_connection_remove_watch_unlocked (DBusConnection *connection,
632 protected_change_watch (connection, watch,
634 _dbus_watch_list_remove_watch,
639 * Toggles a watch and notifies app via connection's
640 * DBusWatchToggledFunction if available. It's an error to call this
641 * function on a watch that was not previously added.
642 * Connection lock should be held when calling this.
644 * @param connection the connection.
645 * @param watch the watch to toggle.
646 * @param enabled whether to enable or disable
649 _dbus_connection_toggle_watch_unlocked (DBusConnection *connection,
653 _dbus_assert (watch != NULL);
655 protected_change_watch (connection, watch,
657 _dbus_watch_list_toggle_watch,
661 typedef dbus_bool_t (* DBusTimeoutAddFunction) (DBusTimeoutList *list,
662 DBusTimeout *timeout);
663 typedef void (* DBusTimeoutRemoveFunction) (DBusTimeoutList *list,
664 DBusTimeout *timeout);
665 typedef void (* DBusTimeoutToggleFunction) (DBusTimeoutList *list,
666 DBusTimeout *timeout,
667 dbus_bool_t enabled);
670 protected_change_timeout (DBusConnection *connection,
671 DBusTimeout *timeout,
672 DBusTimeoutAddFunction add_function,
673 DBusTimeoutRemoveFunction remove_function,
674 DBusTimeoutToggleFunction toggle_function,
677 DBusTimeoutList *timeouts;
680 HAVE_LOCK_CHECK (connection);
682 /* This isn't really safe or reasonable; a better pattern is the "do everything, then
683 * drop lock and call out" one; but it has to be propagated up through all callers
686 timeouts = connection->timeouts;
689 connection->timeouts = NULL;
690 _dbus_connection_ref_unlocked (connection);
691 CONNECTION_UNLOCK (connection);
694 retval = (* add_function) (timeouts, timeout);
695 else if (remove_function)
698 (* remove_function) (timeouts, timeout);
703 (* toggle_function) (timeouts, timeout, enabled);
706 CONNECTION_LOCK (connection);
707 connection->timeouts = timeouts;
708 _dbus_connection_unref_unlocked (connection);
717 * Adds a timeout using the connection's DBusAddTimeoutFunction if
718 * available. Otherwise records the timeout to be added when said
719 * function is available. Also re-adds the timeout if the
720 * DBusAddTimeoutFunction changes. May fail due to lack of memory.
721 * The timeout will fire repeatedly until removed.
722 * Connection lock should be held when calling this.
724 * @param connection the connection.
725 * @param timeout the timeout to add.
726 * @returns #TRUE on success.
729 _dbus_connection_add_timeout_unlocked (DBusConnection *connection,
730 DBusTimeout *timeout)
732 return protected_change_timeout (connection, timeout,
733 _dbus_timeout_list_add_timeout,
738 * Removes a timeout using the connection's DBusRemoveTimeoutFunction
739 * if available. It's an error to call this function on a timeout
740 * that was not previously added.
741 * Connection lock should be held when calling this.
743 * @param connection the connection.
744 * @param timeout the timeout to remove.
747 _dbus_connection_remove_timeout_unlocked (DBusConnection *connection,
748 DBusTimeout *timeout)
750 protected_change_timeout (connection, timeout,
752 _dbus_timeout_list_remove_timeout,
757 * Toggles a timeout and notifies app via connection's
758 * DBusTimeoutToggledFunction if available. It's an error to call this
759 * function on a timeout that was not previously added.
760 * Connection lock should be held when calling this.
762 * @param connection the connection.
763 * @param timeout the timeout to toggle.
764 * @param enabled whether to enable or disable
767 _dbus_connection_toggle_timeout_unlocked (DBusConnection *connection,
768 DBusTimeout *timeout,
771 protected_change_timeout (connection, timeout,
773 _dbus_timeout_list_toggle_timeout,
778 _dbus_connection_attach_pending_call_unlocked (DBusConnection *connection,
779 DBusPendingCall *pending)
781 dbus_uint32_t reply_serial;
782 DBusTimeout *timeout;
784 HAVE_LOCK_CHECK (connection);
786 reply_serial = _dbus_pending_call_get_reply_serial (pending);
788 _dbus_assert (reply_serial != 0);
790 timeout = _dbus_pending_call_get_timeout (pending);
792 if (!_dbus_connection_add_timeout_unlocked (connection, timeout))
795 if (!_dbus_hash_table_insert_int (connection->pending_replies,
799 _dbus_connection_remove_timeout_unlocked (connection, timeout);
801 HAVE_LOCK_CHECK (connection);
805 _dbus_pending_call_set_timeout_added (pending, TRUE);
807 dbus_pending_call_ref (pending);
809 HAVE_LOCK_CHECK (connection);
815 free_pending_call_on_hash_removal (void *data)
817 DBusPendingCall *pending;
818 DBusConnection *connection;
825 connection = _dbus_pending_call_get_connection (pending);
829 if (_dbus_pending_call_is_timeout_added (pending))
831 _dbus_connection_remove_timeout_unlocked (connection,
832 _dbus_pending_call_get_timeout (pending));
834 _dbus_pending_call_set_timeout_added (pending, FALSE);
837 dbus_pending_call_unref (pending);
842 _dbus_connection_detach_pending_call_unlocked (DBusConnection *connection,
843 DBusPendingCall *pending)
845 /* Can't have a destroy notifier on the pending call if we're going to do this */
847 dbus_pending_call_ref (pending);
848 _dbus_hash_table_remove_int (connection->pending_replies,
849 _dbus_pending_call_get_reply_serial (pending));
850 dbus_pending_call_unref (pending);
854 _dbus_connection_detach_pending_call_and_unlock (DBusConnection *connection,
855 DBusPendingCall *pending)
857 /* The idea here is to avoid finalizing the pending call
858 * with the lock held, since there's a destroy notifier
859 * in pending call that goes out to application code.
861 dbus_pending_call_ref (pending);
862 _dbus_hash_table_remove_int (connection->pending_replies,
863 _dbus_pending_call_get_reply_serial (pending));
864 CONNECTION_UNLOCK (connection);
865 dbus_pending_call_unref (pending);
869 * Removes a pending call from the connection, such that
870 * the pending reply will be ignored. May drop the last
871 * reference to the pending call.
873 * @param connection the connection
874 * @param pending the pending call
877 _dbus_connection_remove_pending_call (DBusConnection *connection,
878 DBusPendingCall *pending)
880 CONNECTION_LOCK (connection);
881 _dbus_connection_detach_pending_call_and_unlock (connection, pending);
885 * Acquire the transporter I/O path. This must be done before
886 * doing any I/O in the transporter. May sleep and drop the
887 * IO path mutex while waiting for the I/O path.
889 * @param connection the connection.
890 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
891 * @returns TRUE if the I/O path was acquired.
894 _dbus_connection_acquire_io_path (DBusConnection *connection,
895 int timeout_milliseconds)
897 dbus_bool_t we_acquired;
899 HAVE_LOCK_CHECK (connection);
901 /* We don't want the connection to vanish */
902 _dbus_connection_ref_unlocked (connection);
904 /* We will only touch io_path_acquired which is protected by our mutex */
905 CONNECTION_UNLOCK (connection);
907 _dbus_verbose ("%s locking io_path_mutex\n", _DBUS_FUNCTION_NAME);
908 _dbus_mutex_lock (connection->io_path_mutex);
910 _dbus_verbose ("%s start connection->io_path_acquired = %d timeout = %d\n",
911 _DBUS_FUNCTION_NAME, connection->io_path_acquired, timeout_milliseconds);
915 if (connection->io_path_acquired)
917 if (timeout_milliseconds != -1)
919 _dbus_verbose ("%s waiting %d for IO path to be acquirable\n",
920 _DBUS_FUNCTION_NAME, timeout_milliseconds);
921 _dbus_condvar_wait_timeout (connection->io_path_cond,
922 connection->io_path_mutex,
923 timeout_milliseconds);
927 while (connection->io_path_acquired)
929 _dbus_verbose ("%s waiting for IO path to be acquirable\n", _DBUS_FUNCTION_NAME);
930 _dbus_condvar_wait (connection->io_path_cond, connection->io_path_mutex);
935 if (!connection->io_path_acquired)
938 connection->io_path_acquired = TRUE;
941 _dbus_verbose ("%s end connection->io_path_acquired = %d we_acquired = %d\n",
942 _DBUS_FUNCTION_NAME, connection->io_path_acquired, we_acquired);
944 _dbus_verbose ("%s unlocking io_path_mutex\n", _DBUS_FUNCTION_NAME);
945 _dbus_mutex_unlock (connection->io_path_mutex);
947 CONNECTION_LOCK (connection);
949 HAVE_LOCK_CHECK (connection);
951 _dbus_connection_unref_unlocked (connection);
957 * Release the I/O path when you're done with it. Only call
958 * after you've acquired the I/O. Wakes up at most one thread
959 * currently waiting to acquire the I/O path.
961 * @param connection the connection.
964 _dbus_connection_release_io_path (DBusConnection *connection)
966 HAVE_LOCK_CHECK (connection);
968 _dbus_verbose ("%s locking io_path_mutex\n", _DBUS_FUNCTION_NAME);
969 _dbus_mutex_lock (connection->io_path_mutex);
971 _dbus_assert (connection->io_path_acquired);
973 _dbus_verbose ("%s start connection->io_path_acquired = %d\n",
974 _DBUS_FUNCTION_NAME, connection->io_path_acquired);
976 connection->io_path_acquired = FALSE;
977 _dbus_condvar_wake_one (connection->io_path_cond);
979 _dbus_verbose ("%s unlocking io_path_mutex\n", _DBUS_FUNCTION_NAME);
980 _dbus_mutex_unlock (connection->io_path_mutex);
984 * Queues incoming messages and sends outgoing messages for this
985 * connection, optionally blocking in the process. Each call to
986 * _dbus_connection_do_iteration_unlocked() will call select() or poll() one
987 * time and then read or write data if possible.
989 * The purpose of this function is to be able to flush outgoing
990 * messages or queue up incoming messages without returning
991 * control to the application and causing reentrancy weirdness.
993 * The flags parameter allows you to specify whether to
994 * read incoming messages, write outgoing messages, or both,
995 * and whether to block if no immediate action is possible.
997 * The timeout_milliseconds parameter does nothing unless the
998 * iteration is blocking.
1000 * If there are no outgoing messages and DBUS_ITERATION_DO_READING
1001 * wasn't specified, then it's impossible to block, even if
1002 * you specify DBUS_ITERATION_BLOCK; in that case the function
1003 * returns immediately.
1005 * Called with connection lock held.
1007 * @param connection the connection.
1008 * @param flags iteration flags.
1009 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
1012 _dbus_connection_do_iteration_unlocked (DBusConnection *connection,
1014 int timeout_milliseconds)
1016 _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
1018 HAVE_LOCK_CHECK (connection);
1020 if (connection->n_outgoing == 0)
1021 flags &= ~DBUS_ITERATION_DO_WRITING;
1023 if (_dbus_connection_acquire_io_path (connection,
1024 (flags & DBUS_ITERATION_BLOCK) ? timeout_milliseconds : 0))
1026 HAVE_LOCK_CHECK (connection);
1028 _dbus_transport_do_iteration (connection->transport,
1029 flags, timeout_milliseconds);
1030 _dbus_connection_release_io_path (connection);
1033 HAVE_LOCK_CHECK (connection);
1035 _dbus_verbose ("%s end\n", _DBUS_FUNCTION_NAME);
1039 * Creates a new connection for the given transport. A transport
1040 * represents a message stream that uses some concrete mechanism, such
1041 * as UNIX domain sockets. May return #NULL if insufficient
1042 * memory exists to create the connection.
1044 * @param transport the transport.
1045 * @returns the new connection, or #NULL on failure.
1048 _dbus_connection_new_for_transport (DBusTransport *transport)
1050 DBusConnection *connection;
1051 DBusWatchList *watch_list;
1052 DBusTimeoutList *timeout_list;
1053 DBusHashTable *pending_replies;
1055 DBusMutex *io_path_mutex;
1056 DBusMutex *dispatch_mutex;
1057 DBusCondVar *dispatch_cond;
1058 DBusCondVar *io_path_cond;
1059 DBusList *disconnect_link;
1060 DBusMessage *disconnect_message;
1061 DBusCounter *outgoing_counter;
1062 DBusObjectTree *objects;
1066 pending_replies = NULL;
1067 timeout_list = NULL;
1069 io_path_mutex = NULL;
1070 dispatch_mutex = NULL;
1071 dispatch_cond = NULL;
1072 io_path_cond = NULL;
1073 disconnect_link = NULL;
1074 disconnect_message = NULL;
1075 outgoing_counter = NULL;
1078 watch_list = _dbus_watch_list_new ();
1079 if (watch_list == NULL)
1082 timeout_list = _dbus_timeout_list_new ();
1083 if (timeout_list == NULL)
1087 _dbus_hash_table_new (DBUS_HASH_INT,
1089 (DBusFreeFunction)free_pending_call_on_hash_removal);
1090 if (pending_replies == NULL)
1093 connection = dbus_new0 (DBusConnection, 1);
1094 if (connection == NULL)
1097 mutex = _dbus_mutex_new ();
1101 io_path_mutex = _dbus_mutex_new ();
1102 if (io_path_mutex == NULL)
1105 dispatch_mutex = _dbus_mutex_new ();
1106 if (dispatch_mutex == NULL)
1109 dispatch_cond = _dbus_condvar_new ();
1110 if (dispatch_cond == NULL)
1113 io_path_cond = _dbus_condvar_new ();
1114 if (io_path_cond == NULL)
1117 disconnect_message = dbus_message_new_signal (DBUS_PATH_LOCAL,
1118 DBUS_INTERFACE_LOCAL,
1121 if (disconnect_message == NULL)
1124 disconnect_link = _dbus_list_alloc_link (disconnect_message);
1125 if (disconnect_link == NULL)
1128 outgoing_counter = _dbus_counter_new ();
1129 if (outgoing_counter == NULL)
1132 objects = _dbus_object_tree_new (connection);
1133 if (objects == NULL)
1136 if (_dbus_modify_sigpipe)
1137 _dbus_disable_sigpipe ();
1139 connection->refcount.value = 1;
1140 connection->mutex = mutex;
1141 connection->dispatch_cond = dispatch_cond;
1142 connection->dispatch_mutex = dispatch_mutex;
1143 connection->io_path_cond = io_path_cond;
1144 connection->io_path_mutex = io_path_mutex;
1145 connection->transport = transport;
1146 connection->watches = watch_list;
1147 connection->timeouts = timeout_list;
1148 connection->pending_replies = pending_replies;
1149 connection->outgoing_counter = outgoing_counter;
1150 connection->filter_list = NULL;
1151 connection->last_dispatch_status = DBUS_DISPATCH_COMPLETE; /* so we're notified first time there's data */
1152 connection->objects = objects;
1153 connection->exit_on_disconnect = FALSE;
1154 connection->shareable = FALSE;
1155 #ifndef DBUS_DISABLE_CHECKS
1156 connection->generation = _dbus_current_generation;
1159 _dbus_data_slot_list_init (&connection->slot_list);
1161 connection->client_serial = 1;
1163 connection->disconnect_message_link = disconnect_link;
1165 CONNECTION_LOCK (connection);
1167 if (!_dbus_transport_set_connection (transport, connection))
1170 _dbus_transport_ref (transport);
1172 CONNECTION_UNLOCK (connection);
1177 if (disconnect_message != NULL)
1178 dbus_message_unref (disconnect_message);
1180 if (disconnect_link != NULL)
1181 _dbus_list_free_link (disconnect_link);
1183 if (io_path_cond != NULL)
1184 _dbus_condvar_free (io_path_cond);
1186 if (dispatch_cond != NULL)
1187 _dbus_condvar_free (dispatch_cond);
1190 _dbus_mutex_free (mutex);
1192 if (io_path_mutex != NULL)
1193 _dbus_mutex_free (io_path_mutex);
1195 if (dispatch_mutex != NULL)
1196 _dbus_mutex_free (dispatch_mutex);
1198 if (connection != NULL)
1199 dbus_free (connection);
1201 if (pending_replies)
1202 _dbus_hash_table_unref (pending_replies);
1205 _dbus_watch_list_free (watch_list);
1208 _dbus_timeout_list_free (timeout_list);
1210 if (outgoing_counter)
1211 _dbus_counter_unref (outgoing_counter);
1214 _dbus_object_tree_unref (objects);
1220 * Increments the reference count of a DBusConnection.
1221 * Requires that the caller already holds the connection lock.
1223 * @param connection the connection.
1224 * @returns the connection.
1227 _dbus_connection_ref_unlocked (DBusConnection *connection)
1229 _dbus_assert (connection != NULL);
1230 _dbus_assert (connection->generation == _dbus_current_generation);
1232 HAVE_LOCK_CHECK (connection);
1234 #ifdef DBUS_HAVE_ATOMIC_INT
1235 _dbus_atomic_inc (&connection->refcount);
1237 _dbus_assert (connection->refcount.value > 0);
1238 connection->refcount.value += 1;
1245 * Decrements the reference count of a DBusConnection.
1246 * Requires that the caller already holds the connection lock.
1248 * @param connection the connection.
1251 _dbus_connection_unref_unlocked (DBusConnection *connection)
1253 dbus_bool_t last_unref;
1255 HAVE_LOCK_CHECK (connection);
1257 _dbus_assert (connection != NULL);
1259 /* The connection lock is better than the global
1260 * lock in the atomic increment fallback
1263 #ifdef DBUS_HAVE_ATOMIC_INT
1264 last_unref = (_dbus_atomic_dec (&connection->refcount) == 1);
1266 _dbus_assert (connection->refcount.value > 0);
1268 connection->refcount.value -= 1;
1269 last_unref = (connection->refcount.value == 0);
1271 printf ("unref_unlocked() connection %p count = %d\n", connection, connection->refcount.value);
1276 _dbus_connection_last_unref (connection);
1279 static dbus_uint32_t
1280 _dbus_connection_get_next_client_serial (DBusConnection *connection)
1284 serial = connection->client_serial++;
1286 if (connection->client_serial < 0)
1287 connection->client_serial = 1;
1293 * A callback for use with dbus_watch_new() to create a DBusWatch.
1295 * @todo This is basically a hack - we could delete _dbus_transport_handle_watch()
1296 * and the virtual handle_watch in DBusTransport if we got rid of it.
1297 * The reason this is some work is threading, see the _dbus_connection_handle_watch()
1300 * @param watch the watch.
1301 * @param condition the current condition of the file descriptors being watched.
1302 * @param data must be a pointer to a #DBusConnection
1303 * @returns #FALSE if the IO condition may not have been fully handled due to lack of memory
1306 _dbus_connection_handle_watch (DBusWatch *watch,
1307 unsigned int condition,
1310 DBusConnection *connection;
1312 DBusDispatchStatus status;
1316 _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
1318 CONNECTION_LOCK (connection);
1319 _dbus_connection_acquire_io_path (connection, -1);
1320 HAVE_LOCK_CHECK (connection);
1321 retval = _dbus_transport_handle_watch (connection->transport,
1324 _dbus_connection_release_io_path (connection);
1326 HAVE_LOCK_CHECK (connection);
1328 _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
1330 status = _dbus_connection_get_dispatch_status_unlocked (connection);
1332 /* this calls out to user code */
1333 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1335 _dbus_verbose ("%s end\n", _DBUS_FUNCTION_NAME);
1340 _DBUS_DEFINE_GLOBAL_LOCK (shared_connections);
1341 static DBusHashTable *shared_connections = NULL;
1344 shared_connections_shutdown (void *data)
1346 _DBUS_LOCK (shared_connections);
1348 _dbus_assert (_dbus_hash_table_get_n_entries (shared_connections) == 0);
1349 _dbus_hash_table_unref (shared_connections);
1350 shared_connections = NULL;
1352 _DBUS_UNLOCK (shared_connections);
1356 connection_lookup_shared (DBusAddressEntry *entry,
1357 DBusConnection **result)
1359 _dbus_verbose ("checking for existing connection\n");
1363 _DBUS_LOCK (shared_connections);
1365 if (shared_connections == NULL)
1367 _dbus_verbose ("creating shared_connections hash table\n");
1369 shared_connections = _dbus_hash_table_new (DBUS_HASH_STRING,
1372 if (shared_connections == NULL)
1374 _DBUS_UNLOCK (shared_connections);
1378 if (!_dbus_register_shutdown_func (shared_connections_shutdown, NULL))
1380 _dbus_hash_table_unref (shared_connections);
1381 shared_connections = NULL;
1382 _DBUS_UNLOCK (shared_connections);
1386 _dbus_verbose (" successfully created shared_connections\n");
1388 _DBUS_UNLOCK (shared_connections);
1389 return TRUE; /* no point looking up in the hash we just made */
1395 guid = dbus_address_entry_get_value (entry, "guid");
1399 *result = _dbus_hash_table_lookup_string (shared_connections,
1404 /* The DBusConnection can't have been disconnected
1405 * between the lookup and this code, because the
1406 * disconnection will take the shared_connections lock to
1407 * remove the connection. It can't have been finalized
1408 * since you have to disconnect prior to finalize.
1410 * Thus it's safe to ref the connection.
1412 dbus_connection_ref (*result);
1414 _dbus_verbose ("looked up existing connection to server guid %s\n",
1419 _DBUS_UNLOCK (shared_connections);
1425 connection_record_shared_unlocked (DBusConnection *connection,
1429 char *guid_in_connection;
1431 /* A separate copy of the key is required in the hash table, because
1432 * we don't have a lock on the connection when we are doing a hash
1436 _dbus_assert (connection->server_guid == NULL);
1437 _dbus_assert (connection->shareable);
1439 guid_key = _dbus_strdup (guid);
1440 if (guid_key == NULL)
1443 guid_in_connection = _dbus_strdup (guid);
1444 if (guid_in_connection == NULL)
1446 dbus_free (guid_key);
1450 _DBUS_LOCK (shared_connections);
1451 _dbus_assert (shared_connections != NULL);
1453 if (!_dbus_hash_table_insert_string (shared_connections,
1454 guid_key, connection))
1456 dbus_free (guid_key);
1457 dbus_free (guid_in_connection);
1458 _DBUS_UNLOCK (shared_connections);
1462 connection->server_guid = guid_in_connection;
1464 _dbus_verbose ("stored connection to %s to be shared\n",
1465 connection->server_guid);
1467 _DBUS_UNLOCK (shared_connections);
1469 _dbus_assert (connection->server_guid != NULL);
1475 connection_forget_shared_unlocked (DBusConnection *connection)
1477 HAVE_LOCK_CHECK (connection);
1479 if (connection->server_guid == NULL)
1482 _dbus_verbose ("dropping connection to %s out of the shared table\n",
1483 connection->server_guid);
1485 _DBUS_LOCK (shared_connections);
1487 if (!_dbus_hash_table_remove_string (shared_connections,
1488 connection->server_guid))
1489 _dbus_assert_not_reached ("connection was not in the shared table");
1491 dbus_free (connection->server_guid);
1492 connection->server_guid = NULL;
1494 _DBUS_UNLOCK (shared_connections);
1497 static DBusConnection*
1498 connection_try_from_address_entry (DBusAddressEntry *entry,
1501 DBusTransport *transport;
1502 DBusConnection *connection;
1504 transport = _dbus_transport_open (entry, error);
1506 if (transport == NULL)
1508 _DBUS_ASSERT_ERROR_IS_SET (error);
1512 connection = _dbus_connection_new_for_transport (transport);
1514 _dbus_transport_unref (transport);
1516 if (connection == NULL)
1518 _DBUS_SET_OOM (error);
1522 #ifndef DBUS_DISABLE_CHECKS
1523 _dbus_assert (!connection->have_connection_lock);
1529 * If the shared parameter is true, then any existing connection will
1530 * be used (and if a new connection is created, it will be available
1531 * for use by others). If the shared parameter is false, a new
1532 * connection will always be created, and the new connection will
1533 * never be returned to other callers.
1535 * @param address the address
1536 * @param shared whether the connection is shared or private
1537 * @param error error return
1538 * @returns the connection or #NULL on error
1540 static DBusConnection*
1541 _dbus_connection_open_internal (const char *address,
1545 DBusConnection *connection;
1546 DBusAddressEntry **entries;
1547 DBusError tmp_error;
1548 DBusError first_error;
1551 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1553 _dbus_verbose ("opening %s connection to: %s\n",
1554 shared ? "shared" : "private", address);
1556 if (!dbus_parse_address (address, &entries, &len, error))
1559 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1563 dbus_error_init (&tmp_error);
1564 dbus_error_init (&first_error);
1565 for (i = 0; i < len; i++)
1569 if (!connection_lookup_shared (entries[i], &connection))
1570 _DBUS_SET_OOM (&tmp_error);
1573 if (connection == NULL)
1575 connection = connection_try_from_address_entry (entries[i],
1578 if (connection != NULL && shared)
1582 connection->shareable = TRUE;
1584 guid = dbus_address_entry_get_value (entries[i], "guid");
1586 /* we don't have a connection lock but we know nobody
1587 * else has a handle to the connection
1591 !connection_record_shared_unlocked (connection, guid))
1593 _DBUS_SET_OOM (&tmp_error);
1594 dbus_connection_close (connection);
1595 dbus_connection_unref (connection);
1599 /* but as of now the connection is possibly shared
1600 * since another thread could have pulled it from the table
1608 _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
1611 dbus_move_error (&tmp_error, &first_error);
1613 dbus_error_free (&tmp_error);
1616 /* NOTE we don't have a lock on a possibly-shared connection object */
1618 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1619 _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
1621 if (connection == NULL)
1623 _DBUS_ASSERT_ERROR_IS_SET (&first_error);
1624 dbus_move_error (&first_error, error);
1628 dbus_error_free (&first_error);
1631 dbus_address_entries_free (entries);
1638 * @addtogroup DBusConnection
1644 * Gets a connection to a remote address. If a connection to the given
1645 * address already exists, returns the existing connection with its
1646 * reference count incremented. Otherwise, returns a new connection
1647 * and saves the new connection for possible re-use if a future call
1648 * to dbus_connection_open() asks to connect to the same server.
1650 * Use dbus_connection_open_private() to get a dedicated connection
1651 * not shared with other callers of dbus_connection_open().
1653 * If the open fails, the function returns #NULL, and provides a
1654 * reason for the failure in the error parameter. Pass #NULL for the
1655 * error parameter if you aren't interested in the reason for
1658 * @param address the address.
1659 * @param error address where an error can be returned.
1660 * @returns new connection, or #NULL on failure.
1663 dbus_connection_open (const char *address,
1666 DBusConnection *connection;
1668 _dbus_return_val_if_fail (address != NULL, NULL);
1669 _dbus_return_val_if_error_is_set (error, NULL);
1671 connection = _dbus_connection_open_internal (address,
1679 * Opens a new, dedicated connection to a remote address. Unlike
1680 * dbus_connection_open(), always creates a new connection.
1681 * This connection will not be saved or recycled by libdbus.
1683 * If the open fails, the function returns #NULL, and provides a
1684 * reason for the failure in the error parameter. Pass #NULL for the
1685 * error parameter if you aren't interested in the reason for
1688 * @param address the address.
1689 * @param error address where an error can be returned.
1690 * @returns new connection, or #NULL on failure.
1693 dbus_connection_open_private (const char *address,
1696 DBusConnection *connection;
1698 _dbus_return_val_if_fail (address != NULL, NULL);
1699 _dbus_return_val_if_error_is_set (error, NULL);
1701 connection = _dbus_connection_open_internal (address,
1709 * Increments the reference count of a DBusConnection.
1711 * @param connection the connection.
1712 * @returns the connection.
1715 dbus_connection_ref (DBusConnection *connection)
1717 _dbus_return_val_if_fail (connection != NULL, NULL);
1718 _dbus_return_val_if_fail (connection->generation == _dbus_current_generation, NULL);
1720 /* The connection lock is better than the global
1721 * lock in the atomic increment fallback
1724 #ifdef DBUS_HAVE_ATOMIC_INT
1725 _dbus_atomic_inc (&connection->refcount);
1727 CONNECTION_LOCK (connection);
1728 _dbus_assert (connection->refcount.value > 0);
1730 connection->refcount.value += 1;
1731 CONNECTION_UNLOCK (connection);
1738 free_outgoing_message (void *element,
1741 DBusMessage *message = element;
1742 DBusConnection *connection = data;
1744 _dbus_message_remove_size_counter (message,
1745 connection->outgoing_counter,
1747 dbus_message_unref (message);
1750 /* This is run without the mutex held, but after the last reference
1751 * to the connection has been dropped we should have no thread-related
1755 _dbus_connection_last_unref (DBusConnection *connection)
1759 _dbus_verbose ("Finalizing connection %p\n", connection);
1761 _dbus_assert (connection->refcount.value == 0);
1763 /* You have to disconnect the connection before unref:ing it. Otherwise
1764 * you won't get the disconnected message.
1766 _dbus_assert (!_dbus_transport_get_is_connected (connection->transport));
1767 _dbus_assert (connection->server_guid == NULL);
1769 /* ---- We're going to call various application callbacks here, hope it doesn't break anything... */
1770 _dbus_object_tree_free_all_unlocked (connection->objects);
1772 dbus_connection_set_dispatch_status_function (connection, NULL, NULL, NULL);
1773 dbus_connection_set_wakeup_main_function (connection, NULL, NULL, NULL);
1774 dbus_connection_set_unix_user_function (connection, NULL, NULL, NULL);
1776 _dbus_watch_list_free (connection->watches);
1777 connection->watches = NULL;
1779 _dbus_timeout_list_free (connection->timeouts);
1780 connection->timeouts = NULL;
1782 _dbus_data_slot_list_free (&connection->slot_list);
1784 link = _dbus_list_get_first_link (&connection->filter_list);
1785 while (link != NULL)
1787 DBusMessageFilter *filter = link->data;
1788 DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
1790 filter->function = NULL;
1791 _dbus_message_filter_unref (filter); /* calls app callback */
1796 _dbus_list_clear (&connection->filter_list);
1798 /* ---- Done with stuff that invokes application callbacks */
1800 _dbus_object_tree_unref (connection->objects);
1802 _dbus_hash_table_unref (connection->pending_replies);
1803 connection->pending_replies = NULL;
1805 _dbus_list_clear (&connection->filter_list);
1807 _dbus_list_foreach (&connection->outgoing_messages,
1808 free_outgoing_message,
1810 _dbus_list_clear (&connection->outgoing_messages);
1812 _dbus_list_foreach (&connection->incoming_messages,
1813 (DBusForeachFunction) dbus_message_unref,
1815 _dbus_list_clear (&connection->incoming_messages);
1817 _dbus_counter_unref (connection->outgoing_counter);
1819 _dbus_transport_unref (connection->transport);
1821 if (connection->disconnect_message_link)
1823 DBusMessage *message = connection->disconnect_message_link->data;
1824 dbus_message_unref (message);
1825 _dbus_list_free_link (connection->disconnect_message_link);
1828 _dbus_list_clear (&connection->link_cache);
1830 _dbus_condvar_free (connection->dispatch_cond);
1831 _dbus_condvar_free (connection->io_path_cond);
1833 _dbus_mutex_free (connection->io_path_mutex);
1834 _dbus_mutex_free (connection->dispatch_mutex);
1836 _dbus_mutex_free (connection->mutex);
1838 dbus_free (connection);
1842 * Decrements the reference count of a DBusConnection, and finalizes
1843 * it if the count reaches zero. It is a bug to drop the last reference
1844 * to a connection that has not been disconnected.
1846 * @todo in practice it can be quite tricky to never unref a connection
1847 * that's still connected; maybe there's some way we could avoid
1850 * @param connection the connection.
1853 dbus_connection_unref (DBusConnection *connection)
1855 dbus_bool_t last_unref;
1857 _dbus_return_if_fail (connection != NULL);
1858 _dbus_return_if_fail (connection->generation == _dbus_current_generation);
1860 /* The connection lock is better than the global
1861 * lock in the atomic increment fallback
1864 #ifdef DBUS_HAVE_ATOMIC_INT
1865 last_unref = (_dbus_atomic_dec (&connection->refcount) == 1);
1867 CONNECTION_LOCK (connection);
1869 _dbus_assert (connection->refcount.value > 0);
1871 connection->refcount.value -= 1;
1872 last_unref = (connection->refcount.value == 0);
1875 printf ("unref() connection %p count = %d\n", connection, connection->refcount.value);
1878 CONNECTION_UNLOCK (connection);
1882 _dbus_connection_last_unref (connection);
1886 * Closes the connection, so no further data can be sent or received.
1887 * Any further attempts to send data will result in errors. This
1888 * function does not affect the connection's reference count. It's
1889 * safe to disconnect a connection more than once; all calls after the
1890 * first do nothing. It's impossible to "reopen" a connection, a
1891 * new connection must be created. This function may result in a call
1892 * to the DBusDispatchStatusFunction set with
1893 * dbus_connection_set_dispatch_status_function(), as the disconnect
1894 * message it generates needs to be dispatched.
1896 * @param connection the connection.
1899 dbus_connection_close (DBusConnection *connection)
1901 DBusDispatchStatus status;
1903 _dbus_return_if_fail (connection != NULL);
1904 _dbus_return_if_fail (connection->generation == _dbus_current_generation);
1906 _dbus_verbose ("Disconnecting %p\n", connection);
1908 CONNECTION_LOCK (connection);
1910 _dbus_transport_disconnect (connection->transport);
1912 _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
1913 status = _dbus_connection_get_dispatch_status_unlocked (connection);
1915 /* this calls out to user code */
1916 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1920 _dbus_connection_get_is_connected_unlocked (DBusConnection *connection)
1922 HAVE_LOCK_CHECK (connection);
1923 return _dbus_transport_get_is_connected (connection->transport);
1927 * Gets whether the connection is currently connected. All
1928 * connections are connected when they are opened. A connection may
1929 * become disconnected when the remote application closes its end, or
1930 * exits; a connection may also be disconnected with
1931 * dbus_connection_close().
1933 * @param connection the connection.
1934 * @returns #TRUE if the connection is still alive.
1937 dbus_connection_get_is_connected (DBusConnection *connection)
1941 _dbus_return_val_if_fail (connection != NULL, FALSE);
1943 CONNECTION_LOCK (connection);
1944 res = _dbus_connection_get_is_connected_unlocked (connection);
1945 CONNECTION_UNLOCK (connection);
1951 * Gets whether the connection was authenticated. (Note that
1952 * if the connection was authenticated then disconnected,
1953 * this function still returns #TRUE)
1955 * @param connection the connection
1956 * @returns #TRUE if the connection was ever authenticated
1959 dbus_connection_get_is_authenticated (DBusConnection *connection)
1963 _dbus_return_val_if_fail (connection != NULL, FALSE);
1965 CONNECTION_LOCK (connection);
1966 res = _dbus_transport_get_is_authenticated (connection->transport);
1967 CONNECTION_UNLOCK (connection);
1973 * Set whether _exit() should be called when the connection receives a
1974 * disconnect signal. The call to _exit() comes after any handlers for
1975 * the disconnect signal run; handlers can cancel the exit by calling
1978 * By default, exit_on_disconnect is #FALSE; but for message bus
1979 * connections returned from dbus_bus_get() it will be toggled on
1982 * @param connection the connection
1983 * @param exit_on_disconnect #TRUE if _exit() should be called after a disconnect signal
1986 dbus_connection_set_exit_on_disconnect (DBusConnection *connection,
1987 dbus_bool_t exit_on_disconnect)
1989 _dbus_return_if_fail (connection != NULL);
1991 CONNECTION_LOCK (connection);
1992 connection->exit_on_disconnect = exit_on_disconnect != FALSE;
1993 CONNECTION_UNLOCK (connection);
1996 static DBusPreallocatedSend*
1997 _dbus_connection_preallocate_send_unlocked (DBusConnection *connection)
1999 DBusPreallocatedSend *preallocated;
2001 HAVE_LOCK_CHECK (connection);
2003 _dbus_assert (connection != NULL);
2005 preallocated = dbus_new (DBusPreallocatedSend, 1);
2006 if (preallocated == NULL)
2009 if (connection->link_cache != NULL)
2011 preallocated->queue_link =
2012 _dbus_list_pop_first_link (&connection->link_cache);
2013 preallocated->queue_link->data = NULL;
2017 preallocated->queue_link = _dbus_list_alloc_link (NULL);
2018 if (preallocated->queue_link == NULL)
2022 if (connection->link_cache != NULL)
2024 preallocated->counter_link =
2025 _dbus_list_pop_first_link (&connection->link_cache);
2026 preallocated->counter_link->data = connection->outgoing_counter;
2030 preallocated->counter_link = _dbus_list_alloc_link (connection->outgoing_counter);
2031 if (preallocated->counter_link == NULL)
2035 _dbus_counter_ref (preallocated->counter_link->data);
2037 preallocated->connection = connection;
2039 return preallocated;
2042 _dbus_list_free_link (preallocated->queue_link);
2044 dbus_free (preallocated);
2050 * Preallocates resources needed to send a message, allowing the message
2051 * to be sent without the possibility of memory allocation failure.
2052 * Allows apps to create a future guarantee that they can send
2053 * a message regardless of memory shortages.
2055 * @param connection the connection we're preallocating for.
2056 * @returns the preallocated resources, or #NULL
2058 DBusPreallocatedSend*
2059 dbus_connection_preallocate_send (DBusConnection *connection)
2061 DBusPreallocatedSend *preallocated;
2063 _dbus_return_val_if_fail (connection != NULL, NULL);
2065 CONNECTION_LOCK (connection);
2068 _dbus_connection_preallocate_send_unlocked (connection);
2070 CONNECTION_UNLOCK (connection);
2072 return preallocated;
2076 * Frees preallocated message-sending resources from
2077 * dbus_connection_preallocate_send(). Should only
2078 * be called if the preallocated resources are not used
2079 * to send a message.
2081 * @param connection the connection
2082 * @param preallocated the resources
2085 dbus_connection_free_preallocated_send (DBusConnection *connection,
2086 DBusPreallocatedSend *preallocated)
2088 _dbus_return_if_fail (connection != NULL);
2089 _dbus_return_if_fail (preallocated != NULL);
2090 _dbus_return_if_fail (connection == preallocated->connection);
2092 _dbus_list_free_link (preallocated->queue_link);
2093 _dbus_counter_unref (preallocated->counter_link->data);
2094 _dbus_list_free_link (preallocated->counter_link);
2095 dbus_free (preallocated);
2098 /* Called with lock held, does not update dispatch status */
2100 _dbus_connection_send_preallocated_unlocked_no_update (DBusConnection *connection,
2101 DBusPreallocatedSend *preallocated,
2102 DBusMessage *message,
2103 dbus_uint32_t *client_serial)
2105 dbus_uint32_t serial;
2108 preallocated->queue_link->data = message;
2109 _dbus_list_prepend_link (&connection->outgoing_messages,
2110 preallocated->queue_link);
2112 _dbus_message_add_size_counter_link (message,
2113 preallocated->counter_link);
2115 dbus_free (preallocated);
2116 preallocated = NULL;
2118 dbus_message_ref (message);
2120 connection->n_outgoing += 1;
2122 sig = dbus_message_get_signature (message);
2124 _dbus_verbose ("Message %p (%d %s %s %s '%s') for %s added to outgoing queue %p, %d pending to send\n",
2126 dbus_message_get_type (message),
2127 dbus_message_get_path (message) ?
2128 dbus_message_get_path (message) :
2130 dbus_message_get_interface (message) ?
2131 dbus_message_get_interface (message) :
2133 dbus_message_get_member (message) ?
2134 dbus_message_get_member (message) :
2137 dbus_message_get_destination (message) ?
2138 dbus_message_get_destination (message) :
2141 connection->n_outgoing);
2143 if (dbus_message_get_serial (message) == 0)
2145 serial = _dbus_connection_get_next_client_serial (connection);
2146 _dbus_message_set_serial (message, serial);
2148 *client_serial = serial;
2153 *client_serial = dbus_message_get_serial (message);
2156 _dbus_verbose ("Message %p serial is %u\n",
2157 message, dbus_message_get_serial (message));
2159 _dbus_message_lock (message);
2161 /* Now we need to run an iteration to hopefully just write the messages
2162 * out immediately, and otherwise get them queued up
2164 _dbus_connection_do_iteration_unlocked (connection,
2165 DBUS_ITERATION_DO_WRITING,
2168 /* If stuff is still queued up, be sure we wake up the main loop */
2169 if (connection->n_outgoing > 0)
2170 _dbus_connection_wakeup_mainloop (connection);
2174 _dbus_connection_send_preallocated_and_unlock (DBusConnection *connection,
2175 DBusPreallocatedSend *preallocated,
2176 DBusMessage *message,
2177 dbus_uint32_t *client_serial)
2179 DBusDispatchStatus status;
2181 HAVE_LOCK_CHECK (connection);
2183 _dbus_connection_send_preallocated_unlocked_no_update (connection,
2185 message, client_serial);
2187 _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
2188 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2190 /* this calls out to user code */
2191 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2195 * Sends a message using preallocated resources. This function cannot fail.
2196 * It works identically to dbus_connection_send() in other respects.
2197 * Preallocated resources comes from dbus_connection_preallocate_send().
2198 * This function "consumes" the preallocated resources, they need not
2199 * be freed separately.
2201 * @param connection the connection
2202 * @param preallocated the preallocated resources
2203 * @param message the message to send
2204 * @param client_serial return location for client serial assigned to the message
2207 dbus_connection_send_preallocated (DBusConnection *connection,
2208 DBusPreallocatedSend *preallocated,
2209 DBusMessage *message,
2210 dbus_uint32_t *client_serial)
2212 _dbus_return_if_fail (connection != NULL);
2213 _dbus_return_if_fail (preallocated != NULL);
2214 _dbus_return_if_fail (message != NULL);
2215 _dbus_return_if_fail (preallocated->connection == connection);
2216 _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_METHOD_CALL ||
2217 dbus_message_get_member (message) != NULL);
2218 _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL ||
2219 (dbus_message_get_interface (message) != NULL &&
2220 dbus_message_get_member (message) != NULL));
2222 CONNECTION_LOCK (connection);
2223 _dbus_connection_send_preallocated_and_unlock (connection,
2225 message, client_serial);
2229 _dbus_connection_send_unlocked_no_update (DBusConnection *connection,
2230 DBusMessage *message,
2231 dbus_uint32_t *client_serial)
2233 DBusPreallocatedSend *preallocated;
2235 _dbus_assert (connection != NULL);
2236 _dbus_assert (message != NULL);
2238 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
2239 if (preallocated == NULL)
2242 _dbus_connection_send_preallocated_unlocked_no_update (connection,
2250 _dbus_connection_send_and_unlock (DBusConnection *connection,
2251 DBusMessage *message,
2252 dbus_uint32_t *client_serial)
2254 DBusPreallocatedSend *preallocated;
2256 _dbus_assert (connection != NULL);
2257 _dbus_assert (message != NULL);
2259 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
2260 if (preallocated == NULL)
2262 CONNECTION_UNLOCK (connection);
2266 _dbus_connection_send_preallocated_and_unlock (connection,
2274 * Adds a message to the outgoing message queue. Does not block to
2275 * write the message to the network; that happens asynchronously. To
2276 * force the message to be written, call dbus_connection_flush().
2277 * Because this only queues the message, the only reason it can
2278 * fail is lack of memory. Even if the connection is disconnected,
2279 * no error will be returned.
2281 * If the function fails due to lack of memory, it returns #FALSE.
2282 * The function will never fail for other reasons; even if the
2283 * connection is disconnected, you can queue an outgoing message,
2284 * though obviously it won't be sent.
2286 * @param connection the connection.
2287 * @param message the message to write.
2288 * @param client_serial return location for client serial.
2289 * @returns #TRUE on success.
2292 dbus_connection_send (DBusConnection *connection,
2293 DBusMessage *message,
2294 dbus_uint32_t *client_serial)
2296 _dbus_return_val_if_fail (connection != NULL, FALSE);
2297 _dbus_return_val_if_fail (message != NULL, FALSE);
2299 CONNECTION_LOCK (connection);
2301 return _dbus_connection_send_and_unlock (connection,
2307 reply_handler_timeout (void *data)
2309 DBusConnection *connection;
2310 DBusDispatchStatus status;
2311 DBusPendingCall *pending = data;
2313 connection = _dbus_pending_call_get_connection (pending);
2315 CONNECTION_LOCK (connection);
2316 _dbus_pending_call_queue_timeout_error (pending,
2318 _dbus_connection_remove_timeout_unlocked (connection,
2319 _dbus_pending_call_get_timeout (pending));
2320 _dbus_pending_call_set_timeout_added (pending, FALSE);
2322 _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
2323 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2325 /* Unlocks, and calls out to user code */
2326 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2332 * Queues a message to send, as with dbus_connection_send_message(),
2333 * but also returns a #DBusPendingCall used to receive a reply to the
2334 * message. If no reply is received in the given timeout_milliseconds,
2335 * this function expires the pending reply and generates a synthetic
2336 * error reply (generated in-process, not by the remote application)
2337 * indicating that a timeout occurred.
2339 * A #DBusPendingCall will see a reply message after any filters, but
2340 * before any object instances or other handlers. A #DBusPendingCall
2341 * will always see exactly one reply message, unless it's cancelled
2342 * with dbus_pending_call_cancel().
2344 * If a filter filters out the reply before the handler sees it, the
2345 * reply is immediately timed out and a timeout error reply is
2346 * generated. If a filter removes the timeout error reply then the
2347 * #DBusPendingCall will get confused. Filtering the timeout error
2348 * is thus considered a bug and will print a warning.
2350 * If #NULL is passed for the pending_return, the #DBusPendingCall
2351 * will still be generated internally, and used to track
2352 * the message reply timeout. This means a timeout error will
2353 * occur if no reply arrives, unlike with dbus_connection_send().
2355 * If -1 is passed for the timeout, a sane default timeout is used. -1
2356 * is typically the best value for the timeout for this reason, unless
2357 * you want a very short or very long timeout. There is no way to
2358 * avoid a timeout entirely, other than passing INT_MAX for the
2359 * timeout to postpone it indefinitely.
2361 * @param connection the connection
2362 * @param message the message to send
2363 * @param pending_return return location for a #DBusPendingCall object, or #NULLif connection is disconnected
2364 * @param timeout_milliseconds timeout in milliseconds or -1 for default
2365 * @returns #FALSE if no memory, #TRUE otherwise.
2369 dbus_connection_send_with_reply (DBusConnection *connection,
2370 DBusMessage *message,
2371 DBusPendingCall **pending_return,
2372 int timeout_milliseconds)
2374 DBusPendingCall *pending;
2375 dbus_int32_t serial = -1;
2376 DBusDispatchStatus status;
2378 _dbus_return_val_if_fail (connection != NULL, FALSE);
2379 _dbus_return_val_if_fail (message != NULL, FALSE);
2380 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
2383 *pending_return = NULL;
2385 CONNECTION_LOCK (connection);
2387 if (!_dbus_connection_get_is_connected_unlocked (connection))
2389 CONNECTION_UNLOCK (connection);
2391 *pending_return = NULL;
2396 pending = _dbus_pending_call_new (connection,
2397 timeout_milliseconds,
2398 reply_handler_timeout);
2400 if (pending == NULL)
2402 CONNECTION_UNLOCK (connection);
2406 /* Assign a serial to the message */
2407 serial = dbus_message_get_serial (message);
2410 serial = _dbus_connection_get_next_client_serial (connection);
2411 _dbus_message_set_serial (message, serial);
2414 if (!_dbus_pending_call_set_timeout_error (pending, message, serial))
2417 /* Insert the serial in the pending replies hash;
2418 * hash takes a refcount on DBusPendingCall.
2419 * Also, add the timeout.
2421 if (!_dbus_connection_attach_pending_call_unlocked (connection,
2425 if (!_dbus_connection_send_unlocked_no_update (connection, message, NULL))
2427 _dbus_connection_detach_pending_call_and_unlock (connection,
2429 goto error_unlocked;
2433 *pending_return = pending;
2436 _dbus_connection_detach_pending_call_unlocked (connection, pending);
2437 dbus_pending_call_unref (pending);
2440 _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
2441 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2443 /* this calls out to user code */
2444 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2449 CONNECTION_UNLOCK (connection);
2451 dbus_pending_call_unref (pending);
2455 /* This is slightly strange since we can pop a message here without
2456 * the dispatch lock.
2459 check_for_reply_unlocked (DBusConnection *connection,
2460 dbus_uint32_t client_serial)
2464 HAVE_LOCK_CHECK (connection);
2466 link = _dbus_list_get_first_link (&connection->incoming_messages);
2468 while (link != NULL)
2470 DBusMessage *reply = link->data;
2472 if (dbus_message_get_reply_serial (reply) == client_serial)
2474 _dbus_list_remove_link (&connection->incoming_messages, link);
2475 connection->n_incoming -= 1;
2478 link = _dbus_list_get_next_link (&connection->incoming_messages, link);
2485 connection_timeout_and_complete_all_pending_calls_unlocked (DBusConnection *connection)
2489 _dbus_hash_iter_init (connection->pending_replies, &iter);
2491 /* create list while we remove the iters from the hash
2492 because we need to go over it a couple of times */
2493 while (_dbus_hash_iter_next (&iter))
2495 DBusPendingCall *pending;
2497 pending = (DBusPendingCall *) _dbus_hash_iter_get_value (&iter);
2498 dbus_pending_call_ref (pending);
2500 _dbus_pending_call_queue_timeout_error (pending,
2502 _dbus_connection_remove_timeout_unlocked (connection,
2503 _dbus_pending_call_get_timeout (pending));
2505 _dbus_hash_iter_remove_entry (&iter);
2507 dbus_pending_call_unref (pending);
2512 complete_pending_call_and_unlock (DBusPendingCall *pending,
2513 DBusMessage *message)
2515 _dbus_pending_call_set_reply (pending, message);
2516 dbus_pending_call_ref (pending); /* in case there's no app with a ref held */
2517 _dbus_connection_detach_pending_call_and_unlock (_dbus_pending_call_get_connection (pending), pending);
2519 /* Must be called unlocked since it invokes app callback */
2520 _dbus_pending_call_complete (pending);
2521 dbus_pending_call_unref (pending);
2525 check_for_reply_and_update_dispatch_unlocked (DBusPendingCall *pending)
2528 DBusDispatchStatus status;
2529 DBusConnection *connection;
2531 connection = _dbus_pending_call_get_connection (pending);
2533 reply = check_for_reply_unlocked (connection,
2534 _dbus_pending_call_get_reply_serial (pending));
2537 _dbus_verbose ("%s checked for reply\n", _DBUS_FUNCTION_NAME);
2539 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): got reply\n");
2541 complete_pending_call_and_unlock (pending, reply);
2542 dbus_message_unref (reply);
2544 CONNECTION_LOCK (connection);
2545 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2546 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2547 dbus_pending_call_unref (pending);
2556 * When a function that blocks has been called with a timeout, and we
2557 * run out of memory, the time to wait for memory is based on the
2558 * timeout. If the caller was willing to block a long time we wait a
2559 * relatively long time for memory, if they were only willing to block
2560 * briefly then we retry for memory at a rapid rate.
2562 * @timeout_milliseconds the timeout requested for blocking
2565 _dbus_memory_pause_based_on_timeout (int timeout_milliseconds)
2567 if (timeout_milliseconds == -1)
2568 _dbus_sleep_milliseconds (1000);
2569 else if (timeout_milliseconds < 100)
2570 ; /* just busy loop */
2571 else if (timeout_milliseconds <= 1000)
2572 _dbus_sleep_milliseconds (timeout_milliseconds / 3);
2574 _dbus_sleep_milliseconds (1000);
2578 * Blocks until a pending call times out or gets a reply.
2580 * Does not re-enter the main loop or run filter/path-registered
2581 * callbacks. The reply to the message will not be seen by
2584 * Returns immediately if pending call already got a reply.
2586 * @todo could use performance improvements (it keeps scanning
2587 * the whole message queue for example)
2589 * @param pending the pending call we block for a reply on
2592 _dbus_connection_block_pending_call (DBusPendingCall *pending)
2594 long start_tv_sec, start_tv_usec;
2595 long end_tv_sec, end_tv_usec;
2596 long tv_sec, tv_usec;
2597 DBusDispatchStatus status;
2598 DBusConnection *connection;
2599 dbus_uint32_t client_serial;
2600 int timeout_milliseconds;
2602 _dbus_assert (pending != NULL);
2604 if (dbus_pending_call_get_completed (pending))
2607 connection = _dbus_pending_call_get_connection (pending);
2608 if (connection == NULL)
2609 return; /* call already detached */
2611 dbus_pending_call_ref (pending); /* necessary because the call could be canceled */
2612 client_serial = _dbus_pending_call_get_reply_serial (pending);
2614 /* note that timeout_milliseconds is limited to a smallish value
2615 * in _dbus_pending_call_new() so overflows aren't possible
2618 timeout_milliseconds = dbus_timeout_get_interval (_dbus_pending_call_get_timeout (pending));
2620 /* Flush message queue */
2621 dbus_connection_flush (connection);
2623 CONNECTION_LOCK (connection);
2625 _dbus_get_current_time (&start_tv_sec, &start_tv_usec);
2626 end_tv_sec = start_tv_sec + timeout_milliseconds / 1000;
2627 end_tv_usec = start_tv_usec + (timeout_milliseconds % 1000) * 1000;
2628 end_tv_sec += end_tv_usec / _DBUS_USEC_PER_SECOND;
2629 end_tv_usec = end_tv_usec % _DBUS_USEC_PER_SECOND;
2631 _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",
2632 timeout_milliseconds,
2634 start_tv_sec, start_tv_usec,
2635 end_tv_sec, end_tv_usec);
2637 /* check to see if we already got the data off the socket */
2638 /* from another blocked pending call */
2639 if (check_for_reply_and_update_dispatch_unlocked (pending))
2642 /* Now we wait... */
2643 /* always block at least once as we know we don't have the reply yet */
2644 _dbus_connection_do_iteration_unlocked (connection,
2645 DBUS_ITERATION_DO_READING |
2646 DBUS_ITERATION_BLOCK,
2647 timeout_milliseconds);
2651 _dbus_verbose ("%s top of recheck\n", _DBUS_FUNCTION_NAME);
2653 HAVE_LOCK_CHECK (connection);
2655 /* queue messages and get status */
2657 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2659 /* the get_completed() is in case a dispatch() while we were blocking
2660 * got the reply instead of us.
2662 if (dbus_pending_call_get_completed (pending))
2664 _dbus_verbose ("Pending call completed by dispatch in %s\n", _DBUS_FUNCTION_NAME);
2665 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2666 dbus_pending_call_unref (pending);
2670 if (status == DBUS_DISPATCH_DATA_REMAINS)
2671 if (check_for_reply_and_update_dispatch_unlocked (pending))
2674 _dbus_get_current_time (&tv_sec, &tv_usec);
2676 if (!_dbus_connection_get_is_connected_unlocked (connection))
2678 /* FIXME send a "DBUS_ERROR_DISCONNECTED" instead, just to help
2679 * programmers understand what went wrong since the timeout is
2683 complete_pending_call_and_unlock (pending, NULL);
2684 dbus_pending_call_unref (pending);
2687 else if (tv_sec < start_tv_sec)
2688 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): clock set backward\n");
2689 else if (connection->disconnect_message_link == NULL)
2690 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): disconnected\n");
2691 else if (tv_sec < end_tv_sec ||
2692 (tv_sec == end_tv_sec && tv_usec < end_tv_usec))
2694 timeout_milliseconds = (end_tv_sec - tv_sec) * 1000 +
2695 (end_tv_usec - tv_usec) / 1000;
2696 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): %d milliseconds remain\n", timeout_milliseconds);
2697 _dbus_assert (timeout_milliseconds >= 0);
2699 if (status == DBUS_DISPATCH_NEED_MEMORY)
2701 /* Try sleeping a bit, as we aren't sure we need to block for reading,
2702 * we may already have a reply in the buffer and just can't process
2705 _dbus_verbose ("dbus_connection_send_with_reply_and_block() waiting for more memory\n");
2707 _dbus_memory_pause_based_on_timeout (timeout_milliseconds);
2711 /* block again, we don't have the reply buffered yet. */
2712 _dbus_connection_do_iteration_unlocked (connection,
2713 DBUS_ITERATION_DO_READING |
2714 DBUS_ITERATION_BLOCK,
2715 timeout_milliseconds);
2718 goto recheck_status;
2721 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): Waited %ld milliseconds and got no reply\n",
2722 (tv_sec - start_tv_sec) * 1000 + (tv_usec - start_tv_usec) / 1000);
2724 _dbus_assert (!dbus_pending_call_get_completed (pending));
2726 /* unlock and call user code */
2727 complete_pending_call_and_unlock (pending, NULL);
2729 /* update user code on dispatch status */
2730 CONNECTION_LOCK (connection);
2731 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2732 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2733 dbus_pending_call_unref (pending);
2737 * Sends a message and blocks a certain time period while waiting for
2738 * a reply. This function does not reenter the main loop,
2739 * i.e. messages other than the reply are queued up but not
2740 * processed. This function is used to do non-reentrant "method
2743 * If a normal reply is received, it is returned, and removed from the
2744 * incoming message queue. If it is not received, #NULL is returned
2745 * and the error is set to #DBUS_ERROR_NO_REPLY. If an error reply is
2746 * received, it is converted to a #DBusError and returned as an error,
2747 * then the reply message is deleted. If something else goes wrong,
2748 * result is set to whatever is appropriate, such as
2749 * #DBUS_ERROR_NO_MEMORY or #DBUS_ERROR_DISCONNECTED.
2751 * @param connection the connection
2752 * @param message the message to send
2753 * @param timeout_milliseconds timeout in milliseconds or -1 for default
2754 * @param error return location for error message
2755 * @returns the message that is the reply or #NULL with an error code if the
2759 dbus_connection_send_with_reply_and_block (DBusConnection *connection,
2760 DBusMessage *message,
2761 int timeout_milliseconds,
2765 DBusPendingCall *pending;
2767 _dbus_return_val_if_fail (connection != NULL, NULL);
2768 _dbus_return_val_if_fail (message != NULL, NULL);
2769 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, NULL);
2770 _dbus_return_val_if_error_is_set (error, NULL);
2772 if (!dbus_connection_send_with_reply (connection, message,
2773 &pending, timeout_milliseconds))
2775 _DBUS_SET_OOM (error);
2779 _dbus_assert (pending != NULL);
2781 dbus_pending_call_block (pending);
2783 reply = dbus_pending_call_steal_reply (pending);
2784 dbus_pending_call_unref (pending);
2786 /* call_complete_and_unlock() called from pending_call_block() should
2787 * always fill this in.
2789 _dbus_assert (reply != NULL);
2791 if (dbus_set_error_from_message (error, reply))
2793 dbus_message_unref (reply);
2801 * Blocks until the outgoing message queue is empty.
2803 * @param connection the connection.
2806 dbus_connection_flush (DBusConnection *connection)
2808 /* We have to specify DBUS_ITERATION_DO_READING here because
2809 * otherwise we could have two apps deadlock if they are both doing
2810 * a flush(), and the kernel buffers fill up. This could change the
2813 DBusDispatchStatus status;
2815 _dbus_return_if_fail (connection != NULL);
2817 CONNECTION_LOCK (connection);
2818 while (connection->n_outgoing > 0 &&
2819 _dbus_connection_get_is_connected_unlocked (connection))
2821 _dbus_verbose ("doing iteration in %s\n", _DBUS_FUNCTION_NAME);
2822 HAVE_LOCK_CHECK (connection);
2823 _dbus_connection_do_iteration_unlocked (connection,
2824 DBUS_ITERATION_DO_READING |
2825 DBUS_ITERATION_DO_WRITING |
2826 DBUS_ITERATION_BLOCK,
2830 HAVE_LOCK_CHECK (connection);
2831 _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
2832 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2834 HAVE_LOCK_CHECK (connection);
2835 /* Unlocks and calls out to user code */
2836 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2838 _dbus_verbose ("%s end\n", _DBUS_FUNCTION_NAME);
2842 * This function is intended for use with applications that don't want
2843 * to write a main loop and deal with #DBusWatch and #DBusTimeout. An
2844 * example usage would be:
2847 * while (dbus_connection_read_write_dispatch (connection, -1))
2848 * ; // empty loop body
2851 * In this usage you would normally have set up a filter function to look
2852 * at each message as it is dispatched. The loop terminates when the last
2853 * message from the connection (the disconnected signal) is processed.
2855 * If there are messages to dispatch and the dispatch flag is set, this
2856 * function will dbus_connection_dispatch() once, and return. If there are no
2857 * messages to dispatch, this function will block until it can read or write,
2858 * then read or write, then return.
2860 * The way to think of this function is that it either makes some sort
2861 * of progress, or it blocks.
2863 * The return value indicates whether the disconnect message has been
2864 * processed, NOT whether the connection is connected. This is
2865 * important because even after disconnecting, you want to process any
2866 * messages you received prior to the disconnect.
2868 * @param connection the connection
2869 * @param timeout_milliseconds max time to block or -1 for infinite
2870 * @param dispatch dispatch new messages or leave them on the incoming queue
2871 * @returns #TRUE if the disconnect message has not been processed
2874 _dbus_connection_read_write_dispatch (DBusConnection *connection,
2875 int timeout_milliseconds,
2876 dbus_bool_t dispatch)
2878 DBusDispatchStatus dstatus;
2879 dbus_bool_t dispatched_disconnected;
2881 dstatus = dbus_connection_get_dispatch_status (connection);
2883 if (dispatch && dstatus == DBUS_DISPATCH_DATA_REMAINS)
2885 _dbus_verbose ("doing dispatch in %s\n", _DBUS_FUNCTION_NAME);
2886 dbus_connection_dispatch (connection);
2887 CONNECTION_LOCK (connection);
2889 else if (dstatus == DBUS_DISPATCH_NEED_MEMORY)
2891 _dbus_verbose ("pausing for memory in %s\n", _DBUS_FUNCTION_NAME);
2892 _dbus_memory_pause_based_on_timeout (timeout_milliseconds);
2893 CONNECTION_LOCK (connection);
2897 CONNECTION_LOCK (connection);
2898 if (_dbus_connection_get_is_connected_unlocked (connection))
2900 _dbus_verbose ("doing iteration in %s\n", _DBUS_FUNCTION_NAME);
2901 _dbus_connection_do_iteration_unlocked (connection,
2902 DBUS_ITERATION_DO_READING |
2903 DBUS_ITERATION_DO_WRITING |
2904 DBUS_ITERATION_BLOCK,
2905 timeout_milliseconds);
2909 HAVE_LOCK_CHECK (connection);
2910 dispatched_disconnected = connection->n_incoming == 0 &&
2911 connection->disconnect_message_link == NULL;
2912 CONNECTION_UNLOCK (connection);
2913 return !dispatched_disconnected; /* TRUE if we have not processed disconnected */
2918 * This function is intended for use with applications that don't want
2919 * to write a main loop and deal with #DBusWatch and #DBusTimeout. An
2920 * example usage would be:
2923 * while (dbus_connection_read_write_dispatch (connection, -1))
2924 * ; // empty loop body
2927 * In this usage you would normally have set up a filter function to look
2928 * at each message as it is dispatched. The loop terminates when the last
2929 * message from the connection (the disconnected signal) is processed.
2931 * If there are messages to dispatch, this function will
2932 * dbus_connection_dispatch() once, and return. If there are no
2933 * messages to dispatch, this function will block until it can read or
2934 * write, then read or write, then return.
2936 * The way to think of this function is that it either makes some sort
2937 * of progress, or it blocks.
2939 * The return value indicates whether the disconnect message has been
2940 * processed, NOT whether the connection is connected. This is
2941 * important because even after disconnecting, you want to process any
2942 * messages you received prior to the disconnect.
2944 * @param connection the connection
2945 * @param timeout_milliseconds max time to block or -1 for infinite
2946 * @returns #TRUE if the disconnect message has not been processed
2949 dbus_connection_read_write_dispatch (DBusConnection *connection,
2950 int timeout_milliseconds)
2952 _dbus_return_val_if_fail (connection != NULL, FALSE);
2953 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
2954 return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, TRUE);
2958 * This function is intended for use with applications that don't want to
2959 * write a main loop and deal with #DBusWatch and #DBusTimeout.
2961 * If there are no messages to dispatch, this function will block until it can
2962 * read or write, then read or write, then return.
2964 * The return value indicates whether the disconnect message has been
2965 * processed, NOT whether the connection is connected. This is important
2966 * because even after disconnecting, you want to process any messages you
2967 * received prior to the disconnect.
2969 * @param connection the connection
2970 * @param timeout_milliseconds max time to block or -1 for infinite
2971 * @returns #TRUE if the disconnect message has not been processed
2974 dbus_connection_read_write (DBusConnection *connection,
2975 int timeout_milliseconds)
2977 _dbus_return_val_if_fail (connection != NULL, FALSE);
2978 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
2979 return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, FALSE);
2983 * Returns the first-received message from the incoming message queue,
2984 * leaving it in the queue. If the queue is empty, returns #NULL.
2986 * The caller does not own a reference to the returned message, and
2987 * must either return it using dbus_connection_return_message() or
2988 * keep it after calling dbus_connection_steal_borrowed_message(). No
2989 * one can get at the message while its borrowed, so return it as
2990 * quickly as possible and don't keep a reference to it after
2991 * returning it. If you need to keep the message, make a copy of it.
2993 * dbus_connection_dispatch() will block if called while a borrowed
2994 * message is outstanding; only one piece of code can be playing with
2995 * the incoming queue at a time. This function will block if called
2996 * during a dbus_connection_dispatch().
2998 * @param connection the connection.
2999 * @returns next message in the incoming queue.
3002 dbus_connection_borrow_message (DBusConnection *connection)
3004 DBusDispatchStatus status;
3005 DBusMessage *message;
3007 _dbus_return_val_if_fail (connection != NULL, NULL);
3009 _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
3011 /* this is called for the side effect that it queues
3012 * up any messages from the transport
3014 status = dbus_connection_get_dispatch_status (connection);
3015 if (status != DBUS_DISPATCH_DATA_REMAINS)
3018 CONNECTION_LOCK (connection);
3020 _dbus_connection_acquire_dispatch (connection);
3022 /* While a message is outstanding, the dispatch lock is held */
3023 _dbus_assert (connection->message_borrowed == NULL);
3025 connection->message_borrowed = _dbus_list_get_first (&connection->incoming_messages);
3027 message = connection->message_borrowed;
3029 /* Note that we KEEP the dispatch lock until the message is returned */
3030 if (message == NULL)
3031 _dbus_connection_release_dispatch (connection);
3033 CONNECTION_UNLOCK (connection);
3039 * Used to return a message after peeking at it using
3040 * dbus_connection_borrow_message(). Only called if
3041 * message from dbus_connection_borrow_message() was non-#NULL.
3043 * @param connection the connection
3044 * @param message the message from dbus_connection_borrow_message()
3047 dbus_connection_return_message (DBusConnection *connection,
3048 DBusMessage *message)
3050 _dbus_return_if_fail (connection != NULL);
3051 _dbus_return_if_fail (message != NULL);
3052 _dbus_return_if_fail (message == connection->message_borrowed);
3053 _dbus_return_if_fail (connection->dispatch_acquired);
3055 CONNECTION_LOCK (connection);
3057 _dbus_assert (message == connection->message_borrowed);
3059 connection->message_borrowed = NULL;
3061 _dbus_connection_release_dispatch (connection);
3063 CONNECTION_UNLOCK (connection);
3067 * Used to keep a message after peeking at it using
3068 * dbus_connection_borrow_message(). Before using this function, see
3069 * the caveats/warnings in the documentation for
3070 * dbus_connection_pop_message().
3072 * @param connection the connection
3073 * @param message the message from dbus_connection_borrow_message()
3076 dbus_connection_steal_borrowed_message (DBusConnection *connection,
3077 DBusMessage *message)
3079 DBusMessage *pop_message;
3081 _dbus_return_if_fail (connection != NULL);
3082 _dbus_return_if_fail (message != NULL);
3083 _dbus_return_if_fail (message == connection->message_borrowed);
3084 _dbus_return_if_fail (connection->dispatch_acquired);
3086 CONNECTION_LOCK (connection);
3088 _dbus_assert (message == connection->message_borrowed);
3090 pop_message = _dbus_list_pop_first (&connection->incoming_messages);
3091 _dbus_assert (message == pop_message);
3093 connection->n_incoming -= 1;
3095 _dbus_verbose ("Incoming message %p stolen from queue, %d incoming\n",
3096 message, connection->n_incoming);
3098 connection->message_borrowed = NULL;
3100 _dbus_connection_release_dispatch (connection);
3102 CONNECTION_UNLOCK (connection);
3105 /* See dbus_connection_pop_message, but requires the caller to own
3106 * the lock before calling. May drop the lock while running.
3109 _dbus_connection_pop_message_link_unlocked (DBusConnection *connection)
3111 HAVE_LOCK_CHECK (connection);
3113 _dbus_assert (connection->message_borrowed == NULL);
3115 if (connection->n_incoming > 0)
3119 link = _dbus_list_pop_first_link (&connection->incoming_messages);
3120 connection->n_incoming -= 1;
3122 _dbus_verbose ("Message %p (%d %s %s %s '%s') removed from incoming queue %p, %d incoming\n",
3124 dbus_message_get_type (link->data),
3125 dbus_message_get_path (link->data) ?
3126 dbus_message_get_path (link->data) :
3128 dbus_message_get_interface (link->data) ?
3129 dbus_message_get_interface (link->data) :
3131 dbus_message_get_member (link->data) ?
3132 dbus_message_get_member (link->data) :
3134 dbus_message_get_signature (link->data),
3135 connection, connection->n_incoming);
3143 /* See dbus_connection_pop_message, but requires the caller to own
3144 * the lock before calling. May drop the lock while running.
3147 _dbus_connection_pop_message_unlocked (DBusConnection *connection)
3151 HAVE_LOCK_CHECK (connection);
3153 link = _dbus_connection_pop_message_link_unlocked (connection);
3157 DBusMessage *message;
3159 message = link->data;
3161 _dbus_list_free_link (link);
3170 _dbus_connection_putback_message_link_unlocked (DBusConnection *connection,
3171 DBusList *message_link)
3173 HAVE_LOCK_CHECK (connection);
3175 _dbus_assert (message_link != NULL);
3176 /* You can't borrow a message while a link is outstanding */
3177 _dbus_assert (connection->message_borrowed == NULL);
3178 /* We had to have the dispatch lock across the pop/putback */
3179 _dbus_assert (connection->dispatch_acquired);
3181 _dbus_list_prepend_link (&connection->incoming_messages,
3183 connection->n_incoming += 1;
3185 _dbus_verbose ("Message %p (%d %s %s '%s') put back into queue %p, %d incoming\n",
3187 dbus_message_get_type (message_link->data),
3188 dbus_message_get_interface (message_link->data) ?
3189 dbus_message_get_interface (message_link->data) :
3191 dbus_message_get_member (message_link->data) ?
3192 dbus_message_get_member (message_link->data) :
3194 dbus_message_get_signature (message_link->data),
3195 connection, connection->n_incoming);
3199 * Returns the first-received message from the incoming message queue,
3200 * removing it from the queue. The caller owns a reference to the
3201 * returned message. If the queue is empty, returns #NULL.
3203 * This function bypasses any message handlers that are registered,
3204 * and so using it is usually wrong. Instead, let the main loop invoke
3205 * dbus_connection_dispatch(). Popping messages manually is only
3206 * useful in very simple programs that don't share a #DBusConnection
3207 * with any libraries or other modules.
3209 * There is a lock that covers all ways of accessing the incoming message
3210 * queue, so dbus_connection_dispatch(), dbus_connection_pop_message(),
3211 * dbus_connection_borrow_message(), etc. will all block while one of the others
3212 * in the group is running.
3214 * @param connection the connection.
3215 * @returns next message in the incoming queue.
3218 dbus_connection_pop_message (DBusConnection *connection)
3220 DBusMessage *message;
3221 DBusDispatchStatus status;
3223 _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
3225 /* this is called for the side effect that it queues
3226 * up any messages from the transport
3228 status = dbus_connection_get_dispatch_status (connection);
3229 if (status != DBUS_DISPATCH_DATA_REMAINS)
3232 CONNECTION_LOCK (connection);
3233 _dbus_connection_acquire_dispatch (connection);
3234 HAVE_LOCK_CHECK (connection);
3236 message = _dbus_connection_pop_message_unlocked (connection);
3238 _dbus_verbose ("Returning popped message %p\n", message);
3240 _dbus_connection_release_dispatch (connection);
3241 CONNECTION_UNLOCK (connection);
3247 * Acquire the dispatcher. This is a separate lock so the main
3248 * connection lock can be dropped to call out to application dispatch
3251 * @param connection the connection.
3254 _dbus_connection_acquire_dispatch (DBusConnection *connection)
3256 HAVE_LOCK_CHECK (connection);
3258 _dbus_connection_ref_unlocked (connection);
3259 CONNECTION_UNLOCK (connection);
3261 _dbus_verbose ("%s locking dispatch_mutex\n", _DBUS_FUNCTION_NAME);
3262 _dbus_mutex_lock (connection->dispatch_mutex);
3264 while (connection->dispatch_acquired)
3266 _dbus_verbose ("%s waiting for dispatch to be acquirable\n", _DBUS_FUNCTION_NAME);
3267 _dbus_condvar_wait (connection->dispatch_cond, connection->dispatch_mutex);
3270 _dbus_assert (!connection->dispatch_acquired);
3272 connection->dispatch_acquired = TRUE;
3274 _dbus_verbose ("%s unlocking dispatch_mutex\n", _DBUS_FUNCTION_NAME);
3275 _dbus_mutex_unlock (connection->dispatch_mutex);
3277 CONNECTION_LOCK (connection);
3278 _dbus_connection_unref_unlocked (connection);
3282 * Release the dispatcher when you're done with it. Only call
3283 * after you've acquired the dispatcher. Wakes up at most one
3284 * thread currently waiting to acquire the dispatcher.
3286 * @param connection the connection.
3289 _dbus_connection_release_dispatch (DBusConnection *connection)
3291 HAVE_LOCK_CHECK (connection);
3293 _dbus_verbose ("%s locking dispatch_mutex\n", _DBUS_FUNCTION_NAME);
3294 _dbus_mutex_lock (connection->dispatch_mutex);
3296 _dbus_assert (connection->dispatch_acquired);
3298 connection->dispatch_acquired = FALSE;
3299 _dbus_condvar_wake_one (connection->dispatch_cond);
3301 _dbus_verbose ("%s unlocking dispatch_mutex\n", _DBUS_FUNCTION_NAME);
3302 _dbus_mutex_unlock (connection->dispatch_mutex);
3306 _dbus_connection_failed_pop (DBusConnection *connection,
3307 DBusList *message_link)
3309 _dbus_list_prepend_link (&connection->incoming_messages,
3311 connection->n_incoming += 1;
3314 static DBusDispatchStatus
3315 _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection)
3317 HAVE_LOCK_CHECK (connection);
3319 if (connection->n_incoming > 0)
3320 return DBUS_DISPATCH_DATA_REMAINS;
3321 else if (!_dbus_transport_queue_messages (connection->transport))
3322 return DBUS_DISPATCH_NEED_MEMORY;
3325 DBusDispatchStatus status;
3326 dbus_bool_t is_connected;
3328 status = _dbus_transport_get_dispatch_status (connection->transport);
3329 is_connected = _dbus_transport_get_is_connected (connection->transport);
3331 _dbus_verbose ("dispatch status = %s is_connected = %d\n",
3332 DISPATCH_STATUS_NAME (status), is_connected);
3336 if (status == DBUS_DISPATCH_COMPLETE &&
3337 connection->disconnect_message_link)
3339 _dbus_verbose ("Sending disconnect message from %s\n",
3340 _DBUS_FUNCTION_NAME);
3342 connection_forget_shared_unlocked (connection);
3344 /* If we have pending calls queued timeouts on disconnect */
3345 connection_timeout_and_complete_all_pending_calls_unlocked (connection);
3347 /* We haven't sent the disconnect message already,
3348 * and all real messages have been queued up.
3350 _dbus_connection_queue_synthesized_message_link (connection,
3351 connection->disconnect_message_link);
3352 connection->disconnect_message_link = NULL;
3354 status = DBUS_DISPATCH_DATA_REMAINS;
3357 /* Dump the outgoing queue, we aren't going to be able to
3358 * send it now, and we'd like accessors like
3359 * dbus_connection_get_outgoing_size() to be accurate.
3361 if (connection->n_outgoing > 0)
3365 _dbus_verbose ("Dropping %d outgoing messages since we're disconnected\n",
3366 connection->n_outgoing);
3368 while ((link = _dbus_list_get_last_link (&connection->outgoing_messages)))
3370 _dbus_connection_message_sent (connection, link->data);
3375 if (status != DBUS_DISPATCH_COMPLETE)
3377 else if (connection->n_incoming > 0)
3378 return DBUS_DISPATCH_DATA_REMAINS;
3380 return DBUS_DISPATCH_COMPLETE;
3385 _dbus_connection_update_dispatch_status_and_unlock (DBusConnection *connection,
3386 DBusDispatchStatus new_status)
3388 dbus_bool_t changed;
3389 DBusDispatchStatusFunction function;
3392 HAVE_LOCK_CHECK (connection);
3394 _dbus_connection_ref_unlocked (connection);
3396 changed = new_status != connection->last_dispatch_status;
3398 connection->last_dispatch_status = new_status;
3400 function = connection->dispatch_status_function;
3401 data = connection->dispatch_status_data;
3403 /* We drop the lock */
3404 CONNECTION_UNLOCK (connection);
3406 if (changed && function)
3408 _dbus_verbose ("Notifying of change to dispatch status of %p now %d (%s)\n",
3409 connection, new_status,
3410 DISPATCH_STATUS_NAME (new_status));
3411 (* function) (connection, new_status, data);
3414 dbus_connection_unref (connection);
3418 * Gets the current state (what we would currently return
3419 * from dbus_connection_dispatch()) but doesn't actually
3420 * dispatch any messages.
3422 * @param connection the connection.
3423 * @returns current dispatch status
3426 dbus_connection_get_dispatch_status (DBusConnection *connection)
3428 DBusDispatchStatus status;
3430 _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
3432 _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
3434 CONNECTION_LOCK (connection);
3436 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3438 CONNECTION_UNLOCK (connection);
3444 * Filter funtion for handling the Peer standard interface
3446 static DBusHandlerResult
3447 _dbus_connection_peer_filter_unlocked_no_update (DBusConnection *connection,
3448 DBusMessage *message)
3450 if (dbus_message_is_method_call (message,
3451 DBUS_INTERFACE_PEER,
3457 ret = dbus_message_new_method_return (message);
3459 return DBUS_HANDLER_RESULT_NEED_MEMORY;
3461 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
3463 dbus_message_unref (ret);
3466 return DBUS_HANDLER_RESULT_NEED_MEMORY;
3468 return DBUS_HANDLER_RESULT_HANDLED;
3472 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
3476 * Processes all builtin filter functions
3478 * If the spec specifies a standard interface
3479 * they should be processed from this method
3481 static DBusHandlerResult
3482 _dbus_connection_run_builtin_filters_unlocked_no_update (DBusConnection *connection,
3483 DBusMessage *message)
3485 /* We just run one filter for now but have the option to run more
3486 if the spec calls for it in the future */
3488 return _dbus_connection_peer_filter_unlocked_no_update (connection, message);
3492 * Processes data buffered while handling watches, queueing zero or
3493 * more incoming messages. Then pops the first-received message from
3494 * the current incoming message queue, runs any handlers for it, and
3495 * unrefs the message. Returns a status indicating whether messages/data
3496 * remain, more memory is needed, or all data has been processed.
3498 * Even if the dispatch status is #DBUS_DISPATCH_DATA_REMAINS,
3499 * does not necessarily dispatch a message, as the data may
3500 * be part of authentication or the like.
3502 * @todo some FIXME in here about handling DBUS_HANDLER_RESULT_NEED_MEMORY
3504 * @todo FIXME what if we call out to application code to handle a
3505 * message, holding the dispatch lock, and the application code runs
3506 * the main loop and dispatches again? Probably deadlocks at the
3507 * moment. Maybe we want a dispatch status of DBUS_DISPATCH_IN_PROGRESS,
3508 * and then the GSource etc. could handle the situation? Right now
3509 * our GSource is NO_RECURSE
3511 * @param connection the connection
3512 * @returns dispatch status
3515 dbus_connection_dispatch (DBusConnection *connection)
3517 DBusMessage *message;
3518 DBusList *link, *filter_list_copy, *message_link;
3519 DBusHandlerResult result;
3520 DBusPendingCall *pending;
3521 dbus_int32_t reply_serial;
3522 DBusDispatchStatus status;
3524 _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
3526 _dbus_verbose ("%s\n", _DBUS_FUNCTION_NAME);
3528 CONNECTION_LOCK (connection);
3529 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3530 if (status != DBUS_DISPATCH_DATA_REMAINS)
3532 /* unlocks and calls out to user code */
3533 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3537 /* We need to ref the connection since the callback could potentially
3538 * drop the last ref to it
3540 _dbus_connection_ref_unlocked (connection);
3542 _dbus_connection_acquire_dispatch (connection);
3543 HAVE_LOCK_CHECK (connection);
3545 message_link = _dbus_connection_pop_message_link_unlocked (connection);
3546 if (message_link == NULL)
3548 /* another thread dispatched our stuff */
3550 _dbus_verbose ("another thread dispatched message (during acquire_dispatch above)\n");
3552 _dbus_connection_release_dispatch (connection);
3554 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3556 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3558 dbus_connection_unref (connection);
3563 message = message_link->data;
3565 _dbus_verbose (" dispatching message %p (%d %s %s '%s')\n",
3567 dbus_message_get_type (message),
3568 dbus_message_get_interface (message) ?
3569 dbus_message_get_interface (message) :
3571 dbus_message_get_member (message) ?
3572 dbus_message_get_member (message) :
3574 dbus_message_get_signature (message));
3576 result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
3578 /* Pending call handling must be first, because if you do
3579 * dbus_connection_send_with_reply_and_block() or
3580 * dbus_pending_call_block() then no handlers/filters will be run on
3581 * the reply. We want consistent semantics in the case where we
3582 * dbus_connection_dispatch() the reply.
3585 reply_serial = dbus_message_get_reply_serial (message);
3586 pending = _dbus_hash_table_lookup_int (connection->pending_replies,
3590 _dbus_verbose ("Dispatching a pending reply\n");
3591 complete_pending_call_and_unlock (pending, message);
3592 pending = NULL; /* it's probably unref'd */
3594 CONNECTION_LOCK (connection);
3595 _dbus_verbose ("pending call completed in dispatch\n");
3596 result = DBUS_HANDLER_RESULT_HANDLED;
3600 result = _dbus_connection_run_builtin_filters_unlocked_no_update (connection, message);
3601 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
3604 if (!_dbus_list_copy (&connection->filter_list, &filter_list_copy))
3606 _dbus_connection_release_dispatch (connection);
3607 HAVE_LOCK_CHECK (connection);
3609 _dbus_connection_failed_pop (connection, message_link);
3611 /* unlocks and calls user code */
3612 _dbus_connection_update_dispatch_status_and_unlock (connection,
3613 DBUS_DISPATCH_NEED_MEMORY);
3616 dbus_pending_call_unref (pending);
3617 dbus_connection_unref (connection);
3619 return DBUS_DISPATCH_NEED_MEMORY;
3622 _dbus_list_foreach (&filter_list_copy,
3623 (DBusForeachFunction)_dbus_message_filter_ref,
3626 /* We're still protected from dispatch() reentrancy here
3627 * since we acquired the dispatcher
3629 CONNECTION_UNLOCK (connection);
3631 link = _dbus_list_get_first_link (&filter_list_copy);
3632 while (link != NULL)
3634 DBusMessageFilter *filter = link->data;
3635 DBusList *next = _dbus_list_get_next_link (&filter_list_copy, link);
3637 _dbus_verbose (" running filter on message %p\n", message);
3638 result = (* filter->function) (connection, message, filter->user_data);
3640 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
3646 _dbus_list_foreach (&filter_list_copy,
3647 (DBusForeachFunction)_dbus_message_filter_unref,
3649 _dbus_list_clear (&filter_list_copy);
3651 CONNECTION_LOCK (connection);
3653 if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
3655 _dbus_verbose ("No memory in %s\n", _DBUS_FUNCTION_NAME);
3658 else if (result == DBUS_HANDLER_RESULT_HANDLED)
3660 _dbus_verbose ("filter handled message in dispatch\n");
3664 /* We're still protected from dispatch() reentrancy here
3665 * since we acquired the dispatcher
3667 _dbus_verbose (" running object path dispatch on message %p (%d %s %s '%s')\n",
3669 dbus_message_get_type (message),
3670 dbus_message_get_interface (message) ?
3671 dbus_message_get_interface (message) :
3673 dbus_message_get_member (message) ?
3674 dbus_message_get_member (message) :
3676 dbus_message_get_signature (message));
3678 HAVE_LOCK_CHECK (connection);
3679 result = _dbus_object_tree_dispatch_and_unlock (connection->objects,
3682 CONNECTION_LOCK (connection);
3684 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
3686 _dbus_verbose ("object tree handled message in dispatch\n");
3690 if (dbus_message_get_type (message) == DBUS_MESSAGE_TYPE_METHOD_CALL)
3694 DBusPreallocatedSend *preallocated;
3696 _dbus_verbose (" sending error %s\n",
3697 DBUS_ERROR_UNKNOWN_METHOD);
3699 if (!_dbus_string_init (&str))
3701 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
3702 _dbus_verbose ("no memory for error string in dispatch\n");
3706 if (!_dbus_string_append_printf (&str,
3707 "Method \"%s\" with signature \"%s\" on interface \"%s\" doesn't exist\n",
3708 dbus_message_get_member (message),
3709 dbus_message_get_signature (message),
3710 dbus_message_get_interface (message)))
3712 _dbus_string_free (&str);
3713 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
3714 _dbus_verbose ("no memory for error string in dispatch\n");
3718 reply = dbus_message_new_error (message,
3719 DBUS_ERROR_UNKNOWN_METHOD,
3720 _dbus_string_get_const_data (&str));
3721 _dbus_string_free (&str);
3725 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
3726 _dbus_verbose ("no memory for error reply in dispatch\n");
3730 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
3732 if (preallocated == NULL)
3734 dbus_message_unref (reply);
3735 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
3736 _dbus_verbose ("no memory for error send in dispatch\n");
3740 _dbus_connection_send_preallocated_unlocked_no_update (connection, preallocated,
3743 dbus_message_unref (reply);
3745 result = DBUS_HANDLER_RESULT_HANDLED;
3748 _dbus_verbose (" done dispatching %p (%d %s %s '%s') on connection %p\n", message,
3749 dbus_message_get_type (message),
3750 dbus_message_get_interface (message) ?
3751 dbus_message_get_interface (message) :
3753 dbus_message_get_member (message) ?
3754 dbus_message_get_member (message) :
3756 dbus_message_get_signature (message),
3760 if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
3762 _dbus_verbose ("out of memory in %s\n", _DBUS_FUNCTION_NAME);
3764 /* Put message back, and we'll start over.
3765 * Yes this means handlers must be idempotent if they
3766 * don't return HANDLED; c'est la vie.
3768 _dbus_connection_putback_message_link_unlocked (connection,
3773 _dbus_verbose (" ... done dispatching in %s\n", _DBUS_FUNCTION_NAME);
3775 if (dbus_message_is_signal (message,
3776 DBUS_INTERFACE_LOCAL,
3779 _dbus_bus_check_connection_and_unref (connection);
3781 if (connection->exit_on_disconnect)
3783 CONNECTION_UNLOCK (connection);
3785 _dbus_verbose ("Exiting on Disconnected signal\n");
3787 _dbus_assert_not_reached ("Call to exit() returned");
3791 _dbus_list_free_link (message_link);
3792 dbus_message_unref (message); /* don't want the message to count in max message limits
3793 * in computing dispatch status below
3797 _dbus_connection_release_dispatch (connection);
3798 HAVE_LOCK_CHECK (connection);
3800 _dbus_verbose ("%s before final status update\n", _DBUS_FUNCTION_NAME);
3801 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3803 /* unlocks and calls user code */
3804 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3806 dbus_connection_unref (connection);
3812 * Sets the watch functions for the connection. These functions are
3813 * responsible for making the application's main loop aware of file
3814 * descriptors that need to be monitored for events, using select() or
3815 * poll(). When using Qt, typically the DBusAddWatchFunction would
3816 * create a QSocketNotifier. When using GLib, the DBusAddWatchFunction
3817 * could call g_io_add_watch(), or could be used as part of a more
3818 * elaborate GSource. Note that when a watch is added, it may
3821 * The DBusWatchToggledFunction notifies the application that the
3822 * watch has been enabled or disabled. Call dbus_watch_get_enabled()
3823 * to check this. A disabled watch should have no effect, and enabled
3824 * watch should be added to the main loop. This feature is used
3825 * instead of simply adding/removing the watch because
3826 * enabling/disabling can be done without memory allocation. The
3827 * toggled function may be NULL if a main loop re-queries
3828 * dbus_watch_get_enabled() every time anyway.
3830 * The DBusWatch can be queried for the file descriptor to watch using
3831 * dbus_watch_get_fd(), and for the events to watch for using
3832 * dbus_watch_get_flags(). The flags returned by
3833 * dbus_watch_get_flags() will only contain DBUS_WATCH_READABLE and
3834 * DBUS_WATCH_WRITABLE, never DBUS_WATCH_HANGUP or DBUS_WATCH_ERROR;
3835 * all watches implicitly include a watch for hangups, errors, and
3836 * other exceptional conditions.
3838 * Once a file descriptor becomes readable or writable, or an exception
3839 * occurs, dbus_watch_handle() should be called to
3840 * notify the connection of the file descriptor's condition.
3842 * dbus_watch_handle() cannot be called during the
3843 * DBusAddWatchFunction, as the connection will not be ready to handle
3846 * It is not allowed to reference a DBusWatch after it has been passed
3847 * to remove_function.
3849 * If #FALSE is returned due to lack of memory, the failure may be due
3850 * to a #FALSE return from the new add_function. If so, the
3851 * add_function may have been called successfully one or more times,
3852 * but the remove_function will also have been called to remove any
3853 * successful adds. i.e. if #FALSE is returned the net result
3854 * should be that dbus_connection_set_watch_functions() has no effect,
3855 * but the add_function and remove_function may have been called.
3857 * @todo We need to drop the lock when we call the
3858 * add/remove/toggled functions which can be a side effect
3859 * of setting the watch functions.
3861 * @param connection the connection.
3862 * @param add_function function to begin monitoring a new descriptor.
3863 * @param remove_function function to stop monitoring a descriptor.
3864 * @param toggled_function function to notify of enable/disable
3865 * @param data data to pass to add_function and remove_function.
3866 * @param free_data_function function to be called to free the data.
3867 * @returns #FALSE on failure (no memory)
3870 dbus_connection_set_watch_functions (DBusConnection *connection,
3871 DBusAddWatchFunction add_function,
3872 DBusRemoveWatchFunction remove_function,
3873 DBusWatchToggledFunction toggled_function,
3875 DBusFreeFunction free_data_function)
3878 DBusWatchList *watches;
3880 _dbus_return_val_if_fail (connection != NULL, FALSE);
3882 CONNECTION_LOCK (connection);
3884 #ifndef DBUS_DISABLE_CHECKS
3885 if (connection->watches == NULL)
3887 _dbus_warn ("Re-entrant call to %s is not allowed\n",
3888 _DBUS_FUNCTION_NAME);
3893 /* ref connection for slightly better reentrancy */
3894 _dbus_connection_ref_unlocked (connection);
3896 /* This can call back into user code, and we need to drop the
3897 * connection lock when it does. This is kind of a lame
3900 watches = connection->watches;
3901 connection->watches = NULL;
3902 CONNECTION_UNLOCK (connection);
3904 retval = _dbus_watch_list_set_functions (watches,
3905 add_function, remove_function,
3907 data, free_data_function);
3908 CONNECTION_LOCK (connection);
3909 connection->watches = watches;
3911 CONNECTION_UNLOCK (connection);
3912 /* drop our paranoid refcount */
3913 dbus_connection_unref (connection);
3919 * Sets the timeout functions for the connection. These functions are
3920 * responsible for making the application's main loop aware of timeouts.
3921 * When using Qt, typically the DBusAddTimeoutFunction would create a
3922 * QTimer. When using GLib, the DBusAddTimeoutFunction would call
3925 * The DBusTimeoutToggledFunction notifies the application that the
3926 * timeout has been enabled or disabled. Call
3927 * dbus_timeout_get_enabled() to check this. A disabled timeout should
3928 * have no effect, and enabled timeout should be added to the main
3929 * loop. This feature is used instead of simply adding/removing the
3930 * timeout because enabling/disabling can be done without memory
3931 * allocation. With Qt, QTimer::start() and QTimer::stop() can be used
3932 * to enable and disable. The toggled function may be NULL if a main
3933 * loop re-queries dbus_timeout_get_enabled() every time anyway.
3934 * Whenever a timeout is toggled, its interval may change.
3936 * The DBusTimeout can be queried for the timer interval using
3937 * dbus_timeout_get_interval(). dbus_timeout_handle() should be called
3938 * repeatedly, each time the interval elapses, starting after it has
3939 * elapsed once. The timeout stops firing when it is removed with the
3940 * given remove_function. The timer interval may change whenever the
3941 * timeout is added, removed, or toggled.
3943 * @param connection the connection.
3944 * @param add_function function to add a timeout.
3945 * @param remove_function function to remove a timeout.
3946 * @param toggled_function function to notify of enable/disable
3947 * @param data data to pass to add_function and remove_function.
3948 * @param free_data_function function to be called to free the data.
3949 * @returns #FALSE on failure (no memory)
3952 dbus_connection_set_timeout_functions (DBusConnection *connection,
3953 DBusAddTimeoutFunction add_function,
3954 DBusRemoveTimeoutFunction remove_function,
3955 DBusTimeoutToggledFunction toggled_function,
3957 DBusFreeFunction free_data_function)
3960 DBusTimeoutList *timeouts;
3962 _dbus_return_val_if_fail (connection != NULL, FALSE);
3964 CONNECTION_LOCK (connection);
3966 #ifndef DBUS_DISABLE_CHECKS
3967 if (connection->timeouts == NULL)
3969 _dbus_warn ("Re-entrant call to %s is not allowed\n",
3970 _DBUS_FUNCTION_NAME);
3975 /* ref connection for slightly better reentrancy */
3976 _dbus_connection_ref_unlocked (connection);
3978 timeouts = connection->timeouts;
3979 connection->timeouts = NULL;
3980 CONNECTION_UNLOCK (connection);
3982 retval = _dbus_timeout_list_set_functions (timeouts,
3983 add_function, remove_function,
3985 data, free_data_function);
3986 CONNECTION_LOCK (connection);
3987 connection->timeouts = timeouts;
3989 CONNECTION_UNLOCK (connection);
3990 /* drop our paranoid refcount */
3991 dbus_connection_unref (connection);
3997 * Sets the mainloop wakeup function for the connection. This function is
3998 * responsible for waking up the main loop (if its sleeping) when some some
3999 * change has happened to the connection that the mainloop needs to reconsider
4000 * (e.g. a message has been queued for writing).
4001 * When using Qt, this typically results in a call to QEventLoop::wakeUp().
4002 * When using GLib, it would call g_main_context_wakeup().
4005 * @param connection the connection.
4006 * @param wakeup_main_function function to wake up the mainloop
4007 * @param data data to pass wakeup_main_function
4008 * @param free_data_function function to be called to free the data.
4011 dbus_connection_set_wakeup_main_function (DBusConnection *connection,
4012 DBusWakeupMainFunction wakeup_main_function,
4014 DBusFreeFunction free_data_function)
4017 DBusFreeFunction old_free_data;
4019 _dbus_return_if_fail (connection != NULL);
4021 CONNECTION_LOCK (connection);
4022 old_data = connection->wakeup_main_data;
4023 old_free_data = connection->free_wakeup_main_data;
4025 connection->wakeup_main_function = wakeup_main_function;
4026 connection->wakeup_main_data = data;
4027 connection->free_wakeup_main_data = free_data_function;
4029 CONNECTION_UNLOCK (connection);
4031 /* Callback outside the lock */
4033 (*old_free_data) (old_data);
4037 * Set a function to be invoked when the dispatch status changes.
4038 * If the dispatch status is #DBUS_DISPATCH_DATA_REMAINS, then
4039 * dbus_connection_dispatch() needs to be called to process incoming
4040 * messages. However, dbus_connection_dispatch() MUST NOT BE CALLED
4041 * from inside the DBusDispatchStatusFunction. Indeed, almost
4042 * any reentrancy in this function is a bad idea. Instead,
4043 * the DBusDispatchStatusFunction should simply save an indication
4044 * that messages should be dispatched later, when the main loop
4047 * @param connection the connection
4048 * @param function function to call on dispatch status changes
4049 * @param data data for function
4050 * @param free_data_function free the function data
4053 dbus_connection_set_dispatch_status_function (DBusConnection *connection,
4054 DBusDispatchStatusFunction function,
4056 DBusFreeFunction free_data_function)
4059 DBusFreeFunction old_free_data;
4061 _dbus_return_if_fail (connection != NULL);
4063 CONNECTION_LOCK (connection);
4064 old_data = connection->dispatch_status_data;
4065 old_free_data = connection->free_dispatch_status_data;
4067 connection->dispatch_status_function = function;
4068 connection->dispatch_status_data = data;
4069 connection->free_dispatch_status_data = free_data_function;
4071 CONNECTION_UNLOCK (connection);
4073 /* Callback outside the lock */
4075 (*old_free_data) (old_data);
4079 * Get the UNIX file descriptor of the connection, if any. This can
4080 * be used for SELinux access control checks with getpeercon() for
4081 * example. DO NOT read or write to the file descriptor, or try to
4082 * select() on it; use DBusWatch for main loop integration. Not all
4083 * connections will have a file descriptor. So for adding descriptors
4084 * to the main loop, use dbus_watch_get_fd() and so forth.
4086 * @param connection the connection
4087 * @param fd return location for the file descriptor.
4088 * @returns #TRUE if fd is successfully obtained.
4091 dbus_connection_get_unix_fd (DBusConnection *connection,
4096 _dbus_return_val_if_fail (connection != NULL, FALSE);
4097 _dbus_return_val_if_fail (connection->transport != NULL, FALSE);
4099 CONNECTION_LOCK (connection);
4101 retval = _dbus_transport_get_unix_fd (connection->transport,
4104 CONNECTION_UNLOCK (connection);
4110 * Gets the UNIX user ID of the connection if any.
4111 * Returns #TRUE if the uid is filled in.
4112 * Always returns #FALSE on non-UNIX platforms.
4113 * Always returns #FALSE prior to authenticating the
4116 * @param connection the connection
4117 * @param uid return location for the user ID
4118 * @returns #TRUE if uid is filled in with a valid user ID
4121 dbus_connection_get_unix_user (DBusConnection *connection,
4126 _dbus_return_val_if_fail (connection != NULL, FALSE);
4127 _dbus_return_val_if_fail (uid != NULL, FALSE);
4129 CONNECTION_LOCK (connection);
4131 if (!_dbus_transport_get_is_authenticated (connection->transport))
4134 result = _dbus_transport_get_unix_user (connection->transport,
4136 CONNECTION_UNLOCK (connection);
4142 * Gets the process ID of the connection if any.
4143 * Returns #TRUE if the uid is filled in.
4144 * Always returns #FALSE prior to authenticating the
4147 * @param connection the connection
4148 * @param pid return location for the process ID
4149 * @returns #TRUE if uid is filled in with a valid process ID
4152 dbus_connection_get_unix_process_id (DBusConnection *connection,
4157 _dbus_return_val_if_fail (connection != NULL, FALSE);
4158 _dbus_return_val_if_fail (pid != NULL, FALSE);
4160 CONNECTION_LOCK (connection);
4162 if (!_dbus_transport_get_is_authenticated (connection->transport))
4165 result = _dbus_transport_get_unix_process_id (connection->transport,
4167 CONNECTION_UNLOCK (connection);
4173 * Sets a predicate function used to determine whether a given user ID
4174 * is allowed to connect. When an incoming connection has
4175 * authenticated with a particular user ID, this function is called;
4176 * if it returns #TRUE, the connection is allowed to proceed,
4177 * otherwise the connection is disconnected.
4179 * If the function is set to #NULL (as it is by default), then
4180 * only the same UID as the server process will be allowed to
4183 * @param connection the connection
4184 * @param function the predicate
4185 * @param data data to pass to the predicate
4186 * @param free_data_function function to free the data
4189 dbus_connection_set_unix_user_function (DBusConnection *connection,
4190 DBusAllowUnixUserFunction function,
4192 DBusFreeFunction free_data_function)
4194 void *old_data = NULL;
4195 DBusFreeFunction old_free_function = NULL;
4197 _dbus_return_if_fail (connection != NULL);
4199 CONNECTION_LOCK (connection);
4200 _dbus_transport_set_unix_user_function (connection->transport,
4201 function, data, free_data_function,
4202 &old_data, &old_free_function);
4203 CONNECTION_UNLOCK (connection);
4205 if (old_free_function != NULL)
4206 (* old_free_function) (old_data);
4210 * Adds a message filter. Filters are handlers that are run on all
4211 * incoming messages, prior to the objects registered with
4212 * dbus_connection_register_object_path(). Filters are run in the
4213 * order that they were added. The same handler can be added as a
4214 * filter more than once, in which case it will be run more than once.
4215 * Filters added during a filter callback won't be run on the message
4218 * @todo we don't run filters on messages while blocking without
4219 * entering the main loop, since filters are run as part of
4220 * dbus_connection_dispatch(). This is probably a feature, as filters
4221 * could create arbitrary reentrancy. But kind of sucks if you're
4222 * trying to filter METHOD_RETURN for some reason.
4224 * @param connection the connection
4225 * @param function function to handle messages
4226 * @param user_data user data to pass to the function
4227 * @param free_data_function function to use for freeing user data
4228 * @returns #TRUE on success, #FALSE if not enough memory.
4231 dbus_connection_add_filter (DBusConnection *connection,
4232 DBusHandleMessageFunction function,
4234 DBusFreeFunction free_data_function)
4236 DBusMessageFilter *filter;
4238 _dbus_return_val_if_fail (connection != NULL, FALSE);
4239 _dbus_return_val_if_fail (function != NULL, FALSE);
4241 filter = dbus_new0 (DBusMessageFilter, 1);
4245 filter->refcount.value = 1;
4247 CONNECTION_LOCK (connection);
4249 if (!_dbus_list_append (&connection->filter_list,
4252 _dbus_message_filter_unref (filter);
4253 CONNECTION_UNLOCK (connection);
4257 /* Fill in filter after all memory allocated,
4258 * so we don't run the free_user_data_function
4259 * if the add_filter() fails
4262 filter->function = function;
4263 filter->user_data = user_data;
4264 filter->free_user_data_function = free_data_function;
4266 CONNECTION_UNLOCK (connection);
4271 * Removes a previously-added message filter. It is a programming
4272 * error to call this function for a handler that has not been added
4273 * as a filter. If the given handler was added more than once, only
4274 * one instance of it will be removed (the most recently-added
4277 * @param connection the connection
4278 * @param function the handler to remove
4279 * @param user_data user data for the handler to remove
4283 dbus_connection_remove_filter (DBusConnection *connection,
4284 DBusHandleMessageFunction function,
4288 DBusMessageFilter *filter;
4290 _dbus_return_if_fail (connection != NULL);
4291 _dbus_return_if_fail (function != NULL);
4293 CONNECTION_LOCK (connection);
4297 link = _dbus_list_get_last_link (&connection->filter_list);
4298 while (link != NULL)
4300 filter = link->data;
4302 if (filter->function == function &&
4303 filter->user_data == user_data)
4305 _dbus_list_remove_link (&connection->filter_list, link);
4306 filter->function = NULL;
4311 link = _dbus_list_get_prev_link (&connection->filter_list, link);
4314 CONNECTION_UNLOCK (connection);
4316 #ifndef DBUS_DISABLE_CHECKS
4319 _dbus_warn ("Attempt to remove filter function %p user data %p, but no such filter has been added\n",
4320 function, user_data);
4325 /* Call application code */
4326 if (filter->free_user_data_function)
4327 (* filter->free_user_data_function) (filter->user_data);
4329 filter->free_user_data_function = NULL;
4330 filter->user_data = NULL;
4332 _dbus_message_filter_unref (filter);
4336 * Registers a handler for a given path in the object hierarchy.
4337 * The given vtable handles messages sent to exactly the given path.
4340 * @param connection the connection
4341 * @param path a '/' delimited string of path elements
4342 * @param vtable the virtual table
4343 * @param user_data data to pass to functions in the vtable
4344 * @returns #FALSE if not enough memory
4347 dbus_connection_register_object_path (DBusConnection *connection,
4349 const DBusObjectPathVTable *vtable,
4352 char **decomposed_path;
4355 _dbus_return_val_if_fail (connection != NULL, FALSE);
4356 _dbus_return_val_if_fail (path != NULL, FALSE);
4357 _dbus_return_val_if_fail (path[0] == '/', FALSE);
4358 _dbus_return_val_if_fail (vtable != NULL, FALSE);
4360 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
4363 CONNECTION_LOCK (connection);
4365 retval = _dbus_object_tree_register (connection->objects,
4367 (const char **) decomposed_path, vtable,
4370 CONNECTION_UNLOCK (connection);
4372 dbus_free_string_array (decomposed_path);
4378 * Registers a fallback handler for a given subsection of the object
4379 * hierarchy. The given vtable handles messages at or below the given
4380 * path. You can use this to establish a default message handling
4381 * policy for a whole "subdirectory."
4383 * @param connection the connection
4384 * @param path a '/' delimited string of path elements
4385 * @param vtable the virtual table
4386 * @param user_data data to pass to functions in the vtable
4387 * @returns #FALSE if not enough memory
4390 dbus_connection_register_fallback (DBusConnection *connection,
4392 const DBusObjectPathVTable *vtable,
4395 char **decomposed_path;
4398 _dbus_return_val_if_fail (connection != NULL, FALSE);
4399 _dbus_return_val_if_fail (path != NULL, FALSE);
4400 _dbus_return_val_if_fail (path[0] == '/', FALSE);
4401 _dbus_return_val_if_fail (vtable != NULL, FALSE);
4403 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
4406 CONNECTION_LOCK (connection);
4408 retval = _dbus_object_tree_register (connection->objects,
4410 (const char **) decomposed_path, vtable,
4413 CONNECTION_UNLOCK (connection);
4415 dbus_free_string_array (decomposed_path);
4421 * Unregisters the handler registered with exactly the given path.
4422 * It's a bug to call this function for a path that isn't registered.
4423 * Can unregister both fallback paths and object paths.
4425 * @param connection the connection
4426 * @param path a '/' delimited string of path elements
4427 * @returns #FALSE if not enough memory
4430 dbus_connection_unregister_object_path (DBusConnection *connection,
4433 char **decomposed_path;
4435 _dbus_return_val_if_fail (connection != NULL, FALSE);
4436 _dbus_return_val_if_fail (path != NULL, FALSE);
4437 _dbus_return_val_if_fail (path[0] == '/', FALSE);
4439 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
4442 CONNECTION_LOCK (connection);
4444 _dbus_object_tree_unregister_and_unlock (connection->objects, (const char **) decomposed_path);
4446 dbus_free_string_array (decomposed_path);
4452 * Gets the user data passed to dbus_connection_register_object_path()
4453 * or dbus_connection_register_fallback(). If nothing was registered
4454 * at this path, the data is filled in with #NULL.
4456 * @param connection the connection
4457 * @param path the path you registered with
4458 * @param data_p location to store the user data, or #NULL
4459 * @returns #FALSE if not enough memory
4462 dbus_connection_get_object_path_data (DBusConnection *connection,
4466 char **decomposed_path;
4468 _dbus_return_val_if_fail (connection != NULL, FALSE);
4469 _dbus_return_val_if_fail (path != NULL, FALSE);
4470 _dbus_return_val_if_fail (data_p != NULL, FALSE);
4474 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
4477 CONNECTION_LOCK (connection);
4479 *data_p = _dbus_object_tree_get_user_data_unlocked (connection->objects, (const char**) decomposed_path);
4481 CONNECTION_UNLOCK (connection);
4483 dbus_free_string_array (decomposed_path);
4489 * Lists the registered fallback handlers and object path handlers at
4490 * the given parent_path. The returned array should be freed with
4491 * dbus_free_string_array().
4493 * @param connection the connection
4494 * @param parent_path the path to list the child handlers of
4495 * @param child_entries returns #NULL-terminated array of children
4496 * @returns #FALSE if no memory to allocate the child entries
4499 dbus_connection_list_registered (DBusConnection *connection,
4500 const char *parent_path,
4501 char ***child_entries)
4503 char **decomposed_path;
4505 _dbus_return_val_if_fail (connection != NULL, FALSE);
4506 _dbus_return_val_if_fail (parent_path != NULL, FALSE);
4507 _dbus_return_val_if_fail (parent_path[0] == '/', FALSE);
4508 _dbus_return_val_if_fail (child_entries != NULL, FALSE);
4510 if (!_dbus_decompose_path (parent_path, strlen (parent_path), &decomposed_path, NULL))
4513 CONNECTION_LOCK (connection);
4515 retval = _dbus_object_tree_list_registered_and_unlock (connection->objects,
4516 (const char **) decomposed_path,
4518 dbus_free_string_array (decomposed_path);
4523 static DBusDataSlotAllocator slot_allocator;
4524 _DBUS_DEFINE_GLOBAL_LOCK (connection_slots);
4527 * Allocates an integer ID to be used for storing application-specific
4528 * data on any DBusConnection. The allocated ID may then be used
4529 * with dbus_connection_set_data() and dbus_connection_get_data().
4530 * The passed-in slot must be initialized to -1, and is filled in
4531 * with the slot ID. If the passed-in slot is not -1, it's assumed
4532 * to be already allocated, and its refcount is incremented.
4534 * The allocated slot is global, i.e. all DBusConnection objects will
4535 * have a slot with the given integer ID reserved.
4537 * @param slot_p address of a global variable storing the slot
4538 * @returns #FALSE on failure (no memory)
4541 dbus_connection_allocate_data_slot (dbus_int32_t *slot_p)
4543 return _dbus_data_slot_allocator_alloc (&slot_allocator,
4544 _DBUS_LOCK_NAME (connection_slots),
4549 * Deallocates a global ID for connection data slots.
4550 * dbus_connection_get_data() and dbus_connection_set_data() may no
4551 * longer be used with this slot. Existing data stored on existing
4552 * DBusConnection objects will be freed when the connection is
4553 * finalized, but may not be retrieved (and may only be replaced if
4554 * someone else reallocates the slot). When the refcount on the
4555 * passed-in slot reaches 0, it is set to -1.
4557 * @param slot_p address storing the slot to deallocate
4560 dbus_connection_free_data_slot (dbus_int32_t *slot_p)
4562 _dbus_return_if_fail (*slot_p >= 0);
4564 _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
4568 * Stores a pointer on a DBusConnection, along
4569 * with an optional function to be used for freeing
4570 * the data when the data is set again, or when
4571 * the connection is finalized. The slot number
4572 * must have been allocated with dbus_connection_allocate_data_slot().
4574 * @param connection the connection
4575 * @param slot the slot number
4576 * @param data the data to store
4577 * @param free_data_func finalizer function for the data
4578 * @returns #TRUE if there was enough memory to store the data
4581 dbus_connection_set_data (DBusConnection *connection,
4584 DBusFreeFunction free_data_func)
4586 DBusFreeFunction old_free_func;
4590 _dbus_return_val_if_fail (connection != NULL, FALSE);
4591 _dbus_return_val_if_fail (slot >= 0, FALSE);
4593 CONNECTION_LOCK (connection);
4595 retval = _dbus_data_slot_list_set (&slot_allocator,
4596 &connection->slot_list,
4597 slot, data, free_data_func,
4598 &old_free_func, &old_data);
4600 CONNECTION_UNLOCK (connection);
4604 /* Do the actual free outside the connection lock */
4606 (* old_free_func) (old_data);
4613 * Retrieves data previously set with dbus_connection_set_data().
4614 * The slot must still be allocated (must not have been freed).
4616 * @param connection the connection
4617 * @param slot the slot to get data from
4618 * @returns the data, or #NULL if not found
4621 dbus_connection_get_data (DBusConnection *connection,
4626 _dbus_return_val_if_fail (connection != NULL, NULL);
4628 CONNECTION_LOCK (connection);
4630 res = _dbus_data_slot_list_get (&slot_allocator,
4631 &connection->slot_list,
4634 CONNECTION_UNLOCK (connection);
4640 * This function sets a global flag for whether dbus_connection_new()
4641 * will set SIGPIPE behavior to SIG_IGN.
4643 * @param will_modify_sigpipe #TRUE to allow sigpipe to be set to SIG_IGN
4646 dbus_connection_set_change_sigpipe (dbus_bool_t will_modify_sigpipe)
4648 _dbus_modify_sigpipe = will_modify_sigpipe != FALSE;
4652 * Specifies the maximum size message this connection is allowed to
4653 * receive. Larger messages will result in disconnecting the
4656 * @param connection a #DBusConnection
4657 * @param size maximum message size the connection can receive, in bytes
4660 dbus_connection_set_max_message_size (DBusConnection *connection,
4663 _dbus_return_if_fail (connection != NULL);
4665 CONNECTION_LOCK (connection);
4666 _dbus_transport_set_max_message_size (connection->transport,
4668 CONNECTION_UNLOCK (connection);
4672 * Gets the value set by dbus_connection_set_max_message_size().
4674 * @param connection the connection
4675 * @returns the max size of a single message
4678 dbus_connection_get_max_message_size (DBusConnection *connection)
4682 _dbus_return_val_if_fail (connection != NULL, 0);
4684 CONNECTION_LOCK (connection);
4685 res = _dbus_transport_get_max_message_size (connection->transport);
4686 CONNECTION_UNLOCK (connection);
4691 * Sets the maximum total number of bytes that can be used for all messages
4692 * received on this connection. Messages count toward the maximum until
4693 * they are finalized. When the maximum is reached, the connection will
4694 * not read more data until some messages are finalized.
4696 * The semantics of the maximum are: if outstanding messages are
4697 * already above the maximum, additional messages will not be read.
4698 * The semantics are not: if the next message would cause us to exceed
4699 * the maximum, we don't read it. The reason is that we don't know the
4700 * size of a message until after we read it.
4702 * Thus, the max live messages size can actually be exceeded
4703 * by up to the maximum size of a single message.
4705 * Also, if we read say 1024 bytes off the wire in a single read(),
4706 * and that contains a half-dozen small messages, we may exceed the
4707 * size max by that amount. But this should be inconsequential.
4709 * This does imply that we can't call read() with a buffer larger
4710 * than we're willing to exceed this limit by.
4712 * @param connection the connection
4713 * @param size the maximum size in bytes of all outstanding messages
4716 dbus_connection_set_max_received_size (DBusConnection *connection,
4719 _dbus_return_if_fail (connection != NULL);
4721 CONNECTION_LOCK (connection);
4722 _dbus_transport_set_max_received_size (connection->transport,
4724 CONNECTION_UNLOCK (connection);
4728 * Gets the value set by dbus_connection_set_max_received_size().
4730 * @param connection the connection
4731 * @returns the max size of all live messages
4734 dbus_connection_get_max_received_size (DBusConnection *connection)
4738 _dbus_return_val_if_fail (connection != NULL, 0);
4740 CONNECTION_LOCK (connection);
4741 res = _dbus_transport_get_max_received_size (connection->transport);
4742 CONNECTION_UNLOCK (connection);
4747 * Gets the approximate size in bytes of all messages in the outgoing
4748 * message queue. The size is approximate in that you shouldn't use
4749 * it to decide how many bytes to read off the network or anything
4750 * of that nature, as optimizations may choose to tell small white lies
4751 * to avoid performance overhead.
4753 * @param connection the connection
4754 * @returns the number of bytes that have been queued up but not sent
4757 dbus_connection_get_outgoing_size (DBusConnection *connection)
4761 _dbus_return_val_if_fail (connection != NULL, 0);
4763 CONNECTION_LOCK (connection);
4764 res = _dbus_counter_get_value (connection->outgoing_counter);
4765 CONNECTION_UNLOCK (connection);