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