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