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