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