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