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