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