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