6f38d141c6743439f01bdc783b1afe4cfd5de052
[platform/upstream/dbus.git] / dbus / dbus-connection.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-connection.c DBusConnection object
3  *
4  * Copyright (C) 2002-2006  Red Hat Inc.
5  *
6  * Licensed under the Academic Free License version 2.1
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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
21  *
22  */
23
24 #include <config.h>
25 #include "dbus-shared.h"
26 #include "dbus-connection.h"
27 #include "dbus-list.h"
28 #include "dbus-timeout.h"
29 #include "dbus-transport.h"
30 #include "dbus-watch.h"
31 #include "dbus-connection-internal.h"
32 #include "dbus-pending-call-internal.h"
33 #include "dbus-list.h"
34 #include "dbus-hash.h"
35 #include "dbus-message-internal.h"
36 #include "dbus-message-private.h"
37 #include "dbus-threads.h"
38 #include "dbus-protocol.h"
39 #include "dbus-dataslot.h"
40 #include "dbus-string.h"
41 #include "dbus-pending-call.h"
42 #include "dbus-object-tree.h"
43 #include "dbus-threads-internal.h"
44 #include "dbus-bus.h"
45 #include "dbus-marshal-basic.h"
46
47 #ifdef DBUS_DISABLE_CHECKS
48 #define TOOK_LOCK_CHECK(connection)
49 #define RELEASING_LOCK_CHECK(connection)
50 #define HAVE_LOCK_CHECK(connection)
51 #else
52 #define TOOK_LOCK_CHECK(connection) do {                \
53     _dbus_assert (!(connection)->have_connection_lock); \
54     (connection)->have_connection_lock = TRUE;          \
55   } while (0)
56 #define RELEASING_LOCK_CHECK(connection) do {            \
57     _dbus_assert ((connection)->have_connection_lock);   \
58     (connection)->have_connection_lock = FALSE;          \
59   } while (0)
60 #define HAVE_LOCK_CHECK(connection)        _dbus_assert ((connection)->have_connection_lock)
61 /* A "DO_NOT_HAVE_LOCK_CHECK" is impossible since we need the lock to check the flag */
62 #endif
63
64 #define TRACE_LOCKS 1
65
66 #define CONNECTION_LOCK(connection)   do {                                      \
67     if (TRACE_LOCKS) { _dbus_verbose ("LOCK\n"); }   \
68     _dbus_mutex_lock ((connection)->mutex);                                      \
69     TOOK_LOCK_CHECK (connection);                                               \
70   } while (0)
71
72 #define CONNECTION_UNLOCK(connection) do {                                              \
73     if (TRACE_LOCKS) { _dbus_verbose ("UNLOCK\n");  }        \
74     RELEASING_LOCK_CHECK (connection);                                                  \
75     _dbus_mutex_unlock ((connection)->mutex);                                            \
76   } while (0)
77
78 #define SLOTS_LOCK(connection) do {                     \
79     _dbus_mutex_lock ((connection)->slot_mutex);        \
80   } while (0)
81
82 #define SLOTS_UNLOCK(connection) do {                   \
83     _dbus_mutex_unlock ((connection)->slot_mutex);      \
84   } while (0)
85
86 #define DISPATCH_STATUS_NAME(s)                                            \
87                      ((s) == DBUS_DISPATCH_COMPLETE ? "complete" :         \
88                       (s) == DBUS_DISPATCH_DATA_REMAINS ? "data remains" : \
89                       (s) == DBUS_DISPATCH_NEED_MEMORY ? "need memory" :   \
90                       "???")
91
92 /**
93  * @defgroup DBusConnection DBusConnection
94  * @ingroup  DBus
95  * @brief Connection to another application
96  *
97  * A DBusConnection represents a connection to another
98  * application. Messages can be sent and received via this connection.
99  * The other application may be a message bus; for convenience, the
100  * function dbus_bus_get() is provided to automatically open a
101  * connection to the well-known message buses.
102  * 
103  * In brief a DBusConnection is a message queue associated with some
104  * message transport mechanism such as a socket.  The connection
105  * maintains a queue of incoming messages and a queue of outgoing
106  * messages.
107  *
108  * Several functions use the following terms:
109  * <ul>
110  * <li><b>read</b> means to fill the incoming message queue by reading from the socket</li>
111  * <li><b>write</b> means to drain the outgoing queue by writing to the socket</li>
112  * <li><b>dispatch</b> means to drain the incoming queue by invoking application-provided message handlers</li>
113  * </ul>
114  *
115  * The function dbus_connection_read_write_dispatch() for example does all
116  * three of these things, offering a simple alternative to a main loop.
117  *
118  * In an application with a main loop, the read/write/dispatch
119  * operations are usually separate.
120  *
121  * The connection provides #DBusWatch and #DBusTimeout objects to
122  * the main loop. These are used to know when reading, writing, or
123  * dispatching should be performed.
124  * 
125  * Incoming messages are processed
126  * by calling dbus_connection_dispatch(). dbus_connection_dispatch()
127  * runs any handlers registered for the topmost message in the message
128  * queue, then discards the message, then returns.
129  * 
130  * dbus_connection_get_dispatch_status() indicates whether
131  * messages are currently in the queue that need dispatching.
132  * dbus_connection_set_dispatch_status_function() allows
133  * you to set a function to be used to monitor the dispatch status.
134  * 
135  * If you're using GLib or Qt add-on libraries for D-Bus, there are
136  * special convenience APIs in those libraries that hide
137  * all the details of dispatch and watch/timeout monitoring.
138  * For example, dbus_connection_setup_with_g_main().
139  *
140  * If you aren't using these add-on libraries, but want to process
141  * messages asynchronously, you must manually call
142  * dbus_connection_set_dispatch_status_function(),
143  * dbus_connection_set_watch_functions(),
144  * dbus_connection_set_timeout_functions() providing appropriate
145  * functions to integrate the connection with your application's main
146  * loop. This can be tricky to get right; main loops are not simple.
147  *
148  * If you don't need to be asynchronous, you can ignore #DBusWatch,
149  * #DBusTimeout, and dbus_connection_dispatch().  Instead,
150  * dbus_connection_read_write_dispatch() can be used.
151  *
152  * Or, in <em>very</em> simple applications,
153  * dbus_connection_pop_message() may be all you need, allowing you to
154  * avoid setting up any handler functions (see
155  * dbus_connection_add_filter(),
156  * dbus_connection_register_object_path() for more on handlers).
157  * 
158  * When you use dbus_connection_send() or one of its variants to send
159  * a message, the message is added to the outgoing queue.  It's
160  * actually written to the network later; either in
161  * dbus_watch_handle() invoked by your main loop, or in
162  * dbus_connection_flush() which blocks until it can write out the
163  * entire outgoing queue. The GLib/Qt add-on libraries again
164  * handle the details here for you by setting up watch functions.
165  *
166  * When a connection is disconnected, you are guaranteed to get a
167  * signal "Disconnected" from the interface
168  * #DBUS_INTERFACE_LOCAL, path
169  * #DBUS_PATH_LOCAL.
170  *
171  * You may not drop the last reference to a #DBusConnection
172  * until that connection has been disconnected.
173  *
174  * You may dispatch the unprocessed incoming message queue even if the
175  * connection is disconnected. However, "Disconnected" will always be
176  * the last message in the queue (obviously no messages are received
177  * after disconnection).
178  *
179  * After calling dbus_threads_init(), #DBusConnection has thread
180  * locks and drops them when invoking user callbacks, so in general is
181  * transparently threadsafe. However, #DBusMessage does NOT have
182  * thread locks; you must not send the same message to multiple
183  * #DBusConnection if those connections will be used from different threads,
184  * for example.
185  *
186  * Also, if you dispatch or pop messages from multiple threads, it
187  * may work in the sense that it won't crash, but it's tough to imagine
188  * sane results; it will be completely unpredictable which messages
189  * go to which threads.
190  *
191  * It's recommended to dispatch from a single thread.
192  *
193  * The most useful function to call from multiple threads at once
194  * is dbus_connection_send_with_reply_and_block(). That is,
195  * multiple threads can make method calls at the same time.
196  *
197  * If you aren't using threads, you can use a main loop and
198  * dbus_pending_call_set_notify() to achieve a similar result.
199  */
200
201 /**
202  * @defgroup DBusConnectionInternals DBusConnection implementation details
203  * @ingroup  DBusInternals
204  * @brief Implementation details of DBusConnection
205  *
206  * @{
207  */
208
209 /**
210  * Internal struct representing a message filter function 
211  */
212 typedef struct DBusMessageFilter DBusMessageFilter;
213
214 /**
215  * Internal struct representing a message filter function 
216  */
217 struct DBusMessageFilter
218 {
219   DBusAtomic refcount; /**< Reference count */
220   DBusHandleMessageFunction function; /**< Function to call to filter */
221   void *user_data; /**< User data for the function */
222   DBusFreeFunction free_user_data_function; /**< Function to free the user data */
223 };
224
225
226 /**
227  * Internals of DBusPreallocatedSend
228  */
229 struct DBusPreallocatedSend
230 {
231   DBusConnection *connection; /**< Connection we'd send the message to */
232   DBusList *queue_link;       /**< Preallocated link in the queue */
233   DBusList *counter_link;     /**< Preallocated link in the resource counter */
234 };
235
236 #ifdef HAVE_DECL_MSG_NOSIGNAL
237 static dbus_bool_t _dbus_modify_sigpipe = FALSE;
238 #else
239 static dbus_bool_t _dbus_modify_sigpipe = TRUE;
240 #endif
241
242 /**
243  * Implementation details of DBusConnection. All fields are private.
244  */
245 struct DBusConnection
246 {
247   DBusAtomic refcount; /**< Reference count. */
248
249   DBusMutex *mutex; /**< Lock on the entire DBusConnection */
250
251   DBusMutex *dispatch_mutex;     /**< Protects dispatch_acquired */
252   DBusCondVar *dispatch_cond;    /**< Notify when dispatch_acquired is available */
253   DBusMutex *io_path_mutex;      /**< Protects io_path_acquired */
254   DBusCondVar *io_path_cond;     /**< Notify when io_path_acquired is available */
255   
256   DBusList *outgoing_messages; /**< Queue of messages we need to send, send the end of the list first. */
257   DBusList *incoming_messages; /**< Queue of messages we have received, end of the list received most recently. */
258
259   DBusMessage *message_borrowed; /**< Filled in if the first incoming message has been borrowed;
260                                   *   dispatch_acquired will be set by the borrower
261                                   */
262   
263   int n_outgoing;              /**< Length of outgoing queue. */
264   int n_incoming;              /**< Length of incoming queue. */
265
266   DBusCounter *outgoing_counter; /**< Counts size of outgoing messages. */
267   
268   DBusTransport *transport;    /**< Object that sends/receives messages over network. */
269   DBusWatchList *watches;      /**< Stores active watches. */
270   DBusTimeoutList *timeouts;   /**< Stores active timeouts. */
271   
272   DBusList *filter_list;        /**< List of filters. */
273
274   DBusMutex *slot_mutex;        /**< Lock on slot_list so overall connection lock need not be taken */
275   DBusDataSlotList slot_list;   /**< Data stored by allocated integer ID */
276
277   DBusHashTable *pending_replies;  /**< Hash of message serials to #DBusPendingCall. */  
278   
279   dbus_uint32_t client_serial;       /**< Client serial. Increments each time a message is sent  */
280   DBusList *disconnect_message_link; /**< Preallocated list node for queueing the disconnection message */
281
282   DBusWakeupMainFunction wakeup_main_function; /**< Function to wake up the mainloop  */
283   void *wakeup_main_data; /**< Application data for wakeup_main_function */
284   DBusFreeFunction free_wakeup_main_data; /**< free wakeup_main_data */
285
286   DBusDispatchStatusFunction dispatch_status_function; /**< Function on dispatch status changes  */
287   void *dispatch_status_data; /**< Application data for dispatch_status_function */
288   DBusFreeFunction free_dispatch_status_data; /**< free dispatch_status_data */
289
290   DBusDispatchStatus last_dispatch_status; /**< The last dispatch status we reported to the application. */
291
292   DBusList *link_cache; /**< A cache of linked list links to prevent contention
293                          *   for the global linked list mempool lock
294                          */
295   DBusObjectTree *objects; /**< Object path handlers registered with this connection */
296
297   char *server_guid; /**< GUID of server if we are in shared_connections, #NULL if server GUID is unknown or connection is private */
298
299   /* These two MUST be bools and not bitfields, because they are protected by a separate lock
300    * from connection->mutex and all bitfields in a word have to be read/written together.
301    * So you can't have a different lock for different bitfields in the same word.
302    */
303   dbus_bool_t dispatch_acquired; /**< Someone has dispatch path (can drain incoming queue) */
304   dbus_bool_t io_path_acquired;  /**< Someone has transport io path (can use the transport to read/write messages) */
305   
306   unsigned int shareable : 1; /**< #TRUE if libdbus owns a reference to the connection and can return it from dbus_connection_open() more than once */
307   
308   unsigned int exit_on_disconnect : 1; /**< If #TRUE, exit after handling disconnect signal */
309
310   unsigned int route_peer_messages : 1; /**< If #TRUE, if org.freedesktop.DBus.Peer messages have a bus name, don't handle them automatically */
311
312   unsigned int disconnected_message_arrived : 1;   /**< We popped or are dispatching the disconnected message.
313                                                     * if the disconnect_message_link is NULL then we queued it, but
314                                                     * this flag is whether it got to the head of the queue.
315                                                     */
316   unsigned int disconnected_message_processed : 1; /**< We did our default handling of the disconnected message,
317                                                     * such as closing the connection.
318                                                     */
319   
320 #ifndef DBUS_DISABLE_CHECKS
321   unsigned int have_connection_lock : 1; /**< Used to check locking */
322 #endif
323   
324 #ifndef DBUS_DISABLE_CHECKS
325   int generation; /**< _dbus_current_generation that should correspond to this connection */
326 #endif 
327 };
328
329 static DBusDispatchStatus _dbus_connection_get_dispatch_status_unlocked      (DBusConnection     *connection);
330 static void               _dbus_connection_update_dispatch_status_and_unlock (DBusConnection     *connection,
331                                                                               DBusDispatchStatus  new_status);
332 static void               _dbus_connection_last_unref                        (DBusConnection     *connection);
333 static void               _dbus_connection_acquire_dispatch                  (DBusConnection     *connection);
334 static void               _dbus_connection_release_dispatch                  (DBusConnection     *connection);
335 static DBusDispatchStatus _dbus_connection_flush_unlocked                    (DBusConnection     *connection);
336 static void               _dbus_connection_close_possibly_shared_and_unlock  (DBusConnection     *connection);
337 static dbus_bool_t        _dbus_connection_get_is_connected_unlocked         (DBusConnection     *connection);
338 static dbus_bool_t        _dbus_connection_peek_for_reply_unlocked           (DBusConnection     *connection,
339                                                                               dbus_uint32_t       client_serial);
340
341 static DBusMessageFilter *
342 _dbus_message_filter_ref (DBusMessageFilter *filter)
343 {
344   _dbus_assert (filter->refcount.value > 0);
345   _dbus_atomic_inc (&filter->refcount);
346
347   return filter;
348 }
349
350 static void
351 _dbus_message_filter_unref (DBusMessageFilter *filter)
352 {
353   _dbus_assert (filter->refcount.value > 0);
354
355   if (_dbus_atomic_dec (&filter->refcount) == 1)
356     {
357       if (filter->free_user_data_function)
358         (* filter->free_user_data_function) (filter->user_data);
359       
360       dbus_free (filter);
361     }
362 }
363
364 /**
365  * Acquires the connection lock.
366  *
367  * @param connection the connection.
368  */
369 void
370 _dbus_connection_lock (DBusConnection *connection)
371 {
372   CONNECTION_LOCK (connection);
373 }
374
375 /**
376  * Releases the connection lock.
377  *
378  * @param connection the connection.
379  */
380 void
381 _dbus_connection_unlock (DBusConnection *connection)
382 {
383   CONNECTION_UNLOCK (connection);
384 }
385
386 /**
387  * Wakes up the main loop if it is sleeping
388  * Needed if we're e.g. queueing outgoing messages
389  * on a thread while the mainloop sleeps.
390  *
391  * @param connection the connection.
392  */
393 static void
394 _dbus_connection_wakeup_mainloop (DBusConnection *connection)
395 {
396   if (connection->wakeup_main_function)
397     (*connection->wakeup_main_function) (connection->wakeup_main_data);
398 }
399
400 #ifdef DBUS_BUILD_TESTS
401 /* For now this function isn't used */
402 /**
403  * Adds a message to the incoming message queue, returning #FALSE
404  * if there's insufficient memory to queue the message.
405  * Does not take over refcount of the message.
406  *
407  * @param connection the connection.
408  * @param message the message to queue.
409  * @returns #TRUE on success.
410  */
411 dbus_bool_t
412 _dbus_connection_queue_received_message (DBusConnection *connection,
413                                          DBusMessage    *message)
414 {
415   DBusList *link;
416
417   link = _dbus_list_alloc_link (message);
418   if (link == NULL)
419     return FALSE;
420
421   dbus_message_ref (message);
422   _dbus_connection_queue_received_message_link (connection, link);
423
424   return TRUE;
425 }
426
427 /**
428  * Gets the locks so we can examine them
429  *
430  * @param connection the connection.
431  * @param mutex_loc return for the location of the main mutex pointer
432  * @param dispatch_mutex_loc return location of the dispatch mutex pointer
433  * @param io_path_mutex_loc return location of the io_path mutex pointer
434  * @param dispatch_cond_loc return location of the dispatch conditional 
435  *        variable pointer
436  * @param io_path_cond_loc return location of the io_path conditional 
437  *        variable pointer
438  */ 
439 void 
440 _dbus_connection_test_get_locks (DBusConnection *connection,
441                                  DBusMutex     **mutex_loc,
442                                  DBusMutex     **dispatch_mutex_loc,
443                                  DBusMutex     **io_path_mutex_loc,
444                                  DBusCondVar   **dispatch_cond_loc,
445                                  DBusCondVar   **io_path_cond_loc)
446 {
447   *mutex_loc = connection->mutex;
448   *dispatch_mutex_loc = connection->dispatch_mutex;
449   *io_path_mutex_loc = connection->io_path_mutex; 
450   *dispatch_cond_loc = connection->dispatch_cond;
451   *io_path_cond_loc = connection->io_path_cond;
452 }
453 #endif
454
455 /**
456  * Adds a message-containing list link to the incoming message queue,
457  * taking ownership of the link and the message's current refcount.
458  * Cannot fail due to lack of memory.
459  *
460  * @param connection the connection.
461  * @param link the message link to queue.
462  */
463 void
464 _dbus_connection_queue_received_message_link (DBusConnection  *connection,
465                                               DBusList        *link)
466 {
467   DBusPendingCall *pending;
468   dbus_uint32_t reply_serial;
469   DBusMessage *message;
470   
471   _dbus_assert (_dbus_transport_get_is_authenticated (connection->transport));
472   
473   _dbus_list_append_link (&connection->incoming_messages,
474                           link);
475   message = link->data;
476
477   /* If this is a reply we're waiting on, remove timeout for it */
478   reply_serial = dbus_message_get_reply_serial (message);
479   if (reply_serial != 0)
480     {
481       pending = _dbus_hash_table_lookup_int (connection->pending_replies,
482                                              reply_serial);
483       if (pending != NULL)
484         {
485           if (_dbus_pending_call_is_timeout_added_unlocked (pending))
486             _dbus_connection_remove_timeout_unlocked (connection,
487                                                       _dbus_pending_call_get_timeout_unlocked (pending));
488
489           _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
490         }
491     }
492   
493   
494
495   connection->n_incoming += 1;
496
497   _dbus_connection_wakeup_mainloop (connection);
498   
499   _dbus_verbose ("Message %p (%s %s %s %s '%s' reply to %u) added to incoming queue %p, %d incoming\n",
500                  message,
501                  dbus_message_type_to_string (dbus_message_get_type (message)),
502                  dbus_message_get_path (message) ?
503                  dbus_message_get_path (message) :
504                  "no path",
505                  dbus_message_get_interface (message) ?
506                  dbus_message_get_interface (message) :
507                  "no interface",
508                  dbus_message_get_member (message) ?
509                  dbus_message_get_member (message) :
510                  "no member",
511                  dbus_message_get_signature (message),
512                  dbus_message_get_reply_serial (message),
513                  connection,
514                  connection->n_incoming);}
515
516 /**
517  * Adds a link + message to the incoming message queue.
518  * Can't fail. Takes ownership of both link and message.
519  *
520  * @param connection the connection.
521  * @param link the list node and message to queue.
522  *
523  */
524 void
525 _dbus_connection_queue_synthesized_message_link (DBusConnection *connection,
526                                                  DBusList *link)
527 {
528   HAVE_LOCK_CHECK (connection);
529   
530   _dbus_list_append_link (&connection->incoming_messages, link);
531
532   connection->n_incoming += 1;
533
534   _dbus_connection_wakeup_mainloop (connection);
535   
536   _dbus_verbose ("Synthesized message %p added to incoming queue %p, %d incoming\n",
537                  link->data, connection, connection->n_incoming);
538 }
539
540
541 /**
542  * Checks whether there are messages in the outgoing message queue.
543  * Called with connection lock held.
544  *
545  * @param connection the connection.
546  * @returns #TRUE if the outgoing queue is non-empty.
547  */
548 dbus_bool_t
549 _dbus_connection_has_messages_to_send_unlocked (DBusConnection *connection)
550 {
551   HAVE_LOCK_CHECK (connection);
552   return connection->outgoing_messages != NULL;
553 }
554
555 /**
556  * Checks whether there are messages in the outgoing message queue.
557  * Use dbus_connection_flush() to block until all outgoing
558  * messages have been written to the underlying transport
559  * (such as a socket).
560  * 
561  * @param connection the connection.
562  * @returns #TRUE if the outgoing queue is non-empty.
563  */
564 dbus_bool_t
565 dbus_connection_has_messages_to_send (DBusConnection *connection)
566 {
567   dbus_bool_t v;
568   
569   _dbus_return_val_if_fail (connection != NULL, FALSE);
570
571   CONNECTION_LOCK (connection);
572   v = _dbus_connection_has_messages_to_send_unlocked (connection);
573   CONNECTION_UNLOCK (connection);
574
575   return v;
576 }
577
578 /**
579  * Gets the next outgoing message. The message remains in the
580  * queue, and the caller does not own a reference to it.
581  *
582  * @param connection the connection.
583  * @returns the message to be sent.
584  */ 
585 DBusMessage*
586 _dbus_connection_get_message_to_send (DBusConnection *connection)
587 {
588   HAVE_LOCK_CHECK (connection);
589   
590   return _dbus_list_get_last (&connection->outgoing_messages);
591 }
592
593 /**
594  * Notifies the connection that a message has been sent, so the
595  * message can be removed from the outgoing queue.
596  * Called with the connection lock held.
597  *
598  * @param connection the connection.
599  * @param message the message that was sent.
600  */
601 void
602 _dbus_connection_message_sent (DBusConnection *connection,
603                                DBusMessage    *message)
604 {
605   DBusList *link;
606
607   HAVE_LOCK_CHECK (connection);
608   
609   /* This can be called before we even complete authentication, since
610    * it's called on disconnect to clean up the outgoing queue.
611    * It's also called as we successfully send each message.
612    */
613   
614   link = _dbus_list_get_last_link (&connection->outgoing_messages);
615   _dbus_assert (link != NULL);
616   _dbus_assert (link->data == message);
617
618   /* Save this link in the link cache */
619   _dbus_list_unlink (&connection->outgoing_messages,
620                      link);
621   _dbus_list_prepend_link (&connection->link_cache, link);
622   
623   connection->n_outgoing -= 1;
624
625   _dbus_verbose ("Message %p (%s %s %s %s '%s') removed from outgoing queue %p, %d left to send\n",
626                  message,
627                  dbus_message_type_to_string (dbus_message_get_type (message)),
628                  dbus_message_get_path (message) ?
629                  dbus_message_get_path (message) :
630                  "no path",
631                  dbus_message_get_interface (message) ?
632                  dbus_message_get_interface (message) :
633                  "no interface",
634                  dbus_message_get_member (message) ?
635                  dbus_message_get_member (message) :
636                  "no member",
637                  dbus_message_get_signature (message),
638                  connection, connection->n_outgoing);
639
640   /* Save this link in the link cache also */
641   _dbus_message_remove_counter (message, connection->outgoing_counter,
642                                 &link);
643   _dbus_list_prepend_link (&connection->link_cache, link);
644   
645   dbus_message_unref (message);
646 }
647
648 /** Function to be called in protected_change_watch() with refcount held */
649 typedef dbus_bool_t (* DBusWatchAddFunction)     (DBusWatchList *list,
650                                                   DBusWatch     *watch);
651 /** Function to be called in protected_change_watch() with refcount held */
652 typedef void        (* DBusWatchRemoveFunction)  (DBusWatchList *list,
653                                                   DBusWatch     *watch);
654 /** Function to be called in protected_change_watch() with refcount held */
655 typedef void        (* DBusWatchToggleFunction)  (DBusWatchList *list,
656                                                   DBusWatch     *watch,
657                                                   dbus_bool_t    enabled);
658
659 static dbus_bool_t
660 protected_change_watch (DBusConnection         *connection,
661                         DBusWatch              *watch,
662                         DBusWatchAddFunction    add_function,
663                         DBusWatchRemoveFunction remove_function,
664                         DBusWatchToggleFunction toggle_function,
665                         dbus_bool_t             enabled)
666 {
667   dbus_bool_t retval;
668
669   HAVE_LOCK_CHECK (connection);
670
671   /* The original purpose of protected_change_watch() was to hold a
672    * ref on the connection while dropping the connection lock, then
673    * calling out to the app.  This was a broken hack that did not
674    * work, since the connection was in a hosed state (no WatchList
675    * field) while calling out.
676    *
677    * So for now we'll just keep the lock while calling out. This means
678    * apps are not allowed to call DBusConnection methods inside a
679    * watch function or they will deadlock.
680    *
681    * The "real fix" is to use the _and_unlock() pattern found
682    * elsewhere in the code, to defer calling out to the app until
683    * we're about to drop locks and return flow of control to the app
684    * anyway.
685    *
686    * See http://lists.freedesktop.org/archives/dbus/2007-July/thread.html#8144
687    */
688
689   if (connection->watches)
690     {
691       if (add_function)
692         retval = (* add_function) (connection->watches, watch);
693       else if (remove_function)
694         {
695           retval = TRUE;
696           (* remove_function) (connection->watches, watch);
697         }
698       else
699         {
700           retval = TRUE;
701           (* toggle_function) (connection->watches, watch, enabled);
702         }
703       return retval;
704     }
705   else
706     return FALSE;
707 }
708      
709
710 /**
711  * Adds a watch using the connection's DBusAddWatchFunction if
712  * available. Otherwise records the watch to be added when said
713  * function is available. Also re-adds the watch if the
714  * DBusAddWatchFunction changes. May fail due to lack of memory.
715  * Connection lock should be held when calling this.
716  *
717  * @param connection the connection.
718  * @param watch the watch to add.
719  * @returns #TRUE on success.
720  */
721 dbus_bool_t
722 _dbus_connection_add_watch_unlocked (DBusConnection *connection,
723                                      DBusWatch      *watch)
724 {
725   return protected_change_watch (connection, watch,
726                                  _dbus_watch_list_add_watch,
727                                  NULL, NULL, FALSE);
728 }
729
730 /**
731  * Removes a watch using the connection's DBusRemoveWatchFunction
732  * if available. It's an error to call this function on a watch
733  * that was not previously added.
734  * Connection lock should be held when calling this.
735  *
736  * @param connection the connection.
737  * @param watch the watch to remove.
738  */
739 void
740 _dbus_connection_remove_watch_unlocked (DBusConnection *connection,
741                                         DBusWatch      *watch)
742 {
743   protected_change_watch (connection, watch,
744                           NULL,
745                           _dbus_watch_list_remove_watch,
746                           NULL, FALSE);
747 }
748
749 /**
750  * Toggles a watch and notifies app via connection's
751  * DBusWatchToggledFunction if available. It's an error to call this
752  * function on a watch that was not previously added.
753  * Connection lock should be held when calling this.
754  *
755  * @param connection the connection.
756  * @param watch the watch to toggle.
757  * @param enabled whether to enable or disable
758  */
759 void
760 _dbus_connection_toggle_watch_unlocked (DBusConnection *connection,
761                                         DBusWatch      *watch,
762                                         dbus_bool_t     enabled)
763 {
764   _dbus_assert (watch != NULL);
765
766   protected_change_watch (connection, watch,
767                           NULL, NULL,
768                           _dbus_watch_list_toggle_watch,
769                           enabled);
770 }
771
772 /** Function to be called in protected_change_timeout() with refcount held */
773 typedef dbus_bool_t (* DBusTimeoutAddFunction)    (DBusTimeoutList *list,
774                                                    DBusTimeout     *timeout);
775 /** Function to be called in protected_change_timeout() with refcount held */
776 typedef void        (* DBusTimeoutRemoveFunction) (DBusTimeoutList *list,
777                                                    DBusTimeout     *timeout);
778 /** Function to be called in protected_change_timeout() with refcount held */
779 typedef void        (* DBusTimeoutToggleFunction) (DBusTimeoutList *list,
780                                                    DBusTimeout     *timeout,
781                                                    dbus_bool_t      enabled);
782
783 static dbus_bool_t
784 protected_change_timeout (DBusConnection           *connection,
785                           DBusTimeout              *timeout,
786                           DBusTimeoutAddFunction    add_function,
787                           DBusTimeoutRemoveFunction remove_function,
788                           DBusTimeoutToggleFunction toggle_function,
789                           dbus_bool_t               enabled)
790 {
791   dbus_bool_t retval;
792
793   HAVE_LOCK_CHECK (connection);
794
795   /* The original purpose of protected_change_timeout() was to hold a
796    * ref on the connection while dropping the connection lock, then
797    * calling out to the app.  This was a broken hack that did not
798    * work, since the connection was in a hosed state (no TimeoutList
799    * field) while calling out.
800    *
801    * So for now we'll just keep the lock while calling out. This means
802    * apps are not allowed to call DBusConnection methods inside a
803    * timeout function or they will deadlock.
804    *
805    * The "real fix" is to use the _and_unlock() pattern found
806    * elsewhere in the code, to defer calling out to the app until
807    * we're about to drop locks and return flow of control to the app
808    * anyway.
809    *
810    * See http://lists.freedesktop.org/archives/dbus/2007-July/thread.html#8144
811    */
812
813   if (connection->timeouts)
814     {
815       if (add_function)
816         retval = (* add_function) (connection->timeouts, timeout);
817       else if (remove_function)
818         {
819           retval = TRUE;
820           (* remove_function) (connection->timeouts, timeout);
821         }
822       else
823         {
824           retval = TRUE;
825           (* toggle_function) (connection->timeouts, timeout, enabled);
826         }
827       return retval;
828     }
829   else
830     return FALSE;
831 }
832
833 /**
834  * Adds a timeout using the connection's DBusAddTimeoutFunction if
835  * available. Otherwise records the timeout to be added when said
836  * function is available. Also re-adds the timeout if the
837  * DBusAddTimeoutFunction changes. May fail due to lack of memory.
838  * The timeout will fire repeatedly until removed.
839  * Connection lock should be held when calling this.
840  *
841  * @param connection the connection.
842  * @param timeout the timeout to add.
843  * @returns #TRUE on success.
844  */
845 dbus_bool_t
846 _dbus_connection_add_timeout_unlocked (DBusConnection *connection,
847                                        DBusTimeout    *timeout)
848 {
849   return protected_change_timeout (connection, timeout,
850                                    _dbus_timeout_list_add_timeout,
851                                    NULL, NULL, FALSE);
852 }
853
854 /**
855  * Removes a timeout using the connection's DBusRemoveTimeoutFunction
856  * if available. It's an error to call this function on a timeout
857  * that was not previously added.
858  * Connection lock should be held when calling this.
859  *
860  * @param connection the connection.
861  * @param timeout the timeout to remove.
862  */
863 void
864 _dbus_connection_remove_timeout_unlocked (DBusConnection *connection,
865                                           DBusTimeout    *timeout)
866 {
867   protected_change_timeout (connection, timeout,
868                             NULL,
869                             _dbus_timeout_list_remove_timeout,
870                             NULL, FALSE);
871 }
872
873 /**
874  * Toggles a timeout and notifies app via connection's
875  * DBusTimeoutToggledFunction if available. It's an error to call this
876  * function on a timeout that was not previously added.
877  * Connection lock should be held when calling this.
878  *
879  * @param connection the connection.
880  * @param timeout the timeout to toggle.
881  * @param enabled whether to enable or disable
882  */
883 void
884 _dbus_connection_toggle_timeout_unlocked (DBusConnection   *connection,
885                                           DBusTimeout      *timeout,
886                                           dbus_bool_t       enabled)
887 {
888   protected_change_timeout (connection, timeout,
889                             NULL, NULL,
890                             _dbus_timeout_list_toggle_timeout,
891                             enabled);
892 }
893
894 static dbus_bool_t
895 _dbus_connection_attach_pending_call_unlocked (DBusConnection  *connection,
896                                                DBusPendingCall *pending)
897 {
898   dbus_uint32_t reply_serial;
899   DBusTimeout *timeout;
900
901   HAVE_LOCK_CHECK (connection);
902
903   reply_serial = _dbus_pending_call_get_reply_serial_unlocked (pending);
904
905   _dbus_assert (reply_serial != 0);
906
907   timeout = _dbus_pending_call_get_timeout_unlocked (pending);
908
909   if (timeout)
910     {
911       if (!_dbus_connection_add_timeout_unlocked (connection, timeout))
912         return FALSE;
913       
914       if (!_dbus_hash_table_insert_int (connection->pending_replies,
915                                         reply_serial,
916                                         pending))
917         {
918           _dbus_connection_remove_timeout_unlocked (connection, timeout);
919
920           _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
921           HAVE_LOCK_CHECK (connection);
922           return FALSE;
923         }
924       
925       _dbus_pending_call_set_timeout_added_unlocked (pending, TRUE);
926     }
927   else
928     {
929       if (!_dbus_hash_table_insert_int (connection->pending_replies,
930                                         reply_serial,
931                                         pending))
932         {
933           HAVE_LOCK_CHECK (connection);
934           return FALSE;
935         }
936     }
937
938   _dbus_pending_call_ref_unlocked (pending);
939
940   HAVE_LOCK_CHECK (connection);
941   
942   return TRUE;
943 }
944
945 static void
946 free_pending_call_on_hash_removal (void *data)
947 {
948   DBusPendingCall *pending;
949   DBusConnection  *connection;
950   
951   if (data == NULL)
952     return;
953
954   pending = data;
955
956   connection = _dbus_pending_call_get_connection_unlocked (pending);
957
958   HAVE_LOCK_CHECK (connection);
959   
960   if (_dbus_pending_call_is_timeout_added_unlocked (pending))
961     {
962       _dbus_connection_remove_timeout_unlocked (connection,
963                                                 _dbus_pending_call_get_timeout_unlocked (pending));
964       
965       _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
966     }
967
968   /* FIXME 1.0? this is sort of dangerous and undesirable to drop the lock 
969    * here, but the pending call finalizer could in principle call out to 
970    * application code so we pretty much have to... some larger code reorg 
971    * might be needed.
972    */
973   _dbus_connection_ref_unlocked (connection);
974   _dbus_pending_call_unref_and_unlock (pending);
975   CONNECTION_LOCK (connection);
976   _dbus_connection_unref_unlocked (connection);
977 }
978
979 static void
980 _dbus_connection_detach_pending_call_unlocked (DBusConnection  *connection,
981                                                DBusPendingCall *pending)
982 {
983   /* This ends up unlocking to call the pending call finalizer, which is unexpected to
984    * say the least.
985    */
986   _dbus_hash_table_remove_int (connection->pending_replies,
987                                _dbus_pending_call_get_reply_serial_unlocked (pending));
988 }
989
990 static void
991 _dbus_connection_detach_pending_call_and_unlock (DBusConnection  *connection,
992                                                  DBusPendingCall *pending)
993 {
994   /* The idea here is to avoid finalizing the pending call
995    * with the lock held, since there's a destroy notifier
996    * in pending call that goes out to application code.
997    *
998    * There's an extra unlock inside the hash table
999    * "free pending call" function FIXME...
1000    */
1001   _dbus_pending_call_ref_unlocked (pending);
1002   _dbus_hash_table_remove_int (connection->pending_replies,
1003                                _dbus_pending_call_get_reply_serial_unlocked (pending));
1004
1005   if (_dbus_pending_call_is_timeout_added_unlocked (pending))
1006       _dbus_connection_remove_timeout_unlocked (connection,
1007               _dbus_pending_call_get_timeout_unlocked (pending));
1008
1009   _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
1010
1011   _dbus_pending_call_unref_and_unlock (pending);
1012 }
1013
1014 /**
1015  * Removes a pending call from the connection, such that
1016  * the pending reply will be ignored. May drop the last
1017  * reference to the pending call.
1018  *
1019  * @param connection the connection
1020  * @param pending the pending call
1021  */
1022 void
1023 _dbus_connection_remove_pending_call (DBusConnection  *connection,
1024                                       DBusPendingCall *pending)
1025 {
1026   CONNECTION_LOCK (connection);
1027   _dbus_connection_detach_pending_call_and_unlock (connection, pending);
1028 }
1029
1030 /**
1031  * Acquire the transporter I/O path. This must be done before
1032  * doing any I/O in the transporter. May sleep and drop the
1033  * IO path mutex while waiting for the I/O path.
1034  *
1035  * @param connection the connection.
1036  * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
1037  * @returns TRUE if the I/O path was acquired.
1038  */
1039 static dbus_bool_t
1040 _dbus_connection_acquire_io_path (DBusConnection *connection,
1041                                   int             timeout_milliseconds)
1042 {
1043   dbus_bool_t we_acquired;
1044   
1045   HAVE_LOCK_CHECK (connection);
1046
1047   /* We don't want the connection to vanish */
1048   _dbus_connection_ref_unlocked (connection);
1049
1050   /* We will only touch io_path_acquired which is protected by our mutex */
1051   CONNECTION_UNLOCK (connection);
1052   
1053   _dbus_verbose ("locking io_path_mutex\n");
1054   _dbus_mutex_lock (connection->io_path_mutex);
1055
1056   _dbus_verbose ("start connection->io_path_acquired = %d timeout = %d\n",
1057                  connection->io_path_acquired, timeout_milliseconds);
1058
1059   we_acquired = FALSE;
1060   
1061   if (connection->io_path_acquired)
1062     {
1063       if (timeout_milliseconds != -1)
1064         {
1065           _dbus_verbose ("waiting %d for IO path to be acquirable\n",
1066                          timeout_milliseconds);
1067
1068           if (!_dbus_condvar_wait_timeout (connection->io_path_cond,
1069                                            connection->io_path_mutex,
1070                                            timeout_milliseconds))
1071             {
1072               /* We timed out before anyone signaled. */
1073               /* (writing the loop to handle the !timedout case by
1074                * waiting longer if needed is a pain since dbus
1075                * wraps pthread_cond_timedwait to take a relative
1076                * time instead of absolute, something kind of stupid
1077                * on our part. for now it doesn't matter, we will just
1078                * end up back here eventually.)
1079                */
1080             }
1081         }
1082       else
1083         {
1084           while (connection->io_path_acquired)
1085             {
1086               _dbus_verbose ("waiting for IO path to be acquirable\n");
1087               _dbus_condvar_wait (connection->io_path_cond, 
1088                                   connection->io_path_mutex);
1089             }
1090         }
1091     }
1092   
1093   if (!connection->io_path_acquired)
1094     {
1095       we_acquired = TRUE;
1096       connection->io_path_acquired = TRUE;
1097     }
1098   
1099   _dbus_verbose ("end connection->io_path_acquired = %d we_acquired = %d\n",
1100                  connection->io_path_acquired, we_acquired);
1101
1102   _dbus_verbose ("unlocking io_path_mutex\n");
1103   _dbus_mutex_unlock (connection->io_path_mutex);
1104
1105   CONNECTION_LOCK (connection);
1106   
1107   HAVE_LOCK_CHECK (connection);
1108
1109   _dbus_connection_unref_unlocked (connection);
1110   
1111   return we_acquired;
1112 }
1113
1114 /**
1115  * Release the I/O path when you're done with it. Only call
1116  * after you've acquired the I/O. Wakes up at most one thread
1117  * currently waiting to acquire the I/O path.
1118  *
1119  * @param connection the connection.
1120  */
1121 static void
1122 _dbus_connection_release_io_path (DBusConnection *connection)
1123 {
1124   HAVE_LOCK_CHECK (connection);
1125   
1126   _dbus_verbose ("locking io_path_mutex\n");
1127   _dbus_mutex_lock (connection->io_path_mutex);
1128   
1129   _dbus_assert (connection->io_path_acquired);
1130
1131   _dbus_verbose ("start connection->io_path_acquired = %d\n",
1132                  connection->io_path_acquired);
1133   
1134   connection->io_path_acquired = FALSE;
1135   _dbus_condvar_wake_one (connection->io_path_cond);
1136
1137   _dbus_verbose ("unlocking io_path_mutex\n");
1138   _dbus_mutex_unlock (connection->io_path_mutex);
1139 }
1140
1141 /**
1142  * Queues incoming messages and sends outgoing messages for this
1143  * connection, optionally blocking in the process. Each call to
1144  * _dbus_connection_do_iteration_unlocked() will call select() or poll() one
1145  * time and then read or write data if possible.
1146  *
1147  * The purpose of this function is to be able to flush outgoing
1148  * messages or queue up incoming messages without returning
1149  * control to the application and causing reentrancy weirdness.
1150  *
1151  * The flags parameter allows you to specify whether to
1152  * read incoming messages, write outgoing messages, or both,
1153  * and whether to block if no immediate action is possible.
1154  *
1155  * The timeout_milliseconds parameter does nothing unless the
1156  * iteration is blocking.
1157  *
1158  * If there are no outgoing messages and DBUS_ITERATION_DO_READING
1159  * wasn't specified, then it's impossible to block, even if
1160  * you specify DBUS_ITERATION_BLOCK; in that case the function
1161  * returns immediately.
1162  *
1163  * If pending is not NULL then a check is made if the pending call
1164  * is completed after the io path has been required. If the call
1165  * has been completed nothing is done. This must be done since
1166  * the _dbus_connection_acquire_io_path releases the connection
1167  * lock for a while.
1168  *
1169  * Called with connection lock held.
1170  * 
1171  * @param connection the connection.
1172  * @param pending the pending call that should be checked or NULL
1173  * @param flags iteration flags.
1174  * @param timeout_milliseconds maximum blocking time, or -1 for no limit.
1175  */
1176 void
1177 _dbus_connection_do_iteration_unlocked (DBusConnection *connection,
1178                                         DBusPendingCall *pending,
1179                                         unsigned int    flags,
1180                                         int             timeout_milliseconds)
1181 {
1182   _dbus_verbose ("start\n");
1183   
1184   HAVE_LOCK_CHECK (connection);
1185   
1186   if (connection->n_outgoing == 0)
1187     flags &= ~DBUS_ITERATION_DO_WRITING;
1188
1189   if (_dbus_connection_acquire_io_path (connection,
1190                                         (flags & DBUS_ITERATION_BLOCK) ? timeout_milliseconds : 0))
1191     {
1192       HAVE_LOCK_CHECK (connection);
1193       
1194       if ( (pending != NULL) && _dbus_pending_call_get_completed_unlocked(pending))
1195         {
1196           _dbus_verbose ("pending call completed while acquiring I/O path");
1197         }
1198       else if ( (pending != NULL) &&
1199                 _dbus_connection_peek_for_reply_unlocked (connection,
1200                                                           _dbus_pending_call_get_reply_serial_unlocked (pending)))
1201         {
1202           _dbus_verbose ("pending call completed while acquiring I/O path (reply found in queue)");
1203         }
1204       else
1205         {
1206           _dbus_transport_do_iteration (connection->transport,
1207                                         flags, timeout_milliseconds);
1208         }
1209
1210       _dbus_connection_release_io_path (connection);
1211     }
1212
1213   HAVE_LOCK_CHECK (connection);
1214
1215   _dbus_verbose ("end\n");
1216 }
1217
1218 /**
1219  * Creates a new connection for the given transport.  A transport
1220  * represents a message stream that uses some concrete mechanism, such
1221  * as UNIX domain sockets. May return #NULL if insufficient
1222  * memory exists to create the connection.
1223  *
1224  * @param transport the transport.
1225  * @returns the new connection, or #NULL on failure.
1226  */
1227 DBusConnection*
1228 _dbus_connection_new_for_transport (DBusTransport *transport)
1229 {
1230   DBusConnection *connection;
1231   DBusWatchList *watch_list;
1232   DBusTimeoutList *timeout_list;
1233   DBusHashTable *pending_replies;
1234   DBusList *disconnect_link;
1235   DBusMessage *disconnect_message;
1236   DBusCounter *outgoing_counter;
1237   DBusObjectTree *objects;
1238   
1239   watch_list = NULL;
1240   connection = NULL;
1241   pending_replies = NULL;
1242   timeout_list = NULL;
1243   disconnect_link = NULL;
1244   disconnect_message = NULL;
1245   outgoing_counter = NULL;
1246   objects = NULL;
1247   
1248   watch_list = _dbus_watch_list_new ();
1249   if (watch_list == NULL)
1250     goto error;
1251
1252   timeout_list = _dbus_timeout_list_new ();
1253   if (timeout_list == NULL)
1254     goto error;  
1255
1256   pending_replies =
1257     _dbus_hash_table_new (DBUS_HASH_INT,
1258                           NULL,
1259                           (DBusFreeFunction)free_pending_call_on_hash_removal);
1260   if (pending_replies == NULL)
1261     goto error;
1262   
1263   connection = dbus_new0 (DBusConnection, 1);
1264   if (connection == NULL)
1265     goto error;
1266
1267   _dbus_mutex_new_at_location (&connection->mutex);
1268   if (connection->mutex == NULL)
1269     goto error;
1270
1271   _dbus_mutex_new_at_location (&connection->io_path_mutex);
1272   if (connection->io_path_mutex == NULL)
1273     goto error;
1274
1275   _dbus_mutex_new_at_location (&connection->dispatch_mutex);
1276   if (connection->dispatch_mutex == NULL)
1277     goto error;
1278   
1279   _dbus_condvar_new_at_location (&connection->dispatch_cond);
1280   if (connection->dispatch_cond == NULL)
1281     goto error;
1282   
1283   _dbus_condvar_new_at_location (&connection->io_path_cond);
1284   if (connection->io_path_cond == NULL)
1285     goto error;
1286
1287   _dbus_mutex_new_at_location (&connection->slot_mutex);
1288   if (connection->slot_mutex == NULL)
1289     goto error;
1290
1291   disconnect_message = dbus_message_new_signal (DBUS_PATH_LOCAL,
1292                                                 DBUS_INTERFACE_LOCAL,
1293                                                 "Disconnected");
1294   
1295   if (disconnect_message == NULL)
1296     goto error;
1297
1298   disconnect_link = _dbus_list_alloc_link (disconnect_message);
1299   if (disconnect_link == NULL)
1300     goto error;
1301
1302   outgoing_counter = _dbus_counter_new ();
1303   if (outgoing_counter == NULL)
1304     goto error;
1305
1306   objects = _dbus_object_tree_new (connection);
1307   if (objects == NULL)
1308     goto error;
1309   
1310   if (_dbus_modify_sigpipe)
1311     _dbus_disable_sigpipe ();
1312   
1313   connection->refcount.value = 1;
1314   connection->transport = transport;
1315   connection->watches = watch_list;
1316   connection->timeouts = timeout_list;
1317   connection->pending_replies = pending_replies;
1318   connection->outgoing_counter = outgoing_counter;
1319   connection->filter_list = NULL;
1320   connection->last_dispatch_status = DBUS_DISPATCH_COMPLETE; /* so we're notified first time there's data */
1321   connection->objects = objects;
1322   connection->exit_on_disconnect = FALSE;
1323   connection->shareable = FALSE;
1324   connection->route_peer_messages = FALSE;
1325   connection->disconnected_message_arrived = FALSE;
1326   connection->disconnected_message_processed = FALSE;
1327   
1328 #ifndef DBUS_DISABLE_CHECKS
1329   connection->generation = _dbus_current_generation;
1330 #endif
1331   
1332   _dbus_data_slot_list_init (&connection->slot_list);
1333
1334   connection->client_serial = 1;
1335
1336   connection->disconnect_message_link = disconnect_link;
1337
1338   CONNECTION_LOCK (connection);
1339   
1340   if (!_dbus_transport_set_connection (transport, connection))
1341     {
1342       CONNECTION_UNLOCK (connection);
1343
1344       goto error;
1345     }
1346
1347   _dbus_transport_ref (transport);
1348
1349   CONNECTION_UNLOCK (connection);
1350   
1351   return connection;
1352   
1353  error:
1354   if (disconnect_message != NULL)
1355     dbus_message_unref (disconnect_message);
1356   
1357   if (disconnect_link != NULL)
1358     _dbus_list_free_link (disconnect_link);
1359   
1360   if (connection != NULL)
1361     {
1362       _dbus_condvar_free_at_location (&connection->io_path_cond);
1363       _dbus_condvar_free_at_location (&connection->dispatch_cond);
1364       _dbus_mutex_free_at_location (&connection->mutex);
1365       _dbus_mutex_free_at_location (&connection->io_path_mutex);
1366       _dbus_mutex_free_at_location (&connection->dispatch_mutex);
1367       _dbus_mutex_free_at_location (&connection->slot_mutex);
1368       dbus_free (connection);
1369     }
1370   if (pending_replies)
1371     _dbus_hash_table_unref (pending_replies);
1372   
1373   if (watch_list)
1374     _dbus_watch_list_free (watch_list);
1375
1376   if (timeout_list)
1377     _dbus_timeout_list_free (timeout_list);
1378
1379   if (outgoing_counter)
1380     _dbus_counter_unref (outgoing_counter);
1381
1382   if (objects)
1383     _dbus_object_tree_unref (objects);
1384   
1385   return NULL;
1386 }
1387
1388 /**
1389  * Increments the reference count of a DBusConnection.
1390  * Requires that the caller already holds the connection lock.
1391  *
1392  * @param connection the connection.
1393  * @returns the connection.
1394  */
1395 DBusConnection *
1396 _dbus_connection_ref_unlocked (DBusConnection *connection)
1397 {  
1398   _dbus_assert (connection != NULL);
1399   _dbus_assert (connection->generation == _dbus_current_generation);
1400
1401   HAVE_LOCK_CHECK (connection);
1402   
1403 #ifdef DBUS_HAVE_ATOMIC_INT
1404   _dbus_atomic_inc (&connection->refcount);
1405 #else
1406   _dbus_assert (connection->refcount.value > 0);
1407   connection->refcount.value += 1;
1408 #endif
1409
1410   return connection;
1411 }
1412
1413 /**
1414  * Decrements the reference count of a DBusConnection.
1415  * Requires that the caller already holds the connection lock.
1416  *
1417  * @param connection the connection.
1418  */
1419 void
1420 _dbus_connection_unref_unlocked (DBusConnection *connection)
1421 {
1422   dbus_bool_t last_unref;
1423
1424   HAVE_LOCK_CHECK (connection);
1425   
1426   _dbus_assert (connection != NULL);
1427
1428   /* The connection lock is better than the global
1429    * lock in the atomic increment fallback
1430    */
1431   
1432 #ifdef DBUS_HAVE_ATOMIC_INT
1433   last_unref = (_dbus_atomic_dec (&connection->refcount) == 1);
1434 #else
1435   _dbus_assert (connection->refcount.value > 0);
1436
1437   connection->refcount.value -= 1;
1438   last_unref = (connection->refcount.value == 0);  
1439 #if 0
1440   printf ("unref_unlocked() connection %p count = %d\n", connection, connection->refcount.value);
1441 #endif
1442 #endif
1443   
1444   if (last_unref)
1445     _dbus_connection_last_unref (connection);
1446 }
1447
1448 static dbus_uint32_t
1449 _dbus_connection_get_next_client_serial (DBusConnection *connection)
1450 {
1451   dbus_uint32_t serial;
1452
1453   serial = connection->client_serial++;
1454
1455   if (connection->client_serial == 0)
1456     connection->client_serial = 1;
1457
1458   return serial;
1459 }
1460
1461 /**
1462  * A callback for use with dbus_watch_new() to create a DBusWatch.
1463  * 
1464  * @todo This is basically a hack - we could delete _dbus_transport_handle_watch()
1465  * and the virtual handle_watch in DBusTransport if we got rid of it.
1466  * The reason this is some work is threading, see the _dbus_connection_handle_watch()
1467  * implementation.
1468  *
1469  * @param watch the watch.
1470  * @param condition the current condition of the file descriptors being watched.
1471  * @param data must be a pointer to a #DBusConnection
1472  * @returns #FALSE if the IO condition may not have been fully handled due to lack of memory
1473  */
1474 dbus_bool_t
1475 _dbus_connection_handle_watch (DBusWatch                   *watch,
1476                                unsigned int                 condition,
1477                                void                        *data)
1478 {
1479   DBusConnection *connection;
1480   dbus_bool_t retval;
1481   DBusDispatchStatus status;
1482
1483   connection = data;
1484
1485   _dbus_verbose ("start\n");
1486   
1487   CONNECTION_LOCK (connection);
1488
1489   if (!_dbus_connection_acquire_io_path (connection, 1))
1490     {
1491       /* another thread is handling the message */
1492       CONNECTION_UNLOCK (connection);
1493       return TRUE;
1494     }
1495
1496   HAVE_LOCK_CHECK (connection);
1497   retval = _dbus_transport_handle_watch (connection->transport,
1498                                          watch, condition);
1499
1500   _dbus_connection_release_io_path (connection);
1501
1502   HAVE_LOCK_CHECK (connection);
1503
1504   _dbus_verbose ("middle\n");
1505   
1506   status = _dbus_connection_get_dispatch_status_unlocked (connection);
1507
1508   /* this calls out to user code */
1509   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
1510
1511   _dbus_verbose ("end\n");
1512   
1513   return retval;
1514 }
1515
1516 _DBUS_DEFINE_GLOBAL_LOCK (shared_connections);
1517 static DBusHashTable *shared_connections = NULL;
1518 static DBusList *shared_connections_no_guid = NULL;
1519
1520 static void
1521 close_connection_on_shutdown (DBusConnection *connection)
1522 {
1523   DBusMessage *message;
1524
1525   dbus_connection_ref (connection);
1526   _dbus_connection_close_possibly_shared (connection);
1527
1528   /* Churn through to the Disconnected message */
1529   while ((message = dbus_connection_pop_message (connection)))
1530     {
1531       dbus_message_unref (message);
1532     }
1533   dbus_connection_unref (connection);
1534 }
1535
1536 static void
1537 shared_connections_shutdown (void *data)
1538 {
1539   int n_entries;
1540   
1541   _DBUS_LOCK (shared_connections);
1542   
1543   /* This is a little bit unpleasant... better ideas? */
1544   while ((n_entries = _dbus_hash_table_get_n_entries (shared_connections)) > 0)
1545     {
1546       DBusConnection *connection;
1547       DBusHashIter iter;
1548       
1549       _dbus_hash_iter_init (shared_connections, &iter);
1550       _dbus_hash_iter_next (&iter);
1551        
1552       connection = _dbus_hash_iter_get_value (&iter);
1553
1554       _DBUS_UNLOCK (shared_connections);
1555       close_connection_on_shutdown (connection);
1556       _DBUS_LOCK (shared_connections);
1557
1558       /* The connection should now be dead and not in our hash ... */
1559       _dbus_assert (_dbus_hash_table_get_n_entries (shared_connections) < n_entries);
1560     }
1561
1562   _dbus_assert (_dbus_hash_table_get_n_entries (shared_connections) == 0);
1563   
1564   _dbus_hash_table_unref (shared_connections);
1565   shared_connections = NULL;
1566
1567   if (shared_connections_no_guid != NULL)
1568     {
1569       DBusConnection *connection;
1570       connection = _dbus_list_pop_first (&shared_connections_no_guid);
1571       while (connection != NULL)
1572         {
1573           _DBUS_UNLOCK (shared_connections);
1574           close_connection_on_shutdown (connection);
1575           _DBUS_LOCK (shared_connections);
1576           connection = _dbus_list_pop_first (&shared_connections_no_guid);
1577         }
1578     }
1579
1580   shared_connections_no_guid = NULL;
1581   
1582   _DBUS_UNLOCK (shared_connections);
1583 }
1584
1585 static dbus_bool_t
1586 connection_lookup_shared (DBusAddressEntry  *entry,
1587                           DBusConnection   **result)
1588 {
1589   _dbus_verbose ("checking for existing connection\n");
1590   
1591   *result = NULL;
1592   
1593   _DBUS_LOCK (shared_connections);
1594
1595   if (shared_connections == NULL)
1596     {
1597       _dbus_verbose ("creating shared_connections hash table\n");
1598       
1599       shared_connections = _dbus_hash_table_new (DBUS_HASH_STRING,
1600                                                  dbus_free,
1601                                                  NULL);
1602       if (shared_connections == NULL)
1603         {
1604           _DBUS_UNLOCK (shared_connections);
1605           return FALSE;
1606         }
1607
1608       if (!_dbus_register_shutdown_func (shared_connections_shutdown, NULL))
1609         {
1610           _dbus_hash_table_unref (shared_connections);
1611           shared_connections = NULL;
1612           _DBUS_UNLOCK (shared_connections);
1613           return FALSE;
1614         }
1615
1616       _dbus_verbose ("  successfully created shared_connections\n");
1617       
1618       _DBUS_UNLOCK (shared_connections);
1619       return TRUE; /* no point looking up in the hash we just made */
1620     }
1621   else
1622     {
1623       const char *guid;
1624
1625       guid = dbus_address_entry_get_value (entry, "guid");
1626       
1627       if (guid != NULL)
1628         {
1629           DBusConnection *connection;
1630           
1631           connection = _dbus_hash_table_lookup_string (shared_connections,
1632                                                        guid);
1633
1634           if (connection)
1635             {
1636               /* The DBusConnection can't be finalized without taking
1637                * the shared_connections lock to remove it from the
1638                * hash.  So it's safe to ref the connection here.
1639                * However, it may be disconnected if the Disconnected
1640                * message hasn't been processed yet, in which case we
1641                * want to pretend it isn't in the hash and avoid
1642                * returning it.
1643                *
1644                * The idea is to avoid ever returning a disconnected connection
1645                * from dbus_connection_open(). We could just synchronously
1646                * drop our shared ref to the connection on connection disconnect,
1647                * and then assert here that the connection is connected, but
1648                * that causes reentrancy headaches.
1649                */
1650               CONNECTION_LOCK (connection);
1651               if (_dbus_connection_get_is_connected_unlocked (connection))
1652                 {
1653                   _dbus_connection_ref_unlocked (connection);
1654                   *result = connection;
1655                   _dbus_verbose ("looked up existing connection to server guid %s\n",
1656                                  guid);
1657                 }
1658               else
1659                 {
1660                   _dbus_verbose ("looked up existing connection to server guid %s but it was disconnected so ignoring it\n",
1661                                  guid);
1662                 }
1663               CONNECTION_UNLOCK (connection);
1664             }
1665         }
1666       
1667       _DBUS_UNLOCK (shared_connections);
1668       return TRUE;
1669     }
1670 }
1671
1672 static dbus_bool_t
1673 connection_record_shared_unlocked (DBusConnection *connection,
1674                                    const char     *guid)
1675 {
1676   char *guid_key;
1677   char *guid_in_connection;
1678
1679   HAVE_LOCK_CHECK (connection);
1680   _dbus_assert (connection->server_guid == NULL);
1681   _dbus_assert (connection->shareable);
1682
1683   /* get a hard ref on this connection, even if
1684    * we won't in fact store it in the hash, we still
1685    * need to hold a ref on it until it's disconnected.
1686    */
1687   _dbus_connection_ref_unlocked (connection);
1688
1689   if (guid == NULL)
1690     {
1691       _DBUS_LOCK (shared_connections);
1692
1693       if (!_dbus_list_prepend (&shared_connections_no_guid, connection))
1694         {
1695           _DBUS_UNLOCK (shared_connections);
1696           return FALSE;
1697         }
1698
1699       _DBUS_UNLOCK (shared_connections);
1700       return TRUE; /* don't store in the hash */
1701     }
1702   
1703   /* A separate copy of the key is required in the hash table, because
1704    * we don't have a lock on the connection when we are doing a hash
1705    * lookup.
1706    */
1707   
1708   guid_key = _dbus_strdup (guid);
1709   if (guid_key == NULL)
1710     return FALSE;
1711
1712   guid_in_connection = _dbus_strdup (guid);
1713   if (guid_in_connection == NULL)
1714     {
1715       dbus_free (guid_key);
1716       return FALSE;
1717     }
1718   
1719   _DBUS_LOCK (shared_connections);
1720   _dbus_assert (shared_connections != NULL);
1721   
1722   if (!_dbus_hash_table_insert_string (shared_connections,
1723                                        guid_key, connection))
1724     {
1725       dbus_free (guid_key);
1726       dbus_free (guid_in_connection);
1727       _DBUS_UNLOCK (shared_connections);
1728       return FALSE;
1729     }
1730
1731   connection->server_guid = guid_in_connection;
1732
1733   _dbus_verbose ("stored connection to %s to be shared\n",
1734                  connection->server_guid);
1735   
1736   _DBUS_UNLOCK (shared_connections);
1737
1738   _dbus_assert (connection->server_guid != NULL);
1739   
1740   return TRUE;
1741 }
1742
1743 static void
1744 connection_forget_shared_unlocked (DBusConnection *connection)
1745 {
1746   HAVE_LOCK_CHECK (connection);
1747
1748   if (!connection->shareable)
1749     return;
1750   
1751   _DBUS_LOCK (shared_connections);
1752       
1753   if (connection->server_guid != NULL)
1754     {
1755       _dbus_verbose ("dropping connection to %s out of the shared table\n",
1756                      connection->server_guid);
1757       
1758       if (!_dbus_hash_table_remove_string (shared_connections,
1759                                            connection->server_guid))
1760         _dbus_assert_not_reached ("connection was not in the shared table");
1761       
1762       dbus_free (connection->server_guid);
1763       connection->server_guid = NULL;
1764     }
1765   else
1766     {
1767       _dbus_list_remove (&shared_connections_no_guid, connection);
1768     }
1769
1770   _DBUS_UNLOCK (shared_connections);
1771   
1772   /* remove our reference held on all shareable connections */
1773   _dbus_connection_unref_unlocked (connection);
1774 }
1775
1776 static DBusConnection*
1777 connection_try_from_address_entry (DBusAddressEntry *entry,
1778                                    DBusError        *error)
1779 {
1780   DBusTransport *transport;
1781   DBusConnection *connection;
1782
1783   transport = _dbus_transport_open (entry, error);
1784
1785   if (transport == NULL)
1786     {
1787       _DBUS_ASSERT_ERROR_IS_SET (error);
1788       return NULL;
1789     }
1790
1791   connection = _dbus_connection_new_for_transport (transport);
1792
1793   _dbus_transport_unref (transport);
1794   
1795   if (connection == NULL)
1796     {
1797       _DBUS_SET_OOM (error);
1798       return NULL;
1799     }
1800
1801 #ifndef DBUS_DISABLE_CHECKS
1802   _dbus_assert (!connection->have_connection_lock);
1803 #endif
1804   return connection;
1805 }
1806
1807 /*
1808  * If the shared parameter is true, then any existing connection will
1809  * be used (and if a new connection is created, it will be available
1810  * for use by others). If the shared parameter is false, a new
1811  * connection will always be created, and the new connection will
1812  * never be returned to other callers.
1813  *
1814  * @param address the address
1815  * @param shared whether the connection is shared or private
1816  * @param error error return
1817  * @returns the connection or #NULL on error
1818  */
1819 static DBusConnection*
1820 _dbus_connection_open_internal (const char     *address,
1821                                 dbus_bool_t     shared,
1822                                 DBusError      *error)
1823 {
1824   DBusConnection *connection;
1825   DBusAddressEntry **entries;
1826   DBusError tmp_error = DBUS_ERROR_INIT;
1827   DBusError first_error = DBUS_ERROR_INIT;
1828   int len, i;
1829
1830   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1831
1832   _dbus_verbose ("opening %s connection to: %s\n",
1833                  shared ? "shared" : "private", address);
1834   
1835   if (!dbus_parse_address (address, &entries, &len, error))
1836     return NULL;
1837
1838   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1839   
1840   connection = NULL;
1841
1842   for (i = 0; i < len; i++)
1843     {
1844       if (shared)
1845         {
1846           if (!connection_lookup_shared (entries[i], &connection))
1847             _DBUS_SET_OOM (&tmp_error);
1848         }
1849
1850       if (connection == NULL)
1851         {
1852           connection = connection_try_from_address_entry (entries[i],
1853                                                           &tmp_error);
1854
1855           if (connection != NULL && shared)
1856             {
1857               const char *guid;
1858                   
1859               connection->shareable = TRUE;
1860                   
1861               /* guid may be NULL */
1862               guid = dbus_address_entry_get_value (entries[i], "guid");
1863                   
1864               CONNECTION_LOCK (connection);
1865           
1866               if (!connection_record_shared_unlocked (connection, guid))
1867                 {
1868                   _DBUS_SET_OOM (&tmp_error);
1869                   _dbus_connection_close_possibly_shared_and_unlock (connection);
1870                   dbus_connection_unref (connection);
1871                   connection = NULL;
1872                 }
1873               else
1874                 CONNECTION_UNLOCK (connection);
1875             }
1876         }
1877       
1878       if (connection)
1879         break;
1880
1881       _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
1882       
1883       if (i == 0)
1884         dbus_move_error (&tmp_error, &first_error);
1885       else
1886         dbus_error_free (&tmp_error);
1887     }
1888   
1889   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1890   _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
1891   
1892   if (connection == NULL)
1893     {
1894       _DBUS_ASSERT_ERROR_IS_SET (&first_error);
1895       dbus_move_error (&first_error, error);
1896     }
1897   else
1898     dbus_error_free (&first_error);
1899   
1900   dbus_address_entries_free (entries);
1901   return connection;
1902 }
1903
1904 /**
1905  * Closes a shared OR private connection, while dbus_connection_close() can
1906  * only be used on private connections. Should only be called by the
1907  * dbus code that owns the connection - an owner must be known,
1908  * the open/close state is like malloc/free, not like ref/unref.
1909  * 
1910  * @param connection the connection
1911  */
1912 void
1913 _dbus_connection_close_possibly_shared (DBusConnection *connection)
1914 {
1915   _dbus_assert (connection != NULL);
1916   _dbus_assert (connection->generation == _dbus_current_generation);
1917
1918   CONNECTION_LOCK (connection);
1919   _dbus_connection_close_possibly_shared_and_unlock (connection);
1920 }
1921
1922 static DBusPreallocatedSend*
1923 _dbus_connection_preallocate_send_unlocked (DBusConnection *connection)
1924 {
1925   DBusPreallocatedSend *preallocated;
1926
1927   HAVE_LOCK_CHECK (connection);
1928   
1929   _dbus_assert (connection != NULL);
1930   
1931   preallocated = dbus_new (DBusPreallocatedSend, 1);
1932   if (preallocated == NULL)
1933     return NULL;
1934
1935   if (connection->link_cache != NULL)
1936     {
1937       preallocated->queue_link =
1938         _dbus_list_pop_first_link (&connection->link_cache);
1939       preallocated->queue_link->data = NULL;
1940     }
1941   else
1942     {
1943       preallocated->queue_link = _dbus_list_alloc_link (NULL);
1944       if (preallocated->queue_link == NULL)
1945         goto failed_0;
1946     }
1947   
1948   if (connection->link_cache != NULL)
1949     {
1950       preallocated->counter_link =
1951         _dbus_list_pop_first_link (&connection->link_cache);
1952       preallocated->counter_link->data = connection->outgoing_counter;
1953     }
1954   else
1955     {
1956       preallocated->counter_link = _dbus_list_alloc_link (connection->outgoing_counter);
1957       if (preallocated->counter_link == NULL)
1958         goto failed_1;
1959     }
1960
1961   _dbus_counter_ref (preallocated->counter_link->data);
1962
1963   preallocated->connection = connection;
1964   
1965   return preallocated;
1966   
1967  failed_1:
1968   _dbus_list_free_link (preallocated->queue_link);
1969  failed_0:
1970   dbus_free (preallocated);
1971   
1972   return NULL;
1973 }
1974
1975 /* Called with lock held, does not update dispatch status */
1976 static void
1977 _dbus_connection_send_preallocated_unlocked_no_update (DBusConnection       *connection,
1978                                                        DBusPreallocatedSend *preallocated,
1979                                                        DBusMessage          *message,
1980                                                        dbus_uint32_t        *client_serial)
1981 {
1982   dbus_uint32_t serial;
1983   const char *sig;
1984
1985   preallocated->queue_link->data = message;
1986   _dbus_list_prepend_link (&connection->outgoing_messages,
1987                            preallocated->queue_link);
1988
1989   _dbus_message_add_counter_link (message,
1990                                   preallocated->counter_link);
1991
1992   dbus_free (preallocated);
1993   preallocated = NULL;
1994   
1995   dbus_message_ref (message);
1996   
1997   connection->n_outgoing += 1;
1998
1999   sig = dbus_message_get_signature (message);
2000   
2001   _dbus_verbose ("Message %p (%s %s %s %s '%s') for %s added to outgoing queue %p, %d pending to send\n",
2002                  message,
2003                  dbus_message_type_to_string (dbus_message_get_type (message)),
2004                  dbus_message_get_path (message) ?
2005                  dbus_message_get_path (message) :
2006                  "no path",
2007                  dbus_message_get_interface (message) ?
2008                  dbus_message_get_interface (message) :
2009                  "no interface",
2010                  dbus_message_get_member (message) ?
2011                  dbus_message_get_member (message) :
2012                  "no member",
2013                  sig,
2014                  dbus_message_get_destination (message) ?
2015                  dbus_message_get_destination (message) :
2016                  "null",
2017                  connection,
2018                  connection->n_outgoing);
2019
2020   if (dbus_message_get_serial (message) == 0)
2021     {
2022       serial = _dbus_connection_get_next_client_serial (connection);
2023       dbus_message_set_serial (message, serial);
2024       if (client_serial)
2025         *client_serial = serial;
2026     }
2027   else
2028     {
2029       if (client_serial)
2030         *client_serial = dbus_message_get_serial (message);
2031     }
2032
2033   _dbus_verbose ("Message %p serial is %u\n",
2034                  message, dbus_message_get_serial (message));
2035   
2036   dbus_message_lock (message);
2037
2038   /* Now we need to run an iteration to hopefully just write the messages
2039    * out immediately, and otherwise get them queued up
2040    */
2041   _dbus_connection_do_iteration_unlocked (connection,
2042                                           NULL,
2043                                           DBUS_ITERATION_DO_WRITING,
2044                                           -1);
2045
2046   /* If stuff is still queued up, be sure we wake up the main loop */
2047   if (connection->n_outgoing > 0)
2048     _dbus_connection_wakeup_mainloop (connection);
2049 }
2050
2051 static void
2052 _dbus_connection_send_preallocated_and_unlock (DBusConnection       *connection,
2053                                                DBusPreallocatedSend *preallocated,
2054                                                DBusMessage          *message,
2055                                                dbus_uint32_t        *client_serial)
2056 {
2057   DBusDispatchStatus status;
2058
2059   HAVE_LOCK_CHECK (connection);
2060   
2061   _dbus_connection_send_preallocated_unlocked_no_update (connection,
2062                                                          preallocated,
2063                                                          message, client_serial);
2064
2065   _dbus_verbose ("middle\n");
2066   status = _dbus_connection_get_dispatch_status_unlocked (connection);
2067
2068   /* this calls out to user code */
2069   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2070 }
2071
2072 /**
2073  * Like dbus_connection_send(), but assumes the connection
2074  * is already locked on function entry, and unlocks before returning.
2075  *
2076  * @param connection the connection
2077  * @param message the message to send
2078  * @param client_serial return location for client serial of sent message
2079  * @returns #FALSE on out-of-memory
2080  */
2081 dbus_bool_t
2082 _dbus_connection_send_and_unlock (DBusConnection *connection,
2083                                   DBusMessage    *message,
2084                                   dbus_uint32_t  *client_serial)
2085 {
2086   DBusPreallocatedSend *preallocated;
2087
2088   _dbus_assert (connection != NULL);
2089   _dbus_assert (message != NULL);
2090   
2091   preallocated = _dbus_connection_preallocate_send_unlocked (connection);
2092   if (preallocated == NULL)
2093     {
2094       CONNECTION_UNLOCK (connection);
2095       return FALSE;
2096     }
2097
2098   _dbus_connection_send_preallocated_and_unlock (connection,
2099                                                  preallocated,
2100                                                  message,
2101                                                  client_serial);
2102   return TRUE;
2103 }
2104
2105 /**
2106  * Used internally to handle the semantics of dbus_server_set_new_connection_function().
2107  * If the new connection function does not ref the connection, we want to close it.
2108  *
2109  * A bit of a hack, probably the new connection function should have returned a value
2110  * for whether to close, or should have had to close the connection itself if it
2111  * didn't want it.
2112  *
2113  * But, this works OK as long as the new connection function doesn't do anything
2114  * crazy like keep the connection around without ref'ing it.
2115  *
2116  * We have to lock the connection across refcount check and close in case
2117  * the new connection function spawns a thread that closes and unrefs.
2118  * In that case, if the app thread
2119  * closes and unrefs first, we'll harmlessly close again; if the app thread
2120  * still has the ref, we'll close and then the app will close harmlessly.
2121  * If the app unrefs without closing, the app is broken since if the
2122  * app refs from the new connection function it is supposed to also close.
2123  *
2124  * If we didn't atomically check the refcount and close with the lock held
2125  * though, we could screw this up.
2126  * 
2127  * @param connection the connection
2128  */
2129 void
2130 _dbus_connection_close_if_only_one_ref (DBusConnection *connection)
2131 {
2132   CONNECTION_LOCK (connection);
2133   
2134   _dbus_assert (connection->refcount.value > 0);
2135
2136   if (connection->refcount.value == 1)
2137     _dbus_connection_close_possibly_shared_and_unlock (connection);
2138   else
2139     CONNECTION_UNLOCK (connection);
2140 }
2141
2142
2143 /**
2144  * When a function that blocks has been called with a timeout, and we
2145  * run out of memory, the time to wait for memory is based on the
2146  * timeout. If the caller was willing to block a long time we wait a
2147  * relatively long time for memory, if they were only willing to block
2148  * briefly then we retry for memory at a rapid rate.
2149  *
2150  * @timeout_milliseconds the timeout requested for blocking
2151  */
2152 static void
2153 _dbus_memory_pause_based_on_timeout (int timeout_milliseconds)
2154 {
2155   if (timeout_milliseconds == -1)
2156     _dbus_sleep_milliseconds (1000);
2157   else if (timeout_milliseconds < 100)
2158     ; /* just busy loop */
2159   else if (timeout_milliseconds <= 1000)
2160     _dbus_sleep_milliseconds (timeout_milliseconds / 3);
2161   else
2162     _dbus_sleep_milliseconds (1000);
2163 }
2164
2165 static DBusMessage *
2166 generate_local_error_message (dbus_uint32_t serial, 
2167                               char *error_name, 
2168                               char *error_msg)
2169 {
2170   DBusMessage *message;
2171   message = dbus_message_new (DBUS_MESSAGE_TYPE_ERROR);
2172   if (!message)
2173     goto out;
2174
2175   if (!dbus_message_set_error_name (message, error_name))
2176     {
2177       dbus_message_unref (message);
2178       message = NULL;
2179       goto out; 
2180     }
2181
2182   dbus_message_set_no_reply (message, TRUE); 
2183
2184   if (!dbus_message_set_reply_serial (message,
2185                                       serial))
2186     {
2187       dbus_message_unref (message);
2188       message = NULL;
2189       goto out;
2190     }
2191
2192   if (error_msg != NULL)
2193     {
2194       DBusMessageIter iter;
2195
2196       dbus_message_iter_init_append (message, &iter);
2197       if (!dbus_message_iter_append_basic (&iter,
2198                                            DBUS_TYPE_STRING,
2199                                            &error_msg))
2200         {
2201           dbus_message_unref (message);
2202           message = NULL;
2203           goto out;
2204         }
2205     }
2206
2207  out:
2208   return message;
2209 }
2210
2211 /*
2212  * Peek the incoming queue to see if we got reply for a specific serial
2213  */
2214 static dbus_bool_t
2215 _dbus_connection_peek_for_reply_unlocked (DBusConnection *connection,
2216                                           dbus_uint32_t   client_serial)
2217 {
2218   DBusList *link;
2219   HAVE_LOCK_CHECK (connection);
2220
2221   link = _dbus_list_get_first_link (&connection->incoming_messages);
2222
2223   while (link != NULL)
2224     {
2225       DBusMessage *reply = link->data;
2226
2227       if (dbus_message_get_reply_serial (reply) == client_serial)
2228         {
2229           _dbus_verbose ("%s reply to %d found in queue\n", _DBUS_FUNCTION_NAME, client_serial);
2230           return TRUE;
2231         }
2232       link = _dbus_list_get_next_link (&connection->incoming_messages, link);
2233     }
2234
2235   return FALSE;
2236 }
2237
2238 /* This is slightly strange since we can pop a message here without
2239  * the dispatch lock.
2240  */
2241 static DBusMessage*
2242 check_for_reply_unlocked (DBusConnection *connection,
2243                           dbus_uint32_t   client_serial)
2244 {
2245   DBusList *link;
2246
2247   HAVE_LOCK_CHECK (connection);
2248   
2249   link = _dbus_list_get_first_link (&connection->incoming_messages);
2250
2251   while (link != NULL)
2252     {
2253       DBusMessage *reply = link->data;
2254
2255       if (dbus_message_get_reply_serial (reply) == client_serial)
2256         {
2257           _dbus_list_remove_link (&connection->incoming_messages, link);
2258           connection->n_incoming  -= 1;
2259           return reply;
2260         }
2261       link = _dbus_list_get_next_link (&connection->incoming_messages, link);
2262     }
2263
2264   return NULL;
2265 }
2266
2267 static void
2268 connection_timeout_and_complete_all_pending_calls_unlocked (DBusConnection *connection)
2269 {
2270    /* We can't iterate over the hash in the normal way since we'll be
2271     * dropping the lock for each item. So we restart the
2272     * iter each time as we drain the hash table.
2273     */
2274    
2275    while (_dbus_hash_table_get_n_entries (connection->pending_replies) > 0)
2276     {
2277       DBusPendingCall *pending;
2278       DBusHashIter iter;
2279       
2280       _dbus_hash_iter_init (connection->pending_replies, &iter);
2281       _dbus_hash_iter_next (&iter);
2282        
2283       pending = _dbus_hash_iter_get_value (&iter);
2284       _dbus_pending_call_ref_unlocked (pending);
2285        
2286       _dbus_pending_call_queue_timeout_error_unlocked (pending, 
2287                                                        connection);
2288
2289       if (_dbus_pending_call_is_timeout_added_unlocked (pending))
2290           _dbus_connection_remove_timeout_unlocked (connection,
2291                                                     _dbus_pending_call_get_timeout_unlocked (pending));
2292       _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);       
2293       _dbus_hash_iter_remove_entry (&iter);
2294
2295       _dbus_pending_call_unref_and_unlock (pending);
2296       CONNECTION_LOCK (connection);
2297     }
2298   HAVE_LOCK_CHECK (connection);
2299 }
2300
2301 static void
2302 complete_pending_call_and_unlock (DBusConnection  *connection,
2303                                   DBusPendingCall *pending,
2304                                   DBusMessage     *message)
2305 {
2306   _dbus_pending_call_set_reply_unlocked (pending, message);
2307   _dbus_pending_call_ref_unlocked (pending); /* in case there's no app with a ref held */
2308   _dbus_connection_detach_pending_call_and_unlock (connection, pending);
2309  
2310   /* Must be called unlocked since it invokes app callback */
2311   _dbus_pending_call_complete (pending);
2312   dbus_pending_call_unref (pending);
2313 }
2314
2315 static dbus_bool_t
2316 check_for_reply_and_update_dispatch_unlocked (DBusConnection  *connection,
2317                                               DBusPendingCall *pending)
2318 {
2319   DBusMessage *reply;
2320   DBusDispatchStatus status;
2321
2322   reply = check_for_reply_unlocked (connection, 
2323                                     _dbus_pending_call_get_reply_serial_unlocked (pending));
2324   if (reply != NULL)
2325     {
2326       _dbus_verbose ("checked for reply\n");
2327
2328       _dbus_verbose ("dbus_connection_send_with_reply_and_block(): got reply\n");
2329
2330       complete_pending_call_and_unlock (connection, pending, reply);
2331       dbus_message_unref (reply);
2332
2333       CONNECTION_LOCK (connection);
2334       status = _dbus_connection_get_dispatch_status_unlocked (connection);
2335       _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2336       dbus_pending_call_unref (pending);
2337
2338       return TRUE;
2339     }
2340
2341   return FALSE;
2342 }
2343
2344 /**
2345  * Blocks until a pending call times out or gets a reply.
2346  *
2347  * Does not re-enter the main loop or run filter/path-registered
2348  * callbacks. The reply to the message will not be seen by
2349  * filter callbacks.
2350  *
2351  * Returns immediately if pending call already got a reply.
2352  * 
2353  * @todo could use performance improvements (it keeps scanning
2354  * the whole message queue for example)
2355  *
2356  * @param pending the pending call we block for a reply on
2357  */
2358 void
2359 _dbus_connection_block_pending_call (DBusPendingCall *pending)
2360 {
2361   long start_tv_sec, start_tv_usec;
2362   long tv_sec, tv_usec;
2363   DBusDispatchStatus status;
2364   DBusConnection *connection;
2365   dbus_uint32_t client_serial;
2366   DBusTimeout *timeout;
2367   int timeout_milliseconds, elapsed_milliseconds;
2368
2369   _dbus_assert (pending != NULL);
2370
2371   if (dbus_pending_call_get_completed (pending))
2372     return;
2373
2374   dbus_pending_call_ref (pending); /* necessary because the call could be canceled */
2375
2376   connection = _dbus_pending_call_get_connection_and_lock (pending);
2377   
2378   /* Flush message queue - note, can affect dispatch status */
2379   _dbus_connection_flush_unlocked (connection);
2380
2381   client_serial = _dbus_pending_call_get_reply_serial_unlocked (pending);
2382
2383   /* note that timeout_milliseconds is limited to a smallish value
2384    * in _dbus_pending_call_new() so overflows aren't possible
2385    * below
2386    */
2387   timeout = _dbus_pending_call_get_timeout_unlocked (pending);
2388   if (timeout)
2389     {
2390       timeout_milliseconds = dbus_timeout_get_interval (timeout);
2391       _dbus_get_current_time (&start_tv_sec, &start_tv_usec);
2392
2393       _dbus_verbose ("dbus_connection_send_with_reply_and_block(): will block %d milliseconds for reply serial %u from %ld sec %ld usec\n",
2394                      timeout_milliseconds,
2395                      client_serial,
2396                      start_tv_sec, start_tv_usec);
2397     }
2398   else
2399     {
2400       timeout_milliseconds = -1;
2401
2402       _dbus_verbose ("dbus_connection_send_with_reply_and_block(): will block for reply serial %u\n", client_serial);
2403     }
2404
2405   /* check to see if we already got the data off the socket */
2406   /* from another blocked pending call */
2407   if (check_for_reply_and_update_dispatch_unlocked (connection, pending))
2408     return;
2409
2410   /* Now we wait... */
2411   /* always block at least once as we know we don't have the reply yet */
2412   _dbus_connection_do_iteration_unlocked (connection,
2413                                           pending,
2414                                           DBUS_ITERATION_DO_READING |
2415                                           DBUS_ITERATION_BLOCK,
2416                                           timeout_milliseconds);
2417
2418  recheck_status:
2419
2420   _dbus_verbose ("top of recheck\n");
2421   
2422   HAVE_LOCK_CHECK (connection);
2423   
2424   /* queue messages and get status */
2425
2426   status = _dbus_connection_get_dispatch_status_unlocked (connection);
2427
2428   /* the get_completed() is in case a dispatch() while we were blocking
2429    * got the reply instead of us.
2430    */
2431   if (_dbus_pending_call_get_completed_unlocked (pending))
2432     {
2433       _dbus_verbose ("Pending call completed by dispatch\n");
2434       _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2435       dbus_pending_call_unref (pending);
2436       return;
2437     }
2438   
2439   if (status == DBUS_DISPATCH_DATA_REMAINS)
2440     {
2441       if (check_for_reply_and_update_dispatch_unlocked (connection, pending))
2442         return;
2443     }
2444   
2445   _dbus_get_current_time (&tv_sec, &tv_usec);
2446   elapsed_milliseconds = (tv_sec - start_tv_sec) * 1000 +
2447           (tv_usec - start_tv_usec) / 1000;
2448   
2449   if (!_dbus_connection_get_is_connected_unlocked (connection))
2450     {
2451       DBusMessage *error_msg;
2452
2453       error_msg = generate_local_error_message (client_serial,
2454                                                 DBUS_ERROR_DISCONNECTED, 
2455                                                 "Connection was disconnected before a reply was received"); 
2456
2457       /* on OOM error_msg is set to NULL */
2458       complete_pending_call_and_unlock (connection, pending, error_msg);
2459       dbus_pending_call_unref (pending);
2460       return;
2461     }
2462   else if (connection->disconnect_message_link == NULL)
2463     _dbus_verbose ("dbus_connection_send_with_reply_and_block(): disconnected\n");
2464   else if (timeout == NULL)
2465     {
2466        if (status == DBUS_DISPATCH_NEED_MEMORY)
2467         {
2468           /* Try sleeping a bit, as we aren't sure we need to block for reading,
2469            * we may already have a reply in the buffer and just can't process
2470            * it.
2471            */
2472           _dbus_verbose ("dbus_connection_send_with_reply_and_block() waiting for more memory\n");
2473
2474           _dbus_memory_pause_based_on_timeout (timeout_milliseconds - elapsed_milliseconds);
2475         }
2476       else
2477         {          
2478           /* block again, we don't have the reply buffered yet. */
2479           _dbus_connection_do_iteration_unlocked (connection,
2480                                                   pending,
2481                                                   DBUS_ITERATION_DO_READING |
2482                                                   DBUS_ITERATION_BLOCK,
2483                                                   timeout_milliseconds - elapsed_milliseconds);
2484         }
2485
2486       goto recheck_status;
2487     }
2488   else if (tv_sec < start_tv_sec)
2489     _dbus_verbose ("dbus_connection_send_with_reply_and_block(): clock set backward\n");
2490   else if (elapsed_milliseconds < timeout_milliseconds)
2491     {
2492       _dbus_verbose ("dbus_connection_send_with_reply_and_block(): %d milliseconds remain\n", timeout_milliseconds - elapsed_milliseconds);
2493       
2494       if (status == DBUS_DISPATCH_NEED_MEMORY)
2495         {
2496           /* Try sleeping a bit, as we aren't sure we need to block for reading,
2497            * we may already have a reply in the buffer and just can't process
2498            * it.
2499            */
2500           _dbus_verbose ("dbus_connection_send_with_reply_and_block() waiting for more memory\n");
2501
2502           _dbus_memory_pause_based_on_timeout (timeout_milliseconds - elapsed_milliseconds);
2503         }
2504       else
2505         {          
2506           /* block again, we don't have the reply buffered yet. */
2507           _dbus_connection_do_iteration_unlocked (connection,
2508                                                   NULL,
2509                                                   DBUS_ITERATION_DO_READING |
2510                                                   DBUS_ITERATION_BLOCK,
2511                                                   timeout_milliseconds - elapsed_milliseconds);
2512         }
2513
2514       goto recheck_status;
2515     }
2516
2517   _dbus_verbose ("dbus_connection_send_with_reply_and_block(): Waited %d milliseconds and got no reply\n",
2518                  elapsed_milliseconds);
2519
2520   _dbus_assert (!_dbus_pending_call_get_completed_unlocked (pending));
2521   
2522   /* unlock and call user code */
2523   complete_pending_call_and_unlock (connection, pending, NULL);
2524
2525   /* update user code on dispatch status */
2526   CONNECTION_LOCK (connection);
2527   status = _dbus_connection_get_dispatch_status_unlocked (connection);
2528   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2529   dbus_pending_call_unref (pending);
2530 }
2531
2532 /** @} */
2533
2534 /**
2535  * @addtogroup DBusConnection
2536  *
2537  * @{
2538  */
2539
2540 /**
2541  * Gets a connection to a remote address. If a connection to the given
2542  * address already exists, returns the existing connection with its
2543  * reference count incremented.  Otherwise, returns a new connection
2544  * and saves the new connection for possible re-use if a future call
2545  * to dbus_connection_open() asks to connect to the same server.
2546  *
2547  * Use dbus_connection_open_private() to get a dedicated connection
2548  * not shared with other callers of dbus_connection_open().
2549  *
2550  * If the open fails, the function returns #NULL, and provides a
2551  * reason for the failure in the error parameter. Pass #NULL for the
2552  * error parameter if you aren't interested in the reason for
2553  * failure.
2554  *
2555  * Because this connection is shared, no user of the connection
2556  * may call dbus_connection_close(). However, when you are done with the
2557  * connection you should call dbus_connection_unref().
2558  *
2559  * @note Prefer dbus_connection_open() to dbus_connection_open_private()
2560  * unless you have good reason; connections are expensive enough
2561  * that it's wasteful to create lots of connections to the same
2562  * server.
2563  * 
2564  * @param address the address.
2565  * @param error address where an error can be returned.
2566  * @returns new connection, or #NULL on failure.
2567  */
2568 DBusConnection*
2569 dbus_connection_open (const char     *address,
2570                       DBusError      *error)
2571 {
2572   DBusConnection *connection;
2573
2574   _dbus_return_val_if_fail (address != NULL, NULL);
2575   _dbus_return_val_if_error_is_set (error, NULL);
2576
2577   connection = _dbus_connection_open_internal (address,
2578                                                TRUE,
2579                                                error);
2580
2581   return connection;
2582 }
2583
2584 /**
2585  * Opens a new, dedicated connection to a remote address. Unlike
2586  * dbus_connection_open(), always creates a new connection.
2587  * This connection will not be saved or recycled by libdbus.
2588  *
2589  * If the open fails, the function returns #NULL, and provides a
2590  * reason for the failure in the error parameter. Pass #NULL for the
2591  * error parameter if you aren't interested in the reason for
2592  * failure.
2593  *
2594  * When you are done with this connection, you must
2595  * dbus_connection_close() to disconnect it,
2596  * and dbus_connection_unref() to free the connection object.
2597  * 
2598  * (The dbus_connection_close() can be skipped if the
2599  * connection is already known to be disconnected, for example
2600  * if you are inside a handler for the Disconnected signal.)
2601  *
2602  * @note Prefer dbus_connection_open() to dbus_connection_open_private()
2603  * unless you have good reason; connections are expensive enough
2604  * that it's wasteful to create lots of connections to the same
2605  * server.
2606  *
2607  * @param address the address.
2608  * @param error address where an error can be returned.
2609  * @returns new connection, or #NULL on failure.
2610  */
2611 DBusConnection*
2612 dbus_connection_open_private (const char     *address,
2613                               DBusError      *error)
2614 {
2615   DBusConnection *connection;
2616
2617   _dbus_return_val_if_fail (address != NULL, NULL);
2618   _dbus_return_val_if_error_is_set (error, NULL);
2619
2620   connection = _dbus_connection_open_internal (address,
2621                                                FALSE,
2622                                                error);
2623
2624   return connection;
2625 }
2626
2627 /**
2628  * Increments the reference count of a DBusConnection.
2629  *
2630  * @param connection the connection.
2631  * @returns the connection.
2632  */
2633 DBusConnection *
2634 dbus_connection_ref (DBusConnection *connection)
2635 {
2636   _dbus_return_val_if_fail (connection != NULL, NULL);
2637   _dbus_return_val_if_fail (connection->generation == _dbus_current_generation, NULL);
2638   
2639   /* The connection lock is better than the global
2640    * lock in the atomic increment fallback
2641    *
2642    * (FIXME but for now we always use the atomic version,
2643    * to avoid taking the connection lock, due to
2644    * the mess with set_timeout_functions()/set_watch_functions()
2645    * calling out to the app without dropping locks)
2646    */
2647   
2648 #if 1
2649   _dbus_atomic_inc (&connection->refcount);
2650 #else
2651   CONNECTION_LOCK (connection);
2652   _dbus_assert (connection->refcount.value > 0);
2653
2654   connection->refcount.value += 1;
2655   CONNECTION_UNLOCK (connection);
2656 #endif
2657
2658   return connection;
2659 }
2660
2661 static void
2662 free_outgoing_message (void *element,
2663                        void *data)
2664 {
2665   DBusMessage *message = element;
2666   DBusConnection *connection = data;
2667
2668   _dbus_message_remove_counter (message,
2669                                 connection->outgoing_counter,
2670                                 NULL);
2671   dbus_message_unref (message);
2672 }
2673
2674 /* This is run without the mutex held, but after the last reference
2675  * to the connection has been dropped we should have no thread-related
2676  * problems
2677  */
2678 static void
2679 _dbus_connection_last_unref (DBusConnection *connection)
2680 {
2681   DBusList *link;
2682
2683   _dbus_verbose ("Finalizing connection %p\n", connection);
2684   
2685   _dbus_assert (connection->refcount.value == 0);
2686   
2687   /* You have to disconnect the connection before unref:ing it. Otherwise
2688    * you won't get the disconnected message.
2689    */
2690   _dbus_assert (!_dbus_transport_get_is_connected (connection->transport));
2691   _dbus_assert (connection->server_guid == NULL);
2692   
2693   /* ---- We're going to call various application callbacks here, hope it doesn't break anything... */
2694   _dbus_object_tree_free_all_unlocked (connection->objects);
2695   
2696   dbus_connection_set_dispatch_status_function (connection, NULL, NULL, NULL);
2697   dbus_connection_set_wakeup_main_function (connection, NULL, NULL, NULL);
2698   dbus_connection_set_unix_user_function (connection, NULL, NULL, NULL);
2699   
2700   _dbus_watch_list_free (connection->watches);
2701   connection->watches = NULL;
2702   
2703   _dbus_timeout_list_free (connection->timeouts);
2704   connection->timeouts = NULL;
2705
2706   _dbus_data_slot_list_free (&connection->slot_list);
2707   
2708   link = _dbus_list_get_first_link (&connection->filter_list);
2709   while (link != NULL)
2710     {
2711       DBusMessageFilter *filter = link->data;
2712       DBusList *next = _dbus_list_get_next_link (&connection->filter_list, link);
2713
2714       filter->function = NULL;
2715       _dbus_message_filter_unref (filter); /* calls app callback */
2716       link->data = NULL;
2717       
2718       link = next;
2719     }
2720   _dbus_list_clear (&connection->filter_list);
2721   
2722   /* ---- Done with stuff that invokes application callbacks */
2723
2724   _dbus_object_tree_unref (connection->objects);  
2725
2726   _dbus_hash_table_unref (connection->pending_replies);
2727   connection->pending_replies = NULL;
2728   
2729   _dbus_list_clear (&connection->filter_list);
2730   
2731   _dbus_list_foreach (&connection->outgoing_messages,
2732                       free_outgoing_message,
2733                       connection);
2734   _dbus_list_clear (&connection->outgoing_messages);
2735   
2736   _dbus_list_foreach (&connection->incoming_messages,
2737                       (DBusForeachFunction) dbus_message_unref,
2738                       NULL);
2739   _dbus_list_clear (&connection->incoming_messages);
2740
2741   _dbus_counter_unref (connection->outgoing_counter);
2742
2743   _dbus_transport_unref (connection->transport);
2744
2745   if (connection->disconnect_message_link)
2746     {
2747       DBusMessage *message = connection->disconnect_message_link->data;
2748       dbus_message_unref (message);
2749       _dbus_list_free_link (connection->disconnect_message_link);
2750     }
2751
2752   _dbus_list_clear (&connection->link_cache);
2753   
2754   _dbus_condvar_free_at_location (&connection->dispatch_cond);
2755   _dbus_condvar_free_at_location (&connection->io_path_cond);
2756
2757   _dbus_mutex_free_at_location (&connection->io_path_mutex);
2758   _dbus_mutex_free_at_location (&connection->dispatch_mutex);
2759
2760   _dbus_mutex_free_at_location (&connection->slot_mutex);
2761
2762   _dbus_mutex_free_at_location (&connection->mutex);
2763   
2764   dbus_free (connection);
2765 }
2766
2767 /**
2768  * Decrements the reference count of a DBusConnection, and finalizes
2769  * it if the count reaches zero.
2770  *
2771  * Note: it is a bug to drop the last reference to a connection that
2772  * is still connected.
2773  *
2774  * For shared connections, libdbus will own a reference
2775  * as long as the connection is connected, so you can know that either
2776  * you don't have the last reference, or it's OK to drop the last reference.
2777  * Most connections are shared. dbus_connection_open() and dbus_bus_get()
2778  * return shared connections.
2779  *
2780  * For private connections, the creator of the connection must arrange for
2781  * dbus_connection_close() to be called prior to dropping the last reference.
2782  * Private connections come from dbus_connection_open_private() or dbus_bus_get_private().
2783  *
2784  * @param connection the connection.
2785  */
2786 void
2787 dbus_connection_unref (DBusConnection *connection)
2788 {
2789   dbus_bool_t last_unref;
2790
2791   _dbus_return_if_fail (connection != NULL);
2792   _dbus_return_if_fail (connection->generation == _dbus_current_generation);
2793   
2794   /* The connection lock is better than the global
2795    * lock in the atomic increment fallback
2796    *
2797    * (FIXME but for now we always use the atomic version,
2798    * to avoid taking the connection lock, due to
2799    * the mess with set_timeout_functions()/set_watch_functions()
2800    * calling out to the app without dropping locks)
2801    */
2802   
2803 #if 1
2804   last_unref = (_dbus_atomic_dec (&connection->refcount) == 1);
2805 #else
2806   CONNECTION_LOCK (connection);
2807   
2808   _dbus_assert (connection->refcount.value > 0);
2809
2810   connection->refcount.value -= 1;
2811   last_unref = (connection->refcount.value == 0);
2812
2813 #if 0
2814   printf ("unref() connection %p count = %d\n", connection, connection->refcount.value);
2815 #endif
2816   
2817   CONNECTION_UNLOCK (connection);
2818 #endif
2819   
2820   if (last_unref)
2821     {
2822 #ifndef DBUS_DISABLE_CHECKS
2823       if (_dbus_transport_get_is_connected (connection->transport))
2824         {
2825           _dbus_warn_check_failed ("The last reference on a connection was dropped without closing the connection. This is a bug in an application. See dbus_connection_unref() documentation for details.\n%s",
2826                                    connection->shareable ?
2827                                    "Most likely, the application called unref() too many times and removed a reference belonging to libdbus, since this is a shared connection.\n" : 
2828                                     "Most likely, the application was supposed to call dbus_connection_close(), since this is a private connection.\n");
2829           return;
2830         }
2831 #endif
2832       _dbus_connection_last_unref (connection);
2833     }
2834 }
2835
2836 /*
2837  * Note that the transport can disconnect itself (other end drops us)
2838  * and in that case this function never runs. So this function must
2839  * not do anything more than disconnect the transport and update the
2840  * dispatch status.
2841  * 
2842  * If the transport self-disconnects, then we assume someone will
2843  * dispatch the connection to cause the dispatch status update.
2844  */
2845 static void
2846 _dbus_connection_close_possibly_shared_and_unlock (DBusConnection *connection)
2847 {
2848   DBusDispatchStatus status;
2849
2850   HAVE_LOCK_CHECK (connection);
2851   
2852   _dbus_verbose ("Disconnecting %p\n", connection);
2853
2854   /* We need to ref because update_dispatch_status_and_unlock will unref
2855    * the connection if it was shared and libdbus was the only remaining
2856    * refcount holder.
2857    */
2858   _dbus_connection_ref_unlocked (connection);
2859   
2860   _dbus_transport_disconnect (connection->transport);
2861
2862   /* This has the side effect of queuing the disconnect message link
2863    * (unless we don't have enough memory, possibly, so don't assert it).
2864    * After the disconnect message link is queued, dbus_bus_get/dbus_connection_open
2865    * should never again return the newly-disconnected connection.
2866    *
2867    * However, we only unref the shared connection and exit_on_disconnect when
2868    * the disconnect message reaches the head of the message queue,
2869    * NOT when it's first queued.
2870    */
2871   status = _dbus_connection_get_dispatch_status_unlocked (connection);
2872
2873   /* This calls out to user code */
2874   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
2875
2876   /* Could also call out to user code */
2877   dbus_connection_unref (connection);
2878 }
2879
2880 /**
2881  * Closes a private connection, so no further data can be sent or received.
2882  * This disconnects the transport (such as a socket) underlying the
2883  * connection.
2884  *
2885  * Attempts to send messages after closing a connection are safe, but will result in
2886  * error replies generated locally in libdbus.
2887  * 
2888  * This function does not affect the connection's reference count.  It's
2889  * safe to close a connection more than once; all calls after the
2890  * first do nothing. It's impossible to "reopen" a connection, a
2891  * new connection must be created. This function may result in a call
2892  * to the DBusDispatchStatusFunction set with
2893  * dbus_connection_set_dispatch_status_function(), as the disconnect
2894  * message it generates needs to be dispatched.
2895  *
2896  * If a connection is dropped by the remote application, it will
2897  * close itself. 
2898  * 
2899  * You must close a connection prior to releasing the last reference to
2900  * the connection. If you dbus_connection_unref() for the last time
2901  * without closing the connection, the results are undefined; it
2902  * is a bug in your program and libdbus will try to print a warning.
2903  *
2904  * You may not close a shared connection. Connections created with
2905  * dbus_connection_open() or dbus_bus_get() are shared.
2906  * These connections are owned by libdbus, and applications should
2907  * only unref them, never close them. Applications can know it is
2908  * safe to unref these connections because libdbus will be holding a
2909  * reference as long as the connection is open. Thus, either the
2910  * connection is closed and it is OK to drop the last reference,
2911  * or the connection is open and the app knows it does not have the
2912  * last reference.
2913  *
2914  * Connections created with dbus_connection_open_private() or
2915  * dbus_bus_get_private() are not kept track of or referenced by
2916  * libdbus. The creator of these connections is responsible for
2917  * calling dbus_connection_close() prior to releasing the last
2918  * reference, if the connection is not already disconnected.
2919  *
2920  * @param connection the private (unshared) connection to close
2921  */
2922 void
2923 dbus_connection_close (DBusConnection *connection)
2924 {
2925   _dbus_return_if_fail (connection != NULL);
2926   _dbus_return_if_fail (connection->generation == _dbus_current_generation);
2927
2928   CONNECTION_LOCK (connection);
2929
2930 #ifndef DBUS_DISABLE_CHECKS
2931   if (connection->shareable)
2932     {
2933       CONNECTION_UNLOCK (connection);
2934
2935       _dbus_warn_check_failed ("Applications must not close shared connections - see dbus_connection_close() docs. This is a bug in the application.\n");
2936       return;
2937     }
2938 #endif
2939   
2940   _dbus_connection_close_possibly_shared_and_unlock (connection);
2941 }
2942
2943 static dbus_bool_t
2944 _dbus_connection_get_is_connected_unlocked (DBusConnection *connection)
2945 {
2946   HAVE_LOCK_CHECK (connection);
2947   return _dbus_transport_get_is_connected (connection->transport);
2948 }
2949
2950 /**
2951  * Gets whether the connection is currently open.  A connection may
2952  * become disconnected when the remote application closes its end, or
2953  * exits; a connection may also be disconnected with
2954  * dbus_connection_close().
2955  * 
2956  * There are not separate states for "closed" and "disconnected," the two
2957  * terms are synonymous. This function should really be called
2958  * get_is_open() but for historical reasons is not.
2959  *
2960  * @param connection the connection.
2961  * @returns #TRUE if the connection is still alive.
2962  */
2963 dbus_bool_t
2964 dbus_connection_get_is_connected (DBusConnection *connection)
2965 {
2966   dbus_bool_t res;
2967
2968   _dbus_return_val_if_fail (connection != NULL, FALSE);
2969   
2970   CONNECTION_LOCK (connection);
2971   res = _dbus_connection_get_is_connected_unlocked (connection);
2972   CONNECTION_UNLOCK (connection);
2973   
2974   return res;
2975 }
2976
2977 /**
2978  * Gets whether the connection was authenticated. (Note that
2979  * if the connection was authenticated then disconnected,
2980  * this function still returns #TRUE)
2981  *
2982  * @param connection the connection
2983  * @returns #TRUE if the connection was ever authenticated
2984  */
2985 dbus_bool_t
2986 dbus_connection_get_is_authenticated (DBusConnection *connection)
2987 {
2988   dbus_bool_t res;
2989
2990   _dbus_return_val_if_fail (connection != NULL, FALSE);
2991   
2992   CONNECTION_LOCK (connection);
2993   res = _dbus_transport_get_is_authenticated (connection->transport);
2994   CONNECTION_UNLOCK (connection);
2995   
2996   return res;
2997 }
2998
2999 /**
3000  * Gets whether the connection is not authenticated as a specific
3001  * user.  If the connection is not authenticated, this function
3002  * returns #TRUE, and if it is authenticated but as an anonymous user,
3003  * it returns #TRUE.  If it is authenticated as a specific user, then
3004  * this returns #FALSE. (Note that if the connection was authenticated
3005  * as anonymous then disconnected, this function still returns #TRUE.)
3006  *
3007  * If the connection is not anonymous, you can use
3008  * dbus_connection_get_unix_user() and
3009  * dbus_connection_get_windows_user() to see who it's authorized as.
3010  *
3011  * If you want to prevent non-anonymous authorization, use
3012  * dbus_server_set_auth_mechanisms() to remove the mechanisms that
3013  * allow proving user identity (i.e. only allow the ANONYMOUS
3014  * mechanism).
3015  * 
3016  * @param connection the connection
3017  * @returns #TRUE if not authenticated or authenticated as anonymous 
3018  */
3019 dbus_bool_t
3020 dbus_connection_get_is_anonymous (DBusConnection *connection)
3021 {
3022   dbus_bool_t res;
3023
3024   _dbus_return_val_if_fail (connection != NULL, FALSE);
3025   
3026   CONNECTION_LOCK (connection);
3027   res = _dbus_transport_get_is_anonymous (connection->transport);
3028   CONNECTION_UNLOCK (connection);
3029   
3030   return res;
3031 }
3032
3033 /**
3034  * Gets the ID of the server address we are authenticated to, if this
3035  * connection is on the client side. If the connection is on the
3036  * server side, this will always return #NULL - use dbus_server_get_id()
3037  * to get the ID of your own server, if you are the server side.
3038  * 
3039  * If a client-side connection is not authenticated yet, the ID may be
3040  * available if it was included in the server address, but may not be
3041  * available. The only way to be sure the server ID is available
3042  * is to wait for authentication to complete.
3043  *
3044  * In general, each mode of connecting to a given server will have
3045  * its own ID. So for example, if the session bus daemon is listening
3046  * on UNIX domain sockets and on TCP, then each of those modalities
3047  * will have its own server ID.
3048  *
3049  * If you want an ID that identifies an entire session bus, look at
3050  * dbus_bus_get_id() instead (which is just a convenience wrapper
3051  * around the org.freedesktop.DBus.GetId method invoked on the bus).
3052  *
3053  * You can also get a machine ID; see dbus_get_local_machine_id() to
3054  * get the machine you are on.  There isn't a convenience wrapper, but
3055  * you can invoke org.freedesktop.DBus.Peer.GetMachineId on any peer
3056  * to get the machine ID on the other end.
3057  * 
3058  * The D-Bus specification describes the server ID and other IDs in a
3059  * bit more detail.
3060  *
3061  * @param connection the connection
3062  * @returns the server ID or #NULL if no memory or the connection is server-side
3063  */
3064 char*
3065 dbus_connection_get_server_id (DBusConnection *connection)
3066 {
3067   char *id;
3068
3069   _dbus_return_val_if_fail (connection != NULL, NULL);
3070
3071   CONNECTION_LOCK (connection);
3072   id = _dbus_strdup (_dbus_transport_get_server_id (connection->transport));
3073   CONNECTION_UNLOCK (connection);
3074
3075   return id;
3076 }
3077
3078 /**
3079  * Tests whether a certain type can be send via the connection. This
3080  * will always return TRUE for all types, with the exception of
3081  * DBUS_TYPE_UNIX_FD. The function will return TRUE for
3082  * DBUS_TYPE_UNIX_FD only on systems that know Unix file descriptors
3083  * and can send them via the chosen transport and when the remote side
3084  * supports this.
3085  *
3086  * This function can be used to do runtime checking for types that
3087  * might be unknown to the specific D-Bus client implementation
3088  * version, i.e. it will return FALSE for all types this
3089  * implementation does not know.
3090  *
3091  * @param connection the connection
3092  * @param type the type to check
3093  * @returns TRUE if the type may be send via the connection
3094  */
3095 dbus_bool_t
3096 dbus_connection_can_send_type(DBusConnection *connection,
3097                                   int type)
3098 {
3099   _dbus_return_val_if_fail (connection != NULL, FALSE);
3100
3101   if (!_dbus_type_is_valid(type))
3102     return FALSE;
3103
3104   if (type != DBUS_TYPE_UNIX_FD)
3105     return TRUE;
3106
3107 #ifdef HAVE_UNIX_FD_PASSING
3108   {
3109     dbus_bool_t b;
3110
3111     CONNECTION_LOCK(connection);
3112     b = _dbus_transport_can_pass_unix_fd(connection->transport);
3113     CONNECTION_UNLOCK(connection);
3114
3115     return b;
3116   }
3117 #endif
3118
3119   return FALSE;
3120 }
3121
3122 /**
3123  * Set whether _exit() should be called when the connection receives a
3124  * disconnect signal. The call to _exit() comes after any handlers for
3125  * the disconnect signal run; handlers can cancel the exit by calling
3126  * this function.
3127  *
3128  * By default, exit_on_disconnect is #FALSE; but for message bus
3129  * connections returned from dbus_bus_get() it will be toggled on
3130  * by default.
3131  *
3132  * @param connection the connection
3133  * @param exit_on_disconnect #TRUE if _exit() should be called after a disconnect signal
3134  */
3135 void
3136 dbus_connection_set_exit_on_disconnect (DBusConnection *connection,
3137                                         dbus_bool_t     exit_on_disconnect)
3138 {
3139   _dbus_return_if_fail (connection != NULL);
3140
3141   CONNECTION_LOCK (connection);
3142   connection->exit_on_disconnect = exit_on_disconnect != FALSE;
3143   CONNECTION_UNLOCK (connection);
3144 }
3145
3146 /**
3147  * Preallocates resources needed to send a message, allowing the message 
3148  * to be sent without the possibility of memory allocation failure.
3149  * Allows apps to create a future guarantee that they can send
3150  * a message regardless of memory shortages.
3151  *
3152  * @param connection the connection we're preallocating for.
3153  * @returns the preallocated resources, or #NULL
3154  */
3155 DBusPreallocatedSend*
3156 dbus_connection_preallocate_send (DBusConnection *connection)
3157 {
3158   DBusPreallocatedSend *preallocated;
3159
3160   _dbus_return_val_if_fail (connection != NULL, NULL);
3161
3162   CONNECTION_LOCK (connection);
3163   
3164   preallocated =
3165     _dbus_connection_preallocate_send_unlocked (connection);
3166
3167   CONNECTION_UNLOCK (connection);
3168
3169   return preallocated;
3170 }
3171
3172 /**
3173  * Frees preallocated message-sending resources from
3174  * dbus_connection_preallocate_send(). Should only
3175  * be called if the preallocated resources are not used
3176  * to send a message.
3177  *
3178  * @param connection the connection
3179  * @param preallocated the resources
3180  */
3181 void
3182 dbus_connection_free_preallocated_send (DBusConnection       *connection,
3183                                         DBusPreallocatedSend *preallocated)
3184 {
3185   _dbus_return_if_fail (connection != NULL);
3186   _dbus_return_if_fail (preallocated != NULL);  
3187   _dbus_return_if_fail (connection == preallocated->connection);
3188
3189   _dbus_list_free_link (preallocated->queue_link);
3190   _dbus_counter_unref (preallocated->counter_link->data);
3191   _dbus_list_free_link (preallocated->counter_link);
3192   dbus_free (preallocated);
3193 }
3194
3195 /**
3196  * Sends a message using preallocated resources. This function cannot fail.
3197  * It works identically to dbus_connection_send() in other respects.
3198  * Preallocated resources comes from dbus_connection_preallocate_send().
3199  * This function "consumes" the preallocated resources, they need not
3200  * be freed separately.
3201  *
3202  * @param connection the connection
3203  * @param preallocated the preallocated resources
3204  * @param message the message to send
3205  * @param client_serial return location for client serial assigned to the message
3206  */
3207 void
3208 dbus_connection_send_preallocated (DBusConnection       *connection,
3209                                    DBusPreallocatedSend *preallocated,
3210                                    DBusMessage          *message,
3211                                    dbus_uint32_t        *client_serial)
3212 {
3213   _dbus_return_if_fail (connection != NULL);
3214   _dbus_return_if_fail (preallocated != NULL);
3215   _dbus_return_if_fail (message != NULL);
3216   _dbus_return_if_fail (preallocated->connection == connection);
3217   _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_METHOD_CALL ||
3218                         dbus_message_get_member (message) != NULL);
3219   _dbus_return_if_fail (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL ||
3220                         (dbus_message_get_interface (message) != NULL &&
3221                          dbus_message_get_member (message) != NULL));
3222
3223   CONNECTION_LOCK (connection);
3224
3225 #ifdef HAVE_UNIX_FD_PASSING
3226
3227   if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3228       message->n_unix_fds > 0)
3229     {
3230       /* Refuse to send fds on a connection that cannot handle
3231          them. Unfortunately we cannot return a proper error here, so
3232          the best we can is just return. */
3233       CONNECTION_UNLOCK (connection);
3234       return;
3235     }
3236
3237 #endif
3238
3239   _dbus_connection_send_preallocated_and_unlock (connection,
3240                                                  preallocated,
3241                                                  message, client_serial);
3242 }
3243
3244 static dbus_bool_t
3245 _dbus_connection_send_unlocked_no_update (DBusConnection *connection,
3246                                           DBusMessage    *message,
3247                                           dbus_uint32_t  *client_serial)
3248 {
3249   DBusPreallocatedSend *preallocated;
3250
3251   _dbus_assert (connection != NULL);
3252   _dbus_assert (message != NULL);
3253   
3254   preallocated = _dbus_connection_preallocate_send_unlocked (connection);
3255   if (preallocated == NULL)
3256     return FALSE;
3257
3258   _dbus_connection_send_preallocated_unlocked_no_update (connection,
3259                                                          preallocated,
3260                                                          message,
3261                                                          client_serial);
3262   return TRUE;
3263 }
3264
3265 /**
3266  * Adds a message to the outgoing message queue. Does not block to
3267  * write the message to the network; that happens asynchronously. To
3268  * force the message to be written, call dbus_connection_flush() however
3269  * it is not necessary to call dbus_connection_flush() by hand; the 
3270  * message will be sent the next time the main loop is run. 
3271  * dbus_connection_flush() should only be used, for example, if
3272  * the application was expected to exit before running the main loop.
3273  *
3274  * Because this only queues the message, the only reason it can
3275  * fail is lack of memory. Even if the connection is disconnected,
3276  * no error will be returned. If the function fails due to lack of memory, 
3277  * it returns #FALSE. The function will never fail for other reasons; even 
3278  * if the connection is disconnected, you can queue an outgoing message,
3279  * though obviously it won't be sent.
3280  *
3281  * The message serial is used by the remote application to send a
3282  * reply; see dbus_message_get_serial() or the D-Bus specification.
3283  *
3284  * dbus_message_unref() can be called as soon as this method returns
3285  * as the message queue will hold its own ref until the message is sent.
3286  * 
3287  * @param connection the connection.
3288  * @param message the message to write.
3289  * @param serial return location for message serial, or #NULL if you don't care
3290  * @returns #TRUE on success.
3291  */
3292 dbus_bool_t
3293 dbus_connection_send (DBusConnection *connection,
3294                       DBusMessage    *message,
3295                       dbus_uint32_t  *serial)
3296 {
3297   _dbus_return_val_if_fail (connection != NULL, FALSE);
3298   _dbus_return_val_if_fail (message != NULL, FALSE);
3299
3300   CONNECTION_LOCK (connection);
3301
3302 #ifdef HAVE_UNIX_FD_PASSING
3303
3304   if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3305       message->n_unix_fds > 0)
3306     {
3307       /* Refuse to send fds on a connection that cannot handle
3308          them. Unfortunately we cannot return a proper error here, so
3309          the best we can is just return. */
3310       CONNECTION_UNLOCK (connection);
3311       return FALSE;
3312     }
3313
3314 #endif
3315
3316   return _dbus_connection_send_and_unlock (connection,
3317                                            message,
3318                                            serial);
3319 }
3320
3321 static dbus_bool_t
3322 reply_handler_timeout (void *data)
3323 {
3324   DBusConnection *connection;
3325   DBusDispatchStatus status;
3326   DBusPendingCall *pending = data;
3327
3328   connection = _dbus_pending_call_get_connection_and_lock (pending);
3329
3330   _dbus_pending_call_queue_timeout_error_unlocked (pending, 
3331                                                    connection);
3332   _dbus_connection_remove_timeout_unlocked (connection,
3333                                             _dbus_pending_call_get_timeout_unlocked (pending));
3334   _dbus_pending_call_set_timeout_added_unlocked (pending, FALSE);
3335
3336   _dbus_verbose ("middle\n");
3337   status = _dbus_connection_get_dispatch_status_unlocked (connection);
3338
3339   /* Unlocks, and calls out to user code */
3340   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3341   
3342   return TRUE;
3343 }
3344
3345 /**
3346  * Queues a message to send, as with dbus_connection_send(),
3347  * but also returns a #DBusPendingCall used to receive a reply to the
3348  * message. If no reply is received in the given timeout_milliseconds,
3349  * this function expires the pending reply and generates a synthetic
3350  * error reply (generated in-process, not by the remote application)
3351  * indicating that a timeout occurred.
3352  *
3353  * A #DBusPendingCall will see a reply message before any filters or
3354  * registered object path handlers. See dbus_connection_dispatch() for
3355  * details on when handlers are run.
3356  *
3357  * A #DBusPendingCall will always see exactly one reply message,
3358  * unless it's cancelled with dbus_pending_call_cancel().
3359  * 
3360  * If #NULL is passed for the pending_return, the #DBusPendingCall
3361  * will still be generated internally, and used to track
3362  * the message reply timeout. This means a timeout error will
3363  * occur if no reply arrives, unlike with dbus_connection_send().
3364  *
3365  * If -1 is passed for the timeout, a sane default timeout is used. -1
3366  * is typically the best value for the timeout for this reason, unless
3367  * you want a very short or very long timeout.  If INT_MAX is passed for
3368  * the timeout, no timeout will be set and the call will block forever.
3369  *
3370  * @warning if the connection is disconnected or you try to send Unix
3371  * file descriptors on a connection that does not support them, the
3372  * #DBusPendingCall will be set to #NULL, so be careful with this.
3373  *
3374  * @param connection the connection
3375  * @param message the message to send
3376  * @param pending_return return location for a #DBusPendingCall
3377  * object, or #NULL if connection is disconnected or when you try to
3378  * send Unix file descriptors on a connection that does not support
3379  * them.
3380  * @param timeout_milliseconds timeout in milliseconds, -1 for default or INT_MAX for no timeout
3381  * @returns #FALSE if no memory, #TRUE otherwise.
3382  *
3383  */
3384 dbus_bool_t
3385 dbus_connection_send_with_reply (DBusConnection     *connection,
3386                                  DBusMessage        *message,
3387                                  DBusPendingCall   **pending_return,
3388                                  int                 timeout_milliseconds)
3389 {
3390   DBusPendingCall *pending;
3391   dbus_int32_t serial = -1;
3392   DBusDispatchStatus status;
3393
3394   _dbus_return_val_if_fail (connection != NULL, FALSE);
3395   _dbus_return_val_if_fail (message != NULL, FALSE);
3396   _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3397
3398   if (pending_return)
3399     *pending_return = NULL;
3400
3401   CONNECTION_LOCK (connection);
3402
3403 #ifdef HAVE_UNIX_FD_PASSING
3404
3405   if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3406       message->n_unix_fds > 0)
3407     {
3408       /* Refuse to send fds on a connection that cannot handle
3409          them. Unfortunately we cannot return a proper error here, so
3410          the best we can do is return TRUE but leave *pending_return
3411          as NULL. */
3412       CONNECTION_UNLOCK (connection);
3413       return TRUE;
3414     }
3415
3416 #endif
3417
3418    if (!_dbus_connection_get_is_connected_unlocked (connection))
3419     {
3420       CONNECTION_UNLOCK (connection);
3421
3422       return TRUE;
3423     }
3424
3425   pending = _dbus_pending_call_new_unlocked (connection,
3426                                              timeout_milliseconds,
3427                                              reply_handler_timeout);
3428
3429   if (pending == NULL)
3430     {
3431       CONNECTION_UNLOCK (connection);
3432       return FALSE;
3433     }
3434
3435   /* Assign a serial to the message */
3436   serial = dbus_message_get_serial (message);
3437   if (serial == 0)
3438     {
3439       serial = _dbus_connection_get_next_client_serial (connection);
3440       dbus_message_set_serial (message, serial);
3441     }
3442
3443   if (!_dbus_pending_call_set_timeout_error_unlocked (pending, message, serial))
3444     goto error;
3445     
3446   /* Insert the serial in the pending replies hash;
3447    * hash takes a refcount on DBusPendingCall.
3448    * Also, add the timeout.
3449    */
3450   if (!_dbus_connection_attach_pending_call_unlocked (connection,
3451                                                       pending))
3452     goto error;
3453  
3454   if (!_dbus_connection_send_unlocked_no_update (connection, message, NULL))
3455     {
3456       _dbus_connection_detach_pending_call_and_unlock (connection,
3457                                                        pending);
3458       goto error_unlocked;
3459     }
3460
3461   if (pending_return)
3462     *pending_return = pending; /* hand off refcount */
3463   else
3464     {
3465       _dbus_connection_detach_pending_call_unlocked (connection, pending);
3466       /* we still have a ref to the pending call in this case, we unref
3467        * after unlocking, below
3468        */
3469     }
3470
3471   status = _dbus_connection_get_dispatch_status_unlocked (connection);
3472
3473   /* this calls out to user code */
3474   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3475
3476   if (pending_return == NULL)
3477     dbus_pending_call_unref (pending);
3478   
3479   return TRUE;
3480
3481  error:
3482   CONNECTION_UNLOCK (connection);
3483  error_unlocked:
3484   dbus_pending_call_unref (pending);
3485   return FALSE;
3486 }
3487
3488 /**
3489  * Sends a message and blocks a certain time period while waiting for
3490  * a reply.  This function does not reenter the main loop,
3491  * i.e. messages other than the reply are queued up but not
3492  * processed. This function is used to invoke method calls on a
3493  * remote object.
3494  * 
3495  * If a normal reply is received, it is returned, and removed from the
3496  * incoming message queue. If it is not received, #NULL is returned
3497  * and the error is set to #DBUS_ERROR_NO_REPLY.  If an error reply is
3498  * received, it is converted to a #DBusError and returned as an error,
3499  * then the reply message is deleted and #NULL is returned. If
3500  * something else goes wrong, result is set to whatever is
3501  * appropriate, such as #DBUS_ERROR_NO_MEMORY or
3502  * #DBUS_ERROR_DISCONNECTED.
3503  *
3504  * @warning While this function blocks the calling thread will not be
3505  * processing the incoming message queue. This means you can end up
3506  * deadlocked if the application you're talking to needs you to reply
3507  * to a method. To solve this, either avoid the situation, block in a
3508  * separate thread from the main connection-dispatching thread, or use
3509  * dbus_pending_call_set_notify() to avoid blocking.
3510  *
3511  * @param connection the connection
3512  * @param message the message to send
3513  * @param timeout_milliseconds timeout in milliseconds, -1 for default or INT_MAX for no timeout.
3514  * @param error return location for error message
3515  * @returns the message that is the reply or #NULL with an error code if the
3516  * function fails.
3517  */
3518 DBusMessage*
3519 dbus_connection_send_with_reply_and_block (DBusConnection     *connection,
3520                                            DBusMessage        *message,
3521                                            int                 timeout_milliseconds,
3522                                            DBusError          *error)
3523 {
3524   DBusMessage *reply;
3525   DBusPendingCall *pending;
3526
3527   _dbus_return_val_if_fail (connection != NULL, NULL);
3528   _dbus_return_val_if_fail (message != NULL, NULL);
3529   _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, NULL);
3530   _dbus_return_val_if_error_is_set (error, NULL);
3531
3532 #ifdef HAVE_UNIX_FD_PASSING
3533
3534   CONNECTION_LOCK (connection);
3535   if (!_dbus_transport_can_pass_unix_fd(connection->transport) &&
3536       message->n_unix_fds > 0)
3537     {
3538       CONNECTION_UNLOCK (connection);
3539       dbus_set_error(error, DBUS_ERROR_FAILED, "Cannot send file descriptors on this connection.");
3540       return NULL;
3541     }
3542   CONNECTION_UNLOCK (connection);
3543
3544 #endif
3545
3546   if (!dbus_connection_send_with_reply (connection, message,
3547                                         &pending, timeout_milliseconds))
3548     {
3549       _DBUS_SET_OOM (error);
3550       return NULL;
3551     }
3552
3553   if (pending == NULL)
3554     {
3555       dbus_set_error (error, DBUS_ERROR_DISCONNECTED, "Connection is closed");
3556       return NULL;
3557     }
3558   
3559   dbus_pending_call_block (pending);
3560
3561   reply = dbus_pending_call_steal_reply (pending);
3562   dbus_pending_call_unref (pending);
3563
3564   /* call_complete_and_unlock() called from pending_call_block() should
3565    * always fill this in.
3566    */
3567   _dbus_assert (reply != NULL);
3568   
3569    if (dbus_set_error_from_message (error, reply))
3570     {
3571       dbus_message_unref (reply);
3572       return NULL;
3573     }
3574   else
3575     return reply;
3576 }
3577
3578 /**
3579  * Blocks until the outgoing message queue is empty.
3580  * Assumes connection lock already held.
3581  *
3582  * If you call this, you MUST call update_dispatch_status afterword...
3583  * 
3584  * @param connection the connection.
3585  */
3586 static DBusDispatchStatus
3587 _dbus_connection_flush_unlocked (DBusConnection *connection)
3588 {
3589   /* We have to specify DBUS_ITERATION_DO_READING here because
3590    * otherwise we could have two apps deadlock if they are both doing
3591    * a flush(), and the kernel buffers fill up. This could change the
3592    * dispatch status.
3593    */
3594   DBusDispatchStatus status;
3595
3596   HAVE_LOCK_CHECK (connection);
3597   
3598   while (connection->n_outgoing > 0 &&
3599          _dbus_connection_get_is_connected_unlocked (connection))
3600     {
3601       _dbus_verbose ("doing iteration in\n");
3602       HAVE_LOCK_CHECK (connection);
3603       _dbus_connection_do_iteration_unlocked (connection,
3604                                               NULL,
3605                                               DBUS_ITERATION_DO_READING |
3606                                               DBUS_ITERATION_DO_WRITING |
3607                                               DBUS_ITERATION_BLOCK,
3608                                               -1);
3609     }
3610
3611   HAVE_LOCK_CHECK (connection);
3612   _dbus_verbose ("middle\n");
3613   status = _dbus_connection_get_dispatch_status_unlocked (connection);
3614
3615   HAVE_LOCK_CHECK (connection);
3616   return status;
3617 }
3618
3619 /**
3620  * Blocks until the outgoing message queue is empty.
3621  *
3622  * @param connection the connection.
3623  */
3624 void
3625 dbus_connection_flush (DBusConnection *connection)
3626 {
3627   /* We have to specify DBUS_ITERATION_DO_READING here because
3628    * otherwise we could have two apps deadlock if they are both doing
3629    * a flush(), and the kernel buffers fill up. This could change the
3630    * dispatch status.
3631    */
3632   DBusDispatchStatus status;
3633
3634   _dbus_return_if_fail (connection != NULL);
3635   
3636   CONNECTION_LOCK (connection);
3637
3638   status = _dbus_connection_flush_unlocked (connection);
3639   
3640   HAVE_LOCK_CHECK (connection);
3641   /* Unlocks and calls out to user code */
3642   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3643
3644   _dbus_verbose ("end\n");
3645 }
3646
3647 /**
3648  * This function implements dbus_connection_read_write_dispatch() and
3649  * dbus_connection_read_write() (they pass a different value for the
3650  * dispatch parameter).
3651  * 
3652  * @param connection the connection
3653  * @param timeout_milliseconds max time to block or -1 for infinite
3654  * @param dispatch dispatch new messages or leave them on the incoming queue
3655  * @returns #TRUE if the disconnect message has not been processed
3656  */
3657 static dbus_bool_t
3658 _dbus_connection_read_write_dispatch (DBusConnection *connection,
3659                                      int             timeout_milliseconds, 
3660                                      dbus_bool_t     dispatch)
3661 {
3662   DBusDispatchStatus dstatus;
3663   dbus_bool_t progress_possible;
3664
3665   /* Need to grab a ref here in case we're a private connection and
3666    * the user drops the last ref in a handler we call; see bug 
3667    * https://bugs.freedesktop.org/show_bug.cgi?id=15635
3668    */
3669   dbus_connection_ref (connection);
3670   dstatus = dbus_connection_get_dispatch_status (connection);
3671
3672   if (dispatch && dstatus == DBUS_DISPATCH_DATA_REMAINS)
3673     {
3674       _dbus_verbose ("doing dispatch\n");
3675       dbus_connection_dispatch (connection);
3676       CONNECTION_LOCK (connection);
3677     }
3678   else if (dstatus == DBUS_DISPATCH_NEED_MEMORY)
3679     {
3680       _dbus_verbose ("pausing for memory\n");
3681       _dbus_memory_pause_based_on_timeout (timeout_milliseconds);
3682       CONNECTION_LOCK (connection);
3683     }
3684   else
3685     {
3686       CONNECTION_LOCK (connection);
3687       if (_dbus_connection_get_is_connected_unlocked (connection))
3688         {
3689           _dbus_verbose ("doing iteration\n");
3690           _dbus_connection_do_iteration_unlocked (connection,
3691                                                   NULL,
3692                                                   DBUS_ITERATION_DO_READING |
3693                                                   DBUS_ITERATION_DO_WRITING |
3694                                                   DBUS_ITERATION_BLOCK,
3695                                                   timeout_milliseconds);
3696         }
3697     }
3698   
3699   HAVE_LOCK_CHECK (connection);
3700   /* If we can dispatch, we can make progress until the Disconnected message
3701    * has been processed; if we can only read/write, we can make progress
3702    * as long as the transport is open.
3703    */
3704   if (dispatch)
3705     progress_possible = connection->n_incoming != 0 ||
3706       connection->disconnect_message_link != NULL;
3707   else
3708     progress_possible = _dbus_connection_get_is_connected_unlocked (connection);
3709
3710   CONNECTION_UNLOCK (connection);
3711
3712   dbus_connection_unref (connection);
3713
3714   return progress_possible; /* TRUE if we can make more progress */
3715 }
3716
3717
3718 /**
3719  * This function is intended for use with applications that don't want
3720  * to write a main loop and deal with #DBusWatch and #DBusTimeout. An
3721  * example usage would be:
3722  * 
3723  * @code
3724  *   while (dbus_connection_read_write_dispatch (connection, -1))
3725  *     ; // empty loop body
3726  * @endcode
3727  * 
3728  * In this usage you would normally have set up a filter function to look
3729  * at each message as it is dispatched. The loop terminates when the last
3730  * message from the connection (the disconnected signal) is processed.
3731  * 
3732  * If there are messages to dispatch, this function will
3733  * dbus_connection_dispatch() once, and return. If there are no
3734  * messages to dispatch, this function will block until it can read or
3735  * write, then read or write, then return.
3736  *
3737  * The way to think of this function is that it either makes some sort
3738  * of progress, or it blocks. Note that, while it is blocked on I/O, it
3739  * cannot be interrupted (even by other threads), which makes this function
3740  * unsuitable for applications that do more than just react to received
3741  * messages.
3742  *
3743  * The return value indicates whether the disconnect message has been
3744  * processed, NOT whether the connection is connected. This is
3745  * important because even after disconnecting, you want to process any
3746  * messages you received prior to the disconnect.
3747  *
3748  * @param connection the connection
3749  * @param timeout_milliseconds max time to block or -1 for infinite
3750  * @returns #TRUE if the disconnect message has not been processed
3751  */
3752 dbus_bool_t
3753 dbus_connection_read_write_dispatch (DBusConnection *connection,
3754                                      int             timeout_milliseconds)
3755 {
3756   _dbus_return_val_if_fail (connection != NULL, FALSE);
3757   _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3758    return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, TRUE);
3759 }
3760
3761 /** 
3762  * This function is intended for use with applications that don't want to
3763  * write a main loop and deal with #DBusWatch and #DBusTimeout. See also
3764  * dbus_connection_read_write_dispatch().
3765  * 
3766  * As long as the connection is open, this function will block until it can
3767  * read or write, then read or write, then return #TRUE.
3768  *
3769  * If the connection is closed, the function returns #FALSE.
3770  *
3771  * The return value indicates whether reading or writing is still
3772  * possible, i.e. whether the connection is connected.
3773  *
3774  * Note that even after disconnection, messages may remain in the
3775  * incoming queue that need to be
3776  * processed. dbus_connection_read_write_dispatch() dispatches
3777  * incoming messages for you; with dbus_connection_read_write() you
3778  * have to arrange to drain the incoming queue yourself.
3779  * 
3780  * @param connection the connection 
3781  * @param timeout_milliseconds max time to block or -1 for infinite 
3782  * @returns #TRUE if still connected
3783  */
3784 dbus_bool_t 
3785 dbus_connection_read_write (DBusConnection *connection, 
3786                             int             timeout_milliseconds) 
3787
3788   _dbus_return_val_if_fail (connection != NULL, FALSE);
3789   _dbus_return_val_if_fail (timeout_milliseconds >= 0 || timeout_milliseconds == -1, FALSE);
3790    return _dbus_connection_read_write_dispatch(connection, timeout_milliseconds, FALSE);
3791 }
3792
3793 /* We need to call this anytime we pop the head of the queue, and then
3794  * update_dispatch_status_and_unlock needs to be called afterward
3795  * which will "process" the disconnected message and set
3796  * disconnected_message_processed.
3797  */
3798 static void
3799 check_disconnected_message_arrived_unlocked (DBusConnection *connection,
3800                                              DBusMessage    *head_of_queue)
3801 {
3802   HAVE_LOCK_CHECK (connection);
3803
3804   /* checking that the link is NULL is an optimization to avoid the is_signal call */
3805   if (connection->disconnect_message_link == NULL &&
3806       dbus_message_is_signal (head_of_queue,
3807                               DBUS_INTERFACE_LOCAL,
3808                               "Disconnected"))
3809     {
3810       connection->disconnected_message_arrived = TRUE;
3811     }
3812 }
3813
3814 /**
3815  * Returns the first-received message from the incoming message queue,
3816  * leaving it in the queue. If the queue is empty, returns #NULL.
3817  * 
3818  * The caller does not own a reference to the returned message, and
3819  * must either return it using dbus_connection_return_message() or
3820  * keep it after calling dbus_connection_steal_borrowed_message(). No
3821  * one can get at the message while its borrowed, so return it as
3822  * quickly as possible and don't keep a reference to it after
3823  * returning it. If you need to keep the message, make a copy of it.
3824  *
3825  * dbus_connection_dispatch() will block if called while a borrowed
3826  * message is outstanding; only one piece of code can be playing with
3827  * the incoming queue at a time. This function will block if called
3828  * during a dbus_connection_dispatch().
3829  *
3830  * @param connection the connection.
3831  * @returns next message in the incoming queue.
3832  */
3833 DBusMessage*
3834 dbus_connection_borrow_message (DBusConnection *connection)
3835 {
3836   DBusDispatchStatus status;
3837   DBusMessage *message;
3838
3839   _dbus_return_val_if_fail (connection != NULL, NULL);
3840
3841   _dbus_verbose ("start\n");
3842   
3843   /* this is called for the side effect that it queues
3844    * up any messages from the transport
3845    */
3846   status = dbus_connection_get_dispatch_status (connection);
3847   if (status != DBUS_DISPATCH_DATA_REMAINS)
3848     return NULL;
3849   
3850   CONNECTION_LOCK (connection);
3851
3852   _dbus_connection_acquire_dispatch (connection);
3853
3854   /* While a message is outstanding, the dispatch lock is held */
3855   _dbus_assert (connection->message_borrowed == NULL);
3856
3857   connection->message_borrowed = _dbus_list_get_first (&connection->incoming_messages);
3858   
3859   message = connection->message_borrowed;
3860
3861   check_disconnected_message_arrived_unlocked (connection, message);
3862   
3863   /* Note that we KEEP the dispatch lock until the message is returned */
3864   if (message == NULL)
3865     _dbus_connection_release_dispatch (connection);
3866
3867   CONNECTION_UNLOCK (connection);
3868
3869   /* We don't update dispatch status until it's returned or stolen */
3870   
3871   return message;
3872 }
3873
3874 /**
3875  * Used to return a message after peeking at it using
3876  * dbus_connection_borrow_message(). Only called if
3877  * message from dbus_connection_borrow_message() was non-#NULL.
3878  *
3879  * @param connection the connection
3880  * @param message the message from dbus_connection_borrow_message()
3881  */
3882 void
3883 dbus_connection_return_message (DBusConnection *connection,
3884                                 DBusMessage    *message)
3885 {
3886   DBusDispatchStatus status;
3887   
3888   _dbus_return_if_fail (connection != NULL);
3889   _dbus_return_if_fail (message != NULL);
3890   _dbus_return_if_fail (message == connection->message_borrowed);
3891   _dbus_return_if_fail (connection->dispatch_acquired);
3892   
3893   CONNECTION_LOCK (connection);
3894   
3895   _dbus_assert (message == connection->message_borrowed);
3896   
3897   connection->message_borrowed = NULL;
3898
3899   _dbus_connection_release_dispatch (connection); 
3900
3901   status = _dbus_connection_get_dispatch_status_unlocked (connection);
3902   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3903 }
3904
3905 /**
3906  * Used to keep a message after peeking at it using
3907  * dbus_connection_borrow_message(). Before using this function, see
3908  * the caveats/warnings in the documentation for
3909  * dbus_connection_pop_message().
3910  *
3911  * @param connection the connection
3912  * @param message the message from dbus_connection_borrow_message()
3913  */
3914 void
3915 dbus_connection_steal_borrowed_message (DBusConnection *connection,
3916                                         DBusMessage    *message)
3917 {
3918   DBusMessage *pop_message;
3919   DBusDispatchStatus status;
3920
3921   _dbus_return_if_fail (connection != NULL);
3922   _dbus_return_if_fail (message != NULL);
3923   _dbus_return_if_fail (message == connection->message_borrowed);
3924   _dbus_return_if_fail (connection->dispatch_acquired);
3925   
3926   CONNECTION_LOCK (connection);
3927  
3928   _dbus_assert (message == connection->message_borrowed);
3929
3930   pop_message = _dbus_list_pop_first (&connection->incoming_messages);
3931   _dbus_assert (message == pop_message);
3932   
3933   connection->n_incoming -= 1;
3934  
3935   _dbus_verbose ("Incoming message %p stolen from queue, %d incoming\n",
3936                  message, connection->n_incoming);
3937  
3938   connection->message_borrowed = NULL;
3939
3940   _dbus_connection_release_dispatch (connection);
3941
3942   status = _dbus_connection_get_dispatch_status_unlocked (connection);
3943   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
3944 }
3945
3946 /* See dbus_connection_pop_message, but requires the caller to own
3947  * the lock before calling. May drop the lock while running.
3948  */
3949 static DBusList*
3950 _dbus_connection_pop_message_link_unlocked (DBusConnection *connection)
3951 {
3952   HAVE_LOCK_CHECK (connection);
3953   
3954   _dbus_assert (connection->message_borrowed == NULL);
3955   
3956   if (connection->n_incoming > 0)
3957     {
3958       DBusList *link;
3959
3960       link = _dbus_list_pop_first_link (&connection->incoming_messages);
3961       connection->n_incoming -= 1;
3962
3963       _dbus_verbose ("Message %p (%s %s %s %s '%s') removed from incoming queue %p, %d incoming\n",
3964                      link->data,
3965                      dbus_message_type_to_string (dbus_message_get_type (link->data)),
3966                      dbus_message_get_path (link->data) ?
3967                      dbus_message_get_path (link->data) :
3968                      "no path",
3969                      dbus_message_get_interface (link->data) ?
3970                      dbus_message_get_interface (link->data) :
3971                      "no interface",
3972                      dbus_message_get_member (link->data) ?
3973                      dbus_message_get_member (link->data) :
3974                      "no member",
3975                      dbus_message_get_signature (link->data),
3976                      connection, connection->n_incoming);
3977
3978       check_disconnected_message_arrived_unlocked (connection, link->data);
3979       
3980       return link;
3981     }
3982   else
3983     return NULL;
3984 }
3985
3986 /* See dbus_connection_pop_message, but requires the caller to own
3987  * the lock before calling. May drop the lock while running.
3988  */
3989 static DBusMessage*
3990 _dbus_connection_pop_message_unlocked (DBusConnection *connection)
3991 {
3992   DBusList *link;
3993
3994   HAVE_LOCK_CHECK (connection);
3995   
3996   link = _dbus_connection_pop_message_link_unlocked (connection);
3997
3998   if (link != NULL)
3999     {
4000       DBusMessage *message;
4001       
4002       message = link->data;
4003       
4004       _dbus_list_free_link (link);
4005       
4006       return message;
4007     }
4008   else
4009     return NULL;
4010 }
4011
4012 static void
4013 _dbus_connection_putback_message_link_unlocked (DBusConnection *connection,
4014                                                 DBusList       *message_link)
4015 {
4016   HAVE_LOCK_CHECK (connection);
4017   
4018   _dbus_assert (message_link != NULL);
4019   /* You can't borrow a message while a link is outstanding */
4020   _dbus_assert (connection->message_borrowed == NULL);
4021   /* We had to have the dispatch lock across the pop/putback */
4022   _dbus_assert (connection->dispatch_acquired);
4023
4024   _dbus_list_prepend_link (&connection->incoming_messages,
4025                            message_link);
4026   connection->n_incoming += 1;
4027
4028   _dbus_verbose ("Message %p (%s %s %s '%s') put back into queue %p, %d incoming\n",
4029                  message_link->data,
4030                  dbus_message_type_to_string (dbus_message_get_type (message_link->data)),
4031                  dbus_message_get_interface (message_link->data) ?
4032                  dbus_message_get_interface (message_link->data) :
4033                  "no interface",
4034                  dbus_message_get_member (message_link->data) ?
4035                  dbus_message_get_member (message_link->data) :
4036                  "no member",
4037                  dbus_message_get_signature (message_link->data),
4038                  connection, connection->n_incoming);
4039 }
4040
4041 /**
4042  * Returns the first-received message from the incoming message queue,
4043  * removing it from the queue. The caller owns a reference to the
4044  * returned message. If the queue is empty, returns #NULL.
4045  *
4046  * This function bypasses any message handlers that are registered,
4047  * and so using it is usually wrong. Instead, let the main loop invoke
4048  * dbus_connection_dispatch(). Popping messages manually is only
4049  * useful in very simple programs that don't share a #DBusConnection
4050  * with any libraries or other modules.
4051  *
4052  * There is a lock that covers all ways of accessing the incoming message
4053  * queue, so dbus_connection_dispatch(), dbus_connection_pop_message(),
4054  * dbus_connection_borrow_message(), etc. will all block while one of the others
4055  * in the group is running.
4056  * 
4057  * @param connection the connection.
4058  * @returns next message in the incoming queue.
4059  */
4060 DBusMessage*
4061 dbus_connection_pop_message (DBusConnection *connection)
4062 {
4063   DBusMessage *message;
4064   DBusDispatchStatus status;
4065
4066   _dbus_verbose ("start\n");
4067   
4068   /* this is called for the side effect that it queues
4069    * up any messages from the transport
4070    */
4071   status = dbus_connection_get_dispatch_status (connection);
4072   if (status != DBUS_DISPATCH_DATA_REMAINS)
4073     return NULL;
4074   
4075   CONNECTION_LOCK (connection);
4076   _dbus_connection_acquire_dispatch (connection);
4077   HAVE_LOCK_CHECK (connection);
4078   
4079   message = _dbus_connection_pop_message_unlocked (connection);
4080
4081   _dbus_verbose ("Returning popped message %p\n", message);    
4082
4083   _dbus_connection_release_dispatch (connection);
4084
4085   status = _dbus_connection_get_dispatch_status_unlocked (connection);
4086   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4087   
4088   return message;
4089 }
4090
4091 /**
4092  * Acquire the dispatcher. This is a separate lock so the main
4093  * connection lock can be dropped to call out to application dispatch
4094  * handlers.
4095  *
4096  * @param connection the connection.
4097  */
4098 static void
4099 _dbus_connection_acquire_dispatch (DBusConnection *connection)
4100 {
4101   HAVE_LOCK_CHECK (connection);
4102
4103   _dbus_connection_ref_unlocked (connection);
4104   CONNECTION_UNLOCK (connection);
4105   
4106   _dbus_verbose ("locking dispatch_mutex\n");
4107   _dbus_mutex_lock (connection->dispatch_mutex);
4108
4109   while (connection->dispatch_acquired)
4110     {
4111       _dbus_verbose ("waiting for dispatch to be acquirable\n");
4112       _dbus_condvar_wait (connection->dispatch_cond, 
4113                           connection->dispatch_mutex);
4114     }
4115   
4116   _dbus_assert (!connection->dispatch_acquired);
4117
4118   connection->dispatch_acquired = TRUE;
4119
4120   _dbus_verbose ("unlocking dispatch_mutex\n");
4121   _dbus_mutex_unlock (connection->dispatch_mutex);
4122   
4123   CONNECTION_LOCK (connection);
4124   _dbus_connection_unref_unlocked (connection);
4125 }
4126
4127 /**
4128  * Release the dispatcher when you're done with it. Only call
4129  * after you've acquired the dispatcher. Wakes up at most one
4130  * thread currently waiting to acquire the dispatcher.
4131  *
4132  * @param connection the connection.
4133  */
4134 static void
4135 _dbus_connection_release_dispatch (DBusConnection *connection)
4136 {
4137   HAVE_LOCK_CHECK (connection);
4138   
4139   _dbus_verbose ("locking dispatch_mutex\n");
4140   _dbus_mutex_lock (connection->dispatch_mutex);
4141   
4142   _dbus_assert (connection->dispatch_acquired);
4143
4144   connection->dispatch_acquired = FALSE;
4145   _dbus_condvar_wake_one (connection->dispatch_cond);
4146
4147   _dbus_verbose ("unlocking dispatch_mutex\n");
4148   _dbus_mutex_unlock (connection->dispatch_mutex);
4149 }
4150
4151 static void
4152 _dbus_connection_failed_pop (DBusConnection *connection,
4153                              DBusList       *message_link)
4154 {
4155   _dbus_list_prepend_link (&connection->incoming_messages,
4156                            message_link);
4157   connection->n_incoming += 1;
4158 }
4159
4160 /* Note this may be called multiple times since we don't track whether we already did it */
4161 static void
4162 notify_disconnected_unlocked (DBusConnection *connection)
4163 {
4164   HAVE_LOCK_CHECK (connection);
4165
4166   /* Set the weakref in dbus-bus.c to NULL, so nobody will get a disconnected
4167    * connection from dbus_bus_get(). We make the same guarantee for
4168    * dbus_connection_open() but in a different way since we don't want to
4169    * unref right here; we instead check for connectedness before returning
4170    * the connection from the hash.
4171    */
4172   _dbus_bus_notify_shared_connection_disconnected_unlocked (connection);
4173
4174   /* Dump the outgoing queue, we aren't going to be able to
4175    * send it now, and we'd like accessors like
4176    * dbus_connection_get_outgoing_size() to be accurate.
4177    */
4178   if (connection->n_outgoing > 0)
4179     {
4180       DBusList *link;
4181       
4182       _dbus_verbose ("Dropping %d outgoing messages since we're disconnected\n",
4183                      connection->n_outgoing);
4184       
4185       while ((link = _dbus_list_get_last_link (&connection->outgoing_messages)))
4186         {
4187           _dbus_connection_message_sent (connection, link->data);
4188         }
4189     } 
4190 }
4191
4192 /* Note this may be called multiple times since we don't track whether we already did it */
4193 static DBusDispatchStatus
4194 notify_disconnected_and_dispatch_complete_unlocked (DBusConnection *connection)
4195 {
4196   HAVE_LOCK_CHECK (connection);
4197   
4198   if (connection->disconnect_message_link != NULL)
4199     {
4200       _dbus_verbose ("Sending disconnect message\n");
4201       
4202       /* If we have pending calls, queue their timeouts - we want the Disconnected
4203        * to be the last message, after these timeouts.
4204        */
4205       connection_timeout_and_complete_all_pending_calls_unlocked (connection);
4206       
4207       /* We haven't sent the disconnect message already,
4208        * and all real messages have been queued up.
4209        */
4210       _dbus_connection_queue_synthesized_message_link (connection,
4211                                                        connection->disconnect_message_link);
4212       connection->disconnect_message_link = NULL;
4213
4214       return DBUS_DISPATCH_DATA_REMAINS;
4215     }
4216
4217   return DBUS_DISPATCH_COMPLETE;
4218 }
4219
4220 static DBusDispatchStatus
4221 _dbus_connection_get_dispatch_status_unlocked (DBusConnection *connection)
4222 {
4223   HAVE_LOCK_CHECK (connection);
4224   
4225   if (connection->n_incoming > 0)
4226     return DBUS_DISPATCH_DATA_REMAINS;
4227   else if (!_dbus_transport_queue_messages (connection->transport))
4228     return DBUS_DISPATCH_NEED_MEMORY;
4229   else
4230     {
4231       DBusDispatchStatus status;
4232       dbus_bool_t is_connected;
4233       
4234       status = _dbus_transport_get_dispatch_status (connection->transport);
4235       is_connected = _dbus_transport_get_is_connected (connection->transport);
4236
4237       _dbus_verbose ("dispatch status = %s is_connected = %d\n",
4238                      DISPATCH_STATUS_NAME (status), is_connected);
4239       
4240       if (!is_connected)
4241         {
4242           /* It's possible this would be better done by having an explicit
4243            * notification from _dbus_transport_disconnect() that would
4244            * synchronously do this, instead of waiting for the next dispatch
4245            * status check. However, probably not good to change until it causes
4246            * a problem.
4247            */
4248           notify_disconnected_unlocked (connection);
4249
4250           /* I'm not sure this is needed; the idea is that we want to
4251            * queue the Disconnected only after we've read all the
4252            * messages, but if we're disconnected maybe we are guaranteed
4253            * to have read them all ?
4254            */
4255           if (status == DBUS_DISPATCH_COMPLETE)
4256             status = notify_disconnected_and_dispatch_complete_unlocked (connection);
4257         }
4258       
4259       if (status != DBUS_DISPATCH_COMPLETE)
4260         return status;
4261       else if (connection->n_incoming > 0)
4262         return DBUS_DISPATCH_DATA_REMAINS;
4263       else
4264         return DBUS_DISPATCH_COMPLETE;
4265     }
4266 }
4267
4268 static void
4269 _dbus_connection_update_dispatch_status_and_unlock (DBusConnection    *connection,
4270                                                     DBusDispatchStatus new_status)
4271 {
4272   dbus_bool_t changed;
4273   DBusDispatchStatusFunction function;
4274   void *data;
4275
4276   HAVE_LOCK_CHECK (connection);
4277
4278   _dbus_connection_ref_unlocked (connection);
4279
4280   changed = new_status != connection->last_dispatch_status;
4281
4282   connection->last_dispatch_status = new_status;
4283
4284   function = connection->dispatch_status_function;
4285   data = connection->dispatch_status_data;
4286
4287   if (connection->disconnected_message_arrived &&
4288       !connection->disconnected_message_processed)
4289     {
4290       connection->disconnected_message_processed = TRUE;
4291       
4292       /* this does an unref, but we have a ref
4293        * so we should not run the finalizer here
4294        * inside the lock.
4295        */
4296       connection_forget_shared_unlocked (connection);
4297
4298       if (connection->exit_on_disconnect)
4299         {
4300           CONNECTION_UNLOCK (connection);            
4301           
4302           _dbus_verbose ("Exiting on Disconnected signal\n");
4303           _dbus_exit (1);
4304           _dbus_assert_not_reached ("Call to exit() returned");
4305         }
4306     }
4307   
4308   /* We drop the lock */
4309   CONNECTION_UNLOCK (connection);
4310   
4311   if (changed && function)
4312     {
4313       _dbus_verbose ("Notifying of change to dispatch status of %p now %d (%s)\n",
4314                      connection, new_status,
4315                      DISPATCH_STATUS_NAME (new_status));
4316       (* function) (connection, new_status, data);      
4317     }
4318   
4319   dbus_connection_unref (connection);
4320 }
4321
4322 /**
4323  * Gets the current state of the incoming message queue.
4324  * #DBUS_DISPATCH_DATA_REMAINS indicates that the message queue
4325  * may contain messages. #DBUS_DISPATCH_COMPLETE indicates that the
4326  * incoming queue is empty. #DBUS_DISPATCH_NEED_MEMORY indicates that
4327  * there could be data, but we can't know for sure without more
4328  * memory.
4329  *
4330  * To process the incoming message queue, use dbus_connection_dispatch()
4331  * or (in rare cases) dbus_connection_pop_message().
4332  *
4333  * Note, #DBUS_DISPATCH_DATA_REMAINS really means that either we
4334  * have messages in the queue, or we have raw bytes buffered up
4335  * that need to be parsed. When these bytes are parsed, they
4336  * may not add up to an entire message. Thus, it's possible
4337  * to see a status of #DBUS_DISPATCH_DATA_REMAINS but not
4338  * have a message yet.
4339  *
4340  * In particular this happens on initial connection, because all sorts
4341  * of authentication protocol stuff has to be parsed before the
4342  * first message arrives.
4343  * 
4344  * @param connection the connection.
4345  * @returns current dispatch status
4346  */
4347 DBusDispatchStatus
4348 dbus_connection_get_dispatch_status (DBusConnection *connection)
4349 {
4350   DBusDispatchStatus status;
4351
4352   _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
4353
4354   _dbus_verbose ("start\n");
4355   
4356   CONNECTION_LOCK (connection);
4357
4358   status = _dbus_connection_get_dispatch_status_unlocked (connection);
4359   
4360   CONNECTION_UNLOCK (connection);
4361
4362   return status;
4363 }
4364
4365 /**
4366  * Filter funtion for handling the Peer standard interface.
4367  */
4368 static DBusHandlerResult
4369 _dbus_connection_peer_filter_unlocked_no_update (DBusConnection *connection,
4370                                                  DBusMessage    *message)
4371 {
4372   if (connection->route_peer_messages && dbus_message_get_destination (message) != NULL)
4373     {
4374       /* This means we're letting the bus route this message */
4375       return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4376     }
4377   else if (dbus_message_is_method_call (message,
4378                                         DBUS_INTERFACE_PEER,
4379                                         "Ping"))
4380     {
4381       DBusMessage *ret;
4382       dbus_bool_t sent;
4383       
4384       ret = dbus_message_new_method_return (message);
4385       if (ret == NULL)
4386         return DBUS_HANDLER_RESULT_NEED_MEMORY;
4387      
4388       sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4389
4390       dbus_message_unref (ret);
4391
4392       if (!sent)
4393         return DBUS_HANDLER_RESULT_NEED_MEMORY;
4394       
4395       return DBUS_HANDLER_RESULT_HANDLED;
4396     }
4397   else if (dbus_message_is_method_call (message,
4398                                         DBUS_INTERFACE_PEER,
4399                                         "GetMachineId"))
4400     {
4401       DBusMessage *ret;
4402       dbus_bool_t sent;
4403       DBusString uuid;
4404       
4405       ret = dbus_message_new_method_return (message);
4406       if (ret == NULL)
4407         return DBUS_HANDLER_RESULT_NEED_MEMORY;
4408
4409       sent = FALSE;
4410       _dbus_string_init (&uuid);
4411       if (_dbus_get_local_machine_uuid_encoded (&uuid))
4412         {
4413           const char *v_STRING = _dbus_string_get_const_data (&uuid);
4414           if (dbus_message_append_args (ret,
4415                                         DBUS_TYPE_STRING, &v_STRING,
4416                                         DBUS_TYPE_INVALID))
4417             {
4418               sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4419             }
4420         }
4421       _dbus_string_free (&uuid);
4422       
4423       dbus_message_unref (ret);
4424
4425       if (!sent)
4426         return DBUS_HANDLER_RESULT_NEED_MEMORY;
4427       
4428       return DBUS_HANDLER_RESULT_HANDLED;
4429     }
4430   else if (dbus_message_has_interface (message, DBUS_INTERFACE_PEER))
4431     {
4432       /* We need to bounce anything else with this interface, otherwise apps
4433        * could start extending the interface and when we added extensions
4434        * here to DBusConnection we'd break those apps.
4435        */
4436       
4437       DBusMessage *ret;
4438       dbus_bool_t sent;
4439       
4440       ret = dbus_message_new_error (message,
4441                                     DBUS_ERROR_UNKNOWN_METHOD,
4442                                     "Unknown method invoked on org.freedesktop.DBus.Peer interface");
4443       if (ret == NULL)
4444         return DBUS_HANDLER_RESULT_NEED_MEMORY;
4445       
4446       sent = _dbus_connection_send_unlocked_no_update (connection, ret, NULL);
4447       
4448       dbus_message_unref (ret);
4449       
4450       if (!sent)
4451         return DBUS_HANDLER_RESULT_NEED_MEMORY;
4452       
4453       return DBUS_HANDLER_RESULT_HANDLED;
4454     }
4455   else
4456     {
4457       return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4458     }
4459 }
4460
4461 /**
4462 * Processes all builtin filter functions
4463 *
4464 * If the spec specifies a standard interface
4465 * they should be processed from this method
4466 **/
4467 static DBusHandlerResult
4468 _dbus_connection_run_builtin_filters_unlocked_no_update (DBusConnection *connection,
4469                                                            DBusMessage    *message)
4470 {
4471   /* We just run one filter for now but have the option to run more
4472      if the spec calls for it in the future */
4473
4474   return _dbus_connection_peer_filter_unlocked_no_update (connection, message);
4475 }
4476
4477 /**
4478  * Processes any incoming data.
4479  *
4480  * If there's incoming raw data that has not yet been parsed, it is
4481  * parsed, which may or may not result in adding messages to the
4482  * incoming queue.
4483  *
4484  * The incoming data buffer is filled when the connection reads from
4485  * its underlying transport (such as a socket).  Reading usually
4486  * happens in dbus_watch_handle() or dbus_connection_read_write().
4487  * 
4488  * If there are complete messages in the incoming queue,
4489  * dbus_connection_dispatch() removes one message from the queue and
4490  * processes it. Processing has three steps.
4491  *
4492  * First, any method replies are passed to #DBusPendingCall or
4493  * dbus_connection_send_with_reply_and_block() in order to
4494  * complete the pending method call.
4495  * 
4496  * Second, any filters registered with dbus_connection_add_filter()
4497  * are run. If any filter returns #DBUS_HANDLER_RESULT_HANDLED
4498  * then processing stops after that filter.
4499  *
4500  * Third, if the message is a method call it is forwarded to
4501  * any registered object path handlers added with
4502  * dbus_connection_register_object_path() or
4503  * dbus_connection_register_fallback().
4504  *
4505  * A single call to dbus_connection_dispatch() will process at most
4506  * one message; it will not clear the entire message queue.
4507  *
4508  * Be careful about calling dbus_connection_dispatch() from inside a
4509  * message handler, i.e. calling dbus_connection_dispatch()
4510  * recursively.  If threads have been initialized with a recursive
4511  * mutex function, then this will not deadlock; however, it can
4512  * certainly confuse your application.
4513  * 
4514  * @todo some FIXME in here about handling DBUS_HANDLER_RESULT_NEED_MEMORY
4515  * 
4516  * @param connection the connection
4517  * @returns dispatch status, see dbus_connection_get_dispatch_status()
4518  */
4519 DBusDispatchStatus
4520 dbus_connection_dispatch (DBusConnection *connection)
4521 {
4522   DBusMessage *message;
4523   DBusList *link, *filter_list_copy, *message_link;
4524   DBusHandlerResult result;
4525   DBusPendingCall *pending;
4526   dbus_int32_t reply_serial;
4527   DBusDispatchStatus status;
4528
4529   _dbus_return_val_if_fail (connection != NULL, DBUS_DISPATCH_COMPLETE);
4530
4531   _dbus_verbose ("\n");
4532   
4533   CONNECTION_LOCK (connection);
4534   status = _dbus_connection_get_dispatch_status_unlocked (connection);
4535   if (status != DBUS_DISPATCH_DATA_REMAINS)
4536     {
4537       /* unlocks and calls out to user code */
4538       _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4539       return status;
4540     }
4541   
4542   /* We need to ref the connection since the callback could potentially
4543    * drop the last ref to it
4544    */
4545   _dbus_connection_ref_unlocked (connection);
4546
4547   _dbus_connection_acquire_dispatch (connection);
4548   HAVE_LOCK_CHECK (connection);
4549
4550   message_link = _dbus_connection_pop_message_link_unlocked (connection);
4551   if (message_link == NULL)
4552     {
4553       /* another thread dispatched our stuff */
4554
4555       _dbus_verbose ("another thread dispatched message (during acquire_dispatch above)\n");
4556       
4557       _dbus_connection_release_dispatch (connection);
4558
4559       status = _dbus_connection_get_dispatch_status_unlocked (connection);
4560
4561       _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4562       
4563       dbus_connection_unref (connection);
4564       
4565       return status;
4566     }
4567
4568   message = message_link->data;
4569
4570   _dbus_verbose (" dispatching message %p (%s %s %s '%s')\n",
4571                  message,
4572                  dbus_message_type_to_string (dbus_message_get_type (message)),
4573                  dbus_message_get_interface (message) ?
4574                  dbus_message_get_interface (message) :
4575                  "no interface",
4576                  dbus_message_get_member (message) ?
4577                  dbus_message_get_member (message) :
4578                  "no member",
4579                  dbus_message_get_signature (message));
4580
4581   result = DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
4582   
4583   /* Pending call handling must be first, because if you do
4584    * dbus_connection_send_with_reply_and_block() or
4585    * dbus_pending_call_block() then no handlers/filters will be run on
4586    * the reply. We want consistent semantics in the case where we
4587    * dbus_connection_dispatch() the reply.
4588    */
4589   
4590   reply_serial = dbus_message_get_reply_serial (message);
4591   pending = _dbus_hash_table_lookup_int (connection->pending_replies,
4592                                          reply_serial);
4593   if (pending)
4594     {
4595       _dbus_verbose ("Dispatching a pending reply\n");
4596       complete_pending_call_and_unlock (connection, pending, message);
4597       pending = NULL; /* it's probably unref'd */
4598       
4599       CONNECTION_LOCK (connection);
4600       _dbus_verbose ("pending call completed in dispatch\n");
4601       result = DBUS_HANDLER_RESULT_HANDLED;
4602       goto out;
4603     }
4604
4605   result = _dbus_connection_run_builtin_filters_unlocked_no_update (connection, message);
4606   if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4607     goto out;
4608  
4609   if (!_dbus_list_copy (&connection->filter_list, &filter_list_copy))
4610     {
4611       _dbus_connection_release_dispatch (connection);
4612       HAVE_LOCK_CHECK (connection);
4613       
4614       _dbus_connection_failed_pop (connection, message_link);
4615
4616       /* unlocks and calls user code */
4617       _dbus_connection_update_dispatch_status_and_unlock (connection,
4618                                                           DBUS_DISPATCH_NEED_MEMORY);
4619
4620       if (pending)
4621         dbus_pending_call_unref (pending);
4622       dbus_connection_unref (connection);
4623       
4624       return DBUS_DISPATCH_NEED_MEMORY;
4625     }
4626   
4627   _dbus_list_foreach (&filter_list_copy,
4628                       (DBusForeachFunction)_dbus_message_filter_ref,
4629                       NULL);
4630
4631   /* We're still protected from dispatch() reentrancy here
4632    * since we acquired the dispatcher
4633    */
4634   CONNECTION_UNLOCK (connection);
4635   
4636   link = _dbus_list_get_first_link (&filter_list_copy);
4637   while (link != NULL)
4638     {
4639       DBusMessageFilter *filter = link->data;
4640       DBusList *next = _dbus_list_get_next_link (&filter_list_copy, link);
4641
4642       if (filter->function == NULL)
4643         {
4644           _dbus_verbose ("  filter was removed in a callback function\n");
4645           link = next;
4646           continue;
4647         }
4648
4649       _dbus_verbose ("  running filter on message %p\n", message);
4650       result = (* filter->function) (connection, message, filter->user_data);
4651
4652       if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4653         break;
4654
4655       link = next;
4656     }
4657
4658   _dbus_list_foreach (&filter_list_copy,
4659                       (DBusForeachFunction)_dbus_message_filter_unref,
4660                       NULL);
4661   _dbus_list_clear (&filter_list_copy);
4662   
4663   CONNECTION_LOCK (connection);
4664
4665   if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
4666     {
4667       _dbus_verbose ("No memory\n");
4668       goto out;
4669     }
4670   else if (result == DBUS_HANDLER_RESULT_HANDLED)
4671     {
4672       _dbus_verbose ("filter handled message in dispatch\n");
4673       goto out;
4674     }
4675
4676   /* We're still protected from dispatch() reentrancy here
4677    * since we acquired the dispatcher
4678    */
4679   _dbus_verbose ("  running object path dispatch on message %p (%s %s %s '%s')\n",
4680                  message,
4681                  dbus_message_type_to_string (dbus_message_get_type (message)),
4682                  dbus_message_get_interface (message) ?
4683                  dbus_message_get_interface (message) :
4684                  "no interface",
4685                  dbus_message_get_member (message) ?
4686                  dbus_message_get_member (message) :
4687                  "no member",
4688                  dbus_message_get_signature (message));
4689
4690   HAVE_LOCK_CHECK (connection);
4691   result = _dbus_object_tree_dispatch_and_unlock (connection->objects,
4692                                                   message);
4693   
4694   CONNECTION_LOCK (connection);
4695
4696   if (result != DBUS_HANDLER_RESULT_NOT_YET_HANDLED)
4697     {
4698       _dbus_verbose ("object tree handled message in dispatch\n");
4699       goto out;
4700     }
4701
4702   if (dbus_message_get_type (message) == DBUS_MESSAGE_TYPE_METHOD_CALL)
4703     {
4704       DBusMessage *reply;
4705       DBusString str;
4706       DBusPreallocatedSend *preallocated;
4707
4708       _dbus_verbose ("  sending error %s\n",
4709                      DBUS_ERROR_UNKNOWN_METHOD);
4710       
4711       if (!_dbus_string_init (&str))
4712         {
4713           result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4714           _dbus_verbose ("no memory for error string in dispatch\n");
4715           goto out;
4716         }
4717               
4718       if (!_dbus_string_append_printf (&str,
4719                                        "Method \"%s\" with signature \"%s\" on interface \"%s\" doesn't exist\n",
4720                                        dbus_message_get_member (message),
4721                                        dbus_message_get_signature (message),
4722                                        dbus_message_get_interface (message)))
4723         {
4724           _dbus_string_free (&str);
4725           result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4726           _dbus_verbose ("no memory for error string in dispatch\n");
4727           goto out;
4728         }
4729       
4730       reply = dbus_message_new_error (message,
4731                                       DBUS_ERROR_UNKNOWN_METHOD,
4732                                       _dbus_string_get_const_data (&str));
4733       _dbus_string_free (&str);
4734
4735       if (reply == NULL)
4736         {
4737           result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4738           _dbus_verbose ("no memory for error reply in dispatch\n");
4739           goto out;
4740         }
4741       
4742       preallocated = _dbus_connection_preallocate_send_unlocked (connection);
4743
4744       if (preallocated == NULL)
4745         {
4746           dbus_message_unref (reply);
4747           result = DBUS_HANDLER_RESULT_NEED_MEMORY;
4748           _dbus_verbose ("no memory for error send in dispatch\n");
4749           goto out;
4750         }
4751
4752       _dbus_connection_send_preallocated_unlocked_no_update (connection, preallocated,
4753                                                              reply, NULL);
4754
4755       dbus_message_unref (reply);
4756       
4757       result = DBUS_HANDLER_RESULT_HANDLED;
4758     }
4759   
4760   _dbus_verbose ("  done dispatching %p (%s %s %s '%s') on connection %p\n", message,
4761                  dbus_message_type_to_string (dbus_message_get_type (message)),
4762                  dbus_message_get_interface (message) ?
4763                  dbus_message_get_interface (message) :
4764                  "no interface",
4765                  dbus_message_get_member (message) ?
4766                  dbus_message_get_member (message) :
4767                  "no member",
4768                  dbus_message_get_signature (message),
4769                  connection);
4770   
4771  out:
4772   if (result == DBUS_HANDLER_RESULT_NEED_MEMORY)
4773     {
4774       _dbus_verbose ("out of memory\n");
4775       
4776       /* Put message back, and we'll start over.
4777        * Yes this means handlers must be idempotent if they
4778        * don't return HANDLED; c'est la vie.
4779        */
4780       _dbus_connection_putback_message_link_unlocked (connection,
4781                                                       message_link);
4782     }
4783   else
4784     {
4785       _dbus_verbose (" ... done dispatching\n");
4786       
4787       _dbus_list_free_link (message_link);
4788       dbus_message_unref (message); /* don't want the message to count in max message limits
4789                                      * in computing dispatch status below
4790                                      */
4791     }
4792   
4793   _dbus_connection_release_dispatch (connection);
4794   HAVE_LOCK_CHECK (connection);
4795
4796   _dbus_verbose ("before final status update\n");
4797   status = _dbus_connection_get_dispatch_status_unlocked (connection);
4798
4799   /* unlocks and calls user code */
4800   _dbus_connection_update_dispatch_status_and_unlock (connection, status);
4801   
4802   dbus_connection_unref (connection);
4803   
4804   return status;
4805 }
4806
4807 /**
4808  * Sets the watch functions for the connection. These functions are
4809  * responsible for making the application's main loop aware of file
4810  * descriptors that need to be monitored for events, using select() or
4811  * poll(). When using Qt, typically the DBusAddWatchFunction would
4812  * create a QSocketNotifier. When using GLib, the DBusAddWatchFunction
4813  * could call g_io_add_watch(), or could be used as part of a more
4814  * elaborate GSource. Note that when a watch is added, it may
4815  * not be enabled.
4816  *
4817  * The DBusWatchToggledFunction notifies the application that the
4818  * watch has been enabled or disabled. Call dbus_watch_get_enabled()
4819  * to check this. A disabled watch should have no effect, and enabled
4820  * watch should be added to the main loop. This feature is used
4821  * instead of simply adding/removing the watch because
4822  * enabling/disabling can be done without memory allocation.  The
4823  * toggled function may be NULL if a main loop re-queries
4824  * dbus_watch_get_enabled() every time anyway.
4825  * 
4826  * The DBusWatch can be queried for the file descriptor to watch using
4827  * dbus_watch_get_unix_fd() or dbus_watch_get_socket(), and for the
4828  * events to watch for using dbus_watch_get_flags(). The flags
4829  * returned by dbus_watch_get_flags() will only contain
4830  * DBUS_WATCH_READABLE and DBUS_WATCH_WRITABLE, never
4831  * DBUS_WATCH_HANGUP or DBUS_WATCH_ERROR; all watches implicitly
4832  * include a watch for hangups, errors, and other exceptional
4833  * conditions.
4834  *
4835  * Once a file descriptor becomes readable or writable, or an exception
4836  * occurs, dbus_watch_handle() should be called to
4837  * notify the connection of the file descriptor's condition.
4838  *
4839  * dbus_watch_handle() cannot be called during the
4840  * DBusAddWatchFunction, as the connection will not be ready to handle
4841  * that watch yet.
4842  * 
4843  * It is not allowed to reference a DBusWatch after it has been passed
4844  * to remove_function.
4845  *
4846  * If #FALSE is returned due to lack of memory, the failure may be due
4847  * to a #FALSE return from the new add_function. If so, the
4848  * add_function may have been called successfully one or more times,
4849  * but the remove_function will also have been called to remove any
4850  * successful adds. i.e. if #FALSE is returned the net result
4851  * should be that dbus_connection_set_watch_functions() has no effect,
4852  * but the add_function and remove_function may have been called.
4853  *
4854  * @note The thread lock on DBusConnection is held while
4855  * watch functions are invoked, so inside these functions you
4856  * may not invoke any methods on DBusConnection or it will deadlock.
4857  * See the comments in the code or http://lists.freedesktop.org/archives/dbus/2007-July/tread.html#8144
4858  * if you encounter this issue and want to attempt writing a patch.
4859  * 
4860  * @param connection the connection.
4861  * @param add_function function to begin monitoring a new descriptor.
4862  * @param remove_function function to stop monitoring a descriptor.
4863  * @param toggled_function function to notify of enable/disable
4864  * @param data data to pass to add_function and remove_function.
4865  * @param free_data_function function to be called to free the data.
4866  * @returns #FALSE on failure (no memory)
4867  */
4868 dbus_bool_t
4869 dbus_connection_set_watch_functions (DBusConnection              *connection,
4870                                      DBusAddWatchFunction         add_function,
4871                                      DBusRemoveWatchFunction      remove_function,
4872                                      DBusWatchToggledFunction     toggled_function,
4873                                      void                        *data,
4874                                      DBusFreeFunction             free_data_function)
4875 {
4876   dbus_bool_t retval;
4877
4878   _dbus_return_val_if_fail (connection != NULL, FALSE);
4879   
4880   CONNECTION_LOCK (connection);
4881
4882   retval = _dbus_watch_list_set_functions (connection->watches,
4883                                            add_function, remove_function,
4884                                            toggled_function,
4885                                            data, free_data_function);
4886
4887   CONNECTION_UNLOCK (connection);
4888
4889   return retval;
4890 }
4891
4892 /**
4893  * Sets the timeout functions for the connection. These functions are
4894  * responsible for making the application's main loop aware of timeouts.
4895  * When using Qt, typically the DBusAddTimeoutFunction would create a
4896  * QTimer. When using GLib, the DBusAddTimeoutFunction would call
4897  * g_timeout_add.
4898  * 
4899  * The DBusTimeoutToggledFunction notifies the application that the
4900  * timeout has been enabled or disabled. Call
4901  * dbus_timeout_get_enabled() to check this. A disabled timeout should
4902  * have no effect, and enabled timeout should be added to the main
4903  * loop. This feature is used instead of simply adding/removing the
4904  * timeout because enabling/disabling can be done without memory
4905  * allocation. With Qt, QTimer::start() and QTimer::stop() can be used
4906  * to enable and disable. The toggled function may be NULL if a main
4907  * loop re-queries dbus_timeout_get_enabled() every time anyway.
4908  * Whenever a timeout is toggled, its interval may change.
4909  *
4910  * The DBusTimeout can be queried for the timer interval using
4911  * dbus_timeout_get_interval(). dbus_timeout_handle() should be called
4912  * repeatedly, each time the interval elapses, starting after it has
4913  * elapsed once. The timeout stops firing when it is removed with the
4914  * given remove_function.  The timer interval may change whenever the
4915  * timeout is added, removed, or toggled.
4916  *
4917  * @note The thread lock on DBusConnection is held while
4918  * timeout functions are invoked, so inside these functions you
4919  * may not invoke any methods on DBusConnection or it will deadlock.
4920  * See the comments in the code or http://lists.freedesktop.org/archives/dbus/2007-July/thread.html#8144
4921  * if you encounter this issue and want to attempt writing a patch.
4922  *
4923  * @param connection the connection.
4924  * @param add_function function to add a timeout.
4925  * @param remove_function function to remove a timeout.
4926  * @param toggled_function function to notify of enable/disable
4927  * @param data data to pass to add_function and remove_function.
4928  * @param free_data_function function to be called to free the data.
4929  * @returns #FALSE on failure (no memory)
4930  */
4931 dbus_bool_t
4932 dbus_connection_set_timeout_functions   (DBusConnection            *connection,
4933                                          DBusAddTimeoutFunction     add_function,
4934                                          DBusRemoveTimeoutFunction  remove_function,
4935                                          DBusTimeoutToggledFunction toggled_function,
4936                                          void                      *data,
4937                                          DBusFreeFunction           free_data_function)
4938 {
4939   dbus_bool_t retval;
4940
4941   _dbus_return_val_if_fail (connection != NULL, FALSE);
4942   
4943   CONNECTION_LOCK (connection);
4944
4945   retval = _dbus_timeout_list_set_functions (connection->timeouts,
4946                                              add_function, remove_function,
4947                                              toggled_function,
4948                                              data, free_data_function);
4949
4950   CONNECTION_UNLOCK (connection);
4951
4952   return retval;
4953 }
4954
4955 /**
4956  * Sets the mainloop wakeup function for the connection. This function
4957  * is responsible for waking up the main loop (if its sleeping in
4958  * another thread) when some some change has happened to the
4959  * connection that the mainloop needs to reconsider (e.g. a message
4960  * has been queued for writing).  When using Qt, this typically
4961  * results in a call to QEventLoop::wakeUp().  When using GLib, it
4962  * would call g_main_context_wakeup().
4963  *
4964  * @param connection the connection.
4965  * @param wakeup_main_function function to wake up the mainloop
4966  * @param data data to pass wakeup_main_function
4967  * @param free_data_function function to be called to free the data.
4968  */
4969 void
4970 dbus_connection_set_wakeup_main_function (DBusConnection            *connection,
4971                                           DBusWakeupMainFunction     wakeup_main_function,
4972                                           void                      *data,
4973                                           DBusFreeFunction           free_data_function)
4974 {
4975   void *old_data;
4976   DBusFreeFunction old_free_data;
4977
4978   _dbus_return_if_fail (connection != NULL);
4979   
4980   CONNECTION_LOCK (connection);
4981   old_data = connection->wakeup_main_data;
4982   old_free_data = connection->free_wakeup_main_data;
4983
4984   connection->wakeup_main_function = wakeup_main_function;
4985   connection->wakeup_main_data = data;
4986   connection->free_wakeup_main_data = free_data_function;
4987   
4988   CONNECTION_UNLOCK (connection);
4989
4990   /* Callback outside the lock */
4991   if (old_free_data)
4992     (*old_free_data) (old_data);
4993 }
4994
4995 /**
4996  * Set a function to be invoked when the dispatch status changes.
4997  * If the dispatch status is #DBUS_DISPATCH_DATA_REMAINS, then
4998  * dbus_connection_dispatch() needs to be called to process incoming
4999  * messages. However, dbus_connection_dispatch() MUST NOT BE CALLED
5000  * from inside the DBusDispatchStatusFunction. Indeed, almost
5001  * any reentrancy in this function is a bad idea. Instead,
5002  * the DBusDispatchStatusFunction should simply save an indication
5003  * that messages should be dispatched later, when the main loop
5004  * is re-entered.
5005  *
5006  * If you don't set a dispatch status function, you have to be sure to
5007  * dispatch on every iteration of your main loop, especially if
5008  * dbus_watch_handle() or dbus_timeout_handle() were called.
5009  *
5010  * @param connection the connection
5011  * @param function function to call on dispatch status changes
5012  * @param data data for function
5013  * @param free_data_function free the function data
5014  */
5015 void
5016 dbus_connection_set_dispatch_status_function (DBusConnection             *connection,
5017                                               DBusDispatchStatusFunction  function,
5018                                               void                       *data,
5019                                               DBusFreeFunction            free_data_function)
5020 {
5021   void *old_data;
5022   DBusFreeFunction old_free_data;
5023
5024   _dbus_return_if_fail (connection != NULL);
5025   
5026   CONNECTION_LOCK (connection);
5027   old_data = connection->dispatch_status_data;
5028   old_free_data = connection->free_dispatch_status_data;
5029
5030   connection->dispatch_status_function = function;
5031   connection->dispatch_status_data = data;
5032   connection->free_dispatch_status_data = free_data_function;
5033   
5034   CONNECTION_UNLOCK (connection);
5035
5036   /* Callback outside the lock */
5037   if (old_free_data)
5038     (*old_free_data) (old_data);
5039 }
5040
5041 /**
5042  * Get the UNIX file descriptor of the connection, if any.  This can
5043  * be used for SELinux access control checks with getpeercon() for
5044  * example. DO NOT read or write to the file descriptor, or try to
5045  * select() on it; use DBusWatch for main loop integration. Not all
5046  * connections will have a file descriptor. So for adding descriptors
5047  * to the main loop, use dbus_watch_get_unix_fd() and so forth.
5048  *
5049  * If the connection is socket-based, you can also use
5050  * dbus_connection_get_socket(), which will work on Windows too.
5051  * This function always fails on Windows.
5052  *
5053  * Right now the returned descriptor is always a socket, but
5054  * that is not guaranteed.
5055  * 
5056  * @param connection the connection
5057  * @param fd return location for the file descriptor.
5058  * @returns #TRUE if fd is successfully obtained.
5059  */
5060 dbus_bool_t
5061 dbus_connection_get_unix_fd (DBusConnection *connection,
5062                              int            *fd)
5063 {
5064   _dbus_return_val_if_fail (connection != NULL, FALSE);
5065   _dbus_return_val_if_fail (connection->transport != NULL, FALSE);
5066
5067 #ifdef DBUS_WIN
5068   /* FIXME do this on a lower level */
5069   return FALSE;
5070 #endif
5071   
5072   return dbus_connection_get_socket(connection, fd);
5073 }
5074
5075 /**
5076  * Gets the underlying Windows or UNIX socket file descriptor
5077  * of the connection, if any. DO NOT read or write to the file descriptor, or try to
5078  * select() on it; use DBusWatch for main loop integration. Not all
5079  * connections will have a socket. So for adding descriptors
5080  * to the main loop, use dbus_watch_get_socket() and so forth.
5081  *
5082  * If the connection is not socket-based, this function will return FALSE,
5083  * even if the connection does have a file descriptor of some kind.
5084  * i.e. this function always returns specifically a socket file descriptor.
5085  * 
5086  * @param connection the connection
5087  * @param fd return location for the file descriptor.
5088  * @returns #TRUE if fd is successfully obtained.
5089  */
5090 dbus_bool_t
5091 dbus_connection_get_socket(DBusConnection              *connection,
5092                            int                         *fd)
5093 {
5094   dbus_bool_t retval;
5095
5096   _dbus_return_val_if_fail (connection != NULL, FALSE);
5097   _dbus_return_val_if_fail (connection->transport != NULL, FALSE);
5098   
5099   CONNECTION_LOCK (connection);
5100   
5101   retval = _dbus_transport_get_socket_fd (connection->transport,
5102                                           fd);
5103
5104   CONNECTION_UNLOCK (connection);
5105
5106   return retval;
5107 }
5108
5109
5110 /**
5111  * Gets the UNIX user ID of the connection if known.  Returns #TRUE if
5112  * the uid is filled in.  Always returns #FALSE on non-UNIX platforms
5113  * for now, though in theory someone could hook Windows to NIS or
5114  * something.  Always returns #FALSE prior to authenticating the
5115  * connection.
5116  *
5117  * The UID is only read by servers from clients; clients can't usually
5118  * get the UID of servers, because servers do not authenticate to
5119  * clients.  The returned UID is the UID the connection authenticated
5120  * as.
5121  *
5122  * The message bus is a server and the apps connecting to the bus
5123  * are clients.
5124  *
5125  * You can ask the bus to tell you the UID of another connection though
5126  * if you like; this is done with dbus_bus_get_unix_user().
5127  *
5128  * @param connection the connection
5129  * @param uid return location for the user ID
5130  * @returns #TRUE if uid is filled in with a valid user ID
5131  */
5132 dbus_bool_t
5133 dbus_connection_get_unix_user (DBusConnection *connection,
5134                                unsigned long  *uid)
5135 {
5136   dbus_bool_t result;
5137
5138   _dbus_return_val_if_fail (connection != NULL, FALSE);
5139   _dbus_return_val_if_fail (uid != NULL, FALSE);
5140   
5141   CONNECTION_LOCK (connection);
5142
5143   if (!_dbus_transport_get_is_authenticated (connection->transport))
5144     result = FALSE;
5145   else
5146     result = _dbus_transport_get_unix_user (connection->transport,
5147                                             uid);
5148
5149 #ifdef DBUS_WIN
5150   _dbus_assert (!result);
5151 #endif
5152   
5153   CONNECTION_UNLOCK (connection);
5154
5155   return result;
5156 }
5157
5158 /**
5159  * Gets the process ID of the connection if any.
5160  * Returns #TRUE if the pid is filled in.
5161  * Always returns #FALSE prior to authenticating the
5162  * connection.
5163  *
5164  * @param connection the connection
5165  * @param pid return location for the process ID
5166  * @returns #TRUE if uid is filled in with a valid process ID
5167  */
5168 dbus_bool_t
5169 dbus_connection_get_unix_process_id (DBusConnection *connection,
5170                                      unsigned long  *pid)
5171 {
5172   dbus_bool_t result;
5173
5174   _dbus_return_val_if_fail (connection != NULL, FALSE);
5175   _dbus_return_val_if_fail (pid != NULL, FALSE);
5176   
5177   CONNECTION_LOCK (connection);
5178
5179   if (!_dbus_transport_get_is_authenticated (connection->transport))
5180     result = FALSE;
5181   else
5182     result = _dbus_transport_get_unix_process_id (connection->transport,
5183                                                   pid);
5184
5185   CONNECTION_UNLOCK (connection);
5186
5187   return result;
5188 }
5189
5190 /**
5191  * Gets the ADT audit data of the connection if any.
5192  * Returns #TRUE if the structure pointer is returned.
5193  * Always returns #FALSE prior to authenticating the
5194  * connection.
5195  *
5196  * @param connection the connection
5197  * @param data return location for audit data 
5198  * @returns #TRUE if audit data is filled in with a valid ucred pointer
5199  */
5200 dbus_bool_t
5201 dbus_connection_get_adt_audit_session_data (DBusConnection *connection,
5202                                             void          **data,
5203                                             dbus_int32_t   *data_size)
5204 {
5205   dbus_bool_t result;
5206
5207   _dbus_return_val_if_fail (connection != NULL, FALSE);
5208   _dbus_return_val_if_fail (data != NULL, FALSE);
5209   _dbus_return_val_if_fail (data_size != NULL, FALSE);
5210   
5211   CONNECTION_LOCK (connection);
5212
5213   if (!_dbus_transport_get_is_authenticated (connection->transport))
5214     result = FALSE;
5215   else
5216     result = _dbus_transport_get_adt_audit_session_data (connection->transport,
5217                                                          data,
5218                                                          data_size);
5219   CONNECTION_UNLOCK (connection);
5220
5221   return result;
5222 }
5223
5224 /**
5225  * Sets a predicate function used to determine whether a given user ID
5226  * is allowed to connect. When an incoming connection has
5227  * authenticated with a particular user ID, this function is called;
5228  * if it returns #TRUE, the connection is allowed to proceed,
5229  * otherwise the connection is disconnected.
5230  *
5231  * If the function is set to #NULL (as it is by default), then
5232  * only the same UID as the server process will be allowed to
5233  * connect. Also, root is always allowed to connect.
5234  *
5235  * On Windows, the function will be set and its free_data_function will
5236  * be invoked when the connection is freed or a new function is set.
5237  * However, the function will never be called, because there are
5238  * no UNIX user ids to pass to it, or at least none of the existing
5239  * auth protocols would allow authenticating as a UNIX user on Windows.
5240  * 
5241  * @param connection the connection
5242  * @param function the predicate
5243  * @param data data to pass to the predicate
5244  * @param free_data_function function to free the data
5245  */
5246 void
5247 dbus_connection_set_unix_user_function (DBusConnection             *connection,
5248                                         DBusAllowUnixUserFunction   function,
5249                                         void                       *data,
5250                                         DBusFreeFunction            free_data_function)
5251 {
5252   void *old_data = NULL;
5253   DBusFreeFunction old_free_function = NULL;
5254
5255   _dbus_return_if_fail (connection != NULL);
5256   
5257   CONNECTION_LOCK (connection);
5258   _dbus_transport_set_unix_user_function (connection->transport,
5259                                           function, data, free_data_function,
5260                                           &old_data, &old_free_function);
5261   CONNECTION_UNLOCK (connection);
5262
5263   if (old_free_function != NULL)
5264     (* old_free_function) (old_data);
5265 }
5266
5267 /**
5268  * Gets the Windows user SID of the connection if known.  Returns
5269  * #TRUE if the ID is filled in.  Always returns #FALSE on non-Windows
5270  * platforms for now, though in theory someone could hook UNIX to
5271  * Active Directory or something.  Always returns #FALSE prior to
5272  * authenticating the connection.
5273  *
5274  * The user is only read by servers from clients; clients can't usually
5275  * get the user of servers, because servers do not authenticate to
5276  * clients. The returned user is the user the connection authenticated
5277  * as.
5278  *
5279  * The message bus is a server and the apps connecting to the bus
5280  * are clients.
5281  *
5282  * The returned user string has to be freed with dbus_free().
5283  *
5284  * The return value indicates whether the user SID is available;
5285  * if it's available but we don't have the memory to copy it,
5286  * then the return value is #TRUE and #NULL is given as the SID.
5287  * 
5288  * @todo We would like to be able to say "You can ask the bus to tell
5289  * you the user of another connection though if you like; this is done
5290  * with dbus_bus_get_windows_user()." But this has to be implemented
5291  * in bus/driver.c and dbus/dbus-bus.c, and is pointless anyway
5292  * since on Windows we only use the session bus for now.
5293  *
5294  * @param connection the connection
5295  * @param windows_sid_p return location for an allocated copy of the user ID, or #NULL if no memory
5296  * @returns #TRUE if user is available (returned value may be #NULL anyway if no memory)
5297  */
5298 dbus_bool_t
5299 dbus_connection_get_windows_user (DBusConnection             *connection,
5300                                   char                      **windows_sid_p)
5301 {
5302   dbus_bool_t result;
5303
5304   _dbus_return_val_if_fail (connection != NULL, FALSE);
5305   _dbus_return_val_if_fail (windows_sid_p != NULL, FALSE);
5306   
5307   CONNECTION_LOCK (connection);
5308
5309   if (!_dbus_transport_get_is_authenticated (connection->transport))
5310     result = FALSE;
5311   else
5312     result = _dbus_transport_get_windows_user (connection->transport,
5313                                                windows_sid_p);
5314
5315 #ifdef DBUS_UNIX
5316   _dbus_assert (!result);
5317 #endif
5318   
5319   CONNECTION_UNLOCK (connection);
5320
5321   return result;
5322 }
5323
5324 /**
5325  * Sets a predicate function used to determine whether a given user ID
5326  * is allowed to connect. When an incoming connection has
5327  * authenticated with a particular user ID, this function is called;
5328  * if it returns #TRUE, the connection is allowed to proceed,
5329  * otherwise the connection is disconnected.
5330  *
5331  * If the function is set to #NULL (as it is by default), then
5332  * only the same user owning the server process will be allowed to
5333  * connect.
5334  *
5335  * On UNIX, the function will be set and its free_data_function will
5336  * be invoked when the connection is freed or a new function is set.
5337  * However, the function will never be called, because there is no
5338  * way right now to authenticate as a Windows user on UNIX.
5339  * 
5340  * @param connection the connection
5341  * @param function the predicate
5342  * @param data data to pass to the predicate
5343  * @param free_data_function function to free the data
5344  */
5345 void
5346 dbus_connection_set_windows_user_function (DBusConnection              *connection,
5347                                            DBusAllowWindowsUserFunction function,
5348                                            void                        *data,
5349                                            DBusFreeFunction             free_data_function)
5350 {
5351   void *old_data = NULL;
5352   DBusFreeFunction old_free_function = NULL;
5353
5354   _dbus_return_if_fail (connection != NULL);
5355   
5356   CONNECTION_LOCK (connection);
5357   _dbus_transport_set_windows_user_function (connection->transport,
5358                                              function, data, free_data_function,
5359                                              &old_data, &old_free_function);
5360   CONNECTION_UNLOCK (connection);
5361
5362   if (old_free_function != NULL)
5363     (* old_free_function) (old_data);
5364 }
5365
5366 /**
5367  * This function must be called on the server side of a connection when the
5368  * connection is first seen in the #DBusNewConnectionFunction. If set to
5369  * #TRUE (the default is #FALSE), then the connection can proceed even if
5370  * the client does not authenticate as some user identity, i.e. clients
5371  * can connect anonymously.
5372  * 
5373  * This setting interacts with the available authorization mechanisms
5374  * (see dbus_server_set_auth_mechanisms()). Namely, an auth mechanism
5375  * such as ANONYMOUS that supports anonymous auth must be included in
5376  * the list of available mechanisms for anonymous login to work.
5377  *
5378  * This setting also changes the default rule for connections
5379  * authorized as a user; normally, if a connection authorizes as
5380  * a user identity, it is permitted if the user identity is
5381  * root or the user identity matches the user identity of the server
5382  * process. If anonymous connections are allowed, however,
5383  * then any user identity is allowed.
5384  *
5385  * You can override the rules for connections authorized as a
5386  * user identity with dbus_connection_set_unix_user_function()
5387  * and dbus_connection_set_windows_user_function().
5388  * 
5389  * @param connection the connection
5390  * @param value whether to allow authentication as an anonymous user
5391  */
5392 void
5393 dbus_connection_set_allow_anonymous (DBusConnection             *connection,
5394                                      dbus_bool_t                 value)
5395 {
5396   _dbus_return_if_fail (connection != NULL);
5397   
5398   CONNECTION_LOCK (connection);
5399   _dbus_transport_set_allow_anonymous (connection->transport, value);
5400   CONNECTION_UNLOCK (connection);
5401 }
5402
5403 /**
5404  *
5405  * Normally #DBusConnection automatically handles all messages to the
5406  * org.freedesktop.DBus.Peer interface. However, the message bus wants
5407  * to be able to route methods on that interface through the bus and
5408  * to other applications. If routing peer messages is enabled, then
5409  * messages with the org.freedesktop.DBus.Peer interface that also
5410  * have a bus destination name set will not be automatically
5411  * handled by the #DBusConnection and instead will be dispatched
5412  * normally to the application.
5413  *
5414  * If a normal application sets this flag, it can break things badly.
5415  * So don't set this unless you are the message bus.
5416  *
5417  * @param connection the connection
5418  * @param value #TRUE to pass through org.freedesktop.DBus.Peer messages with a bus name set
5419  */
5420 void
5421 dbus_connection_set_route_peer_messages (DBusConnection             *connection,
5422                                          dbus_bool_t                 value)
5423 {
5424   _dbus_return_if_fail (connection != NULL);
5425   
5426   CONNECTION_LOCK (connection);
5427   connection->route_peer_messages = TRUE;
5428   CONNECTION_UNLOCK (connection);
5429 }
5430
5431 /**
5432  * Adds a message filter. Filters are handlers that are run on all
5433  * incoming messages, prior to the objects registered with
5434  * dbus_connection_register_object_path().  Filters are run in the
5435  * order that they were added.  The same handler can be added as a
5436  * filter more than once, in which case it will be run more than once.
5437  * Filters added during a filter callback won't be run on the message
5438  * being processed.
5439  *
5440  * @todo we don't run filters on messages while blocking without
5441  * entering the main loop, since filters are run as part of
5442  * dbus_connection_dispatch(). This is probably a feature, as filters
5443  * could create arbitrary reentrancy. But kind of sucks if you're
5444  * trying to filter METHOD_RETURN for some reason.
5445  *
5446  * @param connection the connection
5447  * @param function function to handle messages
5448  * @param user_data user data to pass to the function
5449  * @param free_data_function function to use for freeing user data
5450  * @returns #TRUE on success, #FALSE if not enough memory.
5451  */
5452 dbus_bool_t
5453 dbus_connection_add_filter (DBusConnection            *connection,
5454                             DBusHandleMessageFunction  function,
5455                             void                      *user_data,
5456                             DBusFreeFunction           free_data_function)
5457 {
5458   DBusMessageFilter *filter;
5459   
5460   _dbus_return_val_if_fail (connection != NULL, FALSE);
5461   _dbus_return_val_if_fail (function != NULL, FALSE);
5462
5463   filter = dbus_new0 (DBusMessageFilter, 1);
5464   if (filter == NULL)
5465     return FALSE;
5466
5467   filter->refcount.value = 1;
5468   
5469   CONNECTION_LOCK (connection);
5470
5471   if (!_dbus_list_append (&connection->filter_list,
5472                           filter))
5473     {
5474       _dbus_message_filter_unref (filter);
5475       CONNECTION_UNLOCK (connection);
5476       return FALSE;
5477     }
5478
5479   /* Fill in filter after all memory allocated,
5480    * so we don't run the free_user_data_function
5481    * if the add_filter() fails
5482    */
5483   
5484   filter->function = function;
5485   filter->user_data = user_data;
5486   filter->free_user_data_function = free_data_function;
5487         
5488   CONNECTION_UNLOCK (connection);
5489   return TRUE;
5490 }
5491
5492 /**
5493  * Removes a previously-added message filter. It is a programming
5494  * error to call this function for a handler that has not been added
5495  * as a filter. If the given handler was added more than once, only
5496  * one instance of it will be removed (the most recently-added
5497  * instance).
5498  *
5499  * @param connection the connection
5500  * @param function the handler to remove
5501  * @param user_data user data for the handler to remove
5502  *
5503  */
5504 void
5505 dbus_connection_remove_filter (DBusConnection            *connection,
5506                                DBusHandleMessageFunction  function,
5507                                void                      *user_data)
5508 {
5509   DBusList *link;
5510   DBusMessageFilter *filter;
5511   
5512   _dbus_return_if_fail (connection != NULL);
5513   _dbus_return_if_fail (function != NULL);
5514   
5515   CONNECTION_LOCK (connection);
5516
5517   filter = NULL;
5518   
5519   link = _dbus_list_get_last_link (&connection->filter_list);
5520   while (link != NULL)
5521     {
5522       filter = link->data;
5523
5524       if (filter->function == function &&
5525           filter->user_data == user_data)
5526         {
5527           _dbus_list_remove_link (&connection->filter_list, link);
5528           filter->function = NULL;
5529           
5530           break;
5531         }
5532         
5533       link = _dbus_list_get_prev_link (&connection->filter_list, link);
5534       filter = NULL;
5535     }
5536   
5537   CONNECTION_UNLOCK (connection);
5538
5539 #ifndef DBUS_DISABLE_CHECKS
5540   if (filter == NULL)
5541     {
5542       _dbus_warn_check_failed ("Attempt to remove filter function %p user data %p, but no such filter has been added\n",
5543                                function, user_data);
5544       return;
5545     }
5546 #endif
5547   
5548   /* Call application code */
5549   if (filter->free_user_data_function)
5550     (* filter->free_user_data_function) (filter->user_data);
5551
5552   filter->free_user_data_function = NULL;
5553   filter->user_data = NULL;
5554   
5555   _dbus_message_filter_unref (filter);
5556 }
5557
5558 /**
5559  * Registers a handler for a given path in the object hierarchy.
5560  * The given vtable handles messages sent to exactly the given path.
5561  *
5562  * @param connection the connection
5563  * @param path a '/' delimited string of path elements
5564  * @param vtable the virtual table
5565  * @param user_data data to pass to functions in the vtable
5566  * @param error address where an error can be returned
5567  * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5568  *    #DBUS_ERROR_ADDRESS_IN_USE) is reported
5569  */
5570 dbus_bool_t
5571 dbus_connection_try_register_object_path (DBusConnection              *connection,
5572                                           const char                  *path,
5573                                           const DBusObjectPathVTable  *vtable,
5574                                           void                        *user_data,
5575                                           DBusError                   *error)
5576 {
5577   char **decomposed_path;
5578   dbus_bool_t retval;
5579   
5580   _dbus_return_val_if_fail (connection != NULL, FALSE);
5581   _dbus_return_val_if_fail (path != NULL, FALSE);
5582   _dbus_return_val_if_fail (path[0] == '/', FALSE);
5583   _dbus_return_val_if_fail (vtable != NULL, FALSE);
5584
5585   if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5586     return FALSE;
5587
5588   CONNECTION_LOCK (connection);
5589
5590   retval = _dbus_object_tree_register (connection->objects,
5591                                        FALSE,
5592                                        (const char **) decomposed_path, vtable,
5593                                        user_data, error);
5594
5595   CONNECTION_UNLOCK (connection);
5596
5597   dbus_free_string_array (decomposed_path);
5598
5599   return retval;
5600 }
5601
5602 /**
5603  * Registers a handler for a given path in the object hierarchy.
5604  * The given vtable handles messages sent to exactly the given path.
5605  *
5606  * It is a bug to call this function for object paths which already
5607  * have a handler. Use dbus_connection_try_register_object_path() if this
5608  * might be the case.
5609  *
5610  * @param connection the connection
5611  * @param path a '/' delimited string of path elements
5612  * @param vtable the virtual table
5613  * @param user_data data to pass to functions in the vtable
5614  * @returns #FALSE if not enough memory
5615  */
5616 dbus_bool_t
5617 dbus_connection_register_object_path (DBusConnection              *connection,
5618                                       const char                  *path,
5619                                       const DBusObjectPathVTable  *vtable,
5620                                       void                        *user_data)
5621 {
5622   char **decomposed_path;
5623   dbus_bool_t retval;
5624   DBusError error = DBUS_ERROR_INIT;
5625
5626   _dbus_return_val_if_fail (connection != NULL, FALSE);
5627   _dbus_return_val_if_fail (path != NULL, FALSE);
5628   _dbus_return_val_if_fail (path[0] == '/', FALSE);
5629   _dbus_return_val_if_fail (vtable != NULL, FALSE);
5630
5631   if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5632     return FALSE;
5633
5634   CONNECTION_LOCK (connection);
5635
5636   retval = _dbus_object_tree_register (connection->objects,
5637                                        FALSE,
5638                                        (const char **) decomposed_path, vtable,
5639                                        user_data, &error);
5640
5641   CONNECTION_UNLOCK (connection);
5642
5643   dbus_free_string_array (decomposed_path);
5644
5645   if (dbus_error_has_name (&error, DBUS_ERROR_ADDRESS_IN_USE))
5646     {
5647       _dbus_warn ("%s\n", error.message);
5648       dbus_error_free (&error);
5649       return FALSE;
5650     }
5651
5652   return retval;
5653 }
5654
5655 /**
5656  * Registers a fallback handler for a given subsection of the object
5657  * hierarchy.  The given vtable handles messages at or below the given
5658  * path. You can use this to establish a default message handling
5659  * policy for a whole "subdirectory."
5660  *
5661  * @param connection the connection
5662  * @param path a '/' delimited string of path elements
5663  * @param vtable the virtual table
5664  * @param user_data data to pass to functions in the vtable
5665  * @param error address where an error can be returned
5666  * @returns #FALSE if an error (#DBUS_ERROR_NO_MEMORY or
5667  *    #DBUS_ERROR_ADDRESS_IN_USE) is reported
5668  */
5669 dbus_bool_t
5670 dbus_connection_try_register_fallback (DBusConnection              *connection,
5671                                        const char                  *path,
5672                                        const DBusObjectPathVTable  *vtable,
5673                                        void                        *user_data,
5674                                        DBusError                   *error)
5675 {
5676   char **decomposed_path;
5677   dbus_bool_t retval;
5678
5679   _dbus_return_val_if_fail (connection != NULL, FALSE);
5680   _dbus_return_val_if_fail (path != NULL, FALSE);
5681   _dbus_return_val_if_fail (path[0] == '/', FALSE);
5682   _dbus_return_val_if_fail (vtable != NULL, FALSE);
5683
5684   if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5685     return FALSE;
5686
5687   CONNECTION_LOCK (connection);
5688
5689   retval = _dbus_object_tree_register (connection->objects,
5690                                        TRUE,
5691                                        (const char **) decomposed_path, vtable,
5692                                        user_data, error);
5693
5694   CONNECTION_UNLOCK (connection);
5695
5696   dbus_free_string_array (decomposed_path);
5697
5698   return retval;
5699 }
5700
5701 /**
5702  * Registers a fallback handler for a given subsection of the object
5703  * hierarchy.  The given vtable handles messages at or below the given
5704  * path. You can use this to establish a default message handling
5705  * policy for a whole "subdirectory."
5706  *
5707  * It is a bug to call this function for object paths which already
5708  * have a handler. Use dbus_connection_try_register_fallback() if this
5709  * might be the case.
5710  *
5711  * @param connection the connection
5712  * @param path a '/' delimited string of path elements
5713  * @param vtable the virtual table
5714  * @param user_data data to pass to functions in the vtable
5715  * @returns #FALSE if not enough memory
5716  */
5717 dbus_bool_t
5718 dbus_connection_register_fallback (DBusConnection              *connection,
5719                                    const char                  *path,
5720                                    const DBusObjectPathVTable  *vtable,
5721                                    void                        *user_data)
5722 {
5723   char **decomposed_path;
5724   dbus_bool_t retval;
5725   DBusError error = DBUS_ERROR_INIT;
5726
5727   _dbus_return_val_if_fail (connection != NULL, FALSE);
5728   _dbus_return_val_if_fail (path != NULL, FALSE);
5729   _dbus_return_val_if_fail (path[0] == '/', FALSE);
5730   _dbus_return_val_if_fail (vtable != NULL, FALSE);
5731
5732   if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5733     return FALSE;
5734
5735   CONNECTION_LOCK (connection);
5736
5737   retval = _dbus_object_tree_register (connection->objects,
5738                                        TRUE,
5739                                        (const char **) decomposed_path, vtable,
5740                                        user_data, &error);
5741
5742   CONNECTION_UNLOCK (connection);
5743
5744   dbus_free_string_array (decomposed_path);
5745
5746   if (dbus_error_has_name (&error, DBUS_ERROR_ADDRESS_IN_USE))
5747     {
5748       _dbus_warn ("%s\n", error.message);
5749       dbus_error_free (&error);
5750       return FALSE;
5751     }
5752
5753   return retval;
5754 }
5755
5756 /**
5757  * Unregisters the handler registered with exactly the given path.
5758  * It's a bug to call this function for a path that isn't registered.
5759  * Can unregister both fallback paths and object paths.
5760  *
5761  * @param connection the connection
5762  * @param path a '/' delimited string of path elements
5763  * @returns #FALSE if not enough memory
5764  */
5765 dbus_bool_t
5766 dbus_connection_unregister_object_path (DBusConnection              *connection,
5767                                         const char                  *path)
5768 {
5769   char **decomposed_path;
5770
5771   _dbus_return_val_if_fail (connection != NULL, FALSE);
5772   _dbus_return_val_if_fail (path != NULL, FALSE);
5773   _dbus_return_val_if_fail (path[0] == '/', FALSE);
5774
5775   if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5776       return FALSE;
5777
5778   CONNECTION_LOCK (connection);
5779
5780   _dbus_object_tree_unregister_and_unlock (connection->objects, (const char **) decomposed_path);
5781
5782   dbus_free_string_array (decomposed_path);
5783
5784   return TRUE;
5785 }
5786
5787 /**
5788  * Gets the user data passed to dbus_connection_register_object_path()
5789  * or dbus_connection_register_fallback(). If nothing was registered
5790  * at this path, the data is filled in with #NULL.
5791  *
5792  * @param connection the connection
5793  * @param path the path you registered with
5794  * @param data_p location to store the user data, or #NULL
5795  * @returns #FALSE if not enough memory
5796  */
5797 dbus_bool_t
5798 dbus_connection_get_object_path_data (DBusConnection *connection,
5799                                       const char     *path,
5800                                       void          **data_p)
5801 {
5802   char **decomposed_path;
5803
5804   _dbus_return_val_if_fail (connection != NULL, FALSE);
5805   _dbus_return_val_if_fail (path != NULL, FALSE);
5806   _dbus_return_val_if_fail (data_p != NULL, FALSE);
5807
5808   *data_p = NULL;
5809   
5810   if (!_dbus_decompose_path (path, strlen (path), &decomposed_path, NULL))
5811     return FALSE;
5812   
5813   CONNECTION_LOCK (connection);
5814
5815   *data_p = _dbus_object_tree_get_user_data_unlocked (connection->objects, (const char**) decomposed_path);
5816
5817   CONNECTION_UNLOCK (connection);
5818
5819   dbus_free_string_array (decomposed_path);
5820
5821   return TRUE;
5822 }
5823
5824 /**
5825  * Lists the registered fallback handlers and object path handlers at
5826  * the given parent_path. The returned array should be freed with
5827  * dbus_free_string_array().
5828  *
5829  * @param connection the connection
5830  * @param parent_path the path to list the child handlers of
5831  * @param child_entries returns #NULL-terminated array of children
5832  * @returns #FALSE if no memory to allocate the child entries
5833  */
5834 dbus_bool_t
5835 dbus_connection_list_registered (DBusConnection              *connection,
5836                                  const char                  *parent_path,
5837                                  char                      ***child_entries)
5838 {
5839   char **decomposed_path;
5840   dbus_bool_t retval;
5841   _dbus_return_val_if_fail (connection != NULL, FALSE);
5842   _dbus_return_val_if_fail (parent_path != NULL, FALSE);
5843   _dbus_return_val_if_fail (parent_path[0] == '/', FALSE);
5844   _dbus_return_val_if_fail (child_entries != NULL, FALSE);
5845
5846   if (!_dbus_decompose_path (parent_path, strlen (parent_path), &decomposed_path, NULL))
5847     return FALSE;
5848
5849   CONNECTION_LOCK (connection);
5850
5851   retval = _dbus_object_tree_list_registered_and_unlock (connection->objects,
5852                                                          (const char **) decomposed_path,
5853                                                          child_entries);
5854   dbus_free_string_array (decomposed_path);
5855
5856   return retval;
5857 }
5858
5859 static DBusDataSlotAllocator slot_allocator;
5860 _DBUS_DEFINE_GLOBAL_LOCK (connection_slots);
5861
5862 /**
5863  * Allocates an integer ID to be used for storing application-specific
5864  * data on any DBusConnection. The allocated ID may then be used
5865  * with dbus_connection_set_data() and dbus_connection_get_data().
5866  * The passed-in slot must be initialized to -1, and is filled in
5867  * with the slot ID. If the passed-in slot is not -1, it's assumed
5868  * to be already allocated, and its refcount is incremented.
5869  * 
5870  * The allocated slot is global, i.e. all DBusConnection objects will
5871  * have a slot with the given integer ID reserved.
5872  *
5873  * @param slot_p address of a global variable storing the slot
5874  * @returns #FALSE on failure (no memory)
5875  */
5876 dbus_bool_t
5877 dbus_connection_allocate_data_slot (dbus_int32_t *slot_p)
5878 {
5879   return _dbus_data_slot_allocator_alloc (&slot_allocator,
5880                                           &_DBUS_LOCK_NAME (connection_slots),
5881                                           slot_p);
5882 }
5883
5884 /**
5885  * Deallocates a global ID for connection data slots.
5886  * dbus_connection_get_data() and dbus_connection_set_data() may no
5887  * longer be used with this slot.  Existing data stored on existing
5888  * DBusConnection objects will be freed when the connection is
5889  * finalized, but may not be retrieved (and may only be replaced if
5890  * someone else reallocates the slot).  When the refcount on the
5891  * passed-in slot reaches 0, it is set to -1.
5892  *
5893  * @param slot_p address storing the slot to deallocate
5894  */
5895 void
5896 dbus_connection_free_data_slot (dbus_int32_t *slot_p)
5897 {
5898   _dbus_return_if_fail (*slot_p >= 0);
5899   
5900   _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
5901 }
5902
5903 /**
5904  * Stores a pointer on a DBusConnection, along
5905  * with an optional function to be used for freeing
5906  * the data when the data is set again, or when
5907  * the connection is finalized. The slot number
5908  * must have been allocated with dbus_connection_allocate_data_slot().
5909  *
5910  * @note This function does not take the
5911  * main thread lock on DBusConnection, which allows it to be
5912  * used from inside watch and timeout functions. (See the
5913  * note in docs for dbus_connection_set_watch_functions().)
5914  * A side effect of this is that you need to know there's
5915  * a reference held on the connection while invoking
5916  * dbus_connection_set_data(), or the connection could be
5917  * finalized during dbus_connection_set_data().
5918  *
5919  * @param connection the connection
5920  * @param slot the slot number
5921  * @param data the data to store
5922  * @param free_data_func finalizer function for the data
5923  * @returns #TRUE if there was enough memory to store the data
5924  */
5925 dbus_bool_t
5926 dbus_connection_set_data (DBusConnection   *connection,
5927                           dbus_int32_t      slot,
5928                           void             *data,
5929                           DBusFreeFunction  free_data_func)
5930 {
5931   DBusFreeFunction old_free_func;
5932   void *old_data;
5933   dbus_bool_t retval;
5934
5935   _dbus_return_val_if_fail (connection != NULL, FALSE);
5936   _dbus_return_val_if_fail (slot >= 0, FALSE);
5937   
5938   SLOTS_LOCK (connection);
5939
5940   retval = _dbus_data_slot_list_set (&slot_allocator,
5941                                      &connection->slot_list,
5942                                      slot, data, free_data_func,
5943                                      &old_free_func, &old_data);
5944   
5945   SLOTS_UNLOCK (connection);
5946
5947   if (retval)
5948     {
5949       /* Do the actual free outside the connection lock */
5950       if (old_free_func)
5951         (* old_free_func) (old_data);
5952     }
5953
5954   return retval;
5955 }
5956
5957 /**
5958  * Retrieves data previously set with dbus_connection_set_data().
5959  * The slot must still be allocated (must not have been freed).
5960  *
5961  * @note This function does not take the
5962  * main thread lock on DBusConnection, which allows it to be
5963  * used from inside watch and timeout functions. (See the
5964  * note in docs for dbus_connection_set_watch_functions().)
5965  * A side effect of this is that you need to know there's
5966  * a reference held on the connection while invoking
5967  * dbus_connection_get_data(), or the connection could be
5968  * finalized during dbus_connection_get_data().
5969  *
5970  * @param connection the connection
5971  * @param slot the slot to get data from
5972  * @returns the data, or #NULL if not found
5973  */
5974 void*
5975 dbus_connection_get_data (DBusConnection   *connection,
5976                           dbus_int32_t      slot)
5977 {
5978   void *res;
5979
5980   _dbus_return_val_if_fail (connection != NULL, NULL);
5981   
5982   SLOTS_LOCK (connection);
5983
5984   res = _dbus_data_slot_list_get (&slot_allocator,
5985                                   &connection->slot_list,
5986                                   slot);
5987   
5988   SLOTS_UNLOCK (connection);
5989
5990   return res;
5991 }
5992
5993 /**
5994  * This function sets a global flag for whether dbus_connection_new()
5995  * will set SIGPIPE behavior to SIG_IGN.
5996  *
5997  * @param will_modify_sigpipe #TRUE to allow sigpipe to be set to SIG_IGN
5998  */
5999 void
6000 dbus_connection_set_change_sigpipe (dbus_bool_t will_modify_sigpipe)
6001 {  
6002   _dbus_modify_sigpipe = will_modify_sigpipe != FALSE;
6003 }
6004
6005 /**
6006  * Specifies the maximum size message this connection is allowed to
6007  * receive. Larger messages will result in disconnecting the
6008  * connection.
6009  * 
6010  * @param connection a #DBusConnection
6011  * @param size maximum message size the connection can receive, in bytes
6012  */
6013 void
6014 dbus_connection_set_max_message_size (DBusConnection *connection,
6015                                       long            size)
6016 {
6017   _dbus_return_if_fail (connection != NULL);
6018   
6019   CONNECTION_LOCK (connection);
6020   _dbus_transport_set_max_message_size (connection->transport,
6021                                         size);
6022   CONNECTION_UNLOCK (connection);
6023 }
6024
6025 /**
6026  * Gets the value set by dbus_connection_set_max_message_size().
6027  *
6028  * @param connection the connection
6029  * @returns the max size of a single message
6030  */
6031 long
6032 dbus_connection_get_max_message_size (DBusConnection *connection)
6033 {
6034   long res;
6035
6036   _dbus_return_val_if_fail (connection != NULL, 0);
6037   
6038   CONNECTION_LOCK (connection);
6039   res = _dbus_transport_get_max_message_size (connection->transport);
6040   CONNECTION_UNLOCK (connection);
6041   return res;
6042 }
6043
6044 /**
6045  * Specifies the maximum number of unix fds a message on this
6046  * connection is allowed to receive. Messages with more unix fds will
6047  * result in disconnecting the connection.
6048  *
6049  * @param connection a #DBusConnection
6050  * @param size maximum message unix fds the connection can receive
6051  */
6052 void
6053 dbus_connection_set_max_message_unix_fds (DBusConnection *connection,
6054                                           long            n)
6055 {
6056   _dbus_return_if_fail (connection != NULL);
6057
6058   CONNECTION_LOCK (connection);
6059   _dbus_transport_set_max_message_unix_fds (connection->transport,
6060                                             n);
6061   CONNECTION_UNLOCK (connection);
6062 }
6063
6064 /**
6065  * Gets the value set by dbus_connection_set_max_message_unix_fds().
6066  *
6067  * @param connection the connection
6068  * @returns the max numer of unix fds of a single message
6069  */
6070 long
6071 dbus_connection_get_max_message_unix_fds (DBusConnection *connection)
6072 {
6073   long res;
6074
6075   _dbus_return_val_if_fail (connection != NULL, 0);
6076
6077   CONNECTION_LOCK (connection);
6078   res = _dbus_transport_get_max_message_unix_fds (connection->transport);
6079   CONNECTION_UNLOCK (connection);
6080   return res;
6081 }
6082
6083 /**
6084  * Sets the maximum total number of bytes that can be used for all messages
6085  * received on this connection. Messages count toward the maximum until
6086  * they are finalized. When the maximum is reached, the connection will
6087  * not read more data until some messages are finalized.
6088  *
6089  * The semantics of the maximum are: if outstanding messages are
6090  * already above the maximum, additional messages will not be read.
6091  * The semantics are not: if the next message would cause us to exceed
6092  * the maximum, we don't read it. The reason is that we don't know the
6093  * size of a message until after we read it.
6094  *
6095  * Thus, the max live messages size can actually be exceeded
6096  * by up to the maximum size of a single message.
6097  * 
6098  * Also, if we read say 1024 bytes off the wire in a single read(),
6099  * and that contains a half-dozen small messages, we may exceed the
6100  * size max by that amount. But this should be inconsequential.
6101  *
6102  * This does imply that we can't call read() with a buffer larger
6103  * than we're willing to exceed this limit by.
6104  *
6105  * @param connection the connection
6106  * @param size the maximum size in bytes of all outstanding messages
6107  */
6108 void
6109 dbus_connection_set_max_received_size (DBusConnection *connection,
6110                                        long            size)
6111 {
6112   _dbus_return_if_fail (connection != NULL);
6113   
6114   CONNECTION_LOCK (connection);
6115   _dbus_transport_set_max_received_size (connection->transport,
6116                                          size);
6117   CONNECTION_UNLOCK (connection);
6118 }
6119
6120 /**
6121  * Gets the value set by dbus_connection_set_max_received_size().
6122  *
6123  * @param connection the connection
6124  * @returns the max size of all live messages
6125  */
6126 long
6127 dbus_connection_get_max_received_size (DBusConnection *connection)
6128 {
6129   long res;
6130
6131   _dbus_return_val_if_fail (connection != NULL, 0);
6132   
6133   CONNECTION_LOCK (connection);
6134   res = _dbus_transport_get_max_received_size (connection->transport);
6135   CONNECTION_UNLOCK (connection);
6136   return res;
6137 }
6138
6139 /**
6140  * Sets the maximum total number of unix fds that can be used for all messages
6141  * received on this connection. Messages count toward the maximum until
6142  * they are finalized. When the maximum is reached, the connection will
6143  * not read more data until some messages are finalized.
6144  *
6145  * The semantics are analogous to those of dbus_connection_set_max_received_size().
6146  *
6147  * @param connection the connection
6148  * @param size the maximum size in bytes of all outstanding messages
6149  */
6150 void
6151 dbus_connection_set_max_received_unix_fds (DBusConnection *connection,
6152                                            long            n)
6153 {
6154   _dbus_return_if_fail (connection != NULL);
6155
6156   CONNECTION_LOCK (connection);
6157   _dbus_transport_set_max_received_unix_fds (connection->transport,
6158                                              n);
6159   CONNECTION_UNLOCK (connection);
6160 }
6161
6162 /**
6163  * Gets the value set by dbus_connection_set_max_received_unix_fds().
6164  *
6165  * @param connection the connection
6166  * @returns the max unix fds of all live messages
6167  */
6168 long
6169 dbus_connection_get_max_received_unix_fds (DBusConnection *connection)
6170 {
6171   long res;
6172
6173   _dbus_return_val_if_fail (connection != NULL, 0);
6174
6175   CONNECTION_LOCK (connection);
6176   res = _dbus_transport_get_max_received_unix_fds (connection->transport);
6177   CONNECTION_UNLOCK (connection);
6178   return res;
6179 }
6180
6181 /**
6182  * Gets the approximate size in bytes of all messages in the outgoing
6183  * message queue. The size is approximate in that you shouldn't use
6184  * it to decide how many bytes to read off the network or anything
6185  * of that nature, as optimizations may choose to tell small white lies
6186  * to avoid performance overhead.
6187  *
6188  * @param connection the connection
6189  * @returns the number of bytes that have been queued up but not sent
6190  */
6191 long
6192 dbus_connection_get_outgoing_size (DBusConnection *connection)
6193 {
6194   long res;
6195
6196   _dbus_return_val_if_fail (connection != NULL, 0);
6197
6198   CONNECTION_LOCK (connection);
6199   res = _dbus_counter_get_size_value (connection->outgoing_counter);
6200   CONNECTION_UNLOCK (connection);
6201   return res;
6202 }
6203
6204 /**
6205  * Gets the approximate number of uni fds of all messages in the
6206  * outgoing message queue.
6207  *
6208  * @param connection the connection
6209  * @returns the number of unix fds that have been queued up but not sent
6210  */
6211 long
6212 dbus_connection_get_outgoing_unix_fds (DBusConnection *connection)
6213 {
6214   long res;
6215
6216   _dbus_return_val_if_fail (connection != NULL, 0);
6217
6218   CONNECTION_LOCK (connection);
6219   res = _dbus_counter_get_unix_fd_value (connection->outgoing_counter);
6220   CONNECTION_UNLOCK (connection);
6221   return res;
6222 }
6223
6224 /** @} */