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