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