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