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