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