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