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