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