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