Home | History | Annotate | Download | only in dbus
      1 /* -*- mode: C; c-file-style: "gnu" -*- */
      2 /* dbus-connection.c DBusConnection object
      3  *
      4  * Copyright (C) 2002-2006  Red Hat Inc.
      5  *
      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.
     12  *
     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.
     17  *
     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
     21  *
     22  */
     23 
     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"
     44 
     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
     61 
     62 #define TRACE_LOCKS 0
     63 
     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)
     69 
     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)
     75 
     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                       "???")
     81 
     82 /**
     83  * @defgroup DBusConnection DBusConnection
     84  * @ingroup  DBus
     85  * @brief Connection to another application
     86  *
     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.
     92  *
     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.
     97  *
     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>
    104  *
    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.
    107  *
    108  * In an application with a main loop, the read/write/dispatch
    109  * operations are usually separate.
    110  *
    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.
    114  *
    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.
    119  *
    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.
    124  *
    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().
    129  *
    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.
    137  *
    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.
    141  *
    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).
    147  *
    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.
    155  *
    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.
    160  *
    161  * You may not drop the last reference to a #DBusConnection
    162  * until that connection has been disconnected.
    163  *
    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).
    168  *
    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.
    175  *
    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.
    180  *
    181  * It's recommended to dispatch from a single thread.
    182  *
    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.
    186  *
    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.
    189  */
    190 
    191 /**
    192  * @defgroup DBusConnectionInternals DBusConnection implementation details
    193  * @ingroup  DBusInternals
    194  * @brief Implementation details of DBusConnection
    195  *
    196  * @{
    197  */
    198 
    199 /**
    200  * Internal struct representing a message filter function
    201  */
    202 typedef struct DBusMessageFilter DBusMessageFilter;
    203 
    204 /**
    205  * Internal struct representing a message filter function
    206  */
    207 struct DBusMessageFilter
    208 {
    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 */
    213 };
    214 
    215 
    216 /**
    217  * Internals of DBusPreallocatedSend
    218  */
    219 struct DBusPreallocatedSend
    220 {
    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 */
    224 };
    225 
    226 static dbus_bool_t _dbus_modify_sigpipe = TRUE;
    227 
    228 /**
    229  * Implementation details of DBusConnection. All fields are private.
    230  */
    231 struct DBusConnection
    232 {
    233   DBusAtomic refcount; /**< Reference count. */
    234 
    235   DBusMutex *mutex; /**< Lock on the entire DBusConnection */
    236 
    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 */
    241 
    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. */
    244 
    245   DBusMessage *message_borrowed; /**< Filled in if the first incoming message has been borrowed;
    246                                   *   dispatch_acquired will be set by the borrower
    247                                   */
    248 
    249   int n_outgoing;              /**< Length of outgoing queue. */
    250   int n_incoming;              /**< Length of incoming queue. */
    251 
    252   DBusCounter *outgoing_counter; /**< Counts size of outgoing messages. */
    253 
    254   DBusTransport *transport;    /**< Object that sends/receives messages over network. */
    255   DBusWatchList *watches;      /**< Stores active watches. */
    256   DBusTimeoutList *timeouts;   /**< Stores active timeouts. */
    257 
    258   DBusList *filter_list;        /**< List of filters. */
    259 
    260   DBusDataSlotList slot_list;   /**< Data stored by allocated integer ID */
    261 
    262   DBusHashTable *pending_replies;  /**< Hash of message serials to #DBusPendingCall. */
    263 
    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 */
    266 
    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 */
    270 
    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 */
    274 
    275   DBusDispatchStatus last_dispatch_status; /**< The last dispatch status we reported to the application. */
    276 
    277   DBusList *link_cache; /**< A cache of linked list links to prevent contention
    278                          *   for the global linked list mempool lock
    279                          */
    280   DBusObjectTree *objects; /**< Object path handlers registered with this connection */
    281 
    282   char *server_guid; /**< GUID of server if we are in shared_connections, #NULL if server GUID is unknown or connection is private */
    283 
    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.
    287    */
    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) */
    290 
    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 */
    292 
    293   unsigned int exit_on_disconnect : 1; /**< If #TRUE, exit after handling disconnect signal */
    294 
    295   unsigned int route_peer_messages : 1; /**< If #TRUE, if org.freedesktop.DBus.Peer messages have a bus name, don't handle them automatically */
    296 
    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.
    300                                                     */
    301   unsigned int disconnected_message_processed : 1; /**< We did our default handling of the disconnected message,
    302                                                     * such as closing the connection.
    303                                                     */
    304 
    305 #ifndef DBUS_DISABLE_CHECKS
    306   unsigned int have_connection_lock : 1; /**< Used to check locking */
    307 #endif
    308 
    309 #ifndef DBUS_DISABLE_CHECKS
    310   int generation; /**< _dbus_current_generation that should correspond to this connection */
    311 #endif
    312 };
    313 
    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);
    323 static dbus_bool_t        _dbus_connection_peek_for_reply_unlocked           (DBusConnection     *connection,
    324                                                                               dbus_uint32_t       client_serial);
    325 
    326 static DBusMessageFilter *
    327 _dbus_message_filter_ref (DBusMessageFilter *filter)
    328 {
    329   _dbus_assert (filter->refcount.value > 0);
    330   _dbus_atomic_inc (&filter->refcount);
    331 
    332   return filter;
    333 }
    334 
    335 static void
    336 _dbus_message_filter_unref (DBusMessageFilter *filter)
    337 {
    338   _dbus_assert (filter->refcount.value > 0);
    339 
    340   if (_dbus_atomic_dec (&filter->refcount) == 1)
    341     {
    342       if (filter->free_user_data_function)
    343         (* filter->free_user_data_function) (filter->user_data);
    344 
    345       dbus_free (filter);
    346     }
    347 }
    348 
    349 /**
    350  * Acquires the connection lock.
    351  *
    352  * @param connection the connection.
    353  */
    354 void
    355 _dbus_connection_lock (DBusConnection *connection)
    356 {
    357   CONNECTION_LOCK (connection);
    358 }
    359 
    360 /**
    361  * Releases the connection lock.
    362  *
    363  * @param connection the connection.
    364  */
    365 void
    366 _dbus_connection_unlock (DBusConnection *connection)
    367 {
    368   CONNECTION_UNLOCK (connection);
    369 }
    370 
    371 /**
    372  * Wakes up the main loop if it is sleeping
    373  * Needed if we're e.g. queueing outgoing messages
    374  * on a thread while the mainloop sleeps.
    375  *
    376  * @param connection the connection.
    377  */
    378 static void
    379 _dbus_connection_wakeup_mainloop (DBusConnection *connection)
    380 {
    381   if (connection->wakeup_main_function)
    382     (*connection->wakeup_main_function) (connection->wakeup_main_data);
    383 }
    384 
    385 #ifdef DBUS_BUILD_TESTS
    386 /* For now this function isn't used */
    387 /**
    388  * Adds a message to the incoming message queue, returning #FALSE
    389  * if there's insufficient memory to queue the message.
    390  * Does not take over refcount of the message.
    391  *
    392  * @param connection the connection.
    393  * @param message the message to queue.
    394  * @returns #TRUE on success.
    395  */
    396 dbus_bool_t
    397 _dbus_connection_queue_received_message (DBusConnection *connection,
    398                                          DBusMessage    *message)
    399 {
    400   DBusList *link;
    401 
    402   link = _dbus_list_alloc_link (message);
    403   if (link == NULL)
    404     return FALSE;
    405 
    406   dbus_message_ref (message);
    407   _dbus_connection_queue_received_message_link (connection, link);
    408 
    409   return TRUE;
    410 }
    411 
    412 /**
    413  * Gets the locks so we can examine them
    414  *
    415  * @param connection the connection.
    416  * @param mutex_loc return for the location of the main mutex pointer
    417  * @param dispatch_mutex_loc return location of the dispatch mutex pointer
    418  * @param io_path_mutex_loc return location of the io_path mutex pointer
    419  * @param dispatch_cond_loc return location of the dispatch conditional
    420  *        variable pointer
    421  * @param io_path_cond_loc return location of the io_path conditional
    422  *        variable pointer
    423  */
    424 void
    425 _dbus_connection_test_get_locks (DBusConnection *connection,
    426                                  DBusMutex     **mutex_loc,
    427                                  DBusMutex     **dispatch_mutex_loc,
    428                                  DBusMutex     **io_path_mutex_loc,
    429                                  DBusCondVar   **dispatch_cond_loc,
    430                                  DBusCondVar   **io_path_cond_loc)
    431 {
    432   *mutex_loc = connection->mutex;
    433   *dispatch_mutex_loc = connection->dispatch_mutex;
    434   *io_path_mutex_loc = connection->io_path_mutex;
    435   *dispatch_cond_loc = connection->dispatch_cond;
    436   *io_path_cond_loc = connection->io_path_cond;
    437 }
    438 #endif
    439 
    440 /**
    441  * Adds a message-containing list link to the incoming message queue,
    442  * taking ownership of the link and the message's current refcount.
    443  * Cannot fail due to lack of memory.
    444  *
    445  * @param connection the connection.
    446  * @param link the message link to queue.
    447  */
    448 void
    449 _dbus_connection_queue_received_message_link (DBusConnection  *connection,
    450                                               DBusList        *link)
    451 {
    452   DBusPendingCall *pending;
    453   dbus_int32_t reply_serial;
    454   DBusMessage *message;
    455 
    456   _dbus_assert (_dbus_transport_get_is_authenticated (connection->transport));
    457 
    458   _dbus_list_append_link (&connection->incoming_messages,
    459                           link);
    460   message = link->data;
    461 
    462   /* If this is a reply we're waiting on, remove timeout for it */
    463   reply_serial = dbus_message_get_reply_serial (message);
    464   if (reply_serial != -1)
    465     {
    466       pending = _dbus_hash_table_lookup_int (connection->pending_replies,
    467                                              reply_serial);
    468       if (pending != NULL)
    469 	{
    470 	  if (_dbus_pending_call_is_timeout_added_unlocked (pending))
    471             _dbus_connection_remove_timeout_unlocked (connection,
    472                                                       _dbus_pending_call_get_timeout_unlocked (pending));
    473 
    474 	  _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
    475 	}
    476     }
    477 
    478 
    479 
    480   connection->n_incoming += 1;
    481 
    482   _dbus_connection_wakeup_mainloop (connection);
    483 
    484   _dbus_verbose ("Message %p (%d %s %s %s '%s' reply to %u) added to incoming queue %p, %d incoming\n",
    485                  message,
    486                  dbus_message_get_type (message),
    487                  dbus_message_get_path (message) ?
    488                  dbus_message_get_path (message) :
    489                  "no path",
    490                  dbus_message_get_interface (message) ?
    491                  dbus_message_get_interface (message) :
    492                  "no interface",
    493                  dbus_message_get_member (message) ?
    494                  dbus_message_get_member (message) :
    495                  "no member",
    496                  dbus_message_get_signature (message),
    497                  dbus_message_get_reply_serial (message),
    498                  connection,
    499                  connection->n_incoming);}
    500 
    501 /**
    502  * Adds a link + message to the incoming message queue.
    503  * Can't fail. Takes ownership of both link and message.
    504  *
    505  * @param connection the connection.
    506  * @param link the list node and message to queue.
    507  *
    508  */
    509 void
    510 _dbus_connection_queue_synthesized_message_link (DBusConnection *connection,
    511 						 DBusList *link)
    512 {
    513   HAVE_LOCK_CHECK (connection);
    514 
    515   _dbus_list_append_link (&connection->incoming_messages, link);
    516 
    517   connection->n_incoming += 1;
    518 
    519   _dbus_connection_wakeup_mainloop (connection);
    520 
    521   _dbus_verbose ("Synthesized message %p added to incoming queue %p, %d incoming\n",
    522                  link->data, connection, connection->n_incoming);
    523 }
    524 
    525 
    526 /**
    527  * Checks whether there are messages in the outgoing message queue.
    528  * Called with connection lock held.
    529  *
    530  * @param connection the connection.
    531  * @returns #TRUE if the outgoing queue is non-empty.
    532  */
    533 dbus_bool_t
    534 _dbus_connection_has_messages_to_send_unlocked (DBusConnection *connection)
    535 {
    536   HAVE_LOCK_CHECK (connection);
    537   return connection->outgoing_messages != NULL;
    538 }
    539 
    540 /**
    541  * Checks whether there are messages in the outgoing message queue.
    542  * Use dbus_connection_flush() to block until all outgoing
    543  * messages have been written to the underlying transport
    544  * (such as a socket).
    545  *
    546  * @param connection the connection.
    547  * @returns #TRUE if the outgoing queue is non-empty.
    548  */
    549 dbus_bool_t
    550 dbus_connection_has_messages_to_send (DBusConnection *connection)
    551 {
    552   dbus_bool_t v;
    553 
    554   _dbus_return_val_if_fail (connection != NULL, FALSE);
    555 
    556   CONNECTION_LOCK (connection);
    557   v = _dbus_connection_has_messages_to_send_unlocked (connection);
    558   CONNECTION_UNLOCK (connection);
    559 
    560   return v;
    561 }
    562 
    563 /**
    564  * Gets the next outgoing message. The message remains in the
    565  * queue, and the caller does not own a reference to it.
    566  *
    567  * @param connection the connection.
    568  * @returns the message to be sent.
    569  */
    570 DBusMessage*
    571 _dbus_connection_get_message_to_send (DBusConnection *connection)
    572 {
    573   HAVE_LOCK_CHECK (connection);
    574 
    575   return _dbus_list_get_last (&connection->outgoing_messages);
    576 }
    577 
    578 /**
    579  * Notifies the connection that a message has been sent, so the
    580  * message can be removed from the outgoing queue.
    581  * Called with the connection lock held.
    582  *
    583  * @param connection the connection.
    584  * @param message the message that was sent.
    585  */
    586 void
    587 _dbus_connection_message_sent (DBusConnection *connection,
    588                                DBusMessage    *message)
    589 {
    590   DBusList *link;
    591 
    592   HAVE_LOCK_CHECK (connection);
    593 
    594   /* This can be called before we even complete authentication, since
    595    * it's called on disconnect to clean up the outgoing queue.
    596    * It's also called as we successfully send each message.
    597    */
    598 
    599   link = _dbus_list_get_last_link (&connection->outgoing_messages);
    600   _dbus_assert (link != NULL);
    601   _dbus_assert (link->data == message);
    602 
    603   /* Save this link in the link cache */
    604   _dbus_list_unlink (&connection->outgoing_messages,
    605                      link);
    606   _dbus_list_prepend_link (&connection->link_cache, link);
    607 
    608   connection->n_outgoing -= 1;
    609 
    610   _dbus_verbose ("Message %p (%d %s %s %s '%s') removed from outgoing queue %p, %d left to send\n",
    611                  message,
    612                  dbus_message_get_type (message),
    613                  dbus_message_get_path (message) ?
    614                  dbus_message_get_path (message) :
    615                  "no path",
    616                  dbus_message_get_interface (message) ?
    617                  dbus_message_get_interface (message) :
    618                  "no interface",
    619                  dbus_message_get_member (message) ?
    620                  dbus_message_get_member (message) :
    621                  "no member",
    622                  dbus_message_get_signature (message),
    623                  connection, connection->n_outgoing);
    624 
    625   /* Save this link in the link cache also */
    626   _dbus_message_remove_size_counter (message, connection->outgoing_counter,
    627                                      &link);
    628   _dbus_list_prepend_link (&connection->link_cache, link);
    629 
    630   dbus_message_unref (message);
    631 }
    632 
    633 /** Function to be called in protected_change_watch() with refcount held */
    634 typedef dbus_bool_t (* DBusWatchAddFunction)     (DBusWatchList *list,
    635                                                   DBusWatch     *watch);
    636 /** Function to be called in protected_change_watch() with refcount held */
    637 typedef void        (* DBusWatchRemoveFunction)  (DBusWatchList *list,
    638                                                   DBusWatch     *watch);
    639 /** Function to be called in protected_change_watch() with refcount held */
    640 typedef void        (* DBusWatchToggleFunction)  (DBusWatchList *list,
    641                                                   DBusWatch     *watch,
    642                                                   dbus_bool_t    enabled);
    643 
    644 static dbus_bool_t
    645 protected_change_watch (DBusConnection         *connection,
    646                         DBusWatch              *watch,
    647                         DBusWatchAddFunction    add_function,
    648                         DBusWatchRemoveFunction remove_function,
    649                         DBusWatchToggleFunction toggle_function,
    650                         dbus_bool_t             enabled)
    651 {
    652   DBusWatchList *watches;
    653   dbus_bool_t retval;
    654 
    655   HAVE_LOCK_CHECK (connection);
    656 
    657   /* This isn't really safe or reasonable; a better pattern is the "do everything, then
    658    * drop lock and call out" one; but it has to be propagated up through all callers
    659    */
    660 
    661   watches = connection->watches;
    662   if (watches)
    663     {
    664       connection->watches = NULL;
    665       _dbus_connection_ref_unlocked (connection);
    666       CONNECTION_UNLOCK (connection);
    667 
    668       if (add_function)
    669         retval = (* add_function) (watches, watch);
    670       else if (remove_function)
    671         {
    672           retval = TRUE;
    673           (* remove_function) (watches, watch);
    674         }
    675       else
    676         {
    677           retval = TRUE;
    678           (* toggle_function) (watches, watch, enabled);
    679         }
    680 
    681       CONNECTION_LOCK (connection);
    682       connection->watches = watches;
    683       _dbus_connection_unref_unlocked (connection);
    684 
    685       return retval;
    686     }
    687   else
    688     return FALSE;
    689 }
    690 
    691 
    692 /**
    693  * Adds a watch using the connection's DBusAddWatchFunction if
    694  * available. Otherwise records the watch to be added when said
    695  * function is available. Also re-adds the watch if the
    696  * DBusAddWatchFunction changes. May fail due to lack of memory.
    697  * Connection lock should be held when calling this.
    698  *
    699  * @param connection the connection.
    700  * @param watch the watch to add.
    701  * @returns #TRUE on success.
    702  */
    703 dbus_bool_t
    704 _dbus_connection_add_watch_unlocked (DBusConnection *connection,
    705                                      DBusWatch      *watch)
    706 {
    707   return protected_change_watch (connection, watch,
    708                                  _dbus_watch_list_add_watch,
    709                                  NULL, NULL, FALSE);
    710 }
    711 
    712 /**
    713  * Removes a watch using the connection's DBusRemoveWatchFunction
    714  * if available. It's an error to call this function on a watch
    715  * that was not previously added.
    716  * Connection lock should be held when calling this.
    717  *
    718  * @param connection the connection.
    719  * @param watch the watch to remove.
    720  */
    721 void
    722 _dbus_connection_remove_watch_unlocked (DBusConnection *connection,
    723                                         DBusWatch      *watch)
    724 {
    725   protected_change_watch (connection, watch,
    726                           NULL,
    727                           _dbus_watch_list_remove_watch,
    728                           NULL, FALSE);
    729 }
    730 
    731 /**
    732  * Toggles a watch and notifies app via connection's
    733  * DBusWatchToggledFunction if available. It's an error to call this
    734  * function on a watch that was not previously added.
    735  * Connection lock should be held when calling this.
    736  *
    737  * @param connection the connection.
    738  * @param watch the watch to toggle.
    739  * @param enabled whether to enable or disable
    740  */
    741 void
    742 _dbus_connection_toggle_watch_unlocked (DBusConnection *connection,
    743                                         DBusWatch      *watch,
    744                                         dbus_bool_t     enabled)
    745 {
    746   _dbus_assert (watch != NULL);
    747 
    748   protected_change_watch (connection, watch,
    749                           NULL, NULL,
    750                           _dbus_watch_list_toggle_watch,
    751                           enabled);
    752 }
    753 
    754 /** Function to be called in protected_change_timeout() with refcount held */
    755 typedef dbus_bool_t (* DBusTimeoutAddFunction)    (DBusTimeoutList *list,
    756                                                    DBusTimeout     *timeout);
    757 /** Function to be called in protected_change_timeout() with refcount held */
    758 typedef void        (* DBusTimeoutRemoveFunction) (DBusTimeoutList *list,
    759                                                    DBusTimeout     *timeout);
    760 /** Function to be called in protected_change_timeout() with refcount held */
    761 typedef void        (* DBusTimeoutToggleFunction) (DBusTimeoutList *list,
    762                                                    DBusTimeout     *timeout,
    763                                                    dbus_bool_t      enabled);
    764 
    765 static dbus_bool_t
    766 protected_change_timeout (DBusConnection           *connection,
    767                           DBusTimeout              *timeout,
    768                           DBusTimeoutAddFunction    add_function,
    769                           DBusTimeoutRemoveFunction remove_function,
    770                           DBusTimeoutToggleFunction toggle_function,
    771                           dbus_bool_t               enabled)
    772 {
    773   DBusTimeoutList *timeouts;
    774   dbus_bool_t retval;
    775 
    776   HAVE_LOCK_CHECK (connection);
    777 
    778   /* This isn't really safe or reasonable; a better pattern is the "do everything, then
    779    * drop lock and call out" one; but it has to be propagated up through all callers
    780    */
    781 
    782   timeouts = connection->timeouts;
    783   if (timeouts)
    784     {
    785       connection->timeouts = NULL;
    786       _dbus_connection_ref_unlocked (connection);
    787       CONNECTION_UNLOCK (connection);
    788 
    789       if (add_function)
    790         retval = (* add_function) (timeouts, timeout);
    791       else if (remove_function)
    792         {
    793           retval = TRUE;
    794           (* remove_function) (timeouts, timeout);
    795         }
    796       else
    797         {
    798           retval = TRUE;
    799           (* toggle_function) (timeouts, timeout, enabled);
    800         }
    801 
    802       CONNECTION_LOCK (connection);
    803       connection->timeouts = timeouts;
    804       _dbus_connection_unref_unlocked (connection);
    805 
    806       return retval;
    807     }
    808   else
    809     return FALSE;
    810 }
    811 
    812 /**
    813  * Adds a timeout using the connection's DBusAddTimeoutFunction if
    814  * available. Otherwise records the timeout to be added when said
    815  * function is available. Also re-adds the timeout if the
    816  * DBusAddTimeoutFunction changes. May fail due to lack of memory.
    817  * The timeout will fire repeatedly until removed.
    818  * Connection lock should be held when calling this.
    819  *
    820  * @param connection the connection.
    821  * @param timeout the timeout to add.
    822  * @returns #TRUE on success.
    823  */
    824 dbus_bool_t
    825 _dbus_connection_add_timeout_unlocked (DBusConnection *connection,
    826                                        DBusTimeout    *timeout)
    827 {
    828   return protected_change_timeout (connection, timeout,
    829                                    _dbus_timeout_list_add_timeout,
    830                                    NULL, NULL, FALSE);
    831 }
    832 
    833 /**
    834  * Removes a timeout using the connection's DBusRemoveTimeoutFunction
    835  * if available. It's an error to call this function on a timeout
    836  * that was not previously added.
    837  * Connection lock should be held when calling this.
    838  *
    839  * @param connection the connection.
    840  * @param timeout the timeout to remove.
    841  */
    842 void
    843 _dbus_connection_remove_timeout_unlocked (DBusConnection *connection,
    844                                           DBusTimeout    *timeout)
    845 {
    846   protected_change_timeout (connection, timeout,
    847                             NULL,
    848                             _dbus_timeout_list_remove_timeout,
    849                             NULL, FALSE);
    850 }
    851 
    852 /**
    853  * Toggles a timeout and notifies app via connection's
    854  * DBusTimeoutToggledFunction if available. It's an error to call this
    855  * function on a timeout that was not previously added.
    856  * Connection lock should be held when calling this.
    857  *
    858  * @param connection the connection.
    859  * @param timeout the timeout to toggle.
    860  * @param enabled whether to enable or disable
    861  */
    862 void
    863 _dbus_connection_toggle_timeout_unlocked (DBusConnection   *connection,
    864                                           DBusTimeout      *timeout,
    865                                           dbus_bool_t       enabled)
    866 {
    867   protected_change_timeout (connection, timeout,
    868                             NULL, NULL,
    869                             _dbus_timeout_list_toggle_timeout,
    870                             enabled);
    871 }
    872 
    873 static dbus_bool_t
    874 _dbus_connection_attach_pending_call_unlocked (DBusConnection  *connection,
    875                                                DBusPendingCall *pending)
    876 {
    877   dbus_uint32_t reply_serial;
    878   DBusTimeout *timeout;
    879 
    880   HAVE_LOCK_CHECK (connection);
    881 
    882   reply_serial = _dbus_pending_call_get_reply_serial_unlocked (pending);
    883 
    884   _dbus_assert (reply_serial != 0);
    885 
    886   timeout = _dbus_pending_call_get_timeout_unlocked (pending);
    887 
    888   if (!_dbus_connection_add_timeout_unlocked (connection, timeout))
    889     return FALSE;
    890 
    891   if (!_dbus_hash_table_insert_int (connection->pending_replies,
    892                                     reply_serial,
    893                                     pending))
    894     {
    895       _dbus_connection_remove_timeout_unlocked (connection, timeout);
    896 
    897       _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
    898       HAVE_LOCK_CHECK (connection);
    899       return FALSE;
    900     }
    901 
    902   _dbus_pending_call_set_timeout_added_unlocked (pending, TRUE);
    903 
    904   _dbus_pending_call_ref_unlocked (pending);
    905 
    906   HAVE_LOCK_CHECK (connection);
    907 
    908   return TRUE;
    909 }
    910 
    911 static void
    912 free_pending_call_on_hash_removal (void *data)
    913 {
    914   DBusPendingCall *pending;
    915   DBusConnection  *connection;
    916 
    917   if (data == NULL)
    918     return;
    919 
    920   pending = data;
    921 
    922   connection = _dbus_pending_call_get_connection_unlocked (pending);
    923 
    924   HAVE_LOCK_CHECK (connection);
    925 
    926   if (_dbus_pending_call_is_timeout_added_unlocked (pending))
    927     {
    928       _dbus_connection_remove_timeout_unlocked (connection,
    929                                                 _dbus_pending_call_get_timeout_unlocked (pending));
    930 
    931       _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
    932     }
    933 
    934   /* FIXME 1.0? this is sort of dangerous and undesirable to drop the lock
    935    * here, but the pending call finalizer could in principle call out to
    936    * application code so we pretty much have to... some larger code reorg
    937    * might be needed.
    938    */
    939   _dbus_connection_ref_unlocked (connection);
    940   _dbus_pending_call_unref_and_unlock (pending);
    941   CONNECTION_LOCK (connection);
    942   _dbus_connection_unref_unlocked (connection);
    943 }
    944 
    945 static void
    946 _dbus_connection_detach_pending_call_unlocked (DBusConnection  *connection,
    947                                                DBusPendingCall *pending)
    948 {
    949   /* This ends up unlocking to call the pending call finalizer, which is unexpected to
    950    * say the least.
    951    */
    952   _dbus_hash_table_remove_int (connection->pending_replies,
    953                                _dbus_pending_call_get_reply_serial_unlocked (pending));
    954 }
    955 
    956 static void
    957 _dbus_connection_detach_pending_call_and_unlock (DBusConnection  *connection,
    958                                                  DBusPendingCall *pending)
    959 {
    960   /* The idea here is to avoid finalizing the pending call
    961    * with the lock held, since there's a destroy notifier
    962    * in pending call that goes out to application code.
    963    *
    964    * There's an extra unlock inside the hash table
    965    * "free pending call" function FIXME...
    966    */
    967   _dbus_pending_call_ref_unlocked (pending);
    968   _dbus_hash_table_remove_int (connection->pending_replies,
    969                                _dbus_pending_call_get_reply_serial_unlocked (pending));
    970   _dbus_pending_call_unref_and_unlock (pending);
    971 }
    972 
    973 /**
    974  * Removes a pending call from the connection, such that
    975  * the pending reply will be ignored. May drop the last
    976  * reference to the pending call.
    977  *
    978  * @param connection the connection
    979  * @param pending the pending call
    980  */
    981 void
    982 _dbus_connection_remove_pending_call (DBusConnection  *connection,
    983                                       DBusPendingCall *pending)
    984 {
    985   CONNECTION_LOCK (connection);
    986   _dbus_connection_detach_pending_call_and_unlock (connection, pending);
    987 }
    988 
    989 /**
    990  * Acquire the transporter I/O path. This must be done before
    991  * doing any I/O in the transporter. May sleep and drop the
    992  * IO path mutex while waiting for the I/O path.
    993  *
    994  * @param connection the connection.
    995  * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
    996  * @returns TRUE if the I/O path was acquired.
    997  */
    998 static dbus_bool_t
    999 _dbus_connection_acquire_io_path (DBusConnection *connection,
   1000 				  int             timeout_milliseconds)
   1001 {
   1002   dbus_bool_t we_acquired;
   1003 
   1004   HAVE_LOCK_CHECK (connection);
   1005 
   1006   /* We don't want the connection to vanish */
   1007   _dbus_connection_ref_unlocked (connection);
   1008 
   1009   /* We will only touch io_path_acquired which is protected by our mutex */
   1010   CONNECTION_UNLOCK (connection);
   1011 
   1012   _dbus_verbose ("%s locking io_path_mutex\n", _DBUS_FUNCTION_NAME);
   1013   _dbus_mutex_lock (connection->io_path_mutex);
   1014 
   1015   _dbus_verbose ("%s start connection->io_path_acquired = %d timeout = %d\n",
   1016                  _DBUS_FUNCTION_NAME, connection->io_path_acquired, timeout_milliseconds);
   1017 
   1018   we_acquired = FALSE;
   1019 
   1020   if (connection->io_path_acquired)
   1021     {
   1022       if (timeout_milliseconds != -1)
   1023         {
   1024           _dbus_verbose ("%s waiting %d for IO path to be acquirable\n",
   1025                          _DBUS_FUNCTION_NAME, timeout_milliseconds);
   1026 
   1027           if (!_dbus_condvar_wait_timeout (connection->io_path_cond,
   1028                                            connection->io_path_mutex,
   1029                                            timeout_milliseconds))
   1030             {
   1031               /* We timed out before anyone signaled. */
   1032               /* (writing the loop to handle the !timedout case by
   1033                * waiting longer if needed is a pain since dbus
   1034                * wraps pthread_cond_timedwait to take a relative
   1035                * time instead of absolute, something kind of stupid
   1036                * on our part. for now it doesn't matter, we will just
   1037                * end up back here eventually.)
   1038                */
   1039             }
   1040         }
   1041       else
   1042         {
   1043           while (connection->io_path_acquired)
   1044             {
   1045               _dbus_verbose ("%s waiting for IO path to be acquirable\n", _DBUS_FUNCTION_NAME);
   1046               _dbus_condvar_wait (connection->io_path_cond,
   1047                                   connection->io_path_mutex);
   1048             }
   1049         }
   1050     }
   1051 
   1052   if (!connection->io_path_acquired)
   1053     {
   1054       we_acquired = TRUE;
   1055       connection->io_path_acquired = TRUE;
   1056     }
   1057 
   1058   _dbus_verbose ("%s end connection->io_path_acquired = %d we_acquired = %d\n",
   1059                  _DBUS_FUNCTION_NAME, connection->io_path_acquired, we_acquired);
   1060 
   1061   _dbus_verbose ("%s unlocking io_path_mutex\n", _DBUS_FUNCTION_NAME);
   1062   _dbus_mutex_unlock (connection->io_path_mutex);
   1063 
   1064   CONNECTION_LOCK (connection);
   1065 
   1066   HAVE_LOCK_CHECK (connection);
   1067 
   1068   _dbus_connection_unref_unlocked (connection);
   1069 
   1070   return we_acquired;
   1071 }
   1072 
   1073 /**
   1074  * Release the I/O path when you're done with it. Only call
   1075  * after you've acquired the I/O. Wakes up at most one thread
   1076  * currently waiting to acquire the I/O path.
   1077  *
   1078  * @param connection the connection.
   1079  */
   1080 static void
   1081 _dbus_connection_release_io_path (DBusConnection *connection)
   1082 {
   1083   HAVE_LOCK_CHECK (connection);
   1084 
   1085   _dbus_verbose ("%s locking io_path_mutex\n", _DBUS_FUNCTION_NAME);
   1086   _dbus_mutex_lock (connection->io_path_mutex);
   1087 
   1088   _dbus_assert (connection->io_path_acquired);
   1089 
   1090   _dbus_verbose ("%s start connection->io_path_acquired = %d\n",
   1091                  _DBUS_FUNCTION_NAME, connection->io_path_acquired);
   1092 
   1093   connection->io_path_acquired = FALSE;
   1094   _dbus_condvar_wake_one (connection->io_path_cond);
   1095 
   1096   _dbus_verbose ("%s unlocking io_path_mutex\n", _DBUS_FUNCTION_NAME);
   1097   _dbus_mutex_unlock (connection->io_path_mutex);
   1098 }
   1099 
   1100 /**
   1101  * Queues incoming messages and sends outgoing messages for this
   1102  * connection, optionally blocking in the process. Each call to
   1103  * _dbus_connection_do_iteration_unlocked() will call select() or poll() one
   1104  * time and then read or write data if possible.
   1105  *
   1106  * The purpose of this function is to be able to flush outgoing
   1107  * messages or queue up incoming messages without returning
   1108  * control to the application and causing reentrancy weirdness.
   1109  *
   1110  * The flags parameter allows you to specify whether to
   1111  * read incoming messages, write outgoing messages, or both,
   1112  * and whether to block if no immediate action is possible.
   1113  *
   1114  * The timeout_milliseconds parameter does nothing unless the
   1115  * iteration is blocking.
   1116  *
   1117  * If there are no outgoing messages and DBUS_ITERATION_DO_READING
   1118  * wasn't specified, then it's impossible to block, even if
   1119  * you specify DBUS_ITERATION_BLOCK; in that case the function
   1120  * returns immediately.
   1121  *
   1122  * If pending is not NULL then a check is made if the pending call
   1123  * is completed after the io path has been required. If the call
   1124  * has been completed nothing is done. This must be done since
   1125  * the _dbus_connection_acquire_io_path releases the connection
   1126  * lock for a while.
   1127  *
   1128  * Called with connection lock held.
   1129  *
   1130  * @param connection the connection.
   1131  * @param pending the pending call that should be checked or NULL
   1132  * @param flags iteration flags.
   1133  * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
   1134  */
   1135 void
   1136 _dbus_connection_do_iteration_unlocked (DBusConnection *connection,
   1137                                         DBusPendingCall *pending,
   1138                                         unsigned int    flags,
   1139                                         int             timeout_milliseconds)
   1140 {
   1141   _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
   1142 
   1143   HAVE_LOCK_CHECK (connection);
   1144 
   1145   if (connection->n_outgoing == 0)
   1146     flags &= ~DBUS_ITERATION_DO_WRITING;
   1147 
   1148   if (_dbus_connection_acquire_io_path (connection,
   1149 					(flags & DBUS_ITERATION_BLOCK) ? timeout_milliseconds : 0))
   1150     {
   1151       HAVE_LOCK_CHECK (connection);
   1152 
   1153       if ( (pending != NULL) && _dbus_pending_call_get_completed_unlocked(pending))
   1154         {
   1155           _dbus_verbose ("pending call completed while acquiring I/O path");
   1156         }
   1157       else if ( (pending != NULL) &&
   1158                 _dbus_connection_peek_for_reply_unlocked (connection,
   1159                                                           _dbus_pending_call_get_reply_serial_unlocked (pending)))
   1160         {
   1161           _dbus_verbose ("pending call completed while acquiring I/O path (reply found in queue)");
   1162         }
   1163       else
   1164         {
   1165           _dbus_transport_do_iteration (connection->transport,
   1166                                         flags, timeout_milliseconds);
   1167         }
   1168 
   1169       _dbus_connection_release_io_path (connection);
   1170     }
   1171 
   1172   HAVE_LOCK_CHECK (connection);
   1173 
   1174   _dbus_verbose ("%s end\n", _DBUS_FUNCTION_NAME);
   1175 }
   1176 
   1177 /**
   1178  * Creates a new connection for the given transport.  A transport
   1179  * represents a message stream that uses some concrete mechanism, such
   1180  * as UNIX domain sockets. May return #NULL if insufficient
   1181  * memory exists to create the connection.
   1182  *
   1183  * @param transport the transport.
   1184  * @returns the new connection, or #NULL on failure.
   1185  */
   1186 DBusConnection*
   1187 _dbus_connection_new_for_transport (DBusTransport *transport)
   1188 {
   1189   DBusConnection *connection;
   1190   DBusWatchList *watch_list;
   1191   DBusTimeoutList *timeout_list;
   1192   DBusHashTable *pending_replies;
   1193   DBusList *disconnect_link;
   1194   DBusMessage *disconnect_message;
   1195   DBusCounter *outgoing_counter;
   1196   DBusObjectTree *objects;
   1197 
   1198   watch_list = NULL;
   1199   connection = NULL;
   1200   pending_replies = NULL;
   1201   timeout_list = NULL;
   1202   disconnect_link = NULL;
   1203   disconnect_message = NULL;
   1204   outgoing_counter = NULL;
   1205   objects = NULL;
   1206 
   1207   watch_list = _dbus_watch_list_new ();
   1208   if (watch_list == NULL)
   1209     goto error;
   1210 
   1211   timeout_list = _dbus_timeout_list_new ();
   1212   if (timeout_list == NULL)
   1213     goto error;
   1214 
   1215   pending_replies =
   1216     _dbus_hash_table_new (DBUS_HASH_INT,
   1217 			  NULL,
   1218                           (DBusFreeFunction)free_pending_call_on_hash_removal);
   1219   if (pending_replies == NULL)
   1220     goto error;
   1221 
   1222   connection = dbus_new0 (DBusConnection, 1);
   1223   if (connection == NULL)
   1224     goto error;
   1225 
   1226   _dbus_mutex_new_at_location (&connection->mutex);
   1227   if (connection->mutex == NULL)
   1228     goto error;
   1229 
   1230   _dbus_mutex_new_at_location (&connection->io_path_mutex);
   1231   if (connection->io_path_mutex == NULL)
   1232     goto error;
   1233 
   1234   _dbus_mutex_new_at_location (&connection->dispatch_mutex);
   1235   if (connection->dispatch_mutex == NULL)
   1236     goto error;
   1237 
   1238   _dbus_condvar_new_at_location (&connection->dispatch_cond);
   1239   if (connection->dispatch_cond == NULL)
   1240     goto error;
   1241 
   1242   _dbus_condvar_new_at_location (&connection->io_path_cond);
   1243   if (connection->io_path_cond == NULL)
   1244     goto error;
   1245 
   1246   disconnect_message = dbus_message_new_signal (DBUS_PATH_LOCAL,
   1247                                                 DBUS_INTERFACE_LOCAL,
   1248                                                 "Disconnected");
   1249 
   1250   if (disconnect_message == NULL)
   1251     goto error;
   1252 
   1253   disconnect_link = _dbus_list_alloc_link (disconnect_message);
   1254   if (disconnect_link == NULL)
   1255     goto error;
   1256 
   1257   outgoing_counter = _dbus_counter_new ();
   1258   if (outgoing_counter == NULL)
   1259     goto error;
   1260 
   1261   objects = _dbus_object_tree_new (connection);
   1262   if (objects == NULL)
   1263     goto error;
   1264 
   1265   if (_dbus_modify_sigpipe)
   1266     _dbus_disable_sigpipe ();
   1267 
   1268   connection->refcount.value = 1;
   1269   connection->transport = transport;
   1270   connection->watches = watch_list;
   1271   connection->timeouts = timeout_list;
   1272   connection->pending_replies = pending_replies;
   1273   connection->outgoing_counter = outgoing_counter;
   1274   connection->filter_list = NULL;
   1275   connection->last_dispatch_status = DBUS_DISPATCH_COMPLETE; /* so we're notified first time there's data */
   1276   connection->objects = objects;
   1277   connection->exit_on_disconnect = FALSE;
   1278   connection->shareable = FALSE;
   1279   connection->route_peer_messages = FALSE;
   1280   connection->disconnected_message_arrived = FALSE;
   1281   connection->disconnected_message_processed = FALSE;
   1282 
   1283 #ifndef DBUS_DISABLE_CHECKS
   1284   connection->generation = _dbus_current_generation;
   1285 #endif
   1286 
   1287   _dbus_data_slot_list_init (&connection->slot_list);
   1288 
   1289   connection->client_serial = 1;
   1290 
   1291   connection->disconnect_message_link = disconnect_link;
   1292 
   1293   CONNECTION_LOCK (connection);
   1294 
   1295   if (!_dbus_transport_set_connection (transport, connection))
   1296     {
   1297       CONNECTION_UNLOCK (connection);
   1298 
   1299       goto error;
   1300     }
   1301 
   1302   _dbus_transport_ref (transport);
   1303 
   1304   CONNECTION_UNLOCK (connection);
   1305 
   1306   return connection;
   1307 
   1308  error:
   1309   if (disconnect_message != NULL)
   1310     dbus_message_unref (disconnect_message);
   1311 
   1312   if (disconnect_link != NULL)
   1313     _dbus_list_free_link (disconnect_link);
   1314 
   1315   if (connection != NULL)
   1316     {
   1317       _dbus_condvar_free_at_location (&connection->io_path_cond);
   1318       _dbus_condvar_free_at_location (&connection->dispatch_cond);
   1319       _dbus_mutex_free_at_location (&connection->mutex);
   1320       _dbus_mutex_free_at_location (&connection->io_path_mutex);
   1321       _dbus_mutex_free_at_location (&connection->dispatch_mutex);
   1322       dbus_free (connection);
   1323     }
   1324   if (pending_replies)
   1325     _dbus_hash_table_unref (pending_replies);
   1326 
   1327   if (watch_list)
   1328     _dbus_watch_list_free (watch_list);
   1329 
   1330   if (timeout_list)
   1331     _dbus_timeout_list_free (timeout_list);
   1332 
   1333   if (outgoing_counter)
   1334     _dbus_counter_unref (outgoing_counter);
   1335 
   1336   if (objects)
   1337     _dbus_object_tree_unref (objects);
   1338 
   1339   return NULL;
   1340 }
   1341 
   1342 /**
   1343  * Increments the reference count of a DBusConnection.
   1344  * Requires that the caller already holds the connection lock.
   1345  *
   1346  * @param connection the connection.
   1347  * @returns the connection.
   1348  */
   1349 DBusConnection *
   1350 _dbus_connection_ref_unlocked (DBusConnection *connection)
   1351 {
   1352   _dbus_assert (connection != NULL);
   1353   _dbus_assert (connection->generation == _dbus_current_generation);
   1354 
   1355   HAVE_LOCK_CHECK (connection);
   1356 
   1357 #ifdef DBUS_HAVE_ATOMIC_INT
   1358   _dbus_atomic_inc (&connection->refcount);
   1359 #else
   1360   _dbus_assert (connection->refcount.value > 0);
   1361   connection->refcount.value += 1;
   1362 #endif
   1363 
   1364   return connection;
   1365 }
   1366 
   1367 /**
   1368  * Decrements the reference count of a DBusConnection.
   1369  * Requires that the caller already holds the connection lock.
   1370  *
   1371  * @param connection the connection.
   1372  */
   1373 void
   1374 _dbus_connection_unref_unlocked (DBusConnection *connection)
   1375 {
   1376   dbus_bool_t last_unref;
   1377 
   1378   HAVE_LOCK_CHECK (connection);
   1379 
   1380   _dbus_assert (connection != NULL);
   1381 
   1382   /* The connection lock is better than the global
   1383    * lock in the atomic increment fallback
   1384    */
   1385 
   1386 #ifdef DBUS_HAVE_ATOMIC_INT
   1387   last_unref = (_dbus_atomic_dec (&connection->refcount) == 1);
   1388 #else
   1389   _dbus_assert (connection->refcount.value > 0);
   1390 
   1391   connection->refcount.value -= 1;
   1392   last_unref = (connection->refcount.value == 0);
   1393 #if 0
   1394   printf ("unref_unlocked() connection %p count = %d\n", connection, connection->refcount.value);
   1395 #endif
   1396 #endif
   1397 
   1398   if (last_unref)
   1399     _dbus_connection_last_unref (connection);
   1400 }
   1401 
   1402 static dbus_uint32_t
   1403 _dbus_connection_get_next_client_serial (DBusConnection *connection)
   1404 {
   1405   int serial;
   1406 
   1407   serial = connection->client_serial++;
   1408 
   1409   if (connection->client_serial < 0)
   1410     connection->client_serial = 1;
   1411 
   1412   return serial;
   1413 }
   1414 
   1415 /**
   1416  * A callback for use with dbus_watch_new() to create a DBusWatch.
   1417  *
   1418  * @todo This is basically a hack - we could delete _dbus_transport_handle_watch()
   1419  * and the virtual handle_watch in DBusTransport if we got rid of it.
   1420  * The reason this is some work is threading, see the _dbus_connection_handle_watch()
   1421  * implementation.
   1422  *
   1423  * @param watch the watch.
   1424  * @param condition the current condition of the file descriptors being watched.
   1425  * @param data must be a pointer to a #DBusConnection
   1426  * @returns #FALSE if the IO condition may not have been fully handled due to lack of memory
   1427  */
   1428 dbus_bool_t
   1429 _dbus_connection_handle_watch (DBusWatch                   *watch,
   1430                                unsigned int                 condition,
   1431                                void                        *data)
   1432 {
   1433   DBusConnection *connection;
   1434   dbus_bool_t retval;
   1435   DBusDispatchStatus status;
   1436 
   1437   connection = data;
   1438 
   1439   _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
   1440 
   1441   CONNECTION_LOCK (connection);
   1442   _dbus_connection_acquire_io_path (connection, -1);
   1443   HAVE_LOCK_CHECK (connection);
   1444   retval = _dbus_transport_handle_watch (connection->transport,
   1445                                          watch, condition);
   1446 
   1447   _dbus_connection_release_io_path (connection);
   1448 
   1449   HAVE_LOCK_CHECK (connection);
   1450 
   1451   _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
   1452 
   1453   status = _dbus_connection_get_dispatch_status_unlocked (connection);
   1454 
   1455   /* this calls out to user code */
   1456   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
   1457 
   1458   _dbus_verbose ("%s end\n", _DBUS_FUNCTION_NAME);
   1459 
   1460   return retval;
   1461 }
   1462 
   1463 _DBUS_DEFINE_GLOBAL_LOCK (shared_connections);
   1464 static DBusHashTable *shared_connections = NULL;
   1465 
   1466 static void
   1467 shared_connections_shutdown (void *data)
   1468 {
   1469   int n_entries;
   1470 
   1471   _DBUS_LOCK (shared_connections);
   1472 
   1473   /* This is a little bit unpleasant... better ideas? */
   1474   while ((n_entries = _dbus_hash_table_get_n_entries (shared_connections)) > 0)
   1475     {
   1476       DBusConnection *connection;
   1477       DBusMessage *message;
   1478       DBusHashIter iter;
   1479 
   1480       _dbus_hash_iter_init (shared_connections, &iter);
   1481       _dbus_hash_iter_next (&iter);
   1482 
   1483       connection = _dbus_hash_iter_get_value (&iter);
   1484 
   1485       _DBUS_UNLOCK (shared_connections);
   1486 
   1487       dbus_connection_ref (connection);
   1488       _dbus_connection_close_possibly_shared (connection);
   1489 
   1490       /* Churn through to the Disconnected message */
   1491       while ((message = dbus_connection_pop_message (connection)))
   1492         {
   1493           dbus_message_unref (message);
   1494         }
   1495       dbus_connection_unref (connection);
   1496 
   1497       _DBUS_LOCK (shared_connections);
   1498 
   1499       /* The connection should now be dead and not in our hash ... */
   1500       _dbus_assert (_dbus_hash_table_get_n_entries (shared_connections) < n_entries);
   1501     }
   1502 
   1503   _dbus_assert (_dbus_hash_table_get_n_entries (shared_connections) == 0);
   1504 
   1505   _dbus_hash_table_unref (shared_connections);
   1506   shared_connections = NULL;
   1507 
   1508   _DBUS_UNLOCK (shared_connections);
   1509 }
   1510 
   1511 static dbus_bool_t
   1512 connection_lookup_shared (DBusAddressEntry  *entry,
   1513                           DBusConnection   **result)
   1514 {
   1515   _dbus_verbose ("checking for existing connection\n");
   1516 
   1517   *result = NULL;
   1518 
   1519   _DBUS_LOCK (shared_connections);
   1520 
   1521   if (shared_connections == NULL)
   1522     {
   1523       _dbus_verbose ("creating shared_connections hash table\n");
   1524 
   1525       shared_connections = _dbus_hash_table_new (DBUS_HASH_STRING,
   1526                                                  dbus_free,
   1527                                                  NULL);
   1528       if (shared_connections == NULL)
   1529         {
   1530           _DBUS_UNLOCK (shared_connections);
   1531           return FALSE;
   1532         }
   1533 
   1534       if (!_dbus_register_shutdown_func (shared_connections_shutdown, NULL))
   1535         {
   1536           _dbus_hash_table_unref (shared_connections);
   1537           shared_connections = NULL;
   1538           _DBUS_UNLOCK (shared_connections);
   1539           return FALSE;
   1540         }
   1541 
   1542       _dbus_verbose ("  successfully created shared_connections\n");
   1543 
   1544       _DBUS_UNLOCK (shared_connections);
   1545       return TRUE; /* no point looking up in the hash we just made */
   1546     }
   1547   else
   1548     {
   1549       const char *guid;
   1550 
   1551       guid = dbus_address_entry_get_value (entry, "guid");
   1552 
   1553       if (guid != NULL)
   1554         {
   1555           DBusConnection *connection;
   1556 
   1557           connection = _dbus_hash_table_lookup_string (shared_connections,
   1558                                                        guid);
   1559 
   1560           if (connection)
   1561             {
   1562               /* The DBusConnection can't be finalized without taking
   1563                * the shared_connections lock to remove it from the
   1564                * hash.  So it's safe to ref the connection here.
   1565                * However, it may be disconnected if the Disconnected
   1566                * message hasn't been processed yet, in which case we
   1567                * want to pretend it isn't in the hash and avoid
   1568                * returning it.
   1569                *
   1570                * The idea is to avoid ever returning a disconnected connection
   1571                * from dbus_connection_open(). We could just synchronously
   1572                * drop our shared ref to the connection on connection disconnect,
   1573                * and then assert here that the connection is connected, but
   1574                * that causes reentrancy headaches.
   1575                */
   1576               CONNECTION_LOCK (connection);
   1577               if (_dbus_connection_get_is_connected_unlocked (connection))
   1578                 {
   1579                   _dbus_connection_ref_unlocked (connection);
   1580                   *result = connection;
   1581                   _dbus_verbose ("looked up existing connection to server guid %s\n",
   1582                                  guid);
   1583                 }
   1584               else
   1585                 {
   1586                   _dbus_verbose ("looked up existing connection to server guid %s but it was disconnected so ignoring it\n",
   1587                                  guid);
   1588                 }
   1589               CONNECTION_UNLOCK (connection);
   1590             }
   1591         }
   1592 
   1593       _DBUS_UNLOCK (shared_connections);
   1594       return TRUE;
   1595     }
   1596 }
   1597 
   1598 static dbus_bool_t
   1599 connection_record_shared_unlocked (DBusConnection *connection,
   1600                                    const char     *guid)
   1601 {
   1602   char *guid_key;
   1603   char *guid_in_connection;
   1604 
   1605   HAVE_LOCK_CHECK (connection);
   1606   _dbus_assert (connection->server_guid == NULL);
   1607   _dbus_assert (connection->shareable);
   1608 
   1609   /* get a hard ref on this connection, even if
   1610    * we won't in fact store it in the hash, we still
   1611    * need to hold a ref on it until it's disconnected.
   1612    */
   1613   _dbus_connection_ref_unlocked (connection);
   1614 
   1615   if (guid == NULL)
   1616     return TRUE; /* don't store in the hash */
   1617 
   1618   /* A separate copy of the key is required in the hash table, because
   1619    * we don't have a lock on the connection when we are doing a hash
   1620    * lookup.
   1621    */
   1622 
   1623   guid_key = _dbus_strdup (guid);
   1624   if (guid_key == NULL)
   1625     return FALSE;
   1626 
   1627   guid_in_connection = _dbus_strdup (guid);
   1628   if (guid_in_connection == NULL)
   1629     {
   1630       dbus_free (guid_key);
   1631       return FALSE;
   1632     }
   1633 
   1634   _DBUS_LOCK (shared_connections);
   1635   _dbus_assert (shared_connections != NULL);
   1636 
   1637   if (!_dbus_hash_table_insert_string (shared_connections,
   1638                                        guid_key, connection))
   1639     {
   1640       dbus_free (guid_key);
   1641       dbus_free (guid_in_connection);
   1642       _DBUS_UNLOCK (shared_connections);
   1643       return FALSE;
   1644     }
   1645 
   1646   connection->server_guid = guid_in_connection;
   1647 
   1648   _dbus_verbose ("stored connection to %s to be shared\n",
   1649                  connection->server_guid);
   1650 
   1651   _DBUS_UNLOCK (shared_connections);
   1652 
   1653   _dbus_assert (connection->server_guid != NULL);
   1654 
   1655   return TRUE;
   1656 }
   1657 
   1658 static void
   1659 connection_forget_shared_unlocked (DBusConnection *connection)
   1660 {
   1661   HAVE_LOCK_CHECK (connection);
   1662 
   1663   if (!connection->shareable)
   1664     return;
   1665 
   1666   if (connection->server_guid != NULL)
   1667     {
   1668       _dbus_verbose ("dropping connection to %s out of the shared table\n",
   1669                      connection->server_guid);
   1670 
   1671       _DBUS_LOCK (shared_connections);
   1672 
   1673       if (!_dbus_hash_table_remove_string (shared_connections,
   1674                                            connection->server_guid))
   1675         _dbus_assert_not_reached ("connection was not in the shared table");
   1676 
   1677       dbus_free (connection->server_guid);
   1678       connection->server_guid = NULL;
   1679       _DBUS_UNLOCK (shared_connections);
   1680     }
   1681 
   1682   /* remove our reference held on all shareable connections */
   1683   _dbus_connection_unref_unlocked (connection);
   1684 }
   1685 
   1686 static DBusConnection*
   1687 connection_try_from_address_entry (DBusAddressEntry *entry,
   1688                                    DBusError        *error)
   1689 {
   1690   DBusTransport *transport;
   1691   DBusConnection *connection;
   1692 
   1693   transport = _dbus_transport_open (entry, error);
   1694 
   1695   if (transport == NULL)
   1696     {
   1697       _DBUS_ASSERT_ERROR_IS_SET (error);
   1698       return NULL;
   1699     }
   1700 
   1701   connection = _dbus_connection_new_for_transport (transport);
   1702 
   1703   _dbus_transport_unref (transport);
   1704 
   1705   if (connection == NULL)
   1706     {
   1707       _DBUS_SET_OOM (error);
   1708       return NULL;
   1709     }
   1710 
   1711 #ifndef DBUS_DISABLE_CHECKS
   1712   _dbus_assert (!connection->have_connection_lock);
   1713 #endif
   1714   return connection;
   1715 }
   1716 
   1717 /*
   1718  * If the shared parameter is true, then any existing connection will
   1719  * be used (and if a new connection is created, it will be available
   1720  * for use by others). If the shared parameter is false, a new
   1721  * connection will always be created, and the new connection will
   1722  * never be returned to other callers.
   1723  *
   1724  * @param address the address
   1725  * @param shared whether the connection is shared or private
   1726  * @param error error return
   1727  * @returns the connection or #NULL on error
   1728  */
   1729 static DBusConnection*
   1730 _dbus_connection_open_internal (const char     *address,
   1731                                 dbus_bool_t     shared,
   1732                                 DBusError      *error)
   1733 {
   1734   DBusConnection *connection;
   1735   DBusAddressEntry **entries;
   1736   DBusError tmp_error;
   1737   DBusError first_error;
   1738   int len, i;
   1739 
   1740   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
   1741 
   1742   _dbus_verbose ("opening %s connection to: %s\n",
   1743                  shared ? "shared" : "private", address);
   1744 
   1745   if (!dbus_parse_address (address, &entries, &len, error))
   1746     return NULL;
   1747 
   1748   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
   1749 
   1750   connection = NULL;
   1751 
   1752   dbus_error_init (&tmp_error);
   1753   dbus_error_init (&first_error);
   1754   for (i = 0; i < len; i++)
   1755     {
   1756       if (shared)
   1757         {
   1758           if (!connection_lookup_shared (entries[i], &connection))
   1759             _DBUS_SET_OOM (&tmp_error);
   1760         }
   1761 
   1762       if (connection == NULL)
   1763         {
   1764           connection = connection_try_from_address_entry (entries[i],
   1765                                                           &tmp_error);
   1766 
   1767           if (connection != NULL && shared)
   1768             {
   1769               const char *guid;
   1770 
   1771               connection->shareable = TRUE;
   1772 
   1773               /* guid may be NULL */
   1774               guid = dbus_address_entry_get_value (entries[i], "guid");
   1775 
   1776               CONNECTION_LOCK (connection);
   1777 
   1778               if (!connection_record_shared_unlocked (connection, guid))
   1779                 {
   1780                   _DBUS_SET_OOM (&tmp_error);
   1781                   _dbus_connection_close_possibly_shared_and_unlock (connection);
   1782                   dbus_connection_unref (connection);
   1783                   connection = NULL;
   1784                 }
   1785               else
   1786                 CONNECTION_UNLOCK (connection);
   1787             }
   1788         }
   1789 
   1790       if (connection)
   1791         break;
   1792 
   1793       _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
   1794 
   1795       if (i == 0)
   1796         dbus_move_error (&tmp_error, &first_error);
   1797       else
   1798         dbus_error_free (&tmp_error);
   1799     }
   1800 
   1801   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
   1802   _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
   1803 
   1804   if (connection == NULL)
   1805     {
   1806       _DBUS_ASSERT_ERROR_IS_SET (&first_error);
   1807       dbus_move_error (&first_error, error);
   1808     }
   1809   else
   1810     dbus_error_free (&first_error);
   1811 
   1812   dbus_address_entries_free (entries);
   1813   return connection;
   1814 }
   1815 
   1816 /**
   1817  * Closes a shared OR private connection, while dbus_connection_close() can
   1818  * only be used on private connections. Should only be called by the
   1819  * dbus code that owns the connection - an owner must be known,
   1820  * the open/close state is like malloc/free, not like ref/unref.
   1821  *
   1822  * @param connection the connection
   1823  */
   1824 void
   1825 _dbus_connection_close_possibly_shared (DBusConnection *connection)
   1826 {
   1827   _dbus_assert (connection != NULL);
   1828   _dbus_assert (connection->generation == _dbus_current_generation);
   1829 
   1830   CONNECTION_LOCK (connection);
   1831   _dbus_connection_close_possibly_shared_and_unlock (connection);
   1832 }
   1833 
   1834 static DBusPreallocatedSend*
   1835 _dbus_connection_preallocate_send_unlocked (DBusConnection *connection)
   1836 {
   1837   DBusPreallocatedSend *preallocated;
   1838 
   1839   HAVE_LOCK_CHECK (connection);
   1840 
   1841   _dbus_assert (connection != NULL);
   1842 
   1843   preallocated = dbus_new (DBusPreallocatedSend, 1);
   1844   if (preallocated == NULL)
   1845     return NULL;
   1846 
   1847   if (connection->link_cache != NULL)
   1848     {
   1849       preallocated->queue_link =
   1850         _dbus_list_pop_first_link (&connection->link_cache);
   1851       preallocated->queue_link->data = NULL;
   1852     }
   1853   else
   1854     {
   1855       preallocated->queue_link = _dbus_list_alloc_link (NULL);
   1856       if (preallocated->queue_link == NULL)
   1857         goto failed_0;
   1858     }
   1859 
   1860   if (connection->link_cache != NULL)
   1861     {
   1862       preallocated->counter_link =
   1863         _dbus_list_pop_first_link (&connection->link_cache);
   1864       preallocated->counter_link->data = connection->outgoing_counter;
   1865     }
   1866   else
   1867     {
   1868       preallocated->counter_link = _dbus_list_alloc_link (connection->outgoing_counter);
   1869       if (preallocated->counter_link == NULL)
   1870         goto failed_1;
   1871     }
   1872 
   1873   _dbus_counter_ref (preallocated->counter_link->data);
   1874 
   1875   preallocated->connection = connection;
   1876 
   1877   return preallocated;
   1878 
   1879  failed_1:
   1880   _dbus_list_free_link (preallocated->queue_link);
   1881  failed_0:
   1882   dbus_free (preallocated);
   1883 
   1884   return NULL;
   1885 }
   1886 
   1887 /* Called with lock held, does not update dispatch status */
   1888 static void
   1889 _dbus_connection_send_preallocated_unlocked_no_update (DBusConnection       *connection,
   1890                                                        DBusPreallocatedSend *preallocated,
   1891                                                        DBusMessage          *message,
   1892                                                        dbus_uint32_t        *client_serial)
   1893 {
   1894   dbus_uint32_t serial;
   1895   const char *sig;
   1896 
   1897   preallocated->queue_link->data = message;
   1898   _dbus_list_prepend_link (&connection->outgoing_messages,
   1899                            preallocated->queue_link);
   1900 
   1901   _dbus_message_add_size_counter_link (message,
   1902                                        preallocated->counter_link);
   1903 
   1904   dbus_free (preallocated);
   1905   preallocated = NULL;
   1906 
   1907   dbus_message_ref (message);
   1908 
   1909   connection->n_outgoing += 1;
   1910 
   1911   sig = dbus_message_get_signature (message);
   1912 
   1913   _dbus_verbose ("Message %p (%d %s %s %s '%s') for %s added to outgoing queue %p, %d pending to send\n",
   1914                  message,
   1915                  dbus_message_get_type (message),
   1916                  dbus_message_get_path (message) ?
   1917                  dbus_message_get_path (message) :
   1918                  "no path",
   1919                  dbus_message_get_interface (message) ?
   1920                  dbus_message_get_interface (message) :
   1921                  "no interface",
   1922                  dbus_message_get_member (message) ?
   1923                  dbus_message_get_member (message) :
   1924                  "no member",
   1925                  sig,
   1926                  dbus_message_get_destination (message) ?
   1927                  dbus_message_get_destination (message) :
   1928                  "null",
   1929                  connection,
   1930                  connection->n_outgoing);
   1931 
   1932   if (dbus_message_get_serial (message) == 0)
   1933     {
   1934       serial = _dbus_connection_get_next_client_serial (connection);
   1935       _dbus_message_set_serial (message, serial);
   1936       if (client_serial)
   1937         *client_serial = serial;
   1938     }
   1939   else
   1940     {
   1941       if (client_serial)
   1942         *client_serial = dbus_message_get_serial (message);
   1943     }
   1944 
   1945   _dbus_verbose ("Message %p serial is %u\n",
   1946                  message, dbus_message_get_serial (message));
   1947 
   1948   _dbus_message_lock (message);
   1949 
   1950   /* Now we need to run an iteration to hopefully just write the messages
   1951    * out immediately, and otherwise get them queued up
   1952    */
   1953   _dbus_connection_do_iteration_unlocked (connection,
   1954                                           NULL,
   1955                                           DBUS_ITERATION_DO_WRITING,
   1956                                           -1);
   1957 
   1958   /* If stuff is still queued up, be sure we wake up the main loop */
   1959   if (connection->n_outgoing > 0)
   1960     _dbus_connection_wakeup_mainloop (connection);
   1961 }
   1962 
   1963 static void
   1964 _dbus_connection_send_preallocated_and_unlock (DBusConnection       *connection,
   1965 					       DBusPreallocatedSend *preallocated,
   1966 					       DBusMessage          *message,
   1967 					       dbus_uint32_t        *client_serial)
   1968 {
   1969   DBusDispatchStatus status;
   1970 
   1971   HAVE_LOCK_CHECK (connection);
   1972 
   1973   _dbus_connection_send_preallocated_unlocked_no_update (connection,
   1974                                                          preallocated,
   1975                                                          message, client_serial);
   1976 
   1977   _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
   1978   status = _dbus_connection_get_dispatch_status_unlocked (connection);
   1979 
   1980   /* this calls out to user code */
   1981   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
   1982 }
   1983 
   1984 /**
   1985  * Like dbus_connection_send(), but assumes the connection
   1986  * is already locked on function entry, and unlocks before returning.
   1987  *
   1988  * @param connection the connection
   1989  * @param message the message to send
   1990  * @param client_serial return location for client serial of sent message
   1991  * @returns #FALSE on out-of-memory
   1992  */
   1993 dbus_bool_t
   1994 _dbus_connection_send_and_unlock (DBusConnection *connection,
   1995 				  DBusMessage    *message,
   1996 				  dbus_uint32_t  *client_serial)
   1997 {
   1998   DBusPreallocatedSend *preallocated;
   1999 
   2000   _dbus_assert (connection != NULL);
   2001   _dbus_assert (message != NULL);
   2002 
   2003   preallocated = _dbus_connection_preallocate_send_unlocked (connection);
   2004   if (preallocated == NULL)
   2005     {
   2006       CONNECTION_UNLOCK (connection);
   2007       return FALSE;
   2008     }
   2009 
   2010   _dbus_connection_send_preallocated_and_unlock (connection,
   2011 						 preallocated,
   2012 						 message,
   2013 						 client_serial);
   2014   return TRUE;
   2015 }
   2016 
   2017 /**
   2018  * Used internally to handle the semantics of dbus_server_set_new_connection_function().
   2019  * If the new connection function does not ref the connection, we want to close it.
   2020  *
   2021  * A bit of a hack, probably the new connection function should have returned a value
   2022  * for whether to close, or should have had to close the connection itself if it
   2023  * didn't want it.
   2024  *
   2025  * But, this works OK as long as the new connection function doesn't do anything
   2026  * crazy like keep the connection around without ref'ing it.
   2027  *
   2028  * We have to lock the connection across refcount check and close in case
   2029  * the new connection function spawns a thread that closes and unrefs.
   2030  * In that case, if the app thread
   2031  * closes and unrefs first, we'll harmlessly close again; if the app thread
   2032  * still has the ref, we'll close and then the app will close harmlessly.
   2033  * If the app unrefs without closing, the app is broken since if the
   2034  * app refs from the new connection function it is supposed to also close.
   2035  *
   2036  * If we didn't atomically check the refcount and close with the lock held
   2037  * though, we could screw this up.
   2038  *
   2039  * @param connection the connection
   2040  */
   2041 void
   2042 _dbus_connection_close_if_only_one_ref (DBusConnection *connection)
   2043 {
   2044   CONNECTION_LOCK (connection);
   2045 
   2046   _dbus_assert (connection->refcount.value > 0);
   2047 
   2048   if (connection->refcount.value == 1)
   2049     _dbus_connection_close_possibly_shared_and_unlock (connection);
   2050   else
   2051     CONNECTION_UNLOCK (connection);
   2052 }
   2053 
   2054 
   2055 /**
   2056  * When a function that blocks has been called with a timeout, and we
   2057  * run out of memory, the time to wait for memory is based on the
   2058  * timeout. If the caller was willing to block a long time we wait a
   2059  * relatively long time for memory, if they were only willing to block
   2060  * briefly then we retry for memory at a rapid rate.
   2061  *
   2062  * @timeout_milliseconds the timeout requested for blocking
   2063  */
   2064 static void
   2065 _dbus_memory_pause_based_on_timeout (int timeout_milliseconds)
   2066 {
   2067   if (timeout_milliseconds == -1)
   2068     _dbus_sleep_milliseconds (1000);
   2069   else if (timeout_milliseconds < 100)
   2070     ; /* just busy loop */
   2071   else if (timeout_milliseconds <= 1000)
   2072     _dbus_sleep_milliseconds (timeout_milliseconds / 3);
   2073   else
   2074     _dbus_sleep_milliseconds (1000);
   2075 }
   2076 
   2077 static DBusMessage *
   2078 generate_local_error_message (dbus_uint32_t serial,
   2079                               char *error_name,
   2080                               char *error_msg)
   2081 {
   2082   DBusMessage *message;
   2083   message = dbus_message_new (DBUS_MESSAGE_TYPE_ERROR);
   2084   if (!message)
   2085     goto out;
   2086 
   2087   if (!dbus_message_set_error_name (message, error_name))
   2088     {
   2089       dbus_message_unref (message);
   2090       message = NULL;
   2091       goto out;
   2092     }
   2093 
   2094   dbus_message_set_no_reply (message, TRUE);
   2095 
   2096   if (!dbus_message_set_reply_serial (message,
   2097                                       serial))
   2098     {
   2099       dbus_message_unref (message);
   2100       message = NULL;
   2101       goto out;
   2102     }
   2103 
   2104   if (error_msg != NULL)
   2105     {
   2106       DBusMessageIter iter;
   2107 
   2108       dbus_message_iter_init_append (message, &iter);
   2109       if (!dbus_message_iter_append_basic (&iter,
   2110                                            DBUS_TYPE_STRING,
   2111                                            &error_msg))
   2112         {
   2113           dbus_message_unref (message);
   2114           message = NULL;
   2115 	  goto out;
   2116         }
   2117     }
   2118 
   2119  out:
   2120   return message;
   2121 }
   2122 
   2123 /*
   2124  * Peek the incoming queue to see if we got reply for a specific serial
   2125  */
   2126 static dbus_bool_t
   2127 _dbus_connection_peek_for_reply_unlocked (DBusConnection *connection,
   2128                                           dbus_uint32_t   client_serial)
   2129 {
   2130   DBusList *link;
   2131   HAVE_LOCK_CHECK (connection);
   2132 
   2133   link = _dbus_list_get_first_link (&connection->incoming_messages);
   2134 
   2135   while (link != NULL)
   2136     {
   2137       DBusMessage *reply = link->data;
   2138 
   2139       if (dbus_message_get_reply_serial (reply) == client_serial)
   2140         {
   2141           _dbus_verbose ("%s reply to %d found in queue\n", _DBUS_FUNCTION_NAME, client_serial);
   2142           return TRUE;
   2143         }
   2144       link = _dbus_list_get_next_link (&connection->incoming_messages, link);
   2145     }
   2146 
   2147   return FALSE;
   2148 }
   2149 
   2150 /* This is slightly strange since we can pop a message here without
   2151  * the dispatch lock.
   2152  */
   2153 static DBusMessage*
   2154 check_for_reply_unlocked (DBusConnection *connection,
   2155                           dbus_uint32_t   client_serial)
   2156 {
   2157   DBusList *link;
   2158 
   2159   HAVE_LOCK_CHECK (connection);
   2160 
   2161   link = _dbus_list_get_first_link (&connection->incoming_messages);
   2162 
   2163   while (link != NULL)
   2164     {
   2165       DBusMessage *reply = link->data;
   2166 
   2167       if (dbus_message_get_reply_serial (reply) == client_serial)
   2168 	{
   2169 	  _dbus_list_remove_link (&connection->incoming_messages, link);
   2170 	  connection->n_incoming  -= 1;
   2171 	  return reply;
   2172 	}
   2173       link = _dbus_list_get_next_link (&connection->incoming_messages, link);
   2174     }
   2175 
   2176   return NULL;
   2177 }
   2178 
   2179 static void
   2180 connection_timeout_and_complete_all_pending_calls_unlocked (DBusConnection *connection)
   2181 {
   2182    /* We can't iterate over the hash in the normal way since we'll be
   2183     * dropping the lock for each item. So we restart the
   2184     * iter each time as we drain the hash table.
   2185     */
   2186 
   2187    while (_dbus_hash_table_get_n_entries (connection->pending_replies) > 0)
   2188     {
   2189       DBusPendingCall *pending;
   2190       DBusHashIter iter;
   2191 
   2192       _dbus_hash_iter_init (connection->pending_replies, &iter);
   2193       _dbus_hash_iter_next (&iter);
   2194 
   2195       pending = _dbus_hash_iter_get_value (&iter);
   2196       _dbus_pending_call_ref_unlocked (pending);
   2197 
   2198       _dbus_pending_call_queue_timeout_error_unlocked (pending,
   2199                                                        connection);
   2200       _dbus_connection_remove_timeout_unlocked (connection,
   2201                                                 _dbus_pending_call_get_timeout_unlocked (pending));
   2202       _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
   2203       _dbus_hash_iter_remove_entry (&iter);
   2204 
   2205       _dbus_pending_call_unref_and_unlock (pending);
   2206       CONNECTION_LOCK (connection);
   2207     }
   2208   HAVE_LOCK_CHECK (connection);
   2209 }
   2210 
   2211 static void
   2212 complete_pending_call_and_unlock (DBusConnection  *connection,
   2213                                   DBusPendingCall *pending,
   2214                                   DBusMessage     *message)
   2215 {
   2216   _dbus_pending_call_set_reply_unlocked (pending, message);
   2217   _dbus_pending_call_ref_unlocked (pending); /* in case there's no app with a ref held */
   2218   _dbus_connection_detach_pending_call_and_unlock (connection, pending);
   2219 
   2220   /* Must be called unlocked since it invokes app callback */
   2221   _dbus_pending_call_complete (pending);
   2222   dbus_pending_call_unref (pending);
   2223 }
   2224 
   2225 static dbus_bool_t
   2226 check_for_reply_and_update_dispatch_unlocked (DBusConnection  *connection,
   2227                                               DBusPendingCall *pending)
   2228 {
   2229   DBusMessage *reply;
   2230   DBusDispatchStatus status;
   2231 
   2232   reply = check_for_reply_unlocked (connection,
   2233                                     _dbus_pending_call_get_reply_serial_unlocked (pending));
   2234   if (reply != NULL)
   2235     {
   2236       _dbus_verbose ("%s checked for reply\n", _DBUS_FUNCTION_NAME);
   2237 
   2238       _dbus_verbose ("dbus_connection_send_with_reply_and_block(): got reply\n");
   2239 
   2240       complete_pending_call_and_unlock (connection, pending, reply);
   2241       dbus_message_unref (reply);
   2242 
   2243       CONNECTION_LOCK (connection);
   2244       status = _dbus_connection_get_dispatch_status_unlocked (connection);
   2245       _dbus_connection_update_dispatch_status_and_unlock (connection, status);
   2246       dbus_pending_call_unref (pending);
   2247 
   2248       return TRUE;
   2249     }
   2250 
   2251   return FALSE;
   2252 }
   2253 
   2254 /**
   2255  * Blocks until a pending call times out or gets a reply.
   2256  *
   2257  * Does not re-enter the main loop or run filter/path-registered
   2258  * callbacks. The reply to the message will not be seen by
   2259  * filter callbacks.
   2260  *
   2261  * Returns immediately if pending call already got a reply.
   2262  *
   2263  * @todo could use performance improvements (it keeps scanning
   2264  * the whole message queue for example)
   2265  *
   2266  * @param pending the pending call we block for a reply on
   2267  */
   2268 void
   2269 _dbus_connection_block_pending_call (DBusPendingCall *pending)
   2270 {
   2271   long start_tv_sec, start_tv_usec;
   2272   long end_tv_sec, end_tv_usec;
   2273   long tv_sec, tv_usec;
   2274   DBusDispatchStatus status;
   2275   DBusConnection *connection;
   2276   dbus_uint32_t client_serial;
   2277   int timeout_milliseconds;
   2278 
   2279   _dbus_assert (pending != NULL);
   2280 
   2281   if (dbus_pending_call_get_completed (pending))
   2282     return;
   2283 
   2284   dbus_pending_call_ref (pending); /* necessary because the call could be canceled */
   2285 
   2286   connection = _dbus_pending_call_get_connection_and_lock (pending);
   2287 
   2288   /* Flush message queue - note, can affect dispatch status */
   2289   _dbus_connection_flush_unlocked (connection);
   2290 
   2291   client_serial = _dbus_pending_call_get_reply_serial_unlocked (pending);
   2292 
   2293   /* note that timeout_milliseconds is limited to a smallish value
   2294    * in _dbus_pending_call_new() so overflows aren't possible
   2295    * below
   2296    */
   2297   timeout_milliseconds = dbus_timeout_get_interval (_dbus_pending_call_get_timeout_unlocked (pending));
   2298 
   2299   _dbus_get_current_time (&start_tv_sec, &start_tv_usec);
   2300   end_tv_sec = start_tv_sec + timeout_milliseconds / 1000;
   2301   end_tv_usec = start_tv_usec + (timeout_milliseconds % 1000) * 1000;
   2302   end_tv_sec += end_tv_usec / _DBUS_USEC_PER_SECOND;
   2303   end_tv_usec = end_tv_usec % _DBUS_USEC_PER_SECOND;
   2304 
   2305   _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",
   2306                  timeout_milliseconds,
   2307                  client_serial,
   2308                  start_tv_sec, start_tv_usec,
   2309                  end_tv_sec, end_tv_usec);
   2310 
   2311   /* check to see if we already got the data off the socket */
   2312   /* from another blocked pending call */
   2313   if (check_for_reply_and_update_dispatch_unlocked (connection, pending))
   2314     return;
   2315 
   2316   /* Now we wait... */
   2317   /* always block at least once as we know we don't have the reply yet */
   2318   _dbus_connection_do_iteration_unlocked (connection,
   2319                                           pending,
   2320                                           DBUS_ITERATION_DO_READING |
   2321                                           DBUS_ITERATION_BLOCK,
   2322                                           timeout_milliseconds);
   2323 
   2324  recheck_status:
   2325 
   2326   _dbus_verbose ("%s top of recheck\n", _DBUS_FUNCTION_NAME);
   2327 
   2328   HAVE_LOCK_CHECK (connection);
   2329 
   2330   /* queue messages and get status */
   2331 
   2332   status = _dbus_connection_get_dispatch_status_unlocked (connection);
   2333 
   2334   /* the get_completed() is in case a dispatch() while we were blocking
   2335    * got the reply instead of us.
   2336    */
   2337   if (_dbus_pending_call_get_completed_unlocked (pending))
   2338     {
   2339       _dbus_verbose ("Pending call completed by dispatch in %s\n", _DBUS_FUNCTION_NAME);
   2340       _dbus_connection_update_dispatch_status_and_unlock (connection, status);
   2341       dbus_pending_call_unref (pending);
   2342       return;
   2343     }
   2344 
   2345   if (status == DBUS_DISPATCH_DATA_REMAINS) {
   2346     if (check_for_reply_and_update_dispatch_unlocked (connection, pending))
   2347       return;
   2348   }
   2349 
   2350   _dbus_get_current_time (&tv_sec, &tv_usec);
   2351 
   2352   if (!_dbus_connection_get_is_connected_unlocked (connection))
   2353     {
   2354       DBusMessage *error_msg;
   2355 
   2356       error_msg = generate_local_error_message (client_serial,
   2357                                                 DBUS_ERROR_DISCONNECTED,
   2358                                                 "Connection was disconnected before a reply was received");
   2359 
   2360       /* on OOM error_msg is set to NULL */
   2361       complete_pending_call_and_unlock (connection, pending, error_msg);
   2362       dbus_pending_call_unref (pending);
   2363       return;
   2364     }
   2365   else if (tv_sec < start_tv_sec)
   2366     _dbus_verbose ("dbus_connection_send_with_reply_and_block(): clock set backward\n");
   2367   else if (connection->disconnect_message_link == NULL)
   2368     _dbus_verbose ("dbus_connection_send_with_reply_and_block(): disconnected\n");
   2369   else if (tv_sec < end_tv_sec ||
   2370            (tv_sec == end_tv_sec && tv_usec < end_tv_usec))
   2371     {
   2372       timeout_milliseconds = (end_tv_sec - tv_sec) * 1000 +
   2373         (end_tv_usec - tv_usec) / 1000;
   2374       _dbus_verbose ("dbus_connection_send_with_reply_and_block(): %d milliseconds remain\n", timeout_milliseconds);
   2375       _dbus_assert (timeout_milliseconds >= 0);
   2376 
   2377       if (status == DBUS_DISPATCH_NEED_MEMORY)
   2378         {
   2379           /* Try sleeping a bit, as we aren't sure we need to block for reading,
   2380            * we may already have a reply in the buffer and just can't process
   2381            * it.
   2382            */
   2383           _dbus_verbose ("dbus_connection_send_with_reply_and_block() waiting for more memory\n");
   2384 
   2385           _dbus_memory_pause_based_on_timeout (timeout_milliseconds);
   2386         }
   2387       else
   2388         {
   2389           /* block again, we don't have the reply buffered yet. */
   2390           _dbus_connection_do_iteration_unlocked (connection,
   2391                                                   pending,
   2392                                                   DBUS_ITERATION_DO_READING |
   2393                                                   DBUS_ITERATION_BLOCK,
   2394                                                   timeout_milliseconds);
   2395         }
   2396 
   2397       goto recheck_status;
   2398     }
   2399 
   2400   _dbus_verbose ("dbus_connection_send_with_reply_and_block(): Waited %ld milliseconds and got no reply\n",
   2401                  (tv_sec - start_tv_sec) * 1000 + (tv_usec - start_tv_usec) / 1000);
   2402 
   2403   _dbus_assert (!_dbus_pending_call_get_completed_unlocked (pending));
   2404 
   2405   /* unlock and call user code */
   2406   complete_pending_call_and_unlock (connection, pending, NULL);
   2407 
   2408   /* update user code on dispatch status */
   2409   CONNECTION_LOCK (connection);
   2410   status = _dbus_connection_get_dispatch_status_unlocked (connection);
   2411   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
   2412   dbus_pending_call_unref (pending);
   2413 }
   2414 
   2415 /** @} */
   2416 
   2417 /**
   2418  * @addtogroup DBusConnection
   2419  *
   2420  * @{
   2421  */
   2422 
   2423 /**
   2424  * Gets a connection to a remote address. If a connection to the given
   2425  * address already exists, returns the existing connection with its
   2426  * reference count incremented.  Otherwise, returns a new connection
   2427  * and saves the new connection for possible re-use if a future call
   2428  * to dbus_connection_open() asks to connect to the same server.
   2429  *
   2430  * Use dbus_connection_open_private() to get a dedicated connection
   2431  * not shared with other callers of dbus_connection_open().
   2432  *
   2433  * If the open fails, the function returns #NULL, and provides a
   2434  * reason for the failure in the error parameter. Pass #NULL for the
   2435  * error parameter if you aren't interested in the reason for
   2436  * failure.
   2437  *
   2438  * Because this connection is shared, no user of the connection
   2439  * may call dbus_connection_close(). However, when you are done with the
   2440  * connection you should call dbus_connection_unref().
   2441  *
   2442  * @note Prefer dbus_connection_open() to dbus_connection_open_private()
   2443  * unless you have good reason; connections are expensive enough
   2444  * that it's wasteful to create lots of connections to the same
   2445  * server.
   2446  *
   2447  * @param address the address.
   2448  * @param error address where an error can be returned.
   2449  * @returns new connection, or #NULL on failure.
   2450  */
   2451 DBusConnection*
   2452 dbus_connection_open (const char     *address,
   2453                       DBusError      *error)
   2454 {
   2455   DBusConnection *connection;
   2456 
   2457   _dbus_return_val_if_fail (address != NULL, NULL);
   2458   _dbus_return_val_if_error_is_set (error, NULL);
   2459 
   2460   connection = _dbus_connection_open_internal (address,
   2461                                                TRUE,
   2462                                                error);
   2463 
   2464   return connection;
   2465 }
   2466 
   2467 /**
   2468  * Opens a new, dedicated connection to a remote address. Unlike
   2469  * dbus_connection_open(), always creates a new connection.
   2470  * This connection will not be saved or recycled by libdbus.
   2471  *
   2472  * If the open fails, the function returns #NULL, and provides a
   2473  * reason for the failure in the error parameter. Pass #NULL for the
   2474  * error parameter if you aren't interested in the reason for
   2475  * failure.
   2476  *
   2477  * When you are done with this connection, you must
   2478  * dbus_connection_close() to disconnect it,
   2479  * and dbus_connection_unref() to free the connection object.
   2480  *
   2481  * (The dbus_connection_close() can be skipped if the
   2482  * connection is already known to be disconnected, for example
   2483  * if you are inside a handler for the Disconnected signal.)
   2484  *
   2485  * @note Prefer dbus_connection_open() to dbus_connection_open_private()
   2486  * unless you have good reason; connections are expensive enough
   2487  * that it's wasteful to create lots of connections to the same
   2488  * server.
   2489  *
   2490  * @param address the address.
   2491  * @param error address where an error can be returned.
   2492  * @returns new connection, or #NULL on failure.
   2493  */
   2494 DBusConnection*
   2495 dbus_connection_open_private (const char     *address,
   2496                               DBusError      *error)
   2497 {
   2498   DBusConnection *connection;
   2499 
   2500   _dbus_return_val_if_fail (address != NULL, NULL);
   2501   _dbus_return_val_if_error_is_set (error, NULL);
   2502 
   2503   connection = _dbus_connection_open_internal (address,
   2504                                                FALSE,
   2505                                                error);
   2506 
   2507   return connection;
   2508 }
   2509 
   2510 /**
   2511  * Increments the reference count of a DBusConnection.
   2512  *
   2513  * @param connection the connection.
   2514  * @returns the connection.
   2515  */
   2516 DBusConnection *
   2517 dbus_connection_ref (DBusConnection *connection)
   2518 {
   2519   _dbus_return_val_if_fail (connection != NULL, NULL);
   2520   _dbus_return_val_if_fail (connection->generation == _dbus_current_generation, NULL);
   2521 
   2522   /* The connection lock is better than the global
   2523    * lock in the atomic increment fallback
   2524    */
   2525 
   2526 #ifdef DBUS_HAVE_ATOMIC_INT
   2527   _dbus_atomic_inc (&connection->refcount);
   2528 #else
   2529   CONNECTION_LOCK (connection);
   2530   _dbus_assert (connection->refcount.value > 0);
   2531 
   2532   connection->refcount.value += 1;
   2533   CONNECTION_UNLOCK (connection);
   2534 #endif
   2535 
   2536   return connection;
   2537 }
   2538 
   2539 static void
   2540 free_outgoing_message (void *element,
   2541                        void *data)
   2542 {
   2543   DBusMessage *message = element;
   2544   DBusConnection *connection = data;
   2545 
   2546   _dbus_message_remove_size_counter (message,
   2547                                      connection->outgoing_counter,
   2548                                      NULL);
   2549   dbus_message_unref (message);
   2550 }
   2551 
   2552 /* This is run without the mutex held, but after the last reference
   2553  * to the connection has been dropped we should have no thread-related
   2554  * problems
   2555  */
   2556 static void
   2557 _dbus_connection_last_unref (DBusConnection *connection)
   2558 {
   2559   DBusList *link;
   2560 
   2561   _dbus_verbose ("Finalizing connection %p\n", connection);
   2562 
   2563   _dbus_assert (connection->refcount.value == 0);
   2564 
   2565   /* You have to disconnect the connection before unref:ing it. Otherwise
   2566    * you won't get the disconnected message.
   2567    */
   2568   _dbus_assert (!_dbus_transport_get_is_connected (connection->transport));
   2569   _dbus_assert (connection->server_guid == NULL);
   2570 
   2571   /* ---- We're going to call various application callbacks here, hope it doesn't break anything... */
   2572   _dbus_object_tree_free_all_unlocked (connection->objects);
   2573 
   2574   dbus_connection_set_dispatch_status_function (connection, NULL, NULL, NULL);
   2575   dbus_connection_set_wakeup_main_function (connection, NULL, NULL, NULL);
   2576   dbus_connection_set_unix_user_function (connection, NULL, NULL, NULL);
   2577 
   2578   _dbus_watch_list_free (connection->watches);
   2579   connection->watches = NULL;
   2580 
   2581   _dbus_timeout_list_free (connection->timeouts);
   2582   connection->timeouts = NULL;
   2583 
   2584   _dbus_data_slot_list_free (&connection->slot_list);
   2585 
   2586   link = _dbus_list_get_first_link (&connection->filter_list);
   2587   while (link != NULL)
   2588     {
   2589       DBusMessageFilter *filter = link->data;
   2590       DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
   2591 
   2592       filter->function = NULL;
   2593       _dbus_message_filter_unref (filter); /* calls app callback */
   2594       link->data = NULL;
   2595 
   2596       link = next;
   2597     }
   2598   _dbus_list_clear (&connection->filter_list);
   2599 
   2600   /* ---- Done with stuff that invokes application callbacks */
   2601 
   2602   _dbus_object_tree_unref (connection->objects);
   2603 
   2604   _dbus_hash_table_unref (connection->pending_replies);
   2605   connection->pending_replies = NULL;
   2606 
   2607   _dbus_list_clear (&connection->filter_list);
   2608 
   2609   _dbus_list_foreach (&connection->outgoing_messages,
   2610                       free_outgoing_message,
   2611 		      connection);
   2612   _dbus_list_clear (&connection->outgoing_messages);
   2613 
   2614   _dbus_list_foreach (&connection->incoming_messages,
   2615 		      (DBusForeachFunction) dbus_message_unref,
   2616 		      NULL);
   2617   _dbus_list_clear (&connection->incoming_messages);
   2618 
   2619   _dbus_counter_unref (connection->outgoing_counter);
   2620 
   2621   _dbus_transport_unref (connection->transport);
   2622 
   2623   if (connection->disconnect_message_link)
   2624     {
   2625       DBusMessage *message = connection->disconnect_message_link->data;
   2626       dbus_message_unref (message);
   2627       _dbus_list_free_link (connection->disconnect_message_link);
   2628     }
   2629 
   2630   _dbus_list_clear (&connection->link_cache);
   2631 
   2632   _dbus_condvar_free_at_location (&connection->dispatch_cond);
   2633   _dbus_condvar_free_at_location (&connection->io_path_cond);
   2634 
   2635   _dbus_mutex_free_at_location (&connection->io_path_mutex);
   2636   _dbus_mutex_free_at_location (&connection->dispatch_mutex);
   2637 
   2638   _dbus_mutex_free_at_location (&connection->mutex);
   2639 
   2640   dbus_free (connection);
   2641 }
   2642 
   2643 /**
   2644  * Decrements the reference count of a DBusConnection, and finalizes
   2645  * it if the count reaches zero.
   2646  *
   2647  * Note: it is a bug to drop the last reference to a connection that
   2648  * is still connected.
   2649  *
   2650  * For shared connections, libdbus will own a reference
   2651  * as long as the connection is connected, so you can know that either
   2652  * you don't have the last reference, or it's OK to drop the last reference.
   2653  * Most connections are shared. dbus_connection_open() and dbus_bus_get()
   2654  * return shared connections.
   2655  *
   2656  * For private connections, the creator of the connection must arrange for
   2657  * dbus_connection_close() to be called prior to dropping the last reference.
   2658  * Private connections come from dbus_connection_open_private() or dbus_bus_get_private().
   2659  *
   2660  * @param connection the connection.
   2661  */
   2662 void
   2663 dbus_connection_unref (DBusConnection *connection)
   2664 {
   2665   dbus_bool_t last_unref;
   2666 
   2667   _dbus_return_if_fail (connection != NULL);
   2668   _dbus_return_if_fail (connection->generation == _dbus_current_generation);
   2669 
   2670   /* The connection lock is better than the global
   2671    * lock in the atomic increment fallback
   2672    */
   2673 
   2674 #ifdef DBUS_HAVE_ATOMIC_INT
   2675   last_unref = (_dbus_atomic_dec (&connection->refcount) == 1);
   2676 #else
   2677   CONNECTION_LOCK (connection);
   2678 
   2679   _dbus_assert (connection->refcount.value > 0);
   2680 
   2681   connection->refcount.value -= 1;
   2682   last_unref = (connection->refcount.value == 0);
   2683 
   2684 #if 0
   2685   printf ("unref() connection %p count = %d\n", connection, connection->refcount.value);
   2686 #endif
   2687 
   2688   CONNECTION_UNLOCK (connection);
   2689 #endif
   2690 
   2691   if (last_unref)
   2692     {
   2693 #ifndef DBUS_DISABLE_CHECKS
   2694       if (_dbus_transport_get_is_connected (connection->transport))
   2695         {
   2696           _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",
   2697                                    connection->shareable ?
   2698                                    "Most likely, the application called unref() too many times and removed a reference belonging to libdbus, since this is a shared connection.\n" :
   2699                                     "Most likely, the application was supposed to call dbus_connection_close(), since this is a private connection.\n");
   2700           return;
   2701         }
   2702 #endif
   2703       _dbus_connection_last_unref (connection);
   2704     }
   2705 }
   2706 
   2707 /*
   2708  * Note that the transport can disconnect itself (other end drops us)
   2709  * and in that case this function never runs. So this function must
   2710  * not do anything more than disconnect the transport and update the
   2711  * dispatch status.
   2712  *
   2713  * If the transport self-disconnects, then we assume someone will
   2714  * dispatch the connection to cause the dispatch status update.
   2715  */
   2716 static void
   2717 _dbus_connection_close_possibly_shared_and_unlock (DBusConnection *connection)
   2718 {
   2719   DBusDispatchStatus status;
   2720 
   2721   HAVE_LOCK_CHECK (connection);
   2722 
   2723   _dbus_verbose ("Disconnecting %p\n", connection);
   2724 
   2725   /* We need to ref because update_dispatch_status_and_unlock will unref
   2726    * the connection if it was shared and libdbus was the only remaining
   2727    * refcount holder.
   2728    */
   2729   _dbus_connection_ref_unlocked (connection);
   2730 
   2731   _dbus_transport_disconnect (connection->transport);
   2732 
   2733   /* This has the side effect of queuing the disconnect message link
   2734    * (unless we don't have enough memory, possibly, so don't assert it).
   2735    * After the disconnect message link is queued, dbus_bus_get/dbus_connection_open
   2736    * should never again return the newly-disconnected connection.
   2737    *
   2738    * However, we only unref the shared connection and exit_on_disconnect when
   2739    * the disconnect message reaches the head of the message queue,
   2740    * NOT when it's first queued.
   2741    */
   2742   status = _dbus_connection_get_dispatch_status_unlocked (connection);
   2743 
   2744   /* This calls out to user code */
   2745   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
   2746 
   2747   /* Could also call out to user code */
   2748   dbus_connection_unref (connection);
   2749 }
   2750 
   2751 /**
   2752  * Closes a private connection, so no further data can be sent or received.
   2753  * This disconnects the transport (such as a socket) underlying the
   2754  * connection.
   2755  *
   2756  * Attempts to send messages after closing a connection are safe, but will result in
   2757  * error replies generated locally in libdbus.
   2758  *
   2759  * This function does not affect the connection's reference count.  It's
   2760  * safe to close a connection more than once; all calls after the
   2761  * first do nothing. It's impossible to "reopen" a connection, a
   2762  * new connection must be created. This function may result in a call
   2763  * to the DBusDispatchStatusFunction set with
   2764  * dbus_connection_set_dispatch_status_function(), as the disconnect
   2765  * message it generates needs to be dispatched.
   2766  *
   2767  * If a connection is dropped by the remote application, it will
   2768  * close itself.
   2769  *
   2770  * You must close a connection prior to releasing the last reference to
   2771  * the connection. If you dbus_connection_unref() for the last time
   2772  * without closing the connection, the results are undefined; it
   2773  * is a bug in your program and libdbus will try to print a warning.
   2774  *
   2775  * You may not close a shared connection. Connections created with
   2776  * dbus_connection_open() or dbus_bus_get() are shared.
   2777  * These connections are owned by libdbus, and applications should
   2778  * only unref them, never close them. Applications can know it is
   2779  * safe to unref these connections because libdbus will be holding a
   2780  * reference as long as the connection is open. Thus, either the
   2781  * connection is closed and it is OK to drop the last reference,
   2782  * or the connection is open and the app knows it does not have the
   2783  * last reference.
   2784  *
   2785  * Connections created with dbus_connection_open_private() or
   2786  * dbus_bus_get_private() are not kept track of or referenced by
   2787  * libdbus. The creator of these connections is responsible for
   2788  * calling dbus_connection_close() prior to releasing the last
   2789  * reference, if the connection is not already disconnected.
   2790  *
   2791  * @param connection the private (unshared) connection to close
   2792  */
   2793 void
   2794 dbus_connection_close (DBusConnection *connection)
   2795 {
   2796   _dbus_return_if_fail (connection != NULL);
   2797   _dbus_return_if_fail (connection->generation == _dbus_current_generation);
   2798 
   2799   CONNECTION_LOCK (connection);
   2800 
   2801 #ifndef DBUS_DISABLE_CHECKS
   2802   if (connection->shareable)
   2803     {
   2804       CONNECTION_UNLOCK (connection);
   2805 
   2806       _dbus_warn_check_failed ("Applications must not close shared connections - see dbus_connection_close() docs. This is a bug in the application.\n");
   2807       return;
   2808     }
   2809 #endif
   2810 
   2811   _dbus_connection_close_possibly_shared_and_unlock (connection);
   2812 }
   2813 
   2814 static dbus_bool_t
   2815 _dbus_connection_get_is_connected_unlocked (DBusConnection *connection)
   2816 {
   2817   HAVE_LOCK_CHECK (connection);
   2818   return _dbus_transport_get_is_connected (connection->transport);
   2819 }
   2820 
   2821 /**
   2822  * Gets whether the connection is currently open.  A connection may
   2823  * become disconnected when the remote application closes its end, or
   2824  * exits; a connection may also be disconnected with
   2825  * dbus_connection_close().
   2826  *
   2827  * There are not separate states for "closed" and "disconnected," the two
   2828  * terms are synonymous. This function should really be called
   2829  * get_is_open() but for historical reasons is not.
   2830  *
   2831  * @param connection the connection.
   2832  * @returns #TRUE if the connection is still alive.
   2833  */
   2834 dbus_bool_t
   2835 dbus_connection_get_is_connected (DBusConnection *connection)
   2836 {
   2837   dbus_bool_t res;
   2838 
   2839   _dbus_return_val_if_fail (connection != NULL, FALSE);
   2840 
   2841   CONNECTION_LOCK (connection);
   2842   res = _dbus_connection_get_is_connected_unlocked (connection);
   2843   CONNECTION_UNLOCK (connection);
   2844 
   2845   return res;
   2846 }
   2847 
   2848 /**
   2849  * Gets whether the connection was authenticated. (Note that
   2850  * if the connection was authenticated then disconnected,
   2851  * this function still returns #TRUE)
   2852  *
   2853  * @param connection the connection
   2854  * @returns #TRUE if the connection was ever authenticated
   2855  */
   2856 dbus_bool_t
   2857 dbus_connection_get_is_authenticated (DBusConnection *connection)
   2858 {
   2859   dbus_bool_t res;
   2860 
   2861   _dbus_return_val_if_fail (connection != NULL, FALSE);
   2862 
   2863   CONNECTION_LOCK (connection);
   2864   res = _dbus_transport_get_is_authenticated (connection->transport);
   2865   CONNECTION_UNLOCK (connection);
   2866 
   2867   return res;
   2868 }
   2869 
   2870 /**
   2871  * Set whether _exit() should be called when the connection receives a
   2872  * disconnect signal. The call to _exit() comes after any handlers for
   2873  * the disconnect signal run; handlers can cancel the exit by calling
   2874  * this function.
   2875  *
   2876  * By default, exit_on_disconnect is #FALSE; but for message bus
   2877  * connections returned from dbus_bus_get() it will be toggled on
   2878  * by default.
   2879  *
   2880  * @param connection the connection
   2881  * @param exit_on_disconnect #TRUE if _exit() should be called after a disconnect signal
   2882  */
   2883 void
   2884 dbus_connection_set_exit_on_disconnect (DBusConnection *connection,
   2885                                         dbus_bool_t     exit_on_disconnect)
   2886 {
   2887   _dbus_return_if_fail (connection != NULL);
   2888 
   2889   CONNECTION_LOCK (connection);
   2890   connection->exit_on_disconnect = exit_on_disconnect != FALSE;
   2891   CONNECTION_UNLOCK (connection);
   2892 }
   2893 
   2894 /**
   2895  * Preallocates resources needed to send a message, allowing the message
   2896  * to be sent without the possibility of memory allocation failure.
   2897  * Allows apps to create a future guarantee that they can send
   2898  * a message regardless of memory shortages.
   2899  *
   2900  * @param connection the connection we're preallocating for.
   2901  * @returns the preallocated resources, or #NULL
   2902  */
   2903 DBusPreallocatedSend*
   2904 dbus_connection_preallocate_send (DBusConnection *connection)
   2905 {
   2906   DBusPreallocatedSend *preallocated;
   2907 
   2908   _dbus_return_val_if_fail (connection != NULL, NULL);
   2909 
   2910   CONNECTION_LOCK (connection);
   2911 
   2912   preallocated =
   2913     _dbus_connection_preallocate_send_unlocked (connection);
   2914 
   2915   CONNECTION_UNLOCK (connection);
   2916 
   2917   return preallocated;
   2918 }
   2919 
   2920 /**
   2921  * Frees preallocated message-sending resources from
   2922  * dbus_connection_preallocate_send(). Should only
   2923  * be called if the preallocated resources are not used
   2924  * to send a message.
   2925  *
   2926  * @param connection the connection
   2927  * @param preallocated the resources
   2928  */
   2929 void
   2930 dbus_connection_free_preallocated_send (DBusConnection       *connection,
   2931                                         DBusPreallocatedSend *preallocated)
   2932 {
   2933   _dbus_return_if_fail (connection != NULL);
   2934   _dbus_return_if_fail (preallocated != NULL);
   2935   _dbus_return_if_fail (connection == preallocated->connection);
   2936 
   2937   _dbus_list_free_link (preallocated->queue_link);
   2938   _dbus_counter_unref (preallocated->counter_link->data);
   2939   _dbus_list_free_link (preallocated->counter_link);
   2940   dbus_free (preallocated);
   2941 }
   2942 
   2943 /**
   2944  * Sends a message using preallocated resources. This function cannot fail.
   2945  * It works identically to dbus_connection_send() in other respects.
   2946  * Preallocated resources comes from dbus_connection_preallocate_send().
   2947  * This function "consumes" the preallocated resources, they need not
   2948  * be freed separately.
   2949  *
   2950  * @param connection the connection
   2951  * @param preallocated the preallocated resources
   2952  * @param message the message to send
   2953  * @param client_serial return location for client serial assigned to the message
   2954  */
   2955 void
   2956 dbus_connection_send_preallocated (DBusConnection       *connection,
   2957                                    DBusPreallocatedSend *preallocated,
   2958                                    DBusMessage          *message,
   2959                                    dbus_uint32_t        *client_serial)
   2960 {
   2961   _dbus_return_if_fail (connection != NULL);
   2962   _dbus_return_if_fail (preallocated != NULL);
   2963   _dbus_return_if_fail (message != NULL);
   2964   _dbus_return_if_fail (preallocated->connection == connection);
   2965   _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_METHOD_CALL ||
   2966                         dbus_message_get_member (message) != NULL);
   2967   _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL ||
   2968                         (dbus_message_get_interface (message) != NULL &&
   2969                          dbus_message_get_member (message) != NULL));
   2970 
   2971   CONNECTION_LOCK (connection);
   2972   _dbus_connection_send_preallocated_and_unlock (connection,
   2973 						 preallocated,
   2974 						 message, client_serial);
   2975 }
   2976 
   2977 static dbus_bool_t
   2978 _dbus_connection_send_unlocked_no_update (DBusConnection *connection,
   2979                                           DBusMessage    *message,
   2980                                           dbus_uint32_t  *client_serial)
   2981 {
   2982   DBusPreallocatedSend *preallocated;
   2983 
   2984   _dbus_assert (connection != NULL);
   2985   _dbus_assert (message != NULL);
   2986 
   2987   preallocated = _dbus_connection_preallocate_send_unlocked (connection);
   2988   if (preallocated == NULL)
   2989     return FALSE;
   2990 
   2991   _dbus_connection_send_preallocated_unlocked_no_update (connection,
   2992                                                          preallocated,
   2993                                                          message,
   2994                                                          client_serial);
   2995   return TRUE;
   2996 }
   2997 
   2998 /**
   2999  * Adds a message to the outgoing message queue. Does not block to
   3000  * write the message to the network; that happens asynchronously. To
   3001  * force the message to be written, call dbus_connection_flush().
   3002  * Because this only queues the message, the only reason it can
   3003  * fail is lack of memory. Even if the connection is disconnected,
   3004  * no error will be returned.
   3005  *
   3006  * If the function fails due to lack of memory, it returns #FALSE.
   3007  * The function will never fail for other reasons; even if the
   3008  * connection is disconnected, you can queue an outgoing message,
   3009  * though obviously it won't be sent.
   3010  *
   3011  * The message serial is used by the remote application to send a
   3012  * reply; see dbus_message_get_serial() or the D-Bus specification.
   3013  *
   3014  * @param connection the connection.
   3015  * @param message the message to write.
   3016  * @param serial return location for message serial, or #NULL if you don't care
   3017  * @returns #TRUE on success.
   3018  */
   3019 dbus_bool_t
   3020 dbus_connection_send (DBusConnection *connection,
   3021                       DBusMessage    *message,
   3022                       dbus_uint32_t  *serial)
   3023 {
   3024   _dbus_return_val_if_fail (connection != NULL, FALSE);
   3025   _dbus_return_val_if_fail (message != NULL, FALSE);
   3026 
   3027   CONNECTION_LOCK (connection);
   3028 
   3029   return _dbus_connection_send_and_unlock (connection,
   3030 					   message,
   3031 					   serial);
   3032 }
   3033 
   3034 static dbus_bool_t
   3035 reply_handler_timeout (void *data)
   3036 {
   3037   DBusConnection *connection;
   3038   DBusDispatchStatus status;
   3039   DBusPendingCall *pending = data;
   3040 
   3041   connection = _dbus_pending_call_get_connection_and_lock (pending);
   3042 
   3043   _dbus_pending_call_queue_timeout_error_unlocked (pending,
   3044                                                    connection);
   3045   _dbus_connection_remove_timeout_unlocked (connection,
   3046 				            _dbus_pending_call_get_timeout_unlocked (pending));
   3047   _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
   3048 
   3049   _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
   3050   status = _dbus_connection_get_dispatch_status_unlocked (connection);
   3051 
   3052   /* Unlocks, and calls out to user code */
   3053   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
   3054 
   3055   return TRUE;
   3056 }
   3057 
   3058 /**
   3059  * Queues a message to send, as with dbus_connection_send(),
   3060  * but also returns a #DBusPendingCall used to receive a reply to the
   3061  * message. If no reply is received in the given timeout_milliseconds,
   3062  * this function expires the pending reply and generates a synthetic
   3063  * error reply (generated in-process, not by the remote application)
   3064  * indicating that a timeout occurred.
   3065  *
   3066  * A #DBusPendingCall will see a reply message before any filters or
   3067  * registered object path handlers. See dbus_connection_dispatch() for
   3068  * details on when handlers are run.
   3069  *
   3070  * A #DBusPendingCall will always see exactly one reply message,
   3071  * unless it's cancelled with dbus_pending_call_cancel().
   3072  *
   3073  * If #NULL is passed for the pending_return, the #DBusPendingCall
   3074  * will still be generated internally, and used to track
   3075  * the message reply timeout. This means a timeout error will
   3076  * occur if no reply arrives, unlike with dbus_connection_send().
   3077  *
   3078  * If -1 is passed for the timeout, a sane default timeout is used. -1
   3079  * is typically the best value for the timeout for this reason, unless
   3080  * you want a very short or very long timeout.  There is no way to
   3081  * avoid a timeout entirely, other than passing INT_MAX for the
   3082  * timeout to mean "very long timeout." libdbus clamps an INT_MAX
   3083  * timeout down to a few hours timeout though.
   3084  *
   3085  * @warning if the connection is disconnected, the #DBusPendingCall
   3086  * will be set to #NULL, so be careful with this.
   3087  *
   3088  * @param connection the connection
   3089  * @param message the message to send
   3090  * @param pending_return return location for a #DBusPendingCall object, or #NULL if connection is disconnected
   3091  * @param timeout_milliseconds timeout in milliseconds or -1 for default
   3092  * @returns #FALSE if no memory, #TRUE otherwise.
   3093  *
   3094  */
   3095 dbus_bool_t
   3096 dbus_connection_send_with_reply (DBusConnection     *connection,
   3097                                  DBusMessage        *message,
   3098                                  DBusPendingCall   **pending_return,
   3099                                  int                 timeout_milliseconds)
   3100 {
   3101   DBusPendingCall *pending;
   3102   dbus_int32_t serial = -1;
   3103   DBusDispatchStatus status;
   3104 
   3105   _dbus_return_val_if_fail (connection != NULL, FALSE);
   3106   _dbus_return_val_if_fail (message != NULL, FALSE);
   3107   _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
   3108 
   3109   if (pending_return)
   3110     *pending_return = NULL;
   3111 
   3112   CONNECTION_LOCK (connection);
   3113 
   3114    if (!_dbus_connection_get_is_connected_unlocked (connection))
   3115     {
   3116       CONNECTION_UNLOCK (connection);
   3117 
   3118       *pending_return = NULL;
   3119 
   3120       return TRUE;
   3121     }
   3122 
   3123   pending = _dbus_pending_call_new_unlocked (connection,
   3124                                              timeout_milliseconds,
   3125                                              reply_handler_timeout);
   3126 
   3127   if (pending == NULL)
   3128     {
   3129       CONNECTION_UNLOCK (connection);
   3130       return FALSE;
   3131     }
   3132 
   3133   /* Assign a serial to the message */
   3134   serial = dbus_message_get_serial (message);
   3135   if (serial == 0)
   3136     {
   3137       serial = _dbus_connection_get_next_client_serial (connection);
   3138       _dbus_message_set_serial (message, serial);
   3139     }
   3140 
   3141   if (!_dbus_pending_call_set_timeout_error_unlocked (pending, message, serial))
   3142     goto error;
   3143 
   3144   /* Insert the serial in the pending replies hash;
   3145    * hash takes a refcount on DBusPendingCall.
   3146    * Also, add the timeout.
   3147    */
   3148   if (!_dbus_connection_attach_pending_call_unlocked (connection,
   3149 						      pending))
   3150     goto error;
   3151 
   3152   if (!_dbus_connection_send_unlocked_no_update (connection, message, NULL))
   3153     {
   3154       _dbus_connection_detach_pending_call_and_unlock (connection,
   3155 						       pending);
   3156       goto error_unlocked;
   3157     }
   3158 
   3159   if (pending_return)
   3160     *pending_return = pending; /* hand off refcount */
   3161   else
   3162     {
   3163       _dbus_connection_detach_pending_call_unlocked (connection, pending);
   3164       /* we still have a ref to the pending call in this case, we unref
   3165        * after unlocking, below
   3166        */
   3167     }
   3168 
   3169   status = _dbus_connection_get_dispatch_status_unlocked (connection);
   3170 
   3171   /* this calls out to user code */
   3172   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
   3173 
   3174   if (pending_return == NULL)
   3175     dbus_pending_call_unref (pending);
   3176 
   3177   return TRUE;
   3178 
   3179  error:
   3180   CONNECTION_UNLOCK (connection);
   3181  error_unlocked:
   3182   dbus_pending_call_unref (pending);
   3183   return FALSE;
   3184 }
   3185 
   3186 /**
   3187  * Sends a message and blocks a certain time period while waiting for
   3188  * a reply.  This function does not reenter the main loop,
   3189  * i.e. messages other than the reply are queued up but not
   3190  * processed. This function is used to invoke method calls on a
   3191  * remote object.
   3192  *
   3193  * If a normal reply is received, it is returned, and removed from the
   3194  * incoming message queue. If it is not received, #NULL is returned
   3195  * and the error is set to #DBUS_ERROR_NO_REPLY.  If an error reply is
   3196  * received, it is converted to a #DBusError and returned as an error,
   3197  * then the reply message is deleted and #NULL is returned. If
   3198  * something else goes wrong, result is set to whatever is
   3199  * appropriate, such as #DBUS_ERROR_NO_MEMORY or
   3200  * #DBUS_ERROR_DISCONNECTED.
   3201  *
   3202  * @warning While this function blocks the calling thread will not be
   3203  * processing the incoming message queue. This means you can end up
   3204  * deadlocked if the application you're talking to needs you to reply
   3205  * to a method. To solve this, either avoid the situation, block in a
   3206  * separate thread from the main connection-dispatching thread, or use
   3207  * dbus_pending_call_set_notify() to avoid blocking.
   3208  *
   3209  * @param connection the connection
   3210  * @param message the message to send
   3211  * @param timeout_milliseconds timeout in milliseconds or -1 for default
   3212  * @param error return location for error message
   3213  * @returns the message that is the reply or #NULL with an error code if the
   3214  * function fails.
   3215  */
   3216 DBusMessage*
   3217 dbus_connection_send_with_reply_and_block (DBusConnection     *connection,
   3218                                            DBusMessage        *message,
   3219                                            int                 timeout_milliseconds,
   3220                                            DBusError          *error)
   3221 {
   3222   DBusMessage *reply;
   3223   DBusPendingCall *pending;
   3224 
   3225   _dbus_return_val_if_fail (connection != NULL, NULL);
   3226   _dbus_return_val_if_fail (message != NULL, NULL);
   3227   _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, NULL);
   3228   _dbus_return_val_if_error_is_set (error, NULL);
   3229 
   3230   if (!dbus_connection_send_with_reply (connection, message,
   3231                                         &pending, timeout_milliseconds))
   3232     {
   3233       _DBUS_SET_OOM (error);
   3234       return NULL;
   3235     }
   3236 
   3237   if (pending == NULL)
   3238     {
   3239       dbus_set_error (error, DBUS_ERROR_DISCONNECTED, "Connection is closed");
   3240       return NULL;
   3241     }
   3242 
   3243   dbus_pending_call_block (pending);
   3244 
   3245   reply = dbus_pending_call_steal_reply (pending);
   3246   dbus_pending_call_unref (pending);
   3247 
   3248   /* call_complete_and_unlock() called from pending_call_block() should
   3249    * always fill this in.
   3250    */
   3251   _dbus_assert (reply != NULL);
   3252 
   3253    if (dbus_set_error_from_message (error, reply))
   3254     {
   3255       dbus_message_unref (reply);
   3256       return NULL;
   3257     }
   3258   else
   3259     return reply;
   3260 }
   3261 
   3262 /**
   3263  * Blocks until the outgoing message queue is empty.
   3264  * Assumes connection lock already held.
   3265  *
   3266  * If you call this, you MUST call update_dispatch_status afterword...
   3267  *
   3268  * @param connection the connection.
   3269  */
   3270 DBusDispatchStatus
   3271 _dbus_connection_flush_unlocked (DBusConnection *connection)
   3272 {
   3273   /* We have to specify DBUS_ITERATION_DO_READING here because
   3274    * otherwise we could have two apps deadlock if they are both doing
   3275    * a flush(), and the kernel buffers fill up. This could change the
   3276    * dispatch status.
   3277    */
   3278   DBusDispatchStatus status;
   3279 
   3280   HAVE_LOCK_CHECK (connection);
   3281 
   3282   while (connection->n_outgoing > 0 &&
   3283          _dbus_connection_get_is_connected_unlocked (connection))
   3284     {
   3285       _dbus_verbose ("doing iteration in %s\n", _DBUS_FUNCTION_NAME);
   3286       HAVE_LOCK_CHECK (connection);
   3287       _dbus_connection_do_iteration_unlocked (connection,
   3288                                               NULL,
   3289                                               DBUS_ITERATION_DO_READING |
   3290                                               DBUS_ITERATION_DO_WRITING |
   3291                                               DBUS_ITERATION_BLOCK,
   3292                                               -1);
   3293     }
   3294 
   3295   HAVE_LOCK_CHECK (connection);
   3296   _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
   3297   status = _dbus_connection_get_dispatch_status_unlocked (connection);
   3298 
   3299   HAVE_LOCK_CHECK (connection);
   3300   return status;
   3301 }
   3302 
   3303 /**
   3304  * Blocks until the outgoing message queue is empty.
   3305  *
   3306  * @param connection the connection.
   3307  */
   3308 void
   3309 dbus_connection_flush (DBusConnection *connection)
   3310 {
   3311   /* We have to specify DBUS_ITERATION_DO_READING here because
   3312    * otherwise we could have two apps deadlock if they are both doing
   3313    * a flush(), and the kernel buffers fill up. This could change the
   3314    * dispatch status.
   3315    */
   3316   DBusDispatchStatus status;
   3317 
   3318   _dbus_return_if_fail (connection != NULL);
   3319 
   3320   CONNECTION_LOCK (connection);
   3321 
   3322   status = _dbus_connection_flush_unlocked (connection);
   3323 
   3324   HAVE_LOCK_CHECK (connection);
   3325   /* Unlocks and calls out to user code */
   3326   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
   3327 
   3328   _dbus_verbose ("%s end\n", _DBUS_FUNCTION_NAME);
   3329 }
   3330 
   3331 /**
   3332  * This function implements dbus_connection_read_write_dispatch() and
   3333  * dbus_connection_read_write() (they pass a different value for the
   3334  * dispatch parameter).
   3335  *
   3336  * @param connection the connection
   3337  * @param timeout_milliseconds max time to block or -1 for infinite
   3338  * @param dispatch dispatch new messages or leave them on the incoming queue
   3339  * @returns #TRUE if the disconnect message has not been processed
   3340  */
   3341 static dbus_bool_t
   3342 _dbus_connection_read_write_dispatch (DBusConnection *connection,
   3343                                      int             timeout_milliseconds,
   3344                                      dbus_bool_t     dispatch)
   3345 {
   3346   DBusDispatchStatus dstatus;
   3347   dbus_bool_t no_progress_possible;
   3348 
   3349   dstatus = dbus_connection_get_dispatch_status (connection);
   3350 
   3351   if (dispatch && dstatus == DBUS_DISPATCH_DATA_REMAINS)
   3352     {
   3353       _dbus_verbose ("doing dispatch in %s\n", _DBUS_FUNCTION_NAME);
   3354       dbus_connection_dispatch (connection);
   3355       CONNECTION_LOCK (connection);
   3356     }
   3357   else if (dstatus == DBUS_DISPATCH_NEED_MEMORY)
   3358     {
   3359       _dbus_verbose ("pausing for memory in %s\n", _DBUS_FUNCTION_NAME);
   3360       _dbus_memory_pause_based_on_timeout (timeout_milliseconds);
   3361       CONNECTION_LOCK (connection);
   3362     }
   3363   else
   3364     {
   3365       CONNECTION_LOCK (connection);
   3366       if (_dbus_connection_get_is_connected_unlocked (connection))
   3367         {
   3368           _dbus_verbose ("doing iteration in %s\n", _DBUS_FUNCTION_NAME);
   3369           _dbus_connection_do_iteration_unlocked (connection,
   3370                                                   NULL,
   3371                                                   DBUS_ITERATION_DO_READING |
   3372                                                   DBUS_ITERATION_DO_WRITING |
   3373                                                   DBUS_ITERATION_BLOCK,
   3374                                                   timeout_milliseconds);
   3375         }
   3376     }
   3377 
   3378   HAVE_LOCK_CHECK (connection);
   3379   /* If we can dispatch, we can make progress until the Disconnected message
   3380    * has been processed; if we can only read/write, we can make progress
   3381    * as long as the transport is open.
   3382    */
   3383   if (dispatch)
   3384     no_progress_possible = connection->n_incoming == 0 &&
   3385       connection->disconnect_message_link == NULL;
   3386   else
   3387     no_progress_possible = _dbus_connection_get_is_connected_unlocked (connection);
   3388   CONNECTION_UNLOCK (connection);
   3389   return !no_progress_possible; /* TRUE if we can make more progress */
   3390 }
   3391 
   3392 
   3393 /**
   3394  * This function is intended for use with applications that don't want
   3395  * to write a main loop and deal with #DBusWatch and #DBusTimeout. An
   3396  * example usage would be:
   3397  *
   3398  * @code
   3399  *   while (dbus_connection_read_write_dispatch (connection, -1))
   3400  *     ; // empty loop body
   3401  * @endcode
   3402  *
   3403  * In this usage you would normally have set up a filter function to look
   3404  * at each message as it is dispatched. The loop terminates when the last
   3405  * message from the connection (the disconnected signal) is processed.
   3406  *
   3407  * If there are messages to dispatch, this function will
   3408  * dbus_connection_dispatch() once, and return. If there are no
   3409  * messages to dispatch, this function will block until it can read or
   3410  * write, then read or write, then return.
   3411  *
   3412  * The way to think of this function is that it either makes some sort
   3413  * of progress, or it blocks. Note that, while it is blocked on I/O, it
   3414  * cannot be interrupted (even by other threads), which makes this function
   3415  * unsuitable for applications that do more than just react to received
   3416  * messages.
   3417  *
   3418  * The return value indicates whether the disconnect message has been
   3419  * processed, NOT whether the connection is connected. This is
   3420  * important because even after disconnecting, you want to process any
   3421  * messages you received prior to the disconnect.
   3422  *
   3423  * @param connection the connection
   3424  * @param timeout_milliseconds max time to block or -1 for infinite
   3425  * @returns #TRUE if the disconnect message has not been processed
   3426  */
   3427 dbus_bool_t
   3428 dbus_connection_read_write_dispatch (DBusConnection *connection,
   3429                                      int             timeout_milliseconds)
   3430 {
   3431   _dbus_return_val_if_fail (connection != NULL, FALSE);
   3432   _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
   3433    return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, TRUE);
   3434 }
   3435 
   3436 
   3437 /**
   3438  * This function is intended for use with applications that want to
   3439  * dispatch all the events in the incoming/outgoing queue before returning.
   3440  * The function just calls dbus_connection_read_write_dispatch till
   3441  * the incoming queue is empty.
   3442  *
   3443  * @param connection the connection
   3444  * @param timeout_milliseconds max time to block or -1 for infinite
   3445  * @returns #TRUE if the disconnect message has not been processed
   3446  */
   3447 dbus_bool_t
   3448 dbus_connection_read_write_dispatch_greedy (DBusConnection *connection,
   3449                                             int   timeout_milliseconds)
   3450 {
   3451   dbus_bool_t ret, progress_possible;
   3452   int pre_incoming, pre_outgoing;
   3453   do
   3454     {
   3455       pre_incoming = connection->n_incoming;
   3456       pre_outgoing = connection->n_outgoing;
   3457       ret = dbus_connection_read_write_dispatch(connection, timeout_milliseconds);
   3458       /* No need to take a lock here. If another 'reader' thread has read the packet,
   3459        * dbus_connection_read_write_dispatch will just return. If a writer
   3460        * writes a packet between the call and the check, it will get processed
   3461        * in the next call to the function.
   3462        */
   3463       if ((pre_incoming != connection->n_incoming ||
   3464            pre_outgoing != connection->n_outgoing) &&
   3465           (connection->n_incoming > 0 ||
   3466            connection->n_outgoing > 0)) {
   3467         progress_possible = TRUE;
   3468       } else {
   3469         progress_possible = FALSE;
   3470       }
   3471     } while (ret == TRUE && progress_possible);
   3472   return ret;
   3473 }
   3474 
   3475 
   3476 /**
   3477  * This function is intended for use with applications that don't want to
   3478  * write a main loop and deal with #DBusWatch and #DBusTimeout. See also
   3479  * dbus_connection_read_write_dispatch().
   3480  *
   3481  * As long as the connection is open, this function will block until it can
   3482  * read or write, then read or write, then return #TRUE.
   3483  *
   3484  * If the connection is closed, the function returns #FALSE.
   3485  *
   3486  * The return value indicates whether reading or writing is still
   3487  * possible, i.e. whether the connection is connected.
   3488  *
   3489  * Note that even after disconnection, messages may remain in the
   3490  * incoming queue that need to be
   3491  * processed. dbus_connection_read_write_dispatch() dispatches
   3492  * incoming messages for you; with dbus_connection_read_write() you
   3493  * have to arrange to drain the incoming queue yourself.
   3494  *
   3495  * @param connection the connection
   3496  * @param timeout_milliseconds max time to block or -1 for infinite
   3497  * @returns #TRUE if still connected
   3498  */
   3499 dbus_bool_t
   3500 dbus_connection_read_write (DBusConnection *connection,
   3501                             int             timeout_milliseconds)
   3502 {
   3503   _dbus_return_val_if_fail (connection != NULL, FALSE);
   3504   _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
   3505    return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, FALSE);
   3506 }
   3507 
   3508 /* We need to call this anytime we pop the head of the queue, and then
   3509  * update_dispatch_status_and_unlock needs to be called afterward
   3510  * which will "process" the disconnected message and set
   3511  * disconnected_message_processed.
   3512  */
   3513 static void
   3514 check_disconnected_message_arrived_unlocked (DBusConnection *connection,
   3515                                              DBusMessage    *head_of_queue)
   3516 {
   3517   HAVE_LOCK_CHECK (connection);
   3518 
   3519   /* checking that the link is NULL is an optimization to avoid the is_signal call */
   3520   if (connection->disconnect_message_link == NULL &&
   3521       dbus_message_is_signal (head_of_queue,
   3522                               DBUS_INTERFACE_LOCAL,
   3523                               "Disconnected"))
   3524     {
   3525       connection->disconnected_message_arrived = TRUE;
   3526     }
   3527 }
   3528 
   3529 /**
   3530  * Returns the first-received message from the incoming message queue,
   3531  * leaving it in the queue. If the queue is empty, returns #NULL.
   3532  *
   3533  * The caller does not own a reference to the returned message, and
   3534  * must either return it using dbus_connection_return_message() or
   3535  * keep it after calling dbus_connection_steal_borrowed_message(). No
   3536  * one can get at the message while its borrowed, so return it as
   3537  * quickly as possible and don't keep a reference to it after
   3538  * returning it. If you need to keep the message, make a copy of it.
   3539  *
   3540  * dbus_connection_dispatch() will block if called while a borrowed
   3541  * message is outstanding; only one piece of code can be playing with
   3542  * the incoming queue at a time. This function will block if called
   3543  * during a dbus_connection_dispatch().
   3544  *
   3545  * @param connection the connection.
   3546  * @returns next message in the incoming queue.
   3547  */
   3548 DBusMessage*
   3549 dbus_connection_borrow_message (DBusConnection *connection)
   3550 {
   3551   DBusDispatchStatus status;
   3552   DBusMessage *message;
   3553 
   3554   _dbus_return_val_if_fail (connection != NULL, NULL);
   3555 
   3556   _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
   3557 
   3558   /* this is called for the side effect that it queues
   3559    * up any messages from the transport
   3560    */
   3561   status = dbus_connection_get_dispatch_status (connection);
   3562   if (status != DBUS_DISPATCH_DATA_REMAINS)
   3563     return NULL;
   3564 
   3565   CONNECTION_LOCK (connection);
   3566 
   3567   _dbus_connection_acquire_dispatch (connection);
   3568 
   3569   /* While a message is outstanding, the dispatch lock is held */
   3570   _dbus_assert (connection->message_borrowed == NULL);
   3571 
   3572   connection->message_borrowed = _dbus_list_get_first (&connection->incoming_messages);
   3573 
   3574   message = connection->message_borrowed;
   3575 
   3576   check_disconnected_message_arrived_unlocked (connection, message);
   3577 
   3578   /* Note that we KEEP the dispatch lock until the message is returned */
   3579   if (message == NULL)
   3580     _dbus_connection_release_dispatch (connection);
   3581 
   3582   CONNECTION_UNLOCK (connection);
   3583 
   3584   /* We don't update dispatch status until it's returned or stolen */
   3585 
   3586   return message;
   3587 }
   3588 
   3589 /**
   3590  * Used to return a message after peeking at it using
   3591  * dbus_connection_borrow_message(). Only called if
   3592  * message from dbus_connection_borrow_message() was non-#NULL.
   3593  *
   3594  * @param connection the connection
   3595  * @param message the message from dbus_connection_borrow_message()
   3596  */
   3597 void
   3598 dbus_connection_return_message (DBusConnection *connection,
   3599 				DBusMessage    *message)
   3600 {
   3601   DBusDispatchStatus status;
   3602 
   3603   _dbus_return_if_fail (connection != NULL);
   3604   _dbus_return_if_fail (message != NULL);
   3605   _dbus_return_if_fail (message == connection->message_borrowed);
   3606   _dbus_return_if_fail (connection->dispatch_acquired);
   3607 
   3608   CONNECTION_LOCK (connection);
   3609 
   3610   _dbus_assert (message == connection->message_borrowed);
   3611 
   3612   connection->message_borrowed = NULL;
   3613 
   3614   _dbus_connection_release_dispatch (connection);
   3615 
   3616   status = _dbus_connection_get_dispatch_status_unlocked (connection);
   3617   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
   3618 }
   3619 
   3620 /**
   3621  * Used to keep a message after peeking at it using
   3622  * dbus_connection_borrow_message(). Before using this function, see
   3623  * the caveats/warnings in the documentation for
   3624  * dbus_connection_pop_message().
   3625  *
   3626  * @param connection the connection
   3627  * @param message the message from dbus_connection_borrow_message()
   3628  */
   3629 void
   3630 dbus_connection_steal_borrowed_message (DBusConnection *connection,
   3631 					DBusMessage    *message)
   3632 {
   3633   DBusMessage *pop_message;
   3634   DBusDispatchStatus status;
   3635 
   3636   _dbus_return_if_fail (connection != NULL);
   3637   _dbus_return_if_fail (message != NULL);
   3638   _dbus_return_if_fail (message == connection->message_borrowed);
   3639   _dbus_return_if_fail (connection->dispatch_acquired);
   3640 
   3641   CONNECTION_LOCK (connection);
   3642 
   3643   _dbus_assert (message == connection->message_borrowed);
   3644 
   3645   pop_message = _dbus_list_pop_first (&connection->incoming_messages);
   3646   _dbus_assert (message == pop_message);
   3647 
   3648   connection->n_incoming -= 1;
   3649 
   3650   _dbus_verbose ("Incoming message %p stolen from queue, %d incoming\n",
   3651 		 message, connection->n_incoming);
   3652 
   3653   connection->message_borrowed = NULL;
   3654 
   3655   _dbus_connection_release_dispatch (connection);
   3656 
   3657   status = _dbus_connection_get_dispatch_status_unlocked (connection);
   3658   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
   3659 }
   3660 
   3661 /* See dbus_connection_pop_message, but requires the caller to own
   3662  * the lock before calling. May drop the lock while running.
   3663  */
   3664 static DBusList*
   3665 _dbus_connection_pop_message_link_unlocked (DBusConnection *connection)
   3666 {
   3667   HAVE_LOCK_CHECK (connection);
   3668 
   3669   _dbus_assert (connection->message_borrowed == NULL);
   3670 
   3671   if (connection->n_incoming > 0)
   3672     {
   3673       DBusList *link;
   3674 
   3675       link = _dbus_list_pop_first_link (&connection->incoming_messages);
   3676       connection->n_incoming -= 1;
   3677 
   3678       _dbus_verbose ("Message %p (%d %s %s %s '%s') removed from incoming queue %p, %d incoming\n",
   3679                      link->data,
   3680                      dbus_message_get_type (link->data),
   3681                      dbus_message_get_path (link->data) ?
   3682                      dbus_message_get_path (link->data) :
   3683                      "no path",
   3684                      dbus_message_get_interface (link->data) ?
   3685                      dbus_message_get_interface (link->data) :
   3686                      "no interface",
   3687                      dbus_message_get_member (link->data) ?
   3688                      dbus_message_get_member (link->data) :
   3689                      "no member",
   3690                      dbus_message_get_signature (link->data),
   3691                      connection, connection->n_incoming);
   3692 
   3693       check_disconnected_message_arrived_unlocked (connection, link->data);
   3694 
   3695       return link;
   3696     }
   3697   else
   3698     return NULL;
   3699 }
   3700 
   3701 /* See dbus_connection_pop_message, but requires the caller to own
   3702  * the lock before calling. May drop the lock while running.
   3703  */
   3704 static DBusMessage*
   3705 _dbus_connection_pop_message_unlocked (DBusConnection *connection)
   3706 {
   3707   DBusList *link;
   3708 
   3709   HAVE_LOCK_CHECK (connection);
   3710 
   3711   link = _dbus_connection_pop_message_link_unlocked (connection);
   3712 
   3713   if (link != NULL)
   3714     {
   3715       DBusMessage *message;
   3716 
   3717       message = link->data;
   3718 
   3719       _dbus_list_free_link (link);
   3720 
   3721       return message;
   3722     }
   3723   else
   3724     return NULL;
   3725 }
   3726 
   3727 static void
   3728 _dbus_connection_putback_message_link_unlocked (DBusConnection *connection,
   3729                                                 DBusList       *message_link)
   3730 {
   3731   HAVE_LOCK_CHECK (connection);
   3732 
   3733   _dbus_assert (message_link != NULL);
   3734   /* You can't borrow a message while a link is outstanding */
   3735   _dbus_assert (connection->message_borrowed == NULL);
   3736   /* We had to have the dispatch lock across the pop/putback */
   3737   _dbus_assert (connection->dispatch_acquired);
   3738 
   3739   _dbus_list_prepend_link (&connection->incoming_messages,
   3740                            message_link);
   3741   connection->n_incoming += 1;
   3742 
   3743   _dbus_verbose ("Message %p (%d %s %s '%s') put back into queue %p, %d incoming\n",
   3744                  message_link->data,
   3745                  dbus_message_get_type (message_link->data),
   3746                  dbus_message_get_interface (message_link->data) ?
   3747                  dbus_message_get_interface (message_link->data) :
   3748                  "no interface",
   3749                  dbus_message_get_member (message_link->data) ?
   3750                  dbus_message_get_member (message_link->data) :
   3751                  "no member",
   3752                  dbus_message_get_signature (message_link->data),
   3753                  connection, connection->n_incoming);
   3754 }
   3755 
   3756 /**
   3757  * Returns the first-received message from the incoming message queue,
   3758  * removing it from the queue. The caller owns a reference to the
   3759  * returned message. If the queue is empty, returns #NULL.
   3760  *
   3761  * This function bypasses any message handlers that are registered,
   3762  * and so using it is usually wrong. Instead, let the main loop invoke
   3763  * dbus_connection_dispatch(). Popping messages manually is only
   3764  * useful in very simple programs that don't share a #DBusConnection
   3765  * with any libraries or other modules.
   3766  *
   3767  * There is a lock that covers all ways of accessing the incoming message
   3768  * queue, so dbus_connection_dispatch(), dbus_connection_pop_message(),
   3769  * dbus_connection_borrow_message(), etc. will all block while one of the others
   3770  * in the group is running.
   3771  *
   3772  * @param connection the connection.
   3773  * @returns next message in the incoming queue.
   3774  */
   3775 DBusMessage*
   3776 dbus_connection_pop_message (DBusConnection *connection)
   3777 {
   3778   DBusMessage *message;
   3779   DBusDispatchStatus status;
   3780 
   3781   _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
   3782 
   3783   /* this is called for the side effect that it queues
   3784    * up any messages from the transport
   3785    */
   3786   status = dbus_connection_get_dispatch_status (connection);
   3787   if (status != DBUS_DISPATCH_DATA_REMAINS)
   3788     return NULL;
   3789 
   3790   CONNECTION_LOCK (connection);
   3791   _dbus_connection_acquire_dispatch (connection);
   3792   HAVE_LOCK_CHECK (connection);
   3793 
   3794   message = _dbus_connection_pop_message_unlocked (connection);
   3795 
   3796   _dbus_verbose ("Returning popped message %p\n", message);
   3797 
   3798   _dbus_connection_release_dispatch (connection);
   3799 
   3800   status = _dbus_connection_get_dispatch_status_unlocked (connection);
   3801   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
   3802 
   3803   return message;
   3804 }
   3805 
   3806 /**
   3807  * Acquire the dispatcher. This is a separate lock so the main
   3808  * connection lock can be dropped to call out to application dispatch
   3809  * handlers.
   3810  *
   3811  * @param connection the connection.
   3812  */
   3813 static void
   3814 _dbus_connection_acquire_dispatch (DBusConnection *connection)
   3815 {
   3816   HAVE_LOCK_CHECK (connection);
   3817 
   3818   _dbus_connection_ref_unlocked (connection);
   3819   CONNECTION_UNLOCK (connection);
   3820 
   3821   _dbus_verbose ("%s locking dispatch_mutex\n", _DBUS_FUNCTION_NAME);
   3822   _dbus_mutex_lock (connection->dispatch_mutex);
   3823 
   3824   while (connection->dispatch_acquired)
   3825     {
   3826       _dbus_verbose ("%s waiting for dispatch to be acquirable\n", _DBUS_FUNCTION_NAME);
   3827       _dbus_condvar_wait (connection->dispatch_cond,
   3828                           connection->dispatch_mutex);
   3829     }
   3830 
   3831   _dbus_assert (!connection->dispatch_acquired);
   3832 
   3833   connection->dispatch_acquired = TRUE;
   3834 
   3835   _dbus_verbose ("%s unlocking dispatch_mutex\n", _DBUS_FUNCTION_NAME);
   3836   _dbus_mutex_unlock (connection->dispatch_mutex);
   3837 
   3838   CONNECTION_LOCK (connection);
   3839   _dbus_connection_unref_unlocked (connection);
   3840 }
   3841 
   3842 /**
   3843  * Release the dispatcher when you're done with it. Only call
   3844  * after you've acquired the dispatcher. Wakes up at most one
   3845  * thread currently waiting to acquire the dispatcher.
   3846  *
   3847  * @param connection the connection.
   3848  */
   3849 static void
   3850 _dbus_connection_release_dispatch (DBusConnection *connection)
   3851 {
   3852   HAVE_LOCK_CHECK (connection);
   3853 
   3854   _dbus_verbose ("%s locking dispatch_mutex\n", _DBUS_FUNCTION_NAME);
   3855   _dbus_mutex_lock (connection->dispatch_mutex);
   3856 
   3857   _dbus_assert (connection->dispatch_acquired);
   3858 
   3859   connection->dispatch_acquired = FALSE;
   3860   _dbus_condvar_wake_one (connection->dispatch_cond);
   3861 
   3862   _dbus_verbose ("%s unlocking dispatch_mutex\n", _DBUS_FUNCTION_NAME);
   3863   _dbus_mutex_unlock (connection->dispatch_mutex);
   3864 }
   3865 
   3866 static void
   3867 _dbus_connection_failed_pop (DBusConnection *connection,
   3868 			     DBusList       *message_link)
   3869 {
   3870   _dbus_list_prepend_link (&connection->incoming_messages,
   3871 			   message_link);
   3872   connection->n_incoming += 1;
   3873 }
   3874 
   3875 /* Note this may be called multiple times since we don't track whether we already did it */
   3876 static void
   3877 notify_disconnected_unlocked (DBusConnection *connection)
   3878 {
   3879   HAVE_LOCK_CHECK (connection);
   3880 
   3881   /* Set the weakref in dbus-bus.c to NULL, so nobody will get a disconnected
   3882    * connection from dbus_bus_get(). We make the same guarantee for
   3883    * dbus_connection_open() but in a different way since we don't want to
   3884    * unref right here; we instead check for connectedness before returning
   3885    * the connection from the hash.
   3886    */
   3887   _dbus_bus_notify_shared_connection_disconnected_unlocked (connection);
   3888 
   3889   /* Dump the outgoing queue, we aren't going to be able to
   3890    * send it now, and we'd like accessors like
   3891    * dbus_connection_get_outgoing_size() to be accurate.
   3892    */
   3893   if (connection->n_outgoing > 0)
   3894     {
   3895       DBusList *link;
   3896 
   3897       _dbus_verbose ("Dropping %d outgoing messages since we're disconnected\n",
   3898                      connection->n_outgoing);
   3899 
   3900       while ((link = _dbus_list_get_last_link (&connection->outgoing_messages)))
   3901         {
   3902           _dbus_connection_message_sent (connection, link->data);
   3903         }
   3904     }
   3905 }
   3906 
   3907 /* Note this may be called multiple times since we don't track whether we already did it */
   3908 static DBusDispatchStatus
   3909 notify_disconnected_and_dispatch_complete_unlocked (DBusConnection *connection)
   3910 {
   3911   HAVE_LOCK_CHECK (connection);
   3912 
   3913   if (connection->disconnect_message_link != NULL)
   3914     {
   3915       _dbus_verbose ("Sending disconnect message from %s\n",
   3916                      _DBUS_FUNCTION_NAME);
   3917 
   3918       /* If we have pending calls, queue their timeouts - we want the Disconnected
   3919        * to be the last message, after these timeouts.
   3920        */
   3921       connection_timeout_and_complete_all_pending_calls_unlocked (connection);
   3922 
   3923       /* We haven't sent the disconnect message already,
   3924        * and all real messages have been queued up.
   3925        */
   3926       _dbus_connection_queue_synthesized_message_link (connection,
   3927                                                        connection->disconnect_message_link);
   3928       connection->disconnect_message_link = NULL;
   3929 
   3930       return DBUS_DISPATCH_DATA_REMAINS;
   3931     }
   3932 
   3933   return DBUS_DISPATCH_COMPLETE;
   3934 }
   3935 
   3936 static DBusDispatchStatus
   3937 _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection)
   3938 {
   3939   HAVE_LOCK_CHECK (connection);
   3940 
   3941   if (connection->n_incoming > 0)
   3942     return DBUS_DISPATCH_DATA_REMAINS;
   3943   else if (!_dbus_transport_queue_messages (connection->transport))
   3944     return DBUS_DISPATCH_NEED_MEMORY;
   3945   else
   3946     {
   3947       DBusDispatchStatus status;
   3948       dbus_bool_t is_connected;
   3949 
   3950       status = _dbus_transport_get_dispatch_status (connection->transport);
   3951       is_connected = _dbus_transport_get_is_connected (connection->transport);
   3952 
   3953       _dbus_verbose ("dispatch status = %s is_connected = %d\n",
   3954                      DISPATCH_STATUS_NAME (status), is_connected);
   3955 
   3956       if (!is_connected)
   3957         {
   3958           /* It's possible this would be better done by having an explicit
   3959            * notification from _dbus_transport_disconnect() that would
   3960            * synchronously do this, instead of waiting for the next dispatch
   3961            * status check. However, probably not good to change until it causes
   3962            * a problem.
   3963            */
   3964           notify_disconnected_unlocked (connection);
   3965 
   3966           /* I'm not sure this is needed; the idea is that we want to
   3967            * queue the Disconnected only after we've read all the
   3968            * messages, but if we're disconnected maybe we are guaranteed
   3969            * to have read them all ?
   3970            */
   3971           if (status == DBUS_DISPATCH_COMPLETE)
   3972             status = notify_disconnected_and_dispatch_complete_unlocked (connection);
   3973         }
   3974 
   3975       if (status != DBUS_DISPATCH_COMPLETE)
   3976         return status;
   3977       else if (connection->n_incoming > 0)
   3978         return DBUS_DISPATCH_DATA_REMAINS;
   3979       else
   3980         return DBUS_DISPATCH_COMPLETE;
   3981     }
   3982 }
   3983 
   3984 static void
   3985 _dbus_connection_update_dispatch_status_and_unlock (DBusConnection    *connection,
   3986                                                     DBusDispatchStatus new_status)
   3987 {
   3988   dbus_bool_t changed;
   3989   DBusDispatchStatusFunction function;
   3990   void *data;
   3991 
   3992   HAVE_LOCK_CHECK (connection);
   3993 
   3994   _dbus_connection_ref_unlocked (connection);
   3995 
   3996   changed = new_status != connection->last_dispatch_status;
   3997 
   3998   connection->last_dispatch_status = new_status;
   3999 
   4000   function = connection->dispatch_status_function;
   4001   data = connection->dispatch_status_data;
   4002 
   4003   if (connection->disconnected_message_arrived &&
   4004       !connection->disconnected_message_processed)
   4005     {
   4006       connection->disconnected_message_processed = TRUE;
   4007 
   4008       /* this does an unref, but we have a ref
   4009        * so we should not run the finalizer here
   4010        * inside the lock.
   4011        */
   4012       connection_forget_shared_unlocked (connection);
   4013 
   4014       if (connection->exit_on_disconnect)
   4015         {
   4016           CONNECTION_UNLOCK (connection);
   4017 
   4018           _dbus_verbose ("Exiting on Disconnected signal\n");
   4019           _dbus_exit (1);
   4020           _dbus_assert_not_reached ("Call to exit() returned");
   4021         }
   4022     }
   4023 
   4024   /* We drop the lock */
   4025   CONNECTION_UNLOCK (connection);
   4026 
   4027   if (changed && function)
   4028     {
   4029       _dbus_verbose ("Notifying of change to dispatch status of %p now %d (%s)\n",
   4030                      connection, new_status,
   4031                      DISPATCH_STATUS_NAME (new_status));
   4032       (* function) (connection, new_status, data);
   4033     }
   4034 
   4035   dbus_connection_unref (connection);
   4036 }
   4037 
   4038 /**
   4039  * Gets the current state of the incoming message queue.
   4040  * #DBUS_DISPATCH_DATA_REMAINS indicates that the message queue
   4041  * may contain messages. #DBUS_DISPATCH_COMPLETE indicates that the
   4042  * incoming queue is empty. #DBUS_DISPATCH_NEED_MEMORY indicates that
   4043  * there could be data, but we can't know for sure without more
   4044  * memory.
   4045  *
   4046  * To process the incoming message queue, use dbus_connection_dispatch()
   4047  * or (in rare cases) dbus_connection_pop_message().
   4048  *
   4049  * Note, #DBUS_DISPATCH_DATA_REMAINS really means that either we
   4050  * have messages in the queue, or we have raw bytes buffered up
   4051  * that need to be parsed. When these bytes are parsed, they
   4052  * may not add up to an entire message. Thus, it's possible
   4053  * to see a status of #DBUS_DISPATCH_DATA_REMAINS but not
   4054  * have a message yet.
   4055  *
   4056  * In particular this happens on initial connection, because all sorts
   4057  * of authentication protocol stuff has to be parsed before the
   4058  * first message arrives.
   4059  *
   4060  * @param connection the connection.
   4061  * @returns current dispatch status
   4062  */
   4063 DBusDispatchStatus
   4064 dbus_connection_get_dispatch_status (DBusConnection *connection)
   4065 {
   4066   DBusDispatchStatus status;
   4067 
   4068   _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
   4069 
   4070   _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
   4071 
   4072   CONNECTION_LOCK (connection);
   4073 
   4074   status = _dbus_connection_get_dispatch_status_unlocked (connection);
   4075 
   4076   CONNECTION_UNLOCK (connection);
   4077 
   4078   return status;
   4079 }
   4080 
   4081 /**
   4082  * Filter funtion for handling the Peer standard interface.
   4083  */
   4084 static DBusHandlerResult
   4085 _dbus_connection_peer_filter_unlocked_no_update (DBusConnection *connection,
   4086                                                  DBusMessage    *message)
   4087 {
   4088   if (connection->route_peer_messages && dbus_message_get_destination (message) != NULL)
   4089     {
   4090       /* This means we're letting the bus route this message */
   4091       return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
   4092     }
   4093   else if (dbus_message_is_method_call (message,
   4094                                         DBUS_INTERFACE_PEER,
   4095                                         "Ping"))
   4096     {
   4097       DBusMessage *ret;
   4098       dbus_bool_t sent;
   4099 
   4100       ret = dbus_message_new_method_return (message);
   4101       if (ret == NULL)
   4102         return DBUS_HANDLER_RESULT_NEED_MEMORY;
   4103 
   4104       sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
   4105 
   4106       dbus_message_unref (ret);
   4107 
   4108       if (!sent)
   4109         return DBUS_HANDLER_RESULT_NEED_MEMORY;
   4110 
   4111       return DBUS_HANDLER_RESULT_HANDLED;
   4112     }
   4113   else if (dbus_message_is_method_call (message,
   4114                                         DBUS_INTERFACE_PEER,
   4115                                         "GetMachineId"))
   4116     {
   4117       DBusMessage *ret;
   4118       dbus_bool_t sent;
   4119       DBusString uuid;
   4120 
   4121       ret = dbus_message_new_method_return (message);
   4122       if (ret == NULL)
   4123         return DBUS_HANDLER_RESULT_NEED_MEMORY;
   4124 
   4125       sent = FALSE;
   4126       _dbus_string_init (&uuid);
   4127       if (_dbus_get_local_machine_uuid_encoded (&uuid))
   4128         {
   4129           const char *v_STRING = _dbus_string_get_const_data (&uuid);
   4130           if (dbus_message_append_args (ret,
   4131                                         DBUS_TYPE_STRING, &v_STRING,
   4132                                         DBUS_TYPE_INVALID))
   4133             {
   4134               sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
   4135             }
   4136         }
   4137       _dbus_string_free (&uuid);
   4138 
   4139       dbus_message_unref (ret);
   4140 
   4141       if (!sent)
   4142         return DBUS_HANDLER_RESULT_NEED_MEMORY;
   4143 
   4144       return DBUS_HANDLER_RESULT_HANDLED;
   4145     }
   4146   else if (dbus_message_has_interface (message, DBUS_INTERFACE_PEER))
   4147     {
   4148       /* We need to bounce anything else with this interface, otherwise apps
   4149        * could start extending the interface and when we added extensions
   4150        * here to DBusConnection we'd break those apps.
   4151        */
   4152 
   4153       DBusMessage *ret;
   4154       dbus_bool_t sent;
   4155 
   4156       ret = dbus_message_new_error (message,
   4157                                     DBUS_ERROR_UNKNOWN_METHOD,
   4158                                     "Unknown method invoked on org.freedesktop.DBus.Peer interface");
   4159       if (ret == NULL)
   4160         return DBUS_HANDLER_RESULT_NEED_MEMORY;
   4161 
   4162       sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
   4163 
   4164       dbus_message_unref (ret);
   4165 
   4166       if (!sent)
   4167         return DBUS_HANDLER_RESULT_NEED_MEMORY;
   4168 
   4169       return DBUS_HANDLER_RESULT_HANDLED;
   4170     }
   4171   else
   4172     {
   4173       return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
   4174     }
   4175 }
   4176 
   4177 /**
   4178 * Processes all builtin filter functions
   4179 *
   4180 * If the spec specifies a standard interface
   4181 * they should be processed from this method
   4182 **/
   4183 static DBusHandlerResult
   4184 _dbus_connection_run_builtin_filters_unlocked_no_update (DBusConnection *connection,
   4185                                                            DBusMessage    *message)
   4186 {
   4187   /* We just run one filter for now but have the option to run more
   4188      if the spec calls for it in the future */
   4189 
   4190   return _dbus_connection_peer_filter_unlocked_no_update (connection, message);
   4191 }
   4192 
   4193 /**
   4194  * Processes any incoming data.
   4195  *
   4196  * If there's incoming raw data that has not yet been parsed, it is
   4197  * parsed, which may or may not result in adding messages to the
   4198  * incoming queue.
   4199  *
   4200  * The incoming data buffer is filled when the connection reads from
   4201  * its underlying transport (such as a socket).  Reading usually
   4202  * happens in dbus_watch_handle() or dbus_connection_read_write().
   4203  *
   4204  * If there are complete messages in the incoming queue,
   4205  * dbus_connection_dispatch() removes one message from the queue and
   4206  * processes it. Processing has three steps.
   4207  *
   4208  * First, any method replies are passed to #DBusPendingCall or
   4209  * dbus_connection_send_with_reply_and_block() in order to
   4210  * complete the pending method call.
   4211  *
   4212  * Second, any filters registered with dbus_connection_add_filter()
   4213  * are run. If any filter returns #DBUS_HANDLER_RESULT_HANDLED
   4214  * then processing stops after that filter.
   4215  *
   4216  * Third, if the message is a method call it is forwarded to
   4217  * any registered object path handlers added with
   4218  * dbus_connection_register_object_path() or
   4219  * dbus_connection_register_fallback().
   4220  *
   4221  * A single call to dbus_connection_dispatch() will process at most
   4222  * one message; it will not clear the entire message queue.
   4223  *
   4224  * Be careful about calling dbus_connection_dispatch() from inside a
   4225  * message handler, i.e. calling dbus_connection_dispatch()
   4226  * recursively.  If threads have been initialized with a recursive
   4227  * mutex function, then this will not deadlock; however, it can
   4228  * certainly confuse your application.
   4229  *
   4230  * @todo some FIXME in here about handling DBUS_HANDLER_RESULT_NEED_MEMORY
   4231  *
   4232  * @param connection the connection
   4233  * @returns dispatch status, see dbus_connection_get_dispatch_status()
   4234  */
   4235 DBusDispatchStatus
   4236 dbus_connection_dispatch (DBusConnection *connection)
   4237 {
   4238   DBusMessage *message;
   4239   DBusList *link, *filter_list_copy, *message_link;
   4240   DBusHandlerResult result;
   4241   DBusPendingCall *pending;
   4242   dbus_int32_t reply_serial;
   4243   DBusDispatchStatus status;
   4244 
   4245   _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
   4246 
   4247   _dbus_verbose ("%s\n", _DBUS_FUNCTION_NAME);
   4248 
   4249   CONNECTION_LOCK (connection);
   4250   status = _dbus_connection_get_dispatch_status_unlocked (connection);
   4251   if (status != DBUS_DISPATCH_DATA_REMAINS)
   4252     {
   4253       /* unlocks and calls out to user code */
   4254       _dbus_connection_update_dispatch_status_and_unlock (connection, status);
   4255       return status;
   4256     }
   4257 
   4258   /* We need to ref the connection since the callback could potentially
   4259    * drop the last ref to it
   4260    */
   4261   _dbus_connection_ref_unlocked (connection);
   4262 
   4263   _dbus_connection_acquire_dispatch (connection);
   4264   HAVE_LOCK_CHECK (connection);
   4265 
   4266   message_link = _dbus_connection_pop_message_link_unlocked (connection);
   4267   if (message_link == NULL)
   4268     {
   4269       /* another thread dispatched our stuff */
   4270 
   4271       _dbus_verbose ("another thread dispatched message (during acquire_dispatch above)\n");
   4272 
   4273       _dbus_connection_release_dispatch (connection);
   4274 
   4275       status = _dbus_connection_get_dispatch_status_unlocked (connection);
   4276 
   4277       _dbus_connection_update_dispatch_status_and_unlock (connection, status);
   4278 
   4279       dbus_connection_unref (connection);
   4280 
   4281       return status;
   4282     }
   4283 
   4284   message = message_link->data;
   4285 
   4286   _dbus_verbose (" dispatching message %p (%d %s %s '%s')\n",
   4287                  message,
   4288                  dbus_message_get_type (message),
   4289                  dbus_message_get_interface (message) ?
   4290                  dbus_message_get_interface (message) :
   4291                  "no interface",
   4292                  dbus_message_get_member (message) ?
   4293                  dbus_message_get_member (message) :
   4294                  "no member",
   4295                  dbus_message_get_signature (message));
   4296 
   4297   result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
   4298 
   4299   /* Pending call handling must be first, because if you do
   4300    * dbus_connection_send_with_reply_and_block() or
   4301    * dbus_pending_call_block() then no handlers/filters will be run on
   4302    * the reply. We want consistent semantics in the case where we
   4303    * dbus_connection_dispatch() the reply.
   4304    */
   4305 
   4306   reply_serial = dbus_message_get_reply_serial (message);
   4307   pending = _dbus_hash_table_lookup_int (connection->pending_replies,
   4308                                          reply_serial);
   4309   if (pending)
   4310     {
   4311       _dbus_verbose ("Dispatching a pending reply\n");
   4312       complete_pending_call_and_unlock (connection, pending, message);
   4313       pending = NULL; /* it's probably unref'd */
   4314 
   4315       CONNECTION_LOCK (connection);
   4316       _dbus_verbose ("pending call completed in dispatch\n");
   4317       result = DBUS_HANDLER_RESULT_HANDLED;
   4318       goto out;
   4319     }
   4320 
   4321   result = _dbus_connection_run_builtin_filters_unlocked_no_update (connection, message);
   4322   if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
   4323     goto out;
   4324 
   4325   if (!_dbus_list_copy (&connection->filter_list, &filter_list_copy))
   4326     {
   4327       _dbus_connection_release_dispatch (connection);
   4328       HAVE_LOCK_CHECK (connection);
   4329 
   4330       _dbus_connection_failed_pop (connection, message_link);
   4331 
   4332       /* unlocks and calls user code */
   4333       _dbus_connection_update_dispatch_status_and_unlock (connection,
   4334                                                           DBUS_DISPATCH_NEED_MEMORY);
   4335 
   4336       if (pending)
   4337         dbus_pending_call_unref (pending);
   4338       dbus_connection_unref (connection);
   4339 
   4340       return DBUS_DISPATCH_NEED_MEMORY;
   4341     }
   4342 
   4343   _dbus_list_foreach (&filter_list_copy,
   4344 		      (DBusForeachFunction)_dbus_message_filter_ref,
   4345 		      NULL);
   4346 
   4347   /* We're still protected from dispatch() reentrancy here
   4348    * since we acquired the dispatcher
   4349    */
   4350   CONNECTION_UNLOCK (connection);
   4351 
   4352   link = _dbus_list_get_first_link (&filter_list_copy);
   4353   while (link != NULL)
   4354     {
   4355       DBusMessageFilter *filter = link->data;
   4356       DBusList *next = _dbus_list_get_next_link (&filter_list_copy, link);
   4357 
   4358       if (filter->function == NULL)
   4359         {
   4360           _dbus_verbose ("  filter was removed in a callback function\n");
   4361           link = next;
   4362           continue;
   4363         }
   4364 
   4365       _dbus_verbose ("  running filter on message %p\n", message);
   4366       result = (* filter->function) (connection, message, filter->user_data);
   4367 
   4368       if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
   4369 	break;
   4370 
   4371       link = next;
   4372     }
   4373 
   4374   _dbus_list_foreach (&filter_list_copy,
   4375 		      (DBusForeachFunction)_dbus_message_filter_unref,
   4376 		      NULL);
   4377   _dbus_list_clear (&filter_list_copy);
   4378 
   4379   CONNECTION_LOCK (connection);
   4380 
   4381   if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
   4382     {
   4383       _dbus_verbose ("No memory in %s\n", _DBUS_FUNCTION_NAME);
   4384       goto out;
   4385     }
   4386   else if (result == DBUS_HANDLER_RESULT_HANDLED)
   4387     {
   4388       _dbus_verbose ("filter handled message in dispatch\n");
   4389       goto out;
   4390     }
   4391 
   4392   /* We're still protected from dispatch() reentrancy here
   4393    * since we acquired the dispatcher
   4394    */
   4395   _dbus_verbose ("  running object path dispatch on message %p (%d %s %s '%s')\n",
   4396                  message,
   4397                  dbus_message_get_type (message),
   4398                  dbus_message_get_interface (message) ?
   4399                  dbus_message_get_interface (message) :
   4400                  "no interface",
   4401                  dbus_message_get_member (message) ?
   4402                  dbus_message_get_member (message) :
   4403                  "no member",
   4404                  dbus_message_get_signature (message));
   4405 
   4406   HAVE_LOCK_CHECK (connection);
   4407   result = _dbus_object_tree_dispatch_and_unlock (connection->objects,
   4408                                                   message);
   4409 
   4410   CONNECTION_LOCK (connection);
   4411 
   4412   if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
   4413     {
   4414       _dbus_verbose ("object tree handled message in dispatch\n");
   4415       goto out;
   4416     }
   4417 
   4418   if (dbus_message_get_type (message) == DBUS_MESSAGE_TYPE_METHOD_CALL)
   4419     {
   4420       DBusMessage *reply;
   4421       DBusString str;
   4422       DBusPreallocatedSend *preallocated;
   4423 
   4424       _dbus_verbose ("  sending error %s\n",
   4425                      DBUS_ERROR_UNKNOWN_METHOD);
   4426 
   4427       if (!_dbus_string_init (&str))
   4428         {
   4429           result = DBUS_HANDLER_RESULT_NEED_MEMORY;
   4430           _dbus_verbose ("no memory for error string in dispatch\n");
   4431           goto out;
   4432         }
   4433 
   4434       if (!_dbus_string_append_printf (&str,
   4435                                        "Method \"%s\" with signature \"%s\" on interface \"%s\" doesn't exist\n",
   4436                                        dbus_message_get_member (message),
   4437                                        dbus_message_get_signature (message),
   4438                                        dbus_message_get_interface (message)))
   4439         {
   4440           _dbus_string_free (&str);
   4441           result = DBUS_HANDLER_RESULT_NEED_MEMORY;
   4442           _dbus_verbose ("no memory for error string in dispatch\n");
   4443           goto out;
   4444         }
   4445 
   4446       reply = dbus_message_new_error (message,
   4447                                       DBUS_ERROR_UNKNOWN_METHOD,
   4448                                       _dbus_string_get_const_data (&str));
   4449       _dbus_string_free (&str);
   4450 
   4451       if (reply == NULL)
   4452         {
   4453           result = DBUS_HANDLER_RESULT_NEED_MEMORY;
   4454           _dbus_verbose ("no memory for error reply in dispatch\n");
   4455           goto out;
   4456         }
   4457 
   4458       preallocated = _dbus_connection_preallocate_send_unlocked (connection);
   4459 
   4460       if (preallocated == NULL)
   4461         {
   4462           dbus_message_unref (reply);
   4463           result = DBUS_HANDLER_RESULT_NEED_MEMORY;
   4464           _dbus_verbose ("no memory for error send in dispatch\n");
   4465           goto out;
   4466         }
   4467 
   4468       _dbus_connection_send_preallocated_unlocked_no_update (connection, preallocated,
   4469                                                              reply, NULL);
   4470 
   4471       dbus_message_unref (reply);
   4472 
   4473       result = DBUS_HANDLER_RESULT_HANDLED;
   4474     }
   4475 
   4476   _dbus_verbose ("  done dispatching %p (%d %s %s '%s') on connection %p\n", message,
   4477                  dbus_message_get_type (message),
   4478                  dbus_message_get_interface (message) ?
   4479                  dbus_message_get_interface (message) :
   4480                  "no interface",
   4481                  dbus_message_get_member (message) ?
   4482                  dbus_message_get_member (message) :
   4483                  "no member",
   4484                  dbus_message_get_signature (message),
   4485                  connection);
   4486 
   4487  out:
   4488   if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
   4489     {
   4490       _dbus_verbose ("out of memory in %s\n", _DBUS_FUNCTION_NAME);
   4491 
   4492       /* Put message back, and we'll start over.
   4493        * Yes this means handlers must be idempotent if they
   4494        * don't return HANDLED; c'est la vie.
   4495        */
   4496       _dbus_connection_putback_message_link_unlocked (connection,
   4497                                                       message_link);
   4498     }
   4499   else
   4500     {
   4501       _dbus_verbose (" ... done dispatching in %s\n", _DBUS_FUNCTION_NAME);
   4502 
   4503       _dbus_list_free_link (message_link);
   4504       dbus_message_unref (message); /* don't want the message to count in max message limits
   4505                                      * in computing dispatch status below
   4506                                      */
   4507     }
   4508 
   4509   _dbus_connection_release_dispatch (connection);
   4510   HAVE_LOCK_CHECK (connection);
   4511 
   4512   _dbus_verbose ("%s before final status update\n", _DBUS_FUNCTION_NAME);
   4513   status = _dbus_connection_get_dispatch_status_unlocked (connection);
   4514 
   4515   /* unlocks and calls user code */
   4516   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
   4517 
   4518   dbus_connection_unref (connection);
   4519 
   4520   return status;
   4521 }
   4522 
   4523 /**
   4524  * Sets the watch functions for the connection. These functions are
   4525  * responsible for making the application's main loop aware of file
   4526  * descriptors that need to be monitored for events, using select() or
   4527  * poll(). When using Qt, typically the DBusAddWatchFunction would
   4528  * create a QSocketNotifier. When using GLib, the DBusAddWatchFunction
   4529  * could call g_io_add_watch(), or could be used as part of a more
   4530  * elaborate GSource. Note that when a watch is added, it may
   4531  * not be enabled.
   4532  *
   4533  * The DBusWatchToggledFunction notifies the application that the
   4534  * watch has been enabled or disabled. Call dbus_watch_get_enabled()
   4535  * to check this. A disabled watch should have no effect, and enabled
   4536  * watch should be added to the main loop. This feature is used
   4537  * instead of simply adding/removing the watch because
   4538  * enabling/disabling can be done without memory allocation.  The
   4539  * toggled function may be NULL if a main loop re-queries
   4540  * dbus_watch_get_enabled() every time anyway.
   4541  *
   4542  * The DBusWatch can be queried for the file descriptor to watch using
   4543  * dbus_watch_get_fd(), and for the events to watch for using
   4544  * dbus_watch_get_flags(). The flags returned by
   4545  * dbus_watch_get_flags() will only contain DBUS_WATCH_READABLE and
   4546  * DBUS_WATCH_WRITABLE, never DBUS_WATCH_HANGUP or DBUS_WATCH_ERROR;
   4547  * all watches implicitly include a watch for hangups, errors, and
   4548  * other exceptional conditions.
   4549  *
   4550  * Once a file descriptor becomes readable or writable, or an exception
   4551  * occurs, dbus_watch_handle() should be called to
   4552  * notify the connection of the file descriptor's condition.
   4553  *
   4554  * dbus_watch_handle() cannot be called during the
   4555  * DBusAddWatchFunction, as the connection will not be ready to handle
   4556  * that watch yet.
   4557  *
   4558  * It is not allowed to reference a DBusWatch after it has been passed
   4559  * to remove_function.
   4560  *
   4561  * If #FALSE is returned due to lack of memory, the failure may be due
   4562  * to a #FALSE return from the new add_function. If so, the
   4563  * add_function may have been called successfully one or more times,
   4564  * but the remove_function will also have been called to remove any
   4565  * successful adds. i.e. if #FALSE is returned the net result
   4566  * should be that dbus_connection_set_watch_functions() has no effect,
   4567  * but the add_function and remove_function may have been called.
   4568  *
   4569  * @todo We need to drop the lock when we call the
   4570  * add/remove/toggled functions which can be a side effect
   4571  * of setting the watch functions.
   4572  *
   4573  * @param connection the connection.
   4574  * @param add_function function to begin monitoring a new descriptor.
   4575  * @param remove_function function to stop monitoring a descriptor.
   4576  * @param toggled_function function to notify of enable/disable
   4577  * @param data data to pass to add_function and remove_function.
   4578  * @param free_data_function function to be called to free the data.
   4579  * @returns #FALSE on failure (no memory)
   4580  */
   4581 dbus_bool_t
   4582 dbus_connection_set_watch_functions (DBusConnection              *connection,
   4583                                      DBusAddWatchFunction         add_function,
   4584                                      DBusRemoveWatchFunction      remove_function,
   4585                                      DBusWatchToggledFunction     toggled_function,
   4586                                      void                        *data,
   4587                                      DBusFreeFunction             free_data_function)
   4588 {
   4589   dbus_bool_t retval;
   4590   DBusWatchList *watches;
   4591 
   4592   _dbus_return_val_if_fail (connection != NULL, FALSE);
   4593 
   4594   CONNECTION_LOCK (connection);
   4595 
   4596 #ifndef DBUS_DISABLE_CHECKS
   4597   if (connection->watches == NULL)
   4598     {
   4599       _dbus_warn_check_failed ("Re-entrant call to %s is not allowed\n",
   4600                                _DBUS_FUNCTION_NAME);
   4601       return FALSE;
   4602     }
   4603 #endif
   4604 
   4605   /* ref connection for slightly better reentrancy */
   4606   _dbus_connection_ref_unlocked (connection);
   4607 
   4608   /* This can call back into user code, and we need to drop the
   4609    * connection lock when it does. This is kind of a lame
   4610    * way to do it.
   4611    */
   4612   watches = connection->watches;
   4613   connection->watches = NULL;
   4614   CONNECTION_UNLOCK (connection);
   4615 
   4616   retval = _dbus_watch_list_set_functions (watches,
   4617                                            add_function, remove_function,
   4618                                            toggled_function,
   4619                                            data, free_data_function);
   4620   CONNECTION_LOCK (connection);
   4621   connection->watches = watches;
   4622 
   4623   CONNECTION_UNLOCK (connection);
   4624   /* drop our paranoid refcount */
   4625   dbus_connection_unref (connection);
   4626 
   4627   return retval;
   4628 }
   4629 
   4630 /**
   4631  * Sets the timeout functions for the connection. These functions are
   4632  * responsible for making the application's main loop aware of timeouts.
   4633  * When using Qt, typically the DBusAddTimeoutFunction would create a
   4634  * QTimer. When using GLib, the DBusAddTimeoutFunction would call
   4635  * g_timeout_add.
   4636  *
   4637  * The DBusTimeoutToggledFunction notifies the application that the
   4638  * timeout has been enabled or disabled. Call
   4639  * dbus_timeout_get_enabled() to check this. A disabled timeout should
   4640  * have no effect, and enabled timeout should be added to the main
   4641  * loop. This feature is used instead of simply adding/removing the
   4642  * timeout because enabling/disabling can be done without memory
   4643  * allocation. With Qt, QTimer::start() and QTimer::stop() can be used
   4644  * to enable and disable. The toggled function may be NULL if a main
   4645  * loop re-queries dbus_timeout_get_enabled() every time anyway.
   4646  * Whenever a timeout is toggled, its interval may change.
   4647  *
   4648  * The DBusTimeout can be queried for the timer interval using
   4649  * dbus_timeout_get_interval(). dbus_timeout_handle() should be called
   4650  * repeatedly, each time the interval elapses, starting after it has
   4651  * elapsed once. The timeout stops firing when it is removed with the
   4652  * given remove_function.  The timer interval may change whenever the
   4653  * timeout is added, removed, or toggled.
   4654  *
   4655  * @param connection the connection.
   4656  * @param add_function function to add a timeout.
   4657  * @param remove_function function to remove a timeout.
   4658  * @param toggled_function function to notify of enable/disable
   4659  * @param data data to pass to add_function and remove_function.
   4660  * @param free_data_function function to be called to free the data.
   4661  * @returns #FALSE on failure (no memory)
   4662  */
   4663 dbus_bool_t
   4664 dbus_connection_set_timeout_functions   (DBusConnection            *connection,
   4665 					 DBusAddTimeoutFunction     add_function,
   4666 					 DBusRemoveTimeoutFunction  remove_function,
   4667                                          DBusTimeoutToggledFunction toggled_function,
   4668 					 void                      *data,
   4669 					 DBusFreeFunction           free_data_function)
   4670 {
   4671   dbus_bool_t retval;
   4672   DBusTimeoutList *timeouts;
   4673 
   4674   _dbus_return_val_if_fail (connection != NULL, FALSE);
   4675 
   4676   CONNECTION_LOCK (connection);
   4677 
   4678 #ifndef DBUS_DISABLE_CHECKS
   4679   if (connection->timeouts == NULL)
   4680     {
   4681       _dbus_warn_check_failed ("Re-entrant call to %s is not allowed\n",
   4682                                _DBUS_FUNCTION_NAME);
   4683       return FALSE;
   4684     }
   4685 #endif
   4686 
   4687   /* ref connection for slightly better reentrancy */
   4688   _dbus_connection_ref_unlocked (connection);
   4689 
   4690   timeouts = connection->timeouts;
   4691   connection->timeouts = NULL;
   4692   CONNECTION_UNLOCK (connection);
   4693 
   4694   retval = _dbus_timeout_list_set_functions (timeouts,
   4695                                              add_function, remove_function,
   4696                                              toggled_function,
   4697                                              data, free_data_function);
   4698   CONNECTION_LOCK (connection);
   4699   connection->timeouts = timeouts;
   4700 
   4701   CONNECTION_UNLOCK (connection);
   4702   /* drop our paranoid refcount */
   4703   dbus_connection_unref (connection);
   4704 
   4705   return retval;
   4706 }
   4707 
   4708 /**
   4709  * Sets the mainloop wakeup function for the connection. This function
   4710  * is responsible for waking up the main loop (if its sleeping in
   4711  * another thread) when some some change has happened to the
   4712  * connection that the mainloop needs to reconsider (e.g. a message
   4713  * has been queued for writing).  When using Qt, this typically
   4714  * results in a call to QEventLoop::wakeUp().  When using GLib, it
   4715  * would call g_main_context_wakeup().
   4716  *
   4717  * @param connection the connection.
   4718  * @param wakeup_main_function function to wake up the mainloop
   4719  * @param data data to pass wakeup_main_function
   4720  * @param free_data_function function to be called to free the data.
   4721  */
   4722 void
   4723 dbus_connection_set_wakeup_main_function (DBusConnection            *connection,
   4724 					  DBusWakeupMainFunction     wakeup_main_function,
   4725 					  void                      *data,
   4726 					  DBusFreeFunction           free_data_function)
   4727 {
   4728   void *old_data;
   4729   DBusFreeFunction old_free_data;
   4730 
   4731   _dbus_return_if_fail (connection != NULL);
   4732 
   4733   CONNECTION_LOCK (connection);
   4734   old_data = connection->wakeup_main_data;
   4735   old_free_data = connection->free_wakeup_main_data;
   4736 
   4737   connection->wakeup_main_function = wakeup_main_function;
   4738   connection->wakeup_main_data = data;
   4739   connection->free_wakeup_main_data = free_data_function;
   4740 
   4741   CONNECTION_UNLOCK (connection);
   4742 
   4743   /* Callback outside the lock */
   4744   if (old_free_data)
   4745     (*old_free_data) (old_data);
   4746 }
   4747 
   4748 /**
   4749  * Set a function to be invoked when the dispatch status changes.
   4750  * If the dispatch status is #DBUS_DISPATCH_DATA_REMAINS, then
   4751  * dbus_connection_dispatch() needs to be called to process incoming
   4752  * messages. However, dbus_connection_dispatch() MUST NOT BE CALLED
   4753  * from inside the DBusDispatchStatusFunction. Indeed, almost
   4754  * any reentrancy in this function is a bad idea. Instead,
   4755  * the DBusDispatchStatusFunction should simply save an indication
   4756  * that messages should be dispatched later, when the main loop
   4757  * is re-entered.
   4758  *
   4759  * If you don't set a dispatch status function, you have to be sure to
   4760  * dispatch on every iteration of your main loop, especially if
   4761  * dbus_watch_handle() or dbus_timeout_handle() were called.
   4762  *
   4763  * @param connection the connection
   4764  * @param function function to call on dispatch status changes
   4765  * @param data data for function
   4766  * @param free_data_function free the function data
   4767  */
   4768 void
   4769 dbus_connection_set_dispatch_status_function (DBusConnection             *connection,
   4770                                               DBusDispatchStatusFunction  function,
   4771                                               void                       *data,
   4772                                               DBusFreeFunction            free_data_function)
   4773 {
   4774   void *old_data;
   4775   DBusFreeFunction old_free_data;
   4776 
   4777   _dbus_return_if_fail (connection != NULL);
   4778 
   4779   CONNECTION_LOCK (connection);
   4780   old_data = connection->dispatch_status_data;
   4781   old_free_data = connection->free_dispatch_status_data;
   4782 
   4783   connection->dispatch_status_function = function;
   4784   connection->dispatch_status_data = data;
   4785   connection->free_dispatch_status_data = free_data_function;
   4786 
   4787   CONNECTION_UNLOCK (connection);
   4788 
   4789   /* Callback outside the lock */
   4790   if (old_free_data)
   4791     (*old_free_data) (old_data);
   4792 }
   4793 
   4794 /**
   4795  * Get the UNIX file descriptor of the connection, if any.  This can
   4796  * be used for SELinux access control checks with getpeercon() for
   4797  * example. DO NOT read or write to the file descriptor, or try to
   4798  * select() on it; use DBusWatch for main loop integration. Not all
   4799  * connections will have a file descriptor. So for adding descriptors
   4800  * to the main loop, use dbus_watch_get_fd() and so forth.
   4801  *
   4802  * If the connection is socket-based, you can also use
   4803  * dbus_connection_get_socket(), which will work on Windows too.
   4804  * This function always fails on Windows.
   4805  *
   4806  * Right now the returned descriptor is always a socket, but
   4807  * that is not guaranteed.
   4808  *
   4809  * @param connection the connection
   4810  * @param fd return location for the file descriptor.
   4811  * @returns #TRUE if fd is successfully obtained.
   4812  */
   4813 dbus_bool_t
   4814 dbus_connection_get_unix_fd (DBusConnection *connection,
   4815                              int            *fd)
   4816 {
   4817   _dbus_return_val_if_fail (connection != NULL, FALSE);
   4818   _dbus_return_val_if_fail (connection->transport != NULL, FALSE);
   4819 
   4820 #ifdef DBUS_WIN
   4821   /* FIXME do this on a lower level */
   4822   return FALSE;
   4823 #endif
   4824 
   4825   return dbus_connection_get_socket(connection, fd);
   4826 }
   4827 
   4828 /**
   4829  * Gets the underlying Windows or UNIX socket file descriptor
   4830  * of the connection, if any. DO NOT read or write to the file descriptor, or try to
   4831  * select() on it; use DBusWatch for main loop integration. Not all
   4832  * connections will have a socket. So for adding descriptors
   4833  * to the main loop, use dbus_watch_get_fd() and so forth.
   4834  *
   4835  * If the connection is not socket-based, this function will return FALSE,
   4836  * even if the connection does have a file descriptor of some kind.
   4837  * i.e. this function always returns specifically a socket file descriptor.
   4838  *
   4839  * @param connection the connection
   4840  * @param fd return location for the file descriptor.
   4841  * @returns #TRUE if fd is successfully obtained.
   4842  */
   4843 dbus_bool_t
   4844 dbus_connection_get_socket(DBusConnection              *connection,
   4845                            int                         *fd)
   4846 {
   4847   dbus_bool_t retval;
   4848 
   4849   _dbus_return_val_if_fail (connection != NULL, FALSE);
   4850   _dbus_return_val_if_fail (connection->transport != NULL, FALSE);
   4851 
   4852   CONNECTION_LOCK (connection);
   4853 
   4854   retval = _dbus_transport_get_socket_fd (connection->transport,
   4855                                           fd);
   4856 
   4857   CONNECTION_UNLOCK (connection);
   4858 
   4859   return retval;
   4860 }
   4861 
   4862 
   4863 /**
   4864  * Gets the UNIX user ID of the connection if known.  Returns #TRUE if
   4865  * the uid is filled in.  Always returns #FALSE on non-UNIX platforms.
   4866  * Always returns #FALSE prior to authenticating the connection.
   4867  *
   4868  * The UID is only read by servers from clients; clients can't usually
   4869  * get the UID of servers, because servers do not authenticate to
   4870  * clients.  The returned UID is the UID the connection authenticated
   4871  * as.
   4872  *
   4873  * The message bus is a server and the apps connecting to the bus
   4874  * are clients.
   4875  *
   4876  * You can ask the bus to tell you the UID of another connection though
   4877  * if you like; this is done with dbus_bus_get_unix_user().
   4878  *
   4879  * @param connection the connection
   4880  * @param uid return location for the user ID
   4881  * @returns #TRUE if uid is filled in with a valid user ID
   4882  */
   4883 dbus_bool_t
   4884 dbus_connection_get_unix_user (DBusConnection *connection,
   4885                                unsigned long  *uid)
   4886 {
   4887   dbus_bool_t result;
   4888 
   4889   _dbus_return_val_if_fail (connection != NULL, FALSE);
   4890   _dbus_return_val_if_fail (uid != NULL, FALSE);
   4891 
   4892 #ifdef DBUS_WIN
   4893   /* FIXME this should be done at a lower level, but it's kind of hard,
   4894    * just want to be sure we don't ship with this API returning
   4895    * some weird internal fake uid for 1.0
   4896    */
   4897   return FALSE;
   4898 #endif
   4899 
   4900   CONNECTION_LOCK (connection);
   4901 
   4902   if (!_dbus_transport_get_is_authenticated (connection->transport))
   4903     result = FALSE;
   4904   else
   4905     result = _dbus_transport_get_unix_user (connection->transport,
   4906                                             uid);
   4907   CONNECTION_UNLOCK (connection);
   4908 
   4909   return result;
   4910 }
   4911 
   4912 /**
   4913  * Gets the process ID of the connection if any.
   4914  * Returns #TRUE if the uid is filled in.
   4915  * Always returns #FALSE prior to authenticating the
   4916  * connection.
   4917  *
   4918  * @param connection the connection
   4919  * @param pid return location for the process ID
   4920  * @returns #TRUE if uid is filled in with a valid process ID
   4921  */
   4922 dbus_bool_t
   4923 dbus_connection_get_unix_process_id (DBusConnection *connection,
   4924 				     unsigned long  *pid)
   4925 {
   4926   dbus_bool_t result;
   4927 
   4928   _dbus_return_val_if_fail (connection != NULL, FALSE);
   4929   _dbus_return_val_if_fail (pid != NULL, FALSE);
   4930 
   4931 #ifdef DBUS_WIN
   4932   /* FIXME this should be done at a lower level, but it's kind of hard,
   4933    * just want to be sure we don't ship with this API returning
   4934    * some weird internal fake uid for 1.0
   4935    */
   4936   return FALSE;
   4937 #endif
   4938 
   4939   CONNECTION_LOCK (connection);
   4940 
   4941   if (!_dbus_transport_get_is_authenticated (connection->transport))
   4942     result = FALSE;
   4943   else
   4944     result = _dbus_transport_get_unix_process_id (connection->transport,
   4945 						  pid);
   4946   CONNECTION_UNLOCK (connection);
   4947 
   4948   return result;
   4949 }
   4950 
   4951 /**
   4952  * Sets a predicate function used to determine whether a given user ID
   4953  * is allowed to connect. When an incoming connection has
   4954  * authenticated with a particular user ID, this function is called;
   4955  * if it returns #TRUE, the connection is allowed to proceed,
   4956  * otherwise the connection is disconnected.
   4957  *
   4958  * If the function is set to #NULL (as it is by default), then
   4959  * only the same UID as the server process will be allowed to
   4960  * connect.
   4961  *
   4962  * On Windows, the function will be set and its free_data_function will
   4963  * be invoked when the connection is freed or a new function is set.
   4964  * However, the function will never be called, because there are
   4965  * no UNIX user ids to pass to it.
   4966  *
   4967  * @todo add a Windows API analogous to dbus_connection_set_unix_user_function()
   4968  *
   4969  * @param connection the connection
   4970  * @param function the predicate
   4971  * @param data data to pass to the predicate
   4972  * @param free_data_function function to free the data
   4973  */
   4974 void
   4975 dbus_connection_set_unix_user_function (DBusConnection             *connection,
   4976                                         DBusAllowUnixUserFunction   function,
   4977                                         void                       *data,
   4978                                         DBusFreeFunction            free_data_function)
   4979 {
   4980   void *old_data = NULL;
   4981   DBusFreeFunction old_free_function = NULL;
   4982 
   4983   _dbus_return_if_fail (connection != NULL);
   4984 
   4985   CONNECTION_LOCK (connection);
   4986   _dbus_transport_set_unix_user_function (connection->transport,
   4987                                           function, data, free_data_function,
   4988                                           &old_data, &old_free_function);
   4989   CONNECTION_UNLOCK (connection);
   4990 
   4991   if (old_free_function != NULL)
   4992     (* old_free_function) (old_data);
   4993 }
   4994 
   4995 /**
   4996  *
   4997  * Normally #DBusConnection automatically handles all messages to the
   4998  * org.freedesktop.DBus.Peer interface. However, the message bus wants
   4999  * to be able to route methods on that interface through the bus and
   5000  * to other applications. If routing peer messages is enabled, then
   5001  * messages with the org.freedesktop.DBus.Peer interface that also
   5002  * have a bus destination name set will not be automatically
   5003  * handled by the #DBusConnection and instead will be dispatched
   5004  * normally to the application.
   5005  *
   5006  *
   5007  * If a normal application sets this flag, it can break things badly.
   5008  * So don't set this unless you are the message bus.
   5009  *
   5010  * @param connection the connection
   5011  * @param value #TRUE to pass through org.freedesktop.DBus.Peer messages with a bus name set
   5012  */
   5013 void
   5014 dbus_connection_set_route_peer_messages (DBusConnection             *connection,
   5015                                          dbus_bool_t                 value)
   5016 {
   5017   _dbus_return_if_fail (connection != NULL);
   5018 
   5019   CONNECTION_LOCK (connection);
   5020   connection->route_peer_messages = TRUE;
   5021   CONNECTION_UNLOCK (connection);
   5022 }
   5023 
   5024 /**
   5025  * Adds a message filter. Filters are handlers that are run on all
   5026  * incoming messages, prior to the objects registered with
   5027  * dbus_connection_register_object_path().  Filters are run in the
   5028  * order that they were added.  The same handler can be added as a
   5029  * filter more than once, in which case it will be run more than once.
   5030  * Filters added during a filter callback won't be run on the message
   5031  * being processed.
   5032  *
   5033  * @todo we don't run filters on messages while blocking without
   5034  * entering the main loop, since filters are run as part of
   5035  * dbus_connection_dispatch(). This is probably a feature, as filters
   5036  * could create arbitrary reentrancy. But kind of sucks if you're
   5037  * trying to filter METHOD_RETURN for some reason.
   5038  *
   5039  * @param connection the connection
   5040  * @param function function to handle messages
   5041  * @param user_data user data to pass to the function
   5042  * @param free_data_function function to use for freeing user data
   5043  * @returns #TRUE on success, #FALSE if not enough memory.
   5044  */
   5045 dbus_bool_t
   5046 dbus_connection_add_filter (DBusConnection            *connection,
   5047                             DBusHandleMessageFunction  function,
   5048                             void                      *user_data,
   5049                             DBusFreeFunction           free_data_function)
   5050 {
   5051   DBusMessageFilter *filter;
   5052 
   5053   _dbus_return_val_if_fail (connection != NULL, FALSE);
   5054   _dbus_return_val_if_fail (function != NULL, FALSE);
   5055 
   5056   filter = dbus_new0 (DBusMessageFilter, 1);
   5057   if (filter == NULL)
   5058     return FALSE;
   5059 
   5060   filter->refcount.value = 1;
   5061 
   5062   CONNECTION_LOCK (connection);
   5063 
   5064   if (!_dbus_list_append (&connection->filter_list,
   5065                           filter))
   5066     {
   5067       _dbus_message_filter_unref (filter);
   5068       CONNECTION_UNLOCK (connection);
   5069       return FALSE;
   5070     }
   5071 
   5072   /* Fill in filter after all memory allocated,
   5073    * so we don't run the free_user_data_function
   5074    * if the add_filter() fails
   5075    */
   5076 
   5077   filter->function = function;
   5078   filter->user_data = user_data;
   5079   filter->free_user_data_function = free_data_function;
   5080 
   5081   CONNECTION_UNLOCK (connection);
   5082   return TRUE;
   5083 }
   5084 
   5085 /**
   5086  * Removes a previously-added message filter. It is a programming
   5087  * error to call this function for a handler that has not been added
   5088  * as a filter. If the given handler was added more than once, only
   5089  * one instance of it will be removed (the most recently-added
   5090  * instance).
   5091  *
   5092  * @param connection the connection
   5093  * @param function the handler to remove
   5094  * @param user_data user data for the handler to remove
   5095  *
   5096  */
   5097 void
   5098 dbus_connection_remove_filter (DBusConnection            *connection,
   5099                                DBusHandleMessageFunction  function,
   5100                                void                      *user_data)
   5101 {
   5102   DBusList *link;
   5103   DBusMessageFilter *filter;
   5104 
   5105   _dbus_return_if_fail (connection != NULL);
   5106   _dbus_return_if_fail (function != NULL);
   5107 
   5108   CONNECTION_LOCK (connection);
   5109 
   5110   filter = NULL;
   5111 
   5112   link = _dbus_list_get_last_link (&connection->filter_list);
   5113   while (link != NULL)
   5114     {
   5115       filter = link->data;
   5116 
   5117       if (filter->function == function &&
   5118           filter->user_data == user_data)
   5119         {
   5120           _dbus_list_remove_link (&connection->filter_list, link);
   5121           filter->function = NULL;
   5122 
   5123           break;
   5124         }
   5125 
   5126       link = _dbus_list_get_prev_link (&connection->filter_list, link);
   5127     }
   5128 
   5129   CONNECTION_UNLOCK (connection);
   5130 
   5131 #ifndef DBUS_DISABLE_CHECKS
   5132   if (filter == NULL)
   5133     {
   5134       _dbus_warn_check_failed ("Attempt to remove filter function %p user data %p, but no such filter has been added\n",
   5135                                function, user_data);
   5136       return;
   5137     }
   5138 #endif
   5139 
   5140   /* Call application code */
   5141   if (filter->free_user_data_function)
   5142     (* filter->free_user_data_function) (filter->user_data);
   5143 
   5144   filter->free_user_data_function = NULL;
   5145   filter->user_data = NULL;
   5146 
   5147   _dbus_message_filter_unref (filter);
   5148 }
   5149 
   5150 /**
   5151  * Registers a handler for a given path in the object hierarchy.
   5152  * The given vtable handles messages sent to exactly the given path.
   5153  *
   5154  *
   5155  * @param connection the connection
   5156  * @param path a '/' delimited string of path elements
   5157  * @param vtable the virtual table
   5158  * @param user_data data to pass to functions in the vtable
   5159  * @returns #FALSE if not enough memory
   5160  */
   5161 dbus_bool_t
   5162 dbus_connection_register_object_path (DBusConnection              *connection,
   5163                                       const char                  *path,
   5164                                       const DBusObjectPathVTable  *vtable,
   5165                                       void                        *user_data)
   5166 {
   5167   char **decomposed_path;
   5168   dbus_bool_t retval;
   5169 
   5170   _dbus_return_val_if_fail (connection != NULL, FALSE);
   5171   _dbus_return_val_if_fail (path != NULL, FALSE);
   5172   _dbus_return_val_if_fail (path[0] == '/', FALSE);
   5173   _dbus_return_val_if_fail (vtable != NULL, FALSE);
   5174 
   5175   if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
   5176     return FALSE;
   5177 
   5178   CONNECTION_LOCK (connection);
   5179 
   5180   retval = _dbus_object_tree_register (connection->objects,
   5181                                        FALSE,
   5182                                        (const char **) decomposed_path, vtable,
   5183                                        user_data);
   5184 
   5185   CONNECTION_UNLOCK (connection);
   5186 
   5187   dbus_free_string_array (decomposed_path);
   5188 
   5189   return retval;
   5190 }
   5191 
   5192 /**
   5193  * Registers a fallback handler for a given subsection of the object
   5194  * hierarchy.  The given vtable handles messages at or below the given
   5195  * path. You can use this to establish a default message handling
   5196  * policy for a whole "subdirectory."
   5197  *
   5198  * @param connection the connection
   5199  * @param path a '/' delimited string of path elements
   5200  * @param vtable the virtual table
   5201  * @param user_data data to pass to functions in the vtable
   5202  * @returns #FALSE if not enough memory
   5203  */
   5204 dbus_bool_t
   5205 dbus_connection_register_fallback (DBusConnection              *connection,
   5206                                    const char                  *path,
   5207                                    const DBusObjectPathVTable  *vtable,
   5208                                    void                        *user_data)
   5209 {
   5210   char **decomposed_path;
   5211   dbus_bool_t retval;
   5212 
   5213   _dbus_return_val_if_fail (connection != NULL, FALSE);
   5214   _dbus_return_val_if_fail (path != NULL, FALSE);
   5215   _dbus_return_val_if_fail (path[0] == '/', FALSE);
   5216   _dbus_return_val_if_fail (vtable != NULL, FALSE);
   5217 
   5218   if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
   5219     return FALSE;
   5220 
   5221   CONNECTION_LOCK (connection);
   5222 
   5223   retval = _dbus_object_tree_register (connection->objects,
   5224                                        TRUE,
   5225 				       (const char **) decomposed_path, vtable,
   5226                                        user_data);
   5227 
   5228   CONNECTION_UNLOCK (connection);
   5229 
   5230   dbus_free_string_array (decomposed_path);
   5231 
   5232   return retval;
   5233 }
   5234 
   5235 /**
   5236  * Unregisters the handler registered with exactly the given path.
   5237  * It's a bug to call this function for a path that isn't registered.
   5238  * Can unregister both fallback paths and object paths.
   5239  *
   5240  * @param connection the connection
   5241  * @param path a '/' delimited string of path elements
   5242  * @returns #FALSE if not enough memory
   5243  */
   5244 dbus_bool_t
   5245 dbus_connection_unregister_object_path (DBusConnection              *connection,
   5246                                         const char                  *path)
   5247 {
   5248   char **decomposed_path;
   5249 
   5250   _dbus_return_val_if_fail (connection != NULL, FALSE);
   5251   _dbus_return_val_if_fail (path != NULL, FALSE);
   5252   _dbus_return_val_if_fail (path[0] == '/', FALSE);
   5253 
   5254   if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
   5255       return FALSE;
   5256 
   5257   CONNECTION_LOCK (connection);
   5258 
   5259   _dbus_object_tree_unregister_and_unlock (connection->objects, (const char **) decomposed_path);
   5260 
   5261   dbus_free_string_array (decomposed_path);
   5262 
   5263   return TRUE;
   5264 }
   5265 
   5266 /**
   5267  * Gets the user data passed to dbus_connection_register_object_path()
   5268  * or dbus_connection_register_fallback(). If nothing was registered
   5269  * at this path, the data is filled in with #NULL.
   5270  *
   5271  * @param connection the connection
   5272  * @param path the path you registered with
   5273  * @param data_p location to store the user data, or #NULL
   5274  * @returns #FALSE if not enough memory
   5275  */
   5276 dbus_bool_t
   5277 dbus_connection_get_object_path_data (DBusConnection *connection,
   5278                                       const char     *path,
   5279                                       void          **data_p)
   5280 {
   5281   char **decomposed_path;
   5282 
   5283   _dbus_return_val_if_fail (connection != NULL, FALSE);
   5284   _dbus_return_val_if_fail (path != NULL, FALSE);
   5285   _dbus_return_val_if_fail (data_p != NULL, FALSE);
   5286 
   5287   *data_p = NULL;
   5288 
   5289   if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
   5290     return FALSE;
   5291 
   5292   CONNECTION_LOCK (connection);
   5293 
   5294   *data_p = _dbus_object_tree_get_user_data_unlocked (connection->objects, (const char**) decomposed_path);
   5295 
   5296   CONNECTION_UNLOCK (connection);
   5297 
   5298   dbus_free_string_array (decomposed_path);
   5299 
   5300   return TRUE;
   5301 }
   5302 
   5303 /**
   5304  * Lists the registered fallback handlers and object path handlers at
   5305  * the given parent_path. The returned array should be freed with
   5306  * dbus_free_string_array().
   5307  *
   5308  * @param connection the connection
   5309  * @param parent_path the path to list the child handlers of
   5310  * @param child_entries returns #NULL-terminated array of children
   5311  * @returns #FALSE if no memory to allocate the child entries
   5312  */
   5313 dbus_bool_t
   5314 dbus_connection_list_registered (DBusConnection              *connection,
   5315                                  const char                  *parent_path,
   5316                                  char                      ***child_entries)
   5317 {
   5318   char **decomposed_path;
   5319   dbus_bool_t retval;
   5320   _dbus_return_val_if_fail (connection != NULL, FALSE);
   5321   _dbus_return_val_if_fail (parent_path != NULL, FALSE);
   5322   _dbus_return_val_if_fail (parent_path[0] == '/', FALSE);
   5323   _dbus_return_val_if_fail (child_entries != NULL, FALSE);
   5324 
   5325   if (!_dbus_decompose_path (parent_path, strlen (parent_path), &decomposed_path, NULL))
   5326     return FALSE;
   5327 
   5328   CONNECTION_LOCK (connection);
   5329 
   5330   retval = _dbus_object_tree_list_registered_and_unlock (connection->objects,
   5331 							 (const char **) decomposed_path,
   5332 							 child_entries);
   5333   dbus_free_string_array (decomposed_path);
   5334 
   5335   return retval;
   5336 }
   5337 
   5338 static DBusDataSlotAllocator slot_allocator;
   5339 _DBUS_DEFINE_GLOBAL_LOCK (connection_slots);
   5340 
   5341 /**
   5342  * Allocates an integer ID to be used for storing application-specific
   5343  * data on any DBusConnection. The allocated ID may then be used
   5344  * with dbus_connection_set_data() and dbus_connection_get_data().
   5345  * The passed-in slot must be initialized to -1, and is filled in
   5346  * with the slot ID. If the passed-in slot is not -1, it's assumed
   5347  * to be already allocated, and its refcount is incremented.
   5348  *
   5349  * The allocated slot is global, i.e. all DBusConnection objects will
   5350  * have a slot with the given integer ID reserved.
   5351  *
   5352  * @param slot_p address of a global variable storing the slot
   5353  * @returns #FALSE on failure (no memory)
   5354  */
   5355 dbus_bool_t
   5356 dbus_connection_allocate_data_slot (dbus_int32_t *slot_p)
   5357 {
   5358   return _dbus_data_slot_allocator_alloc (&slot_allocator,
   5359                                           &_DBUS_LOCK_NAME (connection_slots),
   5360                                           slot_p);
   5361 }
   5362 
   5363 /**
   5364  * Deallocates a global ID for connection data slots.
   5365  * dbus_connection_get_data() and dbus_connection_set_data() may no
   5366  * longer be used with this slot.  Existing data stored on existing
   5367  * DBusConnection objects will be freed when the connection is
   5368  * finalized, but may not be retrieved (and may only be replaced if
   5369  * someone else reallocates the slot).  When the refcount on the
   5370  * passed-in slot reaches 0, it is set to -1.
   5371  *
   5372  * @param slot_p address storing the slot to deallocate
   5373  */
   5374 void
   5375 dbus_connection_free_data_slot (dbus_int32_t *slot_p)
   5376 {
   5377   _dbus_return_if_fail (*slot_p >= 0);
   5378 
   5379   _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
   5380 }
   5381 
   5382 /**
   5383  * Stores a pointer on a DBusConnection, along
   5384  * with an optional function to be used for freeing
   5385  * the data when the data is set again, or when
   5386  * the connection is finalized. The slot number
   5387  * must have been allocated with dbus_connection_allocate_data_slot().
   5388  *
   5389  * @param connection the connection
   5390  * @param slot the slot number
   5391  * @param data the data to store
   5392  * @param free_data_func finalizer function for the data
   5393  * @returns #TRUE if there was enough memory to store the data
   5394  */
   5395 dbus_bool_t
   5396 dbus_connection_set_data (DBusConnection   *connection,
   5397                           dbus_int32_t      slot,
   5398                           void             *data,
   5399                           DBusFreeFunction  free_data_func)
   5400 {
   5401   DBusFreeFunction old_free_func;
   5402   void *old_data;
   5403   dbus_bool_t retval;
   5404 
   5405   _dbus_return_val_if_fail (connection != NULL, FALSE);
   5406   _dbus_return_val_if_fail (slot >= 0, FALSE);
   5407 
   5408   CONNECTION_LOCK (connection);
   5409 
   5410   retval = _dbus_data_slot_list_set (&slot_allocator,
   5411                                      &connection->slot_list,
   5412                                      slot, data, free_data_func,
   5413                                      &old_free_func, &old_data);
   5414 
   5415   CONNECTION_UNLOCK (connection);
   5416 
   5417   if (retval)
   5418     {
   5419       /* Do the actual free outside the connection lock */
   5420       if (old_free_func)
   5421         (* old_free_func) (old_data);
   5422     }
   5423 
   5424   return retval;
   5425 }
   5426 
   5427 /**
   5428  * Retrieves data previously set with dbus_connection_set_data().
   5429  * The slot must still be allocated (must not have been freed).
   5430  *
   5431  * @param connection the connection
   5432  * @param slot the slot to get data from
   5433  * @returns the data, or #NULL if not found
   5434  */
   5435 void*
   5436 dbus_connection_get_data (DBusConnection   *connection,
   5437                           dbus_int32_t      slot)
   5438 {
   5439   void *res;
   5440 
   5441   _dbus_return_val_if_fail (connection != NULL, NULL);
   5442 
   5443   CONNECTION_LOCK (connection);
   5444 
   5445   res = _dbus_data_slot_list_get (&slot_allocator,
   5446                                   &connection->slot_list,
   5447                                   slot);
   5448 
   5449   CONNECTION_UNLOCK (connection);
   5450 
   5451   return res;
   5452 }
   5453 
   5454 /**
   5455  * This function sets a global flag for whether dbus_connection_new()
   5456  * will set SIGPIPE behavior to SIG_IGN.
   5457  *
   5458  * @param will_modify_sigpipe #TRUE to allow sigpipe to be set to SIG_IGN
   5459  */
   5460 void
   5461 dbus_connection_set_change_sigpipe (dbus_bool_t will_modify_sigpipe)
   5462 {
   5463   _dbus_modify_sigpipe = will_modify_sigpipe != FALSE;
   5464 }
   5465 
   5466 /**
   5467  * Specifies the maximum size message this connection is allowed to
   5468  * receive. Larger messages will result in disconnecting the
   5469  * connection.
   5470  *
   5471  * @param connection a #DBusConnection
   5472  * @param size maximum message size the connection can receive, in bytes
   5473  */
   5474 void
   5475 dbus_connection_set_max_message_size (DBusConnection *connection,
   5476                                       long            size)
   5477 {
   5478   _dbus_return_if_fail (connection != NULL);
   5479 
   5480   CONNECTION_LOCK (connection);
   5481   _dbus_transport_set_max_message_size (connection->transport,
   5482                                         size);
   5483   CONNECTION_UNLOCK (connection);
   5484 }
   5485 
   5486 /**
   5487  * Gets the value set by dbus_connection_set_max_message_size().
   5488  *
   5489  * @param connection the connection
   5490  * @returns the max size of a single message
   5491  */
   5492 long
   5493 dbus_connection_get_max_message_size (DBusConnection *connection)
   5494 {
   5495   long res;
   5496 
   5497   _dbus_return_val_if_fail (connection != NULL, 0);
   5498 
   5499   CONNECTION_LOCK (connection);
   5500   res = _dbus_transport_get_max_message_size (connection->transport);
   5501   CONNECTION_UNLOCK (connection);
   5502   return res;
   5503 }
   5504 
   5505 /**
   5506  * Sets the maximum total number of bytes that can be used for all messages
   5507  * received on this connection. Messages count toward the maximum until
   5508  * they are finalized. When the maximum is reached, the connection will
   5509  * not read more data until some messages are finalized.
   5510  *
   5511  * The semantics of the maximum are: if outstanding messages are
   5512  * already above the maximum, additional messages will not be read.
   5513  * The semantics are not: if the next message would cause us to exceed
   5514  * the maximum, we don't read it. The reason is that we don't know the
   5515  * size of a message until after we read it.
   5516  *
   5517  * Thus, the max live messages size can actually be exceeded
   5518  * by up to the maximum size of a single message.
   5519  *
   5520  * Also, if we read say 1024 bytes off the wire in a single read(),
   5521  * and that contains a half-dozen small messages, we may exceed the
   5522  * size max by that amount. But this should be inconsequential.
   5523  *
   5524  * This does imply that we can't call read() with a buffer larger
   5525  * than we're willing to exceed this limit by.
   5526  *
   5527  * @param connection the connection
   5528  * @param size the maximum size in bytes of all outstanding messages
   5529  */
   5530 void
   5531 dbus_connection_set_max_received_size (DBusConnection *connection,
   5532                                        long            size)
   5533 {
   5534   _dbus_return_if_fail (connection != NULL);
   5535 
   5536   CONNECTION_LOCK (connection);
   5537   _dbus_transport_set_max_received_size (connection->transport,
   5538                                          size);
   5539   CONNECTION_UNLOCK (connection);
   5540 }
   5541 
   5542 /**
   5543  * Gets the value set by dbus_connection_set_max_received_size().
   5544  *
   5545  * @param connection the connection
   5546  * @returns the max size of all live messages
   5547  */
   5548 long
   5549 dbus_connection_get_max_received_size (DBusConnection *connection)
   5550 {
   5551   long res;
   5552 
   5553   _dbus_return_val_if_fail (connection != NULL, 0);
   5554 
   5555   CONNECTION_LOCK (connection);
   5556   res = _dbus_transport_get_max_received_size (connection->transport);
   5557   CONNECTION_UNLOCK (connection);
   5558   return res;
   5559 }
   5560 
   5561 /**
   5562  * Gets the approximate size in bytes of all messages in the outgoing
   5563  * message queue. The size is approximate in that you shouldn't use
   5564  * it to decide how many bytes to read off the network or anything
   5565  * of that nature, as optimizations may choose to tell small white lies
   5566  * to avoid performance overhead.
   5567  *
   5568  * @param connection the connection
   5569  * @returns the number of bytes that have been queued up but not sent
   5570  */
   5571 long
   5572 dbus_connection_get_outgoing_size (DBusConnection *connection)
   5573 {
   5574   long res;
   5575 
   5576   _dbus_return_val_if_fail (connection != NULL, 0);
   5577 
   5578   CONNECTION_LOCK (connection);
   5579   res = _dbus_counter_get_value (connection->outgoing_counter);
   5580   CONNECTION_UNLOCK (connection);
   5581   return res;
   5582 }
   5583 
   5584 /** @} */
   5585