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