Bug 19567 - Make marshaling code usable without DBusConnection
[dbus4win.git] / dbus / dbus-connection.c
blob947c0afee75b8323a9f15345f514f5f7f55a21ac
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-connection.c DBusConnection object
4 * Copyright (C) 2002-2006 Red Hat Inc.
6 * Licensed under the Academic Free License version 2.1
7 *
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 <config.h>
25 #include "dbus-shared.h"
26 #include "dbus-connection.h"
27 #include "dbus-list.h"
28 #include "dbus-timeout.h"
29 #include "dbus-transport.h"
30 #include "dbus-watch.h"
31 #include "dbus-connection-internal.h"
32 #include "dbus-pending-call-internal.h"
33 #include "dbus-list.h"
34 #include "dbus-hash.h"
35 #include "dbus-message-internal.h"
36 #include "dbus-threads.h"
37 #include "dbus-protocol.h"
38 #include "dbus-dataslot.h"
39 #include "dbus-string.h"
40 #include "dbus-pending-call.h"
41 #include "dbus-object-tree.h"
42 #include "dbus-threads-internal.h"
43 #include "dbus-bus.h"
45 #ifdef DBUS_DISABLE_CHECKS
46 #define TOOK_LOCK_CHECK(connection)
47 #define RELEASING_LOCK_CHECK(connection)
48 #define HAVE_LOCK_CHECK(connection)
49 #else
50 #define TOOK_LOCK_CHECK(connection) do { \
51 _dbus_assert (!(connection)->have_connection_lock); \
52 (connection)->have_connection_lock = TRUE; \
53 } while (0)
54 #define RELEASING_LOCK_CHECK(connection) do { \
55 _dbus_assert ((connection)->have_connection_lock); \
56 (connection)->have_connection_lock = FALSE; \
57 } while (0)
58 #define HAVE_LOCK_CHECK(connection) _dbus_assert ((connection)->have_connection_lock)
59 /* A "DO_NOT_HAVE_LOCK_CHECK" is impossible since we need the lock to check the flag */
60 #endif
62 #define TRACE_LOCKS 1
64 #define CONNECTION_LOCK(connection) do { \
65 if (TRACE_LOCKS) { _dbus_verbose (" LOCK: %s\n", _DBUS_FUNCTION_NAME); } \
66 _dbus_mutex_lock ((connection)->mutex); \
67 TOOK_LOCK_CHECK (connection); \
68 } while (0)
70 #define CONNECTION_UNLOCK(connection) do { \
71 if (TRACE_LOCKS) { _dbus_verbose (" UNLOCK: %s\n", _DBUS_FUNCTION_NAME); } \
72 RELEASING_LOCK_CHECK (connection); \
73 _dbus_mutex_unlock ((connection)->mutex); \
74 } while (0)
76 #define DISPATCH_STATUS_NAME(s) \
77 ((s) == DBUS_DISPATCH_COMPLETE ? "complete" : \
78 (s) == DBUS_DISPATCH_DATA_REMAINS ? "data remains" : \
79 (s) == DBUS_DISPATCH_NEED_MEMORY ? "need memory" : \
80 "???")
82 /**
83 * @defgroup DBusConnection DBusConnection
84 * @ingroup DBus
85 * @brief Connection to another application
87 * A DBusConnection represents a connection to another
88 * application. Messages can be sent and received via this connection.
89 * The other application may be a message bus; for convenience, the
90 * function dbus_bus_get() is provided to automatically open a
91 * connection to the well-known message buses.
93 * In brief a DBusConnection is a message queue associated with some
94 * message transport mechanism such as a socket. The connection
95 * maintains a queue of incoming messages and a queue of outgoing
96 * messages.
98 * Several functions use the following terms:
99 * <ul>
100 * <li><b>read</b> means to fill the incoming message queue by reading from the socket</li>
101 * <li><b>write</b> means to drain the outgoing queue by writing to the socket</li>
102 * <li><b>dispatch</b> means to drain the incoming queue by invoking application-provided message handlers</li>
103 * </ul>
105 * The function dbus_connection_read_write_dispatch() for example does all
106 * three of these things, offering a simple alternative to a main loop.
108 * In an application with a main loop, the read/write/dispatch
109 * operations are usually separate.
111 * The connection provides #DBusWatch and #DBusTimeout objects to
112 * the main loop. These are used to know when reading, writing, or
113 * dispatching should be performed.
115 * Incoming messages are processed
116 * by calling dbus_connection_dispatch(). dbus_connection_dispatch()
117 * runs any handlers registered for the topmost message in the message
118 * queue, then discards the message, then returns.
120 * dbus_connection_get_dispatch_status() indicates whether
121 * messages are currently in the queue that need dispatching.
122 * dbus_connection_set_dispatch_status_function() allows
123 * you to set a function to be used to monitor the dispatch status.
125 * If you're using GLib or Qt add-on libraries for D-Bus, there are
126 * special convenience APIs in those libraries that hide
127 * all the details of dispatch and watch/timeout monitoring.
128 * For example, dbus_connection_setup_with_g_main().
130 * If you aren't using these add-on libraries, but want to process
131 * messages asynchronously, you must manually call
132 * dbus_connection_set_dispatch_status_function(),
133 * dbus_connection_set_watch_functions(),
134 * dbus_connection_set_timeout_functions() providing appropriate
135 * functions to integrate the connection with your application's main
136 * loop. This can be tricky to get right; main loops are not simple.
138 * If you don't need to be asynchronous, you can ignore #DBusWatch,
139 * #DBusTimeout, and dbus_connection_dispatch(). Instead,
140 * dbus_connection_read_write_dispatch() can be used.
142 * Or, in <em>very</em> simple applications,
143 * dbus_connection_pop_message() may be all you need, allowing you to
144 * avoid setting up any handler functions (see
145 * dbus_connection_add_filter(),
146 * dbus_connection_register_object_path() for more on handlers).
148 * When you use dbus_connection_send() or one of its variants to send
149 * a message, the message is added to the outgoing queue. It's
150 * actually written to the network later; either in
151 * dbus_watch_handle() invoked by your main loop, or in
152 * dbus_connection_flush() which blocks until it can write out the
153 * entire outgoing queue. The GLib/Qt add-on libraries again
154 * handle the details here for you by setting up watch functions.
156 * When a connection is disconnected, you are guaranteed to get a
157 * signal "Disconnected" from the interface
158 * #DBUS_INTERFACE_LOCAL, path
159 * #DBUS_PATH_LOCAL.
161 * You may not drop the last reference to a #DBusConnection
162 * until that connection has been disconnected.
164 * You may dispatch the unprocessed incoming message queue even if the
165 * connection is disconnected. However, "Disconnected" will always be
166 * the last message in the queue (obviously no messages are received
167 * after disconnection).
169 * After calling dbus_threads_init(), #DBusConnection has thread
170 * locks and drops them when invoking user callbacks, so in general is
171 * transparently threadsafe. However, #DBusMessage does NOT have
172 * thread locks; you must not send the same message to multiple
173 * #DBusConnection if those connections will be used from different threads,
174 * for example.
176 * Also, if you dispatch or pop messages from multiple threads, it
177 * may work in the sense that it won't crash, but it's tough to imagine
178 * sane results; it will be completely unpredictable which messages
179 * go to which threads.
181 * It's recommended to dispatch from a single thread.
183 * The most useful function to call from multiple threads at once
184 * is dbus_connection_send_with_reply_and_block(). That is,
185 * multiple threads can make method calls at the same time.
187 * If you aren't using threads, you can use a main loop and
188 * dbus_pending_call_set_notify() to achieve a similar result.
192 * @defgroup DBusConnectionInternals DBusConnection implementation details
193 * @ingroup DBusInternals
194 * @brief Implementation details of DBusConnection
196 * @{
200 * Internal struct representing a message filter function
202 typedef struct DBusMessageFilter DBusMessageFilter;
205 * Internal struct representing a message filter function
207 struct DBusMessageFilter
209 DBusAtomic refcount; /**< Reference count */
210 DBusHandleMessageFunction function; /**< Function to call to filter */
211 void *user_data; /**< User data for the function */
212 DBusFreeFunction free_user_data_function; /**< Function to free the user data */
217 * Internals of DBusPreallocatedSend
219 struct DBusPreallocatedSend
221 DBusConnection *connection; /**< Connection we'd send the message to */
222 DBusList *queue_link; /**< Preallocated link in the queue */
223 DBusList *counter_link; /**< Preallocated link in the resource counter */
226 static dbus_bool_t _dbus_modify_sigpipe = TRUE;
229 * Implementation details of DBusConnection. All fields are private.
231 struct DBusConnection
233 DBusAtomic refcount; /**< Reference count. */
235 DBusMutex *mutex; /**< Lock on the entire DBusConnection */
237 DBusMutex *dispatch_mutex; /**< Protects dispatch_acquired */
238 DBusCondVar *dispatch_cond; /**< Notify when dispatch_acquired is available */
239 DBusMutex *io_path_mutex; /**< Protects io_path_acquired */
240 DBusCondVar *io_path_cond; /**< Notify when io_path_acquired is available */
242 DBusList *outgoing_messages; /**< Queue of messages we need to send, send the end of the list first. */
243 DBusList *incoming_messages; /**< Queue of messages we have received, end of the list received most recently. */
245 DBusMessage *message_borrowed; /**< Filled in if the first incoming message has been borrowed;
246 * dispatch_acquired will be set by the borrower
249 int n_outgoing; /**< Length of outgoing queue. */
250 int n_incoming; /**< Length of incoming queue. */
252 DBusCounter *outgoing_counter; /**< Counts size of outgoing messages. */
254 DBusTransport *transport; /**< Object that sends/receives messages over network. */
255 DBusWatchList *watches; /**< Stores active watches. */
256 DBusTimeoutList *timeouts; /**< Stores active timeouts. */
258 DBusList *filter_list; /**< List of filters. */
260 DBusDataSlotList slot_list; /**< Data stored by allocated integer ID */
262 DBusHashTable *pending_replies; /**< Hash of message serials to #DBusPendingCall. */
264 dbus_uint32_t client_serial; /**< Client serial. Increments each time a message is sent */
265 DBusList *disconnect_message_link; /**< Preallocated list node for queueing the disconnection message */
267 DBusWakeupMainFunction wakeup_main_function; /**< Function to wake up the mainloop */
268 void *wakeup_main_data; /**< Application data for wakeup_main_function */
269 DBusFreeFunction free_wakeup_main_data; /**< free wakeup_main_data */
271 DBusDispatchStatusFunction dispatch_status_function; /**< Function on dispatch status changes */
272 void *dispatch_status_data; /**< Application data for dispatch_status_function */
273 DBusFreeFunction free_dispatch_status_data; /**< free dispatch_status_data */
275 DBusDispatchStatus last_dispatch_status; /**< The last dispatch status we reported to the application. */
277 DBusList *link_cache; /**< A cache of linked list links to prevent contention
278 * for the global linked list mempool lock
280 DBusObjectTree *objects; /**< Object path handlers registered with this connection */
282 char *server_guid; /**< GUID of server if we are in shared_connections, #NULL if server GUID is unknown or connection is private */
284 /* These two MUST be bools and not bitfields, because they are protected by a separate lock
285 * from connection->mutex and all bitfields in a word have to be read/written together.
286 * So you can't have a different lock for different bitfields in the same word.
288 dbus_bool_t dispatch_acquired; /**< Someone has dispatch path (can drain incoming queue) */
289 dbus_bool_t io_path_acquired; /**< Someone has transport io path (can use the transport to read/write messages) */
291 unsigned int shareable : 1; /**< #TRUE if libdbus owns a reference to the connection and can return it from dbus_connection_open() more than once */
293 unsigned int exit_on_disconnect : 1; /**< If #TRUE, exit after handling disconnect signal */
295 unsigned int route_peer_messages : 1; /**< If #TRUE, if org.freedesktop.DBus.Peer messages have a bus name, don't handle them automatically */
297 unsigned int disconnected_message_arrived : 1; /**< We popped or are dispatching the disconnected message.
298 * if the disconnect_message_link is NULL then we queued it, but
299 * this flag is whether it got to the head of the queue.
301 unsigned int disconnected_message_processed : 1; /**< We did our default handling of the disconnected message,
302 * such as closing the connection.
305 #ifndef DBUS_DISABLE_CHECKS
306 unsigned int have_connection_lock : 1; /**< Used to check locking */
307 #endif
309 #ifndef DBUS_DISABLE_CHECKS
310 int generation; /**< _dbus_current_generation that should correspond to this connection */
311 #endif
314 static DBusDispatchStatus _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection);
315 static void _dbus_connection_update_dispatch_status_and_unlock (DBusConnection *connection,
316 DBusDispatchStatus new_status);
317 static void _dbus_connection_last_unref (DBusConnection *connection);
318 static void _dbus_connection_acquire_dispatch (DBusConnection *connection);
319 static void _dbus_connection_release_dispatch (DBusConnection *connection);
320 static DBusDispatchStatus _dbus_connection_flush_unlocked (DBusConnection *connection);
321 static void _dbus_connection_close_possibly_shared_and_unlock (DBusConnection *connection);
322 static dbus_bool_t _dbus_connection_get_is_connected_unlocked (DBusConnection *connection);
324 static DBusMessageFilter *
325 _dbus_message_filter_ref (DBusMessageFilter *filter)
327 _dbus_assert (filter->refcount.value > 0);
328 _dbus_atomic_inc (&filter->refcount);
330 return filter;
333 static void
334 _dbus_message_filter_unref (DBusMessageFilter *filter)
336 _dbus_assert (filter->refcount.value > 0);
338 if (_dbus_atomic_dec (&filter->refcount) == 1)
340 if (filter->free_user_data_function)
341 (* filter->free_user_data_function) (filter->user_data);
343 dbus_free (filter);
348 * Acquires the connection lock.
350 * @param connection the connection.
352 void
353 _dbus_connection_lock (DBusConnection *connection)
355 CONNECTION_LOCK (connection);
359 * Releases the connection lock.
361 * @param connection the connection.
363 void
364 _dbus_connection_unlock (DBusConnection *connection)
366 CONNECTION_UNLOCK (connection);
370 * Wakes up the main loop if it is sleeping
371 * Needed if we're e.g. queueing outgoing messages
372 * on a thread while the mainloop sleeps.
374 * @param connection the connection.
376 static void
377 _dbus_connection_wakeup_mainloop (DBusConnection *connection)
379 if (connection->wakeup_main_function)
380 (*connection->wakeup_main_function) (connection->wakeup_main_data);
383 #ifdef DBUS_BUILD_TESTS
384 /* For now this function isn't used */
386 * Adds a message to the incoming message queue, returning #FALSE
387 * if there's insufficient memory to queue the message.
388 * Does not take over refcount of the message.
390 * @param connection the connection.
391 * @param message the message to queue.
392 * @returns #TRUE on success.
394 dbus_bool_t
395 _dbus_connection_queue_received_message (DBusConnection *connection,
396 DBusMessage *message)
398 DBusList *link;
400 link = _dbus_list_alloc_link (message);
401 if (link == NULL)
402 return FALSE;
404 dbus_message_ref (message);
405 _dbus_connection_queue_received_message_link (connection, link);
407 return TRUE;
411 * Gets the locks so we can examine them
413 * @param connection the connection.
414 * @param mutex_loc return for the location of the main mutex pointer
415 * @param dispatch_mutex_loc return location of the dispatch mutex pointer
416 * @param io_path_mutex_loc return location of the io_path mutex pointer
417 * @param dispatch_cond_loc return location of the dispatch conditional
418 * variable pointer
419 * @param io_path_cond_loc return location of the io_path conditional
420 * variable pointer
422 void
423 _dbus_connection_test_get_locks (DBusConnection *connection,
424 DBusMutex **mutex_loc,
425 DBusMutex **dispatch_mutex_loc,
426 DBusMutex **io_path_mutex_loc,
427 DBusCondVar **dispatch_cond_loc,
428 DBusCondVar **io_path_cond_loc)
430 *mutex_loc = connection->mutex;
431 *dispatch_mutex_loc = connection->dispatch_mutex;
432 *io_path_mutex_loc = connection->io_path_mutex;
433 *dispatch_cond_loc = connection->dispatch_cond;
434 *io_path_cond_loc = connection->io_path_cond;
436 #endif
439 * Adds a message-containing list link to the incoming message queue,
440 * taking ownership of the link and the message's current refcount.
441 * Cannot fail due to lack of memory.
443 * @param connection the connection.
444 * @param link the message link to queue.
446 void
447 _dbus_connection_queue_received_message_link (DBusConnection *connection,
448 DBusList *link)
450 DBusPendingCall *pending;
451 dbus_uint32_t reply_serial;
452 DBusMessage *message;
454 _dbus_assert (_dbus_transport_get_is_authenticated (connection->transport));
456 _dbus_list_append_link (&connection->incoming_messages,
457 link);
458 message = link->data;
460 /* If this is a reply we're waiting on, remove timeout for it */
461 reply_serial = dbus_message_get_reply_serial (message);
462 if (reply_serial != 0)
464 pending = _dbus_hash_table_lookup_int (connection->pending_replies,
465 reply_serial);
466 if (pending != NULL)
468 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
469 _dbus_connection_remove_timeout_unlocked (connection,
470 _dbus_pending_call_get_timeout_unlocked (pending));
472 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
478 connection->n_incoming += 1;
480 _dbus_connection_wakeup_mainloop (connection);
482 _dbus_verbose ("Message %p (%d %s %s %s '%s' reply to %u) added to incoming queue %p, %d incoming\n",
483 message,
484 dbus_message_get_type (message),
485 dbus_message_get_path (message) ?
486 dbus_message_get_path (message) :
487 "no path",
488 dbus_message_get_interface (message) ?
489 dbus_message_get_interface (message) :
490 "no interface",
491 dbus_message_get_member (message) ?
492 dbus_message_get_member (message) :
493 "no member",
494 dbus_message_get_signature (message),
495 dbus_message_get_reply_serial (message),
496 connection,
497 connection->n_incoming);}
500 * Adds a link + message to the incoming message queue.
501 * Can't fail. Takes ownership of both link and message.
503 * @param connection the connection.
504 * @param link the list node and message to queue.
507 void
508 _dbus_connection_queue_synthesized_message_link (DBusConnection *connection,
509 DBusList *link)
511 HAVE_LOCK_CHECK (connection);
513 _dbus_list_append_link (&connection->incoming_messages, link);
515 connection->n_incoming += 1;
517 _dbus_connection_wakeup_mainloop (connection);
519 _dbus_verbose ("Synthesized message %p added to incoming queue %p, %d incoming\n",
520 link->data, connection, connection->n_incoming);
525 * Checks whether there are messages in the outgoing message queue.
526 * Called with connection lock held.
528 * @param connection the connection.
529 * @returns #TRUE if the outgoing queue is non-empty.
531 dbus_bool_t
532 _dbus_connection_has_messages_to_send_unlocked (DBusConnection *connection)
534 HAVE_LOCK_CHECK (connection);
535 return connection->outgoing_messages != NULL;
539 * Checks whether there are messages in the outgoing message queue.
540 * Use dbus_connection_flush() to block until all outgoing
541 * messages have been written to the underlying transport
542 * (such as a socket).
544 * @param connection the connection.
545 * @returns #TRUE if the outgoing queue is non-empty.
547 dbus_bool_t
548 dbus_connection_has_messages_to_send (DBusConnection *connection)
550 dbus_bool_t v;
552 _dbus_return_val_if_fail (connection != NULL, FALSE);
554 CONNECTION_LOCK (connection);
555 v = _dbus_connection_has_messages_to_send_unlocked (connection);
556 CONNECTION_UNLOCK (connection);
558 return v;
562 * Gets the next outgoing message. The message remains in the
563 * queue, and the caller does not own a reference to it.
565 * @param connection the connection.
566 * @returns the message to be sent.
568 DBusMessage*
569 _dbus_connection_get_message_to_send (DBusConnection *connection)
571 HAVE_LOCK_CHECK (connection);
573 return _dbus_list_get_last (&connection->outgoing_messages);
577 * Notifies the connection that a message has been sent, so the
578 * message can be removed from the outgoing queue.
579 * Called with the connection lock held.
581 * @param connection the connection.
582 * @param message the message that was sent.
584 void
585 _dbus_connection_message_sent (DBusConnection *connection,
586 DBusMessage *message)
588 DBusList *link;
590 HAVE_LOCK_CHECK (connection);
592 /* This can be called before we even complete authentication, since
593 * it's called on disconnect to clean up the outgoing queue.
594 * It's also called as we successfully send each message.
597 link = _dbus_list_get_last_link (&connection->outgoing_messages);
598 _dbus_assert (link != NULL);
599 _dbus_assert (link->data == message);
601 /* Save this link in the link cache */
602 _dbus_list_unlink (&connection->outgoing_messages,
603 link);
604 _dbus_list_prepend_link (&connection->link_cache, link);
606 connection->n_outgoing -= 1;
608 _dbus_verbose ("Message %p (%d %s %s %s '%s') removed from outgoing queue %p, %d left to send\n",
609 message,
610 dbus_message_get_type (message),
611 dbus_message_get_path (message) ?
612 dbus_message_get_path (message) :
613 "no path",
614 dbus_message_get_interface (message) ?
615 dbus_message_get_interface (message) :
616 "no interface",
617 dbus_message_get_member (message) ?
618 dbus_message_get_member (message) :
619 "no member",
620 dbus_message_get_signature (message),
621 connection, connection->n_outgoing);
623 /* Save this link in the link cache also */
624 _dbus_message_remove_size_counter (message, connection->outgoing_counter,
625 &link);
626 _dbus_list_prepend_link (&connection->link_cache, link);
628 dbus_message_unref (message);
631 /** Function to be called in protected_change_watch() with refcount held */
632 typedef dbus_bool_t (* DBusWatchAddFunction) (DBusWatchList *list,
633 DBusWatch *watch);
634 /** Function to be called in protected_change_watch() with refcount held */
635 typedef void (* DBusWatchRemoveFunction) (DBusWatchList *list,
636 DBusWatch *watch);
637 /** Function to be called in protected_change_watch() with refcount held */
638 typedef void (* DBusWatchToggleFunction) (DBusWatchList *list,
639 DBusWatch *watch,
640 dbus_bool_t enabled);
642 static dbus_bool_t
643 protected_change_watch (DBusConnection *connection,
644 DBusWatch *watch,
645 DBusWatchAddFunction add_function,
646 DBusWatchRemoveFunction remove_function,
647 DBusWatchToggleFunction toggle_function,
648 dbus_bool_t enabled)
650 DBusWatchList *watches;
651 dbus_bool_t retval;
653 HAVE_LOCK_CHECK (connection);
655 /* This isn't really safe or reasonable; a better pattern is the "do everything, then
656 * drop lock and call out" one; but it has to be propagated up through all callers
659 watches = connection->watches;
660 if (watches)
662 connection->watches = NULL;
663 _dbus_connection_ref_unlocked (connection);
664 CONNECTION_UNLOCK (connection);
666 if (add_function)
667 retval = (* add_function) (watches, watch);
668 else if (remove_function)
670 retval = TRUE;
671 (* remove_function) (watches, watch);
673 else
675 retval = TRUE;
676 (* toggle_function) (watches, watch, enabled);
679 CONNECTION_LOCK (connection);
680 connection->watches = watches;
681 _dbus_connection_unref_unlocked (connection);
683 return retval;
685 else
686 return FALSE;
691 * Adds a watch using the connection's DBusAddWatchFunction if
692 * available. Otherwise records the watch to be added when said
693 * function is available. Also re-adds the watch if the
694 * DBusAddWatchFunction changes. May fail due to lack of memory.
695 * Connection lock should be held when calling this.
697 * @param connection the connection.
698 * @param watch the watch to add.
699 * @returns #TRUE on success.
701 dbus_bool_t
702 _dbus_connection_add_watch_unlocked (DBusConnection *connection,
703 DBusWatch *watch)
705 return protected_change_watch (connection, watch,
706 _dbus_watch_list_add_watch,
707 NULL, NULL, FALSE);
711 * Removes a watch using the connection's DBusRemoveWatchFunction
712 * if available. It's an error to call this function on a watch
713 * that was not previously added.
714 * Connection lock should be held when calling this.
716 * @param connection the connection.
717 * @param watch the watch to remove.
719 void
720 _dbus_connection_remove_watch_unlocked (DBusConnection *connection,
721 DBusWatch *watch)
723 protected_change_watch (connection, watch,
724 NULL,
725 _dbus_watch_list_remove_watch,
726 NULL, FALSE);
730 * Toggles a watch and notifies app via connection's
731 * DBusWatchToggledFunction if available. It's an error to call this
732 * function on a watch that was not previously added.
733 * Connection lock should be held when calling this.
735 * @param connection the connection.
736 * @param watch the watch to toggle.
737 * @param enabled whether to enable or disable
739 void
740 _dbus_connection_toggle_watch_unlocked (DBusConnection *connection,
741 DBusWatch *watch,
742 dbus_bool_t enabled)
744 _dbus_assert (watch != NULL);
746 protected_change_watch (connection, watch,
747 NULL, NULL,
748 _dbus_watch_list_toggle_watch,
749 enabled);
752 /** Function to be called in protected_change_timeout() with refcount held */
753 typedef dbus_bool_t (* DBusTimeoutAddFunction) (DBusTimeoutList *list,
754 DBusTimeout *timeout);
755 /** Function to be called in protected_change_timeout() with refcount held */
756 typedef void (* DBusTimeoutRemoveFunction) (DBusTimeoutList *list,
757 DBusTimeout *timeout);
758 /** Function to be called in protected_change_timeout() with refcount held */
759 typedef void (* DBusTimeoutToggleFunction) (DBusTimeoutList *list,
760 DBusTimeout *timeout,
761 dbus_bool_t enabled);
763 static dbus_bool_t
764 protected_change_timeout (DBusConnection *connection,
765 DBusTimeout *timeout,
766 DBusTimeoutAddFunction add_function,
767 DBusTimeoutRemoveFunction remove_function,
768 DBusTimeoutToggleFunction toggle_function,
769 dbus_bool_t enabled)
771 DBusTimeoutList *timeouts;
772 dbus_bool_t retval;
774 HAVE_LOCK_CHECK (connection);
776 /* This isn't really safe or reasonable; a better pattern is the "do everything, then
777 * drop lock and call out" one; but it has to be propagated up through all callers
780 timeouts = connection->timeouts;
781 if (timeouts)
783 connection->timeouts = NULL;
784 _dbus_connection_ref_unlocked (connection);
785 CONNECTION_UNLOCK (connection);
787 if (add_function)
788 retval = (* add_function) (timeouts, timeout);
789 else if (remove_function)
791 retval = TRUE;
792 (* remove_function) (timeouts, timeout);
794 else
796 retval = TRUE;
797 (* toggle_function) (timeouts, timeout, enabled);
800 CONNECTION_LOCK (connection);
801 connection->timeouts = timeouts;
802 _dbus_connection_unref_unlocked (connection);
804 return retval;
806 else
807 return FALSE;
811 * Adds a timeout using the connection's DBusAddTimeoutFunction if
812 * available. Otherwise records the timeout to be added when said
813 * function is available. Also re-adds the timeout if the
814 * DBusAddTimeoutFunction changes. May fail due to lack of memory.
815 * The timeout will fire repeatedly until removed.
816 * Connection lock should be held when calling this.
818 * @param connection the connection.
819 * @param timeout the timeout to add.
820 * @returns #TRUE on success.
822 dbus_bool_t
823 _dbus_connection_add_timeout_unlocked (DBusConnection *connection,
824 DBusTimeout *timeout)
826 return protected_change_timeout (connection, timeout,
827 _dbus_timeout_list_add_timeout,
828 NULL, NULL, FALSE);
832 * Removes a timeout using the connection's DBusRemoveTimeoutFunction
833 * if available. It's an error to call this function on a timeout
834 * that was not previously added.
835 * Connection lock should be held when calling this.
837 * @param connection the connection.
838 * @param timeout the timeout to remove.
840 void
841 _dbus_connection_remove_timeout_unlocked (DBusConnection *connection,
842 DBusTimeout *timeout)
844 protected_change_timeout (connection, timeout,
845 NULL,
846 _dbus_timeout_list_remove_timeout,
847 NULL, FALSE);
851 * Toggles a timeout and notifies app via connection's
852 * DBusTimeoutToggledFunction if available. It's an error to call this
853 * function on a timeout that was not previously added.
854 * Connection lock should be held when calling this.
856 * @param connection the connection.
857 * @param timeout the timeout to toggle.
858 * @param enabled whether to enable or disable
860 void
861 _dbus_connection_toggle_timeout_unlocked (DBusConnection *connection,
862 DBusTimeout *timeout,
863 dbus_bool_t enabled)
865 protected_change_timeout (connection, timeout,
866 NULL, NULL,
867 _dbus_timeout_list_toggle_timeout,
868 enabled);
871 static dbus_bool_t
872 _dbus_connection_attach_pending_call_unlocked (DBusConnection *connection,
873 DBusPendingCall *pending)
875 dbus_uint32_t reply_serial;
876 DBusTimeout *timeout;
878 HAVE_LOCK_CHECK (connection);
880 reply_serial = _dbus_pending_call_get_reply_serial_unlocked (pending);
882 _dbus_assert (reply_serial != 0);
884 timeout = _dbus_pending_call_get_timeout_unlocked (pending);
886 if (!_dbus_connection_add_timeout_unlocked (connection, timeout))
887 return FALSE;
889 if (!_dbus_hash_table_insert_int (connection->pending_replies,
890 reply_serial,
891 pending))
893 _dbus_connection_remove_timeout_unlocked (connection, timeout);
895 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
896 HAVE_LOCK_CHECK (connection);
897 return FALSE;
900 _dbus_pending_call_set_timeout_added_unlocked (pending, TRUE);
902 _dbus_pending_call_ref_unlocked (pending);
904 HAVE_LOCK_CHECK (connection);
906 return TRUE;
909 static void
910 free_pending_call_on_hash_removal (void *data)
912 DBusPendingCall *pending;
913 DBusConnection *connection;
915 if (data == NULL)
916 return;
918 pending = data;
920 connection = _dbus_pending_call_get_connection_unlocked (pending);
922 HAVE_LOCK_CHECK (connection);
924 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
926 _dbus_connection_remove_timeout_unlocked (connection,
927 _dbus_pending_call_get_timeout_unlocked (pending));
929 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
932 /* FIXME 1.0? this is sort of dangerous and undesirable to drop the lock
933 * here, but the pending call finalizer could in principle call out to
934 * application code so we pretty much have to... some larger code reorg
935 * might be needed.
937 _dbus_connection_ref_unlocked (connection);
938 _dbus_pending_call_unref_and_unlock (pending);
939 CONNECTION_LOCK (connection);
940 _dbus_connection_unref_unlocked (connection);
943 static void
944 _dbus_connection_detach_pending_call_unlocked (DBusConnection *connection,
945 DBusPendingCall *pending)
947 /* This ends up unlocking to call the pending call finalizer, which is unexpected to
948 * say the least.
950 _dbus_hash_table_remove_int (connection->pending_replies,
951 _dbus_pending_call_get_reply_serial_unlocked (pending));
954 static void
955 _dbus_connection_detach_pending_call_and_unlock (DBusConnection *connection,
956 DBusPendingCall *pending)
958 /* The idea here is to avoid finalizing the pending call
959 * with the lock held, since there's a destroy notifier
960 * in pending call that goes out to application code.
962 * There's an extra unlock inside the hash table
963 * "free pending call" function FIXME...
965 _dbus_pending_call_ref_unlocked (pending);
966 _dbus_hash_table_remove_int (connection->pending_replies,
967 _dbus_pending_call_get_reply_serial_unlocked (pending));
969 if (_dbus_pending_call_is_timeout_added_unlocked (pending))
970 _dbus_connection_remove_timeout_unlocked (connection,
971 _dbus_pending_call_get_timeout_unlocked (pending));
973 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
975 _dbus_pending_call_unref_and_unlock (pending);
979 * Removes a pending call from the connection, such that
980 * the pending reply will be ignored. May drop the last
981 * reference to the pending call.
983 * @param connection the connection
984 * @param pending the pending call
986 void
987 _dbus_connection_remove_pending_call (DBusConnection *connection,
988 DBusPendingCall *pending)
990 CONNECTION_LOCK (connection);
991 _dbus_connection_detach_pending_call_and_unlock (connection, pending);
995 * Acquire the transporter I/O path. This must be done before
996 * doing any I/O in the transporter. May sleep and drop the
997 * IO path mutex while waiting for the I/O path.
999 * @param connection the connection.
1000 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
1001 * @returns TRUE if the I/O path was acquired.
1003 static dbus_bool_t
1004 _dbus_connection_acquire_io_path (DBusConnection *connection,
1005 int timeout_milliseconds)
1007 dbus_bool_t we_acquired;
1009 HAVE_LOCK_CHECK (connection);
1011 /* We don't want the connection to vanish */
1012 _dbus_connection_ref_unlocked (connection);
1014 /* We will only touch io_path_acquired which is protected by our mutex */
1015 CONNECTION_UNLOCK (connection);
1017 _dbus_verbose ("%s locking io_path_mutex\n", _DBUS_FUNCTION_NAME);
1018 _dbus_mutex_lock (connection->io_path_mutex);
1020 _dbus_verbose ("%s start connection->io_path_acquired = %d timeout = %d\n",
1021 _DBUS_FUNCTION_NAME, connection->io_path_acquired, timeout_milliseconds);
1023 we_acquired = FALSE;
1025 if (connection->io_path_acquired)
1027 if (timeout_milliseconds != -1)
1029 _dbus_verbose ("%s waiting %d for IO path to be acquirable\n",
1030 _DBUS_FUNCTION_NAME, timeout_milliseconds);
1032 if (!_dbus_condvar_wait_timeout (connection->io_path_cond,
1033 connection->io_path_mutex,
1034 timeout_milliseconds))
1036 /* We timed out before anyone signaled. */
1037 /* (writing the loop to handle the !timedout case by
1038 * waiting longer if needed is a pain since dbus
1039 * wraps pthread_cond_timedwait to take a relative
1040 * time instead of absolute, something kind of stupid
1041 * on our part. for now it doesn't matter, we will just
1042 * end up back here eventually.)
1046 else
1048 while (connection->io_path_acquired)
1050 _dbus_verbose ("%s waiting for IO path to be acquirable\n", _DBUS_FUNCTION_NAME);
1051 _dbus_condvar_wait (connection->io_path_cond,
1052 connection->io_path_mutex);
1057 if (!connection->io_path_acquired)
1059 we_acquired = TRUE;
1060 connection->io_path_acquired = TRUE;
1063 _dbus_verbose ("%s end connection->io_path_acquired = %d we_acquired = %d\n",
1064 _DBUS_FUNCTION_NAME, connection->io_path_acquired, we_acquired);
1066 _dbus_verbose ("%s unlocking io_path_mutex\n", _DBUS_FUNCTION_NAME);
1067 _dbus_mutex_unlock (connection->io_path_mutex);
1069 CONNECTION_LOCK (connection);
1071 HAVE_LOCK_CHECK (connection);
1073 _dbus_connection_unref_unlocked (connection);
1075 return we_acquired;
1079 * Release the I/O path when you're done with it. Only call
1080 * after you've acquired the I/O. Wakes up at most one thread
1081 * currently waiting to acquire the I/O path.
1083 * @param connection the connection.
1085 static void
1086 _dbus_connection_release_io_path (DBusConnection *connection)
1088 HAVE_LOCK_CHECK (connection);
1090 _dbus_verbose ("%s locking io_path_mutex\n", _DBUS_FUNCTION_NAME);
1091 _dbus_mutex_lock (connection->io_path_mutex);
1093 _dbus_assert (connection->io_path_acquired);
1095 _dbus_verbose ("%s start connection->io_path_acquired = %d\n",
1096 _DBUS_FUNCTION_NAME, connection->io_path_acquired);
1098 connection->io_path_acquired = FALSE;
1099 _dbus_condvar_wake_one (connection->io_path_cond);
1101 _dbus_verbose ("%s unlocking io_path_mutex\n", _DBUS_FUNCTION_NAME);
1102 _dbus_mutex_unlock (connection->io_path_mutex);
1106 * Queues incoming messages and sends outgoing messages for this
1107 * connection, optionally blocking in the process. Each call to
1108 * _dbus_connection_do_iteration_unlocked() will call select() or poll() one
1109 * time and then read or write data if possible.
1111 * The purpose of this function is to be able to flush outgoing
1112 * messages or queue up incoming messages without returning
1113 * control to the application and causing reentrancy weirdness.
1115 * The flags parameter allows you to specify whether to
1116 * read incoming messages, write outgoing messages, or both,
1117 * and whether to block if no immediate action is possible.
1119 * The timeout_milliseconds parameter does nothing unless the
1120 * iteration is blocking.
1122 * If there are no outgoing messages and DBUS_ITERATION_DO_READING
1123 * wasn't specified, then it's impossible to block, even if
1124 * you specify DBUS_ITERATION_BLOCK; in that case the function
1125 * returns immediately.
1127 * Called with connection lock held.
1129 * @param connection the connection.
1130 * @param flags iteration flags.
1131 * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
1133 void
1134 _dbus_connection_do_iteration_unlocked (DBusConnection *connection,
1135 unsigned int flags,
1136 int timeout_milliseconds)
1138 _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
1140 HAVE_LOCK_CHECK (connection);
1142 if (connection->n_outgoing == 0)
1143 flags &= ~DBUS_ITERATION_DO_WRITING;
1145 if (_dbus_connection_acquire_io_path (connection,
1146 (flags & DBUS_ITERATION_BLOCK) ? timeout_milliseconds : 0))
1148 HAVE_LOCK_CHECK (connection);
1150 _dbus_transport_do_iteration (connection->transport,
1151 flags, timeout_milliseconds);
1152 _dbus_connection_release_io_path (connection);
1155 HAVE_LOCK_CHECK (connection);
1157 _dbus_verbose ("%s end\n", _DBUS_FUNCTION_NAME);
1161 * Creates a new connection for the given transport. A transport
1162 * represents a message stream that uses some concrete mechanism, such
1163 * as UNIX domain sockets. May return #NULL if insufficient
1164 * memory exists to create the connection.
1166 * @param transport the transport.
1167 * @returns the new connection, or #NULL on failure.
1169 DBusConnection*
1170 _dbus_connection_new_for_transport (DBusTransport *transport)
1172 DBusConnection *connection;
1173 DBusWatchList *watch_list;
1174 DBusTimeoutList *timeout_list;
1175 DBusHashTable *pending_replies;
1176 DBusList *disconnect_link;
1177 DBusMessage *disconnect_message;
1178 DBusCounter *outgoing_counter;
1179 DBusObjectTree *objects;
1181 watch_list = NULL;
1182 connection = NULL;
1183 pending_replies = NULL;
1184 timeout_list = NULL;
1185 disconnect_link = NULL;
1186 disconnect_message = NULL;
1187 outgoing_counter = NULL;
1188 objects = NULL;
1190 watch_list = _dbus_watch_list_new ();
1191 if (watch_list == NULL)
1192 goto error;
1194 timeout_list = _dbus_timeout_list_new ();
1195 if (timeout_list == NULL)
1196 goto error;
1198 pending_replies =
1199 _dbus_hash_table_new (DBUS_HASH_INT,
1200 NULL,
1201 (DBusFreeFunction)free_pending_call_on_hash_removal);
1202 if (pending_replies == NULL)
1203 goto error;
1205 connection = dbus_new0 (DBusConnection, 1);
1206 if (connection == NULL)
1207 goto error;
1209 _dbus_mutex_new_at_location (&connection->mutex);
1210 if (connection->mutex == NULL)
1211 goto error;
1213 _dbus_mutex_new_at_location (&connection->io_path_mutex);
1214 if (connection->io_path_mutex == NULL)
1215 goto error;
1217 _dbus_mutex_new_at_location (&connection->dispatch_mutex);
1218 if (connection->dispatch_mutex == NULL)
1219 goto error;
1221 _dbus_condvar_new_at_location (&connection->dispatch_cond);
1222 if (connection->dispatch_cond == NULL)
1223 goto error;
1225 _dbus_condvar_new_at_location (&connection->io_path_cond);
1226 if (connection->io_path_cond == NULL)
1227 goto error;
1229 disconnect_message = dbus_message_new_signal (DBUS_PATH_LOCAL,
1230 DBUS_INTERFACE_LOCAL,
1231 "Disconnected");
1233 if (disconnect_message == NULL)
1234 goto error;
1236 disconnect_link = _dbus_list_alloc_link (disconnect_message);
1237 if (disconnect_link == NULL)
1238 goto error;
1240 outgoing_counter = _dbus_counter_new ();
1241 if (outgoing_counter == NULL)
1242 goto error;
1244 objects = _dbus_object_tree_new (connection);
1245 if (objects == NULL)
1246 goto error;
1248 if (_dbus_modify_sigpipe)
1249 _dbus_disable_sigpipe ();
1251 connection->refcount.value = 1;
1252 connection->transport = transport;
1253 connection->watches = watch_list;
1254 connection->timeouts = timeout_list;
1255 connection->pending_replies = pending_replies;
1256 connection->outgoing_counter = outgoing_counter;
1257 connection->filter_list = NULL;
1258 connection->last_dispatch_status = DBUS_DISPATCH_COMPLETE; /* so we're notified first time there's data */
1259 connection->objects = objects;
1260 connection->exit_on_disconnect = FALSE;
1261 connection->shareable = FALSE;
1262 connection->route_peer_messages = FALSE;
1263 connection->disconnected_message_arrived = FALSE;
1264 connection->disconnected_message_processed = FALSE;
1266 #ifndef DBUS_DISABLE_CHECKS
1267 connection->generation = _dbus_current_generation;
1268 #endif
1270 _dbus_data_slot_list_init (&connection->slot_list);
1272 connection->client_serial = 1;
1274 connection->disconnect_message_link = disconnect_link;
1276 CONNECTION_LOCK (connection);
1278 if (!_dbus_transport_set_connection (transport, connection))
1280 CONNECTION_UNLOCK (connection);
1282 goto error;
1285 _dbus_transport_ref (transport);
1287 CONNECTION_UNLOCK (connection);
1289 return connection;
1291 error:
1292 if (disconnect_message != NULL)
1293 dbus_message_unref (disconnect_message);
1295 if (disconnect_link != NULL)
1296 _dbus_list_free_link (disconnect_link);
1298 if (connection != NULL)
1300 _dbus_condvar_free_at_location (&connection->io_path_cond);
1301 _dbus_condvar_free_at_location (&connection->dispatch_cond);
1302 _dbus_mutex_free_at_location (&connection->mutex);
1303 _dbus_mutex_free_at_location (&connection->io_path_mutex);
1304 _dbus_mutex_free_at_location (&connection->dispatch_mutex);
1305 dbus_free (connection);
1307 if (pending_replies)
1308 _dbus_hash_table_unref (pending_replies);
1310 if (watch_list)
1311 _dbus_watch_list_free (watch_list);
1313 if (timeout_list)
1314 _dbus_timeout_list_free (timeout_list);
1316 if (outgoing_counter)
1317 _dbus_counter_unref (outgoing_counter);
1319 if (objects)
1320 _dbus_object_tree_unref (objects);
1322 return NULL;
1326 * Increments the reference count of a DBusConnection.
1327 * Requires that the caller already holds the connection lock.
1329 * @param connection the connection.
1330 * @returns the connection.
1332 DBusConnection *
1333 _dbus_connection_ref_unlocked (DBusConnection *connection)
1335 _dbus_assert (connection != NULL);
1336 _dbus_assert (connection->generation == _dbus_current_generation);
1338 HAVE_LOCK_CHECK (connection);
1340 #ifdef DBUS_HAVE_ATOMIC_INT
1341 _dbus_atomic_inc (&connection->refcount);
1342 #else
1343 _dbus_assert (connection->refcount.value > 0);
1344 connection->refcount.value += 1;
1345 #endif
1347 return connection;
1351 * Decrements the reference count of a DBusConnection.
1352 * Requires that the caller already holds the connection lock.
1354 * @param connection the connection.
1356 void
1357 _dbus_connection_unref_unlocked (DBusConnection *connection)
1359 dbus_bool_t last_unref;
1361 HAVE_LOCK_CHECK (connection);
1363 _dbus_assert (connection != NULL);
1365 /* The connection lock is better than the global
1366 * lock in the atomic increment fallback
1369 #ifdef DBUS_HAVE_ATOMIC_INT
1370 last_unref = (_dbus_atomic_dec (&connection->refcount) == 1);
1371 #else
1372 _dbus_assert (connection->refcount.value > 0);
1374 connection->refcount.value -= 1;
1375 last_unref = (connection->refcount.value == 0);
1376 #if 0
1377 printf ("unref_unlocked() connection %p count = %d\n", connection, connection->refcount.value);
1378 #endif
1379 #endif
1381 if (last_unref)
1382 _dbus_connection_last_unref (connection);
1385 static dbus_uint32_t
1386 _dbus_connection_get_next_client_serial (DBusConnection *connection)
1388 dbus_uint32_t serial;
1390 serial = connection->client_serial++;
1392 if (connection->client_serial == 0)
1393 connection->client_serial = 1;
1395 return serial;
1399 * A callback for use with dbus_watch_new() to create a DBusWatch.
1401 * @todo This is basically a hack - we could delete _dbus_transport_handle_watch()
1402 * and the virtual handle_watch in DBusTransport if we got rid of it.
1403 * The reason this is some work is threading, see the _dbus_connection_handle_watch()
1404 * implementation.
1406 * @param watch the watch.
1407 * @param condition the current condition of the file descriptors being watched.
1408 * @param data must be a pointer to a #DBusConnection
1409 * @returns #FALSE if the IO condition may not have been fully handled due to lack of memory
1411 dbus_bool_t
1412 _dbus_connection_handle_watch (DBusWatch *watch,
1413 unsigned int condition,
1414 void *data)
1416 DBusConnection *connection;
1417 dbus_bool_t retval;
1418 DBusDispatchStatus status;
1420 connection = data;
1422 _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
1424 CONNECTION_LOCK (connection);
1425 _dbus_connection_acquire_io_path (connection, -1);
1426 HAVE_LOCK_CHECK (connection);
1427 retval = _dbus_transport_handle_watch (connection->transport,
1428 watch, condition);
1430 _dbus_connection_release_io_path (connection);
1432 HAVE_LOCK_CHECK (connection);
1434 _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
1436 status = _dbus_connection_get_dispatch_status_unlocked (connection);
1438 /* this calls out to user code */
1439 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1441 _dbus_verbose ("%s end\n", _DBUS_FUNCTION_NAME);
1443 return retval;
1446 _DBUS_DEFINE_GLOBAL_LOCK (shared_connections);
1447 static DBusHashTable *shared_connections = NULL;
1448 static DBusList *shared_connections_no_guid = NULL;
1450 static void
1451 close_connection_on_shutdown (DBusConnection *connection)
1453 DBusMessage *message;
1455 dbus_connection_ref (connection);
1456 _dbus_connection_close_possibly_shared (connection);
1458 /* Churn through to the Disconnected message */
1459 while ((message = dbus_connection_pop_message (connection)))
1461 dbus_message_unref (message);
1463 dbus_connection_unref (connection);
1466 static void
1467 shared_connections_shutdown (void *data)
1469 int n_entries;
1471 _DBUS_LOCK (shared_connections);
1473 /* This is a little bit unpleasant... better ideas? */
1474 while ((n_entries = _dbus_hash_table_get_n_entries (shared_connections)) > 0)
1476 DBusConnection *connection;
1477 DBusHashIter iter;
1479 _dbus_hash_iter_init (shared_connections, &iter);
1480 _dbus_hash_iter_next (&iter);
1482 connection = _dbus_hash_iter_get_value (&iter);
1484 _DBUS_UNLOCK (shared_connections);
1485 close_connection_on_shutdown (connection);
1486 _DBUS_LOCK (shared_connections);
1488 /* The connection should now be dead and not in our hash ... */
1489 _dbus_assert (_dbus_hash_table_get_n_entries (shared_connections) < n_entries);
1492 _dbus_assert (_dbus_hash_table_get_n_entries (shared_connections) == 0);
1494 _dbus_hash_table_unref (shared_connections);
1495 shared_connections = NULL;
1497 if (shared_connections_no_guid != NULL)
1499 DBusConnection *connection;
1500 connection = _dbus_list_pop_first (&shared_connections_no_guid);
1501 while (connection != NULL)
1503 _DBUS_UNLOCK (shared_connections);
1504 close_connection_on_shutdown (connection);
1505 _DBUS_LOCK (shared_connections);
1506 connection = _dbus_list_pop_first (&shared_connections_no_guid);
1510 shared_connections_no_guid = NULL;
1512 _DBUS_UNLOCK (shared_connections);
1515 static dbus_bool_t
1516 connection_lookup_shared (DBusAddressEntry *entry,
1517 DBusConnection **result)
1519 _dbus_verbose ("checking for existing connection\n");
1521 *result = NULL;
1523 _DBUS_LOCK (shared_connections);
1525 if (shared_connections == NULL)
1527 _dbus_verbose ("creating shared_connections hash table\n");
1529 shared_connections = _dbus_hash_table_new (DBUS_HASH_STRING,
1530 dbus_free,
1531 NULL);
1532 if (shared_connections == NULL)
1534 _DBUS_UNLOCK (shared_connections);
1535 return FALSE;
1538 if (!_dbus_register_shutdown_func (shared_connections_shutdown, NULL))
1540 _dbus_hash_table_unref (shared_connections);
1541 shared_connections = NULL;
1542 _DBUS_UNLOCK (shared_connections);
1543 return FALSE;
1546 _dbus_verbose (" successfully created shared_connections\n");
1548 _DBUS_UNLOCK (shared_connections);
1549 return TRUE; /* no point looking up in the hash we just made */
1551 else
1553 const char *guid;
1555 guid = dbus_address_entry_get_value (entry, "guid");
1557 if (guid != NULL)
1559 DBusConnection *connection;
1561 connection = _dbus_hash_table_lookup_string (shared_connections,
1562 guid);
1564 if (connection)
1566 /* The DBusConnection can't be finalized without taking
1567 * the shared_connections lock to remove it from the
1568 * hash. So it's safe to ref the connection here.
1569 * However, it may be disconnected if the Disconnected
1570 * message hasn't been processed yet, in which case we
1571 * want to pretend it isn't in the hash and avoid
1572 * returning it.
1574 * The idea is to avoid ever returning a disconnected connection
1575 * from dbus_connection_open(). We could just synchronously
1576 * drop our shared ref to the connection on connection disconnect,
1577 * and then assert here that the connection is connected, but
1578 * that causes reentrancy headaches.
1580 CONNECTION_LOCK (connection);
1581 if (_dbus_connection_get_is_connected_unlocked (connection))
1583 _dbus_connection_ref_unlocked (connection);
1584 *result = connection;
1585 _dbus_verbose ("looked up existing connection to server guid %s\n",
1586 guid);
1588 else
1590 _dbus_verbose ("looked up existing connection to server guid %s but it was disconnected so ignoring it\n",
1591 guid);
1593 CONNECTION_UNLOCK (connection);
1597 _DBUS_UNLOCK (shared_connections);
1598 return TRUE;
1602 static dbus_bool_t
1603 connection_record_shared_unlocked (DBusConnection *connection,
1604 const char *guid)
1606 char *guid_key;
1607 char *guid_in_connection;
1609 HAVE_LOCK_CHECK (connection);
1610 _dbus_assert (connection->server_guid == NULL);
1611 _dbus_assert (connection->shareable);
1613 /* get a hard ref on this connection, even if
1614 * we won't in fact store it in the hash, we still
1615 * need to hold a ref on it until it's disconnected.
1617 _dbus_connection_ref_unlocked (connection);
1619 if (guid == NULL)
1621 _DBUS_LOCK (shared_connections);
1623 if (!_dbus_list_prepend (&shared_connections_no_guid, connection))
1625 _DBUS_UNLOCK (shared_connections);
1626 return FALSE;
1629 _DBUS_UNLOCK (shared_connections);
1630 return TRUE; /* don't store in the hash */
1633 /* A separate copy of the key is required in the hash table, because
1634 * we don't have a lock on the connection when we are doing a hash
1635 * lookup.
1638 guid_key = _dbus_strdup (guid);
1639 if (guid_key == NULL)
1640 return FALSE;
1642 guid_in_connection = _dbus_strdup (guid);
1643 if (guid_in_connection == NULL)
1645 dbus_free (guid_key);
1646 return FALSE;
1649 _DBUS_LOCK (shared_connections);
1650 _dbus_assert (shared_connections != NULL);
1652 if (!_dbus_hash_table_insert_string (shared_connections,
1653 guid_key, connection))
1655 dbus_free (guid_key);
1656 dbus_free (guid_in_connection);
1657 _DBUS_UNLOCK (shared_connections);
1658 return FALSE;
1661 connection->server_guid = guid_in_connection;
1663 _dbus_verbose ("stored connection to %s to be shared\n",
1664 connection->server_guid);
1666 _DBUS_UNLOCK (shared_connections);
1668 _dbus_assert (connection->server_guid != NULL);
1670 return TRUE;
1673 static void
1674 connection_forget_shared_unlocked (DBusConnection *connection)
1676 HAVE_LOCK_CHECK (connection);
1678 if (!connection->shareable)
1679 return;
1681 _DBUS_LOCK (shared_connections);
1683 if (connection->server_guid != NULL)
1685 _dbus_verbose ("dropping connection to %s out of the shared table\n",
1686 connection->server_guid);
1688 if (!_dbus_hash_table_remove_string (shared_connections,
1689 connection->server_guid))
1690 _dbus_assert_not_reached ("connection was not in the shared table");
1692 dbus_free (connection->server_guid);
1693 connection->server_guid = NULL;
1695 else
1697 _dbus_list_remove (&shared_connections_no_guid, connection);
1700 _DBUS_UNLOCK (shared_connections);
1702 /* remove our reference held on all shareable connections */
1703 _dbus_connection_unref_unlocked (connection);
1706 static DBusConnection*
1707 connection_try_from_address_entry (DBusAddressEntry *entry,
1708 DBusError *error)
1710 DBusTransport *transport;
1711 DBusConnection *connection;
1713 transport = _dbus_transport_open (entry, error);
1715 if (transport == NULL)
1717 _DBUS_ASSERT_ERROR_IS_SET (error);
1718 return NULL;
1721 connection = _dbus_connection_new_for_transport (transport);
1723 _dbus_transport_unref (transport);
1725 if (connection == NULL)
1727 _DBUS_SET_OOM (error);
1728 return NULL;
1731 #ifndef DBUS_DISABLE_CHECKS
1732 _dbus_assert (!connection->have_connection_lock);
1733 #endif
1734 return connection;
1738 * If the shared parameter is true, then any existing connection will
1739 * be used (and if a new connection is created, it will be available
1740 * for use by others). If the shared parameter is false, a new
1741 * connection will always be created, and the new connection will
1742 * never be returned to other callers.
1744 * @param address the address
1745 * @param shared whether the connection is shared or private
1746 * @param error error return
1747 * @returns the connection or #NULL on error
1749 static DBusConnection*
1750 _dbus_connection_open_internal (const char *address,
1751 dbus_bool_t shared,
1752 DBusError *error)
1754 DBusConnection *connection;
1755 DBusAddressEntry **entries;
1756 DBusError tmp_error = DBUS_ERROR_INIT;
1757 DBusError first_error = DBUS_ERROR_INIT;
1758 int len, i;
1760 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1762 _dbus_verbose ("opening %s connection to: %s\n",
1763 shared ? "shared" : "private", address);
1765 if (!dbus_parse_address (address, &entries, &len, error))
1766 return NULL;
1768 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1770 connection = NULL;
1772 for (i = 0; i < len; i++)
1774 if (shared)
1776 if (!connection_lookup_shared (entries[i], &connection))
1777 _DBUS_SET_OOM (&tmp_error);
1780 if (connection == NULL)
1782 connection = connection_try_from_address_entry (entries[i],
1783 &tmp_error);
1785 if (connection != NULL && shared)
1787 const char *guid;
1789 connection->shareable = TRUE;
1791 /* guid may be NULL */
1792 guid = dbus_address_entry_get_value (entries[i], "guid");
1794 CONNECTION_LOCK (connection);
1796 if (!connection_record_shared_unlocked (connection, guid))
1798 _DBUS_SET_OOM (&tmp_error);
1799 _dbus_connection_close_possibly_shared_and_unlock (connection);
1800 dbus_connection_unref (connection);
1801 connection = NULL;
1803 else
1804 CONNECTION_UNLOCK (connection);
1808 if (connection)
1809 break;
1811 _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
1813 if (i == 0)
1814 dbus_move_error (&tmp_error, &first_error);
1815 else
1816 dbus_error_free (&tmp_error);
1819 _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1820 _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
1822 if (connection == NULL)
1824 _DBUS_ASSERT_ERROR_IS_SET (&first_error);
1825 dbus_move_error (&first_error, error);
1827 else
1828 dbus_error_free (&first_error);
1830 dbus_address_entries_free (entries);
1831 return connection;
1835 * Closes a shared OR private connection, while dbus_connection_close() can
1836 * only be used on private connections. Should only be called by the
1837 * dbus code that owns the connection - an owner must be known,
1838 * the open/close state is like malloc/free, not like ref/unref.
1840 * @param connection the connection
1842 void
1843 _dbus_connection_close_possibly_shared (DBusConnection *connection)
1845 _dbus_assert (connection != NULL);
1846 _dbus_assert (connection->generation == _dbus_current_generation);
1848 CONNECTION_LOCK (connection);
1849 _dbus_connection_close_possibly_shared_and_unlock (connection);
1852 static DBusPreallocatedSend*
1853 _dbus_connection_preallocate_send_unlocked (DBusConnection *connection)
1855 DBusPreallocatedSend *preallocated;
1857 HAVE_LOCK_CHECK (connection);
1859 _dbus_assert (connection != NULL);
1861 preallocated = dbus_new (DBusPreallocatedSend, 1);
1862 if (preallocated == NULL)
1863 return NULL;
1865 if (connection->link_cache != NULL)
1867 preallocated->queue_link =
1868 _dbus_list_pop_first_link (&connection->link_cache);
1869 preallocated->queue_link->data = NULL;
1871 else
1873 preallocated->queue_link = _dbus_list_alloc_link (NULL);
1874 if (preallocated->queue_link == NULL)
1875 goto failed_0;
1878 if (connection->link_cache != NULL)
1880 preallocated->counter_link =
1881 _dbus_list_pop_first_link (&connection->link_cache);
1882 preallocated->counter_link->data = connection->outgoing_counter;
1884 else
1886 preallocated->counter_link = _dbus_list_alloc_link (connection->outgoing_counter);
1887 if (preallocated->counter_link == NULL)
1888 goto failed_1;
1891 _dbus_counter_ref (preallocated->counter_link->data);
1893 preallocated->connection = connection;
1895 return preallocated;
1897 failed_1:
1898 _dbus_list_free_link (preallocated->queue_link);
1899 failed_0:
1900 dbus_free (preallocated);
1902 return NULL;
1905 /* Called with lock held, does not update dispatch status */
1906 static void
1907 _dbus_connection_send_preallocated_unlocked_no_update (DBusConnection *connection,
1908 DBusPreallocatedSend *preallocated,
1909 DBusMessage *message,
1910 dbus_uint32_t *client_serial)
1912 dbus_uint32_t serial;
1913 const char *sig;
1915 preallocated->queue_link->data = message;
1916 _dbus_list_prepend_link (&connection->outgoing_messages,
1917 preallocated->queue_link);
1919 _dbus_message_add_size_counter_link (message,
1920 preallocated->counter_link);
1922 dbus_free (preallocated);
1923 preallocated = NULL;
1925 dbus_message_ref (message);
1927 connection->n_outgoing += 1;
1929 sig = dbus_message_get_signature (message);
1931 _dbus_verbose ("Message %p (%d %s %s %s '%s') for %s added to outgoing queue %p, %d pending to send\n",
1932 message,
1933 dbus_message_get_type (message),
1934 dbus_message_get_path (message) ?
1935 dbus_message_get_path (message) :
1936 "no path",
1937 dbus_message_get_interface (message) ?
1938 dbus_message_get_interface (message) :
1939 "no interface",
1940 dbus_message_get_member (message) ?
1941 dbus_message_get_member (message) :
1942 "no member",
1943 sig,
1944 dbus_message_get_destination (message) ?
1945 dbus_message_get_destination (message) :
1946 "null",
1947 connection,
1948 connection->n_outgoing);
1950 if (dbus_message_get_serial (message) == 0)
1952 serial = _dbus_connection_get_next_client_serial (connection);
1953 dbus_message_set_serial (message, serial);
1954 if (client_serial)
1955 *client_serial = serial;
1957 else
1959 if (client_serial)
1960 *client_serial = dbus_message_get_serial (message);
1963 _dbus_verbose ("Message %p serial is %u\n",
1964 message, dbus_message_get_serial (message));
1966 dbus_message_lock (message);
1968 /* Now we need to run an iteration to hopefully just write the messages
1969 * out immediately, and otherwise get them queued up
1971 _dbus_connection_do_iteration_unlocked (connection,
1972 DBUS_ITERATION_DO_WRITING,
1973 -1);
1975 /* If stuff is still queued up, be sure we wake up the main loop */
1976 if (connection->n_outgoing > 0)
1977 _dbus_connection_wakeup_mainloop (connection);
1980 static void
1981 _dbus_connection_send_preallocated_and_unlock (DBusConnection *connection,
1982 DBusPreallocatedSend *preallocated,
1983 DBusMessage *message,
1984 dbus_uint32_t *client_serial)
1986 DBusDispatchStatus status;
1988 HAVE_LOCK_CHECK (connection);
1990 _dbus_connection_send_preallocated_unlocked_no_update (connection,
1991 preallocated,
1992 message, client_serial);
1994 _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
1995 status = _dbus_connection_get_dispatch_status_unlocked (connection);
1997 /* this calls out to user code */
1998 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2002 * Like dbus_connection_send(), but assumes the connection
2003 * is already locked on function entry, and unlocks before returning.
2005 * @param connection the connection
2006 * @param message the message to send
2007 * @param client_serial return location for client serial of sent message
2008 * @returns #FALSE on out-of-memory
2010 dbus_bool_t
2011 _dbus_connection_send_and_unlock (DBusConnection *connection,
2012 DBusMessage *message,
2013 dbus_uint32_t *client_serial)
2015 DBusPreallocatedSend *preallocated;
2017 _dbus_assert (connection != NULL);
2018 _dbus_assert (message != NULL);
2020 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
2021 if (preallocated == NULL)
2023 CONNECTION_UNLOCK (connection);
2024 return FALSE;
2027 _dbus_connection_send_preallocated_and_unlock (connection,
2028 preallocated,
2029 message,
2030 client_serial);
2031 return TRUE;
2035 * Used internally to handle the semantics of dbus_server_set_new_connection_function().
2036 * If the new connection function does not ref the connection, we want to close it.
2038 * A bit of a hack, probably the new connection function should have returned a value
2039 * for whether to close, or should have had to close the connection itself if it
2040 * didn't want it.
2042 * But, this works OK as long as the new connection function doesn't do anything
2043 * crazy like keep the connection around without ref'ing it.
2045 * We have to lock the connection across refcount check and close in case
2046 * the new connection function spawns a thread that closes and unrefs.
2047 * In that case, if the app thread
2048 * closes and unrefs first, we'll harmlessly close again; if the app thread
2049 * still has the ref, we'll close and then the app will close harmlessly.
2050 * If the app unrefs without closing, the app is broken since if the
2051 * app refs from the new connection function it is supposed to also close.
2053 * If we didn't atomically check the refcount and close with the lock held
2054 * though, we could screw this up.
2056 * @param connection the connection
2058 void
2059 _dbus_connection_close_if_only_one_ref (DBusConnection *connection)
2061 CONNECTION_LOCK (connection);
2063 _dbus_assert (connection->refcount.value > 0);
2065 if (connection->refcount.value == 1)
2066 _dbus_connection_close_possibly_shared_and_unlock (connection);
2067 else
2068 CONNECTION_UNLOCK (connection);
2073 * When a function that blocks has been called with a timeout, and we
2074 * run out of memory, the time to wait for memory is based on the
2075 * timeout. If the caller was willing to block a long time we wait a
2076 * relatively long time for memory, if they were only willing to block
2077 * briefly then we retry for memory at a rapid rate.
2079 * @timeout_milliseconds the timeout requested for blocking
2081 static void
2082 _dbus_memory_pause_based_on_timeout (int timeout_milliseconds)
2084 if (timeout_milliseconds == -1)
2085 _dbus_sleep_milliseconds (1000);
2086 else if (timeout_milliseconds < 100)
2087 ; /* just busy loop */
2088 else if (timeout_milliseconds <= 1000)
2089 _dbus_sleep_milliseconds (timeout_milliseconds / 3);
2090 else
2091 _dbus_sleep_milliseconds (1000);
2094 static DBusMessage *
2095 generate_local_error_message (dbus_uint32_t serial,
2096 char *error_name,
2097 char *error_msg)
2099 DBusMessage *message;
2100 message = dbus_message_new (DBUS_MESSAGE_TYPE_ERROR);
2101 if (!message)
2102 goto out;
2104 if (!dbus_message_set_error_name (message, error_name))
2106 dbus_message_unref (message);
2107 message = NULL;
2108 goto out;
2111 dbus_message_set_no_reply (message, TRUE);
2113 if (!dbus_message_set_reply_serial (message,
2114 serial))
2116 dbus_message_unref (message);
2117 message = NULL;
2118 goto out;
2121 if (error_msg != NULL)
2123 DBusMessageIter iter;
2125 dbus_message_iter_init_append (message, &iter);
2126 if (!dbus_message_iter_append_basic (&iter,
2127 DBUS_TYPE_STRING,
2128 &error_msg))
2130 dbus_message_unref (message);
2131 message = NULL;
2132 goto out;
2136 out:
2137 return message;
2141 /* This is slightly strange since we can pop a message here without
2142 * the dispatch lock.
2144 static DBusMessage*
2145 check_for_reply_unlocked (DBusConnection *connection,
2146 dbus_uint32_t client_serial)
2148 DBusList *link;
2150 HAVE_LOCK_CHECK (connection);
2152 link = _dbus_list_get_first_link (&connection->incoming_messages);
2154 while (link != NULL)
2156 DBusMessage *reply = link->data;
2158 if (dbus_message_get_reply_serial (reply) == client_serial)
2160 _dbus_list_remove_link (&connection->incoming_messages, link);
2161 connection->n_incoming -= 1;
2162 return reply;
2164 link = _dbus_list_get_next_link (&connection->incoming_messages, link);
2167 return NULL;
2170 static void
2171 connection_timeout_and_complete_all_pending_calls_unlocked (DBusConnection *connection)
2173 /* We can't iterate over the hash in the normal way since we'll be
2174 * dropping the lock for each item. So we restart the
2175 * iter each time as we drain the hash table.
2178 while (_dbus_hash_table_get_n_entries (connection->pending_replies) > 0)
2180 DBusPendingCall *pending;
2181 DBusHashIter iter;
2183 _dbus_hash_iter_init (connection->pending_replies, &iter);
2184 _dbus_hash_iter_next (&iter);
2186 pending = _dbus_hash_iter_get_value (&iter);
2187 _dbus_pending_call_ref_unlocked (pending);
2189 _dbus_pending_call_queue_timeout_error_unlocked (pending,
2190 connection);
2191 _dbus_connection_remove_timeout_unlocked (connection,
2192 _dbus_pending_call_get_timeout_unlocked (pending));
2193 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
2194 _dbus_hash_iter_remove_entry (&iter);
2196 _dbus_pending_call_unref_and_unlock (pending);
2197 CONNECTION_LOCK (connection);
2199 HAVE_LOCK_CHECK (connection);
2202 static void
2203 complete_pending_call_and_unlock (DBusConnection *connection,
2204 DBusPendingCall *pending,
2205 DBusMessage *message)
2207 _dbus_pending_call_set_reply_unlocked (pending, message);
2208 _dbus_pending_call_ref_unlocked (pending); /* in case there's no app with a ref held */
2209 _dbus_connection_detach_pending_call_and_unlock (connection, pending);
2211 /* Must be called unlocked since it invokes app callback */
2212 _dbus_pending_call_complete (pending);
2213 dbus_pending_call_unref (pending);
2216 static dbus_bool_t
2217 check_for_reply_and_update_dispatch_unlocked (DBusConnection *connection,
2218 DBusPendingCall *pending)
2220 DBusMessage *reply;
2221 DBusDispatchStatus status;
2223 reply = check_for_reply_unlocked (connection,
2224 _dbus_pending_call_get_reply_serial_unlocked (pending));
2225 if (reply != NULL)
2227 _dbus_verbose ("%s checked for reply\n", _DBUS_FUNCTION_NAME);
2229 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): got reply\n");
2231 complete_pending_call_and_unlock (connection, pending, reply);
2232 dbus_message_unref (reply);
2234 CONNECTION_LOCK (connection);
2235 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2236 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2237 dbus_pending_call_unref (pending);
2239 return TRUE;
2242 return FALSE;
2246 * Blocks until a pending call times out or gets a reply.
2248 * Does not re-enter the main loop or run filter/path-registered
2249 * callbacks. The reply to the message will not be seen by
2250 * filter callbacks.
2252 * Returns immediately if pending call already got a reply.
2254 * @todo could use performance improvements (it keeps scanning
2255 * the whole message queue for example)
2257 * @param pending the pending call we block for a reply on
2259 void
2260 _dbus_connection_block_pending_call (DBusPendingCall *pending)
2262 long start_tv_sec, start_tv_usec;
2263 long end_tv_sec, end_tv_usec;
2264 long tv_sec, tv_usec;
2265 DBusDispatchStatus status;
2266 DBusConnection *connection;
2267 dbus_uint32_t client_serial;
2268 int timeout_milliseconds;
2270 _dbus_assert (pending != NULL);
2272 if (dbus_pending_call_get_completed (pending))
2273 return;
2275 dbus_pending_call_ref (pending); /* necessary because the call could be canceled */
2277 connection = _dbus_pending_call_get_connection_and_lock (pending);
2279 /* Flush message queue - note, can affect dispatch status */
2280 _dbus_connection_flush_unlocked (connection);
2282 client_serial = _dbus_pending_call_get_reply_serial_unlocked (pending);
2284 /* note that timeout_milliseconds is limited to a smallish value
2285 * in _dbus_pending_call_new() so overflows aren't possible
2286 * below
2288 timeout_milliseconds = dbus_timeout_get_interval (_dbus_pending_call_get_timeout_unlocked (pending));
2290 _dbus_get_current_time (&start_tv_sec, &start_tv_usec);
2291 end_tv_sec = start_tv_sec + timeout_milliseconds / 1000;
2292 end_tv_usec = start_tv_usec + (timeout_milliseconds % 1000) * 1000;
2293 end_tv_sec += end_tv_usec / _DBUS_USEC_PER_SECOND;
2294 end_tv_usec = end_tv_usec % _DBUS_USEC_PER_SECOND;
2296 _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",
2297 timeout_milliseconds,
2298 client_serial,
2299 start_tv_sec, start_tv_usec,
2300 end_tv_sec, end_tv_usec);
2302 /* check to see if we already got the data off the socket */
2303 /* from another blocked pending call */
2304 if (check_for_reply_and_update_dispatch_unlocked (connection, pending))
2305 return;
2307 /* Now we wait... */
2308 /* always block at least once as we know we don't have the reply yet */
2309 _dbus_connection_do_iteration_unlocked (connection,
2310 DBUS_ITERATION_DO_READING |
2311 DBUS_ITERATION_BLOCK,
2312 timeout_milliseconds);
2314 recheck_status:
2316 _dbus_verbose ("%s top of recheck\n", _DBUS_FUNCTION_NAME);
2318 HAVE_LOCK_CHECK (connection);
2320 /* queue messages and get status */
2322 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2324 /* the get_completed() is in case a dispatch() while we were blocking
2325 * got the reply instead of us.
2327 if (_dbus_pending_call_get_completed_unlocked (pending))
2329 _dbus_verbose ("Pending call completed by dispatch in %s\n", _DBUS_FUNCTION_NAME);
2330 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2331 dbus_pending_call_unref (pending);
2332 return;
2335 if (status == DBUS_DISPATCH_DATA_REMAINS)
2337 if (check_for_reply_and_update_dispatch_unlocked (connection, pending))
2338 return;
2341 _dbus_get_current_time (&tv_sec, &tv_usec);
2343 if (!_dbus_connection_get_is_connected_unlocked (connection))
2345 DBusMessage *error_msg;
2347 error_msg = generate_local_error_message (client_serial,
2348 DBUS_ERROR_DISCONNECTED,
2349 "Connection was disconnected before a reply was received");
2351 /* on OOM error_msg is set to NULL */
2352 complete_pending_call_and_unlock (connection, pending, error_msg);
2353 dbus_pending_call_unref (pending);
2354 return;
2356 else if (tv_sec < start_tv_sec)
2357 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): clock set backward\n");
2358 else if (connection->disconnect_message_link == NULL)
2359 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): disconnected\n");
2360 else if (tv_sec < end_tv_sec ||
2361 (tv_sec == end_tv_sec && tv_usec < end_tv_usec))
2363 timeout_milliseconds = (end_tv_sec - tv_sec) * 1000 +
2364 (end_tv_usec - tv_usec) / 1000;
2365 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): %d milliseconds remain\n", timeout_milliseconds);
2366 _dbus_assert (timeout_milliseconds >= 0);
2368 if (status == DBUS_DISPATCH_NEED_MEMORY)
2370 /* Try sleeping a bit, as we aren't sure we need to block for reading,
2371 * we may already have a reply in the buffer and just can't process
2372 * it.
2374 _dbus_verbose ("dbus_connection_send_with_reply_and_block() waiting for more memory\n");
2376 _dbus_memory_pause_based_on_timeout (timeout_milliseconds);
2378 else
2380 /* block again, we don't have the reply buffered yet. */
2381 _dbus_connection_do_iteration_unlocked (connection,
2382 DBUS_ITERATION_DO_READING |
2383 DBUS_ITERATION_BLOCK,
2384 timeout_milliseconds);
2387 goto recheck_status;
2390 _dbus_verbose ("dbus_connection_send_with_reply_and_block(): Waited %ld milliseconds and got no reply\n",
2391 (tv_sec - start_tv_sec) * 1000 + (tv_usec - start_tv_usec) / 1000);
2393 _dbus_assert (!_dbus_pending_call_get_completed_unlocked (pending));
2395 /* unlock and call user code */
2396 complete_pending_call_and_unlock (connection, pending, NULL);
2398 /* update user code on dispatch status */
2399 CONNECTION_LOCK (connection);
2400 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2401 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2402 dbus_pending_call_unref (pending);
2405 /** @} */
2408 * @addtogroup DBusConnection
2410 * @{
2414 * Gets a connection to a remote address. If a connection to the given
2415 * address already exists, returns the existing connection with its
2416 * reference count incremented. Otherwise, returns a new connection
2417 * and saves the new connection for possible re-use if a future call
2418 * to dbus_connection_open() asks to connect to the same server.
2420 * Use dbus_connection_open_private() to get a dedicated connection
2421 * not shared with other callers of dbus_connection_open().
2423 * If the open fails, the function returns #NULL, and provides a
2424 * reason for the failure in the error parameter. Pass #NULL for the
2425 * error parameter if you aren't interested in the reason for
2426 * failure.
2428 * Because this connection is shared, no user of the connection
2429 * may call dbus_connection_close(). However, when you are done with the
2430 * connection you should call dbus_connection_unref().
2432 * @note Prefer dbus_connection_open() to dbus_connection_open_private()
2433 * unless you have good reason; connections are expensive enough
2434 * that it's wasteful to create lots of connections to the same
2435 * server.
2437 * @param address the address.
2438 * @param error address where an error can be returned.
2439 * @returns new connection, or #NULL on failure.
2441 DBusConnection*
2442 dbus_connection_open (const char *address,
2443 DBusError *error)
2445 DBusConnection *connection;
2447 _dbus_return_val_if_fail (address != NULL, NULL);
2448 _dbus_return_val_if_error_is_set (error, NULL);
2450 connection = _dbus_connection_open_internal (address,
2451 TRUE,
2452 error);
2454 return connection;
2458 * Opens a new, dedicated connection to a remote address. Unlike
2459 * dbus_connection_open(), always creates a new connection.
2460 * This connection will not be saved or recycled by libdbus.
2462 * If the open fails, the function returns #NULL, and provides a
2463 * reason for the failure in the error parameter. Pass #NULL for the
2464 * error parameter if you aren't interested in the reason for
2465 * failure.
2467 * When you are done with this connection, you must
2468 * dbus_connection_close() to disconnect it,
2469 * and dbus_connection_unref() to free the connection object.
2471 * (The dbus_connection_close() can be skipped if the
2472 * connection is already known to be disconnected, for example
2473 * if you are inside a handler for the Disconnected signal.)
2475 * @note Prefer dbus_connection_open() to dbus_connection_open_private()
2476 * unless you have good reason; connections are expensive enough
2477 * that it's wasteful to create lots of connections to the same
2478 * server.
2480 * @param address the address.
2481 * @param error address where an error can be returned.
2482 * @returns new connection, or #NULL on failure.
2484 DBusConnection*
2485 dbus_connection_open_private (const char *address,
2486 DBusError *error)
2488 DBusConnection *connection;
2490 _dbus_return_val_if_fail (address != NULL, NULL);
2491 _dbus_return_val_if_error_is_set (error, NULL);
2493 connection = _dbus_connection_open_internal (address,
2494 FALSE,
2495 error);
2497 return connection;
2501 * Increments the reference count of a DBusConnection.
2503 * @param connection the connection.
2504 * @returns the connection.
2506 DBusConnection *
2507 dbus_connection_ref (DBusConnection *connection)
2509 _dbus_return_val_if_fail (connection != NULL, NULL);
2510 _dbus_return_val_if_fail (connection->generation == _dbus_current_generation, NULL);
2512 /* The connection lock is better than the global
2513 * lock in the atomic increment fallback
2516 #ifdef DBUS_HAVE_ATOMIC_INT
2517 _dbus_atomic_inc (&connection->refcount);
2518 #else
2519 CONNECTION_LOCK (connection);
2520 _dbus_assert (connection->refcount.value > 0);
2522 connection->refcount.value += 1;
2523 CONNECTION_UNLOCK (connection);
2524 #endif
2526 return connection;
2529 static void
2530 free_outgoing_message (void *element,
2531 void *data)
2533 DBusMessage *message = element;
2534 DBusConnection *connection = data;
2536 _dbus_message_remove_size_counter (message,
2537 connection->outgoing_counter,
2538 NULL);
2539 dbus_message_unref (message);
2542 /* This is run without the mutex held, but after the last reference
2543 * to the connection has been dropped we should have no thread-related
2544 * problems
2546 static void
2547 _dbus_connection_last_unref (DBusConnection *connection)
2549 DBusList *link;
2551 _dbus_verbose ("Finalizing connection %p\n", connection);
2553 _dbus_assert (connection->refcount.value == 0);
2555 /* You have to disconnect the connection before unref:ing it. Otherwise
2556 * you won't get the disconnected message.
2558 _dbus_assert (!_dbus_transport_get_is_connected (connection->transport));
2559 _dbus_assert (connection->server_guid == NULL);
2561 /* ---- We're going to call various application callbacks here, hope it doesn't break anything... */
2562 _dbus_object_tree_free_all_unlocked (connection->objects);
2564 dbus_connection_set_dispatch_status_function (connection, NULL, NULL, NULL);
2565 dbus_connection_set_wakeup_main_function (connection, NULL, NULL, NULL);
2566 dbus_connection_set_unix_user_function (connection, NULL, NULL, NULL);
2568 _dbus_watch_list_free (connection->watches);
2569 connection->watches = NULL;
2571 _dbus_timeout_list_free (connection->timeouts);
2572 connection->timeouts = NULL;
2574 _dbus_data_slot_list_free (&connection->slot_list);
2576 link = _dbus_list_get_first_link (&connection->filter_list);
2577 while (link != NULL)
2579 DBusMessageFilter *filter = link->data;
2580 DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
2582 filter->function = NULL;
2583 _dbus_message_filter_unref (filter); /* calls app callback */
2584 link->data = NULL;
2586 link = next;
2588 _dbus_list_clear (&connection->filter_list);
2590 /* ---- Done with stuff that invokes application callbacks */
2592 _dbus_object_tree_unref (connection->objects);
2594 _dbus_hash_table_unref (connection->pending_replies);
2595 connection->pending_replies = NULL;
2597 _dbus_list_clear (&connection->filter_list);
2599 _dbus_list_foreach (&connection->outgoing_messages,
2600 free_outgoing_message,
2601 connection);
2602 _dbus_list_clear (&connection->outgoing_messages);
2604 _dbus_list_foreach (&connection->incoming_messages,
2605 (DBusForeachFunction) dbus_message_unref,
2606 NULL);
2607 _dbus_list_clear (&connection->incoming_messages);
2609 _dbus_counter_unref (connection->outgoing_counter);
2611 _dbus_transport_unref (connection->transport);
2613 if (connection->disconnect_message_link)
2615 DBusMessage *message = connection->disconnect_message_link->data;
2616 dbus_message_unref (message);
2617 _dbus_list_free_link (connection->disconnect_message_link);
2620 _dbus_list_clear (&connection->link_cache);
2622 _dbus_condvar_free_at_location (&connection->dispatch_cond);
2623 _dbus_condvar_free_at_location (&connection->io_path_cond);
2625 _dbus_mutex_free_at_location (&connection->io_path_mutex);
2626 _dbus_mutex_free_at_location (&connection->dispatch_mutex);
2628 _dbus_mutex_free_at_location (&connection->mutex);
2630 dbus_free (connection);
2634 * Decrements the reference count of a DBusConnection, and finalizes
2635 * it if the count reaches zero.
2637 * Note: it is a bug to drop the last reference to a connection that
2638 * is still connected.
2640 * For shared connections, libdbus will own a reference
2641 * as long as the connection is connected, so you can know that either
2642 * you don't have the last reference, or it's OK to drop the last reference.
2643 * Most connections are shared. dbus_connection_open() and dbus_bus_get()
2644 * return shared connections.
2646 * For private connections, the creator of the connection must arrange for
2647 * dbus_connection_close() to be called prior to dropping the last reference.
2648 * Private connections come from dbus_connection_open_private() or dbus_bus_get_private().
2650 * @param connection the connection.
2652 void
2653 dbus_connection_unref (DBusConnection *connection)
2655 dbus_bool_t last_unref;
2657 _dbus_return_if_fail (connection != NULL);
2658 _dbus_return_if_fail (connection->generation == _dbus_current_generation);
2660 /* The connection lock is better than the global
2661 * lock in the atomic increment fallback
2664 #ifdef DBUS_HAVE_ATOMIC_INT
2665 last_unref = (_dbus_atomic_dec (&connection->refcount) == 1);
2666 #else
2667 CONNECTION_LOCK (connection);
2669 _dbus_assert (connection->refcount.value > 0);
2671 connection->refcount.value -= 1;
2672 last_unref = (connection->refcount.value == 0);
2674 #if 0
2675 printf ("unref() connection %p count = %d\n", connection, connection->refcount.value);
2676 #endif
2678 CONNECTION_UNLOCK (connection);
2679 #endif
2681 if (last_unref)
2683 #ifndef DBUS_DISABLE_CHECKS
2684 if (_dbus_transport_get_is_connected (connection->transport))
2686 _dbus_warn_check_failed ("The last reference on a connection was dropped without closing the connection. This is a bug in an application. See dbus_connection_unref() documentation for details.\n%s",
2687 connection->shareable ?
2688 "Most likely, the application called unref() too many times and removed a reference belonging to libdbus, since this is a shared connection.\n" :
2689 "Most likely, the application was supposed to call dbus_connection_close(), since this is a private connection.\n");
2690 return;
2692 #endif
2693 _dbus_connection_last_unref (connection);
2698 * Note that the transport can disconnect itself (other end drops us)
2699 * and in that case this function never runs. So this function must
2700 * not do anything more than disconnect the transport and update the
2701 * dispatch status.
2703 * If the transport self-disconnects, then we assume someone will
2704 * dispatch the connection to cause the dispatch status update.
2706 static void
2707 _dbus_connection_close_possibly_shared_and_unlock (DBusConnection *connection)
2709 DBusDispatchStatus status;
2711 HAVE_LOCK_CHECK (connection);
2713 _dbus_verbose ("Disconnecting %p\n", connection);
2715 /* We need to ref because update_dispatch_status_and_unlock will unref
2716 * the connection if it was shared and libdbus was the only remaining
2717 * refcount holder.
2719 _dbus_connection_ref_unlocked (connection);
2721 _dbus_transport_disconnect (connection->transport);
2723 /* This has the side effect of queuing the disconnect message link
2724 * (unless we don't have enough memory, possibly, so don't assert it).
2725 * After the disconnect message link is queued, dbus_bus_get/dbus_connection_open
2726 * should never again return the newly-disconnected connection.
2728 * However, we only unref the shared connection and exit_on_disconnect when
2729 * the disconnect message reaches the head of the message queue,
2730 * NOT when it's first queued.
2732 status = _dbus_connection_get_dispatch_status_unlocked (connection);
2734 /* This calls out to user code */
2735 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2737 /* Could also call out to user code */
2738 dbus_connection_unref (connection);
2742 * Closes a private connection, so no further data can be sent or received.
2743 * This disconnects the transport (such as a socket) underlying the
2744 * connection.
2746 * Attempts to send messages after closing a connection are safe, but will result in
2747 * error replies generated locally in libdbus.
2749 * This function does not affect the connection's reference count. It's
2750 * safe to close a connection more than once; all calls after the
2751 * first do nothing. It's impossible to "reopen" a connection, a
2752 * new connection must be created. This function may result in a call
2753 * to the DBusDispatchStatusFunction set with
2754 * dbus_connection_set_dispatch_status_function(), as the disconnect
2755 * message it generates needs to be dispatched.
2757 * If a connection is dropped by the remote application, it will
2758 * close itself.
2760 * You must close a connection prior to releasing the last reference to
2761 * the connection. If you dbus_connection_unref() for the last time
2762 * without closing the connection, the results are undefined; it
2763 * is a bug in your program and libdbus will try to print a warning.
2765 * You may not close a shared connection. Connections created with
2766 * dbus_connection_open() or dbus_bus_get() are shared.
2767 * These connections are owned by libdbus, and applications should
2768 * only unref them, never close them. Applications can know it is
2769 * safe to unref these connections because libdbus will be holding a
2770 * reference as long as the connection is open. Thus, either the
2771 * connection is closed and it is OK to drop the last reference,
2772 * or the connection is open and the app knows it does not have the
2773 * last reference.
2775 * Connections created with dbus_connection_open_private() or
2776 * dbus_bus_get_private() are not kept track of or referenced by
2777 * libdbus. The creator of these connections is responsible for
2778 * calling dbus_connection_close() prior to releasing the last
2779 * reference, if the connection is not already disconnected.
2781 * @param connection the private (unshared) connection to close
2783 void
2784 dbus_connection_close (DBusConnection *connection)
2786 _dbus_return_if_fail (connection != NULL);
2787 _dbus_return_if_fail (connection->generation == _dbus_current_generation);
2789 CONNECTION_LOCK (connection);
2791 #ifndef DBUS_DISABLE_CHECKS
2792 if (connection->shareable)
2794 CONNECTION_UNLOCK (connection);
2796 _dbus_warn_check_failed ("Applications must not close shared connections - see dbus_connection_close() docs. This is a bug in the application.\n");
2797 return;
2799 #endif
2801 _dbus_connection_close_possibly_shared_and_unlock (connection);
2804 static dbus_bool_t
2805 _dbus_connection_get_is_connected_unlocked (DBusConnection *connection)
2807 HAVE_LOCK_CHECK (connection);
2808 return _dbus_transport_get_is_connected (connection->transport);
2812 * Gets whether the connection is currently open. A connection may
2813 * become disconnected when the remote application closes its end, or
2814 * exits; a connection may also be disconnected with
2815 * dbus_connection_close().
2817 * There are not separate states for "closed" and "disconnected," the two
2818 * terms are synonymous. This function should really be called
2819 * get_is_open() but for historical reasons is not.
2821 * @param connection the connection.
2822 * @returns #TRUE if the connection is still alive.
2824 dbus_bool_t
2825 dbus_connection_get_is_connected (DBusConnection *connection)
2827 dbus_bool_t res;
2829 _dbus_return_val_if_fail (connection != NULL, FALSE);
2831 CONNECTION_LOCK (connection);
2832 res = _dbus_connection_get_is_connected_unlocked (connection);
2833 CONNECTION_UNLOCK (connection);
2835 return res;
2839 * Gets whether the connection was authenticated. (Note that
2840 * if the connection was authenticated then disconnected,
2841 * this function still returns #TRUE)
2843 * @param connection the connection
2844 * @returns #TRUE if the connection was ever authenticated
2846 dbus_bool_t
2847 dbus_connection_get_is_authenticated (DBusConnection *connection)
2849 dbus_bool_t res;
2851 _dbus_return_val_if_fail (connection != NULL, FALSE);
2853 CONNECTION_LOCK (connection);
2854 res = _dbus_transport_get_is_authenticated (connection->transport);
2855 CONNECTION_UNLOCK (connection);
2857 return res;
2861 * Gets whether the connection is not authenticated as a specific
2862 * user. If the connection is not authenticated, this function
2863 * returns #TRUE, and if it is authenticated but as an anonymous user,
2864 * it returns #TRUE. If it is authenticated as a specific user, then
2865 * this returns #FALSE. (Note that if the connection was authenticated
2866 * as anonymous then disconnected, this function still returns #TRUE.)
2868 * If the connection is not anonymous, you can use
2869 * dbus_connection_get_unix_user() and
2870 * dbus_connection_get_windows_user() to see who it's authorized as.
2872 * If you want to prevent non-anonymous authorization, use
2873 * dbus_server_set_auth_mechanisms() to remove the mechanisms that
2874 * allow proving user identity (i.e. only allow the ANONYMOUS
2875 * mechanism).
2877 * @param connection the connection
2878 * @returns #TRUE if not authenticated or authenticated as anonymous
2880 dbus_bool_t
2881 dbus_connection_get_is_anonymous (DBusConnection *connection)
2883 dbus_bool_t res;
2885 _dbus_return_val_if_fail (connection != NULL, FALSE);
2887 CONNECTION_LOCK (connection);
2888 res = _dbus_transport_get_is_anonymous (connection->transport);
2889 CONNECTION_UNLOCK (connection);
2891 return res;
2895 * Gets the ID of the server address we are authenticated to, if this
2896 * connection is on the client side. If the connection is on the
2897 * server side, this will always return #NULL - use dbus_server_get_id()
2898 * to get the ID of your own server, if you are the server side.
2900 * If a client-side connection is not authenticated yet, the ID may be
2901 * available if it was included in the server address, but may not be
2902 * available. The only way to be sure the server ID is available
2903 * is to wait for authentication to complete.
2905 * In general, each mode of connecting to a given server will have
2906 * its own ID. So for example, if the session bus daemon is listening
2907 * on UNIX domain sockets and on TCP, then each of those modalities
2908 * will have its own server ID.
2910 * If you want an ID that identifies an entire session bus, look at
2911 * dbus_bus_get_id() instead (which is just a convenience wrapper
2912 * around the org.freedesktop.DBus.GetId method invoked on the bus).
2914 * You can also get a machine ID; see dbus_get_local_machine_id() to
2915 * get the machine you are on. There isn't a convenience wrapper, but
2916 * you can invoke org.freedesktop.DBus.Peer.GetMachineId on any peer
2917 * to get the machine ID on the other end.
2919 * The D-Bus specification describes the server ID and other IDs in a
2920 * bit more detail.
2922 * @param connection the connection
2923 * @returns the server ID or #NULL if no memory or the connection is server-side
2925 char*
2926 dbus_connection_get_server_id (DBusConnection *connection)
2928 char *id;
2930 _dbus_return_val_if_fail (connection != NULL, NULL);
2932 CONNECTION_LOCK (connection);
2933 id = _dbus_strdup (_dbus_transport_get_server_id (connection->transport));
2934 CONNECTION_UNLOCK (connection);
2936 return id;
2940 * Set whether _exit() should be called when the connection receives a
2941 * disconnect signal. The call to _exit() comes after any handlers for
2942 * the disconnect signal run; handlers can cancel the exit by calling
2943 * this function.
2945 * By default, exit_on_disconnect is #FALSE; but for message bus
2946 * connections returned from dbus_bus_get() it will be toggled on
2947 * by default.
2949 * @param connection the connection
2950 * @param exit_on_disconnect #TRUE if _exit() should be called after a disconnect signal
2952 void
2953 dbus_connection_set_exit_on_disconnect (DBusConnection *connection,
2954 dbus_bool_t exit_on_disconnect)
2956 _dbus_return_if_fail (connection != NULL);
2958 CONNECTION_LOCK (connection);
2959 connection->exit_on_disconnect = exit_on_disconnect != FALSE;
2960 CONNECTION_UNLOCK (connection);
2964 * Preallocates resources needed to send a message, allowing the message
2965 * to be sent without the possibility of memory allocation failure.
2966 * Allows apps to create a future guarantee that they can send
2967 * a message regardless of memory shortages.
2969 * @param connection the connection we're preallocating for.
2970 * @returns the preallocated resources, or #NULL
2972 DBusPreallocatedSend*
2973 dbus_connection_preallocate_send (DBusConnection *connection)
2975 DBusPreallocatedSend *preallocated;
2977 _dbus_return_val_if_fail (connection != NULL, NULL);
2979 CONNECTION_LOCK (connection);
2981 preallocated =
2982 _dbus_connection_preallocate_send_unlocked (connection);
2984 CONNECTION_UNLOCK (connection);
2986 return preallocated;
2990 * Frees preallocated message-sending resources from
2991 * dbus_connection_preallocate_send(). Should only
2992 * be called if the preallocated resources are not used
2993 * to send a message.
2995 * @param connection the connection
2996 * @param preallocated the resources
2998 void
2999 dbus_connection_free_preallocated_send (DBusConnection *connection,
3000 DBusPreallocatedSend *preallocated)
3002 _dbus_return_if_fail (connection != NULL);
3003 _dbus_return_if_fail (preallocated != NULL);
3004 _dbus_return_if_fail (connection == preallocated->connection);
3006 _dbus_list_free_link (preallocated->queue_link);
3007 _dbus_counter_unref (preallocated->counter_link->data);
3008 _dbus_list_free_link (preallocated->counter_link);
3009 dbus_free (preallocated);
3013 * Sends a message using preallocated resources. This function cannot fail.
3014 * It works identically to dbus_connection_send() in other respects.
3015 * Preallocated resources comes from dbus_connection_preallocate_send().
3016 * This function "consumes" the preallocated resources, they need not
3017 * be freed separately.
3019 * @param connection the connection
3020 * @param preallocated the preallocated resources
3021 * @param message the message to send
3022 * @param client_serial return location for client serial assigned to the message
3024 void
3025 dbus_connection_send_preallocated (DBusConnection *connection,
3026 DBusPreallocatedSend *preallocated,
3027 DBusMessage *message,
3028 dbus_uint32_t *client_serial)
3030 _dbus_return_if_fail (connection != NULL);
3031 _dbus_return_if_fail (preallocated != NULL);
3032 _dbus_return_if_fail (message != NULL);
3033 _dbus_return_if_fail (preallocated->connection == connection);
3034 _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_METHOD_CALL ||
3035 dbus_message_get_member (message) != NULL);
3036 _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL ||
3037 (dbus_message_get_interface (message) != NULL &&
3038 dbus_message_get_member (message) != NULL));
3040 CONNECTION_LOCK (connection);
3041 _dbus_connection_send_preallocated_and_unlock (connection,
3042 preallocated,
3043 message, client_serial);
3046 static dbus_bool_t
3047 _dbus_connection_send_unlocked_no_update (DBusConnection *connection,
3048 DBusMessage *message,
3049 dbus_uint32_t *client_serial)
3051 DBusPreallocatedSend *preallocated;
3053 _dbus_assert (connection != NULL);
3054 _dbus_assert (message != NULL);
3056 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
3057 if (preallocated == NULL)
3058 return FALSE;
3060 _dbus_connection_send_preallocated_unlocked_no_update (connection,
3061 preallocated,
3062 message,
3063 client_serial);
3064 return TRUE;
3068 * Adds a message to the outgoing message queue. Does not block to
3069 * write the message to the network; that happens asynchronously. To
3070 * force the message to be written, call dbus_connection_flush() however
3071 * it is not necessary to call dbus_connection_flush() by hand; the
3072 * message will be sent the next time the main loop is run.
3073 * dbus_connection_flush() should only be used, for example, if
3074 * the application was expected to exit before running the main loop.
3076 * Because this only queues the message, the only reason it can
3077 * fail is lack of memory. Even if the connection is disconnected,
3078 * no error will be returned. If the function fails due to lack of memory,
3079 * it returns #FALSE. The function will never fail for other reasons; even
3080 * if the connection is disconnected, you can queue an outgoing message,
3081 * though obviously it won't be sent.
3083 * The message serial is used by the remote application to send a
3084 * reply; see dbus_message_get_serial() or the D-Bus specification.
3086 * dbus_message_unref() can be called as soon as this method returns
3087 * as the message queue will hold its own ref until the message is sent.
3089 * @param connection the connection.
3090 * @param message the message to write.
3091 * @param serial return location for message serial, or #NULL if you don't care
3092 * @returns #TRUE on success.
3094 dbus_bool_t
3095 dbus_connection_send (DBusConnection *connection,
3096 DBusMessage *message,
3097 dbus_uint32_t *serial)
3099 _dbus_return_val_if_fail (connection != NULL, FALSE);
3100 _dbus_return_val_if_fail (message != NULL, FALSE);
3102 CONNECTION_LOCK (connection);
3104 return _dbus_connection_send_and_unlock (connection,
3105 message,
3106 serial);
3109 static dbus_bool_t
3110 reply_handler_timeout (void *data)
3112 DBusConnection *connection;
3113 DBusDispatchStatus status;
3114 DBusPendingCall *pending = data;
3116 connection = _dbus_pending_call_get_connection_and_lock (pending);
3118 _dbus_pending_call_queue_timeout_error_unlocked (pending,
3119 connection);
3120 _dbus_connection_remove_timeout_unlocked (connection,
3121 _dbus_pending_call_get_timeout_unlocked (pending));
3122 _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
3124 _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
3125 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3127 /* Unlocks, and calls out to user code */
3128 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3130 return TRUE;
3134 * Queues a message to send, as with dbus_connection_send(),
3135 * but also returns a #DBusPendingCall used to receive a reply to the
3136 * message. If no reply is received in the given timeout_milliseconds,
3137 * this function expires the pending reply and generates a synthetic
3138 * error reply (generated in-process, not by the remote application)
3139 * indicating that a timeout occurred.
3141 * A #DBusPendingCall will see a reply message before any filters or
3142 * registered object path handlers. See dbus_connection_dispatch() for
3143 * details on when handlers are run.
3145 * A #DBusPendingCall will always see exactly one reply message,
3146 * unless it's cancelled with dbus_pending_call_cancel().
3148 * If #NULL is passed for the pending_return, the #DBusPendingCall
3149 * will still be generated internally, and used to track
3150 * the message reply timeout. This means a timeout error will
3151 * occur if no reply arrives, unlike with dbus_connection_send().
3153 * If -1 is passed for the timeout, a sane default timeout is used. -1
3154 * is typically the best value for the timeout for this reason, unless
3155 * you want a very short or very long timeout. There is no way to
3156 * avoid a timeout entirely, other than passing INT_MAX for the
3157 * timeout to mean "very long timeout." libdbus clamps an INT_MAX
3158 * timeout down to a few hours timeout though.
3160 * @warning if the connection is disconnected, the #DBusPendingCall
3161 * will be set to #NULL, so be careful with this.
3163 * @param connection the connection
3164 * @param message the message to send
3165 * @param pending_return return location for a #DBusPendingCall object, or #NULL if connection is disconnected
3166 * @param timeout_milliseconds timeout in milliseconds or -1 for default
3167 * @returns #FALSE if no memory, #TRUE otherwise.
3170 dbus_bool_t
3171 dbus_connection_send_with_reply (DBusConnection *connection,
3172 DBusMessage *message,
3173 DBusPendingCall **pending_return,
3174 int timeout_milliseconds)
3176 DBusPendingCall *pending;
3177 dbus_int32_t serial = -1;
3178 DBusDispatchStatus status;
3180 _dbus_return_val_if_fail (connection != NULL, FALSE);
3181 _dbus_return_val_if_fail (message != NULL, FALSE);
3182 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3184 if (pending_return)
3185 *pending_return = NULL;
3187 CONNECTION_LOCK (connection);
3189 if (!_dbus_connection_get_is_connected_unlocked (connection))
3191 CONNECTION_UNLOCK (connection);
3193 return TRUE;
3196 pending = _dbus_pending_call_new_unlocked (connection,
3197 timeout_milliseconds,
3198 reply_handler_timeout);
3200 if (pending == NULL)
3202 CONNECTION_UNLOCK (connection);
3203 return FALSE;
3206 /* Assign a serial to the message */
3207 serial = dbus_message_get_serial (message);
3208 if (serial == 0)
3210 serial = _dbus_connection_get_next_client_serial (connection);
3211 dbus_message_set_serial (message, serial);
3214 if (!_dbus_pending_call_set_timeout_error_unlocked (pending, message, serial))
3215 goto error;
3217 /* Insert the serial in the pending replies hash;
3218 * hash takes a refcount on DBusPendingCall.
3219 * Also, add the timeout.
3221 if (!_dbus_connection_attach_pending_call_unlocked (connection,
3222 pending))
3223 goto error;
3225 if (!_dbus_connection_send_unlocked_no_update (connection, message, NULL))
3227 _dbus_connection_detach_pending_call_and_unlock (connection,
3228 pending);
3229 goto error_unlocked;
3232 if (pending_return)
3233 *pending_return = pending; /* hand off refcount */
3234 else
3236 _dbus_connection_detach_pending_call_unlocked (connection, pending);
3237 /* we still have a ref to the pending call in this case, we unref
3238 * after unlocking, below
3242 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3244 /* this calls out to user code */
3245 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3247 if (pending_return == NULL)
3248 dbus_pending_call_unref (pending);
3250 return TRUE;
3252 error:
3253 CONNECTION_UNLOCK (connection);
3254 error_unlocked:
3255 dbus_pending_call_unref (pending);
3256 return FALSE;
3260 * Sends a message and blocks a certain time period while waiting for
3261 * a reply. This function does not reenter the main loop,
3262 * i.e. messages other than the reply are queued up but not
3263 * processed. This function is used to invoke method calls on a
3264 * remote object.
3266 * If a normal reply is received, it is returned, and removed from the
3267 * incoming message queue. If it is not received, #NULL is returned
3268 * and the error is set to #DBUS_ERROR_NO_REPLY. If an error reply is
3269 * received, it is converted to a #DBusError and returned as an error,
3270 * then the reply message is deleted and #NULL is returned. If
3271 * something else goes wrong, result is set to whatever is
3272 * appropriate, such as #DBUS_ERROR_NO_MEMORY or
3273 * #DBUS_ERROR_DISCONNECTED.
3275 * @warning While this function blocks the calling thread will not be
3276 * processing the incoming message queue. This means you can end up
3277 * deadlocked if the application you're talking to needs you to reply
3278 * to a method. To solve this, either avoid the situation, block in a
3279 * separate thread from the main connection-dispatching thread, or use
3280 * dbus_pending_call_set_notify() to avoid blocking.
3282 * @param connection the connection
3283 * @param message the message to send
3284 * @param timeout_milliseconds timeout in milliseconds or -1 for default
3285 * @param error return location for error message
3286 * @returns the message that is the reply or #NULL with an error code if the
3287 * function fails.
3289 DBusMessage*
3290 dbus_connection_send_with_reply_and_block (DBusConnection *connection,
3291 DBusMessage *message,
3292 int timeout_milliseconds,
3293 DBusError *error)
3295 DBusMessage *reply;
3296 DBusPendingCall *pending;
3298 _dbus_return_val_if_fail (connection != NULL, NULL);
3299 _dbus_return_val_if_fail (message != NULL, NULL);
3300 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, NULL);
3301 _dbus_return_val_if_error_is_set (error, NULL);
3303 if (!dbus_connection_send_with_reply (connection, message,
3304 &pending, timeout_milliseconds))
3306 _DBUS_SET_OOM (error);
3307 return NULL;
3310 if (pending == NULL)
3312 dbus_set_error (error, DBUS_ERROR_DISCONNECTED, "Connection is closed");
3313 return NULL;
3316 dbus_pending_call_block (pending);
3318 reply = dbus_pending_call_steal_reply (pending);
3319 dbus_pending_call_unref (pending);
3321 /* call_complete_and_unlock() called from pending_call_block() should
3322 * always fill this in.
3324 _dbus_assert (reply != NULL);
3326 if (dbus_set_error_from_message (error, reply))
3328 dbus_message_unref (reply);
3329 return NULL;
3331 else
3332 return reply;
3336 * Blocks until the outgoing message queue is empty.
3337 * Assumes connection lock already held.
3339 * If you call this, you MUST call update_dispatch_status afterword...
3341 * @param connection the connection.
3343 static DBusDispatchStatus
3344 _dbus_connection_flush_unlocked (DBusConnection *connection)
3346 /* We have to specify DBUS_ITERATION_DO_READING here because
3347 * otherwise we could have two apps deadlock if they are both doing
3348 * a flush(), and the kernel buffers fill up. This could change the
3349 * dispatch status.
3351 DBusDispatchStatus status;
3353 HAVE_LOCK_CHECK (connection);
3355 while (connection->n_outgoing > 0 &&
3356 _dbus_connection_get_is_connected_unlocked (connection))
3358 _dbus_verbose ("doing iteration in %s\n", _DBUS_FUNCTION_NAME);
3359 HAVE_LOCK_CHECK (connection);
3360 _dbus_connection_do_iteration_unlocked (connection,
3361 DBUS_ITERATION_DO_READING |
3362 DBUS_ITERATION_DO_WRITING |
3363 DBUS_ITERATION_BLOCK,
3364 -1);
3367 HAVE_LOCK_CHECK (connection);
3368 _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
3369 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3371 HAVE_LOCK_CHECK (connection);
3372 return status;
3376 * Blocks until the outgoing message queue is empty.
3378 * @param connection the connection.
3380 void
3381 dbus_connection_flush (DBusConnection *connection)
3383 /* We have to specify DBUS_ITERATION_DO_READING here because
3384 * otherwise we could have two apps deadlock if they are both doing
3385 * a flush(), and the kernel buffers fill up. This could change the
3386 * dispatch status.
3388 DBusDispatchStatus status;
3390 _dbus_return_if_fail (connection != NULL);
3392 CONNECTION_LOCK (connection);
3394 status = _dbus_connection_flush_unlocked (connection);
3396 HAVE_LOCK_CHECK (connection);
3397 /* Unlocks and calls out to user code */
3398 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3400 _dbus_verbose ("%s end\n", _DBUS_FUNCTION_NAME);
3404 * This function implements dbus_connection_read_write_dispatch() and
3405 * dbus_connection_read_write() (they pass a different value for the
3406 * dispatch parameter).
3408 * @param connection the connection
3409 * @param timeout_milliseconds max time to block or -1 for infinite
3410 * @param dispatch dispatch new messages or leave them on the incoming queue
3411 * @returns #TRUE if the disconnect message has not been processed
3413 static dbus_bool_t
3414 _dbus_connection_read_write_dispatch (DBusConnection *connection,
3415 int timeout_milliseconds,
3416 dbus_bool_t dispatch)
3418 DBusDispatchStatus dstatus;
3419 dbus_bool_t progress_possible;
3421 /* Need to grab a ref here in case we're a private connection and
3422 * the user drops the last ref in a handler we call; see bug
3423 * https://bugs.freedesktop.org/show_bug.cgi?id=15635
3425 dbus_connection_ref (connection);
3426 dstatus = dbus_connection_get_dispatch_status (connection);
3428 if (dispatch && dstatus == DBUS_DISPATCH_DATA_REMAINS)
3430 _dbus_verbose ("doing dispatch in %s\n", _DBUS_FUNCTION_NAME);
3431 dbus_connection_dispatch (connection);
3432 CONNECTION_LOCK (connection);
3434 else if (dstatus == DBUS_DISPATCH_NEED_MEMORY)
3436 _dbus_verbose ("pausing for memory in %s\n", _DBUS_FUNCTION_NAME);
3437 _dbus_memory_pause_based_on_timeout (timeout_milliseconds);
3438 CONNECTION_LOCK (connection);
3440 else
3442 CONNECTION_LOCK (connection);
3443 if (_dbus_connection_get_is_connected_unlocked (connection))
3445 _dbus_verbose ("doing iteration in %s\n", _DBUS_FUNCTION_NAME);
3446 _dbus_connection_do_iteration_unlocked (connection,
3447 DBUS_ITERATION_DO_READING |
3448 DBUS_ITERATION_DO_WRITING |
3449 DBUS_ITERATION_BLOCK,
3450 timeout_milliseconds);
3454 HAVE_LOCK_CHECK (connection);
3455 /* If we can dispatch, we can make progress until the Disconnected message
3456 * has been processed; if we can only read/write, we can make progress
3457 * as long as the transport is open.
3459 if (dispatch)
3460 progress_possible = connection->n_incoming != 0 ||
3461 connection->disconnect_message_link != NULL;
3462 else
3463 progress_possible = _dbus_connection_get_is_connected_unlocked (connection);
3465 CONNECTION_UNLOCK (connection);
3467 dbus_connection_unref (connection);
3469 return progress_possible; /* TRUE if we can make more progress */
3474 * This function is intended for use with applications that don't want
3475 * to write a main loop and deal with #DBusWatch and #DBusTimeout. An
3476 * example usage would be:
3478 * @code
3479 * while (dbus_connection_read_write_dispatch (connection, -1))
3480 * ; // empty loop body
3481 * @endcode
3483 * In this usage you would normally have set up a filter function to look
3484 * at each message as it is dispatched. The loop terminates when the last
3485 * message from the connection (the disconnected signal) is processed.
3487 * If there are messages to dispatch, this function will
3488 * dbus_connection_dispatch() once, and return. If there are no
3489 * messages to dispatch, this function will block until it can read or
3490 * write, then read or write, then return.
3492 * The way to think of this function is that it either makes some sort
3493 * of progress, or it blocks. Note that, while it is blocked on I/O, it
3494 * cannot be interrupted (even by other threads), which makes this function
3495 * unsuitable for applications that do more than just react to received
3496 * messages.
3498 * The return value indicates whether the disconnect message has been
3499 * processed, NOT whether the connection is connected. This is
3500 * important because even after disconnecting, you want to process any
3501 * messages you received prior to the disconnect.
3503 * @param connection the connection
3504 * @param timeout_milliseconds max time to block or -1 for infinite
3505 * @returns #TRUE if the disconnect message has not been processed
3507 dbus_bool_t
3508 dbus_connection_read_write_dispatch (DBusConnection *connection,
3509 int timeout_milliseconds)
3511 _dbus_return_val_if_fail (connection != NULL, FALSE);
3512 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3513 return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, TRUE);
3516 /**
3517 * This function is intended for use with applications that don't want to
3518 * write a main loop and deal with #DBusWatch and #DBusTimeout. See also
3519 * dbus_connection_read_write_dispatch().
3521 * As long as the connection is open, this function will block until it can
3522 * read or write, then read or write, then return #TRUE.
3524 * If the connection is closed, the function returns #FALSE.
3526 * The return value indicates whether reading or writing is still
3527 * possible, i.e. whether the connection is connected.
3529 * Note that even after disconnection, messages may remain in the
3530 * incoming queue that need to be
3531 * processed. dbus_connection_read_write_dispatch() dispatches
3532 * incoming messages for you; with dbus_connection_read_write() you
3533 * have to arrange to drain the incoming queue yourself.
3535 * @param connection the connection
3536 * @param timeout_milliseconds max time to block or -1 for infinite
3537 * @returns #TRUE if still connected
3539 dbus_bool_t
3540 dbus_connection_read_write (DBusConnection *connection,
3541 int timeout_milliseconds)
3543 _dbus_return_val_if_fail (connection != NULL, FALSE);
3544 _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3545 return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, FALSE);
3548 /* We need to call this anytime we pop the head of the queue, and then
3549 * update_dispatch_status_and_unlock needs to be called afterward
3550 * which will "process" the disconnected message and set
3551 * disconnected_message_processed.
3553 static void
3554 check_disconnected_message_arrived_unlocked (DBusConnection *connection,
3555 DBusMessage *head_of_queue)
3557 HAVE_LOCK_CHECK (connection);
3559 /* checking that the link is NULL is an optimization to avoid the is_signal call */
3560 if (connection->disconnect_message_link == NULL &&
3561 dbus_message_is_signal (head_of_queue,
3562 DBUS_INTERFACE_LOCAL,
3563 "Disconnected"))
3565 connection->disconnected_message_arrived = TRUE;
3570 * Returns the first-received message from the incoming message queue,
3571 * leaving it in the queue. If the queue is empty, returns #NULL.
3573 * The caller does not own a reference to the returned message, and
3574 * must either return it using dbus_connection_return_message() or
3575 * keep it after calling dbus_connection_steal_borrowed_message(). No
3576 * one can get at the message while its borrowed, so return it as
3577 * quickly as possible and don't keep a reference to it after
3578 * returning it. If you need to keep the message, make a copy of it.
3580 * dbus_connection_dispatch() will block if called while a borrowed
3581 * message is outstanding; only one piece of code can be playing with
3582 * the incoming queue at a time. This function will block if called
3583 * during a dbus_connection_dispatch().
3585 * @param connection the connection.
3586 * @returns next message in the incoming queue.
3588 DBusMessage*
3589 dbus_connection_borrow_message (DBusConnection *connection)
3591 DBusDispatchStatus status;
3592 DBusMessage *message;
3594 _dbus_return_val_if_fail (connection != NULL, NULL);
3596 _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
3598 /* this is called for the side effect that it queues
3599 * up any messages from the transport
3601 status = dbus_connection_get_dispatch_status (connection);
3602 if (status != DBUS_DISPATCH_DATA_REMAINS)
3603 return NULL;
3605 CONNECTION_LOCK (connection);
3607 _dbus_connection_acquire_dispatch (connection);
3609 /* While a message is outstanding, the dispatch lock is held */
3610 _dbus_assert (connection->message_borrowed == NULL);
3612 connection->message_borrowed = _dbus_list_get_first (&connection->incoming_messages);
3614 message = connection->message_borrowed;
3616 check_disconnected_message_arrived_unlocked (connection, message);
3618 /* Note that we KEEP the dispatch lock until the message is returned */
3619 if (message == NULL)
3620 _dbus_connection_release_dispatch (connection);
3622 CONNECTION_UNLOCK (connection);
3624 /* We don't update dispatch status until it's returned or stolen */
3626 return message;
3630 * Used to return a message after peeking at it using
3631 * dbus_connection_borrow_message(). Only called if
3632 * message from dbus_connection_borrow_message() was non-#NULL.
3634 * @param connection the connection
3635 * @param message the message from dbus_connection_borrow_message()
3637 void
3638 dbus_connection_return_message (DBusConnection *connection,
3639 DBusMessage *message)
3641 DBusDispatchStatus status;
3643 _dbus_return_if_fail (connection != NULL);
3644 _dbus_return_if_fail (message != NULL);
3645 _dbus_return_if_fail (message == connection->message_borrowed);
3646 _dbus_return_if_fail (connection->dispatch_acquired);
3648 CONNECTION_LOCK (connection);
3650 _dbus_assert (message == connection->message_borrowed);
3652 connection->message_borrowed = NULL;
3654 _dbus_connection_release_dispatch (connection);
3656 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3657 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3661 * Used to keep a message after peeking at it using
3662 * dbus_connection_borrow_message(). Before using this function, see
3663 * the caveats/warnings in the documentation for
3664 * dbus_connection_pop_message().
3666 * @param connection the connection
3667 * @param message the message from dbus_connection_borrow_message()
3669 void
3670 dbus_connection_steal_borrowed_message (DBusConnection *connection,
3671 DBusMessage *message)
3673 DBusMessage *pop_message;
3674 DBusDispatchStatus status;
3676 _dbus_return_if_fail (connection != NULL);
3677 _dbus_return_if_fail (message != NULL);
3678 _dbus_return_if_fail (message == connection->message_borrowed);
3679 _dbus_return_if_fail (connection->dispatch_acquired);
3681 CONNECTION_LOCK (connection);
3683 _dbus_assert (message == connection->message_borrowed);
3685 pop_message = _dbus_list_pop_first (&connection->incoming_messages);
3686 _dbus_assert (message == pop_message);
3688 connection->n_incoming -= 1;
3690 _dbus_verbose ("Incoming message %p stolen from queue, %d incoming\n",
3691 message, connection->n_incoming);
3693 connection->message_borrowed = NULL;
3695 _dbus_connection_release_dispatch (connection);
3697 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3698 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3701 /* See dbus_connection_pop_message, but requires the caller to own
3702 * the lock before calling. May drop the lock while running.
3704 static DBusList*
3705 _dbus_connection_pop_message_link_unlocked (DBusConnection *connection)
3707 HAVE_LOCK_CHECK (connection);
3709 _dbus_assert (connection->message_borrowed == NULL);
3711 if (connection->n_incoming > 0)
3713 DBusList *link;
3715 link = _dbus_list_pop_first_link (&connection->incoming_messages);
3716 connection->n_incoming -= 1;
3718 _dbus_verbose ("Message %p (%d %s %s %s '%s') removed from incoming queue %p, %d incoming\n",
3719 link->data,
3720 dbus_message_get_type (link->data),
3721 dbus_message_get_path (link->data) ?
3722 dbus_message_get_path (link->data) :
3723 "no path",
3724 dbus_message_get_interface (link->data) ?
3725 dbus_message_get_interface (link->data) :
3726 "no interface",
3727 dbus_message_get_member (link->data) ?
3728 dbus_message_get_member (link->data) :
3729 "no member",
3730 dbus_message_get_signature (link->data),
3731 connection, connection->n_incoming);
3733 check_disconnected_message_arrived_unlocked (connection, link->data);
3735 return link;
3737 else
3738 return NULL;
3741 /* See dbus_connection_pop_message, but requires the caller to own
3742 * the lock before calling. May drop the lock while running.
3744 static DBusMessage*
3745 _dbus_connection_pop_message_unlocked (DBusConnection *connection)
3747 DBusList *link;
3749 HAVE_LOCK_CHECK (connection);
3751 link = _dbus_connection_pop_message_link_unlocked (connection);
3753 if (link != NULL)
3755 DBusMessage *message;
3757 message = link->data;
3759 _dbus_list_free_link (link);
3761 return message;
3763 else
3764 return NULL;
3767 static void
3768 _dbus_connection_putback_message_link_unlocked (DBusConnection *connection,
3769 DBusList *message_link)
3771 HAVE_LOCK_CHECK (connection);
3773 _dbus_assert (message_link != NULL);
3774 /* You can't borrow a message while a link is outstanding */
3775 _dbus_assert (connection->message_borrowed == NULL);
3776 /* We had to have the dispatch lock across the pop/putback */
3777 _dbus_assert (connection->dispatch_acquired);
3779 _dbus_list_prepend_link (&connection->incoming_messages,
3780 message_link);
3781 connection->n_incoming += 1;
3783 _dbus_verbose ("Message %p (%d %s %s '%s') put back into queue %p, %d incoming\n",
3784 message_link->data,
3785 dbus_message_get_type (message_link->data),
3786 dbus_message_get_interface (message_link->data) ?
3787 dbus_message_get_interface (message_link->data) :
3788 "no interface",
3789 dbus_message_get_member (message_link->data) ?
3790 dbus_message_get_member (message_link->data) :
3791 "no member",
3792 dbus_message_get_signature (message_link->data),
3793 connection, connection->n_incoming);
3797 * Returns the first-received message from the incoming message queue,
3798 * removing it from the queue. The caller owns a reference to the
3799 * returned message. If the queue is empty, returns #NULL.
3801 * This function bypasses any message handlers that are registered,
3802 * and so using it is usually wrong. Instead, let the main loop invoke
3803 * dbus_connection_dispatch(). Popping messages manually is only
3804 * useful in very simple programs that don't share a #DBusConnection
3805 * with any libraries or other modules.
3807 * There is a lock that covers all ways of accessing the incoming message
3808 * queue, so dbus_connection_dispatch(), dbus_connection_pop_message(),
3809 * dbus_connection_borrow_message(), etc. will all block while one of the others
3810 * in the group is running.
3812 * @param connection the connection.
3813 * @returns next message in the incoming queue.
3815 DBusMessage*
3816 dbus_connection_pop_message (DBusConnection *connection)
3818 DBusMessage *message;
3819 DBusDispatchStatus status;
3821 _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
3823 /* this is called for the side effect that it queues
3824 * up any messages from the transport
3826 status = dbus_connection_get_dispatch_status (connection);
3827 if (status != DBUS_DISPATCH_DATA_REMAINS)
3828 return NULL;
3830 CONNECTION_LOCK (connection);
3831 _dbus_connection_acquire_dispatch (connection);
3832 HAVE_LOCK_CHECK (connection);
3834 message = _dbus_connection_pop_message_unlocked (connection);
3836 _dbus_verbose ("Returning popped message %p\n", message);
3838 _dbus_connection_release_dispatch (connection);
3840 status = _dbus_connection_get_dispatch_status_unlocked (connection);
3841 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3843 return message;
3847 * Acquire the dispatcher. This is a separate lock so the main
3848 * connection lock can be dropped to call out to application dispatch
3849 * handlers.
3851 * @param connection the connection.
3853 static void
3854 _dbus_connection_acquire_dispatch (DBusConnection *connection)
3856 HAVE_LOCK_CHECK (connection);
3858 _dbus_connection_ref_unlocked (connection);
3859 CONNECTION_UNLOCK (connection);
3861 _dbus_verbose ("%s locking dispatch_mutex\n", _DBUS_FUNCTION_NAME);
3862 _dbus_mutex_lock (connection->dispatch_mutex);
3864 while (connection->dispatch_acquired)
3866 _dbus_verbose ("%s waiting for dispatch to be acquirable\n", _DBUS_FUNCTION_NAME);
3867 _dbus_condvar_wait (connection->dispatch_cond,
3868 connection->dispatch_mutex);
3871 _dbus_assert (!connection->dispatch_acquired);
3873 connection->dispatch_acquired = TRUE;
3875 _dbus_verbose ("%s unlocking dispatch_mutex\n", _DBUS_FUNCTION_NAME);
3876 _dbus_mutex_unlock (connection->dispatch_mutex);
3878 CONNECTION_LOCK (connection);
3879 _dbus_connection_unref_unlocked (connection);
3883 * Release the dispatcher when you're done with it. Only call
3884 * after you've acquired the dispatcher. Wakes up at most one
3885 * thread currently waiting to acquire the dispatcher.
3887 * @param connection the connection.
3889 static void
3890 _dbus_connection_release_dispatch (DBusConnection *connection)
3892 HAVE_LOCK_CHECK (connection);
3894 _dbus_verbose ("%s locking dispatch_mutex\n", _DBUS_FUNCTION_NAME);
3895 _dbus_mutex_lock (connection->dispatch_mutex);
3897 _dbus_assert (connection->dispatch_acquired);
3899 connection->dispatch_acquired = FALSE;
3900 _dbus_condvar_wake_one (connection->dispatch_cond);
3902 _dbus_verbose ("%s unlocking dispatch_mutex\n", _DBUS_FUNCTION_NAME);
3903 _dbus_mutex_unlock (connection->dispatch_mutex);
3906 static void
3907 _dbus_connection_failed_pop (DBusConnection *connection,
3908 DBusList *message_link)
3910 _dbus_list_prepend_link (&connection->incoming_messages,
3911 message_link);
3912 connection->n_incoming += 1;
3915 /* Note this may be called multiple times since we don't track whether we already did it */
3916 static void
3917 notify_disconnected_unlocked (DBusConnection *connection)
3919 HAVE_LOCK_CHECK (connection);
3921 /* Set the weakref in dbus-bus.c to NULL, so nobody will get a disconnected
3922 * connection from dbus_bus_get(). We make the same guarantee for
3923 * dbus_connection_open() but in a different way since we don't want to
3924 * unref right here; we instead check for connectedness before returning
3925 * the connection from the hash.
3927 _dbus_bus_notify_shared_connection_disconnected_unlocked (connection);
3929 /* Dump the outgoing queue, we aren't going to be able to
3930 * send it now, and we'd like accessors like
3931 * dbus_connection_get_outgoing_size() to be accurate.
3933 if (connection->n_outgoing > 0)
3935 DBusList *link;
3937 _dbus_verbose ("Dropping %d outgoing messages since we're disconnected\n",
3938 connection->n_outgoing);
3940 while ((link = _dbus_list_get_last_link (&connection->outgoing_messages)))
3942 _dbus_connection_message_sent (connection, link->data);
3947 /* Note this may be called multiple times since we don't track whether we already did it */
3948 static DBusDispatchStatus
3949 notify_disconnected_and_dispatch_complete_unlocked (DBusConnection *connection)
3951 HAVE_LOCK_CHECK (connection);
3953 if (connection->disconnect_message_link != NULL)
3955 _dbus_verbose ("Sending disconnect message from %s\n",
3956 _DBUS_FUNCTION_NAME);
3958 /* If we have pending calls, queue their timeouts - we want the Disconnected
3959 * to be the last message, after these timeouts.
3961 connection_timeout_and_complete_all_pending_calls_unlocked (connection);
3963 /* We haven't sent the disconnect message already,
3964 * and all real messages have been queued up.
3966 _dbus_connection_queue_synthesized_message_link (connection,
3967 connection->disconnect_message_link);
3968 connection->disconnect_message_link = NULL;
3970 return DBUS_DISPATCH_DATA_REMAINS;
3973 return DBUS_DISPATCH_COMPLETE;
3976 static DBusDispatchStatus
3977 _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection)
3979 HAVE_LOCK_CHECK (connection);
3981 if (connection->n_incoming > 0)
3982 return DBUS_DISPATCH_DATA_REMAINS;
3983 else if (!_dbus_transport_queue_messages (connection->transport))
3984 return DBUS_DISPATCH_NEED_MEMORY;
3985 else
3987 DBusDispatchStatus status;
3988 dbus_bool_t is_connected;
3990 status = _dbus_transport_get_dispatch_status (connection->transport);
3991 is_connected = _dbus_transport_get_is_connected (connection->transport);
3993 _dbus_verbose ("dispatch status = %s is_connected = %d\n",
3994 DISPATCH_STATUS_NAME (status), is_connected);
3996 if (!is_connected)
3998 /* It's possible this would be better done by having an explicit
3999 * notification from _dbus_transport_disconnect() that would
4000 * synchronously do this, instead of waiting for the next dispatch
4001 * status check. However, probably not good to change until it causes
4002 * a problem.
4004 notify_disconnected_unlocked (connection);
4006 /* I'm not sure this is needed; the idea is that we want to
4007 * queue the Disconnected only after we've read all the
4008 * messages, but if we're disconnected maybe we are guaranteed
4009 * to have read them all ?
4011 if (status == DBUS_DISPATCH_COMPLETE)
4012 status = notify_disconnected_and_dispatch_complete_unlocked (connection);
4015 if (status != DBUS_DISPATCH_COMPLETE)
4016 return status;
4017 else if (connection->n_incoming > 0)
4018 return DBUS_DISPATCH_DATA_REMAINS;
4019 else
4020 return DBUS_DISPATCH_COMPLETE;
4024 static void
4025 _dbus_connection_update_dispatch_status_and_unlock (DBusConnection *connection,
4026 DBusDispatchStatus new_status)
4028 dbus_bool_t changed;
4029 DBusDispatchStatusFunction function;
4030 void *data;
4032 HAVE_LOCK_CHECK (connection);
4034 _dbus_connection_ref_unlocked (connection);
4036 changed = new_status != connection->last_dispatch_status;
4038 connection->last_dispatch_status = new_status;
4040 function = connection->dispatch_status_function;
4041 data = connection->dispatch_status_data;
4043 if (connection->disconnected_message_arrived &&
4044 !connection->disconnected_message_processed)
4046 connection->disconnected_message_processed = TRUE;
4048 /* this does an unref, but we have a ref
4049 * so we should not run the finalizer here
4050 * inside the lock.
4052 connection_forget_shared_unlocked (connection);
4054 if (connection->exit_on_disconnect)
4056 CONNECTION_UNLOCK (connection);
4058 _dbus_verbose ("Exiting on Disconnected signal\n");
4059 _dbus_exit (1);
4060 _dbus_assert_not_reached ("Call to exit() returned");
4064 /* We drop the lock */
4065 CONNECTION_UNLOCK (connection);
4067 if (changed && function)
4069 _dbus_verbose ("Notifying of change to dispatch status of %p now %d (%s)\n",
4070 connection, new_status,
4071 DISPATCH_STATUS_NAME (new_status));
4072 (* function) (connection, new_status, data);
4075 dbus_connection_unref (connection);
4079 * Gets the current state of the incoming message queue.
4080 * #DBUS_DISPATCH_DATA_REMAINS indicates that the message queue
4081 * may contain messages. #DBUS_DISPATCH_COMPLETE indicates that the
4082 * incoming queue is empty. #DBUS_DISPATCH_NEED_MEMORY indicates that
4083 * there could be data, but we can't know for sure without more
4084 * memory.
4086 * To process the incoming message queue, use dbus_connection_dispatch()
4087 * or (in rare cases) dbus_connection_pop_message().
4089 * Note, #DBUS_DISPATCH_DATA_REMAINS really means that either we
4090 * have messages in the queue, or we have raw bytes buffered up
4091 * that need to be parsed. When these bytes are parsed, they
4092 * may not add up to an entire message. Thus, it's possible
4093 * to see a status of #DBUS_DISPATCH_DATA_REMAINS but not
4094 * have a message yet.
4096 * In particular this happens on initial connection, because all sorts
4097 * of authentication protocol stuff has to be parsed before the
4098 * first message arrives.
4100 * @param connection the connection.
4101 * @returns current dispatch status
4103 DBusDispatchStatus
4104 dbus_connection_get_dispatch_status (DBusConnection *connection)
4106 DBusDispatchStatus status;
4108 _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
4110 _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
4112 CONNECTION_LOCK (connection);
4114 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4116 CONNECTION_UNLOCK (connection);
4118 return status;
4122 * Filter funtion for handling the Peer standard interface.
4124 static DBusHandlerResult
4125 _dbus_connection_peer_filter_unlocked_no_update (DBusConnection *connection,
4126 DBusMessage *message)
4128 if (connection->route_peer_messages && dbus_message_get_destination (message) != NULL)
4130 /* This means we're letting the bus route this message */
4131 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4133 else if (dbus_message_is_method_call (message,
4134 DBUS_INTERFACE_PEER,
4135 "Ping"))
4137 DBusMessage *ret;
4138 dbus_bool_t sent;
4140 ret = dbus_message_new_method_return (message);
4141 if (ret == NULL)
4142 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4144 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4146 dbus_message_unref (ret);
4148 if (!sent)
4149 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4151 return DBUS_HANDLER_RESULT_HANDLED;
4153 else if (dbus_message_is_method_call (message,
4154 DBUS_INTERFACE_PEER,
4155 "GetMachineId"))
4157 DBusMessage *ret;
4158 dbus_bool_t sent;
4159 DBusString uuid;
4161 ret = dbus_message_new_method_return (message);
4162 if (ret == NULL)
4163 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4165 sent = FALSE;
4166 _dbus_string_init (&uuid);
4167 if (_dbus_get_local_machine_uuid_encoded (&uuid))
4169 const char *v_STRING = _dbus_string_get_const_data (&uuid);
4170 if (dbus_message_append_args (ret,
4171 DBUS_TYPE_STRING, &v_STRING,
4172 DBUS_TYPE_INVALID))
4174 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4177 _dbus_string_free (&uuid);
4179 dbus_message_unref (ret);
4181 if (!sent)
4182 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4184 return DBUS_HANDLER_RESULT_HANDLED;
4186 else if (dbus_message_has_interface (message, DBUS_INTERFACE_PEER))
4188 /* We need to bounce anything else with this interface, otherwise apps
4189 * could start extending the interface and when we added extensions
4190 * here to DBusConnection we'd break those apps.
4193 DBusMessage *ret;
4194 dbus_bool_t sent;
4196 ret = dbus_message_new_error (message,
4197 DBUS_ERROR_UNKNOWN_METHOD,
4198 "Unknown method invoked on org.freedesktop.DBus.Peer interface");
4199 if (ret == NULL)
4200 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4202 sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4204 dbus_message_unref (ret);
4206 if (!sent)
4207 return DBUS_HANDLER_RESULT_NEED_MEMORY;
4209 return DBUS_HANDLER_RESULT_HANDLED;
4211 else
4213 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4218 * Processes all builtin filter functions
4220 * If the spec specifies a standard interface
4221 * they should be processed from this method
4223 static DBusHandlerResult
4224 _dbus_connection_run_builtin_filters_unlocked_no_update (DBusConnection *connection,
4225 DBusMessage *message)
4227 /* We just run one filter for now but have the option to run more
4228 if the spec calls for it in the future */
4230 return _dbus_connection_peer_filter_unlocked_no_update (connection, message);
4234 * Processes any incoming data.
4236 * If there's incoming raw data that has not yet been parsed, it is
4237 * parsed, which may or may not result in adding messages to the
4238 * incoming queue.
4240 * The incoming data buffer is filled when the connection reads from
4241 * its underlying transport (such as a socket). Reading usually
4242 * happens in dbus_watch_handle() or dbus_connection_read_write().
4244 * If there are complete messages in the incoming queue,
4245 * dbus_connection_dispatch() removes one message from the queue and
4246 * processes it. Processing has three steps.
4248 * First, any method replies are passed to #DBusPendingCall or
4249 * dbus_connection_send_with_reply_and_block() in order to
4250 * complete the pending method call.
4252 * Second, any filters registered with dbus_connection_add_filter()
4253 * are run. If any filter returns #DBUS_HANDLER_RESULT_HANDLED
4254 * then processing stops after that filter.
4256 * Third, if the message is a method call it is forwarded to
4257 * any registered object path handlers added with
4258 * dbus_connection_register_object_path() or
4259 * dbus_connection_register_fallback().
4261 * A single call to dbus_connection_dispatch() will process at most
4262 * one message; it will not clear the entire message queue.
4264 * Be careful about calling dbus_connection_dispatch() from inside a
4265 * message handler, i.e. calling dbus_connection_dispatch()
4266 * recursively. If threads have been initialized with a recursive
4267 * mutex function, then this will not deadlock; however, it can
4268 * certainly confuse your application.
4270 * @todo some FIXME in here about handling DBUS_HANDLER_RESULT_NEED_MEMORY
4272 * @param connection the connection
4273 * @returns dispatch status, see dbus_connection_get_dispatch_status()
4275 DBusDispatchStatus
4276 dbus_connection_dispatch (DBusConnection *connection)
4278 DBusMessage *message;
4279 DBusList *link, *filter_list_copy, *message_link;
4280 DBusHandlerResult result;
4281 DBusPendingCall *pending;
4282 dbus_int32_t reply_serial;
4283 DBusDispatchStatus status;
4285 _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
4287 _dbus_verbose ("%s\n", _DBUS_FUNCTION_NAME);
4289 CONNECTION_LOCK (connection);
4290 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4291 if (status != DBUS_DISPATCH_DATA_REMAINS)
4293 /* unlocks and calls out to user code */
4294 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4295 return status;
4298 /* We need to ref the connection since the callback could potentially
4299 * drop the last ref to it
4301 _dbus_connection_ref_unlocked (connection);
4303 _dbus_connection_acquire_dispatch (connection);
4304 HAVE_LOCK_CHECK (connection);
4306 message_link = _dbus_connection_pop_message_link_unlocked (connection);
4307 if (message_link == NULL)
4309 /* another thread dispatched our stuff */
4311 _dbus_verbose ("another thread dispatched message (during acquire_dispatch above)\n");
4313 _dbus_connection_release_dispatch (connection);
4315 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4317 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4319 dbus_connection_unref (connection);
4321 return status;
4324 message = message_link->data;
4326 _dbus_verbose (" dispatching message %p (%d %s %s '%s')\n",
4327 message,
4328 dbus_message_get_type (message),
4329 dbus_message_get_interface (message) ?
4330 dbus_message_get_interface (message) :
4331 "no interface",
4332 dbus_message_get_member (message) ?
4333 dbus_message_get_member (message) :
4334 "no member",
4335 dbus_message_get_signature (message));
4337 result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4339 /* Pending call handling must be first, because if you do
4340 * dbus_connection_send_with_reply_and_block() or
4341 * dbus_pending_call_block() then no handlers/filters will be run on
4342 * the reply. We want consistent semantics in the case where we
4343 * dbus_connection_dispatch() the reply.
4346 reply_serial = dbus_message_get_reply_serial (message);
4347 pending = _dbus_hash_table_lookup_int (connection->pending_replies,
4348 reply_serial);
4349 if (pending)
4351 _dbus_verbose ("Dispatching a pending reply\n");
4352 complete_pending_call_and_unlock (connection, pending, message);
4353 pending = NULL; /* it's probably unref'd */
4355 CONNECTION_LOCK (connection);
4356 _dbus_verbose ("pending call completed in dispatch\n");
4357 result = DBUS_HANDLER_RESULT_HANDLED;
4358 goto out;
4361 result = _dbus_connection_run_builtin_filters_unlocked_no_update (connection, message);
4362 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4363 goto out;
4365 if (!_dbus_list_copy (&connection->filter_list, &filter_list_copy))
4367 _dbus_connection_release_dispatch (connection);
4368 HAVE_LOCK_CHECK (connection);
4370 _dbus_connection_failed_pop (connection, message_link);
4372 /* unlocks and calls user code */
4373 _dbus_connection_update_dispatch_status_and_unlock (connection,
4374 DBUS_DISPATCH_NEED_MEMORY);
4376 if (pending)
4377 dbus_pending_call_unref (pending);
4378 dbus_connection_unref (connection);
4380 return DBUS_DISPATCH_NEED_MEMORY;
4383 _dbus_list_foreach (&filter_list_copy,
4384 (DBusForeachFunction)_dbus_message_filter_ref,
4385 NULL);
4387 /* We're still protected from dispatch() reentrancy here
4388 * since we acquired the dispatcher
4390 CONNECTION_UNLOCK (connection);
4392 link = _dbus_list_get_first_link (&filter_list_copy);
4393 while (link != NULL)
4395 DBusMessageFilter *filter = link->data;
4396 DBusList *next = _dbus_list_get_next_link (&filter_list_copy, link);
4398 if (filter->function == NULL)
4400 _dbus_verbose (" filter was removed in a callback function\n");
4401 link = next;
4402 continue;
4405 _dbus_verbose (" running filter on message %p\n", message);
4406 result = (* filter->function) (connection, message, filter->user_data);
4408 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4409 break;
4411 link = next;
4414 _dbus_list_foreach (&filter_list_copy,
4415 (DBusForeachFunction)_dbus_message_filter_unref,
4416 NULL);
4417 _dbus_list_clear (&filter_list_copy);
4419 CONNECTION_LOCK (connection);
4421 if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
4423 _dbus_verbose ("No memory in %s\n", _DBUS_FUNCTION_NAME);
4424 goto out;
4426 else if (result == DBUS_HANDLER_RESULT_HANDLED)
4428 _dbus_verbose ("filter handled message in dispatch\n");
4429 goto out;
4432 /* We're still protected from dispatch() reentrancy here
4433 * since we acquired the dispatcher
4435 _dbus_verbose (" running object path dispatch on message %p (%d %s %s '%s')\n",
4436 message,
4437 dbus_message_get_type (message),
4438 dbus_message_get_interface (message) ?
4439 dbus_message_get_interface (message) :
4440 "no interface",
4441 dbus_message_get_member (message) ?
4442 dbus_message_get_member (message) :
4443 "no member",
4444 dbus_message_get_signature (message));
4446 HAVE_LOCK_CHECK (connection);
4447 result = _dbus_object_tree_dispatch_and_unlock (connection->objects,
4448 message);
4450 CONNECTION_LOCK (connection);
4452 if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4454 _dbus_verbose ("object tree handled message in dispatch\n");
4455 goto out;
4458 if (dbus_message_get_type (message) == DBUS_MESSAGE_TYPE_METHOD_CALL)
4460 DBusMessage *reply;
4461 DBusString str;
4462 DBusPreallocatedSend *preallocated;
4464 _dbus_verbose (" sending error %s\n",
4465 DBUS_ERROR_UNKNOWN_METHOD);
4467 if (!_dbus_string_init (&str))
4469 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4470 _dbus_verbose ("no memory for error string in dispatch\n");
4471 goto out;
4474 if (!_dbus_string_append_printf (&str,
4475 "Method \"%s\" with signature \"%s\" on interface \"%s\" doesn't exist\n",
4476 dbus_message_get_member (message),
4477 dbus_message_get_signature (message),
4478 dbus_message_get_interface (message)))
4480 _dbus_string_free (&str);
4481 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4482 _dbus_verbose ("no memory for error string in dispatch\n");
4483 goto out;
4486 reply = dbus_message_new_error (message,
4487 DBUS_ERROR_UNKNOWN_METHOD,
4488 _dbus_string_get_const_data (&str));
4489 _dbus_string_free (&str);
4491 if (reply == NULL)
4493 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4494 _dbus_verbose ("no memory for error reply in dispatch\n");
4495 goto out;
4498 preallocated = _dbus_connection_preallocate_send_unlocked (connection);
4500 if (preallocated == NULL)
4502 dbus_message_unref (reply);
4503 result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4504 _dbus_verbose ("no memory for error send in dispatch\n");
4505 goto out;
4508 _dbus_connection_send_preallocated_unlocked_no_update (connection, preallocated,
4509 reply, NULL);
4511 dbus_message_unref (reply);
4513 result = DBUS_HANDLER_RESULT_HANDLED;
4516 _dbus_verbose (" done dispatching %p (%d %s %s '%s') on connection %p\n", message,
4517 dbus_message_get_type (message),
4518 dbus_message_get_interface (message) ?
4519 dbus_message_get_interface (message) :
4520 "no interface",
4521 dbus_message_get_member (message) ?
4522 dbus_message_get_member (message) :
4523 "no member",
4524 dbus_message_get_signature (message),
4525 connection);
4527 out:
4528 if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
4530 _dbus_verbose ("out of memory in %s\n", _DBUS_FUNCTION_NAME);
4532 /* Put message back, and we'll start over.
4533 * Yes this means handlers must be idempotent if they
4534 * don't return HANDLED; c'est la vie.
4536 _dbus_connection_putback_message_link_unlocked (connection,
4537 message_link);
4539 else
4541 _dbus_verbose (" ... done dispatching in %s\n", _DBUS_FUNCTION_NAME);
4543 _dbus_list_free_link (message_link);
4544 dbus_message_unref (message); /* don't want the message to count in max message limits
4545 * in computing dispatch status below
4549 _dbus_connection_release_dispatch (connection);
4550 HAVE_LOCK_CHECK (connection);
4552 _dbus_verbose ("%s before final status update\n", _DBUS_FUNCTION_NAME);
4553 status = _dbus_connection_get_dispatch_status_unlocked (connection);
4555 /* unlocks and calls user code */
4556 _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4558 dbus_connection_unref (connection);
4560 return status;
4564 * Sets the watch functions for the connection. These functions are
4565 * responsible for making the application's main loop aware of file
4566 * descriptors that need to be monitored for events, using select() or
4567 * poll(). When using Qt, typically the DBusAddWatchFunction would
4568 * create a QSocketNotifier. When using GLib, the DBusAddWatchFunction
4569 * could call g_io_add_watch(), or could be used as part of a more
4570 * elaborate GSource. Note that when a watch is added, it may
4571 * not be enabled.
4573 * The DBusWatchToggledFunction notifies the application that the
4574 * watch has been enabled or disabled. Call dbus_watch_get_enabled()
4575 * to check this. A disabled watch should have no effect, and enabled
4576 * watch should be added to the main loop. This feature is used
4577 * instead of simply adding/removing the watch because
4578 * enabling/disabling can be done without memory allocation. The
4579 * toggled function may be NULL if a main loop re-queries
4580 * dbus_watch_get_enabled() every time anyway.
4582 * The DBusWatch can be queried for the file descriptor to watch using
4583 * dbus_watch_get_unix_fd() or dbus_watch_get_socket(), and for the
4584 * events to watch for using dbus_watch_get_flags(). The flags
4585 * returned by dbus_watch_get_flags() will only contain
4586 * DBUS_WATCH_READABLE and DBUS_WATCH_WRITABLE, never
4587 * DBUS_WATCH_HANGUP or DBUS_WATCH_ERROR; all watches implicitly
4588 * include a watch for hangups, errors, and other exceptional
4589 * conditions.
4591 * Once a file descriptor becomes readable or writable, or an exception
4592 * occurs, dbus_watch_handle() should be called to
4593 * notify the connection of the file descriptor's condition.
4595 * dbus_watch_handle() cannot be called during the
4596 * DBusAddWatchFunction, as the connection will not be ready to handle
4597 * that watch yet.
4599 * It is not allowed to reference a DBusWatch after it has been passed
4600 * to remove_function.
4602 * If #FALSE is returned due to lack of memory, the failure may be due
4603 * to a #FALSE return from the new add_function. If so, the
4604 * add_function may have been called successfully one or more times,
4605 * but the remove_function will also have been called to remove any
4606 * successful adds. i.e. if #FALSE is returned the net result
4607 * should be that dbus_connection_set_watch_functions() has no effect,
4608 * but the add_function and remove_function may have been called.
4610 * @todo We need to drop the lock when we call the
4611 * add/remove/toggled functions which can be a side effect
4612 * of setting the watch functions.
4614 * @param connection the connection.
4615 * @param add_function function to begin monitoring a new descriptor.
4616 * @param remove_function function to stop monitoring a descriptor.
4617 * @param toggled_function function to notify of enable/disable
4618 * @param data data to pass to add_function and remove_function.
4619 * @param free_data_function function to be called to free the data.
4620 * @returns #FALSE on failure (no memory)
4622 dbus_bool_t
4623 dbus_connection_set_watch_functions (DBusConnection *connection,
4624 DBusAddWatchFunction add_function,
4625 DBusRemoveWatchFunction remove_function,
4626 DBusWatchToggledFunction toggled_function,
4627 void *data,
4628 DBusFreeFunction free_data_function)
4630 dbus_bool_t retval;
4631 DBusWatchList *watches;
4633 _dbus_return_val_if_fail (connection != NULL, FALSE);
4635 CONNECTION_LOCK (connection);
4637 #ifndef DBUS_DISABLE_CHECKS
4638 if (connection->watches == NULL)
4640 _dbus_warn_check_failed ("Re-entrant call to %s is not allowed\n",
4641 _DBUS_FUNCTION_NAME);
4642 return FALSE;
4644 #endif
4646 /* ref connection for slightly better reentrancy */
4647 _dbus_connection_ref_unlocked (connection);
4649 /* This can call back into user code, and we need to drop the
4650 * connection lock when it does. This is kind of a lame
4651 * way to do it.
4653 watches = connection->watches;
4654 connection->watches = NULL;
4655 CONNECTION_UNLOCK (connection);
4657 retval = _dbus_watch_list_set_functions (watches,
4658 add_function, remove_function,
4659 toggled_function,
4660 data, free_data_function);
4661 CONNECTION_LOCK (connection);
4662 connection->watches = watches;
4664 CONNECTION_UNLOCK (connection);
4665 /* drop our paranoid refcount */
4666 dbus_connection_unref (connection);
4668 return retval;
4672 * Sets the timeout functions for the connection. These functions are
4673 * responsible for making the application's main loop aware of timeouts.
4674 * When using Qt, typically the DBusAddTimeoutFunction would create a
4675 * QTimer. When using GLib, the DBusAddTimeoutFunction would call
4676 * g_timeout_add.
4678 * The DBusTimeoutToggledFunction notifies the application that the
4679 * timeout has been enabled or disabled. Call
4680 * dbus_timeout_get_enabled() to check this. A disabled timeout should
4681 * have no effect, and enabled timeout should be added to the main
4682 * loop. This feature is used instead of simply adding/removing the
4683 * timeout because enabling/disabling can be done without memory
4684 * allocation. With Qt, QTimer::start() and QTimer::stop() can be used
4685 * to enable and disable. The toggled function may be NULL if a main
4686 * loop re-queries dbus_timeout_get_enabled() every time anyway.
4687 * Whenever a timeout is toggled, its interval may change.
4689 * The DBusTimeout can be queried for the timer interval using
4690 * dbus_timeout_get_interval(). dbus_timeout_handle() should be called
4691 * repeatedly, each time the interval elapses, starting after it has
4692 * elapsed once. The timeout stops firing when it is removed with the
4693 * given remove_function. The timer interval may change whenever the
4694 * timeout is added, removed, or toggled.
4696 * @param connection the connection.
4697 * @param add_function function to add a timeout.
4698 * @param remove_function function to remove a timeout.
4699 * @param toggled_function function to notify of enable/disable
4700 * @param data data to pass to add_function and remove_function.
4701 * @param free_data_function function to be called to free the data.
4702 * @returns #FALSE on failure (no memory)
4704 dbus_bool_t
4705 dbus_connection_set_timeout_functions (DBusConnection *connection,
4706 DBusAddTimeoutFunction add_function,
4707 DBusRemoveTimeoutFunction remove_function,
4708 DBusTimeoutToggledFunction toggled_function,
4709 void *data,
4710 DBusFreeFunction free_data_function)
4712 dbus_bool_t retval;
4713 DBusTimeoutList *timeouts;
4715 _dbus_return_val_if_fail (connection != NULL, FALSE);
4717 CONNECTION_LOCK (connection);
4719 #ifndef DBUS_DISABLE_CHECKS
4720 if (connection->timeouts == NULL)
4722 _dbus_warn_check_failed ("Re-entrant call to %s is not allowed\n",
4723 _DBUS_FUNCTION_NAME);
4724 return FALSE;
4726 #endif
4728 /* ref connection for slightly better reentrancy */
4729 _dbus_connection_ref_unlocked (connection);
4731 timeouts = connection->timeouts;
4732 connection->timeouts = NULL;
4733 CONNECTION_UNLOCK (connection);
4735 retval = _dbus_timeout_list_set_functions (timeouts,
4736 add_function, remove_function,
4737 toggled_function,
4738 data, free_data_function);
4739 CONNECTION_LOCK (connection);
4740 connection->timeouts = timeouts;
4742 CONNECTION_UNLOCK (connection);
4743 /* drop our paranoid refcount */
4744 dbus_connection_unref (connection);
4746 return retval;
4750 * Sets the mainloop wakeup function for the connection. This function
4751 * is responsible for waking up the main loop (if its sleeping in
4752 * another thread) when some some change has happened to the
4753 * connection that the mainloop needs to reconsider (e.g. a message
4754 * has been queued for writing). When using Qt, this typically
4755 * results in a call to QEventLoop::wakeUp(). When using GLib, it
4756 * would call g_main_context_wakeup().
4758 * @param connection the connection.
4759 * @param wakeup_main_function function to wake up the mainloop
4760 * @param data data to pass wakeup_main_function
4761 * @param free_data_function function to be called to free the data.
4763 void
4764 dbus_connection_set_wakeup_main_function (DBusConnection *connection,
4765 DBusWakeupMainFunction wakeup_main_function,
4766 void *data,
4767 DBusFreeFunction free_data_function)
4769 void *old_data;
4770 DBusFreeFunction old_free_data;
4772 _dbus_return_if_fail (connection != NULL);
4774 CONNECTION_LOCK (connection);
4775 old_data = connection->wakeup_main_data;
4776 old_free_data = connection->free_wakeup_main_data;
4778 connection->wakeup_main_function = wakeup_main_function;
4779 connection->wakeup_main_data = data;
4780 connection->free_wakeup_main_data = free_data_function;
4782 CONNECTION_UNLOCK (connection);
4784 /* Callback outside the lock */
4785 if (old_free_data)
4786 (*old_free_data) (old_data);
4790 * Set a function to be invoked when the dispatch status changes.
4791 * If the dispatch status is #DBUS_DISPATCH_DATA_REMAINS, then
4792 * dbus_connection_dispatch() needs to be called to process incoming
4793 * messages. However, dbus_connection_dispatch() MUST NOT BE CALLED
4794 * from inside the DBusDispatchStatusFunction. Indeed, almost
4795 * any reentrancy in this function is a bad idea. Instead,
4796 * the DBusDispatchStatusFunction should simply save an indication
4797 * that messages should be dispatched later, when the main loop
4798 * is re-entered.
4800 * If you don't set a dispatch status function, you have to be sure to
4801 * dispatch on every iteration of your main loop, especially if
4802 * dbus_watch_handle() or dbus_timeout_handle() were called.
4804 * @param connection the connection
4805 * @param function function to call on dispatch status changes
4806 * @param data data for function
4807 * @param free_data_function free the function data
4809 void
4810 dbus_connection_set_dispatch_status_function (DBusConnection *connection,
4811 DBusDispatchStatusFunction function,
4812 void *data,
4813 DBusFreeFunction free_data_function)
4815 void *old_data;
4816 DBusFreeFunction old_free_data;
4818 _dbus_return_if_fail (connection != NULL);
4820 CONNECTION_LOCK (connection);
4821 old_data = connection->dispatch_status_data;
4822 old_free_data = connection->free_dispatch_status_data;
4824 connection->dispatch_status_function = function;
4825 connection->dispatch_status_data = data;
4826 connection->free_dispatch_status_data = free_data_function;
4828 CONNECTION_UNLOCK (connection);
4830 /* Callback outside the lock */
4831 if (old_free_data)
4832 (*old_free_data) (old_data);
4836 * Get the UNIX file descriptor of the connection, if any. This can
4837 * be used for SELinux access control checks with getpeercon() for
4838 * example. DO NOT read or write to the file descriptor, or try to
4839 * select() on it; use DBusWatch for main loop integration. Not all
4840 * connections will have a file descriptor. So for adding descriptors
4841 * to the main loop, use dbus_watch_get_unix_fd() and so forth.
4843 * If the connection is socket-based, you can also use
4844 * dbus_connection_get_socket(), which will work on Windows too.
4845 * This function always fails on Windows.
4847 * Right now the returned descriptor is always a socket, but
4848 * that is not guaranteed.
4850 * @param connection the connection
4851 * @param fd return location for the file descriptor.
4852 * @returns #TRUE if fd is successfully obtained.
4854 dbus_bool_t
4855 dbus_connection_get_unix_fd (DBusConnection *connection,
4856 int *fd)
4858 _dbus_return_val_if_fail (connection != NULL, FALSE);
4859 _dbus_return_val_if_fail (connection->transport != NULL, FALSE);
4861 #ifdef DBUS_WIN
4862 /* FIXME do this on a lower level */
4863 return FALSE;
4864 #endif
4866 return dbus_connection_get_socket(connection, fd);
4870 * Gets the underlying Windows or UNIX socket file descriptor
4871 * of the connection, if any. DO NOT read or write to the file descriptor, or try to
4872 * select() on it; use DBusWatch for main loop integration. Not all
4873 * connections will have a socket. So for adding descriptors
4874 * to the main loop, use dbus_watch_get_socket() and so forth.
4876 * If the connection is not socket-based, this function will return FALSE,
4877 * even if the connection does have a file descriptor of some kind.
4878 * i.e. this function always returns specifically a socket file descriptor.
4880 * @param connection the connection
4881 * @param fd return location for the file descriptor.
4882 * @returns #TRUE if fd is successfully obtained.
4884 dbus_bool_t
4885 dbus_connection_get_socket(DBusConnection *connection,
4886 int *fd)
4888 dbus_bool_t retval;
4890 _dbus_return_val_if_fail (connection != NULL, FALSE);
4891 _dbus_return_val_if_fail (connection->transport != NULL, FALSE);
4893 CONNECTION_LOCK (connection);
4895 retval = _dbus_transport_get_socket_fd (connection->transport,
4896 fd);
4898 CONNECTION_UNLOCK (connection);
4900 return retval;
4905 * Gets the UNIX user ID of the connection if known. Returns #TRUE if
4906 * the uid is filled in. Always returns #FALSE on non-UNIX platforms
4907 * for now, though in theory someone could hook Windows to NIS or
4908 * something. Always returns #FALSE prior to authenticating the
4909 * connection.
4911 * The UID is only read by servers from clients; clients can't usually
4912 * get the UID of servers, because servers do not authenticate to
4913 * clients. The returned UID is the UID the connection authenticated
4914 * as.
4916 * The message bus is a server and the apps connecting to the bus
4917 * are clients.
4919 * You can ask the bus to tell you the UID of another connection though
4920 * if you like; this is done with dbus_bus_get_unix_user().
4922 * @param connection the connection
4923 * @param uid return location for the user ID
4924 * @returns #TRUE if uid is filled in with a valid user ID
4926 dbus_bool_t
4927 dbus_connection_get_unix_user (DBusConnection *connection,
4928 unsigned long *uid)
4930 dbus_bool_t result;
4932 _dbus_return_val_if_fail (connection != NULL, FALSE);
4933 _dbus_return_val_if_fail (uid != NULL, FALSE);
4935 CONNECTION_LOCK (connection);
4937 if (!_dbus_transport_get_is_authenticated (connection->transport))
4938 result = FALSE;
4939 else
4940 result = _dbus_transport_get_unix_user (connection->transport,
4941 uid);
4943 #ifdef DBUS_WIN
4944 _dbus_assert (!result);
4945 #endif
4947 CONNECTION_UNLOCK (connection);
4949 return result;
4953 * Gets the process ID of the connection if any.
4954 * Returns #TRUE if the pid is filled in.
4955 * Always returns #FALSE prior to authenticating the
4956 * connection.
4958 * @param connection the connection
4959 * @param pid return location for the process ID
4960 * @returns #TRUE if uid is filled in with a valid process ID
4962 dbus_bool_t
4963 dbus_connection_get_unix_process_id (DBusConnection *connection,
4964 unsigned long *pid)
4966 dbus_bool_t result;
4968 _dbus_return_val_if_fail (connection != NULL, FALSE);
4969 _dbus_return_val_if_fail (pid != NULL, FALSE);
4971 CONNECTION_LOCK (connection);
4973 if (!_dbus_transport_get_is_authenticated (connection->transport))
4974 result = FALSE;
4975 else
4976 result = _dbus_transport_get_unix_process_id (connection->transport,
4977 pid);
4978 #ifdef DBUS_WIN
4979 _dbus_assert (!result);
4980 #endif
4982 CONNECTION_UNLOCK (connection);
4984 return result;
4988 * Gets the ADT audit data of the connection if any.
4989 * Returns #TRUE if the structure pointer is returned.
4990 * Always returns #FALSE prior to authenticating the
4991 * connection.
4993 * @param connection the connection
4994 * @param data return location for audit data
4995 * @returns #TRUE if audit data is filled in with a valid ucred pointer
4997 dbus_bool_t
4998 dbus_connection_get_adt_audit_session_data (DBusConnection *connection,
4999 void **data,
5000 dbus_int32_t *data_size)
5002 dbus_bool_t result;
5004 _dbus_return_val_if_fail (connection != NULL, FALSE);
5005 _dbus_return_val_if_fail (data != NULL, FALSE);
5006 _dbus_return_val_if_fail (data_size != NULL, FALSE);
5008 CONNECTION_LOCK (connection);
5010 if (!_dbus_transport_get_is_authenticated (connection->transport))
5011 result = FALSE;
5012 else
5013 result = _dbus_transport_get_adt_audit_session_data (connection->transport,
5014 data,
5015 data_size);
5016 CONNECTION_UNLOCK (connection);
5018 return result;
5022 * Sets a predicate function used to determine whether a given user ID
5023 * is allowed to connect. When an incoming connection has
5024 * authenticated with a particular user ID, this function is called;
5025 * if it returns #TRUE, the connection is allowed to proceed,
5026 * otherwise the connection is disconnected.
5028 * If the function is set to #NULL (as it is by default), then
5029 * only the same UID as the server process will be allowed to
5030 * connect. Also, root is always allowed to connect.
5032 * On Windows, the function will be set and its free_data_function will
5033 * be invoked when the connection is freed or a new function is set.
5034 * However, the function will never be called, because there are
5035 * no UNIX user ids to pass to it, or at least none of the existing
5036 * auth protocols would allow authenticating as a UNIX user on Windows.
5038 * @param connection the connection
5039 * @param function the predicate
5040 * @param data data to pass to the predicate
5041 * @param free_data_function function to free the data
5043 void
5044 dbus_connection_set_unix_user_function (DBusConnection *connection,
5045 DBusAllowUnixUserFunction function,
5046 void *data,
5047 DBusFreeFunction free_data_function)
5049 void *old_data = NULL;
5050 DBusFreeFunction old_free_function = NULL;
5052 _dbus_return_if_fail (connection != NULL);
5054 CONNECTION_LOCK (connection);
5055 _dbus_transport_set_unix_user_function (connection->transport,
5056 function, data, free_data_function,
5057 &old_data, &old_free_function);
5058 CONNECTION_UNLOCK (connection);
5060 if (old_free_function != NULL)
5061 (* old_free_function) (old_data);
5065 * Gets the Windows user SID of the connection if known. Returns
5066 * #TRUE if the ID is filled in. Always returns #FALSE on non-Windows
5067 * platforms for now, though in theory someone could hook UNIX to
5068 * Active Directory or something. Always returns #FALSE prior to
5069 * authenticating the connection.
5071 * The user is only read by servers from clients; clients can't usually
5072 * get the user of servers, because servers do not authenticate to
5073 * clients. The returned user is the user the connection authenticated
5074 * as.
5076 * The message bus is a server and the apps connecting to the bus
5077 * are clients.
5079 * The returned user string has to be freed with dbus_free().
5081 * The return value indicates whether the user SID is available;
5082 * if it's available but we don't have the memory to copy it,
5083 * then the return value is #TRUE and #NULL is given as the SID.
5085 * @todo We would like to be able to say "You can ask the bus to tell
5086 * you the user of another connection though if you like; this is done
5087 * with dbus_bus_get_windows_user()." But this has to be implemented
5088 * in bus/driver.c and dbus/dbus-bus.c, and is pointless anyway
5089 * since on Windows we only use the session bus for now.
5091 * @param connection the connection
5092 * @param windows_sid_p return location for an allocated copy of the user ID, or #NULL if no memory
5093 * @returns #TRUE if user is available (returned value may be #NULL anyway if no memory)
5095 dbus_bool_t
5096 dbus_connection_get_windows_user (DBusConnection *connection,
5097 char **windows_sid_p)
5099 dbus_bool_t result;
5101 _dbus_return_val_if_fail (connection != NULL, FALSE);
5102 _dbus_return_val_if_fail (windows_sid_p != NULL, FALSE);
5104 CONNECTION_LOCK (connection);
5106 if (!_dbus_transport_get_is_authenticated (connection->transport))
5107 result = FALSE;
5108 else
5109 result = _dbus_transport_get_windows_user (connection->transport,
5110 windows_sid_p);
5112 #ifdef DBUS_UNIX
5113 _dbus_assert (!result);
5114 #endif
5116 CONNECTION_UNLOCK (connection);
5118 return result;
5122 * Sets a predicate function used to determine whether a given user ID
5123 * is allowed to connect. When an incoming connection has
5124 * authenticated with a particular user ID, this function is called;
5125 * if it returns #TRUE, the connection is allowed to proceed,
5126 * otherwise the connection is disconnected.
5128 * If the function is set to #NULL (as it is by default), then
5129 * only the same user owning the server process will be allowed to
5130 * connect.
5132 * On UNIX, the function will be set and its free_data_function will
5133 * be invoked when the connection is freed or a new function is set.
5134 * However, the function will never be called, because there is no
5135 * way right now to authenticate as a Windows user on UNIX.
5137 * @param connection the connection
5138 * @param function the predicate
5139 * @param data data to pass to the predicate
5140 * @param free_data_function function to free the data
5142 void
5143 dbus_connection_set_windows_user_function (DBusConnection *connection,
5144 DBusAllowWindowsUserFunction function,
5145 void *data,
5146 DBusFreeFunction free_data_function)
5148 void *old_data = NULL;
5149 DBusFreeFunction old_free_function = NULL;
5151 _dbus_return_if_fail (connection != NULL);
5153 CONNECTION_LOCK (connection);
5154 _dbus_transport_set_windows_user_function (connection->transport,
5155 function, data, free_data_function,
5156 &old_data, &old_free_function);
5157 CONNECTION_UNLOCK (connection);
5159 if (old_free_function != NULL)
5160 (* old_free_function) (old_data);
5164 * This function must be called on the server side of a connection when the
5165 * connection is first seen in the #DBusNewConnectionFunction. If set to
5166 * #TRUE (the default is #FALSE), then the connection can proceed even if
5167 * the client does not authenticate as some user identity, i.e. clients
5168 * can connect anonymously.
5170 * This setting interacts with the available authorization mechanisms
5171 * (see dbus_server_set_auth_mechanisms()). Namely, an auth mechanism
5172 * such as ANONYMOUS that supports anonymous auth must be included in
5173 * the list of available mechanisms for anonymous login to work.
5175 * This setting also changes the default rule for connections
5176 * authorized as a user; normally, if a connection authorizes as
5177 * a user identity, it is permitted if the user identity is
5178 * root or the user identity matches the user identity of the server
5179 * process. If anonymous connections are allowed, however,
5180 * then any user identity is allowed.
5182 * You can override the rules for connections authorized as a
5183 * user identity with dbus_connection_set_unix_user_function()
5184 * and dbus_connection_set_windows_user_function().
5186 * @param connection the connection
5187 * @param value whether to allow authentication as an anonymous user
5189 void
5190 dbus_connection_set_allow_anonymous (DBusConnection *connection,
5191 dbus_bool_t value)
5193 _dbus_return_if_fail (connection != NULL);
5195 CONNECTION_LOCK (connection);
5196 _dbus_transport_set_allow_anonymous (connection->transport, value);
5197 CONNECTION_UNLOCK (connection);
5202 * Normally #DBusConnection automatically handles all messages to the
5203 * org.freedesktop.DBus.Peer interface. However, the message bus wants
5204 * to be able to route methods on that interface through the bus and
5205 * to other applications. If routing peer messages is enabled, then
5206 * messages with the org.freedesktop.DBus.Peer interface that also
5207 * have a bus destination name set will not be automatically
5208 * handled by the #DBusConnection and instead will be dispatched
5209 * normally to the application.
5211 * If a normal application sets this flag, it can break things badly.
5212 * So don't set this unless you are the message bus.
5214 * @param connection the connection
5215 * @param value #TRUE to pass through org.freedesktop.DBus.Peer messages with a bus name set
5217 void
5218 dbus_connection_set_route_peer_messages (DBusConnection *connection,
5219 dbus_bool_t value)
5221 _dbus_return_if_fail (connection != NULL);
5223 CONNECTION_LOCK (connection);
5224 connection->route_peer_messages = TRUE;
5225 CONNECTION_UNLOCK (connection);
5229 * Adds a message filter. Filters are handlers that are run on all
5230 * incoming messages, prior to the objects registered with
5231 * dbus_connection_register_object_path(). Filters are run in the
5232 * order that they were added. The same handler can be added as a
5233 * filter more than once, in which case it will be run more than once.
5234 * Filters added during a filter callback won't be run on the message
5235 * being processed.
5237 * @todo we don't run filters on messages while blocking without
5238 * entering the main loop, since filters are run as part of
5239 * dbus_connection_dispatch(). This is probably a feature, as filters
5240 * could create arbitrary reentrancy. But kind of sucks if you're
5241 * trying to filter METHOD_RETURN for some reason.
5243 * @param connection the connection
5244 * @param function function to handle messages
5245 * @param user_data user data to pass to the function
5246 * @param free_data_function function to use for freeing user data
5247 * @returns #TRUE on success, #FALSE if not enough memory.
5249 dbus_bool_t
5250 dbus_connection_add_filter (DBusConnection *connection,
5251 DBusHandleMessageFunction function,
5252 void *user_data,
5253 DBusFreeFunction free_data_function)
5255 DBusMessageFilter *filter;
5257 _dbus_return_val_if_fail (connection != NULL, FALSE);
5258 _dbus_return_val_if_fail (function != NULL, FALSE);
5260 filter = dbus_new0 (DBusMessageFilter, 1);
5261 if (filter == NULL)
5262 return FALSE;
5264 filter->refcount.value = 1;
5266 CONNECTION_LOCK (connection);
5268 if (!_dbus_list_append (&connection->filter_list,
5269 filter))
5271 _dbus_message_filter_unref (filter);
5272 CONNECTION_UNLOCK (connection);
5273 return FALSE;
5276 /* Fill in filter after all memory allocated,
5277 * so we don't run the free_user_data_function
5278 * if the add_filter() fails
5281 filter->function = function;
5282 filter->user_data = user_data;
5283 filter->free_user_data_function = free_data_function;
5285 CONNECTION_UNLOCK (connection);
5286 return TRUE;
5290 * Removes a previously-added message filter. It is a programming
5291 * error to call this function for a handler that has not been added
5292 * as a filter. If the given handler was added more than once, only
5293 * one instance of it will be removed (the most recently-added
5294 * instance).
5296 * @param connection the connection
5297 * @param function the handler to remove
5298 * @param user_data user data for the handler to remove
5301 void
5302 dbus_connection_remove_filter (DBusConnection *connection,
5303 DBusHandleMessageFunction function,
5304 void *user_data)
5306 DBusList *link;
5307 DBusMessageFilter *filter;
5309 _dbus_return_if_fail (connection != NULL);
5310 _dbus_return_if_fail (function != NULL);
5312 CONNECTION_LOCK (connection);
5314 filter = NULL;
5316 link = _dbus_list_get_last_link (&connection->filter_list);
5317 while (link != NULL)
5319 filter = link->data;
5321 if (filter->function == function &&
5322 filter->user_data == user_data)
5324 _dbus_list_remove_link (&connection->filter_list, link);
5325 filter->function = NULL;
5327 break;
5330 link = _dbus_list_get_prev_link (&connection->filter_list, link);
5333 CONNECTION_UNLOCK (connection);
5335 #ifndef DBUS_DISABLE_CHECKS
5336 if (filter == NULL)
5338 _dbus_warn_check_failed ("Attempt to remove filter function %p user data %p, but no such filter has been added\n",
5339 function, user_data);
5340 return;
5342 #endif
5344 /* Call application code */
5345 if (filter->free_user_data_function)
5346 (* filter->free_user_data_function) (filter->user_data);
5348 filter->free_user_data_function = NULL;
5349 filter->user_data = NULL;
5351 _dbus_message_filter_unref (filter);
5355 * Registers a handler for a given path in the object hierarchy.
5356 * The given vtable handles messages sent to exactly the given path.
5358 * @param connection the connection
5359 * @param path a '/' delimited string of path elements
5360 * @param vtable the virtual table
5361 * @param user_data data to pass to functions in the vtable
5362 * @param error address where an error can be returned
5363 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5364 * #DBUS_ERROR_ADDRESS_IN_USE) is reported
5366 dbus_bool_t
5367 dbus_connection_try_register_object_path (DBusConnection *connection,
5368 const char *path,
5369 const DBusObjectPathVTable *vtable,
5370 void *user_data,
5371 DBusError *error)
5373 char **decomposed_path;
5374 dbus_bool_t retval;
5376 _dbus_return_val_if_fail (connection != NULL, FALSE);
5377 _dbus_return_val_if_fail (path != NULL, FALSE);
5378 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5379 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5381 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5382 return FALSE;
5384 CONNECTION_LOCK (connection);
5386 retval = _dbus_object_tree_register (connection->objects,
5387 FALSE,
5388 (const char **) decomposed_path, vtable,
5389 user_data, error);
5391 CONNECTION_UNLOCK (connection);
5393 dbus_free_string_array (decomposed_path);
5395 return retval;
5399 * Registers a handler for a given path in the object hierarchy.
5400 * The given vtable handles messages sent to exactly the given path.
5402 * It is a bug to call this function for object paths which already
5403 * have a handler. Use dbus_connection_try_register_object_path() if this
5404 * might be the case.
5406 * @param connection the connection
5407 * @param path a '/' delimited string of path elements
5408 * @param vtable the virtual table
5409 * @param user_data data to pass to functions in the vtable
5410 * @returns #FALSE if not enough memory
5412 dbus_bool_t
5413 dbus_connection_register_object_path (DBusConnection *connection,
5414 const char *path,
5415 const DBusObjectPathVTable *vtable,
5416 void *user_data)
5418 char **decomposed_path;
5419 dbus_bool_t retval;
5420 DBusError error = DBUS_ERROR_INIT;
5422 _dbus_return_val_if_fail (connection != NULL, FALSE);
5423 _dbus_return_val_if_fail (path != NULL, FALSE);
5424 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5425 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5427 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5428 return FALSE;
5430 CONNECTION_LOCK (connection);
5432 retval = _dbus_object_tree_register (connection->objects,
5433 FALSE,
5434 (const char **) decomposed_path, vtable,
5435 user_data, &error);
5437 CONNECTION_UNLOCK (connection);
5439 dbus_free_string_array (decomposed_path);
5441 if (dbus_error_has_name (&error, DBUS_ERROR_ADDRESS_IN_USE))
5443 _dbus_warn ("%s\n", error.message);
5444 dbus_error_free (&error);
5445 return FALSE;
5448 return retval;
5452 * Registers a fallback handler for a given subsection of the object
5453 * hierarchy. The given vtable handles messages at or below the given
5454 * path. You can use this to establish a default message handling
5455 * policy for a whole "subdirectory."
5457 * @param connection the connection
5458 * @param path a '/' delimited string of path elements
5459 * @param vtable the virtual table
5460 * @param user_data data to pass to functions in the vtable
5461 * @param error address where an error can be returned
5462 * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5463 * #DBUS_ERROR_ADDRESS_IN_USE) is reported
5465 dbus_bool_t
5466 dbus_connection_try_register_fallback (DBusConnection *connection,
5467 const char *path,
5468 const DBusObjectPathVTable *vtable,
5469 void *user_data,
5470 DBusError *error)
5472 char **decomposed_path;
5473 dbus_bool_t retval;
5475 _dbus_return_val_if_fail (connection != NULL, FALSE);
5476 _dbus_return_val_if_fail (path != NULL, FALSE);
5477 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5478 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5480 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5481 return FALSE;
5483 CONNECTION_LOCK (connection);
5485 retval = _dbus_object_tree_register (connection->objects,
5486 TRUE,
5487 (const char **) decomposed_path, vtable,
5488 user_data, error);
5490 CONNECTION_UNLOCK (connection);
5492 dbus_free_string_array (decomposed_path);
5494 return retval;
5498 * Registers a fallback handler for a given subsection of the object
5499 * hierarchy. The given vtable handles messages at or below the given
5500 * path. You can use this to establish a default message handling
5501 * policy for a whole "subdirectory."
5503 * It is a bug to call this function for object paths which already
5504 * have a handler. Use dbus_connection_try_register_fallback() if this
5505 * might be the case.
5507 * @param connection the connection
5508 * @param path a '/' delimited string of path elements
5509 * @param vtable the virtual table
5510 * @param user_data data to pass to functions in the vtable
5511 * @returns #FALSE if not enough memory
5513 dbus_bool_t
5514 dbus_connection_register_fallback (DBusConnection *connection,
5515 const char *path,
5516 const DBusObjectPathVTable *vtable,
5517 void *user_data)
5519 char **decomposed_path;
5520 dbus_bool_t retval;
5521 DBusError error = DBUS_ERROR_INIT;
5523 _dbus_return_val_if_fail (connection != NULL, FALSE);
5524 _dbus_return_val_if_fail (path != NULL, FALSE);
5525 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5526 _dbus_return_val_if_fail (vtable != NULL, FALSE);
5528 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5529 return FALSE;
5531 CONNECTION_LOCK (connection);
5533 retval = _dbus_object_tree_register (connection->objects,
5534 TRUE,
5535 (const char **) decomposed_path, vtable,
5536 user_data, &error);
5538 CONNECTION_UNLOCK (connection);
5540 dbus_free_string_array (decomposed_path);
5542 if (dbus_error_has_name (&error, DBUS_ERROR_ADDRESS_IN_USE))
5544 _dbus_warn ("%s\n", error.message);
5545 dbus_error_free (&error);
5546 return FALSE;
5549 return retval;
5553 * Unregisters the handler registered with exactly the given path.
5554 * It's a bug to call this function for a path that isn't registered.
5555 * Can unregister both fallback paths and object paths.
5557 * @param connection the connection
5558 * @param path a '/' delimited string of path elements
5559 * @returns #FALSE if not enough memory
5561 dbus_bool_t
5562 dbus_connection_unregister_object_path (DBusConnection *connection,
5563 const char *path)
5565 char **decomposed_path;
5567 _dbus_return_val_if_fail (connection != NULL, FALSE);
5568 _dbus_return_val_if_fail (path != NULL, FALSE);
5569 _dbus_return_val_if_fail (path[0] == '/', FALSE);
5571 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5572 return FALSE;
5574 CONNECTION_LOCK (connection);
5576 _dbus_object_tree_unregister_and_unlock (connection->objects, (const char **) decomposed_path);
5578 dbus_free_string_array (decomposed_path);
5580 return TRUE;
5584 * Gets the user data passed to dbus_connection_register_object_path()
5585 * or dbus_connection_register_fallback(). If nothing was registered
5586 * at this path, the data is filled in with #NULL.
5588 * @param connection the connection
5589 * @param path the path you registered with
5590 * @param data_p location to store the user data, or #NULL
5591 * @returns #FALSE if not enough memory
5593 dbus_bool_t
5594 dbus_connection_get_object_path_data (DBusConnection *connection,
5595 const char *path,
5596 void **data_p)
5598 char **decomposed_path;
5600 _dbus_return_val_if_fail (connection != NULL, FALSE);
5601 _dbus_return_val_if_fail (path != NULL, FALSE);
5602 _dbus_return_val_if_fail (data_p != NULL, FALSE);
5604 *data_p = NULL;
5606 if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5607 return FALSE;
5609 CONNECTION_LOCK (connection);
5611 *data_p = _dbus_object_tree_get_user_data_unlocked (connection->objects, (const char**) decomposed_path);
5613 CONNECTION_UNLOCK (connection);
5615 dbus_free_string_array (decomposed_path);
5617 return TRUE;
5621 * Lists the registered fallback handlers and object path handlers at
5622 * the given parent_path. The returned array should be freed with
5623 * dbus_free_string_array().
5625 * @param connection the connection
5626 * @param parent_path the path to list the child handlers of
5627 * @param child_entries returns #NULL-terminated array of children
5628 * @returns #FALSE if no memory to allocate the child entries
5630 dbus_bool_t
5631 dbus_connection_list_registered (DBusConnection *connection,
5632 const char *parent_path,
5633 char ***child_entries)
5635 char **decomposed_path;
5636 dbus_bool_t retval;
5637 _dbus_return_val_if_fail (connection != NULL, FALSE);
5638 _dbus_return_val_if_fail (parent_path != NULL, FALSE);
5639 _dbus_return_val_if_fail (parent_path[0] == '/', FALSE);
5640 _dbus_return_val_if_fail (child_entries != NULL, FALSE);
5642 if (!_dbus_decompose_path (parent_path, strlen (parent_path), &decomposed_path, NULL))
5643 return FALSE;
5645 CONNECTION_LOCK (connection);
5647 retval = _dbus_object_tree_list_registered_and_unlock (connection->objects,
5648 (const char **) decomposed_path,
5649 child_entries);
5650 dbus_free_string_array (decomposed_path);
5652 return retval;
5655 static DBusDataSlotAllocator slot_allocator;
5656 _DBUS_DEFINE_GLOBAL_LOCK (connection_slots);
5659 * Allocates an integer ID to be used for storing application-specific
5660 * data on any DBusConnection. The allocated ID may then be used
5661 * with dbus_connection_set_data() and dbus_connection_get_data().
5662 * The passed-in slot must be initialized to -1, and is filled in
5663 * with the slot ID. If the passed-in slot is not -1, it's assumed
5664 * to be already allocated, and its refcount is incremented.
5666 * The allocated slot is global, i.e. all DBusConnection objects will
5667 * have a slot with the given integer ID reserved.
5669 * @param slot_p address of a global variable storing the slot
5670 * @returns #FALSE on failure (no memory)
5672 dbus_bool_t
5673 dbus_connection_allocate_data_slot (dbus_int32_t *slot_p)
5675 return _dbus_data_slot_allocator_alloc (&slot_allocator,
5676 &_DBUS_LOCK_NAME (connection_slots),
5677 slot_p);
5681 * Deallocates a global ID for connection data slots.
5682 * dbus_connection_get_data() and dbus_connection_set_data() may no
5683 * longer be used with this slot. Existing data stored on existing
5684 * DBusConnection objects will be freed when the connection is
5685 * finalized, but may not be retrieved (and may only be replaced if
5686 * someone else reallocates the slot). When the refcount on the
5687 * passed-in slot reaches 0, it is set to -1.
5689 * @param slot_p address storing the slot to deallocate
5691 void
5692 dbus_connection_free_data_slot (dbus_int32_t *slot_p)
5694 _dbus_return_if_fail (*slot_p >= 0);
5696 _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
5700 * Stores a pointer on a DBusConnection, along
5701 * with an optional function to be used for freeing
5702 * the data when the data is set again, or when
5703 * the connection is finalized. The slot number
5704 * must have been allocated with dbus_connection_allocate_data_slot().
5706 * @param connection the connection
5707 * @param slot the slot number
5708 * @param data the data to store
5709 * @param free_data_func finalizer function for the data
5710 * @returns #TRUE if there was enough memory to store the data
5712 dbus_bool_t
5713 dbus_connection_set_data (DBusConnection *connection,
5714 dbus_int32_t slot,
5715 void *data,
5716 DBusFreeFunction free_data_func)
5718 DBusFreeFunction old_free_func;
5719 void *old_data;
5720 dbus_bool_t retval;
5722 _dbus_return_val_if_fail (connection != NULL, FALSE);
5723 _dbus_return_val_if_fail (slot >= 0, FALSE);
5725 CONNECTION_LOCK (connection);
5727 retval = _dbus_data_slot_list_set (&slot_allocator,
5728 &connection->slot_list,
5729 slot, data, free_data_func,
5730 &old_free_func, &old_data);
5732 CONNECTION_UNLOCK (connection);
5734 if (retval)
5736 /* Do the actual free outside the connection lock */
5737 if (old_free_func)
5738 (* old_free_func) (old_data);
5741 return retval;
5745 * Retrieves data previously set with dbus_connection_set_data().
5746 * The slot must still be allocated (must not have been freed).
5748 * @param connection the connection
5749 * @param slot the slot to get data from
5750 * @returns the data, or #NULL if not found
5752 void*
5753 dbus_connection_get_data (DBusConnection *connection,
5754 dbus_int32_t slot)
5756 void *res;
5758 _dbus_return_val_if_fail (connection != NULL, NULL);
5760 CONNECTION_LOCK (connection);
5762 res = _dbus_data_slot_list_get (&slot_allocator,
5763 &connection->slot_list,
5764 slot);
5766 CONNECTION_UNLOCK (connection);
5768 return res;
5772 * This function sets a global flag for whether dbus_connection_new()
5773 * will set SIGPIPE behavior to SIG_IGN.
5775 * @param will_modify_sigpipe #TRUE to allow sigpipe to be set to SIG_IGN
5777 void
5778 dbus_connection_set_change_sigpipe (dbus_bool_t will_modify_sigpipe)
5780 _dbus_modify_sigpipe = will_modify_sigpipe != FALSE;
5784 * Specifies the maximum size message this connection is allowed to
5785 * receive. Larger messages will result in disconnecting the
5786 * connection.
5788 * @param connection a #DBusConnection
5789 * @param size maximum message size the connection can receive, in bytes
5791 void
5792 dbus_connection_set_max_message_size (DBusConnection *connection,
5793 long size)
5795 _dbus_return_if_fail (connection != NULL);
5797 CONNECTION_LOCK (connection);
5798 _dbus_transport_set_max_message_size (connection->transport,
5799 size);
5800 CONNECTION_UNLOCK (connection);
5804 * Gets the value set by dbus_connection_set_max_message_size().
5806 * @param connection the connection
5807 * @returns the max size of a single message
5809 long
5810 dbus_connection_get_max_message_size (DBusConnection *connection)
5812 long res;
5814 _dbus_return_val_if_fail (connection != NULL, 0);
5816 CONNECTION_LOCK (connection);
5817 res = _dbus_transport_get_max_message_size (connection->transport);
5818 CONNECTION_UNLOCK (connection);
5819 return res;
5823 * Sets the maximum total number of bytes that can be used for all messages
5824 * received on this connection. Messages count toward the maximum until
5825 * they are finalized. When the maximum is reached, the connection will
5826 * not read more data until some messages are finalized.
5828 * The semantics of the maximum are: if outstanding messages are
5829 * already above the maximum, additional messages will not be read.
5830 * The semantics are not: if the next message would cause us to exceed
5831 * the maximum, we don't read it. The reason is that we don't know the
5832 * size of a message until after we read it.
5834 * Thus, the max live messages size can actually be exceeded
5835 * by up to the maximum size of a single message.
5837 * Also, if we read say 1024 bytes off the wire in a single read(),
5838 * and that contains a half-dozen small messages, we may exceed the
5839 * size max by that amount. But this should be inconsequential.
5841 * This does imply that we can't call read() with a buffer larger
5842 * than we're willing to exceed this limit by.
5844 * @param connection the connection
5845 * @param size the maximum size in bytes of all outstanding messages
5847 void
5848 dbus_connection_set_max_received_size (DBusConnection *connection,
5849 long size)
5851 _dbus_return_if_fail (connection != NULL);
5853 CONNECTION_LOCK (connection);
5854 _dbus_transport_set_max_received_size (connection->transport,
5855 size);
5856 CONNECTION_UNLOCK (connection);
5860 * Gets the value set by dbus_connection_set_max_received_size().
5862 * @param connection the connection
5863 * @returns the max size of all live messages
5865 long
5866 dbus_connection_get_max_received_size (DBusConnection *connection)
5868 long res;
5870 _dbus_return_val_if_fail (connection != NULL, 0);
5872 CONNECTION_LOCK (connection);
5873 res = _dbus_transport_get_max_received_size (connection->transport);
5874 CONNECTION_UNLOCK (connection);
5875 return res;
5879 * Gets the approximate size in bytes of all messages in the outgoing
5880 * message queue. The size is approximate in that you shouldn't use
5881 * it to decide how many bytes to read off the network or anything
5882 * of that nature, as optimizations may choose to tell small white lies
5883 * to avoid performance overhead.
5885 * @param connection the connection
5886 * @returns the number of bytes that have been queued up but not sent
5888 long
5889 dbus_connection_get_outgoing_size (DBusConnection *connection)
5891 long res;
5893 _dbus_return_val_if_fail (connection != NULL, 0);
5895 CONNECTION_LOCK (connection);
5896 res = _dbus_counter_get_value (connection->outgoing_counter);
5897 CONNECTION_UNLOCK (connection);
5898 return res;
5901 /** @} */