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