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