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