correctly unref connections without guids during shutdown
[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   dbus_uint32_t 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 static DBusList *shared_connections_no_guid = NULL;
1442
1443 static void
1444 close_connection_on_shutdown (DBusConnection *connection)
1445 {
1446   DBusMessage *message;
1447
1448   dbus_connection_ref (connection);
1449   _dbus_connection_close_possibly_shared (connection);
1450
1451   /* Churn through to the Disconnected message */
1452   while ((message = dbus_connection_pop_message (connection)))
1453     {
1454       dbus_message_unref (message);
1455     }
1456   dbus_connection_unref (connection);
1457 }
1458
1459 static void
1460 shared_connections_shutdown (void *data)
1461 {
1462   int n_entries;
1463   
1464   _DBUS_LOCK (shared_connections);
1465   
1466   /* This is a little bit unpleasant... better ideas? */
1467   while ((n_entries = _dbus_hash_table_get_n_entries (shared_connections)) > 0)
1468     {
1469       DBusConnection *connection;
1470       DBusHashIter iter;
1471       
1472       _dbus_hash_iter_init (shared_connections, &iter);
1473       _dbus_hash_iter_next (&iter);
1474        
1475       connection = _dbus_hash_iter_get_value (&iter);
1476
1477       _DBUS_UNLOCK (shared_connections);
1478       close_connection_on_shutdown (connection);
1479       _DBUS_LOCK (shared_connections);
1480
1481       /* The connection should now be dead and not in our hash ... */
1482       _dbus_assert (_dbus_hash_table_get_n_entries (shared_connections) < n_entries);
1483     }
1484
1485   _dbus_assert (_dbus_hash_table_get_n_entries (shared_connections) == 0);
1486   
1487   _dbus_hash_table_unref (shared_connections);
1488   shared_connections = NULL;
1489
1490   if (shared_connections_no_guid != NULL)
1491     {
1492       DBusConnection *connection;
1493       connection = _dbus_list_pop_first (&shared_connections_no_guid);
1494       while (connection != NULL)
1495         {
1496           _DBUS_UNLOCK (shared_connections);
1497           close_connection_on_shutdown (connection);
1498           _DBUS_LOCK (shared_connections);
1499           connection = _dbus_list_pop_first (&shared_connections_no_guid);
1500         }
1501     }
1502
1503   shared_connections_no_guid = NULL;
1504   
1505   _DBUS_UNLOCK (shared_connections);
1506 }
1507
1508 static dbus_bool_t
1509 connection_lookup_shared (DBusAddressEntry  *entry,
1510                           DBusConnection   **result)
1511 {
1512   _dbus_verbose ("checking for existing connection\n");
1513   
1514   *result = NULL;
1515   
1516   _DBUS_LOCK (shared_connections);
1517
1518   if (shared_connections == NULL)
1519     {
1520       _dbus_verbose ("creating shared_connections hash table\n");
1521       
1522       shared_connections = _dbus_hash_table_new (DBUS_HASH_STRING,
1523                                                  dbus_free,
1524                                                  NULL);
1525       if (shared_connections == NULL)
1526         {
1527           _DBUS_UNLOCK (shared_connections);
1528           return FALSE;
1529         }
1530
1531       if (!_dbus_register_shutdown_func (shared_connections_shutdown, NULL))
1532         {
1533           _dbus_hash_table_unref (shared_connections);
1534           shared_connections = NULL;
1535           _DBUS_UNLOCK (shared_connections);
1536           return FALSE;
1537         }
1538
1539       _dbus_verbose ("  successfully created shared_connections\n");
1540       
1541       _DBUS_UNLOCK (shared_connections);
1542       return TRUE; /* no point looking up in the hash we just made */
1543     }
1544   else
1545     {
1546       const char *guid;
1547
1548       guid = dbus_address_entry_get_value (entry, "guid");
1549       
1550       if (guid != NULL)
1551         {
1552           DBusConnection *connection;
1553           
1554           connection = _dbus_hash_table_lookup_string (shared_connections,
1555                                                        guid);
1556
1557           if (connection)
1558             {
1559               /* The DBusConnection can't be finalized without taking
1560                * the shared_connections lock to remove it from the
1561                * hash.  So it's safe to ref the connection here.
1562                * However, it may be disconnected if the Disconnected
1563                * message hasn't been processed yet, in which case we
1564                * want to pretend it isn't in the hash and avoid
1565                * returning it.
1566                *
1567                * The idea is to avoid ever returning a disconnected connection
1568                * from dbus_connection_open(). We could just synchronously
1569                * drop our shared ref to the connection on connection disconnect,
1570                * and then assert here that the connection is connected, but
1571                * that causes reentrancy headaches.
1572                */
1573               CONNECTION_LOCK (connection);
1574               if (_dbus_connection_get_is_connected_unlocked (connection))
1575                 {
1576                   _dbus_connection_ref_unlocked (connection);
1577                   *result = connection;
1578                   _dbus_verbose ("looked up existing connection to server guid %s\n",
1579                                  guid);
1580                 }
1581               else
1582                 {
1583                   _dbus_verbose ("looked up existing connection to server guid %s but it was disconnected so ignoring it\n",
1584                                  guid);
1585                 }
1586               CONNECTION_UNLOCK (connection);
1587             }
1588         }
1589       
1590       _DBUS_UNLOCK (shared_connections);
1591       return TRUE;
1592     }
1593 }
1594
1595 static dbus_bool_t
1596 connection_record_shared_unlocked (DBusConnection *connection,
1597                                    const char     *guid)
1598 {
1599   char *guid_key;
1600   char *guid_in_connection;
1601
1602   HAVE_LOCK_CHECK (connection);
1603   _dbus_assert (connection->server_guid == NULL);
1604   _dbus_assert (connection->shareable);
1605
1606   /* get a hard ref on this connection, even if
1607    * we won't in fact store it in the hash, we still
1608    * need to hold a ref on it until it's disconnected.
1609    */
1610   _dbus_connection_ref_unlocked (connection);
1611
1612   if (guid == NULL)
1613     {
1614       _DBUS_LOCK (shared_connections);
1615
1616       if (!_dbus_list_prepend (&shared_connections_no_guid, connection))
1617         {
1618           _DBUS_UNLOCK (shared_connections);
1619           return FALSE;
1620         }
1621
1622       _DBUS_UNLOCK (shared_connections);
1623       return TRUE; /* don't store in the hash */
1624     }
1625   
1626   /* A separate copy of the key is required in the hash table, because
1627    * we don't have a lock on the connection when we are doing a hash
1628    * lookup.
1629    */
1630   
1631   guid_key = _dbus_strdup (guid);
1632   if (guid_key == NULL)
1633     return FALSE;
1634
1635   guid_in_connection = _dbus_strdup (guid);
1636   if (guid_in_connection == NULL)
1637     {
1638       dbus_free (guid_key);
1639       return FALSE;
1640     }
1641   
1642   _DBUS_LOCK (shared_connections);
1643   _dbus_assert (shared_connections != NULL);
1644   
1645   if (!_dbus_hash_table_insert_string (shared_connections,
1646                                        guid_key, connection))
1647     {
1648       dbus_free (guid_key);
1649       dbus_free (guid_in_connection);
1650       _DBUS_UNLOCK (shared_connections);
1651       return FALSE;
1652     }
1653
1654   connection->server_guid = guid_in_connection;
1655
1656   _dbus_verbose ("stored connection to %s to be shared\n",
1657                  connection->server_guid);
1658   
1659   _DBUS_UNLOCK (shared_connections);
1660
1661   _dbus_assert (connection->server_guid != NULL);
1662   
1663   return TRUE;
1664 }
1665
1666 static void
1667 connection_forget_shared_unlocked (DBusConnection *connection)
1668 {
1669   HAVE_LOCK_CHECK (connection);
1670
1671   if (!connection->shareable)
1672     return;
1673   
1674   if (connection->server_guid != NULL)
1675     {
1676       _dbus_verbose ("dropping connection to %s out of the shared table\n",
1677                      connection->server_guid);
1678       
1679       _DBUS_LOCK (shared_connections);
1680       
1681       if (!_dbus_hash_table_remove_string (shared_connections,
1682                                            connection->server_guid))
1683         _dbus_assert_not_reached ("connection was not in the shared table");
1684       
1685       dbus_free (connection->server_guid);
1686       connection->server_guid = NULL;
1687       _DBUS_UNLOCK (shared_connections);
1688     }
1689   
1690   /* remove our reference held on all shareable connections */
1691   _dbus_connection_unref_unlocked (connection);
1692 }
1693
1694 static DBusConnection*
1695 connection_try_from_address_entry (DBusAddressEntry *entry,
1696                                    DBusError        *error)
1697 {
1698   DBusTransport *transport;
1699   DBusConnection *connection;
1700
1701   transport = _dbus_transport_open (entry, error);
1702
1703   if (transport == NULL)
1704     {
1705       _DBUS_ASSERT_ERROR_IS_SET (error);
1706       return NULL;
1707     }
1708
1709   connection = _dbus_connection_new_for_transport (transport);
1710
1711   _dbus_transport_unref (transport);
1712   
1713   if (connection == NULL)
1714     {
1715       _DBUS_SET_OOM (error);
1716       return NULL;
1717     }
1718
1719 #ifndef DBUS_DISABLE_CHECKS
1720   _dbus_assert (!connection->have_connection_lock);
1721 #endif
1722   return connection;
1723 }
1724
1725 /*
1726  * If the shared parameter is true, then any existing connection will
1727  * be used (and if a new connection is created, it will be available
1728  * for use by others). If the shared parameter is false, a new
1729  * connection will always be created, and the new connection will
1730  * never be returned to other callers.
1731  *
1732  * @param address the address
1733  * @param shared whether the connection is shared or private
1734  * @param error error return
1735  * @returns the connection or #NULL on error
1736  */
1737 static DBusConnection*
1738 _dbus_connection_open_internal (const char     *address,
1739                                 dbus_bool_t     shared,
1740                                 DBusError      *error)
1741 {
1742   DBusConnection *connection;
1743   DBusAddressEntry **entries;
1744   DBusError tmp_error = DBUS_ERROR_INIT;
1745   DBusError first_error = DBUS_ERROR_INIT;
1746   int len, i;
1747
1748   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1749
1750   _dbus_verbose ("opening %s connection to: %s\n",
1751                  shared ? "shared" : "private", address);
1752   
1753   if (!dbus_parse_address (address, &entries, &len, error))
1754     return NULL;
1755
1756   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1757   
1758   connection = NULL;
1759
1760   for (i = 0; i < len; i++)
1761     {
1762       if (shared)
1763         {
1764           if (!connection_lookup_shared (entries[i], &connection))
1765             _DBUS_SET_OOM (&tmp_error);
1766         }
1767
1768       if (connection == NULL)
1769         {
1770           connection = connection_try_from_address_entry (entries[i],
1771                                                           &tmp_error);
1772
1773           if (connection != NULL && shared)
1774             {
1775               const char *guid;
1776                   
1777               connection->shareable = TRUE;
1778                   
1779               /* guid may be NULL */
1780               guid = dbus_address_entry_get_value (entries[i], "guid");
1781                   
1782               CONNECTION_LOCK (connection);
1783           
1784               if (!connection_record_shared_unlocked (connection, guid))
1785                 {
1786                   _DBUS_SET_OOM (&tmp_error);
1787                   _dbus_connection_close_possibly_shared_and_unlock (connection);
1788                   dbus_connection_unref (connection);
1789                   connection = NULL;
1790                 }
1791               else
1792                 CONNECTION_UNLOCK (connection);
1793             }
1794         }
1795       
1796       if (connection)
1797         break;
1798
1799       _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
1800       
1801       if (i == 0)
1802         dbus_move_error (&tmp_error, &first_error);
1803       else
1804         dbus_error_free (&tmp_error);
1805     }
1806   
1807   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1808   _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
1809   
1810   if (connection == NULL)
1811     {
1812       _DBUS_ASSERT_ERROR_IS_SET (&first_error);
1813       dbus_move_error (&first_error, error);
1814     }
1815   else
1816     dbus_error_free (&first_error);
1817   
1818   dbus_address_entries_free (entries);
1819   return connection;
1820 }
1821
1822 /**
1823  * Closes a shared OR private connection, while dbus_connection_close() can
1824  * only be used on private connections. Should only be called by the
1825  * dbus code that owns the connection - an owner must be known,
1826  * the open/close state is like malloc/free, not like ref/unref.
1827  * 
1828  * @param connection the connection
1829  */
1830 void
1831 _dbus_connection_close_possibly_shared (DBusConnection *connection)
1832 {
1833   _dbus_assert (connection != NULL);
1834   _dbus_assert (connection->generation == _dbus_current_generation);
1835
1836   CONNECTION_LOCK (connection);
1837   _dbus_connection_close_possibly_shared_and_unlock (connection);
1838 }
1839
1840 static DBusPreallocatedSend*
1841 _dbus_connection_preallocate_send_unlocked (DBusConnection *connection)
1842 {
1843   DBusPreallocatedSend *preallocated;
1844
1845   HAVE_LOCK_CHECK (connection);
1846   
1847   _dbus_assert (connection != NULL);
1848   
1849   preallocated = dbus_new (DBusPreallocatedSend, 1);
1850   if (preallocated == NULL)
1851     return NULL;
1852
1853   if (connection->link_cache != NULL)
1854     {
1855       preallocated->queue_link =
1856         _dbus_list_pop_first_link (&connection->link_cache);
1857       preallocated->queue_link->data = NULL;
1858     }
1859   else
1860     {
1861       preallocated->queue_link = _dbus_list_alloc_link (NULL);
1862       if (preallocated->queue_link == NULL)
1863         goto failed_0;
1864     }
1865   
1866   if (connection->link_cache != NULL)
1867     {
1868       preallocated->counter_link =
1869         _dbus_list_pop_first_link (&connection->link_cache);
1870       preallocated->counter_link->data = connection->outgoing_counter;
1871     }
1872   else
1873     {
1874       preallocated->counter_link = _dbus_list_alloc_link (connection->outgoing_counter);
1875       if (preallocated->counter_link == NULL)
1876         goto failed_1;
1877     }
1878
1879   _dbus_counter_ref (preallocated->counter_link->data);
1880
1881   preallocated->connection = connection;
1882   
1883   return preallocated;
1884   
1885  failed_1:
1886   _dbus_list_free_link (preallocated->queue_link);
1887  failed_0:
1888   dbus_free (preallocated);
1889   
1890   return NULL;
1891 }
1892
1893 /* Called with lock held, does not update dispatch status */
1894 static void
1895 _dbus_connection_send_preallocated_unlocked_no_update (DBusConnection       *connection,
1896                                                        DBusPreallocatedSend *preallocated,
1897                                                        DBusMessage          *message,
1898                                                        dbus_uint32_t        *client_serial)
1899 {
1900   dbus_uint32_t serial;
1901   const char *sig;
1902
1903   preallocated->queue_link->data = message;
1904   _dbus_list_prepend_link (&connection->outgoing_messages,
1905                            preallocated->queue_link);
1906
1907   _dbus_message_add_size_counter_link (message,
1908                                        preallocated->counter_link);
1909
1910   dbus_free (preallocated);
1911   preallocated = NULL;
1912   
1913   dbus_message_ref (message);
1914   
1915   connection->n_outgoing += 1;
1916
1917   sig = dbus_message_get_signature (message);
1918   
1919   _dbus_verbose ("Message %p (%d %s %s %s '%s') for %s added to outgoing queue %p, %d pending to send\n",
1920                  message,
1921                  dbus_message_get_type (message),
1922                  dbus_message_get_path (message) ?
1923                  dbus_message_get_path (message) :
1924                  "no path",
1925                  dbus_message_get_interface (message) ?
1926                  dbus_message_get_interface (message) :
1927                  "no interface",
1928                  dbus_message_get_member (message) ?
1929                  dbus_message_get_member (message) :
1930                  "no member",
1931                  sig,
1932                  dbus_message_get_destination (message) ?
1933                  dbus_message_get_destination (message) :
1934                  "null",
1935                  connection,
1936                  connection->n_outgoing);
1937
1938   if (dbus_message_get_serial (message) == 0)
1939     {
1940       serial = _dbus_connection_get_next_client_serial (connection);
1941       _dbus_message_set_serial (message, serial);
1942       if (client_serial)
1943         *client_serial = serial;
1944     }
1945   else
1946     {
1947       if (client_serial)
1948         *client_serial = dbus_message_get_serial (message);
1949     }
1950
1951   _dbus_verbose ("Message %p serial is %u\n",
1952                  message, dbus_message_get_serial (message));
1953   
1954   _dbus_message_lock (message);
1955
1956   /* Now we need to run an iteration to hopefully just write the messages
1957    * out immediately, and otherwise get them queued up
1958    */
1959   _dbus_connection_do_iteration_unlocked (connection,
1960                                           DBUS_ITERATION_DO_WRITING,
1961                                           -1);
1962
1963   /* If stuff is still queued up, be sure we wake up the main loop */
1964   if (connection->n_outgoing > 0)
1965     _dbus_connection_wakeup_mainloop (connection);
1966 }
1967
1968 static void
1969 _dbus_connection_send_preallocated_and_unlock (DBusConnection       *connection,
1970                                                DBusPreallocatedSend *preallocated,
1971                                                DBusMessage          *message,
1972                                                dbus_uint32_t        *client_serial)
1973 {
1974   DBusDispatchStatus status;
1975
1976   HAVE_LOCK_CHECK (connection);
1977   
1978   _dbus_connection_send_preallocated_unlocked_no_update (connection,
1979                                                          preallocated,
1980                                                          message, client_serial);
1981
1982   _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
1983   status = _dbus_connection_get_dispatch_status_unlocked (connection);
1984
1985   /* this calls out to user code */
1986   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1987 }
1988
1989 /**
1990  * Like dbus_connection_send(), but assumes the connection
1991  * is already locked on function entry, and unlocks before returning.
1992  *
1993  * @param connection the connection
1994  * @param message the message to send
1995  * @param client_serial return location for client serial of sent message
1996  * @returns #FALSE on out-of-memory
1997  */
1998 dbus_bool_t
1999 _dbus_connection_send_and_unlock (DBusConnection *connection,
2000                                   DBusMessage    *message,
2001                                   dbus_uint32_t  *client_serial)
2002 {
2003   DBusPreallocatedSend *preallocated;
2004
2005   _dbus_assert (connection != NULL);
2006   _dbus_assert (message != NULL);
2007   
2008   preallocated = _dbus_connection_preallocate_send_unlocked (connection);
2009   if (preallocated == NULL)
2010     {
2011       CONNECTION_UNLOCK (connection);
2012       return FALSE;
2013     }
2014
2015   _dbus_connection_send_preallocated_and_unlock (connection,
2016                                                  preallocated,
2017                                                  message,
2018                                                  client_serial);
2019   return TRUE;
2020 }
2021
2022 /**
2023  * Used internally to handle the semantics of dbus_server_set_new_connection_function().
2024  * If the new connection function does not ref the connection, we want to close it.
2025  *
2026  * A bit of a hack, probably the new connection function should have returned a value
2027  * for whether to close, or should have had to close the connection itself if it
2028  * didn't want it.
2029  *
2030  * But, this works OK as long as the new connection function doesn't do anything
2031  * crazy like keep the connection around without ref'ing it.
2032  *
2033  * We have to lock the connection across refcount check and close in case
2034  * the new connection function spawns a thread that closes and unrefs.
2035  * In that case, if the app thread
2036  * closes and unrefs first, we'll harmlessly close again; if the app thread
2037  * still has the ref, we'll close and then the app will close harmlessly.
2038  * If the app unrefs without closing, the app is broken since if the
2039  * app refs from the new connection function it is supposed to also close.
2040  *
2041  * If we didn't atomically check the refcount and close with the lock held
2042  * though, we could screw this up.
2043  * 
2044  * @param connection the connection
2045  */
2046 void
2047 _dbus_connection_close_if_only_one_ref (DBusConnection *connection)
2048 {
2049   CONNECTION_LOCK (connection);
2050   
2051   _dbus_assert (connection->refcount.value > 0);
2052
2053   if (connection->refcount.value == 1)
2054     _dbus_connection_close_possibly_shared_and_unlock (connection);
2055   else
2056     CONNECTION_UNLOCK (connection);
2057 }
2058
2059
2060 /**
2061  * When a function that blocks has been called with a timeout, and we
2062  * run out of memory, the time to wait for memory is based on the
2063  * timeout. If the caller was willing to block a long time we wait a
2064  * relatively long time for memory, if they were only willing to block
2065  * briefly then we retry for memory at a rapid rate.
2066  *
2067  * @timeout_milliseconds the timeout requested for blocking
2068  */
2069 static void
2070 _dbus_memory_pause_based_on_timeout (int timeout_milliseconds)
2071 {
2072   if (timeout_milliseconds == -1)
2073     _dbus_sleep_milliseconds (1000);
2074   else if (timeout_milliseconds < 100)
2075     ; /* just busy loop */
2076   else if (timeout_milliseconds <= 1000)
2077     _dbus_sleep_milliseconds (timeout_milliseconds / 3);
2078   else
2079     _dbus_sleep_milliseconds (1000);
2080 }
2081
2082 static DBusMessage *
2083 generate_local_error_message (dbus_uint32_t serial, 
2084                               char *error_name, 
2085                               char *error_msg)
2086 {
2087   DBusMessage *message;
2088   message = dbus_message_new (DBUS_MESSAGE_TYPE_ERROR);
2089   if (!message)
2090     goto out;
2091
2092   if (!dbus_message_set_error_name (message, error_name))
2093     {
2094       dbus_message_unref (message);
2095       message = NULL;
2096       goto out; 
2097     }
2098
2099   dbus_message_set_no_reply (message, TRUE); 
2100
2101   if (!dbus_message_set_reply_serial (message,
2102                                       serial))
2103     {
2104       dbus_message_unref (message);
2105       message = NULL;
2106       goto out;
2107     }
2108
2109   if (error_msg != NULL)
2110     {
2111       DBusMessageIter iter;
2112
2113       dbus_message_iter_init_append (message, &iter);
2114       if (!dbus_message_iter_append_basic (&iter,
2115                                            DBUS_TYPE_STRING,
2116                                            &error_msg))
2117         {
2118           dbus_message_unref (message);
2119           message = NULL;
2120           goto out;
2121         }
2122     }
2123
2124  out:
2125   return message;
2126 }
2127
2128
2129 /* This is slightly strange since we can pop a message here without
2130  * the dispatch lock.
2131  */
2132 static DBusMessage*
2133 check_for_reply_unlocked (DBusConnection *connection,
2134                           dbus_uint32_t   client_serial)
2135 {
2136   DBusList *link;
2137
2138   HAVE_LOCK_CHECK (connection);
2139   
2140   link = _dbus_list_get_first_link (&connection->incoming_messages);
2141
2142   while (link != NULL)
2143     {
2144       DBusMessage *reply = link->data;
2145
2146       if (dbus_message_get_reply_serial (reply) == client_serial)
2147         {
2148           _dbus_list_remove_link (&connection->incoming_messages, link);
2149           connection->n_incoming  -= 1;
2150           return reply;
2151         }
2152       link = _dbus_list_get_next_link (&connection->incoming_messages, link);
2153     }
2154
2155   return NULL;
2156 }
2157
2158 static void
2159 connection_timeout_and_complete_all_pending_calls_unlocked (DBusConnection *connection)
2160 {
2161    /* We can't iterate over the hash in the normal way since we'll be
2162     * dropping the lock for each item. So we restart the
2163     * iter each time as we drain the hash table.
2164     */
2165    
2166    while (_dbus_hash_table_get_n_entries (connection->pending_replies) > 0)
2167     {
2168       DBusPendingCall *pending;
2169       DBusHashIter iter;
2170       
2171       _dbus_hash_iter_init (connection->pending_replies, &iter);
2172       _dbus_hash_iter_next (&iter);
2173        
2174       pending = _dbus_hash_iter_get_value (&iter);
2175       _dbus_pending_call_ref_unlocked (pending);
2176        
2177       _dbus_pending_call_queue_timeout_error_unlocked (pending, 
2178                                                        connection);
2179       _dbus_connection_remove_timeout_unlocked (connection,
2180                                                 _dbus_pending_call_get_timeout_unlocked (pending));
2181       _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);       
2182       _dbus_hash_iter_remove_entry (&iter);
2183
2184       _dbus_pending_call_unref_and_unlock (pending);
2185       CONNECTION_LOCK (connection);
2186     }
2187   HAVE_LOCK_CHECK (connection);
2188 }
2189
2190 static void
2191 complete_pending_call_and_unlock (DBusConnection  *connection,
2192                                   DBusPendingCall *pending,
2193                                   DBusMessage     *message)
2194 {
2195   _dbus_pending_call_set_reply_unlocked (pending, message);
2196   _dbus_pending_call_ref_unlocked (pending); /* in case there's no app with a ref held */
2197   _dbus_connection_detach_pending_call_and_unlock (connection, pending);
2198  
2199   /* Must be called unlocked since it invokes app callback */
2200   _dbus_pending_call_complete (pending);
2201   dbus_pending_call_unref (pending);
2202 }
2203
2204 static dbus_bool_t
2205 check_for_reply_and_update_dispatch_unlocked (DBusConnection  *connection,
2206                                               DBusPendingCall *pending)
2207 {
2208   DBusMessage *reply;
2209   DBusDispatchStatus status;
2210
2211   reply = check_for_reply_unlocked (connection, 
2212                                     _dbus_pending_call_get_reply_serial_unlocked (pending));
2213   if (reply != NULL)
2214     {
2215       _dbus_verbose ("%s checked for reply\n", _DBUS_FUNCTION_NAME);
2216
2217       _dbus_verbose ("dbus_connection_send_with_reply_and_block(): got reply\n");
2218
2219       complete_pending_call_and_unlock (connection, pending, reply);
2220       dbus_message_unref (reply);
2221
2222       CONNECTION_LOCK (connection);
2223       status = _dbus_connection_get_dispatch_status_unlocked (connection);
2224       _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2225       dbus_pending_call_unref (pending);
2226
2227       return TRUE;
2228     }
2229
2230   return FALSE;
2231 }
2232
2233 /**
2234  * Blocks until a pending call times out or gets a reply.
2235  *
2236  * Does not re-enter the main loop or run filter/path-registered
2237  * callbacks. The reply to the message will not be seen by
2238  * filter callbacks.
2239  *
2240  * Returns immediately if pending call already got a reply.
2241  * 
2242  * @todo could use performance improvements (it keeps scanning
2243  * the whole message queue for example)
2244  *
2245  * @param pending the pending call we block for a reply on
2246  */
2247 void
2248 _dbus_connection_block_pending_call (DBusPendingCall *pending)
2249 {
2250   long start_tv_sec, start_tv_usec;
2251   long end_tv_sec, end_tv_usec;
2252   long tv_sec, tv_usec;
2253   DBusDispatchStatus status;
2254   DBusConnection *connection;
2255   dbus_uint32_t client_serial;
2256   int timeout_milliseconds;
2257
2258   _dbus_assert (pending != NULL);
2259
2260   if (dbus_pending_call_get_completed (pending))
2261     return;
2262
2263   dbus_pending_call_ref (pending); /* necessary because the call could be canceled */
2264
2265   connection = _dbus_pending_call_get_connection_and_lock (pending);
2266   
2267   /* Flush message queue - note, can affect dispatch status */
2268   _dbus_connection_flush_unlocked (connection);
2269
2270   client_serial = _dbus_pending_call_get_reply_serial_unlocked (pending);
2271
2272   /* note that timeout_milliseconds is limited to a smallish value
2273    * in _dbus_pending_call_new() so overflows aren't possible
2274    * below
2275    */
2276   timeout_milliseconds = dbus_timeout_get_interval (_dbus_pending_call_get_timeout_unlocked (pending));
2277   
2278   _dbus_get_current_time (&start_tv_sec, &start_tv_usec);
2279   end_tv_sec = start_tv_sec + timeout_milliseconds / 1000;
2280   end_tv_usec = start_tv_usec + (timeout_milliseconds % 1000) * 1000;
2281   end_tv_sec += end_tv_usec / _DBUS_USEC_PER_SECOND;
2282   end_tv_usec = end_tv_usec % _DBUS_USEC_PER_SECOND;
2283
2284   _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",
2285                  timeout_milliseconds,
2286                  client_serial,
2287                  start_tv_sec, start_tv_usec,
2288                  end_tv_sec, end_tv_usec);
2289
2290   /* check to see if we already got the data off the socket */
2291   /* from another blocked pending call */
2292   if (check_for_reply_and_update_dispatch_unlocked (connection, pending))
2293     return;
2294
2295   /* Now we wait... */
2296   /* always block at least once as we know we don't have the reply yet */
2297   _dbus_connection_do_iteration_unlocked (connection,
2298                                           DBUS_ITERATION_DO_READING |
2299                                           DBUS_ITERATION_BLOCK,
2300                                           timeout_milliseconds);
2301
2302  recheck_status:
2303
2304   _dbus_verbose ("%s top of recheck\n", _DBUS_FUNCTION_NAME);
2305   
2306   HAVE_LOCK_CHECK (connection);
2307   
2308   /* queue messages and get status */
2309
2310   status = _dbus_connection_get_dispatch_status_unlocked (connection);
2311
2312   /* the get_completed() is in case a dispatch() while we were blocking
2313    * got the reply instead of us.
2314    */
2315   if (_dbus_pending_call_get_completed_unlocked (pending))
2316     {
2317       _dbus_verbose ("Pending call completed by dispatch in %s\n", _DBUS_FUNCTION_NAME);
2318       _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2319       dbus_pending_call_unref (pending);
2320       return;
2321     }
2322   
2323   if (status == DBUS_DISPATCH_DATA_REMAINS)
2324     {
2325       if (check_for_reply_and_update_dispatch_unlocked (connection, pending))
2326         return;
2327     }
2328   
2329   _dbus_get_current_time (&tv_sec, &tv_usec);
2330   
2331   if (!_dbus_connection_get_is_connected_unlocked (connection))
2332     {
2333       DBusMessage *error_msg;
2334
2335       error_msg = generate_local_error_message (client_serial,
2336                                                 DBUS_ERROR_DISCONNECTED, 
2337                                                 "Connection was disconnected before a reply was received"); 
2338
2339       /* on OOM error_msg is set to NULL */
2340       complete_pending_call_and_unlock (connection, pending, error_msg);
2341       dbus_pending_call_unref (pending);
2342       return;
2343     }
2344   else if (tv_sec < start_tv_sec)
2345     _dbus_verbose ("dbus_connection_send_with_reply_and_block(): clock set backward\n");
2346   else if (connection->disconnect_message_link == NULL)
2347     _dbus_verbose ("dbus_connection_send_with_reply_and_block(): disconnected\n");
2348   else if (tv_sec < end_tv_sec ||
2349            (tv_sec == end_tv_sec && tv_usec < end_tv_usec))
2350     {
2351       timeout_milliseconds = (end_tv_sec - tv_sec) * 1000 +
2352         (end_tv_usec - tv_usec) / 1000;
2353       _dbus_verbose ("dbus_connection_send_with_reply_and_block(): %d milliseconds remain\n", timeout_milliseconds);
2354       _dbus_assert (timeout_milliseconds >= 0);
2355       
2356       if (status == DBUS_DISPATCH_NEED_MEMORY)
2357         {
2358           /* Try sleeping a bit, as we aren't sure we need to block for reading,
2359            * we may already have a reply in the buffer and just can't process
2360            * it.
2361            */
2362           _dbus_verbose ("dbus_connection_send_with_reply_and_block() waiting for more memory\n");
2363
2364           _dbus_memory_pause_based_on_timeout (timeout_milliseconds);
2365         }
2366       else
2367         {          
2368           /* block again, we don't have the reply buffered yet. */
2369           _dbus_connection_do_iteration_unlocked (connection,
2370                                                   DBUS_ITERATION_DO_READING |
2371                                                   DBUS_ITERATION_BLOCK,
2372                                                   timeout_milliseconds);
2373         }
2374
2375       goto recheck_status;
2376     }
2377
2378   _dbus_verbose ("dbus_connection_send_with_reply_and_block(): Waited %ld milliseconds and got no reply\n",
2379                  (tv_sec - start_tv_sec) * 1000 + (tv_usec - start_tv_usec) / 1000);
2380
2381   _dbus_assert (!_dbus_pending_call_get_completed_unlocked (pending));
2382   
2383   /* unlock and call user code */
2384   complete_pending_call_and_unlock (connection, pending, NULL);
2385
2386   /* update user code on dispatch status */
2387   CONNECTION_LOCK (connection);
2388   status = _dbus_connection_get_dispatch_status_unlocked (connection);
2389   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2390   dbus_pending_call_unref (pending);
2391 }
2392
2393 /** @} */
2394
2395 /**
2396  * @addtogroup DBusConnection
2397  *
2398  * @{
2399  */
2400
2401 /**
2402  * Gets a connection to a remote address. If a connection to the given
2403  * address already exists, returns the existing connection with its
2404  * reference count incremented.  Otherwise, returns a new connection
2405  * and saves the new connection for possible re-use if a future call
2406  * to dbus_connection_open() asks to connect to the same server.
2407  *
2408  * Use dbus_connection_open_private() to get a dedicated connection
2409  * not shared with other callers of dbus_connection_open().
2410  *
2411  * If the open fails, the function returns #NULL, and provides a
2412  * reason for the failure in the error parameter. Pass #NULL for the
2413  * error parameter if you aren't interested in the reason for
2414  * failure.
2415  *
2416  * Because this connection is shared, no user of the connection
2417  * may call dbus_connection_close(). However, when you are done with the
2418  * connection you should call dbus_connection_unref().
2419  *
2420  * @note Prefer dbus_connection_open() to dbus_connection_open_private()
2421  * unless you have good reason; connections are expensive enough
2422  * that it's wasteful to create lots of connections to the same
2423  * server.
2424  * 
2425  * @param address the address.
2426  * @param error address where an error can be returned.
2427  * @returns new connection, or #NULL on failure.
2428  */
2429 DBusConnection*
2430 dbus_connection_open (const char     *address,
2431                       DBusError      *error)
2432 {
2433   DBusConnection *connection;
2434
2435   _dbus_return_val_if_fail (address != NULL, NULL);
2436   _dbus_return_val_if_error_is_set (error, NULL);
2437
2438   connection = _dbus_connection_open_internal (address,
2439                                                TRUE,
2440                                                error);
2441
2442   return connection;
2443 }
2444
2445 /**
2446  * Opens a new, dedicated connection to a remote address. Unlike
2447  * dbus_connection_open(), always creates a new connection.
2448  * This connection will not be saved or recycled by libdbus.
2449  *
2450  * If the open fails, the function returns #NULL, and provides a
2451  * reason for the failure in the error parameter. Pass #NULL for the
2452  * error parameter if you aren't interested in the reason for
2453  * failure.
2454  *
2455  * When you are done with this connection, you must
2456  * dbus_connection_close() to disconnect it,
2457  * and dbus_connection_unref() to free the connection object.
2458  * 
2459  * (The dbus_connection_close() can be skipped if the
2460  * connection is already known to be disconnected, for example
2461  * if you are inside a handler for the Disconnected signal.)
2462  *
2463  * @note Prefer dbus_connection_open() to dbus_connection_open_private()
2464  * unless you have good reason; connections are expensive enough
2465  * that it's wasteful to create lots of connections to the same
2466  * server.
2467  *
2468  * @param address the address.
2469  * @param error address where an error can be returned.
2470  * @returns new connection, or #NULL on failure.
2471  */
2472 DBusConnection*
2473 dbus_connection_open_private (const char     *address,
2474                               DBusError      *error)
2475 {
2476   DBusConnection *connection;
2477
2478   _dbus_return_val_if_fail (address != NULL, NULL);
2479   _dbus_return_val_if_error_is_set (error, NULL);
2480
2481   connection = _dbus_connection_open_internal (address,
2482                                                FALSE,
2483                                                error);
2484
2485   return connection;
2486 }
2487
2488 /**
2489  * Increments the reference count of a DBusConnection.
2490  *
2491  * @param connection the connection.
2492  * @returns the connection.
2493  */
2494 DBusConnection *
2495 dbus_connection_ref (DBusConnection *connection)
2496 {
2497   _dbus_return_val_if_fail (connection != NULL, NULL);
2498   _dbus_return_val_if_fail (connection->generation == _dbus_current_generation, NULL);
2499   
2500   /* The connection lock is better than the global
2501    * lock in the atomic increment fallback
2502    */
2503   
2504 #ifdef DBUS_HAVE_ATOMIC_INT
2505   _dbus_atomic_inc (&connection->refcount);
2506 #else
2507   CONNECTION_LOCK (connection);
2508   _dbus_assert (connection->refcount.value > 0);
2509
2510   connection->refcount.value += 1;
2511   CONNECTION_UNLOCK (connection);
2512 #endif
2513
2514   return connection;
2515 }
2516
2517 static void
2518 free_outgoing_message (void *element,
2519                        void *data)
2520 {
2521   DBusMessage *message = element;
2522   DBusConnection *connection = data;
2523
2524   _dbus_message_remove_size_counter (message,
2525                                      connection->outgoing_counter,
2526                                      NULL);
2527   dbus_message_unref (message);
2528 }
2529
2530 /* This is run without the mutex held, but after the last reference
2531  * to the connection has been dropped we should have no thread-related
2532  * problems
2533  */
2534 static void
2535 _dbus_connection_last_unref (DBusConnection *connection)
2536 {
2537   DBusList *link;
2538
2539   _dbus_verbose ("Finalizing connection %p\n", connection);
2540   
2541   _dbus_assert (connection->refcount.value == 0);
2542   
2543   /* You have to disconnect the connection before unref:ing it. Otherwise
2544    * you won't get the disconnected message.
2545    */
2546   _dbus_assert (!_dbus_transport_get_is_connected (connection->transport));
2547   _dbus_assert (connection->server_guid == NULL);
2548   
2549   /* ---- We're going to call various application callbacks here, hope it doesn't break anything... */
2550   _dbus_object_tree_free_all_unlocked (connection->objects);
2551   
2552   dbus_connection_set_dispatch_status_function (connection, NULL, NULL, NULL);
2553   dbus_connection_set_wakeup_main_function (connection, NULL, NULL, NULL);
2554   dbus_connection_set_unix_user_function (connection, NULL, NULL, NULL);
2555   
2556   _dbus_watch_list_free (connection->watches);
2557   connection->watches = NULL;
2558   
2559   _dbus_timeout_list_free (connection->timeouts);
2560   connection->timeouts = NULL;
2561
2562   _dbus_data_slot_list_free (&connection->slot_list);
2563   
2564   link = _dbus_list_get_first_link (&connection->filter_list);
2565   while (link != NULL)
2566     {
2567       DBusMessageFilter *filter = link->data;
2568       DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
2569
2570       filter->function = NULL;
2571       _dbus_message_filter_unref (filter); /* calls app callback */
2572       link->data = NULL;
2573       
2574       link = next;
2575     }
2576   _dbus_list_clear (&connection->filter_list);
2577   
2578   /* ---- Done with stuff that invokes application callbacks */
2579
2580   _dbus_object_tree_unref (connection->objects);  
2581
2582   _dbus_hash_table_unref (connection->pending_replies);
2583   connection->pending_replies = NULL;
2584   
2585   _dbus_list_clear (&connection->filter_list);
2586   
2587   _dbus_list_foreach (&connection->outgoing_messages,
2588                       free_outgoing_message,
2589                       connection);
2590   _dbus_list_clear (&connection->outgoing_messages);
2591   
2592   _dbus_list_foreach (&connection->incoming_messages,
2593                       (DBusForeachFunction) dbus_message_unref,
2594                       NULL);
2595   _dbus_list_clear (&connection->incoming_messages);
2596
2597   _dbus_counter_unref (connection->outgoing_counter);
2598
2599   _dbus_transport_unref (connection->transport);
2600
2601   if (connection->disconnect_message_link)
2602     {
2603       DBusMessage *message = connection->disconnect_message_link->data;
2604       dbus_message_unref (message);
2605       _dbus_list_free_link (connection->disconnect_message_link);
2606     }
2607
2608   _dbus_list_clear (&connection->link_cache);
2609   
2610   _dbus_condvar_free_at_location (&connection->dispatch_cond);
2611   _dbus_condvar_free_at_location (&connection->io_path_cond);
2612
2613   _dbus_mutex_free_at_location (&connection->io_path_mutex);
2614   _dbus_mutex_free_at_location (&connection->dispatch_mutex);
2615
2616   _dbus_mutex_free_at_location (&connection->mutex);
2617   
2618   dbus_free (connection);
2619 }
2620
2621 /**
2622  * Decrements the reference count of a DBusConnection, and finalizes
2623  * it if the count reaches zero.
2624  *
2625  * Note: it is a bug to drop the last reference to a connection that
2626  * is still connected.
2627  *
2628  * For shared connections, libdbus will own a reference
2629  * as long as the connection is connected, so you can know that either
2630  * you don't have the last reference, or it's OK to drop the last reference.
2631  * Most connections are shared. dbus_connection_open() and dbus_bus_get()
2632  * return shared connections.
2633  *
2634  * For private connections, the creator of the connection must arrange for
2635  * dbus_connection_close() to be called prior to dropping the last reference.
2636  * Private connections come from dbus_connection_open_private() or dbus_bus_get_private().
2637  *
2638  * @param connection the connection.
2639  */
2640 void
2641 dbus_connection_unref (DBusConnection *connection)
2642 {
2643   dbus_bool_t last_unref;
2644
2645   _dbus_return_if_fail (connection != NULL);
2646   _dbus_return_if_fail (connection->generation == _dbus_current_generation);
2647   
2648   /* The connection lock is better than the global
2649    * lock in the atomic increment fallback
2650    */
2651   
2652 #ifdef DBUS_HAVE_ATOMIC_INT
2653   last_unref = (_dbus_atomic_dec (&connection->refcount) == 1);
2654 #else
2655   CONNECTION_LOCK (connection);
2656   
2657   _dbus_assert (connection->refcount.value > 0);
2658
2659   connection->refcount.value -= 1;
2660   last_unref = (connection->refcount.value == 0);
2661
2662 #if 0
2663   printf ("unref() connection %p count = %d\n", connection, connection->refcount.value);
2664 #endif
2665   
2666   CONNECTION_UNLOCK (connection);
2667 #endif
2668   
2669   if (last_unref)
2670     {
2671 #ifndef DBUS_DISABLE_CHECKS
2672       if (_dbus_transport_get_is_connected (connection->transport))
2673         {
2674           _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",
2675                                    connection->shareable ?
2676                                    "Most likely, the application called unref() too many times and removed a reference belonging to libdbus, since this is a shared connection.\n" : 
2677                                     "Most likely, the application was supposed to call dbus_connection_close(), since this is a private connection.\n");
2678           return;
2679         }
2680 #endif
2681       _dbus_connection_last_unref (connection);
2682     }
2683 }
2684
2685 /*
2686  * Note that the transport can disconnect itself (other end drops us)
2687  * and in that case this function never runs. So this function must
2688  * not do anything more than disconnect the transport and update the
2689  * dispatch status.
2690  * 
2691  * If the transport self-disconnects, then we assume someone will
2692  * dispatch the connection to cause the dispatch status update.
2693  */
2694 static void
2695 _dbus_connection_close_possibly_shared_and_unlock (DBusConnection *connection)
2696 {
2697   DBusDispatchStatus status;
2698
2699   HAVE_LOCK_CHECK (connection);
2700   
2701   _dbus_verbose ("Disconnecting %p\n", connection);
2702
2703   /* We need to ref because update_dispatch_status_and_unlock will unref
2704    * the connection if it was shared and libdbus was the only remaining
2705    * refcount holder.
2706    */
2707   _dbus_connection_ref_unlocked (connection);
2708   
2709   _dbus_transport_disconnect (connection->transport);
2710
2711   /* This has the side effect of queuing the disconnect message link
2712    * (unless we don't have enough memory, possibly, so don't assert it).
2713    * After the disconnect message link is queued, dbus_bus_get/dbus_connection_open
2714    * should never again return the newly-disconnected connection.
2715    *
2716    * However, we only unref the shared connection and exit_on_disconnect when
2717    * the disconnect message reaches the head of the message queue,
2718    * NOT when it's first queued.
2719    */
2720   status = _dbus_connection_get_dispatch_status_unlocked (connection);
2721
2722   /* This calls out to user code */
2723   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2724
2725   /* Could also call out to user code */
2726   dbus_connection_unref (connection);
2727 }
2728
2729 /**
2730  * Closes a private connection, so no further data can be sent or received.
2731  * This disconnects the transport (such as a socket) underlying the
2732  * connection.
2733  *
2734  * Attempts to send messages after closing a connection are safe, but will result in
2735  * error replies generated locally in libdbus.
2736  * 
2737  * This function does not affect the connection's reference count.  It's
2738  * safe to close a connection more than once; all calls after the
2739  * first do nothing. It's impossible to "reopen" a connection, a
2740  * new connection must be created. This function may result in a call
2741  * to the DBusDispatchStatusFunction set with
2742  * dbus_connection_set_dispatch_status_function(), as the disconnect
2743  * message it generates needs to be dispatched.
2744  *
2745  * If a connection is dropped by the remote application, it will
2746  * close itself. 
2747  * 
2748  * You must close a connection prior to releasing the last reference to
2749  * the connection. If you dbus_connection_unref() for the last time
2750  * without closing the connection, the results are undefined; it
2751  * is a bug in your program and libdbus will try to print a warning.
2752  *
2753  * You may not close a shared connection. Connections created with
2754  * dbus_connection_open() or dbus_bus_get() are shared.
2755  * These connections are owned by libdbus, and applications should
2756  * only unref them, never close them. Applications can know it is
2757  * safe to unref these connections because libdbus will be holding a
2758  * reference as long as the connection is open. Thus, either the
2759  * connection is closed and it is OK to drop the last reference,
2760  * or the connection is open and the app knows it does not have the
2761  * last reference.
2762  *
2763  * Connections created with dbus_connection_open_private() or
2764  * dbus_bus_get_private() are not kept track of or referenced by
2765  * libdbus. The creator of these connections is responsible for
2766  * calling dbus_connection_close() prior to releasing the last
2767  * reference, if the connection is not already disconnected.
2768  *
2769  * @param connection the private (unshared) connection to close
2770  */
2771 void
2772 dbus_connection_close (DBusConnection *connection)
2773 {
2774   _dbus_return_if_fail (connection != NULL);
2775   _dbus_return_if_fail (connection->generation == _dbus_current_generation);
2776
2777   CONNECTION_LOCK (connection);
2778
2779 #ifndef DBUS_DISABLE_CHECKS
2780   if (connection->shareable)
2781     {
2782       CONNECTION_UNLOCK (connection);
2783
2784       _dbus_warn_check_failed ("Applications must not close shared connections - see dbus_connection_close() docs. This is a bug in the application.\n");
2785       return;
2786     }
2787 #endif
2788   
2789   _dbus_connection_close_possibly_shared_and_unlock (connection);
2790 }
2791
2792 static dbus_bool_t
2793 _dbus_connection_get_is_connected_unlocked (DBusConnection *connection)
2794 {
2795   HAVE_LOCK_CHECK (connection);
2796   return _dbus_transport_get_is_connected (connection->transport);
2797 }
2798
2799 /**
2800  * Gets whether the connection is currently open.  A connection may
2801  * become disconnected when the remote application closes its end, or
2802  * exits; a connection may also be disconnected with
2803  * dbus_connection_close().
2804  * 
2805  * There are not separate states for "closed" and "disconnected," the two
2806  * terms are synonymous. This function should really be called
2807  * get_is_open() but for historical reasons is not.
2808  *
2809  * @param connection the connection.
2810  * @returns #TRUE if the connection is still alive.
2811  */
2812 dbus_bool_t
2813 dbus_connection_get_is_connected (DBusConnection *connection)
2814 {
2815   dbus_bool_t res;
2816
2817   _dbus_return_val_if_fail (connection != NULL, FALSE);
2818   
2819   CONNECTION_LOCK (connection);
2820   res = _dbus_connection_get_is_connected_unlocked (connection);
2821   CONNECTION_UNLOCK (connection);
2822   
2823   return res;
2824 }
2825
2826 /**
2827  * Gets whether the connection was authenticated. (Note that
2828  * if the connection was authenticated then disconnected,
2829  * this function still returns #TRUE)
2830  *
2831  * @param connection the connection
2832  * @returns #TRUE if the connection was ever authenticated
2833  */
2834 dbus_bool_t
2835 dbus_connection_get_is_authenticated (DBusConnection *connection)
2836 {
2837   dbus_bool_t res;
2838
2839   _dbus_return_val_if_fail (connection != NULL, FALSE);
2840   
2841   CONNECTION_LOCK (connection);
2842   res = _dbus_transport_get_is_authenticated (connection->transport);
2843   CONNECTION_UNLOCK (connection);
2844   
2845   return res;
2846 }
2847
2848 /**
2849  * Gets whether the connection is not authenticated as a specific
2850  * user.  If the connection is not authenticated, this function
2851  * returns #TRUE, and if it is authenticated but as an anonymous user,
2852  * it returns #TRUE.  If it is authenticated as a specific user, then
2853  * this returns #FALSE. (Note that if the connection was authenticated
2854  * as anonymous then disconnected, this function still returns #TRUE.)
2855  *
2856  * If the connection is not anonymous, you can use
2857  * dbus_connection_get_unix_user() and
2858  * dbus_connection_get_windows_user() to see who it's authorized as.
2859  *
2860  * If you want to prevent non-anonymous authorization, use
2861  * dbus_server_set_auth_mechanisms() to remove the mechanisms that
2862  * allow proving user identity (i.e. only allow the ANONYMOUS
2863  * mechanism).
2864  * 
2865  * @param connection the connection
2866  * @returns #TRUE if not authenticated or authenticated as anonymous 
2867  */
2868 dbus_bool_t
2869 dbus_connection_get_is_anonymous (DBusConnection *connection)
2870 {
2871   dbus_bool_t res;
2872
2873   _dbus_return_val_if_fail (connection != NULL, FALSE);
2874   
2875   CONNECTION_LOCK (connection);
2876   res = _dbus_transport_get_is_anonymous (connection->transport);
2877   CONNECTION_UNLOCK (connection);
2878   
2879   return res;
2880 }
2881
2882 /**
2883  * Gets the ID of the server address we are authenticated to, if this
2884  * connection is on the client side. If the connection is on the
2885  * server side, this will always return #NULL - use dbus_server_get_id()
2886  * to get the ID of your own server, if you are the server side.
2887  * 
2888  * If a client-side connection is not authenticated yet, the ID may be
2889  * available if it was included in the server address, but may not be
2890  * available. The only way to be sure the server ID is available
2891  * is to wait for authentication to complete.
2892  *
2893  * In general, each mode of connecting to a given server will have
2894  * its own ID. So for example, if the session bus daemon is listening
2895  * on UNIX domain sockets and on TCP, then each of those modalities
2896  * will have its own server ID.
2897  *
2898  * If you want an ID that identifies an entire session bus, look at
2899  * dbus_bus_get_id() instead (which is just a convenience wrapper
2900  * around the org.freedesktop.DBus.GetId method invoked on the bus).
2901  *
2902  * You can also get a machine ID; see dbus_get_local_machine_id() to
2903  * get the machine you are on.  There isn't a convenience wrapper, but
2904  * you can invoke org.freedesktop.DBus.Peer.GetMachineId on any peer
2905  * to get the machine ID on the other end.
2906  * 
2907  * The D-Bus specification describes the server ID and other IDs in a
2908  * bit more detail.
2909  *
2910  * @param connection the connection
2911  * @returns the server ID or #NULL if no memory or the connection is server-side
2912  */
2913 char*
2914 dbus_connection_get_server_id (DBusConnection *connection)
2915 {
2916   char *id;
2917
2918   _dbus_return_val_if_fail (connection != NULL, FALSE);
2919   
2920   CONNECTION_LOCK (connection);
2921   id = _dbus_strdup (_dbus_transport_get_server_id (connection->transport));
2922   CONNECTION_UNLOCK (connection);
2923   
2924   return id;
2925 }
2926
2927 /**
2928  * Set whether _exit() should be called when the connection receives a
2929  * disconnect signal. The call to _exit() comes after any handlers for
2930  * the disconnect signal run; handlers can cancel the exit by calling
2931  * this function.
2932  *
2933  * By default, exit_on_disconnect is #FALSE; but for message bus
2934  * connections returned from dbus_bus_get() it will be toggled on
2935  * by default.
2936  *
2937  * @param connection the connection
2938  * @param exit_on_disconnect #TRUE if _exit() should be called after a disconnect signal
2939  */
2940 void
2941 dbus_connection_set_exit_on_disconnect (DBusConnection *connection,
2942                                         dbus_bool_t     exit_on_disconnect)
2943 {
2944   _dbus_return_if_fail (connection != NULL);
2945
2946   CONNECTION_LOCK (connection);
2947   connection->exit_on_disconnect = exit_on_disconnect != FALSE;
2948   CONNECTION_UNLOCK (connection);
2949 }
2950
2951 /**
2952  * Preallocates resources needed to send a message, allowing the message 
2953  * to be sent without the possibility of memory allocation failure.
2954  * Allows apps to create a future guarantee that they can send
2955  * a message regardless of memory shortages.
2956  *
2957  * @param connection the connection we're preallocating for.
2958  * @returns the preallocated resources, or #NULL
2959  */
2960 DBusPreallocatedSend*
2961 dbus_connection_preallocate_send (DBusConnection *connection)
2962 {
2963   DBusPreallocatedSend *preallocated;
2964
2965   _dbus_return_val_if_fail (connection != NULL, NULL);
2966
2967   CONNECTION_LOCK (connection);
2968   
2969   preallocated =
2970     _dbus_connection_preallocate_send_unlocked (connection);
2971
2972   CONNECTION_UNLOCK (connection);
2973
2974   return preallocated;
2975 }
2976
2977 /**
2978  * Frees preallocated message-sending resources from
2979  * dbus_connection_preallocate_send(). Should only
2980  * be called if the preallocated resources are not used
2981  * to send a message.
2982  *
2983  * @param connection the connection
2984  * @param preallocated the resources
2985  */
2986 void
2987 dbus_connection_free_preallocated_send (DBusConnection       *connection,
2988                                         DBusPreallocatedSend *preallocated)
2989 {
2990   _dbus_return_if_fail (connection != NULL);
2991   _dbus_return_if_fail (preallocated != NULL);  
2992   _dbus_return_if_fail (connection == preallocated->connection);
2993
2994   _dbus_list_free_link (preallocated->queue_link);
2995   _dbus_counter_unref (preallocated->counter_link->data);
2996   _dbus_list_free_link (preallocated->counter_link);
2997   dbus_free (preallocated);
2998 }
2999
3000 /**
3001  * Sends a message using preallocated resources. This function cannot fail.
3002  * It works identically to dbus_connection_send() in other respects.
3003  * Preallocated resources comes from dbus_connection_preallocate_send().
3004  * This function "consumes" the preallocated resources, they need not
3005  * be freed separately.
3006  *
3007  * @param connection the connection
3008  * @param preallocated the preallocated resources
3009  * @param message the message to send
3010  * @param client_serial return location for client serial assigned to the message
3011  */
3012 void
3013 dbus_connection_send_preallocated (DBusConnection       *connection,
3014                                    DBusPreallocatedSend *preallocated,
3015                                    DBusMessage          *message,
3016                                    dbus_uint32_t        *client_serial)
3017 {
3018   _dbus_return_if_fail (connection != NULL);
3019   _dbus_return_if_fail (preallocated != NULL);
3020   _dbus_return_if_fail (message != NULL);
3021   _dbus_return_if_fail (preallocated->connection == connection);
3022   _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_METHOD_CALL ||
3023                         dbus_message_get_member (message) != NULL);
3024   _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL ||
3025                         (dbus_message_get_interface (message) != NULL &&
3026                          dbus_message_get_member (message) != NULL));
3027   
3028   CONNECTION_LOCK (connection);
3029   _dbus_connection_send_preallocated_and_unlock (connection,
3030                                                  preallocated,
3031                                                  message, client_serial);
3032 }
3033
3034 static dbus_bool_t
3035 _dbus_connection_send_unlocked_no_update (DBusConnection *connection,
3036                                           DBusMessage    *message,
3037                                           dbus_uint32_t  *client_serial)
3038 {
3039   DBusPreallocatedSend *preallocated;
3040
3041   _dbus_assert (connection != NULL);
3042   _dbus_assert (message != NULL);
3043   
3044   preallocated = _dbus_connection_preallocate_send_unlocked (connection);
3045   if (preallocated == NULL)
3046     return FALSE;
3047
3048   _dbus_connection_send_preallocated_unlocked_no_update (connection,
3049                                                          preallocated,
3050                                                          message,
3051                                                          client_serial);
3052   return TRUE;
3053 }
3054
3055 /**
3056  * Adds a message to the outgoing message queue. Does not block to
3057  * write the message to the network; that happens asynchronously. To
3058  * force the message to be written, call dbus_connection_flush().
3059  * Because this only queues the message, the only reason it can
3060  * fail is lack of memory. Even if the connection is disconnected,
3061  * no error will be returned.
3062  *
3063  * If the function fails due to lack of memory, it returns #FALSE.
3064  * The function will never fail for other reasons; even if the
3065  * connection is disconnected, you can queue an outgoing message,
3066  * though obviously it won't be sent.
3067  *
3068  * The message serial is used by the remote application to send a
3069  * reply; see dbus_message_get_serial() or the D-Bus specification.
3070  * 
3071  * @param connection the connection.
3072  * @param message the message to write.
3073  * @param serial return location for message serial, or #NULL if you don't care
3074  * @returns #TRUE on success.
3075  */
3076 dbus_bool_t
3077 dbus_connection_send (DBusConnection *connection,
3078                       DBusMessage    *message,
3079                       dbus_uint32_t  *serial)
3080 {
3081   _dbus_return_val_if_fail (connection != NULL, FALSE);
3082   _dbus_return_val_if_fail (message != NULL, FALSE);
3083
3084   CONNECTION_LOCK (connection);
3085
3086   return _dbus_connection_send_and_unlock (connection,
3087                                            message,
3088                                            serial);
3089 }
3090
3091 static dbus_bool_t
3092 reply_handler_timeout (void *data)
3093 {
3094   DBusConnection *connection;
3095   DBusDispatchStatus status;
3096   DBusPendingCall *pending = data;
3097
3098   connection = _dbus_pending_call_get_connection_and_lock (pending);
3099
3100   _dbus_pending_call_queue_timeout_error_unlocked (pending, 
3101                                                    connection);
3102   _dbus_connection_remove_timeout_unlocked (connection,
3103                                             _dbus_pending_call_get_timeout_unlocked (pending));
3104   _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
3105
3106   _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
3107   status = _dbus_connection_get_dispatch_status_unlocked (connection);
3108
3109   /* Unlocks, and calls out to user code */
3110   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3111   
3112   return TRUE;
3113 }
3114
3115 /**
3116  * Queues a message to send, as with dbus_connection_send(),
3117  * but also returns a #DBusPendingCall used to receive a reply to the
3118  * message. If no reply is received in the given timeout_milliseconds,
3119  * this function expires the pending reply and generates a synthetic
3120  * error reply (generated in-process, not by the remote application)
3121  * indicating that a timeout occurred.
3122  *
3123  * A #DBusPendingCall will see a reply message before any filters or
3124  * registered object path handlers. See dbus_connection_dispatch() for
3125  * details on when handlers are run.
3126  *
3127  * A #DBusPendingCall will always see exactly one reply message,
3128  * unless it's cancelled with dbus_pending_call_cancel().
3129  * 
3130  * If #NULL is passed for the pending_return, the #DBusPendingCall
3131  * will still be generated internally, and used to track
3132  * the message reply timeout. This means a timeout error will
3133  * occur if no reply arrives, unlike with dbus_connection_send().
3134  *
3135  * If -1 is passed for the timeout, a sane default timeout is used. -1
3136  * is typically the best value for the timeout for this reason, unless
3137  * you want a very short or very long timeout.  There is no way to
3138  * avoid a timeout entirely, other than passing INT_MAX for the
3139  * timeout to mean "very long timeout." libdbus clamps an INT_MAX
3140  * timeout down to a few hours timeout though.
3141  *
3142  * @warning if the connection is disconnected, the #DBusPendingCall
3143  * will be set to #NULL, so be careful with this.
3144  * 
3145  * @param connection the connection
3146  * @param message the message to send
3147  * @param pending_return return location for a #DBusPendingCall object, or #NULL if connection is disconnected
3148  * @param timeout_milliseconds timeout in milliseconds or -1 for default
3149  * @returns #FALSE if no memory, #TRUE otherwise.
3150  *
3151  */
3152 dbus_bool_t
3153 dbus_connection_send_with_reply (DBusConnection     *connection,
3154                                  DBusMessage        *message,
3155                                  DBusPendingCall   **pending_return,
3156                                  int                 timeout_milliseconds)
3157 {
3158   DBusPendingCall *pending;
3159   dbus_int32_t serial = -1;
3160   DBusDispatchStatus status;
3161
3162   _dbus_return_val_if_fail (connection != NULL, FALSE);
3163   _dbus_return_val_if_fail (message != NULL, FALSE);
3164   _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3165
3166   if (pending_return)
3167     *pending_return = NULL;
3168
3169   CONNECTION_LOCK (connection);
3170
3171    if (!_dbus_connection_get_is_connected_unlocked (connection))
3172     {
3173       CONNECTION_UNLOCK (connection);
3174
3175       return TRUE;
3176     }
3177
3178   pending = _dbus_pending_call_new_unlocked (connection,
3179                                              timeout_milliseconds,
3180                                              reply_handler_timeout);
3181
3182   if (pending == NULL)
3183     {
3184       CONNECTION_UNLOCK (connection);
3185       return FALSE;
3186     }
3187
3188   /* Assign a serial to the message */
3189   serial = dbus_message_get_serial (message);
3190   if (serial == 0)
3191     {
3192       serial = _dbus_connection_get_next_client_serial (connection);
3193       _dbus_message_set_serial (message, serial);
3194     }
3195
3196   if (!_dbus_pending_call_set_timeout_error_unlocked (pending, message, serial))
3197     goto error;
3198     
3199   /* Insert the serial in the pending replies hash;
3200    * hash takes a refcount on DBusPendingCall.
3201    * Also, add the timeout.
3202    */
3203   if (!_dbus_connection_attach_pending_call_unlocked (connection,
3204                                                       pending))
3205     goto error;
3206  
3207   if (!_dbus_connection_send_unlocked_no_update (connection, message, NULL))
3208     {
3209       _dbus_connection_detach_pending_call_and_unlock (connection,
3210                                                        pending);
3211       goto error_unlocked;
3212     }
3213
3214   if (pending_return)
3215     *pending_return = pending; /* hand off refcount */
3216   else
3217     {
3218       _dbus_connection_detach_pending_call_unlocked (connection, pending);
3219       /* we still have a ref to the pending call in this case, we unref
3220        * after unlocking, below
3221        */
3222     }
3223
3224   status = _dbus_connection_get_dispatch_status_unlocked (connection);
3225
3226   /* this calls out to user code */
3227   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3228
3229   if (pending_return == NULL)
3230     dbus_pending_call_unref (pending);
3231   
3232   return TRUE;
3233
3234  error:
3235   CONNECTION_UNLOCK (connection);
3236  error_unlocked:
3237   dbus_pending_call_unref (pending);
3238   return FALSE;
3239 }
3240
3241 /**
3242  * Sends a message and blocks a certain time period while waiting for
3243  * a reply.  This function does not reenter the main loop,
3244  * i.e. messages other than the reply are queued up but not
3245  * processed. This function is used to invoke method calls on a
3246  * remote object.
3247  * 
3248  * If a normal reply is received, it is returned, and removed from the
3249  * incoming message queue. If it is not received, #NULL is returned
3250  * and the error is set to #DBUS_ERROR_NO_REPLY.  If an error reply is
3251  * received, it is converted to a #DBusError and returned as an error,
3252  * then the reply message is deleted and #NULL is returned. If
3253  * something else goes wrong, result is set to whatever is
3254  * appropriate, such as #DBUS_ERROR_NO_MEMORY or
3255  * #DBUS_ERROR_DISCONNECTED.
3256  *
3257  * @warning While this function blocks the calling thread will not be
3258  * processing the incoming message queue. This means you can end up
3259  * deadlocked if the application you're talking to needs you to reply
3260  * to a method. To solve this, either avoid the situation, block in a
3261  * separate thread from the main connection-dispatching thread, or use
3262  * dbus_pending_call_set_notify() to avoid blocking.
3263  *
3264  * @param connection the connection
3265  * @param message the message to send
3266  * @param timeout_milliseconds timeout in milliseconds or -1 for default
3267  * @param error return location for error message
3268  * @returns the message that is the reply or #NULL with an error code if the
3269  * function fails.
3270  */
3271 DBusMessage*
3272 dbus_connection_send_with_reply_and_block (DBusConnection     *connection,
3273                                            DBusMessage        *message,
3274                                            int                 timeout_milliseconds,
3275                                            DBusError          *error)
3276 {
3277   DBusMessage *reply;
3278   DBusPendingCall *pending;
3279   
3280   _dbus_return_val_if_fail (connection != NULL, NULL);
3281   _dbus_return_val_if_fail (message != NULL, NULL);
3282   _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, NULL);
3283   _dbus_return_val_if_error_is_set (error, NULL);
3284   
3285   if (!dbus_connection_send_with_reply (connection, message,
3286                                         &pending, timeout_milliseconds))
3287     {
3288       _DBUS_SET_OOM (error);
3289       return NULL;
3290     }
3291
3292   if (pending == NULL)
3293     {
3294       dbus_set_error (error, DBUS_ERROR_DISCONNECTED, "Connection is closed");
3295       return NULL;
3296     }
3297   
3298   dbus_pending_call_block (pending);
3299
3300   reply = dbus_pending_call_steal_reply (pending);
3301   dbus_pending_call_unref (pending);
3302
3303   /* call_complete_and_unlock() called from pending_call_block() should
3304    * always fill this in.
3305    */
3306   _dbus_assert (reply != NULL);
3307   
3308    if (dbus_set_error_from_message (error, reply))
3309     {
3310       dbus_message_unref (reply);
3311       return NULL;
3312     }
3313   else
3314     return reply;
3315 }
3316
3317 /**
3318  * Blocks until the outgoing message queue is empty.
3319  * Assumes connection lock already held.
3320  *
3321  * If you call this, you MUST call update_dispatch_status afterword...
3322  * 
3323  * @param connection the connection.
3324  */
3325 DBusDispatchStatus
3326 _dbus_connection_flush_unlocked (DBusConnection *connection)
3327 {
3328   /* We have to specify DBUS_ITERATION_DO_READING here because
3329    * otherwise we could have two apps deadlock if they are both doing
3330    * a flush(), and the kernel buffers fill up. This could change the
3331    * dispatch status.
3332    */
3333   DBusDispatchStatus status;
3334
3335   HAVE_LOCK_CHECK (connection);
3336   
3337   while (connection->n_outgoing > 0 &&
3338          _dbus_connection_get_is_connected_unlocked (connection))
3339     {
3340       _dbus_verbose ("doing iteration in %s\n", _DBUS_FUNCTION_NAME);
3341       HAVE_LOCK_CHECK (connection);
3342       _dbus_connection_do_iteration_unlocked (connection,
3343                                               DBUS_ITERATION_DO_READING |
3344                                               DBUS_ITERATION_DO_WRITING |
3345                                               DBUS_ITERATION_BLOCK,
3346                                               -1);
3347     }
3348
3349   HAVE_LOCK_CHECK (connection);
3350   _dbus_verbose ("%s middle\n", _DBUS_FUNCTION_NAME);
3351   status = _dbus_connection_get_dispatch_status_unlocked (connection);
3352
3353   HAVE_LOCK_CHECK (connection);
3354   return status;
3355 }
3356
3357 /**
3358  * Blocks until the outgoing message queue is empty.
3359  *
3360  * @param connection the connection.
3361  */
3362 void
3363 dbus_connection_flush (DBusConnection *connection)
3364 {
3365   /* We have to specify DBUS_ITERATION_DO_READING here because
3366    * otherwise we could have two apps deadlock if they are both doing
3367    * a flush(), and the kernel buffers fill up. This could change the
3368    * dispatch status.
3369    */
3370   DBusDispatchStatus status;
3371
3372   _dbus_return_if_fail (connection != NULL);
3373   
3374   CONNECTION_LOCK (connection);
3375
3376   status = _dbus_connection_flush_unlocked (connection);
3377   
3378   HAVE_LOCK_CHECK (connection);
3379   /* Unlocks and calls out to user code */
3380   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3381
3382   _dbus_verbose ("%s end\n", _DBUS_FUNCTION_NAME);
3383 }
3384
3385 /**
3386  * This function implements dbus_connection_read_write_dispatch() and
3387  * dbus_connection_read_write() (they pass a different value for the
3388  * dispatch parameter).
3389  * 
3390  * @param connection the connection
3391  * @param timeout_milliseconds max time to block or -1 for infinite
3392  * @param dispatch dispatch new messages or leave them on the incoming queue
3393  * @returns #TRUE if the disconnect message has not been processed
3394  */
3395 static dbus_bool_t
3396 _dbus_connection_read_write_dispatch (DBusConnection *connection,
3397                                      int             timeout_milliseconds, 
3398                                      dbus_bool_t     dispatch)
3399 {
3400   DBusDispatchStatus dstatus;
3401   dbus_bool_t no_progress_possible;
3402   
3403   dstatus = dbus_connection_get_dispatch_status (connection);
3404
3405   if (dispatch && dstatus == DBUS_DISPATCH_DATA_REMAINS)
3406     {
3407       _dbus_verbose ("doing dispatch in %s\n", _DBUS_FUNCTION_NAME);
3408       dbus_connection_dispatch (connection);
3409       CONNECTION_LOCK (connection);
3410     }
3411   else if (dstatus == DBUS_DISPATCH_NEED_MEMORY)
3412     {
3413       _dbus_verbose ("pausing for memory in %s\n", _DBUS_FUNCTION_NAME);
3414       _dbus_memory_pause_based_on_timeout (timeout_milliseconds);
3415       CONNECTION_LOCK (connection);
3416     }
3417   else
3418     {
3419       CONNECTION_LOCK (connection);
3420       if (_dbus_connection_get_is_connected_unlocked (connection))
3421         {
3422           _dbus_verbose ("doing iteration in %s\n", _DBUS_FUNCTION_NAME);
3423           _dbus_connection_do_iteration_unlocked (connection,
3424                                                   DBUS_ITERATION_DO_READING |
3425                                                   DBUS_ITERATION_DO_WRITING |
3426                                                   DBUS_ITERATION_BLOCK,
3427                                                   timeout_milliseconds);
3428         }
3429     }
3430   
3431   HAVE_LOCK_CHECK (connection);
3432   /* If we can dispatch, we can make progress until the Disconnected message
3433    * has been processed; if we can only read/write, we can make progress
3434    * as long as the transport is open.
3435    */
3436   if (dispatch)
3437     no_progress_possible = connection->n_incoming == 0 &&
3438       connection->disconnect_message_link == NULL;
3439   else
3440     no_progress_possible = _dbus_connection_get_is_connected_unlocked (connection);
3441   CONNECTION_UNLOCK (connection);
3442   return !no_progress_possible; /* TRUE if we can make more progress */
3443 }
3444
3445
3446 /**
3447  * This function is intended for use with applications that don't want
3448  * to write a main loop and deal with #DBusWatch and #DBusTimeout. An
3449  * example usage would be:
3450  * 
3451  * @code
3452  *   while (dbus_connection_read_write_dispatch (connection, -1))
3453  *     ; // empty loop body
3454  * @endcode
3455  * 
3456  * In this usage you would normally have set up a filter function to look
3457  * at each message as it is dispatched. The loop terminates when the last
3458  * message from the connection (the disconnected signal) is processed.
3459  * 
3460  * If there are messages to dispatch, this function will
3461  * dbus_connection_dispatch() once, and return. If there are no
3462  * messages to dispatch, this function will block until it can read or
3463  * write, then read or write, then return.
3464  *
3465  * The way to think of this function is that it either makes some sort
3466  * of progress, or it blocks. Note that, while it is blocked on I/O, it
3467  * cannot be interrupted (even by other threads), which makes this function
3468  * unsuitable for applications that do more than just react to received
3469  * messages.
3470  *
3471  * The return value indicates whether the disconnect message has been
3472  * processed, NOT whether the connection is connected. This is
3473  * important because even after disconnecting, you want to process any
3474  * messages you received prior to the disconnect.
3475  *
3476  * @param connection the connection
3477  * @param timeout_milliseconds max time to block or -1 for infinite
3478  * @returns #TRUE if the disconnect message has not been processed
3479  */
3480 dbus_bool_t
3481 dbus_connection_read_write_dispatch (DBusConnection *connection,
3482                                      int             timeout_milliseconds)
3483 {
3484   _dbus_return_val_if_fail (connection != NULL, FALSE);
3485   _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3486    return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, TRUE);
3487 }
3488
3489 /** 
3490  * This function is intended for use with applications that don't want to
3491  * write a main loop and deal with #DBusWatch and #DBusTimeout. See also
3492  * dbus_connection_read_write_dispatch().
3493  * 
3494  * As long as the connection is open, this function will block until it can
3495  * read or write, then read or write, then return #TRUE.
3496  *
3497  * If the connection is closed, the function returns #FALSE.
3498  *
3499  * The return value indicates whether reading or writing is still
3500  * possible, i.e. whether the connection is connected.
3501  *
3502  * Note that even after disconnection, messages may remain in the
3503  * incoming queue that need to be
3504  * processed. dbus_connection_read_write_dispatch() dispatches
3505  * incoming messages for you; with dbus_connection_read_write() you
3506  * have to arrange to drain the incoming queue yourself.
3507  * 
3508  * @param connection the connection 
3509  * @param timeout_milliseconds max time to block or -1 for infinite 
3510  * @returns #TRUE if still connected
3511  */
3512 dbus_bool_t 
3513 dbus_connection_read_write (DBusConnection *connection, 
3514                             int             timeout_milliseconds) 
3515
3516   _dbus_return_val_if_fail (connection != NULL, FALSE);
3517   _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3518    return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, FALSE);
3519 }
3520
3521 /* We need to call this anytime we pop the head of the queue, and then
3522  * update_dispatch_status_and_unlock needs to be called afterward
3523  * which will "process" the disconnected message and set
3524  * disconnected_message_processed.
3525  */
3526 static void
3527 check_disconnected_message_arrived_unlocked (DBusConnection *connection,
3528                                              DBusMessage    *head_of_queue)
3529 {
3530   HAVE_LOCK_CHECK (connection);
3531
3532   /* checking that the link is NULL is an optimization to avoid the is_signal call */
3533   if (connection->disconnect_message_link == NULL &&
3534       dbus_message_is_signal (head_of_queue,
3535                               DBUS_INTERFACE_LOCAL,
3536                               "Disconnected"))
3537     {
3538       connection->disconnected_message_arrived = TRUE;
3539     }
3540 }
3541
3542 /**
3543  * Returns the first-received message from the incoming message queue,
3544  * leaving it in the queue. If the queue is empty, returns #NULL.
3545  * 
3546  * The caller does not own a reference to the returned message, and
3547  * must either return it using dbus_connection_return_message() or
3548  * keep it after calling dbus_connection_steal_borrowed_message(). No
3549  * one can get at the message while its borrowed, so return it as
3550  * quickly as possible and don't keep a reference to it after
3551  * returning it. If you need to keep the message, make a copy of it.
3552  *
3553  * dbus_connection_dispatch() will block if called while a borrowed
3554  * message is outstanding; only one piece of code can be playing with
3555  * the incoming queue at a time. This function will block if called
3556  * during a dbus_connection_dispatch().
3557  *
3558  * @param connection the connection.
3559  * @returns next message in the incoming queue.
3560  */
3561 DBusMessage*
3562 dbus_connection_borrow_message (DBusConnection *connection)
3563 {
3564   DBusDispatchStatus status;
3565   DBusMessage *message;
3566
3567   _dbus_return_val_if_fail (connection != NULL, NULL);
3568
3569   _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
3570   
3571   /* this is called for the side effect that it queues
3572    * up any messages from the transport
3573    */
3574   status = dbus_connection_get_dispatch_status (connection);
3575   if (status != DBUS_DISPATCH_DATA_REMAINS)
3576     return NULL;
3577   
3578   CONNECTION_LOCK (connection);
3579
3580   _dbus_connection_acquire_dispatch (connection);
3581
3582   /* While a message is outstanding, the dispatch lock is held */
3583   _dbus_assert (connection->message_borrowed == NULL);
3584
3585   connection->message_borrowed = _dbus_list_get_first (&connection->incoming_messages);
3586   
3587   message = connection->message_borrowed;
3588
3589   check_disconnected_message_arrived_unlocked (connection, message);
3590   
3591   /* Note that we KEEP the dispatch lock until the message is returned */
3592   if (message == NULL)
3593     _dbus_connection_release_dispatch (connection);
3594
3595   CONNECTION_UNLOCK (connection);
3596
3597   /* We don't update dispatch status until it's returned or stolen */
3598   
3599   return message;
3600 }
3601
3602 /**
3603  * Used to return a message after peeking at it using
3604  * dbus_connection_borrow_message(). Only called if
3605  * message from dbus_connection_borrow_message() was non-#NULL.
3606  *
3607  * @param connection the connection
3608  * @param message the message from dbus_connection_borrow_message()
3609  */
3610 void
3611 dbus_connection_return_message (DBusConnection *connection,
3612                                 DBusMessage    *message)
3613 {
3614   DBusDispatchStatus status;
3615   
3616   _dbus_return_if_fail (connection != NULL);
3617   _dbus_return_if_fail (message != NULL);
3618   _dbus_return_if_fail (message == connection->message_borrowed);
3619   _dbus_return_if_fail (connection->dispatch_acquired);
3620   
3621   CONNECTION_LOCK (connection);
3622   
3623   _dbus_assert (message == connection->message_borrowed);
3624   
3625   connection->message_borrowed = NULL;
3626
3627   _dbus_connection_release_dispatch (connection); 
3628
3629   status = _dbus_connection_get_dispatch_status_unlocked (connection);
3630   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3631 }
3632
3633 /**
3634  * Used to keep a message after peeking at it using
3635  * dbus_connection_borrow_message(). Before using this function, see
3636  * the caveats/warnings in the documentation for
3637  * dbus_connection_pop_message().
3638  *
3639  * @param connection the connection
3640  * @param message the message from dbus_connection_borrow_message()
3641  */
3642 void
3643 dbus_connection_steal_borrowed_message (DBusConnection *connection,
3644                                         DBusMessage    *message)
3645 {
3646   DBusMessage *pop_message;
3647   DBusDispatchStatus status;
3648
3649   _dbus_return_if_fail (connection != NULL);
3650   _dbus_return_if_fail (message != NULL);
3651   _dbus_return_if_fail (message == connection->message_borrowed);
3652   _dbus_return_if_fail (connection->dispatch_acquired);
3653   
3654   CONNECTION_LOCK (connection);
3655  
3656   _dbus_assert (message == connection->message_borrowed);
3657
3658   pop_message = _dbus_list_pop_first (&connection->incoming_messages);
3659   _dbus_assert (message == pop_message);
3660   
3661   connection->n_incoming -= 1;
3662  
3663   _dbus_verbose ("Incoming message %p stolen from queue, %d incoming\n",
3664                  message, connection->n_incoming);
3665  
3666   connection->message_borrowed = NULL;
3667
3668   _dbus_connection_release_dispatch (connection);
3669
3670   status = _dbus_connection_get_dispatch_status_unlocked (connection);
3671   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3672 }
3673
3674 /* See dbus_connection_pop_message, but requires the caller to own
3675  * the lock before calling. May drop the lock while running.
3676  */
3677 static DBusList*
3678 _dbus_connection_pop_message_link_unlocked (DBusConnection *connection)
3679 {
3680   HAVE_LOCK_CHECK (connection);
3681   
3682   _dbus_assert (connection->message_borrowed == NULL);
3683   
3684   if (connection->n_incoming > 0)
3685     {
3686       DBusList *link;
3687
3688       link = _dbus_list_pop_first_link (&connection->incoming_messages);
3689       connection->n_incoming -= 1;
3690
3691       _dbus_verbose ("Message %p (%d %s %s %s '%s') removed from incoming queue %p, %d incoming\n",
3692                      link->data,
3693                      dbus_message_get_type (link->data),
3694                      dbus_message_get_path (link->data) ?
3695                      dbus_message_get_path (link->data) :
3696                      "no path",
3697                      dbus_message_get_interface (link->data) ?
3698                      dbus_message_get_interface (link->data) :
3699                      "no interface",
3700                      dbus_message_get_member (link->data) ?
3701                      dbus_message_get_member (link->data) :
3702                      "no member",
3703                      dbus_message_get_signature (link->data),
3704                      connection, connection->n_incoming);
3705
3706       check_disconnected_message_arrived_unlocked (connection, link->data);
3707       
3708       return link;
3709     }
3710   else
3711     return NULL;
3712 }
3713
3714 /* See dbus_connection_pop_message, but requires the caller to own
3715  * the lock before calling. May drop the lock while running.
3716  */
3717 static DBusMessage*
3718 _dbus_connection_pop_message_unlocked (DBusConnection *connection)
3719 {
3720   DBusList *link;
3721
3722   HAVE_LOCK_CHECK (connection);
3723   
3724   link = _dbus_connection_pop_message_link_unlocked (connection);
3725
3726   if (link != NULL)
3727     {
3728       DBusMessage *message;
3729       
3730       message = link->data;
3731       
3732       _dbus_list_free_link (link);
3733       
3734       return message;
3735     }
3736   else
3737     return NULL;
3738 }
3739
3740 static void
3741 _dbus_connection_putback_message_link_unlocked (DBusConnection *connection,
3742                                                 DBusList       *message_link)
3743 {
3744   HAVE_LOCK_CHECK (connection);
3745   
3746   _dbus_assert (message_link != NULL);
3747   /* You can't borrow a message while a link is outstanding */
3748   _dbus_assert (connection->message_borrowed == NULL);
3749   /* We had to have the dispatch lock across the pop/putback */
3750   _dbus_assert (connection->dispatch_acquired);
3751
3752   _dbus_list_prepend_link (&connection->incoming_messages,
3753                            message_link);
3754   connection->n_incoming += 1;
3755
3756   _dbus_verbose ("Message %p (%d %s %s '%s') put back into queue %p, %d incoming\n",
3757                  message_link->data,
3758                  dbus_message_get_type (message_link->data),
3759                  dbus_message_get_interface (message_link->data) ?
3760                  dbus_message_get_interface (message_link->data) :
3761                  "no interface",
3762                  dbus_message_get_member (message_link->data) ?
3763                  dbus_message_get_member (message_link->data) :
3764                  "no member",
3765                  dbus_message_get_signature (message_link->data),
3766                  connection, connection->n_incoming);
3767 }
3768
3769 /**
3770  * Returns the first-received message from the incoming message queue,
3771  * removing it from the queue. The caller owns a reference to the
3772  * returned message. If the queue is empty, returns #NULL.
3773  *
3774  * This function bypasses any message handlers that are registered,
3775  * and so using it is usually wrong. Instead, let the main loop invoke
3776  * dbus_connection_dispatch(). Popping messages manually is only
3777  * useful in very simple programs that don't share a #DBusConnection
3778  * with any libraries or other modules.
3779  *
3780  * There is a lock that covers all ways of accessing the incoming message
3781  * queue, so dbus_connection_dispatch(), dbus_connection_pop_message(),
3782  * dbus_connection_borrow_message(), etc. will all block while one of the others
3783  * in the group is running.
3784  * 
3785  * @param connection the connection.
3786  * @returns next message in the incoming queue.
3787  */
3788 DBusMessage*
3789 dbus_connection_pop_message (DBusConnection *connection)
3790 {
3791   DBusMessage *message;
3792   DBusDispatchStatus status;
3793
3794   _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
3795   
3796   /* this is called for the side effect that it queues
3797    * up any messages from the transport
3798    */
3799   status = dbus_connection_get_dispatch_status (connection);
3800   if (status != DBUS_DISPATCH_DATA_REMAINS)
3801     return NULL;
3802   
3803   CONNECTION_LOCK (connection);
3804   _dbus_connection_acquire_dispatch (connection);
3805   HAVE_LOCK_CHECK (connection);
3806   
3807   message = _dbus_connection_pop_message_unlocked (connection);
3808
3809   _dbus_verbose ("Returning popped message %p\n", message);    
3810
3811   _dbus_connection_release_dispatch (connection);
3812
3813   status = _dbus_connection_get_dispatch_status_unlocked (connection);
3814   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3815   
3816   return message;
3817 }
3818
3819 /**
3820  * Acquire the dispatcher. This is a separate lock so the main
3821  * connection lock can be dropped to call out to application dispatch
3822  * handlers.
3823  *
3824  * @param connection the connection.
3825  */
3826 static void
3827 _dbus_connection_acquire_dispatch (DBusConnection *connection)
3828 {
3829   HAVE_LOCK_CHECK (connection);
3830
3831   _dbus_connection_ref_unlocked (connection);
3832   CONNECTION_UNLOCK (connection);
3833   
3834   _dbus_verbose ("%s locking dispatch_mutex\n", _DBUS_FUNCTION_NAME);
3835   _dbus_mutex_lock (connection->dispatch_mutex);
3836
3837   while (connection->dispatch_acquired)
3838     {
3839       _dbus_verbose ("%s waiting for dispatch to be acquirable\n", _DBUS_FUNCTION_NAME);
3840       _dbus_condvar_wait (connection->dispatch_cond, 
3841                           connection->dispatch_mutex);
3842     }
3843   
3844   _dbus_assert (!connection->dispatch_acquired);
3845
3846   connection->dispatch_acquired = TRUE;
3847
3848   _dbus_verbose ("%s unlocking dispatch_mutex\n", _DBUS_FUNCTION_NAME);
3849   _dbus_mutex_unlock (connection->dispatch_mutex);
3850   
3851   CONNECTION_LOCK (connection);
3852   _dbus_connection_unref_unlocked (connection);
3853 }
3854
3855 /**
3856  * Release the dispatcher when you're done with it. Only call
3857  * after you've acquired the dispatcher. Wakes up at most one
3858  * thread currently waiting to acquire the dispatcher.
3859  *
3860  * @param connection the connection.
3861  */
3862 static void
3863 _dbus_connection_release_dispatch (DBusConnection *connection)
3864 {
3865   HAVE_LOCK_CHECK (connection);
3866   
3867   _dbus_verbose ("%s locking dispatch_mutex\n", _DBUS_FUNCTION_NAME);
3868   _dbus_mutex_lock (connection->dispatch_mutex);
3869   
3870   _dbus_assert (connection->dispatch_acquired);
3871
3872   connection->dispatch_acquired = FALSE;
3873   _dbus_condvar_wake_one (connection->dispatch_cond);
3874
3875   _dbus_verbose ("%s unlocking dispatch_mutex\n", _DBUS_FUNCTION_NAME);
3876   _dbus_mutex_unlock (connection->dispatch_mutex);
3877 }
3878
3879 static void
3880 _dbus_connection_failed_pop (DBusConnection *connection,
3881                              DBusList       *message_link)
3882 {
3883   _dbus_list_prepend_link (&connection->incoming_messages,
3884                            message_link);
3885   connection->n_incoming += 1;
3886 }
3887
3888 /* Note this may be called multiple times since we don't track whether we already did it */
3889 static void
3890 notify_disconnected_unlocked (DBusConnection *connection)
3891 {
3892   HAVE_LOCK_CHECK (connection);
3893
3894   /* Set the weakref in dbus-bus.c to NULL, so nobody will get a disconnected
3895    * connection from dbus_bus_get(). We make the same guarantee for
3896    * dbus_connection_open() but in a different way since we don't want to
3897    * unref right here; we instead check for connectedness before returning
3898    * the connection from the hash.
3899    */
3900   _dbus_bus_notify_shared_connection_disconnected_unlocked (connection);
3901
3902   /* Dump the outgoing queue, we aren't going to be able to
3903    * send it now, and we'd like accessors like
3904    * dbus_connection_get_outgoing_size() to be accurate.
3905    */
3906   if (connection->n_outgoing > 0)
3907     {
3908       DBusList *link;
3909       
3910       _dbus_verbose ("Dropping %d outgoing messages since we're disconnected\n",
3911                      connection->n_outgoing);
3912       
3913       while ((link = _dbus_list_get_last_link (&connection->outgoing_messages)))
3914         {
3915           _dbus_connection_message_sent (connection, link->data);
3916         }
3917     } 
3918 }
3919
3920 /* Note this may be called multiple times since we don't track whether we already did it */
3921 static DBusDispatchStatus
3922 notify_disconnected_and_dispatch_complete_unlocked (DBusConnection *connection)
3923 {
3924   HAVE_LOCK_CHECK (connection);
3925   
3926   if (connection->disconnect_message_link != NULL)
3927     {
3928       _dbus_verbose ("Sending disconnect message from %s\n",
3929                      _DBUS_FUNCTION_NAME);
3930       
3931       /* If we have pending calls, queue their timeouts - we want the Disconnected
3932        * to be the last message, after these timeouts.
3933        */
3934       connection_timeout_and_complete_all_pending_calls_unlocked (connection);
3935       
3936       /* We haven't sent the disconnect message already,
3937        * and all real messages have been queued up.
3938        */
3939       _dbus_connection_queue_synthesized_message_link (connection,
3940                                                        connection->disconnect_message_link);
3941       connection->disconnect_message_link = NULL;
3942
3943       return DBUS_DISPATCH_DATA_REMAINS;
3944     }
3945
3946   return DBUS_DISPATCH_COMPLETE;
3947 }
3948
3949 static DBusDispatchStatus
3950 _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection)
3951 {
3952   HAVE_LOCK_CHECK (connection);
3953   
3954   if (connection->n_incoming > 0)
3955     return DBUS_DISPATCH_DATA_REMAINS;
3956   else if (!_dbus_transport_queue_messages (connection->transport))
3957     return DBUS_DISPATCH_NEED_MEMORY;
3958   else
3959     {
3960       DBusDispatchStatus status;
3961       dbus_bool_t is_connected;
3962       
3963       status = _dbus_transport_get_dispatch_status (connection->transport);
3964       is_connected = _dbus_transport_get_is_connected (connection->transport);
3965
3966       _dbus_verbose ("dispatch status = %s is_connected = %d\n",
3967                      DISPATCH_STATUS_NAME (status), is_connected);
3968       
3969       if (!is_connected)
3970         {
3971           /* It's possible this would be better done by having an explicit
3972            * notification from _dbus_transport_disconnect() that would
3973            * synchronously do this, instead of waiting for the next dispatch
3974            * status check. However, probably not good to change until it causes
3975            * a problem.
3976            */
3977           notify_disconnected_unlocked (connection);
3978
3979           /* I'm not sure this is needed; the idea is that we want to
3980            * queue the Disconnected only after we've read all the
3981            * messages, but if we're disconnected maybe we are guaranteed
3982            * to have read them all ?
3983            */
3984           if (status == DBUS_DISPATCH_COMPLETE)
3985             status = notify_disconnected_and_dispatch_complete_unlocked (connection);
3986         }
3987       
3988       if (status != DBUS_DISPATCH_COMPLETE)
3989         return status;
3990       else if (connection->n_incoming > 0)
3991         return DBUS_DISPATCH_DATA_REMAINS;
3992       else
3993         return DBUS_DISPATCH_COMPLETE;
3994     }
3995 }
3996
3997 static void
3998 _dbus_connection_update_dispatch_status_and_unlock (DBusConnection    *connection,
3999                                                     DBusDispatchStatus new_status)
4000 {
4001   dbus_bool_t changed;
4002   DBusDispatchStatusFunction function;
4003   void *data;
4004
4005   HAVE_LOCK_CHECK (connection);
4006
4007   _dbus_connection_ref_unlocked (connection);
4008
4009   changed = new_status != connection->last_dispatch_status;
4010
4011   connection->last_dispatch_status = new_status;
4012
4013   function = connection->dispatch_status_function;
4014   data = connection->dispatch_status_data;
4015
4016   if (connection->disconnected_message_arrived &&
4017       !connection->disconnected_message_processed)
4018     {
4019       connection->disconnected_message_processed = TRUE;
4020       
4021       /* this does an unref, but we have a ref
4022        * so we should not run the finalizer here
4023        * inside the lock.
4024        */
4025       connection_forget_shared_unlocked (connection);
4026
4027       if (connection->exit_on_disconnect)
4028         {
4029           CONNECTION_UNLOCK (connection);            
4030           
4031           _dbus_verbose ("Exiting on Disconnected signal\n");
4032           _dbus_exit (1);
4033           _dbus_assert_not_reached ("Call to exit() returned");
4034         }
4035     }
4036   
4037   /* We drop the lock */
4038   CONNECTION_UNLOCK (connection);
4039   
4040   if (changed && function)
4041     {
4042       _dbus_verbose ("Notifying of change to dispatch status of %p now %d (%s)\n",
4043                      connection, new_status,
4044                      DISPATCH_STATUS_NAME (new_status));
4045       (* function) (connection, new_status, data);      
4046     }
4047   
4048   dbus_connection_unref (connection);
4049 }
4050
4051 /**
4052  * Gets the current state of the incoming message queue.
4053  * #DBUS_DISPATCH_DATA_REMAINS indicates that the message queue
4054  * may contain messages. #DBUS_DISPATCH_COMPLETE indicates that the
4055  * incoming queue is empty. #DBUS_DISPATCH_NEED_MEMORY indicates that
4056  * there could be data, but we can't know for sure without more
4057  * memory.
4058  *
4059  * To process the incoming message queue, use dbus_connection_dispatch()
4060  * or (in rare cases) dbus_connection_pop_message().
4061  *
4062  * Note, #DBUS_DISPATCH_DATA_REMAINS really means that either we
4063  * have messages in the queue, or we have raw bytes buffered up
4064  * that need to be parsed. When these bytes are parsed, they
4065  * may not add up to an entire message. Thus, it's possible
4066  * to see a status of #DBUS_DISPATCH_DATA_REMAINS but not
4067  * have a message yet.
4068  *
4069  * In particular this happens on initial connection, because all sorts
4070  * of authentication protocol stuff has to be parsed before the
4071  * first message arrives.
4072  * 
4073  * @param connection the connection.
4074  * @returns current dispatch status
4075  */
4076 DBusDispatchStatus
4077 dbus_connection_get_dispatch_status (DBusConnection *connection)
4078 {
4079   DBusDispatchStatus status;
4080
4081   _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
4082
4083   _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
4084   
4085   CONNECTION_LOCK (connection);
4086
4087   status = _dbus_connection_get_dispatch_status_unlocked (connection);
4088   
4089   CONNECTION_UNLOCK (connection);
4090
4091   return status;
4092 }
4093
4094 /**
4095  * Filter funtion for handling the Peer standard interface.
4096  */
4097 static DBusHandlerResult
4098 _dbus_connection_peer_filter_unlocked_no_update (DBusConnection *connection,
4099                                                  DBusMessage    *message)
4100 {
4101   if (connection->route_peer_messages && dbus_message_get_destination (message) != NULL)
4102     {
4103       /* This means we're letting the bus route this message */
4104       return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4105     }
4106   else if (dbus_message_is_method_call (message,
4107                                         DBUS_INTERFACE_PEER,
4108                                         "Ping"))
4109     {
4110       DBusMessage *ret;
4111       dbus_bool_t sent;
4112       
4113       ret = dbus_message_new_method_return (message);
4114       if (ret == NULL)
4115         return DBUS_HANDLER_RESULT_NEED_MEMORY;
4116      
4117       sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4118
4119       dbus_message_unref (ret);
4120
4121       if (!sent)
4122         return DBUS_HANDLER_RESULT_NEED_MEMORY;
4123       
4124       return DBUS_HANDLER_RESULT_HANDLED;
4125     }
4126   else if (dbus_message_is_method_call (message,
4127                                         DBUS_INTERFACE_PEER,
4128                                         "GetMachineId"))
4129     {
4130       DBusMessage *ret;
4131       dbus_bool_t sent;
4132       DBusString uuid;
4133       
4134       ret = dbus_message_new_method_return (message);
4135       if (ret == NULL)
4136         return DBUS_HANDLER_RESULT_NEED_MEMORY;
4137
4138       sent = FALSE;
4139       _dbus_string_init (&uuid);
4140       if (_dbus_get_local_machine_uuid_encoded (&uuid))
4141         {
4142           const char *v_STRING = _dbus_string_get_const_data (&uuid);
4143           if (dbus_message_append_args (ret,
4144                                         DBUS_TYPE_STRING, &v_STRING,
4145                                         DBUS_TYPE_INVALID))
4146             {
4147               sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4148             }
4149         }
4150       _dbus_string_free (&uuid);
4151       
4152       dbus_message_unref (ret);
4153
4154       if (!sent)
4155         return DBUS_HANDLER_RESULT_NEED_MEMORY;
4156       
4157       return DBUS_HANDLER_RESULT_HANDLED;
4158     }
4159   else if (dbus_message_has_interface (message, DBUS_INTERFACE_PEER))
4160     {
4161       /* We need to bounce anything else with this interface, otherwise apps
4162        * could start extending the interface and when we added extensions
4163        * here to DBusConnection we'd break those apps.
4164        */
4165       
4166       DBusMessage *ret;
4167       dbus_bool_t sent;
4168       
4169       ret = dbus_message_new_error (message,
4170                                     DBUS_ERROR_UNKNOWN_METHOD,
4171                                     "Unknown method invoked on org.freedesktop.DBus.Peer interface");
4172       if (ret == NULL)
4173         return DBUS_HANDLER_RESULT_NEED_MEMORY;
4174       
4175       sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4176       
4177       dbus_message_unref (ret);
4178       
4179       if (!sent)
4180         return DBUS_HANDLER_RESULT_NEED_MEMORY;
4181       
4182       return DBUS_HANDLER_RESULT_HANDLED;
4183     }
4184   else
4185     {
4186       return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4187     }
4188 }
4189
4190 /**
4191 * Processes all builtin filter functions
4192 *
4193 * If the spec specifies a standard interface
4194 * they should be processed from this method
4195 **/
4196 static DBusHandlerResult
4197 _dbus_connection_run_builtin_filters_unlocked_no_update (DBusConnection *connection,
4198                                                            DBusMessage    *message)
4199 {
4200   /* We just run one filter for now but have the option to run more
4201      if the spec calls for it in the future */
4202
4203   return _dbus_connection_peer_filter_unlocked_no_update (connection, message);
4204 }
4205
4206 /**
4207  * Processes any incoming data.
4208  *
4209  * If there's incoming raw data that has not yet been parsed, it is
4210  * parsed, which may or may not result in adding messages to the
4211  * incoming queue.
4212  *
4213  * The incoming data buffer is filled when the connection reads from
4214  * its underlying transport (such as a socket).  Reading usually
4215  * happens in dbus_watch_handle() or dbus_connection_read_write().
4216  * 
4217  * If there are complete messages in the incoming queue,
4218  * dbus_connection_dispatch() removes one message from the queue and
4219  * processes it. Processing has three steps.
4220  *
4221  * First, any method replies are passed to #DBusPendingCall or
4222  * dbus_connection_send_with_reply_and_block() in order to
4223  * complete the pending method call.
4224  * 
4225  * Second, any filters registered with dbus_connection_add_filter()
4226  * are run. If any filter returns #DBUS_HANDLER_RESULT_HANDLED
4227  * then processing stops after that filter.
4228  *
4229  * Third, if the message is a method call it is forwarded to
4230  * any registered object path handlers added with
4231  * dbus_connection_register_object_path() or
4232  * dbus_connection_register_fallback().
4233  *
4234  * A single call to dbus_connection_dispatch() will process at most
4235  * one message; it will not clear the entire message queue.
4236  *
4237  * Be careful about calling dbus_connection_dispatch() from inside a
4238  * message handler, i.e. calling dbus_connection_dispatch()
4239  * recursively.  If threads have been initialized with a recursive
4240  * mutex function, then this will not deadlock; however, it can
4241  * certainly confuse your application.
4242  * 
4243  * @todo some FIXME in here about handling DBUS_HANDLER_RESULT_NEED_MEMORY
4244  * 
4245  * @param connection the connection
4246  * @returns dispatch status, see dbus_connection_get_dispatch_status()
4247  */
4248 DBusDispatchStatus
4249 dbus_connection_dispatch (DBusConnection *connection)
4250 {
4251   DBusMessage *message;
4252   DBusList *link, *filter_list_copy, *message_link;
4253   DBusHandlerResult result;
4254   DBusPendingCall *pending;
4255   dbus_int32_t reply_serial;
4256   DBusDispatchStatus status;
4257
4258   _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
4259
4260   _dbus_verbose ("%s\n", _DBUS_FUNCTION_NAME);
4261   
4262   CONNECTION_LOCK (connection);
4263   status = _dbus_connection_get_dispatch_status_unlocked (connection);
4264   if (status != DBUS_DISPATCH_DATA_REMAINS)
4265     {
4266       /* unlocks and calls out to user code */
4267       _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4268       return status;
4269     }
4270   
4271   /* We need to ref the connection since the callback could potentially
4272    * drop the last ref to it
4273    */
4274   _dbus_connection_ref_unlocked (connection);
4275
4276   _dbus_connection_acquire_dispatch (connection);
4277   HAVE_LOCK_CHECK (connection);
4278
4279   message_link = _dbus_connection_pop_message_link_unlocked (connection);
4280   if (message_link == NULL)
4281     {
4282       /* another thread dispatched our stuff */
4283
4284       _dbus_verbose ("another thread dispatched message (during acquire_dispatch above)\n");
4285       
4286       _dbus_connection_release_dispatch (connection);
4287
4288       status = _dbus_connection_get_dispatch_status_unlocked (connection);
4289
4290       _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4291       
4292       dbus_connection_unref (connection);
4293       
4294       return status;
4295     }
4296
4297   message = message_link->data;
4298
4299   _dbus_verbose (" dispatching message %p (%d %s %s '%s')\n",
4300                  message,
4301                  dbus_message_get_type (message),
4302                  dbus_message_get_interface (message) ?
4303                  dbus_message_get_interface (message) :
4304                  "no interface",
4305                  dbus_message_get_member (message) ?
4306                  dbus_message_get_member (message) :
4307                  "no member",
4308                  dbus_message_get_signature (message));
4309
4310   result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4311   
4312   /* Pending call handling must be first, because if you do
4313    * dbus_connection_send_with_reply_and_block() or
4314    * dbus_pending_call_block() then no handlers/filters will be run on
4315    * the reply. We want consistent semantics in the case where we
4316    * dbus_connection_dispatch() the reply.
4317    */
4318   
4319   reply_serial = dbus_message_get_reply_serial (message);
4320   pending = _dbus_hash_table_lookup_int (connection->pending_replies,
4321                                          reply_serial);
4322   if (pending)
4323     {
4324       _dbus_verbose ("Dispatching a pending reply\n");
4325       complete_pending_call_and_unlock (connection, pending, message);
4326       pending = NULL; /* it's probably unref'd */
4327       
4328       CONNECTION_LOCK (connection);
4329       _dbus_verbose ("pending call completed in dispatch\n");
4330       result = DBUS_HANDLER_RESULT_HANDLED;
4331       goto out;
4332     }
4333
4334   result = _dbus_connection_run_builtin_filters_unlocked_no_update (connection, message);
4335   if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4336     goto out;
4337  
4338   if (!_dbus_list_copy (&connection->filter_list, &filter_list_copy))
4339     {
4340       _dbus_connection_release_dispatch (connection);
4341       HAVE_LOCK_CHECK (connection);
4342       
4343       _dbus_connection_failed_pop (connection, message_link);
4344
4345       /* unlocks and calls user code */
4346       _dbus_connection_update_dispatch_status_and_unlock (connection,
4347                                                           DBUS_DISPATCH_NEED_MEMORY);
4348
4349       if (pending)
4350         dbus_pending_call_unref (pending);
4351       dbus_connection_unref (connection);
4352       
4353       return DBUS_DISPATCH_NEED_MEMORY;
4354     }
4355   
4356   _dbus_list_foreach (&filter_list_copy,
4357                       (DBusForeachFunction)_dbus_message_filter_ref,
4358                       NULL);
4359
4360   /* We're still protected from dispatch() reentrancy here
4361    * since we acquired the dispatcher
4362    */
4363   CONNECTION_UNLOCK (connection);
4364   
4365   link = _dbus_list_get_first_link (&filter_list_copy);
4366   while (link != NULL)
4367     {
4368       DBusMessageFilter *filter = link->data;
4369       DBusList *next = _dbus_list_get_next_link (&filter_list_copy, link);
4370
4371       if (filter->function == NULL)
4372         {
4373           _dbus_verbose ("  filter was removed in a callback function\n");
4374           link = next;
4375           continue;
4376         }
4377
4378       _dbus_verbose ("  running filter on message %p\n", message);
4379       result = (* filter->function) (connection, message, filter->user_data);
4380
4381       if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4382         break;
4383
4384       link = next;
4385     }
4386
4387   _dbus_list_foreach (&filter_list_copy,
4388                       (DBusForeachFunction)_dbus_message_filter_unref,
4389                       NULL);
4390   _dbus_list_clear (&filter_list_copy);
4391   
4392   CONNECTION_LOCK (connection);
4393
4394   if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
4395     {
4396       _dbus_verbose ("No memory in %s\n", _DBUS_FUNCTION_NAME);
4397       goto out;
4398     }
4399   else if (result == DBUS_HANDLER_RESULT_HANDLED)
4400     {
4401       _dbus_verbose ("filter handled message in dispatch\n");
4402       goto out;
4403     }
4404
4405   /* We're still protected from dispatch() reentrancy here
4406    * since we acquired the dispatcher
4407    */
4408   _dbus_verbose ("  running object path dispatch on message %p (%d %s %s '%s')\n",
4409                  message,
4410                  dbus_message_get_type (message),
4411                  dbus_message_get_interface (message) ?
4412                  dbus_message_get_interface (message) :
4413                  "no interface",
4414                  dbus_message_get_member (message) ?
4415                  dbus_message_get_member (message) :
4416                  "no member",
4417                  dbus_message_get_signature (message));
4418
4419   HAVE_LOCK_CHECK (connection);
4420   result = _dbus_object_tree_dispatch_and_unlock (connection->objects,
4421                                                   message);
4422   
4423   CONNECTION_LOCK (connection);
4424
4425   if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4426     {
4427       _dbus_verbose ("object tree handled message in dispatch\n");
4428       goto out;
4429     }
4430
4431   if (dbus_message_get_type (message) == DBUS_MESSAGE_TYPE_METHOD_CALL)
4432     {
4433       DBusMessage *reply;
4434       DBusString str;
4435       DBusPreallocatedSend *preallocated;
4436
4437       _dbus_verbose ("  sending error %s\n",
4438                      DBUS_ERROR_UNKNOWN_METHOD);
4439       
4440       if (!_dbus_string_init (&str))
4441         {
4442           result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4443           _dbus_verbose ("no memory for error string in dispatch\n");
4444           goto out;
4445         }
4446               
4447       if (!_dbus_string_append_printf (&str,
4448                                        "Method \"%s\" with signature \"%s\" on interface \"%s\" doesn't exist\n",
4449                                        dbus_message_get_member (message),
4450                                        dbus_message_get_signature (message),
4451                                        dbus_message_get_interface (message)))
4452         {
4453           _dbus_string_free (&str);
4454           result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4455           _dbus_verbose ("no memory for error string in dispatch\n");
4456           goto out;
4457         }
4458       
4459       reply = dbus_message_new_error (message,
4460                                       DBUS_ERROR_UNKNOWN_METHOD,
4461                                       _dbus_string_get_const_data (&str));
4462       _dbus_string_free (&str);
4463
4464       if (reply == NULL)
4465         {
4466           result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4467           _dbus_verbose ("no memory for error reply in dispatch\n");
4468           goto out;
4469         }
4470       
4471       preallocated = _dbus_connection_preallocate_send_unlocked (connection);
4472
4473       if (preallocated == NULL)
4474         {
4475           dbus_message_unref (reply);
4476           result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4477           _dbus_verbose ("no memory for error send in dispatch\n");
4478           goto out;
4479         }
4480
4481       _dbus_connection_send_preallocated_unlocked_no_update (connection, preallocated,
4482                                                              reply, NULL);
4483
4484       dbus_message_unref (reply);
4485       
4486       result = DBUS_HANDLER_RESULT_HANDLED;
4487     }
4488   
4489   _dbus_verbose ("  done dispatching %p (%d %s %s '%s') on connection %p\n", message,
4490                  dbus_message_get_type (message),
4491                  dbus_message_get_interface (message) ?
4492                  dbus_message_get_interface (message) :
4493                  "no interface",
4494                  dbus_message_get_member (message) ?
4495                  dbus_message_get_member (message) :
4496                  "no member",
4497                  dbus_message_get_signature (message),
4498                  connection);
4499   
4500  out:
4501   if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
4502     {
4503       _dbus_verbose ("out of memory in %s\n", _DBUS_FUNCTION_NAME);
4504       
4505       /* Put message back, and we'll start over.
4506        * Yes this means handlers must be idempotent if they
4507        * don't return HANDLED; c'est la vie.
4508        */
4509       _dbus_connection_putback_message_link_unlocked (connection,
4510                                                       message_link);
4511     }
4512   else
4513     {
4514       _dbus_verbose (" ... done dispatching in %s\n", _DBUS_FUNCTION_NAME);
4515       
4516       _dbus_list_free_link (message_link);
4517       dbus_message_unref (message); /* don't want the message to count in max message limits
4518                                      * in computing dispatch status below
4519                                      */
4520     }
4521   
4522   _dbus_connection_release_dispatch (connection);
4523   HAVE_LOCK_CHECK (connection);
4524
4525   _dbus_verbose ("%s before final status update\n", _DBUS_FUNCTION_NAME);
4526   status = _dbus_connection_get_dispatch_status_unlocked (connection);
4527
4528   /* unlocks and calls user code */
4529   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4530   
4531   dbus_connection_unref (connection);
4532   
4533   return status;
4534 }
4535
4536 /**
4537  * Sets the watch functions for the connection. These functions are
4538  * responsible for making the application's main loop aware of file
4539  * descriptors that need to be monitored for events, using select() or
4540  * poll(). When using Qt, typically the DBusAddWatchFunction would
4541  * create a QSocketNotifier. When using GLib, the DBusAddWatchFunction
4542  * could call g_io_add_watch(), or could be used as part of a more
4543  * elaborate GSource. Note that when a watch is added, it may
4544  * not be enabled.
4545  *
4546  * The DBusWatchToggledFunction notifies the application that the
4547  * watch has been enabled or disabled. Call dbus_watch_get_enabled()
4548  * to check this. A disabled watch should have no effect, and enabled
4549  * watch should be added to the main loop. This feature is used
4550  * instead of simply adding/removing the watch because
4551  * enabling/disabling can be done without memory allocation.  The
4552  * toggled function may be NULL if a main loop re-queries
4553  * dbus_watch_get_enabled() every time anyway.
4554  * 
4555  * The DBusWatch can be queried for the file descriptor to watch using
4556  * dbus_watch_get_unix_fd() or dbus_watch_get_socket(), and for the
4557  * events to watch for using dbus_watch_get_flags(). The flags
4558  * returned by dbus_watch_get_flags() will only contain
4559  * DBUS_WATCH_READABLE and DBUS_WATCH_WRITABLE, never
4560  * DBUS_WATCH_HANGUP or DBUS_WATCH_ERROR; all watches implicitly
4561  * include a watch for hangups, errors, and other exceptional
4562  * conditions.
4563  *
4564  * Once a file descriptor becomes readable or writable, or an exception
4565  * occurs, dbus_watch_handle() should be called to
4566  * notify the connection of the file descriptor's condition.
4567  *
4568  * dbus_watch_handle() cannot be called during the
4569  * DBusAddWatchFunction, as the connection will not be ready to handle
4570  * that watch yet.
4571  * 
4572  * It is not allowed to reference a DBusWatch after it has been passed
4573  * to remove_function.
4574  *
4575  * If #FALSE is returned due to lack of memory, the failure may be due
4576  * to a #FALSE return from the new add_function. If so, the
4577  * add_function may have been called successfully one or more times,
4578  * but the remove_function will also have been called to remove any
4579  * successful adds. i.e. if #FALSE is returned the net result
4580  * should be that dbus_connection_set_watch_functions() has no effect,
4581  * but the add_function and remove_function may have been called.
4582  *
4583  * @todo We need to drop the lock when we call the
4584  * add/remove/toggled functions which can be a side effect
4585  * of setting the watch functions.
4586  * 
4587  * @param connection the connection.
4588  * @param add_function function to begin monitoring a new descriptor.
4589  * @param remove_function function to stop monitoring a descriptor.
4590  * @param toggled_function function to notify of enable/disable
4591  * @param data data to pass to add_function and remove_function.
4592  * @param free_data_function function to be called to free the data.
4593  * @returns #FALSE on failure (no memory)
4594  */
4595 dbus_bool_t
4596 dbus_connection_set_watch_functions (DBusConnection              *connection,
4597                                      DBusAddWatchFunction         add_function,
4598                                      DBusRemoveWatchFunction      remove_function,
4599                                      DBusWatchToggledFunction     toggled_function,
4600                                      void                        *data,
4601                                      DBusFreeFunction             free_data_function)
4602 {
4603   dbus_bool_t retval;
4604   DBusWatchList *watches;
4605
4606   _dbus_return_val_if_fail (connection != NULL, FALSE);
4607   
4608   CONNECTION_LOCK (connection);
4609
4610 #ifndef DBUS_DISABLE_CHECKS
4611   if (connection->watches == NULL)
4612     {
4613       _dbus_warn_check_failed ("Re-entrant call to %s is not allowed\n",
4614                                _DBUS_FUNCTION_NAME);
4615       return FALSE;
4616     }
4617 #endif
4618   
4619   /* ref connection for slightly better reentrancy */
4620   _dbus_connection_ref_unlocked (connection);
4621
4622   /* This can call back into user code, and we need to drop the
4623    * connection lock when it does. This is kind of a lame
4624    * way to do it.
4625    */
4626   watches = connection->watches;
4627   connection->watches = NULL;
4628   CONNECTION_UNLOCK (connection);
4629
4630   retval = _dbus_watch_list_set_functions (watches,
4631                                            add_function, remove_function,
4632                                            toggled_function,
4633                                            data, free_data_function);
4634   CONNECTION_LOCK (connection);
4635   connection->watches = watches;
4636   
4637   CONNECTION_UNLOCK (connection);
4638   /* drop our paranoid refcount */
4639   dbus_connection_unref (connection);
4640   
4641   return retval;
4642 }
4643
4644 /**
4645  * Sets the timeout functions for the connection. These functions are
4646  * responsible for making the application's main loop aware of timeouts.
4647  * When using Qt, typically the DBusAddTimeoutFunction would create a
4648  * QTimer. When using GLib, the DBusAddTimeoutFunction would call
4649  * g_timeout_add.
4650  * 
4651  * The DBusTimeoutToggledFunction notifies the application that the
4652  * timeout has been enabled or disabled. Call
4653  * dbus_timeout_get_enabled() to check this. A disabled timeout should
4654  * have no effect, and enabled timeout should be added to the main
4655  * loop. This feature is used instead of simply adding/removing the
4656  * timeout because enabling/disabling can be done without memory
4657  * allocation. With Qt, QTimer::start() and QTimer::stop() can be used
4658  * to enable and disable. The toggled function may be NULL if a main
4659  * loop re-queries dbus_timeout_get_enabled() every time anyway.
4660  * Whenever a timeout is toggled, its interval may change.
4661  *
4662  * The DBusTimeout can be queried for the timer interval using
4663  * dbus_timeout_get_interval(). dbus_timeout_handle() should be called
4664  * repeatedly, each time the interval elapses, starting after it has
4665  * elapsed once. The timeout stops firing when it is removed with the
4666  * given remove_function.  The timer interval may change whenever the
4667  * timeout is added, removed, or toggled.
4668  *
4669  * @param connection the connection.
4670  * @param add_function function to add a timeout.
4671  * @param remove_function function to remove a timeout.
4672  * @param toggled_function function to notify of enable/disable
4673  * @param data data to pass to add_function and remove_function.
4674  * @param free_data_function function to be called to free the data.
4675  * @returns #FALSE on failure (no memory)
4676  */
4677 dbus_bool_t
4678 dbus_connection_set_timeout_functions   (DBusConnection            *connection,
4679                                          DBusAddTimeoutFunction     add_function,
4680                                          DBusRemoveTimeoutFunction  remove_function,
4681                                          DBusTimeoutToggledFunction toggled_function,
4682                                          void                      *data,
4683                                          DBusFreeFunction           free_data_function)
4684 {
4685   dbus_bool_t retval;
4686   DBusTimeoutList *timeouts;
4687
4688   _dbus_return_val_if_fail (connection != NULL, FALSE);
4689   
4690   CONNECTION_LOCK (connection);
4691
4692 #ifndef DBUS_DISABLE_CHECKS
4693   if (connection->timeouts == NULL)
4694     {
4695       _dbus_warn_check_failed ("Re-entrant call to %s is not allowed\n",
4696                                _DBUS_FUNCTION_NAME);
4697       return FALSE;
4698     }
4699 #endif
4700   
4701   /* ref connection for slightly better reentrancy */
4702   _dbus_connection_ref_unlocked (connection);
4703
4704   timeouts = connection->timeouts;
4705   connection->timeouts = NULL;
4706   CONNECTION_UNLOCK (connection);
4707   
4708   retval = _dbus_timeout_list_set_functions (timeouts,
4709                                              add_function, remove_function,
4710                                              toggled_function,
4711                                              data, free_data_function);
4712   CONNECTION_LOCK (connection);
4713   connection->timeouts = timeouts;
4714   
4715   CONNECTION_UNLOCK (connection);
4716   /* drop our paranoid refcount */
4717   dbus_connection_unref (connection);
4718
4719   return retval;
4720 }
4721
4722 /**
4723  * Sets the mainloop wakeup function for the connection. This function
4724  * is responsible for waking up the main loop (if its sleeping in
4725  * another thread) when some some change has happened to the
4726  * connection that the mainloop needs to reconsider (e.g. a message
4727  * has been queued for writing).  When using Qt, this typically
4728  * results in a call to QEventLoop::wakeUp().  When using GLib, it
4729  * would call g_main_context_wakeup().
4730  *
4731  * @param connection the connection.
4732  * @param wakeup_main_function function to wake up the mainloop
4733  * @param data data to pass wakeup_main_function
4734  * @param free_data_function function to be called to free the data.
4735  */
4736 void
4737 dbus_connection_set_wakeup_main_function (DBusConnection            *connection,
4738                                           DBusWakeupMainFunction     wakeup_main_function,
4739                                           void                      *data,
4740                                           DBusFreeFunction           free_data_function)
4741 {
4742   void *old_data;
4743   DBusFreeFunction old_free_data;
4744
4745   _dbus_return_if_fail (connection != NULL);
4746   
4747   CONNECTION_LOCK (connection);
4748   old_data = connection->wakeup_main_data;
4749   old_free_data = connection->free_wakeup_main_data;
4750
4751   connection->wakeup_main_function = wakeup_main_function;
4752   connection->wakeup_main_data = data;
4753   connection->free_wakeup_main_data = free_data_function;
4754   
4755   CONNECTION_UNLOCK (connection);
4756
4757   /* Callback outside the lock */
4758   if (old_free_data)
4759     (*old_free_data) (old_data);
4760 }
4761
4762 /**
4763  * Set a function to be invoked when the dispatch status changes.
4764  * If the dispatch status is #DBUS_DISPATCH_DATA_REMAINS, then
4765  * dbus_connection_dispatch() needs to be called to process incoming
4766  * messages. However, dbus_connection_dispatch() MUST NOT BE CALLED
4767  * from inside the DBusDispatchStatusFunction. Indeed, almost
4768  * any reentrancy in this function is a bad idea. Instead,
4769  * the DBusDispatchStatusFunction should simply save an indication
4770  * that messages should be dispatched later, when the main loop
4771  * is re-entered.
4772  *
4773  * If you don't set a dispatch status function, you have to be sure to
4774  * dispatch on every iteration of your main loop, especially if
4775  * dbus_watch_handle() or dbus_timeout_handle() were called.
4776  *
4777  * @param connection the connection
4778  * @param function function to call on dispatch status changes
4779  * @param data data for function
4780  * @param free_data_function free the function data
4781  */
4782 void
4783 dbus_connection_set_dispatch_status_function (DBusConnection             *connection,
4784                                               DBusDispatchStatusFunction  function,
4785                                               void                       *data,
4786                                               DBusFreeFunction            free_data_function)
4787 {
4788   void *old_data;
4789   DBusFreeFunction old_free_data;
4790
4791   _dbus_return_if_fail (connection != NULL);
4792   
4793   CONNECTION_LOCK (connection);
4794   old_data = connection->dispatch_status_data;
4795   old_free_data = connection->free_dispatch_status_data;
4796
4797   connection->dispatch_status_function = function;
4798   connection->dispatch_status_data = data;
4799   connection->free_dispatch_status_data = free_data_function;
4800   
4801   CONNECTION_UNLOCK (connection);
4802
4803   /* Callback outside the lock */
4804   if (old_free_data)
4805     (*old_free_data) (old_data);
4806 }
4807
4808 /**
4809  * Get the UNIX file descriptor of the connection, if any.  This can
4810  * be used for SELinux access control checks with getpeercon() for
4811  * example. DO NOT read or write to the file descriptor, or try to
4812  * select() on it; use DBusWatch for main loop integration. Not all
4813  * connections will have a file descriptor. So for adding descriptors
4814  * to the main loop, use dbus_watch_get_unix_fd() and so forth.
4815  *
4816  * If the connection is socket-based, you can also use
4817  * dbus_connection_get_socket(), which will work on Windows too.
4818  * This function always fails on Windows.
4819  *
4820  * Right now the returned descriptor is always a socket, but
4821  * that is not guaranteed.
4822  * 
4823  * @param connection the connection
4824  * @param fd return location for the file descriptor.
4825  * @returns #TRUE if fd is successfully obtained.
4826  */
4827 dbus_bool_t
4828 dbus_connection_get_unix_fd (DBusConnection *connection,
4829                              int            *fd)
4830 {
4831   _dbus_return_val_if_fail (connection != NULL, FALSE);
4832   _dbus_return_val_if_fail (connection->transport != NULL, FALSE);
4833
4834 #ifdef DBUS_WIN
4835   /* FIXME do this on a lower level */
4836   return FALSE;
4837 #endif
4838   
4839   return dbus_connection_get_socket(connection, fd);
4840 }
4841
4842 /**
4843  * Gets the underlying Windows or UNIX socket file descriptor
4844  * of the connection, if any. DO NOT read or write to the file descriptor, or try to
4845  * select() on it; use DBusWatch for main loop integration. Not all
4846  * connections will have a socket. So for adding descriptors
4847  * to the main loop, use dbus_watch_get_socket() and so forth.
4848  *
4849  * If the connection is not socket-based, this function will return FALSE,
4850  * even if the connection does have a file descriptor of some kind.
4851  * i.e. this function always returns specifically a socket file descriptor.
4852  * 
4853  * @param connection the connection
4854  * @param fd return location for the file descriptor.
4855  * @returns #TRUE if fd is successfully obtained.
4856  */
4857 dbus_bool_t
4858 dbus_connection_get_socket(DBusConnection              *connection,
4859                            int                         *fd)
4860 {
4861   dbus_bool_t retval;
4862
4863   _dbus_return_val_if_fail (connection != NULL, FALSE);
4864   _dbus_return_val_if_fail (connection->transport != NULL, FALSE);
4865   
4866   CONNECTION_LOCK (connection);
4867   
4868   retval = _dbus_transport_get_socket_fd (connection->transport,
4869                                           fd);
4870
4871   CONNECTION_UNLOCK (connection);
4872
4873   return retval;
4874 }
4875
4876
4877 /**
4878  * Gets the UNIX user ID of the connection if known.  Returns #TRUE if
4879  * the uid is filled in.  Always returns #FALSE on non-UNIX platforms
4880  * for now, though in theory someone could hook Windows to NIS or
4881  * something.  Always returns #FALSE prior to authenticating the
4882  * connection.
4883  *
4884  * The UID is only read by servers from clients; clients can't usually
4885  * get the UID of servers, because servers do not authenticate to
4886  * clients.  The returned UID is the UID the connection authenticated
4887  * as.
4888  *
4889  * The message bus is a server and the apps connecting to the bus
4890  * are clients.
4891  *
4892  * You can ask the bus to tell you the UID of another connection though
4893  * if you like; this is done with dbus_bus_get_unix_user().
4894  *
4895  * @param connection the connection
4896  * @param uid return location for the user ID
4897  * @returns #TRUE if uid is filled in with a valid user ID
4898  */
4899 dbus_bool_t
4900 dbus_connection_get_unix_user (DBusConnection *connection,
4901                                unsigned long  *uid)
4902 {
4903   dbus_bool_t result;
4904
4905   _dbus_return_val_if_fail (connection != NULL, FALSE);
4906   _dbus_return_val_if_fail (uid != NULL, FALSE);
4907   
4908   CONNECTION_LOCK (connection);
4909
4910   if (!_dbus_transport_get_is_authenticated (connection->transport))
4911     result = FALSE;
4912   else
4913     result = _dbus_transport_get_unix_user (connection->transport,
4914                                             uid);
4915
4916 #ifdef DBUS_WIN
4917   _dbus_assert (!result);
4918 #endif
4919   
4920   CONNECTION_UNLOCK (connection);
4921
4922   return result;
4923 }
4924
4925 /**
4926  * Gets the process ID of the connection if any.
4927  * Returns #TRUE if the pid is filled in.
4928  * Always returns #FALSE prior to authenticating the
4929  * connection.
4930  *
4931  * @param connection the connection
4932  * @param pid return location for the process ID
4933  * @returns #TRUE if uid is filled in with a valid process ID
4934  */
4935 dbus_bool_t
4936 dbus_connection_get_unix_process_id (DBusConnection *connection,
4937                                      unsigned long  *pid)
4938 {
4939   dbus_bool_t result;
4940
4941   _dbus_return_val_if_fail (connection != NULL, FALSE);
4942   _dbus_return_val_if_fail (pid != NULL, FALSE);
4943   
4944   CONNECTION_LOCK (connection);
4945
4946   if (!_dbus_transport_get_is_authenticated (connection->transport))
4947     result = FALSE;
4948   else
4949     result = _dbus_transport_get_unix_process_id (connection->transport,
4950                                                   pid);
4951 #ifdef DBUS_WIN
4952   _dbus_assert (!result);
4953 #endif
4954   
4955   CONNECTION_UNLOCK (connection);
4956
4957   return result;
4958 }
4959
4960 /**
4961  * Sets a predicate function used to determine whether a given user ID
4962  * is allowed to connect. When an incoming connection has
4963  * authenticated with a particular user ID, this function is called;
4964  * if it returns #TRUE, the connection is allowed to proceed,
4965  * otherwise the connection is disconnected.
4966  *
4967  * If the function is set to #NULL (as it is by default), then
4968  * only the same UID as the server process will be allowed to
4969  * connect. Also, root is always allowed to connect.
4970  *
4971  * On Windows, the function will be set and its free_data_function will
4972  * be invoked when the connection is freed or a new function is set.
4973  * However, the function will never be called, because there are
4974  * no UNIX user ids to pass to it, or at least none of the existing
4975  * auth protocols would allow authenticating as a UNIX user on Windows.
4976  * 
4977  * @param connection the connection
4978  * @param function the predicate
4979  * @param data data to pass to the predicate
4980  * @param free_data_function function to free the data
4981  */
4982 void
4983 dbus_connection_set_unix_user_function (DBusConnection             *connection,
4984                                         DBusAllowUnixUserFunction   function,
4985                                         void                       *data,
4986                                         DBusFreeFunction            free_data_function)
4987 {
4988   void *old_data = NULL;
4989   DBusFreeFunction old_free_function = NULL;
4990
4991   _dbus_return_if_fail (connection != NULL);
4992   
4993   CONNECTION_LOCK (connection);
4994   _dbus_transport_set_unix_user_function (connection->transport,
4995                                           function, data, free_data_function,
4996                                           &old_data, &old_free_function);
4997   CONNECTION_UNLOCK (connection);
4998
4999   if (old_free_function != NULL)
5000     (* old_free_function) (old_data);
5001 }
5002
5003 /**
5004  * Gets the Windows user SID of the connection if known.  Returns
5005  * #TRUE if the ID is filled in.  Always returns #FALSE on non-Windows
5006  * platforms for now, though in theory someone could hook UNIX to
5007  * Active Directory or something.  Always returns #FALSE prior to
5008  * authenticating the connection.
5009  *
5010  * The user is only read by servers from clients; clients can't usually
5011  * get the user of servers, because servers do not authenticate to
5012  * clients. The returned user is the user the connection authenticated
5013  * as.
5014  *
5015  * The message bus is a server and the apps connecting to the bus
5016  * are clients.
5017  *
5018  * The returned user string has to be freed with dbus_free().
5019  *
5020  * The return value indicates whether the user SID is available;
5021  * if it's available but we don't have the memory to copy it,
5022  * then the return value is #TRUE and #NULL is given as the SID.
5023  * 
5024  * @todo We would like to be able to say "You can ask the bus to tell
5025  * you the user of another connection though if you like; this is done
5026  * with dbus_bus_get_windows_user()." But this has to be implemented
5027  * in bus/driver.c and dbus/dbus-bus.c, and is pointless anyway
5028  * since on Windows we only use the session bus for now.
5029  *
5030  * @param connection the connection
5031  * @param windows_sid_p return location for an allocated copy of the user ID, or #NULL if no memory
5032  * @returns #TRUE if user is available (returned value may be #NULL anyway if no memory)
5033  */
5034 dbus_bool_t
5035 dbus_connection_get_windows_user (DBusConnection             *connection,
5036                                   char                      **windows_sid_p)
5037 {
5038   dbus_bool_t result;
5039
5040   _dbus_return_val_if_fail (connection != NULL, FALSE);
5041   _dbus_return_val_if_fail (windows_sid_p != NULL, FALSE);
5042   
5043   CONNECTION_LOCK (connection);
5044
5045   if (!_dbus_transport_get_is_authenticated (connection->transport))
5046     result = FALSE;
5047   else
5048     result = _dbus_transport_get_windows_user (connection->transport,
5049                                                windows_sid_p);
5050
5051 #ifdef DBUS_UNIX
5052   _dbus_assert (!result);
5053 #endif
5054   
5055   CONNECTION_UNLOCK (connection);
5056
5057   return result;
5058 }
5059
5060 /**
5061  * Sets a predicate function used to determine whether a given user ID
5062  * is allowed to connect. When an incoming connection has
5063  * authenticated with a particular user ID, this function is called;
5064  * if it returns #TRUE, the connection is allowed to proceed,
5065  * otherwise the connection is disconnected.
5066  *
5067  * If the function is set to #NULL (as it is by default), then
5068  * only the same user owning the server process will be allowed to
5069  * connect.
5070  *
5071  * On UNIX, the function will be set and its free_data_function will
5072  * be invoked when the connection is freed or a new function is set.
5073  * However, the function will never be called, because there is no
5074  * way right now to authenticate as a Windows user on UNIX.
5075  * 
5076  * @param connection the connection
5077  * @param function the predicate
5078  * @param data data to pass to the predicate
5079  * @param free_data_function function to free the data
5080  */
5081 void
5082 dbus_connection_set_windows_user_function (DBusConnection              *connection,
5083                                            DBusAllowWindowsUserFunction function,
5084                                            void                        *data,
5085                                            DBusFreeFunction             free_data_function)
5086 {
5087   void *old_data = NULL;
5088   DBusFreeFunction old_free_function = NULL;
5089
5090   _dbus_return_if_fail (connection != NULL);
5091   
5092   CONNECTION_LOCK (connection);
5093   _dbus_transport_set_windows_user_function (connection->transport,
5094                                              function, data, free_data_function,
5095                                              &old_data, &old_free_function);
5096   CONNECTION_UNLOCK (connection);
5097
5098   if (old_free_function != NULL)
5099     (* old_free_function) (old_data);
5100 }
5101
5102 /**
5103  * This function must be called on the server side of a connection when the
5104  * connection is first seen in the #DBusNewConnectionFunction. If set to
5105  * #TRUE (the default is #FALSE), then the connection can proceed even if
5106  * the client does not authenticate as some user identity, i.e. clients
5107  * can connect anonymously.
5108  * 
5109  * This setting interacts with the available authorization mechanisms
5110  * (see dbus_server_set_auth_mechanisms()). Namely, an auth mechanism
5111  * such as ANONYMOUS that supports anonymous auth must be included in
5112  * the list of available mechanisms for anonymous login to work.
5113  *
5114  * This setting also changes the default rule for connections
5115  * authorized as a user; normally, if a connection authorizes as
5116  * a user identity, it is permitted if the user identity is
5117  * root or the user identity matches the user identity of the server
5118  * process. If anonymous connections are allowed, however,
5119  * then any user identity is allowed.
5120  *
5121  * You can override the rules for connections authorized as a
5122  * user identity with dbus_connection_set_unix_user_function()
5123  * and dbus_connection_set_windows_user_function().
5124  * 
5125  * @param connection the connection
5126  * @param value whether to allow authentication as an anonymous user
5127  */
5128 void
5129 dbus_connection_set_allow_anonymous (DBusConnection             *connection,
5130                                      dbus_bool_t                 value)
5131 {
5132   _dbus_return_if_fail (connection != NULL);
5133   
5134   CONNECTION_LOCK (connection);
5135   _dbus_transport_set_allow_anonymous (connection->transport, value);
5136   CONNECTION_UNLOCK (connection);
5137 }
5138
5139 /**
5140  *
5141  * Normally #DBusConnection automatically handles all messages to the
5142  * org.freedesktop.DBus.Peer interface. However, the message bus wants
5143  * to be able to route methods on that interface through the bus and
5144  * to other applications. If routing peer messages is enabled, then
5145  * messages with the org.freedesktop.DBus.Peer interface that also
5146  * have a bus destination name set will not be automatically
5147  * handled by the #DBusConnection and instead will be dispatched
5148  * normally to the application.
5149  *
5150  * If a normal application sets this flag, it can break things badly.
5151  * So don't set this unless you are the message bus.
5152  *
5153  * @param connection the connection
5154  * @param value #TRUE to pass through org.freedesktop.DBus.Peer messages with a bus name set
5155  */
5156 void
5157 dbus_connection_set_route_peer_messages (DBusConnection             *connection,
5158                                          dbus_bool_t                 value)
5159 {
5160   _dbus_return_if_fail (connection != NULL);
5161   
5162   CONNECTION_LOCK (connection);
5163   connection->route_peer_messages = TRUE;
5164   CONNECTION_UNLOCK (connection);
5165 }
5166
5167 /**
5168  * Adds a message filter. Filters are handlers that are run on all
5169  * incoming messages, prior to the objects registered with
5170  * dbus_connection_register_object_path().  Filters are run in the
5171  * order that they were added.  The same handler can be added as a
5172  * filter more than once, in which case it will be run more than once.
5173  * Filters added during a filter callback won't be run on the message
5174  * being processed.
5175  *
5176  * @todo we don't run filters on messages while blocking without
5177  * entering the main loop, since filters are run as part of
5178  * dbus_connection_dispatch(). This is probably a feature, as filters
5179  * could create arbitrary reentrancy. But kind of sucks if you're
5180  * trying to filter METHOD_RETURN for some reason.
5181  *
5182  * @param connection the connection
5183  * @param function function to handle messages
5184  * @param user_data user data to pass to the function
5185  * @param free_data_function function to use for freeing user data
5186  * @returns #TRUE on success, #FALSE if not enough memory.
5187  */
5188 dbus_bool_t
5189 dbus_connection_add_filter (DBusConnection            *connection,
5190                             DBusHandleMessageFunction  function,
5191                             void                      *user_data,
5192                             DBusFreeFunction           free_data_function)
5193 {
5194   DBusMessageFilter *filter;
5195   
5196   _dbus_return_val_if_fail (connection != NULL, FALSE);
5197   _dbus_return_val_if_fail (function != NULL, FALSE);
5198
5199   filter = dbus_new0 (DBusMessageFilter, 1);
5200   if (filter == NULL)
5201     return FALSE;
5202
5203   filter->refcount.value = 1;
5204   
5205   CONNECTION_LOCK (connection);
5206
5207   if (!_dbus_list_append (&connection->filter_list,
5208                           filter))
5209     {
5210       _dbus_message_filter_unref (filter);
5211       CONNECTION_UNLOCK (connection);
5212       return FALSE;
5213     }
5214
5215   /* Fill in filter after all memory allocated,
5216    * so we don't run the free_user_data_function
5217    * if the add_filter() fails
5218    */
5219   
5220   filter->function = function;
5221   filter->user_data = user_data;
5222   filter->free_user_data_function = free_data_function;
5223         
5224   CONNECTION_UNLOCK (connection);
5225   return TRUE;
5226 }
5227
5228 /**
5229  * Removes a previously-added message filter. It is a programming
5230  * error to call this function for a handler that has not been added
5231  * as a filter. If the given handler was added more than once, only
5232  * one instance of it will be removed (the most recently-added
5233  * instance).
5234  *
5235  * @param connection the connection
5236  * @param function the handler to remove
5237  * @param user_data user data for the handler to remove
5238  *
5239  */
5240 void
5241 dbus_connection_remove_filter (DBusConnection            *connection,
5242                                DBusHandleMessageFunction  function,
5243                                void                      *user_data)
5244 {
5245   DBusList *link;
5246   DBusMessageFilter *filter;
5247   
5248   _dbus_return_if_fail (connection != NULL);
5249   _dbus_return_if_fail (function != NULL);
5250   
5251   CONNECTION_LOCK (connection);
5252
5253   filter = NULL;
5254   
5255   link = _dbus_list_get_last_link (&connection->filter_list);
5256   while (link != NULL)
5257     {
5258       filter = link->data;
5259
5260       if (filter->function == function &&
5261           filter->user_data == user_data)
5262         {
5263           _dbus_list_remove_link (&connection->filter_list, link);
5264           filter->function = NULL;
5265           
5266           break;
5267         }
5268         
5269       link = _dbus_list_get_prev_link (&connection->filter_list, link);
5270     }
5271   
5272   CONNECTION_UNLOCK (connection);
5273
5274 #ifndef DBUS_DISABLE_CHECKS
5275   if (filter == NULL)
5276     {
5277       _dbus_warn_check_failed ("Attempt to remove filter function %p user data %p, but no such filter has been added\n",
5278                                function, user_data);
5279       return;
5280     }
5281 #endif
5282   
5283   /* Call application code */
5284   if (filter->free_user_data_function)
5285     (* filter->free_user_data_function) (filter->user_data);
5286
5287   filter->free_user_data_function = NULL;
5288   filter->user_data = NULL;
5289   
5290   _dbus_message_filter_unref (filter);
5291 }
5292
5293 /**
5294  * Registers a handler for a given path in the object hierarchy.
5295  * The given vtable handles messages sent to exactly the given path.
5296  *
5297  * @param connection the connection
5298  * @param path a '/' delimited string of path elements
5299  * @param vtable the virtual table
5300  * @param user_data data to pass to functions in the vtable
5301  * @param error address where an error can be returned
5302  * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5303  *    #DBUS_ERROR_ADDRESS_IN_USE) is reported
5304  */
5305 dbus_bool_t
5306 dbus_connection_try_register_object_path (DBusConnection              *connection,
5307                                           const char                  *path,
5308                                           const DBusObjectPathVTable  *vtable,
5309                                           void                        *user_data,
5310                                           DBusError                   *error)
5311 {
5312   char **decomposed_path;
5313   dbus_bool_t retval;
5314   
5315   _dbus_return_val_if_fail (connection != NULL, FALSE);
5316   _dbus_return_val_if_fail (path != NULL, FALSE);
5317   _dbus_return_val_if_fail (path[0] == '/', FALSE);
5318   _dbus_return_val_if_fail (vtable != NULL, FALSE);
5319
5320   if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5321     return FALSE;
5322
5323   CONNECTION_LOCK (connection);
5324
5325   retval = _dbus_object_tree_register (connection->objects,
5326                                        FALSE,
5327                                        (const char **) decomposed_path, vtable,
5328                                        user_data, error);
5329
5330   CONNECTION_UNLOCK (connection);
5331
5332   dbus_free_string_array (decomposed_path);
5333
5334   return retval;
5335 }
5336
5337 /**
5338  * Registers a handler for a given path in the object hierarchy.
5339  * The given vtable handles messages sent to exactly the given path.
5340  *
5341  * It is a bug to call this function for object paths which already
5342  * have a handler. Use dbus_connection_try_register_object_path() if this
5343  * might be the case.
5344  *
5345  * @param connection the connection
5346  * @param path a '/' delimited string of path elements
5347  * @param vtable the virtual table
5348  * @param user_data data to pass to functions in the vtable
5349  * @returns #FALSE if not enough memory
5350  */
5351 dbus_bool_t
5352 dbus_connection_register_object_path (DBusConnection              *connection,
5353                                       const char                  *path,
5354                                       const DBusObjectPathVTable  *vtable,
5355                                       void                        *user_data)
5356 {
5357   char **decomposed_path;
5358   dbus_bool_t retval;
5359   DBusError error = DBUS_ERROR_INIT;
5360
5361   _dbus_return_val_if_fail (connection != NULL, FALSE);
5362   _dbus_return_val_if_fail (path != NULL, FALSE);
5363   _dbus_return_val_if_fail (path[0] == '/', FALSE);
5364   _dbus_return_val_if_fail (vtable != NULL, FALSE);
5365
5366   if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5367     return FALSE;
5368
5369   CONNECTION_LOCK (connection);
5370
5371   retval = _dbus_object_tree_register (connection->objects,
5372                                        FALSE,
5373                                        (const char **) decomposed_path, vtable,
5374                                        user_data, &error);
5375
5376   CONNECTION_UNLOCK (connection);
5377
5378   dbus_free_string_array (decomposed_path);
5379
5380   if (dbus_error_has_name (&error, DBUS_ERROR_ADDRESS_IN_USE))
5381     {
5382       _dbus_warn ("%s\n", error.message);
5383       dbus_error_free (&error);
5384       return FALSE;
5385     }
5386
5387   return retval;
5388 }
5389
5390 /**
5391  * Registers a fallback handler for a given subsection of the object
5392  * hierarchy.  The given vtable handles messages at or below the given
5393  * path. You can use this to establish a default message handling
5394  * policy for a whole "subdirectory."
5395  *
5396  * @param connection the connection
5397  * @param path a '/' delimited string of path elements
5398  * @param vtable the virtual table
5399  * @param user_data data to pass to functions in the vtable
5400  * @param error address where an error can be returned
5401  * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5402  *    #DBUS_ERROR_ADDRESS_IN_USE) is reported
5403  */
5404 dbus_bool_t
5405 dbus_connection_try_register_fallback (DBusConnection              *connection,
5406                                        const char                  *path,
5407                                        const DBusObjectPathVTable  *vtable,
5408                                        void                        *user_data,
5409                                        DBusError                   *error)
5410 {
5411   char **decomposed_path;
5412   dbus_bool_t retval;
5413
5414   _dbus_return_val_if_fail (connection != NULL, FALSE);
5415   _dbus_return_val_if_fail (path != NULL, FALSE);
5416   _dbus_return_val_if_fail (path[0] == '/', FALSE);
5417   _dbus_return_val_if_fail (vtable != NULL, FALSE);
5418
5419   if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5420     return FALSE;
5421
5422   CONNECTION_LOCK (connection);
5423
5424   retval = _dbus_object_tree_register (connection->objects,
5425                                        TRUE,
5426                                        (const char **) decomposed_path, vtable,
5427                                        user_data, error);
5428
5429   CONNECTION_UNLOCK (connection);
5430
5431   dbus_free_string_array (decomposed_path);
5432
5433   return retval;
5434 }
5435
5436 /**
5437  * Registers a fallback handler for a given subsection of the object
5438  * hierarchy.  The given vtable handles messages at or below the given
5439  * path. You can use this to establish a default message handling
5440  * policy for a whole "subdirectory."
5441  *
5442  * It is a bug to call this function for object paths which already
5443  * have a handler. Use dbus_connection_try_register_fallback() if this
5444  * might be the case.
5445  *
5446  * @param connection the connection
5447  * @param path a '/' delimited string of path elements
5448  * @param vtable the virtual table
5449  * @param user_data data to pass to functions in the vtable
5450  * @returns #FALSE if not enough memory
5451  */
5452 dbus_bool_t
5453 dbus_connection_register_fallback (DBusConnection              *connection,
5454                                    const char                  *path,
5455                                    const DBusObjectPathVTable  *vtable,
5456                                    void                        *user_data)
5457 {
5458   char **decomposed_path;
5459   dbus_bool_t retval;
5460   DBusError error = DBUS_ERROR_INIT;
5461
5462   _dbus_return_val_if_fail (connection != NULL, FALSE);
5463   _dbus_return_val_if_fail (path != NULL, FALSE);
5464   _dbus_return_val_if_fail (path[0] == '/', FALSE);
5465   _dbus_return_val_if_fail (vtable != NULL, FALSE);
5466
5467   if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5468     return FALSE;
5469
5470   CONNECTION_LOCK (connection);
5471
5472   retval = _dbus_object_tree_register (connection->objects,
5473                                        TRUE,
5474                                        (const char **) decomposed_path, vtable,
5475                                        user_data, &error);
5476
5477   CONNECTION_UNLOCK (connection);
5478
5479   dbus_free_string_array (decomposed_path);
5480
5481   if (dbus_error_has_name (&error, DBUS_ERROR_ADDRESS_IN_USE))
5482     {
5483       _dbus_warn ("%s\n", error.message);
5484       dbus_error_free (&error);
5485       return FALSE;
5486     }
5487
5488   return retval;
5489 }
5490
5491 /**
5492  * Unregisters the handler registered with exactly the given path.
5493  * It's a bug to call this function for a path that isn't registered.
5494  * Can unregister both fallback paths and object paths.
5495  *
5496  * @param connection the connection
5497  * @param path a '/' delimited string of path elements
5498  * @returns #FALSE if not enough memory
5499  */
5500 dbus_bool_t
5501 dbus_connection_unregister_object_path (DBusConnection              *connection,
5502                                         const char                  *path)
5503 {
5504   char **decomposed_path;
5505
5506   _dbus_return_val_if_fail (connection != NULL, FALSE);
5507   _dbus_return_val_if_fail (path != NULL, FALSE);
5508   _dbus_return_val_if_fail (path[0] == '/', FALSE);
5509
5510   if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5511       return FALSE;
5512
5513   CONNECTION_LOCK (connection);
5514
5515   _dbus_object_tree_unregister_and_unlock (connection->objects, (const char **) decomposed_path);
5516
5517   dbus_free_string_array (decomposed_path);
5518
5519   return TRUE;
5520 }
5521
5522 /**
5523  * Gets the user data passed to dbus_connection_register_object_path()
5524  * or dbus_connection_register_fallback(). If nothing was registered
5525  * at this path, the data is filled in with #NULL.
5526  *
5527  * @param connection the connection
5528  * @param path the path you registered with
5529  * @param data_p location to store the user data, or #NULL
5530  * @returns #FALSE if not enough memory
5531  */
5532 dbus_bool_t
5533 dbus_connection_get_object_path_data (DBusConnection *connection,
5534                                       const char     *path,
5535                                       void          **data_p)
5536 {
5537   char **decomposed_path;
5538
5539   _dbus_return_val_if_fail (connection != NULL, FALSE);
5540   _dbus_return_val_if_fail (path != NULL, FALSE);
5541   _dbus_return_val_if_fail (data_p != NULL, FALSE);
5542
5543   *data_p = NULL;
5544   
5545   if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5546     return FALSE;
5547   
5548   CONNECTION_LOCK (connection);
5549
5550   *data_p = _dbus_object_tree_get_user_data_unlocked (connection->objects, (const char**) decomposed_path);
5551
5552   CONNECTION_UNLOCK (connection);
5553
5554   dbus_free_string_array (decomposed_path);
5555
5556   return TRUE;
5557 }
5558
5559 /**
5560  * Lists the registered fallback handlers and object path handlers at
5561  * the given parent_path. The returned array should be freed with
5562  * dbus_free_string_array().
5563  *
5564  * @param connection the connection
5565  * @param parent_path the path to list the child handlers of
5566  * @param child_entries returns #NULL-terminated array of children
5567  * @returns #FALSE if no memory to allocate the child entries
5568  */
5569 dbus_bool_t
5570 dbus_connection_list_registered (DBusConnection              *connection,
5571                                  const char                  *parent_path,
5572                                  char                      ***child_entries)
5573 {
5574   char **decomposed_path;
5575   dbus_bool_t retval;
5576   _dbus_return_val_if_fail (connection != NULL, FALSE);
5577   _dbus_return_val_if_fail (parent_path != NULL, FALSE);
5578   _dbus_return_val_if_fail (parent_path[0] == '/', FALSE);
5579   _dbus_return_val_if_fail (child_entries != NULL, FALSE);
5580
5581   if (!_dbus_decompose_path (parent_path, strlen (parent_path), &decomposed_path, NULL))
5582     return FALSE;
5583
5584   CONNECTION_LOCK (connection);
5585
5586   retval = _dbus_object_tree_list_registered_and_unlock (connection->objects,
5587                                                          (const char **) decomposed_path,
5588                                                          child_entries);
5589   dbus_free_string_array (decomposed_path);
5590
5591   return retval;
5592 }
5593
5594 static DBusDataSlotAllocator slot_allocator;
5595 _DBUS_DEFINE_GLOBAL_LOCK (connection_slots);
5596
5597 /**
5598  * Allocates an integer ID to be used for storing application-specific
5599  * data on any DBusConnection. The allocated ID may then be used
5600  * with dbus_connection_set_data() and dbus_connection_get_data().
5601  * The passed-in slot must be initialized to -1, and is filled in
5602  * with the slot ID. If the passed-in slot is not -1, it's assumed
5603  * to be already allocated, and its refcount is incremented.
5604  * 
5605  * The allocated slot is global, i.e. all DBusConnection objects will
5606  * have a slot with the given integer ID reserved.
5607  *
5608  * @param slot_p address of a global variable storing the slot
5609  * @returns #FALSE on failure (no memory)
5610  */
5611 dbus_bool_t
5612 dbus_connection_allocate_data_slot (dbus_int32_t *slot_p)
5613 {
5614   return _dbus_data_slot_allocator_alloc (&slot_allocator,
5615                                           &_DBUS_LOCK_NAME (connection_slots),
5616                                           slot_p);
5617 }
5618
5619 /**
5620  * Deallocates a global ID for connection data slots.
5621  * dbus_connection_get_data() and dbus_connection_set_data() may no
5622  * longer be used with this slot.  Existing data stored on existing
5623  * DBusConnection objects will be freed when the connection is
5624  * finalized, but may not be retrieved (and may only be replaced if
5625  * someone else reallocates the slot).  When the refcount on the
5626  * passed-in slot reaches 0, it is set to -1.
5627  *
5628  * @param slot_p address storing the slot to deallocate
5629  */
5630 void
5631 dbus_connection_free_data_slot (dbus_int32_t *slot_p)
5632 {
5633   _dbus_return_if_fail (*slot_p >= 0);
5634   
5635   _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
5636 }
5637
5638 /**
5639  * Stores a pointer on a DBusConnection, along
5640  * with an optional function to be used for freeing
5641  * the data when the data is set again, or when
5642  * the connection is finalized. The slot number
5643  * must have been allocated with dbus_connection_allocate_data_slot().
5644  *
5645  * @param connection the connection
5646  * @param slot the slot number
5647  * @param data the data to store
5648  * @param free_data_func finalizer function for the data
5649  * @returns #TRUE if there was enough memory to store the data
5650  */
5651 dbus_bool_t
5652 dbus_connection_set_data (DBusConnection   *connection,
5653                           dbus_int32_t      slot,
5654                           void             *data,
5655                           DBusFreeFunction  free_data_func)
5656 {
5657   DBusFreeFunction old_free_func;
5658   void *old_data;
5659   dbus_bool_t retval;
5660
5661   _dbus_return_val_if_fail (connection != NULL, FALSE);
5662   _dbus_return_val_if_fail (slot >= 0, FALSE);
5663   
5664   CONNECTION_LOCK (connection);
5665
5666   retval = _dbus_data_slot_list_set (&slot_allocator,
5667                                      &connection->slot_list,
5668                                      slot, data, free_data_func,
5669                                      &old_free_func, &old_data);
5670   
5671   CONNECTION_UNLOCK (connection);
5672
5673   if (retval)
5674     {
5675       /* Do the actual free outside the connection lock */
5676       if (old_free_func)
5677         (* old_free_func) (old_data);
5678     }
5679
5680   return retval;
5681 }
5682
5683 /**
5684  * Retrieves data previously set with dbus_connection_set_data().
5685  * The slot must still be allocated (must not have been freed).
5686  *
5687  * @param connection the connection
5688  * @param slot the slot to get data from
5689  * @returns the data, or #NULL if not found
5690  */
5691 void*
5692 dbus_connection_get_data (DBusConnection   *connection,
5693                           dbus_int32_t      slot)
5694 {
5695   void *res;
5696
5697   _dbus_return_val_if_fail (connection != NULL, NULL);
5698   
5699   CONNECTION_LOCK (connection);
5700
5701   res = _dbus_data_slot_list_get (&slot_allocator,
5702                                   &connection->slot_list,
5703                                   slot);
5704   
5705   CONNECTION_UNLOCK (connection);
5706
5707   return res;
5708 }
5709
5710 /**
5711  * This function sets a global flag for whether dbus_connection_new()
5712  * will set SIGPIPE behavior to SIG_IGN.
5713  *
5714  * @param will_modify_sigpipe #TRUE to allow sigpipe to be set to SIG_IGN
5715  */
5716 void
5717 dbus_connection_set_change_sigpipe (dbus_bool_t will_modify_sigpipe)
5718 {  
5719   _dbus_modify_sigpipe = will_modify_sigpipe != FALSE;
5720 }
5721
5722 /**
5723  * Specifies the maximum size message this connection is allowed to
5724  * receive. Larger messages will result in disconnecting the
5725  * connection.
5726  * 
5727  * @param connection a #DBusConnection
5728  * @param size maximum message size the connection can receive, in bytes
5729  */
5730 void
5731 dbus_connection_set_max_message_size (DBusConnection *connection,
5732                                       long            size)
5733 {
5734   _dbus_return_if_fail (connection != NULL);
5735   
5736   CONNECTION_LOCK (connection);
5737   _dbus_transport_set_max_message_size (connection->transport,
5738                                         size);
5739   CONNECTION_UNLOCK (connection);
5740 }
5741
5742 /**
5743  * Gets the value set by dbus_connection_set_max_message_size().
5744  *
5745  * @param connection the connection
5746  * @returns the max size of a single message
5747  */
5748 long
5749 dbus_connection_get_max_message_size (DBusConnection *connection)
5750 {
5751   long res;
5752
5753   _dbus_return_val_if_fail (connection != NULL, 0);
5754   
5755   CONNECTION_LOCK (connection);
5756   res = _dbus_transport_get_max_message_size (connection->transport);
5757   CONNECTION_UNLOCK (connection);
5758   return res;
5759 }
5760
5761 /**
5762  * Sets the maximum total number of bytes that can be used for all messages
5763  * received on this connection. Messages count toward the maximum until
5764  * they are finalized. When the maximum is reached, the connection will
5765  * not read more data until some messages are finalized.
5766  *
5767  * The semantics of the maximum are: if outstanding messages are
5768  * already above the maximum, additional messages will not be read.
5769  * The semantics are not: if the next message would cause us to exceed
5770  * the maximum, we don't read it. The reason is that we don't know the
5771  * size of a message until after we read it.
5772  *
5773  * Thus, the max live messages size can actually be exceeded
5774  * by up to the maximum size of a single message.
5775  * 
5776  * Also, if we read say 1024 bytes off the wire in a single read(),
5777  * and that contains a half-dozen small messages, we may exceed the
5778  * size max by that amount. But this should be inconsequential.
5779  *
5780  * This does imply that we can't call read() with a buffer larger
5781  * than we're willing to exceed this limit by.
5782  *
5783  * @param connection the connection
5784  * @param size the maximum size in bytes of all outstanding messages
5785  */
5786 void
5787 dbus_connection_set_max_received_size (DBusConnection *connection,
5788                                        long            size)
5789 {
5790   _dbus_return_if_fail (connection != NULL);
5791   
5792   CONNECTION_LOCK (connection);
5793   _dbus_transport_set_max_received_size (connection->transport,
5794                                          size);
5795   CONNECTION_UNLOCK (connection);
5796 }
5797
5798 /**
5799  * Gets the value set by dbus_connection_set_max_received_size().
5800  *
5801  * @param connection the connection
5802  * @returns the max size of all live messages
5803  */
5804 long
5805 dbus_connection_get_max_received_size (DBusConnection *connection)
5806 {
5807   long res;
5808
5809   _dbus_return_val_if_fail (connection != NULL, 0);
5810   
5811   CONNECTION_LOCK (connection);
5812   res = _dbus_transport_get_max_received_size (connection->transport);
5813   CONNECTION_UNLOCK (connection);
5814   return res;
5815 }
5816
5817 /**
5818  * Gets the approximate size in bytes of all messages in the outgoing
5819  * message queue. The size is approximate in that you shouldn't use
5820  * it to decide how many bytes to read off the network or anything
5821  * of that nature, as optimizations may choose to tell small white lies
5822  * to avoid performance overhead.
5823  *
5824  * @param connection the connection
5825  * @returns the number of bytes that have been queued up but not sent
5826  */
5827 long
5828 dbus_connection_get_outgoing_size (DBusConnection *connection)
5829 {
5830   long res;
5831
5832   _dbus_return_val_if_fail (connection != NULL, 0);
5833   
5834   CONNECTION_LOCK (connection);
5835   res = _dbus_counter_get_value (connection->outgoing_counter);
5836   CONNECTION_UNLOCK (connection);
5837   return res;
5838 }
5839
5840 /** @} */