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