1 /* -*- mode: C; c-file-style: "gnu" -*- */
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 #include "dbus-shared.h"
26 #include "dbus-connection.h"
27 #include "dbus-list.h"
28 #include "dbus-timeout.h"
29 #include "dbus-transport.h"
30 #include "dbus-watch.h"
31 #include "dbus-connection-internal.h"
32 #include "dbus-pending-call-internal.h"
33 #include "dbus-list.h"
34 #include "dbus-hash.h"
35 #include "dbus-message-internal.h"
36 #include "dbus-threads.h"
37 #include "dbus-protocol.h"
38 #include "dbus-dataslot.h"
39 #include "dbus-string.h"
40 #include "dbus-pending-call.h"
41 #include "dbus-object-tree.h"
42 #include "dbus-threads-internal.h"
45 #ifdef DBUS_DISABLE_CHECKS
46 #define TOOK_LOCK_CHECK(connection)
47 #define RELEASING_LOCK_CHECK(connection)
48 #define HAVE_LOCK_CHECK(connection)
50 #define TOOK_LOCK_CHECK(connection) do { \
51 _dbus_assert (!(connection)->have_connection_lock); \
52 (connection)->have_connection_lock = TRUE; \
54 #define RELEASING_LOCK_CHECK(connection) do { \
55 _dbus_assert ((connection)->have_connection_lock); \
56 (connection)->have_connection_lock = FALSE; \
58 #define HAVE_LOCK_CHECK(connection) _dbus_assert ((connection)->have_connection_lock)
59 /* A "DO_NOT_HAVE_LOCK_CHECK" is impossible since we need the lock to check the flag */
64 #define CONNECTION_LOCK(connection) do { \
65 if (TRACE_LOCKS) { _dbus_verbose (" LOCK: %s\n", _DBUS_FUNCTION_NAME); } \
66 _dbus_mutex_lock ((connection)->mutex); \
67 TOOK_LOCK_CHECK (connection); \
70 #define CONNECTION_UNLOCK(connection) do { \
71 if (TRACE_LOCKS) { _dbus_verbose (" UNLOCK: %s\n", _DBUS_FUNCTION_NAME); } \
72 RELEASING_LOCK_CHECK (connection); \
73 _dbus_mutex_unlock ((connection)->mutex); \
76 #define DISPATCH_STATUS_NAME(s) \
77 ((s) == DBUS_DISPATCH_COMPLETE ? "complete" : \
78 (s) == DBUS_DISPATCH_DATA_REMAINS ? "data remains" : \
79 (s) == DBUS_DISPATCH_NEED_MEMORY ? "need memory" : \
83 * @defgroup DBusConnection DBusConnection
85 * @brief Connection to another application
87 * A DBusConnection represents a connection to another
88 * application. Messages can be sent and received via this connection.
89 * The other application may be a message bus; for convenience, the
90 * function dbus_bus_get() is provided to automatically open a
91 * connection to the well-known message buses.
93 * In brief a DBusConnection is a message queue associated with some
94 * message transport mechanism such as a socket. The connection
95 * maintains a queue of incoming messages and a queue of outgoing
98 * Several functions use the following terms:
100 * <li><b>read</b> means to fill the incoming message queue by reading from the socket</li>
101 * <li><b>write</b> means to drain the outgoing queue by writing to the socket</li>
102 * <li><b>dispatch</b> means to drain the incoming queue by invoking application-provided message handlers</li>
105 * The function dbus_connection_read_write_dispatch() for example does all
106 * three of these things, offering a simple alternative to a main loop.
108 * In an application with a main loop, the read/write/dispatch
109 * operations are usually separate.
111 * The connection provides #DBusWatch and #DBusTimeout objects to
112 * the main loop. These are used to know when reading, writing, or
113 * dispatching should be performed.
115 * Incoming messages are processed
116 * by calling dbus_connection_dispatch(). dbus_connection_dispatch()
117 * runs any handlers registered for the topmost message in the message
118 * queue, then discards the message, then returns.
120 * dbus_connection_get_dispatch_status() indicates whether
121 * messages are currently in the queue that need dispatching.
122 * dbus_connection_set_dispatch_status_function() allows
123 * you to set a function to be used to monitor the dispatch status.
125 * If you're using GLib or Qt add-on libraries for D-Bus, there are
126 * special convenience APIs in those libraries that hide
127 * all the details of dispatch and watch/timeout monitoring.
128 * For example, dbus_connection_setup_with_g_main().
130 * If you aren't using these add-on libraries, but want to process
131 * messages asynchronously, you must manually call
132 * dbus_connection_set_dispatch_status_function(),
133 * dbus_connection_set_watch_functions(),
134 * dbus_connection_set_timeout_functions() providing appropriate
135 * functions to integrate the connection with your application's main
136 * loop. This can be tricky to get right; main loops are not simple.
138 * If you don't need to be asynchronous, you can ignore #DBusWatch,
139 * #DBusTimeout, and dbus_connection_dispatch(). Instead,
140 * dbus_connection_read_write_dispatch() can be used.
142 * Or, in <em>very</em> simple applications,
143 * dbus_connection_pop_message() may be all you need, allowing you to
144 * avoid setting up any handler functions (see
145 * dbus_connection_add_filter(),
146 * dbus_connection_register_object_path() for more on handlers).
148 * When you use dbus_connection_send() or one of its variants to send
149 * a message, the message is added to the outgoing queue. It's
150 * actually written to the network later; either in
151 * dbus_watch_handle() invoked by your main loop, or in
152 * dbus_connection_flush() which blocks until it can write out the
153 * entire outgoing queue. The GLib/Qt add-on libraries again
154 * handle the details here for you by setting up watch functions.
156 * When a connection is disconnected, you are guaranteed to get a
157 * signal "Disconnected" from the interface
158 * #DBUS_INTERFACE_LOCAL, path
161 * You may not drop the last reference to a #DBusConnection
162 * until that connection has been disconnected.
164 * You may dispatch the unprocessed incoming message queue even if the
165 * connection is disconnected. However, "Disconnected" will always be
166 * the last message in the queue (obviously no messages are received
167 * after disconnection).
169 * After calling dbus_threads_init(), #DBusConnection has thread
170 * locks and drops them when invoking user callbacks, so in general is
171 * transparently threadsafe. However, #DBusMessage does NOT have
172 * thread locks; you must not send the same message to multiple
173 * #DBusConnection if those connections will be used from different threads,
176 * Also, if you dispatch or pop messages from multiple threads, it
177 * may work in the sense that it won't crash, but it's tough to imagine
178 * sane results; it will be completely unpredictable which messages
179 * go to which threads.
181 * It's recommended to dispatch from a single thread.
183 * The most useful function to call from multiple threads at once
184 * is dbus_connection_send_with_reply_and_block(). That is,
185 * multiple threads can make method calls at the same time.
187 * If you aren't using threads, you can use a main loop and
188 * dbus_pending_call_set_notify() to achieve a similar result.
192 * @defgroup DBusConnectionInternals DBusConnection implementation details
193 * @ingroup DBusInternals
194 * @brief Implementation details of DBusConnection
200 * Internal struct representing a message filter function
202 typedef struct DBusMessageFilter DBusMessageFilter;
205 * Internal struct representing a message filter function
207 struct DBusMessageFilter
209 DBusAtomic refcount; /**< Reference count */
210 DBusHandleMessageFunction function; /**< Function to call to filter */
211 void *user_data; /**< User data for the function */
212 DBusFreeFunction free_user_data_function; /**< Function to free the user data */
217 * Internals of DBusPreallocatedSend
219 struct DBusPreallocatedSend
221 DBusConnection *connection; /**< Connection we'd send the message to */
222 DBusList *queue_link; /**< Preallocated link in the queue */
223 DBusList *counter_link; /**< Preallocated link in the resource counter */
226 static dbus_bool_t _dbus_modify_sigpipe = TRUE;
229 * Implementation details of DBusConnection. All fields are private.
231 struct DBusConnection
233 DBusAtomic refcount; /**< Reference count. */
235 DBusMutex *mutex; /**< Lock on the entire DBusConnection */
237 DBusMutex *dispatch_mutex; /**< Protects dispatch_acquired */
238 DBusCondVar *dispatch_cond; /**< Notify when dispatch_acquired is available */
239 DBusMutex *io_path_mutex; /**< Protects io_path_acquired */
240 DBusCondVar *io_path_cond; /**< Notify when io_path_acquired is available */
242 DBusList *outgoing_messages; /**< Queue of messages we need to send, send the end of the list first. */
243 DBusList *incoming_messages; /**< Queue of messages we have received, end of the list received most recently. */
245 DBusMessage *message_borrowed; /**< Filled in if the first incoming message has been borrowed;
246 * dispatch_acquired will be set by the borrower
249 int n_outgoing; /**< Length of outgoing queue. */
250 int n_incoming; /**< Length of incoming queue. */
252 DBusCounter *outgoing_counter; /**< Counts size of outgoing messages. */
254 DBusTransport *transport; /**< Object that sends/receives messages over network. */
255 DBusWatchList *watches; /**< Stores active watches. */
256 DBusTimeoutList *timeouts; /**< Stores active timeouts. */
258 DBusList *filter_list; /**< List of filters. */
260 DBusDataSlotList slot_list; /**< Data stored by allocated integer ID */
262 DBusHashTable *pending_replies; /**< Hash of message serials to #DBusPendingCall. */
264 dbus_uint32_t client_serial; /**< Client serial. Increments each time a message is sent */
265 DBusList *disconnect_message_link; /**< Preallocated list node for queueing the disconnection message */
267 DBusWakeupMainFunction wakeup_main_function; /**< Function to wake up the mainloop */
268 void *wakeup_main_data; /**< Application data for wakeup_main_function */
269 DBusFreeFunction free_wakeup_main_data; /**< free wakeup_main_data */
271 DBusDispatchStatusFunction dispatch_status_function; /**< Function on dispatch status changes */
272 void *dispatch_status_data; /**< Application data for dispatch_status_function */
273 DBusFreeFunction free_dispatch_status_data; /**< free dispatch_status_data */
275 DBusDispatchStatus last_dispatch_status; /**< The last dispatch status we reported to the application. */
277 DBusList *link_cache; /**< A cache of linked list links to prevent contention
278 * for the global linked list mempool lock
280 DBusObjectTree *objects; /**< Object path handlers registered with this connection */
282 char *server_guid; /**< GUID of server if we are in shared_connections, #NULL if server GUID is unknown or connection is private */
284 unsigned int shareable : 1; /**< #TRUE if libdbus owns a reference to the connection and can return it from dbus_connection_open() more than once */
286 unsigned int dispatch_acquired : 1; /**< Someone has dispatch path (can drain incoming queue) */
287 unsigned int io_path_acquired : 1; /**< Someone has transport io path (can use the transport to read/write messages) */
289 unsigned int exit_on_disconnect : 1; /**< If #TRUE, exit after handling disconnect signal */
291 unsigned int route_peer_messages : 1; /**< If #TRUE, if org.freedesktop.DBus.Peer messages have a bus name, don't handle them automatically */
293 unsigned int disconnected_message_arrived : 1; /**< We popped or are dispatching the disconnected message.
294 * if the disconnect_message_link is NULL then we queued it, but
295 * this flag is whether it got to the head of the queue.
297 unsigned int disconnected_message_processed : 1; /**< We did our default handling of the disconnected message,
298 * such as closing the connection.
301 #ifndef DBUS_DISABLE_CHECKS
302 unsigned int have_connection_lock : 1; /**< Used to check locking */
305 #ifndef DBUS_DISABLE_CHECKS
306 int generation; /**< _dbus_current_generation that should correspond to this connection */
310 static DBusDispatchStatus _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection);
311 static void _dbus_connection_update_dispatch_status_and_unlock (DBusConnection *connection,
312 DBusDispatchStatus new_status);
313 static void _dbus_connection_last_unref (DBusConnection *connection);
314 static void _dbus_connection_acquire_dispatch (DBusConnection *connection);
315 static void _dbus_connection_release_dispatch (DBusConnection *connection);
316 static DBusDispatchStatus _dbus_connection_flush_unlocked (DBusConnection *connection);
317 static void _dbus_connection_close_possibly_shared_and_unlock (DBusConnection *connection);
318 static dbus_bool_t _dbus_connection_get_is_connected_unlocked (DBusConnection *connection);
320 static DBusMessageFilter *
321 _dbus_message_filter_ref (DBusMessageFilter *filter)
323 _dbus_assert (filter->refcount.value > 0);
324 _dbus_atomic_inc (&filter->refcount);
330 _dbus_message_filter_unref (DBusMessageFilter *filter)
332 _dbus_assert (filter->refcount.value > 0);
334 if (_dbus_atomic_dec (&filter->refcount) == 1)
336 if (filter->free_user_data_function)
337 (* filter->free_user_data_function) (filter->user_data);
344 * Acquires the connection lock.
346 * @param connection the connection.
349 _dbus_connection_lock (DBusConnection *connection)
351 CONNECTION_LOCK (connection);
355 * Releases the connection lock.
357 * @param connection the connection.
360 _dbus_connection_unlock (DBusConnection *connection)
362 CONNECTION_UNLOCK (connection);
366 * Wakes up the main loop if it is sleeping
367 * Needed if we're e.g. queueing outgoing messages
368 * on a thread while the mainloop sleeps.
370 * @param connection the connection.
373 _dbus_connection_wakeup_mainloop (DBusConnection *connection)
375 if (connection->wakeup_main_function)
376 (*connection->wakeup_main_function) (connection->wakeup_main_data);
379 #ifdef DBUS_BUILD_TESTS
380 /* For now this function isn't used */
382 * Adds a message to the incoming message queue, returning #FALSE
383 * if there's insufficient memory to queue the message.
384 * Does not take over refcount of the message.
386 * @param connection the connection.
387 * @param message the message to queue.
388 * @returns #TRUE on success.
391 _dbus_connection_queue_received_message (DBusConnection *connection,
392 DBusMessage *message)
396 link = _dbus_list_alloc_link (message);
400 dbus_message_ref (message);
401 _dbus_connection_queue_received_message_link (connection, link);
407 * Gets the locks so we can examine them
409 * @param connection the connection.
410 * @param mutex_loc return for the location of the main mutex pointer
411 * @param dispatch_mutex_loc return location of the dispatch mutex pointer
412 * @param io_path_mutex_loc return location of the io_path mutex pointer
413 * @param dispatch_cond_loc return location of the dispatch conditional
415 * @param io_path_cond_loc return location of the io_path conditional
419 _dbus_connection_test_get_locks (DBusConnection *connection,
420 DBusMutex **mutex_loc,
421 DBusMutex **dispatch_mutex_loc,
422 DBusMutex **io_path_mutex_loc,
423 DBusCondVar **dispatch_cond_loc,
424 DBusCondVar **io_path_cond_loc)
426 *mutex_loc = connection->mutex;
427 *dispatch_mutex_loc = connection->dispatch_mutex;
428 *io_path_mutex_loc = connection->io_path_mutex;
429 *dispatch_cond_loc = connection->dispatch_cond;
430 *io_path_cond_loc = connection->io_path_cond;
435 * Adds a message-containing list link to the incoming message queue,
436 * taking ownership of the link and the message's current refcount.
437 * Cannot fail due to lack of memory.
439 * @param connection the connection.
440 * @param link the message link to queue.
443 _dbus_connection_queue_received_message_link (DBusConnection *connection,
446 DBusPendingCall *pending;
447 dbus_int32_t reply_serial;
448 DBusMessage *message;
450 _dbus_assert (_dbus_transport_get_is_authenticated (connection->transport));
452 _dbus_list_append_link (&connection->incoming_messages,
454 message = link->data;
456 /* If this is a reply we're waiting on, remove timeout for it */
457 reply_serial = dbus_message_get_reply_serial (message);
458 if (reply_serial != -1)
460 pending = _dbus_hash_table_lookup_int (connection->pending_replies,
464 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
465 _dbus_connection_remove_timeout_unlocked (connection,
466 _dbus_pending_call_get_timeout_unlocked (pending));
468 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
474 connection->n_incoming += 1;
476 _dbus_connection_wakeup_mainloop (connection);
478 _dbus_verbose ("Message %p (%d %s %s %s '%s' reply to %u) added to incoming queue %p, %d incoming\n",
480 dbus_message_get_type (message),
481 dbus_message_get_path (message) ?
482 dbus_message_get_path (message) :
484 dbus_message_get_interface (message) ?
485 dbus_message_get_interface (message) :
487 dbus_message_get_member (message) ?
488 dbus_message_get_member (message) :
490 dbus_message_get_signature (message),
491 dbus_message_get_reply_serial (message),
493 connection->n_incoming);}
496 * Adds a link + message to the incoming message queue.
497 * Can't fail. Takes ownership of both link and message.
499 * @param connection the connection.
500 * @param link the list node and message to queue.
504 _dbus_connection_queue_synthesized_message_link (DBusConnection *connection,
507 HAVE_LOCK_CHECK (connection);
509 _dbus_list_append_link (&connection->incoming_messages, link);
511 connection->n_incoming += 1;
513 _dbus_connection_wakeup_mainloop (connection);
515 _dbus_verbose ("Synthesized message %p added to incoming queue %p, %d incoming\n",
516 link->data, connection, connection->n_incoming);
521 * Checks whether there are messages in the outgoing message queue.
522 * Called with connection lock held.
524 * @param connection the connection.
525 * @returns #TRUE if the outgoing queue is non-empty.
528 _dbus_connection_has_messages_to_send_unlocked (DBusConnection *connection)
530 HAVE_LOCK_CHECK (connection);
531 return connection->outgoing_messages != NULL;
535 * Checks whether there are messages in the outgoing message queue.
536 * Use dbus_connection_flush() to block until all outgoing
537 * messages have been written to the underlying transport
538 * (such as a socket).
540 * @param connection the connection.
541 * @returns #TRUE if the outgoing queue is non-empty.
544 dbus_connection_has_messages_to_send (DBusConnection *connection)
548 _dbus_return_val_if_fail (connection != NULL, FALSE);
550 CONNECTION_LOCK (connection);
551 v = _dbus_connection_has_messages_to_send_unlocked (connection);
552 CONNECTION_UNLOCK (connection);
558 * Gets the next outgoing message. The message remains in the
559 * queue, and the caller does not own a reference to it.
561 * @param connection the connection.
562 * @returns the message to be sent.
565 _dbus_connection_get_message_to_send (DBusConnection *connection)
567 HAVE_LOCK_CHECK (connection);
569 return _dbus_list_get_last (&connection->outgoing_messages);
573 * Notifies the connection that a message has been sent, so the
574 * message can be removed from the outgoing queue.
575 * Called with the connection lock held.
577 * @param connection the connection.
578 * @param message the message that was sent.
581 _dbus_connection_message_sent (DBusConnection *connection,
582 DBusMessage *message)
586 HAVE_LOCK_CHECK (connection);
588 /* This can be called before we even complete authentication, since
589 * it's called on disconnect to clean up the outgoing queue.
590 * It's also called as we successfully send each message.
593 link = _dbus_list_get_last_link (&connection->outgoing_messages);
594 _dbus_assert (link != NULL);
595 _dbus_assert (link->data == message);
597 /* Save this link in the link cache */
598 _dbus_list_unlink (&connection->outgoing_messages,
600 _dbus_list_prepend_link (&connection->link_cache, link);
602 connection->n_outgoing -= 1;
604 _dbus_verbose ("Message %p (%d %s %s %s '%s') removed from outgoing queue %p, %d left to send\n",
606 dbus_message_get_type (message),
607 dbus_message_get_path (message) ?
608 dbus_message_get_path (message) :
610 dbus_message_get_interface (message) ?
611 dbus_message_get_interface (message) :
613 dbus_message_get_member (message) ?
614 dbus_message_get_member (message) :
616 dbus_message_get_signature (message),
617 connection, connection->n_outgoing);
619 /* Save this link in the link cache also */
620 _dbus_message_remove_size_counter (message, connection->outgoing_counter,
622 _dbus_list_prepend_link (&connection->link_cache, link);
624 dbus_message_unref (message);
627 /** Function to be called in protected_change_watch() with refcount held */
628 typedef dbus_bool_t (* DBusWatchAddFunction) (DBusWatchList *list,
630 /** Function to be called in protected_change_watch() with refcount held */
631 typedef void (* DBusWatchRemoveFunction) (DBusWatchList *list,
633 /** Function to be called in protected_change_watch() with refcount held */
634 typedef void (* DBusWatchToggleFunction) (DBusWatchList *list,
636 dbus_bool_t enabled);
639 protected_change_watch (DBusConnection *connection,
641 DBusWatchAddFunction add_function,
642 DBusWatchRemoveFunction remove_function,
643 DBusWatchToggleFunction toggle_function,
646 DBusWatchList *watches;
649 HAVE_LOCK_CHECK (connection);
651 /* This isn't really safe or reasonable; a better pattern is the "do everything, then
652 * drop lock and call out" one; but it has to be propagated up through all callers
655 watches = connection->watches;
658 connection->watches = NULL;
659 _dbus_connection_ref_unlocked (connection);
660 CONNECTION_UNLOCK (connection);
663 retval = (* add_function) (watches, watch);
664 else if (remove_function)
667 (* remove_function) (watches, watch);
672 (* toggle_function) (watches, watch, enabled);
675 CONNECTION_LOCK (connection);
676 connection->watches = watches;
677 _dbus_connection_unref_unlocked (connection);
687 * Adds a watch using the connection's DBusAddWatchFunction if
688 * available. Otherwise records the watch to be added when said
689 * function is available. Also re-adds the watch if the
690 * DBusAddWatchFunction changes. May fail due to lack of memory.
691 * Connection lock should be held when calling this.
693 * @param connection the connection.
694 * @param watch the watch to add.
695 * @returns #TRUE on success.
698 _dbus_connection_add_watch_unlocked (DBusConnection *connection,
701 return protected_change_watch (connection, watch,
702 _dbus_watch_list_add_watch,
707 * Removes a watch using the connection's DBusRemoveWatchFunction
708 * if available. It's an error to call this function on a watch
709 * that was not previously added.
710 * Connection lock should be held when calling this.
712 * @param connection the connection.
713 * @param watch the watch to remove.
716 _dbus_connection_remove_watch_unlocked (DBusConnection *connection,
719 protected_change_watch (connection, watch,
721 _dbus_watch_list_remove_watch,
726 * Toggles a watch and notifies app via connection's
727 * DBusWatchToggledFunction if available. It's an error to call this
728 * function on a watch that was not previously added.
729 * Connection lock should be held when calling this.
731 * @param connection the connection.
732 * @param watch the watch to toggle.
733 * @param enabled whether to enable or disable
736 _dbus_connection_toggle_watch_unlocked (DBusConnection *connection,
740 _dbus_assert (watch != NULL);
742 protected_change_watch (connection, watch,
744 _dbus_watch_list_toggle_watch,
748 /** Function to be called in protected_change_timeout() with refcount held */
749 typedef dbus_bool_t (* DBusTimeoutAddFunction) (DBusTimeoutList *list,
750 DBusTimeout *timeout);
751 /** Function to be called in protected_change_timeout() with refcount held */
752 typedef void (* DBusTimeoutRemoveFunction) (DBusTimeoutList *list,
753 DBusTimeout *timeout);
754 /** Function to be called in protected_change_timeout() with refcount held */
755 typedef void (* DBusTimeoutToggleFunction) (DBusTimeoutList *list,
756 DBusTimeout *timeout,
757 dbus_bool_t enabled);
760 protected_change_timeout (DBusConnection *connection,
761 DBusTimeout *timeout,
762 DBusTimeoutAddFunction add_function,
763 DBusTimeoutRemoveFunction remove_function,
764 DBusTimeoutToggleFunction toggle_function,
767 DBusTimeoutList *timeouts;
770 HAVE_LOCK_CHECK (connection);
772 /* This isn't really safe or reasonable; a better pattern is the "do everything, then
773 * drop lock and call out" one; but it has to be propagated up through all callers
776 timeouts = connection->timeouts;
779 connection->timeouts = NULL;
780 _dbus_connection_ref_unlocked (connection);
781 CONNECTION_UNLOCK (connection);
784 retval = (* add_function) (timeouts, timeout);
785 else if (remove_function)
788 (* remove_function) (timeouts, timeout);
793 (* toggle_function) (timeouts, timeout, enabled);
796 CONNECTION_LOCK (connection);
797 connection->timeouts = timeouts;
798 _dbus_connection_unref_unlocked (connection);
807 * Adds a timeout using the connection's DBusAddTimeoutFunction if
808 * available. Otherwise records the timeout to be added when said
809 * function is available. Also re-adds the timeout if the
810 * DBusAddTimeoutFunction changes. May fail due to lack of memory.
811 * The timeout will fire repeatedly until removed.
812 * Connection lock should be held when calling this.
814 * @param connection the connection.
815 * @param timeout the timeout to add.
816 * @returns #TRUE on success.
819 _dbus_connection_add_timeout_unlocked (DBusConnection *connection,
820 DBusTimeout *timeout)
822 return protected_change_timeout (connection, timeout,
823 _dbus_timeout_list_add_timeout,
828 * Removes a timeout using the connection's DBusRemoveTimeoutFunction
829 * if available. It's an error to call this function on a timeout
830 * that was not previously added.
831 * Connection lock should be held when calling this.
833 * @param connection the connection.
834 * @param timeout the timeout to remove.
837 _dbus_connection_remove_timeout_unlocked (DBusConnection *connection,
838 DBusTimeout *timeout)
840 protected_change_timeout (connection, timeout,
842 _dbus_timeout_list_remove_timeout,
847 * Toggles a timeout and notifies app via connection's
848 * DBusTimeoutToggledFunction if available. It's an error to call this
849 * function on a timeout that was not previously added.
850 * Connection lock should be held when calling this.
852 * @param connection the connection.
853 * @param timeout the timeout to toggle.
854 * @param enabled whether to enable or disable
857 _dbus_connection_toggle_timeout_unlocked (DBusConnection *connection,
858 DBusTimeout *timeout,
861 protected_change_timeout (connection, timeout,
863 _dbus_timeout_list_toggle_timeout,
868 _dbus_connection_attach_pending_call_unlocked (DBusConnection *connection,
869 DBusPendingCall *pending)
871 dbus_uint32_t reply_serial;
872 DBusTimeout *timeout;
874 HAVE_LOCK_CHECK (connection);
876 reply_serial = _dbus_pending_call_get_reply_serial_unlocked (pending);
878 _dbus_assert (reply_serial != 0);
880 timeout = _dbus_pending_call_get_timeout_unlocked (pending);
882 if (!_dbus_connection_add_timeout_unlocked (connection, timeout))
885 if (!_dbus_hash_table_insert_int (connection->pending_replies,
889 _dbus_connection_remove_timeout_unlocked (connection, timeout);
891 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
892 HAVE_LOCK_CHECK (connection);
896 _dbus_pending_call_set_timeout_added_unlocked (pending, TRUE);
898 _dbus_pending_call_ref_unlocked (pending);
900 HAVE_LOCK_CHECK (connection);
906 free_pending_call_on_hash_removal (void *data)
908 DBusPendingCall *pending;
909 DBusConnection *connection;
916 connection = _dbus_pending_call_get_connection_unlocked (pending);
918 HAVE_LOCK_CHECK (connection);
920 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
922 _dbus_connection_remove_timeout_unlocked (connection,
923 _dbus_pending_call_get_timeout_unlocked (pending));
925 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
928 /* FIXME 1.0? this is sort of dangerous and undesirable to drop the lock
929 * here, but the pending call finalizer could in principle call out to
930 * application code so we pretty much have to... some larger code reorg
933 _dbus_connection_ref_unlocked (connection);
934 _dbus_pending_call_unref_and_unlock (pending);
935 CONNECTION_LOCK (connection);
936 _dbus_connection_unref_unlocked (connection);
940 _dbus_connection_detach_pending_call_unlocked (DBusConnection *connection,
941 DBusPendingCall *pending)
943 /* This ends up unlocking to call the pending call finalizer, which is unexpected to
946 _dbus_hash_table_remove_int (connection->pending_replies,
947 _dbus_pending_call_get_reply_serial_unlocked (pending));
951 _dbus_connection_detach_pending_call_and_unlock (DBusConnection *connection,
952 DBusPendingCall *pending)
954 /* The idea here is to avoid finalizing the pending call
955 * with the lock held, since there's a destroy notifier
956 * in pending call that goes out to application code.
958 * There's an extra unlock inside the hash table
959 * "free pending call" function FIXME...
961 _dbus_pending_call_ref_unlocked (pending);
962 _dbus_hash_table_remove_int (connection->pending_replies,
963 _dbus_pending_call_get_reply_serial_unlocked (pending));
964 _dbus_pending_call_unref_and_unlock (pending);
968 * Removes a pending call from the connection, such that
969 * the pending reply will be ignored. May drop the last
970 * reference to the pending call.
972 * @param connection the connection
973 * @param pending the pending call
976 _dbus_connection_remove_pending_call (DBusConnection *connection,
977 DBusPendingCall *pending)
979 CONNECTION_LOCK (connection);
980 _dbus_connection_detach_pending_call_and_unlock (connection, pending);
984 * Acquire the transporter I/O path. This must be done before
985 * doing any I/O in the transporter. May sleep and drop the
986 * IO path mutex while waiting for the I/O path.
988 * @param connection the connection.
989 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
990 * @returns TRUE if the I/O path was acquired.
993 _dbus_connection_acquire_io_path (DBusConnection *connection,
994 int timeout_milliseconds)
996 dbus_bool_t we_acquired;
998 HAVE_LOCK_CHECK (connection);
1000 /* We don't want the connection to vanish */
1001 _dbus_connection_ref_unlocked (connection);
1003 /* We will only touch io_path_acquired which is protected by our mutex */
1004 CONNECTION_UNLOCK (connection);
1006 _dbus_verbose ("%s locking io_path_mutex\n", _DBUS_FUNCTION_NAME);
1007 _dbus_mutex_lock (connection->io_path_mutex);
1009 _dbus_verbose ("%s start connection->io_path_acquired = %d timeout = %d\n",
1010 _DBUS_FUNCTION_NAME, connection->io_path_acquired, timeout_milliseconds);
1012 we_acquired = FALSE;
1014 if (connection->io_path_acquired)
1016 if (timeout_milliseconds != -1)
1018 _dbus_verbose ("%s waiting %d for IO path to be acquirable\n",
1019 _DBUS_FUNCTION_NAME, timeout_milliseconds);
1020 _dbus_condvar_wait_timeout (connection->io_path_cond,
1021 connection->io_path_mutex,
1022 timeout_milliseconds);
1026 while (connection->io_path_acquired)
1028 _dbus_verbose ("%s waiting for IO path to be acquirable\n", _DBUS_FUNCTION_NAME);
1029 _dbus_condvar_wait (connection->io_path_cond,
1030 connection->io_path_mutex);
1035 if (!connection->io_path_acquired)
1038 connection->io_path_acquired = TRUE;
1041 _dbus_verbose ("%s end connection->io_path_acquired = %d we_acquired = %d\n",
1042 _DBUS_FUNCTION_NAME, connection->io_path_acquired, we_acquired);
1044 _dbus_verbose ("%s unlocking io_path_mutex\n", _DBUS_FUNCTION_NAME);
1045 _dbus_mutex_unlock (connection->io_path_mutex);
1047 CONNECTION_LOCK (connection);
1049 HAVE_LOCK_CHECK (connection);
1051 _dbus_connection_unref_unlocked (connection);
1057 * Release the I/O path when you're done with it. Only call
1058 * after you've acquired the I/O. Wakes up at most one thread
1059 * currently waiting to acquire the I/O path.
1061 * @param connection the connection.
1064 _dbus_connection_release_io_path (DBusConnection *connection)
1066 HAVE_LOCK_CHECK (connection);
1068 _dbus_verbose ("%s locking io_path_mutex\n", _DBUS_FUNCTION_NAME);
1069 _dbus_mutex_lock (connection->io_path_mutex);
1071 _dbus_assert (connection->io_path_acquired);
1073 _dbus_verbose ("%s start connection->io_path_acquired = %d\n",
1074 _DBUS_FUNCTION_NAME, connection->io_path_acquired);
1076 connection->io_path_acquired = FALSE;
1077 _dbus_condvar_wake_one (connection->io_path_cond);
1079 _dbus_verbose ("%s unlocking io_path_mutex\n", _DBUS_FUNCTION_NAME);
1080 _dbus_mutex_unlock (connection->io_path_mutex);
1084 * Queues incoming messages and sends outgoing messages for this
1085 * connection, optionally blocking in the process. Each call to
1086 * _dbus_connection_do_iteration_unlocked() will call select() or poll() one
1087 * time and then read or write data if possible.
1089 * The purpose of this function is to be able to flush outgoing
1090 * messages or queue up incoming messages without returning
1091 * control to the application and causing reentrancy weirdness.
1093 * The flags parameter allows you to specify whether to
1094 * read incoming messages, write outgoing messages, or both,
1095 * and whether to block if no immediate action is possible.
1097 * The timeout_milliseconds parameter does nothing unless the
1098 * iteration is blocking.
1100 * If there are no outgoing messages and DBUS_ITERATION_DO_READING
1101 * wasn't specified, then it's impossible to block, even if
1102 * you specify DBUS_ITERATION_BLOCK; in that case the function
1103 * returns immediately.
1105 * Called with connection lock held.
1107 * @param connection the connection.
1108 * @param flags iteration flags.
1109 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
1112 _dbus_connection_do_iteration_unlocked (DBusConnection *connection,
1114 int timeout_milliseconds)
1116 _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
1118 HAVE_LOCK_CHECK (connection);
1120 if (connection->n_outgoing == 0)
1121 flags &= ~DBUS_ITERATION_DO_WRITING;
1123 if (_dbus_connection_acquire_io_path (connection,
1124 (flags & DBUS_ITERATION_BLOCK) ? timeout_milliseconds : 0))
1126 HAVE_LOCK_CHECK (connection);
1128 _dbus_transport_do_iteration (connection->transport,
1129 flags, timeout_milliseconds);
1130 _dbus_connection_release_io_path (connection);
1133 HAVE_LOCK_CHECK (connection);
1135 _dbus_verbose ("%s end\n", _DBUS_FUNCTION_NAME);
1139 * Creates a new connection for the given transport. A transport
1140 * represents a message stream that uses some concrete mechanism, such
1141 * as UNIX domain sockets. May return #NULL if insufficient
1142 * memory exists to create the connection.
1144 * @param transport the transport.
1145 * @returns the new connection, or #NULL on failure.
1148 _dbus_connection_new_for_transport (DBusTransport *transport)
1150 DBusConnection *connection;
1151 DBusWatchList *watch_list;
1152 DBusTimeoutList *timeout_list;
1153 DBusHashTable *pending_replies;
1154 DBusList *disconnect_link;
1155 DBusMessage *disconnect_message;
1156 DBusCounter *outgoing_counter;
1157 DBusObjectTree *objects;
1161 pending_replies = NULL;
1162 timeout_list = NULL;
1163 disconnect_link = NULL;
1164 disconnect_message = NULL;
1165 outgoing_counter = NULL;
1168 watch_list = _dbus_watch_list_new ();
1169 if (watch_list == NULL)
1172 timeout_list = _dbus_timeout_list_new ();
1173 if (timeout_list == NULL)
1177 _dbus_hash_table_new (DBUS_HASH_INT,
1179 (DBusFreeFunction)free_pending_call_on_hash_removal);
1180 if (pending_replies == NULL)
1183 connection = dbus_new0 (DBusConnection, 1);
1184 if (connection == NULL)
1187 _dbus_mutex_new_at_location (&connection->mutex);
1188 if (connection->mutex == NULL)
1191 _dbus_mutex_new_at_location (&connection->io_path_mutex);
1192 if (connection->io_path_mutex == NULL)
1195 _dbus_mutex_new_at_location (&connection->dispatch_mutex);
1196 if (connection->dispatch_mutex == NULL)
1199 _dbus_condvar_new_at_location (&connection->dispatch_cond);
1200 if (connection->dispatch_cond == NULL)
1203 _dbus_condvar_new_at_location (&connection->io_path_cond);
1204 if (connection->io_path_cond == NULL)
1207 disconnect_message = dbus_message_new_signal (DBUS_PATH_LOCAL,
1208 DBUS_INTERFACE_LOCAL,
1211 if (disconnect_message == NULL)
1214 disconnect_link = _dbus_list_alloc_link (disconnect_message);
1215 if (disconnect_link == NULL)
1218 outgoing_counter = _dbus_counter_new ();
1219 if (outgoing_counter == NULL)
1222 objects = _dbus_object_tree_new (connection);
1223 if (objects == NULL)
1226 if (_dbus_modify_sigpipe)
1227 _dbus_disable_sigpipe ();
1229 connection->refcount.value = 1;
1230 connection->transport = transport;
1231 connection->watches = watch_list;
1232 connection->timeouts = timeout_list;
1233 connection->pending_replies = pending_replies;
1234 connection->outgoing_counter = outgoing_counter;
1235 connection->filter_list = NULL;
1236 connection->last_dispatch_status = DBUS_DISPATCH_COMPLETE; /* so we're notified first time there's data */
1237 connection->objects = objects;
1238 connection->exit_on_disconnect = FALSE;
1239 connection->shareable = FALSE;
1240 connection->route_peer_messages = FALSE;
1241 connection->disconnected_message_arrived = FALSE;
1242 connection->disconnected_message_processed = FALSE;
1244 #ifndef DBUS_DISABLE_CHECKS
1245 connection->generation = _dbus_current_generation;
1248 _dbus_data_slot_list_init (&connection->slot_list);
1250 connection->client_serial = 1;
1252 connection->disconnect_message_link = disconnect_link;
1254 CONNECTION_LOCK (connection);
1256 if (!_dbus_transport_set_connection (transport, connection))
1258 CONNECTION_UNLOCK (connection);
1263 _dbus_transport_ref (transport);
1265 CONNECTION_UNLOCK (connection);
1270 if (disconnect_message != NULL)
1271 dbus_message_unref (disconnect_message);
1273 if (disconnect_link != NULL)
1274 _dbus_list_free_link (disconnect_link);
1276 if (connection != NULL)
1278 _dbus_condvar_free_at_location (&connection->io_path_cond);
1279 _dbus_condvar_free_at_location (&connection->dispatch_cond);
1280 _dbus_mutex_free_at_location (&connection->mutex);
1281 _dbus_mutex_free_at_location (&connection->io_path_mutex);
1282 _dbus_mutex_free_at_location (&connection->dispatch_mutex);
1283 dbus_free (connection);
1285 if (pending_replies)
1286 _dbus_hash_table_unref (pending_replies);
1289 _dbus_watch_list_free (watch_list);
1292 _dbus_timeout_list_free (timeout_list);
1294 if (outgoing_counter)
1295 _dbus_counter_unref (outgoing_counter);
1298 _dbus_object_tree_unref (objects);
1304 * Increments the reference count of a DBusConnection.
1305 * Requires that the caller already holds the connection lock.
1307 * @param connection the connection.
1308 * @returns the connection.
1311 _dbus_connection_ref_unlocked (DBusConnection *connection)
1313 _dbus_assert (connection != NULL);
1314 _dbus_assert (connection->generation == _dbus_current_generation);
1316 HAVE_LOCK_CHECK (connection);
1318 #ifdef DBUS_HAVE_ATOMIC_INT
1319 _dbus_atomic_inc (&connection->refcount);
1321 _dbus_assert (connection->refcount.value > 0);
1322 connection->refcount.value += 1;
1329 * Decrements the reference count of a DBusConnection.
1330 * Requires that the caller already holds the connection lock.
1332 * @param connection the connection.
1335 _dbus_connection_unref_unlocked (DBusConnection *connection)
1337 dbus_bool_t last_unref;
1339 HAVE_LOCK_CHECK (connection);
1341 _dbus_assert (connection != NULL);
1343 /* The connection lock is better than the global
1344 * lock in the atomic increment fallback
1347 #ifdef DBUS_HAVE_ATOMIC_INT
1348 last_unref = (_dbus_atomic_dec (&connection->refcount) == 1);
1350 _dbus_assert (connection->refcount.value > 0);
1352 connection->refcount.value -= 1;
1353 last_unref = (connection->refcount.value == 0);
1355 printf ("unref_unlocked() connection %p count = %d\n", connection, connection->refcount.value);
1360 _dbus_connection_last_unref (connection);
1363 static dbus_uint32_t
1364 _dbus_connection_get_next_client_serial (DBusConnection *connection)
1368 serial = connection->client_serial++;
1370 if (connection->client_serial < 0)
1371 connection->client_serial = 1;
1377 * A callback for use with dbus_watch_new() to create a DBusWatch.
1379 * @todo This is basically a hack - we could delete _dbus_transport_handle_watch()
1380 * and the virtual handle_watch in DBusTransport if we got rid of it.
1381 * The reason this is some work is threading, see the _dbus_connection_handle_watch()
1384 * @param watch the watch.
1385 * @param condition the current condition of the file descriptors being watched.
1386 * @param data must be a pointer to a #DBusConnection
1387 * @returns #FALSE if the IO condition may not have been fully handled due to lack of memory
1390 _dbus_connection_handle_watch (DBusWatch *watch,
1391 unsigned int condition,
1394 DBusConnection *connection;
1396 DBusDispatchStatus status;
1400 _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
1402 CONNECTION_LOCK (connection);
1403 _dbus_connection_acquire_io_path (connection, -1);
1404 HAVE_LOCK_CHECK (connection);
1405 retval = _dbus_transport_handle_watch (connection->transport,
1408 _dbus_connection_release_io_path (connection);
1410 HAVE_LOCK_CHECK (connection);
1412 _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
1414 status = _dbus_connection_get_dispatch_status_unlocked (connection);
1416 /* this calls out to user code */
1417 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1419 _dbus_verbose ("%s end\n", _DBUS_FUNCTION_NAME);
1424 _DBUS_DEFINE_GLOBAL_LOCK (shared_connections);
1425 static DBusHashTable *shared_connections = NULL;
1428 shared_connections_shutdown (void *data)
1432 _DBUS_LOCK (shared_connections);
1434 /* This is a little bit unpleasant... better ideas? */
1435 while ((n_entries = _dbus_hash_table_get_n_entries (shared_connections)) > 0)
1437 DBusConnection *connection;
1438 DBusMessage *message;
1441 _dbus_hash_iter_init (shared_connections, &iter);
1442 _dbus_hash_iter_next (&iter);
1444 connection = _dbus_hash_iter_get_value (&iter);
1446 _DBUS_UNLOCK (shared_connections);
1448 dbus_connection_ref (connection);
1449 _dbus_connection_close_possibly_shared (connection);
1451 /* Churn through to the Disconnected message */
1452 while ((message = dbus_connection_pop_message (connection)))
1454 dbus_message_unref (message);
1456 dbus_connection_unref (connection);
1458 _DBUS_LOCK (shared_connections);
1460 /* The connection should now be dead and not in our hash ... */
1461 _dbus_assert (_dbus_hash_table_get_n_entries (shared_connections) < n_entries);
1464 _dbus_assert (_dbus_hash_table_get_n_entries (shared_connections) == 0);
1466 _dbus_hash_table_unref (shared_connections);
1467 shared_connections = NULL;
1469 _DBUS_UNLOCK (shared_connections);
1473 connection_lookup_shared (DBusAddressEntry *entry,
1474 DBusConnection **result)
1476 _dbus_verbose ("checking for existing connection\n");
1480 _DBUS_LOCK (shared_connections);
1482 if (shared_connections == NULL)
1484 _dbus_verbose ("creating shared_connections hash table\n");
1486 shared_connections = _dbus_hash_table_new (DBUS_HASH_STRING,
1489 if (shared_connections == NULL)
1491 _DBUS_UNLOCK (shared_connections);
1495 if (!_dbus_register_shutdown_func (shared_connections_shutdown, NULL))
1497 _dbus_hash_table_unref (shared_connections);
1498 shared_connections = NULL;
1499 _DBUS_UNLOCK (shared_connections);
1503 _dbus_verbose (" successfully created shared_connections\n");
1505 _DBUS_UNLOCK (shared_connections);
1506 return TRUE; /* no point looking up in the hash we just made */
1512 guid = dbus_address_entry_get_value (entry, "guid");
1516 DBusConnection *connection;
1518 connection = _dbus_hash_table_lookup_string (shared_connections,
1523 /* The DBusConnection can't be finalized without taking
1524 * the shared_connections lock to remove it from the
1525 * hash. So it's safe to ref the connection here.
1526 * However, it may be disconnected if the Disconnected
1527 * message hasn't been processed yet, in which case we
1528 * want to pretend it isn't in the hash and avoid
1531 * The idea is to avoid ever returning a disconnected connection
1532 * from dbus_connection_open(). We could just synchronously
1533 * drop our shared ref to the connection on connection disconnect,
1534 * and then assert here that the connection is connected, but
1535 * that causes reentrancy headaches.
1537 CONNECTION_LOCK (connection);
1538 if (_dbus_connection_get_is_connected_unlocked (connection))
1540 _dbus_connection_ref_unlocked (connection);
1541 *result = connection;
1542 _dbus_verbose ("looked up existing connection to server guid %s\n",
1547 _dbus_verbose ("looked up existing connection to server guid %s but it was disconnected so ignoring it\n",
1550 CONNECTION_UNLOCK (connection);
1554 _DBUS_UNLOCK (shared_connections);
1560 connection_record_shared_unlocked (DBusConnection *connection,
1564 char *guid_in_connection;
1566 HAVE_LOCK_CHECK (connection);
1567 _dbus_assert (connection->server_guid == NULL);
1568 _dbus_assert (connection->shareable);
1570 /* get a hard ref on this connection, even if
1571 * we won't in fact store it in the hash, we still
1572 * need to hold a ref on it until it's disconnected.
1574 _dbus_connection_ref_unlocked (connection);
1577 return TRUE; /* don't store in the hash */
1579 /* A separate copy of the key is required in the hash table, because
1580 * we don't have a lock on the connection when we are doing a hash
1584 guid_key = _dbus_strdup (guid);
1585 if (guid_key == NULL)
1588 guid_in_connection = _dbus_strdup (guid);
1589 if (guid_in_connection == NULL)
1591 dbus_free (guid_key);
1595 _DBUS_LOCK (shared_connections);
1596 _dbus_assert (shared_connections != NULL);
1598 if (!_dbus_hash_table_insert_string (shared_connections,
1599 guid_key, connection))
1601 dbus_free (guid_key);
1602 dbus_free (guid_in_connection);
1603 _DBUS_UNLOCK (shared_connections);
1607 connection->server_guid = guid_in_connection;
1609 _dbus_verbose ("stored connection to %s to be shared\n",
1610 connection->server_guid);
1612 _DBUS_UNLOCK (shared_connections);
1614 _dbus_assert (connection->server_guid != NULL);
1620 connection_forget_shared_unlocked (DBusConnection *connection)
1622 HAVE_LOCK_CHECK (connection);
1624 if (!connection->shareable)
1627 if (connection->server_guid != NULL)
1629 _dbus_verbose ("dropping connection to %s out of the shared table\n",
1630 connection->server_guid);
1632 _DBUS_LOCK (shared_connections);
1634 if (!_dbus_hash_table_remove_string (shared_connections,
1635 connection->server_guid))
1636 _dbus_assert_not_reached ("connection was not in the shared table");
1638 dbus_free (connection->server_guid);
1639 connection->server_guid = NULL;
1640 _DBUS_UNLOCK (shared_connections);
1643 /* remove our reference held on all shareable connections */
1644 _dbus_connection_unref_unlocked (connection);
1647 static DBusConnection*
1648 connection_try_from_address_entry (DBusAddressEntry *entry,
1651 DBusTransport *transport;
1652 DBusConnection *connection;
1654 transport = _dbus_transport_open (entry, error);
1656 if (transport == NULL)
1658 _DBUS_ASSERT_ERROR_IS_SET (error);
1662 connection = _dbus_connection_new_for_transport (transport);
1664 _dbus_transport_unref (transport);
1666 if (connection == NULL)
1668 _DBUS_SET_OOM (error);
1672 #ifndef DBUS_DISABLE_CHECKS
1673 _dbus_assert (!connection->have_connection_lock);
1679 * If the shared parameter is true, then any existing connection will
1680 * be used (and if a new connection is created, it will be available
1681 * for use by others). If the shared parameter is false, a new
1682 * connection will always be created, and the new connection will
1683 * never be returned to other callers.
1685 * @param address the address
1686 * @param shared whether the connection is shared or private
1687 * @param error error return
1688 * @returns the connection or #NULL on error
1690 static DBusConnection*
1691 _dbus_connection_open_internal (const char *address,
1695 DBusConnection *connection;
1696 DBusAddressEntry **entries;
1697 DBusError tmp_error;
1698 DBusError first_error;
1701 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1703 _dbus_verbose ("opening %s connection to: %s\n",
1704 shared ? "shared" : "private", address);
1706 if (!dbus_parse_address (address, &entries, &len, error))
1709 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1713 dbus_error_init (&tmp_error);
1714 dbus_error_init (&first_error);
1715 for (i = 0; i < len; i++)
1719 if (!connection_lookup_shared (entries[i], &connection))
1720 _DBUS_SET_OOM (&tmp_error);
1723 if (connection == NULL)
1725 connection = connection_try_from_address_entry (entries[i],
1728 if (connection != NULL && shared)
1732 connection->shareable = TRUE;
1734 /* guid may be NULL */
1735 guid = dbus_address_entry_get_value (entries[i], "guid");
1737 CONNECTION_LOCK (connection);
1739 if (!connection_record_shared_unlocked (connection, guid))
1741 _DBUS_SET_OOM (&tmp_error);
1742 _dbus_connection_close_possibly_shared_and_unlock (connection);
1743 dbus_connection_unref (connection);
1747 CONNECTION_UNLOCK (connection);
1754 _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
1757 dbus_move_error (&tmp_error, &first_error);
1759 dbus_error_free (&tmp_error);
1762 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1763 _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
1765 if (connection == NULL)
1767 _DBUS_ASSERT_ERROR_IS_SET (&first_error);
1768 dbus_move_error (&first_error, error);
1771 dbus_error_free (&first_error);
1773 dbus_address_entries_free (entries);
1778 * Closes a shared OR private connection, while dbus_connection_close() can
1779 * only be used on private connections. Should only be called by the
1780 * dbus code that owns the connection - an owner must be known,
1781 * the open/close state is like malloc/free, not like ref/unref.
1783 * @param connection the connection
1786 _dbus_connection_close_possibly_shared (DBusConnection *connection)
1788 _dbus_assert (connection != NULL);
1789 _dbus_assert (connection->generation == _dbus_current_generation);
1791 CONNECTION_LOCK (connection);
1792 _dbus_connection_close_possibly_shared_and_unlock (connection);
1795 static DBusPreallocatedSend*
1796 _dbus_connection_preallocate_send_unlocked (DBusConnection *connection)
1798 DBusPreallocatedSend *preallocated;
1800 HAVE_LOCK_CHECK (connection);
1802 _dbus_assert (connection != NULL);
1804 preallocated = dbus_new (DBusPreallocatedSend, 1);
1805 if (preallocated == NULL)
1808 if (connection->link_cache != NULL)
1810 preallocated->queue_link =
1811 _dbus_list_pop_first_link (&connection->link_cache);
1812 preallocated->queue_link->data = NULL;
1816 preallocated->queue_link = _dbus_list_alloc_link (NULL);
1817 if (preallocated->queue_link == NULL)
1821 if (connection->link_cache != NULL)
1823 preallocated->counter_link =
1824 _dbus_list_pop_first_link (&connection->link_cache);
1825 preallocated->counter_link->data = connection->outgoing_counter;
1829 preallocated->counter_link = _dbus_list_alloc_link (connection->outgoing_counter);
1830 if (preallocated->counter_link == NULL)
1834 _dbus_counter_ref (preallocated->counter_link->data);
1836 preallocated->connection = connection;
1838 return preallocated;
1841 _dbus_list_free_link (preallocated->queue_link);
1843 dbus_free (preallocated);
1848 /* Called with lock held, does not update dispatch status */
1850 _dbus_connection_send_preallocated_unlocked_no_update (DBusConnection *connection,
1851 DBusPreallocatedSend *preallocated,
1852 DBusMessage *message,
1853 dbus_uint32_t *client_serial)
1855 dbus_uint32_t serial;
1858 preallocated->queue_link->data = message;
1859 _dbus_list_prepend_link (&connection->outgoing_messages,
1860 preallocated->queue_link);
1862 _dbus_message_add_size_counter_link (message,
1863 preallocated->counter_link);
1865 dbus_free (preallocated);
1866 preallocated = NULL;
1868 dbus_message_ref (message);
1870 connection->n_outgoing += 1;
1872 sig = dbus_message_get_signature (message);
1874 _dbus_verbose ("Message %p (%d %s %s %s '%s') for %s added to outgoing queue %p, %d pending to send\n",
1876 dbus_message_get_type (message),
1877 dbus_message_get_path (message) ?
1878 dbus_message_get_path (message) :
1880 dbus_message_get_interface (message) ?
1881 dbus_message_get_interface (message) :
1883 dbus_message_get_member (message) ?
1884 dbus_message_get_member (message) :
1887 dbus_message_get_destination (message) ?
1888 dbus_message_get_destination (message) :
1891 connection->n_outgoing);
1893 if (dbus_message_get_serial (message) == 0)
1895 serial = _dbus_connection_get_next_client_serial (connection);
1896 _dbus_message_set_serial (message, serial);
1898 *client_serial = serial;
1903 *client_serial = dbus_message_get_serial (message);
1906 _dbus_verbose ("Message %p serial is %u\n",
1907 message, dbus_message_get_serial (message));
1909 _dbus_message_lock (message);
1911 /* Now we need to run an iteration to hopefully just write the messages
1912 * out immediately, and otherwise get them queued up
1914 _dbus_connection_do_iteration_unlocked (connection,
1915 DBUS_ITERATION_DO_WRITING,
1918 /* If stuff is still queued up, be sure we wake up the main loop */
1919 if (connection->n_outgoing > 0)
1920 _dbus_connection_wakeup_mainloop (connection);
1924 _dbus_connection_send_preallocated_and_unlock (DBusConnection *connection,
1925 DBusPreallocatedSend *preallocated,
1926 DBusMessage *message,
1927 dbus_uint32_t *client_serial)
1929 DBusDispatchStatus status;
1931 HAVE_LOCK_CHECK (connection);
1933 _dbus_connection_send_preallocated_unlocked_no_update (connection,
1935 message, client_serial);
1937 _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
1938 status = _dbus_connection_get_dispatch_status_unlocked (connection);
1940 /* this calls out to user code */
1941 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1945 * Like dbus_connection_send(), but assumes the connection
1946 * is already locked on function entry, and unlocks before returning.
1948 * @param connection the connection
1949 * @param message the message to send
1950 * @param client_serial return location for client serial of sent message
1951 * @returns #FALSE on out-of-memory
1954 _dbus_connection_send_and_unlock (DBusConnection *connection,
1955 DBusMessage *message,
1956 dbus_uint32_t *client_serial)
1958 DBusPreallocatedSend *preallocated;
1960 _dbus_assert (connection != NULL);
1961 _dbus_assert (message != NULL);
1963 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
1964 if (preallocated == NULL)
1966 CONNECTION_UNLOCK (connection);
1970 _dbus_connection_send_preallocated_and_unlock (connection,
1978 * Used internally to handle the semantics of dbus_server_set_new_connection_function().
1979 * If the new connection function does not ref the connection, we want to close it.
1981 * A bit of a hack, probably the new connection function should have returned a value
1982 * for whether to close, or should have had to close the connection itself if it
1985 * But, this works OK as long as the new connection function doesn't do anything
1986 * crazy like keep the connection around without ref'ing it.
1988 * We have to lock the connection across refcount check and close in case
1989 * the new connection function spawns a thread that closes and unrefs.
1990 * In that case, if the app thread
1991 * closes and unrefs first, we'll harmlessly close again; if the app thread
1992 * still has the ref, we'll close and then the app will close harmlessly.
1993 * If the app unrefs without closing, the app is broken since if the
1994 * app refs from the new connection function it is supposed to also close.
1996 * If we didn't atomically check the refcount and close with the lock held
1997 * though, we could screw this up.
1999 * @param connection the connection
2002 _dbus_connection_close_if_only_one_ref (DBusConnection *connection)
2004 CONNECTION_LOCK (connection);
2006 _dbus_assert (connection->refcount.value > 0);
2008 if (connection->refcount.value == 1)
2009 _dbus_connection_close_possibly_shared_and_unlock (connection);
2011 CONNECTION_UNLOCK (connection);
2016 * When a function that blocks has been called with a timeout, and we
2017 * run out of memory, the time to wait for memory is based on the
2018 * timeout. If the caller was willing to block a long time we wait a
2019 * relatively long time for memory, if they were only willing to block
2020 * briefly then we retry for memory at a rapid rate.
2022 * @timeout_milliseconds the timeout requested for blocking
2025 _dbus_memory_pause_based_on_timeout (int timeout_milliseconds)
2027 if (timeout_milliseconds == -1)
2028 _dbus_sleep_milliseconds (1000);
2029 else if (timeout_milliseconds < 100)
2030 ; /* just busy loop */
2031 else if (timeout_milliseconds <= 1000)
2032 _dbus_sleep_milliseconds (timeout_milliseconds / 3);
2034 _dbus_sleep_milliseconds (1000);
2037 static DBusMessage *
2038 generate_local_error_message (dbus_uint32_t serial,
2042 DBusMessage *message;
2043 message = dbus_message_new (DBUS_MESSAGE_TYPE_ERROR);
2047 if (!dbus_message_set_error_name (message, error_name))
2049 dbus_message_unref (message);
2054 dbus_message_set_no_reply (message, TRUE);
2056 if (!dbus_message_set_reply_serial (message,
2059 dbus_message_unref (message);
2064 if (error_msg != NULL)
2066 DBusMessageIter iter;
2068 dbus_message_iter_init_append (message, &iter);
2069 if (!dbus_message_iter_append_basic (&iter,
2073 dbus_message_unref (message);
2084 /* This is slightly strange since we can pop a message here without
2085 * the dispatch lock.
2088 check_for_reply_unlocked (DBusConnection *connection,
2089 dbus_uint32_t client_serial)
2093 HAVE_LOCK_CHECK (connection);
2095 link = _dbus_list_get_first_link (&connection->incoming_messages);
2097 while (link != NULL)
2099 DBusMessage *reply = link->data;
2101 if (dbus_message_get_reply_serial (reply) == client_serial)
2103 _dbus_list_remove_link (&connection->incoming_messages, link);
2104 connection->n_incoming -= 1;
2107 link = _dbus_list_get_next_link (&connection->incoming_messages, link);
2114 connection_timeout_and_complete_all_pending_calls_unlocked (DBusConnection *connection)
2116 /* We can't iterate over the hash in the normal way since we'll be
2117 * dropping the lock for each item. So we restart the
2118 * iter each time as we drain the hash table.
2121 while (_dbus_hash_table_get_n_entries (connection->pending_replies) > 0)
2123 DBusPendingCall *pending;
2126 _dbus_hash_iter_init (connection->pending_replies, &iter);
2127 _dbus_hash_iter_next (&iter);
2129 pending = _dbus_hash_iter_get_value (&iter);
2130 _dbus_pending_call_ref_unlocked (pending);
2132 _dbus_pending_call_queue_timeout_error_unlocked (pending,
2134 _dbus_connection_remove_timeout_unlocked (connection,
2135 _dbus_pending_call_get_timeout_unlocked (pending));
2136 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
2137 _dbus_hash_iter_remove_entry (&iter);
2139 _dbus_pending_call_unref_and_unlock (pending);
2140 CONNECTION_LOCK (connection);
2142 HAVE_LOCK_CHECK (connection);
2146 complete_pending_call_and_unlock (DBusConnection *connection,
2147 DBusPendingCall *pending,
2148 DBusMessage *message)
2150 _dbus_pending_call_set_reply_unlocked (pending, message);
2151 _dbus_pending_call_ref_unlocked (pending); /* in case there's no app with a ref held */
2152 _dbus_connection_detach_pending_call_and_unlock (connection, pending);
2154 /* Must be called unlocked since it invokes app callback */
2155 _dbus_pending_call_complete (pending);
2156 dbus_pending_call_unref (pending);
2160 check_for_reply_and_update_dispatch_unlocked (DBusConnection *connection,
2161 DBusPendingCall *pending)
2164 DBusDispatchStatus status;
2166 reply = check_for_reply_unlocked (connection,
2167 _dbus_pending_call_get_reply_serial_unlocked (pending));
2170 _dbus_verbose ("%s checked for reply\n", _DBUS_FUNCTION_NAME);
2172 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): got reply\n");
2174 complete_pending_call_and_unlock (connection, pending, reply);
2175 dbus_message_unref (reply);
2177 CONNECTION_LOCK (connection);
2178 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2179 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2180 dbus_pending_call_unref (pending);
2189 * Blocks until a pending call times out or gets a reply.
2191 * Does not re-enter the main loop or run filter/path-registered
2192 * callbacks. The reply to the message will not be seen by
2195 * Returns immediately if pending call already got a reply.
2197 * @todo could use performance improvements (it keeps scanning
2198 * the whole message queue for example)
2200 * @param pending the pending call we block for a reply on
2203 _dbus_connection_block_pending_call (DBusPendingCall *pending)
2205 long start_tv_sec, start_tv_usec;
2206 long end_tv_sec, end_tv_usec;
2207 long tv_sec, tv_usec;
2208 DBusDispatchStatus status;
2209 DBusConnection *connection;
2210 dbus_uint32_t client_serial;
2211 int timeout_milliseconds;
2213 _dbus_assert (pending != NULL);
2215 if (dbus_pending_call_get_completed (pending))
2218 dbus_pending_call_ref (pending); /* necessary because the call could be canceled */
2220 connection = _dbus_pending_call_get_connection_and_lock (pending);
2222 /* Flush message queue - note, can affect dispatch status */
2223 _dbus_connection_flush_unlocked (connection);
2225 client_serial = _dbus_pending_call_get_reply_serial_unlocked (pending);
2227 /* note that timeout_milliseconds is limited to a smallish value
2228 * in _dbus_pending_call_new() so overflows aren't possible
2231 timeout_milliseconds = dbus_timeout_get_interval (_dbus_pending_call_get_timeout_unlocked (pending));
2233 _dbus_get_current_time (&start_tv_sec, &start_tv_usec);
2234 end_tv_sec = start_tv_sec + timeout_milliseconds / 1000;
2235 end_tv_usec = start_tv_usec + (timeout_milliseconds % 1000) * 1000;
2236 end_tv_sec += end_tv_usec / _DBUS_USEC_PER_SECOND;
2237 end_tv_usec = end_tv_usec % _DBUS_USEC_PER_SECOND;
2239 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): will block %d milliseconds for reply serial %u from %ld sec %ld usec to %ld sec %ld usec\n",
2240 timeout_milliseconds,
2242 start_tv_sec, start_tv_usec,
2243 end_tv_sec, end_tv_usec);
2245 /* check to see if we already got the data off the socket */
2246 /* from another blocked pending call */
2247 if (check_for_reply_and_update_dispatch_unlocked (connection, pending))
2250 /* Now we wait... */
2251 /* always block at least once as we know we don't have the reply yet */
2252 _dbus_connection_do_iteration_unlocked (connection,
2253 DBUS_ITERATION_DO_READING |
2254 DBUS_ITERATION_BLOCK,
2255 timeout_milliseconds);
2259 _dbus_verbose ("%s top of recheck\n", _DBUS_FUNCTION_NAME);
2261 HAVE_LOCK_CHECK (connection);
2263 /* queue messages and get status */
2265 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2267 /* the get_completed() is in case a dispatch() while we were blocking
2268 * got the reply instead of us.
2270 if (_dbus_pending_call_get_completed_unlocked (pending))
2272 _dbus_verbose ("Pending call completed by dispatch in %s\n", _DBUS_FUNCTION_NAME);
2273 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2274 dbus_pending_call_unref (pending);
2278 if (status == DBUS_DISPATCH_DATA_REMAINS) {
2279 if (check_for_reply_and_update_dispatch_unlocked (connection, pending))
2283 _dbus_get_current_time (&tv_sec, &tv_usec);
2285 if (!_dbus_connection_get_is_connected_unlocked (connection))
2287 DBusMessage *error_msg;
2289 error_msg = generate_local_error_message (client_serial,
2290 DBUS_ERROR_DISCONNECTED,
2291 "Connection was disconnected before a reply was received");
2293 /* on OOM error_msg is set to NULL */
2294 complete_pending_call_and_unlock (connection, pending, error_msg);
2295 dbus_pending_call_unref (pending);
2298 else if (tv_sec < start_tv_sec)
2299 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): clock set backward\n");
2300 else if (connection->disconnect_message_link == NULL)
2301 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): disconnected\n");
2302 else if (tv_sec < end_tv_sec ||
2303 (tv_sec == end_tv_sec && tv_usec < end_tv_usec))
2305 timeout_milliseconds = (end_tv_sec - tv_sec) * 1000 +
2306 (end_tv_usec - tv_usec) / 1000;
2307 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): %d milliseconds remain\n", timeout_milliseconds);
2308 _dbus_assert (timeout_milliseconds >= 0);
2310 if (status == DBUS_DISPATCH_NEED_MEMORY)
2312 /* Try sleeping a bit, as we aren't sure we need to block for reading,
2313 * we may already have a reply in the buffer and just can't process
2316 _dbus_verbose ("dbus_connection_send_with_reply_and_block() waiting for more memory\n");
2318 _dbus_memory_pause_based_on_timeout (timeout_milliseconds);
2322 /* block again, we don't have the reply buffered yet. */
2323 _dbus_connection_do_iteration_unlocked (connection,
2324 DBUS_ITERATION_DO_READING |
2325 DBUS_ITERATION_BLOCK,
2326 timeout_milliseconds);
2329 goto recheck_status;
2332 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): Waited %ld milliseconds and got no reply\n",
2333 (tv_sec - start_tv_sec) * 1000 + (tv_usec - start_tv_usec) / 1000);
2335 _dbus_assert (!_dbus_pending_call_get_completed_unlocked (pending));
2337 /* unlock and call user code */
2338 complete_pending_call_and_unlock (connection, pending, NULL);
2340 /* update user code on dispatch status */
2341 CONNECTION_LOCK (connection);
2342 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2343 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2344 dbus_pending_call_unref (pending);
2350 * @addtogroup DBusConnection
2356 * Gets a connection to a remote address. If a connection to the given
2357 * address already exists, returns the existing connection with its
2358 * reference count incremented. Otherwise, returns a new connection
2359 * and saves the new connection for possible re-use if a future call
2360 * to dbus_connection_open() asks to connect to the same server.
2362 * Use dbus_connection_open_private() to get a dedicated connection
2363 * not shared with other callers of dbus_connection_open().
2365 * If the open fails, the function returns #NULL, and provides a
2366 * reason for the failure in the error parameter. Pass #NULL for the
2367 * error parameter if you aren't interested in the reason for
2370 * Because this connection is shared, no user of the connection
2371 * may call dbus_connection_close(). However, when you are done with the
2372 * connection you should call dbus_connection_unref().
2374 * @param address the address.
2375 * @param error address where an error can be returned.
2376 * @returns new connection, or #NULL on failure.
2379 dbus_connection_open (const char *address,
2382 DBusConnection *connection;
2384 _dbus_return_val_if_fail (address != NULL, NULL);
2385 _dbus_return_val_if_error_is_set (error, NULL);
2387 connection = _dbus_connection_open_internal (address,
2395 * Opens a new, dedicated connection to a remote address. Unlike
2396 * dbus_connection_open(), always creates a new connection.
2397 * This connection will not be saved or recycled by libdbus.
2399 * If the open fails, the function returns #NULL, and provides a
2400 * reason for the failure in the error parameter. Pass #NULL for the
2401 * error parameter if you aren't interested in the reason for
2404 * When you are done with this connection, you must
2405 * dbus_connection_close() to disconnect it,
2406 * and dbus_connection_unref() to free the connection object.
2408 * (The dbus_connection_close() can be skipped if the
2409 * connection is already known to be disconnected, for example
2410 * if you are inside a handler for the Disconnected signal.)
2412 * @param address the address.
2413 * @param error address where an error can be returned.
2414 * @returns new connection, or #NULL on failure.
2417 dbus_connection_open_private (const char *address,
2420 DBusConnection *connection;
2422 _dbus_return_val_if_fail (address != NULL, NULL);
2423 _dbus_return_val_if_error_is_set (error, NULL);
2425 connection = _dbus_connection_open_internal (address,
2433 * Increments the reference count of a DBusConnection.
2435 * @param connection the connection.
2436 * @returns the connection.
2439 dbus_connection_ref (DBusConnection *connection)
2441 _dbus_return_val_if_fail (connection != NULL, NULL);
2442 _dbus_return_val_if_fail (connection->generation == _dbus_current_generation, NULL);
2444 /* The connection lock is better than the global
2445 * lock in the atomic increment fallback
2448 #ifdef DBUS_HAVE_ATOMIC_INT
2449 _dbus_atomic_inc (&connection->refcount);
2451 CONNECTION_LOCK (connection);
2452 _dbus_assert (connection->refcount.value > 0);
2454 connection->refcount.value += 1;
2455 CONNECTION_UNLOCK (connection);
2462 free_outgoing_message (void *element,
2465 DBusMessage *message = element;
2466 DBusConnection *connection = data;
2468 _dbus_message_remove_size_counter (message,
2469 connection->outgoing_counter,
2471 dbus_message_unref (message);
2474 /* This is run without the mutex held, but after the last reference
2475 * to the connection has been dropped we should have no thread-related
2479 _dbus_connection_last_unref (DBusConnection *connection)
2483 _dbus_verbose ("Finalizing connection %p\n", connection);
2485 _dbus_assert (connection->refcount.value == 0);
2487 /* You have to disconnect the connection before unref:ing it. Otherwise
2488 * you won't get the disconnected message.
2490 _dbus_assert (!_dbus_transport_get_is_connected (connection->transport));
2491 _dbus_assert (connection->server_guid == NULL);
2493 /* ---- We're going to call various application callbacks here, hope it doesn't break anything... */
2494 _dbus_object_tree_free_all_unlocked (connection->objects);
2496 dbus_connection_set_dispatch_status_function (connection, NULL, NULL, NULL);
2497 dbus_connection_set_wakeup_main_function (connection, NULL, NULL, NULL);
2498 dbus_connection_set_unix_user_function (connection, NULL, NULL, NULL);
2500 _dbus_watch_list_free (connection->watches);
2501 connection->watches = NULL;
2503 _dbus_timeout_list_free (connection->timeouts);
2504 connection->timeouts = NULL;
2506 _dbus_data_slot_list_free (&connection->slot_list);
2508 link = _dbus_list_get_first_link (&connection->filter_list);
2509 while (link != NULL)
2511 DBusMessageFilter *filter = link->data;
2512 DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
2514 filter->function = NULL;
2515 _dbus_message_filter_unref (filter); /* calls app callback */
2520 _dbus_list_clear (&connection->filter_list);
2522 /* ---- Done with stuff that invokes application callbacks */
2524 _dbus_object_tree_unref (connection->objects);
2526 _dbus_hash_table_unref (connection->pending_replies);
2527 connection->pending_replies = NULL;
2529 _dbus_list_clear (&connection->filter_list);
2531 _dbus_list_foreach (&connection->outgoing_messages,
2532 free_outgoing_message,
2534 _dbus_list_clear (&connection->outgoing_messages);
2536 _dbus_list_foreach (&connection->incoming_messages,
2537 (DBusForeachFunction) dbus_message_unref,
2539 _dbus_list_clear (&connection->incoming_messages);
2541 _dbus_counter_unref (connection->outgoing_counter);
2543 _dbus_transport_unref (connection->transport);
2545 if (connection->disconnect_message_link)
2547 DBusMessage *message = connection->disconnect_message_link->data;
2548 dbus_message_unref (message);
2549 _dbus_list_free_link (connection->disconnect_message_link);
2552 _dbus_list_clear (&connection->link_cache);
2554 _dbus_condvar_free_at_location (&connection->dispatch_cond);
2555 _dbus_condvar_free_at_location (&connection->io_path_cond);
2557 _dbus_mutex_free_at_location (&connection->io_path_mutex);
2558 _dbus_mutex_free_at_location (&connection->dispatch_mutex);
2560 _dbus_mutex_free_at_location (&connection->mutex);
2562 dbus_free (connection);
2566 * Decrements the reference count of a DBusConnection, and finalizes
2567 * it if the count reaches zero.
2569 * Note: it is a bug to drop the last reference to a connection that
2570 * is still connected.
2572 * For shared connections, libdbus will own a reference
2573 * as long as the connection is connected, so you can know that either
2574 * you don't have the last reference, or it's OK to drop the last reference.
2575 * Most connections are shared. dbus_connection_open() and dbus_bus_get()
2576 * return shared connections.
2578 * For private connections, the creator of the connection must arrange for
2579 * dbus_connection_close() to be called prior to dropping the last reference.
2580 * Private connections come from dbus_connection_open_private() or dbus_bus_get_private().
2582 * @param connection the connection.
2585 dbus_connection_unref (DBusConnection *connection)
2587 dbus_bool_t last_unref;
2589 _dbus_return_if_fail (connection != NULL);
2590 _dbus_return_if_fail (connection->generation == _dbus_current_generation);
2592 /* The connection lock is better than the global
2593 * lock in the atomic increment fallback
2596 #ifdef DBUS_HAVE_ATOMIC_INT
2597 last_unref = (_dbus_atomic_dec (&connection->refcount) == 1);
2599 CONNECTION_LOCK (connection);
2601 _dbus_assert (connection->refcount.value > 0);
2603 connection->refcount.value -= 1;
2604 last_unref = (connection->refcount.value == 0);
2607 printf ("unref() connection %p count = %d\n", connection, connection->refcount.value);
2610 CONNECTION_UNLOCK (connection);
2615 #ifndef DBUS_DISABLE_CHECKS
2616 if (_dbus_transport_get_is_connected (connection->transport))
2618 _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",
2619 connection->shareable ?
2620 "Most likely, the application called unref() too many times and removed a reference belonging to libdbus, since this is a shared connection.\n" :
2621 "Most likely, the application was supposed to call dbus_connection_close(), since this is a private connection.\n");
2625 _dbus_connection_last_unref (connection);
2630 * Note that the transport can disconnect itself (other end drops us)
2631 * and in that case this function never runs. So this function must
2632 * not do anything more than disconnect the transport and update the
2635 * If the transport self-disconnects, then we assume someone will
2636 * dispatch the connection to cause the dispatch status update.
2639 _dbus_connection_close_possibly_shared_and_unlock (DBusConnection *connection)
2641 DBusDispatchStatus status;
2643 HAVE_LOCK_CHECK (connection);
2645 _dbus_verbose ("Disconnecting %p\n", connection);
2647 /* We need to ref because update_dispatch_status_and_unlock will unref
2648 * the connection if it was shared and libdbus was the only remaining
2651 _dbus_connection_ref_unlocked (connection);
2653 _dbus_transport_disconnect (connection->transport);
2655 /* This has the side effect of queuing the disconnect message link
2656 * (unless we don't have enough memory, possibly, so don't assert it).
2657 * After the disconnect message link is queued, dbus_bus_get/dbus_connection_open
2658 * should never again return the newly-disconnected connection.
2660 * However, we only unref the shared connection and exit_on_disconnect when
2661 * the disconnect message reaches the head of the message queue,
2662 * NOT when it's first queued.
2664 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2666 /* This calls out to user code */
2667 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2669 /* Could also call out to user code */
2670 dbus_connection_unref (connection);
2674 * Closes a private connection, so no further data can be sent or received.
2675 * This disconnects the transport (such as a socket) underlying the
2678 * Attempts to send messages after closing a connection are safe, but will result in
2679 * error replies generated locally in libdbus.
2681 * This function does not affect the connection's reference count. It's
2682 * safe to close a connection more than once; all calls after the
2683 * first do nothing. It's impossible to "reopen" a connection, a
2684 * new connection must be created. This function may result in a call
2685 * to the DBusDispatchStatusFunction set with
2686 * dbus_connection_set_dispatch_status_function(), as the disconnect
2687 * message it generates needs to be dispatched.
2689 * If a connection is dropped by the remote application, it will
2692 * You must close a connection prior to releasing the last reference to
2693 * the connection. If you dbus_connection_unref() for the last time
2694 * without closing the connection, the results are undefined; it
2695 * is a bug in your program and libdbus will try to print a warning.
2697 * You may not close a shared connection. Connections created with
2698 * dbus_connection_open() or dbus_bus_get() are shared.
2699 * These connections are owned by libdbus, and applications should
2700 * only unref them, never close them. Applications can know it is
2701 * safe to unref these connections because libdbus will be holding a
2702 * reference as long as the connection is open. Thus, either the
2703 * connection is closed and it is OK to drop the last reference,
2704 * or the connection is open and the app knows it does not have the
2707 * Connections created with dbus_connection_open_private() or
2708 * dbus_bus_get_private() are not kept track of or referenced by
2709 * libdbus. The creator of these connections is responsible for
2710 * calling dbus_connection_close() prior to releasing the last
2711 * reference, if the connection is not already disconnected.
2713 * @param connection the private (unshared) connection to close
2716 dbus_connection_close (DBusConnection *connection)
2718 _dbus_return_if_fail (connection != NULL);
2719 _dbus_return_if_fail (connection->generation == _dbus_current_generation);
2721 CONNECTION_LOCK (connection);
2723 #ifndef DBUS_DISABLE_CHECKS
2724 if (connection->shareable)
2726 CONNECTION_UNLOCK (connection);
2728 _dbus_warn_check_failed ("Applications must not close shared connections - see dbus_connection_close() docs. This is a bug in the application.\n");
2733 _dbus_connection_close_possibly_shared_and_unlock (connection);
2737 _dbus_connection_get_is_connected_unlocked (DBusConnection *connection)
2739 HAVE_LOCK_CHECK (connection);
2740 return _dbus_transport_get_is_connected (connection->transport);
2744 * Gets whether the connection is currently open. A connection may
2745 * become disconnected when the remote application closes its end, or
2746 * exits; a connection may also be disconnected with
2747 * dbus_connection_close().
2749 * There are not separate states for "closed" and "disconnected," the two
2750 * terms are synonymous. This function should really be called
2751 * get_is_open() but for historical reasons is not.
2753 * @param connection the connection.
2754 * @returns #TRUE if the connection is still alive.
2757 dbus_connection_get_is_connected (DBusConnection *connection)
2761 _dbus_return_val_if_fail (connection != NULL, FALSE);
2763 CONNECTION_LOCK (connection);
2764 res = _dbus_connection_get_is_connected_unlocked (connection);
2765 CONNECTION_UNLOCK (connection);
2771 * Gets whether the connection was authenticated. (Note that
2772 * if the connection was authenticated then disconnected,
2773 * this function still returns #TRUE)
2775 * @param connection the connection
2776 * @returns #TRUE if the connection was ever authenticated
2779 dbus_connection_get_is_authenticated (DBusConnection *connection)
2783 _dbus_return_val_if_fail (connection != NULL, FALSE);
2785 CONNECTION_LOCK (connection);
2786 res = _dbus_transport_get_is_authenticated (connection->transport);
2787 CONNECTION_UNLOCK (connection);
2793 * Set whether _exit() should be called when the connection receives a
2794 * disconnect signal. The call to _exit() comes after any handlers for
2795 * the disconnect signal run; handlers can cancel the exit by calling
2798 * By default, exit_on_disconnect is #FALSE; but for message bus
2799 * connections returned from dbus_bus_get() it will be toggled on
2802 * @param connection the connection
2803 * @param exit_on_disconnect #TRUE if _exit() should be called after a disconnect signal
2806 dbus_connection_set_exit_on_disconnect (DBusConnection *connection,
2807 dbus_bool_t exit_on_disconnect)
2809 _dbus_return_if_fail (connection != NULL);
2811 CONNECTION_LOCK (connection);
2812 connection->exit_on_disconnect = exit_on_disconnect != FALSE;
2813 CONNECTION_UNLOCK (connection);
2817 * Preallocates resources needed to send a message, allowing the message
2818 * to be sent without the possibility of memory allocation failure.
2819 * Allows apps to create a future guarantee that they can send
2820 * a message regardless of memory shortages.
2822 * @param connection the connection we're preallocating for.
2823 * @returns the preallocated resources, or #NULL
2825 DBusPreallocatedSend*
2826 dbus_connection_preallocate_send (DBusConnection *connection)
2828 DBusPreallocatedSend *preallocated;
2830 _dbus_return_val_if_fail (connection != NULL, NULL);
2832 CONNECTION_LOCK (connection);
2835 _dbus_connection_preallocate_send_unlocked (connection);
2837 CONNECTION_UNLOCK (connection);
2839 return preallocated;
2843 * Frees preallocated message-sending resources from
2844 * dbus_connection_preallocate_send(). Should only
2845 * be called if the preallocated resources are not used
2846 * to send a message.
2848 * @param connection the connection
2849 * @param preallocated the resources
2852 dbus_connection_free_preallocated_send (DBusConnection *connection,
2853 DBusPreallocatedSend *preallocated)
2855 _dbus_return_if_fail (connection != NULL);
2856 _dbus_return_if_fail (preallocated != NULL);
2857 _dbus_return_if_fail (connection == preallocated->connection);
2859 _dbus_list_free_link (preallocated->queue_link);
2860 _dbus_counter_unref (preallocated->counter_link->data);
2861 _dbus_list_free_link (preallocated->counter_link);
2862 dbus_free (preallocated);
2866 * Sends a message using preallocated resources. This function cannot fail.
2867 * It works identically to dbus_connection_send() in other respects.
2868 * Preallocated resources comes from dbus_connection_preallocate_send().
2869 * This function "consumes" the preallocated resources, they need not
2870 * be freed separately.
2872 * @param connection the connection
2873 * @param preallocated the preallocated resources
2874 * @param message the message to send
2875 * @param client_serial return location for client serial assigned to the message
2878 dbus_connection_send_preallocated (DBusConnection *connection,
2879 DBusPreallocatedSend *preallocated,
2880 DBusMessage *message,
2881 dbus_uint32_t *client_serial)
2883 _dbus_return_if_fail (connection != NULL);
2884 _dbus_return_if_fail (preallocated != NULL);
2885 _dbus_return_if_fail (message != NULL);
2886 _dbus_return_if_fail (preallocated->connection == connection);
2887 _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_METHOD_CALL ||
2888 dbus_message_get_member (message) != NULL);
2889 _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL ||
2890 (dbus_message_get_interface (message) != NULL &&
2891 dbus_message_get_member (message) != NULL));
2893 CONNECTION_LOCK (connection);
2894 _dbus_connection_send_preallocated_and_unlock (connection,
2896 message, client_serial);
2900 _dbus_connection_send_unlocked_no_update (DBusConnection *connection,
2901 DBusMessage *message,
2902 dbus_uint32_t *client_serial)
2904 DBusPreallocatedSend *preallocated;
2906 _dbus_assert (connection != NULL);
2907 _dbus_assert (message != NULL);
2909 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
2910 if (preallocated == NULL)
2913 _dbus_connection_send_preallocated_unlocked_no_update (connection,
2921 * Adds a message to the outgoing message queue. Does not block to
2922 * write the message to the network; that happens asynchronously. To
2923 * force the message to be written, call dbus_connection_flush().
2924 * Because this only queues the message, the only reason it can
2925 * fail is lack of memory. Even if the connection is disconnected,
2926 * no error will be returned.
2928 * If the function fails due to lack of memory, it returns #FALSE.
2929 * The function will never fail for other reasons; even if the
2930 * connection is disconnected, you can queue an outgoing message,
2931 * though obviously it won't be sent.
2933 * The message serial is used by the remote application to send a
2934 * reply; see dbus_message_get_serial() or the D-Bus specification.
2936 * @param connection the connection.
2937 * @param message the message to write.
2938 * @param serial return location for message serial, or #NULL if you don't care
2939 * @returns #TRUE on success.
2942 dbus_connection_send (DBusConnection *connection,
2943 DBusMessage *message,
2944 dbus_uint32_t *serial)
2946 _dbus_return_val_if_fail (connection != NULL, FALSE);
2947 _dbus_return_val_if_fail (message != NULL, FALSE);
2949 CONNECTION_LOCK (connection);
2951 return _dbus_connection_send_and_unlock (connection,
2957 reply_handler_timeout (void *data)
2959 DBusConnection *connection;
2960 DBusDispatchStatus status;
2961 DBusPendingCall *pending = data;
2963 connection = _dbus_pending_call_get_connection_and_lock (pending);
2965 _dbus_pending_call_queue_timeout_error_unlocked (pending,
2967 _dbus_connection_remove_timeout_unlocked (connection,
2968 _dbus_pending_call_get_timeout_unlocked (pending));
2969 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
2971 _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
2972 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2974 /* Unlocks, and calls out to user code */
2975 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2981 * Queues a message to send, as with dbus_connection_send(),
2982 * but also returns a #DBusPendingCall used to receive a reply to the
2983 * message. If no reply is received in the given timeout_milliseconds,
2984 * this function expires the pending reply and generates a synthetic
2985 * error reply (generated in-process, not by the remote application)
2986 * indicating that a timeout occurred.
2988 * A #DBusPendingCall will see a reply message before any filters or
2989 * registered object path handlers. See dbus_connection_dispatch() for
2990 * details on when handlers are run.
2992 * A #DBusPendingCall will always see exactly one reply message,
2993 * unless it's cancelled with dbus_pending_call_cancel().
2995 * If #NULL is passed for the pending_return, the #DBusPendingCall
2996 * will still be generated internally, and used to track
2997 * the message reply timeout. This means a timeout error will
2998 * occur if no reply arrives, unlike with dbus_connection_send().
3000 * If -1 is passed for the timeout, a sane default timeout is used. -1
3001 * is typically the best value for the timeout for this reason, unless
3002 * you want a very short or very long timeout. There is no way to
3003 * avoid a timeout entirely, other than passing INT_MAX for the
3004 * timeout to mean "very long timeout." libdbus clamps an INT_MAX
3005 * timeout down to a few hours timeout though.
3007 * @warning if the connection is disconnected, the #DBusPendingCall
3008 * will be set to #NULL, so be careful with this.
3010 * @param connection the connection
3011 * @param message the message to send
3012 * @param pending_return return location for a #DBusPendingCall object, or #NULL if connection is disconnected
3013 * @param timeout_milliseconds timeout in milliseconds or -1 for default
3014 * @returns #FALSE if no memory, #TRUE otherwise.
3018 dbus_connection_send_with_reply (DBusConnection *connection,
3019 DBusMessage *message,
3020 DBusPendingCall **pending_return,
3021 int timeout_milliseconds)
3023 DBusPendingCall *pending;
3024 dbus_int32_t serial = -1;
3025 DBusDispatchStatus status;
3027 _dbus_return_val_if_fail (connection != NULL, FALSE);
3028 _dbus_return_val_if_fail (message != NULL, FALSE);
3029 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3032 *pending_return = NULL;
3034 CONNECTION_LOCK (connection);
3036 if (!_dbus_connection_get_is_connected_unlocked (connection))
3038 CONNECTION_UNLOCK (connection);
3040 *pending_return = NULL;
3045 pending = _dbus_pending_call_new_unlocked (connection,
3046 timeout_milliseconds,
3047 reply_handler_timeout);
3049 if (pending == NULL)
3051 CONNECTION_UNLOCK (connection);
3055 /* Assign a serial to the message */
3056 serial = dbus_message_get_serial (message);
3059 serial = _dbus_connection_get_next_client_serial (connection);
3060 _dbus_message_set_serial (message, serial);
3063 if (!_dbus_pending_call_set_timeout_error_unlocked (pending, message, serial))
3066 /* Insert the serial in the pending replies hash;
3067 * hash takes a refcount on DBusPendingCall.
3068 * Also, add the timeout.
3070 if (!_dbus_connection_attach_pending_call_unlocked (connection,
3074 if (!_dbus_connection_send_unlocked_no_update (connection, message, NULL))
3076 _dbus_connection_detach_pending_call_and_unlock (connection,
3078 goto error_unlocked;
3082 *pending_return = pending; /* hand off refcount */
3085 _dbus_connection_detach_pending_call_unlocked (connection, pending);
3086 /* we still have a ref to the pending call in this case, we unref
3087 * after unlocking, below
3091 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3093 /* this calls out to user code */
3094 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3096 if (pending_return == NULL)
3097 dbus_pending_call_unref (pending);
3102 CONNECTION_UNLOCK (connection);
3104 dbus_pending_call_unref (pending);
3109 * Sends a message and blocks a certain time period while waiting for
3110 * a reply. This function does not reenter the main loop,
3111 * i.e. messages other than the reply are queued up but not
3112 * processed. This function is used to invoke method calls on a
3115 * If a normal reply is received, it is returned, and removed from the
3116 * incoming message queue. If it is not received, #NULL is returned
3117 * and the error is set to #DBUS_ERROR_NO_REPLY. If an error reply is
3118 * received, it is converted to a #DBusError and returned as an error,
3119 * then the reply message is deleted and #NULL is returned. If
3120 * something else goes wrong, result is set to whatever is
3121 * appropriate, such as #DBUS_ERROR_NO_MEMORY or
3122 * #DBUS_ERROR_DISCONNECTED.
3124 * @warning While this function blocks the calling thread will not be
3125 * processing the incoming message queue. This means you can end up
3126 * deadlocked if the application you're talking to needs you to reply
3127 * to a method. To solve this, either avoid the situation, block in a
3128 * separate thread from the main connection-dispatching thread, or use
3129 * dbus_pending_call_set_notify() to avoid blocking.
3131 * @param connection the connection
3132 * @param message the message to send
3133 * @param timeout_milliseconds timeout in milliseconds or -1 for default
3134 * @param error return location for error message
3135 * @returns the message that is the reply or #NULL with an error code if the
3139 dbus_connection_send_with_reply_and_block (DBusConnection *connection,
3140 DBusMessage *message,
3141 int timeout_milliseconds,
3145 DBusPendingCall *pending;
3147 _dbus_return_val_if_fail (connection != NULL, NULL);
3148 _dbus_return_val_if_fail (message != NULL, NULL);
3149 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, NULL);
3150 _dbus_return_val_if_error_is_set (error, NULL);
3152 if (!dbus_connection_send_with_reply (connection, message,
3153 &pending, timeout_milliseconds))
3155 _DBUS_SET_OOM (error);
3159 if (pending == NULL)
3161 dbus_set_error (error, DBUS_ERROR_DISCONNECTED, "Connection is closed");
3165 dbus_pending_call_block (pending);
3167 reply = dbus_pending_call_steal_reply (pending);
3168 dbus_pending_call_unref (pending);
3170 /* call_complete_and_unlock() called from pending_call_block() should
3171 * always fill this in.
3173 _dbus_assert (reply != NULL);
3175 if (dbus_set_error_from_message (error, reply))
3177 dbus_message_unref (reply);
3185 * Blocks until the outgoing message queue is empty.
3186 * Assumes connection lock already held.
3188 * If you call this, you MUST call update_dispatch_status afterword...
3190 * @param connection the connection.
3193 _dbus_connection_flush_unlocked (DBusConnection *connection)
3195 /* We have to specify DBUS_ITERATION_DO_READING here because
3196 * otherwise we could have two apps deadlock if they are both doing
3197 * a flush(), and the kernel buffers fill up. This could change the
3200 DBusDispatchStatus status;
3202 HAVE_LOCK_CHECK (connection);
3204 while (connection->n_outgoing > 0 &&
3205 _dbus_connection_get_is_connected_unlocked (connection))
3207 _dbus_verbose ("doing iteration in %s\n", _DBUS_FUNCTION_NAME);
3208 HAVE_LOCK_CHECK (connection);
3209 _dbus_connection_do_iteration_unlocked (connection,
3210 DBUS_ITERATION_DO_READING |
3211 DBUS_ITERATION_DO_WRITING |
3212 DBUS_ITERATION_BLOCK,
3216 HAVE_LOCK_CHECK (connection);
3217 _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
3218 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3220 HAVE_LOCK_CHECK (connection);
3225 * Blocks until the outgoing message queue is empty.
3227 * @param connection the connection.
3230 dbus_connection_flush (DBusConnection *connection)
3232 /* We have to specify DBUS_ITERATION_DO_READING here because
3233 * otherwise we could have two apps deadlock if they are both doing
3234 * a flush(), and the kernel buffers fill up. This could change the
3237 DBusDispatchStatus status;
3239 _dbus_return_if_fail (connection != NULL);
3241 CONNECTION_LOCK (connection);
3243 status = _dbus_connection_flush_unlocked (connection);
3245 HAVE_LOCK_CHECK (connection);
3246 /* Unlocks and calls out to user code */
3247 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3249 _dbus_verbose ("%s end\n", _DBUS_FUNCTION_NAME);
3253 * This function implements dbus_connection_read_write_dispatch() and
3254 * dbus_connection_read_write() (they pass a different value for the
3255 * dispatch parameter).
3257 * @param connection the connection
3258 * @param timeout_milliseconds max time to block or -1 for infinite
3259 * @param dispatch dispatch new messages or leave them on the incoming queue
3260 * @returns #TRUE if the disconnect message has not been processed
3263 _dbus_connection_read_write_dispatch (DBusConnection *connection,
3264 int timeout_milliseconds,
3265 dbus_bool_t dispatch)
3267 DBusDispatchStatus dstatus;
3268 dbus_bool_t no_progress_possible;
3270 dstatus = dbus_connection_get_dispatch_status (connection);
3272 if (dispatch && dstatus == DBUS_DISPATCH_DATA_REMAINS)
3274 _dbus_verbose ("doing dispatch in %s\n", _DBUS_FUNCTION_NAME);
3275 dbus_connection_dispatch (connection);
3276 CONNECTION_LOCK (connection);
3278 else if (dstatus == DBUS_DISPATCH_NEED_MEMORY)
3280 _dbus_verbose ("pausing for memory in %s\n", _DBUS_FUNCTION_NAME);
3281 _dbus_memory_pause_based_on_timeout (timeout_milliseconds);
3282 CONNECTION_LOCK (connection);
3286 CONNECTION_LOCK (connection);
3287 if (_dbus_connection_get_is_connected_unlocked (connection))
3289 _dbus_verbose ("doing iteration in %s\n", _DBUS_FUNCTION_NAME);
3290 _dbus_connection_do_iteration_unlocked (connection,
3291 DBUS_ITERATION_DO_READING |
3292 DBUS_ITERATION_DO_WRITING |
3293 DBUS_ITERATION_BLOCK,
3294 timeout_milliseconds);
3298 HAVE_LOCK_CHECK (connection);
3299 /* If we can dispatch, we can make progress until the Disconnected message
3300 * has been processed; if we can only read/write, we can make progress
3301 * as long as the transport is open.
3304 no_progress_possible = connection->n_incoming == 0 &&
3305 connection->disconnect_message_link == NULL;
3307 no_progress_possible = _dbus_connection_get_is_connected_unlocked (connection);
3308 CONNECTION_UNLOCK (connection);
3309 return !no_progress_possible; /* TRUE if we can make more progress */
3314 * This function is intended for use with applications that don't want
3315 * to write a main loop and deal with #DBusWatch and #DBusTimeout. An
3316 * example usage would be:
3319 * while (dbus_connection_read_write_dispatch (connection, -1))
3320 * ; // empty loop body
3323 * In this usage you would normally have set up a filter function to look
3324 * at each message as it is dispatched. The loop terminates when the last
3325 * message from the connection (the disconnected signal) is processed.
3327 * If there are messages to dispatch, this function will
3328 * dbus_connection_dispatch() once, and return. If there are no
3329 * messages to dispatch, this function will block until it can read or
3330 * write, then read or write, then return.
3332 * The way to think of this function is that it either makes some sort
3333 * of progress, or it blocks. Note that, while it is blocked on I/O, it
3334 * cannot be interrupted (even by other threads), which makes this function
3335 * unsuitable for applications that do more than just react to received
3338 * The return value indicates whether the disconnect message has been
3339 * processed, NOT whether the connection is connected. This is
3340 * important because even after disconnecting, you want to process any
3341 * messages you received prior to the disconnect.
3343 * @param connection the connection
3344 * @param timeout_milliseconds max time to block or -1 for infinite
3345 * @returns #TRUE if the disconnect message has not been processed
3348 dbus_connection_read_write_dispatch (DBusConnection *connection,
3349 int timeout_milliseconds)
3351 _dbus_return_val_if_fail (connection != NULL, FALSE);
3352 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3353 return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, TRUE);
3357 * This function is intended for use with applications that don't want to
3358 * write a main loop and deal with #DBusWatch and #DBusTimeout. See also
3359 * dbus_connection_read_write_dispatch().
3361 * As long as the connection is open, this function will block until it can
3362 * read or write, then read or write, then return #TRUE.
3364 * If the connection is closed, the function returns #FALSE.
3366 * The return value indicates whether reading or writing is still
3367 * possible, i.e. whether the connection is connected.
3369 * Note that even after disconnection, messages may remain in the
3370 * incoming queue that need to be
3371 * processed. dbus_connection_read_write_dispatch() dispatches
3372 * incoming messages for you; with dbus_connection_read_write() you
3373 * have to arrange to drain the incoming queue yourself.
3375 * @param connection the connection
3376 * @param timeout_milliseconds max time to block or -1 for infinite
3377 * @returns #TRUE if still connected
3380 dbus_connection_read_write (DBusConnection *connection,
3381 int timeout_milliseconds)
3383 _dbus_return_val_if_fail (connection != NULL, FALSE);
3384 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3385 return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, FALSE);
3388 /* We need to call this anytime we pop the head of the queue, and then
3389 * update_dispatch_status_and_unlock needs to be called afterward
3390 * which will "process" the disconnected message and set
3391 * disconnected_message_processed.
3394 check_disconnected_message_arrived_unlocked (DBusConnection *connection,
3395 DBusMessage *head_of_queue)
3397 HAVE_LOCK_CHECK (connection);
3399 /* checking that the link is NULL is an optimization to avoid the is_signal call */
3400 if (connection->disconnect_message_link == NULL &&
3401 dbus_message_is_signal (head_of_queue,
3402 DBUS_INTERFACE_LOCAL,
3405 connection->disconnected_message_arrived = TRUE;
3410 * Returns the first-received message from the incoming message queue,
3411 * leaving it in the queue. If the queue is empty, returns #NULL.
3413 * The caller does not own a reference to the returned message, and
3414 * must either return it using dbus_connection_return_message() or
3415 * keep it after calling dbus_connection_steal_borrowed_message(). No
3416 * one can get at the message while its borrowed, so return it as
3417 * quickly as possible and don't keep a reference to it after
3418 * returning it. If you need to keep the message, make a copy of it.
3420 * dbus_connection_dispatch() will block if called while a borrowed
3421 * message is outstanding; only one piece of code can be playing with
3422 * the incoming queue at a time. This function will block if called
3423 * during a dbus_connection_dispatch().
3425 * @param connection the connection.
3426 * @returns next message in the incoming queue.
3429 dbus_connection_borrow_message (DBusConnection *connection)
3431 DBusDispatchStatus status;
3432 DBusMessage *message;
3434 _dbus_return_val_if_fail (connection != NULL, NULL);
3436 _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
3438 /* this is called for the side effect that it queues
3439 * up any messages from the transport
3441 status = dbus_connection_get_dispatch_status (connection);
3442 if (status != DBUS_DISPATCH_DATA_REMAINS)
3445 CONNECTION_LOCK (connection);
3447 _dbus_connection_acquire_dispatch (connection);
3449 /* While a message is outstanding, the dispatch lock is held */
3450 _dbus_assert (connection->message_borrowed == NULL);
3452 connection->message_borrowed = _dbus_list_get_first (&connection->incoming_messages);
3454 message = connection->message_borrowed;
3456 check_disconnected_message_arrived_unlocked (connection, message);
3458 /* Note that we KEEP the dispatch lock until the message is returned */
3459 if (message == NULL)
3460 _dbus_connection_release_dispatch (connection);
3462 CONNECTION_UNLOCK (connection);
3464 /* We don't update dispatch status until it's returned or stolen */
3470 * Used to return a message after peeking at it using
3471 * dbus_connection_borrow_message(). Only called if
3472 * message from dbus_connection_borrow_message() was non-#NULL.
3474 * @param connection the connection
3475 * @param message the message from dbus_connection_borrow_message()
3478 dbus_connection_return_message (DBusConnection *connection,
3479 DBusMessage *message)
3481 DBusDispatchStatus status;
3483 _dbus_return_if_fail (connection != NULL);
3484 _dbus_return_if_fail (message != NULL);
3485 _dbus_return_if_fail (message == connection->message_borrowed);
3486 _dbus_return_if_fail (connection->dispatch_acquired);
3488 CONNECTION_LOCK (connection);
3490 _dbus_assert (message == connection->message_borrowed);
3492 connection->message_borrowed = NULL;
3494 _dbus_connection_release_dispatch (connection);
3496 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3497 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3501 * Used to keep a message after peeking at it using
3502 * dbus_connection_borrow_message(). Before using this function, see
3503 * the caveats/warnings in the documentation for
3504 * dbus_connection_pop_message().
3506 * @param connection the connection
3507 * @param message the message from dbus_connection_borrow_message()
3510 dbus_connection_steal_borrowed_message (DBusConnection *connection,
3511 DBusMessage *message)
3513 DBusMessage *pop_message;
3514 DBusDispatchStatus status;
3516 _dbus_return_if_fail (connection != NULL);
3517 _dbus_return_if_fail (message != NULL);
3518 _dbus_return_if_fail (message == connection->message_borrowed);
3519 _dbus_return_if_fail (connection->dispatch_acquired);
3521 CONNECTION_LOCK (connection);
3523 _dbus_assert (message == connection->message_borrowed);
3525 pop_message = _dbus_list_pop_first (&connection->incoming_messages);
3526 _dbus_assert (message == pop_message);
3528 connection->n_incoming -= 1;
3530 _dbus_verbose ("Incoming message %p stolen from queue, %d incoming\n",
3531 message, connection->n_incoming);
3533 connection->message_borrowed = NULL;
3535 _dbus_connection_release_dispatch (connection);
3537 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3538 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3541 /* See dbus_connection_pop_message, but requires the caller to own
3542 * the lock before calling. May drop the lock while running.
3545 _dbus_connection_pop_message_link_unlocked (DBusConnection *connection)
3547 HAVE_LOCK_CHECK (connection);
3549 _dbus_assert (connection->message_borrowed == NULL);
3551 if (connection->n_incoming > 0)
3555 link = _dbus_list_pop_first_link (&connection->incoming_messages);
3556 connection->n_incoming -= 1;
3558 _dbus_verbose ("Message %p (%d %s %s %s '%s') removed from incoming queue %p, %d incoming\n",
3560 dbus_message_get_type (link->data),
3561 dbus_message_get_path (link->data) ?
3562 dbus_message_get_path (link->data) :
3564 dbus_message_get_interface (link->data) ?
3565 dbus_message_get_interface (link->data) :
3567 dbus_message_get_member (link->data) ?
3568 dbus_message_get_member (link->data) :
3570 dbus_message_get_signature (link->data),
3571 connection, connection->n_incoming);
3573 check_disconnected_message_arrived_unlocked (connection, link->data);
3581 /* See dbus_connection_pop_message, but requires the caller to own
3582 * the lock before calling. May drop the lock while running.
3585 _dbus_connection_pop_message_unlocked (DBusConnection *connection)
3589 HAVE_LOCK_CHECK (connection);
3591 link = _dbus_connection_pop_message_link_unlocked (connection);
3595 DBusMessage *message;
3597 message = link->data;
3599 _dbus_list_free_link (link);
3608 _dbus_connection_putback_message_link_unlocked (DBusConnection *connection,
3609 DBusList *message_link)
3611 HAVE_LOCK_CHECK (connection);
3613 _dbus_assert (message_link != NULL);
3614 /* You can't borrow a message while a link is outstanding */
3615 _dbus_assert (connection->message_borrowed == NULL);
3616 /* We had to have the dispatch lock across the pop/putback */
3617 _dbus_assert (connection->dispatch_acquired);
3619 _dbus_list_prepend_link (&connection->incoming_messages,
3621 connection->n_incoming += 1;
3623 _dbus_verbose ("Message %p (%d %s %s '%s') put back into queue %p, %d incoming\n",
3625 dbus_message_get_type (message_link->data),
3626 dbus_message_get_interface (message_link->data) ?
3627 dbus_message_get_interface (message_link->data) :
3629 dbus_message_get_member (message_link->data) ?
3630 dbus_message_get_member (message_link->data) :
3632 dbus_message_get_signature (message_link->data),
3633 connection, connection->n_incoming);
3637 * Returns the first-received message from the incoming message queue,
3638 * removing it from the queue. The caller owns a reference to the
3639 * returned message. If the queue is empty, returns #NULL.
3641 * This function bypasses any message handlers that are registered,
3642 * and so using it is usually wrong. Instead, let the main loop invoke
3643 * dbus_connection_dispatch(). Popping messages manually is only
3644 * useful in very simple programs that don't share a #DBusConnection
3645 * with any libraries or other modules.
3647 * There is a lock that covers all ways of accessing the incoming message
3648 * queue, so dbus_connection_dispatch(), dbus_connection_pop_message(),
3649 * dbus_connection_borrow_message(), etc. will all block while one of the others
3650 * in the group is running.
3652 * @param connection the connection.
3653 * @returns next message in the incoming queue.
3656 dbus_connection_pop_message (DBusConnection *connection)
3658 DBusMessage *message;
3659 DBusDispatchStatus status;
3661 _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
3663 /* this is called for the side effect that it queues
3664 * up any messages from the transport
3666 status = dbus_connection_get_dispatch_status (connection);
3667 if (status != DBUS_DISPATCH_DATA_REMAINS)
3670 CONNECTION_LOCK (connection);
3671 _dbus_connection_acquire_dispatch (connection);
3672 HAVE_LOCK_CHECK (connection);
3674 message = _dbus_connection_pop_message_unlocked (connection);
3676 _dbus_verbose ("Returning popped message %p\n", message);
3678 _dbus_connection_release_dispatch (connection);
3680 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3681 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3687 * Acquire the dispatcher. This is a separate lock so the main
3688 * connection lock can be dropped to call out to application dispatch
3691 * @param connection the connection.
3694 _dbus_connection_acquire_dispatch (DBusConnection *connection)
3696 HAVE_LOCK_CHECK (connection);
3698 _dbus_connection_ref_unlocked (connection);
3699 CONNECTION_UNLOCK (connection);
3701 _dbus_verbose ("%s locking dispatch_mutex\n", _DBUS_FUNCTION_NAME);
3702 _dbus_mutex_lock (connection->dispatch_mutex);
3704 while (connection->dispatch_acquired)
3706 _dbus_verbose ("%s waiting for dispatch to be acquirable\n", _DBUS_FUNCTION_NAME);
3707 _dbus_condvar_wait (connection->dispatch_cond,
3708 connection->dispatch_mutex);
3711 _dbus_assert (!connection->dispatch_acquired);
3713 connection->dispatch_acquired = TRUE;
3715 _dbus_verbose ("%s unlocking dispatch_mutex\n", _DBUS_FUNCTION_NAME);
3716 _dbus_mutex_unlock (connection->dispatch_mutex);
3718 CONNECTION_LOCK (connection);
3719 _dbus_connection_unref_unlocked (connection);
3723 * Release the dispatcher when you're done with it. Only call
3724 * after you've acquired the dispatcher. Wakes up at most one
3725 * thread currently waiting to acquire the dispatcher.
3727 * @param connection the connection.
3730 _dbus_connection_release_dispatch (DBusConnection *connection)
3732 HAVE_LOCK_CHECK (connection);
3734 _dbus_verbose ("%s locking dispatch_mutex\n", _DBUS_FUNCTION_NAME);
3735 _dbus_mutex_lock (connection->dispatch_mutex);
3737 _dbus_assert (connection->dispatch_acquired);
3739 connection->dispatch_acquired = FALSE;
3740 _dbus_condvar_wake_one (connection->dispatch_cond);
3742 _dbus_verbose ("%s unlocking dispatch_mutex\n", _DBUS_FUNCTION_NAME);
3743 _dbus_mutex_unlock (connection->dispatch_mutex);
3747 _dbus_connection_failed_pop (DBusConnection *connection,
3748 DBusList *message_link)
3750 _dbus_list_prepend_link (&connection->incoming_messages,
3752 connection->n_incoming += 1;
3755 /* Note this may be called multiple times since we don't track whether we already did it */
3757 notify_disconnected_unlocked (DBusConnection *connection)
3759 HAVE_LOCK_CHECK (connection);
3761 /* Set the weakref in dbus-bus.c to NULL, so nobody will get a disconnected
3762 * connection from dbus_bus_get(). We make the same guarantee for
3763 * dbus_connection_open() but in a different way since we don't want to
3764 * unref right here; we instead check for connectedness before returning
3765 * the connection from the hash.
3767 _dbus_bus_notify_shared_connection_disconnected_unlocked (connection);
3769 /* Dump the outgoing queue, we aren't going to be able to
3770 * send it now, and we'd like accessors like
3771 * dbus_connection_get_outgoing_size() to be accurate.
3773 if (connection->n_outgoing > 0)
3777 _dbus_verbose ("Dropping %d outgoing messages since we're disconnected\n",
3778 connection->n_outgoing);
3780 while ((link = _dbus_list_get_last_link (&connection->outgoing_messages)))
3782 _dbus_connection_message_sent (connection, link->data);
3787 /* Note this may be called multiple times since we don't track whether we already did it */
3788 static DBusDispatchStatus
3789 notify_disconnected_and_dispatch_complete_unlocked (DBusConnection *connection)
3791 HAVE_LOCK_CHECK (connection);
3793 if (connection->disconnect_message_link != NULL)
3795 _dbus_verbose ("Sending disconnect message from %s\n",
3796 _DBUS_FUNCTION_NAME);
3798 /* If we have pending calls, queue their timeouts - we want the Disconnected
3799 * to be the last message, after these timeouts.
3801 connection_timeout_and_complete_all_pending_calls_unlocked (connection);
3803 /* We haven't sent the disconnect message already,
3804 * and all real messages have been queued up.
3806 _dbus_connection_queue_synthesized_message_link (connection,
3807 connection->disconnect_message_link);
3808 connection->disconnect_message_link = NULL;
3810 return DBUS_DISPATCH_DATA_REMAINS;
3813 return DBUS_DISPATCH_COMPLETE;
3816 static DBusDispatchStatus
3817 _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection)
3819 HAVE_LOCK_CHECK (connection);
3821 if (connection->n_incoming > 0)
3822 return DBUS_DISPATCH_DATA_REMAINS;
3823 else if (!_dbus_transport_queue_messages (connection->transport))
3824 return DBUS_DISPATCH_NEED_MEMORY;
3827 DBusDispatchStatus status;
3828 dbus_bool_t is_connected;
3830 status = _dbus_transport_get_dispatch_status (connection->transport);
3831 is_connected = _dbus_transport_get_is_connected (connection->transport);
3833 _dbus_verbose ("dispatch status = %s is_connected = %d\n",
3834 DISPATCH_STATUS_NAME (status), is_connected);
3838 /* It's possible this would be better done by having an explicit
3839 * notification from _dbus_transport_disconnect() that would
3840 * synchronously do this, instead of waiting for the next dispatch
3841 * status check. However, probably not good to change until it causes
3844 notify_disconnected_unlocked (connection);
3846 /* I'm not sure this is needed; the idea is that we want to
3847 * queue the Disconnected only after we've read all the
3848 * messages, but if we're disconnected maybe we are guaranteed
3849 * to have read them all ?
3851 if (status == DBUS_DISPATCH_COMPLETE)
3852 status = notify_disconnected_and_dispatch_complete_unlocked (connection);
3855 if (status != DBUS_DISPATCH_COMPLETE)
3857 else if (connection->n_incoming > 0)
3858 return DBUS_DISPATCH_DATA_REMAINS;
3860 return DBUS_DISPATCH_COMPLETE;
3865 _dbus_connection_update_dispatch_status_and_unlock (DBusConnection *connection,
3866 DBusDispatchStatus new_status)
3868 dbus_bool_t changed;
3869 DBusDispatchStatusFunction function;
3872 HAVE_LOCK_CHECK (connection);
3874 _dbus_connection_ref_unlocked (connection);
3876 changed = new_status != connection->last_dispatch_status;
3878 connection->last_dispatch_status = new_status;
3880 function = connection->dispatch_status_function;
3881 data = connection->dispatch_status_data;
3883 if (connection->disconnected_message_arrived &&
3884 !connection->disconnected_message_processed)
3886 connection->disconnected_message_processed = TRUE;
3888 /* this does an unref, but we have a ref
3889 * so we should not run the finalizer here
3892 connection_forget_shared_unlocked (connection);
3894 if (connection->exit_on_disconnect)
3896 CONNECTION_UNLOCK (connection);
3898 _dbus_verbose ("Exiting on Disconnected signal\n");
3900 _dbus_assert_not_reached ("Call to exit() returned");
3904 /* We drop the lock */
3905 CONNECTION_UNLOCK (connection);
3907 if (changed && function)
3909 _dbus_verbose ("Notifying of change to dispatch status of %p now %d (%s)\n",
3910 connection, new_status,
3911 DISPATCH_STATUS_NAME (new_status));
3912 (* function) (connection, new_status, data);
3915 dbus_connection_unref (connection);
3919 * Gets the current state of the incoming message queue.
3920 * #DBUS_DISPATCH_DATA_REMAINS indicates that the message queue
3921 * may contain messages. #DBUS_DISPATCH_COMPLETE indicates that the
3922 * incoming queue is empty. #DBUS_DISPATCH_NEED_MEMORY indicates that
3923 * there could be data, but we can't know for sure without more
3926 * To process the incoming message queue, use dbus_connection_dispatch()
3927 * or (in rare cases) dbus_connection_pop_message().
3929 * Note, #DBUS_DISPATCH_DATA_REMAINS really means that either we
3930 * have messages in the queue, or we have raw bytes buffered up
3931 * that need to be parsed. When these bytes are parsed, they
3932 * may not add up to an entire message. Thus, it's possible
3933 * to see a status of #DBUS_DISPATCH_DATA_REMAINS but not
3934 * have a message yet.
3936 * In particular this happens on initial connection, because all sorts
3937 * of authentication protocol stuff has to be parsed before the
3938 * first message arrives.
3940 * @param connection the connection.
3941 * @returns current dispatch status
3944 dbus_connection_get_dispatch_status (DBusConnection *connection)
3946 DBusDispatchStatus status;
3948 _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
3950 _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
3952 CONNECTION_LOCK (connection);
3954 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3956 CONNECTION_UNLOCK (connection);
3962 * Filter funtion for handling the Peer standard interface.
3964 static DBusHandlerResult
3965 _dbus_connection_peer_filter_unlocked_no_update (DBusConnection *connection,
3966 DBusMessage *message)
3968 if (connection->route_peer_messages && dbus_message_get_destination (message) != NULL)
3970 /* This means we're letting the bus route this message */
3971 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
3973 else if (dbus_message_is_method_call (message,
3974 DBUS_INTERFACE_PEER,
3980 ret = dbus_message_new_method_return (message);
3982 return DBUS_HANDLER_RESULT_NEED_MEMORY;
3984 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
3986 dbus_message_unref (ret);
3989 return DBUS_HANDLER_RESULT_NEED_MEMORY;
3991 return DBUS_HANDLER_RESULT_HANDLED;
3993 else if (dbus_message_is_method_call (message,
3994 DBUS_INTERFACE_PEER,
4001 ret = dbus_message_new_method_return (message);
4003 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4006 _dbus_string_init (&uuid);
4007 if (_dbus_get_local_machine_uuid_encoded (&uuid))
4009 const char *v_STRING = _dbus_string_get_const_data (&uuid);
4010 if (dbus_message_append_args (ret,
4011 DBUS_TYPE_STRING, &v_STRING,
4014 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4017 _dbus_string_free (&uuid);
4019 dbus_message_unref (ret);
4022 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4024 return DBUS_HANDLER_RESULT_HANDLED;
4026 else if (dbus_message_has_interface (message, DBUS_INTERFACE_PEER))
4028 /* We need to bounce anything else with this interface, otherwise apps
4029 * could start extending the interface and when we added extensions
4030 * here to DBusConnection we'd break those apps.
4036 ret = dbus_message_new_error (message,
4037 DBUS_ERROR_UNKNOWN_METHOD,
4038 "Unknown method invoked on org.freedesktop.DBus.Peer interface");
4040 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4042 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4044 dbus_message_unref (ret);
4047 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4049 return DBUS_HANDLER_RESULT_HANDLED;
4053 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4058 * Processes all builtin filter functions
4060 * If the spec specifies a standard interface
4061 * they should be processed from this method
4063 static DBusHandlerResult
4064 _dbus_connection_run_builtin_filters_unlocked_no_update (DBusConnection *connection,
4065 DBusMessage *message)
4067 /* We just run one filter for now but have the option to run more
4068 if the spec calls for it in the future */
4070 return _dbus_connection_peer_filter_unlocked_no_update (connection, message);
4074 * Processes any incoming data.
4076 * If there's incoming raw data that has not yet been parsed, it is
4077 * parsed, which may or may not result in adding messages to the
4080 * The incoming data buffer is filled when the connection reads from
4081 * its underlying transport (such as a socket). Reading usually
4082 * happens in dbus_watch_handle() or dbus_connection_read_write().
4084 * If there are complete messages in the incoming queue,
4085 * dbus_connection_dispatch() removes one message from the queue and
4086 * processes it. Processing has three steps.
4088 * First, any method replies are passed to #DBusPendingCall or
4089 * dbus_connection_send_with_reply_and_block() in order to
4090 * complete the pending method call.
4092 * Second, any filters registered with dbus_connection_add_filter()
4093 * are run. If any filter returns #DBUS_HANDLER_RESULT_HANDLED
4094 * then processing stops after that filter.
4096 * Third, if the message is a method call it is forwarded to
4097 * any registered object path handlers added with
4098 * dbus_connection_register_object_path() or
4099 * dbus_connection_register_fallback().
4101 * A single call to dbus_connection_dispatch() will process at most
4102 * one message; it will not clear the entire message queue.
4104 * Be careful about calling dbus_connection_dispatch() from inside a
4105 * message handler, i.e. calling dbus_connection_dispatch()
4106 * recursively. If threads have been initialized with a recursive
4107 * mutex function, then this will not deadlock; however, it can
4108 * certainly confuse your application.
4110 * @todo some FIXME in here about handling DBUS_HANDLER_RESULT_NEED_MEMORY
4112 * @param connection the connection
4113 * @returns dispatch status, see dbus_connection_get_dispatch_status()
4116 dbus_connection_dispatch (DBusConnection *connection)
4118 DBusMessage *message;
4119 DBusList *link, *filter_list_copy, *message_link;
4120 DBusHandlerResult result;
4121 DBusPendingCall *pending;
4122 dbus_int32_t reply_serial;
4123 DBusDispatchStatus status;
4125 _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
4127 _dbus_verbose ("%s\n", _DBUS_FUNCTION_NAME);
4129 CONNECTION_LOCK (connection);
4130 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4131 if (status != DBUS_DISPATCH_DATA_REMAINS)
4133 /* unlocks and calls out to user code */
4134 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4138 /* We need to ref the connection since the callback could potentially
4139 * drop the last ref to it
4141 _dbus_connection_ref_unlocked (connection);
4143 _dbus_connection_acquire_dispatch (connection);
4144 HAVE_LOCK_CHECK (connection);
4146 message_link = _dbus_connection_pop_message_link_unlocked (connection);
4147 if (message_link == NULL)
4149 /* another thread dispatched our stuff */
4151 _dbus_verbose ("another thread dispatched message (during acquire_dispatch above)\n");
4153 _dbus_connection_release_dispatch (connection);
4155 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4157 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4159 dbus_connection_unref (connection);
4164 message = message_link->data;
4166 _dbus_verbose (" dispatching message %p (%d %s %s '%s')\n",
4168 dbus_message_get_type (message),
4169 dbus_message_get_interface (message) ?
4170 dbus_message_get_interface (message) :
4172 dbus_message_get_member (message) ?
4173 dbus_message_get_member (message) :
4175 dbus_message_get_signature (message));
4177 result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4179 /* Pending call handling must be first, because if you do
4180 * dbus_connection_send_with_reply_and_block() or
4181 * dbus_pending_call_block() then no handlers/filters will be run on
4182 * the reply. We want consistent semantics in the case where we
4183 * dbus_connection_dispatch() the reply.
4186 reply_serial = dbus_message_get_reply_serial (message);
4187 pending = _dbus_hash_table_lookup_int (connection->pending_replies,
4191 _dbus_verbose ("Dispatching a pending reply\n");
4192 complete_pending_call_and_unlock (connection, pending, message);
4193 pending = NULL; /* it's probably unref'd */
4195 CONNECTION_LOCK (connection);
4196 _dbus_verbose ("pending call completed in dispatch\n");
4197 result = DBUS_HANDLER_RESULT_HANDLED;
4201 result = _dbus_connection_run_builtin_filters_unlocked_no_update (connection, message);
4202 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4205 if (!_dbus_list_copy (&connection->filter_list, &filter_list_copy))
4207 _dbus_connection_release_dispatch (connection);
4208 HAVE_LOCK_CHECK (connection);
4210 _dbus_connection_failed_pop (connection, message_link);
4212 /* unlocks and calls user code */
4213 _dbus_connection_update_dispatch_status_and_unlock (connection,
4214 DBUS_DISPATCH_NEED_MEMORY);
4217 dbus_pending_call_unref (pending);
4218 dbus_connection_unref (connection);
4220 return DBUS_DISPATCH_NEED_MEMORY;
4223 _dbus_list_foreach (&filter_list_copy,
4224 (DBusForeachFunction)_dbus_message_filter_ref,
4227 /* We're still protected from dispatch() reentrancy here
4228 * since we acquired the dispatcher
4230 CONNECTION_UNLOCK (connection);
4232 link = _dbus_list_get_first_link (&filter_list_copy);
4233 while (link != NULL)
4235 DBusMessageFilter *filter = link->data;
4236 DBusList *next = _dbus_list_get_next_link (&filter_list_copy, link);
4238 if (filter->function == NULL)
4240 _dbus_verbose (" filter was removed in a callback function\n");
4245 _dbus_verbose (" running filter on message %p\n", message);
4246 result = (* filter->function) (connection, message, filter->user_data);
4248 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4254 _dbus_list_foreach (&filter_list_copy,
4255 (DBusForeachFunction)_dbus_message_filter_unref,
4257 _dbus_list_clear (&filter_list_copy);
4259 CONNECTION_LOCK (connection);
4261 if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
4263 _dbus_verbose ("No memory in %s\n", _DBUS_FUNCTION_NAME);
4266 else if (result == DBUS_HANDLER_RESULT_HANDLED)
4268 _dbus_verbose ("filter handled message in dispatch\n");
4272 /* We're still protected from dispatch() reentrancy here
4273 * since we acquired the dispatcher
4275 _dbus_verbose (" running object path dispatch on message %p (%d %s %s '%s')\n",
4277 dbus_message_get_type (message),
4278 dbus_message_get_interface (message) ?
4279 dbus_message_get_interface (message) :
4281 dbus_message_get_member (message) ?
4282 dbus_message_get_member (message) :
4284 dbus_message_get_signature (message));
4286 HAVE_LOCK_CHECK (connection);
4287 result = _dbus_object_tree_dispatch_and_unlock (connection->objects,
4290 CONNECTION_LOCK (connection);
4292 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4294 _dbus_verbose ("object tree handled message in dispatch\n");
4298 if (dbus_message_get_type (message) == DBUS_MESSAGE_TYPE_METHOD_CALL)
4302 DBusPreallocatedSend *preallocated;
4304 _dbus_verbose (" sending error %s\n",
4305 DBUS_ERROR_UNKNOWN_METHOD);
4307 if (!_dbus_string_init (&str))
4309 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4310 _dbus_verbose ("no memory for error string in dispatch\n");
4314 if (!_dbus_string_append_printf (&str,
4315 "Method \"%s\" with signature \"%s\" on interface \"%s\" doesn't exist\n",
4316 dbus_message_get_member (message),
4317 dbus_message_get_signature (message),
4318 dbus_message_get_interface (message)))
4320 _dbus_string_free (&str);
4321 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4322 _dbus_verbose ("no memory for error string in dispatch\n");
4326 reply = dbus_message_new_error (message,
4327 DBUS_ERROR_UNKNOWN_METHOD,
4328 _dbus_string_get_const_data (&str));
4329 _dbus_string_free (&str);
4333 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4334 _dbus_verbose ("no memory for error reply in dispatch\n");
4338 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
4340 if (preallocated == NULL)
4342 dbus_message_unref (reply);
4343 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4344 _dbus_verbose ("no memory for error send in dispatch\n");
4348 _dbus_connection_send_preallocated_unlocked_no_update (connection, preallocated,
4351 dbus_message_unref (reply);
4353 result = DBUS_HANDLER_RESULT_HANDLED;
4356 _dbus_verbose (" done dispatching %p (%d %s %s '%s') on connection %p\n", message,
4357 dbus_message_get_type (message),
4358 dbus_message_get_interface (message) ?
4359 dbus_message_get_interface (message) :
4361 dbus_message_get_member (message) ?
4362 dbus_message_get_member (message) :
4364 dbus_message_get_signature (message),
4368 if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
4370 _dbus_verbose ("out of memory in %s\n", _DBUS_FUNCTION_NAME);
4372 /* Put message back, and we'll start over.
4373 * Yes this means handlers must be idempotent if they
4374 * don't return HANDLED; c'est la vie.
4376 _dbus_connection_putback_message_link_unlocked (connection,
4381 _dbus_verbose (" ... done dispatching in %s\n", _DBUS_FUNCTION_NAME);
4383 _dbus_list_free_link (message_link);
4384 dbus_message_unref (message); /* don't want the message to count in max message limits
4385 * in computing dispatch status below
4389 _dbus_connection_release_dispatch (connection);
4390 HAVE_LOCK_CHECK (connection);
4392 _dbus_verbose ("%s before final status update\n", _DBUS_FUNCTION_NAME);
4393 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4395 /* unlocks and calls user code */
4396 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4398 dbus_connection_unref (connection);
4404 * Sets the watch functions for the connection. These functions are
4405 * responsible for making the application's main loop aware of file
4406 * descriptors that need to be monitored for events, using select() or
4407 * poll(). When using Qt, typically the DBusAddWatchFunction would
4408 * create a QSocketNotifier. When using GLib, the DBusAddWatchFunction
4409 * could call g_io_add_watch(), or could be used as part of a more
4410 * elaborate GSource. Note that when a watch is added, it may
4413 * The DBusWatchToggledFunction notifies the application that the
4414 * watch has been enabled or disabled. Call dbus_watch_get_enabled()
4415 * to check this. A disabled watch should have no effect, and enabled
4416 * watch should be added to the main loop. This feature is used
4417 * instead of simply adding/removing the watch because
4418 * enabling/disabling can be done without memory allocation. The
4419 * toggled function may be NULL if a main loop re-queries
4420 * dbus_watch_get_enabled() every time anyway.
4422 * The DBusWatch can be queried for the file descriptor to watch using
4423 * dbus_watch_get_fd(), and for the events to watch for using
4424 * dbus_watch_get_flags(). The flags returned by
4425 * dbus_watch_get_flags() will only contain DBUS_WATCH_READABLE and
4426 * DBUS_WATCH_WRITABLE, never DBUS_WATCH_HANGUP or DBUS_WATCH_ERROR;
4427 * all watches implicitly include a watch for hangups, errors, and
4428 * other exceptional conditions.
4430 * Once a file descriptor becomes readable or writable, or an exception
4431 * occurs, dbus_watch_handle() should be called to
4432 * notify the connection of the file descriptor's condition.
4434 * dbus_watch_handle() cannot be called during the
4435 * DBusAddWatchFunction, as the connection will not be ready to handle
4438 * It is not allowed to reference a DBusWatch after it has been passed
4439 * to remove_function.
4441 * If #FALSE is returned due to lack of memory, the failure may be due
4442 * to a #FALSE return from the new add_function. If so, the
4443 * add_function may have been called successfully one or more times,
4444 * but the remove_function will also have been called to remove any
4445 * successful adds. i.e. if #FALSE is returned the net result
4446 * should be that dbus_connection_set_watch_functions() has no effect,
4447 * but the add_function and remove_function may have been called.
4449 * @todo We need to drop the lock when we call the
4450 * add/remove/toggled functions which can be a side effect
4451 * of setting the watch functions.
4453 * @param connection the connection.
4454 * @param add_function function to begin monitoring a new descriptor.
4455 * @param remove_function function to stop monitoring a descriptor.
4456 * @param toggled_function function to notify of enable/disable
4457 * @param data data to pass to add_function and remove_function.
4458 * @param free_data_function function to be called to free the data.
4459 * @returns #FALSE on failure (no memory)
4462 dbus_connection_set_watch_functions (DBusConnection *connection,
4463 DBusAddWatchFunction add_function,
4464 DBusRemoveWatchFunction remove_function,
4465 DBusWatchToggledFunction toggled_function,
4467 DBusFreeFunction free_data_function)
4470 DBusWatchList *watches;
4472 _dbus_return_val_if_fail (connection != NULL, FALSE);
4474 CONNECTION_LOCK (connection);
4476 #ifndef DBUS_DISABLE_CHECKS
4477 if (connection->watches == NULL)
4479 _dbus_warn_check_failed ("Re-entrant call to %s is not allowed\n",
4480 _DBUS_FUNCTION_NAME);
4485 /* ref connection for slightly better reentrancy */
4486 _dbus_connection_ref_unlocked (connection);
4488 /* This can call back into user code, and we need to drop the
4489 * connection lock when it does. This is kind of a lame
4492 watches = connection->watches;
4493 connection->watches = NULL;
4494 CONNECTION_UNLOCK (connection);
4496 retval = _dbus_watch_list_set_functions (watches,
4497 add_function, remove_function,
4499 data, free_data_function);
4500 CONNECTION_LOCK (connection);
4501 connection->watches = watches;
4503 CONNECTION_UNLOCK (connection);
4504 /* drop our paranoid refcount */
4505 dbus_connection_unref (connection);
4511 * Sets the timeout functions for the connection. These functions are
4512 * responsible for making the application's main loop aware of timeouts.
4513 * When using Qt, typically the DBusAddTimeoutFunction would create a
4514 * QTimer. When using GLib, the DBusAddTimeoutFunction would call
4517 * The DBusTimeoutToggledFunction notifies the application that the
4518 * timeout has been enabled or disabled. Call
4519 * dbus_timeout_get_enabled() to check this. A disabled timeout should
4520 * have no effect, and enabled timeout should be added to the main
4521 * loop. This feature is used instead of simply adding/removing the
4522 * timeout because enabling/disabling can be done without memory
4523 * allocation. With Qt, QTimer::start() and QTimer::stop() can be used
4524 * to enable and disable. The toggled function may be NULL if a main
4525 * loop re-queries dbus_timeout_get_enabled() every time anyway.
4526 * Whenever a timeout is toggled, its interval may change.
4528 * The DBusTimeout can be queried for the timer interval using
4529 * dbus_timeout_get_interval(). dbus_timeout_handle() should be called
4530 * repeatedly, each time the interval elapses, starting after it has
4531 * elapsed once. The timeout stops firing when it is removed with the
4532 * given remove_function. The timer interval may change whenever the
4533 * timeout is added, removed, or toggled.
4535 * @param connection the connection.
4536 * @param add_function function to add a timeout.
4537 * @param remove_function function to remove a timeout.
4538 * @param toggled_function function to notify of enable/disable
4539 * @param data data to pass to add_function and remove_function.
4540 * @param free_data_function function to be called to free the data.
4541 * @returns #FALSE on failure (no memory)
4544 dbus_connection_set_timeout_functions (DBusConnection *connection,
4545 DBusAddTimeoutFunction add_function,
4546 DBusRemoveTimeoutFunction remove_function,
4547 DBusTimeoutToggledFunction toggled_function,
4549 DBusFreeFunction free_data_function)
4552 DBusTimeoutList *timeouts;
4554 _dbus_return_val_if_fail (connection != NULL, FALSE);
4556 CONNECTION_LOCK (connection);
4558 #ifndef DBUS_DISABLE_CHECKS
4559 if (connection->timeouts == NULL)
4561 _dbus_warn_check_failed ("Re-entrant call to %s is not allowed\n",
4562 _DBUS_FUNCTION_NAME);
4567 /* ref connection for slightly better reentrancy */
4568 _dbus_connection_ref_unlocked (connection);
4570 timeouts = connection->timeouts;
4571 connection->timeouts = NULL;
4572 CONNECTION_UNLOCK (connection);
4574 retval = _dbus_timeout_list_set_functions (timeouts,
4575 add_function, remove_function,
4577 data, free_data_function);
4578 CONNECTION_LOCK (connection);
4579 connection->timeouts = timeouts;
4581 CONNECTION_UNLOCK (connection);
4582 /* drop our paranoid refcount */
4583 dbus_connection_unref (connection);
4589 * Sets the mainloop wakeup function for the connection. This function
4590 * is responsible for waking up the main loop (if its sleeping in
4591 * another thread) when some some change has happened to the
4592 * connection that the mainloop needs to reconsider (e.g. a message
4593 * has been queued for writing). When using Qt, this typically
4594 * results in a call to QEventLoop::wakeUp(). When using GLib, it
4595 * would call g_main_context_wakeup().
4597 * @param connection the connection.
4598 * @param wakeup_main_function function to wake up the mainloop
4599 * @param data data to pass wakeup_main_function
4600 * @param free_data_function function to be called to free the data.
4603 dbus_connection_set_wakeup_main_function (DBusConnection *connection,
4604 DBusWakeupMainFunction wakeup_main_function,
4606 DBusFreeFunction free_data_function)
4609 DBusFreeFunction old_free_data;
4611 _dbus_return_if_fail (connection != NULL);
4613 CONNECTION_LOCK (connection);
4614 old_data = connection->wakeup_main_data;
4615 old_free_data = connection->free_wakeup_main_data;
4617 connection->wakeup_main_function = wakeup_main_function;
4618 connection->wakeup_main_data = data;
4619 connection->free_wakeup_main_data = free_data_function;
4621 CONNECTION_UNLOCK (connection);
4623 /* Callback outside the lock */
4625 (*old_free_data) (old_data);
4629 * Set a function to be invoked when the dispatch status changes.
4630 * If the dispatch status is #DBUS_DISPATCH_DATA_REMAINS, then
4631 * dbus_connection_dispatch() needs to be called to process incoming
4632 * messages. However, dbus_connection_dispatch() MUST NOT BE CALLED
4633 * from inside the DBusDispatchStatusFunction. Indeed, almost
4634 * any reentrancy in this function is a bad idea. Instead,
4635 * the DBusDispatchStatusFunction should simply save an indication
4636 * that messages should be dispatched later, when the main loop
4639 * If you don't set a dispatch status function, you have to be sure to
4640 * dispatch on every iteration of your main loop, especially if
4641 * dbus_watch_handle() or dbus_timeout_handle() were called.
4643 * @param connection the connection
4644 * @param function function to call on dispatch status changes
4645 * @param data data for function
4646 * @param free_data_function free the function data
4649 dbus_connection_set_dispatch_status_function (DBusConnection *connection,
4650 DBusDispatchStatusFunction function,
4652 DBusFreeFunction free_data_function)
4655 DBusFreeFunction old_free_data;
4657 _dbus_return_if_fail (connection != NULL);
4659 CONNECTION_LOCK (connection);
4660 old_data = connection->dispatch_status_data;
4661 old_free_data = connection->free_dispatch_status_data;
4663 connection->dispatch_status_function = function;
4664 connection->dispatch_status_data = data;
4665 connection->free_dispatch_status_data = free_data_function;
4667 CONNECTION_UNLOCK (connection);
4669 /* Callback outside the lock */
4671 (*old_free_data) (old_data);
4675 * Get the UNIX file descriptor of the connection, if any. This can
4676 * be used for SELinux access control checks with getpeercon() for
4677 * example. DO NOT read or write to the file descriptor, or try to
4678 * select() on it; use DBusWatch for main loop integration. Not all
4679 * connections will have a file descriptor. So for adding descriptors
4680 * to the main loop, use dbus_watch_get_fd() and so forth.
4682 * If the connection is socket-based, you can also use
4683 * dbus_connection_get_socket(), which will work on Windows too.
4684 * This function always fails on Windows.
4686 * Right now the returned descriptor is always a socket, but
4687 * that is not guaranteed.
4689 * @param connection the connection
4690 * @param fd return location for the file descriptor.
4691 * @returns #TRUE if fd is successfully obtained.
4694 dbus_connection_get_unix_fd (DBusConnection *connection,
4697 _dbus_return_val_if_fail (connection != NULL, FALSE);
4698 _dbus_return_val_if_fail (connection->transport != NULL, FALSE);
4701 /* FIXME do this on a lower level */
4705 return dbus_connection_get_socket(connection, fd);
4709 * Gets the underlying Windows or UNIX socket file descriptor
4710 * of the connection, if any. DO NOT read or write to the file descriptor, or try to
4711 * select() on it; use DBusWatch for main loop integration. Not all
4712 * connections will have a socket. So for adding descriptors
4713 * to the main loop, use dbus_watch_get_fd() and so forth.
4715 * If the connection is not socket-based, this function will return FALSE,
4716 * even if the connection does have a file descriptor of some kind.
4717 * i.e. this function always returns specifically a socket file descriptor.
4719 * @param connection the connection
4720 * @param fd return location for the file descriptor.
4721 * @returns #TRUE if fd is successfully obtained.
4724 dbus_connection_get_socket(DBusConnection *connection,
4729 _dbus_return_val_if_fail (connection != NULL, FALSE);
4730 _dbus_return_val_if_fail (connection->transport != NULL, FALSE);
4732 CONNECTION_LOCK (connection);
4734 retval = _dbus_transport_get_socket_fd (connection->transport,
4737 CONNECTION_UNLOCK (connection);
4744 * Gets the UNIX user ID of the connection if any.
4745 * Returns #TRUE if the uid is filled in.
4746 * Always returns #FALSE on non-UNIX platforms.
4747 * Always returns #FALSE prior to authenticating the
4750 * @param connection the connection
4751 * @param uid return location for the user ID
4752 * @returns #TRUE if uid is filled in with a valid user ID
4755 dbus_connection_get_unix_user (DBusConnection *connection,
4760 _dbus_return_val_if_fail (connection != NULL, FALSE);
4761 _dbus_return_val_if_fail (uid != NULL, FALSE);
4764 /* FIXME this should be done at a lower level, but it's kind of hard,
4765 * just want to be sure we don't ship with this API returning
4766 * some weird internal fake uid for 1.0
4771 CONNECTION_LOCK (connection);
4773 if (!_dbus_transport_get_is_authenticated (connection->transport))
4776 result = _dbus_transport_get_unix_user (connection->transport,
4778 CONNECTION_UNLOCK (connection);
4784 * Gets the process ID of the connection if any.
4785 * Returns #TRUE if the uid is filled in.
4786 * Always returns #FALSE prior to authenticating the
4789 * @param connection the connection
4790 * @param pid return location for the process ID
4791 * @returns #TRUE if uid is filled in with a valid process ID
4794 dbus_connection_get_unix_process_id (DBusConnection *connection,
4799 _dbus_return_val_if_fail (connection != NULL, FALSE);
4800 _dbus_return_val_if_fail (pid != NULL, FALSE);
4803 /* FIXME this should be done at a lower level, but it's kind of hard,
4804 * just want to be sure we don't ship with this API returning
4805 * some weird internal fake uid for 1.0
4810 CONNECTION_LOCK (connection);
4812 if (!_dbus_transport_get_is_authenticated (connection->transport))
4815 result = _dbus_transport_get_unix_process_id (connection->transport,
4817 CONNECTION_UNLOCK (connection);
4823 * Sets a predicate function used to determine whether a given user ID
4824 * is allowed to connect. When an incoming connection has
4825 * authenticated with a particular user ID, this function is called;
4826 * if it returns #TRUE, the connection is allowed to proceed,
4827 * otherwise the connection is disconnected.
4829 * If the function is set to #NULL (as it is by default), then
4830 * only the same UID as the server process will be allowed to
4833 * On Windows, the function will be set and its free_data_function will
4834 * be invoked when the connection is freed or a new function is set.
4835 * However, the function will never be called, because there are
4836 * no UNIX user ids to pass to it.
4838 * @todo add a Windows API analogous to dbus_connection_set_unix_user_function()
4840 * @param connection the connection
4841 * @param function the predicate
4842 * @param data data to pass to the predicate
4843 * @param free_data_function function to free the data
4846 dbus_connection_set_unix_user_function (DBusConnection *connection,
4847 DBusAllowUnixUserFunction function,
4849 DBusFreeFunction free_data_function)
4851 void *old_data = NULL;
4852 DBusFreeFunction old_free_function = NULL;
4854 _dbus_return_if_fail (connection != NULL);
4856 CONNECTION_LOCK (connection);
4857 _dbus_transport_set_unix_user_function (connection->transport,
4858 function, data, free_data_function,
4859 &old_data, &old_free_function);
4860 CONNECTION_UNLOCK (connection);
4862 if (old_free_function != NULL)
4863 (* old_free_function) (old_data);
4868 * Normally #DBusConnection automatically handles all messages to the
4869 * org.freedesktop.DBus.Peer interface. However, the message bus wants
4870 * to be able to route methods on that interface through the bus and
4871 * to other applications. If routing peer messages is enabled, then
4872 * messages with the org.freedesktop.DBus.Peer interface that also
4873 * have a bus destination name set will not be automatically
4874 * handled by the #DBusConnection and instead will be dispatched
4875 * normally to the application.
4878 * If a normal application sets this flag, it can break things badly.
4879 * So don't set this unless you are the message bus.
4881 * @param connection the connection
4882 * @param value #TRUE to pass through org.freedesktop.DBus.Peer messages with a bus name set
4885 dbus_connection_set_route_peer_messages (DBusConnection *connection,
4888 _dbus_return_if_fail (connection != NULL);
4890 CONNECTION_LOCK (connection);
4891 connection->route_peer_messages = TRUE;
4892 CONNECTION_UNLOCK (connection);
4896 * Adds a message filter. Filters are handlers that are run on all
4897 * incoming messages, prior to the objects registered with
4898 * dbus_connection_register_object_path(). Filters are run in the
4899 * order that they were added. The same handler can be added as a
4900 * filter more than once, in which case it will be run more than once.
4901 * Filters added during a filter callback won't be run on the message
4904 * @todo we don't run filters on messages while blocking without
4905 * entering the main loop, since filters are run as part of
4906 * dbus_connection_dispatch(). This is probably a feature, as filters
4907 * could create arbitrary reentrancy. But kind of sucks if you're
4908 * trying to filter METHOD_RETURN for some reason.
4910 * @param connection the connection
4911 * @param function function to handle messages
4912 * @param user_data user data to pass to the function
4913 * @param free_data_function function to use for freeing user data
4914 * @returns #TRUE on success, #FALSE if not enough memory.
4917 dbus_connection_add_filter (DBusConnection *connection,
4918 DBusHandleMessageFunction function,
4920 DBusFreeFunction free_data_function)
4922 DBusMessageFilter *filter;
4924 _dbus_return_val_if_fail (connection != NULL, FALSE);
4925 _dbus_return_val_if_fail (function != NULL, FALSE);
4927 filter = dbus_new0 (DBusMessageFilter, 1);
4931 filter->refcount.value = 1;
4933 CONNECTION_LOCK (connection);
4935 if (!_dbus_list_append (&connection->filter_list,
4938 _dbus_message_filter_unref (filter);
4939 CONNECTION_UNLOCK (connection);
4943 /* Fill in filter after all memory allocated,
4944 * so we don't run the free_user_data_function
4945 * if the add_filter() fails
4948 filter->function = function;
4949 filter->user_data = user_data;
4950 filter->free_user_data_function = free_data_function;
4952 CONNECTION_UNLOCK (connection);
4957 * Removes a previously-added message filter. It is a programming
4958 * error to call this function for a handler that has not been added
4959 * as a filter. If the given handler was added more than once, only
4960 * one instance of it will be removed (the most recently-added
4963 * @param connection the connection
4964 * @param function the handler to remove
4965 * @param user_data user data for the handler to remove
4969 dbus_connection_remove_filter (DBusConnection *connection,
4970 DBusHandleMessageFunction function,
4974 DBusMessageFilter *filter;
4976 _dbus_return_if_fail (connection != NULL);
4977 _dbus_return_if_fail (function != NULL);
4979 CONNECTION_LOCK (connection);
4983 link = _dbus_list_get_last_link (&connection->filter_list);
4984 while (link != NULL)
4986 filter = link->data;
4988 if (filter->function == function &&
4989 filter->user_data == user_data)
4991 _dbus_list_remove_link (&connection->filter_list, link);
4992 filter->function = NULL;
4997 link = _dbus_list_get_prev_link (&connection->filter_list, link);
5000 CONNECTION_UNLOCK (connection);
5002 #ifndef DBUS_DISABLE_CHECKS
5005 _dbus_warn_check_failed ("Attempt to remove filter function %p user data %p, but no such filter has been added\n",
5006 function, user_data);
5011 /* Call application code */
5012 if (filter->free_user_data_function)
5013 (* filter->free_user_data_function) (filter->user_data);
5015 filter->free_user_data_function = NULL;
5016 filter->user_data = NULL;
5018 _dbus_message_filter_unref (filter);
5022 * Registers a handler for a given path in the object hierarchy.
5023 * The given vtable handles messages sent to exactly the given path.
5026 * @param connection the connection
5027 * @param path a '/' delimited string of path elements
5028 * @param vtable the virtual table
5029 * @param user_data data to pass to functions in the vtable
5030 * @returns #FALSE if not enough memory
5033 dbus_connection_register_object_path (DBusConnection *connection,
5035 const DBusObjectPathVTable *vtable,
5038 char **decomposed_path;
5041 _dbus_return_val_if_fail (connection != NULL, FALSE);
5042 _dbus_return_val_if_fail (path != NULL, FALSE);
5043 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5044 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5046 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5049 CONNECTION_LOCK (connection);
5051 retval = _dbus_object_tree_register (connection->objects,
5053 (const char **) decomposed_path, vtable,
5056 CONNECTION_UNLOCK (connection);
5058 dbus_free_string_array (decomposed_path);
5064 * Registers a fallback handler for a given subsection of the object
5065 * hierarchy. The given vtable handles messages at or below the given
5066 * path. You can use this to establish a default message handling
5067 * policy for a whole "subdirectory."
5069 * @param connection the connection
5070 * @param path a '/' delimited string of path elements
5071 * @param vtable the virtual table
5072 * @param user_data data to pass to functions in the vtable
5073 * @returns #FALSE if not enough memory
5076 dbus_connection_register_fallback (DBusConnection *connection,
5078 const DBusObjectPathVTable *vtable,
5081 char **decomposed_path;
5084 _dbus_return_val_if_fail (connection != NULL, FALSE);
5085 _dbus_return_val_if_fail (path != NULL, FALSE);
5086 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5087 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5089 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5092 CONNECTION_LOCK (connection);
5094 retval = _dbus_object_tree_register (connection->objects,
5096 (const char **) decomposed_path, vtable,
5099 CONNECTION_UNLOCK (connection);
5101 dbus_free_string_array (decomposed_path);
5107 * Unregisters the handler registered with exactly the given path.
5108 * It's a bug to call this function for a path that isn't registered.
5109 * Can unregister both fallback paths and object paths.
5111 * @param connection the connection
5112 * @param path a '/' delimited string of path elements
5113 * @returns #FALSE if not enough memory
5116 dbus_connection_unregister_object_path (DBusConnection *connection,
5119 char **decomposed_path;
5121 _dbus_return_val_if_fail (connection != NULL, FALSE);
5122 _dbus_return_val_if_fail (path != NULL, FALSE);
5123 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5125 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5128 CONNECTION_LOCK (connection);
5130 _dbus_object_tree_unregister_and_unlock (connection->objects, (const char **) decomposed_path);
5132 dbus_free_string_array (decomposed_path);
5138 * Gets the user data passed to dbus_connection_register_object_path()
5139 * or dbus_connection_register_fallback(). If nothing was registered
5140 * at this path, the data is filled in with #NULL.
5142 * @param connection the connection
5143 * @param path the path you registered with
5144 * @param data_p location to store the user data, or #NULL
5145 * @returns #FALSE if not enough memory
5148 dbus_connection_get_object_path_data (DBusConnection *connection,
5152 char **decomposed_path;
5154 _dbus_return_val_if_fail (connection != NULL, FALSE);
5155 _dbus_return_val_if_fail (path != NULL, FALSE);
5156 _dbus_return_val_if_fail (data_p != NULL, FALSE);
5160 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5163 CONNECTION_LOCK (connection);
5165 *data_p = _dbus_object_tree_get_user_data_unlocked (connection->objects, (const char**) decomposed_path);
5167 CONNECTION_UNLOCK (connection);
5169 dbus_free_string_array (decomposed_path);
5175 * Lists the registered fallback handlers and object path handlers at
5176 * the given parent_path. The returned array should be freed with
5177 * dbus_free_string_array().
5179 * @param connection the connection
5180 * @param parent_path the path to list the child handlers of
5181 * @param child_entries returns #NULL-terminated array of children
5182 * @returns #FALSE if no memory to allocate the child entries
5185 dbus_connection_list_registered (DBusConnection *connection,
5186 const char *parent_path,
5187 char ***child_entries)
5189 char **decomposed_path;
5191 _dbus_return_val_if_fail (connection != NULL, FALSE);
5192 _dbus_return_val_if_fail (parent_path != NULL, FALSE);
5193 _dbus_return_val_if_fail (parent_path[0] == '/', FALSE);
5194 _dbus_return_val_if_fail (child_entries != NULL, FALSE);
5196 if (!_dbus_decompose_path (parent_path, strlen (parent_path), &decomposed_path, NULL))
5199 CONNECTION_LOCK (connection);
5201 retval = _dbus_object_tree_list_registered_and_unlock (connection->objects,
5202 (const char **) decomposed_path,
5204 dbus_free_string_array (decomposed_path);
5209 static DBusDataSlotAllocator slot_allocator;
5210 _DBUS_DEFINE_GLOBAL_LOCK (connection_slots);
5213 * Allocates an integer ID to be used for storing application-specific
5214 * data on any DBusConnection. The allocated ID may then be used
5215 * with dbus_connection_set_data() and dbus_connection_get_data().
5216 * The passed-in slot must be initialized to -1, and is filled in
5217 * with the slot ID. If the passed-in slot is not -1, it's assumed
5218 * to be already allocated, and its refcount is incremented.
5220 * The allocated slot is global, i.e. all DBusConnection objects will
5221 * have a slot with the given integer ID reserved.
5223 * @param slot_p address of a global variable storing the slot
5224 * @returns #FALSE on failure (no memory)
5227 dbus_connection_allocate_data_slot (dbus_int32_t *slot_p)
5229 return _dbus_data_slot_allocator_alloc (&slot_allocator,
5230 &_DBUS_LOCK_NAME (connection_slots),
5235 * Deallocates a global ID for connection data slots.
5236 * dbus_connection_get_data() and dbus_connection_set_data() may no
5237 * longer be used with this slot. Existing data stored on existing
5238 * DBusConnection objects will be freed when the connection is
5239 * finalized, but may not be retrieved (and may only be replaced if
5240 * someone else reallocates the slot). When the refcount on the
5241 * passed-in slot reaches 0, it is set to -1.
5243 * @param slot_p address storing the slot to deallocate
5246 dbus_connection_free_data_slot (dbus_int32_t *slot_p)
5248 _dbus_return_if_fail (*slot_p >= 0);
5250 _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
5254 * Stores a pointer on a DBusConnection, along
5255 * with an optional function to be used for freeing
5256 * the data when the data is set again, or when
5257 * the connection is finalized. The slot number
5258 * must have been allocated with dbus_connection_allocate_data_slot().
5260 * @param connection the connection
5261 * @param slot the slot number
5262 * @param data the data to store
5263 * @param free_data_func finalizer function for the data
5264 * @returns #TRUE if there was enough memory to store the data
5267 dbus_connection_set_data (DBusConnection *connection,
5270 DBusFreeFunction free_data_func)
5272 DBusFreeFunction old_free_func;
5276 _dbus_return_val_if_fail (connection != NULL, FALSE);
5277 _dbus_return_val_if_fail (slot >= 0, FALSE);
5279 CONNECTION_LOCK (connection);
5281 retval = _dbus_data_slot_list_set (&slot_allocator,
5282 &connection->slot_list,
5283 slot, data, free_data_func,
5284 &old_free_func, &old_data);
5286 CONNECTION_UNLOCK (connection);
5290 /* Do the actual free outside the connection lock */
5292 (* old_free_func) (old_data);
5299 * Retrieves data previously set with dbus_connection_set_data().
5300 * The slot must still be allocated (must not have been freed).
5302 * @param connection the connection
5303 * @param slot the slot to get data from
5304 * @returns the data, or #NULL if not found
5307 dbus_connection_get_data (DBusConnection *connection,
5312 _dbus_return_val_if_fail (connection != NULL, NULL);
5314 CONNECTION_LOCK (connection);
5316 res = _dbus_data_slot_list_get (&slot_allocator,
5317 &connection->slot_list,
5320 CONNECTION_UNLOCK (connection);
5326 * This function sets a global flag for whether dbus_connection_new()
5327 * will set SIGPIPE behavior to SIG_IGN.
5329 * @param will_modify_sigpipe #TRUE to allow sigpipe to be set to SIG_IGN
5332 dbus_connection_set_change_sigpipe (dbus_bool_t will_modify_sigpipe)
5334 _dbus_modify_sigpipe = will_modify_sigpipe != FALSE;
5338 * Specifies the maximum size message this connection is allowed to
5339 * receive. Larger messages will result in disconnecting the
5342 * @param connection a #DBusConnection
5343 * @param size maximum message size the connection can receive, in bytes
5346 dbus_connection_set_max_message_size (DBusConnection *connection,
5349 _dbus_return_if_fail (connection != NULL);
5351 CONNECTION_LOCK (connection);
5352 _dbus_transport_set_max_message_size (connection->transport,
5354 CONNECTION_UNLOCK (connection);
5358 * Gets the value set by dbus_connection_set_max_message_size().
5360 * @param connection the connection
5361 * @returns the max size of a single message
5364 dbus_connection_get_max_message_size (DBusConnection *connection)
5368 _dbus_return_val_if_fail (connection != NULL, 0);
5370 CONNECTION_LOCK (connection);
5371 res = _dbus_transport_get_max_message_size (connection->transport);
5372 CONNECTION_UNLOCK (connection);
5377 * Sets the maximum total number of bytes that can be used for all messages
5378 * received on this connection. Messages count toward the maximum until
5379 * they are finalized. When the maximum is reached, the connection will
5380 * not read more data until some messages are finalized.
5382 * The semantics of the maximum are: if outstanding messages are
5383 * already above the maximum, additional messages will not be read.
5384 * The semantics are not: if the next message would cause us to exceed
5385 * the maximum, we don't read it. The reason is that we don't know the
5386 * size of a message until after we read it.
5388 * Thus, the max live messages size can actually be exceeded
5389 * by up to the maximum size of a single message.
5391 * Also, if we read say 1024 bytes off the wire in a single read(),
5392 * and that contains a half-dozen small messages, we may exceed the
5393 * size max by that amount. But this should be inconsequential.
5395 * This does imply that we can't call read() with a buffer larger
5396 * than we're willing to exceed this limit by.
5398 * @param connection the connection
5399 * @param size the maximum size in bytes of all outstanding messages
5402 dbus_connection_set_max_received_size (DBusConnection *connection,
5405 _dbus_return_if_fail (connection != NULL);
5407 CONNECTION_LOCK (connection);
5408 _dbus_transport_set_max_received_size (connection->transport,
5410 CONNECTION_UNLOCK (connection);
5414 * Gets the value set by dbus_connection_set_max_received_size().
5416 * @param connection the connection
5417 * @returns the max size of all live messages
5420 dbus_connection_get_max_received_size (DBusConnection *connection)
5424 _dbus_return_val_if_fail (connection != NULL, 0);
5426 CONNECTION_LOCK (connection);
5427 res = _dbus_transport_get_max_received_size (connection->transport);
5428 CONNECTION_UNLOCK (connection);
5433 * Gets the approximate size in bytes of all messages in the outgoing
5434 * message queue. The size is approximate in that you shouldn't use
5435 * it to decide how many bytes to read off the network or anything
5436 * of that nature, as optimizations may choose to tell small white lies
5437 * to avoid performance overhead.
5439 * @param connection the connection
5440 * @returns the number of bytes that have been queued up but not sent
5443 dbus_connection_get_outgoing_size (DBusConnection *connection)
5447 _dbus_return_val_if_fail (connection != NULL, 0);
5449 CONNECTION_LOCK (connection);
5450 res = _dbus_counter_get_value (connection->outgoing_counter);
5451 CONNECTION_UNLOCK (connection);
5456 * Obtains the machine UUID of the machine this process is running on.
5458 * The returned string must be freed with dbus_free().
5460 * This UUID is guaranteed to remain the same until the next reboot
5461 * (unless the sysadmin foolishly changes it and screws themselves).
5462 * It will usually remain the same across reboots also, but hardware
5463 * configuration changes or rebuilding the machine could break that.
5465 * The idea is that two processes with the same machine ID should be
5466 * able to use shared memory, UNIX domain sockets, process IDs, and other
5467 * features of the OS that require both processes to be running
5468 * on the same OS kernel instance.
5470 * The machine ID can also be used to create unique per-machine
5471 * instances. For example, you could use it in bus names or
5472 * X selection names.
5474 * The machine ID is preferred over the machine hostname, because
5475 * the hostname is frequently set to "localhost.localdomain" and
5476 * may also change at runtime.
5478 * You can get the machine ID of a remote application by invoking the
5479 * method GetMachineId from interface org.freedesktop.DBus.Peer.
5481 * If the remote application has the same machine ID as the one
5482 * returned by this function, then the remote application is on the
5483 * same machine as your application.
5485 * @returns a 32-byte-long hex-encoded UUID string, or #NULL if insufficient memory
5488 dbus_get_local_machine_id (void)
5494 _dbus_string_init (&uuid);
5495 if (!_dbus_get_local_machine_uuid_encoded (&uuid) ||
5496 !_dbus_string_steal_data (&uuid, &s))
5498 _dbus_string_free (&uuid);
5503 _dbus_string_free (&uuid);