1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-connection.c DBusConnection object
4 * Copyright (C) 2002-2006 Red Hat Inc.
5 * Copyright (C) 2013 Samsung Electronics
7 * Licensed under the Academic Free License version 2.1
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 #include "dbus-shared.h"
27 #include "dbus-connection.h"
28 #include "dbus-list.h"
29 #include "dbus-timeout.h"
30 #include "dbus-transport.h"
31 #include "dbus-watch.h"
32 #include "dbus-connection-internal.h"
33 #include "dbus-pending-call-internal.h"
34 #include "dbus-list.h"
35 #include "dbus-hash.h"
36 #include "dbus-message-internal.h"
37 #include "dbus-message-private.h"
38 #include "dbus-threads.h"
39 #include "dbus-protocol.h"
40 #include "dbus-dataslot.h"
41 #include "dbus-string.h"
42 #include "dbus-signature.h"
43 #include "dbus-pending-call.h"
44 #include "dbus-object-tree.h"
45 #include "dbus-threads-internal.h"
47 #include "dbus-marshal-basic.h"
48 #ifdef ENABLE_KDBUS_TRANSPORT
49 #include "dbus-transport-kdbus.h"
53 #ifdef DBUS_DISABLE_CHECKS
54 #define TOOK_LOCK_CHECK(connection)
55 #define RELEASING_LOCK_CHECK(connection)
56 #define HAVE_LOCK_CHECK(connection)
58 #define TOOK_LOCK_CHECK(connection) do { \
59 _dbus_assert (!(connection)->have_connection_lock); \
60 (connection)->have_connection_lock = TRUE; \
62 #define RELEASING_LOCK_CHECK(connection) do { \
63 _dbus_assert ((connection)->have_connection_lock); \
64 (connection)->have_connection_lock = FALSE; \
66 #define HAVE_LOCK_CHECK(connection) _dbus_assert ((connection)->have_connection_lock)
67 /* A "DO_NOT_HAVE_LOCK_CHECK" is impossible since we need the lock to check the flag */
72 #define CONNECTION_LOCK(connection) do { \
73 if (TRACE_LOCKS) { _dbus_verbose ("LOCK\n"); } \
74 _dbus_rmutex_lock ((connection)->mutex); \
75 TOOK_LOCK_CHECK (connection); \
78 #define CONNECTION_UNLOCK(connection) _dbus_connection_unlock (connection)
80 #define SLOTS_LOCK(connection) do { \
81 _dbus_rmutex_lock ((connection)->slot_mutex); \
84 #define SLOTS_UNLOCK(connection) do { \
85 _dbus_rmutex_unlock ((connection)->slot_mutex); \
88 #define DISPATCH_STATUS_NAME(s) \
89 ((s) == DBUS_DISPATCH_COMPLETE ? "complete" : \
90 (s) == DBUS_DISPATCH_DATA_REMAINS ? "data remains" : \
91 (s) == DBUS_DISPATCH_NEED_MEMORY ? "need memory" : \
95 * @defgroup DBusConnection DBusConnection
97 * @brief Connection to another application
99 * A DBusConnection represents a connection to another
100 * application. Messages can be sent and received via this connection.
101 * The other application may be a message bus; for convenience, the
102 * function dbus_bus_get() is provided to automatically open a
103 * connection to the well-known message buses.
105 * In brief a DBusConnection is a message queue associated with some
106 * message transport mechanism such as a socket. The connection
107 * maintains a queue of incoming messages and a queue of outgoing
110 * Several functions use the following terms:
112 * <li><b>read</b> means to fill the incoming message queue by reading from the socket</li>
113 * <li><b>write</b> means to drain the outgoing queue by writing to the socket</li>
114 * <li><b>dispatch</b> means to drain the incoming queue by invoking application-provided message handlers</li>
117 * The function dbus_connection_read_write_dispatch() for example does all
118 * three of these things, offering a simple alternative to a main loop.
120 * In an application with a main loop, the read/write/dispatch
121 * operations are usually separate.
123 * The connection provides #DBusWatch and #DBusTimeout objects to
124 * the main loop. These are used to know when reading, writing, or
125 * dispatching should be performed.
127 * Incoming messages are processed
128 * by calling dbus_connection_dispatch(). dbus_connection_dispatch()
129 * runs any handlers registered for the topmost message in the message
130 * queue, then discards the message, then returns.
132 * dbus_connection_get_dispatch_status() indicates whether
133 * messages are currently in the queue that need dispatching.
134 * dbus_connection_set_dispatch_status_function() allows
135 * you to set a function to be used to monitor the dispatch status.
137 * If you're using GLib or Qt add-on libraries for D-Bus, there are
138 * special convenience APIs in those libraries that hide
139 * all the details of dispatch and watch/timeout monitoring.
140 * For example, dbus_connection_setup_with_g_main().
142 * If you aren't using these add-on libraries, but want to process
143 * messages asynchronously, you must manually call
144 * dbus_connection_set_dispatch_status_function(),
145 * dbus_connection_set_watch_functions(),
146 * dbus_connection_set_timeout_functions() providing appropriate
147 * functions to integrate the connection with your application's main
148 * loop. This can be tricky to get right; main loops are not simple.
150 * If you don't need to be asynchronous, you can ignore #DBusWatch,
151 * #DBusTimeout, and dbus_connection_dispatch(). Instead,
152 * dbus_connection_read_write_dispatch() can be used.
154 * Or, in <em>very</em> simple applications,
155 * dbus_connection_pop_message() may be all you need, allowing you to
156 * avoid setting up any handler functions (see
157 * dbus_connection_add_filter(),
158 * dbus_connection_register_object_path() for more on handlers).
160 * When you use dbus_connection_send() or one of its variants to send
161 * a message, the message is added to the outgoing queue. It's
162 * actually written to the network later; either in
163 * dbus_watch_handle() invoked by your main loop, or in
164 * dbus_connection_flush() which blocks until it can write out the
165 * entire outgoing queue. The GLib/Qt add-on libraries again
166 * handle the details here for you by setting up watch functions.
168 * When a connection is disconnected, you are guaranteed to get a
169 * signal "Disconnected" from the interface
170 * #DBUS_INTERFACE_LOCAL, path
173 * You may not drop the last reference to a #DBusConnection
174 * until that connection has been disconnected.
176 * You may dispatch the unprocessed incoming message queue even if the
177 * connection is disconnected. However, "Disconnected" will always be
178 * the last message in the queue (obviously no messages are received
179 * after disconnection).
181 * After calling dbus_threads_init(), #DBusConnection has thread
182 * locks and drops them when invoking user callbacks, so in general is
183 * transparently threadsafe. However, #DBusMessage does NOT have
184 * thread locks; you must not send the same message to multiple
185 * #DBusConnection if those connections will be used from different threads,
188 * Also, if you dispatch or pop messages from multiple threads, it
189 * may work in the sense that it won't crash, but it's tough to imagine
190 * sane results; it will be completely unpredictable which messages
191 * go to which threads.
193 * It's recommended to dispatch from a single thread.
195 * The most useful function to call from multiple threads at once
196 * is dbus_connection_send_with_reply_and_block(). That is,
197 * multiple threads can make method calls at the same time.
199 * If you aren't using threads, you can use a main loop and
200 * dbus_pending_call_set_notify() to achieve a similar result.
204 * @defgroup DBusConnectionInternals DBusConnection implementation details
205 * @ingroup DBusInternals
206 * @brief Implementation details of DBusConnection
212 _dbus_connection_trace_ref (DBusConnection *connection,
217 #ifdef DBUS_ENABLE_VERBOSE_MODE
218 static int enabled = -1;
220 _dbus_trace_ref ("DBusConnection", connection, old_refcount, new_refcount,
221 why, "DBUS_CONNECTION_TRACE", &enabled);
226 * Internal struct representing a message filter function
228 typedef struct DBusMessageFilter DBusMessageFilter;
231 * Internal struct representing a message filter function
233 struct DBusMessageFilter
235 DBusAtomic refcount; /**< Reference count */
236 DBusHandleMessageFunction function; /**< Function to call to filter */
237 void *user_data; /**< User data for the function */
238 DBusFreeFunction free_user_data_function; /**< Function to free the user data */
243 * Internals of DBusPreallocatedSend
245 struct DBusPreallocatedSend
247 DBusConnection *connection; /**< Connection we'd send the message to */
248 DBusList *queue_link; /**< Preallocated link in the queue */
249 DBusList *counter_link; /**< Preallocated link in the resource counter */
252 #if HAVE_DECL_MSG_NOSIGNAL
253 static dbus_bool_t _dbus_modify_sigpipe = FALSE;
255 static dbus_bool_t _dbus_modify_sigpipe = TRUE;
259 * Implementation details of DBusConnection. All fields are private.
261 struct DBusConnection
263 DBusAtomic refcount; /**< Reference count. */
265 DBusRMutex *mutex; /**< Lock on the entire DBusConnection */
267 DBusCMutex *dispatch_mutex; /**< Protects dispatch_acquired */
268 DBusCondVar *dispatch_cond; /**< Notify when dispatch_acquired is available */
269 DBusCMutex *io_path_mutex; /**< Protects io_path_acquired */
270 DBusCondVar *io_path_cond; /**< Notify when io_path_acquired is available */
272 DBusList *outgoing_messages; /**< Queue of messages we need to send, send the end of the list first. */
273 DBusList *incoming_messages; /**< Queue of messages we have received, end of the list received most recently. */
274 DBusList *expired_messages; /**< Messages that will be released when we next unlock. */
276 DBusMessage *message_borrowed; /**< Filled in if the first incoming message has been borrowed;
277 * dispatch_acquired will be set by the borrower
280 int n_outgoing; /**< Length of outgoing queue. */
281 int n_incoming; /**< Length of incoming queue. */
283 DBusCounter *outgoing_counter; /**< Counts size of outgoing messages. */
285 DBusTransport *transport; /**< Object that sends/receives messages over network. */
286 DBusWatchList *watches; /**< Stores active watches. */
287 DBusTimeoutList *timeouts; /**< Stores active timeouts. */
289 DBusList *filter_list; /**< List of filters. */
291 DBusRMutex *slot_mutex; /**< Lock on slot_list so overall connection lock need not be taken */
292 DBusDataSlotList slot_list; /**< Data stored by allocated integer ID */
294 DBusHashTable *pending_replies; /**< Hash of message serials to #DBusPendingCall. */
296 dbus_uint32_t client_serial; /**< Client serial. Increments each time a message is sent */
297 DBusList *disconnect_message_link; /**< Preallocated list node for queueing the disconnection message */
299 DBusWakeupMainFunction wakeup_main_function; /**< Function to wake up the mainloop */
300 void *wakeup_main_data; /**< Application data for wakeup_main_function */
301 DBusFreeFunction free_wakeup_main_data; /**< free wakeup_main_data */
303 DBusDispatchStatusFunction dispatch_status_function; /**< Function on dispatch status changes */
304 void *dispatch_status_data; /**< Application data for dispatch_status_function */
305 DBusFreeFunction free_dispatch_status_data; /**< free dispatch_status_data */
307 DBusDispatchStatus last_dispatch_status; /**< The last dispatch status we reported to the application. */
309 DBusObjectTree *objects; /**< Object path handlers registered with this connection */
311 char *server_guid; /**< GUID of server if we are in shared_connections, #NULL if server GUID is unknown or connection is private */
313 /* These two MUST be bools and not bitfields, because they are protected by a separate lock
314 * from connection->mutex and all bitfields in a word have to be read/written together.
315 * So you can't have a different lock for different bitfields in the same word.
317 dbus_bool_t dispatch_acquired; /**< Someone has dispatch path (can drain incoming queue) */
318 dbus_bool_t io_path_acquired; /**< Someone has transport io path (can use the transport to read/write messages) */
320 unsigned int shareable : 1; /**< #TRUE if libdbus owns a reference to the connection and can return it from dbus_connection_open() more than once */
322 unsigned int exit_on_disconnect : 1; /**< If #TRUE, exit after handling disconnect signal */
324 unsigned int route_peer_messages : 1; /**< If #TRUE, if org.freedesktop.DBus.Peer messages have a bus name, don't handle them automatically */
326 unsigned int disconnected_message_arrived : 1; /**< We popped or are dispatching the disconnected message.
327 * if the disconnect_message_link is NULL then we queued it, but
328 * this flag is whether it got to the head of the queue.
330 unsigned int disconnected_message_processed : 1; /**< We did our default handling of the disconnected message,
331 * such as closing the connection.
334 #ifndef DBUS_DISABLE_CHECKS
335 unsigned int have_connection_lock : 1; /**< Used to check locking */
338 #if defined(DBUS_ENABLE_CHECKS) || defined(DBUS_ENABLE_ASSERT)
339 int generation; /**< _dbus_current_generation that should correspond to this connection */
343 static DBusDispatchStatus _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection);
344 static void _dbus_connection_update_dispatch_status_and_unlock (DBusConnection *connection,
345 DBusDispatchStatus new_status);
346 static void _dbus_connection_last_unref (DBusConnection *connection);
347 static void _dbus_connection_acquire_dispatch (DBusConnection *connection);
348 static void _dbus_connection_release_dispatch (DBusConnection *connection);
349 static DBusDispatchStatus _dbus_connection_flush_unlocked (DBusConnection *connection);
350 static void _dbus_connection_close_possibly_shared_and_unlock (DBusConnection *connection);
351 static dbus_bool_t _dbus_connection_get_is_connected_unlocked (DBusConnection *connection);
352 static dbus_bool_t _dbus_connection_peek_for_reply_unlocked (DBusConnection *connection,
353 dbus_uint32_t client_serial);
355 static DBusMessageFilter *
356 _dbus_message_filter_ref (DBusMessageFilter *filter)
358 #ifdef DBUS_DISABLE_ASSERT
359 _dbus_atomic_inc (&filter->refcount);
361 dbus_int32_t old_value;
363 old_value = _dbus_atomic_inc (&filter->refcount);
364 _dbus_assert (old_value > 0);
371 _dbus_message_filter_unref (DBusMessageFilter *filter)
373 dbus_int32_t old_value;
375 old_value = _dbus_atomic_dec (&filter->refcount);
376 _dbus_assert (old_value > 0);
380 if (filter->free_user_data_function)
381 (* filter->free_user_data_function) (filter->user_data);
388 * Acquires the connection lock.
390 * @param connection the connection.
393 _dbus_connection_lock (DBusConnection *connection)
395 CONNECTION_LOCK (connection);
399 * Releases the connection lock.
401 * @param connection the connection.
404 _dbus_connection_unlock (DBusConnection *connection)
406 DBusList *expired_messages;
411 _dbus_verbose ("UNLOCK\n");
414 /* If we had messages that expired (fell off the incoming or outgoing
415 * queues) while we were locked, actually release them now */
416 expired_messages = connection->expired_messages;
417 connection->expired_messages = NULL;
419 RELEASING_LOCK_CHECK (connection);
420 _dbus_rmutex_unlock (connection->mutex);
422 for (iter = _dbus_list_pop_first_link (&expired_messages);
424 iter = _dbus_list_pop_first_link (&expired_messages))
426 DBusMessage *message = iter->data;
428 dbus_message_unref (message);
429 _dbus_list_free_link (iter);
434 * Wakes up the main loop if it is sleeping
435 * Needed if we're e.g. queueing outgoing messages
436 * on a thread while the mainloop sleeps.
438 * @param connection the connection.
441 _dbus_connection_wakeup_mainloop (DBusConnection *connection)
443 if (connection->wakeup_main_function)
444 (*connection->wakeup_main_function) (connection->wakeup_main_data);
447 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
449 * Gets the locks so we can examine them
451 * @param connection the connection.
452 * @param mutex_loc return for the location of the main mutex pointer
453 * @param dispatch_mutex_loc return location of the dispatch mutex pointer
454 * @param io_path_mutex_loc return location of the io_path mutex pointer
455 * @param dispatch_cond_loc return location of the dispatch conditional
457 * @param io_path_cond_loc return location of the io_path conditional
461 _dbus_connection_test_get_locks (DBusConnection *connection,
462 DBusMutex **mutex_loc,
463 DBusMutex **dispatch_mutex_loc,
464 DBusMutex **io_path_mutex_loc,
465 DBusCondVar **dispatch_cond_loc,
466 DBusCondVar **io_path_cond_loc)
468 *mutex_loc = (DBusMutex *) connection->mutex;
469 *dispatch_mutex_loc = (DBusMutex *) connection->dispatch_mutex;
470 *io_path_mutex_loc = (DBusMutex *) connection->io_path_mutex;
471 *dispatch_cond_loc = connection->dispatch_cond;
472 *io_path_cond_loc = connection->io_path_cond;
477 * Adds a message-containing list link to the incoming message queue,
478 * taking ownership of the link and the message's current refcount.
479 * Cannot fail due to lack of memory.
481 * @param connection the connection.
482 * @param link the message link to queue.
485 _dbus_connection_queue_received_message_link (DBusConnection *connection,
488 DBusPendingCall *pending;
489 dbus_uint32_t reply_serial;
490 DBusMessage *message;
492 _dbus_assert (_dbus_transport_peek_is_authenticated (connection->transport));
494 _dbus_list_append_link (&connection->incoming_messages,
496 message = link->data;
498 /* If this is a reply we're waiting on, remove timeout for it */
499 reply_serial = dbus_message_get_reply_serial (message);
500 if (reply_serial != 0)
502 pending = _dbus_hash_table_lookup_int (connection->pending_replies,
506 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
507 _dbus_connection_remove_timeout_unlocked (connection,
508 _dbus_pending_call_get_timeout_unlocked (pending));
510 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
516 connection->n_incoming += 1;
518 _dbus_connection_wakeup_mainloop (connection);
520 _dbus_verbose ("Message %p (%s %s %s %s '%s' reply to %u) added to incoming queue %p, %d incoming\n",
522 dbus_message_type_to_string (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 dbus_message_get_reply_serial (message),
535 connection->n_incoming);
537 _dbus_message_trace_ref (message, -1, -1,
538 "_dbus_conection_queue_received_message_link");
542 * Adds a link + message to the incoming message queue.
543 * Can't fail. Takes ownership of both link and message.
545 * @param connection the connection.
546 * @param link the list node and message to queue.
550 _dbus_connection_queue_synthesized_message_link (DBusConnection *connection,
553 HAVE_LOCK_CHECK (connection);
555 _dbus_list_append_link (&connection->incoming_messages, link);
557 connection->n_incoming += 1;
559 _dbus_connection_wakeup_mainloop (connection);
561 _dbus_message_trace_ref (link->data, -1, -1,
562 "_dbus_connection_queue_synthesized_message_link");
564 _dbus_verbose ("Synthesized message %p added to incoming queue %p, %d incoming\n",
565 link->data, connection, connection->n_incoming);
570 * Checks whether there are messages in the outgoing message queue.
571 * Called with connection lock held.
573 * @param connection the connection.
574 * @returns #TRUE if the outgoing queue is non-empty.
577 _dbus_connection_has_messages_to_send_unlocked (DBusConnection *connection)
579 HAVE_LOCK_CHECK (connection);
580 return connection->outgoing_messages != NULL;
584 * Checks whether there are messages in the outgoing message queue.
585 * Use dbus_connection_flush() to block until all outgoing
586 * messages have been written to the underlying transport
587 * (such as a socket).
589 * @param connection the connection.
590 * @returns #TRUE if the outgoing queue is non-empty.
593 dbus_connection_has_messages_to_send (DBusConnection *connection)
597 _dbus_return_val_if_fail (connection != NULL, FALSE);
599 CONNECTION_LOCK (connection);
600 v = _dbus_connection_has_messages_to_send_unlocked (connection);
601 CONNECTION_UNLOCK (connection);
607 * Gets the next outgoing message. The message remains in the
608 * queue, and the caller does not own a reference to it.
610 * @param connection the connection.
611 * @returns the message to be sent.
614 _dbus_connection_get_message_to_send (DBusConnection *connection)
616 HAVE_LOCK_CHECK (connection);
618 return _dbus_list_get_last (&connection->outgoing_messages);
622 * Notifies the connection that a message has been sent, so the
623 * message can be removed from the outgoing queue.
624 * Called with the connection lock held.
626 * @param connection the connection.
627 * @param message the message that was sent.
630 _dbus_connection_message_sent_unlocked (DBusConnection *connection,
631 DBusMessage *message)
635 HAVE_LOCK_CHECK (connection);
637 /* This can be called before we even complete authentication, since
638 * it's called on disconnect to clean up the outgoing queue.
639 * It's also called as we successfully send each message.
642 link = _dbus_list_get_last_link (&connection->outgoing_messages);
643 _dbus_assert (link != NULL);
644 _dbus_assert (link->data == message);
646 _dbus_list_unlink (&connection->outgoing_messages,
648 _dbus_list_prepend_link (&connection->expired_messages, link);
650 connection->n_outgoing -= 1;
652 _dbus_verbose ("Message %p (%s %s %s %s '%s') removed from outgoing queue %p, %d left to send\n",
654 dbus_message_type_to_string (dbus_message_get_type (message)),
655 dbus_message_get_path (message) ?
656 dbus_message_get_path (message) :
658 dbus_message_get_interface (message) ?
659 dbus_message_get_interface (message) :
661 dbus_message_get_member (message) ?
662 dbus_message_get_member (message) :
664 dbus_message_get_signature (message),
665 connection, connection->n_outgoing);
667 /* It's OK that in principle we call the notify function, because for the
668 * outgoing limit, there isn't one */
669 _dbus_message_remove_counter (message, connection->outgoing_counter);
671 /* The message will actually be unreffed when we unlock */
674 /** Function to be called in protected_change_watch() with refcount held */
675 typedef dbus_bool_t (* DBusWatchAddFunction) (DBusWatchList *list,
677 /** Function to be called in protected_change_watch() with refcount held */
678 typedef void (* DBusWatchRemoveFunction) (DBusWatchList *list,
680 /** Function to be called in protected_change_watch() with refcount held */
681 typedef void (* DBusWatchToggleFunction) (DBusWatchList *list,
683 dbus_bool_t enabled);
686 protected_change_watch (DBusConnection *connection,
688 DBusWatchAddFunction add_function,
689 DBusWatchRemoveFunction remove_function,
690 DBusWatchToggleFunction toggle_function,
695 HAVE_LOCK_CHECK (connection);
697 /* The original purpose of protected_change_watch() was to hold a
698 * ref on the connection while dropping the connection lock, then
699 * calling out to the app. This was a broken hack that did not
700 * work, since the connection was in a hosed state (no WatchList
701 * field) while calling out.
703 * So for now we'll just keep the lock while calling out. This means
704 * apps are not allowed to call DBusConnection methods inside a
705 * watch function or they will deadlock.
707 * The "real fix" is to use the _and_unlock() pattern found
708 * elsewhere in the code, to defer calling out to the app until
709 * we're about to drop locks and return flow of control to the app
712 * See http://lists.freedesktop.org/archives/dbus/2007-July/thread.html#8144
715 if (connection->watches)
718 retval = (* add_function) (connection->watches, watch);
719 else if (remove_function)
722 (* remove_function) (connection->watches, watch);
727 (* toggle_function) (connection->watches, watch, enabled);
737 * Adds a watch using the connection's DBusAddWatchFunction if
738 * available. Otherwise records the watch to be added when said
739 * function is available. Also re-adds the watch if the
740 * DBusAddWatchFunction changes. May fail due to lack of memory.
741 * Connection lock should be held when calling this.
743 * @param connection the connection.
744 * @param watch the watch to add.
745 * @returns #TRUE on success.
748 _dbus_connection_add_watch_unlocked (DBusConnection *connection,
751 return protected_change_watch (connection, watch,
752 _dbus_watch_list_add_watch,
757 * Removes a watch using the connection's DBusRemoveWatchFunction
758 * if available. It's an error to call this function on a watch
759 * that was not previously added.
760 * Connection lock should be held when calling this.
762 * @param connection the connection.
763 * @param watch the watch to remove.
766 _dbus_connection_remove_watch_unlocked (DBusConnection *connection,
769 protected_change_watch (connection, watch,
771 _dbus_watch_list_remove_watch,
776 * Toggles a watch and notifies app via connection's
777 * DBusWatchToggledFunction if available. It's an error to call this
778 * function on a watch that was not previously added.
779 * Connection lock should be held when calling this.
781 * @param connection the connection.
782 * @param watch the watch to toggle.
783 * @param enabled whether to enable or disable
786 _dbus_connection_toggle_watch_unlocked (DBusConnection *connection,
790 _dbus_assert (watch != NULL);
792 protected_change_watch (connection, watch,
794 _dbus_watch_list_toggle_watch,
798 /** Function to be called in protected_change_timeout() with refcount held */
799 typedef dbus_bool_t (* DBusTimeoutAddFunction) (DBusTimeoutList *list,
800 DBusTimeout *timeout);
801 /** Function to be called in protected_change_timeout() with refcount held */
802 typedef void (* DBusTimeoutRemoveFunction) (DBusTimeoutList *list,
803 DBusTimeout *timeout);
804 /** Function to be called in protected_change_timeout() with refcount held */
805 typedef void (* DBusTimeoutToggleFunction) (DBusTimeoutList *list,
806 DBusTimeout *timeout,
807 dbus_bool_t enabled);
810 protected_change_timeout (DBusConnection *connection,
811 DBusTimeout *timeout,
812 DBusTimeoutAddFunction add_function,
813 DBusTimeoutRemoveFunction remove_function,
814 DBusTimeoutToggleFunction toggle_function,
819 HAVE_LOCK_CHECK (connection);
821 /* The original purpose of protected_change_timeout() was to hold a
822 * ref on the connection while dropping the connection lock, then
823 * calling out to the app. This was a broken hack that did not
824 * work, since the connection was in a hosed state (no TimeoutList
825 * field) while calling out.
827 * So for now we'll just keep the lock while calling out. This means
828 * apps are not allowed to call DBusConnection methods inside a
829 * timeout function or they will deadlock.
831 * The "real fix" is to use the _and_unlock() pattern found
832 * elsewhere in the code, to defer calling out to the app until
833 * we're about to drop locks and return flow of control to the app
836 * See http://lists.freedesktop.org/archives/dbus/2007-July/thread.html#8144
839 if (connection->timeouts)
842 retval = (* add_function) (connection->timeouts, timeout);
843 else if (remove_function)
846 (* remove_function) (connection->timeouts, timeout);
851 (* toggle_function) (connection->timeouts, timeout, enabled);
860 * Adds a timeout using the connection's DBusAddTimeoutFunction if
861 * available. Otherwise records the timeout to be added when said
862 * function is available. Also re-adds the timeout if the
863 * DBusAddTimeoutFunction changes. May fail due to lack of memory.
864 * The timeout will fire repeatedly until removed.
865 * Connection lock should be held when calling this.
867 * @param connection the connection.
868 * @param timeout the timeout to add.
869 * @returns #TRUE on success.
872 _dbus_connection_add_timeout_unlocked (DBusConnection *connection,
873 DBusTimeout *timeout)
875 return protected_change_timeout (connection, timeout,
876 _dbus_timeout_list_add_timeout,
881 * Removes a timeout using the connection's DBusRemoveTimeoutFunction
882 * if available. It's an error to call this function on a timeout
883 * that was not previously added.
884 * Connection lock should be held when calling this.
886 * @param connection the connection.
887 * @param timeout the timeout to remove.
890 _dbus_connection_remove_timeout_unlocked (DBusConnection *connection,
891 DBusTimeout *timeout)
893 protected_change_timeout (connection, timeout,
895 _dbus_timeout_list_remove_timeout,
900 * Toggles a timeout and notifies app via connection's
901 * DBusTimeoutToggledFunction if available. It's an error to call this
902 * function on a timeout that was not previously added.
903 * Connection lock should be held when calling this.
905 * @param connection the connection.
906 * @param timeout the timeout to toggle.
907 * @param enabled whether to enable or disable
910 _dbus_connection_toggle_timeout_unlocked (DBusConnection *connection,
911 DBusTimeout *timeout,
914 protected_change_timeout (connection, timeout,
916 _dbus_timeout_list_toggle_timeout,
921 _dbus_connection_attach_pending_call_unlocked (DBusConnection *connection,
922 DBusPendingCall *pending)
924 dbus_uint32_t reply_serial;
925 DBusTimeout *timeout;
927 HAVE_LOCK_CHECK (connection);
929 reply_serial = _dbus_pending_call_get_reply_serial_unlocked (pending);
931 _dbus_assert (reply_serial != 0);
933 timeout = _dbus_pending_call_get_timeout_unlocked (pending);
937 if (!_dbus_connection_add_timeout_unlocked (connection, timeout))
940 if (!_dbus_hash_table_insert_int (connection->pending_replies,
944 _dbus_connection_remove_timeout_unlocked (connection, timeout);
946 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
947 HAVE_LOCK_CHECK (connection);
951 _dbus_pending_call_set_timeout_added_unlocked (pending, TRUE);
955 if (!_dbus_hash_table_insert_int (connection->pending_replies,
959 HAVE_LOCK_CHECK (connection);
964 _dbus_pending_call_ref_unlocked (pending);
966 HAVE_LOCK_CHECK (connection);
972 free_pending_call_on_hash_removal (void *data)
974 DBusPendingCall *pending;
975 DBusConnection *connection;
982 connection = _dbus_pending_call_get_connection_unlocked (pending);
984 HAVE_LOCK_CHECK (connection);
986 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
988 _dbus_connection_remove_timeout_unlocked (connection,
989 _dbus_pending_call_get_timeout_unlocked (pending));
991 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
994 /* FIXME 1.0? this is sort of dangerous and undesirable to drop the lock
995 * here, but the pending call finalizer could in principle call out to
996 * application code so we pretty much have to... some larger code reorg
999 _dbus_connection_ref_unlocked (connection);
1000 _dbus_pending_call_unref_and_unlock (pending);
1001 CONNECTION_LOCK (connection);
1002 _dbus_connection_unref_unlocked (connection);
1006 _dbus_connection_detach_pending_call_unlocked (DBusConnection *connection,
1007 DBusPendingCall *pending)
1009 /* This ends up unlocking to call the pending call finalizer, which is unexpected to
1012 _dbus_hash_table_remove_int (connection->pending_replies,
1013 _dbus_pending_call_get_reply_serial_unlocked (pending));
1017 _dbus_connection_detach_pending_call_and_unlock (DBusConnection *connection,
1018 DBusPendingCall *pending)
1020 /* The idea here is to avoid finalizing the pending call
1021 * with the lock held, since there's a destroy notifier
1022 * in pending call that goes out to application code.
1024 * There's an extra unlock inside the hash table
1025 * "free pending call" function FIXME...
1027 _dbus_pending_call_ref_unlocked (pending);
1028 _dbus_hash_table_remove_int (connection->pending_replies,
1029 _dbus_pending_call_get_reply_serial_unlocked (pending));
1031 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
1032 _dbus_connection_remove_timeout_unlocked (connection,
1033 _dbus_pending_call_get_timeout_unlocked (pending));
1035 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
1037 _dbus_pending_call_unref_and_unlock (pending);
1041 * Removes a pending call from the connection, such that
1042 * the pending reply will be ignored. May drop the last
1043 * reference to the pending call.
1045 * @param connection the connection
1046 * @param pending the pending call
1049 _dbus_connection_remove_pending_call (DBusConnection *connection,
1050 DBusPendingCall *pending)
1052 CONNECTION_LOCK (connection);
1053 _dbus_connection_detach_pending_call_and_unlock (connection, pending);
1057 * Acquire the transporter I/O path. This must be done before
1058 * doing any I/O in the transporter. May sleep and drop the
1059 * IO path mutex while waiting for the I/O path.
1061 * @param connection the connection.
1062 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
1063 * @returns TRUE if the I/O path was acquired.
1066 _dbus_connection_acquire_io_path (DBusConnection *connection,
1067 int timeout_milliseconds)
1069 dbus_bool_t we_acquired;
1071 HAVE_LOCK_CHECK (connection);
1073 /* We don't want the connection to vanish */
1074 _dbus_connection_ref_unlocked (connection);
1076 /* We will only touch io_path_acquired which is protected by our mutex */
1077 CONNECTION_UNLOCK (connection);
1079 _dbus_verbose ("locking io_path_mutex\n");
1080 _dbus_cmutex_lock (connection->io_path_mutex);
1082 _dbus_verbose ("start connection->io_path_acquired = %d timeout = %d\n",
1083 connection->io_path_acquired, timeout_milliseconds);
1085 we_acquired = FALSE;
1087 if (connection->io_path_acquired)
1089 if (timeout_milliseconds != -1)
1091 _dbus_verbose ("waiting %d for IO path to be acquirable\n",
1092 timeout_milliseconds);
1094 if (!_dbus_condvar_wait_timeout (connection->io_path_cond,
1095 connection->io_path_mutex,
1096 timeout_milliseconds))
1098 /* We timed out before anyone signaled. */
1099 /* (writing the loop to handle the !timedout case by
1100 * waiting longer if needed is a pain since dbus
1101 * wraps pthread_cond_timedwait to take a relative
1102 * time instead of absolute, something kind of stupid
1103 * on our part. for now it doesn't matter, we will just
1104 * end up back here eventually.)
1110 while (connection->io_path_acquired)
1112 _dbus_verbose ("waiting for IO path to be acquirable\n");
1113 _dbus_condvar_wait (connection->io_path_cond,
1114 connection->io_path_mutex);
1119 if (!connection->io_path_acquired)
1122 connection->io_path_acquired = TRUE;
1125 _dbus_verbose ("end connection->io_path_acquired = %d we_acquired = %d\n",
1126 connection->io_path_acquired, we_acquired);
1128 _dbus_verbose ("unlocking io_path_mutex\n");
1129 _dbus_cmutex_unlock (connection->io_path_mutex);
1131 CONNECTION_LOCK (connection);
1133 HAVE_LOCK_CHECK (connection);
1135 _dbus_connection_unref_unlocked (connection);
1141 * Release the I/O path when you're done with it. Only call
1142 * after you've acquired the I/O. Wakes up at most one thread
1143 * currently waiting to acquire the I/O path.
1145 * @param connection the connection.
1148 _dbus_connection_release_io_path (DBusConnection *connection)
1150 HAVE_LOCK_CHECK (connection);
1152 _dbus_verbose ("locking io_path_mutex\n");
1153 _dbus_cmutex_lock (connection->io_path_mutex);
1155 _dbus_assert (connection->io_path_acquired);
1157 _dbus_verbose ("start connection->io_path_acquired = %d\n",
1158 connection->io_path_acquired);
1160 connection->io_path_acquired = FALSE;
1161 _dbus_condvar_wake_one (connection->io_path_cond);
1163 _dbus_verbose ("unlocking io_path_mutex\n");
1164 _dbus_cmutex_unlock (connection->io_path_mutex);
1168 * Queues incoming messages and sends outgoing messages for this
1169 * connection, optionally blocking in the process. Each call to
1170 * _dbus_connection_do_iteration_unlocked() will call select() or poll() one
1171 * time and then read or write data if possible.
1173 * The purpose of this function is to be able to flush outgoing
1174 * messages or queue up incoming messages without returning
1175 * control to the application and causing reentrancy weirdness.
1177 * The flags parameter allows you to specify whether to
1178 * read incoming messages, write outgoing messages, or both,
1179 * and whether to block if no immediate action is possible.
1181 * The timeout_milliseconds parameter does nothing unless the
1182 * iteration is blocking.
1184 * If there are no outgoing messages and DBUS_ITERATION_DO_READING
1185 * wasn't specified, then it's impossible to block, even if
1186 * you specify DBUS_ITERATION_BLOCK; in that case the function
1187 * returns immediately.
1189 * If pending is not NULL then a check is made if the pending call
1190 * is completed after the io path has been required. If the call
1191 * has been completed nothing is done. This must be done since
1192 * the _dbus_connection_acquire_io_path releases the connection
1195 * Called with connection lock held.
1197 * @param connection the connection.
1198 * @param pending the pending call that should be checked or NULL
1199 * @param flags iteration flags.
1200 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
1203 _dbus_connection_do_iteration_unlocked (DBusConnection *connection,
1204 DBusPendingCall *pending,
1206 int timeout_milliseconds)
1208 _dbus_verbose ("start\n");
1210 HAVE_LOCK_CHECK (connection);
1212 if (connection->n_outgoing == 0)
1213 flags &= ~DBUS_ITERATION_DO_WRITING;
1215 if (_dbus_connection_acquire_io_path (connection,
1216 (flags & DBUS_ITERATION_BLOCK) ? timeout_milliseconds : 0))
1218 HAVE_LOCK_CHECK (connection);
1220 if ( (pending != NULL) && _dbus_pending_call_get_completed_unlocked(pending))
1222 _dbus_verbose ("pending call completed while acquiring I/O path");
1224 else if ( (pending != NULL) &&
1225 _dbus_connection_peek_for_reply_unlocked (connection,
1226 _dbus_pending_call_get_reply_serial_unlocked (pending)))
1228 _dbus_verbose ("pending call completed while acquiring I/O path (reply found in queue)");
1232 _dbus_transport_do_iteration (connection->transport,
1233 flags, timeout_milliseconds);
1236 _dbus_connection_release_io_path (connection);
1239 HAVE_LOCK_CHECK (connection);
1241 _dbus_verbose ("end\n");
1245 * Creates a new connection for the given transport. A transport
1246 * represents a message stream that uses some concrete mechanism, such
1247 * as UNIX domain sockets. May return #NULL if insufficient
1248 * memory exists to create the connection.
1250 * @param transport the transport.
1251 * @returns the new connection, or #NULL on failure.
1253 #ifdef ENABLE_KDBUS_TRANSPORT
1254 static DBusConnection*
1255 _dbus_connection_new_for_transport_internal (DBusTransport *transport, dbus_bool_t exists)
1258 _dbus_connection_new_for_transport (DBusTransport *transport)
1261 DBusConnection *connection;
1262 DBusWatchList *watch_list;
1263 DBusTimeoutList *timeout_list;
1264 DBusHashTable *pending_replies;
1265 DBusList *disconnect_link;
1266 DBusMessage *disconnect_message;
1267 DBusCounter *outgoing_counter;
1268 DBusObjectTree *objects;
1272 pending_replies = NULL;
1273 timeout_list = NULL;
1274 disconnect_link = NULL;
1275 disconnect_message = NULL;
1276 outgoing_counter = NULL;
1279 watch_list = _dbus_watch_list_new ();
1280 if (watch_list == NULL)
1283 timeout_list = _dbus_timeout_list_new ();
1284 if (timeout_list == NULL)
1288 _dbus_hash_table_new (DBUS_HASH_INT,
1290 (DBusFreeFunction)free_pending_call_on_hash_removal);
1291 if (pending_replies == NULL)
1294 connection = dbus_new0 (DBusConnection, 1);
1295 if (connection == NULL)
1298 _dbus_rmutex_new_at_location (&connection->mutex);
1299 if (connection->mutex == NULL)
1302 _dbus_cmutex_new_at_location (&connection->io_path_mutex);
1303 if (connection->io_path_mutex == NULL)
1306 _dbus_cmutex_new_at_location (&connection->dispatch_mutex);
1307 if (connection->dispatch_mutex == NULL)
1310 _dbus_condvar_new_at_location (&connection->dispatch_cond);
1311 if (connection->dispatch_cond == NULL)
1314 _dbus_condvar_new_at_location (&connection->io_path_cond);
1315 if (connection->io_path_cond == NULL)
1318 _dbus_rmutex_new_at_location (&connection->slot_mutex);
1319 if (connection->slot_mutex == NULL)
1322 disconnect_message = dbus_message_new_signal (DBUS_PATH_LOCAL,
1323 DBUS_INTERFACE_LOCAL,
1326 if (disconnect_message == NULL)
1329 disconnect_link = _dbus_list_alloc_link (disconnect_message);
1330 if (disconnect_link == NULL)
1333 outgoing_counter = _dbus_counter_new ();
1334 if (outgoing_counter == NULL)
1337 objects = _dbus_object_tree_new (connection);
1338 if (objects == NULL)
1341 if (_dbus_modify_sigpipe)
1342 _dbus_disable_sigpipe ();
1344 /* initialized to 0: use atomic op to avoid mixing atomic and non-atomic */
1345 _dbus_atomic_inc (&connection->refcount);
1346 connection->transport = transport;
1347 connection->watches = watch_list;
1348 connection->timeouts = timeout_list;
1349 connection->pending_replies = pending_replies;
1350 connection->outgoing_counter = outgoing_counter;
1351 connection->filter_list = NULL;
1352 connection->last_dispatch_status = DBUS_DISPATCH_COMPLETE; /* so we're notified first time there's data */
1353 connection->objects = objects;
1354 connection->exit_on_disconnect = FALSE;
1355 connection->shareable = FALSE;
1356 connection->route_peer_messages = FALSE;
1357 connection->disconnected_message_arrived = FALSE;
1358 connection->disconnected_message_processed = FALSE;
1360 #if defined(DBUS_ENABLE_CHECKS) || defined(DBUS_ENABLE_ASSERT)
1361 connection->generation = _dbus_current_generation;
1364 _dbus_data_slot_list_init (&connection->slot_list);
1366 connection->client_serial = 1;
1368 connection->disconnect_message_link = disconnect_link;
1370 #ifdef ENABLE_KDBUS_TRANSPORT
1374 CONNECTION_LOCK (connection);
1376 if (!_dbus_transport_set_connection (transport, connection))
1378 CONNECTION_UNLOCK (connection);
1383 _dbus_transport_ref (transport);
1385 CONNECTION_UNLOCK (connection);
1388 _dbus_connection_trace_ref (connection, 0, 1, "new_for_transport");
1392 if (disconnect_message != NULL)
1393 dbus_message_unref (disconnect_message);
1395 if (disconnect_link != NULL)
1396 _dbus_list_free_link (disconnect_link);
1398 if (connection != NULL)
1400 _dbus_condvar_free_at_location (&connection->io_path_cond);
1401 _dbus_condvar_free_at_location (&connection->dispatch_cond);
1402 _dbus_rmutex_free_at_location (&connection->mutex);
1403 _dbus_cmutex_free_at_location (&connection->io_path_mutex);
1404 _dbus_cmutex_free_at_location (&connection->dispatch_mutex);
1405 _dbus_rmutex_free_at_location (&connection->slot_mutex);
1406 dbus_free (connection);
1408 if (pending_replies)
1409 _dbus_hash_table_unref (pending_replies);
1412 _dbus_watch_list_free (watch_list);
1415 _dbus_timeout_list_free (timeout_list);
1417 if (outgoing_counter)
1418 _dbus_counter_unref (outgoing_counter);
1421 _dbus_object_tree_unref (objects);
1426 #ifdef ENABLE_KDBUS_TRANSPORT
1428 * Creates a new connection for the given transport. A transport
1429 * represents a message stream that uses some concrete mechanism, such
1430 * as UNIX domain sockets. May return #NULL if insufficient
1431 * memory exists to create the connection.
1433 * @param transport the transport.
1434 * @returns the new connection, or #NULL on failure.
1437 _dbus_connection_new_for_transport (DBusTransport *transport)
1439 return _dbus_connection_new_for_transport_internal(transport, FALSE);
1443 _dbus_connection_new_for_used_transport (DBusTransport *transport)
1445 return _dbus_connection_new_for_transport_internal(transport, TRUE);
1450 * Increments the reference count of a DBusConnection.
1451 * Requires that the caller already holds the connection lock.
1453 * @param connection the connection.
1454 * @returns the connection.
1457 _dbus_connection_ref_unlocked (DBusConnection *connection)
1459 dbus_int32_t old_refcount;
1461 _dbus_assert (connection != NULL);
1462 _dbus_assert (connection->generation == _dbus_current_generation);
1464 HAVE_LOCK_CHECK (connection);
1466 old_refcount = _dbus_atomic_inc (&connection->refcount);
1467 _dbus_connection_trace_ref (connection, old_refcount, old_refcount + 1,
1474 * Decrements the reference count of a DBusConnection.
1475 * Requires that the caller already holds the connection lock.
1477 * @param connection the connection.
1480 _dbus_connection_unref_unlocked (DBusConnection *connection)
1482 dbus_int32_t old_refcount;
1484 HAVE_LOCK_CHECK (connection);
1486 _dbus_assert (connection != NULL);
1488 old_refcount = _dbus_atomic_dec (&connection->refcount);
1490 _dbus_connection_trace_ref (connection, old_refcount, old_refcount - 1,
1493 if (old_refcount == 1)
1494 _dbus_connection_last_unref (connection);
1497 static dbus_uint32_t
1498 _dbus_connection_get_next_client_serial (DBusConnection *connection)
1500 dbus_uint32_t serial;
1502 serial = connection->client_serial++;
1504 if (connection->client_serial == 0)
1505 connection->client_serial = 1;
1511 * A callback for use with dbus_watch_new() to create a DBusWatch.
1513 * @todo This is basically a hack - we could delete _dbus_transport_handle_watch()
1514 * and the virtual handle_watch in DBusTransport if we got rid of it.
1515 * The reason this is some work is threading, see the _dbus_connection_handle_watch()
1518 * @param watch the watch.
1519 * @param condition the current condition of the file descriptors being watched.
1520 * @param data must be a pointer to a #DBusConnection
1521 * @returns #FALSE if the IO condition may not have been fully handled due to lack of memory
1524 _dbus_connection_handle_watch (DBusWatch *watch,
1525 unsigned int condition,
1528 DBusConnection *connection;
1530 DBusDispatchStatus status;
1534 _dbus_verbose ("start\n");
1536 CONNECTION_LOCK (connection);
1538 if (!_dbus_connection_acquire_io_path (connection, 1))
1540 /* another thread is handling the message */
1541 CONNECTION_UNLOCK (connection);
1545 HAVE_LOCK_CHECK (connection);
1546 retval = _dbus_transport_handle_watch (connection->transport,
1549 _dbus_connection_release_io_path (connection);
1551 HAVE_LOCK_CHECK (connection);
1553 _dbus_verbose ("middle\n");
1555 status = _dbus_connection_get_dispatch_status_unlocked (connection);
1557 /* this calls out to user code */
1558 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1560 _dbus_verbose ("end\n");
1565 /* Protected by _DBUS_LOCK (shared_connections) */
1566 static DBusHashTable *shared_connections = NULL;
1567 static DBusList *shared_connections_no_guid = NULL;
1570 close_connection_on_shutdown (DBusConnection *connection)
1572 DBusMessage *message;
1574 dbus_connection_ref (connection);
1575 _dbus_connection_close_possibly_shared (connection);
1577 /* Churn through to the Disconnected message */
1578 while ((message = dbus_connection_pop_message (connection)))
1580 dbus_message_unref (message);
1582 dbus_connection_unref (connection);
1586 shared_connections_shutdown (void *data)
1590 if (!_DBUS_LOCK (shared_connections))
1592 /* We'd have initialized locks before adding anything, so there
1593 * can't be anything there. */
1597 /* This is a little bit unpleasant... better ideas? */
1598 while ((n_entries = _dbus_hash_table_get_n_entries (shared_connections)) > 0)
1600 DBusConnection *connection;
1603 _dbus_hash_iter_init (shared_connections, &iter);
1604 _dbus_hash_iter_next (&iter);
1606 connection = _dbus_hash_iter_get_value (&iter);
1608 _DBUS_UNLOCK (shared_connections);
1609 close_connection_on_shutdown (connection);
1610 if (!_DBUS_LOCK (shared_connections))
1611 _dbus_assert_not_reached ("global locks were already initialized");
1613 /* The connection should now be dead and not in our hash ... */
1614 _dbus_assert (_dbus_hash_table_get_n_entries (shared_connections) < n_entries);
1617 _dbus_assert (_dbus_hash_table_get_n_entries (shared_connections) == 0);
1619 _dbus_hash_table_unref (shared_connections);
1620 shared_connections = NULL;
1622 if (shared_connections_no_guid != NULL)
1624 DBusConnection *connection;
1625 connection = _dbus_list_pop_first (&shared_connections_no_guid);
1626 while (connection != NULL)
1628 _DBUS_UNLOCK (shared_connections);
1629 close_connection_on_shutdown (connection);
1630 if (!_DBUS_LOCK (shared_connections))
1631 _dbus_assert_not_reached ("global locks were already initialized");
1632 connection = _dbus_list_pop_first (&shared_connections_no_guid);
1636 shared_connections_no_guid = NULL;
1638 _DBUS_UNLOCK (shared_connections);
1642 connection_lookup_shared (DBusAddressEntry *entry,
1643 DBusConnection **result)
1645 _dbus_verbose ("checking for existing connection\n");
1649 if (!_DBUS_LOCK (shared_connections))
1651 /* If it was shared, we'd have initialized global locks when we put
1652 * it in shared_connections. */
1656 if (shared_connections == NULL)
1658 _dbus_verbose ("creating shared_connections hash table\n");
1660 shared_connections = _dbus_hash_table_new (DBUS_HASH_STRING,
1663 if (shared_connections == NULL)
1665 _DBUS_UNLOCK (shared_connections);
1669 if (!_dbus_register_shutdown_func (shared_connections_shutdown, NULL))
1671 _dbus_hash_table_unref (shared_connections);
1672 shared_connections = NULL;
1673 _DBUS_UNLOCK (shared_connections);
1677 _dbus_verbose (" successfully created shared_connections\n");
1679 _DBUS_UNLOCK (shared_connections);
1680 return TRUE; /* no point looking up in the hash we just made */
1686 guid = dbus_address_entry_get_value (entry, "guid");
1690 DBusConnection *connection;
1692 connection = _dbus_hash_table_lookup_string (shared_connections,
1697 /* The DBusConnection can't be finalized without taking
1698 * the shared_connections lock to remove it from the
1699 * hash. So it's safe to ref the connection here.
1700 * However, it may be disconnected if the Disconnected
1701 * message hasn't been processed yet, in which case we
1702 * want to pretend it isn't in the hash and avoid
1705 * The idea is to avoid ever returning a disconnected connection
1706 * from dbus_connection_open(). We could just synchronously
1707 * drop our shared ref to the connection on connection disconnect,
1708 * and then assert here that the connection is connected, but
1709 * that causes reentrancy headaches.
1711 CONNECTION_LOCK (connection);
1712 if (_dbus_connection_get_is_connected_unlocked (connection))
1714 _dbus_connection_ref_unlocked (connection);
1715 *result = connection;
1716 _dbus_verbose ("looked up existing connection to server guid %s\n",
1721 _dbus_verbose ("looked up existing connection to server guid %s but it was disconnected so ignoring it\n",
1724 CONNECTION_UNLOCK (connection);
1728 _DBUS_UNLOCK (shared_connections);
1734 connection_record_shared_unlocked (DBusConnection *connection,
1738 char *guid_in_connection;
1740 HAVE_LOCK_CHECK (connection);
1741 _dbus_assert (connection->server_guid == NULL);
1742 _dbus_assert (connection->shareable);
1744 /* get a hard ref on this connection, even if
1745 * we won't in fact store it in the hash, we still
1746 * need to hold a ref on it until it's disconnected.
1748 _dbus_connection_ref_unlocked (connection);
1752 if (!_DBUS_LOCK (shared_connections))
1755 if (!_dbus_list_prepend (&shared_connections_no_guid, connection))
1757 _DBUS_UNLOCK (shared_connections);
1761 _DBUS_UNLOCK (shared_connections);
1762 return TRUE; /* don't store in the hash */
1765 /* A separate copy of the key is required in the hash table, because
1766 * we don't have a lock on the connection when we are doing a hash
1770 guid_key = _dbus_strdup (guid);
1771 if (guid_key == NULL)
1774 guid_in_connection = _dbus_strdup (guid);
1775 if (guid_in_connection == NULL)
1777 dbus_free (guid_key);
1781 if (!_DBUS_LOCK (shared_connections))
1783 dbus_free (guid_in_connection);
1784 dbus_free (guid_key);
1788 _dbus_assert (shared_connections != NULL);
1790 if (!_dbus_hash_table_insert_string (shared_connections,
1791 guid_key, connection))
1793 dbus_free (guid_key);
1794 dbus_free (guid_in_connection);
1795 _DBUS_UNLOCK (shared_connections);
1799 connection->server_guid = guid_in_connection;
1801 _dbus_verbose ("stored connection to %s to be shared\n",
1802 connection->server_guid);
1804 _DBUS_UNLOCK (shared_connections);
1806 _dbus_assert (connection->server_guid != NULL);
1812 connection_forget_shared_unlocked (DBusConnection *connection)
1814 HAVE_LOCK_CHECK (connection);
1816 if (!connection->shareable)
1819 if (!_DBUS_LOCK (shared_connections))
1821 /* If it was shared, we'd have initialized global locks when we put
1822 * it in the table; so it can't be there. */
1826 if (connection->server_guid != NULL)
1828 _dbus_verbose ("dropping connection to %s out of the shared table\n",
1829 connection->server_guid);
1831 if (!_dbus_hash_table_remove_string (shared_connections,
1832 connection->server_guid))
1833 _dbus_assert_not_reached ("connection was not in the shared table");
1835 dbus_free (connection->server_guid);
1836 connection->server_guid = NULL;
1840 _dbus_list_remove (&shared_connections_no_guid, connection);
1843 _DBUS_UNLOCK (shared_connections);
1845 /* remove our reference held on all shareable connections */
1846 _dbus_connection_unref_unlocked (connection);
1849 static DBusConnection*
1850 connection_try_from_address_entry (DBusAddressEntry *entry,
1853 DBusTransport *transport;
1854 DBusConnection *connection;
1856 transport = _dbus_transport_open (entry, error);
1858 if (transport == NULL)
1860 _DBUS_ASSERT_ERROR_IS_SET (error);
1864 connection = _dbus_connection_new_for_transport (transport);
1866 _dbus_transport_unref (transport);
1868 if (connection == NULL)
1870 _DBUS_SET_OOM (error);
1874 #ifndef DBUS_DISABLE_CHECKS
1875 _dbus_assert (!connection->have_connection_lock);
1882 * If the shared parameter is true, then any existing connection will
1883 * be used (and if a new connection is created, it will be available
1884 * for use by others). If the shared parameter is false, a new
1885 * connection will always be created, and the new connection will
1886 * never be returned to other callers.
1888 * @param address the address
1889 * @param shared whether the connection is shared or private
1890 * @param error error return
1891 * @returns the connection or #NULL on error
1893 static DBusConnection*
1894 _dbus_connection_open_internal (const char *address,
1898 DBusConnection *connection;
1899 DBusAddressEntry **entries;
1900 DBusError tmp_error = DBUS_ERROR_INIT;
1901 DBusError first_error = DBUS_ERROR_INIT;
1904 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1906 _dbus_verbose ("opening %s connection to: %s\n",
1907 shared ? "shared" : "private", address);
1909 if (!dbus_parse_address (address, &entries, &len, error))
1912 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1916 for (i = 0; i < len; i++)
1920 if (!connection_lookup_shared (entries[i], &connection))
1921 _DBUS_SET_OOM (&tmp_error);
1924 if (connection == NULL)
1926 connection = connection_try_from_address_entry (entries[i],
1929 if (connection != NULL && shared)
1933 connection->shareable = TRUE;
1935 /* guid may be NULL */
1936 guid = dbus_address_entry_get_value (entries[i], "guid");
1938 CONNECTION_LOCK (connection);
1940 if (!connection_record_shared_unlocked (connection, guid))
1942 _DBUS_SET_OOM (&tmp_error);
1943 _dbus_connection_close_possibly_shared_and_unlock (connection);
1944 dbus_connection_unref (connection);
1948 CONNECTION_UNLOCK (connection);
1955 _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
1958 dbus_move_error (&tmp_error, &first_error);
1960 dbus_error_free (&tmp_error);
1963 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1964 _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
1966 if (connection == NULL)
1968 _DBUS_ASSERT_ERROR_IS_SET (&first_error);
1969 dbus_move_error (&first_error, error);
1972 dbus_error_free (&first_error);
1974 dbus_address_entries_free (entries);
1979 * Closes a shared OR private connection, while dbus_connection_close() can
1980 * only be used on private connections. Should only be called by the
1981 * dbus code that owns the connection - an owner must be known,
1982 * the open/close state is like malloc/free, not like ref/unref.
1984 * @param connection the connection
1987 _dbus_connection_close_possibly_shared (DBusConnection *connection)
1989 _dbus_assert (connection != NULL);
1990 _dbus_assert (connection->generation == _dbus_current_generation);
1992 CONNECTION_LOCK (connection);
1993 _dbus_connection_close_possibly_shared_and_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 preallocated->queue_link = _dbus_list_alloc_link (NULL);
2010 if (preallocated->queue_link == NULL)
2013 preallocated->counter_link = _dbus_list_alloc_link (connection->outgoing_counter);
2014 if (preallocated->counter_link == NULL)
2017 _dbus_counter_ref (preallocated->counter_link->data);
2019 preallocated->connection = connection;
2021 return preallocated;
2024 _dbus_list_free_link (preallocated->queue_link);
2026 dbus_free (preallocated);
2031 /* Called with lock held, does not update dispatch status */
2033 _dbus_connection_send_preallocated_unlocked_no_update (DBusConnection *connection,
2034 DBusPreallocatedSend *preallocated,
2035 DBusMessage *message,
2036 dbus_uint32_t *client_serial)
2038 dbus_uint32_t serial;
2040 preallocated->queue_link->data = message;
2041 _dbus_list_prepend_link (&connection->outgoing_messages,
2042 preallocated->queue_link);
2044 /* It's OK that we'll never call the notify function, because for the
2045 * outgoing limit, there isn't one */
2046 _dbus_message_add_counter_link (message,
2047 preallocated->counter_link);
2049 dbus_free (preallocated);
2050 preallocated = NULL;
2052 dbus_message_ref (message);
2054 connection->n_outgoing += 1;
2056 _dbus_verbose ("Message %p (%s %s %s %s '%s') for %s added to outgoing queue %p, %d pending to send\n",
2058 dbus_message_type_to_string (dbus_message_get_type (message)),
2059 dbus_message_get_path (message) ?
2060 dbus_message_get_path (message) :
2062 dbus_message_get_interface (message) ?
2063 dbus_message_get_interface (message) :
2065 dbus_message_get_member (message) ?
2066 dbus_message_get_member (message) :
2068 dbus_message_get_signature (message),
2069 dbus_message_get_destination (message) ?
2070 dbus_message_get_destination (message) :
2073 connection->n_outgoing);
2075 if (dbus_message_get_serial (message) == 0)
2077 serial = _dbus_connection_get_next_client_serial (connection);
2078 dbus_message_set_serial (message, serial);
2080 *client_serial = serial;
2085 *client_serial = dbus_message_get_serial (message);
2088 _dbus_verbose ("Message %p serial is %u\n",
2089 message, dbus_message_get_serial (message));
2091 dbus_message_lock (message);
2093 /* Now we need to run an iteration to hopefully just write the messages
2094 * out immediately, and otherwise get them queued up
2096 _dbus_connection_do_iteration_unlocked (connection,
2098 DBUS_ITERATION_DO_WRITING,
2101 /* If stuff is still queued up, be sure we wake up the main loop */
2102 if (connection->n_outgoing > 0)
2103 _dbus_connection_wakeup_mainloop (connection);
2107 _dbus_connection_send_preallocated_and_unlock (DBusConnection *connection,
2108 DBusPreallocatedSend *preallocated,
2109 DBusMessage *message,
2110 dbus_uint32_t *client_serial)
2112 DBusDispatchStatus status;
2114 HAVE_LOCK_CHECK (connection);
2116 _dbus_connection_send_preallocated_unlocked_no_update (connection,
2118 message, client_serial);
2120 _dbus_verbose ("middle\n");
2121 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2123 /* this calls out to user code */
2124 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2128 * Like dbus_connection_send(), but assumes the connection
2129 * is already locked on function entry, and unlocks before returning.
2131 * @param connection the connection
2132 * @param message the message to send
2133 * @param client_serial return location for client serial of sent message
2134 * @returns #FALSE on out-of-memory
2137 _dbus_connection_send_and_unlock (DBusConnection *connection,
2138 DBusMessage *message,
2139 dbus_uint32_t *client_serial)
2141 DBusPreallocatedSend *preallocated;
2143 _dbus_assert (connection != NULL);
2144 _dbus_assert (message != NULL);
2146 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
2147 if (preallocated == NULL)
2149 CONNECTION_UNLOCK (connection);
2153 _dbus_connection_send_preallocated_and_unlock (connection,
2161 * Used internally to handle the semantics of dbus_server_set_new_connection_function().
2162 * If the new connection function does not ref the connection, we want to close it.
2164 * A bit of a hack, probably the new connection function should have returned a value
2165 * for whether to close, or should have had to close the connection itself if it
2168 * But, this works OK as long as the new connection function doesn't do anything
2169 * crazy like keep the connection around without ref'ing it.
2171 * We have to lock the connection across refcount check and close in case
2172 * the new connection function spawns a thread that closes and unrefs.
2173 * In that case, if the app thread
2174 * closes and unrefs first, we'll harmlessly close again; if the app thread
2175 * still has the ref, we'll close and then the app will close harmlessly.
2176 * If the app unrefs without closing, the app is broken since if the
2177 * app refs from the new connection function it is supposed to also close.
2179 * If we didn't atomically check the refcount and close with the lock held
2180 * though, we could screw this up.
2182 * @param connection the connection
2185 _dbus_connection_close_if_only_one_ref (DBusConnection *connection)
2187 dbus_int32_t refcount;
2189 CONNECTION_LOCK (connection);
2191 refcount = _dbus_atomic_get (&connection->refcount);
2192 /* The caller should have at least one ref */
2193 _dbus_assert (refcount >= 1);
2196 _dbus_connection_close_possibly_shared_and_unlock (connection);
2198 CONNECTION_UNLOCK (connection);
2203 * When a function that blocks has been called with a timeout, and we
2204 * run out of memory, the time to wait for memory is based on the
2205 * timeout. If the caller was willing to block a long time we wait a
2206 * relatively long time for memory, if they were only willing to block
2207 * briefly then we retry for memory at a rapid rate.
2209 * @param timeout_milliseconds the timeout requested for blocking
2212 _dbus_memory_pause_based_on_timeout (int timeout_milliseconds)
2214 if (timeout_milliseconds == -1)
2215 _dbus_sleep_milliseconds (1000);
2216 else if (timeout_milliseconds < 100)
2217 ; /* just busy loop */
2218 else if (timeout_milliseconds <= 1000)
2219 _dbus_sleep_milliseconds (timeout_milliseconds / 3);
2221 _dbus_sleep_milliseconds (1000);
2225 generate_local_error_message (dbus_uint32_t serial,
2229 DBusMessage *message;
2230 message = dbus_message_new (DBUS_MESSAGE_TYPE_ERROR);
2234 if (!dbus_message_set_error_name (message, error_name))
2236 dbus_message_unref (message);
2241 dbus_message_set_no_reply (message, TRUE);
2243 if (!dbus_message_set_reply_serial (message,
2246 dbus_message_unref (message);
2251 if (error_msg != NULL)
2253 DBusMessageIter iter;
2255 dbus_message_iter_init_append (message, &iter);
2256 if (!dbus_message_iter_append_basic (&iter,
2260 dbus_message_unref (message);
2271 * Peek the incoming queue to see if we got reply for a specific serial
2274 _dbus_connection_peek_for_reply_unlocked (DBusConnection *connection,
2275 dbus_uint32_t client_serial)
2278 HAVE_LOCK_CHECK (connection);
2280 link = _dbus_list_get_first_link (&connection->incoming_messages);
2282 while (link != NULL)
2284 DBusMessage *reply = link->data;
2286 if (dbus_message_get_reply_serial (reply) == client_serial)
2288 _dbus_verbose ("%s reply to %d found in queue\n", _DBUS_FUNCTION_NAME, client_serial);
2291 link = _dbus_list_get_next_link (&connection->incoming_messages, link);
2297 /* This is slightly strange since we can pop a message here without
2298 * the dispatch lock.
2301 check_for_reply_unlocked (DBusConnection *connection,
2302 dbus_uint32_t client_serial)
2306 HAVE_LOCK_CHECK (connection);
2308 link = _dbus_list_get_first_link (&connection->incoming_messages);
2310 while (link != NULL)
2312 DBusMessage *reply = link->data;
2314 if (dbus_message_get_reply_serial (reply) == client_serial)
2316 _dbus_list_remove_link (&connection->incoming_messages, link);
2317 connection->n_incoming -= 1;
2320 link = _dbus_list_get_next_link (&connection->incoming_messages, link);
2327 connection_timeout_and_complete_all_pending_calls_unlocked (DBusConnection *connection)
2329 /* We can't iterate over the hash in the normal way since we'll be
2330 * dropping the lock for each item. So we restart the
2331 * iter each time as we drain the hash table.
2334 while (_dbus_hash_table_get_n_entries (connection->pending_replies) > 0)
2336 DBusPendingCall *pending;
2339 _dbus_hash_iter_init (connection->pending_replies, &iter);
2340 _dbus_hash_iter_next (&iter);
2342 pending = _dbus_hash_iter_get_value (&iter);
2343 _dbus_pending_call_ref_unlocked (pending);
2345 _dbus_pending_call_queue_timeout_error_unlocked (pending,
2348 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
2349 _dbus_connection_remove_timeout_unlocked (connection,
2350 _dbus_pending_call_get_timeout_unlocked (pending));
2351 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
2352 _dbus_hash_iter_remove_entry (&iter);
2354 _dbus_pending_call_unref_and_unlock (pending);
2355 CONNECTION_LOCK (connection);
2357 HAVE_LOCK_CHECK (connection);
2361 complete_pending_call_and_unlock (DBusConnection *connection,
2362 DBusPendingCall *pending,
2363 DBusMessage *message)
2365 _dbus_pending_call_set_reply_unlocked (pending, message);
2366 _dbus_pending_call_ref_unlocked (pending); /* in case there's no app with a ref held */
2367 _dbus_connection_detach_pending_call_and_unlock (connection, pending);
2369 /* Must be called unlocked since it invokes app callback */
2370 _dbus_pending_call_complete (pending);
2371 dbus_pending_call_unref (pending);
2375 check_for_reply_and_update_dispatch_unlocked (DBusConnection *connection,
2376 DBusPendingCall *pending)
2379 DBusDispatchStatus status;
2381 reply = check_for_reply_unlocked (connection,
2382 _dbus_pending_call_get_reply_serial_unlocked (pending));
2385 _dbus_verbose ("checked for reply\n");
2387 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): got reply\n");
2389 complete_pending_call_and_unlock (connection, pending, reply);
2390 dbus_message_unref (reply);
2392 CONNECTION_LOCK (connection);
2393 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2394 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2395 dbus_pending_call_unref (pending);
2404 * Blocks until a pending call times out or gets a reply.
2406 * Does not re-enter the main loop or run filter/path-registered
2407 * callbacks. The reply to the message will not be seen by
2410 * Returns immediately if pending call already got a reply.
2412 * @todo could use performance improvements (it keeps scanning
2413 * the whole message queue for example)
2415 * @param pending the pending call we block for a reply on
2418 _dbus_connection_block_pending_call (DBusPendingCall *pending)
2420 long start_tv_sec, start_tv_usec;
2421 long tv_sec, tv_usec;
2422 DBusDispatchStatus status;
2423 DBusConnection *connection;
2424 dbus_uint32_t client_serial;
2425 DBusTimeout *timeout;
2426 int timeout_milliseconds, elapsed_milliseconds;
2428 _dbus_assert (pending != NULL);
2430 if (dbus_pending_call_get_completed (pending))
2433 dbus_pending_call_ref (pending); /* necessary because the call could be canceled */
2435 connection = _dbus_pending_call_get_connection_and_lock (pending);
2437 /* Flush message queue - note, can affect dispatch status */
2438 _dbus_connection_flush_unlocked (connection);
2440 client_serial = _dbus_pending_call_get_reply_serial_unlocked (pending);
2442 /* note that timeout_milliseconds is limited to a smallish value
2443 * in _dbus_pending_call_new() so overflows aren't possible
2446 timeout = _dbus_pending_call_get_timeout_unlocked (pending);
2447 _dbus_get_monotonic_time (&start_tv_sec, &start_tv_usec);
2450 timeout_milliseconds = dbus_timeout_get_interval (timeout);
2452 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): will block %d milliseconds for reply serial %u from %ld sec %ld usec\n",
2453 timeout_milliseconds,
2455 start_tv_sec, start_tv_usec);
2459 timeout_milliseconds = -1;
2461 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): will block for reply serial %u\n", client_serial);
2464 /* check to see if we already got the data off the socket */
2465 /* from another blocked pending call */
2466 if (check_for_reply_and_update_dispatch_unlocked (connection, pending))
2469 /* Now we wait... */
2470 /* always block at least once as we know we don't have the reply yet */
2471 _dbus_connection_do_iteration_unlocked (connection,
2473 DBUS_ITERATION_DO_READING |
2474 DBUS_ITERATION_BLOCK,
2475 timeout_milliseconds);
2479 _dbus_verbose ("top of recheck\n");
2481 HAVE_LOCK_CHECK (connection);
2483 /* queue messages and get status */
2485 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2487 /* the get_completed() is in case a dispatch() while we were blocking
2488 * got the reply instead of us.
2490 if (_dbus_pending_call_get_completed_unlocked (pending))
2492 _dbus_verbose ("Pending call completed by dispatch\n");
2493 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2494 dbus_pending_call_unref (pending);
2498 if (status == DBUS_DISPATCH_DATA_REMAINS)
2500 if (check_for_reply_and_update_dispatch_unlocked (connection, pending))
2504 _dbus_get_monotonic_time (&tv_sec, &tv_usec);
2505 elapsed_milliseconds = (tv_sec - start_tv_sec) * 1000 +
2506 (tv_usec - start_tv_usec) / 1000;
2508 if (!_dbus_connection_get_is_connected_unlocked (connection))
2510 DBusMessage *error_msg;
2512 error_msg = generate_local_error_message (client_serial,
2513 DBUS_ERROR_DISCONNECTED,
2514 "Connection was disconnected before a reply was received");
2516 /* on OOM error_msg is set to NULL */
2517 complete_pending_call_and_unlock (connection, pending, error_msg);
2518 dbus_pending_call_unref (pending);
2521 else if (connection->disconnect_message_link == NULL)
2522 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): disconnected\n");
2523 else if (timeout == NULL)
2525 if (status == DBUS_DISPATCH_NEED_MEMORY)
2527 /* Try sleeping a bit, as we aren't sure we need to block for reading,
2528 * we may already have a reply in the buffer and just can't process
2531 _dbus_verbose ("dbus_connection_send_with_reply_and_block() waiting for more memory\n");
2533 _dbus_memory_pause_based_on_timeout (timeout_milliseconds - elapsed_milliseconds);
2537 /* block again, we don't have the reply buffered yet. */
2538 _dbus_connection_do_iteration_unlocked (connection,
2540 DBUS_ITERATION_DO_READING |
2541 DBUS_ITERATION_BLOCK,
2542 timeout_milliseconds - elapsed_milliseconds);
2545 goto recheck_status;
2547 else if (tv_sec < start_tv_sec)
2548 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): clock set backward\n");
2549 else if (elapsed_milliseconds < timeout_milliseconds)
2551 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): %d milliseconds remain\n", timeout_milliseconds - elapsed_milliseconds);
2553 if (status == DBUS_DISPATCH_NEED_MEMORY)
2555 /* Try sleeping a bit, as we aren't sure we need to block for reading,
2556 * we may already have a reply in the buffer and just can't process
2559 _dbus_verbose ("dbus_connection_send_with_reply_and_block() waiting for more memory\n");
2561 _dbus_memory_pause_based_on_timeout (timeout_milliseconds - elapsed_milliseconds);
2565 /* block again, we don't have the reply buffered yet. */
2566 _dbus_connection_do_iteration_unlocked (connection,
2568 DBUS_ITERATION_DO_READING |
2569 DBUS_ITERATION_BLOCK,
2570 timeout_milliseconds - elapsed_milliseconds);
2573 goto recheck_status;
2576 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): Waited %d milliseconds and got no reply\n",
2577 elapsed_milliseconds);
2579 _dbus_assert (!_dbus_pending_call_get_completed_unlocked (pending));
2581 /* unlock and call user code */
2582 complete_pending_call_and_unlock (connection, pending, NULL);
2584 /* update user code on dispatch status */
2585 CONNECTION_LOCK (connection);
2586 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2587 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2588 dbus_pending_call_unref (pending);
2594 * @addtogroup DBusConnection
2600 * Gets a connection to a remote address. If a connection to the given
2601 * address already exists, returns the existing connection with its
2602 * reference count incremented. Otherwise, returns a new connection
2603 * and saves the new connection for possible re-use if a future call
2604 * to dbus_connection_open() asks to connect to the same server.
2606 * Use dbus_connection_open_private() to get a dedicated connection
2607 * not shared with other callers of dbus_connection_open().
2609 * If the open fails, the function returns #NULL, and provides a
2610 * reason for the failure in the error parameter. Pass #NULL for the
2611 * error parameter if you aren't interested in the reason for
2614 * Because this connection is shared, no user of the connection
2615 * may call dbus_connection_close(). However, when you are done with the
2616 * connection you should call dbus_connection_unref().
2618 * @note Prefer dbus_connection_open() to dbus_connection_open_private()
2619 * unless you have good reason; connections are expensive enough
2620 * that it's wasteful to create lots of connections to the same
2623 * @param address the address.
2624 * @param error address where an error can be returned.
2625 * @returns new connection, or #NULL on failure.
2628 dbus_connection_open (const char *address,
2631 DBusConnection *connection;
2633 _dbus_return_val_if_fail (address != NULL, NULL);
2634 _dbus_return_val_if_error_is_set (error, NULL);
2636 connection = _dbus_connection_open_internal (address,
2644 * Opens a new, dedicated connection to a remote address. Unlike
2645 * dbus_connection_open(), always creates a new connection.
2646 * This connection will not be saved or recycled by libdbus.
2648 * If the open fails, the function returns #NULL, and provides a
2649 * reason for the failure in the error parameter. Pass #NULL for the
2650 * error parameter if you aren't interested in the reason for
2653 * When you are done with this connection, you must
2654 * dbus_connection_close() to disconnect it,
2655 * and dbus_connection_unref() to free the connection object.
2657 * (The dbus_connection_close() can be skipped if the
2658 * connection is already known to be disconnected, for example
2659 * if you are inside a handler for the Disconnected signal.)
2661 * @note Prefer dbus_connection_open() to dbus_connection_open_private()
2662 * unless you have good reason; connections are expensive enough
2663 * that it's wasteful to create lots of connections to the same
2666 * @param address the address.
2667 * @param error address where an error can be returned.
2668 * @returns new connection, or #NULL on failure.
2671 dbus_connection_open_private (const char *address,
2674 DBusConnection *connection;
2676 _dbus_return_val_if_fail (address != NULL, NULL);
2677 _dbus_return_val_if_error_is_set (error, NULL);
2679 connection = _dbus_connection_open_internal (address,
2687 * Increments the reference count of a DBusConnection.
2689 * @param connection the connection.
2690 * @returns the connection.
2693 dbus_connection_ref (DBusConnection *connection)
2695 dbus_int32_t old_refcount;
2697 _dbus_return_val_if_fail (connection != NULL, NULL);
2698 _dbus_return_val_if_fail (connection->generation == _dbus_current_generation, NULL);
2699 old_refcount = _dbus_atomic_inc (&connection->refcount);
2700 _dbus_connection_trace_ref (connection, old_refcount, old_refcount + 1,
2707 free_outgoing_message (void *element,
2710 DBusMessage *message = element;
2711 DBusConnection *connection = data;
2713 _dbus_message_remove_counter (message, connection->outgoing_counter);
2714 dbus_message_unref (message);
2717 #ifdef ENABLE_KDBUS_TRANSPORT
2719 _dbus_connection_last_unref_internal (DBusConnection *connection, dbus_bool_t unref_transport)
2722 _dbus_connection_last_unref (DBusConnection *connection)
2727 _dbus_verbose ("Finalizing connection %p\n", connection);
2729 _dbus_assert (_dbus_atomic_get (&connection->refcount) == 0);
2731 /* You have to disconnect the connection before unref:ing it. Otherwise
2732 * you won't get the disconnected message.
2734 #ifdef ENABLE_KDBUS_TRANSPORT
2737 _dbus_assert (!_dbus_transport_get_is_connected (connection->transport));
2738 _dbus_assert (connection->server_guid == NULL);
2740 /* ---- We're going to call various application callbacks here, hope it doesn't break anything... */
2741 _dbus_object_tree_free_all_unlocked (connection->objects);
2743 dbus_connection_set_dispatch_status_function (connection, NULL, NULL, NULL);
2744 dbus_connection_set_wakeup_main_function (connection, NULL, NULL, NULL);
2745 dbus_connection_set_unix_user_function (connection, NULL, NULL, NULL);
2746 dbus_connection_set_windows_user_function (connection, NULL, NULL, NULL);
2748 _dbus_watch_list_free (connection->watches);
2749 connection->watches = NULL;
2751 _dbus_timeout_list_free (connection->timeouts);
2752 connection->timeouts = NULL;
2754 _dbus_data_slot_list_free (&connection->slot_list);
2756 link = _dbus_list_get_first_link (&connection->filter_list);
2757 while (link != NULL)
2759 DBusMessageFilter *filter = link->data;
2760 DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
2762 filter->function = NULL;
2763 _dbus_message_filter_unref (filter); /* calls app callback */
2768 _dbus_list_clear (&connection->filter_list);
2770 /* ---- Done with stuff that invokes application callbacks */
2772 _dbus_object_tree_unref (connection->objects);
2774 _dbus_hash_table_unref (connection->pending_replies);
2775 connection->pending_replies = NULL;
2777 _dbus_list_clear (&connection->filter_list);
2779 _dbus_list_foreach (&connection->outgoing_messages,
2780 free_outgoing_message,
2782 _dbus_list_clear (&connection->outgoing_messages);
2784 _dbus_list_foreach (&connection->incoming_messages,
2785 (DBusForeachFunction) dbus_message_unref,
2787 _dbus_list_clear (&connection->incoming_messages);
2789 _dbus_counter_unref (connection->outgoing_counter);
2791 #ifdef ENABLE_KDBUS_TRANSPORT
2794 _dbus_transport_unref (connection->transport);
2796 if (connection->disconnect_message_link)
2798 DBusMessage *message = connection->disconnect_message_link->data;
2799 dbus_message_unref (message);
2800 _dbus_list_free_link (connection->disconnect_message_link);
2803 _dbus_condvar_free_at_location (&connection->dispatch_cond);
2804 _dbus_condvar_free_at_location (&connection->io_path_cond);
2806 _dbus_cmutex_free_at_location (&connection->io_path_mutex);
2807 _dbus_cmutex_free_at_location (&connection->dispatch_mutex);
2809 _dbus_rmutex_free_at_location (&connection->slot_mutex);
2811 _dbus_rmutex_free_at_location (&connection->mutex);
2813 dbus_free (connection);
2816 #ifdef ENABLE_KDBUS_TRANSPORT
2817 /* This is run without the mutex held, but after the last reference
2818 * to the connection has been dropped we should have no thread-related
2822 _dbus_connection_last_unref (DBusConnection *connection)
2824 _dbus_connection_last_unref_internal(connection, TRUE);
2829 * Decrements the reference count of a DBusConnection, and finalizes
2830 * it if the count reaches zero.
2832 * Note: it is a bug to drop the last reference to a connection that
2833 * is still connected.
2835 * For shared connections, libdbus will own a reference
2836 * as long as the connection is connected, so you can know that either
2837 * you don't have the last reference, or it's OK to drop the last reference.
2838 * Most connections are shared. dbus_connection_open() and dbus_bus_get()
2839 * return shared connections.
2841 * For private connections, the creator of the connection must arrange for
2842 * dbus_connection_close() to be called prior to dropping the last reference.
2843 * Private connections come from dbus_connection_open_private() or dbus_bus_get_private().
2845 * @param connection the connection.
2848 dbus_connection_unref (DBusConnection *connection)
2850 dbus_int32_t old_refcount;
2852 _dbus_return_if_fail (connection != NULL);
2853 _dbus_return_if_fail (connection->generation == _dbus_current_generation);
2855 old_refcount = _dbus_atomic_dec (&connection->refcount);
2857 _dbus_connection_trace_ref (connection, old_refcount, old_refcount - 1,
2860 if (old_refcount == 1)
2862 #ifndef DBUS_DISABLE_CHECKS
2863 if (_dbus_transport_get_is_connected (connection->transport))
2865 _dbus_warn_check_failed ("The last reference on a connection was dropped without closing the connection. This is a bug in an application. See dbus_connection_unref() documentation for details.\n%s",
2866 connection->shareable ?
2867 "Most likely, the application called unref() too many times and removed a reference belonging to libdbus, since this is a shared connection.\n" :
2868 "Most likely, the application was supposed to call dbus_connection_close(), since this is a private connection.\n");
2872 _dbus_connection_last_unref (connection);
2876 #ifdef ENABLE_KDBUS_TRANSPORT
2878 dbus_connection_unref_phantom (DBusConnection *connection)
2880 dbus_int32_t old_refcount;
2882 _dbus_return_if_fail (connection != NULL);
2883 _dbus_return_if_fail (connection->generation == _dbus_current_generation);
2885 old_refcount = _dbus_atomic_dec (&connection->refcount);
2887 _dbus_connection_trace_ref (connection, old_refcount, old_refcount - 1, "unref");
2889 if (old_refcount == 1)
2890 _dbus_connection_last_unref_internal(connection, FALSE);
2895 * Note that the transport can disconnect itself (other end drops us)
2896 * and in that case this function never runs. So this function must
2897 * not do anything more than disconnect the transport and update the
2900 * If the transport self-disconnects, then we assume someone will
2901 * dispatch the connection to cause the dispatch status update.
2904 _dbus_connection_close_possibly_shared_and_unlock (DBusConnection *connection)
2906 DBusDispatchStatus status;
2908 HAVE_LOCK_CHECK (connection);
2910 _dbus_verbose ("Disconnecting %p\n", connection);
2912 /* We need to ref because update_dispatch_status_and_unlock will unref
2913 * the connection if it was shared and libdbus was the only remaining
2916 _dbus_connection_ref_unlocked (connection);
2918 _dbus_transport_disconnect (connection->transport);
2920 /* This has the side effect of queuing the disconnect message link
2921 * (unless we don't have enough memory, possibly, so don't assert it).
2922 * After the disconnect message link is queued, dbus_bus_get/dbus_connection_open
2923 * should never again return the newly-disconnected connection.
2925 * However, we only unref the shared connection and exit_on_disconnect when
2926 * the disconnect message reaches the head of the message queue,
2927 * NOT when it's first queued.
2929 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2931 /* This calls out to user code */
2932 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2934 /* Could also call out to user code */
2935 dbus_connection_unref (connection);
2939 * Closes a private connection, so no further data can be sent or received.
2940 * This disconnects the transport (such as a socket) underlying the
2943 * Attempts to send messages after closing a connection are safe, but will result in
2944 * error replies generated locally in libdbus.
2946 * This function does not affect the connection's reference count. It's
2947 * safe to close a connection more than once; all calls after the
2948 * first do nothing. It's impossible to "reopen" a connection, a
2949 * new connection must be created. This function may result in a call
2950 * to the DBusDispatchStatusFunction set with
2951 * dbus_connection_set_dispatch_status_function(), as the disconnect
2952 * message it generates needs to be dispatched.
2954 * If a connection is dropped by the remote application, it will
2957 * You must close a connection prior to releasing the last reference to
2958 * the connection. If you dbus_connection_unref() for the last time
2959 * without closing the connection, the results are undefined; it
2960 * is a bug in your program and libdbus will try to print a warning.
2962 * You may not close a shared connection. Connections created with
2963 * dbus_connection_open() or dbus_bus_get() are shared.
2964 * These connections are owned by libdbus, and applications should
2965 * only unref them, never close them. Applications can know it is
2966 * safe to unref these connections because libdbus will be holding a
2967 * reference as long as the connection is open. Thus, either the
2968 * connection is closed and it is OK to drop the last reference,
2969 * or the connection is open and the app knows it does not have the
2972 * Connections created with dbus_connection_open_private() or
2973 * dbus_bus_get_private() are not kept track of or referenced by
2974 * libdbus. The creator of these connections is responsible for
2975 * calling dbus_connection_close() prior to releasing the last
2976 * reference, if the connection is not already disconnected.
2978 * @param connection the private (unshared) connection to close
2981 dbus_connection_close (DBusConnection *connection)
2983 _dbus_return_if_fail (connection != NULL);
2984 _dbus_return_if_fail (connection->generation == _dbus_current_generation);
2986 CONNECTION_LOCK (connection);
2988 #ifndef DBUS_DISABLE_CHECKS
2989 if (connection->shareable)
2991 CONNECTION_UNLOCK (connection);
2993 _dbus_warn_check_failed ("Applications must not close shared connections - see dbus_connection_close() docs. This is a bug in the application.\n");
2998 _dbus_connection_close_possibly_shared_and_unlock (connection);
3002 _dbus_connection_get_is_connected_unlocked (DBusConnection *connection)
3004 HAVE_LOCK_CHECK (connection);
3005 return _dbus_transport_get_is_connected (connection->transport);
3009 * Gets whether the connection is currently open. A connection may
3010 * become disconnected when the remote application closes its end, or
3011 * exits; a connection may also be disconnected with
3012 * dbus_connection_close().
3014 * There are not separate states for "closed" and "disconnected," the two
3015 * terms are synonymous. This function should really be called
3016 * get_is_open() but for historical reasons is not.
3018 * @param connection the connection.
3019 * @returns #TRUE if the connection is still alive.
3022 dbus_connection_get_is_connected (DBusConnection *connection)
3026 _dbus_return_val_if_fail (connection != NULL, FALSE);
3028 CONNECTION_LOCK (connection);
3029 res = _dbus_connection_get_is_connected_unlocked (connection);
3030 CONNECTION_UNLOCK (connection);
3036 * Gets whether the connection was authenticated. (Note that
3037 * if the connection was authenticated then disconnected,
3038 * this function still returns #TRUE)
3040 * @param connection the connection
3041 * @returns #TRUE if the connection was ever authenticated
3044 dbus_connection_get_is_authenticated (DBusConnection *connection)
3048 _dbus_return_val_if_fail (connection != NULL, FALSE);
3050 CONNECTION_LOCK (connection);
3051 res = _dbus_transport_try_to_authenticate (connection->transport);
3052 CONNECTION_UNLOCK (connection);
3057 #ifdef ENABLE_KDBUS_TRANSPORT
3059 * Sets authenticated status for connection. Needed for kdbus, where authentication is
3060 * made in different manner.
3061 * LOCK commented out because called with lock already set
3062 * @param connection the connection
3065 dbus_connection_set_is_authenticated (DBusConnection *connection)
3067 _dbus_return_val_if_fail (connection != NULL, FALSE);
3069 // CONNECTION_LOCK (connection);
3070 connection->transport->authenticated = TRUE;
3071 // CONNECTION_UNLOCK (connection);
3078 * Gets whether the connection is not authenticated as a specific
3079 * user. If the connection is not authenticated, this function
3080 * returns #TRUE, and if it is authenticated but as an anonymous user,
3081 * it returns #TRUE. If it is authenticated as a specific user, then
3082 * this returns #FALSE. (Note that if the connection was authenticated
3083 * as anonymous then disconnected, this function still returns #TRUE.)
3085 * If the connection is not anonymous, you can use
3086 * dbus_connection_get_unix_user() and
3087 * dbus_connection_get_windows_user() to see who it's authorized as.
3089 * If you want to prevent non-anonymous authorization, use
3090 * dbus_server_set_auth_mechanisms() to remove the mechanisms that
3091 * allow proving user identity (i.e. only allow the ANONYMOUS
3094 * @param connection the connection
3095 * @returns #TRUE if not authenticated or authenticated as anonymous
3098 dbus_connection_get_is_anonymous (DBusConnection *connection)
3102 _dbus_return_val_if_fail (connection != NULL, FALSE);
3104 CONNECTION_LOCK (connection);
3105 res = _dbus_transport_get_is_anonymous (connection->transport);
3106 CONNECTION_UNLOCK (connection);
3112 * Gets the ID of the server address we are authenticated to, if this
3113 * connection is on the client side. If the connection is on the
3114 * server side, this will always return #NULL - use dbus_server_get_id()
3115 * to get the ID of your own server, if you are the server side.
3117 * If a client-side connection is not authenticated yet, the ID may be
3118 * available if it was included in the server address, but may not be
3119 * available. The only way to be sure the server ID is available
3120 * is to wait for authentication to complete.
3122 * In general, each mode of connecting to a given server will have
3123 * its own ID. So for example, if the session bus daemon is listening
3124 * on UNIX domain sockets and on TCP, then each of those modalities
3125 * will have its own server ID.
3127 * If you want an ID that identifies an entire session bus, look at
3128 * dbus_bus_get_id() instead (which is just a convenience wrapper
3129 * around the org.freedesktop.DBus.GetId method invoked on the bus).
3131 * You can also get a machine ID; see dbus_get_local_machine_id() to
3132 * get the machine you are on. There isn't a convenience wrapper, but
3133 * you can invoke org.freedesktop.DBus.Peer.GetMachineId on any peer
3134 * to get the machine ID on the other end.
3136 * The D-Bus specification describes the server ID and other IDs in a
3139 * @param connection the connection
3140 * @returns the server ID or #NULL if no memory or the connection is server-side
3143 dbus_connection_get_server_id (DBusConnection *connection)
3147 _dbus_return_val_if_fail (connection != NULL, NULL);
3149 CONNECTION_LOCK (connection);
3150 id = _dbus_strdup (_dbus_transport_get_server_id (connection->transport));
3151 CONNECTION_UNLOCK (connection);
3157 * Tests whether a certain type can be send via the connection. This
3158 * will always return TRUE for all types, with the exception of
3159 * DBUS_TYPE_UNIX_FD. The function will return TRUE for
3160 * DBUS_TYPE_UNIX_FD only on systems that know Unix file descriptors
3161 * and can send them via the chosen transport and when the remote side
3164 * This function can be used to do runtime checking for types that
3165 * might be unknown to the specific D-Bus client implementation
3166 * version, i.e. it will return FALSE for all types this
3167 * implementation does not know, including invalid or reserved types.
3169 * @param connection the connection
3170 * @param type the type to check
3171 * @returns TRUE if the type may be send via the connection
3174 dbus_connection_can_send_type(DBusConnection *connection,
3177 _dbus_return_val_if_fail (connection != NULL, FALSE);
3179 if (!dbus_type_is_valid (type))
3182 if (type != DBUS_TYPE_UNIX_FD)
3185 #ifdef HAVE_UNIX_FD_PASSING
3189 CONNECTION_LOCK(connection);
3190 b = _dbus_transport_can_pass_unix_fd(connection->transport);
3191 CONNECTION_UNLOCK(connection);
3201 * Set whether _exit() should be called when the connection receives a
3202 * disconnect signal. The call to _exit() comes after any handlers for
3203 * the disconnect signal run; handlers can cancel the exit by calling
3206 * By default, exit_on_disconnect is #FALSE; but for message bus
3207 * connections returned from dbus_bus_get() it will be toggled on
3210 * @param connection the connection
3211 * @param exit_on_disconnect #TRUE if _exit() should be called after a disconnect signal
3214 dbus_connection_set_exit_on_disconnect (DBusConnection *connection,
3215 dbus_bool_t exit_on_disconnect)
3217 _dbus_return_if_fail (connection != NULL);
3219 CONNECTION_LOCK (connection);
3220 connection->exit_on_disconnect = exit_on_disconnect != FALSE;
3221 CONNECTION_UNLOCK (connection);
3225 * Preallocates resources needed to send a message, allowing the message
3226 * to be sent without the possibility of memory allocation failure.
3227 * Allows apps to create a future guarantee that they can send
3228 * a message regardless of memory shortages.
3230 * @param connection the connection we're preallocating for.
3231 * @returns the preallocated resources, or #NULL
3233 DBusPreallocatedSend*
3234 dbus_connection_preallocate_send (DBusConnection *connection)
3236 DBusPreallocatedSend *preallocated;
3238 _dbus_return_val_if_fail (connection != NULL, NULL);
3240 CONNECTION_LOCK (connection);
3243 _dbus_connection_preallocate_send_unlocked (connection);
3245 CONNECTION_UNLOCK (connection);
3247 return preallocated;
3251 * Frees preallocated message-sending resources from
3252 * dbus_connection_preallocate_send(). Should only
3253 * be called if the preallocated resources are not used
3254 * to send a message.
3256 * @param connection the connection
3257 * @param preallocated the resources
3260 dbus_connection_free_preallocated_send (DBusConnection *connection,
3261 DBusPreallocatedSend *preallocated)
3263 _dbus_return_if_fail (connection != NULL);
3264 _dbus_return_if_fail (preallocated != NULL);
3265 _dbus_return_if_fail (connection == preallocated->connection);
3267 _dbus_list_free_link (preallocated->queue_link);
3268 _dbus_counter_unref (preallocated->counter_link->data);
3269 _dbus_list_free_link (preallocated->counter_link);
3270 dbus_free (preallocated);
3274 * Sends a message using preallocated resources. This function cannot fail.
3275 * It works identically to dbus_connection_send() in other respects.
3276 * Preallocated resources comes from dbus_connection_preallocate_send().
3277 * This function "consumes" the preallocated resources, they need not
3278 * be freed separately.
3280 * @param connection the connection
3281 * @param preallocated the preallocated resources
3282 * @param message the message to send
3283 * @param client_serial return location for client serial assigned to the message
3286 dbus_connection_send_preallocated (DBusConnection *connection,
3287 DBusPreallocatedSend *preallocated,
3288 DBusMessage *message,
3289 dbus_uint32_t *client_serial)
3291 _dbus_return_if_fail (connection != NULL);
3292 _dbus_return_if_fail (preallocated != NULL);
3293 _dbus_return_if_fail (message != NULL);
3294 _dbus_return_if_fail (preallocated->connection == connection);
3295 _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_METHOD_CALL ||
3296 dbus_message_get_member (message) != NULL);
3297 _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL ||
3298 (dbus_message_get_interface (message) != NULL &&
3299 dbus_message_get_member (message) != NULL));
3301 CONNECTION_LOCK (connection);
3303 #ifdef HAVE_UNIX_FD_PASSING
3305 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3306 message->n_unix_fds > 0)
3308 /* Refuse to send fds on a connection that cannot handle
3309 them. Unfortunately we cannot return a proper error here, so
3310 the best we can is just return. */
3311 CONNECTION_UNLOCK (connection);
3317 _dbus_connection_send_preallocated_and_unlock (connection,
3319 message, client_serial);
3323 _dbus_connection_send_unlocked_no_update (DBusConnection *connection,
3324 DBusMessage *message,
3325 dbus_uint32_t *client_serial)
3327 DBusPreallocatedSend *preallocated;
3329 _dbus_assert (connection != NULL);
3330 _dbus_assert (message != NULL);
3332 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
3333 if (preallocated == NULL)
3336 _dbus_connection_send_preallocated_unlocked_no_update (connection,
3344 * Adds a message to the outgoing message queue. Does not block to
3345 * write the message to the network; that happens asynchronously. To
3346 * force the message to be written, call dbus_connection_flush() however
3347 * it is not necessary to call dbus_connection_flush() by hand; the
3348 * message will be sent the next time the main loop is run.
3349 * dbus_connection_flush() should only be used, for example, if
3350 * the application was expected to exit before running the main loop.
3352 * Because this only queues the message, the only reason it can
3353 * fail is lack of memory. Even if the connection is disconnected,
3354 * no error will be returned. If the function fails due to lack of memory,
3355 * it returns #FALSE. The function will never fail for other reasons; even
3356 * if the connection is disconnected, you can queue an outgoing message,
3357 * though obviously it won't be sent.
3359 * The message serial is used by the remote application to send a
3360 * reply; see dbus_message_get_serial() or the D-Bus specification.
3362 * dbus_message_unref() can be called as soon as this method returns
3363 * as the message queue will hold its own ref until the message is sent.
3365 * @param connection the connection.
3366 * @param message the message to write.
3367 * @param serial return location for message serial, or #NULL if you don't care
3368 * @returns #TRUE on success.
3371 dbus_connection_send (DBusConnection *connection,
3372 DBusMessage *message,
3373 dbus_uint32_t *serial)
3375 _dbus_return_val_if_fail (connection != NULL, FALSE);
3376 _dbus_return_val_if_fail (message != NULL, FALSE);
3378 CONNECTION_LOCK (connection);
3380 #ifdef HAVE_UNIX_FD_PASSING
3382 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3383 message->n_unix_fds > 0)
3385 /* Refuse to send fds on a connection that cannot handle
3386 them. Unfortunately we cannot return a proper error here, so
3387 the best we can is just return. */
3388 CONNECTION_UNLOCK (connection);
3394 return _dbus_connection_send_and_unlock (connection,
3400 reply_handler_timeout (void *data)
3402 DBusConnection *connection;
3403 DBusDispatchStatus status;
3404 DBusPendingCall *pending = data;
3406 connection = _dbus_pending_call_get_connection_and_lock (pending);
3407 _dbus_connection_ref_unlocked (connection);
3409 _dbus_pending_call_queue_timeout_error_unlocked (pending,
3411 _dbus_connection_remove_timeout_unlocked (connection,
3412 _dbus_pending_call_get_timeout_unlocked (pending));
3413 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
3415 _dbus_verbose ("middle\n");
3416 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3418 /* Unlocks, and calls out to user code */
3419 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3420 dbus_connection_unref (connection);
3426 * Queues a message to send, as with dbus_connection_send(),
3427 * but also returns a #DBusPendingCall used to receive a reply to the
3428 * message. If no reply is received in the given timeout_milliseconds,
3429 * this function expires the pending reply and generates a synthetic
3430 * error reply (generated in-process, not by the remote application)
3431 * indicating that a timeout occurred.
3433 * A #DBusPendingCall will see a reply message before any filters or
3434 * registered object path handlers. See dbus_connection_dispatch() for
3435 * details on when handlers are run.
3437 * A #DBusPendingCall will always see exactly one reply message,
3438 * unless it's cancelled with dbus_pending_call_cancel().
3440 * If #NULL is passed for the pending_return, the #DBusPendingCall
3441 * will still be generated internally, and used to track
3442 * the message reply timeout. This means a timeout error will
3443 * occur if no reply arrives, unlike with dbus_connection_send().
3445 * If -1 is passed for the timeout, a sane default timeout is used. -1
3446 * is typically the best value for the timeout for this reason, unless
3447 * you want a very short or very long timeout. If #DBUS_TIMEOUT_INFINITE is
3448 * passed for the timeout, no timeout will be set and the call will block
3451 * @warning if the connection is disconnected or you try to send Unix
3452 * file descriptors on a connection that does not support them, the
3453 * #DBusPendingCall will be set to #NULL, so be careful with this.
3455 * @param connection the connection
3456 * @param message the message to send
3457 * @param pending_return return location for a #DBusPendingCall
3458 * object, or #NULL if connection is disconnected or when you try to
3459 * send Unix file descriptors on a connection that does not support
3461 * @param timeout_milliseconds timeout in milliseconds, -1 (or
3462 * #DBUS_TIMEOUT_USE_DEFAULT) for default or #DBUS_TIMEOUT_INFINITE for no
3464 * @returns #FALSE if no memory, #TRUE otherwise.
3468 dbus_connection_send_with_reply (DBusConnection *connection,
3469 DBusMessage *message,
3470 DBusPendingCall **pending_return,
3471 int timeout_milliseconds)
3473 DBusPendingCall *pending;
3474 dbus_int32_t serial = -1;
3475 DBusDispatchStatus status;
3477 _dbus_return_val_if_fail (connection != NULL, FALSE);
3478 _dbus_return_val_if_fail (message != NULL, FALSE);
3479 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3482 *pending_return = NULL;
3484 CONNECTION_LOCK (connection);
3486 #ifdef HAVE_UNIX_FD_PASSING
3488 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3489 message->n_unix_fds > 0)
3491 /* Refuse to send fds on a connection that cannot handle
3492 them. Unfortunately we cannot return a proper error here, so
3493 the best we can do is return TRUE but leave *pending_return
3495 CONNECTION_UNLOCK (connection);
3501 if (!_dbus_connection_get_is_connected_unlocked (connection))
3503 CONNECTION_UNLOCK (connection);
3508 pending = _dbus_pending_call_new_unlocked (connection,
3509 timeout_milliseconds,
3510 reply_handler_timeout);
3512 if (pending == NULL)
3514 CONNECTION_UNLOCK (connection);
3518 /* Assign a serial to the message */
3519 serial = dbus_message_get_serial (message);
3522 serial = _dbus_connection_get_next_client_serial (connection);
3523 dbus_message_set_serial (message, serial);
3526 if (!_dbus_pending_call_set_timeout_error_unlocked (pending, message, serial))
3529 /* Insert the serial in the pending replies hash;
3530 * hash takes a refcount on DBusPendingCall.
3531 * Also, add the timeout.
3533 if (!_dbus_connection_attach_pending_call_unlocked (connection,
3537 if (!_dbus_connection_send_unlocked_no_update (connection, message, NULL))
3539 _dbus_connection_detach_pending_call_and_unlock (connection,
3541 goto error_unlocked;
3545 *pending_return = pending; /* hand off refcount */
3548 _dbus_connection_detach_pending_call_unlocked (connection, pending);
3549 /* we still have a ref to the pending call in this case, we unref
3550 * after unlocking, below
3554 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3556 /* this calls out to user code */
3557 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3559 if (pending_return == NULL)
3560 dbus_pending_call_unref (pending);
3565 CONNECTION_UNLOCK (connection);
3567 dbus_pending_call_unref (pending);
3572 * Sends a message and blocks a certain time period while waiting for
3573 * a reply. This function does not reenter the main loop,
3574 * i.e. messages other than the reply are queued up but not
3575 * processed. This function is used to invoke method calls on a
3578 * If a normal reply is received, it is returned, and removed from the
3579 * incoming message queue. If it is not received, #NULL is returned
3580 * and the error is set to #DBUS_ERROR_NO_REPLY. If an error reply is
3581 * received, it is converted to a #DBusError and returned as an error,
3582 * then the reply message is deleted and #NULL is returned. If
3583 * something else goes wrong, result is set to whatever is
3584 * appropriate, such as #DBUS_ERROR_NO_MEMORY or
3585 * #DBUS_ERROR_DISCONNECTED.
3587 * @warning While this function blocks the calling thread will not be
3588 * processing the incoming message queue. This means you can end up
3589 * deadlocked if the application you're talking to needs you to reply
3590 * to a method. To solve this, either avoid the situation, block in a
3591 * separate thread from the main connection-dispatching thread, or use
3592 * dbus_pending_call_set_notify() to avoid blocking.
3594 * @param connection the connection
3595 * @param message the message to send
3596 * @param timeout_milliseconds timeout in milliseconds, -1 (or
3597 * #DBUS_TIMEOUT_USE_DEFAULT) for default or #DBUS_TIMEOUT_INFINITE for no
3599 * @param error return location for error message
3600 * @returns the message that is the reply or #NULL with an error code if the
3604 dbus_connection_send_with_reply_and_block (DBusConnection *connection,
3605 DBusMessage *message,
3606 int timeout_milliseconds,
3610 DBusPendingCall *pending;
3612 _dbus_return_val_if_fail (connection != NULL, NULL);
3613 _dbus_return_val_if_fail (message != NULL, NULL);
3614 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, NULL);
3615 _dbus_return_val_if_error_is_set (error, NULL);
3617 #ifdef HAVE_UNIX_FD_PASSING
3619 CONNECTION_LOCK (connection);
3620 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3621 message->n_unix_fds > 0)
3623 CONNECTION_UNLOCK (connection);
3624 dbus_set_error(error, DBUS_ERROR_FAILED, "Cannot send file descriptors on this connection.");
3627 CONNECTION_UNLOCK (connection);
3631 if (!dbus_connection_send_with_reply (connection, message,
3632 &pending, timeout_milliseconds))
3634 _DBUS_SET_OOM (error);
3638 if (pending == NULL)
3640 dbus_set_error (error, DBUS_ERROR_DISCONNECTED, "Connection is closed");
3644 dbus_pending_call_block (pending);
3646 reply = dbus_pending_call_steal_reply (pending);
3647 dbus_pending_call_unref (pending);
3649 /* call_complete_and_unlock() called from pending_call_block() should
3650 * always fill this in.
3652 _dbus_assert (reply != NULL);
3654 if (dbus_set_error_from_message (error, reply))
3656 dbus_message_unref (reply);
3664 * Blocks until the outgoing message queue is empty.
3665 * Assumes connection lock already held.
3667 * If you call this, you MUST call update_dispatch_status afterword...
3669 * @param connection the connection.
3671 static DBusDispatchStatus
3672 _dbus_connection_flush_unlocked (DBusConnection *connection)
3674 /* We have to specify DBUS_ITERATION_DO_READING here because
3675 * otherwise we could have two apps deadlock if they are both doing
3676 * a flush(), and the kernel buffers fill up. This could change the
3679 DBusDispatchStatus status;
3681 HAVE_LOCK_CHECK (connection);
3683 while (connection->n_outgoing > 0 &&
3684 _dbus_connection_get_is_connected_unlocked (connection))
3686 _dbus_verbose ("doing iteration in\n");
3687 HAVE_LOCK_CHECK (connection);
3688 _dbus_connection_do_iteration_unlocked (connection,
3690 DBUS_ITERATION_DO_READING |
3691 DBUS_ITERATION_DO_WRITING |
3692 DBUS_ITERATION_BLOCK,
3696 HAVE_LOCK_CHECK (connection);
3697 _dbus_verbose ("middle\n");
3698 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3700 HAVE_LOCK_CHECK (connection);
3705 * Blocks until the outgoing message queue is empty.
3707 * @param connection the connection.
3710 dbus_connection_flush (DBusConnection *connection)
3712 /* We have to specify DBUS_ITERATION_DO_READING here because
3713 * otherwise we could have two apps deadlock if they are both doing
3714 * a flush(), and the kernel buffers fill up. This could change the
3717 DBusDispatchStatus status;
3719 _dbus_return_if_fail (connection != NULL);
3721 CONNECTION_LOCK (connection);
3723 status = _dbus_connection_flush_unlocked (connection);
3725 HAVE_LOCK_CHECK (connection);
3726 /* Unlocks and calls out to user code */
3727 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3729 _dbus_verbose ("end\n");
3733 * This function implements dbus_connection_read_write_dispatch() and
3734 * dbus_connection_read_write() (they pass a different value for the
3735 * dispatch parameter).
3737 * @param connection the connection
3738 * @param timeout_milliseconds max time to block or -1 for infinite
3739 * @param dispatch dispatch new messages or leave them on the incoming queue
3740 * @returns #TRUE if the disconnect message has not been processed
3743 _dbus_connection_read_write_dispatch (DBusConnection *connection,
3744 int timeout_milliseconds,
3745 dbus_bool_t dispatch)
3747 DBusDispatchStatus dstatus;
3748 dbus_bool_t progress_possible;
3750 /* Need to grab a ref here in case we're a private connection and
3751 * the user drops the last ref in a handler we call; see bug
3752 * https://bugs.freedesktop.org/show_bug.cgi?id=15635
3754 dbus_connection_ref (connection);
3755 dstatus = dbus_connection_get_dispatch_status (connection);
3757 if (dispatch && dstatus == DBUS_DISPATCH_DATA_REMAINS)
3759 _dbus_verbose ("doing dispatch\n");
3760 dbus_connection_dispatch (connection);
3761 CONNECTION_LOCK (connection);
3763 else if (dstatus == DBUS_DISPATCH_NEED_MEMORY)
3765 _dbus_verbose ("pausing for memory\n");
3766 _dbus_memory_pause_based_on_timeout (timeout_milliseconds);
3767 CONNECTION_LOCK (connection);
3771 CONNECTION_LOCK (connection);
3772 if (_dbus_connection_get_is_connected_unlocked (connection))
3774 _dbus_verbose ("doing iteration\n");
3775 _dbus_connection_do_iteration_unlocked (connection,
3777 DBUS_ITERATION_DO_READING |
3778 DBUS_ITERATION_DO_WRITING |
3779 DBUS_ITERATION_BLOCK,
3780 timeout_milliseconds);
3784 HAVE_LOCK_CHECK (connection);
3785 /* If we can dispatch, we can make progress until the Disconnected message
3786 * has been processed; if we can only read/write, we can make progress
3787 * as long as the transport is open.
3790 progress_possible = connection->n_incoming != 0 ||
3791 connection->disconnect_message_link != NULL;
3793 progress_possible = _dbus_connection_get_is_connected_unlocked (connection);
3795 CONNECTION_UNLOCK (connection);
3797 dbus_connection_unref (connection);
3799 return progress_possible; /* TRUE if we can make more progress */
3804 * This function is intended for use with applications that don't want
3805 * to write a main loop and deal with #DBusWatch and #DBusTimeout. An
3806 * example usage would be:
3809 * while (dbus_connection_read_write_dispatch (connection, -1))
3810 * ; // empty loop body
3813 * In this usage you would normally have set up a filter function to look
3814 * at each message as it is dispatched. The loop terminates when the last
3815 * message from the connection (the disconnected signal) is processed.
3817 * If there are messages to dispatch, this function will
3818 * dbus_connection_dispatch() once, and return. If there are no
3819 * messages to dispatch, this function will block until it can read or
3820 * write, then read or write, then return.
3822 * The way to think of this function is that it either makes some sort
3823 * of progress, or it blocks. Note that, while it is blocked on I/O, it
3824 * cannot be interrupted (even by other threads), which makes this function
3825 * unsuitable for applications that do more than just react to received
3828 * The return value indicates whether the disconnect message has been
3829 * processed, NOT whether the connection is connected. This is
3830 * important because even after disconnecting, you want to process any
3831 * messages you received prior to the disconnect.
3833 * @param connection the connection
3834 * @param timeout_milliseconds max time to block or -1 for infinite
3835 * @returns #TRUE if the disconnect message has not been processed
3838 dbus_connection_read_write_dispatch (DBusConnection *connection,
3839 int timeout_milliseconds)
3841 _dbus_return_val_if_fail (connection != NULL, FALSE);
3842 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3843 return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, TRUE);
3847 * This function is intended for use with applications that don't want to
3848 * write a main loop and deal with #DBusWatch and #DBusTimeout. See also
3849 * dbus_connection_read_write_dispatch().
3851 * As long as the connection is open, this function will block until it can
3852 * read or write, then read or write, then return #TRUE.
3854 * If the connection is closed, the function returns #FALSE.
3856 * The return value indicates whether reading or writing is still
3857 * possible, i.e. whether the connection is connected.
3859 * Note that even after disconnection, messages may remain in the
3860 * incoming queue that need to be
3861 * processed. dbus_connection_read_write_dispatch() dispatches
3862 * incoming messages for you; with dbus_connection_read_write() you
3863 * have to arrange to drain the incoming queue yourself.
3865 * @param connection the connection
3866 * @param timeout_milliseconds max time to block or -1 for infinite
3867 * @returns #TRUE if still connected
3870 dbus_connection_read_write (DBusConnection *connection,
3871 int timeout_milliseconds)
3873 _dbus_return_val_if_fail (connection != NULL, FALSE);
3874 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3875 return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, FALSE);
3878 /* We need to call this anytime we pop the head of the queue, and then
3879 * update_dispatch_status_and_unlock needs to be called afterward
3880 * which will "process" the disconnected message and set
3881 * disconnected_message_processed.
3884 check_disconnected_message_arrived_unlocked (DBusConnection *connection,
3885 DBusMessage *head_of_queue)
3887 HAVE_LOCK_CHECK (connection);
3889 /* checking that the link is NULL is an optimization to avoid the is_signal call */
3890 if (connection->disconnect_message_link == NULL &&
3891 dbus_message_is_signal (head_of_queue,
3892 DBUS_INTERFACE_LOCAL,
3895 connection->disconnected_message_arrived = TRUE;
3900 * Returns the first-received message from the incoming message queue,
3901 * leaving it in the queue. If the queue is empty, returns #NULL.
3903 * The caller does not own a reference to the returned message, and
3904 * must either return it using dbus_connection_return_message() or
3905 * keep it after calling dbus_connection_steal_borrowed_message(). No
3906 * one can get at the message while its borrowed, so return it as
3907 * quickly as possible and don't keep a reference to it after
3908 * returning it. If you need to keep the message, make a copy of it.
3910 * dbus_connection_dispatch() will block if called while a borrowed
3911 * message is outstanding; only one piece of code can be playing with
3912 * the incoming queue at a time. This function will block if called
3913 * during a dbus_connection_dispatch().
3915 * @param connection the connection.
3916 * @returns next message in the incoming queue.
3919 dbus_connection_borrow_message (DBusConnection *connection)
3921 DBusDispatchStatus status;
3922 DBusMessage *message;
3924 _dbus_return_val_if_fail (connection != NULL, NULL);
3926 _dbus_verbose ("start\n");
3928 /* this is called for the side effect that it queues
3929 * up any messages from the transport
3931 status = dbus_connection_get_dispatch_status (connection);
3932 if (status != DBUS_DISPATCH_DATA_REMAINS)
3935 CONNECTION_LOCK (connection);
3937 _dbus_connection_acquire_dispatch (connection);
3939 /* While a message is outstanding, the dispatch lock is held */
3940 _dbus_assert (connection->message_borrowed == NULL);
3942 connection->message_borrowed = _dbus_list_get_first (&connection->incoming_messages);
3944 message = connection->message_borrowed;
3946 check_disconnected_message_arrived_unlocked (connection, message);
3948 /* Note that we KEEP the dispatch lock until the message is returned */
3949 if (message == NULL)
3950 _dbus_connection_release_dispatch (connection);
3952 CONNECTION_UNLOCK (connection);
3954 _dbus_message_trace_ref (message, -1, -1, "dbus_connection_borrow_message");
3956 /* We don't update dispatch status until it's returned or stolen */
3962 * Used to return a message after peeking at it using
3963 * dbus_connection_borrow_message(). Only called if
3964 * message from dbus_connection_borrow_message() was non-#NULL.
3966 * @param connection the connection
3967 * @param message the message from dbus_connection_borrow_message()
3970 dbus_connection_return_message (DBusConnection *connection,
3971 DBusMessage *message)
3973 DBusDispatchStatus status;
3975 _dbus_return_if_fail (connection != NULL);
3976 _dbus_return_if_fail (message != NULL);
3977 _dbus_return_if_fail (message == connection->message_borrowed);
3978 _dbus_return_if_fail (connection->dispatch_acquired);
3980 CONNECTION_LOCK (connection);
3982 _dbus_assert (message == connection->message_borrowed);
3984 connection->message_borrowed = NULL;
3986 _dbus_connection_release_dispatch (connection);
3988 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3989 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3991 _dbus_message_trace_ref (message, -1, -1, "dbus_connection_return_message");
3995 * Used to keep a message after peeking at it using
3996 * dbus_connection_borrow_message(). Before using this function, see
3997 * the caveats/warnings in the documentation for
3998 * dbus_connection_pop_message().
4000 * @param connection the connection
4001 * @param message the message from dbus_connection_borrow_message()
4004 dbus_connection_steal_borrowed_message (DBusConnection *connection,
4005 DBusMessage *message)
4007 DBusMessage *pop_message;
4008 DBusDispatchStatus status;
4010 _dbus_return_if_fail (connection != NULL);
4011 _dbus_return_if_fail (message != NULL);
4012 _dbus_return_if_fail (message == connection->message_borrowed);
4013 _dbus_return_if_fail (connection->dispatch_acquired);
4015 CONNECTION_LOCK (connection);
4017 _dbus_assert (message == connection->message_borrowed);
4019 pop_message = _dbus_list_pop_first (&connection->incoming_messages);
4020 _dbus_assert (message == pop_message);
4021 (void) pop_message; /* unused unless asserting */
4023 connection->n_incoming -= 1;
4025 _dbus_verbose ("Incoming message %p stolen from queue, %d incoming\n",
4026 message, connection->n_incoming);
4028 connection->message_borrowed = NULL;
4030 _dbus_connection_release_dispatch (connection);
4032 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4033 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4034 _dbus_message_trace_ref (message, -1, -1,
4035 "dbus_connection_steal_borrowed_message");
4038 /* See dbus_connection_pop_message, but requires the caller to own
4039 * the lock before calling. May drop the lock while running.
4042 _dbus_connection_pop_message_link_unlocked (DBusConnection *connection)
4044 HAVE_LOCK_CHECK (connection);
4046 _dbus_assert (connection->message_borrowed == NULL);
4048 if (connection->n_incoming > 0)
4052 link = _dbus_list_pop_first_link (&connection->incoming_messages);
4053 connection->n_incoming -= 1;
4055 _dbus_verbose ("Message %p (%s %s %s %s sig:'%s' serial:%u) removed from incoming queue %p, %d incoming\n",
4057 dbus_message_type_to_string (dbus_message_get_type (link->data)),
4058 dbus_message_get_path (link->data) ?
4059 dbus_message_get_path (link->data) :
4061 dbus_message_get_interface (link->data) ?
4062 dbus_message_get_interface (link->data) :
4064 dbus_message_get_member (link->data) ?
4065 dbus_message_get_member (link->data) :
4067 dbus_message_get_signature (link->data),
4068 dbus_message_get_serial (link->data),
4069 connection, connection->n_incoming);
4071 _dbus_message_trace_ref (link->data, -1, -1,
4072 "_dbus_connection_pop_message_link_unlocked");
4074 check_disconnected_message_arrived_unlocked (connection, link->data);
4082 /* See dbus_connection_pop_message, but requires the caller to own
4083 * the lock before calling. May drop the lock while running.
4086 _dbus_connection_pop_message_unlocked (DBusConnection *connection)
4090 HAVE_LOCK_CHECK (connection);
4092 link = _dbus_connection_pop_message_link_unlocked (connection);
4096 DBusMessage *message;
4098 message = link->data;
4100 _dbus_list_free_link (link);
4109 _dbus_connection_putback_message_link_unlocked (DBusConnection *connection,
4110 DBusList *message_link)
4112 HAVE_LOCK_CHECK (connection);
4114 _dbus_assert (message_link != NULL);
4115 /* You can't borrow a message while a link is outstanding */
4116 _dbus_assert (connection->message_borrowed == NULL);
4117 /* We had to have the dispatch lock across the pop/putback */
4118 _dbus_assert (connection->dispatch_acquired);
4120 _dbus_list_prepend_link (&connection->incoming_messages,
4122 connection->n_incoming += 1;
4124 _dbus_verbose ("Message %p (%s %s %s '%s') put back into queue %p, %d incoming\n",
4126 dbus_message_type_to_string (dbus_message_get_type (message_link->data)),
4127 dbus_message_get_interface (message_link->data) ?
4128 dbus_message_get_interface (message_link->data) :
4130 dbus_message_get_member (message_link->data) ?
4131 dbus_message_get_member (message_link->data) :
4133 dbus_message_get_signature (message_link->data),
4134 connection, connection->n_incoming);
4136 _dbus_message_trace_ref (message_link->data, -1, -1,
4137 "_dbus_connection_putback_message_link_unlocked");
4141 * Returns the first-received message from the incoming message queue,
4142 * removing it from the queue. The caller owns a reference to the
4143 * returned message. If the queue is empty, returns #NULL.
4145 * This function bypasses any message handlers that are registered,
4146 * and so using it is usually wrong. Instead, let the main loop invoke
4147 * dbus_connection_dispatch(). Popping messages manually is only
4148 * useful in very simple programs that don't share a #DBusConnection
4149 * with any libraries or other modules.
4151 * There is a lock that covers all ways of accessing the incoming message
4152 * queue, so dbus_connection_dispatch(), dbus_connection_pop_message(),
4153 * dbus_connection_borrow_message(), etc. will all block while one of the others
4154 * in the group is running.
4156 * @param connection the connection.
4157 * @returns next message in the incoming queue.
4160 dbus_connection_pop_message (DBusConnection *connection)
4162 DBusMessage *message;
4163 DBusDispatchStatus status;
4165 _dbus_verbose ("start\n");
4167 /* this is called for the side effect that it queues
4168 * up any messages from the transport
4170 status = dbus_connection_get_dispatch_status (connection);
4171 if (status != DBUS_DISPATCH_DATA_REMAINS)
4174 CONNECTION_LOCK (connection);
4175 _dbus_connection_acquire_dispatch (connection);
4176 HAVE_LOCK_CHECK (connection);
4178 message = _dbus_connection_pop_message_unlocked (connection);
4180 _dbus_verbose ("Returning popped message %p\n", message);
4182 _dbus_connection_release_dispatch (connection);
4184 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4185 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4191 * Acquire the dispatcher. This is a separate lock so the main
4192 * connection lock can be dropped to call out to application dispatch
4195 * @param connection the connection.
4198 _dbus_connection_acquire_dispatch (DBusConnection *connection)
4200 HAVE_LOCK_CHECK (connection);
4202 _dbus_connection_ref_unlocked (connection);
4203 CONNECTION_UNLOCK (connection);
4205 _dbus_verbose ("locking dispatch_mutex\n");
4206 _dbus_cmutex_lock (connection->dispatch_mutex);
4208 while (connection->dispatch_acquired)
4210 _dbus_verbose ("waiting for dispatch to be acquirable\n");
4211 _dbus_condvar_wait (connection->dispatch_cond,
4212 connection->dispatch_mutex);
4215 _dbus_assert (!connection->dispatch_acquired);
4217 connection->dispatch_acquired = TRUE;
4219 _dbus_verbose ("unlocking dispatch_mutex\n");
4220 _dbus_cmutex_unlock (connection->dispatch_mutex);
4222 CONNECTION_LOCK (connection);
4223 _dbus_connection_unref_unlocked (connection);
4227 * Release the dispatcher when you're done with it. Only call
4228 * after you've acquired the dispatcher. Wakes up at most one
4229 * thread currently waiting to acquire the dispatcher.
4231 * @param connection the connection.
4234 _dbus_connection_release_dispatch (DBusConnection *connection)
4236 HAVE_LOCK_CHECK (connection);
4238 _dbus_verbose ("locking dispatch_mutex\n");
4239 _dbus_cmutex_lock (connection->dispatch_mutex);
4241 _dbus_assert (connection->dispatch_acquired);
4243 connection->dispatch_acquired = FALSE;
4244 _dbus_condvar_wake_one (connection->dispatch_cond);
4246 _dbus_verbose ("unlocking dispatch_mutex\n");
4247 _dbus_cmutex_unlock (connection->dispatch_mutex);
4251 _dbus_connection_failed_pop (DBusConnection *connection,
4252 DBusList *message_link)
4254 _dbus_list_prepend_link (&connection->incoming_messages,
4256 connection->n_incoming += 1;
4259 /* Note this may be called multiple times since we don't track whether we already did it */
4261 notify_disconnected_unlocked (DBusConnection *connection)
4263 HAVE_LOCK_CHECK (connection);
4265 /* Set the weakref in dbus-bus.c to NULL, so nobody will get a disconnected
4266 * connection from dbus_bus_get(). We make the same guarantee for
4267 * dbus_connection_open() but in a different way since we don't want to
4268 * unref right here; we instead check for connectedness before returning
4269 * the connection from the hash.
4271 _dbus_bus_notify_shared_connection_disconnected_unlocked (connection);
4273 /* Dump the outgoing queue, we aren't going to be able to
4274 * send it now, and we'd like accessors like
4275 * dbus_connection_get_outgoing_size() to be accurate.
4277 if (connection->n_outgoing > 0)
4281 _dbus_verbose ("Dropping %d outgoing messages since we're disconnected\n",
4282 connection->n_outgoing);
4284 while ((link = _dbus_list_get_last_link (&connection->outgoing_messages)))
4286 _dbus_connection_message_sent_unlocked (connection, link->data);
4291 /* Note this may be called multiple times since we don't track whether we already did it */
4292 static DBusDispatchStatus
4293 notify_disconnected_and_dispatch_complete_unlocked (DBusConnection *connection)
4295 HAVE_LOCK_CHECK (connection);
4297 if (connection->disconnect_message_link != NULL)
4299 _dbus_verbose ("Sending disconnect message\n");
4301 /* If we have pending calls, queue their timeouts - we want the Disconnected
4302 * to be the last message, after these timeouts.
4304 connection_timeout_and_complete_all_pending_calls_unlocked (connection);
4306 /* We haven't sent the disconnect message already,
4307 * and all real messages have been queued up.
4309 _dbus_connection_queue_synthesized_message_link (connection,
4310 connection->disconnect_message_link);
4311 connection->disconnect_message_link = NULL;
4313 return DBUS_DISPATCH_DATA_REMAINS;
4316 return DBUS_DISPATCH_COMPLETE;
4319 static DBusDispatchStatus
4320 _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection)
4322 HAVE_LOCK_CHECK (connection);
4324 if (connection->n_incoming > 0)
4325 return DBUS_DISPATCH_DATA_REMAINS;
4326 else if (!_dbus_transport_queue_messages (connection->transport))
4327 return DBUS_DISPATCH_NEED_MEMORY;
4330 DBusDispatchStatus status;
4331 dbus_bool_t is_connected;
4333 status = _dbus_transport_get_dispatch_status (connection->transport);
4334 is_connected = _dbus_transport_get_is_connected (connection->transport);
4336 _dbus_verbose ("dispatch status = %s is_connected = %d\n",
4337 DISPATCH_STATUS_NAME (status), is_connected);
4341 /* It's possible this would be better done by having an explicit
4342 * notification from _dbus_transport_disconnect() that would
4343 * synchronously do this, instead of waiting for the next dispatch
4344 * status check. However, probably not good to change until it causes
4347 notify_disconnected_unlocked (connection);
4349 /* I'm not sure this is needed; the idea is that we want to
4350 * queue the Disconnected only after we've read all the
4351 * messages, but if we're disconnected maybe we are guaranteed
4352 * to have read them all ?
4354 if (status == DBUS_DISPATCH_COMPLETE)
4355 status = notify_disconnected_and_dispatch_complete_unlocked (connection);
4358 if (status != DBUS_DISPATCH_COMPLETE)
4360 else if (connection->n_incoming > 0)
4361 return DBUS_DISPATCH_DATA_REMAINS;
4363 return DBUS_DISPATCH_COMPLETE;
4368 _dbus_connection_update_dispatch_status_and_unlock (DBusConnection *connection,
4369 DBusDispatchStatus new_status)
4371 dbus_bool_t changed;
4372 DBusDispatchStatusFunction function;
4375 HAVE_LOCK_CHECK (connection);
4377 _dbus_connection_ref_unlocked (connection);
4379 changed = new_status != connection->last_dispatch_status;
4381 connection->last_dispatch_status = new_status;
4383 function = connection->dispatch_status_function;
4384 data = connection->dispatch_status_data;
4386 if (connection->disconnected_message_arrived &&
4387 !connection->disconnected_message_processed)
4389 connection->disconnected_message_processed = TRUE;
4391 /* this does an unref, but we have a ref
4392 * so we should not run the finalizer here
4395 connection_forget_shared_unlocked (connection);
4397 if (connection->exit_on_disconnect)
4399 CONNECTION_UNLOCK (connection);
4401 _dbus_verbose ("Exiting on Disconnected signal\n");
4403 _dbus_assert_not_reached ("Call to exit() returned");
4407 /* We drop the lock */
4408 CONNECTION_UNLOCK (connection);
4410 if (changed && function)
4412 _dbus_verbose ("Notifying of change to dispatch status of %p now %d (%s)\n",
4413 connection, new_status,
4414 DISPATCH_STATUS_NAME (new_status));
4415 (* function) (connection, new_status, data);
4418 dbus_connection_unref (connection);
4422 * Gets the current state of the incoming message queue.
4423 * #DBUS_DISPATCH_DATA_REMAINS indicates that the message queue
4424 * may contain messages. #DBUS_DISPATCH_COMPLETE indicates that the
4425 * incoming queue is empty. #DBUS_DISPATCH_NEED_MEMORY indicates that
4426 * there could be data, but we can't know for sure without more
4429 * To process the incoming message queue, use dbus_connection_dispatch()
4430 * or (in rare cases) dbus_connection_pop_message().
4432 * Note, #DBUS_DISPATCH_DATA_REMAINS really means that either we
4433 * have messages in the queue, or we have raw bytes buffered up
4434 * that need to be parsed. When these bytes are parsed, they
4435 * may not add up to an entire message. Thus, it's possible
4436 * to see a status of #DBUS_DISPATCH_DATA_REMAINS but not
4437 * have a message yet.
4439 * In particular this happens on initial connection, because all sorts
4440 * of authentication protocol stuff has to be parsed before the
4441 * first message arrives.
4443 * @param connection the connection.
4444 * @returns current dispatch status
4447 dbus_connection_get_dispatch_status (DBusConnection *connection)
4449 DBusDispatchStatus status;
4451 _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
4453 _dbus_verbose ("start\n");
4455 CONNECTION_LOCK (connection);
4457 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4459 CONNECTION_UNLOCK (connection);
4465 * Filter funtion for handling the Peer standard interface.
4467 static DBusHandlerResult
4468 _dbus_connection_peer_filter_unlocked_no_update (DBusConnection *connection,
4469 DBusMessage *message)
4471 dbus_bool_t sent = FALSE;
4472 DBusMessage *ret = NULL;
4473 DBusList *expire_link;
4475 if (connection->route_peer_messages && dbus_message_get_destination (message) != NULL)
4477 /* This means we're letting the bus route this message */
4478 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4481 if (!dbus_message_has_interface (message, DBUS_INTERFACE_PEER))
4483 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4486 /* Preallocate a linked-list link, so that if we need to dispose of a
4487 * message, we can attach it to the expired list */
4488 expire_link = _dbus_list_alloc_link (NULL);
4491 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4493 if (dbus_message_is_method_call (message,
4494 DBUS_INTERFACE_PEER,
4497 ret = dbus_message_new_method_return (message);
4501 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4503 else if (dbus_message_is_method_call (message,
4504 DBUS_INTERFACE_PEER,
4509 ret = dbus_message_new_method_return (message);
4513 _dbus_string_init (&uuid);
4514 if (_dbus_get_local_machine_uuid_encoded (&uuid))
4516 const char *v_STRING = _dbus_string_get_const_data (&uuid);
4517 if (dbus_message_append_args (ret,
4518 DBUS_TYPE_STRING, &v_STRING,
4521 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4524 _dbus_string_free (&uuid);
4528 /* We need to bounce anything else with this interface, otherwise apps
4529 * could start extending the interface and when we added extensions
4530 * here to DBusConnection we'd break those apps.
4532 ret = dbus_message_new_error (message,
4533 DBUS_ERROR_UNKNOWN_METHOD,
4534 "Unknown method invoked on org.freedesktop.DBus.Peer interface");
4538 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4544 _dbus_list_free_link (expire_link);
4548 /* It'll be safe to unref the reply when we unlock */
4549 expire_link->data = ret;
4550 _dbus_list_prepend_link (&connection->expired_messages, expire_link);
4554 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4556 return DBUS_HANDLER_RESULT_HANDLED;
4560 * Processes all builtin filter functions
4562 * If the spec specifies a standard interface
4563 * they should be processed from this method
4565 static DBusHandlerResult
4566 _dbus_connection_run_builtin_filters_unlocked_no_update (DBusConnection *connection,
4567 DBusMessage *message)
4569 /* We just run one filter for now but have the option to run more
4570 if the spec calls for it in the future */
4572 return _dbus_connection_peer_filter_unlocked_no_update (connection, message);
4576 * Processes any incoming data.
4578 * If there's incoming raw data that has not yet been parsed, it is
4579 * parsed, which may or may not result in adding messages to the
4582 * The incoming data buffer is filled when the connection reads from
4583 * its underlying transport (such as a socket). Reading usually
4584 * happens in dbus_watch_handle() or dbus_connection_read_write().
4586 * If there are complete messages in the incoming queue,
4587 * dbus_connection_dispatch() removes one message from the queue and
4588 * processes it. Processing has three steps.
4590 * First, any method replies are passed to #DBusPendingCall or
4591 * dbus_connection_send_with_reply_and_block() in order to
4592 * complete the pending method call.
4594 * Second, any filters registered with dbus_connection_add_filter()
4595 * are run. If any filter returns #DBUS_HANDLER_RESULT_HANDLED
4596 * then processing stops after that filter.
4598 * Third, if the message is a method call it is forwarded to
4599 * any registered object path handlers added with
4600 * dbus_connection_register_object_path() or
4601 * dbus_connection_register_fallback().
4603 * A single call to dbus_connection_dispatch() will process at most
4604 * one message; it will not clear the entire message queue.
4606 * Be careful about calling dbus_connection_dispatch() from inside a
4607 * message handler, i.e. calling dbus_connection_dispatch()
4608 * recursively. If threads have been initialized with a recursive
4609 * mutex function, then this will not deadlock; however, it can
4610 * certainly confuse your application.
4612 * @todo some FIXME in here about handling DBUS_HANDLER_RESULT_NEED_MEMORY
4614 * @param connection the connection
4615 * @returns dispatch status, see dbus_connection_get_dispatch_status()
4618 dbus_connection_dispatch (DBusConnection *connection)
4620 DBusMessage *message;
4621 DBusList *link, *filter_list_copy, *message_link;
4622 DBusHandlerResult result;
4623 DBusPendingCall *pending;
4624 dbus_int32_t reply_serial;
4625 DBusDispatchStatus status;
4626 dbus_bool_t found_object;
4628 _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
4630 _dbus_verbose ("\n");
4632 CONNECTION_LOCK (connection);
4633 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4634 if (status != DBUS_DISPATCH_DATA_REMAINS)
4636 /* unlocks and calls out to user code */
4637 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4641 /* We need to ref the connection since the callback could potentially
4642 * drop the last ref to it
4644 _dbus_connection_ref_unlocked (connection);
4646 _dbus_connection_acquire_dispatch (connection);
4647 HAVE_LOCK_CHECK (connection);
4649 message_link = _dbus_connection_pop_message_link_unlocked (connection);
4650 if (message_link == NULL)
4652 /* another thread dispatched our stuff */
4654 _dbus_verbose ("another thread dispatched message (during acquire_dispatch above)\n");
4656 _dbus_connection_release_dispatch (connection);
4658 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4660 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4662 dbus_connection_unref (connection);
4667 message = message_link->data;
4669 _dbus_verbose (" dispatching message %p (%s %s %s '%s')\n",
4671 dbus_message_type_to_string (dbus_message_get_type (message)),
4672 dbus_message_get_interface (message) ?
4673 dbus_message_get_interface (message) :
4675 dbus_message_get_member (message) ?
4676 dbus_message_get_member (message) :
4678 dbus_message_get_signature (message));
4680 result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4682 /* Pending call handling must be first, because if you do
4683 * dbus_connection_send_with_reply_and_block() or
4684 * dbus_pending_call_block() then no handlers/filters will be run on
4685 * the reply. We want consistent semantics in the case where we
4686 * dbus_connection_dispatch() the reply.
4689 reply_serial = dbus_message_get_reply_serial (message);
4690 pending = _dbus_hash_table_lookup_int (connection->pending_replies,
4694 _dbus_verbose ("Dispatching a pending reply\n");
4695 complete_pending_call_and_unlock (connection, pending, message);
4696 pending = NULL; /* it's probably unref'd */
4698 CONNECTION_LOCK (connection);
4699 _dbus_verbose ("pending call completed in dispatch\n");
4700 result = DBUS_HANDLER_RESULT_HANDLED;
4704 result = _dbus_connection_run_builtin_filters_unlocked_no_update (connection, message);
4705 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4708 if (!_dbus_list_copy (&connection->filter_list, &filter_list_copy))
4710 _dbus_connection_release_dispatch (connection);
4711 HAVE_LOCK_CHECK (connection);
4713 _dbus_connection_failed_pop (connection, message_link);
4715 /* unlocks and calls user code */
4716 _dbus_connection_update_dispatch_status_and_unlock (connection,
4717 DBUS_DISPATCH_NEED_MEMORY);
4718 dbus_connection_unref (connection);
4720 return DBUS_DISPATCH_NEED_MEMORY;
4723 _dbus_list_foreach (&filter_list_copy,
4724 (DBusForeachFunction)_dbus_message_filter_ref,
4727 /* We're still protected from dispatch() reentrancy here
4728 * since we acquired the dispatcher
4730 CONNECTION_UNLOCK (connection);
4732 link = _dbus_list_get_first_link (&filter_list_copy);
4733 while (link != NULL)
4735 DBusMessageFilter *filter = link->data;
4736 DBusList *next = _dbus_list_get_next_link (&filter_list_copy, link);
4738 if (filter->function == NULL)
4740 _dbus_verbose (" filter was removed in a callback function\n");
4745 _dbus_verbose (" running filter on message %p\n", message);
4746 result = (* filter->function) (connection, message, filter->user_data);
4748 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4754 _dbus_list_foreach (&filter_list_copy,
4755 (DBusForeachFunction)_dbus_message_filter_unref,
4757 _dbus_list_clear (&filter_list_copy);
4759 CONNECTION_LOCK (connection);
4761 if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
4763 _dbus_verbose ("No memory\n");
4766 else if (result == DBUS_HANDLER_RESULT_HANDLED)
4768 _dbus_verbose ("filter handled message in dispatch\n");
4772 /* We're still protected from dispatch() reentrancy here
4773 * since we acquired the dispatcher
4775 _dbus_verbose (" running object path dispatch on message %p (%s %s %s '%s')\n",
4777 dbus_message_type_to_string (dbus_message_get_type (message)),
4778 dbus_message_get_interface (message) ?
4779 dbus_message_get_interface (message) :
4781 dbus_message_get_member (message) ?
4782 dbus_message_get_member (message) :
4784 dbus_message_get_signature (message));
4786 HAVE_LOCK_CHECK (connection);
4787 result = _dbus_object_tree_dispatch_and_unlock (connection->objects,
4791 CONNECTION_LOCK (connection);
4793 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4795 _dbus_verbose ("object tree handled message in dispatch\n");
4799 if (dbus_message_get_type (message) == DBUS_MESSAGE_TYPE_METHOD_CALL)
4803 DBusPreallocatedSend *preallocated;
4804 DBusList *expire_link;
4806 _dbus_verbose (" sending error %s\n",
4807 DBUS_ERROR_UNKNOWN_METHOD);
4809 if (!_dbus_string_init (&str))
4811 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4812 _dbus_verbose ("no memory for error string in dispatch\n");
4816 if (!_dbus_string_append_printf (&str,
4817 "Method \"%s\" with signature \"%s\" on interface \"%s\" doesn't exist\n",
4818 dbus_message_get_member (message),
4819 dbus_message_get_signature (message),
4820 dbus_message_get_interface (message)))
4822 _dbus_string_free (&str);
4823 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4824 _dbus_verbose ("no memory for error string in dispatch\n");
4828 reply = dbus_message_new_error (message,
4829 found_object ? DBUS_ERROR_UNKNOWN_METHOD : DBUS_ERROR_UNKNOWN_OBJECT,
4830 _dbus_string_get_const_data (&str));
4831 _dbus_string_free (&str);
4835 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4836 _dbus_verbose ("no memory for error reply in dispatch\n");
4840 expire_link = _dbus_list_alloc_link (reply);
4842 if (expire_link == NULL)
4844 dbus_message_unref (reply);
4845 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4846 _dbus_verbose ("no memory for error send in dispatch\n");
4850 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
4852 if (preallocated == NULL)
4854 _dbus_list_free_link (expire_link);
4855 /* It's OK that this is finalized, because it hasn't been seen by
4856 * anything that could attach user callbacks */
4857 dbus_message_unref (reply);
4858 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4859 _dbus_verbose ("no memory for error send in dispatch\n");
4863 _dbus_connection_send_preallocated_unlocked_no_update (connection, preallocated,
4865 /* reply will be freed when we release the lock */
4866 _dbus_list_prepend_link (&connection->expired_messages, expire_link);
4868 result = DBUS_HANDLER_RESULT_HANDLED;
4871 _dbus_verbose (" done dispatching %p (%s %s %s '%s') on connection %p\n", message,
4872 dbus_message_type_to_string (dbus_message_get_type (message)),
4873 dbus_message_get_interface (message) ?
4874 dbus_message_get_interface (message) :
4876 dbus_message_get_member (message) ?
4877 dbus_message_get_member (message) :
4879 dbus_message_get_signature (message),
4883 if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
4885 _dbus_verbose ("out of memory\n");
4887 /* Put message back, and we'll start over.
4888 * Yes this means handlers must be idempotent if they
4889 * don't return HANDLED; c'est la vie.
4891 _dbus_connection_putback_message_link_unlocked (connection,
4893 /* now we don't want to free them */
4894 message_link = NULL;
4899 _dbus_verbose (" ... done dispatching\n");
4902 _dbus_connection_release_dispatch (connection);
4903 HAVE_LOCK_CHECK (connection);
4905 if (message != NULL)
4907 /* We don't want this message to count in maximum message limits when
4908 * computing the dispatch status, below. We have to drop the lock
4909 * temporarily, because finalizing a message can trigger callbacks.
4911 * We have a reference to the connection, and we don't use any cached
4912 * pointers to the connection's internals below this point, so it should
4913 * be safe to drop the lock and take it back. */
4914 CONNECTION_UNLOCK (connection);
4915 dbus_message_unref (message);
4916 CONNECTION_LOCK (connection);
4919 if (message_link != NULL)
4920 _dbus_list_free_link (message_link);
4922 _dbus_verbose ("before final status update\n");
4923 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4925 /* unlocks and calls user code */
4926 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4928 dbus_connection_unref (connection);
4934 * Sets the watch functions for the connection. These functions are
4935 * responsible for making the application's main loop aware of file
4936 * descriptors that need to be monitored for events, using select() or
4937 * poll(). When using Qt, typically the DBusAddWatchFunction would
4938 * create a QSocketNotifier. When using GLib, the DBusAddWatchFunction
4939 * could call g_io_add_watch(), or could be used as part of a more
4940 * elaborate GSource. Note that when a watch is added, it may
4943 * The DBusWatchToggledFunction notifies the application that the
4944 * watch has been enabled or disabled. Call dbus_watch_get_enabled()
4945 * to check this. A disabled watch should have no effect, and enabled
4946 * watch should be added to the main loop. This feature is used
4947 * instead of simply adding/removing the watch because
4948 * enabling/disabling can be done without memory allocation. The
4949 * toggled function may be NULL if a main loop re-queries
4950 * dbus_watch_get_enabled() every time anyway.
4952 * The DBusWatch can be queried for the file descriptor to watch using
4953 * dbus_watch_get_unix_fd() or dbus_watch_get_socket(), and for the
4954 * events to watch for using dbus_watch_get_flags(). The flags
4955 * returned by dbus_watch_get_flags() will only contain
4956 * DBUS_WATCH_READABLE and DBUS_WATCH_WRITABLE, never
4957 * DBUS_WATCH_HANGUP or DBUS_WATCH_ERROR; all watches implicitly
4958 * include a watch for hangups, errors, and other exceptional
4961 * Once a file descriptor becomes readable or writable, or an exception
4962 * occurs, dbus_watch_handle() should be called to
4963 * notify the connection of the file descriptor's condition.
4965 * dbus_watch_handle() cannot be called during the
4966 * DBusAddWatchFunction, as the connection will not be ready to handle
4969 * It is not allowed to reference a DBusWatch after it has been passed
4970 * to remove_function.
4972 * If #FALSE is returned due to lack of memory, the failure may be due
4973 * to a #FALSE return from the new add_function. If so, the
4974 * add_function may have been called successfully one or more times,
4975 * but the remove_function will also have been called to remove any
4976 * successful adds. i.e. if #FALSE is returned the net result
4977 * should be that dbus_connection_set_watch_functions() has no effect,
4978 * but the add_function and remove_function may have been called.
4980 * @note The thread lock on DBusConnection is held while
4981 * watch functions are invoked, so inside these functions you
4982 * may not invoke any methods on DBusConnection or it will deadlock.
4983 * See the comments in the code or http://lists.freedesktop.org/archives/dbus/2007-July/tread.html#8144
4984 * if you encounter this issue and want to attempt writing a patch.
4986 * @param connection the connection.
4987 * @param add_function function to begin monitoring a new descriptor.
4988 * @param remove_function function to stop monitoring a descriptor.
4989 * @param toggled_function function to notify of enable/disable
4990 * @param data data to pass to add_function and remove_function.
4991 * @param free_data_function function to be called to free the data.
4992 * @returns #FALSE on failure (no memory)
4995 dbus_connection_set_watch_functions (DBusConnection *connection,
4996 DBusAddWatchFunction add_function,
4997 DBusRemoveWatchFunction remove_function,
4998 DBusWatchToggledFunction toggled_function,
5000 DBusFreeFunction free_data_function)
5004 _dbus_return_val_if_fail (connection != NULL, FALSE);
5006 CONNECTION_LOCK (connection);
5008 retval = _dbus_watch_list_set_functions (connection->watches,
5009 add_function, remove_function,
5011 data, free_data_function);
5013 CONNECTION_UNLOCK (connection);
5019 * Sets the timeout functions for the connection. These functions are
5020 * responsible for making the application's main loop aware of timeouts.
5021 * When using Qt, typically the DBusAddTimeoutFunction would create a
5022 * QTimer. When using GLib, the DBusAddTimeoutFunction would call
5025 * The DBusTimeoutToggledFunction notifies the application that the
5026 * timeout has been enabled or disabled. Call
5027 * dbus_timeout_get_enabled() to check this. A disabled timeout should
5028 * have no effect, and enabled timeout should be added to the main
5029 * loop. This feature is used instead of simply adding/removing the
5030 * timeout because enabling/disabling can be done without memory
5031 * allocation. With Qt, QTimer::start() and QTimer::stop() can be used
5032 * to enable and disable. The toggled function may be NULL if a main
5033 * loop re-queries dbus_timeout_get_enabled() every time anyway.
5034 * Whenever a timeout is toggled, its interval may change.
5036 * The DBusTimeout can be queried for the timer interval using
5037 * dbus_timeout_get_interval(). dbus_timeout_handle() should be called
5038 * repeatedly, each time the interval elapses, starting after it has
5039 * elapsed once. The timeout stops firing when it is removed with the
5040 * given remove_function. The timer interval may change whenever the
5041 * timeout is added, removed, or toggled.
5043 * @note The thread lock on DBusConnection is held while
5044 * timeout functions are invoked, so inside these functions you
5045 * may not invoke any methods on DBusConnection or it will deadlock.
5046 * See the comments in the code or http://lists.freedesktop.org/archives/dbus/2007-July/thread.html#8144
5047 * if you encounter this issue and want to attempt writing a patch.
5049 * @param connection the connection.
5050 * @param add_function function to add a timeout.
5051 * @param remove_function function to remove a timeout.
5052 * @param toggled_function function to notify of enable/disable
5053 * @param data data to pass to add_function and remove_function.
5054 * @param free_data_function function to be called to free the data.
5055 * @returns #FALSE on failure (no memory)
5058 dbus_connection_set_timeout_functions (DBusConnection *connection,
5059 DBusAddTimeoutFunction add_function,
5060 DBusRemoveTimeoutFunction remove_function,
5061 DBusTimeoutToggledFunction toggled_function,
5063 DBusFreeFunction free_data_function)
5067 _dbus_return_val_if_fail (connection != NULL, FALSE);
5069 CONNECTION_LOCK (connection);
5071 retval = _dbus_timeout_list_set_functions (connection->timeouts,
5072 add_function, remove_function,
5074 data, free_data_function);
5076 CONNECTION_UNLOCK (connection);
5082 * Sets the mainloop wakeup function for the connection. This function
5083 * is responsible for waking up the main loop (if its sleeping in
5084 * another thread) when some some change has happened to the
5085 * connection that the mainloop needs to reconsider (e.g. a message
5086 * has been queued for writing). When using Qt, this typically
5087 * results in a call to QEventLoop::wakeUp(). When using GLib, it
5088 * would call g_main_context_wakeup().
5090 * @param connection the connection.
5091 * @param wakeup_main_function function to wake up the mainloop
5092 * @param data data to pass wakeup_main_function
5093 * @param free_data_function function to be called to free the data.
5096 dbus_connection_set_wakeup_main_function (DBusConnection *connection,
5097 DBusWakeupMainFunction wakeup_main_function,
5099 DBusFreeFunction free_data_function)
5102 DBusFreeFunction old_free_data;
5104 _dbus_return_if_fail (connection != NULL);
5106 CONNECTION_LOCK (connection);
5107 old_data = connection->wakeup_main_data;
5108 old_free_data = connection->free_wakeup_main_data;
5110 connection->wakeup_main_function = wakeup_main_function;
5111 connection->wakeup_main_data = data;
5112 connection->free_wakeup_main_data = free_data_function;
5114 CONNECTION_UNLOCK (connection);
5116 /* Callback outside the lock */
5118 (*old_free_data) (old_data);
5122 * Set a function to be invoked when the dispatch status changes.
5123 * If the dispatch status is #DBUS_DISPATCH_DATA_REMAINS, then
5124 * dbus_connection_dispatch() needs to be called to process incoming
5125 * messages. However, dbus_connection_dispatch() MUST NOT BE CALLED
5126 * from inside the DBusDispatchStatusFunction. Indeed, almost
5127 * any reentrancy in this function is a bad idea. Instead,
5128 * the DBusDispatchStatusFunction should simply save an indication
5129 * that messages should be dispatched later, when the main loop
5132 * If you don't set a dispatch status function, you have to be sure to
5133 * dispatch on every iteration of your main loop, especially if
5134 * dbus_watch_handle() or dbus_timeout_handle() were called.
5136 * @param connection the connection
5137 * @param function function to call on dispatch status changes
5138 * @param data data for function
5139 * @param free_data_function free the function data
5142 dbus_connection_set_dispatch_status_function (DBusConnection *connection,
5143 DBusDispatchStatusFunction function,
5145 DBusFreeFunction free_data_function)
5148 DBusFreeFunction old_free_data;
5150 _dbus_return_if_fail (connection != NULL);
5152 CONNECTION_LOCK (connection);
5153 old_data = connection->dispatch_status_data;
5154 old_free_data = connection->free_dispatch_status_data;
5156 connection->dispatch_status_function = function;
5157 connection->dispatch_status_data = data;
5158 connection->free_dispatch_status_data = free_data_function;
5160 CONNECTION_UNLOCK (connection);
5162 /* Callback outside the lock */
5164 (*old_free_data) (old_data);
5168 * Get the UNIX file descriptor of the connection, if any. This can
5169 * be used for SELinux access control checks with getpeercon() for
5170 * example. DO NOT read or write to the file descriptor, or try to
5171 * select() on it; use DBusWatch for main loop integration. Not all
5172 * connections will have a file descriptor. So for adding descriptors
5173 * to the main loop, use dbus_watch_get_unix_fd() and so forth.
5175 * If the connection is socket-based, you can also use
5176 * dbus_connection_get_socket(), which will work on Windows too.
5177 * This function always fails on Windows.
5179 * Right now the returned descriptor is always a socket, but
5180 * that is not guaranteed.
5182 * @param connection the connection
5183 * @param fd return location for the file descriptor.
5184 * @returns #TRUE if fd is successfully obtained.
5187 dbus_connection_get_unix_fd (DBusConnection *connection,
5190 _dbus_return_val_if_fail (connection != NULL, FALSE);
5191 _dbus_return_val_if_fail (connection->transport != NULL, FALSE);
5194 /* FIXME do this on a lower level */
5198 return dbus_connection_get_socket(connection, fd);
5202 * Gets the underlying Windows or UNIX socket file descriptor
5203 * of the connection, if any. DO NOT read or write to the file descriptor, or try to
5204 * select() on it; use DBusWatch for main loop integration. Not all
5205 * connections will have a socket. So for adding descriptors
5206 * to the main loop, use dbus_watch_get_socket() and so forth.
5208 * If the connection is not socket-based, this function will return FALSE,
5209 * even if the connection does have a file descriptor of some kind.
5210 * i.e. this function always returns specifically a socket file descriptor.
5212 * @param connection the connection
5213 * @param fd return location for the file descriptor.
5214 * @returns #TRUE if fd is successfully obtained.
5217 dbus_connection_get_socket(DBusConnection *connection,
5222 _dbus_return_val_if_fail (connection != NULL, FALSE);
5223 _dbus_return_val_if_fail (connection->transport != NULL, FALSE);
5225 CONNECTION_LOCK (connection);
5227 retval = _dbus_transport_get_socket_fd (connection->transport,
5230 CONNECTION_UNLOCK (connection);
5236 * Gets the UNIX user ID of the connection if known. Returns #TRUE if
5237 * the uid is filled in. Always returns #FALSE on non-UNIX platforms
5238 * for now, though in theory someone could hook Windows to NIS or
5239 * something. Always returns #FALSE prior to authenticating the
5242 * The UID is only read by servers from clients; clients can't usually
5243 * get the UID of servers, because servers do not authenticate to
5244 * clients. The returned UID is the UID the connection authenticated
5247 * The message bus is a server and the apps connecting to the bus
5250 * You can ask the bus to tell you the UID of another connection though
5251 * if you like; this is done with dbus_bus_get_unix_user().
5253 * @param connection the connection
5254 * @param uid return location for the user ID
5255 * @returns #TRUE if uid is filled in with a valid user ID
5257 #ifdef ENABLE_KDBUS_TRANSPORT
5259 dbus_connection_get_unix_user_dbus (DBusConnection *connection,
5263 dbus_connection_get_unix_user (DBusConnection *connection,
5269 _dbus_return_val_if_fail (connection != NULL, FALSE);
5270 _dbus_return_val_if_fail (uid != NULL, FALSE);
5272 CONNECTION_LOCK (connection);
5274 if (!_dbus_transport_try_to_authenticate (connection->transport))
5277 result = _dbus_transport_get_unix_user (connection->transport,
5281 _dbus_assert (!result);
5284 CONNECTION_UNLOCK (connection);
5290 * Gets the process ID of the connection if any.
5291 * Returns #TRUE if the pid is filled in.
5292 * Always returns #FALSE prior to authenticating the
5295 * @param connection the connection
5296 * @param pid return location for the process ID
5297 * @returns #TRUE if uid is filled in with a valid process ID
5299 #ifdef ENABLE_KDBUS_TRANSPORT
5301 dbus_connection_get_unix_process_id_dbus (DBusConnection *connection,
5305 dbus_connection_get_unix_process_id (DBusConnection *connection,
5311 _dbus_return_val_if_fail (connection != NULL, FALSE);
5312 _dbus_return_val_if_fail (pid != NULL, FALSE);
5314 CONNECTION_LOCK (connection);
5316 if (!_dbus_transport_try_to_authenticate (connection->transport))
5319 result = _dbus_transport_get_unix_process_id (connection->transport,
5322 CONNECTION_UNLOCK (connection);
5328 * Gets the ADT audit data of the connection if any.
5329 * Returns #TRUE if the structure pointer is returned.
5330 * Always returns #FALSE prior to authenticating the
5333 * @param connection the connection
5334 * @param data return location for audit data
5335 * @param data_size return location for length of audit data
5336 * @returns #TRUE if audit data is filled in with a valid ucred pointer
5339 dbus_connection_get_adt_audit_session_data (DBusConnection *connection,
5341 dbus_int32_t *data_size)
5345 _dbus_return_val_if_fail (connection != NULL, FALSE);
5346 _dbus_return_val_if_fail (data != NULL, FALSE);
5347 _dbus_return_val_if_fail (data_size != NULL, FALSE);
5349 CONNECTION_LOCK (connection);
5351 if (!_dbus_transport_try_to_authenticate (connection->transport))
5354 result = _dbus_transport_get_adt_audit_session_data (connection->transport,
5357 CONNECTION_UNLOCK (connection);
5363 * Sets a predicate function used to determine whether a given user ID
5364 * is allowed to connect. When an incoming connection has
5365 * authenticated with a particular user ID, this function is called;
5366 * if it returns #TRUE, the connection is allowed to proceed,
5367 * otherwise the connection is disconnected.
5369 * If the function is set to #NULL (as it is by default), then
5370 * only the same UID as the server process will be allowed to
5371 * connect. Also, root is always allowed to connect.
5373 * On Windows, the function will be set and its free_data_function will
5374 * be invoked when the connection is freed or a new function is set.
5375 * However, the function will never be called, because there are
5376 * no UNIX user ids to pass to it, or at least none of the existing
5377 * auth protocols would allow authenticating as a UNIX user on Windows.
5379 * @param connection the connection
5380 * @param function the predicate
5381 * @param data data to pass to the predicate
5382 * @param free_data_function function to free the data
5385 dbus_connection_set_unix_user_function (DBusConnection *connection,
5386 DBusAllowUnixUserFunction function,
5388 DBusFreeFunction free_data_function)
5390 void *old_data = NULL;
5391 DBusFreeFunction old_free_function = NULL;
5393 _dbus_return_if_fail (connection != NULL);
5395 CONNECTION_LOCK (connection);
5396 _dbus_transport_set_unix_user_function (connection->transport,
5397 function, data, free_data_function,
5398 &old_data, &old_free_function);
5399 CONNECTION_UNLOCK (connection);
5401 if (old_free_function != NULL)
5402 (* old_free_function) (old_data);
5406 * Gets the Windows user SID of the connection if known. Returns
5407 * #TRUE if the ID is filled in. Always returns #FALSE on non-Windows
5408 * platforms for now, though in theory someone could hook UNIX to
5409 * Active Directory or something. Always returns #FALSE prior to
5410 * authenticating the connection.
5412 * The user is only read by servers from clients; clients can't usually
5413 * get the user of servers, because servers do not authenticate to
5414 * clients. The returned user is the user the connection authenticated
5417 * The message bus is a server and the apps connecting to the bus
5420 * The returned user string has to be freed with dbus_free().
5422 * The return value indicates whether the user SID is available;
5423 * if it's available but we don't have the memory to copy it,
5424 * then the return value is #TRUE and #NULL is given as the SID.
5426 * @todo We would like to be able to say "You can ask the bus to tell
5427 * you the user of another connection though if you like; this is done
5428 * with dbus_bus_get_windows_user()." But this has to be implemented
5429 * in bus/driver.c and dbus/dbus-bus.c, and is pointless anyway
5430 * since on Windows we only use the session bus for now.
5432 * @param connection the connection
5433 * @param windows_sid_p return location for an allocated copy of the user ID, or #NULL if no memory
5434 * @returns #TRUE if user is available (returned value may be #NULL anyway if no memory)
5437 dbus_connection_get_windows_user (DBusConnection *connection,
5438 char **windows_sid_p)
5442 _dbus_return_val_if_fail (connection != NULL, FALSE);
5443 _dbus_return_val_if_fail (windows_sid_p != NULL, FALSE);
5445 CONNECTION_LOCK (connection);
5447 if (!_dbus_transport_try_to_authenticate (connection->transport))
5450 result = _dbus_transport_get_windows_user (connection->transport,
5454 _dbus_assert (!result);
5457 CONNECTION_UNLOCK (connection);
5463 * Sets a predicate function used to determine whether a given user ID
5464 * is allowed to connect. When an incoming connection has
5465 * authenticated with a particular user ID, this function is called;
5466 * if it returns #TRUE, the connection is allowed to proceed,
5467 * otherwise the connection is disconnected.
5469 * If the function is set to #NULL (as it is by default), then
5470 * only the same user owning the server process will be allowed to
5473 * On UNIX, the function will be set and its free_data_function will
5474 * be invoked when the connection is freed or a new function is set.
5475 * However, the function will never be called, because there is no
5476 * way right now to authenticate as a Windows user on UNIX.
5478 * @param connection the connection
5479 * @param function the predicate
5480 * @param data data to pass to the predicate
5481 * @param free_data_function function to free the data
5484 dbus_connection_set_windows_user_function (DBusConnection *connection,
5485 DBusAllowWindowsUserFunction function,
5487 DBusFreeFunction free_data_function)
5489 void *old_data = NULL;
5490 DBusFreeFunction old_free_function = NULL;
5492 _dbus_return_if_fail (connection != NULL);
5494 CONNECTION_LOCK (connection);
5495 _dbus_transport_set_windows_user_function (connection->transport,
5496 function, data, free_data_function,
5497 &old_data, &old_free_function);
5498 CONNECTION_UNLOCK (connection);
5500 if (old_free_function != NULL)
5501 (* old_free_function) (old_data);
5505 * This function must be called on the server side of a connection when the
5506 * connection is first seen in the #DBusNewConnectionFunction. If set to
5507 * #TRUE (the default is #FALSE), then the connection can proceed even if
5508 * the client does not authenticate as some user identity, i.e. clients
5509 * can connect anonymously.
5511 * This setting interacts with the available authorization mechanisms
5512 * (see dbus_server_set_auth_mechanisms()). Namely, an auth mechanism
5513 * such as ANONYMOUS that supports anonymous auth must be included in
5514 * the list of available mechanisms for anonymous login to work.
5516 * This setting also changes the default rule for connections
5517 * authorized as a user; normally, if a connection authorizes as
5518 * a user identity, it is permitted if the user identity is
5519 * root or the user identity matches the user identity of the server
5520 * process. If anonymous connections are allowed, however,
5521 * then any user identity is allowed.
5523 * You can override the rules for connections authorized as a
5524 * user identity with dbus_connection_set_unix_user_function()
5525 * and dbus_connection_set_windows_user_function().
5527 * @param connection the connection
5528 * @param value whether to allow authentication as an anonymous user
5531 dbus_connection_set_allow_anonymous (DBusConnection *connection,
5534 _dbus_return_if_fail (connection != NULL);
5536 CONNECTION_LOCK (connection);
5537 _dbus_transport_set_allow_anonymous (connection->transport, value);
5538 CONNECTION_UNLOCK (connection);
5543 * Normally #DBusConnection automatically handles all messages to the
5544 * org.freedesktop.DBus.Peer interface. However, the message bus wants
5545 * to be able to route methods on that interface through the bus and
5546 * to other applications. If routing peer messages is enabled, then
5547 * messages with the org.freedesktop.DBus.Peer interface that also
5548 * have a bus destination name set will not be automatically
5549 * handled by the #DBusConnection and instead will be dispatched
5550 * normally to the application.
5552 * If a normal application sets this flag, it can break things badly.
5553 * So don't set this unless you are the message bus.
5555 * @param connection the connection
5556 * @param value #TRUE to pass through org.freedesktop.DBus.Peer messages with a bus name set
5559 dbus_connection_set_route_peer_messages (DBusConnection *connection,
5562 _dbus_return_if_fail (connection != NULL);
5564 CONNECTION_LOCK (connection);
5565 connection->route_peer_messages = TRUE;
5566 CONNECTION_UNLOCK (connection);
5570 * Adds a message filter. Filters are handlers that are run on all
5571 * incoming messages, prior to the objects registered with
5572 * dbus_connection_register_object_path(). Filters are run in the
5573 * order that they were added. The same handler can be added as a
5574 * filter more than once, in which case it will be run more than once.
5575 * Filters added during a filter callback won't be run on the message
5578 * @todo we don't run filters on messages while blocking without
5579 * entering the main loop, since filters are run as part of
5580 * dbus_connection_dispatch(). This is probably a feature, as filters
5581 * could create arbitrary reentrancy. But kind of sucks if you're
5582 * trying to filter METHOD_RETURN for some reason.
5584 * @param connection the connection
5585 * @param function function to handle messages
5586 * @param user_data user data to pass to the function
5587 * @param free_data_function function to use for freeing user data
5588 * @returns #TRUE on success, #FALSE if not enough memory.
5591 dbus_connection_add_filter (DBusConnection *connection,
5592 DBusHandleMessageFunction function,
5594 DBusFreeFunction free_data_function)
5596 DBusMessageFilter *filter;
5598 _dbus_return_val_if_fail (connection != NULL, FALSE);
5599 _dbus_return_val_if_fail (function != NULL, FALSE);
5601 filter = dbus_new0 (DBusMessageFilter, 1);
5605 _dbus_atomic_inc (&filter->refcount);
5607 CONNECTION_LOCK (connection);
5609 if (!_dbus_list_append (&connection->filter_list,
5612 _dbus_message_filter_unref (filter);
5613 CONNECTION_UNLOCK (connection);
5617 /* Fill in filter after all memory allocated,
5618 * so we don't run the free_user_data_function
5619 * if the add_filter() fails
5622 filter->function = function;
5623 filter->user_data = user_data;
5624 filter->free_user_data_function = free_data_function;
5626 CONNECTION_UNLOCK (connection);
5631 * Removes a previously-added message filter. It is a programming
5632 * error to call this function for a handler that has not been added
5633 * as a filter. If the given handler was added more than once, only
5634 * one instance of it will be removed (the most recently-added
5637 * @param connection the connection
5638 * @param function the handler to remove
5639 * @param user_data user data for the handler to remove
5643 dbus_connection_remove_filter (DBusConnection *connection,
5644 DBusHandleMessageFunction function,
5648 DBusMessageFilter *filter;
5650 _dbus_return_if_fail (connection != NULL);
5651 _dbus_return_if_fail (function != NULL);
5653 CONNECTION_LOCK (connection);
5657 link = _dbus_list_get_last_link (&connection->filter_list);
5658 while (link != NULL)
5660 filter = link->data;
5662 if (filter->function == function &&
5663 filter->user_data == user_data)
5665 _dbus_list_remove_link (&connection->filter_list, link);
5666 filter->function = NULL;
5671 link = _dbus_list_get_prev_link (&connection->filter_list, link);
5675 CONNECTION_UNLOCK (connection);
5677 #ifndef DBUS_DISABLE_CHECKS
5680 _dbus_warn_check_failed ("Attempt to remove filter function %p user data %p, but no such filter has been added\n",
5681 function, user_data);
5686 /* Call application code */
5687 if (filter->free_user_data_function)
5688 (* filter->free_user_data_function) (filter->user_data);
5690 filter->free_user_data_function = NULL;
5691 filter->user_data = NULL;
5693 _dbus_message_filter_unref (filter);
5697 * Registers a handler for a given path or subsection in the object
5698 * hierarchy. The given vtable handles messages sent to exactly the
5699 * given path or also for paths bellow that, depending on fallback
5702 * @param connection the connection
5703 * @param fallback whether to handle messages also for "subdirectory"
5704 * @param path a '/' delimited string of path elements
5705 * @param vtable the virtual table
5706 * @param user_data data to pass to functions in the vtable
5707 * @param error address where an error can be returned
5708 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5709 * #DBUS_ERROR_OBJECT_PATH_IN_USE) is reported
5712 _dbus_connection_register_object_path (DBusConnection *connection,
5713 dbus_bool_t fallback,
5715 const DBusObjectPathVTable *vtable,
5719 char **decomposed_path;
5722 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5725 CONNECTION_LOCK (connection);
5727 retval = _dbus_object_tree_register (connection->objects,
5729 (const char **) decomposed_path, vtable,
5732 CONNECTION_UNLOCK (connection);
5734 dbus_free_string_array (decomposed_path);
5740 * Registers a handler for a given path in the object hierarchy.
5741 * The given vtable handles messages sent to exactly the given path.
5743 * @param connection the connection
5744 * @param path a '/' delimited string of path elements
5745 * @param vtable the virtual table
5746 * @param user_data data to pass to functions in the vtable
5747 * @param error address where an error can be returned
5748 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5749 * #DBUS_ERROR_OBJECT_PATH_IN_USE) is reported
5752 dbus_connection_try_register_object_path (DBusConnection *connection,
5754 const DBusObjectPathVTable *vtable,
5758 _dbus_return_val_if_fail (connection != NULL, FALSE);
5759 _dbus_return_val_if_fail (path != NULL, FALSE);
5760 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5761 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5763 return _dbus_connection_register_object_path (connection, FALSE, path, vtable, user_data, error);
5767 * Registers a handler for a given path in the object hierarchy.
5768 * The given vtable handles messages sent to exactly the given path.
5770 * It is a bug to call this function for object paths which already
5771 * have a handler. Use dbus_connection_try_register_object_path() if this
5772 * might be the case.
5774 * @param connection the connection
5775 * @param path a '/' delimited string of path elements
5776 * @param vtable the virtual table
5777 * @param user_data data to pass to functions in the vtable
5778 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5779 * #DBUS_ERROR_OBJECT_PATH_IN_USE) ocurred
5782 dbus_connection_register_object_path (DBusConnection *connection,
5784 const DBusObjectPathVTable *vtable,
5788 DBusError error = DBUS_ERROR_INIT;
5790 _dbus_return_val_if_fail (connection != NULL, FALSE);
5791 _dbus_return_val_if_fail (path != NULL, FALSE);
5792 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5793 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5795 retval = _dbus_connection_register_object_path (connection, FALSE, path, vtable, user_data, &error);
5797 if (dbus_error_has_name (&error, DBUS_ERROR_OBJECT_PATH_IN_USE))
5799 _dbus_warn ("%s\n", error.message);
5800 dbus_error_free (&error);
5808 * Registers a fallback handler for a given subsection of the object
5809 * hierarchy. The given vtable handles messages at or below the given
5810 * path. You can use this to establish a default message handling
5811 * policy for a whole "subdirectory."
5813 * @param connection the connection
5814 * @param path a '/' delimited string of path elements
5815 * @param vtable the virtual table
5816 * @param user_data data to pass to functions in the vtable
5817 * @param error address where an error can be returned
5818 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5819 * #DBUS_ERROR_OBJECT_PATH_IN_USE) is reported
5822 dbus_connection_try_register_fallback (DBusConnection *connection,
5824 const DBusObjectPathVTable *vtable,
5828 _dbus_return_val_if_fail (connection != NULL, FALSE);
5829 _dbus_return_val_if_fail (path != NULL, FALSE);
5830 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5831 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5833 return _dbus_connection_register_object_path (connection, TRUE, path, vtable, user_data, error);
5837 * Registers a fallback handler for a given subsection of the object
5838 * hierarchy. The given vtable handles messages at or below the given
5839 * path. You can use this to establish a default message handling
5840 * policy for a whole "subdirectory."
5842 * It is a bug to call this function for object paths which already
5843 * have a handler. Use dbus_connection_try_register_fallback() if this
5844 * might be the case.
5846 * @param connection the connection
5847 * @param path a '/' delimited string of path elements
5848 * @param vtable the virtual table
5849 * @param user_data data to pass to functions in the vtable
5850 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5851 * #DBUS_ERROR_OBJECT_PATH_IN_USE) occured
5854 dbus_connection_register_fallback (DBusConnection *connection,
5856 const DBusObjectPathVTable *vtable,
5860 DBusError error = DBUS_ERROR_INIT;
5862 _dbus_return_val_if_fail (connection != NULL, FALSE);
5863 _dbus_return_val_if_fail (path != NULL, FALSE);
5864 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5865 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5867 retval = _dbus_connection_register_object_path (connection, TRUE, path, vtable, user_data, &error);
5869 if (dbus_error_has_name (&error, DBUS_ERROR_OBJECT_PATH_IN_USE))
5871 _dbus_warn ("%s\n", error.message);
5872 dbus_error_free (&error);
5880 * Unregisters the handler registered with exactly the given path.
5881 * It's a bug to call this function for a path that isn't registered.
5882 * Can unregister both fallback paths and object paths.
5884 * @param connection the connection
5885 * @param path a '/' delimited string of path elements
5886 * @returns #FALSE if not enough memory
5889 dbus_connection_unregister_object_path (DBusConnection *connection,
5892 char **decomposed_path;
5894 _dbus_return_val_if_fail (connection != NULL, FALSE);
5895 _dbus_return_val_if_fail (path != NULL, FALSE);
5896 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5898 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5901 CONNECTION_LOCK (connection);
5903 _dbus_object_tree_unregister_and_unlock (connection->objects, (const char **) decomposed_path);
5905 dbus_free_string_array (decomposed_path);
5911 * Gets the user data passed to dbus_connection_register_object_path()
5912 * or dbus_connection_register_fallback(). If nothing was registered
5913 * at this path, the data is filled in with #NULL.
5915 * @param connection the connection
5916 * @param path the path you registered with
5917 * @param data_p location to store the user data, or #NULL
5918 * @returns #FALSE if not enough memory
5921 dbus_connection_get_object_path_data (DBusConnection *connection,
5925 char **decomposed_path;
5927 _dbus_return_val_if_fail (connection != NULL, FALSE);
5928 _dbus_return_val_if_fail (path != NULL, FALSE);
5929 _dbus_return_val_if_fail (data_p != NULL, FALSE);
5933 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5936 CONNECTION_LOCK (connection);
5938 *data_p = _dbus_object_tree_get_user_data_unlocked (connection->objects, (const char**) decomposed_path);
5940 CONNECTION_UNLOCK (connection);
5942 dbus_free_string_array (decomposed_path);
5948 * Lists the registered fallback handlers and object path handlers at
5949 * the given parent_path. The returned array should be freed with
5950 * dbus_free_string_array().
5952 * @param connection the connection
5953 * @param parent_path the path to list the child handlers of
5954 * @param child_entries returns #NULL-terminated array of children
5955 * @returns #FALSE if no memory to allocate the child entries
5958 dbus_connection_list_registered (DBusConnection *connection,
5959 const char *parent_path,
5960 char ***child_entries)
5962 char **decomposed_path;
5964 _dbus_return_val_if_fail (connection != NULL, FALSE);
5965 _dbus_return_val_if_fail (parent_path != NULL, FALSE);
5966 _dbus_return_val_if_fail (parent_path[0] == '/', FALSE);
5967 _dbus_return_val_if_fail (child_entries != NULL, FALSE);
5969 if (!_dbus_decompose_path (parent_path, strlen (parent_path), &decomposed_path, NULL))
5972 CONNECTION_LOCK (connection);
5974 retval = _dbus_object_tree_list_registered_and_unlock (connection->objects,
5975 (const char **) decomposed_path,
5977 dbus_free_string_array (decomposed_path);
5982 static DBusDataSlotAllocator slot_allocator =
5983 _DBUS_DATA_SLOT_ALLOCATOR_INIT (_DBUS_LOCK_NAME (connection_slots));
5986 * Allocates an integer ID to be used for storing application-specific
5987 * data on any DBusConnection. The allocated ID may then be used
5988 * with dbus_connection_set_data() and dbus_connection_get_data().
5989 * The passed-in slot must be initialized to -1, and is filled in
5990 * with the slot ID. If the passed-in slot is not -1, it's assumed
5991 * to be already allocated, and its refcount is incremented.
5993 * The allocated slot is global, i.e. all DBusConnection objects will
5994 * have a slot with the given integer ID reserved.
5996 * @param slot_p address of a global variable storing the slot
5997 * @returns #FALSE on failure (no memory)
6000 dbus_connection_allocate_data_slot (dbus_int32_t *slot_p)
6002 return _dbus_data_slot_allocator_alloc (&slot_allocator,
6007 * Deallocates a global ID for connection data slots.
6008 * dbus_connection_get_data() and dbus_connection_set_data() may no
6009 * longer be used with this slot. Existing data stored on existing
6010 * DBusConnection objects will be freed when the connection is
6011 * finalized, but may not be retrieved (and may only be replaced if
6012 * someone else reallocates the slot). When the refcount on the
6013 * passed-in slot reaches 0, it is set to -1.
6015 * @param slot_p address storing the slot to deallocate
6018 dbus_connection_free_data_slot (dbus_int32_t *slot_p)
6020 _dbus_return_if_fail (*slot_p >= 0);
6022 _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
6026 * Stores a pointer on a DBusConnection, along
6027 * with an optional function to be used for freeing
6028 * the data when the data is set again, or when
6029 * the connection is finalized. The slot number
6030 * must have been allocated with dbus_connection_allocate_data_slot().
6032 * @note This function does not take the
6033 * main thread lock on DBusConnection, which allows it to be
6034 * used from inside watch and timeout functions. (See the
6035 * note in docs for dbus_connection_set_watch_functions().)
6036 * A side effect of this is that you need to know there's
6037 * a reference held on the connection while invoking
6038 * dbus_connection_set_data(), or the connection could be
6039 * finalized during dbus_connection_set_data().
6041 * @param connection the connection
6042 * @param slot the slot number
6043 * @param data the data to store
6044 * @param free_data_func finalizer function for the data
6045 * @returns #TRUE if there was enough memory to store the data
6048 dbus_connection_set_data (DBusConnection *connection,
6051 DBusFreeFunction free_data_func)
6053 DBusFreeFunction old_free_func;
6057 _dbus_return_val_if_fail (connection != NULL, FALSE);
6058 _dbus_return_val_if_fail (slot >= 0, FALSE);
6060 SLOTS_LOCK (connection);
6062 retval = _dbus_data_slot_list_set (&slot_allocator,
6063 &connection->slot_list,
6064 slot, data, free_data_func,
6065 &old_free_func, &old_data);
6067 SLOTS_UNLOCK (connection);
6071 /* Do the actual free outside the connection lock */
6073 (* old_free_func) (old_data);
6080 * Retrieves data previously set with dbus_connection_set_data().
6081 * The slot must still be allocated (must not have been freed).
6083 * @note This function does not take the
6084 * main thread lock on DBusConnection, which allows it to be
6085 * used from inside watch and timeout functions. (See the
6086 * note in docs for dbus_connection_set_watch_functions().)
6087 * A side effect of this is that you need to know there's
6088 * a reference held on the connection while invoking
6089 * dbus_connection_get_data(), or the connection could be
6090 * finalized during dbus_connection_get_data().
6092 * @param connection the connection
6093 * @param slot the slot to get data from
6094 * @returns the data, or #NULL if not found
6097 dbus_connection_get_data (DBusConnection *connection,
6102 _dbus_return_val_if_fail (connection != NULL, NULL);
6103 _dbus_return_val_if_fail (slot >= 0, NULL);
6105 SLOTS_LOCK (connection);
6107 res = _dbus_data_slot_list_get (&slot_allocator,
6108 &connection->slot_list,
6111 SLOTS_UNLOCK (connection);
6117 * This function sets a global flag for whether dbus_connection_new()
6118 * will set SIGPIPE behavior to SIG_IGN.
6120 * @param will_modify_sigpipe #TRUE to allow sigpipe to be set to SIG_IGN
6123 dbus_connection_set_change_sigpipe (dbus_bool_t will_modify_sigpipe)
6125 _dbus_modify_sigpipe = will_modify_sigpipe != FALSE;
6129 * Specifies the maximum size message this connection is allowed to
6130 * receive. Larger messages will result in disconnecting the
6133 * @param connection a #DBusConnection
6134 * @param size maximum message size the connection can receive, in bytes
6137 dbus_connection_set_max_message_size (DBusConnection *connection,
6140 _dbus_return_if_fail (connection != NULL);
6142 CONNECTION_LOCK (connection);
6143 _dbus_transport_set_max_message_size (connection->transport,
6145 CONNECTION_UNLOCK (connection);
6149 * Gets the value set by dbus_connection_set_max_message_size().
6151 * @param connection the connection
6152 * @returns the max size of a single message
6155 dbus_connection_get_max_message_size (DBusConnection *connection)
6159 _dbus_return_val_if_fail (connection != NULL, 0);
6161 CONNECTION_LOCK (connection);
6162 res = _dbus_transport_get_max_message_size (connection->transport);
6163 CONNECTION_UNLOCK (connection);
6168 * Specifies the maximum number of unix fds a message on this
6169 * connection is allowed to receive. Messages with more unix fds will
6170 * result in disconnecting the connection.
6172 * @param connection a #DBusConnection
6173 * @param n maximum message unix fds the connection can receive
6176 dbus_connection_set_max_message_unix_fds (DBusConnection *connection,
6179 _dbus_return_if_fail (connection != NULL);
6181 CONNECTION_LOCK (connection);
6182 _dbus_transport_set_max_message_unix_fds (connection->transport,
6184 CONNECTION_UNLOCK (connection);
6188 * Gets the value set by dbus_connection_set_max_message_unix_fds().
6190 * @param connection the connection
6191 * @returns the max numer of unix fds of a single message
6194 dbus_connection_get_max_message_unix_fds (DBusConnection *connection)
6198 _dbus_return_val_if_fail (connection != NULL, 0);
6200 CONNECTION_LOCK (connection);
6201 res = _dbus_transport_get_max_message_unix_fds (connection->transport);
6202 CONNECTION_UNLOCK (connection);
6207 * Sets the maximum total number of bytes that can be used for all messages
6208 * received on this connection. Messages count toward the maximum until
6209 * they are finalized. When the maximum is reached, the connection will
6210 * not read more data until some messages are finalized.
6212 * The semantics of the maximum are: if outstanding messages are
6213 * already above the maximum, additional messages will not be read.
6214 * The semantics are not: if the next message would cause us to exceed
6215 * the maximum, we don't read it. The reason is that we don't know the
6216 * size of a message until after we read it.
6218 * Thus, the max live messages size can actually be exceeded
6219 * by up to the maximum size of a single message.
6221 * Also, if we read say 1024 bytes off the wire in a single read(),
6222 * and that contains a half-dozen small messages, we may exceed the
6223 * size max by that amount. But this should be inconsequential.
6225 * This does imply that we can't call read() with a buffer larger
6226 * than we're willing to exceed this limit by.
6228 * @param connection the connection
6229 * @param size the maximum size in bytes of all outstanding messages
6232 dbus_connection_set_max_received_size (DBusConnection *connection,
6235 _dbus_return_if_fail (connection != NULL);
6237 CONNECTION_LOCK (connection);
6238 _dbus_transport_set_max_received_size (connection->transport,
6240 CONNECTION_UNLOCK (connection);
6244 * Gets the value set by dbus_connection_set_max_received_size().
6246 * @param connection the connection
6247 * @returns the max size of all live messages
6250 dbus_connection_get_max_received_size (DBusConnection *connection)
6254 _dbus_return_val_if_fail (connection != NULL, 0);
6256 CONNECTION_LOCK (connection);
6257 res = _dbus_transport_get_max_received_size (connection->transport);
6258 CONNECTION_UNLOCK (connection);
6263 * Sets the maximum total number of unix fds that can be used for all messages
6264 * received on this connection. Messages count toward the maximum until
6265 * they are finalized. When the maximum is reached, the connection will
6266 * not read more data until some messages are finalized.
6268 * The semantics are analogous to those of dbus_connection_set_max_received_size().
6270 * @param connection the connection
6271 * @param n the maximum size in bytes of all outstanding messages
6274 dbus_connection_set_max_received_unix_fds (DBusConnection *connection,
6277 _dbus_return_if_fail (connection != NULL);
6279 CONNECTION_LOCK (connection);
6280 _dbus_transport_set_max_received_unix_fds (connection->transport,
6282 CONNECTION_UNLOCK (connection);
6286 * Gets the value set by dbus_connection_set_max_received_unix_fds().
6288 * @param connection the connection
6289 * @returns the max unix fds of all live messages
6292 dbus_connection_get_max_received_unix_fds (DBusConnection *connection)
6296 _dbus_return_val_if_fail (connection != NULL, 0);
6298 CONNECTION_LOCK (connection);
6299 res = _dbus_transport_get_max_received_unix_fds (connection->transport);
6300 CONNECTION_UNLOCK (connection);
6305 * Gets the approximate size in bytes of all messages in the outgoing
6306 * message queue. The size is approximate in that you shouldn't use
6307 * it to decide how many bytes to read off the network or anything
6308 * of that nature, as optimizations may choose to tell small white lies
6309 * to avoid performance overhead.
6311 * @param connection the connection
6312 * @returns the number of bytes that have been queued up but not sent
6315 dbus_connection_get_outgoing_size (DBusConnection *connection)
6319 _dbus_return_val_if_fail (connection != NULL, 0);
6321 CONNECTION_LOCK (connection);
6322 res = _dbus_counter_get_size_value (connection->outgoing_counter);
6323 CONNECTION_UNLOCK (connection);
6327 #ifdef DBUS_ENABLE_STATS
6329 _dbus_connection_get_stats (DBusConnection *connection,
6330 dbus_uint32_t *in_messages,
6331 dbus_uint32_t *in_bytes,
6332 dbus_uint32_t *in_fds,
6333 dbus_uint32_t *in_peak_bytes,
6334 dbus_uint32_t *in_peak_fds,
6335 dbus_uint32_t *out_messages,
6336 dbus_uint32_t *out_bytes,
6337 dbus_uint32_t *out_fds,
6338 dbus_uint32_t *out_peak_bytes,
6339 dbus_uint32_t *out_peak_fds)
6341 CONNECTION_LOCK (connection);
6343 if (in_messages != NULL)
6344 *in_messages = connection->n_incoming;
6346 _dbus_transport_get_stats (connection->transport,
6347 in_bytes, in_fds, in_peak_bytes, in_peak_fds);
6349 if (out_messages != NULL)
6350 *out_messages = connection->n_outgoing;
6352 if (out_bytes != NULL)
6353 *out_bytes = _dbus_counter_get_size_value (connection->outgoing_counter);
6355 if (out_fds != NULL)
6356 *out_fds = _dbus_counter_get_unix_fd_value (connection->outgoing_counter);
6358 if (out_peak_bytes != NULL)
6359 *out_peak_bytes = _dbus_counter_get_peak_size_value (connection->outgoing_counter);
6361 if (out_peak_fds != NULL)
6362 *out_peak_fds = _dbus_counter_get_peak_unix_fd_value (connection->outgoing_counter);
6364 CONNECTION_UNLOCK (connection);
6366 #endif /* DBUS_ENABLE_STATS */
6369 * Gets the approximate number of uni fds of all messages in the
6370 * outgoing message queue.
6372 * @param connection the connection
6373 * @returns the number of unix fds that have been queued up but not sent
6376 dbus_connection_get_outgoing_unix_fds (DBusConnection *connection)
6380 _dbus_return_val_if_fail (connection != NULL, 0);
6382 CONNECTION_LOCK (connection);
6383 res = _dbus_counter_get_unix_fd_value (connection->outgoing_counter);
6384 CONNECTION_UNLOCK (connection);
6389 * Returns the address of the transport object of this connection
6391 * @param connection the connection
6392 * @returns the address string
6395 _dbus_connection_get_address (DBusConnection *connection)
6397 return _dbus_transport_get_address (connection->transport);
6400 #ifdef ENABLE_KDBUS_TRANSPORT
6402 dbus_connection_get_transport(DBusConnection *connection)
6404 _dbus_return_val_if_fail (connection != NULL, NULL);
6406 return connection->transport;