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