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