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