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