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