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