1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-connection.c DBusConnection object
4 * Copyright (C) 2002, 2003 Red Hat Inc.
6 * Licensed under the Academic Free License version 1.2
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 #include "dbus-connection.h"
26 #include "dbus-list.h"
27 #include "dbus-timeout.h"
28 #include "dbus-transport.h"
29 #include "dbus-watch.h"
30 #include "dbus-connection-internal.h"
31 #include "dbus-list.h"
32 #include "dbus-hash.h"
33 #include "dbus-message-internal.h"
34 #include "dbus-message-handler.h"
35 #include "dbus-threads.h"
36 #include "dbus-protocol.h"
37 #include "dbus-dataslot.h"
40 #define CONNECTION_LOCK(connection) do { \
41 _dbus_verbose (" LOCK: %s\n", _DBUS_FUNCTION_NAME); \
42 dbus_mutex_lock ((connection)->mutex); \
44 #define CONNECTION_UNLOCK(connection) do { \
45 _dbus_verbose (" UNLOCK: %s\n", _DBUS_FUNCTION_NAME); \
46 dbus_mutex_unlock ((connection)->mutex); \
49 #define CONNECTION_LOCK(connection) dbus_mutex_lock ((connection)->mutex)
50 #define CONNECTION_UNLOCK(connection) dbus_mutex_unlock ((connection)->mutex)
54 * @defgroup DBusConnection DBusConnection
56 * @brief Connection to another application
58 * A DBusConnection represents a connection to another
59 * application. Messages can be sent and received via this connection.
60 * The other application may be a message bus; for convenience, the
61 * function dbus_bus_get() is provided to automatically open a
62 * connection to the well-known message buses.
64 * In brief a DBusConnection is a message queue associated with some
65 * message transport mechanism such as a socket. The connection
66 * maintains a queue of incoming messages and a queue of outgoing
69 * Incoming messages are normally processed by calling
70 * dbus_connection_dispatch(). dbus_connection_dispatch() runs any
71 * handlers registered for the topmost message in the message queue,
72 * then discards the message, then returns.
74 * dbus_connection_get_dispatch_status() indicates whether
75 * messages are currently in the queue that need dispatching.
76 * dbus_connection_set_dispatch_status_function() allows
77 * you to set a function to be used to monitor the dispatch status.
79 * If you're using GLib or Qt add-on libraries for D-BUS, there are
80 * special convenience functions in those libraries that hide
81 * all the details of dispatch and watch/timeout monitoring.
82 * For example, dbus_connection_setup_with_g_main().
84 * If you aren't using these add-on libraries, you have to manually
85 * call dbus_connection_set_dispatch_status_function(),
86 * dbus_connection_set_watch_functions(),
87 * dbus_connection_set_timeout_functions() providing appropriate
88 * functions to integrate the connection with your application's main
91 * When you use dbus_connection_send() or one of its variants to send
92 * a message, the message is added to the outgoing queue. It's
93 * actually written to the network later; either in
94 * dbus_watch_handle() invoked by your main loop, or in
95 * dbus_connection_flush() which blocks until it can write out the
96 * entire outgoing queue. The GLib/Qt add-on libraries again
97 * handle the details here for you by setting up watch functions.
99 * When a connection is disconnected, you are guaranteed to get a
100 * message with the name #DBUS_MESSAGE_LOCAL_DISCONNECT.
102 * You may not drop the last reference to a #DBusConnection
103 * until that connection has been disconnected.
105 * You may dispatch the unprocessed incoming message queue even if the
106 * connection is disconnected. However, #DBUS_MESSAGE_LOCAL_DISCONNECT
107 * will always be the last message in the queue (obviously no messages
108 * are received after disconnection).
110 * #DBusConnection has thread locks and drops them when invoking user
111 * callbacks, so in general is transparently threadsafe. However,
112 * #DBusMessage does NOT have thread locks; you must not send the same
113 * message to multiple #DBusConnection that will be used from
118 * @defgroup DBusConnectionInternals DBusConnection implementation details
119 * @ingroup DBusInternals
120 * @brief Implementation details of DBusConnection
125 /** default timeout value when waiting for a message reply */
126 #define DEFAULT_TIMEOUT_VALUE (15 * 1000)
128 static dbus_bool_t _dbus_modify_sigpipe = TRUE;
131 * Implementation details of DBusConnection. All fields are private.
133 struct DBusConnection
135 DBusAtomic refcount; /**< Reference count. */
137 DBusMutex *mutex; /**< Lock on the entire DBusConnection */
139 dbus_bool_t dispatch_acquired; /**< Protects dispatch() */
140 DBusCondVar *dispatch_cond; /**< Protects dispatch() */
142 dbus_bool_t io_path_acquired; /**< Protects transport io path */
143 DBusCondVar *io_path_cond; /**< Protects transport io path */
145 DBusList *outgoing_messages; /**< Queue of messages we need to send, send the end of the list first. */
146 DBusList *incoming_messages; /**< Queue of messages we have received, end of the list received most recently. */
148 DBusMessage *message_borrowed; /**< True if the first incoming message has been borrowed */
149 DBusCondVar *message_returned_cond; /**< Used with dbus_connection_borrow_message() */
151 int n_outgoing; /**< Length of outgoing queue. */
152 int n_incoming; /**< Length of incoming queue. */
154 DBusCounter *outgoing_counter; /**< Counts size of outgoing messages. */
156 DBusTransport *transport; /**< Object that sends/receives messages over network. */
157 DBusWatchList *watches; /**< Stores active watches. */
158 DBusTimeoutList *timeouts; /**< Stores active timeouts. */
160 DBusHashTable *handler_table; /**< Table of registered DBusMessageHandler */
161 DBusList *filter_list; /**< List of filters. */
163 DBusDataSlotList slot_list; /**< Data stored by allocated integer ID */
165 DBusHashTable *pending_replies; /**< Hash of message serials and their message handlers. */
167 dbus_uint32_t client_serial; /**< Client serial. Increments each time a message is sent */
168 DBusList *disconnect_message_link; /**< Preallocated list node for queueing the disconnection message */
170 DBusWakeupMainFunction wakeup_main_function; /**< Function to wake up the mainloop */
171 void *wakeup_main_data; /**< Application data for wakeup_main_function */
172 DBusFreeFunction free_wakeup_main_data; /**< free wakeup_main_data */
174 DBusDispatchStatusFunction dispatch_status_function; /**< Function on dispatch status changes */
175 void *dispatch_status_data; /**< Application data for dispatch_status_function */
176 DBusFreeFunction free_dispatch_status_data; /**< free dispatch_status_data */
178 DBusDispatchStatus last_dispatch_status; /**< The last dispatch status we reported to the application. */
180 DBusList *link_cache; /**< A cache of linked list links to prevent contention
181 * for the global linked list mempool lock
187 DBusConnection *connection;
188 DBusMessageHandler *handler;
189 DBusTimeout *timeout;
192 DBusList *timeout_link; /* Preallocated timeout response */
194 dbus_bool_t timeout_added;
195 dbus_bool_t connection_added;
198 static void reply_handler_data_free (ReplyHandlerData *data);
200 static void _dbus_connection_remove_timeout_locked (DBusConnection *connection,
201 DBusTimeout *timeout);
202 static DBusDispatchStatus _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection);
203 static void _dbus_connection_update_dispatch_status_and_unlock (DBusConnection *connection,
204 DBusDispatchStatus new_status);
209 * Acquires the connection lock.
211 * @param connection the connection.
214 _dbus_connection_lock (DBusConnection *connection)
216 CONNECTION_LOCK (connection);
220 * Releases the connection lock.
222 * @param connection the connection.
225 _dbus_connection_unlock (DBusConnection *connection)
227 CONNECTION_UNLOCK (connection);
231 * Wakes up the main loop if it is sleeping
232 * Needed if we're e.g. queueing outgoing messages
233 * on a thread while the mainloop sleeps.
235 * @param connection the connection.
238 _dbus_connection_wakeup_mainloop (DBusConnection *connection)
240 if (connection->wakeup_main_function)
241 (*connection->wakeup_main_function) (connection->wakeup_main_data);
244 #ifdef DBUS_BUILD_TESTS
245 /* For now this function isn't used */
247 * Adds a message to the incoming message queue, returning #FALSE
248 * if there's insufficient memory to queue the message.
249 * Does not take over refcount of the message.
251 * @param connection the connection.
252 * @param message the message to queue.
253 * @returns #TRUE on success.
256 _dbus_connection_queue_received_message (DBusConnection *connection,
257 DBusMessage *message)
261 link = _dbus_list_alloc_link (message);
265 dbus_message_ref (message);
266 _dbus_connection_queue_received_message_link (connection, link);
273 * Adds a message-containing list link to the incoming message queue,
274 * taking ownership of the link and the message's current refcount.
275 * Cannot fail due to lack of memory.
277 * @param connection the connection.
278 * @param link the message link to queue.
281 _dbus_connection_queue_received_message_link (DBusConnection *connection,
284 ReplyHandlerData *reply_handler_data;
285 dbus_int32_t reply_serial;
286 DBusMessage *message;
288 _dbus_assert (_dbus_transport_get_is_authenticated (connection->transport));
290 _dbus_list_append_link (&connection->incoming_messages,
292 message = link->data;
294 /* If this is a reply we're waiting on, remove timeout for it */
295 reply_serial = dbus_message_get_reply_serial (message);
296 if (reply_serial != -1)
298 reply_handler_data = _dbus_hash_table_lookup_int (connection->pending_replies,
300 if (reply_handler_data != NULL)
302 if (reply_handler_data->timeout_added)
303 _dbus_connection_remove_timeout_locked (connection,
304 reply_handler_data->timeout);
305 reply_handler_data->timeout_added = FALSE;
309 connection->n_incoming += 1;
311 _dbus_connection_wakeup_mainloop (connection);
313 _dbus_assert (dbus_message_get_name (message) != NULL);
314 _dbus_verbose ("Message %p (%s) added to incoming queue %p, %d incoming\n",
315 message, dbus_message_get_name (message),
317 connection->n_incoming);
321 * Adds a link + message to the incoming message queue.
322 * Can't fail. Takes ownership of both link and message.
324 * @param connection the connection.
325 * @param link the list node and message to queue.
327 * @todo This needs to wake up the mainloop if it is in
328 * a poll/select and this is a multithreaded app.
331 _dbus_connection_queue_synthesized_message_link (DBusConnection *connection,
334 _dbus_list_append_link (&connection->incoming_messages, link);
336 connection->n_incoming += 1;
338 _dbus_connection_wakeup_mainloop (connection);
340 _dbus_verbose ("Synthesized message %p added to incoming queue %p, %d incoming\n",
341 link->data, connection, connection->n_incoming);
346 * Checks whether there are messages in the outgoing message queue.
348 * @param connection the connection.
349 * @returns #TRUE if the outgoing queue is non-empty.
352 _dbus_connection_have_messages_to_send (DBusConnection *connection)
354 return connection->outgoing_messages != NULL;
358 * Gets the next outgoing message. The message remains in the
359 * queue, and the caller does not own a reference to it.
361 * @param connection the connection.
362 * @returns the message to be sent.
365 _dbus_connection_get_message_to_send (DBusConnection *connection)
367 return _dbus_list_get_last (&connection->outgoing_messages);
371 * Notifies the connection that a message has been sent, so the
372 * message can be removed from the outgoing queue.
373 * Called with the connection lock held.
375 * @param connection the connection.
376 * @param message the message that was sent.
379 _dbus_connection_message_sent (DBusConnection *connection,
380 DBusMessage *message)
384 _dbus_assert (_dbus_transport_get_is_authenticated (connection->transport));
386 link = _dbus_list_get_last_link (&connection->outgoing_messages);
387 _dbus_assert (link != NULL);
388 _dbus_assert (link->data == message);
390 /* Save this link in the link cache */
391 _dbus_list_unlink (&connection->outgoing_messages,
393 _dbus_list_prepend_link (&connection->link_cache, link);
395 connection->n_outgoing -= 1;
397 _dbus_verbose ("Message %p (%s) removed from outgoing queue %p, %d left to send\n",
398 message, dbus_message_get_name (message),
399 connection, connection->n_outgoing);
401 /* Save this link in the link cache also */
402 _dbus_message_remove_size_counter (message, connection->outgoing_counter,
404 _dbus_list_prepend_link (&connection->link_cache, link);
406 dbus_message_unref (message);
408 if (connection->n_outgoing == 0)
409 _dbus_transport_messages_pending (connection->transport,
410 connection->n_outgoing);
414 * Adds a watch using the connection's DBusAddWatchFunction if
415 * available. Otherwise records the watch to be added when said
416 * function is available. Also re-adds the watch if the
417 * DBusAddWatchFunction changes. May fail due to lack of memory.
419 * @param connection the connection.
420 * @param watch the watch to add.
421 * @returns #TRUE on success.
424 _dbus_connection_add_watch (DBusConnection *connection,
427 if (connection->watches) /* null during finalize */
428 return _dbus_watch_list_add_watch (connection->watches,
435 * Removes a watch using the connection's DBusRemoveWatchFunction
436 * if available. It's an error to call this function on a watch
437 * that was not previously added.
439 * @param connection the connection.
440 * @param watch the watch to remove.
443 _dbus_connection_remove_watch (DBusConnection *connection,
446 if (connection->watches) /* null during finalize */
447 _dbus_watch_list_remove_watch (connection->watches,
452 * Toggles a watch and notifies app via connection's
453 * DBusWatchToggledFunction if available. It's an error to call this
454 * function on a watch that was not previously added.
456 * @param connection the connection.
457 * @param watch the watch to toggle.
458 * @param enabled whether to enable or disable
461 _dbus_connection_toggle_watch (DBusConnection *connection,
465 if (connection->watches) /* null during finalize */
466 _dbus_watch_list_toggle_watch (connection->watches,
471 * Adds a timeout using the connection's DBusAddTimeoutFunction if
472 * available. Otherwise records the timeout to be added when said
473 * function is available. Also re-adds the timeout if the
474 * DBusAddTimeoutFunction changes. May fail due to lack of memory.
475 * The timeout will fire repeatedly until removed.
477 * @param connection the connection.
478 * @param timeout the timeout to add.
479 * @returns #TRUE on success.
482 _dbus_connection_add_timeout (DBusConnection *connection,
483 DBusTimeout *timeout)
485 if (connection->timeouts) /* null during finalize */
486 return _dbus_timeout_list_add_timeout (connection->timeouts,
493 * Removes a timeout using the connection's DBusRemoveTimeoutFunction
494 * if available. It's an error to call this function on a timeout
495 * that was not previously added.
497 * @param connection the connection.
498 * @param timeout the timeout to remove.
501 _dbus_connection_remove_timeout (DBusConnection *connection,
502 DBusTimeout *timeout)
504 if (connection->timeouts) /* null during finalize */
505 _dbus_timeout_list_remove_timeout (connection->timeouts,
510 _dbus_connection_remove_timeout_locked (DBusConnection *connection,
511 DBusTimeout *timeout)
513 CONNECTION_LOCK (connection);
514 _dbus_connection_remove_timeout (connection, timeout);
515 CONNECTION_UNLOCK (connection);
519 * Toggles a timeout and notifies app via connection's
520 * DBusTimeoutToggledFunction if available. It's an error to call this
521 * function on a timeout that was not previously added.
523 * @param connection the connection.
524 * @param timeout the timeout to toggle.
525 * @param enabled whether to enable or disable
528 _dbus_connection_toggle_timeout (DBusConnection *connection,
529 DBusTimeout *timeout,
532 if (connection->timeouts) /* null during finalize */
533 _dbus_timeout_list_toggle_timeout (connection->timeouts,
538 * Tells the connection that the transport has been disconnected.
539 * Results in posting a disconnect message on the incoming message
540 * queue. Only has an effect the first time it's called.
542 * @param connection the connection
545 _dbus_connection_notify_disconnected (DBusConnection *connection)
547 if (connection->disconnect_message_link)
549 /* We haven't sent the disconnect message already */
550 _dbus_connection_queue_synthesized_message_link (connection,
551 connection->disconnect_message_link);
552 connection->disconnect_message_link = NULL;
558 * Acquire the transporter I/O path. This must be done before
559 * doing any I/O in the transporter. May sleep and drop the
560 * connection mutex while waiting for the I/O path.
562 * @param connection the connection.
563 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
564 * @returns TRUE if the I/O path was acquired.
567 _dbus_connection_acquire_io_path (DBusConnection *connection,
568 int timeout_milliseconds)
570 dbus_bool_t res = TRUE;
572 if (connection->io_path_acquired)
574 if (timeout_milliseconds != -1)
575 res = dbus_condvar_wait_timeout (connection->io_path_cond,
577 timeout_milliseconds);
579 dbus_condvar_wait (connection->io_path_cond, connection->mutex);
584 _dbus_assert (!connection->io_path_acquired);
586 connection->io_path_acquired = TRUE;
593 * Release the I/O path when you're done with it. Only call
594 * after you've acquired the I/O. Wakes up at most one thread
595 * currently waiting to acquire the I/O path.
597 * @param connection the connection.
600 _dbus_connection_release_io_path (DBusConnection *connection)
602 _dbus_assert (connection->io_path_acquired);
604 connection->io_path_acquired = FALSE;
605 dbus_condvar_wake_one (connection->io_path_cond);
610 * Queues incoming messages and sends outgoing messages for this
611 * connection, optionally blocking in the process. Each call to
612 * _dbus_connection_do_iteration() will call select() or poll() one
613 * time and then read or write data if possible.
615 * The purpose of this function is to be able to flush outgoing
616 * messages or queue up incoming messages without returning
617 * control to the application and causing reentrancy weirdness.
619 * The flags parameter allows you to specify whether to
620 * read incoming messages, write outgoing messages, or both,
621 * and whether to block if no immediate action is possible.
623 * The timeout_milliseconds parameter does nothing unless the
624 * iteration is blocking.
626 * If there are no outgoing messages and DBUS_ITERATION_DO_READING
627 * wasn't specified, then it's impossible to block, even if
628 * you specify DBUS_ITERATION_BLOCK; in that case the function
629 * returns immediately.
631 * @param connection the connection.
632 * @param flags iteration flags.
633 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
636 _dbus_connection_do_iteration (DBusConnection *connection,
638 int timeout_milliseconds)
640 if (connection->n_outgoing == 0)
641 flags &= ~DBUS_ITERATION_DO_WRITING;
643 if (_dbus_connection_acquire_io_path (connection,
644 (flags & DBUS_ITERATION_BLOCK) ? timeout_milliseconds : 0))
646 _dbus_transport_do_iteration (connection->transport,
647 flags, timeout_milliseconds);
648 _dbus_connection_release_io_path (connection);
653 * Creates a new connection for the given transport. A transport
654 * represents a message stream that uses some concrete mechanism, such
655 * as UNIX domain sockets. May return #NULL if insufficient
656 * memory exists to create the connection.
658 * @param transport the transport.
659 * @returns the new connection, or #NULL on failure.
662 _dbus_connection_new_for_transport (DBusTransport *transport)
664 DBusConnection *connection;
665 DBusWatchList *watch_list;
666 DBusTimeoutList *timeout_list;
667 DBusHashTable *handler_table, *pending_replies;
669 DBusCondVar *message_returned_cond;
670 DBusCondVar *dispatch_cond;
671 DBusCondVar *io_path_cond;
672 DBusList *disconnect_link;
673 DBusMessage *disconnect_message;
674 DBusCounter *outgoing_counter;
678 handler_table = NULL;
679 pending_replies = NULL;
682 message_returned_cond = NULL;
683 dispatch_cond = NULL;
685 disconnect_link = NULL;
686 disconnect_message = NULL;
687 outgoing_counter = NULL;
689 watch_list = _dbus_watch_list_new ();
690 if (watch_list == NULL)
693 timeout_list = _dbus_timeout_list_new ();
694 if (timeout_list == NULL)
698 _dbus_hash_table_new (DBUS_HASH_STRING,
700 if (handler_table == NULL)
704 _dbus_hash_table_new (DBUS_HASH_INT,
705 NULL, (DBusFreeFunction)reply_handler_data_free);
706 if (pending_replies == NULL)
709 connection = dbus_new0 (DBusConnection, 1);
710 if (connection == NULL)
713 mutex = dbus_mutex_new ();
717 message_returned_cond = dbus_condvar_new ();
718 if (message_returned_cond == NULL)
721 dispatch_cond = dbus_condvar_new ();
722 if (dispatch_cond == NULL)
725 io_path_cond = dbus_condvar_new ();
726 if (io_path_cond == NULL)
729 disconnect_message = dbus_message_new (DBUS_MESSAGE_LOCAL_DISCONNECT, NULL);
730 if (disconnect_message == NULL)
733 disconnect_link = _dbus_list_alloc_link (disconnect_message);
734 if (disconnect_link == NULL)
737 outgoing_counter = _dbus_counter_new ();
738 if (outgoing_counter == NULL)
741 if (_dbus_modify_sigpipe)
742 _dbus_disable_sigpipe ();
744 connection->refcount.value = 1;
745 connection->mutex = mutex;
746 connection->dispatch_cond = dispatch_cond;
747 connection->io_path_cond = io_path_cond;
748 connection->message_returned_cond = message_returned_cond;
749 connection->transport = transport;
750 connection->watches = watch_list;
751 connection->timeouts = timeout_list;
752 connection->handler_table = handler_table;
753 connection->pending_replies = pending_replies;
754 connection->outgoing_counter = outgoing_counter;
755 connection->filter_list = NULL;
756 connection->last_dispatch_status = DBUS_DISPATCH_COMPLETE; /* so we're notified first time there's data */
758 _dbus_data_slot_list_init (&connection->slot_list);
760 connection->client_serial = 1;
762 connection->disconnect_message_link = disconnect_link;
764 if (!_dbus_transport_set_connection (transport, connection))
767 _dbus_transport_ref (transport);
772 if (disconnect_message != NULL)
773 dbus_message_unref (disconnect_message);
775 if (disconnect_link != NULL)
776 _dbus_list_free_link (disconnect_link);
778 if (io_path_cond != NULL)
779 dbus_condvar_free (io_path_cond);
781 if (dispatch_cond != NULL)
782 dbus_condvar_free (dispatch_cond);
784 if (message_returned_cond != NULL)
785 dbus_condvar_free (message_returned_cond);
788 dbus_mutex_free (mutex);
790 if (connection != NULL)
791 dbus_free (connection);
794 _dbus_hash_table_unref (handler_table);
797 _dbus_hash_table_unref (pending_replies);
800 _dbus_watch_list_free (watch_list);
803 _dbus_timeout_list_free (timeout_list);
805 if (outgoing_counter)
806 _dbus_counter_unref (outgoing_counter);
812 * Increments the reference count of a DBusConnection.
813 * Requires that the caller already holds the connection lock.
815 * @param connection the connection.
818 _dbus_connection_ref_unlocked (DBusConnection *connection)
820 #ifdef DBUS_HAVE_ATOMIC_INT
821 _dbus_atomic_inc (&connection->refcount);
823 _dbus_assert (connection->refcount.value > 0);
824 connection->refcount.value += 1;
829 _dbus_connection_get_next_client_serial (DBusConnection *connection)
833 serial = connection->client_serial++;
835 if (connection->client_serial < 0)
836 connection->client_serial = 1;
842 * Used to notify a connection when a DBusMessageHandler is
843 * destroyed, so the connection can drop any reference
844 * to the handler. This is a private function, but still
845 * takes the connection lock. Don't call it with the lock held.
847 * @todo needs to check in pending_replies too.
849 * @param connection the connection
850 * @param handler the handler
853 _dbus_connection_handler_destroyed_locked (DBusConnection *connection,
854 DBusMessageHandler *handler)
859 CONNECTION_LOCK (connection);
861 _dbus_hash_iter_init (connection->handler_table, &iter);
862 while (_dbus_hash_iter_next (&iter))
864 DBusMessageHandler *h = _dbus_hash_iter_get_value (&iter);
867 _dbus_hash_iter_remove_entry (&iter);
870 link = _dbus_list_get_first_link (&connection->filter_list);
873 DBusMessageHandler *h = link->data;
874 DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
877 _dbus_list_remove_link (&connection->filter_list,
882 CONNECTION_UNLOCK (connection);
886 * A callback for use with dbus_watch_new() to create a DBusWatch.
888 * @todo This is basically a hack - we could delete _dbus_transport_handle_watch()
889 * and the virtual handle_watch in DBusTransport if we got rid of it.
890 * The reason this is some work is threading, see the _dbus_connection_handle_watch()
893 * @param watch the watch.
894 * @param condition the current condition of the file descriptors being watched.
895 * @param data must be a pointer to a #DBusConnection
896 * @returns #FALSE if the IO condition may not have been fully handled due to lack of memory
899 _dbus_connection_handle_watch (DBusWatch *watch,
900 unsigned int condition,
903 DBusConnection *connection;
905 DBusDispatchStatus status;
909 CONNECTION_LOCK (connection);
910 _dbus_connection_acquire_io_path (connection, -1);
911 retval = _dbus_transport_handle_watch (connection->transport,
913 _dbus_connection_release_io_path (connection);
915 status = _dbus_connection_get_dispatch_status_unlocked (connection);
917 /* this calls out to user code */
918 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
926 * @addtogroup DBusConnection
932 * Opens a new connection to a remote address.
934 * @todo specify what the address parameter is. Right now
935 * it's just the name of a UNIX domain socket. It should be
936 * something more complex that encodes which transport to use.
938 * If the open fails, the function returns #NULL, and provides
939 * a reason for the failure in the result parameter. Pass
940 * #NULL for the result parameter if you aren't interested
941 * in the reason for failure.
943 * @param address the address.
944 * @param error address where an error can be returned.
945 * @returns new connection, or #NULL on failure.
948 dbus_connection_open (const char *address,
951 DBusConnection *connection;
952 DBusTransport *transport;
954 _dbus_return_val_if_fail (address != NULL, NULL);
955 _dbus_return_val_if_error_is_set (error, NULL);
957 transport = _dbus_transport_open (address, error);
958 if (transport == NULL)
960 _DBUS_ASSERT_ERROR_IS_SET (error);
964 connection = _dbus_connection_new_for_transport (transport);
966 _dbus_transport_unref (transport);
968 if (connection == NULL)
970 dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
978 * Increments the reference count of a DBusConnection.
980 * @param connection the connection.
983 dbus_connection_ref (DBusConnection *connection)
985 _dbus_return_if_fail (connection != NULL);
987 /* The connection lock is better than the global
988 * lock in the atomic increment fallback
991 #ifdef DBUS_HAVE_ATOMIC_INT
992 _dbus_atomic_inc (&connection->refcount);
994 CONNECTION_LOCK (connection);
995 _dbus_assert (connection->refcount.value > 0);
997 connection->refcount.value += 1;
998 CONNECTION_UNLOCK (connection);
1003 free_outgoing_message (void *element,
1006 DBusMessage *message = element;
1007 DBusConnection *connection = data;
1009 _dbus_message_remove_size_counter (message,
1010 connection->outgoing_counter,
1012 dbus_message_unref (message);
1015 /* This is run without the mutex held, but after the last reference
1016 * to the connection has been dropped we should have no thread-related
1020 _dbus_connection_last_unref (DBusConnection *connection)
1025 _dbus_verbose ("Finalizing connection %p\n", connection);
1027 _dbus_assert (connection->refcount.value == 0);
1029 /* You have to disconnect the connection before unref:ing it. Otherwise
1030 * you won't get the disconnected message.
1032 _dbus_assert (!_dbus_transport_get_is_connected (connection->transport));
1034 /* ---- We're going to call various application callbacks here, hope it doesn't break anything... */
1035 dbus_connection_set_dispatch_status_function (connection, NULL, NULL, NULL);
1036 dbus_connection_set_wakeup_main_function (connection, NULL, NULL, NULL);
1037 dbus_connection_set_unix_user_function (connection, NULL, NULL, NULL);
1039 _dbus_watch_list_free (connection->watches);
1040 connection->watches = NULL;
1042 _dbus_timeout_list_free (connection->timeouts);
1043 connection->timeouts = NULL;
1045 _dbus_data_slot_list_free (&connection->slot_list);
1046 /* ---- Done with stuff that invokes application callbacks */
1048 _dbus_hash_iter_init (connection->handler_table, &iter);
1049 while (_dbus_hash_iter_next (&iter))
1051 DBusMessageHandler *h = _dbus_hash_iter_get_value (&iter);
1053 _dbus_message_handler_remove_connection (h, connection);
1056 link = _dbus_list_get_first_link (&connection->filter_list);
1057 while (link != NULL)
1059 DBusMessageHandler *h = link->data;
1060 DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
1062 _dbus_message_handler_remove_connection (h, connection);
1067 _dbus_hash_table_unref (connection->handler_table);
1068 connection->handler_table = NULL;
1070 _dbus_hash_table_unref (connection->pending_replies);
1071 connection->pending_replies = NULL;
1073 _dbus_list_clear (&connection->filter_list);
1075 _dbus_list_foreach (&connection->outgoing_messages,
1076 free_outgoing_message,
1078 _dbus_list_clear (&connection->outgoing_messages);
1080 _dbus_list_foreach (&connection->incoming_messages,
1081 (DBusForeachFunction) dbus_message_unref,
1083 _dbus_list_clear (&connection->incoming_messages);
1085 _dbus_counter_unref (connection->outgoing_counter);
1087 _dbus_transport_unref (connection->transport);
1089 if (connection->disconnect_message_link)
1091 DBusMessage *message = connection->disconnect_message_link->data;
1092 dbus_message_unref (message);
1093 _dbus_list_free_link (connection->disconnect_message_link);
1096 _dbus_list_clear (&connection->link_cache);
1098 dbus_condvar_free (connection->dispatch_cond);
1099 dbus_condvar_free (connection->io_path_cond);
1100 dbus_condvar_free (connection->message_returned_cond);
1102 dbus_mutex_free (connection->mutex);
1104 dbus_free (connection);
1108 * Decrements the reference count of a DBusConnection, and finalizes
1109 * it if the count reaches zero. It is a bug to drop the last reference
1110 * to a connection that has not been disconnected.
1112 * @todo in practice it can be quite tricky to never unref a connection
1113 * that's still connected; maybe there's some way we could avoid
1116 * @param connection the connection.
1119 dbus_connection_unref (DBusConnection *connection)
1121 dbus_bool_t last_unref;
1123 _dbus_return_if_fail (connection != NULL);
1125 /* The connection lock is better than the global
1126 * lock in the atomic increment fallback
1129 #ifdef DBUS_HAVE_ATOMIC_INT
1130 last_unref = (_dbus_atomic_dec (&connection->refcount) == 1);
1132 CONNECTION_LOCK (connection);
1134 _dbus_assert (connection->refcount.value > 0);
1136 connection->refcount.value -= 1;
1137 last_unref = (connection->refcount.value == 0);
1140 printf ("unref() connection %p count = %d\n", connection, connection->refcount.value);
1143 CONNECTION_UNLOCK (connection);
1147 _dbus_connection_last_unref (connection);
1151 * Closes the connection, so no further data can be sent or received.
1152 * Any further attempts to send data will result in errors. This
1153 * function does not affect the connection's reference count. It's
1154 * safe to disconnect a connection more than once; all calls after the
1155 * first do nothing. It's impossible to "reconnect" a connection, a
1156 * new connection must be created.
1158 * @param connection the connection.
1161 dbus_connection_disconnect (DBusConnection *connection)
1163 _dbus_return_if_fail (connection != NULL);
1165 CONNECTION_LOCK (connection);
1166 _dbus_transport_disconnect (connection->transport);
1167 CONNECTION_UNLOCK (connection);
1171 _dbus_connection_get_is_connected_unlocked (DBusConnection *connection)
1173 return _dbus_transport_get_is_connected (connection->transport);
1177 * Gets whether the connection is currently connected. All
1178 * connections are connected when they are opened. A connection may
1179 * become disconnected when the remote application closes its end, or
1180 * exits; a connection may also be disconnected with
1181 * dbus_connection_disconnect().
1183 * @param connection the connection.
1184 * @returns #TRUE if the connection is still alive.
1187 dbus_connection_get_is_connected (DBusConnection *connection)
1191 _dbus_return_val_if_fail (connection != NULL, FALSE);
1193 CONNECTION_LOCK (connection);
1194 res = _dbus_connection_get_is_connected_unlocked (connection);
1195 CONNECTION_UNLOCK (connection);
1201 * Gets whether the connection was authenticated. (Note that
1202 * if the connection was authenticated then disconnected,
1203 * this function still returns #TRUE)
1205 * @param connection the connection
1206 * @returns #TRUE if the connection was ever authenticated
1209 dbus_connection_get_is_authenticated (DBusConnection *connection)
1213 _dbus_return_val_if_fail (connection != NULL, FALSE);
1215 CONNECTION_LOCK (connection);
1216 res = _dbus_transport_get_is_authenticated (connection->transport);
1217 CONNECTION_UNLOCK (connection);
1222 struct DBusPreallocatedSend
1224 DBusConnection *connection;
1225 DBusList *queue_link;
1226 DBusList *counter_link;
1229 static DBusPreallocatedSend*
1230 _dbus_connection_preallocate_send_unlocked (DBusConnection *connection)
1232 DBusPreallocatedSend *preallocated;
1234 _dbus_return_val_if_fail (connection != NULL, NULL);
1236 preallocated = dbus_new (DBusPreallocatedSend, 1);
1237 if (preallocated == NULL)
1240 if (connection->link_cache != NULL)
1242 preallocated->queue_link =
1243 _dbus_list_pop_first_link (&connection->link_cache);
1244 preallocated->queue_link->data = NULL;
1248 preallocated->queue_link = _dbus_list_alloc_link (NULL);
1249 if (preallocated->queue_link == NULL)
1253 if (connection->link_cache != NULL)
1255 preallocated->counter_link =
1256 _dbus_list_pop_first_link (&connection->link_cache);
1257 preallocated->counter_link->data = connection->outgoing_counter;
1261 preallocated->counter_link = _dbus_list_alloc_link (connection->outgoing_counter);
1262 if (preallocated->counter_link == NULL)
1266 _dbus_counter_ref (preallocated->counter_link->data);
1268 preallocated->connection = connection;
1270 return preallocated;
1273 _dbus_list_free_link (preallocated->queue_link);
1275 dbus_free (preallocated);
1281 * Preallocates resources needed to send a message, allowing the message
1282 * to be sent without the possibility of memory allocation failure.
1283 * Allows apps to create a future guarantee that they can send
1284 * a message regardless of memory shortages.
1286 * @param connection the connection we're preallocating for.
1287 * @returns the preallocated resources, or #NULL
1289 DBusPreallocatedSend*
1290 dbus_connection_preallocate_send (DBusConnection *connection)
1292 DBusPreallocatedSend *preallocated;
1294 _dbus_return_val_if_fail (connection != NULL, NULL);
1296 CONNECTION_LOCK (connection);
1299 _dbus_connection_preallocate_send_unlocked (connection);
1301 CONNECTION_UNLOCK (connection);
1303 return preallocated;
1307 * Frees preallocated message-sending resources from
1308 * dbus_connection_preallocate_send(). Should only
1309 * be called if the preallocated resources are not used
1310 * to send a message.
1312 * @param connection the connection
1313 * @param preallocated the resources
1316 dbus_connection_free_preallocated_send (DBusConnection *connection,
1317 DBusPreallocatedSend *preallocated)
1319 _dbus_return_if_fail (connection != NULL);
1320 _dbus_return_if_fail (preallocated != NULL);
1321 _dbus_return_if_fail (connection == preallocated->connection);
1323 _dbus_list_free_link (preallocated->queue_link);
1324 _dbus_counter_unref (preallocated->counter_link->data);
1325 _dbus_list_free_link (preallocated->counter_link);
1326 dbus_free (preallocated);
1330 _dbus_connection_send_preallocated_unlocked (DBusConnection *connection,
1331 DBusPreallocatedSend *preallocated,
1332 DBusMessage *message,
1333 dbus_uint32_t *client_serial)
1335 dbus_uint32_t serial;
1337 preallocated->queue_link->data = message;
1338 _dbus_list_prepend_link (&connection->outgoing_messages,
1339 preallocated->queue_link);
1341 _dbus_message_add_size_counter_link (message,
1342 preallocated->counter_link);
1344 dbus_free (preallocated);
1345 preallocated = NULL;
1347 dbus_message_ref (message);
1349 connection->n_outgoing += 1;
1351 _dbus_verbose ("Message %p (%s) added to outgoing queue %p, %d pending to send\n",
1353 dbus_message_get_name (message),
1355 connection->n_outgoing);
1357 if (dbus_message_get_serial (message) == 0)
1359 serial = _dbus_connection_get_next_client_serial (connection);
1360 _dbus_message_set_serial (message, serial);
1362 *client_serial = serial;
1367 *client_serial = dbus_message_get_serial (message);
1370 _dbus_message_lock (message);
1372 if (connection->n_outgoing == 1)
1373 _dbus_transport_messages_pending (connection->transport,
1374 connection->n_outgoing);
1376 _dbus_connection_wakeup_mainloop (connection);
1380 * Sends a message using preallocated resources. This function cannot fail.
1381 * It works identically to dbus_connection_send() in other respects.
1382 * Preallocated resources comes from dbus_connection_preallocate_send().
1383 * This function "consumes" the preallocated resources, they need not
1384 * be freed separately.
1386 * @param connection the connection
1387 * @param preallocated the preallocated resources
1388 * @param message the message to send
1389 * @param client_serial return location for client serial assigned to the message
1392 dbus_connection_send_preallocated (DBusConnection *connection,
1393 DBusPreallocatedSend *preallocated,
1394 DBusMessage *message,
1395 dbus_uint32_t *client_serial)
1397 _dbus_return_if_fail (connection != NULL);
1398 _dbus_return_if_fail (preallocated != NULL);
1399 _dbus_return_if_fail (message != NULL);
1400 _dbus_return_if_fail (preallocated->connection == connection);
1401 _dbus_return_if_fail (dbus_message_get_name (message) != NULL);
1403 CONNECTION_LOCK (connection);
1404 _dbus_connection_send_preallocated_unlocked (connection,
1406 message, client_serial);
1407 CONNECTION_UNLOCK (connection);
1411 * Adds a message to the outgoing message queue. Does not block to
1412 * write the message to the network; that happens asynchronously. To
1413 * force the message to be written, call dbus_connection_flush().
1414 * Because this only queues the message, the only reason it can
1415 * fail is lack of memory. Even if the connection is disconnected,
1416 * no error will be returned.
1418 * If the function fails due to lack of memory, it returns #FALSE.
1419 * The function will never fail for other reasons; even if the
1420 * connection is disconnected, you can queue an outgoing message,
1421 * though obviously it won't be sent.
1423 * @param connection the connection.
1424 * @param message the message to write.
1425 * @param client_serial return location for client serial.
1426 * @returns #TRUE on success.
1429 dbus_connection_send (DBusConnection *connection,
1430 DBusMessage *message,
1431 dbus_uint32_t *client_serial)
1433 DBusPreallocatedSend *preallocated;
1435 _dbus_return_val_if_fail (connection != NULL, FALSE);
1436 _dbus_return_val_if_fail (message != NULL, FALSE);
1438 CONNECTION_LOCK (connection);
1440 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
1441 if (preallocated == NULL)
1443 CONNECTION_UNLOCK (connection);
1448 _dbus_connection_send_preallocated_unlocked (connection,
1452 CONNECTION_UNLOCK (connection);
1458 reply_handler_timeout (void *data)
1460 DBusConnection *connection;
1461 ReplyHandlerData *reply_handler_data = data;
1462 DBusDispatchStatus status;
1464 connection = reply_handler_data->connection;
1466 CONNECTION_LOCK (connection);
1467 if (reply_handler_data->timeout_link)
1469 _dbus_connection_queue_synthesized_message_link (connection,
1470 reply_handler_data->timeout_link);
1471 reply_handler_data->timeout_link = NULL;
1474 _dbus_connection_remove_timeout (connection,
1475 reply_handler_data->timeout);
1476 reply_handler_data->timeout_added = FALSE;
1478 status = _dbus_connection_get_dispatch_status_unlocked (connection);
1480 /* Unlocks, and calls out to user code */
1481 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1487 reply_handler_data_free (ReplyHandlerData *data)
1492 if (data->timeout_added)
1493 _dbus_connection_remove_timeout_locked (data->connection,
1496 if (data->connection_added)
1497 _dbus_message_handler_remove_connection (data->handler,
1500 if (data->timeout_link)
1502 dbus_message_unref ((DBusMessage *)data->timeout_link->data);
1503 _dbus_list_free_link (data->timeout_link);
1506 dbus_message_handler_unref (data->handler);
1512 * Queues a message to send, as with dbus_connection_send_message(),
1513 * but also sets up a DBusMessageHandler to receive a reply to the
1514 * message. If no reply is received in the given timeout_milliseconds,
1515 * expires the pending reply and sends the DBusMessageHandler a
1516 * synthetic error reply (generated in-process, not by the remote
1517 * application) indicating that a timeout occurred.
1519 * Reply handlers see their replies after message filters see them,
1520 * but before message handlers added with
1521 * dbus_connection_register_handler() see them, regardless of the
1522 * reply message's name. Reply handlers are only handed a single
1523 * message as a reply, after one reply has been seen the handler is
1524 * removed. If a filter filters out the reply before the handler sees
1525 * it, the reply is immediately timed out and a timeout error reply is
1526 * generated. If a filter removes the timeout error reply then the
1527 * reply handler will never be called. Filters should not do this.
1529 * If #NULL is passed for the reply_handler, the timeout reply will
1530 * still be generated and placed into the message queue, but no
1531 * specific message handler will receive the reply.
1533 * If -1 is passed for the timeout, a sane default timeout is used. -1
1534 * is typically the best value for the timeout for this reason, unless
1535 * you want a very short or very long timeout. There is no way to
1536 * avoid a timeout entirely, other than passing INT_MAX for the
1537 * timeout to postpone it indefinitely.
1539 * @param connection the connection
1540 * @param message the message to send
1541 * @param reply_handler message handler expecting the reply, or #NULL
1542 * @param timeout_milliseconds timeout in milliseconds or -1 for default
1543 * @returns #TRUE if the message is successfully queued, #FALSE if no memory.
1547 dbus_connection_send_with_reply (DBusConnection *connection,
1548 DBusMessage *message,
1549 DBusMessageHandler *reply_handler,
1550 int timeout_milliseconds)
1552 DBusTimeout *timeout;
1553 ReplyHandlerData *data;
1555 DBusList *reply_link;
1556 dbus_int32_t serial = -1;
1558 _dbus_return_val_if_fail (connection != NULL, FALSE);
1559 _dbus_return_val_if_fail (message != NULL, FALSE);
1560 _dbus_return_val_if_fail (reply_handler != NULL, FALSE);
1561 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
1563 if (timeout_milliseconds == -1)
1564 timeout_milliseconds = DEFAULT_TIMEOUT_VALUE;
1566 data = dbus_new0 (ReplyHandlerData, 1);
1571 timeout = _dbus_timeout_new (timeout_milliseconds, reply_handler_timeout,
1576 reply_handler_data_free (data);
1580 CONNECTION_LOCK (connection);
1583 if (!_dbus_connection_add_timeout (connection, timeout))
1585 reply_handler_data_free (data);
1586 _dbus_timeout_unref (timeout);
1587 CONNECTION_UNLOCK (connection);
1591 /* The connection now owns the reference to the timeout. */
1592 _dbus_timeout_unref (timeout);
1594 data->timeout_added = TRUE;
1595 data->timeout = timeout;
1596 data->connection = connection;
1598 if (!_dbus_message_handler_add_connection (reply_handler, connection))
1600 CONNECTION_UNLOCK (connection);
1601 reply_handler_data_free (data);
1604 data->connection_added = TRUE;
1606 /* Assign a serial to the message */
1607 if (dbus_message_get_serial (message) == 0)
1609 serial = _dbus_connection_get_next_client_serial (connection);
1610 _dbus_message_set_serial (message, serial);
1613 data->handler = reply_handler;
1614 data->serial = serial;
1616 dbus_message_handler_ref (reply_handler);
1618 reply = dbus_message_new_error_reply (message, DBUS_ERROR_NO_REPLY,
1619 "No reply within specified time");
1622 CONNECTION_UNLOCK (connection);
1623 reply_handler_data_free (data);
1627 reply_link = _dbus_list_alloc_link (reply);
1630 CONNECTION_UNLOCK (connection);
1631 dbus_message_unref (reply);
1632 reply_handler_data_free (data);
1636 data->timeout_link = reply_link;
1638 /* Insert the serial in the pending replies hash. */
1639 if (!_dbus_hash_table_insert_int (connection->pending_replies, serial, data))
1641 CONNECTION_UNLOCK (connection);
1642 reply_handler_data_free (data);
1646 CONNECTION_UNLOCK (connection);
1648 if (!dbus_connection_send (connection, message, NULL))
1650 /* This will free the handler data too */
1651 _dbus_hash_table_remove_int (connection->pending_replies, serial);
1660 check_for_reply_unlocked (DBusConnection *connection,
1661 dbus_uint32_t client_serial)
1665 link = _dbus_list_get_first_link (&connection->incoming_messages);
1667 while (link != NULL)
1669 DBusMessage *reply = link->data;
1671 if (dbus_message_get_reply_serial (reply) == client_serial)
1673 _dbus_list_remove_link (&connection->incoming_messages, link);
1674 connection->n_incoming -= 1;
1675 dbus_message_ref (reply);
1678 link = _dbus_list_get_next_link (&connection->incoming_messages, link);
1685 * Sends a message and blocks a certain time period while waiting for a reply.
1686 * This function does not dispatch any message handlers until the main loop
1687 * has been reached. This function is used to do non-reentrant "method calls."
1688 * If a reply is received, it is returned, and removed from the incoming
1689 * message queue. If it is not received, #NULL is returned and the
1690 * error is set to #DBUS_ERROR_NO_REPLY. If something else goes
1691 * wrong, result is set to whatever is appropriate, such as
1692 * #DBUS_ERROR_NO_MEMORY or #DBUS_ERROR_DISCONNECTED.
1694 * @todo could use performance improvements (it keeps scanning
1695 * the whole message queue for example) and has thread issues,
1696 * see comments in source
1698 * @param connection the connection
1699 * @param message the message to send
1700 * @param timeout_milliseconds timeout in milliseconds or -1 for default
1701 * @param error return location for error message
1702 * @returns the message that is the reply or #NULL with an error code if the
1706 dbus_connection_send_with_reply_and_block (DBusConnection *connection,
1707 DBusMessage *message,
1708 int timeout_milliseconds,
1711 dbus_uint32_t client_serial;
1712 long start_tv_sec, start_tv_usec;
1713 long end_tv_sec, end_tv_usec;
1714 long tv_sec, tv_usec;
1715 DBusDispatchStatus status;
1717 _dbus_return_val_if_fail (connection != NULL, NULL);
1718 _dbus_return_val_if_fail (message != NULL, NULL);
1719 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
1720 _dbus_return_val_if_error_is_set (error, NULL);
1722 if (timeout_milliseconds == -1)
1723 timeout_milliseconds = DEFAULT_TIMEOUT_VALUE;
1725 /* it would probably seem logical to pass in _DBUS_INT_MAX
1726 * for infinite timeout, but then math below would get
1727 * all overflow-prone, so smack that down.
1729 if (timeout_milliseconds > _DBUS_ONE_HOUR_IN_MILLISECONDS * 6)
1730 timeout_milliseconds = _DBUS_ONE_HOUR_IN_MILLISECONDS * 6;
1732 if (!dbus_connection_send (connection, message, &client_serial))
1734 _DBUS_SET_OOM (error);
1740 /* Flush message queue */
1741 dbus_connection_flush (connection);
1743 CONNECTION_LOCK (connection);
1745 _dbus_get_current_time (&start_tv_sec, &start_tv_usec);
1746 end_tv_sec = start_tv_sec + timeout_milliseconds / 1000;
1747 end_tv_usec = start_tv_usec + (timeout_milliseconds % 1000) * 1000;
1748 end_tv_sec += end_tv_usec / _DBUS_USEC_PER_SECOND;
1749 end_tv_usec = end_tv_usec % _DBUS_USEC_PER_SECOND;
1751 _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",
1752 timeout_milliseconds,
1754 start_tv_sec, start_tv_usec,
1755 end_tv_sec, end_tv_usec);
1757 /* Now we wait... */
1758 /* THREAD TODO: This is busted. What if a dispatch() or pop_message
1759 * gets the message before we do?
1761 /* always block at least once as we know we don't have the reply yet */
1762 _dbus_connection_do_iteration (connection,
1763 DBUS_ITERATION_DO_READING |
1764 DBUS_ITERATION_BLOCK,
1765 timeout_milliseconds);
1769 /* queue messages and get status */
1770 status = _dbus_connection_get_dispatch_status_unlocked (connection);
1772 if (status == DBUS_DISPATCH_DATA_REMAINS)
1776 reply = check_for_reply_unlocked (connection, client_serial);
1779 status = _dbus_connection_get_dispatch_status_unlocked (connection);
1781 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): got reply %s\n",
1782 dbus_message_get_name (reply));
1784 /* Unlocks, and calls out to user code */
1785 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1791 _dbus_get_current_time (&tv_sec, &tv_usec);
1793 if (tv_sec < start_tv_sec)
1794 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): clock set backward\n");
1795 else if (connection->disconnect_message_link == NULL)
1796 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): disconnected\n");
1797 else if (tv_sec < end_tv_sec ||
1798 (tv_sec == end_tv_sec && tv_usec < end_tv_usec))
1800 timeout_milliseconds = (end_tv_sec - tv_sec) * 1000 +
1801 (end_tv_usec - tv_usec) / 1000;
1802 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): %d milliseconds remain\n", timeout_milliseconds);
1803 _dbus_assert (timeout_milliseconds >= 0);
1805 if (status == DBUS_DISPATCH_NEED_MEMORY)
1807 /* Try sleeping a bit, as we aren't sure we need to block for reading,
1808 * we may already have a reply in the buffer and just can't process
1811 _dbus_verbose ("dbus_connection_send_with_reply_and_block() waiting for more memory\n");
1813 if (timeout_milliseconds < 100)
1814 ; /* just busy loop */
1815 else if (timeout_milliseconds <= 1000)
1816 _dbus_sleep_milliseconds (timeout_milliseconds / 3);
1818 _dbus_sleep_milliseconds (1000);
1822 /* block again, we don't have the reply buffered yet. */
1823 _dbus_connection_do_iteration (connection,
1824 DBUS_ITERATION_DO_READING |
1825 DBUS_ITERATION_BLOCK,
1826 timeout_milliseconds);
1829 goto recheck_status;
1832 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): Waited %ld milliseconds and got no reply\n",
1833 (tv_sec - start_tv_sec) * 1000 + (tv_usec - start_tv_usec) / 1000);
1835 if (dbus_connection_get_is_connected (connection))
1836 dbus_set_error (error, DBUS_ERROR_NO_REPLY, "Message did not receive a reply");
1838 dbus_set_error (error, DBUS_ERROR_DISCONNECTED, "Disconnected prior to receiving a reply");
1840 /* unlocks and calls out to user code */
1841 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1847 * Blocks until the outgoing message queue is empty.
1849 * @param connection the connection.
1852 dbus_connection_flush (DBusConnection *connection)
1854 /* We have to specify DBUS_ITERATION_DO_READING here because
1855 * otherwise we could have two apps deadlock if they are both doing
1856 * a flush(), and the kernel buffers fill up. This could change the
1859 DBusDispatchStatus status;
1861 _dbus_return_if_fail (connection != NULL);
1863 CONNECTION_LOCK (connection);
1864 while (connection->n_outgoing > 0 &&
1865 _dbus_connection_get_is_connected_unlocked (connection))
1866 _dbus_connection_do_iteration (connection,
1867 DBUS_ITERATION_DO_READING |
1868 DBUS_ITERATION_DO_WRITING |
1869 DBUS_ITERATION_BLOCK,
1872 status = _dbus_connection_get_dispatch_status_unlocked (connection);
1874 /* Unlocks and calls out to user code */
1875 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1878 /* Call with mutex held. Will drop it while waiting and re-acquire
1882 _dbus_connection_wait_for_borrowed (DBusConnection *connection)
1884 _dbus_assert (connection->message_borrowed != NULL);
1886 while (connection->message_borrowed != NULL)
1887 dbus_condvar_wait (connection->message_returned_cond, connection->mutex);
1891 * Returns the first-received message from the incoming message queue,
1892 * leaving it in the queue. If the queue is empty, returns #NULL.
1894 * The caller does not own a reference to the returned message, and
1895 * must either return it using dbus_connection_return_message() or
1896 * keep it after calling dbus_connection_steal_borrowed_message(). No
1897 * one can get at the message while its borrowed, so return it as
1898 * quickly as possible and don't keep a reference to it after
1899 * returning it. If you need to keep the message, make a copy of it.
1901 * @param connection the connection.
1902 * @returns next message in the incoming queue.
1905 dbus_connection_borrow_message (DBusConnection *connection)
1907 DBusMessage *message;
1908 DBusDispatchStatus status;
1910 _dbus_return_val_if_fail (connection != NULL, NULL);
1912 /* this is called for the side effect that it queues
1913 * up any messages from the transport
1915 status = dbus_connection_get_dispatch_status (connection);
1916 if (status != DBUS_DISPATCH_DATA_REMAINS)
1919 CONNECTION_LOCK (connection);
1921 if (connection->message_borrowed != NULL)
1922 _dbus_connection_wait_for_borrowed (connection);
1924 message = _dbus_list_get_first (&connection->incoming_messages);
1927 connection->message_borrowed = message;
1929 CONNECTION_UNLOCK (connection);
1934 * Used to return a message after peeking at it using
1935 * dbus_connection_borrow_message().
1937 * @param connection the connection
1938 * @param message the message from dbus_connection_borrow_message()
1941 dbus_connection_return_message (DBusConnection *connection,
1942 DBusMessage *message)
1944 _dbus_return_if_fail (connection != NULL);
1945 _dbus_return_if_fail (message != NULL);
1947 CONNECTION_LOCK (connection);
1949 _dbus_assert (message == connection->message_borrowed);
1951 connection->message_borrowed = NULL;
1952 dbus_condvar_wake_all (connection->message_returned_cond);
1954 CONNECTION_UNLOCK (connection);
1958 * Used to keep a message after peeking at it using
1959 * dbus_connection_borrow_message(). Before using this function, see
1960 * the caveats/warnings in the documentation for
1961 * dbus_connection_pop_message().
1963 * @param connection the connection
1964 * @param message the message from dbus_connection_borrow_message()
1967 dbus_connection_steal_borrowed_message (DBusConnection *connection,
1968 DBusMessage *message)
1970 DBusMessage *pop_message;
1972 _dbus_return_if_fail (connection != NULL);
1973 _dbus_return_if_fail (message != NULL);
1975 CONNECTION_LOCK (connection);
1977 _dbus_assert (message == connection->message_borrowed);
1979 pop_message = _dbus_list_pop_first (&connection->incoming_messages);
1980 _dbus_assert (message == pop_message);
1982 connection->n_incoming -= 1;
1984 _dbus_verbose ("Incoming message %p stolen from queue, %d incoming\n",
1985 message, connection->n_incoming);
1987 connection->message_borrowed = NULL;
1988 dbus_condvar_wake_all (connection->message_returned_cond);
1990 CONNECTION_UNLOCK (connection);
1993 /* See dbus_connection_pop_message, but requires the caller to own
1994 * the lock before calling. May drop the lock while running.
1997 _dbus_connection_pop_message_link_unlocked (DBusConnection *connection)
1999 if (connection->message_borrowed != NULL)
2000 _dbus_connection_wait_for_borrowed (connection);
2002 if (connection->n_incoming > 0)
2006 link = _dbus_list_pop_first_link (&connection->incoming_messages);
2007 connection->n_incoming -= 1;
2009 _dbus_verbose ("Message %p (%s) removed from incoming queue %p, %d incoming\n",
2010 link->data, dbus_message_get_name (link->data),
2011 connection, connection->n_incoming);
2019 /* See dbus_connection_pop_message, but requires the caller to own
2020 * the lock before calling. May drop the lock while running.
2023 _dbus_connection_pop_message_unlocked (DBusConnection *connection)
2027 link = _dbus_connection_pop_message_link_unlocked (connection);
2031 DBusMessage *message;
2033 message = link->data;
2035 _dbus_list_free_link (link);
2045 * Returns the first-received message from the incoming message queue,
2046 * removing it from the queue. The caller owns a reference to the
2047 * returned message. If the queue is empty, returns #NULL.
2049 * This function bypasses any message handlers that are registered,
2050 * and so using it is usually wrong. Instead, let the main loop invoke
2051 * dbus_connection_dispatch(). Popping messages manually is only
2052 * useful in very simple programs that don't share a #DBusConnection
2053 * with any libraries or other modules.
2055 * @param connection the connection.
2056 * @returns next message in the incoming queue.
2059 dbus_connection_pop_message (DBusConnection *connection)
2061 DBusMessage *message;
2062 DBusDispatchStatus status;
2064 /* this is called for the side effect that it queues
2065 * up any messages from the transport
2067 status = dbus_connection_get_dispatch_status (connection);
2068 if (status != DBUS_DISPATCH_DATA_REMAINS)
2071 CONNECTION_LOCK (connection);
2073 message = _dbus_connection_pop_message_unlocked (connection);
2075 _dbus_verbose ("Returning popped message %p\n", message);
2077 CONNECTION_UNLOCK (connection);
2083 * Acquire the dispatcher. This must be done before dispatching
2084 * messages in order to guarantee the right order of
2085 * message delivery. May sleep and drop the connection mutex
2086 * while waiting for the dispatcher.
2088 * @param connection the connection.
2091 _dbus_connection_acquire_dispatch (DBusConnection *connection)
2093 if (connection->dispatch_acquired)
2094 dbus_condvar_wait (connection->dispatch_cond, connection->mutex);
2095 _dbus_assert (!connection->dispatch_acquired);
2097 connection->dispatch_acquired = TRUE;
2101 * Release the dispatcher when you're done with it. Only call
2102 * after you've acquired the dispatcher. Wakes up at most one
2103 * thread currently waiting to acquire the dispatcher.
2105 * @param connection the connection.
2108 _dbus_connection_release_dispatch (DBusConnection *connection)
2110 _dbus_assert (connection->dispatch_acquired);
2112 connection->dispatch_acquired = FALSE;
2113 dbus_condvar_wake_one (connection->dispatch_cond);
2117 _dbus_connection_failed_pop (DBusConnection *connection,
2118 DBusList *message_link)
2120 _dbus_list_prepend_link (&connection->incoming_messages,
2122 connection->n_incoming += 1;
2125 static DBusDispatchStatus
2126 _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection)
2128 if (connection->n_incoming > 0)
2129 return DBUS_DISPATCH_DATA_REMAINS;
2130 else if (!_dbus_transport_queue_messages (connection->transport))
2131 return DBUS_DISPATCH_NEED_MEMORY;
2134 DBusDispatchStatus status;
2136 status = _dbus_transport_get_dispatch_status (connection->transport);
2138 if (status != DBUS_DISPATCH_COMPLETE)
2140 else if (connection->n_incoming > 0)
2141 return DBUS_DISPATCH_DATA_REMAINS;
2143 return DBUS_DISPATCH_COMPLETE;
2148 _dbus_connection_update_dispatch_status_and_unlock (DBusConnection *connection,
2149 DBusDispatchStatus new_status)
2151 dbus_bool_t changed;
2152 DBusDispatchStatusFunction function;
2155 /* We have the lock */
2157 _dbus_connection_ref_unlocked (connection);
2159 changed = new_status != connection->last_dispatch_status;
2161 connection->last_dispatch_status = new_status;
2163 function = connection->dispatch_status_function;
2164 data = connection->dispatch_status_data;
2166 /* We drop the lock */
2167 CONNECTION_UNLOCK (connection);
2169 if (changed && function)
2171 _dbus_verbose ("Notifying of change to dispatch status of %p now %d (%s)\n",
2172 connection, new_status,
2173 new_status == DBUS_DISPATCH_COMPLETE ? "complete" :
2174 new_status == DBUS_DISPATCH_DATA_REMAINS ? "data remains" :
2175 new_status == DBUS_DISPATCH_NEED_MEMORY ? "need memory" :
2177 (* function) (connection, new_status, data);
2180 dbus_connection_unref (connection);
2184 * Gets the current state (what we would currently return
2185 * from dbus_connection_dispatch()) but doesn't actually
2186 * dispatch any messages.
2188 * @param connection the connection.
2189 * @returns current dispatch status
2192 dbus_connection_get_dispatch_status (DBusConnection *connection)
2194 DBusDispatchStatus status;
2196 _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
2198 CONNECTION_LOCK (connection);
2200 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2202 CONNECTION_UNLOCK (connection);
2208 * Processes data buffered while handling watches, queueing zero or
2209 * more incoming messages. Then pops the first-received message from
2210 * the current incoming message queue, runs any handlers for it, and
2211 * unrefs the message. Returns a status indicating whether messages/data
2212 * remain, more memory is needed, or all data has been processed.
2214 * Even if the dispatch status is #DBUS_DISPATCH_DATA_REMAINS,
2215 * does not necessarily dispatch a message, as the data may
2216 * be part of authentication or the like.
2218 * @param connection the connection
2219 * @returns dispatch status
2222 dbus_connection_dispatch (DBusConnection *connection)
2224 DBusMessageHandler *handler;
2225 DBusMessage *message;
2226 DBusList *link, *filter_list_copy, *message_link;
2227 DBusHandlerResult result;
2228 ReplyHandlerData *reply_handler_data;
2230 dbus_int32_t reply_serial;
2231 DBusDispatchStatus status;
2233 _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
2235 CONNECTION_LOCK (connection);
2236 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2237 if (status != DBUS_DISPATCH_DATA_REMAINS)
2239 /* unlocks and calls out to user code */
2240 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2244 /* We need to ref the connection since the callback could potentially
2245 * drop the last ref to it
2247 _dbus_connection_ref_unlocked (connection);
2249 _dbus_connection_acquire_dispatch (connection);
2251 /* This call may drop the lock during the execution (if waiting for
2252 * borrowed messages to be returned) but the order of message
2253 * dispatch if several threads call dispatch() is still
2254 * protected by the lock, since only one will get the lock, and that
2255 * one will finish the message dispatching
2257 message_link = _dbus_connection_pop_message_link_unlocked (connection);
2258 if (message_link == NULL)
2260 /* another thread dispatched our stuff */
2262 _dbus_connection_release_dispatch (connection);
2264 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2266 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2268 dbus_connection_unref (connection);
2273 message = message_link->data;
2275 result = DBUS_HANDLER_RESULT_ALLOW_MORE_HANDLERS;
2277 reply_serial = dbus_message_get_reply_serial (message);
2278 reply_handler_data = _dbus_hash_table_lookup_int (connection->pending_replies,
2281 if (!_dbus_list_copy (&connection->filter_list, &filter_list_copy))
2283 _dbus_connection_release_dispatch (connection);
2285 _dbus_connection_failed_pop (connection, message_link);
2287 /* unlocks and calls user code */
2288 _dbus_connection_update_dispatch_status_and_unlock (connection,
2289 DBUS_DISPATCH_NEED_MEMORY);
2291 dbus_connection_unref (connection);
2293 return DBUS_DISPATCH_NEED_MEMORY;
2296 _dbus_list_foreach (&filter_list_copy,
2297 (DBusForeachFunction)dbus_message_handler_ref,
2300 /* We're still protected from dispatch() reentrancy here
2301 * since we acquired the dispatcher
2303 CONNECTION_UNLOCK (connection);
2305 link = _dbus_list_get_first_link (&filter_list_copy);
2306 while (link != NULL)
2308 DBusMessageHandler *handler = link->data;
2309 DBusList *next = _dbus_list_get_next_link (&filter_list_copy, link);
2311 _dbus_verbose (" running filter on message %p\n", message);
2312 result = _dbus_message_handler_handle_message (handler, connection,
2315 if (result == DBUS_HANDLER_RESULT_REMOVE_MESSAGE)
2321 _dbus_list_foreach (&filter_list_copy,
2322 (DBusForeachFunction)dbus_message_handler_unref,
2324 _dbus_list_clear (&filter_list_copy);
2326 CONNECTION_LOCK (connection);
2328 /* Did a reply we were waiting on get filtered? */
2329 if (reply_handler_data && result == DBUS_HANDLER_RESULT_REMOVE_MESSAGE)
2331 /* Queue the timeout immediately! */
2332 if (reply_handler_data->timeout_link)
2334 _dbus_connection_queue_synthesized_message_link (connection,
2335 reply_handler_data->timeout_link);
2336 reply_handler_data->timeout_link = NULL;
2340 /* We already queued the timeout? Then it was filtered! */
2341 _dbus_warn ("The timeout error with reply serial %d was filtered, so the reply handler will never be called.\n", reply_serial);
2345 if (result == DBUS_HANDLER_RESULT_REMOVE_MESSAGE)
2348 if (reply_handler_data)
2350 CONNECTION_UNLOCK (connection);
2352 _dbus_verbose (" running reply handler on message %p\n", message);
2354 result = _dbus_message_handler_handle_message (reply_handler_data->handler,
2355 connection, message);
2356 reply_handler_data_free (reply_handler_data);
2357 CONNECTION_LOCK (connection);
2361 name = dbus_message_get_name (message);
2364 handler = _dbus_hash_table_lookup_string (connection->handler_table,
2366 if (handler != NULL)
2368 /* We're still protected from dispatch() reentrancy here
2369 * since we acquired the dispatcher
2371 CONNECTION_UNLOCK (connection);
2373 _dbus_verbose (" running app handler on message %p (%s)\n",
2374 message, dbus_message_get_name (message));
2376 result = _dbus_message_handler_handle_message (handler, connection,
2378 CONNECTION_LOCK (connection);
2379 if (result == DBUS_HANDLER_RESULT_REMOVE_MESSAGE)
2384 _dbus_verbose (" done dispatching %p (%s) on connection %p\n", message,
2385 dbus_message_get_name (message), connection);
2388 _dbus_connection_release_dispatch (connection);
2390 _dbus_list_free_link (message_link);
2391 dbus_message_unref (message); /* don't want the message to count in max message limits
2392 * in computing dispatch status
2395 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2397 /* unlocks and calls user code */
2398 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2400 dbus_connection_unref (connection);
2406 * Sets the watch functions for the connection. These functions are
2407 * responsible for making the application's main loop aware of file
2408 * descriptors that need to be monitored for events, using select() or
2409 * poll(). When using Qt, typically the DBusAddWatchFunction would
2410 * create a QSocketNotifier. When using GLib, the DBusAddWatchFunction
2411 * could call g_io_add_watch(), or could be used as part of a more
2412 * elaborate GSource. Note that when a watch is added, it may
2415 * The DBusWatchToggledFunction notifies the application that the
2416 * watch has been enabled or disabled. Call dbus_watch_get_enabled()
2417 * to check this. A disabled watch should have no effect, and enabled
2418 * watch should be added to the main loop. This feature is used
2419 * instead of simply adding/removing the watch because
2420 * enabling/disabling can be done without memory allocation. The
2421 * toggled function may be NULL if a main loop re-queries
2422 * dbus_watch_get_enabled() every time anyway.
2424 * The DBusWatch can be queried for the file descriptor to watch using
2425 * dbus_watch_get_fd(), and for the events to watch for using
2426 * dbus_watch_get_flags(). The flags returned by
2427 * dbus_watch_get_flags() will only contain DBUS_WATCH_READABLE and
2428 * DBUS_WATCH_WRITABLE, never DBUS_WATCH_HANGUP or DBUS_WATCH_ERROR;
2429 * all watches implicitly include a watch for hangups, errors, and
2430 * other exceptional conditions.
2432 * Once a file descriptor becomes readable or writable, or an exception
2433 * occurs, dbus_watch_handle() should be called to
2434 * notify the connection of the file descriptor's condition.
2436 * dbus_watch_handle() cannot be called during the
2437 * DBusAddWatchFunction, as the connection will not be ready to handle
2440 * It is not allowed to reference a DBusWatch after it has been passed
2441 * to remove_function.
2443 * If #FALSE is returned due to lack of memory, the failure may be due
2444 * to a #FALSE return from the new add_function. If so, the
2445 * add_function may have been called successfully one or more times,
2446 * but the remove_function will also have been called to remove any
2447 * successful adds. i.e. if #FALSE is returned the net result
2448 * should be that dbus_connection_set_watch_functions() has no effect,
2449 * but the add_function and remove_function may have been called.
2451 * @todo We need to drop the lock when we call the
2452 * add/remove/toggled functions which can be a side effect
2453 * of setting the watch functions.
2455 * @param connection the connection.
2456 * @param add_function function to begin monitoring a new descriptor.
2457 * @param remove_function function to stop monitoring a descriptor.
2458 * @param toggled_function function to notify of enable/disable
2459 * @param data data to pass to add_function and remove_function.
2460 * @param free_data_function function to be called to free the data.
2461 * @returns #FALSE on failure (no memory)
2464 dbus_connection_set_watch_functions (DBusConnection *connection,
2465 DBusAddWatchFunction add_function,
2466 DBusRemoveWatchFunction remove_function,
2467 DBusWatchToggledFunction toggled_function,
2469 DBusFreeFunction free_data_function)
2473 _dbus_return_val_if_fail (connection != NULL, FALSE);
2475 CONNECTION_LOCK (connection);
2476 /* ref connection for slightly better reentrancy */
2477 _dbus_connection_ref_unlocked (connection);
2479 /* FIXME this can call back into user code, and we need to drop the
2480 * connection lock when it does.
2482 retval = _dbus_watch_list_set_functions (connection->watches,
2483 add_function, remove_function,
2485 data, free_data_function);
2487 CONNECTION_UNLOCK (connection);
2488 /* drop our paranoid refcount */
2489 dbus_connection_unref (connection);
2495 * Sets the timeout functions for the connection. These functions are
2496 * responsible for making the application's main loop aware of timeouts.
2497 * When using Qt, typically the DBusAddTimeoutFunction would create a
2498 * QTimer. When using GLib, the DBusAddTimeoutFunction would call
2501 * The DBusTimeoutToggledFunction notifies the application that the
2502 * timeout has been enabled or disabled. Call
2503 * dbus_timeout_get_enabled() to check this. A disabled timeout should
2504 * have no effect, and enabled timeout should be added to the main
2505 * loop. This feature is used instead of simply adding/removing the
2506 * timeout because enabling/disabling can be done without memory
2507 * allocation. With Qt, QTimer::start() and QTimer::stop() can be used
2508 * to enable and disable. The toggled function may be NULL if a main
2509 * loop re-queries dbus_timeout_get_enabled() every time anyway.
2510 * Whenever a timeout is toggled, its interval may change.
2512 * The DBusTimeout can be queried for the timer interval using
2513 * dbus_timeout_get_interval(). dbus_timeout_handle() should be called
2514 * repeatedly, each time the interval elapses, starting after it has
2515 * elapsed once. The timeout stops firing when it is removed with the
2516 * given remove_function. The timer interval may change whenever the
2517 * timeout is added, removed, or toggled.
2519 * @param connection the connection.
2520 * @param add_function function to add a timeout.
2521 * @param remove_function function to remove a timeout.
2522 * @param toggled_function function to notify of enable/disable
2523 * @param data data to pass to add_function and remove_function.
2524 * @param free_data_function function to be called to free the data.
2525 * @returns #FALSE on failure (no memory)
2528 dbus_connection_set_timeout_functions (DBusConnection *connection,
2529 DBusAddTimeoutFunction add_function,
2530 DBusRemoveTimeoutFunction remove_function,
2531 DBusTimeoutToggledFunction toggled_function,
2533 DBusFreeFunction free_data_function)
2537 _dbus_return_val_if_fail (connection != NULL, FALSE);
2539 CONNECTION_LOCK (connection);
2540 /* ref connection for slightly better reentrancy */
2541 _dbus_connection_ref_unlocked (connection);
2543 retval = _dbus_timeout_list_set_functions (connection->timeouts,
2544 add_function, remove_function,
2546 data, free_data_function);
2548 CONNECTION_UNLOCK (connection);
2549 /* drop our paranoid refcount */
2550 dbus_connection_unref (connection);
2556 * Sets the mainloop wakeup function for the connection. Thi function is
2557 * responsible for waking up the main loop (if its sleeping) when some some
2558 * change has happened to the connection that the mainloop needs to reconsiders
2559 * (e.g. a message has been queued for writing).
2560 * When using Qt, this typically results in a call to QEventLoop::wakeUp().
2561 * When using GLib, it would call g_main_context_wakeup().
2564 * @param connection the connection.
2565 * @param wakeup_main_function function to wake up the mainloop
2566 * @param data data to pass wakeup_main_function
2567 * @param free_data_function function to be called to free the data.
2570 dbus_connection_set_wakeup_main_function (DBusConnection *connection,
2571 DBusWakeupMainFunction wakeup_main_function,
2573 DBusFreeFunction free_data_function)
2576 DBusFreeFunction old_free_data;
2578 _dbus_return_if_fail (connection != NULL);
2580 CONNECTION_LOCK (connection);
2581 old_data = connection->wakeup_main_data;
2582 old_free_data = connection->free_wakeup_main_data;
2584 connection->wakeup_main_function = wakeup_main_function;
2585 connection->wakeup_main_data = data;
2586 connection->free_wakeup_main_data = free_data_function;
2588 CONNECTION_UNLOCK (connection);
2590 /* Callback outside the lock */
2592 (*old_free_data) (old_data);
2596 * Set a function to be invoked when the dispatch status changes.
2597 * If the dispatch status is #DBUS_DISPATCH_DATA_REMAINS, then
2598 * dbus_connection_dispatch() needs to be called to process incoming
2599 * messages. However, dbus_connection_dispatch() MUST NOT BE CALLED
2600 * from inside the DBusDispatchStatusFunction. Indeed, almost
2601 * any reentrancy in this function is a bad idea. Instead,
2602 * the DBusDispatchStatusFunction should simply save an indication
2603 * that messages should be dispatched later, when the main loop
2606 * @param connection the connection
2607 * @param function function to call on dispatch status changes
2608 * @param data data for function
2609 * @param free_data_function free the function data
2612 dbus_connection_set_dispatch_status_function (DBusConnection *connection,
2613 DBusDispatchStatusFunction function,
2615 DBusFreeFunction free_data_function)
2618 DBusFreeFunction old_free_data;
2620 _dbus_return_if_fail (connection != NULL);
2622 CONNECTION_LOCK (connection);
2623 old_data = connection->dispatch_status_data;
2624 old_free_data = connection->free_dispatch_status_data;
2626 connection->dispatch_status_function = function;
2627 connection->dispatch_status_data = data;
2628 connection->free_dispatch_status_data = free_data_function;
2630 CONNECTION_UNLOCK (connection);
2632 /* Callback outside the lock */
2634 (*old_free_data) (old_data);
2638 * Gets the UNIX user ID of the connection if any.
2639 * Returns #TRUE if the uid is filled in.
2640 * Always returns #FALSE on non-UNIX platforms.
2641 * Always returns #FALSE prior to authenticating the
2644 * @param connection the connection
2645 * @param uid return location for the user ID
2646 * @returns #TRUE if uid is filled in with a valid user ID
2649 dbus_connection_get_unix_user (DBusConnection *connection,
2654 _dbus_return_val_if_fail (connection != NULL, FALSE);
2655 _dbus_return_val_if_fail (uid != NULL, FALSE);
2657 CONNECTION_LOCK (connection);
2659 if (!_dbus_transport_get_is_authenticated (connection->transport))
2662 result = _dbus_transport_get_unix_user (connection->transport,
2664 CONNECTION_UNLOCK (connection);
2670 * Sets a predicate function used to determine whether a given user ID
2671 * is allowed to connect. When an incoming connection has
2672 * authenticated with a particular user ID, this function is called;
2673 * if it returns #TRUE, the connection is allowed to proceed,
2674 * otherwise the connection is disconnected.
2676 * If the function is set to #NULL (as it is by default), then
2677 * only the same UID as the server process will be allowed to
2680 * @param connection the connection
2681 * @param function the predicate
2682 * @param data data to pass to the predicate
2683 * @param free_data_function function to free the data
2686 dbus_connection_set_unix_user_function (DBusConnection *connection,
2687 DBusAllowUnixUserFunction function,
2689 DBusFreeFunction free_data_function)
2691 void *old_data = NULL;
2692 DBusFreeFunction old_free_function = NULL;
2694 _dbus_return_if_fail (connection != NULL);
2696 CONNECTION_LOCK (connection);
2697 _dbus_transport_set_unix_user_function (connection->transport,
2698 function, data, free_data_function,
2699 &old_data, &old_free_function);
2700 CONNECTION_UNLOCK (connection);
2702 if (old_free_function != NULL)
2703 (* old_free_function) (old_data);
2707 * Adds a message filter. Filters are handlers that are run on
2708 * all incoming messages, prior to the normal handlers
2709 * registered with dbus_connection_register_handler().
2710 * Filters are run in the order that they were added.
2711 * The same handler can be added as a filter more than once, in
2712 * which case it will be run more than once.
2713 * Filters added during a filter callback won't be run on the
2714 * message being processed.
2716 * The connection does NOT add a reference to the message handler;
2717 * instead, if the message handler is finalized, the connection simply
2718 * forgets about it. Thus the caller of this function must keep a
2719 * reference to the message handler.
2721 * @param connection the connection
2722 * @param handler the handler
2723 * @returns #TRUE on success, #FALSE if not enough memory.
2726 dbus_connection_add_filter (DBusConnection *connection,
2727 DBusMessageHandler *handler)
2729 _dbus_return_val_if_fail (connection != NULL, FALSE);
2730 _dbus_return_val_if_fail (handler != NULL, FALSE);
2732 CONNECTION_LOCK (connection);
2733 if (!_dbus_message_handler_add_connection (handler, connection))
2735 CONNECTION_UNLOCK (connection);
2739 if (!_dbus_list_append (&connection->filter_list,
2742 _dbus_message_handler_remove_connection (handler, connection);
2743 CONNECTION_UNLOCK (connection);
2747 CONNECTION_UNLOCK (connection);
2752 * Removes a previously-added message filter. It is a programming
2753 * error to call this function for a handler that has not
2754 * been added as a filter. If the given handler was added
2755 * more than once, only one instance of it will be removed
2756 * (the most recently-added instance).
2758 * @param connection the connection
2759 * @param handler the handler to remove
2763 dbus_connection_remove_filter (DBusConnection *connection,
2764 DBusMessageHandler *handler)
2766 _dbus_return_if_fail (connection != NULL);
2767 _dbus_return_if_fail (handler != NULL);
2769 CONNECTION_LOCK (connection);
2770 if (!_dbus_list_remove_last (&connection->filter_list, handler))
2772 _dbus_warn ("Tried to remove a DBusConnection filter that had not been added\n");
2773 CONNECTION_UNLOCK (connection);
2777 _dbus_message_handler_remove_connection (handler, connection);
2779 CONNECTION_UNLOCK (connection);
2783 * Registers a handler for a list of message names. A single handler
2784 * can be registered for any number of message names, but each message
2785 * name can only have one handler at a time. It's not allowed to call
2786 * this function with the name of a message that already has a
2787 * handler. If the function returns #FALSE, the handlers were not
2788 * registered due to lack of memory.
2790 * The connection does NOT add a reference to the message handler;
2791 * instead, if the message handler is finalized, the connection simply
2792 * forgets about it. Thus the caller of this function must keep a
2793 * reference to the message handler.
2795 * @todo the messages_to_handle arg may be more convenient if it's a
2796 * single string instead of an array. Though right now MessageHandler
2797 * is sort of designed to say be associated with an entire object with
2798 * multiple methods, that's why for example the connection only
2799 * weakrefs it. So maybe the "manual" API should be different.
2801 * @param connection the connection
2802 * @param handler the handler
2803 * @param messages_to_handle the messages to handle
2804 * @param n_messages the number of message names in messages_to_handle
2805 * @returns #TRUE on success, #FALSE if no memory or another handler already exists
2809 dbus_connection_register_handler (DBusConnection *connection,
2810 DBusMessageHandler *handler,
2811 const char **messages_to_handle,
2816 _dbus_return_val_if_fail (connection != NULL, FALSE);
2817 _dbus_return_val_if_fail (handler != NULL, FALSE);
2818 _dbus_return_val_if_fail (n_messages >= 0, FALSE);
2819 _dbus_return_val_if_fail (n_messages == 0 || messages_to_handle != NULL, FALSE);
2821 CONNECTION_LOCK (connection);
2823 while (i < n_messages)
2828 key = _dbus_strdup (messages_to_handle[i]);
2832 if (!_dbus_hash_iter_lookup (connection->handler_table,
2840 if (_dbus_hash_iter_get_value (&iter) != NULL)
2842 _dbus_warn ("Bug in application: attempted to register a second handler for %s\n",
2843 messages_to_handle[i]);
2844 dbus_free (key); /* won't have replaced the old key with the new one */
2848 if (!_dbus_message_handler_add_connection (handler, connection))
2850 _dbus_hash_iter_remove_entry (&iter);
2851 /* key has freed on nuking the entry */
2855 _dbus_hash_iter_set_value (&iter, handler);
2860 CONNECTION_UNLOCK (connection);
2864 /* unregister everything registered so far,
2865 * so we don't fail partially
2867 dbus_connection_unregister_handler (connection,
2872 CONNECTION_UNLOCK (connection);
2877 * Unregisters a handler for a list of message names. The handlers
2878 * must have been previously registered.
2880 * @param connection the connection
2881 * @param handler the handler
2882 * @param messages_to_handle the messages to handle
2883 * @param n_messages the number of message names in messages_to_handle
2887 dbus_connection_unregister_handler (DBusConnection *connection,
2888 DBusMessageHandler *handler,
2889 const char **messages_to_handle,
2894 _dbus_return_if_fail (connection != NULL);
2895 _dbus_return_if_fail (handler != NULL);
2896 _dbus_return_if_fail (n_messages >= 0);
2897 _dbus_return_if_fail (n_messages == 0 || messages_to_handle != NULL);
2899 CONNECTION_LOCK (connection);
2901 while (i < n_messages)
2905 if (!_dbus_hash_iter_lookup (connection->handler_table,
2906 (char*) messages_to_handle[i], FALSE,
2909 _dbus_warn ("Bug in application: attempted to unregister handler for %s which was not registered\n",
2910 messages_to_handle[i]);
2912 else if (_dbus_hash_iter_get_value (&iter) != handler)
2914 _dbus_warn ("Bug in application: attempted to unregister handler for %s which was registered by a different handler\n",
2915 messages_to_handle[i]);
2919 _dbus_hash_iter_remove_entry (&iter);
2920 _dbus_message_handler_remove_connection (handler, connection);
2926 CONNECTION_UNLOCK (connection);
2929 static DBusDataSlotAllocator slot_allocator;
2930 _DBUS_DEFINE_GLOBAL_LOCK (connection_slots);
2933 * Allocates an integer ID to be used for storing application-specific
2934 * data on any DBusConnection. The allocated ID may then be used
2935 * with dbus_connection_set_data() and dbus_connection_get_data().
2936 * If allocation fails, -1 is returned. Again, the allocated
2937 * slot is global, i.e. all DBusConnection objects will
2938 * have a slot with the given integer ID reserved.
2940 * @returns -1 on failure, otherwise the data slot ID
2943 dbus_connection_allocate_data_slot (void)
2945 return _dbus_data_slot_allocator_alloc (&slot_allocator,
2946 _DBUS_LOCK_NAME (connection_slots));
2950 * Deallocates a global ID for connection data slots.
2951 * dbus_connection_get_data() and dbus_connection_set_data()
2952 * may no longer be used with this slot.
2953 * Existing data stored on existing DBusConnection objects
2954 * will be freed when the connection is finalized,
2955 * but may not be retrieved (and may only be replaced
2956 * if someone else reallocates the slot).
2958 * @param slot the slot to deallocate
2961 dbus_connection_free_data_slot (int slot)
2963 _dbus_data_slot_allocator_free (&slot_allocator, slot);
2967 * Stores a pointer on a DBusConnection, along
2968 * with an optional function to be used for freeing
2969 * the data when the data is set again, or when
2970 * the connection is finalized. The slot number
2971 * must have been allocated with dbus_connection_allocate_data_slot().
2973 * @param connection the connection
2974 * @param slot the slot number
2975 * @param data the data to store
2976 * @param free_data_func finalizer function for the data
2977 * @returns #TRUE if there was enough memory to store the data
2980 dbus_connection_set_data (DBusConnection *connection,
2983 DBusFreeFunction free_data_func)
2985 DBusFreeFunction old_free_func;
2989 _dbus_return_val_if_fail (connection != NULL, FALSE);
2990 _dbus_return_val_if_fail (slot >= 0, FALSE);
2992 CONNECTION_LOCK (connection);
2994 retval = _dbus_data_slot_list_set (&slot_allocator,
2995 &connection->slot_list,
2996 slot, data, free_data_func,
2997 &old_free_func, &old_data);
2999 CONNECTION_UNLOCK (connection);
3003 /* Do the actual free outside the connection lock */
3005 (* old_free_func) (old_data);
3012 * Retrieves data previously set with dbus_connection_set_data().
3013 * The slot must still be allocated (must not have been freed).
3015 * @param connection the connection
3016 * @param slot the slot to get data from
3017 * @returns the data, or #NULL if not found
3020 dbus_connection_get_data (DBusConnection *connection,
3025 _dbus_return_val_if_fail (connection != NULL, NULL);
3027 CONNECTION_LOCK (connection);
3029 res = _dbus_data_slot_list_get (&slot_allocator,
3030 &connection->slot_list,
3033 CONNECTION_UNLOCK (connection);
3039 * This function sets a global flag for whether dbus_connection_new()
3040 * will set SIGPIPE behavior to SIG_IGN.
3042 * @param will_modify_sigpipe #TRUE to allow sigpipe to be set to SIG_IGN
3045 dbus_connection_set_change_sigpipe (dbus_bool_t will_modify_sigpipe)
3047 _dbus_modify_sigpipe = will_modify_sigpipe != FALSE;
3051 * Specifies the maximum size message this connection is allowed to
3052 * receive. Larger messages will result in disconnecting the
3055 * @param connection a #DBusConnection
3056 * @param size maximum message size the connection can receive, in bytes
3059 dbus_connection_set_max_message_size (DBusConnection *connection,
3062 _dbus_return_if_fail (connection != NULL);
3064 CONNECTION_LOCK (connection);
3065 _dbus_transport_set_max_message_size (connection->transport,
3067 CONNECTION_UNLOCK (connection);
3071 * Gets the value set by dbus_connection_set_max_message_size().
3073 * @param connection the connection
3074 * @returns the max size of a single message
3077 dbus_connection_get_max_message_size (DBusConnection *connection)
3081 _dbus_return_val_if_fail (connection != NULL, 0);
3083 CONNECTION_LOCK (connection);
3084 res = _dbus_transport_get_max_message_size (connection->transport);
3085 CONNECTION_UNLOCK (connection);
3090 * Sets the maximum total number of bytes that can be used for all messages
3091 * received on this connection. Messages count toward the maximum until
3092 * they are finalized. When the maximum is reached, the connection will
3093 * not read more data until some messages are finalized.
3095 * The semantics of the maximum are: if outstanding messages are
3096 * already above the maximum, additional messages will not be read.
3097 * The semantics are not: if the next message would cause us to exceed
3098 * the maximum, we don't read it. The reason is that we don't know the
3099 * size of a message until after we read it.
3101 * Thus, the max live messages size can actually be exceeded
3102 * by up to the maximum size of a single message.
3104 * Also, if we read say 1024 bytes off the wire in a single read(),
3105 * and that contains a half-dozen small messages, we may exceed the
3106 * size max by that amount. But this should be inconsequential.
3108 * This does imply that we can't call read() with a buffer larger
3109 * than we're willing to exceed this limit by.
3111 * @param connection the connection
3112 * @param size the maximum size in bytes of all outstanding messages
3115 dbus_connection_set_max_received_size (DBusConnection *connection,
3118 _dbus_return_if_fail (connection != NULL);
3120 CONNECTION_LOCK (connection);
3121 _dbus_transport_set_max_received_size (connection->transport,
3123 CONNECTION_UNLOCK (connection);
3127 * Gets the value set by dbus_connection_set_max_received_size().
3129 * @param connection the connection
3130 * @returns the max size of all live messages
3133 dbus_connection_get_max_received_size (DBusConnection *connection)
3137 _dbus_return_val_if_fail (connection != NULL, 0);
3139 CONNECTION_LOCK (connection);
3140 res = _dbus_transport_get_max_received_size (connection->transport);
3141 CONNECTION_UNLOCK (connection);
3146 * Gets the approximate size in bytes of all messages in the outgoing
3147 * message queue. The size is approximate in that you shouldn't use
3148 * it to decide how many bytes to read off the network or anything
3149 * of that nature, as optimizations may choose to tell small white lies
3150 * to avoid performance overhead.
3152 * @param connection the connection
3153 * @returns the number of bytes that have been queued up but not sent
3156 dbus_connection_get_outgoing_size (DBusConnection *connection)
3160 _dbus_return_val_if_fail (connection != NULL, 0);
3162 CONNECTION_LOCK (connection);
3163 res = _dbus_counter_get_value (connection->outgoing_counter);
3164 CONNECTION_UNLOCK (connection);