2003-02-26 Havoc Pennington <hp@pobox.com>
[platform/upstream/dbus.git] / dbus / dbus-connection.c
1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-connection.c DBusConnection object
3  *
4  * Copyright (C) 2002, 2003  Red Hat Inc.
5  *
6  * Licensed under the Academic Free License version 1.2
7  * 
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  * 
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  *
22  */
23
24 #include "dbus-connection.h"
25 #include "dbus-list.h"
26 #include "dbus-timeout.h"
27 #include "dbus-transport.h"
28 #include "dbus-watch.h"
29 #include "dbus-connection-internal.h"
30 #include "dbus-list.h"
31 #include "dbus-hash.h"
32 #include "dbus-message-internal.h"
33 #include "dbus-message-handler.h"
34 #include "dbus-threads.h"
35 #include "dbus-protocol.h"
36 #include "dbus-dataslot.h"
37
38 /**
39  * @defgroup DBusConnection DBusConnection
40  * @ingroup  DBus
41  * @brief Connection to another application
42  *
43  * A DBusConnection represents a connection to another
44  * application. Messages can be sent and received via this connection.
45  *
46  * The connection maintains a queue of incoming messages and a queue
47  * of outgoing messages. dbus_connection_pop_message() and friends
48  * can be used to read incoming messages from the queue.
49  * Outgoing messages are automatically discarded as they are
50  * written to the network.
51  *
52  * In brief a DBusConnection is a message queue associated with some
53  * message transport mechanism such as a socket.
54  * 
55  */
56
57 /**
58  * @defgroup DBusConnectionInternals DBusConnection implementation details
59  * @ingroup  DBusInternals
60  * @brief Implementation details of DBusConnection
61  *
62  * @{
63  */
64
65 /** default timeout value when waiting for a message reply */
66 #define DEFAULT_TIMEOUT_VALUE (15 * 1000)
67
68 static dbus_bool_t _dbus_modify_sigpipe = TRUE;
69
70 /**
71  * Implementation details of DBusConnection. All fields are private.
72  */
73 struct DBusConnection
74 {
75   int refcount; /**< Reference count. */
76
77   DBusMutex *mutex; /**< Lock on the entire DBusConnection */
78
79   dbus_bool_t dispatch_acquired; /**< Protects dispatch_message */
80   DBusCondVar *dispatch_cond;    /**< Protects dispatch_message */
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   DBusTransport *transport;    /**< Object that sends/receives messages over network. */
95   DBusWatchList *watches;      /**< Stores active watches. */
96   DBusTimeoutList *timeouts;   /**< Stores active timeouts. */
97   
98   DBusHashTable *handler_table; /**< Table of registered DBusMessageHandler */
99   DBusList *filter_list;        /**< List of filters. */
100
101   DBusDataSlotList slot_list;   /**< Data stored by allocated integer ID */
102
103   DBusHashTable *pending_replies;  /**< Hash of message serials and their message handlers. */  
104   DBusCounter *connection_counter; /**< Counter that we decrement when finalized */
105   
106   int client_serial;            /**< Client serial. Increments each time a message is sent  */
107   DBusList *disconnect_message_link; /**< Preallocated list node for queueing the disconnection message */
108 };
109
110 typedef struct
111 {
112   DBusConnection *connection;
113   DBusMessageHandler *handler;
114   DBusTimeout *timeout;
115   int serial;
116
117   DBusList *timeout_link; /* Preallocated timeout response */
118   
119   dbus_bool_t timeout_added;
120   dbus_bool_t connection_added;
121 } ReplyHandlerData;
122
123 static void reply_handler_data_free (ReplyHandlerData *data);
124
125 static void _dbus_connection_remove_timeout_locked (DBusConnection *connection,
126                                                     DBusTimeout    *timeout);
127
128 /**
129  * Acquires the connection lock.
130  *
131  * @param connection the connection.
132  */
133 void
134 _dbus_connection_lock (DBusConnection *connection)
135 {
136   dbus_mutex_lock (connection->mutex);
137 }
138
139 /**
140  * Releases the connection lock.
141  *
142  * @param connection the connection.
143  */
144 void
145 _dbus_connection_unlock (DBusConnection *connection)
146 {
147   dbus_mutex_unlock (connection->mutex);
148 }
149
150
151 /**
152  * Adds a message to the incoming message queue, returning #FALSE
153  * if there's insufficient memory to queue the message.
154  *
155  * @param connection the connection.
156  * @param message the message to queue.
157  * @returns #TRUE on success.
158  */
159 dbus_bool_t
160 _dbus_connection_queue_received_message (DBusConnection *connection,
161                                          DBusMessage    *message)
162 {
163   ReplyHandlerData *reply_handler_data;
164   dbus_int32_t reply_serial;
165   
166   _dbus_assert (_dbus_transport_get_is_authenticated (connection->transport));
167   
168   if (!_dbus_list_append (&connection->incoming_messages,
169                           message))
170     return FALSE;
171
172   /* If this is a reply we're waiting on, remove timeout for it */
173   reply_serial = _dbus_message_get_reply_serial (message);
174   if (reply_serial != -1)
175     {
176       reply_handler_data = _dbus_hash_table_lookup_int (connection->pending_replies,
177                                                         reply_serial);
178       if (reply_handler_data != NULL)
179         {
180           if (reply_handler_data->timeout_added)
181             _dbus_connection_remove_timeout_locked (connection,
182                                                     reply_handler_data->timeout);
183           reply_handler_data->timeout_added = FALSE;
184         }
185     }
186   
187   dbus_message_ref (message);
188   connection->n_incoming += 1;
189
190   _dbus_verbose ("Incoming message %p added to queue, %d incoming\n",
191                  message, connection->n_incoming);
192   
193   return TRUE;
194 }
195
196 /**
197  * Adds a link + message to the incoming message queue.
198  * Can't fail. Takes ownership of both link and message.
199  *
200  * @param connection the connection.
201  * @param link the list node and message to queue.
202  *
203  * @todo This needs to wake up the mainloop if it is in
204  * a poll/select and this is a multithreaded app.
205  */
206 static void
207 _dbus_connection_queue_synthesized_message_link (DBusConnection *connection,
208                                                  DBusList *link)
209 {
210   _dbus_list_append_link (&connection->incoming_messages, link);
211
212   connection->n_incoming += 1;
213
214   _dbus_verbose ("Incoming synthesized message %p added to queue, %d incoming\n",
215                  link->data, connection->n_incoming);
216 }
217
218
219 /**
220  * Checks whether there are messages in the outgoing message queue.
221  *
222  * @param connection the connection.
223  * @returns #TRUE if the outgoing queue is non-empty.
224  */
225 dbus_bool_t
226 _dbus_connection_have_messages_to_send (DBusConnection *connection)
227 {
228   return connection->outgoing_messages != NULL;
229 }
230
231 /**
232  * Gets the next outgoing message. The message remains in the
233  * queue, and the caller does not own a reference to it.
234  *
235  * @param connection the connection.
236  * @returns the message to be sent.
237  */ 
238 DBusMessage*
239 _dbus_connection_get_message_to_send (DBusConnection *connection)
240 {
241   return _dbus_list_get_last (&connection->outgoing_messages);
242 }
243
244 /**
245  * Notifies the connection that a message has been sent, so the
246  * message can be removed from the outgoing queue.
247  *
248  * @param connection the connection.
249  * @param message the message that was sent.
250  */
251 void
252 _dbus_connection_message_sent (DBusConnection *connection,
253                                DBusMessage    *message)
254 {
255   _dbus_assert (_dbus_transport_get_is_authenticated (connection->transport));
256   _dbus_assert (message == _dbus_list_get_last (&connection->outgoing_messages));
257   
258   _dbus_list_pop_last (&connection->outgoing_messages);
259   dbus_message_unref (message);
260   
261   connection->n_outgoing -= 1;
262
263   _dbus_verbose ("Message %p removed from outgoing queue, %d left to send\n",
264                  message, connection->n_outgoing);
265   
266   if (connection->n_outgoing == 0)
267     _dbus_transport_messages_pending (connection->transport,
268                                       connection->n_outgoing);  
269 }
270
271 /**
272  * Adds a watch using the connection's DBusAddWatchFunction if
273  * available. Otherwise records the watch to be added when said
274  * function is available. Also re-adds the watch if the
275  * DBusAddWatchFunction changes. May fail due to lack of memory.
276  *
277  * @param connection the connection.
278  * @param watch the watch to add.
279  * @returns #TRUE on success.
280  */
281 dbus_bool_t
282 _dbus_connection_add_watch (DBusConnection *connection,
283                             DBusWatch      *watch)
284 {
285   if (connection->watches) /* null during finalize */
286     return _dbus_watch_list_add_watch (connection->watches,
287                                        watch);
288   else
289     return FALSE;
290 }
291
292 /**
293  * Removes a watch using the connection's DBusRemoveWatchFunction
294  * if available. It's an error to call this function on a watch
295  * that was not previously added.
296  *
297  * @param connection the connection.
298  * @param watch the watch to remove.
299  */
300 void
301 _dbus_connection_remove_watch (DBusConnection *connection,
302                                DBusWatch      *watch)
303 {
304   if (connection->watches) /* null during finalize */
305     _dbus_watch_list_remove_watch (connection->watches,
306                                    watch);
307 }
308
309 /**
310  * Adds a timeout using the connection's DBusAddTimeoutFunction if
311  * available. Otherwise records the timeout to be added when said
312  * function is available. Also re-adds the timeout if the
313  * DBusAddTimeoutFunction changes. May fail due to lack of memory.
314  *
315  * @param connection the connection.
316  * @param timeout the timeout to add.
317  * @returns #TRUE on success.
318  */
319 dbus_bool_t
320 _dbus_connection_add_timeout (DBusConnection *connection,
321                               DBusTimeout    *timeout)
322 {
323  if (connection->timeouts) /* null during finalize */
324     return _dbus_timeout_list_add_timeout (connection->timeouts,
325                                            timeout);
326   else
327     return FALSE;  
328 }
329
330 /**
331  * Removes a timeout using the connection's DBusRemoveTimeoutFunction
332  * if available. It's an error to call this function on a timeout
333  * that was not previously added.
334  *
335  * @param connection the connection.
336  * @param timeout the timeout to remove.
337  */
338 void
339 _dbus_connection_remove_timeout (DBusConnection *connection,
340                                  DBusTimeout    *timeout)
341 {
342   if (connection->timeouts) /* null during finalize */
343     _dbus_timeout_list_remove_timeout (connection->timeouts,
344                                        timeout);
345 }
346
347 static void
348 _dbus_connection_remove_timeout_locked (DBusConnection *connection,
349                                         DBusTimeout    *timeout)
350 {
351   dbus_mutex_lock (connection->mutex);
352   _dbus_connection_remove_timeout (connection, timeout);
353   dbus_mutex_unlock (connection->mutex);
354 }
355
356
357 /**
358  * Tells the connection that the transport has been disconnected.
359  * Results in posting a disconnect message on the incoming message
360  * queue.  Only has an effect the first time it's called.
361  *
362  * @param connection the connection
363  */
364 void
365 _dbus_connection_notify_disconnected (DBusConnection *connection)
366 {
367   if (connection->disconnect_message_link)
368     {
369       /* We haven't sent the disconnect message already */
370       _dbus_connection_queue_synthesized_message_link (connection,
371                                                        connection->disconnect_message_link);
372       connection->disconnect_message_link = NULL;
373     }
374 }
375
376
377 /**
378  * Acquire the transporter I/O path. This must be done before
379  * doing any I/O in the transporter. May sleep and drop the
380  * connection mutex while waiting for the I/O path.
381  *
382  * @param connection the connection.
383  * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
384  * @returns TRUE if the I/O path was acquired.
385  */
386 static dbus_bool_t
387 _dbus_connection_acquire_io_path (DBusConnection *connection,
388                                   int timeout_milliseconds)
389 {
390   dbus_bool_t res = TRUE;
391   if (timeout_milliseconds != -1) 
392     res = dbus_condvar_wait_timeout (connection->io_path_cond,
393                                      connection->mutex,
394                                      timeout_milliseconds);
395   else
396     dbus_condvar_wait (connection->io_path_cond, connection->mutex);
397
398   if (res)
399     {
400       _dbus_assert (!connection->io_path_acquired);
401
402       connection->io_path_acquired = TRUE;
403     }
404   
405   return res;
406 }
407
408 /**
409  * Release the I/O path when you're done with it. Only call
410  * after you've acquired the I/O. Wakes up at most one thread
411  * currently waiting to acquire the I/O path.
412  *
413  * @param connection the connection.
414  */
415 static void
416 _dbus_connection_release_io_path (DBusConnection *connection)
417 {
418   _dbus_assert (connection->io_path_acquired);
419
420   connection->io_path_acquired = FALSE;
421   dbus_condvar_wake_one (connection->io_path_cond);
422 }
423
424
425 /**
426  * Queues incoming messages and sends outgoing messages for this
427  * connection, optionally blocking in the process. Each call to
428  * _dbus_connection_do_iteration() will call select() or poll() one
429  * time and then read or write data if possible.
430  *
431  * The purpose of this function is to be able to flush outgoing
432  * messages or queue up incoming messages without returning
433  * control to the application and causing reentrancy weirdness.
434  *
435  * The flags parameter allows you to specify whether to
436  * read incoming messages, write outgoing messages, or both,
437  * and whether to block if no immediate action is possible.
438  *
439  * The timeout_milliseconds parameter does nothing unless the
440  * iteration is blocking.
441  *
442  * If there are no outgoing messages and DBUS_ITERATION_DO_READING
443  * wasn't specified, then it's impossible to block, even if
444  * you specify DBUS_ITERATION_BLOCK; in that case the function
445  * returns immediately.
446  * 
447  * @param connection the connection.
448  * @param flags iteration flags.
449  * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
450  */
451 void
452 _dbus_connection_do_iteration (DBusConnection *connection,
453                                unsigned int    flags,
454                                int             timeout_milliseconds)
455 {
456   if (connection->n_outgoing == 0)
457     flags &= ~DBUS_ITERATION_DO_WRITING;
458
459   if (_dbus_connection_acquire_io_path (connection,
460                                         (flags & DBUS_ITERATION_BLOCK)?timeout_milliseconds:0))
461     {
462       _dbus_transport_do_iteration (connection->transport,
463                                     flags, timeout_milliseconds);
464       _dbus_connection_release_io_path (connection);
465     }
466 }
467
468 /**
469  * Creates a new connection for the given transport.  A transport
470  * represents a message stream that uses some concrete mechanism, such
471  * as UNIX domain sockets. May return #NULL if insufficient
472  * memory exists to create the connection.
473  *
474  * @param transport the transport.
475  * @returns the new connection, or #NULL on failure.
476  */
477 DBusConnection*
478 _dbus_connection_new_for_transport (DBusTransport *transport)
479 {
480   DBusConnection *connection;
481   DBusWatchList *watch_list;
482   DBusTimeoutList *timeout_list;
483   DBusHashTable *handler_table, *pending_replies;
484   DBusMutex *mutex;
485   DBusCondVar *message_returned_cond;
486   DBusCondVar *dispatch_cond;
487   DBusCondVar *io_path_cond;
488   DBusList *disconnect_link;
489   DBusMessage *disconnect_message;
490
491   watch_list = NULL;
492   connection = NULL;
493   handler_table = NULL;
494   pending_replies = NULL;
495   timeout_list = NULL;
496   mutex = NULL;
497   message_returned_cond = NULL;
498   dispatch_cond = NULL;
499   io_path_cond = NULL;
500   disconnect_link = NULL;
501   disconnect_message = NULL;
502   
503   watch_list = _dbus_watch_list_new ();
504   if (watch_list == NULL)
505     goto error;
506
507   timeout_list = _dbus_timeout_list_new ();
508   if (timeout_list == NULL)
509     goto error;
510   
511   handler_table =
512     _dbus_hash_table_new (DBUS_HASH_STRING,
513                           dbus_free, NULL);
514   if (handler_table == NULL)
515     goto error;
516
517   pending_replies =
518     _dbus_hash_table_new (DBUS_HASH_INT,
519                           NULL, (DBusFreeFunction)reply_handler_data_free);
520   if (pending_replies == NULL)
521     goto error;
522   
523   connection = dbus_new0 (DBusConnection, 1);
524   if (connection == NULL)
525     goto error;
526
527   mutex = dbus_mutex_new ();
528   if (mutex == NULL)
529     goto error;
530   
531   message_returned_cond = dbus_condvar_new ();
532   if (message_returned_cond == NULL)
533     goto error;
534   
535   dispatch_cond = dbus_condvar_new ();
536   if (dispatch_cond == NULL)
537     goto error;
538   
539   io_path_cond = dbus_condvar_new ();
540   if (io_path_cond == NULL)
541     goto error;
542
543   disconnect_message = dbus_message_new (NULL, DBUS_MESSAGE_LOCAL_DISCONNECT);
544   if (disconnect_message == NULL)
545     goto error;
546
547   disconnect_link = _dbus_list_alloc_link (disconnect_message);
548   if (disconnect_link == NULL)
549     goto error;
550
551   if (_dbus_modify_sigpipe)
552     _dbus_disable_sigpipe ();
553   
554   connection->refcount = 1;
555   connection->mutex = mutex;
556   connection->dispatch_cond = dispatch_cond;
557   connection->io_path_cond = io_path_cond;
558   connection->message_returned_cond = message_returned_cond;
559   connection->transport = transport;
560   connection->watches = watch_list;
561   connection->timeouts = timeout_list;
562   connection->handler_table = handler_table;
563   connection->pending_replies = pending_replies;
564   connection->filter_list = NULL;
565
566   _dbus_data_slot_list_init (&connection->slot_list);
567
568   connection->client_serial = 1;
569
570   connection->disconnect_message_link = disconnect_link;
571   
572   _dbus_transport_ref (transport);
573   _dbus_transport_set_connection (transport, connection);
574   
575   return connection;
576   
577  error:
578   if (disconnect_message != NULL)
579     dbus_message_unref (disconnect_message);
580   
581   if (disconnect_link != NULL)
582     _dbus_list_free_link (disconnect_link);
583   
584   if (io_path_cond != NULL)
585     dbus_condvar_free (io_path_cond);
586   
587   if (dispatch_cond != NULL)
588     dbus_condvar_free (dispatch_cond);
589   
590   if (message_returned_cond != NULL)
591     dbus_condvar_free (message_returned_cond);
592   
593   if (mutex != NULL)
594     dbus_mutex_free (mutex);
595
596   if (connection != NULL)
597     dbus_free (connection);
598
599   if (handler_table)
600     _dbus_hash_table_unref (handler_table);
601
602   if (pending_replies)
603     _dbus_hash_table_unref (pending_replies);
604   
605   if (watch_list)
606     _dbus_watch_list_free (watch_list);
607
608   if (timeout_list)
609     _dbus_timeout_list_free (timeout_list);
610   
611   return NULL;
612 }
613
614 static dbus_int32_t
615 _dbus_connection_get_next_client_serial (DBusConnection *connection)
616 {
617   int serial;
618
619   serial = connection->client_serial++;
620
621   if (connection->client_serial < 0)
622     connection->client_serial = 1;
623   
624   return serial;
625 }
626
627 /**
628  * Used to notify a connection when a DBusMessageHandler is
629  * destroyed, so the connection can drop any reference
630  * to the handler. This is a private function, but still
631  * takes the connection lock. Don't call it with the lock held.
632  *
633  * @todo needs to check in pending_replies too.
634  * 
635  * @param connection the connection
636  * @param handler the handler
637  */
638 void
639 _dbus_connection_handler_destroyed_locked (DBusConnection     *connection,
640                                            DBusMessageHandler *handler)
641 {
642   DBusHashIter iter;
643   DBusList *link;
644
645   dbus_mutex_lock (connection->mutex);
646   
647   _dbus_hash_iter_init (connection->handler_table, &iter);
648   while (_dbus_hash_iter_next (&iter))
649     {
650       DBusMessageHandler *h = _dbus_hash_iter_get_value (&iter);
651
652       if (h == handler)
653         _dbus_hash_iter_remove_entry (&iter);
654     }
655
656   link = _dbus_list_get_first_link (&connection->filter_list);
657   while (link != NULL)
658     {
659       DBusMessageHandler *h = link->data;
660       DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
661
662       if (h == handler)
663         _dbus_list_remove_link (&connection->filter_list,
664                                 link);
665       
666       link = next;
667     }
668   dbus_mutex_unlock (connection->mutex);
669 }
670
671 /**
672  * Adds the counter used to count the number of open connections.
673  * Increments the counter by one, and saves it to be decremented
674  * again when this connection is finalized.
675  *
676  * @param connection a #DBusConnection
677  * @param counter counter that tracks number of connections
678  */
679 void
680 _dbus_connection_set_connection_counter (DBusConnection *connection,
681                                          DBusCounter    *counter)
682 {
683   _dbus_assert (connection->connection_counter == NULL);
684   
685   connection->connection_counter = counter;
686   _dbus_counter_ref (connection->connection_counter);
687   _dbus_counter_adjust (connection->connection_counter, 1);
688 }
689
690 /** @} */
691
692 /**
693  * @addtogroup DBusConnection
694  *
695  * @{
696  */
697
698 /**
699  * Opens a new connection to a remote address.
700  *
701  * @todo specify what the address parameter is. Right now
702  * it's just the name of a UNIX domain socket. It should be
703  * something more complex that encodes which transport to use.
704  *
705  * If the open fails, the function returns #NULL, and provides
706  * a reason for the failure in the result parameter. Pass
707  * #NULL for the result parameter if you aren't interested
708  * in the reason for failure.
709  * 
710  * @param address the address.
711  * @param result address where a result code can be returned.
712  * @returns new connection, or #NULL on failure.
713  */
714 DBusConnection*
715 dbus_connection_open (const char     *address,
716                       DBusResultCode *result)
717 {
718   DBusConnection *connection;
719   DBusTransport *transport;
720   
721   transport = _dbus_transport_open (address, result);
722   if (transport == NULL)
723     return NULL;
724   
725   connection = _dbus_connection_new_for_transport (transport);
726
727   _dbus_transport_unref (transport);
728   
729   if (connection == NULL)
730     {
731       dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
732       return NULL;
733     }
734   
735   return connection;
736 }
737
738 /**
739  * Increments the reference count of a DBusConnection.
740  *
741  * @param connection the connection.
742  */
743 void
744 dbus_connection_ref (DBusConnection *connection)
745 {
746   dbus_mutex_lock (connection->mutex);
747   _dbus_assert (connection->refcount > 0);
748
749   connection->refcount += 1;
750   dbus_mutex_unlock (connection->mutex);
751 }
752
753 /**
754  * Increments the reference count of a DBusConnection.
755  * Requires that the caller already holds the connection lock.
756  *
757  * @param connection the connection.
758  */
759 void
760 _dbus_connection_ref_unlocked (DBusConnection *connection)
761 {
762   _dbus_assert (connection->refcount > 0);
763   connection->refcount += 1;
764 }
765
766
767 /* This is run without the mutex held, but after the last reference
768  * to the connection has been dropped we should have no thread-related
769  * problems
770  */
771 static void
772 _dbus_connection_last_unref (DBusConnection *connection)
773 {
774   DBusHashIter iter;
775   DBusList *link;
776
777   _dbus_assert (!_dbus_transport_get_is_connected (connection->transport));
778   
779   if (connection->connection_counter != NULL)
780     {
781       /* subtract ourselves from the counter */
782       _dbus_counter_adjust (connection->connection_counter, - 1);
783       _dbus_counter_unref (connection->connection_counter);
784       connection->connection_counter = NULL;
785     }
786   
787   _dbus_watch_list_free (connection->watches);
788   connection->watches = NULL;
789   
790   _dbus_timeout_list_free (connection->timeouts);
791   connection->timeouts = NULL;
792
793   /* calls out to application code... */
794   _dbus_data_slot_list_free (&connection->slot_list);
795   
796   _dbus_hash_iter_init (connection->handler_table, &iter);
797   while (_dbus_hash_iter_next (&iter))
798     {
799       DBusMessageHandler *h = _dbus_hash_iter_get_value (&iter);
800       
801       _dbus_message_handler_remove_connection (h, connection);
802     }
803   
804   link = _dbus_list_get_first_link (&connection->filter_list);
805   while (link != NULL)
806     {
807       DBusMessageHandler *h = link->data;
808       DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
809       
810       _dbus_message_handler_remove_connection (h, connection);
811       
812       link = next;
813     }
814
815   _dbus_hash_table_unref (connection->handler_table);
816   connection->handler_table = NULL;
817
818   _dbus_hash_table_unref (connection->pending_replies);
819   connection->pending_replies = NULL;
820   
821   _dbus_list_clear (&connection->filter_list);
822   
823   _dbus_list_foreach (&connection->outgoing_messages,
824                       (DBusForeachFunction) dbus_message_unref,
825                       NULL);
826   _dbus_list_clear (&connection->outgoing_messages);
827   
828   _dbus_list_foreach (&connection->incoming_messages,
829                       (DBusForeachFunction) dbus_message_unref,
830                       NULL);
831   _dbus_list_clear (&connection->incoming_messages);
832   
833   _dbus_transport_unref (connection->transport);
834
835   if (connection->disconnect_message_link)
836     {
837       DBusMessage *message = connection->disconnect_message_link->data;
838       dbus_message_unref (message);
839       _dbus_list_free_link (connection->disconnect_message_link);
840     }
841   
842   dbus_condvar_free (connection->dispatch_cond);
843   dbus_condvar_free (connection->io_path_cond);
844   dbus_condvar_free (connection->message_returned_cond);
845   
846   dbus_mutex_free (connection->mutex);
847   
848   dbus_free (connection);
849 }
850
851 /**
852  * Decrements the reference count of a DBusConnection, and finalizes
853  * it if the count reaches zero.  It is a bug to drop the last reference
854  * to a connection that has not been disconnected.
855  *
856  * @param connection the connection.
857  */
858 void
859 dbus_connection_unref (DBusConnection *connection)
860 {
861   dbus_bool_t last_unref;
862   
863   dbus_mutex_lock (connection->mutex);
864   
865   _dbus_assert (connection != NULL);
866   _dbus_assert (connection->refcount > 0);
867
868   connection->refcount -= 1;
869   last_unref = (connection->refcount == 0);
870
871   dbus_mutex_unlock (connection->mutex);
872
873   if (last_unref)
874     _dbus_connection_last_unref (connection);
875 }
876
877 /**
878  * Closes the connection, so no further data can be sent or received.
879  * Any further attempts to send data will result in errors.  This
880  * function does not affect the connection's reference count.  It's
881  * safe to disconnect a connection more than once; all calls after the
882  * first do nothing. It's impossible to "reconnect" a connection, a
883  * new connection must be created.
884  *
885  * @param connection the connection.
886  */
887 void
888 dbus_connection_disconnect (DBusConnection *connection)
889 {
890   dbus_mutex_lock (connection->mutex);
891   _dbus_transport_disconnect (connection->transport);
892   dbus_mutex_unlock (connection->mutex);
893 }
894
895 /**
896  * Gets whether the connection is currently connected.  All
897  * connections are connected when they are opened.  A connection may
898  * become disconnected when the remote application closes its end, or
899  * exits; a connection may also be disconnected with
900  * dbus_connection_disconnect().
901  *
902  * @param connection the connection.
903  * @returns #TRUE if the connection is still alive.
904  */
905 dbus_bool_t
906 dbus_connection_get_is_connected (DBusConnection *connection)
907 {
908   dbus_bool_t res;
909   
910   dbus_mutex_lock (connection->mutex);
911   res = _dbus_transport_get_is_connected (connection->transport);
912   dbus_mutex_unlock (connection->mutex);
913   
914   return res;
915 }
916
917 /**
918  * Gets whether the connection was authenticated. (Note that
919  * if the connection was authenticated then disconnected,
920  * this function still returns #TRUE)
921  *
922  * @param connection the connection
923  * @returns #TRUE if the connection was ever authenticated
924  */
925 dbus_bool_t
926 dbus_connection_get_is_authenticated (DBusConnection *connection)
927 {
928   dbus_bool_t res;
929   
930   dbus_mutex_lock (connection->mutex);
931   res = _dbus_transport_get_is_authenticated (connection->transport);
932   dbus_mutex_unlock (connection->mutex);
933   
934   return res;
935 }
936
937 /**
938  * Adds a message to the outgoing message queue. Does not block to
939  * write the message to the network; that happens asynchronously. to
940  * force the message to be written, call dbus_connection_flush().
941  *
942  * If the function fails, it returns #FALSE and returns the
943  * reason for failure via the result parameter.
944  * The result parameter can be #NULL if you aren't interested
945  * in the reason for the failure.
946  * 
947  * @param connection the connection.
948  * @param message the message to write.
949  * @param client_serial return location for client serial.
950  * @param result address where result code can be placed.
951  * @returns #TRUE on success.
952  */
953 dbus_bool_t
954 dbus_connection_send_message (DBusConnection *connection,
955                               DBusMessage    *message,
956                               dbus_int32_t   *client_serial,                          
957                               DBusResultCode *result)
958
959 {
960   dbus_int32_t serial;
961
962   dbus_mutex_lock (connection->mutex);
963
964   if (!_dbus_list_prepend (&connection->outgoing_messages,
965                            message))
966     {
967       dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
968       dbus_mutex_unlock (connection->mutex);
969       return FALSE;
970     }
971
972   dbus_message_ref (message);
973   connection->n_outgoing += 1;
974
975   _dbus_verbose ("Message %p added to outgoing queue, %d pending to send\n",
976                  message, connection->n_outgoing);
977
978   if (_dbus_message_get_client_serial (message) == -1)
979     {
980       serial = _dbus_connection_get_next_client_serial (connection);
981       _dbus_message_set_client_serial (message, serial);
982     }
983   
984   if (client_serial)
985     *client_serial = _dbus_message_get_client_serial (message);
986   
987   _dbus_message_lock (message);
988
989   if (connection->n_outgoing == 1)
990     _dbus_transport_messages_pending (connection->transport,
991                                       connection->n_outgoing);
992
993   dbus_mutex_unlock (connection->mutex);
994   
995   return TRUE;
996 }
997
998 static void
999 reply_handler_timeout (void *data)
1000 {
1001   DBusConnection *connection;
1002   ReplyHandlerData *reply_handler_data = data;
1003
1004   connection = reply_handler_data->connection;
1005   
1006   dbus_mutex_lock (connection->mutex);
1007   if (reply_handler_data->timeout_link)
1008     {
1009       _dbus_connection_queue_synthesized_message_link (connection,
1010                                                        reply_handler_data->timeout_link);
1011       reply_handler_data->timeout_link = NULL;
1012     }
1013
1014   _dbus_connection_remove_timeout (connection,
1015                                    reply_handler_data->timeout);
1016   reply_handler_data->timeout_added = FALSE;
1017   
1018   dbus_mutex_unlock (connection->mutex);
1019 }
1020
1021 static void
1022 reply_handler_data_free (ReplyHandlerData *data)
1023 {
1024   if (!data)
1025     return;
1026
1027   if (data->timeout_added)
1028     _dbus_connection_remove_timeout_locked (data->connection,
1029                                             data->timeout);
1030
1031   if (data->connection_added)
1032     _dbus_message_handler_remove_connection (data->handler,
1033                                              data->connection);
1034
1035   if (data->timeout_link)
1036     {
1037       dbus_message_unref ((DBusMessage *)data->timeout_link->data);
1038       _dbus_list_free_link (data->timeout_link);
1039     }
1040   
1041   dbus_message_handler_unref (data->handler);
1042   
1043   dbus_free (data);
1044 }
1045
1046 /**
1047  * Queues a message to send, as with dbus_connection_send_message(),
1048  * but also sets up a DBusMessageHandler to receive a reply to the
1049  * message. If no reply is received in the given timeout_milliseconds,
1050  * expires the pending reply and sends the DBusMessageHandler a
1051  * synthetic error reply (generated in-process, not by the remote
1052  * application) indicating that a timeout occurred.
1053  *
1054  * Reply handlers see their replies after message filters see them,
1055  * but before message handlers added with
1056  * dbus_connection_register_handler() see them, regardless of the
1057  * reply message's name. Reply handlers are only handed a single
1058  * message as a reply, after one reply has been seen the handler is
1059  * removed. If a filter filters out the reply before the handler sees
1060  * it, the reply is immediately timed out and a timeout error reply is
1061  * generated. If a filter removes the timeout error reply then the
1062  * reply handler will never be called. Filters should not do this.
1063  * 
1064  * If #NULL is passed for the reply_handler, the timeout reply will
1065  * still be generated and placed into the message queue, but no
1066  * specific message handler will receive the reply.
1067  *
1068  * If -1 is passed for the timeout, a sane default timeout is used. -1
1069  * is typically the best value for the timeout for this reason, unless
1070  * you want a very short or very long timeout.  There is no way to
1071  * avoid a timeout entirely, other than passing INT_MAX for the
1072  * timeout to postpone it indefinitely.
1073  *
1074  * @todo I think we should rename this function family
1075  * dbus_connection_send(), send_with_reply(), etc. (i.e.
1076  * drop the "message" part), the names are too long.
1077  * 
1078  * @param connection the connection
1079  * @param message the message to send
1080  * @param reply_handler message handler expecting the reply, or #NULL
1081  * @param timeout_milliseconds timeout in milliseconds or -1 for default
1082  * @param result return location for result code
1083  * @returns #TRUE if the message is successfully queued, #FALSE if no memory.
1084  *
1085  */
1086 dbus_bool_t
1087 dbus_connection_send_message_with_reply (DBusConnection     *connection,
1088                                          DBusMessage        *message,
1089                                          DBusMessageHandler *reply_handler,
1090                                          int                 timeout_milliseconds,
1091                                          DBusResultCode     *result)
1092 {
1093   DBusTimeout *timeout;
1094   ReplyHandlerData *data;
1095   DBusMessage *reply;
1096   DBusList *reply_link;
1097   dbus_int32_t serial = -1;
1098   
1099   if (timeout_milliseconds == -1)
1100     timeout_milliseconds = DEFAULT_TIMEOUT_VALUE;
1101
1102   data = dbus_new0 (ReplyHandlerData, 1);
1103
1104   if (!data)
1105     {
1106       dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
1107       return FALSE;
1108     }
1109   
1110   timeout = _dbus_timeout_new (timeout_milliseconds, reply_handler_timeout,
1111                                data, NULL);
1112
1113   if (!timeout)
1114     {
1115       reply_handler_data_free (data);
1116       dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
1117       return FALSE;
1118     }
1119
1120   dbus_mutex_lock (connection->mutex);
1121   
1122   /* Add timeout */
1123   if (!_dbus_connection_add_timeout (connection, timeout))
1124     {
1125       reply_handler_data_free (data);
1126       _dbus_timeout_unref (timeout);
1127       dbus_mutex_unlock (connection->mutex);
1128       
1129       dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
1130       return FALSE;
1131     }
1132
1133   /* The connection now owns the reference to the timeout. */
1134   _dbus_timeout_unref (timeout);
1135   
1136   data->timeout_added = TRUE;
1137   data->timeout = timeout;
1138   data->connection = connection;
1139   
1140   if (!_dbus_message_handler_add_connection (reply_handler, connection))
1141     {
1142       dbus_mutex_unlock (connection->mutex);
1143       reply_handler_data_free (data);
1144       
1145       dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
1146       return FALSE;
1147     }
1148   data->connection_added = TRUE;
1149   
1150   /* Assign a serial to the message */
1151   if (_dbus_message_get_client_serial (message) == -1)
1152     {
1153       serial = _dbus_connection_get_next_client_serial (connection);
1154       _dbus_message_set_client_serial (message, serial);
1155     }
1156
1157   data->handler = reply_handler;
1158   data->serial = serial;
1159
1160   dbus_message_handler_ref (reply_handler);
1161
1162   reply = dbus_message_new_error_reply (message, DBUS_ERROR_NO_REPLY,
1163                                         "No reply within specified time");
1164   if (!reply)
1165     {
1166       dbus_mutex_unlock (connection->mutex);
1167       reply_handler_data_free (data);
1168       
1169       dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
1170       return FALSE;
1171     }
1172
1173   reply_link = _dbus_list_alloc_link (reply);
1174   if (!reply)
1175     {
1176       dbus_mutex_unlock (connection->mutex);
1177       dbus_message_unref (reply);
1178       reply_handler_data_free (data);
1179       
1180       dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
1181       return FALSE;
1182     }
1183
1184   data->timeout_link = reply_link;
1185   
1186   /* Insert the serial in the pending replies hash. */
1187   if (!_dbus_hash_table_insert_int (connection->pending_replies, serial, data))
1188     {
1189       dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
1190       dbus_mutex_unlock (connection->mutex);
1191       reply_handler_data_free (data);
1192       
1193       return FALSE;
1194     }
1195
1196   dbus_mutex_unlock (connection->mutex);
1197   
1198   if (!dbus_connection_send_message (connection, message, NULL, result))
1199     {
1200       /* This will free the handler data too */
1201       _dbus_hash_table_remove_int (connection->pending_replies, serial);
1202       return FALSE;
1203     }
1204
1205   dbus_set_result (result, DBUS_RESULT_SUCCESS);  
1206   return TRUE;
1207 }
1208
1209 /**
1210  * Sends a message and blocks a certain time period while waiting for a reply.
1211  * This function does not dispatch any message handlers until the main loop
1212  * has been reached. This function is used to do non-reentrant "method calls."
1213  * If a reply is received, it is returned, and removed from the incoming
1214  * message queue. If it is not received, #NULL is returned and the
1215  * result is set to #DBUS_RESULT_NO_REPLY. If something else goes
1216  * wrong, result is set to whatever is appropriate, such as
1217  * #DBUS_RESULT_NO_MEMORY.
1218  *
1219  * @todo could use performance improvements (it keeps scanning
1220  * the whole message queue for example) and has thread issues,
1221  * see comments in source
1222  *
1223  * @param connection the connection
1224  * @param message the message to send
1225  * @param timeout_milliseconds timeout in milliseconds or -1 for default
1226  * @param result return location for result code
1227  * @returns the message that is the reply or #NULL with an error code if the
1228  * function fails.
1229  */
1230 DBusMessage *
1231 dbus_connection_send_message_with_reply_and_block (DBusConnection     *connection,
1232                                                    DBusMessage        *message,
1233                                                    int                 timeout_milliseconds,
1234                                                    DBusResultCode     *result)
1235 {
1236   dbus_int32_t client_serial;
1237   DBusList *link;
1238   long start_tv_sec, start_tv_usec;
1239   long end_tv_sec, end_tv_usec;
1240   long tv_sec, tv_usec;
1241
1242   if (timeout_milliseconds == -1)
1243     timeout_milliseconds = DEFAULT_TIMEOUT_VALUE;
1244
1245   /* it would probably seem logical to pass in _DBUS_INT_MAX
1246    * for infinite timeout, but then math below would get
1247    * all overflow-prone, so smack that down.
1248    */
1249   if (timeout_milliseconds > _DBUS_ONE_HOUR_IN_MILLISECONDS * 6)
1250     timeout_milliseconds = _DBUS_ONE_HOUR_IN_MILLISECONDS * 6;
1251   
1252   if (!dbus_connection_send_message (connection, message, &client_serial, result))
1253     return NULL;
1254
1255   message = NULL;
1256   
1257   /* Flush message queue */
1258   dbus_connection_flush (connection);
1259
1260   dbus_mutex_lock (connection->mutex);
1261
1262   _dbus_get_current_time (&start_tv_sec, &start_tv_usec);
1263   end_tv_sec = start_tv_sec + timeout_milliseconds / 1000;
1264   end_tv_usec = start_tv_usec + (timeout_milliseconds % 1000) * 1000;
1265   end_tv_sec += end_tv_usec / _DBUS_USEC_PER_SECOND;
1266   end_tv_usec = end_tv_usec % _DBUS_USEC_PER_SECOND;
1267
1268   _dbus_verbose ("will block %d milliseconds from %ld sec %ld usec to %ld sec %ld usec\n",
1269                  timeout_milliseconds,
1270                  start_tv_sec, start_tv_usec,
1271                  end_tv_sec, end_tv_usec);
1272   
1273   /* Now we wait... */
1274   /* THREAD TODO: This is busted. What if a dispatch_message or pop_message
1275    * gets the message before we do?
1276    */
1277  block_again:  
1278   
1279   _dbus_connection_do_iteration (connection,
1280                                  DBUS_ITERATION_DO_READING |
1281                                  DBUS_ITERATION_BLOCK,
1282                                  timeout_milliseconds);
1283
1284   /* Check if we've gotten a reply */
1285   link = _dbus_list_get_first_link (&connection->incoming_messages);
1286
1287   while (link != NULL)
1288     {
1289       DBusMessage *reply = link->data;
1290
1291       if (_dbus_message_get_reply_serial (reply) == client_serial)
1292         {
1293           _dbus_list_remove (&connection->incoming_messages, link);
1294           dbus_message_ref (reply);
1295
1296           if (result)
1297             *result = DBUS_RESULT_SUCCESS;
1298           
1299           dbus_mutex_unlock (connection->mutex);
1300           return reply;
1301         }
1302       link = _dbus_list_get_next_link (&connection->incoming_messages, link);
1303     }
1304
1305   _dbus_get_current_time (&tv_sec, &tv_usec);
1306   
1307   if (tv_sec < start_tv_sec)
1308     ; /* clock set backward, bail out */
1309   else if (connection->disconnect_message_link == NULL)
1310     ; /* we're disconnected, bail out */
1311   else if (tv_sec < end_tv_sec ||
1312            (tv_sec == end_tv_sec && tv_usec < end_tv_usec))
1313     {
1314       timeout_milliseconds = (end_tv_sec - tv_sec) * 1000 +
1315         (end_tv_usec - tv_usec) / 1000;
1316       _dbus_verbose ("%d milliseconds remain\n", timeout_milliseconds);
1317       _dbus_assert (timeout_milliseconds > 0);
1318
1319       goto block_again; /* not expired yet */
1320     }
1321
1322   if (dbus_connection_get_is_connected (connection))
1323     dbus_set_result (result, DBUS_RESULT_NO_REPLY);
1324   else
1325     dbus_set_result (result, DBUS_RESULT_DISCONNECTED);
1326
1327   dbus_mutex_unlock (connection->mutex);
1328
1329   return NULL;
1330 }
1331
1332 /**
1333  * Blocks until the outgoing message queue is empty.
1334  *
1335  * @param connection the connection.
1336  */
1337 void
1338 dbus_connection_flush (DBusConnection *connection)
1339 {
1340   dbus_mutex_lock (connection->mutex);
1341   while (connection->n_outgoing > 0)
1342     _dbus_connection_do_iteration (connection,
1343                                    DBUS_ITERATION_DO_WRITING |
1344                                    DBUS_ITERATION_BLOCK,
1345                                    -1);
1346   dbus_mutex_unlock (connection->mutex);
1347 }
1348
1349 /**
1350  * Gets the number of messages in the incoming message queue.
1351  *
1352  * @param connection the connection.
1353  * @returns the number of messages in the queue.
1354  */
1355 int
1356 dbus_connection_get_n_messages (DBusConnection *connection)
1357 {
1358   int res;
1359
1360   dbus_mutex_lock (connection->mutex);
1361   res = connection->n_incoming;
1362   dbus_mutex_unlock (connection->mutex);
1363   return res;
1364 }
1365
1366
1367 /* Call with mutex held. Will drop it while waiting and re-acquire
1368  * before returning
1369  */
1370 static void
1371 _dbus_connection_wait_for_borrowed (DBusConnection *connection)
1372 {
1373   _dbus_assert (connection->message_borrowed != NULL);
1374
1375   while (connection->message_borrowed != NULL)
1376     dbus_condvar_wait (connection->message_returned_cond, connection->mutex);
1377 }
1378
1379 /**
1380  * Returns the first-received message from the incoming message queue,
1381  * leaving it in the queue. If the queue is empty, returns #NULL.
1382  * 
1383  * The caller does not own a reference to the returned message, and must
1384  * either return it using dbus_connection_return_message or keep it after
1385  * calling dbus_connection_steal_borrowed_message. No one can get at the
1386  * message while its borrowed, so return it as quickly as possible and
1387  * don't keep a reference to it after returning it. If you need to keep
1388  * the message, make a copy of it.
1389  *
1390  * @param connection the connection.
1391  * @returns next message in the incoming queue.
1392  */
1393 DBusMessage*
1394 dbus_connection_borrow_message  (DBusConnection *connection)
1395 {
1396   DBusMessage *message;
1397
1398   dbus_mutex_lock (connection->mutex);
1399
1400   if (connection->message_borrowed != NULL)
1401     _dbus_connection_wait_for_borrowed (connection);
1402   
1403   message = _dbus_list_get_first (&connection->incoming_messages);
1404
1405   if (message) 
1406     connection->message_borrowed = message;
1407   
1408   dbus_mutex_unlock (connection->mutex);
1409   return message;
1410 }
1411
1412 /**
1413  * @todo docs
1414  */
1415 void
1416 dbus_connection_return_message (DBusConnection *connection,
1417                                 DBusMessage    *message)
1418 {
1419   dbus_mutex_lock (connection->mutex);
1420   
1421   _dbus_assert (message == connection->message_borrowed);
1422   
1423   connection->message_borrowed = NULL;
1424   dbus_condvar_wake_all (connection->message_returned_cond);
1425   
1426   dbus_mutex_unlock (connection->mutex);
1427 }
1428
1429 /**
1430  * @todo docs
1431  */
1432 void
1433 dbus_connection_steal_borrowed_message (DBusConnection *connection,
1434                                         DBusMessage    *message)
1435 {
1436   DBusMessage *pop_message;
1437   
1438   dbus_mutex_lock (connection->mutex);
1439  
1440   _dbus_assert (message == connection->message_borrowed);
1441
1442   pop_message = _dbus_list_pop_first (&connection->incoming_messages);
1443   _dbus_assert (message == pop_message);
1444   
1445   connection->n_incoming -= 1;
1446  
1447   _dbus_verbose ("Incoming message %p stolen from queue, %d incoming\n",
1448                  message, connection->n_incoming);
1449  
1450   connection->message_borrowed = NULL;
1451   dbus_condvar_wake_all (connection->message_returned_cond);
1452   
1453   dbus_mutex_unlock (connection->mutex);
1454 }
1455
1456
1457 /* See dbus_connection_pop_message, but requires the caller to own
1458  * the lock before calling. May drop the lock while running.
1459  */
1460 static DBusMessage*
1461 _dbus_connection_pop_message_unlocked (DBusConnection *connection)
1462 {
1463   if (connection->message_borrowed != NULL)
1464     _dbus_connection_wait_for_borrowed (connection);
1465   
1466   if (connection->n_incoming > 0)
1467     {
1468       DBusMessage *message;
1469
1470       message = _dbus_list_pop_first (&connection->incoming_messages);
1471       connection->n_incoming -= 1;
1472
1473       _dbus_verbose ("Incoming message %p removed from queue, %d incoming\n",
1474                      message, connection->n_incoming);
1475
1476       return message;
1477     }
1478   else
1479     return NULL;
1480 }
1481
1482
1483 /**
1484  * Returns the first-received message from the incoming message queue,
1485  * removing it from the queue. The caller owns a reference to the
1486  * returned message. If the queue is empty, returns #NULL.
1487  *
1488  * @param connection the connection.
1489  * @returns next message in the incoming queue.
1490  */
1491 DBusMessage*
1492 dbus_connection_pop_message (DBusConnection *connection)
1493 {
1494   DBusMessage *message;
1495   dbus_mutex_lock (connection->mutex);
1496
1497   message = _dbus_connection_pop_message_unlocked (connection);
1498   
1499   dbus_mutex_unlock (connection->mutex);
1500   
1501   return message;
1502 }
1503
1504 /**
1505  * Acquire the dispatcher. This must be done before dispatching
1506  * messages in order to guarantee the right order of
1507  * message delivery. May sleep and drop the connection mutex
1508  * while waiting for the dispatcher.
1509  *
1510  * @param connection the connection.
1511  */
1512 static void
1513 _dbus_connection_acquire_dispatch (DBusConnection *connection)
1514 {
1515   dbus_condvar_wait (connection->dispatch_cond, connection->mutex);
1516   _dbus_assert (!connection->dispatch_acquired);
1517
1518   connection->dispatch_acquired = TRUE;
1519 }
1520
1521 /**
1522  * Release the dispatcher when you're done with it. Only call
1523  * after you've acquired the dispatcher. Wakes up at most one
1524  * thread currently waiting to acquire the dispatcher.
1525  *
1526  * @param connection the connection.
1527  */
1528 static void
1529 _dbus_connection_release_dispatch (DBusConnection *connection)
1530 {
1531   _dbus_assert (connection->dispatch_acquired);
1532
1533   connection->dispatch_acquired = FALSE;
1534   dbus_condvar_wake_one (connection->dispatch_cond);
1535 }
1536
1537 static void
1538 _dbus_connection_failed_pop (DBusConnection *connection,
1539                              DBusList *message_link)
1540 {
1541   _dbus_list_prepend_link (&connection->incoming_messages,
1542                            message_link);
1543   connection->n_incoming += 1;
1544 }
1545
1546 /**
1547  * Pops the first-received message from the current incoming message
1548  * queue, runs any handlers for it, then unrefs the message.
1549  *
1550  * @param connection the connection
1551  * @returns #TRUE if the queue is not empty after dispatch
1552  */
1553 dbus_bool_t
1554 dbus_connection_dispatch_message (DBusConnection *connection)
1555 {
1556   DBusMessageHandler *handler;
1557   DBusMessage *message;
1558   DBusList *link, *filter_list_copy, *message_link;
1559   DBusHandlerResult result;
1560   ReplyHandlerData *reply_handler_data;
1561   const char *name;
1562   dbus_int32_t reply_serial;
1563
1564   /* Preallocate link so we can put the message back on failure */
1565   message_link = _dbus_list_alloc_link (NULL);
1566   if (message_link == NULL)
1567     return FALSE;
1568   
1569   dbus_mutex_lock (connection->mutex);
1570
1571   /* We need to ref the connection since the callback could potentially
1572    * drop the last ref to it */
1573   _dbus_connection_ref_unlocked (connection);
1574
1575   _dbus_connection_acquire_dispatch (connection);
1576   
1577   /* This call may drop the lock during the execution (if waiting for
1578    * borrowed messages to be returned) but the order of message
1579    * dispatch if several threads call dispatch_message is still
1580    * protected by the lock, since only one will get the lock, and that
1581    * one will finish the message dispatching
1582    */
1583   message = _dbus_connection_pop_message_unlocked (connection);
1584   if (message == NULL)
1585     {
1586       _dbus_connection_release_dispatch (connection);
1587       dbus_mutex_unlock (connection->mutex);
1588       dbus_connection_unref (connection);
1589       return FALSE;
1590     }
1591   
1592   message_link->data = message;
1593   
1594   result = DBUS_HANDLER_RESULT_ALLOW_MORE_HANDLERS;
1595
1596   reply_serial = _dbus_message_get_reply_serial (message);
1597   reply_handler_data = _dbus_hash_table_lookup_int (connection->pending_replies,
1598                                                     reply_serial);
1599   
1600   if (!_dbus_list_copy (&connection->filter_list, &filter_list_copy))
1601     {
1602       _dbus_connection_release_dispatch (connection);
1603       dbus_mutex_unlock (connection->mutex);
1604       _dbus_connection_failed_pop (connection, message_link);
1605       dbus_connection_unref (connection);
1606       return FALSE;
1607     }
1608   
1609   _dbus_list_foreach (&filter_list_copy,
1610                       (DBusForeachFunction)dbus_message_handler_ref,
1611                       NULL);
1612
1613   /* We're still protected from dispatch_message reentrancy here
1614    * since we acquired the dispatcher
1615    */
1616   dbus_mutex_unlock (connection->mutex);
1617   
1618   link = _dbus_list_get_first_link (&filter_list_copy);
1619   while (link != NULL)
1620     {
1621       DBusMessageHandler *handler = link->data;
1622       DBusList *next = _dbus_list_get_next_link (&filter_list_copy, link);
1623
1624       result = _dbus_message_handler_handle_message (handler, connection,
1625                                                      message);
1626
1627       if (result == DBUS_HANDLER_RESULT_REMOVE_MESSAGE)
1628         break;
1629
1630       link = next;
1631     }
1632
1633   _dbus_list_foreach (&filter_list_copy,
1634                       (DBusForeachFunction)dbus_message_handler_unref,
1635                       NULL);
1636   _dbus_list_clear (&filter_list_copy);
1637   
1638   dbus_mutex_lock (connection->mutex);
1639
1640   /* Did a reply we were waiting on get filtered? */
1641   if (reply_handler_data && result == DBUS_HANDLER_RESULT_REMOVE_MESSAGE)
1642     {
1643       /* Queue the timeout immediately! */
1644       if (reply_handler_data->timeout_link)
1645         {
1646           _dbus_connection_queue_synthesized_message_link (connection,
1647                                                            reply_handler_data->timeout_link);
1648           reply_handler_data->timeout_link = NULL;
1649         }
1650       else
1651         {
1652           /* We already queued the timeout? Then it was filtered! */
1653           _dbus_warn ("The timeout error with reply serial %d was filtered, so the reply handler will never be called.\n", reply_serial);
1654         }
1655     }
1656   
1657   if (result == DBUS_HANDLER_RESULT_REMOVE_MESSAGE)
1658     goto out;
1659
1660   if (reply_handler_data)
1661     {
1662       dbus_mutex_unlock (connection->mutex);
1663       result = _dbus_message_handler_handle_message (reply_handler_data->handler,
1664                                                      connection, message);
1665       reply_handler_data_free (reply_handler_data);
1666       dbus_mutex_lock (connection->mutex);
1667       goto out;
1668     }
1669   
1670   name = dbus_message_get_name (message);
1671   if (name != NULL)
1672     {
1673       handler = _dbus_hash_table_lookup_string (connection->handler_table,
1674                                                 name);
1675       if (handler != NULL)
1676         {
1677           /* We're still protected from dispatch_message reentrancy here
1678            * since we acquired the dispatcher */
1679           dbus_mutex_unlock (connection->mutex);
1680           result = _dbus_message_handler_handle_message (handler, connection,
1681                                                          message);
1682           dbus_mutex_lock (connection->mutex);
1683           if (result == DBUS_HANDLER_RESULT_REMOVE_MESSAGE)
1684             goto out;
1685         }
1686     }
1687
1688  out:
1689   _dbus_connection_release_dispatch (connection);
1690   dbus_mutex_unlock (connection->mutex);
1691   _dbus_list_free_link (message_link);
1692   dbus_connection_unref (connection);
1693   dbus_message_unref (message);
1694   
1695   return connection->n_incoming > 0;
1696 }
1697
1698 /**
1699  * Sets the watch functions for the connection. These functions are
1700  * responsible for making the application's main loop aware of file
1701  * descriptors that need to be monitored for events, using select() or
1702  * poll(). When using Qt, typically the DBusAddWatchFunction would
1703  * create a QSocketNotifier. When using GLib, the DBusAddWatchFunction
1704  * could call g_io_add_watch(), or could be used as part of a more
1705  * elaborate GSource.
1706  *
1707  * The DBusWatch can be queried for the file descriptor to watch using
1708  * dbus_watch_get_fd(), and for the events to watch for using
1709  * dbus_watch_get_flags(). The flags returned by
1710  * dbus_watch_get_flags() will only contain DBUS_WATCH_READABLE and
1711  * DBUS_WATCH_WRITABLE, never DBUS_WATCH_HANGUP or DBUS_WATCH_ERROR;
1712  * all watches implicitly include a watch for hangups, errors, and
1713  * other exceptional conditions.
1714  *
1715  * Once a file descriptor becomes readable or writable, or an exception
1716  * occurs, dbus_connection_handle_watch() should be called to
1717  * notify the connection of the file descriptor's condition.
1718  *
1719  * dbus_connection_handle_watch() cannot be called during the
1720  * DBusAddWatchFunction, as the connection will not be ready to handle
1721  * that watch yet.
1722  * 
1723  * It is not allowed to reference a DBusWatch after it has been passed
1724  * to remove_function.
1725  * 
1726  * @param connection the connection.
1727  * @param add_function function to begin monitoring a new descriptor.
1728  * @param remove_function function to stop monitoring a descriptor.
1729  * @param data data to pass to add_function and remove_function.
1730  * @param free_data_function function to be called to free the data.
1731  */
1732 void
1733 dbus_connection_set_watch_functions (DBusConnection              *connection,
1734                                      DBusAddWatchFunction         add_function,
1735                                      DBusRemoveWatchFunction      remove_function,
1736                                      void                        *data,
1737                                      DBusFreeFunction             free_data_function)
1738 {
1739   dbus_mutex_lock (connection->mutex);
1740   /* ref connection for slightly better reentrancy */
1741   _dbus_connection_ref_unlocked (connection);
1742   
1743   _dbus_watch_list_set_functions (connection->watches,
1744                                   add_function, remove_function,
1745                                   data, free_data_function);
1746   
1747   dbus_mutex_unlock (connection->mutex);
1748   /* drop our paranoid refcount */
1749   dbus_connection_unref (connection);
1750 }
1751
1752 /**
1753  * Sets the timeout functions for the connection. These functions are
1754  * responsible for making the application's main loop aware of timeouts.
1755  * When using Qt, typically the DBusAddTimeoutFunction would create a
1756  * QTimer. When using GLib, the DBusAddTimeoutFunction would call
1757  * g_timeout_add.
1758  *
1759  * The DBusTimeout can be queried for the timer interval using
1760  * dbus_timeout_get_interval.
1761  *
1762  * Once a timeout occurs, dbus_timeout_handle should be called to invoke
1763  * the timeout's callback.
1764  *
1765  * @param connection the connection.
1766  * @param add_function function to add a timeout.
1767  * @param remove_function function to remove a timeout.
1768  * @param data data to pass to add_function and remove_function.
1769  * @param free_data_function function to be called to free the data.
1770  */
1771 void
1772 dbus_connection_set_timeout_functions   (DBusConnection            *connection,
1773                                          DBusAddTimeoutFunction     add_function,
1774                                          DBusRemoveTimeoutFunction  remove_function,
1775                                          void                      *data,
1776                                          DBusFreeFunction           free_data_function)
1777 {
1778   dbus_mutex_lock (connection->mutex);
1779   /* ref connection for slightly better reentrancy */
1780   _dbus_connection_ref_unlocked (connection);
1781   
1782   _dbus_timeout_list_set_functions (connection->timeouts,
1783                                     add_function, remove_function,
1784                                     data, free_data_function);
1785   
1786   dbus_mutex_unlock (connection->mutex);
1787   /* drop our paranoid refcount */
1788   dbus_connection_unref (connection);  
1789 }
1790
1791 /**
1792  * Called to notify the connection when a previously-added watch
1793  * is ready for reading or writing, or has an exception such
1794  * as a hangup.
1795  *
1796  * @param connection the connection.
1797  * @param watch the watch.
1798  * @param condition the current condition of the file descriptors being watched.
1799  */
1800 void
1801 dbus_connection_handle_watch (DBusConnection              *connection,
1802                               DBusWatch                   *watch,
1803                               unsigned int                 condition)
1804 {
1805   dbus_mutex_lock (connection->mutex);
1806   _dbus_connection_acquire_io_path (connection, -1);
1807   _dbus_transport_handle_watch (connection->transport,
1808                                 watch, condition);
1809   _dbus_connection_release_io_path (connection);
1810   dbus_mutex_unlock (connection->mutex);
1811 }
1812
1813 /**
1814  * Adds a message filter. Filters are handlers that are run on
1815  * all incoming messages, prior to the normal handlers
1816  * registered with dbus_connection_register_handler().
1817  * Filters are run in the order that they were added.
1818  * The same handler can be added as a filter more than once, in
1819  * which case it will be run more than once.
1820  * Filters added during a filter callback won't be run on the
1821  * message being processed.
1822  *
1823  * @param connection the connection
1824  * @param handler the handler
1825  * @returns #TRUE on success, #FALSE if not enough memory.
1826  */
1827 dbus_bool_t
1828 dbus_connection_add_filter (DBusConnection      *connection,
1829                             DBusMessageHandler  *handler)
1830 {
1831   dbus_mutex_lock (connection->mutex);
1832   if (!_dbus_message_handler_add_connection (handler, connection))
1833     {
1834       dbus_mutex_unlock (connection->mutex);
1835       return FALSE;
1836     }
1837
1838   if (!_dbus_list_append (&connection->filter_list,
1839                           handler))
1840     {
1841       _dbus_message_handler_remove_connection (handler, connection);
1842       dbus_mutex_unlock (connection->mutex);
1843       return FALSE;
1844     }
1845
1846   dbus_mutex_unlock (connection->mutex);
1847   return TRUE;
1848 }
1849
1850 /**
1851  * Removes a previously-added message filter. It is a programming
1852  * error to call this function for a handler that has not
1853  * been added as a filter. If the given handler was added
1854  * more than once, only one instance of it will be removed
1855  * (the most recently-added instance).
1856  *
1857  * @param connection the connection
1858  * @param handler the handler to remove
1859  *
1860  */
1861 void
1862 dbus_connection_remove_filter (DBusConnection      *connection,
1863                                DBusMessageHandler  *handler)
1864 {
1865   dbus_mutex_lock (connection->mutex);
1866   if (!_dbus_list_remove_last (&connection->filter_list, handler))
1867     {
1868       _dbus_warn ("Tried to remove a DBusConnection filter that had not been added\n");
1869       dbus_mutex_unlock (connection->mutex);
1870       return;
1871     }
1872
1873   _dbus_message_handler_remove_connection (handler, connection);
1874
1875   dbus_mutex_unlock (connection->mutex);
1876 }
1877
1878 /**
1879  * Registers a handler for a list of message names. A single handler
1880  * can be registered for any number of message names, but each message
1881  * name can only have one handler at a time. It's not allowed to call
1882  * this function with the name of a message that already has a
1883  * handler. If the function returns #FALSE, the handlers were not
1884  * registered due to lack of memory.
1885  *
1886  * @todo the messages_to_handle arg may be more convenient if it's a
1887  * single string instead of an array. Though right now MessageHandler
1888  * is sort of designed to say be associated with an entire object with
1889  * multiple methods, that's why for example the connection only
1890  * weakrefs it.  So maybe the "manual" API should be different.
1891  * 
1892  * @param connection the connection
1893  * @param handler the handler
1894  * @param messages_to_handle the messages to handle
1895  * @param n_messages the number of message names in messages_to_handle
1896  * @returns #TRUE on success, #FALSE if no memory or another handler already exists
1897  * 
1898  **/
1899 dbus_bool_t
1900 dbus_connection_register_handler (DBusConnection     *connection,
1901                                   DBusMessageHandler *handler,
1902                                   const char        **messages_to_handle,
1903                                   int                 n_messages)
1904 {
1905   int i;
1906
1907   dbus_mutex_lock (connection->mutex);
1908   i = 0;
1909   while (i < n_messages)
1910     {
1911       DBusHashIter iter;
1912       char *key;
1913
1914       key = _dbus_strdup (messages_to_handle[i]);
1915       if (key == NULL)
1916         goto failed;
1917       
1918       if (!_dbus_hash_iter_lookup (connection->handler_table,
1919                                    key, TRUE,
1920                                    &iter))
1921         {
1922           dbus_free (key);
1923           goto failed;
1924         }
1925
1926       if (_dbus_hash_iter_get_value (&iter) != NULL)
1927         {
1928           _dbus_warn ("Bug in application: attempted to register a second handler for %s\n",
1929                       messages_to_handle[i]);
1930           dbus_free (key); /* won't have replaced the old key with the new one */
1931           goto failed;
1932         }
1933
1934       if (!_dbus_message_handler_add_connection (handler, connection))
1935         {
1936           _dbus_hash_iter_remove_entry (&iter);
1937           /* key has freed on nuking the entry */
1938           goto failed;
1939         }
1940       
1941       _dbus_hash_iter_set_value (&iter, handler);
1942
1943       ++i;
1944     }
1945   
1946   dbus_mutex_unlock (connection->mutex);
1947   return TRUE;
1948   
1949  failed:
1950   /* unregister everything registered so far,
1951    * so we don't fail partially
1952    */
1953   dbus_connection_unregister_handler (connection,
1954                                       handler,
1955                                       messages_to_handle,
1956                                       i);
1957
1958   dbus_mutex_unlock (connection->mutex);
1959   return FALSE;
1960 }
1961
1962 /**
1963  * Unregisters a handler for a list of message names. The handlers
1964  * must have been previously registered.
1965  *
1966  * @param connection the connection
1967  * @param handler the handler
1968  * @param messages_to_handle the messages to handle
1969  * @param n_messages the number of message names in messages_to_handle
1970  * 
1971  **/
1972 void
1973 dbus_connection_unregister_handler (DBusConnection     *connection,
1974                                     DBusMessageHandler *handler,
1975                                     const char        **messages_to_handle,
1976                                     int                 n_messages)
1977 {
1978   int i;
1979
1980   dbus_mutex_lock (connection->mutex);
1981   i = 0;
1982   while (i < n_messages)
1983     {
1984       DBusHashIter iter;
1985
1986       if (!_dbus_hash_iter_lookup (connection->handler_table,
1987                                    (char*) messages_to_handle[i], FALSE,
1988                                    &iter))
1989         {
1990           _dbus_warn ("Bug in application: attempted to unregister handler for %s which was not registered\n",
1991                       messages_to_handle[i]);
1992         }
1993       else if (_dbus_hash_iter_get_value (&iter) != handler)
1994         {
1995           _dbus_warn ("Bug in application: attempted to unregister handler for %s which was registered by a different handler\n",
1996                       messages_to_handle[i]);
1997         }
1998       else
1999         {
2000           _dbus_hash_iter_remove_entry (&iter);
2001           _dbus_message_handler_remove_connection (handler, connection);
2002         }
2003
2004       ++i;
2005     }
2006
2007   dbus_mutex_unlock (connection->mutex);
2008 }
2009
2010 static DBusDataSlotAllocator slot_allocator;
2011
2012 /**
2013  * Initialize the mutex used for #DBusConnection data
2014  * slot reservations.
2015  *
2016  * @returns the mutex
2017  */
2018 DBusMutex *
2019 _dbus_connection_slots_init_lock (void)
2020 {
2021   if (!_dbus_data_slot_allocator_init (&slot_allocator))
2022     return NULL;
2023   else
2024     return slot_allocator.lock;
2025 }
2026
2027 /**
2028  * Allocates an integer ID to be used for storing application-specific
2029  * data on any DBusConnection. The allocated ID may then be used
2030  * with dbus_connection_set_data() and dbus_connection_get_data().
2031  * If allocation fails, -1 is returned. Again, the allocated
2032  * slot is global, i.e. all DBusConnection objects will
2033  * have a slot with the given integer ID reserved.
2034  *
2035  * @returns -1 on failure, otherwise the data slot ID
2036  */
2037 int
2038 dbus_connection_allocate_data_slot (void)
2039 {
2040   return _dbus_data_slot_allocator_alloc (&slot_allocator);
2041 }
2042
2043 /**
2044  * Deallocates a global ID for connection data slots.
2045  * dbus_connection_get_data() and dbus_connection_set_data()
2046  * may no longer be used with this slot.
2047  * Existing data stored on existing DBusConnection objects
2048  * will be freed when the connection is finalized,
2049  * but may not be retrieved (and may only be replaced
2050  * if someone else reallocates the slot).
2051  *
2052  * @param slot the slot to deallocate
2053  */
2054 void
2055 dbus_connection_free_data_slot (int slot)
2056 {
2057   _dbus_data_slot_allocator_free (&slot_allocator, slot);
2058 }
2059
2060 /**
2061  * Stores a pointer on a DBusConnection, along
2062  * with an optional function to be used for freeing
2063  * the data when the data is set again, or when
2064  * the connection is finalized. The slot number
2065  * must have been allocated with dbus_connection_allocate_data_slot().
2066  *
2067  * @param connection the connection
2068  * @param slot the slot number
2069  * @param data the data to store
2070  * @param free_data_func finalizer function for the data
2071  * @returns #TRUE if there was enough memory to store the data
2072  */
2073 dbus_bool_t
2074 dbus_connection_set_data (DBusConnection   *connection,
2075                           int               slot,
2076                           void             *data,
2077                           DBusFreeFunction  free_data_func)
2078 {
2079   DBusFreeFunction old_free_func;
2080   void *old_data;
2081   dbus_bool_t retval;
2082   
2083   dbus_mutex_lock (connection->mutex);
2084
2085   retval = _dbus_data_slot_list_set (&slot_allocator,
2086                                      &connection->slot_list,
2087                                      slot, data, free_data_func,
2088                                      &old_free_func, &old_data);
2089   
2090   dbus_mutex_unlock (connection->mutex);
2091
2092   if (retval)
2093     {
2094       /* Do the actual free outside the connection lock */
2095       if (old_free_func)
2096         (* old_free_func) (old_data);
2097     }
2098
2099   return retval;
2100 }
2101
2102 /**
2103  * Retrieves data previously set with dbus_connection_set_data().
2104  * The slot must still be allocated (must not have been freed).
2105  *
2106  * @param connection the connection
2107  * @param slot the slot to get data from
2108  * @returns the data, or #NULL if not found
2109  */
2110 void*
2111 dbus_connection_get_data (DBusConnection   *connection,
2112                           int               slot)
2113 {
2114   void *res;
2115   
2116   dbus_mutex_lock (connection->mutex);
2117
2118   res = _dbus_data_slot_list_get (&slot_allocator,
2119                                   &connection->slot_list,
2120                                   slot);
2121   
2122   dbus_mutex_unlock (connection->mutex);
2123
2124   return res;
2125 }
2126
2127 /**
2128  * This function sets a global flag for whether dbus_connection_new()
2129  * will set SIGPIPE behavior to SIG_IGN.
2130  *
2131  * @param will_modify_sigpipe #TRUE to allow sigpipe to be set to SIG_IGN
2132  */
2133 void
2134 dbus_connection_set_change_sigpipe (dbus_bool_t will_modify_sigpipe)
2135 {
2136   _dbus_modify_sigpipe = will_modify_sigpipe;
2137 }
2138
2139 /**
2140  * Specifies the maximum size message this connection is allowed to
2141  * receive. Larger messages will result in disconnecting the
2142  * connection.
2143  * 
2144  * @param connection a #DBusConnection
2145  * @param size maximum message size the connection can receive, in bytes
2146  */
2147 void
2148 dbus_connection_set_max_message_size (DBusConnection *connection,
2149                                       long            size)
2150 {
2151   dbus_mutex_lock (connection->mutex);
2152   _dbus_transport_set_max_message_size (connection->transport,
2153                                         size);
2154   dbus_mutex_unlock (connection->mutex);
2155 }
2156
2157 /**
2158  * Gets the value set by dbus_connection_set_max_message_size().
2159  *
2160  * @param connection the connection
2161  * @returns the max size of a single message
2162  */
2163 long
2164 dbus_connection_get_max_message_size (DBusConnection *connection)
2165 {
2166   long res;
2167   dbus_mutex_lock (connection->mutex);
2168   res = _dbus_transport_get_max_message_size (connection->transport);
2169   dbus_mutex_unlock (connection->mutex);
2170   return res;
2171 }
2172
2173 /**
2174  * Sets the maximum total number of bytes that can be used for all messages
2175  * received on this connection. Messages count toward the maximum until
2176  * they are finalized. When the maximum is reached, the connection will
2177  * not read more data until some messages are finalized.
2178  *
2179  * The semantics of the maximum are: if outstanding messages are
2180  * already above the maximum, additional messages will not be read.
2181  * The semantics are not: if the next message would cause us to exceed
2182  * the maximum, we don't read it. The reason is that we don't know the
2183  * size of a message until after we read it.
2184  *
2185  * Thus, the max live messages size can actually be exceeded
2186  * by up to the maximum size of a single message.
2187  * 
2188  * Also, if we read say 1024 bytes off the wire in a single read(),
2189  * and that contains a half-dozen small messages, we may exceed the
2190  * size max by that amount. But this should be inconsequential.
2191  *
2192  * @param connection the connection
2193  * @param size the maximum size in bytes of all outstanding messages
2194  */
2195 void
2196 dbus_connection_set_max_live_messages_size (DBusConnection *connection,
2197                                             long            size)
2198 {
2199   dbus_mutex_lock (connection->mutex);
2200   _dbus_transport_set_max_live_messages_size (connection->transport,
2201                                               size);
2202   dbus_mutex_unlock (connection->mutex);
2203 }
2204
2205 /**
2206  * Gets the value set by dbus_connection_set_max_live_messages_size().
2207  *
2208  * @param connection the connection
2209  * @returns the max size of all live messages
2210  */
2211 long
2212 dbus_connection_get_max_live_messages_size (DBusConnection *connection)
2213 {
2214   long res;
2215   dbus_mutex_lock (connection->mutex);
2216   res = _dbus_transport_get_max_live_messages_size (connection->transport);
2217   dbus_mutex_unlock (connection->mutex);
2218   return res;
2219 }
2220
2221 /** @} */