bceef2a6eafc3900ee96510e703a266354490e2c
[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  Red Hat Inc.
5  *
6  * Licensed under the Academic Free License version 1.2
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-connection.h"
26 #include "dbus-list.h"
27 #include "dbus-timeout.h"
28 #include "dbus-transport.h"
29 #include "dbus-watch.h"
30 #include "dbus-connection-internal.h"
31 #include "dbus-list.h"
32 #include "dbus-hash.h"
33 #include "dbus-message-internal.h"
34 #include "dbus-threads.h"
35 #include "dbus-protocol.h"
36 #include "dbus-dataslot.h"
37 #include "dbus-string.h"
38 #include "dbus-pending-call.h"
39 #include "dbus-object-tree.h"
40
41 #if 0
42 #define CONNECTION_LOCK(connection)   do {                      \
43     _dbus_verbose ("  LOCK: %s\n", _DBUS_FUNCTION_NAME);        \
44     dbus_mutex_lock ((connection)->mutex);                      \
45   } while (0)
46 #define CONNECTION_UNLOCK(connection) do {                      \
47     _dbus_verbose ("  UNLOCK: %s\n", _DBUS_FUNCTION_NAME);      \
48     dbus_mutex_unlock ((connection)->mutex);                    \
49   } while (0)
50 #else
51 #define CONNECTION_LOCK(connection)    dbus_mutex_lock ((connection)->mutex)
52 #define CONNECTION_UNLOCK(connection)  dbus_mutex_unlock ((connection)->mutex)
53 #endif
54
55 /**
56  * @defgroup DBusConnection DBusConnection
57  * @ingroup  DBus
58  * @brief Connection to another application
59  *
60  * A DBusConnection represents a connection to another
61  * application. Messages can be sent and received via this connection.
62  * The other application may be a message bus; for convenience, the
63  * function dbus_bus_get() is provided to automatically open a
64  * connection to the well-known message buses.
65  * 
66  * In brief a DBusConnection is a message queue associated with some
67  * message transport mechanism such as a socket.  The connection
68  * maintains a queue of incoming messages and a queue of outgoing
69  * messages.
70  *
71  * Incoming messages are normally processed by calling
72  * dbus_connection_dispatch(). dbus_connection_dispatch() runs any
73  * handlers registered for the topmost message in the message queue,
74  * then discards the message, then returns.
75  * 
76  * dbus_connection_get_dispatch_status() indicates whether
77  * messages are currently in the queue that need dispatching.
78  * dbus_connection_set_dispatch_status_function() allows
79  * you to set a function to be used to monitor the dispatch status.
80  *
81  * If you're using GLib or Qt add-on libraries for D-BUS, there are
82  * special convenience APIs in those libraries that hide
83  * all the details of dispatch and watch/timeout monitoring.
84  * For example, dbus_connection_setup_with_g_main().
85  *
86  * If you aren't using these add-on libraries, you have to manually
87  * call dbus_connection_set_dispatch_status_function(),
88  * dbus_connection_set_watch_functions(),
89  * dbus_connection_set_timeout_functions() providing appropriate
90  * functions to integrate the connection with your application's main
91  * loop.
92  *
93  * When you use dbus_connection_send() or one of its variants to send
94  * a message, the message is added to the outgoing queue.  It's
95  * actually written to the network later; either in
96  * dbus_watch_handle() invoked by your main loop, or in
97  * dbus_connection_flush() which blocks until it can write out the
98  * entire outgoing queue. The GLib/Qt add-on libraries again
99  * handle the details here for you by setting up watch functions.
100  *
101  * When a connection is disconnected, you are guaranteed to get a
102  * message with the name #DBUS_MESSAGE_LOCAL_DISCONNECT.
103  *
104  * You may not drop the last reference to a #DBusConnection
105  * until that connection has been disconnected.
106  *
107  * You may dispatch the unprocessed incoming message queue even if the
108  * connection is disconnected. However, #DBUS_MESSAGE_LOCAL_DISCONNECT
109  * will always be the last message in the queue (obviously no messages
110  * are received after disconnection).
111  *
112  * #DBusConnection has thread locks and drops them when invoking user
113  * callbacks, so in general is transparently threadsafe. However,
114  * #DBusMessage does NOT have thread locks; you must not send the same
115  * message to multiple #DBusConnection that will be used from
116  * different threads.
117  */
118
119 /**
120  * @defgroup DBusConnectionInternals DBusConnection implementation details
121  * @ingroup  DBusInternals
122  * @brief Implementation details of DBusConnection
123  *
124  * @{
125  */
126
127 /**
128  * Internal struct representing a message filter function 
129  */
130 typedef struct DBusMessageFilter DBusMessageFilter;
131
132 /**
133  * Internal struct representing a message filter function 
134  */
135 struct DBusMessageFilter
136 {
137   DBusAtomic refcount; /**< Reference count */
138   DBusHandleMessageFunction function; /**< Function to call to filter */
139   void *user_data; /**< User data for the function */
140   DBusFreeFunction free_user_data_function; /**< Function to free the user data */
141 };
142
143
144 /**
145  * Internals of DBusPreallocatedSend
146  */
147 struct DBusPreallocatedSend
148 {
149   DBusConnection *connection; /**< Connection we'd send the message to */
150   DBusList *queue_link;       /**< Preallocated link in the queue */
151   DBusList *counter_link;     /**< Preallocated link in the resource counter */
152 };
153
154 static dbus_bool_t _dbus_modify_sigpipe = TRUE;
155
156 /**
157  * Implementation details of DBusConnection. All fields are private.
158  */
159 struct DBusConnection
160 {
161   DBusAtomic refcount; /**< Reference count. */
162
163   DBusMutex *mutex; /**< Lock on the entire DBusConnection */
164
165   dbus_bool_t dispatch_acquired; /**< Protects dispatch() */
166   DBusCondVar *dispatch_cond;    /**< Protects dispatch() */
167
168   dbus_bool_t io_path_acquired;  /**< Protects transport io path */
169   DBusCondVar *io_path_cond;     /**< Protects transport io path */
170   
171   DBusList *outgoing_messages; /**< Queue of messages we need to send, send the end of the list first. */
172   DBusList *incoming_messages; /**< Queue of messages we have received, end of the list received most recently. */
173
174   DBusMessage *message_borrowed; /**< True if the first incoming message has been borrowed */
175   DBusCondVar *message_returned_cond; /**< Used with dbus_connection_borrow_message() */
176   
177   int n_outgoing;              /**< Length of outgoing queue. */
178   int n_incoming;              /**< Length of incoming queue. */
179
180   DBusCounter *outgoing_counter; /**< Counts size of outgoing messages. */
181   
182   DBusTransport *transport;    /**< Object that sends/receives messages over network. */
183   DBusWatchList *watches;      /**< Stores active watches. */
184   DBusTimeoutList *timeouts;   /**< Stores active timeouts. */
185   
186   DBusList *filter_list;        /**< List of filters. */
187
188   DBusDataSlotList slot_list;   /**< Data stored by allocated integer ID */
189
190   DBusHashTable *pending_replies;  /**< Hash of message serials to #DBusPendingCall. */  
191   
192   dbus_uint32_t client_serial;       /**< Client serial. Increments each time a message is sent  */
193   DBusList *disconnect_message_link; /**< Preallocated list node for queueing the disconnection message */
194
195   DBusWakeupMainFunction wakeup_main_function; /**< Function to wake up the mainloop  */
196   void *wakeup_main_data; /**< Application data for wakeup_main_function */
197   DBusFreeFunction free_wakeup_main_data; /**< free wakeup_main_data */
198
199   DBusDispatchStatusFunction dispatch_status_function; /**< Function on dispatch status changes  */
200   void *dispatch_status_data; /**< Application data for dispatch_status_function */
201   DBusFreeFunction free_dispatch_status_data; /**< free dispatch_status_data */
202
203   DBusDispatchStatus last_dispatch_status; /**< The last dispatch status we reported to the application. */
204
205   DBusList *link_cache; /**< A cache of linked list links to prevent contention
206                          *   for the global linked list mempool lock
207                          */
208   DBusObjectTree *objects; /**< Object path handlers registered with this connection */
209
210   unsigned int exit_on_disconnect : 1; /**< If #TRUE, exit after handling disconnect signal */
211 };
212
213 static void               _dbus_connection_remove_timeout_locked             (DBusConnection     *connection,
214                                                                               DBusTimeout        *timeout);
215 static DBusDispatchStatus _dbus_connection_get_dispatch_status_unlocked      (DBusConnection     *connection);
216 static void               _dbus_connection_update_dispatch_status_and_unlock (DBusConnection     *connection,
217                                                                               DBusDispatchStatus  new_status);
218 static void               _dbus_connection_last_unref                        (DBusConnection     *connection);
219
220 static void
221 _dbus_message_filter_ref (DBusMessageFilter *filter)
222 {
223   _dbus_assert (filter->refcount.value > 0);
224   _dbus_atomic_inc (&filter->refcount);
225 }
226
227 static void
228 _dbus_message_filter_unref (DBusMessageFilter *filter)
229 {
230   _dbus_assert (filter->refcount.value > 0);
231
232   if (_dbus_atomic_dec (&filter->refcount) == 1)
233     {
234       if (filter->free_user_data_function)
235         (* filter->free_user_data_function) (filter->user_data);
236       
237       dbus_free (filter);
238     }
239 }
240
241 /**
242  * Acquires the connection lock.
243  *
244  * @param connection the connection.
245  */
246 void
247 _dbus_connection_lock (DBusConnection *connection)
248 {
249   CONNECTION_LOCK (connection);
250 }
251
252 /**
253  * Releases the connection lock.
254  *
255  * @param connection the connection.
256  */
257 void
258 _dbus_connection_unlock (DBusConnection *connection)
259 {
260   CONNECTION_UNLOCK (connection);
261 }
262
263 /**
264  * Wakes up the main loop if it is sleeping
265  * Needed if we're e.g. queueing outgoing messages
266  * on a thread while the mainloop sleeps.
267  *
268  * @param connection the connection.
269  */
270 static void
271 _dbus_connection_wakeup_mainloop (DBusConnection *connection)
272 {
273   if (connection->wakeup_main_function)
274     (*connection->wakeup_main_function) (connection->wakeup_main_data);
275 }
276
277 #ifdef DBUS_BUILD_TESTS
278 /* For now this function isn't used */
279 /**
280  * Adds a message to the incoming message queue, returning #FALSE
281  * if there's insufficient memory to queue the message.
282  * Does not take over refcount of the message.
283  *
284  * @param connection the connection.
285  * @param message the message to queue.
286  * @returns #TRUE on success.
287  */
288 dbus_bool_t
289 _dbus_connection_queue_received_message (DBusConnection *connection,
290                                          DBusMessage    *message)
291 {
292   DBusList *link;
293
294   link = _dbus_list_alloc_link (message);
295   if (link == NULL)
296     return FALSE;
297
298   dbus_message_ref (message);
299   _dbus_connection_queue_received_message_link (connection, link);
300
301   return TRUE;
302 }
303 #endif
304
305 /**
306  * Adds a message-containing list link to the incoming message queue,
307  * taking ownership of the link and the message's current refcount.
308  * Cannot fail due to lack of memory.
309  *
310  * @param connection the connection.
311  * @param link the message link to queue.
312  */
313 void
314 _dbus_connection_queue_received_message_link (DBusConnection  *connection,
315                                               DBusList        *link)
316 {
317   DBusPendingCall *pending;
318   dbus_int32_t reply_serial;
319   DBusMessage *message;
320   
321   _dbus_assert (_dbus_transport_get_is_authenticated (connection->transport));
322   
323   _dbus_list_append_link (&connection->incoming_messages,
324                           link);
325   message = link->data;
326
327   /* If this is a reply we're waiting on, remove timeout for it */
328   reply_serial = dbus_message_get_reply_serial (message);
329   if (reply_serial != -1)
330     {
331       pending = _dbus_hash_table_lookup_int (connection->pending_replies,
332                                              reply_serial);
333       if (pending != NULL)
334         {
335           if (pending->timeout_added)
336             _dbus_connection_remove_timeout_locked (connection,
337                                                     pending->timeout);
338
339           pending->timeout_added = FALSE;
340         }
341     }
342   
343   connection->n_incoming += 1;
344
345   _dbus_connection_wakeup_mainloop (connection);
346   
347   _dbus_verbose ("Message %p (%d %s '%s') added to incoming queue %p, %d incoming\n",
348                  message,
349                  dbus_message_get_type (message),
350                  dbus_message_get_interface (message) ?
351                  dbus_message_get_interface (message) :
352                  "no interface",
353                  dbus_message_get_signature (message),
354                  connection,
355                  connection->n_incoming);
356 }
357
358 /**
359  * Adds a link + message to the incoming message queue.
360  * Can't fail. Takes ownership of both link and message.
361  *
362  * @param connection the connection.
363  * @param link the list node and message to queue.
364  *
365  * @todo This needs to wake up the mainloop if it is in
366  * a poll/select and this is a multithreaded app.
367  */
368 static void
369 _dbus_connection_queue_synthesized_message_link (DBusConnection *connection,
370                                                  DBusList *link)
371 {
372   _dbus_list_append_link (&connection->incoming_messages, link);
373
374   connection->n_incoming += 1;
375
376   _dbus_connection_wakeup_mainloop (connection);
377   
378   _dbus_verbose ("Synthesized message %p added to incoming queue %p, %d incoming\n",
379                  link->data, connection, connection->n_incoming);
380 }
381
382
383 /**
384  * Checks whether there are messages in the outgoing message queue.
385  *
386  * @param connection the connection.
387  * @returns #TRUE if the outgoing queue is non-empty.
388  */
389 dbus_bool_t
390 _dbus_connection_have_messages_to_send (DBusConnection *connection)
391 {
392   return connection->outgoing_messages != NULL;
393 }
394
395 /**
396  * Gets the next outgoing message. The message remains in the
397  * queue, and the caller does not own a reference to it.
398  *
399  * @param connection the connection.
400  * @returns the message to be sent.
401  */ 
402 DBusMessage*
403 _dbus_connection_get_message_to_send (DBusConnection *connection)
404 {
405   return _dbus_list_get_last (&connection->outgoing_messages);
406 }
407
408 /**
409  * Notifies the connection that a message has been sent, so the
410  * message can be removed from the outgoing queue.
411  * Called with the connection lock held.
412  *
413  * @param connection the connection.
414  * @param message the message that was sent.
415  */
416 void
417 _dbus_connection_message_sent (DBusConnection *connection,
418                                DBusMessage    *message)
419 {
420   DBusList *link;
421   
422   _dbus_assert (_dbus_transport_get_is_authenticated (connection->transport));
423   
424   link = _dbus_list_get_last_link (&connection->outgoing_messages);
425   _dbus_assert (link != NULL);
426   _dbus_assert (link->data == message);
427
428   /* Save this link in the link cache */
429   _dbus_list_unlink (&connection->outgoing_messages,
430                      link);
431   _dbus_list_prepend_link (&connection->link_cache, link);
432   
433   connection->n_outgoing -= 1;
434
435   _dbus_verbose ("Message %p (%d %s '%s') removed from outgoing queue %p, %d left to send\n",
436                  message,
437                  dbus_message_get_type (message),
438                  dbus_message_get_interface (message) ?
439                  dbus_message_get_interface (message) :
440                  "no interface",
441                  dbus_message_get_signature (message),
442                  connection, connection->n_outgoing);
443
444   /* Save this link in the link cache also */
445   _dbus_message_remove_size_counter (message, connection->outgoing_counter,
446                                      &link);
447   _dbus_list_prepend_link (&connection->link_cache, link);
448   
449   dbus_message_unref (message);
450   
451   if (connection->n_outgoing == 0)
452     _dbus_transport_messages_pending (connection->transport,
453                                       connection->n_outgoing);  
454 }
455
456 /**
457  * Adds a watch using the connection's DBusAddWatchFunction if
458  * available. Otherwise records the watch to be added when said
459  * function is available. Also re-adds the watch if the
460  * DBusAddWatchFunction changes. May fail due to lack of memory.
461  *
462  * @param connection the connection.
463  * @param watch the watch to add.
464  * @returns #TRUE on success.
465  */
466 dbus_bool_t
467 _dbus_connection_add_watch (DBusConnection *connection,
468                             DBusWatch      *watch)
469 {
470   if (connection->watches) /* null during finalize */
471     return _dbus_watch_list_add_watch (connection->watches,
472                                        watch);
473   else
474     return FALSE;
475 }
476
477 /**
478  * Removes a watch using the connection's DBusRemoveWatchFunction
479  * if available. It's an error to call this function on a watch
480  * that was not previously added.
481  *
482  * @param connection the connection.
483  * @param watch the watch to remove.
484  */
485 void
486 _dbus_connection_remove_watch (DBusConnection *connection,
487                                DBusWatch      *watch)
488 {
489   if (connection->watches) /* null during finalize */
490     _dbus_watch_list_remove_watch (connection->watches,
491                                    watch);
492 }
493
494 /**
495  * Toggles a watch and notifies app via connection's
496  * DBusWatchToggledFunction if available. It's an error to call this
497  * function on a watch that was not previously added.
498  *
499  * @param connection the connection.
500  * @param watch the watch to toggle.
501  * @param enabled whether to enable or disable
502  */
503 void
504 _dbus_connection_toggle_watch (DBusConnection *connection,
505                                DBusWatch      *watch,
506                                dbus_bool_t     enabled)
507 {
508   if (connection->watches) /* null during finalize */
509     _dbus_watch_list_toggle_watch (connection->watches,
510                                    watch, enabled);
511 }
512
513 /**
514  * Adds a timeout using the connection's DBusAddTimeoutFunction if
515  * available. Otherwise records the timeout to be added when said
516  * function is available. Also re-adds the timeout if the
517  * DBusAddTimeoutFunction changes. May fail due to lack of memory.
518  * The timeout will fire repeatedly until removed.
519  *
520  * @param connection the connection.
521  * @param timeout the timeout to add.
522  * @returns #TRUE on success.
523  */
524 dbus_bool_t
525 _dbus_connection_add_timeout (DBusConnection *connection,
526                               DBusTimeout    *timeout)
527 {
528  if (connection->timeouts) /* null during finalize */
529     return _dbus_timeout_list_add_timeout (connection->timeouts,
530                                            timeout);
531   else
532     return FALSE;  
533 }
534
535 /**
536  * Removes a timeout using the connection's DBusRemoveTimeoutFunction
537  * if available. It's an error to call this function on a timeout
538  * that was not previously added.
539  *
540  * @param connection the connection.
541  * @param timeout the timeout to remove.
542  */
543 void
544 _dbus_connection_remove_timeout (DBusConnection *connection,
545                                  DBusTimeout    *timeout)
546 {
547   if (connection->timeouts) /* null during finalize */
548     _dbus_timeout_list_remove_timeout (connection->timeouts,
549                                        timeout);
550 }
551
552 static void
553 _dbus_connection_remove_timeout_locked (DBusConnection *connection,
554                                         DBusTimeout    *timeout)
555 {
556   CONNECTION_LOCK (connection);
557   _dbus_connection_remove_timeout (connection, timeout);
558   CONNECTION_UNLOCK (connection);
559 }
560
561 /**
562  * Toggles a timeout and notifies app via connection's
563  * DBusTimeoutToggledFunction if available. It's an error to call this
564  * function on a timeout that was not previously added.
565  *
566  * @param connection the connection.
567  * @param timeout the timeout to toggle.
568  * @param enabled whether to enable or disable
569  */
570 void
571 _dbus_connection_toggle_timeout (DBusConnection *connection,
572                                  DBusTimeout      *timeout,
573                                  dbus_bool_t     enabled)
574 {
575   if (connection->timeouts) /* null during finalize */
576     _dbus_timeout_list_toggle_timeout (connection->timeouts,
577                                        timeout, enabled);
578 }
579
580 /**
581  * Tells the connection that the transport has been disconnected.
582  * Results in posting a disconnect message on the incoming message
583  * queue.  Only has an effect the first time it's called.
584  *
585  * @param connection the connection
586  */
587 void
588 _dbus_connection_notify_disconnected (DBusConnection *connection)
589 {
590   if (connection->disconnect_message_link)
591     {
592       /* We haven't sent the disconnect message already */
593       _dbus_connection_queue_synthesized_message_link (connection,
594                                                        connection->disconnect_message_link);
595       connection->disconnect_message_link = NULL;
596     }
597 }
598
599 static dbus_bool_t
600 _dbus_connection_attach_pending_call_unlocked (DBusConnection  *connection,
601                                                DBusPendingCall *pending)
602 {
603   _dbus_assert (pending->reply_serial != 0);
604
605   if (!_dbus_connection_add_timeout (connection, pending->timeout))
606     return FALSE;
607   
608   if (!_dbus_hash_table_insert_int (connection->pending_replies,
609                                     pending->reply_serial,
610                                     pending))
611     {
612       _dbus_connection_remove_timeout (connection, pending->timeout);
613       return FALSE;
614     }
615   
616   pending->timeout_added = TRUE;
617   pending->connection = connection;
618
619   dbus_pending_call_ref (pending);
620   
621   return TRUE;
622 }
623
624 static void
625 free_pending_call_on_hash_removal (void *data)
626 {
627   DBusPendingCall *pending;
628   
629   if (data == NULL)
630     return;
631
632   pending = data;
633
634   if (pending->connection)
635     {
636       if (pending->timeout_added)
637         {
638           _dbus_connection_remove_timeout (pending->connection,
639                                            pending->timeout);
640           pending->timeout_added = FALSE;
641         }
642
643       pending->connection = NULL;
644       
645       dbus_pending_call_unref (pending);
646     }
647 }
648
649 static void
650 _dbus_connection_detach_pending_call_and_unlock (DBusConnection  *connection,
651                                                  DBusPendingCall *pending)
652 {
653   /* The idea here is to avoid finalizing the pending call
654    * with the lock held, since there's a destroy notifier
655    * in pending call that goes out to application code.
656    */
657   dbus_pending_call_ref (pending);
658   _dbus_hash_table_remove_int (connection->pending_replies,
659                                pending->reply_serial);
660   CONNECTION_UNLOCK (connection);
661   dbus_pending_call_unref (pending);
662 }
663
664 /**
665  * Removes a pending call from the connection, such that
666  * the pending reply will be ignored. May drop the last
667  * reference to the pending call.
668  *
669  * @param connection the connection
670  * @param pending the pending call
671  */
672 void
673 _dbus_connection_remove_pending_call (DBusConnection  *connection,
674                                       DBusPendingCall *pending)
675 {
676   CONNECTION_LOCK (connection);
677   _dbus_connection_detach_pending_call_and_unlock (connection, pending);
678 }
679
680 /**
681  * Completes a pending call with the given message,
682  * or if the message is #NULL, by timing out the pending call.
683  * 
684  * @param pending the pending call
685  * @param message the message to complete the call with, or #NULL
686  *  to time out the call
687  */
688 void
689 _dbus_pending_call_complete_and_unlock (DBusPendingCall *pending,
690                                         DBusMessage     *message)
691 {
692   if (message == NULL)
693     {
694       message = pending->timeout_link->data;
695       _dbus_list_clear (&pending->timeout_link);
696     }
697   else
698     dbus_message_ref (message);
699
700   _dbus_verbose ("  handing message %p (%s) to pending call serial %u\n",
701                  message,
702                  dbus_message_get_type (message) == DBUS_MESSAGE_TYPE_METHOD_RETURN ?
703                  "method return" :
704                  dbus_message_get_type (message) == DBUS_MESSAGE_TYPE_ERROR ?
705                  "error" : "other type",
706                  pending->reply_serial);
707   
708   _dbus_assert (pending->reply == NULL);
709   _dbus_assert (pending->reply_serial == dbus_message_get_reply_serial (message));
710   pending->reply = message;
711   
712   dbus_pending_call_ref (pending); /* in case there's no app with a ref held */
713   _dbus_connection_detach_pending_call_and_unlock (pending->connection, pending);
714   
715   /* Must be called unlocked since it invokes app callback */
716   _dbus_pending_call_notify (pending);
717   dbus_pending_call_unref (pending);
718 }
719
720 /**
721  * Acquire the transporter I/O path. This must be done before
722  * doing any I/O in the transporter. May sleep and drop the
723  * connection mutex while waiting for the I/O path.
724  *
725  * @param connection the connection.
726  * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
727  * @returns TRUE if the I/O path was acquired.
728  */
729 static dbus_bool_t
730 _dbus_connection_acquire_io_path (DBusConnection *connection,
731                                   int timeout_milliseconds)
732 {
733   dbus_bool_t res = TRUE;
734
735   if (connection->io_path_acquired)
736     {
737       if (timeout_milliseconds != -1) 
738         res = dbus_condvar_wait_timeout (connection->io_path_cond,
739                                          connection->mutex,
740                                          timeout_milliseconds);
741       else
742         dbus_condvar_wait (connection->io_path_cond, connection->mutex);
743     }
744   
745   if (res)
746     {
747       _dbus_assert (!connection->io_path_acquired);
748
749       connection->io_path_acquired = TRUE;
750     }
751   
752   return res;
753 }
754
755 /**
756  * Release the I/O path when you're done with it. Only call
757  * after you've acquired the I/O. Wakes up at most one thread
758  * currently waiting to acquire the I/O path.
759  *
760  * @param connection the connection.
761  */
762 static void
763 _dbus_connection_release_io_path (DBusConnection *connection)
764 {
765   _dbus_assert (connection->io_path_acquired);
766
767   connection->io_path_acquired = FALSE;
768   dbus_condvar_wake_one (connection->io_path_cond);
769 }
770
771
772 /**
773  * Queues incoming messages and sends outgoing messages for this
774  * connection, optionally blocking in the process. Each call to
775  * _dbus_connection_do_iteration() will call select() or poll() one
776  * time and then read or write data if possible.
777  *
778  * The purpose of this function is to be able to flush outgoing
779  * messages or queue up incoming messages without returning
780  * control to the application and causing reentrancy weirdness.
781  *
782  * The flags parameter allows you to specify whether to
783  * read incoming messages, write outgoing messages, or both,
784  * and whether to block if no immediate action is possible.
785  *
786  * The timeout_milliseconds parameter does nothing unless the
787  * iteration is blocking.
788  *
789  * If there are no outgoing messages and DBUS_ITERATION_DO_READING
790  * wasn't specified, then it's impossible to block, even if
791  * you specify DBUS_ITERATION_BLOCK; in that case the function
792  * returns immediately.
793  * 
794  * @param connection the connection.
795  * @param flags iteration flags.
796  * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
797  */
798 void
799 _dbus_connection_do_iteration (DBusConnection *connection,
800                                unsigned int    flags,
801                                int             timeout_milliseconds)
802 {
803   if (connection->n_outgoing == 0)
804     flags &= ~DBUS_ITERATION_DO_WRITING;
805
806   if (_dbus_connection_acquire_io_path (connection,
807                                         (flags & DBUS_ITERATION_BLOCK) ? timeout_milliseconds : 0))
808     {
809       _dbus_transport_do_iteration (connection->transport,
810                                     flags, timeout_milliseconds);
811       _dbus_connection_release_io_path (connection);
812     }
813 }
814
815 /**
816  * Creates a new connection for the given transport.  A transport
817  * represents a message stream that uses some concrete mechanism, such
818  * as UNIX domain sockets. May return #NULL if insufficient
819  * memory exists to create the connection.
820  *
821  * @param transport the transport.
822  * @returns the new connection, or #NULL on failure.
823  */
824 DBusConnection*
825 _dbus_connection_new_for_transport (DBusTransport *transport)
826 {
827   DBusConnection *connection;
828   DBusWatchList *watch_list;
829   DBusTimeoutList *timeout_list;
830   DBusHashTable *pending_replies;
831   DBusMutex *mutex;
832   DBusCondVar *message_returned_cond;
833   DBusCondVar *dispatch_cond;
834   DBusCondVar *io_path_cond;
835   DBusList *disconnect_link;
836   DBusMessage *disconnect_message;
837   DBusCounter *outgoing_counter;
838   DBusObjectTree *objects;
839   
840   watch_list = NULL;
841   connection = NULL;
842   pending_replies = NULL;
843   timeout_list = NULL;
844   mutex = NULL;
845   message_returned_cond = NULL;
846   dispatch_cond = NULL;
847   io_path_cond = NULL;
848   disconnect_link = NULL;
849   disconnect_message = NULL;
850   outgoing_counter = NULL;
851   objects = NULL;
852   
853   watch_list = _dbus_watch_list_new ();
854   if (watch_list == NULL)
855     goto error;
856
857   timeout_list = _dbus_timeout_list_new ();
858   if (timeout_list == NULL)
859     goto error;  
860
861   pending_replies =
862     _dbus_hash_table_new (DBUS_HASH_INT,
863                           NULL,
864                           (DBusFreeFunction)free_pending_call_on_hash_removal);
865   if (pending_replies == NULL)
866     goto error;
867   
868   connection = dbus_new0 (DBusConnection, 1);
869   if (connection == NULL)
870     goto error;
871
872   mutex = dbus_mutex_new ();
873   if (mutex == NULL)
874     goto error;
875   
876   message_returned_cond = dbus_condvar_new ();
877   if (message_returned_cond == NULL)
878     goto error;
879   
880   dispatch_cond = dbus_condvar_new ();
881   if (dispatch_cond == NULL)
882     goto error;
883   
884   io_path_cond = dbus_condvar_new ();
885   if (io_path_cond == NULL)
886     goto error;
887
888   disconnect_message = dbus_message_new_signal (DBUS_PATH_ORG_FREEDESKTOP_LOCAL,
889                                                 DBUS_INTERFACE_ORG_FREEDESKTOP_LOCAL,
890                                                 "Disconnected");
891   
892   if (disconnect_message == NULL)
893     goto error;
894
895   disconnect_link = _dbus_list_alloc_link (disconnect_message);
896   if (disconnect_link == NULL)
897     goto error;
898
899   outgoing_counter = _dbus_counter_new ();
900   if (outgoing_counter == NULL)
901     goto error;
902
903   objects = _dbus_object_tree_new (connection);
904   if (objects == NULL)
905     goto error;
906   
907   if (_dbus_modify_sigpipe)
908     _dbus_disable_sigpipe ();
909   
910   connection->refcount.value = 1;
911   connection->mutex = mutex;
912   connection->dispatch_cond = dispatch_cond;
913   connection->io_path_cond = io_path_cond;
914   connection->message_returned_cond = message_returned_cond;
915   connection->transport = transport;
916   connection->watches = watch_list;
917   connection->timeouts = timeout_list;
918   connection->pending_replies = pending_replies;
919   connection->outgoing_counter = outgoing_counter;
920   connection->filter_list = NULL;
921   connection->last_dispatch_status = DBUS_DISPATCH_COMPLETE; /* so we're notified first time there's data */
922   connection->objects = objects;
923   connection->exit_on_disconnect = FALSE;
924   
925   _dbus_data_slot_list_init (&connection->slot_list);
926
927   connection->client_serial = 1;
928
929   connection->disconnect_message_link = disconnect_link;
930   
931   if (!_dbus_transport_set_connection (transport, connection))
932     goto error;
933
934   _dbus_transport_ref (transport);  
935   
936   return connection;
937   
938  error:
939   if (disconnect_message != NULL)
940     dbus_message_unref (disconnect_message);
941   
942   if (disconnect_link != NULL)
943     _dbus_list_free_link (disconnect_link);
944   
945   if (io_path_cond != NULL)
946     dbus_condvar_free (io_path_cond);
947   
948   if (dispatch_cond != NULL)
949     dbus_condvar_free (dispatch_cond);
950   
951   if (message_returned_cond != NULL)
952     dbus_condvar_free (message_returned_cond);
953   
954   if (mutex != NULL)
955     dbus_mutex_free (mutex);
956
957   if (connection != NULL)
958     dbus_free (connection);
959
960   if (pending_replies)
961     _dbus_hash_table_unref (pending_replies);
962   
963   if (watch_list)
964     _dbus_watch_list_free (watch_list);
965
966   if (timeout_list)
967     _dbus_timeout_list_free (timeout_list);
968
969   if (outgoing_counter)
970     _dbus_counter_unref (outgoing_counter);
971
972   if (objects)
973     _dbus_object_tree_unref (objects);
974   
975   return NULL;
976 }
977
978 /**
979  * Increments the reference count of a DBusConnection.
980  * Requires that the caller already holds the connection lock.
981  *
982  * @param connection the connection.
983  */
984 void
985 _dbus_connection_ref_unlocked (DBusConnection *connection)
986 {
987 #ifdef DBUS_HAVE_ATOMIC_INT
988   _dbus_atomic_inc (&connection->refcount);
989 #else
990   _dbus_assert (connection->refcount.value > 0);
991   connection->refcount.value += 1;
992 #endif
993 }
994
995 /**
996  * Decrements the reference count of a DBusConnection.
997  * Requires that the caller already holds the connection lock.
998  *
999  * @param connection the connection.
1000  */
1001 void
1002 _dbus_connection_unref_unlocked (DBusConnection *connection)
1003 {
1004   dbus_bool_t last_unref;
1005
1006   _dbus_return_if_fail (connection != NULL);
1007
1008   /* The connection lock is better than the global
1009    * lock in the atomic increment fallback
1010    */
1011   
1012 #ifdef DBUS_HAVE_ATOMIC_INT
1013   last_unref = (_dbus_atomic_dec (&connection->refcount) == 1);
1014 #else  
1015   _dbus_assert (connection->refcount.value > 0);
1016
1017   connection->refcount.value -= 1;
1018   last_unref = (connection->refcount.value == 0);
1019 #if 0
1020   printf ("unref_unlocked() connection %p count = %d\n", connection, connection->refcount.value);
1021 #endif
1022 #endif
1023   
1024   if (last_unref)
1025     _dbus_connection_last_unref (connection);
1026 }
1027
1028 static dbus_uint32_t
1029 _dbus_connection_get_next_client_serial (DBusConnection *connection)
1030 {
1031   int serial;
1032
1033   serial = connection->client_serial++;
1034
1035   if (connection->client_serial < 0)
1036     connection->client_serial = 1;
1037   
1038   return serial;
1039 }
1040
1041 /**
1042  * A callback for use with dbus_watch_new() to create a DBusWatch.
1043  * 
1044  * @todo This is basically a hack - we could delete _dbus_transport_handle_watch()
1045  * and the virtual handle_watch in DBusTransport if we got rid of it.
1046  * The reason this is some work is threading, see the _dbus_connection_handle_watch()
1047  * implementation.
1048  *
1049  * @param watch the watch.
1050  * @param condition the current condition of the file descriptors being watched.
1051  * @param data must be a pointer to a #DBusConnection
1052  * @returns #FALSE if the IO condition may not have been fully handled due to lack of memory
1053  */
1054 dbus_bool_t
1055 _dbus_connection_handle_watch (DBusWatch                   *watch,
1056                                unsigned int                 condition,
1057                                void                        *data)
1058 {
1059   DBusConnection *connection;
1060   dbus_bool_t retval;
1061   DBusDispatchStatus status;
1062
1063   connection = data;
1064   
1065   CONNECTION_LOCK (connection);
1066   _dbus_connection_acquire_io_path (connection, -1);
1067   retval = _dbus_transport_handle_watch (connection->transport,
1068                                          watch, condition);
1069   _dbus_connection_release_io_path (connection);
1070
1071   status = _dbus_connection_get_dispatch_status_unlocked (connection);
1072
1073   /* this calls out to user code */
1074   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1075   
1076   return retval;
1077 }
1078
1079 /** @} */
1080
1081 /**
1082  * @addtogroup DBusConnection
1083  *
1084  * @{
1085  */
1086
1087 /**
1088  * Opens a new connection to a remote address.
1089  *
1090  * @todo specify what the address parameter is. Right now
1091  * it's just the name of a UNIX domain socket. It should be
1092  * something more complex that encodes which transport to use.
1093  *
1094  * If the open fails, the function returns #NULL, and provides
1095  * a reason for the failure in the result parameter. Pass
1096  * #NULL for the result parameter if you aren't interested
1097  * in the reason for failure.
1098  * 
1099  * @param address the address.
1100  * @param error address where an error can be returned.
1101  * @returns new connection, or #NULL on failure.
1102  */
1103 DBusConnection*
1104 dbus_connection_open (const char     *address,
1105                       DBusError      *error)
1106 {
1107   DBusConnection *connection;
1108   DBusTransport *transport;
1109
1110   _dbus_return_val_if_fail (address != NULL, NULL);
1111   _dbus_return_val_if_error_is_set (error, NULL);
1112   
1113   transport = _dbus_transport_open (address, error);
1114   if (transport == NULL)
1115     {
1116       _DBUS_ASSERT_ERROR_IS_SET (error);
1117       return NULL;
1118     }
1119   
1120   connection = _dbus_connection_new_for_transport (transport);
1121
1122   _dbus_transport_unref (transport);
1123   
1124   if (connection == NULL)
1125     {
1126       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1127       return NULL;
1128     }
1129   
1130   return connection;
1131 }
1132
1133 /**
1134  * Increments the reference count of a DBusConnection.
1135  *
1136  * @param connection the connection.
1137  */
1138 void
1139 dbus_connection_ref (DBusConnection *connection)
1140 {
1141   _dbus_return_if_fail (connection != NULL);
1142
1143   /* The connection lock is better than the global
1144    * lock in the atomic increment fallback
1145    */
1146   
1147 #ifdef DBUS_HAVE_ATOMIC_INT
1148   _dbus_atomic_inc (&connection->refcount);
1149 #else
1150   CONNECTION_LOCK (connection);
1151   _dbus_assert (connection->refcount.value > 0);
1152
1153   connection->refcount.value += 1;
1154   CONNECTION_UNLOCK (connection);
1155 #endif
1156 }
1157
1158 static void
1159 free_outgoing_message (void *element,
1160                        void *data)
1161 {
1162   DBusMessage *message = element;
1163   DBusConnection *connection = data;
1164
1165   _dbus_message_remove_size_counter (message,
1166                                      connection->outgoing_counter,
1167                                      NULL);
1168   dbus_message_unref (message);
1169 }
1170
1171 /* This is run without the mutex held, but after the last reference
1172  * to the connection has been dropped we should have no thread-related
1173  * problems
1174  */
1175 static void
1176 _dbus_connection_last_unref (DBusConnection *connection)
1177 {
1178   DBusList *link;
1179
1180   _dbus_verbose ("Finalizing connection %p\n", connection);
1181   
1182   _dbus_assert (connection->refcount.value == 0);
1183   
1184   /* You have to disconnect the connection before unref:ing it. Otherwise
1185    * you won't get the disconnected message.
1186    */
1187   _dbus_assert (!_dbus_transport_get_is_connected (connection->transport));
1188
1189   /* ---- We're going to call various application callbacks here, hope it doesn't break anything... */
1190   _dbus_object_tree_free_all_unlocked (connection->objects);
1191   
1192   dbus_connection_set_dispatch_status_function (connection, NULL, NULL, NULL);
1193   dbus_connection_set_wakeup_main_function (connection, NULL, NULL, NULL);
1194   dbus_connection_set_unix_user_function (connection, NULL, NULL, NULL);
1195   
1196   _dbus_watch_list_free (connection->watches);
1197   connection->watches = NULL;
1198   
1199   _dbus_timeout_list_free (connection->timeouts);
1200   connection->timeouts = NULL;
1201
1202   _dbus_data_slot_list_free (&connection->slot_list);
1203   
1204   link = _dbus_list_get_first_link (&connection->filter_list);
1205   while (link != NULL)
1206     {
1207       DBusMessageFilter *filter = link->data;
1208       DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
1209
1210       filter->function = NULL;
1211       _dbus_message_filter_unref (filter); /* calls app callback */
1212       link->data = NULL;
1213       
1214       link = next;
1215     }
1216   _dbus_list_clear (&connection->filter_list);
1217   
1218   /* ---- Done with stuff that invokes application callbacks */
1219
1220   _dbus_object_tree_unref (connection->objects);  
1221
1222   _dbus_hash_table_unref (connection->pending_replies);
1223   connection->pending_replies = NULL;
1224   
1225   _dbus_list_clear (&connection->filter_list);
1226   
1227   _dbus_list_foreach (&connection->outgoing_messages,
1228                       free_outgoing_message,
1229                       connection);
1230   _dbus_list_clear (&connection->outgoing_messages);
1231   
1232   _dbus_list_foreach (&connection->incoming_messages,
1233                       (DBusForeachFunction) dbus_message_unref,
1234                       NULL);
1235   _dbus_list_clear (&connection->incoming_messages);
1236
1237   _dbus_counter_unref (connection->outgoing_counter);
1238   
1239   _dbus_transport_unref (connection->transport);
1240
1241   if (connection->disconnect_message_link)
1242     {
1243       DBusMessage *message = connection->disconnect_message_link->data;
1244       dbus_message_unref (message);
1245       _dbus_list_free_link (connection->disconnect_message_link);
1246     }
1247
1248   _dbus_list_clear (&connection->link_cache);
1249   
1250   dbus_condvar_free (connection->dispatch_cond);
1251   dbus_condvar_free (connection->io_path_cond);
1252   dbus_condvar_free (connection->message_returned_cond);  
1253   
1254   dbus_mutex_free (connection->mutex);
1255   
1256   dbus_free (connection);
1257 }
1258
1259 /**
1260  * Decrements the reference count of a DBusConnection, and finalizes
1261  * it if the count reaches zero.  It is a bug to drop the last reference
1262  * to a connection that has not been disconnected.
1263  *
1264  * @todo in practice it can be quite tricky to never unref a connection
1265  * that's still connected; maybe there's some way we could avoid
1266  * the requirement.
1267  *
1268  * @param connection the connection.
1269  */
1270 void
1271 dbus_connection_unref (DBusConnection *connection)
1272 {
1273   dbus_bool_t last_unref;
1274
1275   _dbus_return_if_fail (connection != NULL);
1276
1277   /* The connection lock is better than the global
1278    * lock in the atomic increment fallback
1279    */
1280   
1281 #ifdef DBUS_HAVE_ATOMIC_INT
1282   last_unref = (_dbus_atomic_dec (&connection->refcount) == 1);
1283 #else
1284   CONNECTION_LOCK (connection);
1285   
1286   _dbus_assert (connection->refcount.value > 0);
1287
1288   connection->refcount.value -= 1;
1289   last_unref = (connection->refcount.value == 0);
1290
1291 #if 0
1292   printf ("unref() connection %p count = %d\n", connection, connection->refcount.value);
1293 #endif
1294   
1295   CONNECTION_UNLOCK (connection);
1296 #endif
1297   
1298   if (last_unref)
1299     _dbus_connection_last_unref (connection);
1300 }
1301
1302 /**
1303  * Closes the connection, so no further data can be sent or received.
1304  * Any further attempts to send data will result in errors.  This
1305  * function does not affect the connection's reference count.  It's
1306  * safe to disconnect a connection more than once; all calls after the
1307  * first do nothing. It's impossible to "reconnect" a connection, a
1308  * new connection must be created.
1309  *
1310  * @param connection the connection.
1311  */
1312 void
1313 dbus_connection_disconnect (DBusConnection *connection)
1314 {
1315   _dbus_return_if_fail (connection != NULL);
1316   
1317   CONNECTION_LOCK (connection);
1318   _dbus_transport_disconnect (connection->transport);
1319   CONNECTION_UNLOCK (connection);
1320 }
1321
1322 static dbus_bool_t
1323 _dbus_connection_get_is_connected_unlocked (DBusConnection *connection)
1324 {
1325   return _dbus_transport_get_is_connected (connection->transport);
1326 }
1327
1328 /**
1329  * Gets whether the connection is currently connected.  All
1330  * connections are connected when they are opened.  A connection may
1331  * become disconnected when the remote application closes its end, or
1332  * exits; a connection may also be disconnected with
1333  * dbus_connection_disconnect().
1334  *
1335  * @param connection the connection.
1336  * @returns #TRUE if the connection is still alive.
1337  */
1338 dbus_bool_t
1339 dbus_connection_get_is_connected (DBusConnection *connection)
1340 {
1341   dbus_bool_t res;
1342
1343   _dbus_return_val_if_fail (connection != NULL, FALSE);
1344   
1345   CONNECTION_LOCK (connection);
1346   res = _dbus_connection_get_is_connected_unlocked (connection);
1347   CONNECTION_UNLOCK (connection);
1348   
1349   return res;
1350 }
1351
1352 /**
1353  * Gets whether the connection was authenticated. (Note that
1354  * if the connection was authenticated then disconnected,
1355  * this function still returns #TRUE)
1356  *
1357  * @param connection the connection
1358  * @returns #TRUE if the connection was ever authenticated
1359  */
1360 dbus_bool_t
1361 dbus_connection_get_is_authenticated (DBusConnection *connection)
1362 {
1363   dbus_bool_t res;
1364
1365   _dbus_return_val_if_fail (connection != NULL, FALSE);
1366   
1367   CONNECTION_LOCK (connection);
1368   res = _dbus_transport_get_is_authenticated (connection->transport);
1369   CONNECTION_UNLOCK (connection);
1370   
1371   return res;
1372 }
1373
1374 /**
1375  * Set whether _exit() should be called when the connection receives a
1376  * disconnect signal. The call to _exit() comes after any handlers for
1377  * the disconnect signal run; handlers can cancel the exit by calling
1378  * this function.
1379  *
1380  * By default, exit_on_disconnect is #FALSE; but for message bus
1381  * connections returned from dbus_bus_get() it will be toggled on
1382  * by default.
1383  *
1384  * @param connection the connection
1385  * @param exit_on_disconnect #TRUE if _exit() should be called after a disconnect signal
1386  */
1387 void
1388 dbus_connection_set_exit_on_disconnect (DBusConnection *connection,
1389                                         dbus_bool_t     exit_on_disconnect)
1390 {
1391   _dbus_return_if_fail (connection != NULL);
1392
1393   CONNECTION_LOCK (connection);
1394   connection->exit_on_disconnect = exit_on_disconnect != FALSE;
1395   CONNECTION_UNLOCK (connection);
1396 }
1397
1398 static DBusPreallocatedSend*
1399 _dbus_connection_preallocate_send_unlocked (DBusConnection *connection)
1400 {
1401   DBusPreallocatedSend *preallocated;
1402
1403   _dbus_return_val_if_fail (connection != NULL, NULL);
1404   
1405   preallocated = dbus_new (DBusPreallocatedSend, 1);
1406   if (preallocated == NULL)
1407     return NULL;
1408
1409   if (connection->link_cache != NULL)
1410     {
1411       preallocated->queue_link =
1412         _dbus_list_pop_first_link (&connection->link_cache);
1413       preallocated->queue_link->data = NULL;
1414     }
1415   else
1416     {
1417       preallocated->queue_link = _dbus_list_alloc_link (NULL);
1418       if (preallocated->queue_link == NULL)
1419         goto failed_0;
1420     }
1421   
1422   if (connection->link_cache != NULL)
1423     {
1424       preallocated->counter_link =
1425         _dbus_list_pop_first_link (&connection->link_cache);
1426       preallocated->counter_link->data = connection->outgoing_counter;
1427     }
1428   else
1429     {
1430       preallocated->counter_link = _dbus_list_alloc_link (connection->outgoing_counter);
1431       if (preallocated->counter_link == NULL)
1432         goto failed_1;
1433     }
1434
1435   _dbus_counter_ref (preallocated->counter_link->data);
1436
1437   preallocated->connection = connection;
1438   
1439   return preallocated;
1440   
1441  failed_1:
1442   _dbus_list_free_link (preallocated->queue_link);
1443  failed_0:
1444   dbus_free (preallocated);
1445   
1446   return NULL;
1447 }
1448
1449 /**
1450  * Preallocates resources needed to send a message, allowing the message 
1451  * to be sent without the possibility of memory allocation failure.
1452  * Allows apps to create a future guarantee that they can send
1453  * a message regardless of memory shortages.
1454  *
1455  * @param connection the connection we're preallocating for.
1456  * @returns the preallocated resources, or #NULL
1457  */
1458 DBusPreallocatedSend*
1459 dbus_connection_preallocate_send (DBusConnection *connection)
1460 {
1461   DBusPreallocatedSend *preallocated;
1462
1463   _dbus_return_val_if_fail (connection != NULL, NULL);
1464
1465   CONNECTION_LOCK (connection);
1466   
1467   preallocated =
1468     _dbus_connection_preallocate_send_unlocked (connection);
1469
1470   CONNECTION_UNLOCK (connection);
1471
1472   return preallocated;
1473 }
1474
1475 /**
1476  * Frees preallocated message-sending resources from
1477  * dbus_connection_preallocate_send(). Should only
1478  * be called if the preallocated resources are not used
1479  * to send a message.
1480  *
1481  * @param connection the connection
1482  * @param preallocated the resources
1483  */
1484 void
1485 dbus_connection_free_preallocated_send (DBusConnection       *connection,
1486                                         DBusPreallocatedSend *preallocated)
1487 {
1488   _dbus_return_if_fail (connection != NULL);
1489   _dbus_return_if_fail (preallocated != NULL);  
1490   _dbus_return_if_fail (connection == preallocated->connection);
1491
1492   _dbus_list_free_link (preallocated->queue_link);
1493   _dbus_counter_unref (preallocated->counter_link->data);
1494   _dbus_list_free_link (preallocated->counter_link);
1495   dbus_free (preallocated);
1496 }
1497
1498 static void
1499 _dbus_connection_send_preallocated_unlocked (DBusConnection       *connection,
1500                                              DBusPreallocatedSend *preallocated,
1501                                              DBusMessage          *message,
1502                                              dbus_uint32_t        *client_serial)
1503 {
1504   dbus_uint32_t serial;
1505
1506   preallocated->queue_link->data = message;
1507   _dbus_list_prepend_link (&connection->outgoing_messages,
1508                            preallocated->queue_link);
1509
1510   _dbus_message_add_size_counter_link (message,
1511                                        preallocated->counter_link);
1512
1513   dbus_free (preallocated);
1514   preallocated = NULL;
1515   
1516   dbus_message_ref (message);
1517   
1518   connection->n_outgoing += 1;
1519
1520   _dbus_verbose ("Message %p (%d %s '%s') added to outgoing queue %p, %d pending to send\n",
1521                  message,
1522                  dbus_message_get_type (message),
1523                  dbus_message_get_interface (message) ?
1524                  dbus_message_get_interface (message) :
1525                  "no interface",
1526                  dbus_message_get_signature (message),
1527                  connection,
1528                  connection->n_outgoing);
1529
1530   if (dbus_message_get_serial (message) == 0)
1531     {
1532       serial = _dbus_connection_get_next_client_serial (connection);
1533       _dbus_message_set_serial (message, serial);
1534       if (client_serial)
1535         *client_serial = serial;
1536     }
1537   else
1538     {
1539       if (client_serial)
1540         *client_serial = dbus_message_get_serial (message);
1541     }
1542   
1543   _dbus_message_lock (message);
1544
1545   if (connection->n_outgoing == 1)
1546     _dbus_transport_messages_pending (connection->transport,
1547                                       connection->n_outgoing);
1548   
1549   _dbus_connection_wakeup_mainloop (connection);
1550 }
1551
1552 /**
1553  * Sends a message using preallocated resources. This function cannot fail.
1554  * It works identically to dbus_connection_send() in other respects.
1555  * Preallocated resources comes from dbus_connection_preallocate_send().
1556  * This function "consumes" the preallocated resources, they need not
1557  * be freed separately.
1558  *
1559  * @param connection the connection
1560  * @param preallocated the preallocated resources
1561  * @param message the message to send
1562  * @param client_serial return location for client serial assigned to the message
1563  */
1564 void
1565 dbus_connection_send_preallocated (DBusConnection       *connection,
1566                                    DBusPreallocatedSend *preallocated,
1567                                    DBusMessage          *message,
1568                                    dbus_uint32_t        *client_serial)
1569 {
1570   _dbus_return_if_fail (connection != NULL);
1571   _dbus_return_if_fail (preallocated != NULL);
1572   _dbus_return_if_fail (message != NULL);
1573   _dbus_return_if_fail (preallocated->connection == connection);
1574   _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_METHOD_CALL ||
1575                         (dbus_message_get_interface (message) != NULL &&
1576                          dbus_message_get_member (message) != NULL));
1577   _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL ||
1578                         (dbus_message_get_interface (message) != NULL &&
1579                          dbus_message_get_member (message) != NULL));
1580   
1581   CONNECTION_LOCK (connection);
1582   _dbus_connection_send_preallocated_unlocked (connection,
1583                                                preallocated,
1584                                                message, client_serial);
1585   CONNECTION_UNLOCK (connection);  
1586 }
1587
1588 static dbus_bool_t
1589 _dbus_connection_send_unlocked (DBusConnection *connection,
1590                                 DBusMessage    *message,
1591                                 dbus_uint32_t  *client_serial)
1592 {
1593   DBusPreallocatedSend *preallocated;
1594
1595   _dbus_assert (connection != NULL);
1596   _dbus_assert (message != NULL);
1597   
1598   preallocated = _dbus_connection_preallocate_send_unlocked (connection);
1599   if (preallocated == NULL)
1600     return FALSE;
1601
1602
1603   _dbus_connection_send_preallocated_unlocked (connection,
1604                                                preallocated,
1605                                                message,
1606                                                client_serial);
1607   return TRUE;
1608 }
1609
1610 /**
1611  * Adds a message to the outgoing message queue. Does not block to
1612  * write the message to the network; that happens asynchronously. To
1613  * force the message to be written, call dbus_connection_flush().
1614  * Because this only queues the message, the only reason it can
1615  * fail is lack of memory. Even if the connection is disconnected,
1616  * no error will be returned.
1617  *
1618  * If the function fails due to lack of memory, it returns #FALSE.
1619  * The function will never fail for other reasons; even if the
1620  * connection is disconnected, you can queue an outgoing message,
1621  * though obviously it won't be sent.
1622  * 
1623  * @param connection the connection.
1624  * @param message the message to write.
1625  * @param client_serial return location for client serial.
1626  * @returns #TRUE on success.
1627  */
1628 dbus_bool_t
1629 dbus_connection_send (DBusConnection *connection,
1630                       DBusMessage    *message,
1631                       dbus_uint32_t  *client_serial)
1632 {
1633   _dbus_return_val_if_fail (connection != NULL, FALSE);
1634   _dbus_return_val_if_fail (message != NULL, FALSE);
1635
1636   CONNECTION_LOCK (connection);
1637
1638   if (!_dbus_connection_send_unlocked (connection, message, client_serial))
1639     {
1640       CONNECTION_UNLOCK (connection);
1641       return FALSE;
1642     }
1643
1644   CONNECTION_UNLOCK (connection);
1645   return TRUE;
1646 }
1647
1648 static dbus_bool_t
1649 reply_handler_timeout (void *data)
1650 {
1651   DBusConnection *connection;
1652   DBusDispatchStatus status;
1653   DBusPendingCall *pending = data;
1654
1655   connection = pending->connection;
1656   
1657   CONNECTION_LOCK (connection);
1658   if (pending->timeout_link)
1659     {
1660       _dbus_connection_queue_synthesized_message_link (connection,
1661                                                        pending->timeout_link);
1662       pending->timeout_link = NULL;
1663     }
1664
1665   _dbus_connection_remove_timeout (connection,
1666                                    pending->timeout);
1667   pending->timeout_added = FALSE;
1668
1669   status = _dbus_connection_get_dispatch_status_unlocked (connection);
1670
1671   /* Unlocks, and calls out to user code */
1672   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1673   
1674   return TRUE;
1675 }
1676
1677 /**
1678  * Queues a message to send, as with dbus_connection_send_message(),
1679  * but also returns a #DBusPendingCall used to receive a reply to the
1680  * message. If no reply is received in the given timeout_milliseconds,
1681  * this function expires the pending reply and generates a synthetic
1682  * error reply (generated in-process, not by the remote application)
1683  * indicating that a timeout occurred.
1684  *
1685  * A #DBusPendingCall will see a reply message after any filters, but
1686  * before any object instances or other handlers. A #DBusPendingCall
1687  * will always see exactly one reply message, unless it's cancelled
1688  * with dbus_pending_call_cancel().
1689  * 
1690  * If a filter filters out the reply before the handler sees it, the
1691  * reply is immediately timed out and a timeout error reply is
1692  * generated. If a filter removes the timeout error reply then the
1693  * #DBusPendingCall will get confused. Filtering the timeout error
1694  * is thus considered a bug and will print a warning.
1695  * 
1696  * If #NULL is passed for the pending_return, the #DBusPendingCall
1697  * will still be generated internally, and used to track
1698  * the message reply timeout. This means a timeout error will
1699  * occur if no reply arrives, unlike with dbus_connection_send().
1700  *
1701  * If -1 is passed for the timeout, a sane default timeout is used. -1
1702  * is typically the best value for the timeout for this reason, unless
1703  * you want a very short or very long timeout.  There is no way to
1704  * avoid a timeout entirely, other than passing INT_MAX for the
1705  * timeout to postpone it indefinitely.
1706  * 
1707  * @param connection the connection
1708  * @param message the message to send
1709  * @param pending_return return location for a #DBusPendingCall object, or #NULL
1710  * @param timeout_milliseconds timeout in milliseconds or -1 for default
1711  * @returns #TRUE if the message is successfully queued, #FALSE if no memory.
1712  *
1713  */
1714 dbus_bool_t
1715 dbus_connection_send_with_reply (DBusConnection     *connection,
1716                                  DBusMessage        *message,
1717                                  DBusPendingCall   **pending_return,
1718                                  int                 timeout_milliseconds)
1719 {
1720   DBusPendingCall *pending;
1721   DBusMessage *reply;
1722   DBusList *reply_link;
1723   dbus_int32_t serial = -1;
1724
1725   _dbus_return_val_if_fail (connection != NULL, FALSE);
1726   _dbus_return_val_if_fail (message != NULL, FALSE);
1727   _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
1728
1729   if (pending_return)
1730     *pending_return = NULL;
1731   
1732   pending = _dbus_pending_call_new (connection,
1733                                     timeout_milliseconds,
1734                                     reply_handler_timeout);
1735
1736   if (pending == NULL)
1737     return FALSE;
1738
1739   CONNECTION_LOCK (connection);
1740   
1741   /* Assign a serial to the message */
1742   if (dbus_message_get_serial (message) == 0)
1743     {
1744       serial = _dbus_connection_get_next_client_serial (connection);
1745       _dbus_message_set_serial (message, serial);
1746     }
1747
1748   pending->reply_serial = serial;
1749
1750   reply = dbus_message_new_error (message, DBUS_ERROR_NO_REPLY,
1751                                   "No reply within specified time");
1752   if (!reply)
1753     {
1754       CONNECTION_UNLOCK (connection);
1755       dbus_pending_call_unref (pending);
1756       return FALSE;
1757     }
1758
1759   reply_link = _dbus_list_alloc_link (reply);
1760   if (!reply)
1761     {
1762       CONNECTION_UNLOCK (connection);
1763       dbus_message_unref (reply);
1764       dbus_pending_call_unref (pending);
1765       return FALSE;
1766     }
1767
1768   pending->timeout_link = reply_link;
1769
1770   /* Insert the serial in the pending replies hash;
1771    * hash takes a refcount on DBusPendingCall.
1772    * Also, add the timeout.
1773    */
1774   if (!_dbus_connection_attach_pending_call_unlocked (connection,
1775                                                       pending))
1776     {
1777       CONNECTION_UNLOCK (connection);
1778       dbus_pending_call_unref (pending);
1779       return FALSE;
1780     }
1781   
1782   if (!_dbus_connection_send_unlocked (connection, message, NULL))
1783     {
1784       _dbus_connection_detach_pending_call_and_unlock (connection,
1785                                                        pending);
1786       return FALSE;
1787     }
1788
1789   if (pending_return)
1790     {
1791       dbus_pending_call_ref (pending);
1792       *pending_return = pending;
1793     }
1794
1795   CONNECTION_UNLOCK (connection);
1796   
1797   return TRUE;
1798 }
1799
1800 static DBusMessage*
1801 check_for_reply_unlocked (DBusConnection *connection,
1802                           dbus_uint32_t   client_serial)
1803 {
1804   DBusList *link;
1805   
1806   link = _dbus_list_get_first_link (&connection->incoming_messages);
1807
1808   while (link != NULL)
1809     {
1810       DBusMessage *reply = link->data;
1811
1812       if (dbus_message_get_reply_serial (reply) == client_serial)
1813         {
1814           _dbus_list_remove_link (&connection->incoming_messages, link);
1815           connection->n_incoming  -= 1;
1816           dbus_message_ref (reply);
1817           return reply;
1818         }
1819       link = _dbus_list_get_next_link (&connection->incoming_messages, link);
1820     }
1821
1822   return NULL;
1823 }
1824
1825 /**
1826  * Blocks a certain time period while waiting for a reply.
1827  * If no reply arrives, returns #NULL.
1828  *
1829  * @todo could use performance improvements (it keeps scanning
1830  * the whole message queue for example) and has thread issues,
1831  * see comments in source
1832  *
1833  * @param connection the connection
1834  * @param client_serial the reply serial to wait for
1835  * @param timeout_milliseconds timeout in milliseconds or -1 for default
1836  * @returns the message that is the reply or #NULL if no reply
1837  */
1838 DBusMessage*
1839 _dbus_connection_block_for_reply (DBusConnection     *connection,
1840                                   dbus_uint32_t       client_serial,
1841                                   int                 timeout_milliseconds)
1842 {
1843   long start_tv_sec, start_tv_usec;
1844   long end_tv_sec, end_tv_usec;
1845   long tv_sec, tv_usec;
1846   DBusDispatchStatus status;
1847
1848   _dbus_return_val_if_fail (connection != NULL, NULL);
1849   _dbus_return_val_if_fail (client_serial != 0, NULL);
1850   _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
1851   
1852   if (timeout_milliseconds == -1)
1853     timeout_milliseconds = _DBUS_DEFAULT_TIMEOUT_VALUE;
1854
1855   /* it would probably seem logical to pass in _DBUS_INT_MAX
1856    * for infinite timeout, but then math below would get
1857    * all overflow-prone, so smack that down.
1858    */
1859   if (timeout_milliseconds > _DBUS_ONE_HOUR_IN_MILLISECONDS * 6)
1860     timeout_milliseconds = _DBUS_ONE_HOUR_IN_MILLISECONDS * 6;
1861   
1862   /* Flush message queue */
1863   dbus_connection_flush (connection);
1864
1865   CONNECTION_LOCK (connection);
1866
1867   _dbus_get_current_time (&start_tv_sec, &start_tv_usec);
1868   end_tv_sec = start_tv_sec + timeout_milliseconds / 1000;
1869   end_tv_usec = start_tv_usec + (timeout_milliseconds % 1000) * 1000;
1870   end_tv_sec += end_tv_usec / _DBUS_USEC_PER_SECOND;
1871   end_tv_usec = end_tv_usec % _DBUS_USEC_PER_SECOND;
1872
1873   _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",
1874                  timeout_milliseconds,
1875                  client_serial,
1876                  start_tv_sec, start_tv_usec,
1877                  end_tv_sec, end_tv_usec);
1878   
1879   /* Now we wait... */
1880   /* THREAD TODO: This is busted. What if a dispatch() or pop_message
1881    * gets the message before we do?
1882    */
1883   /* always block at least once as we know we don't have the reply yet */
1884   _dbus_connection_do_iteration (connection,
1885                                  DBUS_ITERATION_DO_READING |
1886                                  DBUS_ITERATION_BLOCK,
1887                                  timeout_milliseconds);
1888
1889  recheck_status:
1890
1891   /* queue messages and get status */
1892   status = _dbus_connection_get_dispatch_status_unlocked (connection);
1893
1894   if (status == DBUS_DISPATCH_DATA_REMAINS)
1895     {
1896       DBusMessage *reply;
1897       
1898       reply = check_for_reply_unlocked (connection, client_serial);
1899       if (reply != NULL)
1900         {          
1901           status = _dbus_connection_get_dispatch_status_unlocked (connection);
1902
1903           _dbus_verbose ("dbus_connection_send_with_reply_and_block(): got reply\n");
1904
1905           /* Unlocks, and calls out to user code */
1906           _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1907           
1908           return reply;
1909         }
1910     }
1911   
1912   _dbus_get_current_time (&tv_sec, &tv_usec);
1913   
1914   if (tv_sec < start_tv_sec)
1915     _dbus_verbose ("dbus_connection_send_with_reply_and_block(): clock set backward\n");
1916   else if (connection->disconnect_message_link == NULL)
1917     _dbus_verbose ("dbus_connection_send_with_reply_and_block(): disconnected\n");
1918   else if (tv_sec < end_tv_sec ||
1919            (tv_sec == end_tv_sec && tv_usec < end_tv_usec))
1920     {
1921       timeout_milliseconds = (end_tv_sec - tv_sec) * 1000 +
1922         (end_tv_usec - tv_usec) / 1000;
1923       _dbus_verbose ("dbus_connection_send_with_reply_and_block(): %d milliseconds remain\n", timeout_milliseconds);
1924       _dbus_assert (timeout_milliseconds >= 0);
1925       
1926       if (status == DBUS_DISPATCH_NEED_MEMORY)
1927         {
1928           /* Try sleeping a bit, as we aren't sure we need to block for reading,
1929            * we may already have a reply in the buffer and just can't process
1930            * it.
1931            */
1932           _dbus_verbose ("dbus_connection_send_with_reply_and_block() waiting for more memory\n");
1933           
1934           if (timeout_milliseconds < 100)
1935             ; /* just busy loop */
1936           else if (timeout_milliseconds <= 1000)
1937             _dbus_sleep_milliseconds (timeout_milliseconds / 3);
1938           else
1939             _dbus_sleep_milliseconds (1000);
1940         }
1941       else
1942         {          
1943           /* block again, we don't have the reply buffered yet. */
1944           _dbus_connection_do_iteration (connection,
1945                                          DBUS_ITERATION_DO_READING |
1946                                          DBUS_ITERATION_BLOCK,
1947                                          timeout_milliseconds);
1948         }
1949
1950       goto recheck_status;
1951     }
1952
1953   _dbus_verbose ("dbus_connection_send_with_reply_and_block(): Waited %ld milliseconds and got no reply\n",
1954                  (tv_sec - start_tv_sec) * 1000 + (tv_usec - start_tv_usec) / 1000);
1955
1956   /* unlocks and calls out to user code */
1957   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1958
1959   return NULL;
1960 }
1961
1962 /**
1963  * Sends a message and blocks a certain time period while waiting for
1964  * a reply.  This function does not reenter the main loop,
1965  * i.e. messages other than the reply are queued up but not
1966  * processed. This function is used to do non-reentrant "method
1967  * calls."
1968  * 
1969  * If a normal reply is received, it is returned, and removed from the
1970  * incoming message queue. If it is not received, #NULL is returned
1971  * and the error is set to #DBUS_ERROR_NO_REPLY.  If an error reply is
1972  * received, it is converted to a #DBusError and returned as an error,
1973  * then the reply message is deleted. If something else goes wrong,
1974  * result is set to whatever is appropriate, such as
1975  * #DBUS_ERROR_NO_MEMORY or #DBUS_ERROR_DISCONNECTED.
1976  *
1977  * @param connection the connection
1978  * @param message the message to send
1979  * @param timeout_milliseconds timeout in milliseconds or -1 for default
1980  * @param error return location for error message
1981  * @returns the message that is the reply or #NULL with an error code if the
1982  * function fails.
1983  */
1984 DBusMessage *
1985 dbus_connection_send_with_reply_and_block (DBusConnection     *connection,
1986                                            DBusMessage        *message,
1987                                            int                 timeout_milliseconds,
1988                                            DBusError          *error)
1989 {
1990   dbus_uint32_t client_serial;
1991   DBusMessage *reply;
1992   
1993   _dbus_return_val_if_fail (connection != NULL, NULL);
1994   _dbus_return_val_if_fail (message != NULL, NULL);
1995   _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);  
1996   _dbus_return_val_if_error_is_set (error, NULL);
1997   
1998   if (!dbus_connection_send (connection, message, &client_serial))
1999     {
2000       _DBUS_SET_OOM (error);
2001       return NULL;
2002     }
2003
2004   reply = _dbus_connection_block_for_reply (connection,
2005                                             client_serial,
2006                                             timeout_milliseconds);
2007   
2008   if (reply == NULL)
2009     {
2010       if (dbus_connection_get_is_connected (connection))
2011         dbus_set_error (error, DBUS_ERROR_NO_REPLY, "Message did not receive a reply");
2012       else
2013         dbus_set_error (error, DBUS_ERROR_DISCONNECTED, "Disconnected prior to receiving a reply");
2014
2015       return NULL;
2016     }
2017   else if (dbus_set_error_from_message (error, reply))
2018     {
2019       dbus_message_unref (reply);
2020       return NULL;
2021     }
2022   else
2023     return reply;
2024 }
2025
2026 /**
2027  * Blocks until the outgoing message queue is empty.
2028  *
2029  * @param connection the connection.
2030  */
2031 void
2032 dbus_connection_flush (DBusConnection *connection)
2033 {
2034   /* We have to specify DBUS_ITERATION_DO_READING here because
2035    * otherwise we could have two apps deadlock if they are both doing
2036    * a flush(), and the kernel buffers fill up. This could change the
2037    * dispatch status.
2038    */
2039   DBusDispatchStatus status;
2040
2041   _dbus_return_if_fail (connection != NULL);
2042   
2043   CONNECTION_LOCK (connection);
2044   while (connection->n_outgoing > 0 &&
2045          _dbus_connection_get_is_connected_unlocked (connection))
2046     _dbus_connection_do_iteration (connection,
2047                                    DBUS_ITERATION_DO_READING |
2048                                    DBUS_ITERATION_DO_WRITING |
2049                                    DBUS_ITERATION_BLOCK,
2050                                    -1);
2051
2052   status = _dbus_connection_get_dispatch_status_unlocked (connection);
2053
2054   /* Unlocks and calls out to user code */
2055   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2056 }
2057
2058 /* Call with mutex held. Will drop it while waiting and re-acquire
2059  * before returning
2060  */
2061 static void
2062 _dbus_connection_wait_for_borrowed (DBusConnection *connection)
2063 {
2064   _dbus_assert (connection->message_borrowed != NULL);
2065
2066   while (connection->message_borrowed != NULL)
2067     dbus_condvar_wait (connection->message_returned_cond, connection->mutex);
2068 }
2069
2070 /**
2071  * Returns the first-received message from the incoming message queue,
2072  * leaving it in the queue. If the queue is empty, returns #NULL.
2073  * 
2074  * The caller does not own a reference to the returned message, and
2075  * must either return it using dbus_connection_return_message() or
2076  * keep it after calling dbus_connection_steal_borrowed_message(). No
2077  * one can get at the message while its borrowed, so return it as
2078  * quickly as possible and don't keep a reference to it after
2079  * returning it. If you need to keep the message, make a copy of it.
2080  *
2081  * @param connection the connection.
2082  * @returns next message in the incoming queue.
2083  */
2084 DBusMessage*
2085 dbus_connection_borrow_message  (DBusConnection *connection)
2086 {
2087   DBusMessage *message;
2088   DBusDispatchStatus status;
2089
2090   _dbus_return_val_if_fail (connection != NULL, NULL);
2091   /* can't borrow during dispatch */
2092   _dbus_return_val_if_fail (!connection->dispatch_acquired, NULL);
2093   
2094   /* this is called for the side effect that it queues
2095    * up any messages from the transport
2096    */
2097   status = dbus_connection_get_dispatch_status (connection);
2098   if (status != DBUS_DISPATCH_DATA_REMAINS)
2099     return NULL;
2100   
2101   CONNECTION_LOCK (connection);
2102
2103   if (connection->message_borrowed != NULL)
2104     _dbus_connection_wait_for_borrowed (connection);
2105   
2106   message = _dbus_list_get_first (&connection->incoming_messages);
2107
2108   if (message) 
2109     connection->message_borrowed = message;
2110   
2111   CONNECTION_UNLOCK (connection);
2112   return message;
2113 }
2114
2115 /**
2116  * Used to return a message after peeking at it using
2117  * dbus_connection_borrow_message().
2118  *
2119  * @param connection the connection
2120  * @param message the message from dbus_connection_borrow_message()
2121  */
2122 void
2123 dbus_connection_return_message (DBusConnection *connection,
2124                                 DBusMessage    *message)
2125 {
2126   _dbus_return_if_fail (connection != NULL);
2127   _dbus_return_if_fail (message != NULL);
2128   /* can't borrow during dispatch */
2129   _dbus_return_if_fail (!connection->dispatch_acquired);
2130   
2131   CONNECTION_LOCK (connection);
2132   
2133   _dbus_assert (message == connection->message_borrowed);
2134   
2135   connection->message_borrowed = NULL;
2136   dbus_condvar_wake_all (connection->message_returned_cond);
2137   
2138   CONNECTION_UNLOCK (connection);
2139 }
2140
2141 /**
2142  * Used to keep a message after peeking at it using
2143  * dbus_connection_borrow_message(). Before using this function, see
2144  * the caveats/warnings in the documentation for
2145  * dbus_connection_pop_message().
2146  *
2147  * @param connection the connection
2148  * @param message the message from dbus_connection_borrow_message()
2149  */
2150 void
2151 dbus_connection_steal_borrowed_message (DBusConnection *connection,
2152                                         DBusMessage    *message)
2153 {
2154   DBusMessage *pop_message;
2155
2156   _dbus_return_if_fail (connection != NULL);
2157   _dbus_return_if_fail (message != NULL);
2158   /* can't borrow during dispatch */
2159   _dbus_return_if_fail (!connection->dispatch_acquired);
2160   
2161   CONNECTION_LOCK (connection);
2162  
2163   _dbus_assert (message == connection->message_borrowed);
2164
2165   pop_message = _dbus_list_pop_first (&connection->incoming_messages);
2166   _dbus_assert (message == pop_message);
2167   
2168   connection->n_incoming -= 1;
2169  
2170   _dbus_verbose ("Incoming message %p stolen from queue, %d incoming\n",
2171                  message, connection->n_incoming);
2172  
2173   connection->message_borrowed = NULL;
2174   dbus_condvar_wake_all (connection->message_returned_cond);
2175   
2176   CONNECTION_UNLOCK (connection);
2177 }
2178
2179 /* See dbus_connection_pop_message, but requires the caller to own
2180  * the lock before calling. May drop the lock while running.
2181  */
2182 static DBusList*
2183 _dbus_connection_pop_message_link_unlocked (DBusConnection *connection)
2184 {
2185   if (connection->message_borrowed != NULL)
2186     _dbus_connection_wait_for_borrowed (connection);
2187   
2188   if (connection->n_incoming > 0)
2189     {
2190       DBusList *link;
2191
2192       link = _dbus_list_pop_first_link (&connection->incoming_messages);
2193       connection->n_incoming -= 1;
2194
2195       _dbus_verbose ("Message %p (%d %s '%s') removed from incoming queue %p, %d incoming\n",
2196                      link->data,
2197                      dbus_message_get_type (link->data),
2198                      dbus_message_get_interface (link->data) ?
2199                      dbus_message_get_interface (link->data) :
2200                      "no interface",
2201                      dbus_message_get_signature (link->data),
2202                      connection, connection->n_incoming);
2203
2204       return link;
2205     }
2206   else
2207     return NULL;
2208 }
2209
2210 /* See dbus_connection_pop_message, but requires the caller to own
2211  * the lock before calling. May drop the lock while running.
2212  */
2213 static DBusMessage*
2214 _dbus_connection_pop_message_unlocked (DBusConnection *connection)
2215 {
2216   DBusList *link;
2217   
2218   link = _dbus_connection_pop_message_link_unlocked (connection);
2219
2220   if (link != NULL)
2221     {
2222       DBusMessage *message;
2223       
2224       message = link->data;
2225       
2226       _dbus_list_free_link (link);
2227       
2228       return message;
2229     }
2230   else
2231     return NULL;
2232 }
2233
2234 static void
2235 _dbus_connection_putback_message_link_unlocked (DBusConnection *connection,
2236                                                 DBusList       *message_link)
2237 {
2238   _dbus_assert (message_link != NULL);
2239   /* You can't borrow a message while a link is outstanding */
2240   _dbus_assert (connection->message_borrowed == NULL);
2241
2242   _dbus_list_prepend_link (&connection->incoming_messages,
2243                            message_link);
2244   connection->n_incoming += 1;
2245
2246   _dbus_verbose ("Message %p (%d %s '%s') put back into queue %p, %d incoming\n",
2247                  message_link->data,
2248                  dbus_message_get_type (message_link->data),
2249                  dbus_message_get_interface (message_link->data) ?
2250                  dbus_message_get_interface (message_link->data) :
2251                  "no interface",
2252                  dbus_message_get_signature (message_link->data),
2253                  connection, connection->n_incoming);
2254 }
2255
2256 /**
2257  * Returns the first-received message from the incoming message queue,
2258  * removing it from the queue. The caller owns a reference to the
2259  * returned message. If the queue is empty, returns #NULL.
2260  *
2261  * This function bypasses any message handlers that are registered,
2262  * and so using it is usually wrong. Instead, let the main loop invoke
2263  * dbus_connection_dispatch(). Popping messages manually is only
2264  * useful in very simple programs that don't share a #DBusConnection
2265  * with any libraries or other modules.
2266  *
2267  * @param connection the connection.
2268  * @returns next message in the incoming queue.
2269  */
2270 DBusMessage*
2271 dbus_connection_pop_message (DBusConnection *connection)
2272 {
2273   DBusMessage *message;
2274   DBusDispatchStatus status;
2275
2276   /* this is called for the side effect that it queues
2277    * up any messages from the transport
2278    */
2279   status = dbus_connection_get_dispatch_status (connection);
2280   if (status != DBUS_DISPATCH_DATA_REMAINS)
2281     return NULL;
2282   
2283   CONNECTION_LOCK (connection);
2284
2285   message = _dbus_connection_pop_message_unlocked (connection);
2286
2287   _dbus_verbose ("Returning popped message %p\n", message);    
2288   
2289   CONNECTION_UNLOCK (connection);
2290   
2291   return message;
2292 }
2293
2294 /**
2295  * Acquire the dispatcher. This must be done before dispatching
2296  * messages in order to guarantee the right order of
2297  * message delivery. May sleep and drop the connection mutex
2298  * while waiting for the dispatcher.
2299  *
2300  * @param connection the connection.
2301  */
2302 static void
2303 _dbus_connection_acquire_dispatch (DBusConnection *connection)
2304 {
2305   if (connection->dispatch_acquired)
2306     dbus_condvar_wait (connection->dispatch_cond, connection->mutex);
2307   _dbus_assert (!connection->dispatch_acquired);
2308
2309   connection->dispatch_acquired = TRUE;
2310 }
2311
2312 /**
2313  * Release the dispatcher when you're done with it. Only call
2314  * after you've acquired the dispatcher. Wakes up at most one
2315  * thread currently waiting to acquire the dispatcher.
2316  *
2317  * @param connection the connection.
2318  */
2319 static void
2320 _dbus_connection_release_dispatch (DBusConnection *connection)
2321 {
2322   _dbus_assert (connection->dispatch_acquired);
2323
2324   connection->dispatch_acquired = FALSE;
2325   dbus_condvar_wake_one (connection->dispatch_cond);
2326 }
2327
2328 static void
2329 _dbus_connection_failed_pop (DBusConnection *connection,
2330                              DBusList       *message_link)
2331 {
2332   _dbus_list_prepend_link (&connection->incoming_messages,
2333                            message_link);
2334   connection->n_incoming += 1;
2335 }
2336
2337 static DBusDispatchStatus
2338 _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection)
2339 {
2340   if (connection->n_incoming > 0)
2341     return DBUS_DISPATCH_DATA_REMAINS;
2342   else if (!_dbus_transport_queue_messages (connection->transport))
2343     return DBUS_DISPATCH_NEED_MEMORY;
2344   else
2345     {
2346       DBusDispatchStatus status;
2347       
2348       status = _dbus_transport_get_dispatch_status (connection->transport);
2349
2350       if (status != DBUS_DISPATCH_COMPLETE)
2351         return status;
2352       else if (connection->n_incoming > 0)
2353         return DBUS_DISPATCH_DATA_REMAINS;
2354       else
2355         return DBUS_DISPATCH_COMPLETE;
2356     }
2357 }
2358
2359 static void
2360 _dbus_connection_update_dispatch_status_and_unlock (DBusConnection    *connection,
2361                                                     DBusDispatchStatus new_status)
2362 {
2363   dbus_bool_t changed;
2364   DBusDispatchStatusFunction function;
2365   void *data;
2366
2367   /* We have the lock */
2368
2369   _dbus_connection_ref_unlocked (connection);
2370
2371   changed = new_status != connection->last_dispatch_status;
2372
2373   connection->last_dispatch_status = new_status;
2374
2375   function = connection->dispatch_status_function;
2376   data = connection->dispatch_status_data;
2377
2378   /* We drop the lock */
2379   CONNECTION_UNLOCK (connection);
2380   
2381   if (changed && function)
2382     {
2383       _dbus_verbose ("Notifying of change to dispatch status of %p now %d (%s)\n",
2384                      connection, new_status,
2385                      new_status == DBUS_DISPATCH_COMPLETE ? "complete" :
2386                      new_status == DBUS_DISPATCH_DATA_REMAINS ? "data remains" :
2387                      new_status == DBUS_DISPATCH_NEED_MEMORY ? "need memory" :
2388                      "???");
2389       (* function) (connection, new_status, data);      
2390     }
2391   
2392   dbus_connection_unref (connection);
2393 }
2394
2395 /**
2396  * Gets the current state (what we would currently return
2397  * from dbus_connection_dispatch()) but doesn't actually
2398  * dispatch any messages.
2399  * 
2400  * @param connection the connection.
2401  * @returns current dispatch status
2402  */
2403 DBusDispatchStatus
2404 dbus_connection_get_dispatch_status (DBusConnection *connection)
2405 {
2406   DBusDispatchStatus status;
2407
2408   _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
2409   
2410   CONNECTION_LOCK (connection);
2411
2412   status = _dbus_connection_get_dispatch_status_unlocked (connection);
2413   
2414   CONNECTION_UNLOCK (connection);
2415
2416   return status;
2417 }
2418
2419 /**
2420  * Processes data buffered while handling watches, queueing zero or
2421  * more incoming messages. Then pops the first-received message from
2422  * the current incoming message queue, runs any handlers for it, and
2423  * unrefs the message. Returns a status indicating whether messages/data
2424  * remain, more memory is needed, or all data has been processed.
2425  * 
2426  * Even if the dispatch status is #DBUS_DISPATCH_DATA_REMAINS,
2427  * does not necessarily dispatch a message, as the data may
2428  * be part of authentication or the like.
2429  *
2430  * @todo some FIXME in here about handling DBUS_HANDLER_RESULT_NEED_MEMORY
2431  *
2432  * @todo right now a message filter gets run on replies to a pending
2433  * call in here, but not in the case where we block without
2434  * entering the main loop.
2435  * 
2436  * @param connection the connection
2437  * @returns dispatch status
2438  */
2439 DBusDispatchStatus
2440 dbus_connection_dispatch (DBusConnection *connection)
2441 {
2442   DBusMessage *message;
2443   DBusList *link, *filter_list_copy, *message_link;
2444   DBusHandlerResult result;
2445   DBusPendingCall *pending;
2446   dbus_int32_t reply_serial;
2447   DBusDispatchStatus status;
2448
2449   _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
2450
2451   CONNECTION_LOCK (connection);
2452   status = _dbus_connection_get_dispatch_status_unlocked (connection);
2453   if (status != DBUS_DISPATCH_DATA_REMAINS)
2454     {
2455       /* unlocks and calls out to user code */
2456       _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2457       return status;
2458     }
2459   
2460   /* We need to ref the connection since the callback could potentially
2461    * drop the last ref to it
2462    */
2463   _dbus_connection_ref_unlocked (connection);
2464
2465   _dbus_connection_acquire_dispatch (connection);
2466   
2467   /* This call may drop the lock during the execution (if waiting for
2468    * borrowed messages to be returned) but the order of message
2469    * dispatch if several threads call dispatch() is still
2470    * protected by the lock, since only one will get the lock, and that
2471    * one will finish the message dispatching
2472    */
2473   message_link = _dbus_connection_pop_message_link_unlocked (connection);
2474   if (message_link == NULL)
2475     {
2476       /* another thread dispatched our stuff */
2477
2478       _dbus_connection_release_dispatch (connection);
2479
2480       status = _dbus_connection_get_dispatch_status_unlocked (connection);
2481
2482       _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2483       
2484       dbus_connection_unref (connection);
2485       
2486       return status;
2487     }
2488
2489   message = message_link->data;
2490   
2491   result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
2492
2493   reply_serial = dbus_message_get_reply_serial (message);
2494   pending = _dbus_hash_table_lookup_int (connection->pending_replies,
2495                                          reply_serial);
2496   
2497   if (!_dbus_list_copy (&connection->filter_list, &filter_list_copy))
2498     {
2499       _dbus_connection_release_dispatch (connection);
2500
2501       _dbus_connection_failed_pop (connection, message_link);
2502
2503       /* unlocks and calls user code */
2504       _dbus_connection_update_dispatch_status_and_unlock (connection,
2505                                                           DBUS_DISPATCH_NEED_MEMORY);
2506
2507       dbus_connection_unref (connection);
2508       
2509       return DBUS_DISPATCH_NEED_MEMORY;
2510     }
2511   
2512   _dbus_list_foreach (&filter_list_copy,
2513                       (DBusForeachFunction)_dbus_message_filter_ref,
2514                       NULL);
2515
2516   /* We're still protected from dispatch() reentrancy here
2517    * since we acquired the dispatcher
2518    */
2519   CONNECTION_UNLOCK (connection);
2520   
2521   link = _dbus_list_get_first_link (&filter_list_copy);
2522   while (link != NULL)
2523     {
2524       DBusMessageFilter *filter = link->data;
2525       DBusList *next = _dbus_list_get_next_link (&filter_list_copy, link);
2526
2527       _dbus_verbose ("  running filter on message %p\n", message);
2528       result = (* filter->function) (connection, message, filter->user_data);
2529
2530       if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
2531         break;
2532
2533       link = next;
2534     }
2535
2536   _dbus_list_foreach (&filter_list_copy,
2537                       (DBusForeachFunction)_dbus_message_filter_unref,
2538                       NULL);
2539   _dbus_list_clear (&filter_list_copy);
2540   
2541   CONNECTION_LOCK (connection);
2542
2543   if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
2544     goto out;
2545   
2546   /* Did a reply we were waiting on get filtered? */
2547   if (pending && result == DBUS_HANDLER_RESULT_HANDLED)
2548     {
2549       /* Queue the timeout immediately! */
2550       if (pending->timeout_link)
2551         {
2552           _dbus_connection_queue_synthesized_message_link (connection,
2553                                                            pending->timeout_link);
2554           pending->timeout_link = NULL;
2555         }
2556       else
2557         {
2558           /* We already queued the timeout? Then it was filtered! */
2559           _dbus_warn ("The timeout error with reply serial %d was filtered, so the DBusPendingCall will never stop pending.\n", reply_serial);
2560         }
2561     }
2562   
2563   if (result == DBUS_HANDLER_RESULT_HANDLED)
2564     goto out;
2565   
2566   if (pending)
2567     {
2568       _dbus_pending_call_complete_and_unlock (pending, message);
2569
2570       pending = NULL;
2571       
2572       CONNECTION_LOCK (connection);
2573       goto out;
2574     }
2575
2576   /* We're still protected from dispatch() reentrancy here
2577    * since we acquired the dispatcher
2578    */
2579   _dbus_verbose ("  running object path dispatch on message %p (%d %s '%s')\n",
2580                  message,
2581                  dbus_message_get_type (message),
2582                  dbus_message_get_interface (message) ?
2583                  dbus_message_get_interface (message) :
2584                  "no interface");
2585   
2586   result = _dbus_object_tree_dispatch_and_unlock (connection->objects,
2587                                                   message);
2588   
2589   CONNECTION_LOCK (connection);
2590
2591   if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
2592     goto out;
2593
2594   if (dbus_message_get_type (message) == DBUS_MESSAGE_TYPE_METHOD_CALL)
2595     {
2596       DBusMessage *reply;
2597       DBusString str;
2598       DBusPreallocatedSend *preallocated;
2599
2600       _dbus_verbose ("  sending error %s\n",
2601                      DBUS_ERROR_UNKNOWN_METHOD);
2602       
2603       if (!_dbus_string_init (&str))
2604         {
2605           result = DBUS_HANDLER_RESULT_NEED_MEMORY;
2606           goto out;
2607         }
2608               
2609       if (!_dbus_string_append_printf (&str,
2610                                        "Method \"%s\" on interface \"%s\" doesn't exist\n",
2611                                        dbus_message_get_member (message),
2612                                        dbus_message_get_interface (message)))
2613         {
2614           _dbus_string_free (&str);
2615           result = DBUS_HANDLER_RESULT_NEED_MEMORY;
2616           goto out;
2617         }
2618       
2619       reply = dbus_message_new_error (message,
2620                                       DBUS_ERROR_UNKNOWN_METHOD,
2621                                       _dbus_string_get_const_data (&str));
2622       _dbus_string_free (&str);
2623
2624       if (reply == NULL)
2625         {
2626           result = DBUS_HANDLER_RESULT_NEED_MEMORY;
2627           goto out;
2628         }
2629       
2630       preallocated = _dbus_connection_preallocate_send_unlocked (connection);
2631
2632       if (preallocated == NULL)
2633         {
2634           dbus_message_unref (reply);
2635           result = DBUS_HANDLER_RESULT_NEED_MEMORY;
2636           goto out;
2637         }
2638
2639       _dbus_connection_send_preallocated_unlocked (connection, preallocated,
2640                                                    reply, NULL);
2641
2642       dbus_message_unref (reply);
2643       
2644       result = DBUS_HANDLER_RESULT_HANDLED;
2645     }
2646   
2647   _dbus_verbose ("  done dispatching %p (%d %s '%s') on connection %p\n", message,
2648                  dbus_message_get_type (message),
2649                  dbus_message_get_interface (message) ?
2650                  dbus_message_get_interface (message) :
2651                  "no interface",
2652                  dbus_message_get_signature (message),
2653                  connection);
2654   
2655  out:
2656   if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
2657     {
2658       _dbus_verbose ("out of memory in %s\n", _DBUS_FUNCTION_NAME);
2659       
2660       /* Put message back, and we'll start over.
2661        * Yes this means handlers must be idempotent if they
2662        * don't return HANDLED; c'est la vie.
2663        */
2664       _dbus_connection_putback_message_link_unlocked (connection,
2665                                                       message_link);
2666     }
2667   else
2668     {
2669       _dbus_verbose ("Done with message in %s\n", _DBUS_FUNCTION_NAME);
2670       
2671       if (connection->exit_on_disconnect &&
2672           dbus_message_is_signal (message,
2673                                   DBUS_INTERFACE_ORG_FREEDESKTOP_LOCAL,
2674                                   "Disconnected"))
2675         {
2676           _dbus_verbose ("Exiting on Disconnected signal\n");
2677           CONNECTION_UNLOCK (connection);
2678           _dbus_exit (1);
2679           _dbus_assert_not_reached ("Call to exit() returned");
2680         }
2681       
2682       _dbus_list_free_link (message_link);
2683       dbus_message_unref (message); /* don't want the message to count in max message limits
2684                                      * in computing dispatch status below
2685                                      */
2686     }
2687   
2688   _dbus_connection_release_dispatch (connection);
2689   
2690   status = _dbus_connection_get_dispatch_status_unlocked (connection);
2691
2692   /* unlocks and calls user code */
2693   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2694   
2695   dbus_connection_unref (connection);
2696   
2697   return status;
2698 }
2699
2700 /**
2701  * Sets the watch functions for the connection. These functions are
2702  * responsible for making the application's main loop aware of file
2703  * descriptors that need to be monitored for events, using select() or
2704  * poll(). When using Qt, typically the DBusAddWatchFunction would
2705  * create a QSocketNotifier. When using GLib, the DBusAddWatchFunction
2706  * could call g_io_add_watch(), or could be used as part of a more
2707  * elaborate GSource. Note that when a watch is added, it may
2708  * not be enabled.
2709  *
2710  * The DBusWatchToggledFunction notifies the application that the
2711  * watch has been enabled or disabled. Call dbus_watch_get_enabled()
2712  * to check this. A disabled watch should have no effect, and enabled
2713  * watch should be added to the main loop. This feature is used
2714  * instead of simply adding/removing the watch because
2715  * enabling/disabling can be done without memory allocation.  The
2716  * toggled function may be NULL if a main loop re-queries
2717  * dbus_watch_get_enabled() every time anyway.
2718  * 
2719  * The DBusWatch can be queried for the file descriptor to watch using
2720  * dbus_watch_get_fd(), and for the events to watch for using
2721  * dbus_watch_get_flags(). The flags returned by
2722  * dbus_watch_get_flags() will only contain DBUS_WATCH_READABLE and
2723  * DBUS_WATCH_WRITABLE, never DBUS_WATCH_HANGUP or DBUS_WATCH_ERROR;
2724  * all watches implicitly include a watch for hangups, errors, and
2725  * other exceptional conditions.
2726  *
2727  * Once a file descriptor becomes readable or writable, or an exception
2728  * occurs, dbus_watch_handle() should be called to
2729  * notify the connection of the file descriptor's condition.
2730  *
2731  * dbus_watch_handle() cannot be called during the
2732  * DBusAddWatchFunction, as the connection will not be ready to handle
2733  * that watch yet.
2734  * 
2735  * It is not allowed to reference a DBusWatch after it has been passed
2736  * to remove_function.
2737  *
2738  * If #FALSE is returned due to lack of memory, the failure may be due
2739  * to a #FALSE return from the new add_function. If so, the
2740  * add_function may have been called successfully one or more times,
2741  * but the remove_function will also have been called to remove any
2742  * successful adds. i.e. if #FALSE is returned the net result
2743  * should be that dbus_connection_set_watch_functions() has no effect,
2744  * but the add_function and remove_function may have been called.
2745  *
2746  * @todo We need to drop the lock when we call the
2747  * add/remove/toggled functions which can be a side effect
2748  * of setting the watch functions.
2749  * 
2750  * @param connection the connection.
2751  * @param add_function function to begin monitoring a new descriptor.
2752  * @param remove_function function to stop monitoring a descriptor.
2753  * @param toggled_function function to notify of enable/disable
2754  * @param data data to pass to add_function and remove_function.
2755  * @param free_data_function function to be called to free the data.
2756  * @returns #FALSE on failure (no memory)
2757  */
2758 dbus_bool_t
2759 dbus_connection_set_watch_functions (DBusConnection              *connection,
2760                                      DBusAddWatchFunction         add_function,
2761                                      DBusRemoveWatchFunction      remove_function,
2762                                      DBusWatchToggledFunction     toggled_function,
2763                                      void                        *data,
2764                                      DBusFreeFunction             free_data_function)
2765 {
2766   dbus_bool_t retval;
2767
2768   _dbus_return_val_if_fail (connection != NULL, FALSE);
2769   
2770   CONNECTION_LOCK (connection);
2771   /* ref connection for slightly better reentrancy */
2772   _dbus_connection_ref_unlocked (connection);
2773
2774   /* FIXME this can call back into user code, and we need to drop the
2775    * connection lock when it does.
2776    */
2777   retval = _dbus_watch_list_set_functions (connection->watches,
2778                                            add_function, remove_function,
2779                                            toggled_function,
2780                                            data, free_data_function);
2781   
2782   CONNECTION_UNLOCK (connection);
2783   /* drop our paranoid refcount */
2784   dbus_connection_unref (connection);
2785
2786   return retval;
2787 }
2788
2789 /**
2790  * Sets the timeout functions for the connection. These functions are
2791  * responsible for making the application's main loop aware of timeouts.
2792  * When using Qt, typically the DBusAddTimeoutFunction would create a
2793  * QTimer. When using GLib, the DBusAddTimeoutFunction would call
2794  * g_timeout_add.
2795  * 
2796  * The DBusTimeoutToggledFunction notifies the application that the
2797  * timeout has been enabled or disabled. Call
2798  * dbus_timeout_get_enabled() to check this. A disabled timeout should
2799  * have no effect, and enabled timeout should be added to the main
2800  * loop. This feature is used instead of simply adding/removing the
2801  * timeout because enabling/disabling can be done without memory
2802  * allocation. With Qt, QTimer::start() and QTimer::stop() can be used
2803  * to enable and disable. The toggled function may be NULL if a main
2804  * loop re-queries dbus_timeout_get_enabled() every time anyway.
2805  * Whenever a timeout is toggled, its interval may change.
2806  *
2807  * The DBusTimeout can be queried for the timer interval using
2808  * dbus_timeout_get_interval(). dbus_timeout_handle() should be called
2809  * repeatedly, each time the interval elapses, starting after it has
2810  * elapsed once. The timeout stops firing when it is removed with the
2811  * given remove_function.  The timer interval may change whenever the
2812  * timeout is added, removed, or toggled.
2813  *
2814  * @param connection the connection.
2815  * @param add_function function to add a timeout.
2816  * @param remove_function function to remove a timeout.
2817  * @param toggled_function function to notify of enable/disable
2818  * @param data data to pass to add_function and remove_function.
2819  * @param free_data_function function to be called to free the data.
2820  * @returns #FALSE on failure (no memory)
2821  */
2822 dbus_bool_t
2823 dbus_connection_set_timeout_functions   (DBusConnection            *connection,
2824                                          DBusAddTimeoutFunction     add_function,
2825                                          DBusRemoveTimeoutFunction  remove_function,
2826                                          DBusTimeoutToggledFunction toggled_function,
2827                                          void                      *data,
2828                                          DBusFreeFunction           free_data_function)
2829 {
2830   dbus_bool_t retval;
2831
2832   _dbus_return_val_if_fail (connection != NULL, FALSE);
2833   
2834   CONNECTION_LOCK (connection);
2835   /* ref connection for slightly better reentrancy */
2836   _dbus_connection_ref_unlocked (connection);
2837   
2838   retval = _dbus_timeout_list_set_functions (connection->timeouts,
2839                                              add_function, remove_function,
2840                                              toggled_function,
2841                                              data, free_data_function);
2842   
2843   CONNECTION_UNLOCK (connection);
2844   /* drop our paranoid refcount */
2845   dbus_connection_unref (connection);
2846
2847   return retval;
2848 }
2849
2850 /**
2851  * Sets the mainloop wakeup function for the connection. Thi function is
2852  * responsible for waking up the main loop (if its sleeping) when some some
2853  * change has happened to the connection that the mainloop needs to reconsiders
2854  * (e.g. a message has been queued for writing).
2855  * When using Qt, this typically results in a call to QEventLoop::wakeUp().
2856  * When using GLib, it would call g_main_context_wakeup().
2857  *
2858  *
2859  * @param connection the connection.
2860  * @param wakeup_main_function function to wake up the mainloop
2861  * @param data data to pass wakeup_main_function
2862  * @param free_data_function function to be called to free the data.
2863  */
2864 void
2865 dbus_connection_set_wakeup_main_function (DBusConnection            *connection,
2866                                           DBusWakeupMainFunction     wakeup_main_function,
2867                                           void                      *data,
2868                                           DBusFreeFunction           free_data_function)
2869 {
2870   void *old_data;
2871   DBusFreeFunction old_free_data;
2872
2873   _dbus_return_if_fail (connection != NULL);
2874   
2875   CONNECTION_LOCK (connection);
2876   old_data = connection->wakeup_main_data;
2877   old_free_data = connection->free_wakeup_main_data;
2878
2879   connection->wakeup_main_function = wakeup_main_function;
2880   connection->wakeup_main_data = data;
2881   connection->free_wakeup_main_data = free_data_function;
2882   
2883   CONNECTION_UNLOCK (connection);
2884
2885   /* Callback outside the lock */
2886   if (old_free_data)
2887     (*old_free_data) (old_data);
2888 }
2889
2890 /**
2891  * Set a function to be invoked when the dispatch status changes.
2892  * If the dispatch status is #DBUS_DISPATCH_DATA_REMAINS, then
2893  * dbus_connection_dispatch() needs to be called to process incoming
2894  * messages. However, dbus_connection_dispatch() MUST NOT BE CALLED
2895  * from inside the DBusDispatchStatusFunction. Indeed, almost
2896  * any reentrancy in this function is a bad idea. Instead,
2897  * the DBusDispatchStatusFunction should simply save an indication
2898  * that messages should be dispatched later, when the main loop
2899  * is re-entered.
2900  *
2901  * @param connection the connection
2902  * @param function function to call on dispatch status changes
2903  * @param data data for function
2904  * @param free_data_function free the function data
2905  */
2906 void
2907 dbus_connection_set_dispatch_status_function (DBusConnection             *connection,
2908                                               DBusDispatchStatusFunction  function,
2909                                               void                       *data,
2910                                               DBusFreeFunction            free_data_function)
2911 {
2912   void *old_data;
2913   DBusFreeFunction old_free_data;
2914
2915   _dbus_return_if_fail (connection != NULL);
2916   
2917   CONNECTION_LOCK (connection);
2918   old_data = connection->dispatch_status_data;
2919   old_free_data = connection->free_dispatch_status_data;
2920
2921   connection->dispatch_status_function = function;
2922   connection->dispatch_status_data = data;
2923   connection->free_dispatch_status_data = free_data_function;
2924   
2925   CONNECTION_UNLOCK (connection);
2926
2927   /* Callback outside the lock */
2928   if (old_free_data)
2929     (*old_free_data) (old_data);
2930 }
2931
2932 /**
2933  * Gets the UNIX user ID of the connection if any.
2934  * Returns #TRUE if the uid is filled in.
2935  * Always returns #FALSE on non-UNIX platforms.
2936  * Always returns #FALSE prior to authenticating the
2937  * connection.
2938  *
2939  * @param connection the connection
2940  * @param uid return location for the user ID
2941  * @returns #TRUE if uid is filled in with a valid user ID
2942  */
2943 dbus_bool_t
2944 dbus_connection_get_unix_user (DBusConnection *connection,
2945                                unsigned long  *uid)
2946 {
2947   dbus_bool_t result;
2948
2949   _dbus_return_val_if_fail (connection != NULL, FALSE);
2950   _dbus_return_val_if_fail (uid != NULL, FALSE);
2951   
2952   CONNECTION_LOCK (connection);
2953
2954   if (!_dbus_transport_get_is_authenticated (connection->transport))
2955     result = FALSE;
2956   else
2957     result = _dbus_transport_get_unix_user (connection->transport,
2958                                             uid);
2959   CONNECTION_UNLOCK (connection);
2960
2961   return result;
2962 }
2963
2964 /**
2965  * Sets a predicate function used to determine whether a given user ID
2966  * is allowed to connect. When an incoming connection has
2967  * authenticated with a particular user ID, this function is called;
2968  * if it returns #TRUE, the connection is allowed to proceed,
2969  * otherwise the connection is disconnected.
2970  *
2971  * If the function is set to #NULL (as it is by default), then
2972  * only the same UID as the server process will be allowed to
2973  * connect.
2974  *
2975  * @param connection the connection
2976  * @param function the predicate
2977  * @param data data to pass to the predicate
2978  * @param free_data_function function to free the data
2979  */
2980 void
2981 dbus_connection_set_unix_user_function (DBusConnection             *connection,
2982                                         DBusAllowUnixUserFunction   function,
2983                                         void                       *data,
2984                                         DBusFreeFunction            free_data_function)
2985 {
2986   void *old_data = NULL;
2987   DBusFreeFunction old_free_function = NULL;
2988
2989   _dbus_return_if_fail (connection != NULL);
2990   
2991   CONNECTION_LOCK (connection);
2992   _dbus_transport_set_unix_user_function (connection->transport,
2993                                           function, data, free_data_function,
2994                                           &old_data, &old_free_function);
2995   CONNECTION_UNLOCK (connection);
2996
2997   if (old_free_function != NULL)
2998     (* old_free_function) (old_data);    
2999 }
3000
3001 /**
3002  * Adds a message filter. Filters are handlers that are run on all
3003  * incoming messages, prior to the objects registered with
3004  * dbus_connection_register_object_path().  Filters are run in the
3005  * order that they were added.  The same handler can be added as a
3006  * filter more than once, in which case it will be run more than once.
3007  * Filters added during a filter callback won't be run on the message
3008  * being processed.
3009  *
3010  * @todo we don't run filters on messages while blocking without
3011  * entering the main loop, since filters are run as part of
3012  * dbus_connection_dispatch().
3013  *
3014  * @param connection the connection
3015  * @param function function to handle messages
3016  * @param user_data user data to pass to the function
3017  * @param free_data_function function to use for freeing user data
3018  * @returns #TRUE on success, #FALSE if not enough memory.
3019  */
3020 dbus_bool_t
3021 dbus_connection_add_filter (DBusConnection            *connection,
3022                             DBusHandleMessageFunction  function,
3023                             void                      *user_data,
3024                             DBusFreeFunction           free_data_function)
3025 {
3026   DBusMessageFilter *filter;
3027   
3028   _dbus_return_val_if_fail (connection != NULL, FALSE);
3029   _dbus_return_val_if_fail (function != NULL, FALSE);
3030
3031   filter = dbus_new0 (DBusMessageFilter, 1);
3032   if (filter == NULL)
3033     return FALSE;
3034
3035   filter->refcount.value = 1;
3036   
3037   CONNECTION_LOCK (connection);
3038
3039   if (!_dbus_list_append (&connection->filter_list,
3040                           filter))
3041     {
3042       _dbus_message_filter_unref (filter);
3043       CONNECTION_UNLOCK (connection);
3044       return FALSE;
3045     }
3046
3047   /* Fill in filter after all memory allocated,
3048    * so we don't run the free_user_data_function
3049    * if the add_filter() fails
3050    */
3051   
3052   filter->function = function;
3053   filter->user_data = user_data;
3054   filter->free_user_data_function = free_data_function;
3055         
3056   CONNECTION_UNLOCK (connection);
3057   return TRUE;
3058 }
3059
3060 /**
3061  * Removes a previously-added message filter. It is a programming
3062  * error to call this function for a handler that has not been added
3063  * as a filter. If the given handler was added more than once, only
3064  * one instance of it will be removed (the most recently-added
3065  * instance).
3066  *
3067  * @param connection the connection
3068  * @param function the handler to remove
3069  * @param user_data user data for the handler to remove
3070  *
3071  */
3072 void
3073 dbus_connection_remove_filter (DBusConnection            *connection,
3074                                DBusHandleMessageFunction  function,
3075                                void                      *user_data)
3076 {
3077   DBusList *link;
3078   DBusMessageFilter *filter;
3079   
3080   _dbus_return_if_fail (connection != NULL);
3081   _dbus_return_if_fail (function != NULL);
3082   
3083   CONNECTION_LOCK (connection);
3084
3085   filter = NULL;
3086   
3087   link = _dbus_list_get_last_link (&connection->filter_list);
3088   while (link != NULL)
3089     {
3090       filter = link->data;
3091
3092       if (filter->function == function &&
3093           filter->user_data == user_data)
3094         {
3095           _dbus_list_remove_link (&connection->filter_list, link);
3096           filter->function = NULL;
3097           
3098           break;
3099         }
3100         
3101       link = _dbus_list_get_prev_link (&connection->filter_list, link);
3102     }
3103   
3104   CONNECTION_UNLOCK (connection);
3105
3106 #ifndef DBUS_DISABLE_CHECKS
3107   if (filter == NULL)
3108     {
3109       _dbus_warn ("Attempt to remove filter function %p user data %p, but no such filter has been added\n",
3110                   function, user_data);
3111       return;
3112     }
3113 #endif
3114   
3115   /* Call application code */
3116   if (filter->free_user_data_function)
3117     (* filter->free_user_data_function) (filter->user_data);
3118
3119   filter->free_user_data_function = NULL;
3120   filter->user_data = NULL;
3121   
3122   _dbus_message_filter_unref (filter);
3123 }
3124
3125 /**
3126  * Registers a handler for a given path in the object hierarchy.
3127  * The given vtable handles messages sent to exactly the given path.
3128  *
3129  *
3130  * @param connection the connection
3131  * @param path #NULL-terminated array of path elements
3132  * @param vtable the virtual table
3133  * @param user_data data to pass to functions in the vtable
3134  * @returns #FALSE if not enough memory
3135  */
3136 dbus_bool_t
3137 dbus_connection_register_object_path (DBusConnection              *connection,
3138                                       const char                 **path,
3139                                       const DBusObjectPathVTable  *vtable,
3140                                       void                        *user_data)
3141 {
3142   dbus_bool_t retval;
3143   
3144   _dbus_return_val_if_fail (connection != NULL, FALSE);
3145   _dbus_return_val_if_fail (path != NULL, FALSE);
3146   _dbus_return_val_if_fail (path[0] != NULL, FALSE);
3147   _dbus_return_val_if_fail (vtable != NULL, FALSE);
3148
3149   CONNECTION_LOCK (connection);
3150
3151   retval = _dbus_object_tree_register (connection->objects,
3152                                        FALSE,
3153                                        path, vtable,
3154                                        user_data);
3155
3156   CONNECTION_UNLOCK (connection);
3157
3158   return retval;
3159 }
3160
3161 /**
3162  * Registers a fallback handler for a given subsection of the object
3163  * hierarchy.  The given vtable handles messages at or below the given
3164  * path. You can use this to establish a default message handling
3165  * policy for a whole "subdirectory."
3166  *
3167  * @param connection the connection
3168  * @param path #NULL-terminated array of path elements
3169  * @param vtable the virtual table
3170  * @param user_data data to pass to functions in the vtable
3171  * @returns #FALSE if not enough memory
3172  */
3173 dbus_bool_t
3174 dbus_connection_register_fallback (DBusConnection              *connection,
3175                                    const char                 **path,
3176                                    const DBusObjectPathVTable  *vtable,
3177                                    void                        *user_data)
3178 {
3179   dbus_bool_t retval;
3180   
3181   _dbus_return_val_if_fail (connection != NULL, FALSE);
3182   _dbus_return_val_if_fail (path != NULL, FALSE);
3183   _dbus_return_val_if_fail (path[0] != NULL, FALSE);
3184   _dbus_return_val_if_fail (vtable != NULL, FALSE);
3185
3186   CONNECTION_LOCK (connection);
3187
3188   retval = _dbus_object_tree_register (connection->objects,
3189                                        TRUE,
3190                                        path, vtable,
3191                                        user_data);
3192
3193   CONNECTION_UNLOCK (connection);
3194
3195   return retval;
3196 }
3197
3198 /**
3199  * Unregisters the handler registered with exactly the given path.
3200  * It's a bug to call this function for a path that isn't registered.
3201  * Can unregister both fallback paths and object paths.
3202  *
3203  * @param connection the connection
3204  * @param path the #NULL-terminated array of path elements
3205  */
3206 void
3207 dbus_connection_unregister_object_path (DBusConnection              *connection,
3208                                         const char                 **path)
3209 {
3210   _dbus_return_if_fail (connection != NULL);
3211   _dbus_return_if_fail (path != NULL);
3212   _dbus_return_if_fail (path[0] != NULL);
3213
3214   CONNECTION_LOCK (connection);
3215
3216   return _dbus_object_tree_unregister_and_unlock (connection->objects,
3217                                                   path);
3218 }
3219
3220 /**
3221  * Lists the registered fallback handlers and object path handlers at
3222  * the given parent_path. The returned array should be freed with
3223  * dbus_free_string_array().
3224  *
3225  * @param connection the connection
3226  * @param parent_path the path to list the child handlers of
3227  * @param child_entries returns #NULL-terminated array of children
3228  * @returns #FALSE if no memory to allocate the child entries
3229  */
3230 dbus_bool_t
3231 dbus_connection_list_registered (DBusConnection              *connection,
3232                                  const char                 **parent_path,
3233                                  char                      ***child_entries)
3234 {
3235   _dbus_return_val_if_fail (connection != NULL, FALSE);
3236   _dbus_return_val_if_fail (parent_path != NULL, FALSE);
3237   _dbus_return_val_if_fail (child_entries != NULL, FALSE);
3238
3239   CONNECTION_LOCK (connection);
3240
3241   return _dbus_object_tree_list_registered_and_unlock (connection->objects,
3242                                                        parent_path,
3243                                                        child_entries);
3244 }
3245
3246 static DBusDataSlotAllocator slot_allocator;
3247 _DBUS_DEFINE_GLOBAL_LOCK (connection_slots);
3248
3249 /**
3250  * Allocates an integer ID to be used for storing application-specific
3251  * data on any DBusConnection. The allocated ID may then be used
3252  * with dbus_connection_set_data() and dbus_connection_get_data().
3253  * The passed-in slot must be initialized to -1, and is filled in
3254  * with the slot ID. If the passed-in slot is not -1, it's assumed
3255  * to be already allocated, and its refcount is incremented.
3256  * 
3257  * The allocated slot is global, i.e. all DBusConnection objects will
3258  * have a slot with the given integer ID reserved.
3259  *
3260  * @param slot_p address of a global variable storing the slot
3261  * @returns #FALSE on failure (no memory)
3262  */
3263 dbus_bool_t
3264 dbus_connection_allocate_data_slot (dbus_int32_t *slot_p)
3265 {
3266   return _dbus_data_slot_allocator_alloc (&slot_allocator,
3267                                           _DBUS_LOCK_NAME (connection_slots),
3268                                           slot_p);
3269 }
3270
3271 /**
3272  * Deallocates a global ID for connection data slots.
3273  * dbus_connection_get_data() and dbus_connection_set_data() may no
3274  * longer be used with this slot.  Existing data stored on existing
3275  * DBusConnection objects will be freed when the connection is
3276  * finalized, but may not be retrieved (and may only be replaced if
3277  * someone else reallocates the slot).  When the refcount on the
3278  * passed-in slot reaches 0, it is set to -1.
3279  *
3280  * @param slot_p address storing the slot to deallocate
3281  */
3282 void
3283 dbus_connection_free_data_slot (dbus_int32_t *slot_p)
3284 {
3285   _dbus_return_if_fail (*slot_p >= 0);
3286   
3287   _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
3288 }
3289
3290 /**
3291  * Stores a pointer on a DBusConnection, along
3292  * with an optional function to be used for freeing
3293  * the data when the data is set again, or when
3294  * the connection is finalized. The slot number
3295  * must have been allocated with dbus_connection_allocate_data_slot().
3296  *
3297  * @param connection the connection
3298  * @param slot the slot number
3299  * @param data the data to store
3300  * @param free_data_func finalizer function for the data
3301  * @returns #TRUE if there was enough memory to store the data
3302  */
3303 dbus_bool_t
3304 dbus_connection_set_data (DBusConnection   *connection,
3305                           dbus_int32_t      slot,
3306                           void             *data,
3307                           DBusFreeFunction  free_data_func)
3308 {
3309   DBusFreeFunction old_free_func;
3310   void *old_data;
3311   dbus_bool_t retval;
3312
3313   _dbus_return_val_if_fail (connection != NULL, FALSE);
3314   _dbus_return_val_if_fail (slot >= 0, FALSE);
3315   
3316   CONNECTION_LOCK (connection);
3317
3318   retval = _dbus_data_slot_list_set (&slot_allocator,
3319                                      &connection->slot_list,
3320                                      slot, data, free_data_func,
3321                                      &old_free_func, &old_data);
3322   
3323   CONNECTION_UNLOCK (connection);
3324
3325   if (retval)
3326     {
3327       /* Do the actual free outside the connection lock */
3328       if (old_free_func)
3329         (* old_free_func) (old_data);
3330     }
3331
3332   return retval;
3333 }
3334
3335 /**
3336  * Retrieves data previously set with dbus_connection_set_data().
3337  * The slot must still be allocated (must not have been freed).
3338  *
3339  * @param connection the connection
3340  * @param slot the slot to get data from
3341  * @returns the data, or #NULL if not found
3342  */
3343 void*
3344 dbus_connection_get_data (DBusConnection   *connection,
3345                           dbus_int32_t      slot)
3346 {
3347   void *res;
3348
3349   _dbus_return_val_if_fail (connection != NULL, NULL);
3350   
3351   CONNECTION_LOCK (connection);
3352
3353   res = _dbus_data_slot_list_get (&slot_allocator,
3354                                   &connection->slot_list,
3355                                   slot);
3356   
3357   CONNECTION_UNLOCK (connection);
3358
3359   return res;
3360 }
3361
3362 /**
3363  * This function sets a global flag for whether dbus_connection_new()
3364  * will set SIGPIPE behavior to SIG_IGN.
3365  *
3366  * @param will_modify_sigpipe #TRUE to allow sigpipe to be set to SIG_IGN
3367  */
3368 void
3369 dbus_connection_set_change_sigpipe (dbus_bool_t will_modify_sigpipe)
3370 {  
3371   _dbus_modify_sigpipe = will_modify_sigpipe != FALSE;
3372 }
3373
3374 /**
3375  * Specifies the maximum size message this connection is allowed to
3376  * receive. Larger messages will result in disconnecting the
3377  * connection.
3378  * 
3379  * @param connection a #DBusConnection
3380  * @param size maximum message size the connection can receive, in bytes
3381  */
3382 void
3383 dbus_connection_set_max_message_size (DBusConnection *connection,
3384                                       long            size)
3385 {
3386   _dbus_return_if_fail (connection != NULL);
3387   
3388   CONNECTION_LOCK (connection);
3389   _dbus_transport_set_max_message_size (connection->transport,
3390                                         size);
3391   CONNECTION_UNLOCK (connection);
3392 }
3393
3394 /**
3395  * Gets the value set by dbus_connection_set_max_message_size().
3396  *
3397  * @param connection the connection
3398  * @returns the max size of a single message
3399  */
3400 long
3401 dbus_connection_get_max_message_size (DBusConnection *connection)
3402 {
3403   long res;
3404
3405   _dbus_return_val_if_fail (connection != NULL, 0);
3406   
3407   CONNECTION_LOCK (connection);
3408   res = _dbus_transport_get_max_message_size (connection->transport);
3409   CONNECTION_UNLOCK (connection);
3410   return res;
3411 }
3412
3413 /**
3414  * Sets the maximum total number of bytes that can be used for all messages
3415  * received on this connection. Messages count toward the maximum until
3416  * they are finalized. When the maximum is reached, the connection will
3417  * not read more data until some messages are finalized.
3418  *
3419  * The semantics of the maximum are: if outstanding messages are
3420  * already above the maximum, additional messages will not be read.
3421  * The semantics are not: if the next message would cause us to exceed
3422  * the maximum, we don't read it. The reason is that we don't know the
3423  * size of a message until after we read it.
3424  *
3425  * Thus, the max live messages size can actually be exceeded
3426  * by up to the maximum size of a single message.
3427  * 
3428  * Also, if we read say 1024 bytes off the wire in a single read(),
3429  * and that contains a half-dozen small messages, we may exceed the
3430  * size max by that amount. But this should be inconsequential.
3431  *
3432  * This does imply that we can't call read() with a buffer larger
3433  * than we're willing to exceed this limit by.
3434  *
3435  * @param connection the connection
3436  * @param size the maximum size in bytes of all outstanding messages
3437  */
3438 void
3439 dbus_connection_set_max_received_size (DBusConnection *connection,
3440                                        long            size)
3441 {
3442   _dbus_return_if_fail (connection != NULL);
3443   
3444   CONNECTION_LOCK (connection);
3445   _dbus_transport_set_max_received_size (connection->transport,
3446                                          size);
3447   CONNECTION_UNLOCK (connection);
3448 }
3449
3450 /**
3451  * Gets the value set by dbus_connection_set_max_received_size().
3452  *
3453  * @param connection the connection
3454  * @returns the max size of all live messages
3455  */
3456 long
3457 dbus_connection_get_max_received_size (DBusConnection *connection)
3458 {
3459   long res;
3460
3461   _dbus_return_val_if_fail (connection != NULL, 0);
3462   
3463   CONNECTION_LOCK (connection);
3464   res = _dbus_transport_get_max_received_size (connection->transport);
3465   CONNECTION_UNLOCK (connection);
3466   return res;
3467 }
3468
3469 /**
3470  * Gets the approximate size in bytes of all messages in the outgoing
3471  * message queue. The size is approximate in that you shouldn't use
3472  * it to decide how many bytes to read off the network or anything
3473  * of that nature, as optimizations may choose to tell small white lies
3474  * to avoid performance overhead.
3475  *
3476  * @param connection the connection
3477  * @returns the number of bytes that have been queued up but not sent
3478  */
3479 long
3480 dbus_connection_get_outgoing_size (DBusConnection *connection)
3481 {
3482   long res;
3483
3484   _dbus_return_val_if_fail (connection != NULL, 0);
3485   
3486   CONNECTION_LOCK (connection);
3487   res = _dbus_counter_get_value (connection->outgoing_counter);
3488   CONNECTION_UNLOCK (connection);
3489   return res;
3490 }
3491
3492 /** @} */