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