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