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