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