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