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