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