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