2003-08-10 Havoc Pennington <hp@pobox.com>
[platform/upstream/dbus.git] / dbus / dbus-connection.c
1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-connection.c DBusConnection object
3  *
4  * Copyright (C) 2002, 2003  Red Hat Inc.
5  *
6  * Licensed under the Academic Free License version 1.2
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-connection.h"
26 #include "dbus-list.h"
27 #include "dbus-timeout.h"
28 #include "dbus-transport.h"
29 #include "dbus-watch.h"
30 #include "dbus-connection-internal.h"
31 #include "dbus-list.h"
32 #include "dbus-hash.h"
33 #include "dbus-message-internal.h"
34 #include "dbus-message-handler.h"
35 #include "dbus-threads.h"
36 #include "dbus-protocol.h"
37 #include "dbus-dataslot.h"
38 #include "dbus-object-registry.h"
39
40 #if 0
41 #define CONNECTION_LOCK(connection)   do {                      \
42     _dbus_verbose ("  LOCK: %s\n", _DBUS_FUNCTION_NAME);        \
43     dbus_mutex_lock ((connection)->mutex);                      \
44   } while (0)
45 #define CONNECTION_UNLOCK(connection) do {                      \
46     _dbus_verbose ("  UNLOCK: %s\n", _DBUS_FUNCTION_NAME);      \
47     dbus_mutex_unlock ((connection)->mutex);                    \
48   } while (0)
49 #else
50 #define CONNECTION_LOCK(connection)    dbus_mutex_lock ((connection)->mutex)
51 #define CONNECTION_UNLOCK(connection)  dbus_mutex_unlock ((connection)->mutex)
52 #endif
53
54 /**
55  * @defgroup DBusConnection DBusConnection
56  * @ingroup  DBus
57  * @brief Connection to another application
58  *
59  * A DBusConnection represents a connection to another
60  * application. Messages can be sent and received via this connection.
61  * The other application may be a message bus; for convenience, the
62  * function dbus_bus_get() is provided to automatically open a
63  * connection to the well-known message buses.
64  * 
65  * In brief a DBusConnection is a message queue associated with some
66  * message transport mechanism such as a socket.  The connection
67  * maintains a queue of incoming messages and a queue of outgoing
68  * messages.
69  *
70  * Incoming messages are normally processed by calling
71  * dbus_connection_dispatch(). dbus_connection_dispatch() runs any
72  * handlers registered for the topmost message in the message queue,
73  * then discards the message, then returns.
74  * 
75  * dbus_connection_get_dispatch_status() indicates whether
76  * messages are currently in the queue that need dispatching.
77  * dbus_connection_set_dispatch_status_function() allows
78  * you to set a function to be used to monitor the dispatch status.
79  *
80  * If you're using GLib or Qt add-on libraries for D-BUS, there are
81  * special convenience APIs in those libraries that hide
82  * all the details of dispatch and watch/timeout monitoring.
83  * For example, dbus_connection_setup_with_g_main().
84  *
85  * If you aren't using these add-on libraries, you have to manually
86  * call dbus_connection_set_dispatch_status_function(),
87  * dbus_connection_set_watch_functions(),
88  * dbus_connection_set_timeout_functions() providing appropriate
89  * functions to integrate the connection with your application's main
90  * loop.
91  *
92  * When you use dbus_connection_send() or one of its variants to send
93  * a message, the message is added to the outgoing queue.  It's
94  * actually written to the network later; either in
95  * dbus_watch_handle() invoked by your main loop, or in
96  * dbus_connection_flush() which blocks until it can write out the
97  * entire outgoing queue. The GLib/Qt add-on libraries again
98  * handle the details here for you by setting up watch functions.
99  *
100  * When a connection is disconnected, you are guaranteed to get a
101  * message with the name #DBUS_MESSAGE_LOCAL_DISCONNECT.
102  *
103  * You may not drop the last reference to a #DBusConnection
104  * until that connection has been disconnected.
105  *
106  * You may dispatch the unprocessed incoming message queue even if the
107  * connection is disconnected. However, #DBUS_MESSAGE_LOCAL_DISCONNECT
108  * will always be the last message in the queue (obviously no messages
109  * are received after disconnection).
110  *
111  * #DBusConnection has thread locks and drops them when invoking user
112  * callbacks, so in general is transparently threadsafe. However,
113  * #DBusMessage does NOT have thread locks; you must not send the same
114  * message to multiple #DBusConnection that will be used from
115  * different threads.
116  */
117
118 /**
119  * @defgroup DBusConnectionInternals DBusConnection implementation details
120  * @ingroup  DBusInternals
121  * @brief Implementation details of DBusConnection
122  *
123  * @{
124  */
125
126 /** default timeout value when waiting for a message reply */
127 #define DEFAULT_TIMEOUT_VALUE (15 * 1000)
128
129 static dbus_bool_t _dbus_modify_sigpipe = TRUE;
130
131 /**
132  * Implementation details of DBusConnection. All fields are private.
133  */
134 struct DBusConnection
135 {
136   DBusAtomic refcount; /**< Reference count. */
137
138   DBusMutex *mutex; /**< Lock on the entire DBusConnection */
139
140   dbus_bool_t dispatch_acquired; /**< Protects dispatch() */
141   DBusCondVar *dispatch_cond;    /**< Protects dispatch() */
142
143   dbus_bool_t io_path_acquired;  /**< Protects transport io path */
144   DBusCondVar *io_path_cond;     /**< Protects transport io path */
145   
146   DBusList *outgoing_messages; /**< Queue of messages we need to send, send the end of the list first. */
147   DBusList *incoming_messages; /**< Queue of messages we have received, end of the list received most recently. */
148
149   DBusMessage *message_borrowed; /**< True if the first incoming message has been borrowed */
150   DBusCondVar *message_returned_cond; /**< Used with dbus_connection_borrow_message() */
151   
152   int n_outgoing;              /**< Length of outgoing queue. */
153   int n_incoming;              /**< Length of incoming queue. */
154
155   DBusCounter *outgoing_counter; /**< Counts size of outgoing messages. */
156   
157   DBusTransport *transport;    /**< Object that sends/receives messages over network. */
158   DBusWatchList *watches;      /**< Stores active watches. */
159   DBusTimeoutList *timeouts;   /**< Stores active timeouts. */
160   
161   DBusList *filter_list;        /**< List of filters. */
162
163   DBusDataSlotList slot_list;   /**< Data stored by allocated integer ID */
164
165   DBusHashTable *pending_replies;  /**< Hash of message serials and their message handlers. */  
166   
167   dbus_uint32_t client_serial;       /**< Client serial. Increments each time a message is sent  */
168   DBusList *disconnect_message_link; /**< Preallocated list node for queueing the disconnection message */
169
170   DBusWakeupMainFunction wakeup_main_function; /**< Function to wake up the mainloop  */
171   void *wakeup_main_data; /**< Application data for wakeup_main_function */
172   DBusFreeFunction free_wakeup_main_data; /**< free wakeup_main_data */
173
174   DBusDispatchStatusFunction dispatch_status_function; /**< Function on dispatch status changes  */
175   void *dispatch_status_data; /**< Application data for dispatch_status_function */
176   DBusFreeFunction free_dispatch_status_data; /**< free dispatch_status_data */
177
178   DBusDispatchStatus last_dispatch_status; /**< The last dispatch status we reported to the application. */
179
180   DBusList *link_cache; /**< A cache of linked list links to prevent contention
181                          *   for the global linked list mempool lock
182                          */
183   DBusObjectRegistry *objects; /**< Objects registered with this connection */
184 };
185
186 typedef struct
187 {
188   DBusConnection *connection;
189   DBusMessageHandler *handler;
190   DBusTimeout *timeout;
191   int serial;
192
193   DBusList *timeout_link; /* Preallocated timeout response */
194   
195   dbus_bool_t timeout_added;
196   dbus_bool_t connection_added;
197 } ReplyHandlerData;
198
199 static void reply_handler_data_free (ReplyHandlerData *data);
200
201 static void               _dbus_connection_remove_timeout_locked             (DBusConnection     *connection,
202                                                                               DBusTimeout        *timeout);
203 static DBusDispatchStatus _dbus_connection_get_dispatch_status_unlocked      (DBusConnection     *connection);
204 static void               _dbus_connection_update_dispatch_status_and_unlock (DBusConnection     *connection,
205                                                                               DBusDispatchStatus  new_status);
206 static void               _dbus_connection_last_unref                        (DBusConnection     *connection);
207
208
209 /**
210  * Acquires the connection lock.
211  *
212  * @param connection the connection.
213  */
214 void
215 _dbus_connection_lock (DBusConnection *connection)
216 {
217   CONNECTION_LOCK (connection);
218 }
219
220 /**
221  * Releases the connection lock.
222  *
223  * @param connection the connection.
224  */
225 void
226 _dbus_connection_unlock (DBusConnection *connection)
227 {
228   CONNECTION_UNLOCK (connection);
229 }
230
231 /**
232  * Wakes up the main loop if it is sleeping
233  * Needed if we're e.g. queueing outgoing messages
234  * on a thread while the mainloop sleeps.
235  *
236  * @param connection the connection.
237  */
238 static void
239 _dbus_connection_wakeup_mainloop (DBusConnection *connection)
240 {
241   if (connection->wakeup_main_function)
242     (*connection->wakeup_main_function) (connection->wakeup_main_data);
243 }
244
245 #ifdef DBUS_BUILD_TESTS
246 /* For now this function isn't used */
247 /**
248  * Adds a message to the incoming message queue, returning #FALSE
249  * if there's insufficient memory to queue the message.
250  * Does not take over refcount of the message.
251  *
252  * @param connection the connection.
253  * @param message the message to queue.
254  * @returns #TRUE on success.
255  */
256 dbus_bool_t
257 _dbus_connection_queue_received_message (DBusConnection *connection,
258                                          DBusMessage    *message)
259 {
260   DBusList *link;
261
262   link = _dbus_list_alloc_link (message);
263   if (link == NULL)
264     return FALSE;
265
266   dbus_message_ref (message);
267   _dbus_connection_queue_received_message_link (connection, link);
268
269   return TRUE;
270 }
271 #endif
272
273 /**
274  * Adds a message-containing list link to the incoming message queue,
275  * taking ownership of the link and the message's current refcount.
276  * Cannot fail due to lack of memory.
277  *
278  * @param connection the connection.
279  * @param link the message link to queue.
280  */
281 void
282 _dbus_connection_queue_received_message_link (DBusConnection  *connection,
283                                               DBusList        *link)
284 {
285   ReplyHandlerData *reply_handler_data;
286   dbus_int32_t reply_serial;
287   DBusMessage *message;
288   
289   _dbus_assert (_dbus_transport_get_is_authenticated (connection->transport));
290   
291   _dbus_list_append_link (&connection->incoming_messages,
292                           link);
293   message = link->data;
294
295   /* If this is a reply we're waiting on, remove timeout for it */
296   reply_serial = dbus_message_get_reply_serial (message);
297   if (reply_serial != -1)
298     {
299       reply_handler_data = _dbus_hash_table_lookup_int (connection->pending_replies,
300                                                         reply_serial);
301       if (reply_handler_data != NULL)
302         {
303           if (reply_handler_data->timeout_added)
304             _dbus_connection_remove_timeout_locked (connection,
305                                                     reply_handler_data->timeout);
306           reply_handler_data->timeout_added = FALSE;
307         }
308     }
309   
310   connection->n_incoming += 1;
311
312   _dbus_connection_wakeup_mainloop (connection);
313   
314   _dbus_assert (dbus_message_get_name (message) != NULL);
315   _dbus_verbose ("Message %p (%s) added to incoming queue %p, %d incoming\n",
316                  message, dbus_message_get_name (message),
317                  connection,
318                  connection->n_incoming);
319 }
320
321 /**
322  * Adds a link + message to the incoming message queue.
323  * Can't fail. Takes ownership of both link and message.
324  *
325  * @param connection the connection.
326  * @param link the list node and message to queue.
327  *
328  * @todo This needs to wake up the mainloop if it is in
329  * a poll/select and this is a multithreaded app.
330  */
331 static void
332 _dbus_connection_queue_synthesized_message_link (DBusConnection *connection,
333                                                  DBusList *link)
334 {
335   _dbus_list_append_link (&connection->incoming_messages, link);
336
337   connection->n_incoming += 1;
338
339   _dbus_connection_wakeup_mainloop (connection);
340   
341   _dbus_verbose ("Synthesized message %p added to incoming queue %p, %d incoming\n",
342                  link->data, connection, connection->n_incoming);
343 }
344
345
346 /**
347  * Checks whether there are messages in the outgoing message queue.
348  *
349  * @param connection the connection.
350  * @returns #TRUE if the outgoing queue is non-empty.
351  */
352 dbus_bool_t
353 _dbus_connection_have_messages_to_send (DBusConnection *connection)
354 {
355   return connection->outgoing_messages != NULL;
356 }
357
358 /**
359  * Gets the next outgoing message. The message remains in the
360  * queue, and the caller does not own a reference to it.
361  *
362  * @param connection the connection.
363  * @returns the message to be sent.
364  */ 
365 DBusMessage*
366 _dbus_connection_get_message_to_send (DBusConnection *connection)
367 {
368   return _dbus_list_get_last (&connection->outgoing_messages);
369 }
370
371 /**
372  * Notifies the connection that a message has been sent, so the
373  * message can be removed from the outgoing queue.
374  * Called with the connection lock held.
375  *
376  * @param connection the connection.
377  * @param message the message that was sent.
378  */
379 void
380 _dbus_connection_message_sent (DBusConnection *connection,
381                                DBusMessage    *message)
382 {
383   DBusList *link;
384   
385   _dbus_assert (_dbus_transport_get_is_authenticated (connection->transport));
386   
387   link = _dbus_list_get_last_link (&connection->outgoing_messages);
388   _dbus_assert (link != NULL);
389   _dbus_assert (link->data == message);
390
391   /* Save this link in the link cache */
392   _dbus_list_unlink (&connection->outgoing_messages,
393                      link);
394   _dbus_list_prepend_link (&connection->link_cache, link);
395   
396   connection->n_outgoing -= 1;
397
398   _dbus_verbose ("Message %p (%s) removed from outgoing queue %p, %d left to send\n",
399                  message, dbus_message_get_name (message),
400                  connection, connection->n_outgoing);
401
402   /* Save this link in the link cache also */
403   _dbus_message_remove_size_counter (message, connection->outgoing_counter,
404                                      &link);
405   _dbus_list_prepend_link (&connection->link_cache, link);
406   
407   dbus_message_unref (message);
408   
409   if (connection->n_outgoing == 0)
410     _dbus_transport_messages_pending (connection->transport,
411                                       connection->n_outgoing);  
412 }
413
414 /**
415  * Adds a watch using the connection's DBusAddWatchFunction if
416  * available. Otherwise records the watch to be added when said
417  * function is available. Also re-adds the watch if the
418  * DBusAddWatchFunction changes. May fail due to lack of memory.
419  *
420  * @param connection the connection.
421  * @param watch the watch to add.
422  * @returns #TRUE on success.
423  */
424 dbus_bool_t
425 _dbus_connection_add_watch (DBusConnection *connection,
426                             DBusWatch      *watch)
427 {
428   if (connection->watches) /* null during finalize */
429     return _dbus_watch_list_add_watch (connection->watches,
430                                        watch);
431   else
432     return FALSE;
433 }
434
435 /**
436  * Removes a watch using the connection's DBusRemoveWatchFunction
437  * if available. It's an error to call this function on a watch
438  * that was not previously added.
439  *
440  * @param connection the connection.
441  * @param watch the watch to remove.
442  */
443 void
444 _dbus_connection_remove_watch (DBusConnection *connection,
445                                DBusWatch      *watch)
446 {
447   if (connection->watches) /* null during finalize */
448     _dbus_watch_list_remove_watch (connection->watches,
449                                    watch);
450 }
451
452 /**
453  * Toggles a watch and notifies app via connection's
454  * DBusWatchToggledFunction if available. It's an error to call this
455  * function on a watch that was not previously added.
456  *
457  * @param connection the connection.
458  * @param watch the watch to toggle.
459  * @param enabled whether to enable or disable
460  */
461 void
462 _dbus_connection_toggle_watch (DBusConnection *connection,
463                                DBusWatch      *watch,
464                                dbus_bool_t     enabled)
465 {
466   if (connection->watches) /* null during finalize */
467     _dbus_watch_list_toggle_watch (connection->watches,
468                                    watch, enabled);
469 }
470
471 /**
472  * Adds a timeout using the connection's DBusAddTimeoutFunction if
473  * available. Otherwise records the timeout to be added when said
474  * function is available. Also re-adds the timeout if the
475  * DBusAddTimeoutFunction changes. May fail due to lack of memory.
476  * The timeout will fire repeatedly until removed.
477  *
478  * @param connection the connection.
479  * @param timeout the timeout to add.
480  * @returns #TRUE on success.
481  */
482 dbus_bool_t
483 _dbus_connection_add_timeout (DBusConnection *connection,
484                               DBusTimeout    *timeout)
485 {
486  if (connection->timeouts) /* null during finalize */
487     return _dbus_timeout_list_add_timeout (connection->timeouts,
488                                            timeout);
489   else
490     return FALSE;  
491 }
492
493 /**
494  * Removes a timeout using the connection's DBusRemoveTimeoutFunction
495  * if available. It's an error to call this function on a timeout
496  * that was not previously added.
497  *
498  * @param connection the connection.
499  * @param timeout the timeout to remove.
500  */
501 void
502 _dbus_connection_remove_timeout (DBusConnection *connection,
503                                  DBusTimeout    *timeout)
504 {
505   if (connection->timeouts) /* null during finalize */
506     _dbus_timeout_list_remove_timeout (connection->timeouts,
507                                        timeout);
508 }
509
510 static void
511 _dbus_connection_remove_timeout_locked (DBusConnection *connection,
512                                         DBusTimeout    *timeout)
513 {
514   CONNECTION_LOCK (connection);
515   _dbus_connection_remove_timeout (connection, timeout);
516   CONNECTION_UNLOCK (connection);
517 }
518
519 /**
520  * Toggles a timeout and notifies app via connection's
521  * DBusTimeoutToggledFunction if available. It's an error to call this
522  * function on a timeout that was not previously added.
523  *
524  * @param connection the connection.
525  * @param timeout the timeout to toggle.
526  * @param enabled whether to enable or disable
527  */
528 void
529 _dbus_connection_toggle_timeout (DBusConnection *connection,
530                                  DBusTimeout      *timeout,
531                                  dbus_bool_t     enabled)
532 {
533   if (connection->timeouts) /* null during finalize */
534     _dbus_timeout_list_toggle_timeout (connection->timeouts,
535                                        timeout, enabled);
536 }
537
538 /**
539  * Tells the connection that the transport has been disconnected.
540  * Results in posting a disconnect message on the incoming message
541  * queue.  Only has an effect the first time it's called.
542  *
543  * @param connection the connection
544  */
545 void
546 _dbus_connection_notify_disconnected (DBusConnection *connection)
547 {
548   if (connection->disconnect_message_link)
549     {
550       /* We haven't sent the disconnect message already */
551       _dbus_connection_queue_synthesized_message_link (connection,
552                                                        connection->disconnect_message_link);
553       connection->disconnect_message_link = NULL;
554     }
555 }
556
557
558 /**
559  * Acquire the transporter I/O path. This must be done before
560  * doing any I/O in the transporter. May sleep and drop the
561  * connection mutex while waiting for the I/O path.
562  *
563  * @param connection the connection.
564  * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
565  * @returns TRUE if the I/O path was acquired.
566  */
567 static dbus_bool_t
568 _dbus_connection_acquire_io_path (DBusConnection *connection,
569                                   int timeout_milliseconds)
570 {
571   dbus_bool_t res = TRUE;
572
573   if (connection->io_path_acquired)
574     {
575       if (timeout_milliseconds != -1) 
576         res = dbus_condvar_wait_timeout (connection->io_path_cond,
577                                          connection->mutex,
578                                          timeout_milliseconds);
579       else
580         dbus_condvar_wait (connection->io_path_cond, connection->mutex);
581     }
582   
583   if (res)
584     {
585       _dbus_assert (!connection->io_path_acquired);
586
587       connection->io_path_acquired = TRUE;
588     }
589   
590   return res;
591 }
592
593 /**
594  * Release the I/O path when you're done with it. Only call
595  * after you've acquired the I/O. Wakes up at most one thread
596  * currently waiting to acquire the I/O path.
597  *
598  * @param connection the connection.
599  */
600 static void
601 _dbus_connection_release_io_path (DBusConnection *connection)
602 {
603   _dbus_assert (connection->io_path_acquired);
604
605   connection->io_path_acquired = FALSE;
606   dbus_condvar_wake_one (connection->io_path_cond);
607 }
608
609
610 /**
611  * Queues incoming messages and sends outgoing messages for this
612  * connection, optionally blocking in the process. Each call to
613  * _dbus_connection_do_iteration() will call select() or poll() one
614  * time and then read or write data if possible.
615  *
616  * The purpose of this function is to be able to flush outgoing
617  * messages or queue up incoming messages without returning
618  * control to the application and causing reentrancy weirdness.
619  *
620  * The flags parameter allows you to specify whether to
621  * read incoming messages, write outgoing messages, or both,
622  * and whether to block if no immediate action is possible.
623  *
624  * The timeout_milliseconds parameter does nothing unless the
625  * iteration is blocking.
626  *
627  * If there are no outgoing messages and DBUS_ITERATION_DO_READING
628  * wasn't specified, then it's impossible to block, even if
629  * you specify DBUS_ITERATION_BLOCK; in that case the function
630  * returns immediately.
631  * 
632  * @param connection the connection.
633  * @param flags iteration flags.
634  * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
635  */
636 void
637 _dbus_connection_do_iteration (DBusConnection *connection,
638                                unsigned int    flags,
639                                int             timeout_milliseconds)
640 {
641   if (connection->n_outgoing == 0)
642     flags &= ~DBUS_ITERATION_DO_WRITING;
643
644   if (_dbus_connection_acquire_io_path (connection,
645                                         (flags & DBUS_ITERATION_BLOCK) ? timeout_milliseconds : 0))
646     {
647       _dbus_transport_do_iteration (connection->transport,
648                                     flags, timeout_milliseconds);
649       _dbus_connection_release_io_path (connection);
650     }
651 }
652
653 /**
654  * Creates a new connection for the given transport.  A transport
655  * represents a message stream that uses some concrete mechanism, such
656  * as UNIX domain sockets. May return #NULL if insufficient
657  * memory exists to create the connection.
658  *
659  * @param transport the transport.
660  * @returns the new connection, or #NULL on failure.
661  */
662 DBusConnection*
663 _dbus_connection_new_for_transport (DBusTransport *transport)
664 {
665   DBusConnection *connection;
666   DBusWatchList *watch_list;
667   DBusTimeoutList *timeout_list;
668   DBusHashTable *pending_replies;
669   DBusMutex *mutex;
670   DBusCondVar *message_returned_cond;
671   DBusCondVar *dispatch_cond;
672   DBusCondVar *io_path_cond;
673   DBusList *disconnect_link;
674   DBusMessage *disconnect_message;
675   DBusCounter *outgoing_counter;
676   DBusObjectRegistry *objects;
677   
678   watch_list = NULL;
679   connection = NULL;
680   pending_replies = NULL;
681   timeout_list = NULL;
682   mutex = NULL;
683   message_returned_cond = NULL;
684   dispatch_cond = NULL;
685   io_path_cond = NULL;
686   disconnect_link = NULL;
687   disconnect_message = NULL;
688   outgoing_counter = NULL;
689   objects = NULL;
690   
691   watch_list = _dbus_watch_list_new ();
692   if (watch_list == NULL)
693     goto error;
694
695   timeout_list = _dbus_timeout_list_new ();
696   if (timeout_list == NULL)
697     goto error;  
698
699   pending_replies =
700     _dbus_hash_table_new (DBUS_HASH_INT,
701                           NULL, (DBusFreeFunction)reply_handler_data_free);
702   if (pending_replies == NULL)
703     goto error;
704   
705   connection = dbus_new0 (DBusConnection, 1);
706   if (connection == NULL)
707     goto error;
708
709   mutex = dbus_mutex_new ();
710   if (mutex == NULL)
711     goto error;
712   
713   message_returned_cond = dbus_condvar_new ();
714   if (message_returned_cond == NULL)
715     goto error;
716   
717   dispatch_cond = dbus_condvar_new ();
718   if (dispatch_cond == NULL)
719     goto error;
720   
721   io_path_cond = dbus_condvar_new ();
722   if (io_path_cond == NULL)
723     goto error;
724
725   disconnect_message = dbus_message_new_signal (DBUS_MESSAGE_LOCAL_DISCONNECT);
726   if (disconnect_message == NULL)
727     goto error;
728
729   disconnect_link = _dbus_list_alloc_link (disconnect_message);
730   if (disconnect_link == NULL)
731     goto error;
732
733   outgoing_counter = _dbus_counter_new ();
734   if (outgoing_counter == NULL)
735     goto error;
736
737   objects = _dbus_object_registry_new (connection);
738   if (objects == NULL)
739     goto error;
740   
741   if (_dbus_modify_sigpipe)
742     _dbus_disable_sigpipe ();
743   
744   connection->refcount.value = 1;
745   connection->mutex = mutex;
746   connection->dispatch_cond = dispatch_cond;
747   connection->io_path_cond = io_path_cond;
748   connection->message_returned_cond = message_returned_cond;
749   connection->transport = transport;
750   connection->watches = watch_list;
751   connection->timeouts = timeout_list;
752   connection->pending_replies = pending_replies;
753   connection->outgoing_counter = outgoing_counter;
754   connection->filter_list = NULL;
755   connection->last_dispatch_status = DBUS_DISPATCH_COMPLETE; /* so we're notified first time there's data */
756   connection->objects = objects;
757   
758   _dbus_data_slot_list_init (&connection->slot_list);
759
760   connection->client_serial = 1;
761
762   connection->disconnect_message_link = disconnect_link;
763   
764   if (!_dbus_transport_set_connection (transport, connection))
765     goto error;
766
767   _dbus_transport_ref (transport);  
768   
769   return connection;
770   
771  error:
772   if (disconnect_message != NULL)
773     dbus_message_unref (disconnect_message);
774   
775   if (disconnect_link != NULL)
776     _dbus_list_free_link (disconnect_link);
777   
778   if (io_path_cond != NULL)
779     dbus_condvar_free (io_path_cond);
780   
781   if (dispatch_cond != NULL)
782     dbus_condvar_free (dispatch_cond);
783   
784   if (message_returned_cond != NULL)
785     dbus_condvar_free (message_returned_cond);
786   
787   if (mutex != NULL)
788     dbus_mutex_free (mutex);
789
790   if (connection != NULL)
791     dbus_free (connection);
792
793   if (pending_replies)
794     _dbus_hash_table_unref (pending_replies);
795   
796   if (watch_list)
797     _dbus_watch_list_free (watch_list);
798
799   if (timeout_list)
800     _dbus_timeout_list_free (timeout_list);
801
802   if (outgoing_counter)
803     _dbus_counter_unref (outgoing_counter);
804
805   if (objects)
806     _dbus_object_registry_unref (objects);
807   
808   return NULL;
809 }
810
811 /**
812  * Increments the reference count of a DBusConnection.
813  * Requires that the caller already holds the connection lock.
814  *
815  * @param connection the connection.
816  */
817 void
818 _dbus_connection_ref_unlocked (DBusConnection *connection)
819 {
820 #ifdef DBUS_HAVE_ATOMIC_INT
821   _dbus_atomic_inc (&connection->refcount);
822 #else
823   _dbus_assert (connection->refcount.value > 0);
824   connection->refcount.value += 1;
825 #endif
826 }
827
828 /**
829  * Decrements the reference count of a DBusConnection.
830  * Requires that the caller already holds the connection lock.
831  *
832  * @param connection the connection.
833  */
834 void
835 _dbus_connection_unref_unlocked (DBusConnection *connection)
836 {
837   dbus_bool_t last_unref;
838
839   _dbus_return_if_fail (connection != NULL);
840
841   /* The connection lock is better than the global
842    * lock in the atomic increment fallback
843    */
844   
845 #ifdef DBUS_HAVE_ATOMIC_INT
846   last_unref = (_dbus_atomic_dec (&connection->refcount) == 1);
847 #else  
848   _dbus_assert (connection->refcount.value > 0);
849
850   connection->refcount.value -= 1;
851   last_unref = (connection->refcount.value == 0);
852 #if 0
853   printf ("unref_unlocked() connection %p count = %d\n", connection, connection->refcount.value);
854 #endif
855 #endif
856   
857   if (last_unref)
858     _dbus_connection_last_unref (connection);
859 }
860
861 static dbus_uint32_t
862 _dbus_connection_get_next_client_serial (DBusConnection *connection)
863 {
864   int serial;
865
866   serial = connection->client_serial++;
867
868   if (connection->client_serial < 0)
869     connection->client_serial = 1;
870   
871   return serial;
872 }
873
874 /**
875  * Used to notify a connection when a DBusMessageHandler is
876  * destroyed, so the connection can drop any reference
877  * to the handler. This is a private function, but still
878  * takes the connection lock. Don't call it with the lock held.
879  *
880  * @todo needs to check in pending_replies too.
881  * 
882  * @param connection the connection
883  * @param handler the handler
884  */
885 void
886 _dbus_connection_handler_destroyed_locked (DBusConnection     *connection,
887                                            DBusMessageHandler *handler)
888 {
889   DBusList *link;
890
891   CONNECTION_LOCK (connection);
892
893   link = _dbus_list_get_first_link (&connection->filter_list);
894   while (link != NULL)
895     {
896       DBusMessageHandler *h = link->data;
897       DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
898
899       if (h == handler)
900         _dbus_list_remove_link (&connection->filter_list,
901                                 link);
902       
903       link = next;
904     }
905   CONNECTION_UNLOCK (connection);
906 }
907
908 /**
909  * A callback for use with dbus_watch_new() to create a DBusWatch.
910  * 
911  * @todo This is basically a hack - we could delete _dbus_transport_handle_watch()
912  * and the virtual handle_watch in DBusTransport if we got rid of it.
913  * The reason this is some work is threading, see the _dbus_connection_handle_watch()
914  * implementation.
915  *
916  * @param watch the watch.
917  * @param condition the current condition of the file descriptors being watched.
918  * @param data must be a pointer to a #DBusConnection
919  * @returns #FALSE if the IO condition may not have been fully handled due to lack of memory
920  */
921 dbus_bool_t
922 _dbus_connection_handle_watch (DBusWatch                   *watch,
923                                unsigned int                 condition,
924                                void                        *data)
925 {
926   DBusConnection *connection;
927   dbus_bool_t retval;
928   DBusDispatchStatus status;
929
930   connection = data;
931   
932   CONNECTION_LOCK (connection);
933   _dbus_connection_acquire_io_path (connection, -1);
934   retval = _dbus_transport_handle_watch (connection->transport,
935                                          watch, condition);
936   _dbus_connection_release_io_path (connection);
937
938   status = _dbus_connection_get_dispatch_status_unlocked (connection);
939
940   /* this calls out to user code */
941   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
942   
943   return retval;
944 }
945
946 /**
947  * Get the server ID to be used in the object ID for an object
948  * registered with this connection.
949  *
950  * @todo implement this function
951  * 
952  * @param connection the connection.
953  * @returns the  portion of the object ID
954  */
955 void
956 _dbus_connection_init_id (DBusConnection *connection,
957                           DBusObjectID   *object_id)
958 {
959   /* FIXME */
960   dbus_object_id_set_server_bits (object_id, 15);
961   dbus_object_id_set_client_bits (object_id, 31);
962   dbus_object_id_set_is_server_bit (object_id, FALSE);
963 }
964
965 /** @} */
966
967 /**
968  * @addtogroup DBusConnection
969  *
970  * @{
971  */
972
973 /**
974  * Opens a new connection to a remote address.
975  *
976  * @todo specify what the address parameter is. Right now
977  * it's just the name of a UNIX domain socket. It should be
978  * something more complex that encodes which transport to use.
979  *
980  * If the open fails, the function returns #NULL, and provides
981  * a reason for the failure in the result parameter. Pass
982  * #NULL for the result parameter if you aren't interested
983  * in the reason for failure.
984  * 
985  * @param address the address.
986  * @param error address where an error can be returned.
987  * @returns new connection, or #NULL on failure.
988  */
989 DBusConnection*
990 dbus_connection_open (const char     *address,
991                       DBusError      *error)
992 {
993   DBusConnection *connection;
994   DBusTransport *transport;
995
996   _dbus_return_val_if_fail (address != NULL, NULL);
997   _dbus_return_val_if_error_is_set (error, NULL);
998   
999   transport = _dbus_transport_open (address, error);
1000   if (transport == NULL)
1001     {
1002       _DBUS_ASSERT_ERROR_IS_SET (error);
1003       return NULL;
1004     }
1005   
1006   connection = _dbus_connection_new_for_transport (transport);
1007
1008   _dbus_transport_unref (transport);
1009   
1010   if (connection == NULL)
1011     {
1012       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1013       return NULL;
1014     }
1015   
1016   return connection;
1017 }
1018
1019 /**
1020  * Increments the reference count of a DBusConnection.
1021  *
1022  * @param connection the connection.
1023  */
1024 void
1025 dbus_connection_ref (DBusConnection *connection)
1026 {
1027   _dbus_return_if_fail (connection != NULL);
1028
1029   /* The connection lock is better than the global
1030    * lock in the atomic increment fallback
1031    */
1032   
1033 #ifdef DBUS_HAVE_ATOMIC_INT
1034   _dbus_atomic_inc (&connection->refcount);
1035 #else
1036   CONNECTION_LOCK (connection);
1037   _dbus_assert (connection->refcount.value > 0);
1038
1039   connection->refcount.value += 1;
1040   CONNECTION_UNLOCK (connection);
1041 #endif
1042 }
1043
1044 static void
1045 free_outgoing_message (void *element,
1046                        void *data)
1047 {
1048   DBusMessage *message = element;
1049   DBusConnection *connection = data;
1050
1051   _dbus_message_remove_size_counter (message,
1052                                      connection->outgoing_counter,
1053                                      NULL);
1054   dbus_message_unref (message);
1055 }
1056
1057 /* This is run without the mutex held, but after the last reference
1058  * to the connection has been dropped we should have no thread-related
1059  * problems
1060  */
1061 static void
1062 _dbus_connection_last_unref (DBusConnection *connection)
1063 {
1064   DBusList *link;
1065
1066   _dbus_verbose ("Finalizing connection %p\n", connection);
1067   
1068   _dbus_assert (connection->refcount.value == 0);
1069   
1070   /* You have to disconnect the connection before unref:ing it. Otherwise
1071    * you won't get the disconnected message.
1072    */
1073   _dbus_assert (!_dbus_transport_get_is_connected (connection->transport));
1074
1075   /* ---- We're going to call various application callbacks here, hope it doesn't break anything... */
1076   _dbus_object_registry_free_all_unlocked (connection->objects);
1077   
1078   dbus_connection_set_dispatch_status_function (connection, NULL, NULL, NULL);
1079   dbus_connection_set_wakeup_main_function (connection, NULL, NULL, NULL);
1080   dbus_connection_set_unix_user_function (connection, NULL, NULL, NULL);
1081   
1082   _dbus_watch_list_free (connection->watches);
1083   connection->watches = NULL;
1084   
1085   _dbus_timeout_list_free (connection->timeouts);
1086   connection->timeouts = NULL;
1087
1088   _dbus_data_slot_list_free (&connection->slot_list);
1089   /* ---- Done with stuff that invokes application callbacks */
1090   
1091   link = _dbus_list_get_first_link (&connection->filter_list);
1092   while (link != NULL)
1093     {
1094       DBusMessageHandler *h = link->data;
1095       DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
1096       
1097       _dbus_message_handler_remove_connection (h, connection);
1098       
1099       link = next;
1100     }
1101
1102   _dbus_object_registry_unref (connection->objects);  
1103
1104   _dbus_hash_table_unref (connection->pending_replies);
1105   connection->pending_replies = NULL;
1106   
1107   _dbus_list_clear (&connection->filter_list);
1108   
1109   _dbus_list_foreach (&connection->outgoing_messages,
1110                       free_outgoing_message,
1111                       connection);
1112   _dbus_list_clear (&connection->outgoing_messages);
1113   
1114   _dbus_list_foreach (&connection->incoming_messages,
1115                       (DBusForeachFunction) dbus_message_unref,
1116                       NULL);
1117   _dbus_list_clear (&connection->incoming_messages);
1118
1119   _dbus_counter_unref (connection->outgoing_counter);
1120   
1121   _dbus_transport_unref (connection->transport);
1122
1123   if (connection->disconnect_message_link)
1124     {
1125       DBusMessage *message = connection->disconnect_message_link->data;
1126       dbus_message_unref (message);
1127       _dbus_list_free_link (connection->disconnect_message_link);
1128     }
1129
1130   _dbus_list_clear (&connection->link_cache);
1131   
1132   dbus_condvar_free (connection->dispatch_cond);
1133   dbus_condvar_free (connection->io_path_cond);
1134   dbus_condvar_free (connection->message_returned_cond);  
1135   
1136   dbus_mutex_free (connection->mutex);
1137   
1138   dbus_free (connection);
1139 }
1140
1141 /**
1142  * Decrements the reference count of a DBusConnection, and finalizes
1143  * it if the count reaches zero.  It is a bug to drop the last reference
1144  * to a connection that has not been disconnected.
1145  *
1146  * @todo in practice it can be quite tricky to never unref a connection
1147  * that's still connected; maybe there's some way we could avoid
1148  * the requirement.
1149  *
1150  * @param connection the connection.
1151  */
1152 void
1153 dbus_connection_unref (DBusConnection *connection)
1154 {
1155   dbus_bool_t last_unref;
1156
1157   _dbus_return_if_fail (connection != NULL);
1158
1159   /* The connection lock is better than the global
1160    * lock in the atomic increment fallback
1161    */
1162   
1163 #ifdef DBUS_HAVE_ATOMIC_INT
1164   last_unref = (_dbus_atomic_dec (&connection->refcount) == 1);
1165 #else
1166   CONNECTION_LOCK (connection);
1167   
1168   _dbus_assert (connection->refcount.value > 0);
1169
1170   connection->refcount.value -= 1;
1171   last_unref = (connection->refcount.value == 0);
1172
1173 #if 0
1174   printf ("unref() connection %p count = %d\n", connection, connection->refcount.value);
1175 #endif
1176   
1177   CONNECTION_UNLOCK (connection);
1178 #endif
1179   
1180   if (last_unref)
1181     _dbus_connection_last_unref (connection);
1182 }
1183
1184 /**
1185  * Closes the connection, so no further data can be sent or received.
1186  * Any further attempts to send data will result in errors.  This
1187  * function does not affect the connection's reference count.  It's
1188  * safe to disconnect a connection more than once; all calls after the
1189  * first do nothing. It's impossible to "reconnect" a connection, a
1190  * new connection must be created.
1191  *
1192  * @param connection the connection.
1193  */
1194 void
1195 dbus_connection_disconnect (DBusConnection *connection)
1196 {
1197   _dbus_return_if_fail (connection != NULL);
1198   
1199   CONNECTION_LOCK (connection);
1200   _dbus_transport_disconnect (connection->transport);
1201   CONNECTION_UNLOCK (connection);
1202 }
1203
1204 static dbus_bool_t
1205 _dbus_connection_get_is_connected_unlocked (DBusConnection *connection)
1206 {
1207   return _dbus_transport_get_is_connected (connection->transport);
1208 }
1209
1210 /**
1211  * Gets whether the connection is currently connected.  All
1212  * connections are connected when they are opened.  A connection may
1213  * become disconnected when the remote application closes its end, or
1214  * exits; a connection may also be disconnected with
1215  * dbus_connection_disconnect().
1216  *
1217  * @param connection the connection.
1218  * @returns #TRUE if the connection is still alive.
1219  */
1220 dbus_bool_t
1221 dbus_connection_get_is_connected (DBusConnection *connection)
1222 {
1223   dbus_bool_t res;
1224
1225   _dbus_return_val_if_fail (connection != NULL, FALSE);
1226   
1227   CONNECTION_LOCK (connection);
1228   res = _dbus_connection_get_is_connected_unlocked (connection);
1229   CONNECTION_UNLOCK (connection);
1230   
1231   return res;
1232 }
1233
1234 /**
1235  * Gets whether the connection was authenticated. (Note that
1236  * if the connection was authenticated then disconnected,
1237  * this function still returns #TRUE)
1238  *
1239  * @param connection the connection
1240  * @returns #TRUE if the connection was ever authenticated
1241  */
1242 dbus_bool_t
1243 dbus_connection_get_is_authenticated (DBusConnection *connection)
1244 {
1245   dbus_bool_t res;
1246
1247   _dbus_return_val_if_fail (connection != NULL, FALSE);
1248   
1249   CONNECTION_LOCK (connection);
1250   res = _dbus_transport_get_is_authenticated (connection->transport);
1251   CONNECTION_UNLOCK (connection);
1252   
1253   return res;
1254 }
1255
1256 struct DBusPreallocatedSend
1257 {
1258   DBusConnection *connection;
1259   DBusList *queue_link;
1260   DBusList *counter_link;
1261 };
1262
1263 static DBusPreallocatedSend*
1264 _dbus_connection_preallocate_send_unlocked (DBusConnection *connection)
1265 {
1266   DBusPreallocatedSend *preallocated;
1267
1268   _dbus_return_val_if_fail (connection != NULL, NULL);
1269   
1270   preallocated = dbus_new (DBusPreallocatedSend, 1);
1271   if (preallocated == NULL)
1272     return NULL;
1273
1274   if (connection->link_cache != NULL)
1275     {
1276       preallocated->queue_link =
1277         _dbus_list_pop_first_link (&connection->link_cache);
1278       preallocated->queue_link->data = NULL;
1279     }
1280   else
1281     {
1282       preallocated->queue_link = _dbus_list_alloc_link (NULL);
1283       if (preallocated->queue_link == NULL)
1284         goto failed_0;
1285     }
1286   
1287   if (connection->link_cache != NULL)
1288     {
1289       preallocated->counter_link =
1290         _dbus_list_pop_first_link (&connection->link_cache);
1291       preallocated->counter_link->data = connection->outgoing_counter;
1292     }
1293   else
1294     {
1295       preallocated->counter_link = _dbus_list_alloc_link (connection->outgoing_counter);
1296       if (preallocated->counter_link == NULL)
1297         goto failed_1;
1298     }
1299
1300   _dbus_counter_ref (preallocated->counter_link->data);
1301
1302   preallocated->connection = connection;
1303   
1304   return preallocated;
1305   
1306  failed_1:
1307   _dbus_list_free_link (preallocated->queue_link);
1308  failed_0:
1309   dbus_free (preallocated);
1310   
1311   return NULL;
1312 }
1313
1314 /**
1315  * Preallocates resources needed to send a message, allowing the message 
1316  * to be sent without the possibility of memory allocation failure.
1317  * Allows apps to create a future guarantee that they can send
1318  * a message regardless of memory shortages.
1319  *
1320  * @param connection the connection we're preallocating for.
1321  * @returns the preallocated resources, or #NULL
1322  */
1323 DBusPreallocatedSend*
1324 dbus_connection_preallocate_send (DBusConnection *connection)
1325 {
1326   DBusPreallocatedSend *preallocated;
1327
1328   _dbus_return_val_if_fail (connection != NULL, NULL);
1329
1330   CONNECTION_LOCK (connection);
1331   
1332   preallocated =
1333     _dbus_connection_preallocate_send_unlocked (connection);
1334
1335   CONNECTION_UNLOCK (connection);
1336
1337   return preallocated;
1338 }
1339
1340 /**
1341  * Frees preallocated message-sending resources from
1342  * dbus_connection_preallocate_send(). Should only
1343  * be called if the preallocated resources are not used
1344  * to send a message.
1345  *
1346  * @param connection the connection
1347  * @param preallocated the resources
1348  */
1349 void
1350 dbus_connection_free_preallocated_send (DBusConnection       *connection,
1351                                         DBusPreallocatedSend *preallocated)
1352 {
1353   _dbus_return_if_fail (connection != NULL);
1354   _dbus_return_if_fail (preallocated != NULL);  
1355   _dbus_return_if_fail (connection == preallocated->connection);
1356
1357   _dbus_list_free_link (preallocated->queue_link);
1358   _dbus_counter_unref (preallocated->counter_link->data);
1359   _dbus_list_free_link (preallocated->counter_link);
1360   dbus_free (preallocated);
1361 }
1362
1363 static void
1364 _dbus_connection_send_preallocated_unlocked (DBusConnection       *connection,
1365                                              DBusPreallocatedSend *preallocated,
1366                                              DBusMessage          *message,
1367                                              dbus_uint32_t        *client_serial)
1368 {
1369   dbus_uint32_t serial;
1370
1371   preallocated->queue_link->data = message;
1372   _dbus_list_prepend_link (&connection->outgoing_messages,
1373                            preallocated->queue_link);
1374
1375   _dbus_message_add_size_counter_link (message,
1376                                        preallocated->counter_link);
1377
1378   dbus_free (preallocated);
1379   preallocated = NULL;
1380   
1381   dbus_message_ref (message);
1382   
1383   connection->n_outgoing += 1;
1384
1385   _dbus_verbose ("Message %p (%s) added to outgoing queue %p, %d pending to send\n",
1386                  message,
1387                  dbus_message_get_name (message),
1388                  connection,
1389                  connection->n_outgoing);
1390
1391   if (dbus_message_get_serial (message) == 0)
1392     {
1393       serial = _dbus_connection_get_next_client_serial (connection);
1394       _dbus_message_set_serial (message, serial);
1395       if (client_serial)
1396         *client_serial = serial;
1397     }
1398   else
1399     {
1400       if (client_serial)
1401         *client_serial = dbus_message_get_serial (message);
1402     }
1403   
1404   _dbus_message_lock (message);
1405
1406   if (connection->n_outgoing == 1)
1407     _dbus_transport_messages_pending (connection->transport,
1408                                       connection->n_outgoing);
1409   
1410   _dbus_connection_wakeup_mainloop (connection);
1411 }
1412
1413 /**
1414  * Sends a message using preallocated resources. This function cannot fail.
1415  * It works identically to dbus_connection_send() in other respects.
1416  * Preallocated resources comes from dbus_connection_preallocate_send().
1417  * This function "consumes" the preallocated resources, they need not
1418  * be freed separately.
1419  *
1420  * @param connection the connection
1421  * @param preallocated the preallocated resources
1422  * @param message the message to send
1423  * @param client_serial return location for client serial assigned to the message
1424  */
1425 void
1426 dbus_connection_send_preallocated (DBusConnection       *connection,
1427                                    DBusPreallocatedSend *preallocated,
1428                                    DBusMessage          *message,
1429                                    dbus_uint32_t        *client_serial)
1430 {
1431   _dbus_return_if_fail (connection != NULL);
1432   _dbus_return_if_fail (preallocated != NULL);
1433   _dbus_return_if_fail (message != NULL);
1434   _dbus_return_if_fail (preallocated->connection == connection);
1435   _dbus_return_if_fail (dbus_message_get_name (message) != NULL);
1436   
1437   CONNECTION_LOCK (connection);
1438   _dbus_connection_send_preallocated_unlocked (connection,
1439                                                preallocated,
1440                                                message, client_serial);
1441   CONNECTION_UNLOCK (connection);  
1442 }
1443
1444 /**
1445  * Adds a message to the outgoing message queue. Does not block to
1446  * write the message to the network; that happens asynchronously. To
1447  * force the message to be written, call dbus_connection_flush().
1448  * Because this only queues the message, the only reason it can
1449  * fail is lack of memory. Even if the connection is disconnected,
1450  * no error will be returned.
1451  *
1452  * If the function fails due to lack of memory, it returns #FALSE.
1453  * The function will never fail for other reasons; even if the
1454  * connection is disconnected, you can queue an outgoing message,
1455  * though obviously it won't be sent.
1456  * 
1457  * @param connection the connection.
1458  * @param message the message to write.
1459  * @param client_serial return location for client serial.
1460  * @returns #TRUE on success.
1461  */
1462 dbus_bool_t
1463 dbus_connection_send (DBusConnection *connection,
1464                       DBusMessage    *message,
1465                       dbus_uint32_t  *client_serial)
1466 {
1467   DBusPreallocatedSend *preallocated;
1468
1469   _dbus_return_val_if_fail (connection != NULL, FALSE);
1470   _dbus_return_val_if_fail (message != NULL, FALSE);
1471
1472   CONNECTION_LOCK (connection);
1473   
1474   preallocated = _dbus_connection_preallocate_send_unlocked (connection);
1475   if (preallocated == NULL)
1476     {
1477       CONNECTION_UNLOCK (connection);
1478       return FALSE;
1479     }
1480   else
1481     {
1482       _dbus_connection_send_preallocated_unlocked (connection,
1483                                                    preallocated,
1484                                                    message,
1485                                                    client_serial);
1486       CONNECTION_UNLOCK (connection);
1487       return TRUE;
1488     }
1489 }
1490
1491 static dbus_bool_t
1492 reply_handler_timeout (void *data)
1493 {
1494   DBusConnection *connection;
1495   ReplyHandlerData *reply_handler_data = data;
1496   DBusDispatchStatus status;
1497
1498   connection = reply_handler_data->connection;
1499   
1500   CONNECTION_LOCK (connection);
1501   if (reply_handler_data->timeout_link)
1502     {
1503       _dbus_connection_queue_synthesized_message_link (connection,
1504                                                        reply_handler_data->timeout_link);
1505       reply_handler_data->timeout_link = NULL;
1506     }
1507
1508   _dbus_connection_remove_timeout (connection,
1509                                    reply_handler_data->timeout);
1510   reply_handler_data->timeout_added = FALSE;
1511
1512   status = _dbus_connection_get_dispatch_status_unlocked (connection);
1513
1514   /* Unlocks, and calls out to user code */
1515   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1516   
1517   return TRUE;
1518 }
1519
1520 static void
1521 reply_handler_data_free (ReplyHandlerData *data)
1522 {
1523   if (!data)
1524     return;
1525
1526   if (data->timeout_added)
1527     _dbus_connection_remove_timeout_locked (data->connection,
1528                                             data->timeout);
1529
1530   if (data->connection_added)
1531     _dbus_message_handler_remove_connection (data->handler,
1532                                              data->connection);
1533
1534   if (data->timeout_link)
1535     {
1536       dbus_message_unref ((DBusMessage *)data->timeout_link->data);
1537       _dbus_list_free_link (data->timeout_link);
1538     }
1539   
1540   dbus_message_handler_unref (data->handler);
1541   
1542   dbus_free (data);
1543 }
1544
1545 /**
1546  * Queues a message to send, as with dbus_connection_send_message(),
1547  * but also sets up a DBusMessageHandler to receive a reply to the
1548  * message. If no reply is received in the given timeout_milliseconds,
1549  * expires the pending reply and sends the DBusMessageHandler a
1550  * synthetic error reply (generated in-process, not by the remote
1551  * application) indicating that a timeout occurred.
1552  *
1553  * Reply handlers see their replies after message filters see them,
1554  * but before message handlers added with
1555  * dbus_connection_register_handler() see them, regardless of the
1556  * reply message's name. Reply handlers are only handed a single
1557  * message as a reply, after one reply has been seen the handler is
1558  * removed. If a filter filters out the reply before the handler sees
1559  * it, the reply is immediately timed out and a timeout error reply is
1560  * generated. If a filter removes the timeout error reply then the
1561  * reply handler will never be called. Filters should not do this.
1562  * 
1563  * If #NULL is passed for the reply_handler, the timeout reply will
1564  * still be generated and placed into the message queue, but no
1565  * specific message handler will receive the reply.
1566  *
1567  * If -1 is passed for the timeout, a sane default timeout is used. -1
1568  * is typically the best value for the timeout for this reason, unless
1569  * you want a very short or very long timeout.  There is no way to
1570  * avoid a timeout entirely, other than passing INT_MAX for the
1571  * timeout to postpone it indefinitely.
1572  * 
1573  * @param connection the connection
1574  * @param message the message to send
1575  * @param reply_handler message handler expecting the reply, or #NULL
1576  * @param timeout_milliseconds timeout in milliseconds or -1 for default
1577  * @returns #TRUE if the message is successfully queued, #FALSE if no memory.
1578  *
1579  */
1580 dbus_bool_t
1581 dbus_connection_send_with_reply (DBusConnection     *connection,
1582                                  DBusMessage        *message,
1583                                  DBusMessageHandler *reply_handler,
1584                                  int                 timeout_milliseconds)
1585 {
1586   DBusTimeout *timeout;
1587   ReplyHandlerData *data;
1588   DBusMessage *reply;
1589   DBusList *reply_link;
1590   dbus_int32_t serial = -1;
1591
1592   _dbus_return_val_if_fail (connection != NULL, FALSE);
1593   _dbus_return_val_if_fail (message != NULL, FALSE);
1594   _dbus_return_val_if_fail (reply_handler != NULL, FALSE);
1595   _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
1596   
1597   if (timeout_milliseconds == -1)
1598     timeout_milliseconds = DEFAULT_TIMEOUT_VALUE;
1599
1600   data = dbus_new0 (ReplyHandlerData, 1);
1601
1602   if (!data)
1603     return FALSE;
1604   
1605   timeout = _dbus_timeout_new (timeout_milliseconds, reply_handler_timeout,
1606                                data, NULL);
1607
1608   if (!timeout)
1609     {
1610       reply_handler_data_free (data);
1611       return FALSE;
1612     }
1613
1614   CONNECTION_LOCK (connection);
1615   
1616   /* Add timeout */
1617   if (!_dbus_connection_add_timeout (connection, timeout))
1618     {
1619       reply_handler_data_free (data);
1620       _dbus_timeout_unref (timeout);
1621       CONNECTION_UNLOCK (connection);
1622       return FALSE;
1623     }
1624
1625   /* The connection now owns the reference to the timeout. */
1626   _dbus_timeout_unref (timeout);
1627   
1628   data->timeout_added = TRUE;
1629   data->timeout = timeout;
1630   data->connection = connection;
1631   
1632   if (!_dbus_message_handler_add_connection (reply_handler, connection))
1633     {
1634       CONNECTION_UNLOCK (connection);
1635       reply_handler_data_free (data);
1636       return FALSE;
1637     }
1638   data->connection_added = TRUE;
1639   
1640   /* Assign a serial to the message */
1641   if (dbus_message_get_serial (message) == 0)
1642     {
1643       serial = _dbus_connection_get_next_client_serial (connection);
1644       _dbus_message_set_serial (message, serial);
1645     }
1646
1647   data->handler = reply_handler;
1648   data->serial = serial;
1649
1650   dbus_message_handler_ref (reply_handler);
1651
1652   reply = dbus_message_new_error (message, DBUS_ERROR_NO_REPLY,
1653                                   "No reply within specified time");
1654   if (!reply)
1655     {
1656       CONNECTION_UNLOCK (connection);
1657       reply_handler_data_free (data);
1658       return FALSE;
1659     }
1660
1661   reply_link = _dbus_list_alloc_link (reply);
1662   if (!reply)
1663     {
1664       CONNECTION_UNLOCK (connection);
1665       dbus_message_unref (reply);
1666       reply_handler_data_free (data);
1667       return FALSE;
1668     }
1669
1670   data->timeout_link = reply_link;
1671   
1672   /* Insert the serial in the pending replies hash. */
1673   if (!_dbus_hash_table_insert_int (connection->pending_replies, serial, data))
1674     {
1675       CONNECTION_UNLOCK (connection);
1676       reply_handler_data_free (data);      
1677       return FALSE;
1678     }
1679
1680   CONNECTION_UNLOCK (connection);
1681   
1682   if (!dbus_connection_send (connection, message, NULL))
1683     {
1684       /* This will free the handler data too */
1685       _dbus_hash_table_remove_int (connection->pending_replies, serial);
1686       return FALSE;
1687     }
1688
1689   return TRUE;
1690 }
1691
1692
1693 static DBusMessage*
1694 check_for_reply_unlocked (DBusConnection *connection,
1695                           dbus_uint32_t   client_serial)
1696 {
1697   DBusList *link;
1698   
1699   link = _dbus_list_get_first_link (&connection->incoming_messages);
1700
1701   while (link != NULL)
1702     {
1703       DBusMessage *reply = link->data;
1704
1705       if (dbus_message_get_reply_serial (reply) == client_serial)
1706         {
1707           _dbus_list_remove_link (&connection->incoming_messages, link);
1708           connection->n_incoming  -= 1;
1709           dbus_message_ref (reply);
1710           return reply;
1711         }
1712       link = _dbus_list_get_next_link (&connection->incoming_messages, link);
1713     }
1714
1715   return NULL;
1716 }
1717
1718 /**
1719  * Sends a message and blocks a certain time period while waiting for a reply.
1720  * This function does not dispatch any message handlers until the main loop
1721  * has been reached. This function is used to do non-reentrant "method calls."
1722  * If a reply is received, it is returned, and removed from the incoming
1723  * message queue. If it is not received, #NULL is returned and the
1724  * error is set to #DBUS_ERROR_NO_REPLY. If something else goes
1725  * wrong, result is set to whatever is appropriate, such as
1726  * #DBUS_ERROR_NO_MEMORY or #DBUS_ERROR_DISCONNECTED.
1727  *
1728  * @todo could use performance improvements (it keeps scanning
1729  * the whole message queue for example) and has thread issues,
1730  * see comments in source
1731  *
1732  * @param connection the connection
1733  * @param message the message to send
1734  * @param timeout_milliseconds timeout in milliseconds or -1 for default
1735  * @param error return location for error message
1736  * @returns the message that is the reply or #NULL with an error code if the
1737  * function fails.
1738  */
1739 DBusMessage *
1740 dbus_connection_send_with_reply_and_block (DBusConnection     *connection,
1741                                            DBusMessage        *message,
1742                                            int                 timeout_milliseconds,
1743                                            DBusError          *error)
1744 {
1745   dbus_uint32_t client_serial;
1746   long start_tv_sec, start_tv_usec;
1747   long end_tv_sec, end_tv_usec;
1748   long tv_sec, tv_usec;
1749   DBusDispatchStatus status;
1750
1751   _dbus_return_val_if_fail (connection != NULL, NULL);
1752   _dbus_return_val_if_fail (message != NULL, NULL);
1753   _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);  
1754   _dbus_return_val_if_error_is_set (error, NULL);
1755   
1756   if (timeout_milliseconds == -1)
1757     timeout_milliseconds = DEFAULT_TIMEOUT_VALUE;
1758
1759   /* it would probably seem logical to pass in _DBUS_INT_MAX
1760    * for infinite timeout, but then math below would get
1761    * all overflow-prone, so smack that down.
1762    */
1763   if (timeout_milliseconds > _DBUS_ONE_HOUR_IN_MILLISECONDS * 6)
1764     timeout_milliseconds = _DBUS_ONE_HOUR_IN_MILLISECONDS * 6;
1765   
1766   if (!dbus_connection_send (connection, message, &client_serial))
1767     {
1768       _DBUS_SET_OOM (error);
1769       return NULL;
1770     }
1771
1772   message = NULL;
1773   
1774   /* Flush message queue */
1775   dbus_connection_flush (connection);
1776
1777   CONNECTION_LOCK (connection);
1778
1779   _dbus_get_current_time (&start_tv_sec, &start_tv_usec);
1780   end_tv_sec = start_tv_sec + timeout_milliseconds / 1000;
1781   end_tv_usec = start_tv_usec + (timeout_milliseconds % 1000) * 1000;
1782   end_tv_sec += end_tv_usec / _DBUS_USEC_PER_SECOND;
1783   end_tv_usec = end_tv_usec % _DBUS_USEC_PER_SECOND;
1784
1785   _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",
1786                  timeout_milliseconds,
1787                  client_serial,
1788                  start_tv_sec, start_tv_usec,
1789                  end_tv_sec, end_tv_usec);
1790   
1791   /* Now we wait... */
1792   /* THREAD TODO: This is busted. What if a dispatch() or pop_message
1793    * gets the message before we do?
1794    */
1795   /* always block at least once as we know we don't have the reply yet */
1796   _dbus_connection_do_iteration (connection,
1797                                  DBUS_ITERATION_DO_READING |
1798                                  DBUS_ITERATION_BLOCK,
1799                                  timeout_milliseconds);
1800
1801  recheck_status:
1802
1803   /* queue messages and get status */
1804   status = _dbus_connection_get_dispatch_status_unlocked (connection);
1805
1806   if (status == DBUS_DISPATCH_DATA_REMAINS)
1807     {
1808       DBusMessage *reply;
1809       
1810       reply = check_for_reply_unlocked (connection, client_serial);
1811       if (reply != NULL)
1812         {          
1813           status = _dbus_connection_get_dispatch_status_unlocked (connection);
1814
1815           _dbus_verbose ("dbus_connection_send_with_reply_and_block(): got reply %s\n",
1816                          dbus_message_get_name (reply));
1817
1818           /* Unlocks, and calls out to user code */
1819           _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1820           
1821           return reply;
1822         }
1823     }
1824   
1825   _dbus_get_current_time (&tv_sec, &tv_usec);
1826   
1827   if (tv_sec < start_tv_sec)
1828     _dbus_verbose ("dbus_connection_send_with_reply_and_block(): clock set backward\n");
1829   else if (connection->disconnect_message_link == NULL)
1830     _dbus_verbose ("dbus_connection_send_with_reply_and_block(): disconnected\n");
1831   else if (tv_sec < end_tv_sec ||
1832            (tv_sec == end_tv_sec && tv_usec < end_tv_usec))
1833     {
1834       timeout_milliseconds = (end_tv_sec - tv_sec) * 1000 +
1835         (end_tv_usec - tv_usec) / 1000;
1836       _dbus_verbose ("dbus_connection_send_with_reply_and_block(): %d milliseconds remain\n", timeout_milliseconds);
1837       _dbus_assert (timeout_milliseconds >= 0);
1838       
1839       if (status == DBUS_DISPATCH_NEED_MEMORY)
1840         {
1841           /* Try sleeping a bit, as we aren't sure we need to block for reading,
1842            * we may already have a reply in the buffer and just can't process
1843            * it.
1844            */
1845           _dbus_verbose ("dbus_connection_send_with_reply_and_block() waiting for more memory\n");
1846           
1847           if (timeout_milliseconds < 100)
1848             ; /* just busy loop */
1849           else if (timeout_milliseconds <= 1000)
1850             _dbus_sleep_milliseconds (timeout_milliseconds / 3);
1851           else
1852             _dbus_sleep_milliseconds (1000);
1853         }
1854       else
1855         {          
1856           /* block again, we don't have the reply buffered yet. */
1857           _dbus_connection_do_iteration (connection,
1858                                          DBUS_ITERATION_DO_READING |
1859                                          DBUS_ITERATION_BLOCK,
1860                                          timeout_milliseconds);
1861         }
1862
1863       goto recheck_status;
1864     }
1865
1866   _dbus_verbose ("dbus_connection_send_with_reply_and_block(): Waited %ld milliseconds and got no reply\n",
1867                  (tv_sec - start_tv_sec) * 1000 + (tv_usec - start_tv_usec) / 1000);
1868   
1869   if (dbus_connection_get_is_connected (connection))
1870     dbus_set_error (error, DBUS_ERROR_NO_REPLY, "Message did not receive a reply");
1871   else
1872     dbus_set_error (error, DBUS_ERROR_DISCONNECTED, "Disconnected prior to receiving a reply");
1873
1874   /* unlocks and calls out to user code */
1875   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1876
1877   return NULL;
1878 }
1879
1880 /**
1881  * Blocks until the outgoing message queue is empty.
1882  *
1883  * @param connection the connection.
1884  */
1885 void
1886 dbus_connection_flush (DBusConnection *connection)
1887 {
1888   /* We have to specify DBUS_ITERATION_DO_READING here because
1889    * otherwise we could have two apps deadlock if they are both doing
1890    * a flush(), and the kernel buffers fill up. This could change the
1891    * dispatch status.
1892    */
1893   DBusDispatchStatus status;
1894
1895   _dbus_return_if_fail (connection != NULL);
1896   
1897   CONNECTION_LOCK (connection);
1898   while (connection->n_outgoing > 0 &&
1899          _dbus_connection_get_is_connected_unlocked (connection))
1900     _dbus_connection_do_iteration (connection,
1901                                    DBUS_ITERATION_DO_READING |
1902                                    DBUS_ITERATION_DO_WRITING |
1903                                    DBUS_ITERATION_BLOCK,
1904                                    -1);
1905
1906   status = _dbus_connection_get_dispatch_status_unlocked (connection);
1907
1908   /* Unlocks and calls out to user code */
1909   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1910 }
1911
1912 /* Call with mutex held. Will drop it while waiting and re-acquire
1913  * before returning
1914  */
1915 static void
1916 _dbus_connection_wait_for_borrowed (DBusConnection *connection)
1917 {
1918   _dbus_assert (connection->message_borrowed != NULL);
1919
1920   while (connection->message_borrowed != NULL)
1921     dbus_condvar_wait (connection->message_returned_cond, connection->mutex);
1922 }
1923
1924 /**
1925  * Returns the first-received message from the incoming message queue,
1926  * leaving it in the queue. If the queue is empty, returns #NULL.
1927  * 
1928  * The caller does not own a reference to the returned message, and
1929  * must either return it using dbus_connection_return_message() or
1930  * keep it after calling dbus_connection_steal_borrowed_message(). No
1931  * one can get at the message while its borrowed, so return it as
1932  * quickly as possible and don't keep a reference to it after
1933  * returning it. If you need to keep the message, make a copy of it.
1934  *
1935  * @param connection the connection.
1936  * @returns next message in the incoming queue.
1937  */
1938 DBusMessage*
1939 dbus_connection_borrow_message  (DBusConnection *connection)
1940 {
1941   DBusMessage *message;
1942   DBusDispatchStatus status;
1943
1944   _dbus_return_val_if_fail (connection != NULL, NULL);
1945   
1946   /* this is called for the side effect that it queues
1947    * up any messages from the transport
1948    */
1949   status = dbus_connection_get_dispatch_status (connection);
1950   if (status != DBUS_DISPATCH_DATA_REMAINS)
1951     return NULL;
1952   
1953   CONNECTION_LOCK (connection);
1954
1955   if (connection->message_borrowed != NULL)
1956     _dbus_connection_wait_for_borrowed (connection);
1957   
1958   message = _dbus_list_get_first (&connection->incoming_messages);
1959
1960   if (message) 
1961     connection->message_borrowed = message;
1962   
1963   CONNECTION_UNLOCK (connection);
1964   return message;
1965 }
1966
1967 /**
1968  * Used to return a message after peeking at it using
1969  * dbus_connection_borrow_message().
1970  *
1971  * @param connection the connection
1972  * @param message the message from dbus_connection_borrow_message()
1973  */
1974 void
1975 dbus_connection_return_message (DBusConnection *connection,
1976                                 DBusMessage    *message)
1977 {
1978   _dbus_return_if_fail (connection != NULL);
1979   _dbus_return_if_fail (message != NULL);
1980   
1981   CONNECTION_LOCK (connection);
1982   
1983   _dbus_assert (message == connection->message_borrowed);
1984   
1985   connection->message_borrowed = NULL;
1986   dbus_condvar_wake_all (connection->message_returned_cond);
1987   
1988   CONNECTION_UNLOCK (connection);
1989 }
1990
1991 /**
1992  * Used to keep a message after peeking at it using
1993  * dbus_connection_borrow_message(). Before using this function, see
1994  * the caveats/warnings in the documentation for
1995  * dbus_connection_pop_message().
1996  *
1997  * @param connection the connection
1998  * @param message the message from dbus_connection_borrow_message()
1999  */
2000 void
2001 dbus_connection_steal_borrowed_message (DBusConnection *connection,
2002                                         DBusMessage    *message)
2003 {
2004   DBusMessage *pop_message;
2005
2006   _dbus_return_if_fail (connection != NULL);
2007   _dbus_return_if_fail (message != NULL);
2008   
2009   CONNECTION_LOCK (connection);
2010  
2011   _dbus_assert (message == connection->message_borrowed);
2012
2013   pop_message = _dbus_list_pop_first (&connection->incoming_messages);
2014   _dbus_assert (message == pop_message);
2015   
2016   connection->n_incoming -= 1;
2017  
2018   _dbus_verbose ("Incoming message %p stolen from queue, %d incoming\n",
2019                  message, connection->n_incoming);
2020  
2021   connection->message_borrowed = NULL;
2022   dbus_condvar_wake_all (connection->message_returned_cond);
2023   
2024   CONNECTION_UNLOCK (connection);
2025 }
2026
2027 /* See dbus_connection_pop_message, but requires the caller to own
2028  * the lock before calling. May drop the lock while running.
2029  */
2030 static DBusList*
2031 _dbus_connection_pop_message_link_unlocked (DBusConnection *connection)
2032 {
2033   if (connection->message_borrowed != NULL)
2034     _dbus_connection_wait_for_borrowed (connection);
2035   
2036   if (connection->n_incoming > 0)
2037     {
2038       DBusList *link;
2039
2040       link = _dbus_list_pop_first_link (&connection->incoming_messages);
2041       connection->n_incoming -= 1;
2042
2043       _dbus_verbose ("Message %p (%s) removed from incoming queue %p, %d incoming\n",
2044                      link->data, dbus_message_get_name (link->data),
2045                      connection, connection->n_incoming);
2046
2047       return link;
2048     }
2049   else
2050     return NULL;
2051 }
2052
2053 /* See dbus_connection_pop_message, but requires the caller to own
2054  * the lock before calling. May drop the lock while running.
2055  */
2056 static DBusMessage*
2057 _dbus_connection_pop_message_unlocked (DBusConnection *connection)
2058 {
2059   DBusList *link;
2060   
2061   link = _dbus_connection_pop_message_link_unlocked (connection);
2062
2063   if (link != NULL)
2064     {
2065       DBusMessage *message;
2066       
2067       message = link->data;
2068       
2069       _dbus_list_free_link (link);
2070       
2071       return message;
2072     }
2073   else
2074     return NULL;
2075 }
2076
2077
2078 /**
2079  * Returns the first-received message from the incoming message queue,
2080  * removing it from the queue. The caller owns a reference to the
2081  * returned message. If the queue is empty, returns #NULL.
2082  *
2083  * This function bypasses any message handlers that are registered,
2084  * and so using it is usually wrong. Instead, let the main loop invoke
2085  * dbus_connection_dispatch(). Popping messages manually is only
2086  * useful in very simple programs that don't share a #DBusConnection
2087  * with any libraries or other modules.
2088  *
2089  * @param connection the connection.
2090  * @returns next message in the incoming queue.
2091  */
2092 DBusMessage*
2093 dbus_connection_pop_message (DBusConnection *connection)
2094 {
2095   DBusMessage *message;
2096   DBusDispatchStatus status;
2097
2098   /* this is called for the side effect that it queues
2099    * up any messages from the transport
2100    */
2101   status = dbus_connection_get_dispatch_status (connection);
2102   if (status != DBUS_DISPATCH_DATA_REMAINS)
2103     return NULL;
2104   
2105   CONNECTION_LOCK (connection);
2106
2107   message = _dbus_connection_pop_message_unlocked (connection);
2108
2109   _dbus_verbose ("Returning popped message %p\n", message);    
2110   
2111   CONNECTION_UNLOCK (connection);
2112   
2113   return message;
2114 }
2115
2116 /**
2117  * Acquire the dispatcher. This must be done before dispatching
2118  * messages in order to guarantee the right order of
2119  * message delivery. May sleep and drop the connection mutex
2120  * while waiting for the dispatcher.
2121  *
2122  * @param connection the connection.
2123  */
2124 static void
2125 _dbus_connection_acquire_dispatch (DBusConnection *connection)
2126 {
2127   if (connection->dispatch_acquired)
2128     dbus_condvar_wait (connection->dispatch_cond, connection->mutex);
2129   _dbus_assert (!connection->dispatch_acquired);
2130
2131   connection->dispatch_acquired = TRUE;
2132 }
2133
2134 /**
2135  * Release the dispatcher when you're done with it. Only call
2136  * after you've acquired the dispatcher. Wakes up at most one
2137  * thread currently waiting to acquire the dispatcher.
2138  *
2139  * @param connection the connection.
2140  */
2141 static void
2142 _dbus_connection_release_dispatch (DBusConnection *connection)
2143 {
2144   _dbus_assert (connection->dispatch_acquired);
2145
2146   connection->dispatch_acquired = FALSE;
2147   dbus_condvar_wake_one (connection->dispatch_cond);
2148 }
2149
2150 static void
2151 _dbus_connection_failed_pop (DBusConnection *connection,
2152                              DBusList       *message_link)
2153 {
2154   _dbus_list_prepend_link (&connection->incoming_messages,
2155                            message_link);
2156   connection->n_incoming += 1;
2157 }
2158
2159 static DBusDispatchStatus
2160 _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection)
2161 {
2162   if (connection->n_incoming > 0)
2163     return DBUS_DISPATCH_DATA_REMAINS;
2164   else if (!_dbus_transport_queue_messages (connection->transport))
2165     return DBUS_DISPATCH_NEED_MEMORY;
2166   else
2167     {
2168       DBusDispatchStatus status;
2169       
2170       status = _dbus_transport_get_dispatch_status (connection->transport);
2171
2172       if (status != DBUS_DISPATCH_COMPLETE)
2173         return status;
2174       else if (connection->n_incoming > 0)
2175         return DBUS_DISPATCH_DATA_REMAINS;
2176       else
2177         return DBUS_DISPATCH_COMPLETE;
2178     }
2179 }
2180
2181 static void
2182 _dbus_connection_update_dispatch_status_and_unlock (DBusConnection    *connection,
2183                                                     DBusDispatchStatus new_status)
2184 {
2185   dbus_bool_t changed;
2186   DBusDispatchStatusFunction function;
2187   void *data;
2188
2189   /* We have the lock */
2190
2191   _dbus_connection_ref_unlocked (connection);
2192
2193   changed = new_status != connection->last_dispatch_status;
2194
2195   connection->last_dispatch_status = new_status;
2196
2197   function = connection->dispatch_status_function;
2198   data = connection->dispatch_status_data;
2199
2200   /* We drop the lock */
2201   CONNECTION_UNLOCK (connection);
2202   
2203   if (changed && function)
2204     {
2205       _dbus_verbose ("Notifying of change to dispatch status of %p now %d (%s)\n",
2206                      connection, new_status,
2207                      new_status == DBUS_DISPATCH_COMPLETE ? "complete" :
2208                      new_status == DBUS_DISPATCH_DATA_REMAINS ? "data remains" :
2209                      new_status == DBUS_DISPATCH_NEED_MEMORY ? "need memory" :
2210                      "???");
2211       (* function) (connection, new_status, data);      
2212     }
2213   
2214   dbus_connection_unref (connection);
2215 }
2216
2217 /**
2218  * Gets the current state (what we would currently return
2219  * from dbus_connection_dispatch()) but doesn't actually
2220  * dispatch any messages.
2221  * 
2222  * @param connection the connection.
2223  * @returns current dispatch status
2224  */
2225 DBusDispatchStatus
2226 dbus_connection_get_dispatch_status (DBusConnection *connection)
2227 {
2228   DBusDispatchStatus status;
2229
2230   _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
2231   
2232   CONNECTION_LOCK (connection);
2233
2234   status = _dbus_connection_get_dispatch_status_unlocked (connection);
2235   
2236   CONNECTION_UNLOCK (connection);
2237
2238   return status;
2239 }
2240
2241 /**
2242  * Processes data buffered while handling watches, queueing zero or
2243  * more incoming messages. Then pops the first-received message from
2244  * the current incoming message queue, runs any handlers for it, and
2245  * unrefs the message. Returns a status indicating whether messages/data
2246  * remain, more memory is needed, or all data has been processed.
2247  * 
2248  * Even if the dispatch status is #DBUS_DISPATCH_DATA_REMAINS,
2249  * does not necessarily dispatch a message, as the data may
2250  * be part of authentication or the like.
2251  *
2252  * @todo some FIXME in here about handling DBUS_HANDLER_RESULT_NEED_MEMORY
2253  * 
2254  * @param connection the connection
2255  * @returns dispatch status
2256  */
2257 DBusDispatchStatus
2258 dbus_connection_dispatch (DBusConnection *connection)
2259 {
2260   DBusMessage *message;
2261   DBusList *link, *filter_list_copy, *message_link;
2262   DBusHandlerResult result;
2263   ReplyHandlerData *reply_handler_data;
2264   dbus_int32_t reply_serial;
2265   DBusDispatchStatus status;
2266
2267   _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
2268
2269   CONNECTION_LOCK (connection);
2270   status = _dbus_connection_get_dispatch_status_unlocked (connection);
2271   if (status != DBUS_DISPATCH_DATA_REMAINS)
2272     {
2273       /* unlocks and calls out to user code */
2274       _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2275       return status;
2276     }
2277   
2278   /* We need to ref the connection since the callback could potentially
2279    * drop the last ref to it
2280    */
2281   _dbus_connection_ref_unlocked (connection);
2282
2283   _dbus_connection_acquire_dispatch (connection);
2284   
2285   /* This call may drop the lock during the execution (if waiting for
2286    * borrowed messages to be returned) but the order of message
2287    * dispatch if several threads call dispatch() is still
2288    * protected by the lock, since only one will get the lock, and that
2289    * one will finish the message dispatching
2290    */
2291   message_link = _dbus_connection_pop_message_link_unlocked (connection);
2292   if (message_link == NULL)
2293     {
2294       /* another thread dispatched our stuff */
2295
2296       _dbus_connection_release_dispatch (connection);
2297
2298       status = _dbus_connection_get_dispatch_status_unlocked (connection);
2299
2300       _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2301       
2302       dbus_connection_unref (connection);
2303       
2304       return status;
2305     }
2306
2307   message = message_link->data;
2308   
2309   result = DBUS_HANDLER_RESULT_ALLOW_MORE_HANDLERS;
2310
2311   reply_serial = dbus_message_get_reply_serial (message);
2312   reply_handler_data = _dbus_hash_table_lookup_int (connection->pending_replies,
2313                                                     reply_serial);
2314   
2315   if (!_dbus_list_copy (&connection->filter_list, &filter_list_copy))
2316     {
2317       _dbus_connection_release_dispatch (connection);
2318
2319       _dbus_connection_failed_pop (connection, message_link);
2320
2321       /* unlocks and calls user code */
2322       _dbus_connection_update_dispatch_status_and_unlock (connection,
2323                                                           DBUS_DISPATCH_NEED_MEMORY);
2324
2325       dbus_connection_unref (connection);
2326       
2327       return DBUS_DISPATCH_NEED_MEMORY;
2328     }
2329   
2330   _dbus_list_foreach (&filter_list_copy,
2331                       (DBusForeachFunction)dbus_message_handler_ref,
2332                       NULL);
2333
2334   /* We're still protected from dispatch() reentrancy here
2335    * since we acquired the dispatcher
2336    */
2337   CONNECTION_UNLOCK (connection);
2338   
2339   link = _dbus_list_get_first_link (&filter_list_copy);
2340   while (link != NULL)
2341     {
2342       DBusMessageHandler *handler = link->data;
2343       DBusList *next = _dbus_list_get_next_link (&filter_list_copy, link);
2344
2345       _dbus_verbose ("  running filter on message %p\n", message);
2346       result = _dbus_message_handler_handle_message (handler, connection,
2347                                                      message);
2348
2349       if (result != DBUS_HANDLER_RESULT_ALLOW_MORE_HANDLERS)
2350         break;
2351
2352       link = next;
2353     }
2354
2355   _dbus_list_foreach (&filter_list_copy,
2356                       (DBusForeachFunction)dbus_message_handler_unref,
2357                       NULL);
2358   _dbus_list_clear (&filter_list_copy);
2359   
2360   CONNECTION_LOCK (connection);
2361
2362   if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
2363     /* FIXME */ ;
2364   
2365   /* Did a reply we were waiting on get filtered? */
2366   if (reply_handler_data && result == DBUS_HANDLER_RESULT_REMOVE_MESSAGE)
2367     {
2368       /* Queue the timeout immediately! */
2369       if (reply_handler_data->timeout_link)
2370         {
2371           _dbus_connection_queue_synthesized_message_link (connection,
2372                                                            reply_handler_data->timeout_link);
2373           reply_handler_data->timeout_link = NULL;
2374         }
2375       else
2376         {
2377           /* We already queued the timeout? Then it was filtered! */
2378           _dbus_warn ("The timeout error with reply serial %d was filtered, so the reply handler will never be called.\n", reply_serial);
2379         }
2380     }
2381   
2382   if (result == DBUS_HANDLER_RESULT_REMOVE_MESSAGE)
2383     goto out;
2384   
2385   if (reply_handler_data)
2386     {
2387       CONNECTION_UNLOCK (connection);
2388
2389       _dbus_verbose ("  running reply handler on message %p\n", message);
2390       
2391       result = _dbus_message_handler_handle_message (reply_handler_data->handler,
2392                                                      connection, message);
2393       reply_handler_data_free (reply_handler_data);
2394       CONNECTION_LOCK (connection);
2395       goto out;
2396     }
2397
2398   /* We're still protected from dispatch() reentrancy here
2399    * since we acquired the dispatcher
2400    */
2401   _dbus_verbose ("  running object handler on message %p (%s)\n",
2402                  message, dbus_message_get_name (message));
2403   
2404   result = _dbus_object_registry_handle_and_unlock (connection->objects,
2405                                                     message);
2406   
2407   CONNECTION_LOCK (connection);
2408   if (result == DBUS_HANDLER_RESULT_REMOVE_MESSAGE)
2409     goto out;
2410
2411   if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
2412     /* FIXME */ ; 
2413   
2414   _dbus_verbose ("  done dispatching %p (%s) on connection %p\n", message,
2415                  dbus_message_get_name (message), connection);
2416   
2417  out:
2418   _dbus_connection_release_dispatch (connection);
2419
2420   _dbus_list_free_link (message_link);
2421   dbus_message_unref (message); /* don't want the message to count in max message limits
2422                                  * in computing dispatch status
2423                                  */
2424   
2425   status = _dbus_connection_get_dispatch_status_unlocked (connection);
2426
2427   /* unlocks and calls user code */
2428   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2429   
2430   dbus_connection_unref (connection);
2431   
2432   return status;
2433 }
2434
2435 /**
2436  * Sets the watch functions for the connection. These functions are
2437  * responsible for making the application's main loop aware of file
2438  * descriptors that need to be monitored for events, using select() or
2439  * poll(). When using Qt, typically the DBusAddWatchFunction would
2440  * create a QSocketNotifier. When using GLib, the DBusAddWatchFunction
2441  * could call g_io_add_watch(), or could be used as part of a more
2442  * elaborate GSource. Note that when a watch is added, it may
2443  * not be enabled.
2444  *
2445  * The DBusWatchToggledFunction notifies the application that the
2446  * watch has been enabled or disabled. Call dbus_watch_get_enabled()
2447  * to check this. A disabled watch should have no effect, and enabled
2448  * watch should be added to the main loop. This feature is used
2449  * instead of simply adding/removing the watch because
2450  * enabling/disabling can be done without memory allocation.  The
2451  * toggled function may be NULL if a main loop re-queries
2452  * dbus_watch_get_enabled() every time anyway.
2453  * 
2454  * The DBusWatch can be queried for the file descriptor to watch using
2455  * dbus_watch_get_fd(), and for the events to watch for using
2456  * dbus_watch_get_flags(). The flags returned by
2457  * dbus_watch_get_flags() will only contain DBUS_WATCH_READABLE and
2458  * DBUS_WATCH_WRITABLE, never DBUS_WATCH_HANGUP or DBUS_WATCH_ERROR;
2459  * all watches implicitly include a watch for hangups, errors, and
2460  * other exceptional conditions.
2461  *
2462  * Once a file descriptor becomes readable or writable, or an exception
2463  * occurs, dbus_watch_handle() should be called to
2464  * notify the connection of the file descriptor's condition.
2465  *
2466  * dbus_watch_handle() cannot be called during the
2467  * DBusAddWatchFunction, as the connection will not be ready to handle
2468  * that watch yet.
2469  * 
2470  * It is not allowed to reference a DBusWatch after it has been passed
2471  * to remove_function.
2472  *
2473  * If #FALSE is returned due to lack of memory, the failure may be due
2474  * to a #FALSE return from the new add_function. If so, the
2475  * add_function may have been called successfully one or more times,
2476  * but the remove_function will also have been called to remove any
2477  * successful adds. i.e. if #FALSE is returned the net result
2478  * should be that dbus_connection_set_watch_functions() has no effect,
2479  * but the add_function and remove_function may have been called.
2480  *
2481  * @todo We need to drop the lock when we call the
2482  * add/remove/toggled functions which can be a side effect
2483  * of setting the watch functions.
2484  * 
2485  * @param connection the connection.
2486  * @param add_function function to begin monitoring a new descriptor.
2487  * @param remove_function function to stop monitoring a descriptor.
2488  * @param toggled_function function to notify of enable/disable
2489  * @param data data to pass to add_function and remove_function.
2490  * @param free_data_function function to be called to free the data.
2491  * @returns #FALSE on failure (no memory)
2492  */
2493 dbus_bool_t
2494 dbus_connection_set_watch_functions (DBusConnection              *connection,
2495                                      DBusAddWatchFunction         add_function,
2496                                      DBusRemoveWatchFunction      remove_function,
2497                                      DBusWatchToggledFunction     toggled_function,
2498                                      void                        *data,
2499                                      DBusFreeFunction             free_data_function)
2500 {
2501   dbus_bool_t retval;
2502
2503   _dbus_return_val_if_fail (connection != NULL, FALSE);
2504   
2505   CONNECTION_LOCK (connection);
2506   /* ref connection for slightly better reentrancy */
2507   _dbus_connection_ref_unlocked (connection);
2508
2509   /* FIXME this can call back into user code, and we need to drop the
2510    * connection lock when it does.
2511    */
2512   retval = _dbus_watch_list_set_functions (connection->watches,
2513                                            add_function, remove_function,
2514                                            toggled_function,
2515                                            data, free_data_function);
2516   
2517   CONNECTION_UNLOCK (connection);
2518   /* drop our paranoid refcount */
2519   dbus_connection_unref (connection);
2520
2521   return retval;
2522 }
2523
2524 /**
2525  * Sets the timeout functions for the connection. These functions are
2526  * responsible for making the application's main loop aware of timeouts.
2527  * When using Qt, typically the DBusAddTimeoutFunction would create a
2528  * QTimer. When using GLib, the DBusAddTimeoutFunction would call
2529  * g_timeout_add.
2530  * 
2531  * The DBusTimeoutToggledFunction notifies the application that the
2532  * timeout has been enabled or disabled. Call
2533  * dbus_timeout_get_enabled() to check this. A disabled timeout should
2534  * have no effect, and enabled timeout should be added to the main
2535  * loop. This feature is used instead of simply adding/removing the
2536  * timeout because enabling/disabling can be done without memory
2537  * allocation. With Qt, QTimer::start() and QTimer::stop() can be used
2538  * to enable and disable. The toggled function may be NULL if a main
2539  * loop re-queries dbus_timeout_get_enabled() every time anyway.
2540  * Whenever a timeout is toggled, its interval may change.
2541  *
2542  * The DBusTimeout can be queried for the timer interval using
2543  * dbus_timeout_get_interval(). dbus_timeout_handle() should be called
2544  * repeatedly, each time the interval elapses, starting after it has
2545  * elapsed once. The timeout stops firing when it is removed with the
2546  * given remove_function.  The timer interval may change whenever the
2547  * timeout is added, removed, or toggled.
2548  *
2549  * @param connection the connection.
2550  * @param add_function function to add a timeout.
2551  * @param remove_function function to remove a timeout.
2552  * @param toggled_function function to notify of enable/disable
2553  * @param data data to pass to add_function and remove_function.
2554  * @param free_data_function function to be called to free the data.
2555  * @returns #FALSE on failure (no memory)
2556  */
2557 dbus_bool_t
2558 dbus_connection_set_timeout_functions   (DBusConnection            *connection,
2559                                          DBusAddTimeoutFunction     add_function,
2560                                          DBusRemoveTimeoutFunction  remove_function,
2561                                          DBusTimeoutToggledFunction toggled_function,
2562                                          void                      *data,
2563                                          DBusFreeFunction           free_data_function)
2564 {
2565   dbus_bool_t retval;
2566
2567   _dbus_return_val_if_fail (connection != NULL, FALSE);
2568   
2569   CONNECTION_LOCK (connection);
2570   /* ref connection for slightly better reentrancy */
2571   _dbus_connection_ref_unlocked (connection);
2572   
2573   retval = _dbus_timeout_list_set_functions (connection->timeouts,
2574                                              add_function, remove_function,
2575                                              toggled_function,
2576                                              data, free_data_function);
2577   
2578   CONNECTION_UNLOCK (connection);
2579   /* drop our paranoid refcount */
2580   dbus_connection_unref (connection);
2581
2582   return retval;
2583 }
2584
2585 /**
2586  * Sets the mainloop wakeup function for the connection. Thi function is
2587  * responsible for waking up the main loop (if its sleeping) when some some
2588  * change has happened to the connection that the mainloop needs to reconsiders
2589  * (e.g. a message has been queued for writing).
2590  * When using Qt, this typically results in a call to QEventLoop::wakeUp().
2591  * When using GLib, it would call g_main_context_wakeup().
2592  *
2593  *
2594  * @param connection the connection.
2595  * @param wakeup_main_function function to wake up the mainloop
2596  * @param data data to pass wakeup_main_function
2597  * @param free_data_function function to be called to free the data.
2598  */
2599 void
2600 dbus_connection_set_wakeup_main_function (DBusConnection            *connection,
2601                                           DBusWakeupMainFunction     wakeup_main_function,
2602                                           void                      *data,
2603                                           DBusFreeFunction           free_data_function)
2604 {
2605   void *old_data;
2606   DBusFreeFunction old_free_data;
2607
2608   _dbus_return_if_fail (connection != NULL);
2609   
2610   CONNECTION_LOCK (connection);
2611   old_data = connection->wakeup_main_data;
2612   old_free_data = connection->free_wakeup_main_data;
2613
2614   connection->wakeup_main_function = wakeup_main_function;
2615   connection->wakeup_main_data = data;
2616   connection->free_wakeup_main_data = free_data_function;
2617   
2618   CONNECTION_UNLOCK (connection);
2619
2620   /* Callback outside the lock */
2621   if (old_free_data)
2622     (*old_free_data) (old_data);
2623 }
2624
2625 /**
2626  * Set a function to be invoked when the dispatch status changes.
2627  * If the dispatch status is #DBUS_DISPATCH_DATA_REMAINS, then
2628  * dbus_connection_dispatch() needs to be called to process incoming
2629  * messages. However, dbus_connection_dispatch() MUST NOT BE CALLED
2630  * from inside the DBusDispatchStatusFunction. Indeed, almost
2631  * any reentrancy in this function is a bad idea. Instead,
2632  * the DBusDispatchStatusFunction should simply save an indication
2633  * that messages should be dispatched later, when the main loop
2634  * is re-entered.
2635  *
2636  * @param connection the connection
2637  * @param function function to call on dispatch status changes
2638  * @param data data for function
2639  * @param free_data_function free the function data
2640  */
2641 void
2642 dbus_connection_set_dispatch_status_function (DBusConnection             *connection,
2643                                               DBusDispatchStatusFunction  function,
2644                                               void                       *data,
2645                                               DBusFreeFunction            free_data_function)
2646 {
2647   void *old_data;
2648   DBusFreeFunction old_free_data;
2649
2650   _dbus_return_if_fail (connection != NULL);
2651   
2652   CONNECTION_LOCK (connection);
2653   old_data = connection->dispatch_status_data;
2654   old_free_data = connection->free_dispatch_status_data;
2655
2656   connection->dispatch_status_function = function;
2657   connection->dispatch_status_data = data;
2658   connection->free_dispatch_status_data = free_data_function;
2659   
2660   CONNECTION_UNLOCK (connection);
2661
2662   /* Callback outside the lock */
2663   if (old_free_data)
2664     (*old_free_data) (old_data);
2665 }
2666
2667 /**
2668  * Gets the UNIX user ID of the connection if any.
2669  * Returns #TRUE if the uid is filled in.
2670  * Always returns #FALSE on non-UNIX platforms.
2671  * Always returns #FALSE prior to authenticating the
2672  * connection.
2673  *
2674  * @param connection the connection
2675  * @param uid return location for the user ID
2676  * @returns #TRUE if uid is filled in with a valid user ID
2677  */
2678 dbus_bool_t
2679 dbus_connection_get_unix_user (DBusConnection *connection,
2680                                unsigned long  *uid)
2681 {
2682   dbus_bool_t result;
2683
2684   _dbus_return_val_if_fail (connection != NULL, FALSE);
2685   _dbus_return_val_if_fail (uid != NULL, FALSE);
2686   
2687   CONNECTION_LOCK (connection);
2688
2689   if (!_dbus_transport_get_is_authenticated (connection->transport))
2690     result = FALSE;
2691   else
2692     result = _dbus_transport_get_unix_user (connection->transport,
2693                                             uid);
2694   CONNECTION_UNLOCK (connection);
2695
2696   return result;
2697 }
2698
2699 /**
2700  * Sets a predicate function used to determine whether a given user ID
2701  * is allowed to connect. When an incoming connection has
2702  * authenticated with a particular user ID, this function is called;
2703  * if it returns #TRUE, the connection is allowed to proceed,
2704  * otherwise the connection is disconnected.
2705  *
2706  * If the function is set to #NULL (as it is by default), then
2707  * only the same UID as the server process will be allowed to
2708  * connect.
2709  *
2710  * @param connection the connection
2711  * @param function the predicate
2712  * @param data data to pass to the predicate
2713  * @param free_data_function function to free the data
2714  */
2715 void
2716 dbus_connection_set_unix_user_function (DBusConnection             *connection,
2717                                         DBusAllowUnixUserFunction   function,
2718                                         void                       *data,
2719                                         DBusFreeFunction            free_data_function)
2720 {
2721   void *old_data = NULL;
2722   DBusFreeFunction old_free_function = NULL;
2723
2724   _dbus_return_if_fail (connection != NULL);
2725   
2726   CONNECTION_LOCK (connection);
2727   _dbus_transport_set_unix_user_function (connection->transport,
2728                                           function, data, free_data_function,
2729                                           &old_data, &old_free_function);
2730   CONNECTION_UNLOCK (connection);
2731
2732   if (old_free_function != NULL)
2733     (* old_free_function) (old_data);    
2734 }
2735
2736 /**
2737  * Adds a message filter. Filters are handlers that are run on
2738  * all incoming messages, prior to the objects
2739  * registered with dbus_connection_register_object().
2740  * Filters are run in the order that they were added.
2741  * The same handler can be added as a filter more than once, in
2742  * which case it will be run more than once.
2743  * Filters added during a filter callback won't be run on the
2744  * message being processed.
2745  *
2746  * The connection does NOT add a reference to the message handler;
2747  * instead, if the message handler is finalized, the connection simply
2748  * forgets about it. Thus the caller of this function must keep a
2749  * reference to the message handler.
2750  *
2751  * @param connection the connection
2752  * @param handler the handler
2753  * @returns #TRUE on success, #FALSE if not enough memory.
2754  */
2755 dbus_bool_t
2756 dbus_connection_add_filter (DBusConnection      *connection,
2757                             DBusMessageHandler  *handler)
2758 {
2759   _dbus_return_val_if_fail (connection != NULL, FALSE);
2760   _dbus_return_val_if_fail (handler != NULL, FALSE);
2761
2762   CONNECTION_LOCK (connection);
2763   if (!_dbus_message_handler_add_connection (handler, connection))
2764     {
2765       CONNECTION_UNLOCK (connection);
2766       return FALSE;
2767     }
2768
2769   if (!_dbus_list_append (&connection->filter_list,
2770                           handler))
2771     {
2772       _dbus_message_handler_remove_connection (handler, connection);
2773       CONNECTION_UNLOCK (connection);
2774       return FALSE;
2775     }
2776
2777   CONNECTION_UNLOCK (connection);
2778   return TRUE;
2779 }
2780
2781 /**
2782  * Removes a previously-added message filter. It is a programming
2783  * error to call this function for a handler that has not
2784  * been added as a filter. If the given handler was added
2785  * more than once, only one instance of it will be removed
2786  * (the most recently-added instance).
2787  *
2788  * @param connection the connection
2789  * @param handler the handler to remove
2790  *
2791  */
2792 void
2793 dbus_connection_remove_filter (DBusConnection      *connection,
2794                                DBusMessageHandler  *handler)
2795 {
2796   _dbus_return_if_fail (connection != NULL);
2797   _dbus_return_if_fail (handler != NULL);
2798   
2799   CONNECTION_LOCK (connection);
2800   if (!_dbus_list_remove_last (&connection->filter_list, handler))
2801     {
2802       _dbus_warn ("Tried to remove a DBusConnection filter that had not been added\n");
2803       CONNECTION_UNLOCK (connection);
2804       return;
2805     }
2806
2807   _dbus_message_handler_remove_connection (handler, connection);
2808
2809   CONNECTION_UNLOCK (connection);
2810 }
2811
2812 /**
2813  * Registers an object with the connection. This object is assigned an
2814  * object ID, and will be visible under this ID and with the provided
2815  * interfaces to the peer application on the other end of the
2816  * connection. The object instance should be passed in as object_impl;
2817  * the instance can be any datatype, as long as it fits in a void*.
2818  *
2819  * As a side effect of calling this function, the "registered"
2820  * callback in the #DBusObjectVTable will be invoked.
2821  *
2822  * If the object is deleted, be sure to unregister it with
2823  * dbus_connection_unregister_object() or it will continue to get
2824  * messages.
2825  *
2826  * @param connection the connection to register the instance with
2827  * @param interfaces #NULL-terminated array of interface names the instance supports
2828  * @param vtable virtual table of functions for manipulating the instance
2829  * @param object_impl object instance
2830  * @param object_id if non-#NULL, object ID to initialize with the new object's ID
2831  * @returns #FALSE if not enough memory to register the object instance
2832  */
2833 dbus_bool_t
2834 dbus_connection_register_object (DBusConnection          *connection,
2835                                  const char             **interfaces,
2836                                  const DBusObjectVTable  *vtable,
2837                                  void                    *object_impl,
2838                                  DBusObjectID            *object_id)
2839 {
2840   _dbus_return_val_if_fail (connection != NULL, FALSE);
2841   _dbus_return_val_if_fail (vtable != NULL, FALSE);
2842   _dbus_return_val_if_fail (vtable->dbus_internal_pad1 == NULL, FALSE);
2843   _dbus_return_val_if_fail (vtable->dbus_internal_pad2 == NULL, FALSE);
2844   _dbus_return_val_if_fail (vtable->dbus_internal_pad3 == NULL, FALSE);
2845   
2846   CONNECTION_LOCK (connection);
2847
2848   return _dbus_object_registry_add_and_unlock (connection->objects,
2849                                                interfaces,
2850                                                vtable,
2851                                                object_impl,
2852                                                object_id);
2853 }
2854
2855 /**
2856  * Reverses the effects of dbus_connection_register_object(),
2857  * and invokes the "unregistered" callback in the #DBusObjectVTable
2858  * for the given object. The passed-in object ID must be a valid,
2859  * registered object ID or the results are undefined.
2860  *
2861  * @param connection the connection to unregister the object ID from
2862  * @param object_id the object ID to unregister
2863  */
2864 void
2865 dbus_connection_unregister_object (DBusConnection     *connection,
2866                                    const DBusObjectID *object_id)
2867 {
2868   _dbus_return_if_fail (connection != NULL);  
2869
2870   CONNECTION_LOCK (connection);
2871
2872   return _dbus_object_registry_remove_and_unlock (connection->objects,
2873                                                   object_id);
2874 }
2875
2876 static DBusDataSlotAllocator slot_allocator;
2877 _DBUS_DEFINE_GLOBAL_LOCK (connection_slots);
2878
2879 /**
2880  * Allocates an integer ID to be used for storing application-specific
2881  * data on any DBusConnection. The allocated ID may then be used
2882  * with dbus_connection_set_data() and dbus_connection_get_data().
2883  * The passed-in slot must be initialized to -1, and is filled in
2884  * with the slot ID. If the passed-in slot is not -1, it's assumed
2885  * to be already allocated, and its refcount is incremented.
2886  * 
2887  * The allocated slot is global, i.e. all DBusConnection objects will
2888  * have a slot with the given integer ID reserved.
2889  *
2890  * @param slot_p address of a global variable storing the slot
2891  * @returns #FALSE on failure (no memory)
2892  */
2893 dbus_bool_t
2894 dbus_connection_allocate_data_slot (dbus_int32_t *slot_p)
2895 {
2896   return _dbus_data_slot_allocator_alloc (&slot_allocator,
2897                                           _DBUS_LOCK_NAME (connection_slots),
2898                                           slot_p);
2899 }
2900
2901 /**
2902  * Deallocates a global ID for connection data slots.
2903  * dbus_connection_get_data() and dbus_connection_set_data() may no
2904  * longer be used with this slot.  Existing data stored on existing
2905  * DBusConnection objects will be freed when the connection is
2906  * finalized, but may not be retrieved (and may only be replaced if
2907  * someone else reallocates the slot).  When the refcount on the
2908  * passed-in slot reaches 0, it is set to -1.
2909  *
2910  * @param slot_p address storing the slot to deallocate
2911  */
2912 void
2913 dbus_connection_free_data_slot (dbus_int32_t *slot_p)
2914 {
2915   _dbus_return_if_fail (*slot_p >= 0);
2916   
2917   _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
2918 }
2919
2920 /**
2921  * Stores a pointer on a DBusConnection, along
2922  * with an optional function to be used for freeing
2923  * the data when the data is set again, or when
2924  * the connection is finalized. The slot number
2925  * must have been allocated with dbus_connection_allocate_data_slot().
2926  *
2927  * @param connection the connection
2928  * @param slot the slot number
2929  * @param data the data to store
2930  * @param free_data_func finalizer function for the data
2931  * @returns #TRUE if there was enough memory to store the data
2932  */
2933 dbus_bool_t
2934 dbus_connection_set_data (DBusConnection   *connection,
2935                           dbus_int32_t      slot,
2936                           void             *data,
2937                           DBusFreeFunction  free_data_func)
2938 {
2939   DBusFreeFunction old_free_func;
2940   void *old_data;
2941   dbus_bool_t retval;
2942
2943   _dbus_return_val_if_fail (connection != NULL, FALSE);
2944   _dbus_return_val_if_fail (slot >= 0, FALSE);
2945   
2946   CONNECTION_LOCK (connection);
2947
2948   retval = _dbus_data_slot_list_set (&slot_allocator,
2949                                      &connection->slot_list,
2950                                      slot, data, free_data_func,
2951                                      &old_free_func, &old_data);
2952   
2953   CONNECTION_UNLOCK (connection);
2954
2955   if (retval)
2956     {
2957       /* Do the actual free outside the connection lock */
2958       if (old_free_func)
2959         (* old_free_func) (old_data);
2960     }
2961
2962   return retval;
2963 }
2964
2965 /**
2966  * Retrieves data previously set with dbus_connection_set_data().
2967  * The slot must still be allocated (must not have been freed).
2968  *
2969  * @param connection the connection
2970  * @param slot the slot to get data from
2971  * @returns the data, or #NULL if not found
2972  */
2973 void*
2974 dbus_connection_get_data (DBusConnection   *connection,
2975                           dbus_int32_t      slot)
2976 {
2977   void *res;
2978
2979   _dbus_return_val_if_fail (connection != NULL, NULL);
2980   
2981   CONNECTION_LOCK (connection);
2982
2983   res = _dbus_data_slot_list_get (&slot_allocator,
2984                                   &connection->slot_list,
2985                                   slot);
2986   
2987   CONNECTION_UNLOCK (connection);
2988
2989   return res;
2990 }
2991
2992 /**
2993  * This function sets a global flag for whether dbus_connection_new()
2994  * will set SIGPIPE behavior to SIG_IGN.
2995  *
2996  * @param will_modify_sigpipe #TRUE to allow sigpipe to be set to SIG_IGN
2997  */
2998 void
2999 dbus_connection_set_change_sigpipe (dbus_bool_t will_modify_sigpipe)
3000 {  
3001   _dbus_modify_sigpipe = will_modify_sigpipe != FALSE;
3002 }
3003
3004 /**
3005  * Specifies the maximum size message this connection is allowed to
3006  * receive. Larger messages will result in disconnecting the
3007  * connection.
3008  * 
3009  * @param connection a #DBusConnection
3010  * @param size maximum message size the connection can receive, in bytes
3011  */
3012 void
3013 dbus_connection_set_max_message_size (DBusConnection *connection,
3014                                       long            size)
3015 {
3016   _dbus_return_if_fail (connection != NULL);
3017   
3018   CONNECTION_LOCK (connection);
3019   _dbus_transport_set_max_message_size (connection->transport,
3020                                         size);
3021   CONNECTION_UNLOCK (connection);
3022 }
3023
3024 /**
3025  * Gets the value set by dbus_connection_set_max_message_size().
3026  *
3027  * @param connection the connection
3028  * @returns the max size of a single message
3029  */
3030 long
3031 dbus_connection_get_max_message_size (DBusConnection *connection)
3032 {
3033   long res;
3034
3035   _dbus_return_val_if_fail (connection != NULL, 0);
3036   
3037   CONNECTION_LOCK (connection);
3038   res = _dbus_transport_get_max_message_size (connection->transport);
3039   CONNECTION_UNLOCK (connection);
3040   return res;
3041 }
3042
3043 /**
3044  * Sets the maximum total number of bytes that can be used for all messages
3045  * received on this connection. Messages count toward the maximum until
3046  * they are finalized. When the maximum is reached, the connection will
3047  * not read more data until some messages are finalized.
3048  *
3049  * The semantics of the maximum are: if outstanding messages are
3050  * already above the maximum, additional messages will not be read.
3051  * The semantics are not: if the next message would cause us to exceed
3052  * the maximum, we don't read it. The reason is that we don't know the
3053  * size of a message until after we read it.
3054  *
3055  * Thus, the max live messages size can actually be exceeded
3056  * by up to the maximum size of a single message.
3057  * 
3058  * Also, if we read say 1024 bytes off the wire in a single read(),
3059  * and that contains a half-dozen small messages, we may exceed the
3060  * size max by that amount. But this should be inconsequential.
3061  *
3062  * This does imply that we can't call read() with a buffer larger
3063  * than we're willing to exceed this limit by.
3064  *
3065  * @param connection the connection
3066  * @param size the maximum size in bytes of all outstanding messages
3067  */
3068 void
3069 dbus_connection_set_max_received_size (DBusConnection *connection,
3070                                        long            size)
3071 {
3072   _dbus_return_if_fail (connection != NULL);
3073   
3074   CONNECTION_LOCK (connection);
3075   _dbus_transport_set_max_received_size (connection->transport,
3076                                          size);
3077   CONNECTION_UNLOCK (connection);
3078 }
3079
3080 /**
3081  * Gets the value set by dbus_connection_set_max_received_size().
3082  *
3083  * @param connection the connection
3084  * @returns the max size of all live messages
3085  */
3086 long
3087 dbus_connection_get_max_received_size (DBusConnection *connection)
3088 {
3089   long res;
3090
3091   _dbus_return_val_if_fail (connection != NULL, 0);
3092   
3093   CONNECTION_LOCK (connection);
3094   res = _dbus_transport_get_max_received_size (connection->transport);
3095   CONNECTION_UNLOCK (connection);
3096   return res;
3097 }
3098
3099 /**
3100  * Gets the approximate size in bytes of all messages in the outgoing
3101  * message queue. The size is approximate in that you shouldn't use
3102  * it to decide how many bytes to read off the network or anything
3103  * of that nature, as optimizations may choose to tell small white lies
3104  * to avoid performance overhead.
3105  *
3106  * @param connection the connection
3107  * @returns the number of bytes that have been queued up but not sent
3108  */
3109 long
3110 dbus_connection_get_outgoing_size (DBusConnection *connection)
3111 {
3112   long res;
3113
3114   _dbus_return_val_if_fail (connection != NULL, 0);
3115   
3116   CONNECTION_LOCK (connection);
3117   res = _dbus_counter_get_value (connection->outgoing_counter);
3118   CONNECTION_UNLOCK (connection);
3119   return res;
3120 }
3121
3122 /** @} */