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
24 #include "dbus-connection.h"
25 #include "dbus-list.h"
26 #include "dbus-timeout.h"
27 #include "dbus-transport.h"
28 #include "dbus-watch.h"
29 #include "dbus-connection-internal.h"
30 #include "dbus-list.h"
31 #include "dbus-hash.h"
32 #include "dbus-message-internal.h"
33 #include "dbus-message-handler.h"
34 #include "dbus-threads.h"
35 #include "dbus-protocol.h"
36 #include "dbus-dataslot.h"
39 * @defgroup DBusConnection DBusConnection
41 * @brief Connection to another application
43 * A DBusConnection represents a connection to another
44 * application. Messages can be sent and received via this connection.
46 * The connection maintains a queue of incoming messages and a queue
47 * of outgoing messages. dbus_connection_pop_message() and friends
48 * can be used to read incoming messages from the queue.
49 * Outgoing messages are automatically discarded as they are
50 * written to the network.
52 * In brief a DBusConnection is a message queue associated with some
53 * message transport mechanism such as a socket.
58 * @defgroup DBusConnectionInternals DBusConnection implementation details
59 * @ingroup DBusInternals
60 * @brief Implementation details of DBusConnection
65 /** default timeout value when waiting for a message reply */
66 #define DEFAULT_TIMEOUT_VALUE (15 * 1000)
68 static dbus_bool_t _dbus_modify_sigpipe = TRUE;
71 * Implementation details of DBusConnection. All fields are private.
75 int refcount; /**< Reference count. */
77 DBusMutex *mutex; /**< Lock on the entire DBusConnection */
79 dbus_bool_t dispatch_acquired; /**< Protects dispatch_message */
80 DBusCondVar *dispatch_cond; /**< Protects dispatch_message */
82 dbus_bool_t io_path_acquired; /**< Protects transport io path */
83 DBusCondVar *io_path_cond; /**< Protects transport io path */
85 DBusList *outgoing_messages; /**< Queue of messages we need to send, send the end of the list first. */
86 DBusList *incoming_messages; /**< Queue of messages we have received, end of the list received most recently. */
88 DBusMessage *message_borrowed; /**< True if the first incoming message has been borrowed */
89 DBusCondVar *message_returned_cond; /**< Used with dbus_connection_borrow_message() */
91 int n_outgoing; /**< Length of outgoing queue. */
92 int n_incoming; /**< Length of incoming queue. */
94 DBusTransport *transport; /**< Object that sends/receives messages over network. */
95 DBusWatchList *watches; /**< Stores active watches. */
96 DBusTimeoutList *timeouts; /**< Stores active timeouts. */
98 DBusHashTable *handler_table; /**< Table of registered DBusMessageHandler */
99 DBusList *filter_list; /**< List of filters. */
101 DBusDataSlotList slot_list; /**< Data stored by allocated integer ID */
103 DBusHashTable *pending_replies; /**< Hash of message serials and their message handlers. */
104 DBusCounter *connection_counter; /**< Counter that we decrement when finalized */
106 int client_serial; /**< Client serial. Increments each time a message is sent */
107 DBusList *disconnect_message_link; /**< Preallocated list node for queueing the disconnection message */
109 DBusWakeupMainFunction wakeup_main_function; /**< Function to wake up the mainloop */
110 void *wakeup_main_data; /**< Application data for wakeup_main_function */
111 DBusFreeFunction free_wakeup_main_data; /**< free wakeup_main_data */
116 DBusConnection *connection;
117 DBusMessageHandler *handler;
118 DBusTimeout *timeout;
121 DBusList *timeout_link; /* Preallocated timeout response */
123 dbus_bool_t timeout_added;
124 dbus_bool_t connection_added;
127 static void reply_handler_data_free (ReplyHandlerData *data);
129 static void _dbus_connection_remove_timeout_locked (DBusConnection *connection,
130 DBusTimeout *timeout);
133 * Acquires the connection lock.
135 * @param connection the connection.
138 _dbus_connection_lock (DBusConnection *connection)
140 dbus_mutex_lock (connection->mutex);
144 * Releases the connection lock.
146 * @param connection the connection.
149 _dbus_connection_unlock (DBusConnection *connection)
151 dbus_mutex_unlock (connection->mutex);
155 * Wakes up the main loop if it is sleeping
156 * Needed if we're e.g. queueing outgoing messages
157 * on a thread while the mainloop sleeps.
159 * @param connection the connection.
162 _dbus_connection_wakeup_mainloop (DBusConnection *connection)
164 if (connection->wakeup_main_function)
165 (*connection->wakeup_main_function) (connection->wakeup_main_data);
169 * Adds a message to the incoming message queue, returning #FALSE
170 * if there's insufficient memory to queue the message.
172 * @param connection the connection.
173 * @param message the message to queue.
174 * @returns #TRUE on success.
177 _dbus_connection_queue_received_message (DBusConnection *connection,
178 DBusMessage *message)
180 ReplyHandlerData *reply_handler_data;
181 dbus_int32_t reply_serial;
183 _dbus_assert (_dbus_transport_get_is_authenticated (connection->transport));
185 if (!_dbus_list_append (&connection->incoming_messages,
189 /* If this is a reply we're waiting on, remove timeout for it */
190 reply_serial = dbus_message_get_reply_serial (message);
191 if (reply_serial != -1)
193 reply_handler_data = _dbus_hash_table_lookup_int (connection->pending_replies,
195 if (reply_handler_data != NULL)
197 if (reply_handler_data->timeout_added)
198 _dbus_connection_remove_timeout_locked (connection,
199 reply_handler_data->timeout);
200 reply_handler_data->timeout_added = FALSE;
204 dbus_message_ref (message);
205 connection->n_incoming += 1;
207 _dbus_connection_wakeup_mainloop (connection);
209 _dbus_assert (dbus_message_get_name (message) != NULL);
210 _dbus_verbose ("Incoming message %p (%s) added to queue, %d incoming\n",
211 message, dbus_message_get_name (message),
212 connection->n_incoming);
218 * Adds a link + message to the incoming message queue.
219 * Can't fail. Takes ownership of both link and message.
221 * @param connection the connection.
222 * @param link the list node and message to queue.
224 * @todo This needs to wake up the mainloop if it is in
225 * a poll/select and this is a multithreaded app.
228 _dbus_connection_queue_synthesized_message_link (DBusConnection *connection,
231 _dbus_list_append_link (&connection->incoming_messages, link);
233 connection->n_incoming += 1;
235 _dbus_connection_wakeup_mainloop (connection);
237 _dbus_verbose ("Incoming synthesized message %p added to queue, %d incoming\n",
238 link->data, connection->n_incoming);
243 * Checks whether there are messages in the outgoing message queue.
245 * @param connection the connection.
246 * @returns #TRUE if the outgoing queue is non-empty.
249 _dbus_connection_have_messages_to_send (DBusConnection *connection)
251 return connection->outgoing_messages != NULL;
255 * Gets the next outgoing message. The message remains in the
256 * queue, and the caller does not own a reference to it.
258 * @param connection the connection.
259 * @returns the message to be sent.
262 _dbus_connection_get_message_to_send (DBusConnection *connection)
264 return _dbus_list_get_last (&connection->outgoing_messages);
268 * Notifies the connection that a message has been sent, so the
269 * message can be removed from the outgoing queue.
271 * @param connection the connection.
272 * @param message the message that was sent.
275 _dbus_connection_message_sent (DBusConnection *connection,
276 DBusMessage *message)
278 _dbus_assert (_dbus_transport_get_is_authenticated (connection->transport));
279 _dbus_assert (message == _dbus_list_get_last (&connection->outgoing_messages));
281 _dbus_list_pop_last (&connection->outgoing_messages);
282 dbus_message_unref (message);
284 connection->n_outgoing -= 1;
286 _dbus_verbose ("Message %p removed from outgoing queue, %d left to send\n",
287 message, connection->n_outgoing);
289 if (connection->n_outgoing == 0)
290 _dbus_transport_messages_pending (connection->transport,
291 connection->n_outgoing);
295 * Adds a watch using the connection's DBusAddWatchFunction if
296 * available. Otherwise records the watch to be added when said
297 * function is available. Also re-adds the watch if the
298 * DBusAddWatchFunction changes. May fail due to lack of memory.
300 * @param connection the connection.
301 * @param watch the watch to add.
302 * @returns #TRUE on success.
305 _dbus_connection_add_watch (DBusConnection *connection,
308 if (connection->watches) /* null during finalize */
309 return _dbus_watch_list_add_watch (connection->watches,
316 * Removes a watch using the connection's DBusRemoveWatchFunction
317 * if available. It's an error to call this function on a watch
318 * that was not previously added.
320 * @param connection the connection.
321 * @param watch the watch to remove.
324 _dbus_connection_remove_watch (DBusConnection *connection,
327 if (connection->watches) /* null during finalize */
328 _dbus_watch_list_remove_watch (connection->watches,
333 * Adds a timeout using the connection's DBusAddTimeoutFunction if
334 * available. Otherwise records the timeout to be added when said
335 * function is available. Also re-adds the timeout if the
336 * DBusAddTimeoutFunction changes. May fail due to lack of memory.
337 * The timeout will fire only one time.
339 * @param connection the connection.
340 * @param timeout the timeout to add.
341 * @returns #TRUE on success.
344 _dbus_connection_add_timeout (DBusConnection *connection,
345 DBusTimeout *timeout)
347 if (connection->timeouts) /* null during finalize */
348 return _dbus_timeout_list_add_timeout (connection->timeouts,
355 * Removes a timeout using the connection's DBusRemoveTimeoutFunction
356 * if available. It's an error to call this function on a timeout
357 * that was not previously added.
359 * @param connection the connection.
360 * @param timeout the timeout to remove.
363 _dbus_connection_remove_timeout (DBusConnection *connection,
364 DBusTimeout *timeout)
366 if (connection->timeouts) /* null during finalize */
367 _dbus_timeout_list_remove_timeout (connection->timeouts,
372 _dbus_connection_remove_timeout_locked (DBusConnection *connection,
373 DBusTimeout *timeout)
375 dbus_mutex_lock (connection->mutex);
376 _dbus_connection_remove_timeout (connection, timeout);
377 dbus_mutex_unlock (connection->mutex);
382 * Tells the connection that the transport has been disconnected.
383 * Results in posting a disconnect message on the incoming message
384 * queue. Only has an effect the first time it's called.
386 * @param connection the connection
389 _dbus_connection_notify_disconnected (DBusConnection *connection)
391 if (connection->disconnect_message_link)
393 /* We haven't sent the disconnect message already */
394 _dbus_connection_queue_synthesized_message_link (connection,
395 connection->disconnect_message_link);
396 connection->disconnect_message_link = NULL;
402 * Acquire the transporter I/O path. This must be done before
403 * doing any I/O in the transporter. May sleep and drop the
404 * connection mutex while waiting for the I/O path.
406 * @param connection the connection.
407 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
408 * @returns TRUE if the I/O path was acquired.
411 _dbus_connection_acquire_io_path (DBusConnection *connection,
412 int timeout_milliseconds)
414 dbus_bool_t res = TRUE;
416 if (connection->io_path_acquired)
418 if (timeout_milliseconds != -1)
419 res = dbus_condvar_wait_timeout (connection->io_path_cond,
421 timeout_milliseconds);
423 dbus_condvar_wait (connection->io_path_cond, connection->mutex);
428 _dbus_assert (!connection->io_path_acquired);
430 connection->io_path_acquired = TRUE;
437 * Release the I/O path when you're done with it. Only call
438 * after you've acquired the I/O. Wakes up at most one thread
439 * currently waiting to acquire the I/O path.
441 * @param connection the connection.
444 _dbus_connection_release_io_path (DBusConnection *connection)
446 _dbus_assert (connection->io_path_acquired);
448 connection->io_path_acquired = FALSE;
449 dbus_condvar_wake_one (connection->io_path_cond);
454 * Queues incoming messages and sends outgoing messages for this
455 * connection, optionally blocking in the process. Each call to
456 * _dbus_connection_do_iteration() will call select() or poll() one
457 * time and then read or write data if possible.
459 * The purpose of this function is to be able to flush outgoing
460 * messages or queue up incoming messages without returning
461 * control to the application and causing reentrancy weirdness.
463 * The flags parameter allows you to specify whether to
464 * read incoming messages, write outgoing messages, or both,
465 * and whether to block if no immediate action is possible.
467 * The timeout_milliseconds parameter does nothing unless the
468 * iteration is blocking.
470 * If there are no outgoing messages and DBUS_ITERATION_DO_READING
471 * wasn't specified, then it's impossible to block, even if
472 * you specify DBUS_ITERATION_BLOCK; in that case the function
473 * returns immediately.
475 * @param connection the connection.
476 * @param flags iteration flags.
477 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
480 _dbus_connection_do_iteration (DBusConnection *connection,
482 int timeout_milliseconds)
484 if (connection->n_outgoing == 0)
485 flags &= ~DBUS_ITERATION_DO_WRITING;
487 if (_dbus_connection_acquire_io_path (connection,
488 (flags & DBUS_ITERATION_BLOCK)?timeout_milliseconds:0))
490 _dbus_transport_do_iteration (connection->transport,
491 flags, timeout_milliseconds);
492 _dbus_connection_release_io_path (connection);
497 * Creates a new connection for the given transport. A transport
498 * represents a message stream that uses some concrete mechanism, such
499 * as UNIX domain sockets. May return #NULL if insufficient
500 * memory exists to create the connection.
502 * @param transport the transport.
503 * @returns the new connection, or #NULL on failure.
506 _dbus_connection_new_for_transport (DBusTransport *transport)
508 DBusConnection *connection;
509 DBusWatchList *watch_list;
510 DBusTimeoutList *timeout_list;
511 DBusHashTable *handler_table, *pending_replies;
513 DBusCondVar *message_returned_cond;
514 DBusCondVar *dispatch_cond;
515 DBusCondVar *io_path_cond;
516 DBusList *disconnect_link;
517 DBusMessage *disconnect_message;
521 handler_table = NULL;
522 pending_replies = NULL;
525 message_returned_cond = NULL;
526 dispatch_cond = NULL;
528 disconnect_link = NULL;
529 disconnect_message = NULL;
531 watch_list = _dbus_watch_list_new ();
532 if (watch_list == NULL)
535 timeout_list = _dbus_timeout_list_new ();
536 if (timeout_list == NULL)
540 _dbus_hash_table_new (DBUS_HASH_STRING,
542 if (handler_table == NULL)
546 _dbus_hash_table_new (DBUS_HASH_INT,
547 NULL, (DBusFreeFunction)reply_handler_data_free);
548 if (pending_replies == NULL)
551 connection = dbus_new0 (DBusConnection, 1);
552 if (connection == NULL)
555 mutex = dbus_mutex_new ();
559 message_returned_cond = dbus_condvar_new ();
560 if (message_returned_cond == NULL)
563 dispatch_cond = dbus_condvar_new ();
564 if (dispatch_cond == NULL)
567 io_path_cond = dbus_condvar_new ();
568 if (io_path_cond == NULL)
571 disconnect_message = dbus_message_new (NULL, DBUS_MESSAGE_LOCAL_DISCONNECT);
572 if (disconnect_message == NULL)
575 disconnect_link = _dbus_list_alloc_link (disconnect_message);
576 if (disconnect_link == NULL)
579 if (_dbus_modify_sigpipe)
580 _dbus_disable_sigpipe ();
582 connection->refcount = 1;
583 connection->mutex = mutex;
584 connection->dispatch_cond = dispatch_cond;
585 connection->io_path_cond = io_path_cond;
586 connection->message_returned_cond = message_returned_cond;
587 connection->transport = transport;
588 connection->watches = watch_list;
589 connection->timeouts = timeout_list;
590 connection->handler_table = handler_table;
591 connection->pending_replies = pending_replies;
592 connection->filter_list = NULL;
594 _dbus_data_slot_list_init (&connection->slot_list);
596 connection->client_serial = 1;
598 connection->disconnect_message_link = disconnect_link;
600 _dbus_transport_ref (transport);
601 _dbus_transport_set_connection (transport, connection);
606 if (disconnect_message != NULL)
607 dbus_message_unref (disconnect_message);
609 if (disconnect_link != NULL)
610 _dbus_list_free_link (disconnect_link);
612 if (io_path_cond != NULL)
613 dbus_condvar_free (io_path_cond);
615 if (dispatch_cond != NULL)
616 dbus_condvar_free (dispatch_cond);
618 if (message_returned_cond != NULL)
619 dbus_condvar_free (message_returned_cond);
622 dbus_mutex_free (mutex);
624 if (connection != NULL)
625 dbus_free (connection);
628 _dbus_hash_table_unref (handler_table);
631 _dbus_hash_table_unref (pending_replies);
634 _dbus_watch_list_free (watch_list);
637 _dbus_timeout_list_free (timeout_list);
643 _dbus_connection_get_next_client_serial (DBusConnection *connection)
647 serial = connection->client_serial++;
649 if (connection->client_serial < 0)
650 connection->client_serial = 1;
656 * Used to notify a connection when a DBusMessageHandler is
657 * destroyed, so the connection can drop any reference
658 * to the handler. This is a private function, but still
659 * takes the connection lock. Don't call it with the lock held.
661 * @todo needs to check in pending_replies too.
663 * @param connection the connection
664 * @param handler the handler
667 _dbus_connection_handler_destroyed_locked (DBusConnection *connection,
668 DBusMessageHandler *handler)
673 dbus_mutex_lock (connection->mutex);
675 _dbus_hash_iter_init (connection->handler_table, &iter);
676 while (_dbus_hash_iter_next (&iter))
678 DBusMessageHandler *h = _dbus_hash_iter_get_value (&iter);
681 _dbus_hash_iter_remove_entry (&iter);
684 link = _dbus_list_get_first_link (&connection->filter_list);
687 DBusMessageHandler *h = link->data;
688 DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
691 _dbus_list_remove_link (&connection->filter_list,
696 dbus_mutex_unlock (connection->mutex);
700 * Adds the counter used to count the number of open connections.
701 * Increments the counter by one, and saves it to be decremented
702 * again when this connection is finalized.
704 * @param connection a #DBusConnection
705 * @param counter counter that tracks number of connections
708 _dbus_connection_set_connection_counter (DBusConnection *connection,
709 DBusCounter *counter)
711 _dbus_assert (connection->connection_counter == NULL);
713 connection->connection_counter = counter;
714 _dbus_counter_ref (connection->connection_counter);
715 _dbus_counter_adjust (connection->connection_counter, 1);
721 * @addtogroup DBusConnection
727 * Opens a new connection to a remote address.
729 * @todo specify what the address parameter is. Right now
730 * it's just the name of a UNIX domain socket. It should be
731 * something more complex that encodes which transport to use.
733 * If the open fails, the function returns #NULL, and provides
734 * a reason for the failure in the result parameter. Pass
735 * #NULL for the result parameter if you aren't interested
736 * in the reason for failure.
738 * @param address the address.
739 * @param result address where a result code can be returned.
740 * @returns new connection, or #NULL on failure.
743 dbus_connection_open (const char *address,
744 DBusResultCode *result)
746 DBusConnection *connection;
747 DBusTransport *transport;
749 transport = _dbus_transport_open (address, result);
750 if (transport == NULL)
753 connection = _dbus_connection_new_for_transport (transport);
755 _dbus_transport_unref (transport);
757 if (connection == NULL)
759 dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
767 * Increments the reference count of a DBusConnection.
769 * @param connection the connection.
772 dbus_connection_ref (DBusConnection *connection)
774 dbus_mutex_lock (connection->mutex);
775 _dbus_assert (connection->refcount > 0);
777 connection->refcount += 1;
778 dbus_mutex_unlock (connection->mutex);
782 * Increments the reference count of a DBusConnection.
783 * Requires that the caller already holds the connection lock.
785 * @param connection the connection.
788 _dbus_connection_ref_unlocked (DBusConnection *connection)
790 _dbus_assert (connection->refcount > 0);
791 connection->refcount += 1;
795 /* This is run without the mutex held, but after the last reference
796 * to the connection has been dropped we should have no thread-related
800 _dbus_connection_last_unref (DBusConnection *connection)
805 /* You have to disconnect the connection before unref:ing it. Otherwise
806 * you won't get the disconnected message.
808 _dbus_assert (!_dbus_transport_get_is_connected (connection->transport));
810 if (connection->connection_counter != NULL)
812 /* subtract ourselves from the counter */
813 _dbus_counter_adjust (connection->connection_counter, - 1);
814 _dbus_counter_unref (connection->connection_counter);
815 connection->connection_counter = NULL;
818 _dbus_watch_list_free (connection->watches);
819 connection->watches = NULL;
821 _dbus_timeout_list_free (connection->timeouts);
822 connection->timeouts = NULL;
824 /* calls out to application code... */
825 _dbus_data_slot_list_free (&connection->slot_list);
827 _dbus_hash_iter_init (connection->handler_table, &iter);
828 while (_dbus_hash_iter_next (&iter))
830 DBusMessageHandler *h = _dbus_hash_iter_get_value (&iter);
832 _dbus_message_handler_remove_connection (h, connection);
835 link = _dbus_list_get_first_link (&connection->filter_list);
838 DBusMessageHandler *h = link->data;
839 DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
841 _dbus_message_handler_remove_connection (h, connection);
846 _dbus_hash_table_unref (connection->handler_table);
847 connection->handler_table = NULL;
849 _dbus_hash_table_unref (connection->pending_replies);
850 connection->pending_replies = NULL;
852 _dbus_list_clear (&connection->filter_list);
854 _dbus_list_foreach (&connection->outgoing_messages,
855 (DBusForeachFunction) dbus_message_unref,
857 _dbus_list_clear (&connection->outgoing_messages);
859 _dbus_list_foreach (&connection->incoming_messages,
860 (DBusForeachFunction) dbus_message_unref,
862 _dbus_list_clear (&connection->incoming_messages);
864 _dbus_transport_unref (connection->transport);
866 if (connection->disconnect_message_link)
868 DBusMessage *message = connection->disconnect_message_link->data;
869 dbus_message_unref (message);
870 _dbus_list_free_link (connection->disconnect_message_link);
873 dbus_condvar_free (connection->dispatch_cond);
874 dbus_condvar_free (connection->io_path_cond);
875 dbus_condvar_free (connection->message_returned_cond);
877 dbus_mutex_free (connection->mutex);
879 dbus_free (connection);
883 * Decrements the reference count of a DBusConnection, and finalizes
884 * it if the count reaches zero. It is a bug to drop the last reference
885 * to a connection that has not been disconnected.
887 * @param connection the connection.
890 dbus_connection_unref (DBusConnection *connection)
892 dbus_bool_t last_unref;
894 dbus_mutex_lock (connection->mutex);
896 _dbus_assert (connection != NULL);
897 _dbus_assert (connection->refcount > 0);
899 connection->refcount -= 1;
900 last_unref = (connection->refcount == 0);
902 dbus_mutex_unlock (connection->mutex);
905 _dbus_connection_last_unref (connection);
909 * Closes the connection, so no further data can be sent or received.
910 * Any further attempts to send data will result in errors. This
911 * function does not affect the connection's reference count. It's
912 * safe to disconnect a connection more than once; all calls after the
913 * first do nothing. It's impossible to "reconnect" a connection, a
914 * new connection must be created.
916 * @param connection the connection.
919 dbus_connection_disconnect (DBusConnection *connection)
921 dbus_mutex_lock (connection->mutex);
922 _dbus_transport_disconnect (connection->transport);
923 dbus_mutex_unlock (connection->mutex);
927 * Gets whether the connection is currently connected. All
928 * connections are connected when they are opened. A connection may
929 * become disconnected when the remote application closes its end, or
930 * exits; a connection may also be disconnected with
931 * dbus_connection_disconnect().
933 * @param connection the connection.
934 * @returns #TRUE if the connection is still alive.
937 dbus_connection_get_is_connected (DBusConnection *connection)
941 dbus_mutex_lock (connection->mutex);
942 res = _dbus_transport_get_is_connected (connection->transport);
943 dbus_mutex_unlock (connection->mutex);
949 * Gets whether the connection was authenticated. (Note that
950 * if the connection was authenticated then disconnected,
951 * this function still returns #TRUE)
953 * @param connection the connection
954 * @returns #TRUE if the connection was ever authenticated
957 dbus_connection_get_is_authenticated (DBusConnection *connection)
961 dbus_mutex_lock (connection->mutex);
962 res = _dbus_transport_get_is_authenticated (connection->transport);
963 dbus_mutex_unlock (connection->mutex);
969 * Preallocates resources needed to send a message, allowing the message
970 * to be sent without the possibility of memory allocation failure.
971 * Allows apps to create a future guarantee that they can send
972 * a message regardless of memory shortages.
974 * @param connection the connection we're preallocating for.
975 * @returns the preallocated resources, or #NULL
977 DBusPreallocatedSend*
978 dbus_connection_preallocate_send (DBusConnection *connection)
980 /* we store "connection" in the link just to enforce via
981 * assertion that preallocated links are only used
982 * with the connection they were created for.
984 return (DBusPreallocatedSend*) _dbus_list_alloc_link (connection);
988 * Frees preallocated message-sending resources from
989 * dbus_connection_preallocate_send(). Should only
990 * be called if the preallocated resources are not used
993 * @param connection the connection
994 * @param preallocated the resources
997 dbus_connection_free_preallocated_send (DBusConnection *connection,
998 DBusPreallocatedSend *preallocated)
1000 DBusList *link = (DBusList*) preallocated;
1001 _dbus_assert (link->data == connection);
1002 _dbus_list_free_link (link);
1006 * Sends a message using preallocated resources. This function cannot fail.
1007 * It works identically to dbus_connection_send() in other respects.
1008 * Preallocated resources comes from dbus_connection_preallocate_send().
1009 * This function "consumes" the preallocated resources, they need not
1010 * be freed separately.
1012 * @param connection the connection
1013 * @param preallocated the preallocated resources
1014 * @param message the message to send
1015 * @param client_serial return location for client serial assigned to the message
1018 dbus_connection_send_preallocated (DBusConnection *connection,
1019 DBusPreallocatedSend *preallocated,
1020 DBusMessage *message,
1021 dbus_int32_t *client_serial)
1023 DBusList *link = (DBusList*) preallocated;
1024 dbus_int32_t serial;
1026 _dbus_assert (link->data == connection);
1027 _dbus_assert (dbus_message_get_name (message) != NULL);
1029 dbus_mutex_lock (connection->mutex);
1031 link->data = message;
1032 _dbus_list_prepend_link (&connection->outgoing_messages,
1035 dbus_message_ref (message);
1036 connection->n_outgoing += 1;
1038 _dbus_verbose ("Message %p (%s) added to outgoing queue, %d pending to send\n",
1040 dbus_message_get_name (message),
1041 connection->n_outgoing);
1043 if (dbus_message_get_serial (message) == -1)
1045 serial = _dbus_connection_get_next_client_serial (connection);
1046 _dbus_message_set_serial (message, serial);
1050 *client_serial = dbus_message_get_serial (message);
1052 _dbus_message_lock (message);
1054 if (connection->n_outgoing == 1)
1055 _dbus_transport_messages_pending (connection->transport,
1056 connection->n_outgoing);
1058 _dbus_connection_wakeup_mainloop (connection);
1060 dbus_mutex_unlock (connection->mutex);
1064 * Adds a message to the outgoing message queue. Does not block to
1065 * write the message to the network; that happens asynchronously. To
1066 * force the message to be written, call dbus_connection_flush().
1067 * Because this only queues the message, the only reason it can
1068 * fail is lack of memory. Even if the connection is disconnected,
1069 * no error will be returned.
1071 * If the function fails, it returns #FALSE and returns the
1072 * reason for failure via the result parameter.
1073 * The result parameter can be #NULL if you aren't interested
1074 * in the reason for the failure.
1076 * @param connection the connection.
1077 * @param message the message to write.
1078 * @param client_serial return location for client serial.
1079 * @returns #TRUE on success.
1082 dbus_connection_send (DBusConnection *connection,
1083 DBusMessage *message,
1084 dbus_int32_t *client_serial)
1086 DBusPreallocatedSend *preallocated;
1088 preallocated = dbus_connection_preallocate_send (connection);
1089 if (preallocated == NULL)
1095 dbus_connection_send_preallocated (connection, preallocated, message, client_serial);
1101 reply_handler_timeout (void *data)
1103 DBusConnection *connection;
1104 ReplyHandlerData *reply_handler_data = data;
1106 connection = reply_handler_data->connection;
1108 dbus_mutex_lock (connection->mutex);
1109 if (reply_handler_data->timeout_link)
1111 _dbus_connection_queue_synthesized_message_link (connection,
1112 reply_handler_data->timeout_link);
1113 reply_handler_data->timeout_link = NULL;
1116 _dbus_connection_remove_timeout (connection,
1117 reply_handler_data->timeout);
1118 reply_handler_data->timeout_added = FALSE;
1120 dbus_mutex_unlock (connection->mutex);
1124 reply_handler_data_free (ReplyHandlerData *data)
1129 if (data->timeout_added)
1130 _dbus_connection_remove_timeout_locked (data->connection,
1133 if (data->connection_added)
1134 _dbus_message_handler_remove_connection (data->handler,
1137 if (data->timeout_link)
1139 dbus_message_unref ((DBusMessage *)data->timeout_link->data);
1140 _dbus_list_free_link (data->timeout_link);
1143 dbus_message_handler_unref (data->handler);
1149 * Queues a message to send, as with dbus_connection_send_message(),
1150 * but also sets up a DBusMessageHandler to receive a reply to the
1151 * message. If no reply is received in the given timeout_milliseconds,
1152 * expires the pending reply and sends the DBusMessageHandler a
1153 * synthetic error reply (generated in-process, not by the remote
1154 * application) indicating that a timeout occurred.
1156 * Reply handlers see their replies after message filters see them,
1157 * but before message handlers added with
1158 * dbus_connection_register_handler() see them, regardless of the
1159 * reply message's name. Reply handlers are only handed a single
1160 * message as a reply, after one reply has been seen the handler is
1161 * removed. If a filter filters out the reply before the handler sees
1162 * it, the reply is immediately timed out and a timeout error reply is
1163 * generated. If a filter removes the timeout error reply then the
1164 * reply handler will never be called. Filters should not do this.
1166 * If #NULL is passed for the reply_handler, the timeout reply will
1167 * still be generated and placed into the message queue, but no
1168 * specific message handler will receive the reply.
1170 * If -1 is passed for the timeout, a sane default timeout is used. -1
1171 * is typically the best value for the timeout for this reason, unless
1172 * you want a very short or very long timeout. There is no way to
1173 * avoid a timeout entirely, other than passing INT_MAX for the
1174 * timeout to postpone it indefinitely.
1176 * @param connection the connection
1177 * @param message the message to send
1178 * @param reply_handler message handler expecting the reply, or #NULL
1179 * @param timeout_milliseconds timeout in milliseconds or -1 for default
1180 * @returns #TRUE if the message is successfully queued, #FALSE if no memory.
1184 dbus_connection_send_with_reply (DBusConnection *connection,
1185 DBusMessage *message,
1186 DBusMessageHandler *reply_handler,
1187 int timeout_milliseconds)
1189 DBusTimeout *timeout;
1190 ReplyHandlerData *data;
1192 DBusList *reply_link;
1193 dbus_int32_t serial = -1;
1195 if (timeout_milliseconds == -1)
1196 timeout_milliseconds = DEFAULT_TIMEOUT_VALUE;
1198 data = dbus_new0 (ReplyHandlerData, 1);
1203 timeout = _dbus_timeout_new (timeout_milliseconds, reply_handler_timeout,
1208 reply_handler_data_free (data);
1212 dbus_mutex_lock (connection->mutex);
1215 if (!_dbus_connection_add_timeout (connection, timeout))
1217 reply_handler_data_free (data);
1218 _dbus_timeout_unref (timeout);
1219 dbus_mutex_unlock (connection->mutex);
1223 /* The connection now owns the reference to the timeout. */
1224 _dbus_timeout_unref (timeout);
1226 data->timeout_added = TRUE;
1227 data->timeout = timeout;
1228 data->connection = connection;
1230 if (!_dbus_message_handler_add_connection (reply_handler, connection))
1232 dbus_mutex_unlock (connection->mutex);
1233 reply_handler_data_free (data);
1236 data->connection_added = TRUE;
1238 /* Assign a serial to the message */
1239 if (dbus_message_get_serial (message) == -1)
1241 serial = _dbus_connection_get_next_client_serial (connection);
1242 _dbus_message_set_serial (message, serial);
1245 data->handler = reply_handler;
1246 data->serial = serial;
1248 dbus_message_handler_ref (reply_handler);
1250 reply = dbus_message_new_error_reply (message, DBUS_ERROR_NO_REPLY,
1251 "No reply within specified time");
1254 dbus_mutex_unlock (connection->mutex);
1255 reply_handler_data_free (data);
1259 reply_link = _dbus_list_alloc_link (reply);
1262 dbus_mutex_unlock (connection->mutex);
1263 dbus_message_unref (reply);
1264 reply_handler_data_free (data);
1268 data->timeout_link = reply_link;
1270 /* Insert the serial in the pending replies hash. */
1271 if (!_dbus_hash_table_insert_int (connection->pending_replies, serial, data))
1273 dbus_mutex_unlock (connection->mutex);
1274 reply_handler_data_free (data);
1278 dbus_mutex_unlock (connection->mutex);
1280 if (!dbus_connection_send (connection, message, NULL))
1282 /* This will free the handler data too */
1283 _dbus_hash_table_remove_int (connection->pending_replies, serial);
1291 * Sends a message and blocks a certain time period while waiting for a reply.
1292 * This function does not dispatch any message handlers until the main loop
1293 * has been reached. This function is used to do non-reentrant "method calls."
1294 * If a reply is received, it is returned, and removed from the incoming
1295 * message queue. If it is not received, #NULL is returned and the
1296 * error is set to #DBUS_ERROR_NO_REPLY. If something else goes
1297 * wrong, result is set to whatever is appropriate, such as
1298 * #DBUS_ERROR_NO_MEMORY or #DBUS_ERROR_DISCONNECTED.
1300 * @todo could use performance improvements (it keeps scanning
1301 * the whole message queue for example) and has thread issues,
1302 * see comments in source
1304 * @param connection the connection
1305 * @param message the message to send
1306 * @param timeout_milliseconds timeout in milliseconds or -1 for default
1307 * @param error return location for error message
1308 * @returns the message that is the reply or #NULL with an error code if the
1312 dbus_connection_send_with_reply_and_block (DBusConnection *connection,
1313 DBusMessage *message,
1314 int timeout_milliseconds,
1317 dbus_int32_t client_serial;
1319 long start_tv_sec, start_tv_usec;
1320 long end_tv_sec, end_tv_usec;
1321 long tv_sec, tv_usec;
1323 if (timeout_milliseconds == -1)
1324 timeout_milliseconds = DEFAULT_TIMEOUT_VALUE;
1326 /* it would probably seem logical to pass in _DBUS_INT_MAX
1327 * for infinite timeout, but then math below would get
1328 * all overflow-prone, so smack that down.
1330 if (timeout_milliseconds > _DBUS_ONE_HOUR_IN_MILLISECONDS * 6)
1331 timeout_milliseconds = _DBUS_ONE_HOUR_IN_MILLISECONDS * 6;
1333 if (!dbus_connection_send (connection, message, &client_serial))
1335 _DBUS_SET_OOM (error);
1341 /* Flush message queue */
1342 dbus_connection_flush (connection);
1344 dbus_mutex_lock (connection->mutex);
1346 _dbus_get_current_time (&start_tv_sec, &start_tv_usec);
1347 end_tv_sec = start_tv_sec + timeout_milliseconds / 1000;
1348 end_tv_usec = start_tv_usec + (timeout_milliseconds % 1000) * 1000;
1349 end_tv_sec += end_tv_usec / _DBUS_USEC_PER_SECOND;
1350 end_tv_usec = end_tv_usec % _DBUS_USEC_PER_SECOND;
1352 _dbus_verbose ("will block %d milliseconds from %ld sec %ld usec to %ld sec %ld usec\n",
1353 timeout_milliseconds,
1354 start_tv_sec, start_tv_usec,
1355 end_tv_sec, end_tv_usec);
1357 /* Now we wait... */
1358 /* THREAD TODO: This is busted. What if a dispatch_message or pop_message
1359 * gets the message before we do?
1363 _dbus_connection_do_iteration (connection,
1364 DBUS_ITERATION_DO_READING |
1365 DBUS_ITERATION_BLOCK,
1366 timeout_milliseconds);
1368 /* Check if we've gotten a reply */
1369 link = _dbus_list_get_first_link (&connection->incoming_messages);
1371 while (link != NULL)
1373 DBusMessage *reply = link->data;
1375 if (dbus_message_get_reply_serial (reply) == client_serial)
1377 _dbus_list_remove_link (&connection->incoming_messages, link);
1378 dbus_message_ref (reply);
1380 dbus_mutex_unlock (connection->mutex);
1383 link = _dbus_list_get_next_link (&connection->incoming_messages, link);
1386 _dbus_get_current_time (&tv_sec, &tv_usec);
1388 if (tv_sec < start_tv_sec)
1389 ; /* clock set backward, bail out */
1390 else if (connection->disconnect_message_link == NULL)
1391 ; /* we're disconnected, bail out */
1392 else if (tv_sec < end_tv_sec ||
1393 (tv_sec == end_tv_sec && tv_usec < end_tv_usec))
1395 timeout_milliseconds = (end_tv_sec - tv_sec) * 1000 +
1396 (end_tv_usec - tv_usec) / 1000;
1397 _dbus_verbose ("%d milliseconds remain\n", timeout_milliseconds);
1398 _dbus_assert (timeout_milliseconds > 0);
1400 goto block_again; /* not expired yet */
1403 if (dbus_connection_get_is_connected (connection))
1404 dbus_set_error (error, DBUS_ERROR_NO_REPLY, "Message did not receive a reply");
1406 dbus_set_error (error, DBUS_ERROR_DISCONNECTED, "Disconnected prior to receiving a reply");
1408 dbus_mutex_unlock (connection->mutex);
1414 * Blocks until the outgoing message queue is empty.
1416 * @param connection the connection.
1419 dbus_connection_flush (DBusConnection *connection)
1421 /* We have to specify DBUS_ITERATION_DO_READING here
1422 * because otherwise we could have two apps deadlock
1423 * if they are both doing a flush(), and the kernel
1427 dbus_mutex_lock (connection->mutex);
1428 while (connection->n_outgoing > 0)
1429 _dbus_connection_do_iteration (connection,
1430 DBUS_ITERATION_DO_READING |
1431 DBUS_ITERATION_DO_WRITING |
1432 DBUS_ITERATION_BLOCK,
1434 dbus_mutex_unlock (connection->mutex);
1438 * Gets the number of messages in the incoming message queue.
1440 * @param connection the connection.
1441 * @returns the number of messages in the queue.
1444 dbus_connection_get_n_messages (DBusConnection *connection)
1448 dbus_mutex_lock (connection->mutex);
1449 res = connection->n_incoming;
1450 dbus_mutex_unlock (connection->mutex);
1455 /* Call with mutex held. Will drop it while waiting and re-acquire
1459 _dbus_connection_wait_for_borrowed (DBusConnection *connection)
1461 _dbus_assert (connection->message_borrowed != NULL);
1463 while (connection->message_borrowed != NULL)
1464 dbus_condvar_wait (connection->message_returned_cond, connection->mutex);
1468 * Returns the first-received message from the incoming message queue,
1469 * leaving it in the queue. If the queue is empty, returns #NULL.
1471 * The caller does not own a reference to the returned message, and must
1472 * either return it using dbus_connection_return_message or keep it after
1473 * calling dbus_connection_steal_borrowed_message. No one can get at the
1474 * message while its borrowed, so return it as quickly as possible and
1475 * don't keep a reference to it after returning it. If you need to keep
1476 * the message, make a copy of it.
1478 * @param connection the connection.
1479 * @returns next message in the incoming queue.
1482 dbus_connection_borrow_message (DBusConnection *connection)
1484 DBusMessage *message;
1486 dbus_mutex_lock (connection->mutex);
1488 if (connection->message_borrowed != NULL)
1489 _dbus_connection_wait_for_borrowed (connection);
1491 message = _dbus_list_get_first (&connection->incoming_messages);
1494 connection->message_borrowed = message;
1496 dbus_mutex_unlock (connection->mutex);
1504 dbus_connection_return_message (DBusConnection *connection,
1505 DBusMessage *message)
1507 dbus_mutex_lock (connection->mutex);
1509 _dbus_assert (message == connection->message_borrowed);
1511 connection->message_borrowed = NULL;
1512 dbus_condvar_wake_all (connection->message_returned_cond);
1514 dbus_mutex_unlock (connection->mutex);
1521 dbus_connection_steal_borrowed_message (DBusConnection *connection,
1522 DBusMessage *message)
1524 DBusMessage *pop_message;
1526 dbus_mutex_lock (connection->mutex);
1528 _dbus_assert (message == connection->message_borrowed);
1530 pop_message = _dbus_list_pop_first (&connection->incoming_messages);
1531 _dbus_assert (message == pop_message);
1533 connection->n_incoming -= 1;
1535 _dbus_verbose ("Incoming message %p stolen from queue, %d incoming\n",
1536 message, connection->n_incoming);
1538 connection->message_borrowed = NULL;
1539 dbus_condvar_wake_all (connection->message_returned_cond);
1541 dbus_mutex_unlock (connection->mutex);
1545 /* See dbus_connection_pop_message, but requires the caller to own
1546 * the lock before calling. May drop the lock while running.
1549 _dbus_connection_pop_message_unlocked (DBusConnection *connection)
1551 if (connection->message_borrowed != NULL)
1552 _dbus_connection_wait_for_borrowed (connection);
1554 if (connection->n_incoming > 0)
1556 DBusMessage *message;
1558 message = _dbus_list_pop_first (&connection->incoming_messages);
1559 connection->n_incoming -= 1;
1561 _dbus_verbose ("Incoming message %p removed from queue, %d incoming\n",
1562 message, connection->n_incoming);
1572 * Returns the first-received message from the incoming message queue,
1573 * removing it from the queue. The caller owns a reference to the
1574 * returned message. If the queue is empty, returns #NULL.
1576 * @param connection the connection.
1577 * @returns next message in the incoming queue.
1580 dbus_connection_pop_message (DBusConnection *connection)
1582 DBusMessage *message;
1583 dbus_mutex_lock (connection->mutex);
1585 message = _dbus_connection_pop_message_unlocked (connection);
1587 dbus_mutex_unlock (connection->mutex);
1593 * Acquire the dispatcher. This must be done before dispatching
1594 * messages in order to guarantee the right order of
1595 * message delivery. May sleep and drop the connection mutex
1596 * while waiting for the dispatcher.
1598 * @param connection the connection.
1601 _dbus_connection_acquire_dispatch (DBusConnection *connection)
1603 if (connection->dispatch_acquired)
1604 dbus_condvar_wait (connection->dispatch_cond, connection->mutex);
1605 _dbus_assert (!connection->dispatch_acquired);
1607 connection->dispatch_acquired = TRUE;
1611 * Release the dispatcher when you're done with it. Only call
1612 * after you've acquired the dispatcher. Wakes up at most one
1613 * thread currently waiting to acquire the dispatcher.
1615 * @param connection the connection.
1618 _dbus_connection_release_dispatch (DBusConnection *connection)
1620 _dbus_assert (connection->dispatch_acquired);
1622 connection->dispatch_acquired = FALSE;
1623 dbus_condvar_wake_one (connection->dispatch_cond);
1627 _dbus_connection_failed_pop (DBusConnection *connection,
1628 DBusList *message_link)
1630 _dbus_list_prepend_link (&connection->incoming_messages,
1632 connection->n_incoming += 1;
1636 * Pops the first-received message from the current incoming message
1637 * queue, runs any handlers for it, then unrefs the message.
1639 * @param connection the connection
1640 * @returns #TRUE if the queue is not empty after dispatch
1643 dbus_connection_dispatch_message (DBusConnection *connection)
1645 DBusMessageHandler *handler;
1646 DBusMessage *message;
1647 DBusList *link, *filter_list_copy, *message_link;
1648 DBusHandlerResult result;
1649 ReplyHandlerData *reply_handler_data;
1651 dbus_int32_t reply_serial;
1653 /* Preallocate link so we can put the message back on failure */
1654 message_link = _dbus_list_alloc_link (NULL);
1655 if (message_link == NULL)
1658 dbus_mutex_lock (connection->mutex);
1660 /* We need to ref the connection since the callback could potentially
1661 * drop the last ref to it */
1662 _dbus_connection_ref_unlocked (connection);
1664 _dbus_connection_acquire_dispatch (connection);
1666 /* This call may drop the lock during the execution (if waiting for
1667 * borrowed messages to be returned) but the order of message
1668 * dispatch if several threads call dispatch_message is still
1669 * protected by the lock, since only one will get the lock, and that
1670 * one will finish the message dispatching
1672 message = _dbus_connection_pop_message_unlocked (connection);
1673 if (message == NULL)
1675 _dbus_connection_release_dispatch (connection);
1676 dbus_mutex_unlock (connection->mutex);
1677 dbus_connection_unref (connection);
1681 message_link->data = message;
1683 result = DBUS_HANDLER_RESULT_ALLOW_MORE_HANDLERS;
1685 reply_serial = dbus_message_get_reply_serial (message);
1686 reply_handler_data = _dbus_hash_table_lookup_int (connection->pending_replies,
1689 if (!_dbus_list_copy (&connection->filter_list, &filter_list_copy))
1691 _dbus_connection_release_dispatch (connection);
1692 dbus_mutex_unlock (connection->mutex);
1693 _dbus_connection_failed_pop (connection, message_link);
1694 dbus_connection_unref (connection);
1698 _dbus_list_foreach (&filter_list_copy,
1699 (DBusForeachFunction)dbus_message_handler_ref,
1702 /* We're still protected from dispatch_message reentrancy here
1703 * since we acquired the dispatcher
1705 dbus_mutex_unlock (connection->mutex);
1707 link = _dbus_list_get_first_link (&filter_list_copy);
1708 while (link != NULL)
1710 DBusMessageHandler *handler = link->data;
1711 DBusList *next = _dbus_list_get_next_link (&filter_list_copy, link);
1713 result = _dbus_message_handler_handle_message (handler, connection,
1716 if (result == DBUS_HANDLER_RESULT_REMOVE_MESSAGE)
1722 _dbus_list_foreach (&filter_list_copy,
1723 (DBusForeachFunction)dbus_message_handler_unref,
1725 _dbus_list_clear (&filter_list_copy);
1727 dbus_mutex_lock (connection->mutex);
1729 /* Did a reply we were waiting on get filtered? */
1730 if (reply_handler_data && result == DBUS_HANDLER_RESULT_REMOVE_MESSAGE)
1732 /* Queue the timeout immediately! */
1733 if (reply_handler_data->timeout_link)
1735 _dbus_connection_queue_synthesized_message_link (connection,
1736 reply_handler_data->timeout_link);
1737 reply_handler_data->timeout_link = NULL;
1741 /* We already queued the timeout? Then it was filtered! */
1742 _dbus_warn ("The timeout error with reply serial %d was filtered, so the reply handler will never be called.\n", reply_serial);
1746 if (result == DBUS_HANDLER_RESULT_REMOVE_MESSAGE)
1749 if (reply_handler_data)
1751 dbus_mutex_unlock (connection->mutex);
1752 result = _dbus_message_handler_handle_message (reply_handler_data->handler,
1753 connection, message);
1754 reply_handler_data_free (reply_handler_data);
1755 dbus_mutex_lock (connection->mutex);
1759 name = dbus_message_get_name (message);
1762 handler = _dbus_hash_table_lookup_string (connection->handler_table,
1764 if (handler != NULL)
1766 /* We're still protected from dispatch_message reentrancy here
1767 * since we acquired the dispatcher */
1768 dbus_mutex_unlock (connection->mutex);
1769 result = _dbus_message_handler_handle_message (handler, connection,
1771 dbus_mutex_lock (connection->mutex);
1772 if (result == DBUS_HANDLER_RESULT_REMOVE_MESSAGE)
1778 _dbus_connection_release_dispatch (connection);
1779 dbus_mutex_unlock (connection->mutex);
1780 _dbus_list_free_link (message_link);
1781 dbus_connection_unref (connection);
1782 dbus_message_unref (message);
1784 return connection->n_incoming > 0;
1788 * Sets the watch functions for the connection. These functions are
1789 * responsible for making the application's main loop aware of file
1790 * descriptors that need to be monitored for events, using select() or
1791 * poll(). When using Qt, typically the DBusAddWatchFunction would
1792 * create a QSocketNotifier. When using GLib, the DBusAddWatchFunction
1793 * could call g_io_add_watch(), or could be used as part of a more
1794 * elaborate GSource.
1796 * The DBusWatch can be queried for the file descriptor to watch using
1797 * dbus_watch_get_fd(), and for the events to watch for using
1798 * dbus_watch_get_flags(). The flags returned by
1799 * dbus_watch_get_flags() will only contain DBUS_WATCH_READABLE and
1800 * DBUS_WATCH_WRITABLE, never DBUS_WATCH_HANGUP or DBUS_WATCH_ERROR;
1801 * all watches implicitly include a watch for hangups, errors, and
1802 * other exceptional conditions.
1804 * Once a file descriptor becomes readable or writable, or an exception
1805 * occurs, dbus_connection_handle_watch() should be called to
1806 * notify the connection of the file descriptor's condition.
1808 * dbus_connection_handle_watch() cannot be called during the
1809 * DBusAddWatchFunction, as the connection will not be ready to handle
1812 * It is not allowed to reference a DBusWatch after it has been passed
1813 * to remove_function.
1815 * If #FALSE is returned due to lack of memory, the failure may be due
1816 * to a #FALSE return from the new add_function. If so, the
1817 * add_function may have been called successfully one or more times,
1818 * but the remove_function will also have been called to remove any
1819 * successful adds. i.e. if #FALSE is returned the net result
1820 * should be that dbus_connection_set_watch_functions() has no effect,
1821 * but the add_function and remove_function may have been called.
1823 * @param connection the connection.
1824 * @param add_function function to begin monitoring a new descriptor.
1825 * @param remove_function function to stop monitoring a descriptor.
1826 * @param data data to pass to add_function and remove_function.
1827 * @param free_data_function function to be called to free the data.
1828 * @returns #FALSE on failure (no memory)
1831 dbus_connection_set_watch_functions (DBusConnection *connection,
1832 DBusAddWatchFunction add_function,
1833 DBusRemoveWatchFunction remove_function,
1835 DBusFreeFunction free_data_function)
1839 dbus_mutex_lock (connection->mutex);
1840 /* ref connection for slightly better reentrancy */
1841 _dbus_connection_ref_unlocked (connection);
1843 retval = _dbus_watch_list_set_functions (connection->watches,
1844 add_function, remove_function,
1845 data, free_data_function);
1847 dbus_mutex_unlock (connection->mutex);
1848 /* drop our paranoid refcount */
1849 dbus_connection_unref (connection);
1855 * Sets the timeout functions for the connection. These functions are
1856 * responsible for making the application's main loop aware of timeouts.
1857 * When using Qt, typically the DBusAddTimeoutFunction would create a
1858 * QTimer. When using GLib, the DBusAddTimeoutFunction would call
1861 * The DBusTimeout can be queried for the timer interval using
1862 * dbus_timeout_get_interval.
1864 * Once a timeout occurs, dbus_timeout_handle should be called to invoke
1865 * the timeout's callback, and the timeout should be automatically
1866 * removed. i.e. timeouts are one-shot.
1868 * @param connection the connection.
1869 * @param add_function function to add a timeout.
1870 * @param remove_function function to remove a timeout.
1871 * @param data data to pass to add_function and remove_function.
1872 * @param free_data_function function to be called to free the data.
1873 * @returns #FALSE on failure (no memory)
1876 dbus_connection_set_timeout_functions (DBusConnection *connection,
1877 DBusAddTimeoutFunction add_function,
1878 DBusRemoveTimeoutFunction remove_function,
1880 DBusFreeFunction free_data_function)
1884 dbus_mutex_lock (connection->mutex);
1885 /* ref connection for slightly better reentrancy */
1886 _dbus_connection_ref_unlocked (connection);
1888 retval = _dbus_timeout_list_set_functions (connection->timeouts,
1889 add_function, remove_function,
1890 data, free_data_function);
1892 dbus_mutex_unlock (connection->mutex);
1893 /* drop our paranoid refcount */
1894 dbus_connection_unref (connection);
1900 * Sets the mainloop wakeup function for the connection. Thi function is
1901 * responsible for waking up the main loop (if its sleeping) when some some
1902 * change has happened to the connection that the mainloop needs to reconsiders
1903 * (e.g. a message has been queued for writing).
1904 * When using Qt, this typically results in a call to QEventLoop::wakeUp().
1905 * When using GLib, it would call g_main_context_wakeup().
1908 * @param connection the connection.
1909 * @param wakeup_main_function function to wake up the mainloop
1910 * @param data data to pass wakeup_main_function
1911 * @param free_data_function function to be called to free the data.
1914 dbus_connection_set_wakeup_main_function (DBusConnection *connection,
1915 DBusWakeupMainFunction wakeup_main_function,
1917 DBusFreeFunction free_data_function)
1920 DBusFreeFunction old_free_data;
1922 dbus_mutex_lock (connection->mutex);
1923 old_data = connection->wakeup_main_data;
1924 old_free_data = connection->free_wakeup_main_data;
1926 connection->wakeup_main_function = wakeup_main_function;
1927 connection->wakeup_main_data = data;
1928 connection->free_wakeup_main_data = free_data_function;
1930 dbus_mutex_unlock (connection->mutex);
1932 /* Callback outside the lock */
1934 (*old_free_data) (old_data);
1938 * Called to notify the connection when a previously-added watch
1939 * is ready for reading or writing, or has an exception such
1942 * @param connection the connection.
1943 * @param watch the watch.
1944 * @param condition the current condition of the file descriptors being watched.
1947 dbus_connection_handle_watch (DBusConnection *connection,
1949 unsigned int condition)
1951 dbus_mutex_lock (connection->mutex);
1952 _dbus_connection_acquire_io_path (connection, -1);
1953 _dbus_transport_handle_watch (connection->transport,
1955 _dbus_connection_release_io_path (connection);
1956 dbus_mutex_unlock (connection->mutex);
1960 * Adds a message filter. Filters are handlers that are run on
1961 * all incoming messages, prior to the normal handlers
1962 * registered with dbus_connection_register_handler().
1963 * Filters are run in the order that they were added.
1964 * The same handler can be added as a filter more than once, in
1965 * which case it will be run more than once.
1966 * Filters added during a filter callback won't be run on the
1967 * message being processed.
1969 * @param connection the connection
1970 * @param handler the handler
1971 * @returns #TRUE on success, #FALSE if not enough memory.
1974 dbus_connection_add_filter (DBusConnection *connection,
1975 DBusMessageHandler *handler)
1977 dbus_mutex_lock (connection->mutex);
1978 if (!_dbus_message_handler_add_connection (handler, connection))
1980 dbus_mutex_unlock (connection->mutex);
1984 if (!_dbus_list_append (&connection->filter_list,
1987 _dbus_message_handler_remove_connection (handler, connection);
1988 dbus_mutex_unlock (connection->mutex);
1992 dbus_mutex_unlock (connection->mutex);
1997 * Removes a previously-added message filter. It is a programming
1998 * error to call this function for a handler that has not
1999 * been added as a filter. If the given handler was added
2000 * more than once, only one instance of it will be removed
2001 * (the most recently-added instance).
2003 * @param connection the connection
2004 * @param handler the handler to remove
2008 dbus_connection_remove_filter (DBusConnection *connection,
2009 DBusMessageHandler *handler)
2011 dbus_mutex_lock (connection->mutex);
2012 if (!_dbus_list_remove_last (&connection->filter_list, handler))
2014 _dbus_warn ("Tried to remove a DBusConnection filter that had not been added\n");
2015 dbus_mutex_unlock (connection->mutex);
2019 _dbus_message_handler_remove_connection (handler, connection);
2021 dbus_mutex_unlock (connection->mutex);
2025 * Registers a handler for a list of message names. A single handler
2026 * can be registered for any number of message names, but each message
2027 * name can only have one handler at a time. It's not allowed to call
2028 * this function with the name of a message that already has a
2029 * handler. If the function returns #FALSE, the handlers were not
2030 * registered due to lack of memory.
2032 * @todo the messages_to_handle arg may be more convenient if it's a
2033 * single string instead of an array. Though right now MessageHandler
2034 * is sort of designed to say be associated with an entire object with
2035 * multiple methods, that's why for example the connection only
2036 * weakrefs it. So maybe the "manual" API should be different.
2038 * @param connection the connection
2039 * @param handler the handler
2040 * @param messages_to_handle the messages to handle
2041 * @param n_messages the number of message names in messages_to_handle
2042 * @returns #TRUE on success, #FALSE if no memory or another handler already exists
2046 dbus_connection_register_handler (DBusConnection *connection,
2047 DBusMessageHandler *handler,
2048 const char **messages_to_handle,
2053 dbus_mutex_lock (connection->mutex);
2055 while (i < n_messages)
2060 key = _dbus_strdup (messages_to_handle[i]);
2064 if (!_dbus_hash_iter_lookup (connection->handler_table,
2072 if (_dbus_hash_iter_get_value (&iter) != NULL)
2074 _dbus_warn ("Bug in application: attempted to register a second handler for %s\n",
2075 messages_to_handle[i]);
2076 dbus_free (key); /* won't have replaced the old key with the new one */
2080 if (!_dbus_message_handler_add_connection (handler, connection))
2082 _dbus_hash_iter_remove_entry (&iter);
2083 /* key has freed on nuking the entry */
2087 _dbus_hash_iter_set_value (&iter, handler);
2092 dbus_mutex_unlock (connection->mutex);
2096 /* unregister everything registered so far,
2097 * so we don't fail partially
2099 dbus_connection_unregister_handler (connection,
2104 dbus_mutex_unlock (connection->mutex);
2109 * Unregisters a handler for a list of message names. The handlers
2110 * must have been previously registered.
2112 * @param connection the connection
2113 * @param handler the handler
2114 * @param messages_to_handle the messages to handle
2115 * @param n_messages the number of message names in messages_to_handle
2119 dbus_connection_unregister_handler (DBusConnection *connection,
2120 DBusMessageHandler *handler,
2121 const char **messages_to_handle,
2126 dbus_mutex_lock (connection->mutex);
2128 while (i < n_messages)
2132 if (!_dbus_hash_iter_lookup (connection->handler_table,
2133 (char*) messages_to_handle[i], FALSE,
2136 _dbus_warn ("Bug in application: attempted to unregister handler for %s which was not registered\n",
2137 messages_to_handle[i]);
2139 else if (_dbus_hash_iter_get_value (&iter) != handler)
2141 _dbus_warn ("Bug in application: attempted to unregister handler for %s which was registered by a different handler\n",
2142 messages_to_handle[i]);
2146 _dbus_hash_iter_remove_entry (&iter);
2147 _dbus_message_handler_remove_connection (handler, connection);
2153 dbus_mutex_unlock (connection->mutex);
2156 static DBusDataSlotAllocator slot_allocator;
2159 * Initialize the mutex used for #DBusConnection data
2160 * slot reservations.
2162 * @returns the mutex
2165 _dbus_connection_slots_init_lock (void)
2167 if (!_dbus_data_slot_allocator_init (&slot_allocator))
2170 return slot_allocator.lock;
2174 * Allocates an integer ID to be used for storing application-specific
2175 * data on any DBusConnection. The allocated ID may then be used
2176 * with dbus_connection_set_data() and dbus_connection_get_data().
2177 * If allocation fails, -1 is returned. Again, the allocated
2178 * slot is global, i.e. all DBusConnection objects will
2179 * have a slot with the given integer ID reserved.
2181 * @returns -1 on failure, otherwise the data slot ID
2184 dbus_connection_allocate_data_slot (void)
2186 return _dbus_data_slot_allocator_alloc (&slot_allocator);
2190 * Deallocates a global ID for connection data slots.
2191 * dbus_connection_get_data() and dbus_connection_set_data()
2192 * may no longer be used with this slot.
2193 * Existing data stored on existing DBusConnection objects
2194 * will be freed when the connection is finalized,
2195 * but may not be retrieved (and may only be replaced
2196 * if someone else reallocates the slot).
2198 * @param slot the slot to deallocate
2201 dbus_connection_free_data_slot (int slot)
2203 _dbus_data_slot_allocator_free (&slot_allocator, slot);
2207 * Stores a pointer on a DBusConnection, along
2208 * with an optional function to be used for freeing
2209 * the data when the data is set again, or when
2210 * the connection is finalized. The slot number
2211 * must have been allocated with dbus_connection_allocate_data_slot().
2213 * @param connection the connection
2214 * @param slot the slot number
2215 * @param data the data to store
2216 * @param free_data_func finalizer function for the data
2217 * @returns #TRUE if there was enough memory to store the data
2220 dbus_connection_set_data (DBusConnection *connection,
2223 DBusFreeFunction free_data_func)
2225 DBusFreeFunction old_free_func;
2229 dbus_mutex_lock (connection->mutex);
2231 retval = _dbus_data_slot_list_set (&slot_allocator,
2232 &connection->slot_list,
2233 slot, data, free_data_func,
2234 &old_free_func, &old_data);
2236 dbus_mutex_unlock (connection->mutex);
2240 /* Do the actual free outside the connection lock */
2242 (* old_free_func) (old_data);
2249 * Retrieves data previously set with dbus_connection_set_data().
2250 * The slot must still be allocated (must not have been freed).
2252 * @param connection the connection
2253 * @param slot the slot to get data from
2254 * @returns the data, or #NULL if not found
2257 dbus_connection_get_data (DBusConnection *connection,
2262 dbus_mutex_lock (connection->mutex);
2264 res = _dbus_data_slot_list_get (&slot_allocator,
2265 &connection->slot_list,
2268 dbus_mutex_unlock (connection->mutex);
2274 * This function sets a global flag for whether dbus_connection_new()
2275 * will set SIGPIPE behavior to SIG_IGN.
2277 * @param will_modify_sigpipe #TRUE to allow sigpipe to be set to SIG_IGN
2280 dbus_connection_set_change_sigpipe (dbus_bool_t will_modify_sigpipe)
2282 _dbus_modify_sigpipe = will_modify_sigpipe;
2286 * Specifies the maximum size message this connection is allowed to
2287 * receive. Larger messages will result in disconnecting the
2290 * @param connection a #DBusConnection
2291 * @param size maximum message size the connection can receive, in bytes
2294 dbus_connection_set_max_message_size (DBusConnection *connection,
2297 dbus_mutex_lock (connection->mutex);
2298 _dbus_transport_set_max_message_size (connection->transport,
2300 dbus_mutex_unlock (connection->mutex);
2304 * Gets the value set by dbus_connection_set_max_message_size().
2306 * @param connection the connection
2307 * @returns the max size of a single message
2310 dbus_connection_get_max_message_size (DBusConnection *connection)
2313 dbus_mutex_lock (connection->mutex);
2314 res = _dbus_transport_get_max_message_size (connection->transport);
2315 dbus_mutex_unlock (connection->mutex);
2320 * Sets the maximum total number of bytes that can be used for all messages
2321 * received on this connection. Messages count toward the maximum until
2322 * they are finalized. When the maximum is reached, the connection will
2323 * not read more data until some messages are finalized.
2325 * The semantics of the maximum are: if outstanding messages are
2326 * already above the maximum, additional messages will not be read.
2327 * The semantics are not: if the next message would cause us to exceed
2328 * the maximum, we don't read it. The reason is that we don't know the
2329 * size of a message until after we read it.
2331 * Thus, the max live messages size can actually be exceeded
2332 * by up to the maximum size of a single message.
2334 * Also, if we read say 1024 bytes off the wire in a single read(),
2335 * and that contains a half-dozen small messages, we may exceed the
2336 * size max by that amount. But this should be inconsequential.
2338 * @param connection the connection
2339 * @param size the maximum size in bytes of all outstanding messages
2342 dbus_connection_set_max_live_messages_size (DBusConnection *connection,
2345 dbus_mutex_lock (connection->mutex);
2346 _dbus_transport_set_max_live_messages_size (connection->transport,
2348 dbus_mutex_unlock (connection->mutex);
2352 * Gets the value set by dbus_connection_set_max_live_messages_size().
2354 * @param connection the connection
2355 * @returns the max size of all live messages
2358 dbus_connection_get_max_live_messages_size (DBusConnection *connection)
2361 dbus_mutex_lock (connection->mutex);
2362 res = _dbus_transport_get_max_live_messages_size (connection->transport);
2363 dbus_mutex_unlock (connection->mutex);