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