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