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