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.
6 * Licensed under the Academic Free License version 2.1
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 #include "dbus-shared.h"
26 #include "dbus-connection.h"
27 #include "dbus-list.h"
28 #include "dbus-timeout.h"
29 #include "dbus-transport.h"
30 #include "dbus-watch.h"
31 #include "dbus-connection-internal.h"
32 #include "dbus-pending-call-internal.h"
33 #include "dbus-list.h"
34 #include "dbus-hash.h"
35 #include "dbus-message-internal.h"
36 #include "dbus-message-private.h"
37 #include "dbus-threads.h"
38 #include "dbus-protocol.h"
39 #include "dbus-dataslot.h"
40 #include "dbus-string.h"
41 #include "dbus-signature.h"
42 #include "dbus-pending-call.h"
43 #include "dbus-object-tree.h"
44 #include "dbus-threads-internal.h"
46 #include "dbus-marshal-basic.h"
47 #include "dbus-transport-kdbus.h"
50 #ifdef DBUS_DISABLE_CHECKS
51 #define TOOK_LOCK_CHECK(connection)
52 #define RELEASING_LOCK_CHECK(connection)
53 #define HAVE_LOCK_CHECK(connection)
55 #define TOOK_LOCK_CHECK(connection) do { \
56 _dbus_assert (!(connection)->have_connection_lock); \
57 (connection)->have_connection_lock = TRUE; \
59 #define RELEASING_LOCK_CHECK(connection) do { \
60 _dbus_assert ((connection)->have_connection_lock); \
61 (connection)->have_connection_lock = FALSE; \
63 #define HAVE_LOCK_CHECK(connection) _dbus_assert ((connection)->have_connection_lock)
64 /* A "DO_NOT_HAVE_LOCK_CHECK" is impossible since we need the lock to check the flag */
69 #define CONNECTION_LOCK(connection) do { \
70 if (TRACE_LOCKS) { _dbus_verbose ("LOCK\n"); } \
71 _dbus_rmutex_lock ((connection)->mutex); \
72 TOOK_LOCK_CHECK (connection); \
75 #define CONNECTION_UNLOCK(connection) _dbus_connection_unlock (connection)
77 #define SLOTS_LOCK(connection) do { \
78 _dbus_rmutex_lock ((connection)->slot_mutex); \
81 #define SLOTS_UNLOCK(connection) do { \
82 _dbus_rmutex_unlock ((connection)->slot_mutex); \
85 #define DISPATCH_STATUS_NAME(s) \
86 ((s) == DBUS_DISPATCH_COMPLETE ? "complete" : \
87 (s) == DBUS_DISPATCH_DATA_REMAINS ? "data remains" : \
88 (s) == DBUS_DISPATCH_NEED_MEMORY ? "need memory" : \
92 * @defgroup DBusConnection DBusConnection
94 * @brief Connection to another application
96 * A DBusConnection represents a connection to another
97 * application. Messages can be sent and received via this connection.
98 * The other application may be a message bus; for convenience, the
99 * function dbus_bus_get() is provided to automatically open a
100 * connection to the well-known message buses.
102 * In brief a DBusConnection is a message queue associated with some
103 * message transport mechanism such as a socket. The connection
104 * maintains a queue of incoming messages and a queue of outgoing
107 * Several functions use the following terms:
109 * <li><b>read</b> means to fill the incoming message queue by reading from the socket</li>
110 * <li><b>write</b> means to drain the outgoing queue by writing to the socket</li>
111 * <li><b>dispatch</b> means to drain the incoming queue by invoking application-provided message handlers</li>
114 * The function dbus_connection_read_write_dispatch() for example does all
115 * three of these things, offering a simple alternative to a main loop.
117 * In an application with a main loop, the read/write/dispatch
118 * operations are usually separate.
120 * The connection provides #DBusWatch and #DBusTimeout objects to
121 * the main loop. These are used to know when reading, writing, or
122 * dispatching should be performed.
124 * Incoming messages are processed
125 * by calling dbus_connection_dispatch(). dbus_connection_dispatch()
126 * runs any handlers registered for the topmost message in the message
127 * queue, then discards the message, then returns.
129 * dbus_connection_get_dispatch_status() indicates whether
130 * messages are currently in the queue that need dispatching.
131 * dbus_connection_set_dispatch_status_function() allows
132 * you to set a function to be used to monitor the dispatch status.
134 * If you're using GLib or Qt add-on libraries for D-Bus, there are
135 * special convenience APIs in those libraries that hide
136 * all the details of dispatch and watch/timeout monitoring.
137 * For example, dbus_connection_setup_with_g_main().
139 * If you aren't using these add-on libraries, but want to process
140 * messages asynchronously, you must manually call
141 * dbus_connection_set_dispatch_status_function(),
142 * dbus_connection_set_watch_functions(),
143 * dbus_connection_set_timeout_functions() providing appropriate
144 * functions to integrate the connection with your application's main
145 * loop. This can be tricky to get right; main loops are not simple.
147 * If you don't need to be asynchronous, you can ignore #DBusWatch,
148 * #DBusTimeout, and dbus_connection_dispatch(). Instead,
149 * dbus_connection_read_write_dispatch() can be used.
151 * Or, in <em>very</em> simple applications,
152 * dbus_connection_pop_message() may be all you need, allowing you to
153 * avoid setting up any handler functions (see
154 * dbus_connection_add_filter(),
155 * dbus_connection_register_object_path() for more on handlers).
157 * When you use dbus_connection_send() or one of its variants to send
158 * a message, the message is added to the outgoing queue. It's
159 * actually written to the network later; either in
160 * dbus_watch_handle() invoked by your main loop, or in
161 * dbus_connection_flush() which blocks until it can write out the
162 * entire outgoing queue. The GLib/Qt add-on libraries again
163 * handle the details here for you by setting up watch functions.
165 * When a connection is disconnected, you are guaranteed to get a
166 * signal "Disconnected" from the interface
167 * #DBUS_INTERFACE_LOCAL, path
170 * You may not drop the last reference to a #DBusConnection
171 * until that connection has been disconnected.
173 * You may dispatch the unprocessed incoming message queue even if the
174 * connection is disconnected. However, "Disconnected" will always be
175 * the last message in the queue (obviously no messages are received
176 * after disconnection).
178 * After calling dbus_threads_init(), #DBusConnection has thread
179 * locks and drops them when invoking user callbacks, so in general is
180 * transparently threadsafe. However, #DBusMessage does NOT have
181 * thread locks; you must not send the same message to multiple
182 * #DBusConnection if those connections will be used from different threads,
185 * Also, if you dispatch or pop messages from multiple threads, it
186 * may work in the sense that it won't crash, but it's tough to imagine
187 * sane results; it will be completely unpredictable which messages
188 * go to which threads.
190 * It's recommended to dispatch from a single thread.
192 * The most useful function to call from multiple threads at once
193 * is dbus_connection_send_with_reply_and_block(). That is,
194 * multiple threads can make method calls at the same time.
196 * If you aren't using threads, you can use a main loop and
197 * dbus_pending_call_set_notify() to achieve a similar result.
201 * @defgroup DBusConnectionInternals DBusConnection implementation details
202 * @ingroup DBusInternals
203 * @brief Implementation details of DBusConnection
209 _dbus_connection_trace_ref (DBusConnection *connection,
214 #ifdef DBUS_ENABLE_VERBOSE_MODE
215 static int enabled = -1;
217 _dbus_trace_ref ("DBusConnection", connection, old_refcount, new_refcount,
218 why, "DBUS_CONNECTION_TRACE", &enabled);
223 * Internal struct representing a message filter function
225 typedef struct DBusMessageFilter DBusMessageFilter;
228 * Internal struct representing a message filter function
230 struct DBusMessageFilter
232 DBusAtomic refcount; /**< Reference count */
233 DBusHandleMessageFunction function; /**< Function to call to filter */
234 void *user_data; /**< User data for the function */
235 DBusFreeFunction free_user_data_function; /**< Function to free the user data */
240 * Internals of DBusPreallocatedSend
242 struct DBusPreallocatedSend
244 DBusConnection *connection; /**< Connection we'd send the message to */
245 DBusList *queue_link; /**< Preallocated link in the queue */
246 DBusList *counter_link; /**< Preallocated link in the resource counter */
249 #if HAVE_DECL_MSG_NOSIGNAL
250 static dbus_bool_t _dbus_modify_sigpipe = FALSE;
252 static dbus_bool_t _dbus_modify_sigpipe = TRUE;
256 * Implementation details of DBusConnection. All fields are private.
258 struct DBusConnection
260 DBusAtomic refcount; /**< Reference count. */
262 DBusRMutex *mutex; /**< Lock on the entire DBusConnection */
264 DBusCMutex *dispatch_mutex; /**< Protects dispatch_acquired */
265 DBusCondVar *dispatch_cond; /**< Notify when dispatch_acquired is available */
266 DBusCMutex *io_path_mutex; /**< Protects io_path_acquired */
267 DBusCondVar *io_path_cond; /**< Notify when io_path_acquired is available */
269 DBusList *outgoing_messages; /**< Queue of messages we need to send, send the end of the list first. */
270 DBusList *incoming_messages; /**< Queue of messages we have received, end of the list received most recently. */
271 DBusList *expired_messages; /**< Messages that will be released when we next unlock. */
273 DBusMessage *message_borrowed; /**< Filled in if the first incoming message has been borrowed;
274 * dispatch_acquired will be set by the borrower
277 int n_outgoing; /**< Length of outgoing queue. */
278 int n_incoming; /**< Length of incoming queue. */
280 DBusCounter *outgoing_counter; /**< Counts size of outgoing messages. */
282 DBusTransport *transport; /**< Object that sends/receives messages over network. */
283 DBusWatchList *watches; /**< Stores active watches. */
284 DBusTimeoutList *timeouts; /**< Stores active timeouts. */
286 DBusList *filter_list; /**< List of filters. */
288 DBusRMutex *slot_mutex; /**< Lock on slot_list so overall connection lock need not be taken */
289 DBusDataSlotList slot_list; /**< Data stored by allocated integer ID */
291 DBusHashTable *pending_replies; /**< Hash of message serials to #DBusPendingCall. */
293 dbus_uint32_t client_serial; /**< Client serial. Increments each time a message is sent */
294 DBusList *disconnect_message_link; /**< Preallocated list node for queueing the disconnection message */
296 DBusWakeupMainFunction wakeup_main_function; /**< Function to wake up the mainloop */
297 void *wakeup_main_data; /**< Application data for wakeup_main_function */
298 DBusFreeFunction free_wakeup_main_data; /**< free wakeup_main_data */
300 DBusDispatchStatusFunction dispatch_status_function; /**< Function on dispatch status changes */
301 void *dispatch_status_data; /**< Application data for dispatch_status_function */
302 DBusFreeFunction free_dispatch_status_data; /**< free dispatch_status_data */
304 DBusDispatchStatus last_dispatch_status; /**< The last dispatch status we reported to the application. */
306 DBusObjectTree *objects; /**< Object path handlers registered with this connection */
308 char *server_guid; /**< GUID of server if we are in shared_connections, #NULL if server GUID is unknown or connection is private */
310 /* These two MUST be bools and not bitfields, because they are protected by a separate lock
311 * from connection->mutex and all bitfields in a word have to be read/written together.
312 * So you can't have a different lock for different bitfields in the same word.
314 dbus_bool_t dispatch_acquired; /**< Someone has dispatch path (can drain incoming queue) */
315 dbus_bool_t io_path_acquired; /**< Someone has transport io path (can use the transport to read/write messages) */
317 unsigned int shareable : 1; /**< #TRUE if libdbus owns a reference to the connection and can return it from dbus_connection_open() more than once */
319 unsigned int exit_on_disconnect : 1; /**< If #TRUE, exit after handling disconnect signal */
321 unsigned int route_peer_messages : 1; /**< If #TRUE, if org.freedesktop.DBus.Peer messages have a bus name, don't handle them automatically */
323 unsigned int disconnected_message_arrived : 1; /**< We popped or are dispatching the disconnected message.
324 * if the disconnect_message_link is NULL then we queued it, but
325 * this flag is whether it got to the head of the queue.
327 unsigned int disconnected_message_processed : 1; /**< We did our default handling of the disconnected message,
328 * such as closing the connection.
331 #ifndef DBUS_DISABLE_CHECKS
332 unsigned int have_connection_lock : 1; /**< Used to check locking */
335 #if defined(DBUS_ENABLE_CHECKS) || defined(DBUS_ENABLE_ASSERT)
336 int generation; /**< _dbus_current_generation that should correspond to this connection */
338 unsigned int is_kdbus; /* Samsung change: to spare comparing address too often. 0 - uninitialized, 1 - not kdbus, 2 - kdbus */
339 char* sender; /* Samsung change: to spare building sender name for each message sent */
342 static DBusDispatchStatus _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection);
343 static void _dbus_connection_update_dispatch_status_and_unlock (DBusConnection *connection,
344 DBusDispatchStatus new_status);
345 static void _dbus_connection_last_unref (DBusConnection *connection);
346 static void _dbus_connection_acquire_dispatch (DBusConnection *connection);
347 static void _dbus_connection_release_dispatch (DBusConnection *connection);
348 static DBusDispatchStatus _dbus_connection_flush_unlocked (DBusConnection *connection);
349 static void _dbus_connection_close_possibly_shared_and_unlock (DBusConnection *connection);
350 static dbus_bool_t _dbus_connection_get_is_connected_unlocked (DBusConnection *connection);
351 static dbus_bool_t _dbus_connection_peek_for_reply_unlocked (DBusConnection *connection,
352 dbus_uint32_t client_serial);
354 static DBusMessageFilter *
355 _dbus_message_filter_ref (DBusMessageFilter *filter)
357 #ifdef DBUS_DISABLE_ASSERT
358 _dbus_atomic_inc (&filter->refcount);
360 dbus_int32_t old_value;
362 old_value = _dbus_atomic_inc (&filter->refcount);
363 _dbus_assert (old_value > 0);
370 _dbus_message_filter_unref (DBusMessageFilter *filter)
372 dbus_int32_t old_value;
374 old_value = _dbus_atomic_dec (&filter->refcount);
375 _dbus_assert (old_value > 0);
379 if (filter->free_user_data_function)
380 (* filter->free_user_data_function) (filter->user_data);
387 * Acquires the connection lock.
389 * @param connection the connection.
392 _dbus_connection_lock (DBusConnection *connection)
394 CONNECTION_LOCK (connection);
398 * Releases the connection lock.
400 * @param connection the connection.
403 _dbus_connection_unlock (DBusConnection *connection)
405 DBusList *expired_messages;
410 _dbus_verbose ("UNLOCK\n");
413 /* If we had messages that expired (fell off the incoming or outgoing
414 * queues) while we were locked, actually release them now */
415 expired_messages = connection->expired_messages;
416 connection->expired_messages = NULL;
418 RELEASING_LOCK_CHECK (connection);
419 _dbus_rmutex_unlock (connection->mutex);
421 for (iter = _dbus_list_pop_first_link (&expired_messages);
423 iter = _dbus_list_pop_first_link (&expired_messages))
425 DBusMessage *message = iter->data;
427 dbus_message_unref (message);
428 _dbus_list_free_link (iter);
433 * Wakes up the main loop if it is sleeping
434 * Needed if we're e.g. queueing outgoing messages
435 * on a thread while the mainloop sleeps.
437 * @param connection the connection.
440 _dbus_connection_wakeup_mainloop (DBusConnection *connection)
442 if (connection->wakeup_main_function)
443 (*connection->wakeup_main_function) (connection->wakeup_main_data);
446 #ifdef DBUS_ENABLE_EMBEDDED_TESTS
448 * Gets the locks so we can examine them
450 * @param connection the connection.
451 * @param mutex_loc return for the location of the main mutex pointer
452 * @param dispatch_mutex_loc return location of the dispatch mutex pointer
453 * @param io_path_mutex_loc return location of the io_path mutex pointer
454 * @param dispatch_cond_loc return location of the dispatch conditional
456 * @param io_path_cond_loc return location of the io_path conditional
460 _dbus_connection_test_get_locks (DBusConnection *connection,
461 DBusMutex **mutex_loc,
462 DBusMutex **dispatch_mutex_loc,
463 DBusMutex **io_path_mutex_loc,
464 DBusCondVar **dispatch_cond_loc,
465 DBusCondVar **io_path_cond_loc)
467 *mutex_loc = (DBusMutex *) connection->mutex;
468 *dispatch_mutex_loc = (DBusMutex *) connection->dispatch_mutex;
469 *io_path_mutex_loc = (DBusMutex *) connection->io_path_mutex;
470 *dispatch_cond_loc = connection->dispatch_cond;
471 *io_path_cond_loc = connection->io_path_cond;
476 * Adds a message-containing list link to the incoming message queue,
477 * taking ownership of the link and the message's current refcount.
478 * Cannot fail due to lack of memory.
480 * @param connection the connection.
481 * @param link the message link to queue.
484 _dbus_connection_queue_received_message_link (DBusConnection *connection,
487 DBusPendingCall *pending;
488 dbus_uint32_t reply_serial;
489 DBusMessage *message;
491 _dbus_assert (_dbus_transport_peek_is_authenticated (connection->transport));
493 _dbus_list_append_link (&connection->incoming_messages,
495 message = link->data;
497 /* If this is a reply we're waiting on, remove timeout for it */
498 reply_serial = dbus_message_get_reply_serial (message);
499 if (reply_serial != 0)
501 pending = _dbus_hash_table_lookup_int (connection->pending_replies,
505 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
506 _dbus_connection_remove_timeout_unlocked (connection,
507 _dbus_pending_call_get_timeout_unlocked (pending));
509 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
515 connection->n_incoming += 1;
517 _dbus_connection_wakeup_mainloop (connection);
519 _dbus_verbose ("Message %p (%s %s %s %s '%s' reply to %u) added to incoming queue %p, %d incoming\n",
521 dbus_message_type_to_string (dbus_message_get_type (message)),
522 dbus_message_get_path (message) ?
523 dbus_message_get_path (message) :
525 dbus_message_get_interface (message) ?
526 dbus_message_get_interface (message) :
528 dbus_message_get_member (message) ?
529 dbus_message_get_member (message) :
531 dbus_message_get_signature (message),
532 dbus_message_get_reply_serial (message),
534 connection->n_incoming);
536 _dbus_message_trace_ref (message, -1, -1,
537 "_dbus_conection_queue_received_message_link");
541 * Adds a link + message to the incoming message queue.
542 * Can't fail. Takes ownership of both link and message.
544 * @param connection the connection.
545 * @param link the list node and message to queue.
549 _dbus_connection_queue_synthesized_message_link (DBusConnection *connection,
552 HAVE_LOCK_CHECK (connection);
554 _dbus_list_append_link (&connection->incoming_messages, link);
556 connection->n_incoming += 1;
558 _dbus_connection_wakeup_mainloop (connection);
560 _dbus_message_trace_ref (link->data, -1, -1,
561 "_dbus_connection_queue_synthesized_message_link");
563 _dbus_verbose ("Synthesized message %p added to incoming queue %p, %d incoming\n",
564 link->data, connection, connection->n_incoming);
569 * Checks whether there are messages in the outgoing message queue.
570 * Called with connection lock held.
572 * @param connection the connection.
573 * @returns #TRUE if the outgoing queue is non-empty.
576 _dbus_connection_has_messages_to_send_unlocked (DBusConnection *connection)
578 HAVE_LOCK_CHECK (connection);
579 return connection->outgoing_messages != NULL;
583 * Checks whether there are messages in the outgoing message queue.
584 * Use dbus_connection_flush() to block until all outgoing
585 * messages have been written to the underlying transport
586 * (such as a socket).
588 * @param connection the connection.
589 * @returns #TRUE if the outgoing queue is non-empty.
592 dbus_connection_has_messages_to_send (DBusConnection *connection)
596 _dbus_return_val_if_fail (connection != NULL, FALSE);
598 CONNECTION_LOCK (connection);
599 v = _dbus_connection_has_messages_to_send_unlocked (connection);
600 CONNECTION_UNLOCK (connection);
606 * Gets the next outgoing message. The message remains in the
607 * queue, and the caller does not own a reference to it.
609 * @param connection the connection.
610 * @returns the message to be sent.
613 _dbus_connection_get_message_to_send (DBusConnection *connection)
615 HAVE_LOCK_CHECK (connection);
617 return _dbus_list_get_last (&connection->outgoing_messages);
621 * Notifies the connection that a message has been sent, so the
622 * message can be removed from the outgoing queue.
623 * Called with the connection lock held.
625 * @param connection the connection.
626 * @param message the message that was sent.
629 _dbus_connection_message_sent_unlocked (DBusConnection *connection,
630 DBusMessage *message)
634 HAVE_LOCK_CHECK (connection);
636 /* This can be called before we even complete authentication, since
637 * it's called on disconnect to clean up the outgoing queue.
638 * It's also called as we successfully send each message.
641 link = _dbus_list_get_last_link (&connection->outgoing_messages);
642 _dbus_assert (link != NULL);
643 _dbus_assert (link->data == message);
645 _dbus_list_unlink (&connection->outgoing_messages,
647 _dbus_list_prepend_link (&connection->expired_messages, link);
649 connection->n_outgoing -= 1;
651 _dbus_verbose ("Message %p (%s %s %s %s '%s') removed from outgoing queue %p, %d left to send\n",
653 dbus_message_type_to_string (dbus_message_get_type (message)),
654 dbus_message_get_path (message) ?
655 dbus_message_get_path (message) :
657 dbus_message_get_interface (message) ?
658 dbus_message_get_interface (message) :
660 dbus_message_get_member (message) ?
661 dbus_message_get_member (message) :
663 dbus_message_get_signature (message),
664 connection, connection->n_outgoing);
666 /* It's OK that in principle we call the notify function, because for the
667 * outgoing limit, there isn't one */
668 _dbus_message_remove_counter (message, connection->outgoing_counter);
670 /* The message will actually be unreffed when we unlock */
673 /** Function to be called in protected_change_watch() with refcount held */
674 typedef dbus_bool_t (* DBusWatchAddFunction) (DBusWatchList *list,
676 /** Function to be called in protected_change_watch() with refcount held */
677 typedef void (* DBusWatchRemoveFunction) (DBusWatchList *list,
679 /** Function to be called in protected_change_watch() with refcount held */
680 typedef void (* DBusWatchToggleFunction) (DBusWatchList *list,
682 dbus_bool_t enabled);
685 protected_change_watch (DBusConnection *connection,
687 DBusWatchAddFunction add_function,
688 DBusWatchRemoveFunction remove_function,
689 DBusWatchToggleFunction toggle_function,
694 HAVE_LOCK_CHECK (connection);
696 /* The original purpose of protected_change_watch() was to hold a
697 * ref on the connection while dropping the connection lock, then
698 * calling out to the app. This was a broken hack that did not
699 * work, since the connection was in a hosed state (no WatchList
700 * field) while calling out.
702 * So for now we'll just keep the lock while calling out. This means
703 * apps are not allowed to call DBusConnection methods inside a
704 * watch function or they will deadlock.
706 * The "real fix" is to use the _and_unlock() pattern found
707 * elsewhere in the code, to defer calling out to the app until
708 * we're about to drop locks and return flow of control to the app
711 * See http://lists.freedesktop.org/archives/dbus/2007-July/thread.html#8144
714 if (connection->watches)
717 retval = (* add_function) (connection->watches, watch);
718 else if (remove_function)
721 (* remove_function) (connection->watches, watch);
726 (* toggle_function) (connection->watches, watch, enabled);
736 * Adds a watch using the connection's DBusAddWatchFunction if
737 * available. Otherwise records the watch to be added when said
738 * function is available. Also re-adds the watch if the
739 * DBusAddWatchFunction changes. May fail due to lack of memory.
740 * Connection lock should be held when calling this.
742 * @param connection the connection.
743 * @param watch the watch to add.
744 * @returns #TRUE on success.
747 _dbus_connection_add_watch_unlocked (DBusConnection *connection,
750 return protected_change_watch (connection, watch,
751 _dbus_watch_list_add_watch,
756 * Removes a watch using the connection's DBusRemoveWatchFunction
757 * if available. It's an error to call this function on a watch
758 * that was not previously added.
759 * Connection lock should be held when calling this.
761 * @param connection the connection.
762 * @param watch the watch to remove.
765 _dbus_connection_remove_watch_unlocked (DBusConnection *connection,
768 protected_change_watch (connection, watch,
770 _dbus_watch_list_remove_watch,
775 * Toggles a watch and notifies app via connection's
776 * DBusWatchToggledFunction if available. It's an error to call this
777 * function on a watch that was not previously added.
778 * Connection lock should be held when calling this.
780 * @param connection the connection.
781 * @param watch the watch to toggle.
782 * @param enabled whether to enable or disable
785 _dbus_connection_toggle_watch_unlocked (DBusConnection *connection,
789 _dbus_assert (watch != NULL);
791 protected_change_watch (connection, watch,
793 _dbus_watch_list_toggle_watch,
797 /** Function to be called in protected_change_timeout() with refcount held */
798 typedef dbus_bool_t (* DBusTimeoutAddFunction) (DBusTimeoutList *list,
799 DBusTimeout *timeout);
800 /** Function to be called in protected_change_timeout() with refcount held */
801 typedef void (* DBusTimeoutRemoveFunction) (DBusTimeoutList *list,
802 DBusTimeout *timeout);
803 /** Function to be called in protected_change_timeout() with refcount held */
804 typedef void (* DBusTimeoutToggleFunction) (DBusTimeoutList *list,
805 DBusTimeout *timeout,
806 dbus_bool_t enabled);
809 protected_change_timeout (DBusConnection *connection,
810 DBusTimeout *timeout,
811 DBusTimeoutAddFunction add_function,
812 DBusTimeoutRemoveFunction remove_function,
813 DBusTimeoutToggleFunction toggle_function,
818 HAVE_LOCK_CHECK (connection);
820 /* The original purpose of protected_change_timeout() was to hold a
821 * ref on the connection while dropping the connection lock, then
822 * calling out to the app. This was a broken hack that did not
823 * work, since the connection was in a hosed state (no TimeoutList
824 * field) while calling out.
826 * So for now we'll just keep the lock while calling out. This means
827 * apps are not allowed to call DBusConnection methods inside a
828 * timeout function or they will deadlock.
830 * The "real fix" is to use the _and_unlock() pattern found
831 * elsewhere in the code, to defer calling out to the app until
832 * we're about to drop locks and return flow of control to the app
835 * See http://lists.freedesktop.org/archives/dbus/2007-July/thread.html#8144
838 if (connection->timeouts)
841 retval = (* add_function) (connection->timeouts, timeout);
842 else if (remove_function)
845 (* remove_function) (connection->timeouts, timeout);
850 (* toggle_function) (connection->timeouts, timeout, enabled);
859 * Adds a timeout using the connection's DBusAddTimeoutFunction if
860 * available. Otherwise records the timeout to be added when said
861 * function is available. Also re-adds the timeout if the
862 * DBusAddTimeoutFunction changes. May fail due to lack of memory.
863 * The timeout will fire repeatedly until removed.
864 * Connection lock should be held when calling this.
866 * @param connection the connection.
867 * @param timeout the timeout to add.
868 * @returns #TRUE on success.
871 _dbus_connection_add_timeout_unlocked (DBusConnection *connection,
872 DBusTimeout *timeout)
874 return protected_change_timeout (connection, timeout,
875 _dbus_timeout_list_add_timeout,
880 * Removes a timeout using the connection's DBusRemoveTimeoutFunction
881 * if available. It's an error to call this function on a timeout
882 * that was not previously added.
883 * Connection lock should be held when calling this.
885 * @param connection the connection.
886 * @param timeout the timeout to remove.
889 _dbus_connection_remove_timeout_unlocked (DBusConnection *connection,
890 DBusTimeout *timeout)
892 protected_change_timeout (connection, timeout,
894 _dbus_timeout_list_remove_timeout,
899 * Toggles a timeout and notifies app via connection's
900 * DBusTimeoutToggledFunction if available. It's an error to call this
901 * function on a timeout that was not previously added.
902 * Connection lock should be held when calling this.
904 * @param connection the connection.
905 * @param timeout the timeout to toggle.
906 * @param enabled whether to enable or disable
909 _dbus_connection_toggle_timeout_unlocked (DBusConnection *connection,
910 DBusTimeout *timeout,
913 protected_change_timeout (connection, timeout,
915 _dbus_timeout_list_toggle_timeout,
920 _dbus_connection_attach_pending_call_unlocked (DBusConnection *connection,
921 DBusPendingCall *pending)
923 dbus_uint32_t reply_serial;
924 DBusTimeout *timeout;
926 HAVE_LOCK_CHECK (connection);
928 reply_serial = _dbus_pending_call_get_reply_serial_unlocked (pending);
930 _dbus_assert (reply_serial != 0);
932 timeout = _dbus_pending_call_get_timeout_unlocked (pending);
936 if (!_dbus_connection_add_timeout_unlocked (connection, timeout))
939 if (!_dbus_hash_table_insert_int (connection->pending_replies,
943 _dbus_connection_remove_timeout_unlocked (connection, timeout);
945 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
946 HAVE_LOCK_CHECK (connection);
950 _dbus_pending_call_set_timeout_added_unlocked (pending, TRUE);
954 if (!_dbus_hash_table_insert_int (connection->pending_replies,
958 HAVE_LOCK_CHECK (connection);
963 _dbus_pending_call_ref_unlocked (pending);
965 HAVE_LOCK_CHECK (connection);
971 free_pending_call_on_hash_removal (void *data)
973 DBusPendingCall *pending;
974 DBusConnection *connection;
981 connection = _dbus_pending_call_get_connection_unlocked (pending);
983 HAVE_LOCK_CHECK (connection);
985 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
987 _dbus_connection_remove_timeout_unlocked (connection,
988 _dbus_pending_call_get_timeout_unlocked (pending));
990 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
993 /* FIXME 1.0? this is sort of dangerous and undesirable to drop the lock
994 * here, but the pending call finalizer could in principle call out to
995 * application code so we pretty much have to... some larger code reorg
998 _dbus_connection_ref_unlocked (connection);
999 _dbus_pending_call_unref_and_unlock (pending);
1000 CONNECTION_LOCK (connection);
1001 _dbus_connection_unref_unlocked (connection);
1005 _dbus_connection_detach_pending_call_unlocked (DBusConnection *connection,
1006 DBusPendingCall *pending)
1008 /* This ends up unlocking to call the pending call finalizer, which is unexpected to
1011 _dbus_hash_table_remove_int (connection->pending_replies,
1012 _dbus_pending_call_get_reply_serial_unlocked (pending));
1016 _dbus_connection_detach_pending_call_and_unlock (DBusConnection *connection,
1017 DBusPendingCall *pending)
1019 /* The idea here is to avoid finalizing the pending call
1020 * with the lock held, since there's a destroy notifier
1021 * in pending call that goes out to application code.
1023 * There's an extra unlock inside the hash table
1024 * "free pending call" function FIXME...
1026 _dbus_pending_call_ref_unlocked (pending);
1027 _dbus_hash_table_remove_int (connection->pending_replies,
1028 _dbus_pending_call_get_reply_serial_unlocked (pending));
1030 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
1031 _dbus_connection_remove_timeout_unlocked (connection,
1032 _dbus_pending_call_get_timeout_unlocked (pending));
1034 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
1036 _dbus_pending_call_unref_and_unlock (pending);
1040 * Removes a pending call from the connection, such that
1041 * the pending reply will be ignored. May drop the last
1042 * reference to the pending call.
1044 * @param connection the connection
1045 * @param pending the pending call
1048 _dbus_connection_remove_pending_call (DBusConnection *connection,
1049 DBusPendingCall *pending)
1051 CONNECTION_LOCK (connection);
1052 _dbus_connection_detach_pending_call_and_unlock (connection, pending);
1056 * Acquire the transporter I/O path. This must be done before
1057 * doing any I/O in the transporter. May sleep and drop the
1058 * IO path mutex while waiting for the I/O path.
1060 * @param connection the connection.
1061 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
1062 * @returns TRUE if the I/O path was acquired.
1065 _dbus_connection_acquire_io_path (DBusConnection *connection,
1066 int timeout_milliseconds)
1068 dbus_bool_t we_acquired;
1070 HAVE_LOCK_CHECK (connection);
1072 /* We don't want the connection to vanish */
1073 _dbus_connection_ref_unlocked (connection);
1075 /* We will only touch io_path_acquired which is protected by our mutex */
1076 CONNECTION_UNLOCK (connection);
1078 _dbus_verbose ("locking io_path_mutex\n");
1079 _dbus_cmutex_lock (connection->io_path_mutex);
1081 _dbus_verbose ("start connection->io_path_acquired = %d timeout = %d\n",
1082 connection->io_path_acquired, timeout_milliseconds);
1084 we_acquired = FALSE;
1086 if (connection->io_path_acquired)
1088 if (timeout_milliseconds != -1)
1090 _dbus_verbose ("waiting %d for IO path to be acquirable\n",
1091 timeout_milliseconds);
1093 if (!_dbus_condvar_wait_timeout (connection->io_path_cond,
1094 connection->io_path_mutex,
1095 timeout_milliseconds))
1097 /* We timed out before anyone signaled. */
1098 /* (writing the loop to handle the !timedout case by
1099 * waiting longer if needed is a pain since dbus
1100 * wraps pthread_cond_timedwait to take a relative
1101 * time instead of absolute, something kind of stupid
1102 * on our part. for now it doesn't matter, we will just
1103 * end up back here eventually.)
1109 while (connection->io_path_acquired)
1111 _dbus_verbose ("waiting for IO path to be acquirable\n");
1112 _dbus_condvar_wait (connection->io_path_cond,
1113 connection->io_path_mutex);
1118 if (!connection->io_path_acquired)
1121 connection->io_path_acquired = TRUE;
1124 _dbus_verbose ("end connection->io_path_acquired = %d we_acquired = %d\n",
1125 connection->io_path_acquired, we_acquired);
1127 _dbus_verbose ("unlocking io_path_mutex\n");
1128 _dbus_cmutex_unlock (connection->io_path_mutex);
1130 CONNECTION_LOCK (connection);
1132 HAVE_LOCK_CHECK (connection);
1134 _dbus_connection_unref_unlocked (connection);
1140 * Release the I/O path when you're done with it. Only call
1141 * after you've acquired the I/O. Wakes up at most one thread
1142 * currently waiting to acquire the I/O path.
1144 * @param connection the connection.
1147 _dbus_connection_release_io_path (DBusConnection *connection)
1149 HAVE_LOCK_CHECK (connection);
1151 _dbus_verbose ("locking io_path_mutex\n");
1152 _dbus_cmutex_lock (connection->io_path_mutex);
1154 _dbus_assert (connection->io_path_acquired);
1156 _dbus_verbose ("start connection->io_path_acquired = %d\n",
1157 connection->io_path_acquired);
1159 connection->io_path_acquired = FALSE;
1160 _dbus_condvar_wake_one (connection->io_path_cond);
1162 _dbus_verbose ("unlocking io_path_mutex\n");
1163 _dbus_cmutex_unlock (connection->io_path_mutex);
1167 * Queues incoming messages and sends outgoing messages for this
1168 * connection, optionally blocking in the process. Each call to
1169 * _dbus_connection_do_iteration_unlocked() will call select() or poll() one
1170 * time and then read or write data if possible.
1172 * The purpose of this function is to be able to flush outgoing
1173 * messages or queue up incoming messages without returning
1174 * control to the application and causing reentrancy weirdness.
1176 * The flags parameter allows you to specify whether to
1177 * read incoming messages, write outgoing messages, or both,
1178 * and whether to block if no immediate action is possible.
1180 * The timeout_milliseconds parameter does nothing unless the
1181 * iteration is blocking.
1183 * If there are no outgoing messages and DBUS_ITERATION_DO_READING
1184 * wasn't specified, then it's impossible to block, even if
1185 * you specify DBUS_ITERATION_BLOCK; in that case the function
1186 * returns immediately.
1188 * If pending is not NULL then a check is made if the pending call
1189 * is completed after the io path has been required. If the call
1190 * has been completed nothing is done. This must be done since
1191 * the _dbus_connection_acquire_io_path releases the connection
1194 * Called with connection lock held.
1196 * @param connection the connection.
1197 * @param pending the pending call that should be checked or NULL
1198 * @param flags iteration flags.
1199 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
1202 _dbus_connection_do_iteration_unlocked (DBusConnection *connection,
1203 DBusPendingCall *pending,
1205 int timeout_milliseconds)
1207 _dbus_verbose ("start\n");
1209 HAVE_LOCK_CHECK (connection);
1211 if (connection->n_outgoing == 0)
1212 flags &= ~DBUS_ITERATION_DO_WRITING;
1214 if (_dbus_connection_acquire_io_path (connection,
1215 (flags & DBUS_ITERATION_BLOCK) ? timeout_milliseconds : 0))
1217 HAVE_LOCK_CHECK (connection);
1219 if ( (pending != NULL) && _dbus_pending_call_get_completed_unlocked(pending))
1221 _dbus_verbose ("pending call completed while acquiring I/O path");
1223 else if ( (pending != NULL) &&
1224 _dbus_connection_peek_for_reply_unlocked (connection,
1225 _dbus_pending_call_get_reply_serial_unlocked (pending)))
1227 _dbus_verbose ("pending call completed while acquiring I/O path (reply found in queue)");
1231 _dbus_transport_do_iteration (connection->transport,
1232 flags, timeout_milliseconds);
1235 _dbus_connection_release_io_path (connection);
1238 HAVE_LOCK_CHECK (connection);
1240 _dbus_verbose ("end\n");
1244 * Creates a new connection for the given transport. A transport
1245 * represents a message stream that uses some concrete mechanism, such
1246 * as UNIX domain sockets. May return #NULL if insufficient
1247 * memory exists to create the connection.
1249 * @param transport the transport.
1250 * @returns the new connection, or #NULL on failure.
1253 _dbus_connection_new_for_transport (DBusTransport *transport)
1255 DBusConnection *connection;
1256 DBusWatchList *watch_list;
1257 DBusTimeoutList *timeout_list;
1258 DBusHashTable *pending_replies;
1259 DBusList *disconnect_link;
1260 DBusMessage *disconnect_message;
1261 DBusCounter *outgoing_counter;
1262 DBusObjectTree *objects;
1266 pending_replies = NULL;
1267 timeout_list = NULL;
1268 disconnect_link = NULL;
1269 disconnect_message = NULL;
1270 outgoing_counter = NULL;
1273 watch_list = _dbus_watch_list_new ();
1274 if (watch_list == NULL)
1277 timeout_list = _dbus_timeout_list_new ();
1278 if (timeout_list == NULL)
1282 _dbus_hash_table_new (DBUS_HASH_INT,
1284 (DBusFreeFunction)free_pending_call_on_hash_removal);
1285 if (pending_replies == NULL)
1288 connection = dbus_new0 (DBusConnection, 1);
1289 if (connection == NULL)
1292 _dbus_rmutex_new_at_location (&connection->mutex);
1293 if (connection->mutex == NULL)
1296 _dbus_cmutex_new_at_location (&connection->io_path_mutex);
1297 if (connection->io_path_mutex == NULL)
1300 _dbus_cmutex_new_at_location (&connection->dispatch_mutex);
1301 if (connection->dispatch_mutex == NULL)
1304 _dbus_condvar_new_at_location (&connection->dispatch_cond);
1305 if (connection->dispatch_cond == NULL)
1308 _dbus_condvar_new_at_location (&connection->io_path_cond);
1309 if (connection->io_path_cond == NULL)
1312 _dbus_rmutex_new_at_location (&connection->slot_mutex);
1313 if (connection->slot_mutex == NULL)
1316 disconnect_message = dbus_message_new_signal (DBUS_PATH_LOCAL,
1317 DBUS_INTERFACE_LOCAL,
1320 if (disconnect_message == NULL)
1323 disconnect_link = _dbus_list_alloc_link (disconnect_message);
1324 if (disconnect_link == NULL)
1327 outgoing_counter = _dbus_counter_new ();
1328 if (outgoing_counter == NULL)
1331 objects = _dbus_object_tree_new (connection);
1332 if (objects == NULL)
1335 if (_dbus_modify_sigpipe)
1336 _dbus_disable_sigpipe ();
1338 /* initialized to 0: use atomic op to avoid mixing atomic and non-atomic */
1339 _dbus_atomic_inc (&connection->refcount);
1340 connection->transport = transport;
1341 connection->watches = watch_list;
1342 connection->timeouts = timeout_list;
1343 connection->pending_replies = pending_replies;
1344 connection->outgoing_counter = outgoing_counter;
1345 connection->filter_list = NULL;
1346 connection->last_dispatch_status = DBUS_DISPATCH_COMPLETE; /* so we're notified first time there's data */
1347 connection->objects = objects;
1348 connection->exit_on_disconnect = FALSE;
1349 connection->shareable = FALSE;
1350 connection->route_peer_messages = FALSE;
1351 connection->disconnected_message_arrived = FALSE;
1352 connection->disconnected_message_processed = FALSE;
1354 #if defined(DBUS_ENABLE_CHECKS) || defined(DBUS_ENABLE_ASSERT)
1355 connection->generation = _dbus_current_generation;
1358 _dbus_data_slot_list_init (&connection->slot_list);
1360 connection->client_serial = 1;
1362 connection->disconnect_message_link = disconnect_link;
1364 CONNECTION_LOCK (connection);
1366 if (!_dbus_transport_set_connection (transport, connection))
1368 CONNECTION_UNLOCK (connection);
1373 _dbus_transport_ref (transport);
1375 CONNECTION_UNLOCK (connection);
1377 _dbus_connection_trace_ref (connection, 0, 1, "new_for_transport");
1381 if (disconnect_message != NULL)
1382 dbus_message_unref (disconnect_message);
1384 if (disconnect_link != NULL)
1385 _dbus_list_free_link (disconnect_link);
1387 if (connection != NULL)
1389 _dbus_condvar_free_at_location (&connection->io_path_cond);
1390 _dbus_condvar_free_at_location (&connection->dispatch_cond);
1391 _dbus_rmutex_free_at_location (&connection->mutex);
1392 _dbus_cmutex_free_at_location (&connection->io_path_mutex);
1393 _dbus_cmutex_free_at_location (&connection->dispatch_mutex);
1394 _dbus_rmutex_free_at_location (&connection->slot_mutex);
1395 dbus_free (connection);
1397 if (pending_replies)
1398 _dbus_hash_table_unref (pending_replies);
1401 _dbus_watch_list_free (watch_list);
1404 _dbus_timeout_list_free (timeout_list);
1406 if (outgoing_counter)
1407 _dbus_counter_unref (outgoing_counter);
1410 _dbus_object_tree_unref (objects);
1416 * Increments the reference count of a DBusConnection.
1417 * Requires that the caller already holds the connection lock.
1419 * @param connection the connection.
1420 * @returns the connection.
1423 _dbus_connection_ref_unlocked (DBusConnection *connection)
1425 dbus_int32_t old_refcount;
1427 _dbus_assert (connection != NULL);
1428 _dbus_assert (connection->generation == _dbus_current_generation);
1430 HAVE_LOCK_CHECK (connection);
1432 old_refcount = _dbus_atomic_inc (&connection->refcount);
1433 _dbus_connection_trace_ref (connection, old_refcount, old_refcount + 1,
1440 * Decrements the reference count of a DBusConnection.
1441 * Requires that the caller already holds the connection lock.
1443 * @param connection the connection.
1446 _dbus_connection_unref_unlocked (DBusConnection *connection)
1448 dbus_int32_t old_refcount;
1450 HAVE_LOCK_CHECK (connection);
1452 _dbus_assert (connection != NULL);
1454 old_refcount = _dbus_atomic_dec (&connection->refcount);
1456 _dbus_connection_trace_ref (connection, old_refcount, old_refcount - 1,
1459 if (old_refcount == 1)
1460 _dbus_connection_last_unref (connection);
1463 static dbus_uint32_t
1464 _dbus_connection_get_next_client_serial (DBusConnection *connection)
1466 dbus_uint32_t serial;
1468 serial = connection->client_serial++;
1470 if (connection->client_serial == 0)
1471 connection->client_serial = 1;
1477 * A callback for use with dbus_watch_new() to create a DBusWatch.
1479 * @todo This is basically a hack - we could delete _dbus_transport_handle_watch()
1480 * and the virtual handle_watch in DBusTransport if we got rid of it.
1481 * The reason this is some work is threading, see the _dbus_connection_handle_watch()
1484 * @param watch the watch.
1485 * @param condition the current condition of the file descriptors being watched.
1486 * @param data must be a pointer to a #DBusConnection
1487 * @returns #FALSE if the IO condition may not have been fully handled due to lack of memory
1490 _dbus_connection_handle_watch (DBusWatch *watch,
1491 unsigned int condition,
1494 DBusConnection *connection;
1496 DBusDispatchStatus status;
1500 _dbus_verbose ("start\n");
1502 CONNECTION_LOCK (connection);
1504 if (!_dbus_connection_acquire_io_path (connection, 1))
1506 /* another thread is handling the message */
1507 CONNECTION_UNLOCK (connection);
1511 HAVE_LOCK_CHECK (connection);
1512 retval = _dbus_transport_handle_watch (connection->transport,
1515 _dbus_connection_release_io_path (connection);
1517 HAVE_LOCK_CHECK (connection);
1519 _dbus_verbose ("middle\n");
1521 status = _dbus_connection_get_dispatch_status_unlocked (connection);
1523 /* this calls out to user code */
1524 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1526 _dbus_verbose ("end\n");
1531 /* Protected by _DBUS_LOCK (shared_connections) */
1532 static DBusHashTable *shared_connections = NULL;
1533 static DBusList *shared_connections_no_guid = NULL;
1536 close_connection_on_shutdown (DBusConnection *connection)
1538 DBusMessage *message;
1540 dbus_connection_ref (connection);
1541 _dbus_connection_close_possibly_shared (connection);
1543 /* Churn through to the Disconnected message */
1544 while ((message = dbus_connection_pop_message (connection)))
1546 dbus_message_unref (message);
1548 dbus_connection_unref (connection);
1552 shared_connections_shutdown (void *data)
1556 if (!_DBUS_LOCK (shared_connections))
1558 /* We'd have initialized locks before adding anything, so there
1559 * can't be anything there. */
1563 /* This is a little bit unpleasant... better ideas? */
1564 while ((n_entries = _dbus_hash_table_get_n_entries (shared_connections)) > 0)
1566 DBusConnection *connection;
1569 _dbus_hash_iter_init (shared_connections, &iter);
1570 _dbus_hash_iter_next (&iter);
1572 connection = _dbus_hash_iter_get_value (&iter);
1574 _DBUS_UNLOCK (shared_connections);
1575 close_connection_on_shutdown (connection);
1576 if (!_DBUS_LOCK (shared_connections))
1577 _dbus_assert_not_reached ("global locks were already initialized");
1579 /* The connection should now be dead and not in our hash ... */
1580 _dbus_assert (_dbus_hash_table_get_n_entries (shared_connections) < n_entries);
1583 _dbus_assert (_dbus_hash_table_get_n_entries (shared_connections) == 0);
1585 _dbus_hash_table_unref (shared_connections);
1586 shared_connections = NULL;
1588 if (shared_connections_no_guid != NULL)
1590 DBusConnection *connection;
1591 connection = _dbus_list_pop_first (&shared_connections_no_guid);
1592 while (connection != NULL)
1594 _DBUS_UNLOCK (shared_connections);
1595 close_connection_on_shutdown (connection);
1596 if (!_DBUS_LOCK (shared_connections))
1597 _dbus_assert_not_reached ("global locks were already initialized");
1598 connection = _dbus_list_pop_first (&shared_connections_no_guid);
1602 shared_connections_no_guid = NULL;
1604 _DBUS_UNLOCK (shared_connections);
1608 connection_lookup_shared (DBusAddressEntry *entry,
1609 DBusConnection **result)
1611 _dbus_verbose ("checking for existing connection\n");
1615 if (!_DBUS_LOCK (shared_connections))
1617 /* If it was shared, we'd have initialized global locks when we put
1618 * it in shared_connections. */
1622 if (shared_connections == NULL)
1624 _dbus_verbose ("creating shared_connections hash table\n");
1626 shared_connections = _dbus_hash_table_new (DBUS_HASH_STRING,
1629 if (shared_connections == NULL)
1631 _DBUS_UNLOCK (shared_connections);
1635 if (!_dbus_register_shutdown_func (shared_connections_shutdown, NULL))
1637 _dbus_hash_table_unref (shared_connections);
1638 shared_connections = NULL;
1639 _DBUS_UNLOCK (shared_connections);
1643 _dbus_verbose (" successfully created shared_connections\n");
1645 _DBUS_UNLOCK (shared_connections);
1646 return TRUE; /* no point looking up in the hash we just made */
1652 guid = dbus_address_entry_get_value (entry, "guid");
1656 DBusConnection *connection;
1658 connection = _dbus_hash_table_lookup_string (shared_connections,
1663 /* The DBusConnection can't be finalized without taking
1664 * the shared_connections lock to remove it from the
1665 * hash. So it's safe to ref the connection here.
1666 * However, it may be disconnected if the Disconnected
1667 * message hasn't been processed yet, in which case we
1668 * want to pretend it isn't in the hash and avoid
1671 * The idea is to avoid ever returning a disconnected connection
1672 * from dbus_connection_open(). We could just synchronously
1673 * drop our shared ref to the connection on connection disconnect,
1674 * and then assert here that the connection is connected, but
1675 * that causes reentrancy headaches.
1677 CONNECTION_LOCK (connection);
1678 if (_dbus_connection_get_is_connected_unlocked (connection))
1680 _dbus_connection_ref_unlocked (connection);
1681 *result = connection;
1682 _dbus_verbose ("looked up existing connection to server guid %s\n",
1687 _dbus_verbose ("looked up existing connection to server guid %s but it was disconnected so ignoring it\n",
1690 CONNECTION_UNLOCK (connection);
1694 _DBUS_UNLOCK (shared_connections);
1700 connection_record_shared_unlocked (DBusConnection *connection,
1704 char *guid_in_connection;
1706 HAVE_LOCK_CHECK (connection);
1707 _dbus_assert (connection->server_guid == NULL);
1708 _dbus_assert (connection->shareable);
1710 /* get a hard ref on this connection, even if
1711 * we won't in fact store it in the hash, we still
1712 * need to hold a ref on it until it's disconnected.
1714 _dbus_connection_ref_unlocked (connection);
1718 if (!_DBUS_LOCK (shared_connections))
1721 if (!_dbus_list_prepend (&shared_connections_no_guid, connection))
1723 _DBUS_UNLOCK (shared_connections);
1727 _DBUS_UNLOCK (shared_connections);
1728 return TRUE; /* don't store in the hash */
1731 /* A separate copy of the key is required in the hash table, because
1732 * we don't have a lock on the connection when we are doing a hash
1736 guid_key = _dbus_strdup (guid);
1737 if (guid_key == NULL)
1740 guid_in_connection = _dbus_strdup (guid);
1741 if (guid_in_connection == NULL)
1743 dbus_free (guid_key);
1747 if (!_DBUS_LOCK (shared_connections))
1749 dbus_free (guid_in_connection);
1750 dbus_free (guid_key);
1754 _dbus_assert (shared_connections != NULL);
1756 if (!_dbus_hash_table_insert_string (shared_connections,
1757 guid_key, connection))
1759 dbus_free (guid_key);
1760 dbus_free (guid_in_connection);
1761 _DBUS_UNLOCK (shared_connections);
1765 connection->server_guid = guid_in_connection;
1767 _dbus_verbose ("stored connection to %s to be shared\n",
1768 connection->server_guid);
1770 _DBUS_UNLOCK (shared_connections);
1772 _dbus_assert (connection->server_guid != NULL);
1778 connection_forget_shared_unlocked (DBusConnection *connection)
1780 HAVE_LOCK_CHECK (connection);
1782 if (!connection->shareable)
1785 if (!_DBUS_LOCK (shared_connections))
1787 /* If it was shared, we'd have initialized global locks when we put
1788 * it in the table; so it can't be there. */
1792 if (connection->server_guid != NULL)
1794 _dbus_verbose ("dropping connection to %s out of the shared table\n",
1795 connection->server_guid);
1797 if (!_dbus_hash_table_remove_string (shared_connections,
1798 connection->server_guid))
1799 _dbus_assert_not_reached ("connection was not in the shared table");
1801 dbus_free (connection->server_guid);
1802 connection->server_guid = NULL;
1806 _dbus_list_remove (&shared_connections_no_guid, connection);
1809 _DBUS_UNLOCK (shared_connections);
1811 /* remove our reference held on all shareable connections */
1812 _dbus_connection_unref_unlocked (connection);
1815 static DBusConnection*
1816 connection_try_from_address_entry (DBusAddressEntry *entry,
1819 DBusTransport *transport;
1820 DBusConnection *connection;
1822 transport = _dbus_transport_open (entry, error);
1824 if (transport == NULL)
1826 _DBUS_ASSERT_ERROR_IS_SET (error);
1830 connection = _dbus_connection_new_for_transport (transport);
1832 _dbus_transport_unref (transport);
1834 if (connection == NULL)
1836 _DBUS_SET_OOM (error);
1840 #ifndef DBUS_DISABLE_CHECKS
1841 _dbus_assert (!connection->have_connection_lock);
1848 * If the shared parameter is true, then any existing connection will
1849 * be used (and if a new connection is created, it will be available
1850 * for use by others). If the shared parameter is false, a new
1851 * connection will always be created, and the new connection will
1852 * never be returned to other callers.
1854 * @param address the address
1855 * @param shared whether the connection is shared or private
1856 * @param error error return
1857 * @returns the connection or #NULL on error
1859 static DBusConnection*
1860 _dbus_connection_open_internal (const char *address,
1864 DBusConnection *connection;
1865 DBusAddressEntry **entries;
1866 DBusError tmp_error = DBUS_ERROR_INIT;
1867 DBusError first_error = DBUS_ERROR_INIT;
1870 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1872 _dbus_verbose ("opening %s connection to: %s\n",
1873 shared ? "shared" : "private", address);
1875 if (!dbus_parse_address (address, &entries, &len, error))
1878 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1882 for (i = 0; i < len; i++)
1886 if (!connection_lookup_shared (entries[i], &connection))
1887 _DBUS_SET_OOM (&tmp_error);
1890 if (connection == NULL)
1892 connection = connection_try_from_address_entry (entries[i],
1895 if (connection != NULL && shared)
1899 connection->shareable = TRUE;
1901 /* guid may be NULL */
1902 guid = dbus_address_entry_get_value (entries[i], "guid");
1904 CONNECTION_LOCK (connection);
1906 if (!connection_record_shared_unlocked (connection, guid))
1908 _DBUS_SET_OOM (&tmp_error);
1909 _dbus_connection_close_possibly_shared_and_unlock (connection);
1910 dbus_connection_unref (connection);
1914 CONNECTION_UNLOCK (connection);
1921 _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
1924 dbus_move_error (&tmp_error, &first_error);
1926 dbus_error_free (&tmp_error);
1929 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1930 _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
1932 if (connection == NULL)
1934 _DBUS_ASSERT_ERROR_IS_SET (&first_error);
1935 dbus_move_error (&first_error, error);
1938 dbus_error_free (&first_error);
1940 dbus_address_entries_free (entries);
1945 * Closes a shared OR private connection, while dbus_connection_close() can
1946 * only be used on private connections. Should only be called by the
1947 * dbus code that owns the connection - an owner must be known,
1948 * the open/close state is like malloc/free, not like ref/unref.
1950 * @param connection the connection
1953 _dbus_connection_close_possibly_shared (DBusConnection *connection)
1955 _dbus_assert (connection != NULL);
1956 _dbus_assert (connection->generation == _dbus_current_generation);
1958 CONNECTION_LOCK (connection);
1959 _dbus_connection_close_possibly_shared_and_unlock (connection);
1962 static DBusPreallocatedSend*
1963 _dbus_connection_preallocate_send_unlocked (DBusConnection *connection)
1965 DBusPreallocatedSend *preallocated;
1967 HAVE_LOCK_CHECK (connection);
1969 _dbus_assert (connection != NULL);
1971 preallocated = dbus_new (DBusPreallocatedSend, 1);
1972 if (preallocated == NULL)
1975 preallocated->queue_link = _dbus_list_alloc_link (NULL);
1976 if (preallocated->queue_link == NULL)
1979 preallocated->counter_link = _dbus_list_alloc_link (connection->outgoing_counter);
1980 if (preallocated->counter_link == NULL)
1983 _dbus_counter_ref (preallocated->counter_link->data);
1985 preallocated->connection = connection;
1987 return preallocated;
1990 _dbus_list_free_link (preallocated->queue_link);
1992 dbus_free (preallocated);
1997 void dbus_connection_set_sender(DBusConnection *connection, char *value)
1999 connection->sender = value;
2002 char* dbus_connection_get_sender(DBusConnection *connection)
2004 return connection->sender;
2007 unsigned int dbus_connection_get_is_kdbus(DBusConnection *connection)
2009 return connection->is_kdbus;
2012 void dbus_connection_set_is_kdbus(DBusConnection *connection, unsigned int value)
2014 connection->is_kdbus = value;
2017 /* Called with lock held, does not update dispatch status */
2019 _dbus_connection_send_preallocated_unlocked_no_update (DBusConnection *connection,
2020 DBusPreallocatedSend *preallocated,
2021 DBusMessage *message,
2022 dbus_uint32_t *client_serial)
2024 dbus_uint32_t serial;
2027 preallocated->queue_link->data = message;
2028 _dbus_list_prepend_link (&connection->outgoing_messages,
2029 preallocated->queue_link);
2031 /* It's OK that we'll never call the notify function, because for the
2032 * outgoing limit, there isn't one */
2033 _dbus_message_add_counter_link (message,
2034 preallocated->counter_link);
2036 dbus_free (preallocated);
2037 preallocated = NULL;
2039 dbus_message_ref (message);
2041 connection->n_outgoing += 1;
2043 _dbus_verbose ("Message %p (%s %s %s %s '%s') for %s added to outgoing queue %p, %d pending to send\n",
2045 dbus_message_type_to_string (dbus_message_get_type (message)),
2046 dbus_message_get_path (message) ?
2047 dbus_message_get_path (message) :
2049 dbus_message_get_interface (message) ?
2050 dbus_message_get_interface (message) :
2052 dbus_message_get_member (message) ?
2053 dbus_message_get_member (message) :
2055 dbus_message_get_signature (message),
2056 dbus_message_get_destination (message) ?
2057 dbus_message_get_destination (message) :
2060 connection->n_outgoing);
2062 if (dbus_message_get_serial (message) == 0)
2064 serial = _dbus_connection_get_next_client_serial (connection);
2065 dbus_message_set_serial (message, serial);
2067 *client_serial = serial;
2072 *client_serial = dbus_message_get_serial (message);
2075 _dbus_verbose ("Message %p serial is %u\n",
2076 message, dbus_message_get_serial (message));
2078 if(dbus_transport_is_kdbus(connection))
2080 sender = dbus_connection_get_sender(connection);
2081 dbus_message_set_sender(message, sender);
2084 dbus_message_lock (message);
2086 /* Now we need to run an iteration to hopefully just write the messages
2087 * out immediately, and otherwise get them queued up
2089 _dbus_connection_do_iteration_unlocked (connection,
2091 DBUS_ITERATION_DO_WRITING,
2094 /* If stuff is still queued up, be sure we wake up the main loop */
2095 if (connection->n_outgoing > 0)
2096 _dbus_connection_wakeup_mainloop (connection);
2100 _dbus_connection_send_preallocated_and_unlock (DBusConnection *connection,
2101 DBusPreallocatedSend *preallocated,
2102 DBusMessage *message,
2103 dbus_uint32_t *client_serial)
2105 DBusDispatchStatus status;
2107 HAVE_LOCK_CHECK (connection);
2109 _dbus_connection_send_preallocated_unlocked_no_update (connection,
2111 message, client_serial);
2113 _dbus_verbose ("middle\n");
2114 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2116 /* this calls out to user code */
2117 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2121 * Like dbus_connection_send(), but assumes the connection
2122 * is already locked on function entry, and unlocks before returning.
2124 * @param connection the connection
2125 * @param message the message to send
2126 * @param client_serial return location for client serial of sent message
2127 * @returns #FALSE on out-of-memory
2130 _dbus_connection_send_and_unlock (DBusConnection *connection,
2131 DBusMessage *message,
2132 dbus_uint32_t *client_serial)
2134 DBusPreallocatedSend *preallocated;
2136 _dbus_assert (connection != NULL);
2137 _dbus_assert (message != NULL);
2139 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
2140 if (preallocated == NULL)
2142 CONNECTION_UNLOCK (connection);
2146 _dbus_connection_send_preallocated_and_unlock (connection,
2154 * Used internally to handle the semantics of dbus_server_set_new_connection_function().
2155 * If the new connection function does not ref the connection, we want to close it.
2157 * A bit of a hack, probably the new connection function should have returned a value
2158 * for whether to close, or should have had to close the connection itself if it
2161 * But, this works OK as long as the new connection function doesn't do anything
2162 * crazy like keep the connection around without ref'ing it.
2164 * We have to lock the connection across refcount check and close in case
2165 * the new connection function spawns a thread that closes and unrefs.
2166 * In that case, if the app thread
2167 * closes and unrefs first, we'll harmlessly close again; if the app thread
2168 * still has the ref, we'll close and then the app will close harmlessly.
2169 * If the app unrefs without closing, the app is broken since if the
2170 * app refs from the new connection function it is supposed to also close.
2172 * If we didn't atomically check the refcount and close with the lock held
2173 * though, we could screw this up.
2175 * @param connection the connection
2178 _dbus_connection_close_if_only_one_ref (DBusConnection *connection)
2180 dbus_int32_t refcount;
2182 CONNECTION_LOCK (connection);
2184 refcount = _dbus_atomic_get (&connection->refcount);
2185 /* The caller should have at least one ref */
2186 _dbus_assert (refcount >= 1);
2189 _dbus_connection_close_possibly_shared_and_unlock (connection);
2191 CONNECTION_UNLOCK (connection);
2196 * When a function that blocks has been called with a timeout, and we
2197 * run out of memory, the time to wait for memory is based on the
2198 * timeout. If the caller was willing to block a long time we wait a
2199 * relatively long time for memory, if they were only willing to block
2200 * briefly then we retry for memory at a rapid rate.
2202 * @param timeout_milliseconds the timeout requested for blocking
2205 _dbus_memory_pause_based_on_timeout (int timeout_milliseconds)
2207 if (timeout_milliseconds == -1)
2208 _dbus_sleep_milliseconds (1000);
2209 else if (timeout_milliseconds < 100)
2210 ; /* just busy loop */
2211 else if (timeout_milliseconds <= 1000)
2212 _dbus_sleep_milliseconds (timeout_milliseconds / 3);
2214 _dbus_sleep_milliseconds (1000);
2218 generate_local_error_message (dbus_uint32_t serial,
2222 DBusMessage *message;
2223 message = dbus_message_new (DBUS_MESSAGE_TYPE_ERROR);
2227 if (!dbus_message_set_error_name (message, error_name))
2229 dbus_message_unref (message);
2234 dbus_message_set_no_reply (message, TRUE);
2236 if (!dbus_message_set_reply_serial (message,
2239 dbus_message_unref (message);
2244 if (error_msg != NULL)
2246 DBusMessageIter iter;
2248 dbus_message_iter_init_append (message, &iter);
2249 if (!dbus_message_iter_append_basic (&iter,
2253 dbus_message_unref (message);
2264 * Peek the incoming queue to see if we got reply for a specific serial
2267 _dbus_connection_peek_for_reply_unlocked (DBusConnection *connection,
2268 dbus_uint32_t client_serial)
2271 HAVE_LOCK_CHECK (connection);
2273 link = _dbus_list_get_first_link (&connection->incoming_messages);
2275 while (link != NULL)
2277 DBusMessage *reply = link->data;
2279 if (dbus_message_get_reply_serial (reply) == client_serial)
2281 _dbus_verbose ("%s reply to %d found in queue\n", _DBUS_FUNCTION_NAME, client_serial);
2284 link = _dbus_list_get_next_link (&connection->incoming_messages, link);
2290 /* This is slightly strange since we can pop a message here without
2291 * the dispatch lock.
2294 check_for_reply_unlocked (DBusConnection *connection,
2295 dbus_uint32_t client_serial)
2299 HAVE_LOCK_CHECK (connection);
2301 link = _dbus_list_get_first_link (&connection->incoming_messages);
2303 while (link != NULL)
2305 DBusMessage *reply = link->data;
2307 if (dbus_message_get_reply_serial (reply) == client_serial)
2309 _dbus_list_remove_link (&connection->incoming_messages, link);
2310 connection->n_incoming -= 1;
2313 link = _dbus_list_get_next_link (&connection->incoming_messages, link);
2320 connection_timeout_and_complete_all_pending_calls_unlocked (DBusConnection *connection)
2322 /* We can't iterate over the hash in the normal way since we'll be
2323 * dropping the lock for each item. So we restart the
2324 * iter each time as we drain the hash table.
2327 while (_dbus_hash_table_get_n_entries (connection->pending_replies) > 0)
2329 DBusPendingCall *pending;
2332 _dbus_hash_iter_init (connection->pending_replies, &iter);
2333 _dbus_hash_iter_next (&iter);
2335 pending = _dbus_hash_iter_get_value (&iter);
2336 _dbus_pending_call_ref_unlocked (pending);
2338 _dbus_pending_call_queue_timeout_error_unlocked (pending,
2341 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
2342 _dbus_connection_remove_timeout_unlocked (connection,
2343 _dbus_pending_call_get_timeout_unlocked (pending));
2344 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
2345 _dbus_hash_iter_remove_entry (&iter);
2347 _dbus_pending_call_unref_and_unlock (pending);
2348 CONNECTION_LOCK (connection);
2350 HAVE_LOCK_CHECK (connection);
2354 complete_pending_call_and_unlock (DBusConnection *connection,
2355 DBusPendingCall *pending,
2356 DBusMessage *message)
2358 _dbus_pending_call_set_reply_unlocked (pending, message);
2359 _dbus_pending_call_ref_unlocked (pending); /* in case there's no app with a ref held */
2360 _dbus_connection_detach_pending_call_and_unlock (connection, pending);
2362 /* Must be called unlocked since it invokes app callback */
2363 _dbus_pending_call_complete (pending);
2364 dbus_pending_call_unref (pending);
2368 check_for_reply_and_update_dispatch_unlocked (DBusConnection *connection,
2369 DBusPendingCall *pending)
2372 DBusDispatchStatus status;
2374 reply = check_for_reply_unlocked (connection,
2375 _dbus_pending_call_get_reply_serial_unlocked (pending));
2378 _dbus_verbose ("checked for reply\n");
2380 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): got reply\n");
2382 complete_pending_call_and_unlock (connection, pending, reply);
2383 dbus_message_unref (reply);
2385 CONNECTION_LOCK (connection);
2386 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2387 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2388 dbus_pending_call_unref (pending);
2397 * Blocks until a pending call times out or gets a reply.
2399 * Does not re-enter the main loop or run filter/path-registered
2400 * callbacks. The reply to the message will not be seen by
2403 * Returns immediately if pending call already got a reply.
2405 * @todo could use performance improvements (it keeps scanning
2406 * the whole message queue for example)
2408 * @param pending the pending call we block for a reply on
2411 _dbus_connection_block_pending_call (DBusPendingCall *pending)
2413 long start_tv_sec, start_tv_usec;
2414 long tv_sec, tv_usec;
2415 DBusDispatchStatus status;
2416 DBusConnection *connection;
2417 dbus_uint32_t client_serial;
2418 DBusTimeout *timeout;
2419 int timeout_milliseconds, elapsed_milliseconds;
2421 _dbus_assert (pending != NULL);
2423 if (dbus_pending_call_get_completed (pending))
2426 dbus_pending_call_ref (pending); /* necessary because the call could be canceled */
2428 connection = _dbus_pending_call_get_connection_and_lock (pending);
2430 /* Flush message queue - note, can affect dispatch status */
2431 _dbus_connection_flush_unlocked (connection);
2433 client_serial = _dbus_pending_call_get_reply_serial_unlocked (pending);
2435 /* note that timeout_milliseconds is limited to a smallish value
2436 * in _dbus_pending_call_new() so overflows aren't possible
2439 timeout = _dbus_pending_call_get_timeout_unlocked (pending);
2440 _dbus_get_monotonic_time (&start_tv_sec, &start_tv_usec);
2443 timeout_milliseconds = dbus_timeout_get_interval (timeout);
2445 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): will block %d milliseconds for reply serial %u from %ld sec %ld usec\n",
2446 timeout_milliseconds,
2448 start_tv_sec, start_tv_usec);
2452 timeout_milliseconds = -1;
2454 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): will block for reply serial %u\n", client_serial);
2457 /* check to see if we already got the data off the socket */
2458 /* from another blocked pending call */
2459 if (check_for_reply_and_update_dispatch_unlocked (connection, pending))
2462 /* Now we wait... */
2463 /* always block at least once as we know we don't have the reply yet */
2464 _dbus_connection_do_iteration_unlocked (connection,
2466 DBUS_ITERATION_DO_READING |
2467 DBUS_ITERATION_BLOCK,
2468 timeout_milliseconds);
2472 _dbus_verbose ("top of recheck\n");
2474 HAVE_LOCK_CHECK (connection);
2476 /* queue messages and get status */
2478 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2480 /* the get_completed() is in case a dispatch() while we were blocking
2481 * got the reply instead of us.
2483 if (_dbus_pending_call_get_completed_unlocked (pending))
2485 _dbus_verbose ("Pending call completed by dispatch\n");
2486 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2487 dbus_pending_call_unref (pending);
2491 if (status == DBUS_DISPATCH_DATA_REMAINS)
2493 if (check_for_reply_and_update_dispatch_unlocked (connection, pending))
2497 _dbus_get_monotonic_time (&tv_sec, &tv_usec);
2498 elapsed_milliseconds = (tv_sec - start_tv_sec) * 1000 +
2499 (tv_usec - start_tv_usec) / 1000;
2501 if (!_dbus_connection_get_is_connected_unlocked (connection))
2503 DBusMessage *error_msg;
2505 error_msg = generate_local_error_message (client_serial,
2506 DBUS_ERROR_DISCONNECTED,
2507 "Connection was disconnected before a reply was received");
2509 /* on OOM error_msg is set to NULL */
2510 complete_pending_call_and_unlock (connection, pending, error_msg);
2511 dbus_pending_call_unref (pending);
2514 else if (connection->disconnect_message_link == NULL)
2515 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): disconnected\n");
2516 else if (timeout == NULL)
2518 if (status == DBUS_DISPATCH_NEED_MEMORY)
2520 /* Try sleeping a bit, as we aren't sure we need to block for reading,
2521 * we may already have a reply in the buffer and just can't process
2524 _dbus_verbose ("dbus_connection_send_with_reply_and_block() waiting for more memory\n");
2526 _dbus_memory_pause_based_on_timeout (timeout_milliseconds - elapsed_milliseconds);
2530 /* block again, we don't have the reply buffered yet. */
2531 _dbus_connection_do_iteration_unlocked (connection,
2533 DBUS_ITERATION_DO_READING |
2534 DBUS_ITERATION_BLOCK,
2535 timeout_milliseconds - elapsed_milliseconds);
2538 goto recheck_status;
2540 else if (tv_sec < start_tv_sec)
2541 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): clock set backward\n");
2542 else if (elapsed_milliseconds < timeout_milliseconds)
2544 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): %d milliseconds remain\n", timeout_milliseconds - elapsed_milliseconds);
2546 if (status == DBUS_DISPATCH_NEED_MEMORY)
2548 /* Try sleeping a bit, as we aren't sure we need to block for reading,
2549 * we may already have a reply in the buffer and just can't process
2552 _dbus_verbose ("dbus_connection_send_with_reply_and_block() waiting for more memory\n");
2554 _dbus_memory_pause_based_on_timeout (timeout_milliseconds - elapsed_milliseconds);
2558 /* block again, we don't have the reply buffered yet. */
2559 _dbus_connection_do_iteration_unlocked (connection,
2561 DBUS_ITERATION_DO_READING |
2562 DBUS_ITERATION_BLOCK,
2563 timeout_milliseconds - elapsed_milliseconds);
2566 goto recheck_status;
2569 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): Waited %d milliseconds and got no reply\n",
2570 elapsed_milliseconds);
2572 _dbus_assert (!_dbus_pending_call_get_completed_unlocked (pending));
2574 /* unlock and call user code */
2575 complete_pending_call_and_unlock (connection, pending, NULL);
2577 /* update user code on dispatch status */
2578 CONNECTION_LOCK (connection);
2579 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2580 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2581 dbus_pending_call_unref (pending);
2587 * @addtogroup DBusConnection
2593 * Gets a connection to a remote address. If a connection to the given
2594 * address already exists, returns the existing connection with its
2595 * reference count incremented. Otherwise, returns a new connection
2596 * and saves the new connection for possible re-use if a future call
2597 * to dbus_connection_open() asks to connect to the same server.
2599 * Use dbus_connection_open_private() to get a dedicated connection
2600 * not shared with other callers of dbus_connection_open().
2602 * If the open fails, the function returns #NULL, and provides a
2603 * reason for the failure in the error parameter. Pass #NULL for the
2604 * error parameter if you aren't interested in the reason for
2607 * Because this connection is shared, no user of the connection
2608 * may call dbus_connection_close(). However, when you are done with the
2609 * connection you should call dbus_connection_unref().
2611 * @note Prefer dbus_connection_open() to dbus_connection_open_private()
2612 * unless you have good reason; connections are expensive enough
2613 * that it's wasteful to create lots of connections to the same
2616 * @param address the address.
2617 * @param error address where an error can be returned.
2618 * @returns new connection, or #NULL on failure.
2621 dbus_connection_open (const char *address,
2624 DBusConnection *connection;
2626 _dbus_return_val_if_fail (address != NULL, NULL);
2627 _dbus_return_val_if_error_is_set (error, NULL);
2629 connection = _dbus_connection_open_internal (address,
2637 * Opens a new, dedicated connection to a remote address. Unlike
2638 * dbus_connection_open(), always creates a new connection.
2639 * This connection will not be saved or recycled by libdbus.
2641 * If the open fails, the function returns #NULL, and provides a
2642 * reason for the failure in the error parameter. Pass #NULL for the
2643 * error parameter if you aren't interested in the reason for
2646 * When you are done with this connection, you must
2647 * dbus_connection_close() to disconnect it,
2648 * and dbus_connection_unref() to free the connection object.
2650 * (The dbus_connection_close() can be skipped if the
2651 * connection is already known to be disconnected, for example
2652 * if you are inside a handler for the Disconnected signal.)
2654 * @note Prefer dbus_connection_open() to dbus_connection_open_private()
2655 * unless you have good reason; connections are expensive enough
2656 * that it's wasteful to create lots of connections to the same
2659 * @param address the address.
2660 * @param error address where an error can be returned.
2661 * @returns new connection, or #NULL on failure.
2664 dbus_connection_open_private (const char *address,
2667 DBusConnection *connection;
2669 _dbus_return_val_if_fail (address != NULL, NULL);
2670 _dbus_return_val_if_error_is_set (error, NULL);
2672 connection = _dbus_connection_open_internal (address,
2680 * Increments the reference count of a DBusConnection.
2682 * @param connection the connection.
2683 * @returns the connection.
2686 dbus_connection_ref (DBusConnection *connection)
2688 dbus_int32_t old_refcount;
2690 _dbus_return_val_if_fail (connection != NULL, NULL);
2691 _dbus_return_val_if_fail (connection->generation == _dbus_current_generation, NULL);
2692 old_refcount = _dbus_atomic_inc (&connection->refcount);
2693 _dbus_connection_trace_ref (connection, old_refcount, old_refcount + 1,
2700 free_outgoing_message (void *element,
2703 DBusMessage *message = element;
2704 DBusConnection *connection = data;
2706 _dbus_message_remove_counter (message, connection->outgoing_counter);
2707 dbus_message_unref (message);
2710 /* This is run without the mutex held, but after the last reference
2711 * to the connection has been dropped we should have no thread-related
2715 _dbus_connection_last_unref (DBusConnection *connection)
2719 _dbus_verbose ("Finalizing connection %p\n", connection);
2721 _dbus_assert (_dbus_atomic_get (&connection->refcount) == 0);
2723 /* You have to disconnect the connection before unref:ing it. Otherwise
2724 * you won't get the disconnected message.
2726 _dbus_assert (!_dbus_transport_get_is_connected (connection->transport));
2727 _dbus_assert (connection->server_guid == NULL);
2729 /* ---- We're going to call various application callbacks here, hope it doesn't break anything... */
2730 _dbus_object_tree_free_all_unlocked (connection->objects);
2732 dbus_connection_set_dispatch_status_function (connection, NULL, NULL, NULL);
2733 dbus_connection_set_wakeup_main_function (connection, NULL, NULL, NULL);
2734 dbus_connection_set_unix_user_function (connection, NULL, NULL, NULL);
2735 dbus_connection_set_windows_user_function (connection, NULL, NULL, NULL);
2737 _dbus_watch_list_free (connection->watches);
2738 connection->watches = NULL;
2740 _dbus_timeout_list_free (connection->timeouts);
2741 connection->timeouts = NULL;
2743 _dbus_data_slot_list_free (&connection->slot_list);
2745 link = _dbus_list_get_first_link (&connection->filter_list);
2746 while (link != NULL)
2748 DBusMessageFilter *filter = link->data;
2749 DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
2751 filter->function = NULL;
2752 _dbus_message_filter_unref (filter); /* calls app callback */
2757 _dbus_list_clear (&connection->filter_list);
2759 /* ---- Done with stuff that invokes application callbacks */
2761 _dbus_object_tree_unref (connection->objects);
2763 _dbus_hash_table_unref (connection->pending_replies);
2764 connection->pending_replies = NULL;
2766 _dbus_list_clear (&connection->filter_list);
2768 _dbus_list_foreach (&connection->outgoing_messages,
2769 free_outgoing_message,
2771 _dbus_list_clear (&connection->outgoing_messages);
2773 _dbus_list_foreach (&connection->incoming_messages,
2774 (DBusForeachFunction) dbus_message_unref,
2776 _dbus_list_clear (&connection->incoming_messages);
2778 _dbus_counter_unref (connection->outgoing_counter);
2780 _dbus_transport_unref (connection->transport);
2782 if (connection->disconnect_message_link)
2784 DBusMessage *message = connection->disconnect_message_link->data;
2785 dbus_message_unref (message);
2786 _dbus_list_free_link (connection->disconnect_message_link);
2789 _dbus_condvar_free_at_location (&connection->dispatch_cond);
2790 _dbus_condvar_free_at_location (&connection->io_path_cond);
2792 _dbus_cmutex_free_at_location (&connection->io_path_mutex);
2793 _dbus_cmutex_free_at_location (&connection->dispatch_mutex);
2795 _dbus_rmutex_free_at_location (&connection->slot_mutex);
2797 _dbus_rmutex_free_at_location (&connection->mutex);
2799 dbus_free (connection);
2803 * Decrements the reference count of a DBusConnection, and finalizes
2804 * it if the count reaches zero.
2806 * Note: it is a bug to drop the last reference to a connection that
2807 * is still connected.
2809 * For shared connections, libdbus will own a reference
2810 * as long as the connection is connected, so you can know that either
2811 * you don't have the last reference, or it's OK to drop the last reference.
2812 * Most connections are shared. dbus_connection_open() and dbus_bus_get()
2813 * return shared connections.
2815 * For private connections, the creator of the connection must arrange for
2816 * dbus_connection_close() to be called prior to dropping the last reference.
2817 * Private connections come from dbus_connection_open_private() or dbus_bus_get_private().
2819 * @param connection the connection.
2822 dbus_connection_unref (DBusConnection *connection)
2824 dbus_int32_t old_refcount;
2826 _dbus_return_if_fail (connection != NULL);
2827 _dbus_return_if_fail (connection->generation == _dbus_current_generation);
2829 old_refcount = _dbus_atomic_dec (&connection->refcount);
2831 _dbus_connection_trace_ref (connection, old_refcount, old_refcount - 1,
2834 if (old_refcount == 1)
2836 #ifndef DBUS_DISABLE_CHECKS
2837 if (_dbus_transport_get_is_connected (connection->transport))
2839 _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",
2840 connection->shareable ?
2841 "Most likely, the application called unref() too many times and removed a reference belonging to libdbus, since this is a shared connection.\n" :
2842 "Most likely, the application was supposed to call dbus_connection_close(), since this is a private connection.\n");
2846 _dbus_connection_last_unref (connection);
2851 * Note that the transport can disconnect itself (other end drops us)
2852 * and in that case this function never runs. So this function must
2853 * not do anything more than disconnect the transport and update the
2856 * If the transport self-disconnects, then we assume someone will
2857 * dispatch the connection to cause the dispatch status update.
2860 _dbus_connection_close_possibly_shared_and_unlock (DBusConnection *connection)
2862 DBusDispatchStatus status;
2864 HAVE_LOCK_CHECK (connection);
2866 _dbus_verbose ("Disconnecting %p\n", connection);
2868 /* We need to ref because update_dispatch_status_and_unlock will unref
2869 * the connection if it was shared and libdbus was the only remaining
2872 _dbus_connection_ref_unlocked (connection);
2874 _dbus_transport_disconnect (connection->transport);
2876 /* This has the side effect of queuing the disconnect message link
2877 * (unless we don't have enough memory, possibly, so don't assert it).
2878 * After the disconnect message link is queued, dbus_bus_get/dbus_connection_open
2879 * should never again return the newly-disconnected connection.
2881 * However, we only unref the shared connection and exit_on_disconnect when
2882 * the disconnect message reaches the head of the message queue,
2883 * NOT when it's first queued.
2885 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2887 /* This calls out to user code */
2888 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2890 /* Could also call out to user code */
2891 dbus_connection_unref (connection);
2895 * Closes a private connection, so no further data can be sent or received.
2896 * This disconnects the transport (such as a socket) underlying the
2899 * Attempts to send messages after closing a connection are safe, but will result in
2900 * error replies generated locally in libdbus.
2902 * This function does not affect the connection's reference count. It's
2903 * safe to close a connection more than once; all calls after the
2904 * first do nothing. It's impossible to "reopen" a connection, a
2905 * new connection must be created. This function may result in a call
2906 * to the DBusDispatchStatusFunction set with
2907 * dbus_connection_set_dispatch_status_function(), as the disconnect
2908 * message it generates needs to be dispatched.
2910 * If a connection is dropped by the remote application, it will
2913 * You must close a connection prior to releasing the last reference to
2914 * the connection. If you dbus_connection_unref() for the last time
2915 * without closing the connection, the results are undefined; it
2916 * is a bug in your program and libdbus will try to print a warning.
2918 * You may not close a shared connection. Connections created with
2919 * dbus_connection_open() or dbus_bus_get() are shared.
2920 * These connections are owned by libdbus, and applications should
2921 * only unref them, never close them. Applications can know it is
2922 * safe to unref these connections because libdbus will be holding a
2923 * reference as long as the connection is open. Thus, either the
2924 * connection is closed and it is OK to drop the last reference,
2925 * or the connection is open and the app knows it does not have the
2928 * Connections created with dbus_connection_open_private() or
2929 * dbus_bus_get_private() are not kept track of or referenced by
2930 * libdbus. The creator of these connections is responsible for
2931 * calling dbus_connection_close() prior to releasing the last
2932 * reference, if the connection is not already disconnected.
2934 * @param connection the private (unshared) connection to close
2937 dbus_connection_close (DBusConnection *connection)
2939 _dbus_return_if_fail (connection != NULL);
2940 _dbus_return_if_fail (connection->generation == _dbus_current_generation);
2942 CONNECTION_LOCK (connection);
2944 #ifndef DBUS_DISABLE_CHECKS
2945 if (connection->shareable)
2947 CONNECTION_UNLOCK (connection);
2949 _dbus_warn_check_failed ("Applications must not close shared connections - see dbus_connection_close() docs. This is a bug in the application.\n");
2954 _dbus_connection_close_possibly_shared_and_unlock (connection);
2958 _dbus_connection_get_is_connected_unlocked (DBusConnection *connection)
2960 HAVE_LOCK_CHECK (connection);
2961 return _dbus_transport_get_is_connected (connection->transport);
2965 * Gets whether the connection is currently open. A connection may
2966 * become disconnected when the remote application closes its end, or
2967 * exits; a connection may also be disconnected with
2968 * dbus_connection_close().
2970 * There are not separate states for "closed" and "disconnected," the two
2971 * terms are synonymous. This function should really be called
2972 * get_is_open() but for historical reasons is not.
2974 * @param connection the connection.
2975 * @returns #TRUE if the connection is still alive.
2978 dbus_connection_get_is_connected (DBusConnection *connection)
2982 _dbus_return_val_if_fail (connection != NULL, FALSE);
2984 CONNECTION_LOCK (connection);
2985 res = _dbus_connection_get_is_connected_unlocked (connection);
2986 CONNECTION_UNLOCK (connection);
2992 * Gets whether the connection was authenticated. (Note that
2993 * if the connection was authenticated then disconnected,
2994 * this function still returns #TRUE)
2996 * @param connection the connection
2997 * @returns #TRUE if the connection was ever authenticated
3000 dbus_connection_get_is_authenticated (DBusConnection *connection)
3004 _dbus_return_val_if_fail (connection != NULL, FALSE);
3006 CONNECTION_LOCK (connection);
3007 res = _dbus_transport_try_to_authenticate (connection->transport);
3008 CONNECTION_UNLOCK (connection);
3014 * Sets authenticated status for connection. Needed for kdbus, where authentication is
3015 * made in different manner.
3017 * @param connection the connection
3020 dbus_connection_set_is_authenticated (DBusConnection *connection)
3022 _dbus_return_val_if_fail (connection != NULL, FALSE);
3024 CONNECTION_LOCK (connection);
3025 connection->transport->authenticated = TRUE;
3026 CONNECTION_UNLOCK (connection);
3032 * Gets whether the connection is not authenticated as a specific
3033 * user. If the connection is not authenticated, this function
3034 * returns #TRUE, and if it is authenticated but as an anonymous user,
3035 * it returns #TRUE. If it is authenticated as a specific user, then
3036 * this returns #FALSE. (Note that if the connection was authenticated
3037 * as anonymous then disconnected, this function still returns #TRUE.)
3039 * If the connection is not anonymous, you can use
3040 * dbus_connection_get_unix_user() and
3041 * dbus_connection_get_windows_user() to see who it's authorized as.
3043 * If you want to prevent non-anonymous authorization, use
3044 * dbus_server_set_auth_mechanisms() to remove the mechanisms that
3045 * allow proving user identity (i.e. only allow the ANONYMOUS
3048 * @param connection the connection
3049 * @returns #TRUE if not authenticated or authenticated as anonymous
3052 dbus_connection_get_is_anonymous (DBusConnection *connection)
3056 _dbus_return_val_if_fail (connection != NULL, FALSE);
3058 CONNECTION_LOCK (connection);
3059 res = _dbus_transport_get_is_anonymous (connection->transport);
3060 CONNECTION_UNLOCK (connection);
3066 * Gets the ID of the server address we are authenticated to, if this
3067 * connection is on the client side. If the connection is on the
3068 * server side, this will always return #NULL - use dbus_server_get_id()
3069 * to get the ID of your own server, if you are the server side.
3071 * If a client-side connection is not authenticated yet, the ID may be
3072 * available if it was included in the server address, but may not be
3073 * available. The only way to be sure the server ID is available
3074 * is to wait for authentication to complete.
3076 * In general, each mode of connecting to a given server will have
3077 * its own ID. So for example, if the session bus daemon is listening
3078 * on UNIX domain sockets and on TCP, then each of those modalities
3079 * will have its own server ID.
3081 * If you want an ID that identifies an entire session bus, look at
3082 * dbus_bus_get_id() instead (which is just a convenience wrapper
3083 * around the org.freedesktop.DBus.GetId method invoked on the bus).
3085 * You can also get a machine ID; see dbus_get_local_machine_id() to
3086 * get the machine you are on. There isn't a convenience wrapper, but
3087 * you can invoke org.freedesktop.DBus.Peer.GetMachineId on any peer
3088 * to get the machine ID on the other end.
3090 * The D-Bus specification describes the server ID and other IDs in a
3093 * @param connection the connection
3094 * @returns the server ID or #NULL if no memory or the connection is server-side
3097 dbus_connection_get_server_id (DBusConnection *connection)
3101 _dbus_return_val_if_fail (connection != NULL, NULL);
3103 CONNECTION_LOCK (connection);
3104 id = _dbus_strdup (_dbus_transport_get_server_id (connection->transport));
3105 CONNECTION_UNLOCK (connection);
3111 * Tests whether a certain type can be send via the connection. This
3112 * will always return TRUE for all types, with the exception of
3113 * DBUS_TYPE_UNIX_FD. The function will return TRUE for
3114 * DBUS_TYPE_UNIX_FD only on systems that know Unix file descriptors
3115 * and can send them via the chosen transport and when the remote side
3118 * This function can be used to do runtime checking for types that
3119 * might be unknown to the specific D-Bus client implementation
3120 * version, i.e. it will return FALSE for all types this
3121 * implementation does not know, including invalid or reserved types.
3123 * @param connection the connection
3124 * @param type the type to check
3125 * @returns TRUE if the type may be send via the connection
3128 dbus_connection_can_send_type(DBusConnection *connection,
3131 _dbus_return_val_if_fail (connection != NULL, FALSE);
3133 if (!dbus_type_is_valid (type))
3136 if (type != DBUS_TYPE_UNIX_FD)
3139 #ifdef HAVE_UNIX_FD_PASSING
3143 CONNECTION_LOCK(connection);
3144 b = _dbus_transport_can_pass_unix_fd(connection->transport);
3145 CONNECTION_UNLOCK(connection);
3155 * Set whether _exit() should be called when the connection receives a
3156 * disconnect signal. The call to _exit() comes after any handlers for
3157 * the disconnect signal run; handlers can cancel the exit by calling
3160 * By default, exit_on_disconnect is #FALSE; but for message bus
3161 * connections returned from dbus_bus_get() it will be toggled on
3164 * @param connection the connection
3165 * @param exit_on_disconnect #TRUE if _exit() should be called after a disconnect signal
3168 dbus_connection_set_exit_on_disconnect (DBusConnection *connection,
3169 dbus_bool_t exit_on_disconnect)
3171 _dbus_return_if_fail (connection != NULL);
3173 CONNECTION_LOCK (connection);
3174 connection->exit_on_disconnect = exit_on_disconnect != FALSE;
3175 CONNECTION_UNLOCK (connection);
3179 * Preallocates resources needed to send a message, allowing the message
3180 * to be sent without the possibility of memory allocation failure.
3181 * Allows apps to create a future guarantee that they can send
3182 * a message regardless of memory shortages.
3184 * @param connection the connection we're preallocating for.
3185 * @returns the preallocated resources, or #NULL
3187 DBusPreallocatedSend*
3188 dbus_connection_preallocate_send (DBusConnection *connection)
3190 DBusPreallocatedSend *preallocated;
3192 _dbus_return_val_if_fail (connection != NULL, NULL);
3194 CONNECTION_LOCK (connection);
3197 _dbus_connection_preallocate_send_unlocked (connection);
3199 CONNECTION_UNLOCK (connection);
3201 return preallocated;
3205 * Frees preallocated message-sending resources from
3206 * dbus_connection_preallocate_send(). Should only
3207 * be called if the preallocated resources are not used
3208 * to send a message.
3210 * @param connection the connection
3211 * @param preallocated the resources
3214 dbus_connection_free_preallocated_send (DBusConnection *connection,
3215 DBusPreallocatedSend *preallocated)
3217 _dbus_return_if_fail (connection != NULL);
3218 _dbus_return_if_fail (preallocated != NULL);
3219 _dbus_return_if_fail (connection == preallocated->connection);
3221 _dbus_list_free_link (preallocated->queue_link);
3222 _dbus_counter_unref (preallocated->counter_link->data);
3223 _dbus_list_free_link (preallocated->counter_link);
3224 dbus_free (preallocated);
3228 * Sends a message using preallocated resources. This function cannot fail.
3229 * It works identically to dbus_connection_send() in other respects.
3230 * Preallocated resources comes from dbus_connection_preallocate_send().
3231 * This function "consumes" the preallocated resources, they need not
3232 * be freed separately.
3234 * @param connection the connection
3235 * @param preallocated the preallocated resources
3236 * @param message the message to send
3237 * @param client_serial return location for client serial assigned to the message
3240 dbus_connection_send_preallocated (DBusConnection *connection,
3241 DBusPreallocatedSend *preallocated,
3242 DBusMessage *message,
3243 dbus_uint32_t *client_serial)
3245 _dbus_return_if_fail (connection != NULL);
3246 _dbus_return_if_fail (preallocated != NULL);
3247 _dbus_return_if_fail (message != NULL);
3248 _dbus_return_if_fail (preallocated->connection == connection);
3249 _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_METHOD_CALL ||
3250 dbus_message_get_member (message) != NULL);
3251 _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL ||
3252 (dbus_message_get_interface (message) != NULL &&
3253 dbus_message_get_member (message) != NULL));
3255 CONNECTION_LOCK (connection);
3257 #ifdef HAVE_UNIX_FD_PASSING
3259 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3260 message->n_unix_fds > 0)
3262 /* Refuse to send fds on a connection that cannot handle
3263 them. Unfortunately we cannot return a proper error here, so
3264 the best we can is just return. */
3265 CONNECTION_UNLOCK (connection);
3271 _dbus_connection_send_preallocated_and_unlock (connection,
3273 message, client_serial);
3277 _dbus_connection_send_unlocked_no_update (DBusConnection *connection,
3278 DBusMessage *message,
3279 dbus_uint32_t *client_serial)
3281 DBusPreallocatedSend *preallocated;
3283 _dbus_assert (connection != NULL);
3284 _dbus_assert (message != NULL);
3286 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
3287 if (preallocated == NULL)
3290 _dbus_connection_send_preallocated_unlocked_no_update (connection,
3298 * Adds a message to the outgoing message queue. Does not block to
3299 * write the message to the network; that happens asynchronously. To
3300 * force the message to be written, call dbus_connection_flush() however
3301 * it is not necessary to call dbus_connection_flush() by hand; the
3302 * message will be sent the next time the main loop is run.
3303 * dbus_connection_flush() should only be used, for example, if
3304 * the application was expected to exit before running the main loop.
3306 * Because this only queues the message, the only reason it can
3307 * fail is lack of memory. Even if the connection is disconnected,
3308 * no error will be returned. If the function fails due to lack of memory,
3309 * it returns #FALSE. The function will never fail for other reasons; even
3310 * if the connection is disconnected, you can queue an outgoing message,
3311 * though obviously it won't be sent.
3313 * The message serial is used by the remote application to send a
3314 * reply; see dbus_message_get_serial() or the D-Bus specification.
3316 * dbus_message_unref() can be called as soon as this method returns
3317 * as the message queue will hold its own ref until the message is sent.
3319 * @param connection the connection.
3320 * @param message the message to write.
3321 * @param serial return location for message serial, or #NULL if you don't care
3322 * @returns #TRUE on success.
3325 dbus_connection_send (DBusConnection *connection,
3326 DBusMessage *message,
3327 dbus_uint32_t *serial)
3329 _dbus_return_val_if_fail (connection != NULL, FALSE);
3330 _dbus_return_val_if_fail (message != NULL, FALSE);
3332 CONNECTION_LOCK (connection);
3334 #ifdef HAVE_UNIX_FD_PASSING
3336 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3337 message->n_unix_fds > 0)
3339 /* Refuse to send fds on a connection that cannot handle
3340 them. Unfortunately we cannot return a proper error here, so
3341 the best we can is just return. */
3342 CONNECTION_UNLOCK (connection);
3348 return _dbus_connection_send_and_unlock (connection,
3354 reply_handler_timeout (void *data)
3356 DBusConnection *connection;
3357 DBusDispatchStatus status;
3358 DBusPendingCall *pending = data;
3360 connection = _dbus_pending_call_get_connection_and_lock (pending);
3361 _dbus_connection_ref_unlocked (connection);
3363 _dbus_pending_call_queue_timeout_error_unlocked (pending,
3365 _dbus_connection_remove_timeout_unlocked (connection,
3366 _dbus_pending_call_get_timeout_unlocked (pending));
3367 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
3369 _dbus_verbose ("middle\n");
3370 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3372 /* Unlocks, and calls out to user code */
3373 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3374 dbus_connection_unref (connection);
3380 * Queues a message to send, as with dbus_connection_send(),
3381 * but also returns a #DBusPendingCall used to receive a reply to the
3382 * message. If no reply is received in the given timeout_milliseconds,
3383 * this function expires the pending reply and generates a synthetic
3384 * error reply (generated in-process, not by the remote application)
3385 * indicating that a timeout occurred.
3387 * A #DBusPendingCall will see a reply message before any filters or
3388 * registered object path handlers. See dbus_connection_dispatch() for
3389 * details on when handlers are run.
3391 * A #DBusPendingCall will always see exactly one reply message,
3392 * unless it's cancelled with dbus_pending_call_cancel().
3394 * If #NULL is passed for the pending_return, the #DBusPendingCall
3395 * will still be generated internally, and used to track
3396 * the message reply timeout. This means a timeout error will
3397 * occur if no reply arrives, unlike with dbus_connection_send().
3399 * If -1 is passed for the timeout, a sane default timeout is used. -1
3400 * is typically the best value for the timeout for this reason, unless
3401 * you want a very short or very long timeout. If #DBUS_TIMEOUT_INFINITE is
3402 * passed for the timeout, no timeout will be set and the call will block
3405 * @warning if the connection is disconnected or you try to send Unix
3406 * file descriptors on a connection that does not support them, the
3407 * #DBusPendingCall will be set to #NULL, so be careful with this.
3409 * @param connection the connection
3410 * @param message the message to send
3411 * @param pending_return return location for a #DBusPendingCall
3412 * object, or #NULL if connection is disconnected or when you try to
3413 * send Unix file descriptors on a connection that does not support
3415 * @param timeout_milliseconds timeout in milliseconds, -1 (or
3416 * #DBUS_TIMEOUT_USE_DEFAULT) for default or #DBUS_TIMEOUT_INFINITE for no
3418 * @returns #FALSE if no memory, #TRUE otherwise.
3422 dbus_connection_send_with_reply (DBusConnection *connection,
3423 DBusMessage *message,
3424 DBusPendingCall **pending_return,
3425 int timeout_milliseconds)
3427 DBusPendingCall *pending;
3428 dbus_int32_t serial = -1;
3429 DBusDispatchStatus status;
3431 _dbus_return_val_if_fail (connection != NULL, FALSE);
3432 _dbus_return_val_if_fail (message != NULL, FALSE);
3433 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3436 *pending_return = NULL;
3438 CONNECTION_LOCK (connection);
3440 #ifdef HAVE_UNIX_FD_PASSING
3442 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3443 message->n_unix_fds > 0)
3445 /* Refuse to send fds on a connection that cannot handle
3446 them. Unfortunately we cannot return a proper error here, so
3447 the best we can do is return TRUE but leave *pending_return
3449 CONNECTION_UNLOCK (connection);
3455 if (!_dbus_connection_get_is_connected_unlocked (connection))
3457 CONNECTION_UNLOCK (connection);
3462 pending = _dbus_pending_call_new_unlocked (connection,
3463 timeout_milliseconds,
3464 reply_handler_timeout);
3466 if (pending == NULL)
3468 CONNECTION_UNLOCK (connection);
3472 /* Assign a serial to the message */
3473 serial = dbus_message_get_serial (message);
3476 serial = _dbus_connection_get_next_client_serial (connection);
3477 dbus_message_set_serial (message, serial);
3480 if (!_dbus_pending_call_set_timeout_error_unlocked (pending, message, serial))
3483 /* Insert the serial in the pending replies hash;
3484 * hash takes a refcount on DBusPendingCall.
3485 * Also, add the timeout.
3487 if (!_dbus_connection_attach_pending_call_unlocked (connection,
3491 if (!_dbus_connection_send_unlocked_no_update (connection, message, NULL))
3493 _dbus_connection_detach_pending_call_and_unlock (connection,
3495 goto error_unlocked;
3499 *pending_return = pending; /* hand off refcount */
3502 _dbus_connection_detach_pending_call_unlocked (connection, pending);
3503 /* we still have a ref to the pending call in this case, we unref
3504 * after unlocking, below
3508 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3510 /* this calls out to user code */
3511 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3513 if (pending_return == NULL)
3514 dbus_pending_call_unref (pending);
3519 CONNECTION_UNLOCK (connection);
3521 dbus_pending_call_unref (pending);
3526 * Sends a message and blocks a certain time period while waiting for
3527 * a reply. This function does not reenter the main loop,
3528 * i.e. messages other than the reply are queued up but not
3529 * processed. This function is used to invoke method calls on a
3532 * If a normal reply is received, it is returned, and removed from the
3533 * incoming message queue. If it is not received, #NULL is returned
3534 * and the error is set to #DBUS_ERROR_NO_REPLY. If an error reply is
3535 * received, it is converted to a #DBusError and returned as an error,
3536 * then the reply message is deleted and #NULL is returned. If
3537 * something else goes wrong, result is set to whatever is
3538 * appropriate, such as #DBUS_ERROR_NO_MEMORY or
3539 * #DBUS_ERROR_DISCONNECTED.
3541 * @warning While this function blocks the calling thread will not be
3542 * processing the incoming message queue. This means you can end up
3543 * deadlocked if the application you're talking to needs you to reply
3544 * to a method. To solve this, either avoid the situation, block in a
3545 * separate thread from the main connection-dispatching thread, or use
3546 * dbus_pending_call_set_notify() to avoid blocking.
3548 * @param connection the connection
3549 * @param message the message to send
3550 * @param timeout_milliseconds timeout in milliseconds, -1 (or
3551 * #DBUS_TIMEOUT_USE_DEFAULT) for default or #DBUS_TIMEOUT_INFINITE for no
3553 * @param error return location for error message
3554 * @returns the message that is the reply or #NULL with an error code if the
3558 dbus_connection_send_with_reply_and_block (DBusConnection *connection,
3559 DBusMessage *message,
3560 int timeout_milliseconds,
3564 DBusPendingCall *pending;
3566 _dbus_return_val_if_fail (connection != NULL, NULL);
3567 _dbus_return_val_if_fail (message != NULL, NULL);
3568 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, NULL);
3569 _dbus_return_val_if_error_is_set (error, NULL);
3571 #ifdef HAVE_UNIX_FD_PASSING
3573 CONNECTION_LOCK (connection);
3574 if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3575 message->n_unix_fds > 0)
3577 CONNECTION_UNLOCK (connection);
3578 dbus_set_error(error, DBUS_ERROR_FAILED, "Cannot send file descriptors on this connection.");
3581 CONNECTION_UNLOCK (connection);
3585 if (!dbus_connection_send_with_reply (connection, message,
3586 &pending, timeout_milliseconds))
3588 _DBUS_SET_OOM (error);
3592 if (pending == NULL)
3594 dbus_set_error (error, DBUS_ERROR_DISCONNECTED, "Connection is closed");
3598 dbus_pending_call_block (pending);
3600 reply = dbus_pending_call_steal_reply (pending);
3601 dbus_pending_call_unref (pending);
3603 /* call_complete_and_unlock() called from pending_call_block() should
3604 * always fill this in.
3606 _dbus_assert (reply != NULL);
3608 if (dbus_set_error_from_message (error, reply))
3610 dbus_message_unref (reply);
3618 * Blocks until the outgoing message queue is empty.
3619 * Assumes connection lock already held.
3621 * If you call this, you MUST call update_dispatch_status afterword...
3623 * @param connection the connection.
3625 static DBusDispatchStatus
3626 _dbus_connection_flush_unlocked (DBusConnection *connection)
3628 /* We have to specify DBUS_ITERATION_DO_READING here because
3629 * otherwise we could have two apps deadlock if they are both doing
3630 * a flush(), and the kernel buffers fill up. This could change the
3633 DBusDispatchStatus status;
3635 HAVE_LOCK_CHECK (connection);
3637 while (connection->n_outgoing > 0 &&
3638 _dbus_connection_get_is_connected_unlocked (connection))
3640 _dbus_verbose ("doing iteration in\n");
3641 HAVE_LOCK_CHECK (connection);
3642 _dbus_connection_do_iteration_unlocked (connection,
3644 DBUS_ITERATION_DO_READING |
3645 DBUS_ITERATION_DO_WRITING |
3646 DBUS_ITERATION_BLOCK,
3650 HAVE_LOCK_CHECK (connection);
3651 _dbus_verbose ("middle\n");
3652 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3654 HAVE_LOCK_CHECK (connection);
3659 * Blocks until the outgoing message queue is empty.
3661 * @param connection the connection.
3664 dbus_connection_flush (DBusConnection *connection)
3666 /* We have to specify DBUS_ITERATION_DO_READING here because
3667 * otherwise we could have two apps deadlock if they are both doing
3668 * a flush(), and the kernel buffers fill up. This could change the
3671 DBusDispatchStatus status;
3673 _dbus_return_if_fail (connection != NULL);
3675 CONNECTION_LOCK (connection);
3677 status = _dbus_connection_flush_unlocked (connection);
3679 HAVE_LOCK_CHECK (connection);
3680 /* Unlocks and calls out to user code */
3681 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3683 _dbus_verbose ("end\n");
3687 * This function implements dbus_connection_read_write_dispatch() and
3688 * dbus_connection_read_write() (they pass a different value for the
3689 * dispatch parameter).
3691 * @param connection the connection
3692 * @param timeout_milliseconds max time to block or -1 for infinite
3693 * @param dispatch dispatch new messages or leave them on the incoming queue
3694 * @returns #TRUE if the disconnect message has not been processed
3697 _dbus_connection_read_write_dispatch (DBusConnection *connection,
3698 int timeout_milliseconds,
3699 dbus_bool_t dispatch)
3701 DBusDispatchStatus dstatus;
3702 dbus_bool_t progress_possible;
3704 /* Need to grab a ref here in case we're a private connection and
3705 * the user drops the last ref in a handler we call; see bug
3706 * https://bugs.freedesktop.org/show_bug.cgi?id=15635
3708 dbus_connection_ref (connection);
3709 dstatus = dbus_connection_get_dispatch_status (connection);
3711 if (dispatch && dstatus == DBUS_DISPATCH_DATA_REMAINS)
3713 _dbus_verbose ("doing dispatch\n");
3714 dbus_connection_dispatch (connection);
3715 CONNECTION_LOCK (connection);
3717 else if (dstatus == DBUS_DISPATCH_NEED_MEMORY)
3719 _dbus_verbose ("pausing for memory\n");
3720 _dbus_memory_pause_based_on_timeout (timeout_milliseconds);
3721 CONNECTION_LOCK (connection);
3725 CONNECTION_LOCK (connection);
3726 if (_dbus_connection_get_is_connected_unlocked (connection))
3728 _dbus_verbose ("doing iteration\n");
3729 _dbus_connection_do_iteration_unlocked (connection,
3731 DBUS_ITERATION_DO_READING |
3732 DBUS_ITERATION_DO_WRITING |
3733 DBUS_ITERATION_BLOCK,
3734 timeout_milliseconds);
3738 HAVE_LOCK_CHECK (connection);
3739 /* If we can dispatch, we can make progress until the Disconnected message
3740 * has been processed; if we can only read/write, we can make progress
3741 * as long as the transport is open.
3744 progress_possible = connection->n_incoming != 0 ||
3745 connection->disconnect_message_link != NULL;
3747 progress_possible = _dbus_connection_get_is_connected_unlocked (connection);
3749 CONNECTION_UNLOCK (connection);
3751 dbus_connection_unref (connection);
3753 return progress_possible; /* TRUE if we can make more progress */
3758 * This function is intended for use with applications that don't want
3759 * to write a main loop and deal with #DBusWatch and #DBusTimeout. An
3760 * example usage would be:
3763 * while (dbus_connection_read_write_dispatch (connection, -1))
3764 * ; // empty loop body
3767 * In this usage you would normally have set up a filter function to look
3768 * at each message as it is dispatched. The loop terminates when the last
3769 * message from the connection (the disconnected signal) is processed.
3771 * If there are messages to dispatch, this function will
3772 * dbus_connection_dispatch() once, and return. If there are no
3773 * messages to dispatch, this function will block until it can read or
3774 * write, then read or write, then return.
3776 * The way to think of this function is that it either makes some sort
3777 * of progress, or it blocks. Note that, while it is blocked on I/O, it
3778 * cannot be interrupted (even by other threads), which makes this function
3779 * unsuitable for applications that do more than just react to received
3782 * The return value indicates whether the disconnect message has been
3783 * processed, NOT whether the connection is connected. This is
3784 * important because even after disconnecting, you want to process any
3785 * messages you received prior to the disconnect.
3787 * @param connection the connection
3788 * @param timeout_milliseconds max time to block or -1 for infinite
3789 * @returns #TRUE if the disconnect message has not been processed
3792 dbus_connection_read_write_dispatch (DBusConnection *connection,
3793 int timeout_milliseconds)
3795 _dbus_return_val_if_fail (connection != NULL, FALSE);
3796 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3797 return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, TRUE);
3801 * This function is intended for use with applications that don't want to
3802 * write a main loop and deal with #DBusWatch and #DBusTimeout. See also
3803 * dbus_connection_read_write_dispatch().
3805 * As long as the connection is open, this function will block until it can
3806 * read or write, then read or write, then return #TRUE.
3808 * If the connection is closed, the function returns #FALSE.
3810 * The return value indicates whether reading or writing is still
3811 * possible, i.e. whether the connection is connected.
3813 * Note that even after disconnection, messages may remain in the
3814 * incoming queue that need to be
3815 * processed. dbus_connection_read_write_dispatch() dispatches
3816 * incoming messages for you; with dbus_connection_read_write() you
3817 * have to arrange to drain the incoming queue yourself.
3819 * @param connection the connection
3820 * @param timeout_milliseconds max time to block or -1 for infinite
3821 * @returns #TRUE if still connected
3824 dbus_connection_read_write (DBusConnection *connection,
3825 int timeout_milliseconds)
3827 _dbus_return_val_if_fail (connection != NULL, FALSE);
3828 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3829 return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, FALSE);
3832 /* We need to call this anytime we pop the head of the queue, and then
3833 * update_dispatch_status_and_unlock needs to be called afterward
3834 * which will "process" the disconnected message and set
3835 * disconnected_message_processed.
3838 check_disconnected_message_arrived_unlocked (DBusConnection *connection,
3839 DBusMessage *head_of_queue)
3841 HAVE_LOCK_CHECK (connection);
3843 /* checking that the link is NULL is an optimization to avoid the is_signal call */
3844 if (connection->disconnect_message_link == NULL &&
3845 dbus_message_is_signal (head_of_queue,
3846 DBUS_INTERFACE_LOCAL,
3849 connection->disconnected_message_arrived = TRUE;
3854 * Returns the first-received message from the incoming message queue,
3855 * leaving it in the queue. If the queue is empty, returns #NULL.
3857 * The caller does not own a reference to the returned message, and
3858 * must either return it using dbus_connection_return_message() or
3859 * keep it after calling dbus_connection_steal_borrowed_message(). No
3860 * one can get at the message while its borrowed, so return it as
3861 * quickly as possible and don't keep a reference to it after
3862 * returning it. If you need to keep the message, make a copy of it.
3864 * dbus_connection_dispatch() will block if called while a borrowed
3865 * message is outstanding; only one piece of code can be playing with
3866 * the incoming queue at a time. This function will block if called
3867 * during a dbus_connection_dispatch().
3869 * @param connection the connection.
3870 * @returns next message in the incoming queue.
3873 dbus_connection_borrow_message (DBusConnection *connection)
3875 DBusDispatchStatus status;
3876 DBusMessage *message;
3878 _dbus_return_val_if_fail (connection != NULL, NULL);
3880 _dbus_verbose ("start\n");
3882 /* this is called for the side effect that it queues
3883 * up any messages from the transport
3885 status = dbus_connection_get_dispatch_status (connection);
3886 if (status != DBUS_DISPATCH_DATA_REMAINS)
3889 CONNECTION_LOCK (connection);
3891 _dbus_connection_acquire_dispatch (connection);
3893 /* While a message is outstanding, the dispatch lock is held */
3894 _dbus_assert (connection->message_borrowed == NULL);
3896 connection->message_borrowed = _dbus_list_get_first (&connection->incoming_messages);
3898 message = connection->message_borrowed;
3900 check_disconnected_message_arrived_unlocked (connection, message);
3902 /* Note that we KEEP the dispatch lock until the message is returned */
3903 if (message == NULL)
3904 _dbus_connection_release_dispatch (connection);
3906 CONNECTION_UNLOCK (connection);
3908 _dbus_message_trace_ref (message, -1, -1, "dbus_connection_borrow_message");
3910 /* We don't update dispatch status until it's returned or stolen */
3916 * Used to return a message after peeking at it using
3917 * dbus_connection_borrow_message(). Only called if
3918 * message from dbus_connection_borrow_message() was non-#NULL.
3920 * @param connection the connection
3921 * @param message the message from dbus_connection_borrow_message()
3924 dbus_connection_return_message (DBusConnection *connection,
3925 DBusMessage *message)
3927 DBusDispatchStatus status;
3929 _dbus_return_if_fail (connection != NULL);
3930 _dbus_return_if_fail (message != NULL);
3931 _dbus_return_if_fail (message == connection->message_borrowed);
3932 _dbus_return_if_fail (connection->dispatch_acquired);
3934 CONNECTION_LOCK (connection);
3936 _dbus_assert (message == connection->message_borrowed);
3938 connection->message_borrowed = NULL;
3940 _dbus_connection_release_dispatch (connection);
3942 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3943 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3945 _dbus_message_trace_ref (message, -1, -1, "dbus_connection_return_message");
3949 * Used to keep a message after peeking at it using
3950 * dbus_connection_borrow_message(). Before using this function, see
3951 * the caveats/warnings in the documentation for
3952 * dbus_connection_pop_message().
3954 * @param connection the connection
3955 * @param message the message from dbus_connection_borrow_message()
3958 dbus_connection_steal_borrowed_message (DBusConnection *connection,
3959 DBusMessage *message)
3961 DBusMessage *pop_message;
3962 DBusDispatchStatus status;
3964 _dbus_return_if_fail (connection != NULL);
3965 _dbus_return_if_fail (message != NULL);
3966 _dbus_return_if_fail (message == connection->message_borrowed);
3967 _dbus_return_if_fail (connection->dispatch_acquired);
3969 CONNECTION_LOCK (connection);
3971 _dbus_assert (message == connection->message_borrowed);
3973 pop_message = _dbus_list_pop_first (&connection->incoming_messages);
3974 _dbus_assert (message == pop_message);
3975 (void) pop_message; /* unused unless asserting */
3977 connection->n_incoming -= 1;
3979 _dbus_verbose ("Incoming message %p stolen from queue, %d incoming\n",
3980 message, connection->n_incoming);
3982 connection->message_borrowed = NULL;
3984 _dbus_connection_release_dispatch (connection);
3986 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3987 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3988 _dbus_message_trace_ref (message, -1, -1,
3989 "dbus_connection_steal_borrowed_message");
3992 /* See dbus_connection_pop_message, but requires the caller to own
3993 * the lock before calling. May drop the lock while running.
3996 _dbus_connection_pop_message_link_unlocked (DBusConnection *connection)
3998 HAVE_LOCK_CHECK (connection);
4000 _dbus_assert (connection->message_borrowed == NULL);
4002 if (connection->n_incoming > 0)
4006 link = _dbus_list_pop_first_link (&connection->incoming_messages);
4007 connection->n_incoming -= 1;
4009 _dbus_verbose ("Message %p (%s %s %s %s sig:'%s' serial:%u) removed from incoming queue %p, %d incoming\n",
4011 dbus_message_type_to_string (dbus_message_get_type (link->data)),
4012 dbus_message_get_path (link->data) ?
4013 dbus_message_get_path (link->data) :
4015 dbus_message_get_interface (link->data) ?
4016 dbus_message_get_interface (link->data) :
4018 dbus_message_get_member (link->data) ?
4019 dbus_message_get_member (link->data) :
4021 dbus_message_get_signature (link->data),
4022 dbus_message_get_serial (link->data),
4023 connection, connection->n_incoming);
4025 _dbus_message_trace_ref (link->data, -1, -1,
4026 "_dbus_connection_pop_message_link_unlocked");
4028 check_disconnected_message_arrived_unlocked (connection, link->data);
4036 /* See dbus_connection_pop_message, but requires the caller to own
4037 * the lock before calling. May drop the lock while running.
4040 _dbus_connection_pop_message_unlocked (DBusConnection *connection)
4044 HAVE_LOCK_CHECK (connection);
4046 link = _dbus_connection_pop_message_link_unlocked (connection);
4050 DBusMessage *message;
4052 message = link->data;
4054 _dbus_list_free_link (link);
4063 _dbus_connection_putback_message_link_unlocked (DBusConnection *connection,
4064 DBusList *message_link)
4066 HAVE_LOCK_CHECK (connection);
4068 _dbus_assert (message_link != NULL);
4069 /* You can't borrow a message while a link is outstanding */
4070 _dbus_assert (connection->message_borrowed == NULL);
4071 /* We had to have the dispatch lock across the pop/putback */
4072 _dbus_assert (connection->dispatch_acquired);
4074 _dbus_list_prepend_link (&connection->incoming_messages,
4076 connection->n_incoming += 1;
4078 _dbus_verbose ("Message %p (%s %s %s '%s') put back into queue %p, %d incoming\n",
4080 dbus_message_type_to_string (dbus_message_get_type (message_link->data)),
4081 dbus_message_get_interface (message_link->data) ?
4082 dbus_message_get_interface (message_link->data) :
4084 dbus_message_get_member (message_link->data) ?
4085 dbus_message_get_member (message_link->data) :
4087 dbus_message_get_signature (message_link->data),
4088 connection, connection->n_incoming);
4090 _dbus_message_trace_ref (message_link->data, -1, -1,
4091 "_dbus_connection_putback_message_link_unlocked");
4095 * Returns the first-received message from the incoming message queue,
4096 * removing it from the queue. The caller owns a reference to the
4097 * returned message. If the queue is empty, returns #NULL.
4099 * This function bypasses any message handlers that are registered,
4100 * and so using it is usually wrong. Instead, let the main loop invoke
4101 * dbus_connection_dispatch(). Popping messages manually is only
4102 * useful in very simple programs that don't share a #DBusConnection
4103 * with any libraries or other modules.
4105 * There is a lock that covers all ways of accessing the incoming message
4106 * queue, so dbus_connection_dispatch(), dbus_connection_pop_message(),
4107 * dbus_connection_borrow_message(), etc. will all block while one of the others
4108 * in the group is running.
4110 * @param connection the connection.
4111 * @returns next message in the incoming queue.
4114 dbus_connection_pop_message (DBusConnection *connection)
4116 DBusMessage *message;
4117 DBusDispatchStatus status;
4119 _dbus_verbose ("start\n");
4121 /* this is called for the side effect that it queues
4122 * up any messages from the transport
4124 status = dbus_connection_get_dispatch_status (connection);
4125 if (status != DBUS_DISPATCH_DATA_REMAINS)
4128 CONNECTION_LOCK (connection);
4129 _dbus_connection_acquire_dispatch (connection);
4130 HAVE_LOCK_CHECK (connection);
4132 message = _dbus_connection_pop_message_unlocked (connection);
4134 _dbus_verbose ("Returning popped message %p\n", message);
4136 _dbus_connection_release_dispatch (connection);
4138 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4139 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4145 * Acquire the dispatcher. This is a separate lock so the main
4146 * connection lock can be dropped to call out to application dispatch
4149 * @param connection the connection.
4152 _dbus_connection_acquire_dispatch (DBusConnection *connection)
4154 HAVE_LOCK_CHECK (connection);
4156 _dbus_connection_ref_unlocked (connection);
4157 CONNECTION_UNLOCK (connection);
4159 _dbus_verbose ("locking dispatch_mutex\n");
4160 _dbus_cmutex_lock (connection->dispatch_mutex);
4162 while (connection->dispatch_acquired)
4164 _dbus_verbose ("waiting for dispatch to be acquirable\n");
4165 _dbus_condvar_wait (connection->dispatch_cond,
4166 connection->dispatch_mutex);
4169 _dbus_assert (!connection->dispatch_acquired);
4171 connection->dispatch_acquired = TRUE;
4173 _dbus_verbose ("unlocking dispatch_mutex\n");
4174 _dbus_cmutex_unlock (connection->dispatch_mutex);
4176 CONNECTION_LOCK (connection);
4177 _dbus_connection_unref_unlocked (connection);
4181 * Release the dispatcher when you're done with it. Only call
4182 * after you've acquired the dispatcher. Wakes up at most one
4183 * thread currently waiting to acquire the dispatcher.
4185 * @param connection the connection.
4188 _dbus_connection_release_dispatch (DBusConnection *connection)
4190 HAVE_LOCK_CHECK (connection);
4192 _dbus_verbose ("locking dispatch_mutex\n");
4193 _dbus_cmutex_lock (connection->dispatch_mutex);
4195 _dbus_assert (connection->dispatch_acquired);
4197 connection->dispatch_acquired = FALSE;
4198 _dbus_condvar_wake_one (connection->dispatch_cond);
4200 _dbus_verbose ("unlocking dispatch_mutex\n");
4201 _dbus_cmutex_unlock (connection->dispatch_mutex);
4205 _dbus_connection_failed_pop (DBusConnection *connection,
4206 DBusList *message_link)
4208 _dbus_list_prepend_link (&connection->incoming_messages,
4210 connection->n_incoming += 1;
4213 /* Note this may be called multiple times since we don't track whether we already did it */
4215 notify_disconnected_unlocked (DBusConnection *connection)
4217 HAVE_LOCK_CHECK (connection);
4219 /* Set the weakref in dbus-bus.c to NULL, so nobody will get a disconnected
4220 * connection from dbus_bus_get(). We make the same guarantee for
4221 * dbus_connection_open() but in a different way since we don't want to
4222 * unref right here; we instead check for connectedness before returning
4223 * the connection from the hash.
4225 _dbus_bus_notify_shared_connection_disconnected_unlocked (connection);
4227 /* Dump the outgoing queue, we aren't going to be able to
4228 * send it now, and we'd like accessors like
4229 * dbus_connection_get_outgoing_size() to be accurate.
4231 if (connection->n_outgoing > 0)
4235 _dbus_verbose ("Dropping %d outgoing messages since we're disconnected\n",
4236 connection->n_outgoing);
4238 while ((link = _dbus_list_get_last_link (&connection->outgoing_messages)))
4240 _dbus_connection_message_sent_unlocked (connection, link->data);
4245 /* Note this may be called multiple times since we don't track whether we already did it */
4246 static DBusDispatchStatus
4247 notify_disconnected_and_dispatch_complete_unlocked (DBusConnection *connection)
4249 HAVE_LOCK_CHECK (connection);
4251 if (connection->disconnect_message_link != NULL)
4253 _dbus_verbose ("Sending disconnect message\n");
4255 /* If we have pending calls, queue their timeouts - we want the Disconnected
4256 * to be the last message, after these timeouts.
4258 connection_timeout_and_complete_all_pending_calls_unlocked (connection);
4260 /* We haven't sent the disconnect message already,
4261 * and all real messages have been queued up.
4263 _dbus_connection_queue_synthesized_message_link (connection,
4264 connection->disconnect_message_link);
4265 connection->disconnect_message_link = NULL;
4267 return DBUS_DISPATCH_DATA_REMAINS;
4270 return DBUS_DISPATCH_COMPLETE;
4273 static DBusDispatchStatus
4274 _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection)
4276 HAVE_LOCK_CHECK (connection);
4278 if (connection->n_incoming > 0)
4279 return DBUS_DISPATCH_DATA_REMAINS;
4280 else if (!_dbus_transport_queue_messages (connection->transport))
4281 return DBUS_DISPATCH_NEED_MEMORY;
4284 DBusDispatchStatus status;
4285 dbus_bool_t is_connected;
4287 status = _dbus_transport_get_dispatch_status (connection->transport);
4288 is_connected = _dbus_transport_get_is_connected (connection->transport);
4290 _dbus_verbose ("dispatch status = %s is_connected = %d\n",
4291 DISPATCH_STATUS_NAME (status), is_connected);
4295 /* It's possible this would be better done by having an explicit
4296 * notification from _dbus_transport_disconnect() that would
4297 * synchronously do this, instead of waiting for the next dispatch
4298 * status check. However, probably not good to change until it causes
4301 notify_disconnected_unlocked (connection);
4303 /* I'm not sure this is needed; the idea is that we want to
4304 * queue the Disconnected only after we've read all the
4305 * messages, but if we're disconnected maybe we are guaranteed
4306 * to have read them all ?
4308 if (status == DBUS_DISPATCH_COMPLETE)
4309 status = notify_disconnected_and_dispatch_complete_unlocked (connection);
4312 if (status != DBUS_DISPATCH_COMPLETE)
4314 else if (connection->n_incoming > 0)
4315 return DBUS_DISPATCH_DATA_REMAINS;
4317 return DBUS_DISPATCH_COMPLETE;
4322 _dbus_connection_update_dispatch_status_and_unlock (DBusConnection *connection,
4323 DBusDispatchStatus new_status)
4325 dbus_bool_t changed;
4326 DBusDispatchStatusFunction function;
4329 HAVE_LOCK_CHECK (connection);
4331 _dbus_connection_ref_unlocked (connection);
4333 changed = new_status != connection->last_dispatch_status;
4335 connection->last_dispatch_status = new_status;
4337 function = connection->dispatch_status_function;
4338 data = connection->dispatch_status_data;
4340 if (connection->disconnected_message_arrived &&
4341 !connection->disconnected_message_processed)
4343 connection->disconnected_message_processed = TRUE;
4345 /* this does an unref, but we have a ref
4346 * so we should not run the finalizer here
4349 connection_forget_shared_unlocked (connection);
4351 if (connection->exit_on_disconnect)
4353 CONNECTION_UNLOCK (connection);
4355 _dbus_verbose ("Exiting on Disconnected signal\n");
4357 _dbus_assert_not_reached ("Call to exit() returned");
4361 /* We drop the lock */
4362 CONNECTION_UNLOCK (connection);
4364 if (changed && function)
4366 _dbus_verbose ("Notifying of change to dispatch status of %p now %d (%s)\n",
4367 connection, new_status,
4368 DISPATCH_STATUS_NAME (new_status));
4369 (* function) (connection, new_status, data);
4372 dbus_connection_unref (connection);
4376 * Gets the current state of the incoming message queue.
4377 * #DBUS_DISPATCH_DATA_REMAINS indicates that the message queue
4378 * may contain messages. #DBUS_DISPATCH_COMPLETE indicates that the
4379 * incoming queue is empty. #DBUS_DISPATCH_NEED_MEMORY indicates that
4380 * there could be data, but we can't know for sure without more
4383 * To process the incoming message queue, use dbus_connection_dispatch()
4384 * or (in rare cases) dbus_connection_pop_message().
4386 * Note, #DBUS_DISPATCH_DATA_REMAINS really means that either we
4387 * have messages in the queue, or we have raw bytes buffered up
4388 * that need to be parsed. When these bytes are parsed, they
4389 * may not add up to an entire message. Thus, it's possible
4390 * to see a status of #DBUS_DISPATCH_DATA_REMAINS but not
4391 * have a message yet.
4393 * In particular this happens on initial connection, because all sorts
4394 * of authentication protocol stuff has to be parsed before the
4395 * first message arrives.
4397 * @param connection the connection.
4398 * @returns current dispatch status
4401 dbus_connection_get_dispatch_status (DBusConnection *connection)
4403 DBusDispatchStatus status;
4405 _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
4407 _dbus_verbose ("start\n");
4409 CONNECTION_LOCK (connection);
4411 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4413 CONNECTION_UNLOCK (connection);
4419 * Filter funtion for handling the Peer standard interface.
4421 static DBusHandlerResult
4422 _dbus_connection_peer_filter_unlocked_no_update (DBusConnection *connection,
4423 DBusMessage *message)
4425 dbus_bool_t sent = FALSE;
4426 DBusMessage *ret = NULL;
4427 DBusList *expire_link;
4429 if (connection->route_peer_messages && dbus_message_get_destination (message) != NULL)
4431 /* This means we're letting the bus route this message */
4432 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4435 if (!dbus_message_has_interface (message, DBUS_INTERFACE_PEER))
4437 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4440 /* Preallocate a linked-list link, so that if we need to dispose of a
4441 * message, we can attach it to the expired list */
4442 expire_link = _dbus_list_alloc_link (NULL);
4445 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4447 if (dbus_message_is_method_call (message,
4448 DBUS_INTERFACE_PEER,
4451 ret = dbus_message_new_method_return (message);
4455 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4457 else if (dbus_message_is_method_call (message,
4458 DBUS_INTERFACE_PEER,
4463 ret = dbus_message_new_method_return (message);
4467 _dbus_string_init (&uuid);
4468 if (_dbus_get_local_machine_uuid_encoded (&uuid))
4470 const char *v_STRING = _dbus_string_get_const_data (&uuid);
4471 if (dbus_message_append_args (ret,
4472 DBUS_TYPE_STRING, &v_STRING,
4475 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4478 _dbus_string_free (&uuid);
4482 /* We need to bounce anything else with this interface, otherwise apps
4483 * could start extending the interface and when we added extensions
4484 * here to DBusConnection we'd break those apps.
4486 ret = dbus_message_new_error (message,
4487 DBUS_ERROR_UNKNOWN_METHOD,
4488 "Unknown method invoked on org.freedesktop.DBus.Peer interface");
4492 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4498 _dbus_list_free_link (expire_link);
4502 /* It'll be safe to unref the reply when we unlock */
4503 expire_link->data = ret;
4504 _dbus_list_prepend_link (&connection->expired_messages, expire_link);
4508 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4510 return DBUS_HANDLER_RESULT_HANDLED;
4514 * Processes all builtin filter functions
4516 * If the spec specifies a standard interface
4517 * they should be processed from this method
4519 static DBusHandlerResult
4520 _dbus_connection_run_builtin_filters_unlocked_no_update (DBusConnection *connection,
4521 DBusMessage *message)
4523 /* We just run one filter for now but have the option to run more
4524 if the spec calls for it in the future */
4526 return _dbus_connection_peer_filter_unlocked_no_update (connection, message);
4530 * Processes any incoming data.
4532 * If there's incoming raw data that has not yet been parsed, it is
4533 * parsed, which may or may not result in adding messages to the
4536 * The incoming data buffer is filled when the connection reads from
4537 * its underlying transport (such as a socket). Reading usually
4538 * happens in dbus_watch_handle() or dbus_connection_read_write().
4540 * If there are complete messages in the incoming queue,
4541 * dbus_connection_dispatch() removes one message from the queue and
4542 * processes it. Processing has three steps.
4544 * First, any method replies are passed to #DBusPendingCall or
4545 * dbus_connection_send_with_reply_and_block() in order to
4546 * complete the pending method call.
4548 * Second, any filters registered with dbus_connection_add_filter()
4549 * are run. If any filter returns #DBUS_HANDLER_RESULT_HANDLED
4550 * then processing stops after that filter.
4552 * Third, if the message is a method call it is forwarded to
4553 * any registered object path handlers added with
4554 * dbus_connection_register_object_path() or
4555 * dbus_connection_register_fallback().
4557 * A single call to dbus_connection_dispatch() will process at most
4558 * one message; it will not clear the entire message queue.
4560 * Be careful about calling dbus_connection_dispatch() from inside a
4561 * message handler, i.e. calling dbus_connection_dispatch()
4562 * recursively. If threads have been initialized with a recursive
4563 * mutex function, then this will not deadlock; however, it can
4564 * certainly confuse your application.
4566 * @todo some FIXME in here about handling DBUS_HANDLER_RESULT_NEED_MEMORY
4568 * @param connection the connection
4569 * @returns dispatch status, see dbus_connection_get_dispatch_status()
4572 dbus_connection_dispatch (DBusConnection *connection)
4574 DBusMessage *message;
4575 DBusList *link, *filter_list_copy, *message_link;
4576 DBusHandlerResult result;
4577 DBusPendingCall *pending;
4578 dbus_int32_t reply_serial;
4579 DBusDispatchStatus status;
4580 dbus_bool_t found_object;
4582 _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
4584 _dbus_verbose ("\n");
4586 CONNECTION_LOCK (connection);
4587 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4588 if (status != DBUS_DISPATCH_DATA_REMAINS)
4590 /* unlocks and calls out to user code */
4591 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4595 /* We need to ref the connection since the callback could potentially
4596 * drop the last ref to it
4598 _dbus_connection_ref_unlocked (connection);
4600 _dbus_connection_acquire_dispatch (connection);
4601 HAVE_LOCK_CHECK (connection);
4603 message_link = _dbus_connection_pop_message_link_unlocked (connection);
4604 if (message_link == NULL)
4606 /* another thread dispatched our stuff */
4608 _dbus_verbose ("another thread dispatched message (during acquire_dispatch above)\n");
4610 _dbus_connection_release_dispatch (connection);
4612 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4614 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4616 dbus_connection_unref (connection);
4621 message = message_link->data;
4623 _dbus_verbose (" dispatching message %p (%s %s %s '%s')\n",
4625 dbus_message_type_to_string (dbus_message_get_type (message)),
4626 dbus_message_get_interface (message) ?
4627 dbus_message_get_interface (message) :
4629 dbus_message_get_member (message) ?
4630 dbus_message_get_member (message) :
4632 dbus_message_get_signature (message));
4634 result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4636 /* Pending call handling must be first, because if you do
4637 * dbus_connection_send_with_reply_and_block() or
4638 * dbus_pending_call_block() then no handlers/filters will be run on
4639 * the reply. We want consistent semantics in the case where we
4640 * dbus_connection_dispatch() the reply.
4643 reply_serial = dbus_message_get_reply_serial (message);
4644 pending = _dbus_hash_table_lookup_int (connection->pending_replies,
4648 _dbus_verbose ("Dispatching a pending reply\n");
4649 complete_pending_call_and_unlock (connection, pending, message);
4650 pending = NULL; /* it's probably unref'd */
4652 CONNECTION_LOCK (connection);
4653 _dbus_verbose ("pending call completed in dispatch\n");
4654 result = DBUS_HANDLER_RESULT_HANDLED;
4658 result = _dbus_connection_run_builtin_filters_unlocked_no_update (connection, message);
4659 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4662 if (!_dbus_list_copy (&connection->filter_list, &filter_list_copy))
4664 _dbus_connection_release_dispatch (connection);
4665 HAVE_LOCK_CHECK (connection);
4667 _dbus_connection_failed_pop (connection, message_link);
4669 /* unlocks and calls user code */
4670 _dbus_connection_update_dispatch_status_and_unlock (connection,
4671 DBUS_DISPATCH_NEED_MEMORY);
4672 dbus_connection_unref (connection);
4674 return DBUS_DISPATCH_NEED_MEMORY;
4677 _dbus_list_foreach (&filter_list_copy,
4678 (DBusForeachFunction)_dbus_message_filter_ref,
4681 /* We're still protected from dispatch() reentrancy here
4682 * since we acquired the dispatcher
4684 CONNECTION_UNLOCK (connection);
4686 link = _dbus_list_get_first_link (&filter_list_copy);
4687 while (link != NULL)
4689 DBusMessageFilter *filter = link->data;
4690 DBusList *next = _dbus_list_get_next_link (&filter_list_copy, link);
4692 if (filter->function == NULL)
4694 _dbus_verbose (" filter was removed in a callback function\n");
4699 _dbus_verbose (" running filter on message %p\n", message);
4700 result = (* filter->function) (connection, message, filter->user_data);
4702 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4708 _dbus_list_foreach (&filter_list_copy,
4709 (DBusForeachFunction)_dbus_message_filter_unref,
4711 _dbus_list_clear (&filter_list_copy);
4713 CONNECTION_LOCK (connection);
4715 if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
4717 _dbus_verbose ("No memory\n");
4720 else if (result == DBUS_HANDLER_RESULT_HANDLED)
4722 _dbus_verbose ("filter handled message in dispatch\n");
4726 /* We're still protected from dispatch() reentrancy here
4727 * since we acquired the dispatcher
4729 _dbus_verbose (" running object path dispatch on message %p (%s %s %s '%s')\n",
4731 dbus_message_type_to_string (dbus_message_get_type (message)),
4732 dbus_message_get_interface (message) ?
4733 dbus_message_get_interface (message) :
4735 dbus_message_get_member (message) ?
4736 dbus_message_get_member (message) :
4738 dbus_message_get_signature (message));
4740 HAVE_LOCK_CHECK (connection);
4741 result = _dbus_object_tree_dispatch_and_unlock (connection->objects,
4745 CONNECTION_LOCK (connection);
4747 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4749 _dbus_verbose ("object tree handled message in dispatch\n");
4753 if (dbus_message_get_type (message) == DBUS_MESSAGE_TYPE_METHOD_CALL)
4757 DBusPreallocatedSend *preallocated;
4758 DBusList *expire_link;
4760 _dbus_verbose (" sending error %s\n",
4761 DBUS_ERROR_UNKNOWN_METHOD);
4763 if (!_dbus_string_init (&str))
4765 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4766 _dbus_verbose ("no memory for error string in dispatch\n");
4770 if (!_dbus_string_append_printf (&str,
4771 "Method \"%s\" with signature \"%s\" on interface \"%s\" doesn't exist\n",
4772 dbus_message_get_member (message),
4773 dbus_message_get_signature (message),
4774 dbus_message_get_interface (message)))
4776 _dbus_string_free (&str);
4777 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4778 _dbus_verbose ("no memory for error string in dispatch\n");
4782 reply = dbus_message_new_error (message,
4783 found_object ? DBUS_ERROR_UNKNOWN_METHOD : DBUS_ERROR_UNKNOWN_OBJECT,
4784 _dbus_string_get_const_data (&str));
4785 _dbus_string_free (&str);
4789 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4790 _dbus_verbose ("no memory for error reply in dispatch\n");
4794 expire_link = _dbus_list_alloc_link (reply);
4796 if (expire_link == NULL)
4798 dbus_message_unref (reply);
4799 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4800 _dbus_verbose ("no memory for error send in dispatch\n");
4804 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
4806 if (preallocated == NULL)
4808 _dbus_list_free_link (expire_link);
4809 /* It's OK that this is finalized, because it hasn't been seen by
4810 * anything that could attach user callbacks */
4811 dbus_message_unref (reply);
4812 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4813 _dbus_verbose ("no memory for error send in dispatch\n");
4817 _dbus_connection_send_preallocated_unlocked_no_update (connection, preallocated,
4819 /* reply will be freed when we release the lock */
4820 _dbus_list_prepend_link (&connection->expired_messages, expire_link);
4822 result = DBUS_HANDLER_RESULT_HANDLED;
4825 _dbus_verbose (" done dispatching %p (%s %s %s '%s') on connection %p\n", message,
4826 dbus_message_type_to_string (dbus_message_get_type (message)),
4827 dbus_message_get_interface (message) ?
4828 dbus_message_get_interface (message) :
4830 dbus_message_get_member (message) ?
4831 dbus_message_get_member (message) :
4833 dbus_message_get_signature (message),
4837 if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
4839 _dbus_verbose ("out of memory\n");
4841 /* Put message back, and we'll start over.
4842 * Yes this means handlers must be idempotent if they
4843 * don't return HANDLED; c'est la vie.
4845 _dbus_connection_putback_message_link_unlocked (connection,
4847 /* now we don't want to free them */
4848 message_link = NULL;
4853 _dbus_verbose (" ... done dispatching\n");
4856 _dbus_connection_release_dispatch (connection);
4857 HAVE_LOCK_CHECK (connection);
4859 if (message != NULL)
4861 /* We don't want this message to count in maximum message limits when
4862 * computing the dispatch status, below. We have to drop the lock
4863 * temporarily, because finalizing a message can trigger callbacks.
4865 * We have a reference to the connection, and we don't use any cached
4866 * pointers to the connection's internals below this point, so it should
4867 * be safe to drop the lock and take it back. */
4868 CONNECTION_UNLOCK (connection);
4869 dbus_message_unref (message);
4870 CONNECTION_LOCK (connection);
4873 if (message_link != NULL)
4874 _dbus_list_free_link (message_link);
4876 _dbus_verbose ("before final status update\n");
4877 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4879 /* unlocks and calls user code */
4880 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4882 dbus_connection_unref (connection);
4888 * Sets the watch functions for the connection. These functions are
4889 * responsible for making the application's main loop aware of file
4890 * descriptors that need to be monitored for events, using select() or
4891 * poll(). When using Qt, typically the DBusAddWatchFunction would
4892 * create a QSocketNotifier. When using GLib, the DBusAddWatchFunction
4893 * could call g_io_add_watch(), or could be used as part of a more
4894 * elaborate GSource. Note that when a watch is added, it may
4897 * The DBusWatchToggledFunction notifies the application that the
4898 * watch has been enabled or disabled. Call dbus_watch_get_enabled()
4899 * to check this. A disabled watch should have no effect, and enabled
4900 * watch should be added to the main loop. This feature is used
4901 * instead of simply adding/removing the watch because
4902 * enabling/disabling can be done without memory allocation. The
4903 * toggled function may be NULL if a main loop re-queries
4904 * dbus_watch_get_enabled() every time anyway.
4906 * The DBusWatch can be queried for the file descriptor to watch using
4907 * dbus_watch_get_unix_fd() or dbus_watch_get_socket(), and for the
4908 * events to watch for using dbus_watch_get_flags(). The flags
4909 * returned by dbus_watch_get_flags() will only contain
4910 * DBUS_WATCH_READABLE and DBUS_WATCH_WRITABLE, never
4911 * DBUS_WATCH_HANGUP or DBUS_WATCH_ERROR; all watches implicitly
4912 * include a watch for hangups, errors, and other exceptional
4915 * Once a file descriptor becomes readable or writable, or an exception
4916 * occurs, dbus_watch_handle() should be called to
4917 * notify the connection of the file descriptor's condition.
4919 * dbus_watch_handle() cannot be called during the
4920 * DBusAddWatchFunction, as the connection will not be ready to handle
4923 * It is not allowed to reference a DBusWatch after it has been passed
4924 * to remove_function.
4926 * If #FALSE is returned due to lack of memory, the failure may be due
4927 * to a #FALSE return from the new add_function. If so, the
4928 * add_function may have been called successfully one or more times,
4929 * but the remove_function will also have been called to remove any
4930 * successful adds. i.e. if #FALSE is returned the net result
4931 * should be that dbus_connection_set_watch_functions() has no effect,
4932 * but the add_function and remove_function may have been called.
4934 * @note The thread lock on DBusConnection is held while
4935 * watch functions are invoked, so inside these functions you
4936 * may not invoke any methods on DBusConnection or it will deadlock.
4937 * See the comments in the code or http://lists.freedesktop.org/archives/dbus/2007-July/tread.html#8144
4938 * if you encounter this issue and want to attempt writing a patch.
4940 * @param connection the connection.
4941 * @param add_function function to begin monitoring a new descriptor.
4942 * @param remove_function function to stop monitoring a descriptor.
4943 * @param toggled_function function to notify of enable/disable
4944 * @param data data to pass to add_function and remove_function.
4945 * @param free_data_function function to be called to free the data.
4946 * @returns #FALSE on failure (no memory)
4949 dbus_connection_set_watch_functions (DBusConnection *connection,
4950 DBusAddWatchFunction add_function,
4951 DBusRemoveWatchFunction remove_function,
4952 DBusWatchToggledFunction toggled_function,
4954 DBusFreeFunction free_data_function)
4958 _dbus_return_val_if_fail (connection != NULL, FALSE);
4960 CONNECTION_LOCK (connection);
4962 retval = _dbus_watch_list_set_functions (connection->watches,
4963 add_function, remove_function,
4965 data, free_data_function);
4967 CONNECTION_UNLOCK (connection);
4973 * Sets the timeout functions for the connection. These functions are
4974 * responsible for making the application's main loop aware of timeouts.
4975 * When using Qt, typically the DBusAddTimeoutFunction would create a
4976 * QTimer. When using GLib, the DBusAddTimeoutFunction would call
4979 * The DBusTimeoutToggledFunction notifies the application that the
4980 * timeout has been enabled or disabled. Call
4981 * dbus_timeout_get_enabled() to check this. A disabled timeout should
4982 * have no effect, and enabled timeout should be added to the main
4983 * loop. This feature is used instead of simply adding/removing the
4984 * timeout because enabling/disabling can be done without memory
4985 * allocation. With Qt, QTimer::start() and QTimer::stop() can be used
4986 * to enable and disable. The toggled function may be NULL if a main
4987 * loop re-queries dbus_timeout_get_enabled() every time anyway.
4988 * Whenever a timeout is toggled, its interval may change.
4990 * The DBusTimeout can be queried for the timer interval using
4991 * dbus_timeout_get_interval(). dbus_timeout_handle() should be called
4992 * repeatedly, each time the interval elapses, starting after it has
4993 * elapsed once. The timeout stops firing when it is removed with the
4994 * given remove_function. The timer interval may change whenever the
4995 * timeout is added, removed, or toggled.
4997 * @note The thread lock on DBusConnection is held while
4998 * timeout functions are invoked, so inside these functions you
4999 * may not invoke any methods on DBusConnection or it will deadlock.
5000 * See the comments in the code or http://lists.freedesktop.org/archives/dbus/2007-July/thread.html#8144
5001 * if you encounter this issue and want to attempt writing a patch.
5003 * @param connection the connection.
5004 * @param add_function function to add a timeout.
5005 * @param remove_function function to remove a timeout.
5006 * @param toggled_function function to notify of enable/disable
5007 * @param data data to pass to add_function and remove_function.
5008 * @param free_data_function function to be called to free the data.
5009 * @returns #FALSE on failure (no memory)
5012 dbus_connection_set_timeout_functions (DBusConnection *connection,
5013 DBusAddTimeoutFunction add_function,
5014 DBusRemoveTimeoutFunction remove_function,
5015 DBusTimeoutToggledFunction toggled_function,
5017 DBusFreeFunction free_data_function)
5021 _dbus_return_val_if_fail (connection != NULL, FALSE);
5023 CONNECTION_LOCK (connection);
5025 retval = _dbus_timeout_list_set_functions (connection->timeouts,
5026 add_function, remove_function,
5028 data, free_data_function);
5030 CONNECTION_UNLOCK (connection);
5036 * Sets the mainloop wakeup function for the connection. This function
5037 * is responsible for waking up the main loop (if its sleeping in
5038 * another thread) when some some change has happened to the
5039 * connection that the mainloop needs to reconsider (e.g. a message
5040 * has been queued for writing). When using Qt, this typically
5041 * results in a call to QEventLoop::wakeUp(). When using GLib, it
5042 * would call g_main_context_wakeup().
5044 * @param connection the connection.
5045 * @param wakeup_main_function function to wake up the mainloop
5046 * @param data data to pass wakeup_main_function
5047 * @param free_data_function function to be called to free the data.
5050 dbus_connection_set_wakeup_main_function (DBusConnection *connection,
5051 DBusWakeupMainFunction wakeup_main_function,
5053 DBusFreeFunction free_data_function)
5056 DBusFreeFunction old_free_data;
5058 _dbus_return_if_fail (connection != NULL);
5060 CONNECTION_LOCK (connection);
5061 old_data = connection->wakeup_main_data;
5062 old_free_data = connection->free_wakeup_main_data;
5064 connection->wakeup_main_function = wakeup_main_function;
5065 connection->wakeup_main_data = data;
5066 connection->free_wakeup_main_data = free_data_function;
5068 CONNECTION_UNLOCK (connection);
5070 /* Callback outside the lock */
5072 (*old_free_data) (old_data);
5076 * Set a function to be invoked when the dispatch status changes.
5077 * If the dispatch status is #DBUS_DISPATCH_DATA_REMAINS, then
5078 * dbus_connection_dispatch() needs to be called to process incoming
5079 * messages. However, dbus_connection_dispatch() MUST NOT BE CALLED
5080 * from inside the DBusDispatchStatusFunction. Indeed, almost
5081 * any reentrancy in this function is a bad idea. Instead,
5082 * the DBusDispatchStatusFunction should simply save an indication
5083 * that messages should be dispatched later, when the main loop
5086 * If you don't set a dispatch status function, you have to be sure to
5087 * dispatch on every iteration of your main loop, especially if
5088 * dbus_watch_handle() or dbus_timeout_handle() were called.
5090 * @param connection the connection
5091 * @param function function to call on dispatch status changes
5092 * @param data data for function
5093 * @param free_data_function free the function data
5096 dbus_connection_set_dispatch_status_function (DBusConnection *connection,
5097 DBusDispatchStatusFunction 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->dispatch_status_data;
5108 old_free_data = connection->free_dispatch_status_data;
5110 connection->dispatch_status_function = function;
5111 connection->dispatch_status_data = data;
5112 connection->free_dispatch_status_data = free_data_function;
5114 CONNECTION_UNLOCK (connection);
5116 /* Callback outside the lock */
5118 (*old_free_data) (old_data);
5122 * Get the UNIX file descriptor of the connection, if any. This can
5123 * be used for SELinux access control checks with getpeercon() for
5124 * example. DO NOT read or write to the file descriptor, or try to
5125 * select() on it; use DBusWatch for main loop integration. Not all
5126 * connections will have a file descriptor. So for adding descriptors
5127 * to the main loop, use dbus_watch_get_unix_fd() and so forth.
5129 * If the connection is socket-based, you can also use
5130 * dbus_connection_get_socket(), which will work on Windows too.
5131 * This function always fails on Windows.
5133 * Right now the returned descriptor is always a socket, but
5134 * that is not guaranteed.
5136 * @param connection the connection
5137 * @param fd return location for the file descriptor.
5138 * @returns #TRUE if fd is successfully obtained.
5141 dbus_connection_get_unix_fd (DBusConnection *connection,
5144 _dbus_return_val_if_fail (connection != NULL, FALSE);
5145 _dbus_return_val_if_fail (connection->transport != NULL, FALSE);
5148 /* FIXME do this on a lower level */
5152 return dbus_connection_get_socket(connection, fd);
5156 * Gets the underlying Windows or UNIX socket file descriptor
5157 * of the connection, if any. DO NOT read or write to the file descriptor, or try to
5158 * select() on it; use DBusWatch for main loop integration. Not all
5159 * connections will have a socket. So for adding descriptors
5160 * to the main loop, use dbus_watch_get_socket() and so forth.
5162 * If the connection is not socket-based, this function will return FALSE,
5163 * even if the connection does have a file descriptor of some kind.
5164 * i.e. this function always returns specifically a socket file descriptor.
5166 * @param connection the connection
5167 * @param fd return location for the file descriptor.
5168 * @returns #TRUE if fd is successfully obtained.
5171 dbus_connection_get_socket(DBusConnection *connection,
5176 _dbus_return_val_if_fail (connection != NULL, FALSE);
5177 _dbus_return_val_if_fail (connection->transport != NULL, FALSE);
5179 CONNECTION_LOCK (connection);
5181 retval = _dbus_transport_get_socket_fd (connection->transport,
5184 CONNECTION_UNLOCK (connection);
5191 * Gets the UNIX user ID of the connection if known. Returns #TRUE if
5192 * the uid is filled in. Always returns #FALSE on non-UNIX platforms
5193 * for now, though in theory someone could hook Windows to NIS or
5194 * something. Always returns #FALSE prior to authenticating the
5197 * The UID is only read by servers from clients; clients can't usually
5198 * get the UID of servers, because servers do not authenticate to
5199 * clients. The returned UID is the UID the connection authenticated
5202 * The message bus is a server and the apps connecting to the bus
5205 * You can ask the bus to tell you the UID of another connection though
5206 * if you like; this is done with dbus_bus_get_unix_user().
5208 * @param connection the connection
5209 * @param uid return location for the user ID
5210 * @returns #TRUE if uid is filled in with a valid user ID
5213 dbus_connection_get_unix_user (DBusConnection *connection,
5218 _dbus_return_val_if_fail (connection != NULL, FALSE);
5219 _dbus_return_val_if_fail (uid != NULL, FALSE);
5221 CONNECTION_LOCK (connection);
5223 if (!_dbus_transport_try_to_authenticate (connection->transport))
5226 result = _dbus_transport_get_unix_user (connection->transport,
5230 _dbus_assert (!result);
5233 CONNECTION_UNLOCK (connection);
5239 * Gets the process ID of the connection if any.
5240 * Returns #TRUE if the pid is filled in.
5241 * Always returns #FALSE prior to authenticating the
5244 * @param connection the connection
5245 * @param pid return location for the process ID
5246 * @returns #TRUE if uid is filled in with a valid process ID
5249 dbus_connection_get_unix_process_id (DBusConnection *connection,
5254 _dbus_return_val_if_fail (connection != NULL, FALSE);
5255 _dbus_return_val_if_fail (pid != NULL, FALSE);
5257 CONNECTION_LOCK (connection);
5259 if (!_dbus_transport_try_to_authenticate (connection->transport))
5262 result = _dbus_transport_get_unix_process_id (connection->transport,
5265 CONNECTION_UNLOCK (connection);
5271 * Gets the ADT audit data of the connection if any.
5272 * Returns #TRUE if the structure pointer is returned.
5273 * Always returns #FALSE prior to authenticating the
5276 * @param connection the connection
5277 * @param data return location for audit data
5278 * @param data_size return location for length of audit data
5279 * @returns #TRUE if audit data is filled in with a valid ucred pointer
5282 dbus_connection_get_adt_audit_session_data (DBusConnection *connection,
5284 dbus_int32_t *data_size)
5288 _dbus_return_val_if_fail (connection != NULL, FALSE);
5289 _dbus_return_val_if_fail (data != NULL, FALSE);
5290 _dbus_return_val_if_fail (data_size != NULL, FALSE);
5292 CONNECTION_LOCK (connection);
5294 if (!_dbus_transport_try_to_authenticate (connection->transport))
5297 result = _dbus_transport_get_adt_audit_session_data (connection->transport,
5300 CONNECTION_UNLOCK (connection);
5306 * Sets a predicate function used to determine whether a given user ID
5307 * is allowed to connect. When an incoming connection has
5308 * authenticated with a particular user ID, this function is called;
5309 * if it returns #TRUE, the connection is allowed to proceed,
5310 * otherwise the connection is disconnected.
5312 * If the function is set to #NULL (as it is by default), then
5313 * only the same UID as the server process will be allowed to
5314 * connect. Also, root is always allowed to connect.
5316 * On Windows, the function will be set and its free_data_function will
5317 * be invoked when the connection is freed or a new function is set.
5318 * However, the function will never be called, because there are
5319 * no UNIX user ids to pass to it, or at least none of the existing
5320 * auth protocols would allow authenticating as a UNIX user on Windows.
5322 * @param connection the connection
5323 * @param function the predicate
5324 * @param data data to pass to the predicate
5325 * @param free_data_function function to free the data
5328 dbus_connection_set_unix_user_function (DBusConnection *connection,
5329 DBusAllowUnixUserFunction function,
5331 DBusFreeFunction free_data_function)
5333 void *old_data = NULL;
5334 DBusFreeFunction old_free_function = NULL;
5336 _dbus_return_if_fail (connection != NULL);
5338 CONNECTION_LOCK (connection);
5339 _dbus_transport_set_unix_user_function (connection->transport,
5340 function, data, free_data_function,
5341 &old_data, &old_free_function);
5342 CONNECTION_UNLOCK (connection);
5344 if (old_free_function != NULL)
5345 (* old_free_function) (old_data);
5349 * Gets the Windows user SID of the connection if known. Returns
5350 * #TRUE if the ID is filled in. Always returns #FALSE on non-Windows
5351 * platforms for now, though in theory someone could hook UNIX to
5352 * Active Directory or something. Always returns #FALSE prior to
5353 * authenticating the connection.
5355 * The user is only read by servers from clients; clients can't usually
5356 * get the user of servers, because servers do not authenticate to
5357 * clients. The returned user is the user the connection authenticated
5360 * The message bus is a server and the apps connecting to the bus
5363 * The returned user string has to be freed with dbus_free().
5365 * The return value indicates whether the user SID is available;
5366 * if it's available but we don't have the memory to copy it,
5367 * then the return value is #TRUE and #NULL is given as the SID.
5369 * @todo We would like to be able to say "You can ask the bus to tell
5370 * you the user of another connection though if you like; this is done
5371 * with dbus_bus_get_windows_user()." But this has to be implemented
5372 * in bus/driver.c and dbus/dbus-bus.c, and is pointless anyway
5373 * since on Windows we only use the session bus for now.
5375 * @param connection the connection
5376 * @param windows_sid_p return location for an allocated copy of the user ID, or #NULL if no memory
5377 * @returns #TRUE if user is available (returned value may be #NULL anyway if no memory)
5380 dbus_connection_get_windows_user (DBusConnection *connection,
5381 char **windows_sid_p)
5385 _dbus_return_val_if_fail (connection != NULL, FALSE);
5386 _dbus_return_val_if_fail (windows_sid_p != NULL, FALSE);
5388 CONNECTION_LOCK (connection);
5390 if (!_dbus_transport_try_to_authenticate (connection->transport))
5393 result = _dbus_transport_get_windows_user (connection->transport,
5397 _dbus_assert (!result);
5400 CONNECTION_UNLOCK (connection);
5406 * Sets a predicate function used to determine whether a given user ID
5407 * is allowed to connect. When an incoming connection has
5408 * authenticated with a particular user ID, this function is called;
5409 * if it returns #TRUE, the connection is allowed to proceed,
5410 * otherwise the connection is disconnected.
5412 * If the function is set to #NULL (as it is by default), then
5413 * only the same user owning the server process will be allowed to
5416 * On UNIX, the function will be set and its free_data_function will
5417 * be invoked when the connection is freed or a new function is set.
5418 * However, the function will never be called, because there is no
5419 * way right now to authenticate as a Windows user on UNIX.
5421 * @param connection the connection
5422 * @param function the predicate
5423 * @param data data to pass to the predicate
5424 * @param free_data_function function to free the data
5427 dbus_connection_set_windows_user_function (DBusConnection *connection,
5428 DBusAllowWindowsUserFunction function,
5430 DBusFreeFunction free_data_function)
5432 void *old_data = NULL;
5433 DBusFreeFunction old_free_function = NULL;
5435 _dbus_return_if_fail (connection != NULL);
5437 CONNECTION_LOCK (connection);
5438 _dbus_transport_set_windows_user_function (connection->transport,
5439 function, data, free_data_function,
5440 &old_data, &old_free_function);
5441 CONNECTION_UNLOCK (connection);
5443 if (old_free_function != NULL)
5444 (* old_free_function) (old_data);
5448 * This function must be called on the server side of a connection when the
5449 * connection is first seen in the #DBusNewConnectionFunction. If set to
5450 * #TRUE (the default is #FALSE), then the connection can proceed even if
5451 * the client does not authenticate as some user identity, i.e. clients
5452 * can connect anonymously.
5454 * This setting interacts with the available authorization mechanisms
5455 * (see dbus_server_set_auth_mechanisms()). Namely, an auth mechanism
5456 * such as ANONYMOUS that supports anonymous auth must be included in
5457 * the list of available mechanisms for anonymous login to work.
5459 * This setting also changes the default rule for connections
5460 * authorized as a user; normally, if a connection authorizes as
5461 * a user identity, it is permitted if the user identity is
5462 * root or the user identity matches the user identity of the server
5463 * process. If anonymous connections are allowed, however,
5464 * then any user identity is allowed.
5466 * You can override the rules for connections authorized as a
5467 * user identity with dbus_connection_set_unix_user_function()
5468 * and dbus_connection_set_windows_user_function().
5470 * @param connection the connection
5471 * @param value whether to allow authentication as an anonymous user
5474 dbus_connection_set_allow_anonymous (DBusConnection *connection,
5477 _dbus_return_if_fail (connection != NULL);
5479 CONNECTION_LOCK (connection);
5480 _dbus_transport_set_allow_anonymous (connection->transport, value);
5481 CONNECTION_UNLOCK (connection);
5486 * Normally #DBusConnection automatically handles all messages to the
5487 * org.freedesktop.DBus.Peer interface. However, the message bus wants
5488 * to be able to route methods on that interface through the bus and
5489 * to other applications. If routing peer messages is enabled, then
5490 * messages with the org.freedesktop.DBus.Peer interface that also
5491 * have a bus destination name set will not be automatically
5492 * handled by the #DBusConnection and instead will be dispatched
5493 * normally to the application.
5495 * If a normal application sets this flag, it can break things badly.
5496 * So don't set this unless you are the message bus.
5498 * @param connection the connection
5499 * @param value #TRUE to pass through org.freedesktop.DBus.Peer messages with a bus name set
5502 dbus_connection_set_route_peer_messages (DBusConnection *connection,
5505 _dbus_return_if_fail (connection != NULL);
5507 CONNECTION_LOCK (connection);
5508 connection->route_peer_messages = TRUE;
5509 CONNECTION_UNLOCK (connection);
5513 * Adds a message filter. Filters are handlers that are run on all
5514 * incoming messages, prior to the objects registered with
5515 * dbus_connection_register_object_path(). Filters are run in the
5516 * order that they were added. The same handler can be added as a
5517 * filter more than once, in which case it will be run more than once.
5518 * Filters added during a filter callback won't be run on the message
5521 * @todo we don't run filters on messages while blocking without
5522 * entering the main loop, since filters are run as part of
5523 * dbus_connection_dispatch(). This is probably a feature, as filters
5524 * could create arbitrary reentrancy. But kind of sucks if you're
5525 * trying to filter METHOD_RETURN for some reason.
5527 * @param connection the connection
5528 * @param function function to handle messages
5529 * @param user_data user data to pass to the function
5530 * @param free_data_function function to use for freeing user data
5531 * @returns #TRUE on success, #FALSE if not enough memory.
5534 dbus_connection_add_filter (DBusConnection *connection,
5535 DBusHandleMessageFunction function,
5537 DBusFreeFunction free_data_function)
5539 DBusMessageFilter *filter;
5541 _dbus_return_val_if_fail (connection != NULL, FALSE);
5542 _dbus_return_val_if_fail (function != NULL, FALSE);
5544 filter = dbus_new0 (DBusMessageFilter, 1);
5548 _dbus_atomic_inc (&filter->refcount);
5550 CONNECTION_LOCK (connection);
5552 if (!_dbus_list_append (&connection->filter_list,
5555 _dbus_message_filter_unref (filter);
5556 CONNECTION_UNLOCK (connection);
5560 /* Fill in filter after all memory allocated,
5561 * so we don't run the free_user_data_function
5562 * if the add_filter() fails
5565 filter->function = function;
5566 filter->user_data = user_data;
5567 filter->free_user_data_function = free_data_function;
5569 CONNECTION_UNLOCK (connection);
5574 * Removes a previously-added message filter. It is a programming
5575 * error to call this function for a handler that has not been added
5576 * as a filter. If the given handler was added more than once, only
5577 * one instance of it will be removed (the most recently-added
5580 * @param connection the connection
5581 * @param function the handler to remove
5582 * @param user_data user data for the handler to remove
5586 dbus_connection_remove_filter (DBusConnection *connection,
5587 DBusHandleMessageFunction function,
5591 DBusMessageFilter *filter;
5593 _dbus_return_if_fail (connection != NULL);
5594 _dbus_return_if_fail (function != NULL);
5596 CONNECTION_LOCK (connection);
5600 link = _dbus_list_get_last_link (&connection->filter_list);
5601 while (link != NULL)
5603 filter = link->data;
5605 if (filter->function == function &&
5606 filter->user_data == user_data)
5608 _dbus_list_remove_link (&connection->filter_list, link);
5609 filter->function = NULL;
5614 link = _dbus_list_get_prev_link (&connection->filter_list, link);
5618 CONNECTION_UNLOCK (connection);
5620 #ifndef DBUS_DISABLE_CHECKS
5623 _dbus_warn_check_failed ("Attempt to remove filter function %p user data %p, but no such filter has been added\n",
5624 function, user_data);
5629 /* Call application code */
5630 if (filter->free_user_data_function)
5631 (* filter->free_user_data_function) (filter->user_data);
5633 filter->free_user_data_function = NULL;
5634 filter->user_data = NULL;
5636 _dbus_message_filter_unref (filter);
5640 * Registers a handler for a given path or subsection in the object
5641 * hierarchy. The given vtable handles messages sent to exactly the
5642 * given path or also for paths bellow that, depending on fallback
5645 * @param connection the connection
5646 * @param fallback whether to handle messages also for "subdirectory"
5647 * @param path a '/' delimited string of path elements
5648 * @param vtable the virtual table
5649 * @param user_data data to pass to functions in the vtable
5650 * @param error address where an error can be returned
5651 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5652 * #DBUS_ERROR_OBJECT_PATH_IN_USE) is reported
5655 _dbus_connection_register_object_path (DBusConnection *connection,
5656 dbus_bool_t fallback,
5658 const DBusObjectPathVTable *vtable,
5662 char **decomposed_path;
5665 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5668 CONNECTION_LOCK (connection);
5670 retval = _dbus_object_tree_register (connection->objects,
5672 (const char **) decomposed_path, vtable,
5675 CONNECTION_UNLOCK (connection);
5677 dbus_free_string_array (decomposed_path);
5683 * Registers a handler for a given path in the object hierarchy.
5684 * The given vtable handles messages sent to exactly the given path.
5686 * @param connection the connection
5687 * @param path a '/' delimited string of path elements
5688 * @param vtable the virtual table
5689 * @param user_data data to pass to functions in the vtable
5690 * @param error address where an error can be returned
5691 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5692 * #DBUS_ERROR_OBJECT_PATH_IN_USE) is reported
5695 dbus_connection_try_register_object_path (DBusConnection *connection,
5697 const DBusObjectPathVTable *vtable,
5701 _dbus_return_val_if_fail (connection != NULL, FALSE);
5702 _dbus_return_val_if_fail (path != NULL, FALSE);
5703 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5704 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5706 return _dbus_connection_register_object_path (connection, FALSE, path, vtable, user_data, error);
5710 * Registers a handler for a given path in the object hierarchy.
5711 * The given vtable handles messages sent to exactly the given path.
5713 * It is a bug to call this function for object paths which already
5714 * have a handler. Use dbus_connection_try_register_object_path() if this
5715 * might be the case.
5717 * @param connection the connection
5718 * @param path a '/' delimited string of path elements
5719 * @param vtable the virtual table
5720 * @param user_data data to pass to functions in the vtable
5721 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5722 * #DBUS_ERROR_OBJECT_PATH_IN_USE) ocurred
5725 dbus_connection_register_object_path (DBusConnection *connection,
5727 const DBusObjectPathVTable *vtable,
5731 DBusError error = DBUS_ERROR_INIT;
5733 _dbus_return_val_if_fail (connection != NULL, FALSE);
5734 _dbus_return_val_if_fail (path != NULL, FALSE);
5735 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5736 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5738 retval = _dbus_connection_register_object_path (connection, FALSE, path, vtable, user_data, &error);
5740 if (dbus_error_has_name (&error, DBUS_ERROR_OBJECT_PATH_IN_USE))
5742 _dbus_warn ("%s\n", error.message);
5743 dbus_error_free (&error);
5751 * Registers a fallback handler for a given subsection of the object
5752 * hierarchy. The given vtable handles messages at or below the given
5753 * path. You can use this to establish a default message handling
5754 * policy for a whole "subdirectory."
5756 * @param connection the connection
5757 * @param path a '/' delimited string of path elements
5758 * @param vtable the virtual table
5759 * @param user_data data to pass to functions in the vtable
5760 * @param error address where an error can be returned
5761 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5762 * #DBUS_ERROR_OBJECT_PATH_IN_USE) is reported
5765 dbus_connection_try_register_fallback (DBusConnection *connection,
5767 const DBusObjectPathVTable *vtable,
5771 _dbus_return_val_if_fail (connection != NULL, FALSE);
5772 _dbus_return_val_if_fail (path != NULL, FALSE);
5773 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5774 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5776 return _dbus_connection_register_object_path (connection, TRUE, path, vtable, user_data, error);
5780 * Registers a fallback handler for a given subsection of the object
5781 * hierarchy. The given vtable handles messages at or below the given
5782 * path. You can use this to establish a default message handling
5783 * policy for a whole "subdirectory."
5785 * It is a bug to call this function for object paths which already
5786 * have a handler. Use dbus_connection_try_register_fallback() if this
5787 * might be the case.
5789 * @param connection the connection
5790 * @param path a '/' delimited string of path elements
5791 * @param vtable the virtual table
5792 * @param user_data data to pass to functions in the vtable
5793 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5794 * #DBUS_ERROR_OBJECT_PATH_IN_USE) occured
5797 dbus_connection_register_fallback (DBusConnection *connection,
5799 const DBusObjectPathVTable *vtable,
5803 DBusError error = DBUS_ERROR_INIT;
5805 _dbus_return_val_if_fail (connection != NULL, FALSE);
5806 _dbus_return_val_if_fail (path != NULL, FALSE);
5807 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5808 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5810 retval = _dbus_connection_register_object_path (connection, TRUE, path, vtable, user_data, &error);
5812 if (dbus_error_has_name (&error, DBUS_ERROR_OBJECT_PATH_IN_USE))
5814 _dbus_warn ("%s\n", error.message);
5815 dbus_error_free (&error);
5823 * Unregisters the handler registered with exactly the given path.
5824 * It's a bug to call this function for a path that isn't registered.
5825 * Can unregister both fallback paths and object paths.
5827 * @param connection the connection
5828 * @param path a '/' delimited string of path elements
5829 * @returns #FALSE if not enough memory
5832 dbus_connection_unregister_object_path (DBusConnection *connection,
5835 char **decomposed_path;
5837 _dbus_return_val_if_fail (connection != NULL, FALSE);
5838 _dbus_return_val_if_fail (path != NULL, FALSE);
5839 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5841 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5844 CONNECTION_LOCK (connection);
5846 _dbus_object_tree_unregister_and_unlock (connection->objects, (const char **) decomposed_path);
5848 dbus_free_string_array (decomposed_path);
5854 * Gets the user data passed to dbus_connection_register_object_path()
5855 * or dbus_connection_register_fallback(). If nothing was registered
5856 * at this path, the data is filled in with #NULL.
5858 * @param connection the connection
5859 * @param path the path you registered with
5860 * @param data_p location to store the user data, or #NULL
5861 * @returns #FALSE if not enough memory
5864 dbus_connection_get_object_path_data (DBusConnection *connection,
5868 char **decomposed_path;
5870 _dbus_return_val_if_fail (connection != NULL, FALSE);
5871 _dbus_return_val_if_fail (path != NULL, FALSE);
5872 _dbus_return_val_if_fail (data_p != NULL, FALSE);
5876 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5879 CONNECTION_LOCK (connection);
5881 *data_p = _dbus_object_tree_get_user_data_unlocked (connection->objects, (const char**) decomposed_path);
5883 CONNECTION_UNLOCK (connection);
5885 dbus_free_string_array (decomposed_path);
5891 * Lists the registered fallback handlers and object path handlers at
5892 * the given parent_path. The returned array should be freed with
5893 * dbus_free_string_array().
5895 * @param connection the connection
5896 * @param parent_path the path to list the child handlers of
5897 * @param child_entries returns #NULL-terminated array of children
5898 * @returns #FALSE if no memory to allocate the child entries
5901 dbus_connection_list_registered (DBusConnection *connection,
5902 const char *parent_path,
5903 char ***child_entries)
5905 char **decomposed_path;
5907 _dbus_return_val_if_fail (connection != NULL, FALSE);
5908 _dbus_return_val_if_fail (parent_path != NULL, FALSE);
5909 _dbus_return_val_if_fail (parent_path[0] == '/', FALSE);
5910 _dbus_return_val_if_fail (child_entries != NULL, FALSE);
5912 if (!_dbus_decompose_path (parent_path, strlen (parent_path), &decomposed_path, NULL))
5915 CONNECTION_LOCK (connection);
5917 retval = _dbus_object_tree_list_registered_and_unlock (connection->objects,
5918 (const char **) decomposed_path,
5920 dbus_free_string_array (decomposed_path);
5925 static DBusDataSlotAllocator slot_allocator =
5926 _DBUS_DATA_SLOT_ALLOCATOR_INIT (_DBUS_LOCK_NAME (connection_slots));
5929 * Allocates an integer ID to be used for storing application-specific
5930 * data on any DBusConnection. The allocated ID may then be used
5931 * with dbus_connection_set_data() and dbus_connection_get_data().
5932 * The passed-in slot must be initialized to -1, and is filled in
5933 * with the slot ID. If the passed-in slot is not -1, it's assumed
5934 * to be already allocated, and its refcount is incremented.
5936 * The allocated slot is global, i.e. all DBusConnection objects will
5937 * have a slot with the given integer ID reserved.
5939 * @param slot_p address of a global variable storing the slot
5940 * @returns #FALSE on failure (no memory)
5943 dbus_connection_allocate_data_slot (dbus_int32_t *slot_p)
5945 return _dbus_data_slot_allocator_alloc (&slot_allocator,
5950 * Deallocates a global ID for connection data slots.
5951 * dbus_connection_get_data() and dbus_connection_set_data() may no
5952 * longer be used with this slot. Existing data stored on existing
5953 * DBusConnection objects will be freed when the connection is
5954 * finalized, but may not be retrieved (and may only be replaced if
5955 * someone else reallocates the slot). When the refcount on the
5956 * passed-in slot reaches 0, it is set to -1.
5958 * @param slot_p address storing the slot to deallocate
5961 dbus_connection_free_data_slot (dbus_int32_t *slot_p)
5963 _dbus_return_if_fail (*slot_p >= 0);
5965 _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
5969 * Stores a pointer on a DBusConnection, along
5970 * with an optional function to be used for freeing
5971 * the data when the data is set again, or when
5972 * the connection is finalized. The slot number
5973 * must have been allocated with dbus_connection_allocate_data_slot().
5975 * @note This function does not take the
5976 * main thread lock on DBusConnection, which allows it to be
5977 * used from inside watch and timeout functions. (See the
5978 * note in docs for dbus_connection_set_watch_functions().)
5979 * A side effect of this is that you need to know there's
5980 * a reference held on the connection while invoking
5981 * dbus_connection_set_data(), or the connection could be
5982 * finalized during dbus_connection_set_data().
5984 * @param connection the connection
5985 * @param slot the slot number
5986 * @param data the data to store
5987 * @param free_data_func finalizer function for the data
5988 * @returns #TRUE if there was enough memory to store the data
5991 dbus_connection_set_data (DBusConnection *connection,
5994 DBusFreeFunction free_data_func)
5996 DBusFreeFunction old_free_func;
6000 _dbus_return_val_if_fail (connection != NULL, FALSE);
6001 _dbus_return_val_if_fail (slot >= 0, FALSE);
6003 SLOTS_LOCK (connection);
6005 retval = _dbus_data_slot_list_set (&slot_allocator,
6006 &connection->slot_list,
6007 slot, data, free_data_func,
6008 &old_free_func, &old_data);
6010 SLOTS_UNLOCK (connection);
6014 /* Do the actual free outside the connection lock */
6016 (* old_free_func) (old_data);
6023 * Retrieves data previously set with dbus_connection_set_data().
6024 * The slot must still be allocated (must not have been freed).
6026 * @note This function does not take the
6027 * main thread lock on DBusConnection, which allows it to be
6028 * used from inside watch and timeout functions. (See the
6029 * note in docs for dbus_connection_set_watch_functions().)
6030 * A side effect of this is that you need to know there's
6031 * a reference held on the connection while invoking
6032 * dbus_connection_get_data(), or the connection could be
6033 * finalized during dbus_connection_get_data().
6035 * @param connection the connection
6036 * @param slot the slot to get data from
6037 * @returns the data, or #NULL if not found
6040 dbus_connection_get_data (DBusConnection *connection,
6045 _dbus_return_val_if_fail (connection != NULL, NULL);
6046 _dbus_return_val_if_fail (slot >= 0, NULL);
6048 SLOTS_LOCK (connection);
6050 res = _dbus_data_slot_list_get (&slot_allocator,
6051 &connection->slot_list,
6054 SLOTS_UNLOCK (connection);
6060 * This function sets a global flag for whether dbus_connection_new()
6061 * will set SIGPIPE behavior to SIG_IGN.
6063 * @param will_modify_sigpipe #TRUE to allow sigpipe to be set to SIG_IGN
6066 dbus_connection_set_change_sigpipe (dbus_bool_t will_modify_sigpipe)
6068 _dbus_modify_sigpipe = will_modify_sigpipe != FALSE;
6072 * Specifies the maximum size message this connection is allowed to
6073 * receive. Larger messages will result in disconnecting the
6076 * @param connection a #DBusConnection
6077 * @param size maximum message size the connection can receive, in bytes
6080 dbus_connection_set_max_message_size (DBusConnection *connection,
6083 _dbus_return_if_fail (connection != NULL);
6085 CONNECTION_LOCK (connection);
6086 _dbus_transport_set_max_message_size (connection->transport,
6088 CONNECTION_UNLOCK (connection);
6092 * Gets the value set by dbus_connection_set_max_message_size().
6094 * @param connection the connection
6095 * @returns the max size of a single message
6098 dbus_connection_get_max_message_size (DBusConnection *connection)
6102 _dbus_return_val_if_fail (connection != NULL, 0);
6104 CONNECTION_LOCK (connection);
6105 res = _dbus_transport_get_max_message_size (connection->transport);
6106 CONNECTION_UNLOCK (connection);
6111 * Specifies the maximum number of unix fds a message on this
6112 * connection is allowed to receive. Messages with more unix fds will
6113 * result in disconnecting the connection.
6115 * @param connection a #DBusConnection
6116 * @param n maximum message unix fds the connection can receive
6119 dbus_connection_set_max_message_unix_fds (DBusConnection *connection,
6122 _dbus_return_if_fail (connection != NULL);
6124 CONNECTION_LOCK (connection);
6125 _dbus_transport_set_max_message_unix_fds (connection->transport,
6127 CONNECTION_UNLOCK (connection);
6131 * Gets the value set by dbus_connection_set_max_message_unix_fds().
6133 * @param connection the connection
6134 * @returns the max numer of unix fds of a single message
6137 dbus_connection_get_max_message_unix_fds (DBusConnection *connection)
6141 _dbus_return_val_if_fail (connection != NULL, 0);
6143 CONNECTION_LOCK (connection);
6144 res = _dbus_transport_get_max_message_unix_fds (connection->transport);
6145 CONNECTION_UNLOCK (connection);
6150 * Sets the maximum total number of bytes that can be used for all messages
6151 * received on this connection. Messages count toward the maximum until
6152 * they are finalized. When the maximum is reached, the connection will
6153 * not read more data until some messages are finalized.
6155 * The semantics of the maximum are: if outstanding messages are
6156 * already above the maximum, additional messages will not be read.
6157 * The semantics are not: if the next message would cause us to exceed
6158 * the maximum, we don't read it. The reason is that we don't know the
6159 * size of a message until after we read it.
6161 * Thus, the max live messages size can actually be exceeded
6162 * by up to the maximum size of a single message.
6164 * Also, if we read say 1024 bytes off the wire in a single read(),
6165 * and that contains a half-dozen small messages, we may exceed the
6166 * size max by that amount. But this should be inconsequential.
6168 * This does imply that we can't call read() with a buffer larger
6169 * than we're willing to exceed this limit by.
6171 * @param connection the connection
6172 * @param size the maximum size in bytes of all outstanding messages
6175 dbus_connection_set_max_received_size (DBusConnection *connection,
6178 _dbus_return_if_fail (connection != NULL);
6180 CONNECTION_LOCK (connection);
6181 _dbus_transport_set_max_received_size (connection->transport,
6183 CONNECTION_UNLOCK (connection);
6187 * Gets the value set by dbus_connection_set_max_received_size().
6189 * @param connection the connection
6190 * @returns the max size of all live messages
6193 dbus_connection_get_max_received_size (DBusConnection *connection)
6197 _dbus_return_val_if_fail (connection != NULL, 0);
6199 CONNECTION_LOCK (connection);
6200 res = _dbus_transport_get_max_received_size (connection->transport);
6201 CONNECTION_UNLOCK (connection);
6206 * Sets the maximum total number of unix fds that can be used for all messages
6207 * received on this connection. Messages count toward the maximum until
6208 * they are finalized. When the maximum is reached, the connection will
6209 * not read more data until some messages are finalized.
6211 * The semantics are analogous to those of dbus_connection_set_max_received_size().
6213 * @param connection the connection
6214 * @param n the maximum size in bytes of all outstanding messages
6217 dbus_connection_set_max_received_unix_fds (DBusConnection *connection,
6220 _dbus_return_if_fail (connection != NULL);
6222 CONNECTION_LOCK (connection);
6223 _dbus_transport_set_max_received_unix_fds (connection->transport,
6225 CONNECTION_UNLOCK (connection);
6229 * Gets the value set by dbus_connection_set_max_received_unix_fds().
6231 * @param connection the connection
6232 * @returns the max unix fds of all live messages
6235 dbus_connection_get_max_received_unix_fds (DBusConnection *connection)
6239 _dbus_return_val_if_fail (connection != NULL, 0);
6241 CONNECTION_LOCK (connection);
6242 res = _dbus_transport_get_max_received_unix_fds (connection->transport);
6243 CONNECTION_UNLOCK (connection);
6248 * Gets the approximate size in bytes of all messages in the outgoing
6249 * message queue. The size is approximate in that you shouldn't use
6250 * it to decide how many bytes to read off the network or anything
6251 * of that nature, as optimizations may choose to tell small white lies
6252 * to avoid performance overhead.
6254 * @param connection the connection
6255 * @returns the number of bytes that have been queued up but not sent
6258 dbus_connection_get_outgoing_size (DBusConnection *connection)
6262 _dbus_return_val_if_fail (connection != NULL, 0);
6264 CONNECTION_LOCK (connection);
6265 res = _dbus_counter_get_size_value (connection->outgoing_counter);
6266 CONNECTION_UNLOCK (connection);
6270 #ifdef DBUS_ENABLE_STATS
6272 _dbus_connection_get_stats (DBusConnection *connection,
6273 dbus_uint32_t *in_messages,
6274 dbus_uint32_t *in_bytes,
6275 dbus_uint32_t *in_fds,
6276 dbus_uint32_t *in_peak_bytes,
6277 dbus_uint32_t *in_peak_fds,
6278 dbus_uint32_t *out_messages,
6279 dbus_uint32_t *out_bytes,
6280 dbus_uint32_t *out_fds,
6281 dbus_uint32_t *out_peak_bytes,
6282 dbus_uint32_t *out_peak_fds)
6284 CONNECTION_LOCK (connection);
6286 if (in_messages != NULL)
6287 *in_messages = connection->n_incoming;
6289 _dbus_transport_get_stats (connection->transport,
6290 in_bytes, in_fds, in_peak_bytes, in_peak_fds);
6292 if (out_messages != NULL)
6293 *out_messages = connection->n_outgoing;
6295 if (out_bytes != NULL)
6296 *out_bytes = _dbus_counter_get_size_value (connection->outgoing_counter);
6298 if (out_fds != NULL)
6299 *out_fds = _dbus_counter_get_unix_fd_value (connection->outgoing_counter);
6301 if (out_peak_bytes != NULL)
6302 *out_peak_bytes = _dbus_counter_get_peak_size_value (connection->outgoing_counter);
6304 if (out_peak_fds != NULL)
6305 *out_peak_fds = _dbus_counter_get_peak_unix_fd_value (connection->outgoing_counter);
6307 CONNECTION_UNLOCK (connection);
6309 #endif /* DBUS_ENABLE_STATS */
6312 * Gets the approximate number of uni fds of all messages in the
6313 * outgoing message queue.
6315 * @param connection the connection
6316 * @returns the number of unix fds that have been queued up but not sent
6319 dbus_connection_get_outgoing_unix_fds (DBusConnection *connection)
6323 _dbus_return_val_if_fail (connection != NULL, 0);
6325 CONNECTION_LOCK (connection);
6326 res = _dbus_counter_get_unix_fd_value (connection->outgoing_counter);
6327 CONNECTION_UNLOCK (connection);
6332 * Returns the address of the transport object of this connection
6334 * @param connection the connection
6335 * @returns the address string
6338 _dbus_connection_get_address (DBusConnection *connection)
6340 return _dbus_transport_get_address (connection->transport);
6344 dbus_connection_get_transport(DBusConnection *connection)
6346 _dbus_return_val_if_fail (connection != NULL, NULL);
6348 return connection->transport;