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