da7a755a4a67ac9753a90e28fa548d8c5de51b2b
[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   int 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;
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_int32_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_int32_t         *client_serial)
1151 {
1152   dbus_int32_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) == -1)
1180     {
1181       serial = _dbus_connection_get_next_client_serial (connection);
1182       _dbus_message_set_serial (message, serial);
1183     }
1184   
1185   if (client_serial)
1186     *client_serial = dbus_message_get_serial (message);
1187   
1188   _dbus_message_lock (message);
1189
1190   if (connection->n_outgoing == 1)
1191     _dbus_transport_messages_pending (connection->transport,
1192                                       connection->n_outgoing);
1193   
1194   _dbus_connection_wakeup_mainloop (connection);
1195
1196   dbus_mutex_unlock (connection->mutex);
1197 }
1198
1199 /**
1200  * Adds a message to the outgoing message queue. Does not block to
1201  * write the message to the network; that happens asynchronously. To
1202  * force the message to be written, call dbus_connection_flush().
1203  * Because this only queues the message, the only reason it can
1204  * fail is lack of memory. Even if the connection is disconnected,
1205  * no error will be returned.
1206  *
1207  * If the function fails due to lack of memory, it returns #FALSE.
1208  * The function will never fail for other reasons; even if the
1209  * connection is disconnected, you can queue an outgoing message,
1210  * though obviously it won't be sent.
1211  * 
1212  * @param connection the connection.
1213  * @param message the message to write.
1214  * @param client_serial return location for client serial.
1215  * @returns #TRUE on success.
1216  */
1217 dbus_bool_t
1218 dbus_connection_send (DBusConnection *connection,
1219                       DBusMessage    *message,
1220                       dbus_int32_t   *client_serial)
1221 {
1222   DBusPreallocatedSend *preallocated;
1223
1224   preallocated = dbus_connection_preallocate_send (connection);
1225   if (preallocated == NULL)
1226     {
1227       return FALSE;
1228     }
1229   else
1230     {
1231       dbus_connection_send_preallocated (connection, preallocated, message, client_serial);
1232       return TRUE;
1233     }
1234 }
1235
1236 static dbus_bool_t
1237 reply_handler_timeout (void *data)
1238 {
1239   DBusConnection *connection;
1240   ReplyHandlerData *reply_handler_data = data;
1241   DBusDispatchStatus status;
1242
1243   connection = reply_handler_data->connection;
1244   
1245   dbus_mutex_lock (connection->mutex);
1246   if (reply_handler_data->timeout_link)
1247     {
1248       _dbus_connection_queue_synthesized_message_link (connection,
1249                                                        reply_handler_data->timeout_link);
1250       reply_handler_data->timeout_link = NULL;
1251     }
1252
1253   _dbus_connection_remove_timeout (connection,
1254                                    reply_handler_data->timeout);
1255   reply_handler_data->timeout_added = FALSE;
1256
1257   status = _dbus_connection_get_dispatch_status_unlocked (connection);
1258   
1259   dbus_mutex_unlock (connection->mutex);
1260
1261   _dbus_connection_update_dispatch_status_locked (connection, status);
1262   
1263   return TRUE;
1264 }
1265
1266 static void
1267 reply_handler_data_free (ReplyHandlerData *data)
1268 {
1269   if (!data)
1270     return;
1271
1272   if (data->timeout_added)
1273     _dbus_connection_remove_timeout_locked (data->connection,
1274                                             data->timeout);
1275
1276   if (data->connection_added)
1277     _dbus_message_handler_remove_connection (data->handler,
1278                                              data->connection);
1279
1280   if (data->timeout_link)
1281     {
1282       dbus_message_unref ((DBusMessage *)data->timeout_link->data);
1283       _dbus_list_free_link (data->timeout_link);
1284     }
1285   
1286   dbus_message_handler_unref (data->handler);
1287   
1288   dbus_free (data);
1289 }
1290
1291 /**
1292  * Queues a message to send, as with dbus_connection_send_message(),
1293  * but also sets up a DBusMessageHandler to receive a reply to the
1294  * message. If no reply is received in the given timeout_milliseconds,
1295  * expires the pending reply and sends the DBusMessageHandler a
1296  * synthetic error reply (generated in-process, not by the remote
1297  * application) indicating that a timeout occurred.
1298  *
1299  * Reply handlers see their replies after message filters see them,
1300  * but before message handlers added with
1301  * dbus_connection_register_handler() see them, regardless of the
1302  * reply message's name. Reply handlers are only handed a single
1303  * message as a reply, after one reply has been seen the handler is
1304  * removed. If a filter filters out the reply before the handler sees
1305  * it, the reply is immediately timed out and a timeout error reply is
1306  * generated. If a filter removes the timeout error reply then the
1307  * reply handler will never be called. Filters should not do this.
1308  * 
1309  * If #NULL is passed for the reply_handler, the timeout reply will
1310  * still be generated and placed into the message queue, but no
1311  * specific message handler will receive the reply.
1312  *
1313  * If -1 is passed for the timeout, a sane default timeout is used. -1
1314  * is typically the best value for the timeout for this reason, unless
1315  * you want a very short or very long timeout.  There is no way to
1316  * avoid a timeout entirely, other than passing INT_MAX for the
1317  * timeout to postpone it indefinitely.
1318  * 
1319  * @param connection the connection
1320  * @param message the message to send
1321  * @param reply_handler message handler expecting the reply, or #NULL
1322  * @param timeout_milliseconds timeout in milliseconds or -1 for default
1323  * @returns #TRUE if the message is successfully queued, #FALSE if no memory.
1324  *
1325  */
1326 dbus_bool_t
1327 dbus_connection_send_with_reply (DBusConnection     *connection,
1328                                  DBusMessage        *message,
1329                                  DBusMessageHandler *reply_handler,
1330                                  int                 timeout_milliseconds)
1331 {
1332   DBusTimeout *timeout;
1333   ReplyHandlerData *data;
1334   DBusMessage *reply;
1335   DBusList *reply_link;
1336   dbus_int32_t serial = -1;
1337   
1338   if (timeout_milliseconds == -1)
1339     timeout_milliseconds = DEFAULT_TIMEOUT_VALUE;
1340
1341   data = dbus_new0 (ReplyHandlerData, 1);
1342
1343   if (!data)
1344     return FALSE;
1345   
1346   timeout = _dbus_timeout_new (timeout_milliseconds, reply_handler_timeout,
1347                                data, NULL);
1348
1349   if (!timeout)
1350     {
1351       reply_handler_data_free (data);
1352       return FALSE;
1353     }
1354
1355   dbus_mutex_lock (connection->mutex);
1356   
1357   /* Add timeout */
1358   if (!_dbus_connection_add_timeout (connection, timeout))
1359     {
1360       reply_handler_data_free (data);
1361       _dbus_timeout_unref (timeout);
1362       dbus_mutex_unlock (connection->mutex);
1363       return FALSE;
1364     }
1365
1366   /* The connection now owns the reference to the timeout. */
1367   _dbus_timeout_unref (timeout);
1368   
1369   data->timeout_added = TRUE;
1370   data->timeout = timeout;
1371   data->connection = connection;
1372   
1373   if (!_dbus_message_handler_add_connection (reply_handler, connection))
1374     {
1375       dbus_mutex_unlock (connection->mutex);
1376       reply_handler_data_free (data);
1377       return FALSE;
1378     }
1379   data->connection_added = TRUE;
1380   
1381   /* Assign a serial to the message */
1382   if (dbus_message_get_serial (message) == -1)
1383     {
1384       serial = _dbus_connection_get_next_client_serial (connection);
1385       _dbus_message_set_serial (message, serial);
1386     }
1387
1388   data->handler = reply_handler;
1389   data->serial = serial;
1390
1391   dbus_message_handler_ref (reply_handler);
1392
1393   reply = dbus_message_new_error_reply (message, DBUS_ERROR_NO_REPLY,
1394                                         "No reply within specified time");
1395   if (!reply)
1396     {
1397       dbus_mutex_unlock (connection->mutex);
1398       reply_handler_data_free (data);
1399       return FALSE;
1400     }
1401
1402   reply_link = _dbus_list_alloc_link (reply);
1403   if (!reply)
1404     {
1405       dbus_mutex_unlock (connection->mutex);
1406       dbus_message_unref (reply);
1407       reply_handler_data_free (data);
1408       return FALSE;
1409     }
1410
1411   data->timeout_link = reply_link;
1412   
1413   /* Insert the serial in the pending replies hash. */
1414   if (!_dbus_hash_table_insert_int (connection->pending_replies, serial, data))
1415     {
1416       dbus_mutex_unlock (connection->mutex);
1417       reply_handler_data_free (data);      
1418       return FALSE;
1419     }
1420
1421   dbus_mutex_unlock (connection->mutex);
1422   
1423   if (!dbus_connection_send (connection, message, NULL))
1424     {
1425       /* This will free the handler data too */
1426       _dbus_hash_table_remove_int (connection->pending_replies, serial);
1427       return FALSE;
1428     }
1429
1430   return TRUE;
1431 }
1432
1433
1434 static DBusMessage*
1435 check_for_reply_unlocked (DBusConnection *connection,
1436                           dbus_int32_t    client_serial)
1437 {
1438   DBusList *link;
1439   
1440   link = _dbus_list_get_first_link (&connection->incoming_messages);
1441
1442   while (link != NULL)
1443     {
1444       DBusMessage *reply = link->data;
1445
1446       if (dbus_message_get_reply_serial (reply) == client_serial)
1447         {
1448           _dbus_list_remove_link (&connection->incoming_messages, link);
1449           connection->n_incoming  -= 1;
1450           dbus_message_ref (reply);
1451           return reply;
1452         }
1453       link = _dbus_list_get_next_link (&connection->incoming_messages, link);
1454     }
1455
1456   return NULL;
1457 }
1458
1459 /**
1460  * Sends a message and blocks a certain time period while waiting for a reply.
1461  * This function does not dispatch any message handlers until the main loop
1462  * has been reached. This function is used to do non-reentrant "method calls."
1463  * If a reply is received, it is returned, and removed from the incoming
1464  * message queue. If it is not received, #NULL is returned and the
1465  * error is set to #DBUS_ERROR_NO_REPLY. If something else goes
1466  * wrong, result is set to whatever is appropriate, such as
1467  * #DBUS_ERROR_NO_MEMORY or #DBUS_ERROR_DISCONNECTED.
1468  *
1469  * @todo could use performance improvements (it keeps scanning
1470  * the whole message queue for example) and has thread issues,
1471  * see comments in source
1472  *
1473  * @param connection the connection
1474  * @param message the message to send
1475  * @param timeout_milliseconds timeout in milliseconds or -1 for default
1476  * @param error return location for error message
1477  * @returns the message that is the reply or #NULL with an error code if the
1478  * function fails.
1479  */
1480 DBusMessage *
1481 dbus_connection_send_with_reply_and_block (DBusConnection     *connection,
1482                                            DBusMessage        *message,
1483                                            int                 timeout_milliseconds,
1484                                            DBusError          *error)
1485 {
1486   dbus_int32_t client_serial;
1487   long start_tv_sec, start_tv_usec;
1488   long end_tv_sec, end_tv_usec;
1489   long tv_sec, tv_usec;
1490   DBusDispatchStatus status;
1491
1492   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1493   
1494   if (timeout_milliseconds == -1)
1495     timeout_milliseconds = DEFAULT_TIMEOUT_VALUE;
1496
1497   /* it would probably seem logical to pass in _DBUS_INT_MAX
1498    * for infinite timeout, but then math below would get
1499    * all overflow-prone, so smack that down.
1500    */
1501   if (timeout_milliseconds > _DBUS_ONE_HOUR_IN_MILLISECONDS * 6)
1502     timeout_milliseconds = _DBUS_ONE_HOUR_IN_MILLISECONDS * 6;
1503   
1504   if (!dbus_connection_send (connection, message, &client_serial))
1505     {
1506       _DBUS_SET_OOM (error);
1507       return NULL;
1508     }
1509
1510   message = NULL;
1511   
1512   /* Flush message queue */
1513   dbus_connection_flush (connection);
1514
1515   dbus_mutex_lock (connection->mutex);
1516
1517   _dbus_get_current_time (&start_tv_sec, &start_tv_usec);
1518   end_tv_sec = start_tv_sec + timeout_milliseconds / 1000;
1519   end_tv_usec = start_tv_usec + (timeout_milliseconds % 1000) * 1000;
1520   end_tv_sec += end_tv_usec / _DBUS_USEC_PER_SECOND;
1521   end_tv_usec = end_tv_usec % _DBUS_USEC_PER_SECOND;
1522
1523   _dbus_verbose ("dbus_connection_send_with_reply_and_block(): will block %d milliseconds for reply serial %d from %ld sec %ld usec to %ld sec %ld usec\n",
1524                  timeout_milliseconds,
1525                  client_serial,
1526                  start_tv_sec, start_tv_usec,
1527                  end_tv_sec, end_tv_usec);
1528   
1529   /* Now we wait... */
1530   /* THREAD TODO: This is busted. What if a dispatch() or pop_message
1531    * gets the message before we do?
1532    */
1533   /* always block at least once as we know we don't have the reply yet */
1534   _dbus_connection_do_iteration (connection,
1535                                  DBUS_ITERATION_DO_READING |
1536                                  DBUS_ITERATION_BLOCK,
1537                                  timeout_milliseconds);
1538
1539  recheck_status:
1540
1541   /* queue messages and get status */
1542   status = _dbus_connection_get_dispatch_status_unlocked (connection);
1543
1544   if (status == DBUS_DISPATCH_DATA_REMAINS)
1545     {
1546       DBusMessage *reply;
1547       
1548       reply = check_for_reply_unlocked (connection, client_serial);
1549       if (reply != NULL)
1550         {          
1551           status = _dbus_connection_get_dispatch_status_unlocked (connection);
1552           
1553           dbus_mutex_unlock (connection->mutex);
1554
1555           _dbus_verbose ("dbus_connection_send_with_reply_and_block(): got reply %s\n",
1556                          dbus_message_get_name (reply));
1557
1558           _dbus_connection_update_dispatch_status_locked (connection, status);
1559           
1560           return reply;
1561         }
1562     }
1563   
1564   _dbus_get_current_time (&tv_sec, &tv_usec);
1565   
1566   if (tv_sec < start_tv_sec)
1567     _dbus_verbose ("dbus_connection_send_with_reply_and_block(): clock set backward\n");
1568   else if (connection->disconnect_message_link == NULL)
1569     _dbus_verbose ("dbus_connection_send_with_reply_and_block(): disconnected\n");
1570   else if (tv_sec < end_tv_sec ||
1571            (tv_sec == end_tv_sec && tv_usec < end_tv_usec))
1572     {
1573       timeout_milliseconds = (end_tv_sec - tv_sec) * 1000 +
1574         (end_tv_usec - tv_usec) / 1000;
1575       _dbus_verbose ("dbus_connection_send_with_reply_and_block(): %d milliseconds remain\n", timeout_milliseconds);
1576       _dbus_assert (timeout_milliseconds >= 0);
1577       
1578       if (status == DBUS_DISPATCH_NEED_MEMORY)
1579         {
1580           /* Try sleeping a bit, as we aren't sure we need to block for reading,
1581            * we may already have a reply in the buffer and just can't process
1582            * it.
1583            */
1584           _dbus_verbose ("dbus_connection_send_with_reply_and_block() waiting for more memory\n");
1585           
1586           if (timeout_milliseconds < 100)
1587             ; /* just busy loop */
1588           else if (timeout_milliseconds <= 1000)
1589             _dbus_sleep_milliseconds (timeout_milliseconds / 3);
1590           else
1591             _dbus_sleep_milliseconds (1000);
1592         }
1593       else
1594         {          
1595           /* block again, we don't have the reply buffered yet. */
1596           _dbus_connection_do_iteration (connection,
1597                                          DBUS_ITERATION_DO_READING |
1598                                          DBUS_ITERATION_BLOCK,
1599                                          timeout_milliseconds);
1600         }
1601
1602       goto recheck_status;
1603     }
1604
1605   _dbus_verbose ("dbus_connection_send_with_reply_and_block(): Waited %ld milliseconds and got no reply\n",
1606                  (tv_sec - start_tv_sec) * 1000 + (tv_usec - start_tv_usec) / 1000);
1607   
1608   if (dbus_connection_get_is_connected (connection))
1609     dbus_set_error (error, DBUS_ERROR_NO_REPLY, "Message did not receive a reply");
1610   else
1611     dbus_set_error (error, DBUS_ERROR_DISCONNECTED, "Disconnected prior to receiving a reply");
1612   
1613   dbus_mutex_unlock (connection->mutex);
1614
1615   _dbus_connection_update_dispatch_status_locked (connection, status);
1616
1617   return NULL;
1618 }
1619
1620 /**
1621  * Blocks until the outgoing message queue is empty.
1622  *
1623  * @param connection the connection.
1624  */
1625 void
1626 dbus_connection_flush (DBusConnection *connection)
1627 {
1628   /* We have to specify DBUS_ITERATION_DO_READING here because
1629    * otherwise we could have two apps deadlock if they are both doing
1630    * a flush(), and the kernel buffers fill up. This could change the
1631    * dispatch status.
1632    */
1633   DBusDispatchStatus status;
1634   
1635   dbus_mutex_lock (connection->mutex);
1636   while (connection->n_outgoing > 0 &&
1637          dbus_connection_get_is_connected (connection))
1638     _dbus_connection_do_iteration (connection,
1639                                    DBUS_ITERATION_DO_READING |
1640                                    DBUS_ITERATION_DO_WRITING |
1641                                    DBUS_ITERATION_BLOCK,
1642                                    -1);
1643
1644   status = _dbus_connection_get_dispatch_status_unlocked (connection);
1645   
1646   dbus_mutex_unlock (connection->mutex);
1647
1648   _dbus_connection_update_dispatch_status_locked (connection, status);
1649 }
1650
1651 /* Call with mutex held. Will drop it while waiting and re-acquire
1652  * before returning
1653  */
1654 static void
1655 _dbus_connection_wait_for_borrowed (DBusConnection *connection)
1656 {
1657   _dbus_assert (connection->message_borrowed != NULL);
1658
1659   while (connection->message_borrowed != NULL)
1660     dbus_condvar_wait (connection->message_returned_cond, connection->mutex);
1661 }
1662
1663 /**
1664  * Returns the first-received message from the incoming message queue,
1665  * leaving it in the queue. If the queue is empty, returns #NULL.
1666  * 
1667  * The caller does not own a reference to the returned message, and must
1668  * either return it using dbus_connection_return_message or keep it after
1669  * calling dbus_connection_steal_borrowed_message. No one can get at the
1670  * message while its borrowed, so return it as quickly as possible and
1671  * don't keep a reference to it after returning it. If you need to keep
1672  * the message, make a copy of it.
1673  *
1674  * @param connection the connection.
1675  * @returns next message in the incoming queue.
1676  */
1677 DBusMessage*
1678 dbus_connection_borrow_message  (DBusConnection *connection)
1679 {
1680   DBusMessage *message;
1681   DBusDispatchStatus status;
1682   
1683   /* this is called for the side effect that it queues
1684    * up any messages from the transport
1685    */
1686   status = dbus_connection_get_dispatch_status (connection);
1687   if (status != DBUS_DISPATCH_DATA_REMAINS)
1688     return NULL;
1689   
1690   dbus_mutex_lock (connection->mutex);
1691
1692   if (connection->message_borrowed != NULL)
1693     _dbus_connection_wait_for_borrowed (connection);
1694   
1695   message = _dbus_list_get_first (&connection->incoming_messages);
1696
1697   if (message) 
1698     connection->message_borrowed = message;
1699   
1700   dbus_mutex_unlock (connection->mutex);
1701   return message;
1702 }
1703
1704 /**
1705  * @todo docs
1706  */
1707 void
1708 dbus_connection_return_message (DBusConnection *connection,
1709                                 DBusMessage    *message)
1710 {
1711   dbus_mutex_lock (connection->mutex);
1712   
1713   _dbus_assert (message == connection->message_borrowed);
1714   
1715   connection->message_borrowed = NULL;
1716   dbus_condvar_wake_all (connection->message_returned_cond);
1717   
1718   dbus_mutex_unlock (connection->mutex);
1719 }
1720
1721 /**
1722  * @todo docs
1723  */
1724 void
1725 dbus_connection_steal_borrowed_message (DBusConnection *connection,
1726                                         DBusMessage    *message)
1727 {
1728   DBusMessage *pop_message;
1729   
1730   dbus_mutex_lock (connection->mutex);
1731  
1732   _dbus_assert (message == connection->message_borrowed);
1733
1734   pop_message = _dbus_list_pop_first (&connection->incoming_messages);
1735   _dbus_assert (message == pop_message);
1736   
1737   connection->n_incoming -= 1;
1738  
1739   _dbus_verbose ("Incoming message %p stolen from queue, %d incoming\n",
1740                  message, connection->n_incoming);
1741  
1742   connection->message_borrowed = NULL;
1743   dbus_condvar_wake_all (connection->message_returned_cond);
1744   
1745   dbus_mutex_unlock (connection->mutex);
1746 }
1747
1748 /* See dbus_connection_pop_message, but requires the caller to own
1749  * the lock before calling. May drop the lock while running.
1750  */
1751 static DBusList*
1752 _dbus_connection_pop_message_link_unlocked (DBusConnection *connection)
1753 {
1754   if (connection->message_borrowed != NULL)
1755     _dbus_connection_wait_for_borrowed (connection);
1756   
1757   if (connection->n_incoming > 0)
1758     {
1759       DBusList *link;
1760
1761       link = _dbus_list_pop_first_link (&connection->incoming_messages);
1762       connection->n_incoming -= 1;
1763
1764       _dbus_verbose ("Message %p (%s) removed from incoming queue %p, %d incoming\n",
1765                      link->data, dbus_message_get_name (link->data),
1766                      connection, connection->n_incoming);
1767
1768       return link;
1769     }
1770   else
1771     return NULL;
1772 }
1773
1774 /* See dbus_connection_pop_message, but requires the caller to own
1775  * the lock before calling. May drop the lock while running.
1776  */
1777 static DBusMessage*
1778 _dbus_connection_pop_message_unlocked (DBusConnection *connection)
1779 {
1780   DBusList *link;
1781   
1782   link = _dbus_connection_pop_message_link_unlocked (connection);
1783
1784   if (link != NULL)
1785     {
1786       DBusMessage *message;
1787       
1788       message = link->data;
1789       
1790       _dbus_list_free_link (link);
1791       
1792       return message;
1793     }
1794   else
1795     return NULL;
1796 }
1797
1798
1799 /**
1800  * Returns the first-received message from the incoming message queue,
1801  * removing it from the queue. The caller owns a reference to the
1802  * returned message. If the queue is empty, returns #NULL.
1803  *
1804  * @param connection the connection.
1805  * @returns next message in the incoming queue.
1806  */
1807 DBusMessage*
1808 dbus_connection_pop_message (DBusConnection *connection)
1809 {
1810   DBusMessage *message;
1811   DBusDispatchStatus status;
1812
1813   /* this is called for the side effect that it queues
1814    * up any messages from the transport
1815    */
1816   status = dbus_connection_get_dispatch_status (connection);
1817   if (status != DBUS_DISPATCH_DATA_REMAINS)
1818     return NULL;
1819   
1820   dbus_mutex_lock (connection->mutex);
1821
1822   message = _dbus_connection_pop_message_unlocked (connection);
1823
1824   _dbus_verbose ("Returning popped message %p\n", message);    
1825   
1826   dbus_mutex_unlock (connection->mutex);
1827   
1828   return message;
1829 }
1830
1831 /**
1832  * Acquire the dispatcher. This must be done before dispatching
1833  * messages in order to guarantee the right order of
1834  * message delivery. May sleep and drop the connection mutex
1835  * while waiting for the dispatcher.
1836  *
1837  * @param connection the connection.
1838  */
1839 static void
1840 _dbus_connection_acquire_dispatch (DBusConnection *connection)
1841 {
1842   if (connection->dispatch_acquired)
1843     dbus_condvar_wait (connection->dispatch_cond, connection->mutex);
1844   _dbus_assert (!connection->dispatch_acquired);
1845
1846   connection->dispatch_acquired = TRUE;
1847 }
1848
1849 /**
1850  * Release the dispatcher when you're done with it. Only call
1851  * after you've acquired the dispatcher. Wakes up at most one
1852  * thread currently waiting to acquire the dispatcher.
1853  *
1854  * @param connection the connection.
1855  */
1856 static void
1857 _dbus_connection_release_dispatch (DBusConnection *connection)
1858 {
1859   _dbus_assert (connection->dispatch_acquired);
1860
1861   connection->dispatch_acquired = FALSE;
1862   dbus_condvar_wake_one (connection->dispatch_cond);
1863 }
1864
1865 static void
1866 _dbus_connection_failed_pop (DBusConnection *connection,
1867                              DBusList *message_link)
1868 {
1869   _dbus_list_prepend_link (&connection->incoming_messages,
1870                            message_link);
1871   connection->n_incoming += 1;
1872 }
1873
1874 static DBusDispatchStatus
1875 _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection)
1876 {
1877   if (connection->n_incoming > 0)
1878     return DBUS_DISPATCH_DATA_REMAINS;
1879   else if (!_dbus_transport_queue_messages (connection->transport))
1880     return DBUS_DISPATCH_NEED_MEMORY;
1881   else
1882     {
1883       DBusDispatchStatus status;
1884       
1885       status = _dbus_transport_get_dispatch_status (connection->transport);
1886
1887       if (status != DBUS_DISPATCH_COMPLETE)
1888         return status;
1889       else if (connection->n_incoming > 0)
1890         return DBUS_DISPATCH_DATA_REMAINS;
1891       else
1892         return DBUS_DISPATCH_COMPLETE;
1893     }
1894 }
1895
1896 static void
1897 _dbus_connection_update_dispatch_status_locked (DBusConnection    *connection,
1898                                                 DBusDispatchStatus new_status)
1899 {
1900   dbus_bool_t changed;
1901   DBusDispatchStatusFunction function;
1902   void *data;
1903   
1904   dbus_mutex_lock (connection->mutex);
1905   _dbus_connection_ref_unlocked (connection);
1906
1907   changed = new_status != connection->last_dispatch_status;
1908
1909   connection->last_dispatch_status = new_status;
1910
1911   function = connection->dispatch_status_function;
1912   data = connection->dispatch_status_data;
1913   
1914   dbus_mutex_unlock (connection->mutex);
1915   
1916   if (changed && function)
1917     {
1918       _dbus_verbose ("Notifying of change to dispatch status of %p now %d (%s)\n",
1919                      connection, new_status,
1920                      new_status == DBUS_DISPATCH_COMPLETE ? "complete" :
1921                      new_status == DBUS_DISPATCH_DATA_REMAINS ? "data remains" :
1922                      new_status == DBUS_DISPATCH_NEED_MEMORY ? "need memory" :
1923                      "???");
1924       (* function) (connection, new_status, data);      
1925     }
1926   
1927   dbus_connection_unref (connection);
1928 }
1929
1930 /**
1931  * Gets the current state (what we would currently return
1932  * from dbus_connection_dispatch()) but doesn't actually
1933  * dispatch any messages.
1934  * 
1935  * @param connection the connection.
1936  * @returns current dispatch status
1937  */
1938 DBusDispatchStatus
1939 dbus_connection_get_dispatch_status (DBusConnection *connection)
1940 {
1941   DBusDispatchStatus status;
1942   
1943   dbus_mutex_lock (connection->mutex);
1944
1945   status = _dbus_connection_get_dispatch_status_unlocked (connection);
1946   
1947   dbus_mutex_unlock (connection->mutex);
1948
1949   return status;
1950 }
1951
1952 /**
1953  * Processes data buffered while handling watches, queueing zero or
1954  * more incoming messages. Then pops the first-received message from
1955  * the current incoming message queue, runs any handlers for it, and
1956  * unrefs the message. Returns a status indicating whether messages/data
1957  * remain, more memory is needed, or all data has been processed.
1958  *
1959  * @param connection the connection
1960  * @returns dispatch status
1961  */
1962 DBusDispatchStatus
1963 dbus_connection_dispatch (DBusConnection *connection)
1964 {
1965   DBusMessageHandler *handler;
1966   DBusMessage *message;
1967   DBusList *link, *filter_list_copy, *message_link;
1968   DBusHandlerResult result;
1969   ReplyHandlerData *reply_handler_data;
1970   const char *name;
1971   dbus_int32_t reply_serial;
1972   DBusDispatchStatus status;
1973   
1974   status = dbus_connection_get_dispatch_status (connection);
1975   if (status != DBUS_DISPATCH_DATA_REMAINS)
1976     {
1977       _dbus_connection_update_dispatch_status_locked (connection, status);
1978       return status;
1979     }
1980
1981   dbus_mutex_lock (connection->mutex);
1982   
1983   /* We need to ref the connection since the callback could potentially
1984    * drop the last ref to it
1985    */
1986   _dbus_connection_ref_unlocked (connection);
1987
1988   _dbus_connection_acquire_dispatch (connection);
1989   
1990   /* This call may drop the lock during the execution (if waiting for
1991    * borrowed messages to be returned) but the order of message
1992    * dispatch if several threads call dispatch() is still
1993    * protected by the lock, since only one will get the lock, and that
1994    * one will finish the message dispatching
1995    */
1996   message_link = _dbus_connection_pop_message_link_unlocked (connection);
1997   if (message_link == NULL)
1998     {
1999       /* another thread dispatched our stuff */
2000
2001       _dbus_connection_release_dispatch (connection);
2002       dbus_mutex_unlock (connection->mutex);
2003
2004       status = dbus_connection_get_dispatch_status (connection);
2005
2006       _dbus_connection_update_dispatch_status_locked (connection, status);
2007       
2008       dbus_connection_unref (connection);
2009       
2010       return status;
2011     }
2012
2013   message = message_link->data;
2014   
2015   result = DBUS_HANDLER_RESULT_ALLOW_MORE_HANDLERS;
2016
2017   reply_serial = dbus_message_get_reply_serial (message);
2018   reply_handler_data = _dbus_hash_table_lookup_int (connection->pending_replies,
2019                                                     reply_serial);
2020   
2021   if (!_dbus_list_copy (&connection->filter_list, &filter_list_copy))
2022     {
2023       _dbus_connection_release_dispatch (connection);
2024       dbus_mutex_unlock (connection->mutex);
2025       _dbus_connection_failed_pop (connection, message_link);
2026
2027       _dbus_connection_update_dispatch_status_locked (connection, DBUS_DISPATCH_NEED_MEMORY);
2028
2029       dbus_connection_unref (connection);
2030       
2031       return DBUS_DISPATCH_NEED_MEMORY;
2032     }
2033   
2034   _dbus_list_foreach (&filter_list_copy,
2035                       (DBusForeachFunction)dbus_message_handler_ref,
2036                       NULL);
2037
2038   /* We're still protected from dispatch() reentrancy here
2039    * since we acquired the dispatcher
2040    */
2041   dbus_mutex_unlock (connection->mutex);
2042   
2043   link = _dbus_list_get_first_link (&filter_list_copy);
2044   while (link != NULL)
2045     {
2046       DBusMessageHandler *handler = link->data;
2047       DBusList *next = _dbus_list_get_next_link (&filter_list_copy, link);
2048
2049       _dbus_verbose ("  running filter on message %p\n", message);
2050       result = _dbus_message_handler_handle_message (handler, connection,
2051                                                      message);
2052
2053       if (result == DBUS_HANDLER_RESULT_REMOVE_MESSAGE)
2054         break;
2055
2056       link = next;
2057     }
2058
2059   _dbus_list_foreach (&filter_list_copy,
2060                       (DBusForeachFunction)dbus_message_handler_unref,
2061                       NULL);
2062   _dbus_list_clear (&filter_list_copy);
2063   
2064   dbus_mutex_lock (connection->mutex);
2065
2066   /* Did a reply we were waiting on get filtered? */
2067   if (reply_handler_data && result == DBUS_HANDLER_RESULT_REMOVE_MESSAGE)
2068     {
2069       /* Queue the timeout immediately! */
2070       if (reply_handler_data->timeout_link)
2071         {
2072           _dbus_connection_queue_synthesized_message_link (connection,
2073                                                            reply_handler_data->timeout_link);
2074           reply_handler_data->timeout_link = NULL;
2075         }
2076       else
2077         {
2078           /* We already queued the timeout? Then it was filtered! */
2079           _dbus_warn ("The timeout error with reply serial %d was filtered, so the reply handler will never be called.\n", reply_serial);
2080         }
2081     }
2082   
2083   if (result == DBUS_HANDLER_RESULT_REMOVE_MESSAGE)
2084     goto out;
2085
2086   if (reply_handler_data)
2087     {
2088       dbus_mutex_unlock (connection->mutex);
2089
2090       _dbus_verbose ("  running reply handler on message %p\n", message);
2091       
2092       result = _dbus_message_handler_handle_message (reply_handler_data->handler,
2093                                                      connection, message);
2094       reply_handler_data_free (reply_handler_data);
2095       dbus_mutex_lock (connection->mutex);
2096       goto out;
2097     }
2098   
2099   name = dbus_message_get_name (message);
2100   if (name != NULL)
2101     {
2102       handler = _dbus_hash_table_lookup_string (connection->handler_table,
2103                                                 name);
2104       if (handler != NULL)
2105         {
2106           /* We're still protected from dispatch() reentrancy here
2107            * since we acquired the dispatcher
2108            */
2109           dbus_mutex_unlock (connection->mutex);
2110
2111           _dbus_verbose ("  running app handler on message %p (%s)\n",
2112                          message, dbus_message_get_name (message));
2113           
2114           result = _dbus_message_handler_handle_message (handler, connection,
2115                                                          message);
2116           dbus_mutex_lock (connection->mutex);
2117           if (result == DBUS_HANDLER_RESULT_REMOVE_MESSAGE)
2118             goto out;
2119         }
2120     }
2121
2122   _dbus_verbose ("  done dispatching %p (%s) on connection %p\n", message,
2123                  dbus_message_get_name (message), connection);
2124   
2125  out:
2126   _dbus_connection_release_dispatch (connection);
2127   dbus_mutex_unlock (connection->mutex);
2128   _dbus_list_free_link (message_link);
2129   dbus_message_unref (message); /* don't want the message to count in max message limits
2130                                  * in computing dispatch status
2131                                  */
2132   
2133   status = dbus_connection_get_dispatch_status (connection);
2134
2135   _dbus_connection_update_dispatch_status_locked (connection, status);
2136   
2137   dbus_connection_unref (connection);
2138   
2139   return status;
2140 }
2141
2142 /**
2143  * Sets the watch functions for the connection. These functions are
2144  * responsible for making the application's main loop aware of file
2145  * descriptors that need to be monitored for events, using select() or
2146  * poll(). When using Qt, typically the DBusAddWatchFunction would
2147  * create a QSocketNotifier. When using GLib, the DBusAddWatchFunction
2148  * could call g_io_add_watch(), or could be used as part of a more
2149  * elaborate GSource. Note that when a watch is added, it may
2150  * not be enabled.
2151  *
2152  * The DBusWatchToggledFunction notifies the application that the
2153  * watch has been enabled or disabled. Call dbus_watch_get_enabled()
2154  * to check this. A disabled watch should have no effect, and enabled
2155  * watch should be added to the main loop. This feature is used
2156  * instead of simply adding/removing the watch because
2157  * enabling/disabling can be done without memory allocation.  The
2158  * toggled function may be NULL if a main loop re-queries
2159  * dbus_watch_get_enabled() every time anyway.
2160  * 
2161  * The DBusWatch can be queried for the file descriptor to watch using
2162  * dbus_watch_get_fd(), and for the events to watch for using
2163  * dbus_watch_get_flags(). The flags returned by
2164  * dbus_watch_get_flags() will only contain DBUS_WATCH_READABLE and
2165  * DBUS_WATCH_WRITABLE, never DBUS_WATCH_HANGUP or DBUS_WATCH_ERROR;
2166  * all watches implicitly include a watch for hangups, errors, and
2167  * other exceptional conditions.
2168  *
2169  * Once a file descriptor becomes readable or writable, or an exception
2170  * occurs, dbus_connection_handle_watch() should be called to
2171  * notify the connection of the file descriptor's condition.
2172  *
2173  * dbus_connection_handle_watch() cannot be called during the
2174  * DBusAddWatchFunction, as the connection will not be ready to handle
2175  * that watch yet.
2176  * 
2177  * It is not allowed to reference a DBusWatch after it has been passed
2178  * to remove_function.
2179  *
2180  * If #FALSE is returned due to lack of memory, the failure may be due
2181  * to a #FALSE return from the new add_function. If so, the
2182  * add_function may have been called successfully one or more times,
2183  * but the remove_function will also have been called to remove any
2184  * successful adds. i.e. if #FALSE is returned the net result
2185  * should be that dbus_connection_set_watch_functions() has no effect,
2186  * but the add_function and remove_function may have been called.
2187  *
2188  * @todo We need to drop the lock when we call the
2189  * add/remove/toggled functions which can be a side effect
2190  * of setting the watch functions.
2191  * 
2192  * @param connection the connection.
2193  * @param add_function function to begin monitoring a new descriptor.
2194  * @param remove_function function to stop monitoring a descriptor.
2195  * @param toggled_function function to notify of enable/disable
2196  * @param data data to pass to add_function and remove_function.
2197  * @param free_data_function function to be called to free the data.
2198  * @returns #FALSE on failure (no memory)
2199  */
2200 dbus_bool_t
2201 dbus_connection_set_watch_functions (DBusConnection              *connection,
2202                                      DBusAddWatchFunction         add_function,
2203                                      DBusRemoveWatchFunction      remove_function,
2204                                      DBusWatchToggledFunction     toggled_function,
2205                                      void                        *data,
2206                                      DBusFreeFunction             free_data_function)
2207 {
2208   dbus_bool_t retval;
2209   
2210   dbus_mutex_lock (connection->mutex);
2211   /* ref connection for slightly better reentrancy */
2212   _dbus_connection_ref_unlocked (connection);
2213
2214   /* FIXME this can call back into user code, and we need to drop the
2215    * connection lock when it does.
2216    */
2217   retval = _dbus_watch_list_set_functions (connection->watches,
2218                                            add_function, remove_function,
2219                                            toggled_function,
2220                                            data, free_data_function);
2221   
2222   dbus_mutex_unlock (connection->mutex);
2223   /* drop our paranoid refcount */
2224   dbus_connection_unref (connection);
2225
2226   return retval;
2227 }
2228
2229 /**
2230  * Sets the timeout functions for the connection. These functions are
2231  * responsible for making the application's main loop aware of timeouts.
2232  * When using Qt, typically the DBusAddTimeoutFunction would create a
2233  * QTimer. When using GLib, the DBusAddTimeoutFunction would call
2234  * g_timeout_add.
2235  * 
2236  * The DBusTimeoutToggledFunction notifies the application that the
2237  * timeout has been enabled or disabled. Call
2238  * dbus_timeout_get_enabled() to check this. A disabled timeout should
2239  * have no effect, and enabled timeout should be added to the main
2240  * loop. This feature is used instead of simply adding/removing the
2241  * timeout because enabling/disabling can be done without memory
2242  * allocation. With Qt, QTimer::start() and QTimer::stop() can be used
2243  * to enable and disable. The toggled function may be NULL if a main
2244  * loop re-queries dbus_timeout_get_enabled() every time anyway.
2245  *
2246  * The DBusTimeout can be queried for the timer interval using
2247  * dbus_timeout_get_interval(). dbus_timeout_handle() should
2248  * be called repeatedly, each time the interval elapses, starting
2249  * after it has elapsed once. The timeout stops firing when
2250  * it is removed with the given remove_function.
2251  *
2252  * @param connection the connection.
2253  * @param add_function function to add a timeout.
2254  * @param remove_function function to remove a timeout.
2255  * @param toggled_function function to notify of enable/disable
2256  * @param data data to pass to add_function and remove_function.
2257  * @param free_data_function function to be called to free the data.
2258  * @returns #FALSE on failure (no memory)
2259  */
2260 dbus_bool_t
2261 dbus_connection_set_timeout_functions   (DBusConnection            *connection,
2262                                          DBusAddTimeoutFunction     add_function,
2263                                          DBusRemoveTimeoutFunction  remove_function,
2264                                          DBusTimeoutToggledFunction toggled_function,
2265                                          void                      *data,
2266                                          DBusFreeFunction           free_data_function)
2267 {
2268   dbus_bool_t retval;
2269   
2270   dbus_mutex_lock (connection->mutex);
2271   /* ref connection for slightly better reentrancy */
2272   _dbus_connection_ref_unlocked (connection);
2273   
2274   retval = _dbus_timeout_list_set_functions (connection->timeouts,
2275                                              add_function, remove_function,
2276                                              toggled_function,
2277                                              data, free_data_function);
2278   
2279   dbus_mutex_unlock (connection->mutex);
2280   /* drop our paranoid refcount */
2281   dbus_connection_unref (connection);
2282
2283   return retval;
2284 }
2285
2286 /**
2287  * Sets the mainloop wakeup function for the connection. Thi function is
2288  * responsible for waking up the main loop (if its sleeping) when some some
2289  * change has happened to the connection that the mainloop needs to reconsiders
2290  * (e.g. a message has been queued for writing).
2291  * When using Qt, this typically results in a call to QEventLoop::wakeUp().
2292  * When using GLib, it would call g_main_context_wakeup().
2293  *
2294  *
2295  * @param connection the connection.
2296  * @param wakeup_main_function function to wake up the mainloop
2297  * @param data data to pass wakeup_main_function
2298  * @param free_data_function function to be called to free the data.
2299  */
2300 void
2301 dbus_connection_set_wakeup_main_function (DBusConnection            *connection,
2302                                           DBusWakeupMainFunction     wakeup_main_function,
2303                                           void                      *data,
2304                                           DBusFreeFunction           free_data_function)
2305 {
2306   void *old_data;
2307   DBusFreeFunction old_free_data;
2308   
2309   dbus_mutex_lock (connection->mutex);
2310   old_data = connection->wakeup_main_data;
2311   old_free_data = connection->free_wakeup_main_data;
2312
2313   connection->wakeup_main_function = wakeup_main_function;
2314   connection->wakeup_main_data = data;
2315   connection->free_wakeup_main_data = free_data_function;
2316   
2317   dbus_mutex_unlock (connection->mutex);
2318
2319   /* Callback outside the lock */
2320   if (old_free_data)
2321     (*old_free_data) (old_data);
2322 }
2323
2324 /**
2325  * Set a function to be invoked when the dispatch status changes.
2326  * If the dispatch status is #DBUS_DISPATCH_DATA_REMAINS, then
2327  * dbus_connection_dispatch() needs to be called to process incoming
2328  * messages. However, dbus_connection_dispatch() MUST NOT BE CALLED
2329  * from inside the DBusDispatchStatusFunction. Indeed, almost
2330  * any reentrancy in this function is a bad idea. Instead,
2331  * the DBusDispatchStatusFunction should simply save an indication
2332  * that messages should be dispatched later, when the main loop
2333  * is re-entered.
2334  *
2335  * @param connection the connection
2336  * @param function function to call on dispatch status changes
2337  * @param data data for function
2338  * @param free_data_function free the function data
2339  */
2340 void
2341 dbus_connection_set_dispatch_status_function (DBusConnection             *connection,
2342                                               DBusDispatchStatusFunction  function,
2343                                               void                       *data,
2344                                               DBusFreeFunction            free_data_function)
2345 {
2346   void *old_data;
2347   DBusFreeFunction old_free_data;
2348   
2349   dbus_mutex_lock (connection->mutex);
2350   old_data = connection->dispatch_status_data;
2351   old_free_data = connection->free_dispatch_status_data;
2352
2353   connection->dispatch_status_function = function;
2354   connection->dispatch_status_data = data;
2355   connection->free_dispatch_status_data = free_data_function;
2356   
2357   dbus_mutex_unlock (connection->mutex);
2358
2359   /* Callback outside the lock */
2360   if (old_free_data)
2361     (*old_free_data) (old_data);
2362 }
2363
2364 /**
2365  * Called to notify the connection when a previously-added watch
2366  * is ready for reading or writing, or has an exception such
2367  * as a hangup.
2368  *
2369  * If this function returns #FALSE, then the file descriptor may still
2370  * be ready for reading or writing, but more memory is needed in order
2371  * to do the reading or writing. If you ignore the #FALSE return, your
2372  * application may spin in a busy loop on the file descriptor until
2373  * memory becomes available, but nothing more catastrophic should
2374  * happen.
2375  *
2376  * @param connection the connection.
2377  * @param watch the watch.
2378  * @param condition the current condition of the file descriptors being watched.
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 (DBusConnection              *connection,
2383                               DBusWatch                   *watch,
2384                               unsigned int                 condition)
2385 {
2386   dbus_bool_t retval;
2387   DBusDispatchStatus status;
2388   
2389   dbus_mutex_lock (connection->mutex);
2390   _dbus_connection_acquire_io_path (connection, -1);
2391   retval = _dbus_transport_handle_watch (connection->transport,
2392                                          watch, condition);
2393   _dbus_connection_release_io_path (connection);
2394
2395   status = _dbus_connection_get_dispatch_status_unlocked (connection);
2396   
2397   dbus_mutex_unlock (connection->mutex);
2398
2399   _dbus_connection_update_dispatch_status_locked (connection, status);
2400   
2401   return retval;
2402 }
2403
2404 /**
2405  * Gets the UNIX user ID of the connection if any.
2406  * Returns #TRUE if the uid is filled in.
2407  * Always returns #FALSE on non-UNIX platforms.
2408  * Always returns #FALSE prior to authenticating the
2409  * connection.
2410  *
2411  * @param connection the connection
2412  * @param uid return location for the user ID
2413  * @returns #TRUE if uid is filled in with a valid user ID
2414  */
2415 dbus_bool_t
2416 dbus_connection_get_unix_user (DBusConnection *connection,
2417                                unsigned long  *uid)
2418 {
2419   dbus_bool_t result;
2420
2421   dbus_mutex_lock (connection->mutex);
2422
2423   if (!_dbus_transport_get_is_authenticated (connection->transport))
2424     result = FALSE;
2425   else
2426     result = _dbus_transport_get_unix_user (connection->transport,
2427                                             uid);
2428   dbus_mutex_unlock (connection->mutex);
2429
2430   return result;
2431 }
2432
2433 /**
2434  * Sets a predicate function used to determine whether a given user ID
2435  * is allowed to connect. When an incoming connection has
2436  * authenticated with a particular user ID, this function is called;
2437  * if it returns #TRUE, the connection is allowed to proceed,
2438  * otherwise the connection is disconnected.
2439  *
2440  * If the function is set to #NULL (as it is by default), then
2441  * only the same UID as the server process will be allowed to
2442  * connect.
2443  *
2444  * @param connection the connection
2445  * @param function the predicate
2446  * @param data data to pass to the predicate
2447  * @param free_data_function function to free the data
2448  */
2449 void
2450 dbus_connection_set_unix_user_function (DBusConnection             *connection,
2451                                         DBusAllowUnixUserFunction   function,
2452                                         void                       *data,
2453                                         DBusFreeFunction            free_data_function)
2454 {
2455   void *old_data = NULL;
2456   DBusFreeFunction old_free_function = NULL;
2457
2458   dbus_mutex_lock (connection->mutex);
2459   _dbus_transport_set_unix_user_function (connection->transport,
2460                                           function, data, free_data_function,
2461                                           &old_data, &old_free_function);
2462   dbus_mutex_unlock (connection->mutex);
2463
2464   if (old_free_function != NULL)
2465     (* old_free_function) (old_data);    
2466 }
2467
2468 /**
2469  * Adds a message filter. Filters are handlers that are run on
2470  * all incoming messages, prior to the normal handlers
2471  * registered with dbus_connection_register_handler().
2472  * Filters are run in the order that they were added.
2473  * The same handler can be added as a filter more than once, in
2474  * which case it will be run more than once.
2475  * Filters added during a filter callback won't be run on the
2476  * message being processed.
2477  *
2478  * @param connection the connection
2479  * @param handler the handler
2480  * @returns #TRUE on success, #FALSE if not enough memory.
2481  */
2482 dbus_bool_t
2483 dbus_connection_add_filter (DBusConnection      *connection,
2484                             DBusMessageHandler  *handler)
2485 {
2486   dbus_mutex_lock (connection->mutex);
2487   if (!_dbus_message_handler_add_connection (handler, connection))
2488     {
2489       dbus_mutex_unlock (connection->mutex);
2490       return FALSE;
2491     }
2492
2493   if (!_dbus_list_append (&connection->filter_list,
2494                           handler))
2495     {
2496       _dbus_message_handler_remove_connection (handler, connection);
2497       dbus_mutex_unlock (connection->mutex);
2498       return FALSE;
2499     }
2500
2501   dbus_mutex_unlock (connection->mutex);
2502   return TRUE;
2503 }
2504
2505 /**
2506  * Removes a previously-added message filter. It is a programming
2507  * error to call this function for a handler that has not
2508  * been added as a filter. If the given handler was added
2509  * more than once, only one instance of it will be removed
2510  * (the most recently-added instance).
2511  *
2512  * @param connection the connection
2513  * @param handler the handler to remove
2514  *
2515  */
2516 void
2517 dbus_connection_remove_filter (DBusConnection      *connection,
2518                                DBusMessageHandler  *handler)
2519 {
2520   dbus_mutex_lock (connection->mutex);
2521   if (!_dbus_list_remove_last (&connection->filter_list, handler))
2522     {
2523       _dbus_warn ("Tried to remove a DBusConnection filter that had not been added\n");
2524       dbus_mutex_unlock (connection->mutex);
2525       return;
2526     }
2527
2528   _dbus_message_handler_remove_connection (handler, connection);
2529
2530   dbus_mutex_unlock (connection->mutex);
2531 }
2532
2533 /**
2534  * Registers a handler for a list of message names. A single handler
2535  * can be registered for any number of message names, but each message
2536  * name can only have one handler at a time. It's not allowed to call
2537  * this function with the name of a message that already has a
2538  * handler. If the function returns #FALSE, the handlers were not
2539  * registered due to lack of memory.
2540  *
2541  * @todo the messages_to_handle arg may be more convenient if it's a
2542  * single string instead of an array. Though right now MessageHandler
2543  * is sort of designed to say be associated with an entire object with
2544  * multiple methods, that's why for example the connection only
2545  * weakrefs it.  So maybe the "manual" API should be different.
2546  * 
2547  * @param connection the connection
2548  * @param handler the handler
2549  * @param messages_to_handle the messages to handle
2550  * @param n_messages the number of message names in messages_to_handle
2551  * @returns #TRUE on success, #FALSE if no memory or another handler already exists
2552  * 
2553  **/
2554 dbus_bool_t
2555 dbus_connection_register_handler (DBusConnection     *connection,
2556                                   DBusMessageHandler *handler,
2557                                   const char        **messages_to_handle,
2558                                   int                 n_messages)
2559 {
2560   int i;
2561
2562   dbus_mutex_lock (connection->mutex);
2563   i = 0;
2564   while (i < n_messages)
2565     {
2566       DBusHashIter iter;
2567       char *key;
2568
2569       key = _dbus_strdup (messages_to_handle[i]);
2570       if (key == NULL)
2571         goto failed;
2572       
2573       if (!_dbus_hash_iter_lookup (connection->handler_table,
2574                                    key, TRUE,
2575                                    &iter))
2576         {
2577           dbus_free (key);
2578           goto failed;
2579         }
2580
2581       if (_dbus_hash_iter_get_value (&iter) != NULL)
2582         {
2583           _dbus_warn ("Bug in application: attempted to register a second handler for %s\n",
2584                       messages_to_handle[i]);
2585           dbus_free (key); /* won't have replaced the old key with the new one */
2586           goto failed;
2587         }
2588
2589       if (!_dbus_message_handler_add_connection (handler, connection))
2590         {
2591           _dbus_hash_iter_remove_entry (&iter);
2592           /* key has freed on nuking the entry */
2593           goto failed;
2594         }
2595       
2596       _dbus_hash_iter_set_value (&iter, handler);
2597
2598       ++i;
2599     }
2600   
2601   dbus_mutex_unlock (connection->mutex);
2602   return TRUE;
2603   
2604  failed:
2605   /* unregister everything registered so far,
2606    * so we don't fail partially
2607    */
2608   dbus_connection_unregister_handler (connection,
2609                                       handler,
2610                                       messages_to_handle,
2611                                       i);
2612
2613   dbus_mutex_unlock (connection->mutex);
2614   return FALSE;
2615 }
2616
2617 /**
2618  * Unregisters a handler for a list of message names. The handlers
2619  * must have been previously registered.
2620  *
2621  * @param connection the connection
2622  * @param handler the handler
2623  * @param messages_to_handle the messages to handle
2624  * @param n_messages the number of message names in messages_to_handle
2625  * 
2626  **/
2627 void
2628 dbus_connection_unregister_handler (DBusConnection     *connection,
2629                                     DBusMessageHandler *handler,
2630                                     const char        **messages_to_handle,
2631                                     int                 n_messages)
2632 {
2633   int i;
2634
2635   dbus_mutex_lock (connection->mutex);
2636   i = 0;
2637   while (i < n_messages)
2638     {
2639       DBusHashIter iter;
2640
2641       if (!_dbus_hash_iter_lookup (connection->handler_table,
2642                                    (char*) messages_to_handle[i], FALSE,
2643                                    &iter))
2644         {
2645           _dbus_warn ("Bug in application: attempted to unregister handler for %s which was not registered\n",
2646                       messages_to_handle[i]);
2647         }
2648       else if (_dbus_hash_iter_get_value (&iter) != handler)
2649         {
2650           _dbus_warn ("Bug in application: attempted to unregister handler for %s which was registered by a different handler\n",
2651                       messages_to_handle[i]);
2652         }
2653       else
2654         {
2655           _dbus_hash_iter_remove_entry (&iter);
2656           _dbus_message_handler_remove_connection (handler, connection);
2657         }
2658
2659       ++i;
2660     }
2661
2662   dbus_mutex_unlock (connection->mutex);
2663 }
2664
2665 static DBusDataSlotAllocator slot_allocator;
2666 _DBUS_DEFINE_GLOBAL_LOCK (connection_slots);
2667
2668 /**
2669  * Allocates an integer ID to be used for storing application-specific
2670  * data on any DBusConnection. The allocated ID may then be used
2671  * with dbus_connection_set_data() and dbus_connection_get_data().
2672  * If allocation fails, -1 is returned. Again, the allocated
2673  * slot is global, i.e. all DBusConnection objects will
2674  * have a slot with the given integer ID reserved.
2675  *
2676  * @returns -1 on failure, otherwise the data slot ID
2677  */
2678 int
2679 dbus_connection_allocate_data_slot (void)
2680 {
2681   return _dbus_data_slot_allocator_alloc (&slot_allocator,
2682                                           _DBUS_LOCK_NAME (connection_slots));
2683 }
2684
2685 /**
2686  * Deallocates a global ID for connection data slots.
2687  * dbus_connection_get_data() and dbus_connection_set_data()
2688  * may no longer be used with this slot.
2689  * Existing data stored on existing DBusConnection objects
2690  * will be freed when the connection is finalized,
2691  * but may not be retrieved (and may only be replaced
2692  * if someone else reallocates the slot).
2693  *
2694  * @param slot the slot to deallocate
2695  */
2696 void
2697 dbus_connection_free_data_slot (int slot)
2698 {
2699   _dbus_data_slot_allocator_free (&slot_allocator, slot);
2700 }
2701
2702 /**
2703  * Stores a pointer on a DBusConnection, along
2704  * with an optional function to be used for freeing
2705  * the data when the data is set again, or when
2706  * the connection is finalized. The slot number
2707  * must have been allocated with dbus_connection_allocate_data_slot().
2708  *
2709  * @param connection the connection
2710  * @param slot the slot number
2711  * @param data the data to store
2712  * @param free_data_func finalizer function for the data
2713  * @returns #TRUE if there was enough memory to store the data
2714  */
2715 dbus_bool_t
2716 dbus_connection_set_data (DBusConnection   *connection,
2717                           int               slot,
2718                           void             *data,
2719                           DBusFreeFunction  free_data_func)
2720 {
2721   DBusFreeFunction old_free_func;
2722   void *old_data;
2723   dbus_bool_t retval;
2724   
2725   dbus_mutex_lock (connection->mutex);
2726
2727   retval = _dbus_data_slot_list_set (&slot_allocator,
2728                                      &connection->slot_list,
2729                                      slot, data, free_data_func,
2730                                      &old_free_func, &old_data);
2731   
2732   dbus_mutex_unlock (connection->mutex);
2733
2734   if (retval)
2735     {
2736       /* Do the actual free outside the connection lock */
2737       if (old_free_func)
2738         (* old_free_func) (old_data);
2739     }
2740
2741   return retval;
2742 }
2743
2744 /**
2745  * Retrieves data previously set with dbus_connection_set_data().
2746  * The slot must still be allocated (must not have been freed).
2747  *
2748  * @param connection the connection
2749  * @param slot the slot to get data from
2750  * @returns the data, or #NULL if not found
2751  */
2752 void*
2753 dbus_connection_get_data (DBusConnection   *connection,
2754                           int               slot)
2755 {
2756   void *res;
2757   
2758   dbus_mutex_lock (connection->mutex);
2759
2760   res = _dbus_data_slot_list_get (&slot_allocator,
2761                                   &connection->slot_list,
2762                                   slot);
2763   
2764   dbus_mutex_unlock (connection->mutex);
2765
2766   return res;
2767 }
2768
2769 /**
2770  * This function sets a global flag for whether dbus_connection_new()
2771  * will set SIGPIPE behavior to SIG_IGN.
2772  *
2773  * @param will_modify_sigpipe #TRUE to allow sigpipe to be set to SIG_IGN
2774  */
2775 void
2776 dbus_connection_set_change_sigpipe (dbus_bool_t will_modify_sigpipe)
2777 {
2778   _dbus_modify_sigpipe = will_modify_sigpipe;
2779 }
2780
2781 /**
2782  * Specifies the maximum size message this connection is allowed to
2783  * receive. Larger messages will result in disconnecting the
2784  * connection.
2785  * 
2786  * @param connection a #DBusConnection
2787  * @param size maximum message size the connection can receive, in bytes
2788  */
2789 void
2790 dbus_connection_set_max_message_size (DBusConnection *connection,
2791                                       long            size)
2792 {
2793   dbus_mutex_lock (connection->mutex);
2794   _dbus_transport_set_max_message_size (connection->transport,
2795                                         size);
2796   dbus_mutex_unlock (connection->mutex);
2797 }
2798
2799 /**
2800  * Gets the value set by dbus_connection_set_max_message_size().
2801  *
2802  * @param connection the connection
2803  * @returns the max size of a single message
2804  */
2805 long
2806 dbus_connection_get_max_message_size (DBusConnection *connection)
2807 {
2808   long res;
2809   dbus_mutex_lock (connection->mutex);
2810   res = _dbus_transport_get_max_message_size (connection->transport);
2811   dbus_mutex_unlock (connection->mutex);
2812   return res;
2813 }
2814
2815 /**
2816  * Sets the maximum total number of bytes that can be used for all messages
2817  * received on this connection. Messages count toward the maximum until
2818  * they are finalized. When the maximum is reached, the connection will
2819  * not read more data until some messages are finalized.
2820  *
2821  * The semantics of the maximum are: if outstanding messages are
2822  * already above the maximum, additional messages will not be read.
2823  * The semantics are not: if the next message would cause us to exceed
2824  * the maximum, we don't read it. The reason is that we don't know the
2825  * size of a message until after we read it.
2826  *
2827  * Thus, the max live messages size can actually be exceeded
2828  * by up to the maximum size of a single message.
2829  * 
2830  * Also, if we read say 1024 bytes off the wire in a single read(),
2831  * and that contains a half-dozen small messages, we may exceed the
2832  * size max by that amount. But this should be inconsequential.
2833  *
2834  * This does imply that we can't call read() with a buffer larger
2835  * than we're willing to exceed this limit by.
2836  *
2837  * @param connection the connection
2838  * @param size the maximum size in bytes of all outstanding messages
2839  */
2840 void
2841 dbus_connection_set_max_received_size (DBusConnection *connection,
2842                                                 long            size)
2843 {
2844   dbus_mutex_lock (connection->mutex);
2845   _dbus_transport_set_max_received_size (connection->transport,
2846                                          size);
2847   dbus_mutex_unlock (connection->mutex);
2848 }
2849
2850 /**
2851  * Gets the value set by dbus_connection_set_max_received_size().
2852  *
2853  * @param connection the connection
2854  * @returns the max size of all live messages
2855  */
2856 long
2857 dbus_connection_get_max_received_size (DBusConnection *connection)
2858 {
2859   long res;
2860   dbus_mutex_lock (connection->mutex);
2861   res = _dbus_transport_get_max_received_size (connection->transport);
2862   dbus_mutex_unlock (connection->mutex);
2863   return res;
2864 }
2865
2866 /**
2867  * Gets the approximate size in bytes of all messages in the outgoing
2868  * message queue. The size is approximate in that you shouldn't use
2869  * it to decide how many bytes to read off the network or anything
2870  * of that nature, as optimizations may choose to tell small white lies
2871  * to avoid performance overhead.
2872  *
2873  * @param connection the connection
2874  * @returns the number of bytes that have been queued up but not sent
2875  */
2876 long
2877 dbus_connection_get_outgoing_size (DBusConnection *connection)
2878 {
2879   long res;
2880   dbus_mutex_lock (connection->mutex);
2881   res = _dbus_counter_get_value (connection->outgoing_counter);
2882   dbus_mutex_unlock (connection->mutex);
2883   return res;
2884 }
2885
2886 /** @} */