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