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