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