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