[kdbus] Add possibility to unsubscribe NameAcquired and NameLost signals
[platform/upstream/glib.git] / gio / gdbusconnection.c
1 /* GDBus - GLib D-Bus Library
2  *
3  * Copyright (C) 2008-2010 Red Hat, Inc.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General
16  * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
17  *
18  * Author: David Zeuthen <davidz@redhat.com>
19  */
20
21 /*
22  * TODO for GDBus:
23  *
24  * - would be nice to expose GDBusAuthMechanism and an extension point
25  *
26  * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
27  *   the mechanism VFuncs need to be able to set an error.
28  *
29  * - Need to document other mechanisms/sources for determining the D-Bus
30  *   address of a well-known bus.
31  *
32  *   - e.g. on Win32 we need code like from here
33  *
34  *     http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
35  *
36  *     that was never copied over here because it originally was copy-paste
37  *     from the GPLv2 / AFL 2.1 libdbus sources.
38  *
39  *   - on OS X we need to look in launchd for the address
40  *
41  *     https://bugs.freedesktop.org/show_bug.cgi?id=14259
42  *
43  *   - on X11 we need to look in a X11 property on the X server
44  *     - (we can also just use dbus-launch(1) from the D-Bus
45  *        distribution)
46  *
47  *   - (ideally) this requires D-Bus spec work because none of
48  *     this has never really been specced out properly (except
49  *     the X11 bits)
50  *
51  * - Related to the above, we also need to be able to launch a message bus
52  *   instance.... Since we don't want to write our own bus daemon we should
53  *   launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
54  *
55  * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
56  *   to specify where the nonce is stored. This will allow people to use
57  *   G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
58  *   to easily achieve secure RPC via nonce-tcp.
59  *
60  * - need to expose an extension point for resolving D-Bus address and
61  *   turning them into GIOStream objects. This will allow us to implement
62  *   e.g. X11 D-Bus transports without dlopen()'ing or linking against
63  *   libX11 from libgio.
64  *   - see g_dbus_address_connect() in gdbusaddress.c
65  *
66  * - would be cute to use kernel-specific APIs to resolve fds for
67  *   debug output when using G_DBUS_DEBUG=message, e.g. in addition to
68  *
69  *     fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
70  *
71  *   maybe we can show more information about what fd 21 really is.
72  *   Ryan suggests looking in /proc/self/fd for clues / symlinks!
73  *   Initial experiments on Linux 2.6 suggests that the symlink looks
74  *   like this:
75  *
76  *    3 -> /proc/18068/fd
77  *
78  *   e.g. not of much use.
79  *
80  *  - GDBus High-Level docs
81  *    - Proxy: properties, signals...
82  *    - Connection: IOStream based, ::close, connection setup steps
83  *                  mainloop integration, threading
84  *    - Differences from libdbus (extend "Migrating from")
85  *      - the message handling thread
86  *      - Using GVariant instead of GValue
87  *    - Explain why the high-level API is a good thing and what
88  *      kind of pitfalls it avoids
89  *      - Export objects before claiming names
90  *    - Talk about auto-starting services (cf. GBusNameWatcherFlags)
91  *
92  *  - use abstract sockets in test code
93  *   - right now it doesn't work, dbus-daemon(1) fails with
94  *
95  *        /gdbus/connection/filter: Failed to start message bus: Failed to bind
96  *        socket "/tmp/g-dbus-tests-pid-28531": Address already in use
97  *        ** WARNING **: Error reading address from dbus daemon, 0 bytes read
98  *
99  *     or similar.
100  */
101
102 #include "config.h"
103
104 #include <stdlib.h>
105 #include <string.h>
106
107 #include "gdbusauth.h"
108 #include "gdbusutils.h"
109 #include "gdbusaddress.h"
110 #include "gdbusmessage.h"
111 #include "gdbusconnection.h"
112 #include "gdbuserror.h"
113 #include "gioenumtypes.h"
114 #include "gdbusintrospection.h"
115 #include "gdbusmethodinvocation.h"
116 #include "gdbusprivate.h"
117 #include "gdbusauthobserver.h"
118 #include "ginitable.h"
119 #include "gasyncinitable.h"
120 #include "giostream.h"
121 #include "gasyncresult.h"
122 #include "gsimpleasyncresult.h"
123
124 #ifdef G_OS_UNIX
125 #include "gkdbus.h"
126 #include "gkdbusconnection.h"
127 #include "gunixconnection.h"
128 #include "gunixfdmessage.h"
129 #endif
130
131 #include "glibintl.h"
132
133 /**
134  * SECTION:gdbusconnection
135  * @short_description: D-Bus Connections
136  * @include: gio/gio.h
137  *
138  * The #GDBusConnection type is used for D-Bus connections to remote
139  * peers such as a message buses. It is a low-level API that offers a
140  * lot of flexibility. For instance, it lets you establish a connection
141  * over any transport that can by represented as an #GIOStream.
142  *
143  * This class is rarely used directly in D-Bus clients. If you are writing
144  * a D-Bus client, it is often easier to use the g_bus_own_name(),
145  * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
146  *
147  * As an exception to the usual GLib rule that a particular object must not
148  * be used by two threads at the same time, #GDBusConnection's methods may be
149  * called from any thread. This is so that g_bus_get() and g_bus_get_sync()
150  * can safely return the same #GDBusConnection when called from any thread.
151  *
152  * Most of the ways to obtain a #GDBusConnection automatically initialize it
153  * (i.e. connect to D-Bus): for instance, g_dbus_connection_new() and
154  * g_bus_get(), and the synchronous versions of those methods, give you an
155  * initialized connection. Language bindings for GIO should use
156  * g_initable_new() or g_async_initable_new_async(), which also initialize the
157  * connection.
158  *
159  * If you construct an uninitialized #GDBusConnection, such as via
160  * g_object_new(), you must initialize it via g_initable_init() or
161  * g_async_initable_init_async() before using its methods or properties.
162  * Calling methods or accessing properties on a #GDBusConnection that has not
163  * completed initialization successfully is considered to be invalid, and leads
164  * to undefined behaviour. In particular, if initialization fails with a
165  * #GError, the only valid thing you can do with that #GDBusConnection is to
166  * free it with g_object_unref().
167  *
168  * ## An example D-Bus server # {#gdbus-server}
169  *
170  * Here is an example for a D-Bus server:
171  * [gdbus-example-server.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-server.c)
172  *
173  * ## An example for exporting a subtree # {#gdbus-subtree-server}
174  *
175  * Here is an example for exporting a subtree:
176  * [gdbus-example-subtree.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-subtree.c)
177  *
178  * ## An example for file descriptor passing # {#gdbus-unix-fd-client}
179  *
180  * Here is an example for passing UNIX file descriptors:
181  * [gdbus-unix-fd-client.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-unix-fd-client.c)
182  *
183  * ## An example for exporting a GObject # {#gdbus-export}
184  *
185  * Here is an example for exporting a #GObject:
186  * [gdbus-example-export.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-export.c)
187  */
188
189 /* ---------------------------------------------------------------------------------------------------- */
190
191 typedef struct _GDBusConnectionClass GDBusConnectionClass;
192
193 /**
194  * GDBusConnectionClass:
195  * @closed: Signal class handler for the #GDBusConnection::closed signal.
196  *
197  * Class structure for #GDBusConnection.
198  *
199  * Since: 2.26
200  */
201 struct _GDBusConnectionClass
202 {
203   /*< private >*/
204   GObjectClass parent_class;
205
206   /*< public >*/
207   /* Signals */
208   void (*closed) (GDBusConnection *connection,
209                   gboolean         remote_peer_vanished,
210                   GError          *error);
211 };
212
213 G_LOCK_DEFINE_STATIC (message_bus_lock);
214
215 static GWeakRef the_session_bus;
216 static GWeakRef the_system_bus;
217 static GWeakRef the_user_bus;
218 static GWeakRef the_machine_bus;
219
220 /* Extra pseudo-member of GDBusSendMessageFlags.
221  * Set by initable_init() to indicate that despite not being initialized yet,
222  * enough of the only-valid-after-init members are set that we can send a
223  * message, and we're being called from its thread, so no memory barrier is
224  * required before accessing them.
225  */
226 #define SEND_MESSAGE_FLAGS_INITIALIZING (1<<31)
227
228 /* Same as SEND_MESSAGE_FLAGS_INITIALIZING, but in GDBusCallFlags */
229 #define CALL_FLAGS_INITIALIZING (1<<31)
230
231 /* ---------------------------------------------------------------------------------------------------- */
232
233 typedef struct
234 {
235   GDestroyNotify              callback;
236   gpointer                    user_data;
237   GMainContext               *context;
238 } CallDestroyNotifyData;
239
240 static gboolean
241 call_destroy_notify_data_in_idle (gpointer user_data)
242 {
243   CallDestroyNotifyData *data = user_data;
244   data->callback (data->user_data);
245   return FALSE;
246 }
247
248 static void
249 call_destroy_notify_data_free (CallDestroyNotifyData *data)
250 {
251   if (data->context != NULL)
252     g_main_context_unref (data->context);
253   g_free (data);
254 }
255
256 /*
257  * call_destroy_notify: <internal>
258  * @context: (allow-none): A #GMainContext or %NULL.
259  * @callback: (allow-none): A #GDestroyNotify or %NULL.
260  * @user_data: Data to pass to @callback.
261  *
262  * Schedules @callback to run in @context.
263  */
264 static void
265 call_destroy_notify (GMainContext  *context,
266                      GDestroyNotify callback,
267                      gpointer       user_data)
268 {
269   GSource *idle_source;
270   CallDestroyNotifyData *data;
271
272   if (callback == NULL)
273     goto out;
274
275   data = g_new0 (CallDestroyNotifyData, 1);
276   data->callback = callback;
277   data->user_data = user_data;
278   data->context = context;
279   if (data->context != NULL)
280     g_main_context_ref (data->context);
281
282   idle_source = g_idle_source_new ();
283   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
284   g_source_set_callback (idle_source,
285                          call_destroy_notify_data_in_idle,
286                          data,
287                          (GDestroyNotify) call_destroy_notify_data_free);
288   g_source_set_name (idle_source, "[gio] call_destroy_notify_data_in_idle");
289   g_source_attach (idle_source, data->context);
290   g_source_unref (idle_source);
291
292  out:
293   ;
294 }
295
296 /* ---------------------------------------------------------------------------------------------------- */
297
298 static gboolean
299 _g_strv_has_string (const gchar* const *haystack,
300                     const gchar        *needle)
301 {
302   guint n;
303
304   for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
305     {
306       if (g_strcmp0 (haystack[n], needle) == 0)
307         return TRUE;
308     }
309   return FALSE;
310 }
311
312 /* ---------------------------------------------------------------------------------------------------- */
313
314 #ifdef G_OS_WIN32
315 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
316 #else
317 // TODO: for some reason this doesn't work on Windows
318 #define CONNECTION_ENSURE_LOCK(obj) do {                                \
319     if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock)))                     \
320       {                                                                 \
321         g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
322                              "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
323       }                                                                 \
324   } while (FALSE)
325 #endif
326
327 #define CONNECTION_LOCK(obj) do {                                       \
328     g_mutex_lock (&(obj)->lock);                                        \
329   } while (FALSE)
330
331 #define CONNECTION_UNLOCK(obj) do {                                     \
332     g_mutex_unlock (&(obj)->lock);                                      \
333   } while (FALSE)
334
335 /* Flags in connection->atomic_flags */
336 enum {
337     FLAG_INITIALIZED = 1 << 0,
338     FLAG_EXIT_ON_CLOSE = 1 << 1,
339     FLAG_CLOSED = 1 << 2
340 };
341
342 /**
343  * GDBusConnection:
344  *
345  * The #GDBusConnection structure contains only private data and
346  * should only be accessed using the provided API.
347  *
348  * Since: 2.26
349  */
350 struct _GDBusConnection
351 {
352   /*< private >*/
353   GObject parent_instance;
354
355   /* ------------------------------------------------------------------------ */
356   /* -- General object state ------------------------------------------------ */
357   /* ------------------------------------------------------------------------ */
358
359   /* General-purpose lock for most fields */
360   GMutex lock;
361
362   /* A lock used in the init() method of the GInitable interface - see comments
363    * in initable_init() for why a separate lock is needed.
364    *
365    * If you need both @lock and @init_lock, you must take @init_lock first.
366    */
367   GMutex init_lock;
368
369   /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
370    * someone calls org.freedesktop.DBus.Peer.GetMachineId(). Protected by @lock.
371    */
372   gchar *machine_id;
373
374   /* The underlying stream used for communication
375    * Read-only after initable_init(), so it may be read if you either
376    * hold @init_lock or check for initialization first.
377    */
378   GIOStream *stream;
379
380   /* The object used for authentication (if any).
381    * Read-only after initable_init(), so it may be read if you either
382    * hold @init_lock or check for initialization first.
383    */
384   GDBusAuth *auth;
385
386   /* Last serial used. Protected by @lock. */
387   guint32 last_serial;
388
389   /* The object used to send/receive messages.
390    * Read-only after initable_init(), so it may be read if you either
391    * hold @init_lock or check for initialization first.
392    */
393   GDBusWorker *worker;
394
395   /* If connected to a message bus, this contains the unique name assigned to
396    * us by the bus (e.g. ":1.42").
397    * Read-only after initable_init(), so it may be read if you either
398    * hold @init_lock or check for initialization first.
399    */
400   gchar *bus_unique_name;
401
402   /* The GUID returned by the other side if we authenticed as a client or
403    * the GUID to use if authenticating as a server.
404    * Read-only after initable_init(), so it may be read if you either
405    * hold @init_lock or check for initialization first.
406    */
407   gchar *guid;
408
409   /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
410    * Inspect @initialization_error to see whether it succeeded or failed.
411    *
412    * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
413    *
414    * FLAG_CLOSED is the closed property. It may be read at any time, but
415    * may only be written while holding @lock.
416    */
417   volatile gint atomic_flags;
418
419   /* If the connection could not be established during initable_init(),
420    * this GError will be set.
421    * Read-only after initable_init(), so it may be read if you either
422    * hold @init_lock or check for initialization first.
423    */
424   GError *initialization_error;
425
426   /* The result of g_main_context_ref_thread_default() when the object
427    * was created (the GObject _init() function) - this is used for delivery
428    * of the :closed GObject signal.
429    *
430    * Only set in the GObject init function, so no locks are needed.
431    */
432   GMainContext *main_context_at_construction;
433
434   /* Read-only construct properties, no locks needed */
435   gchar *address;
436   GDBusConnectionFlags flags;
437
438   /* Map used for managing method replies, protected by @lock */
439   GHashTable *map_method_serial_to_send_message_data;  /* guint32 -> SendMessageData* */
440
441   /* Maps used for managing signal subscription, protected by @lock */
442   GHashTable *map_rule_to_signal_data;                      /* match rule (gchar*)    -> SignalData */
443   GHashTable *map_id_to_signal_data;                        /* id (guint)             -> SignalData */
444   GHashTable *map_sender_unique_name_to_signal_data_array;  /* unique sender (gchar*) -> GPtrArray* of SignalData */
445
446   /* Maps used for managing exported objects and subtrees,
447    * protected by @lock
448    */
449   GHashTable *map_object_path_to_eo;  /* gchar* -> ExportedObject* */
450   GHashTable *map_id_to_ei;           /* guint  -> ExportedInterface* */
451   GHashTable *map_object_path_to_es;  /* gchar* -> ExportedSubtree* */
452   GHashTable *map_id_to_es;           /* guint  -> ExportedSubtree* */
453
454   /* Map used for storing last used serials for each thread, protected by @lock */
455   GHashTable *map_thread_to_last_serial;
456
457   /* Structure used for message filters, protected by @lock */
458   GPtrArray *filters;
459
460   /* Capabilities negotiated during authentication
461    * Read-only after initable_init(), so it may be read without holding a
462    * lock, if you check for initialization first.
463    */
464   GDBusCapabilityFlags capabilities;
465
466   /* Protected by @init_lock */
467   GDBusAuthObserver *authentication_observer;
468
469   /* Read-only after initable_init(), so it may be read if you either
470    * hold @init_lock or check for initialization first.
471    */
472   GCredentials *credentials;
473
474   /* set to TRUE when finalizing */
475   gboolean finalizing;
476 };
477
478 typedef struct ExportedObject ExportedObject;
479 static void exported_object_free (ExportedObject *eo);
480
481 typedef struct ExportedSubtree ExportedSubtree;
482 static void exported_subtree_free (ExportedSubtree *es);
483
484 enum
485 {
486   CLOSED_SIGNAL,
487   LAST_SIGNAL,
488 };
489
490 enum
491 {
492   PROP_0,
493   PROP_STREAM,
494   PROP_ADDRESS,
495   PROP_FLAGS,
496   PROP_GUID,
497   PROP_UNIQUE_NAME,
498   PROP_CLOSED,
499   PROP_EXIT_ON_CLOSE,
500   PROP_CAPABILITY_FLAGS,
501   PROP_AUTHENTICATION_OBSERVER,
502 };
503
504 static void distribute_signals (GDBusConnection  *connection,
505                                 GDBusMessage     *message);
506
507 static void distribute_method_call (GDBusConnection  *connection,
508                                     GDBusMessage     *message);
509
510 static gboolean handle_generic_unlocked (GDBusConnection *connection,
511                                          GDBusMessage    *message);
512
513
514 static void purge_all_signal_subscriptions (GDBusConnection *connection);
515 static void purge_all_filters (GDBusConnection *connection);
516
517 static void schedule_method_call (GDBusConnection            *connection,
518                                   GDBusMessage               *message,
519                                   guint                       registration_id,
520                                   guint                       subtree_registration_id,
521                                   const GDBusInterfaceInfo   *interface_info,
522                                   const GDBusMethodInfo      *method_info,
523                                   const GDBusPropertyInfo    *property_info,
524                                   GVariant                   *parameters,
525                                   const GDBusInterfaceVTable *vtable,
526                                   GMainContext               *main_context,
527                                   gpointer                    user_data);
528
529 #define _G_ENSURE_LOCK(name) do {                                       \
530     if (G_UNLIKELY (G_TRYLOCK(name)))                                   \
531       {                                                                 \
532         g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
533                              "_G_ENSURE_LOCK: Lock '" #name "' is not locked"); \
534       }                                                                 \
535   } while (FALSE)                                                       \
536
537 static guint signals[LAST_SIGNAL] = { 0 };
538
539 static void initable_iface_init       (GInitableIface      *initable_iface);
540 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
541
542 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
543                          G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
544                          G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
545                          );
546
547 /*
548  * Check that all members of @connection that can only be accessed after
549  * the connection is initialized can safely be accessed. If not,
550  * log a critical warning. This function is a memory barrier.
551  *
552  * Returns: %TRUE if initialized
553  */
554 static gboolean
555 check_initialized (GDBusConnection *connection)
556 {
557   /* The access to @atomic_flags isn't conditional, so that this function
558    * provides a memory barrier for thread-safety even if checks are disabled.
559    * (If you don't want this stricter guarantee, you can call
560    * g_return_if_fail (check_initialized (c)).)
561    *
562    * This isn't strictly necessary now that we've decided use of an
563    * uninitialized GDBusConnection is undefined behaviour, but it seems
564    * better to be as deterministic as is feasible.
565    *
566    * (Anything that could suffer a crash from seeing undefined values
567    * must have a race condition - thread A initializes the connection while
568    * thread B calls a method without initialization, hoping that thread A will
569    * win the race - so its behaviour is undefined anyway.)
570    */
571   gint flags = g_atomic_int_get (&connection->atomic_flags);
572
573   g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
574
575   /* We can safely access this, due to the memory barrier above */
576   g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
577
578   return TRUE;
579 }
580
581 typedef enum {
582     MAY_BE_UNINITIALIZED = (1<<1)
583 } CheckUnclosedFlags;
584
585 /*
586  * Check the same thing as check_initialized(), and also that the
587  * connection is not closed. If the connection is uninitialized,
588  * raise a critical warning (it's programmer error); if it's closed,
589  * raise a recoverable GError (it's a runtime error).
590  *
591  * This function is a memory barrier.
592  *
593  * Returns: %TRUE if initialized and not closed
594  */
595 static gboolean
596 check_unclosed (GDBusConnection     *connection,
597                 CheckUnclosedFlags   check,
598                 GError             **error)
599 {
600   /* check_initialized() is effectively inlined, so we don't waste time
601    * doing two memory barriers
602    */
603   gint flags = g_atomic_int_get (&connection->atomic_flags);
604
605   if (!(check & MAY_BE_UNINITIALIZED))
606     {
607       g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
608       g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
609     }
610
611   if (flags & FLAG_CLOSED)
612     {
613       g_set_error_literal (error,
614                            G_IO_ERROR,
615                            G_IO_ERROR_CLOSED,
616                            _("The connection is closed"));
617       return FALSE;
618     }
619
620   return TRUE;
621 }
622
623 static GHashTable *alive_connections = NULL;
624
625 static void
626 g_dbus_connection_dispose (GObject *object)
627 {
628   GDBusConnection *connection = G_DBUS_CONNECTION (object);
629
630   G_LOCK (message_bus_lock);
631   CONNECTION_LOCK (connection);
632   if (connection->worker != NULL)
633     {
634       _g_dbus_worker_stop (connection->worker);
635       connection->worker = NULL;
636       if (alive_connections != NULL)
637         g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
638     }
639   else
640     {
641       if (alive_connections != NULL)
642         g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
643     }
644   CONNECTION_UNLOCK (connection);
645   G_UNLOCK (message_bus_lock);
646
647   if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
648     G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
649 }
650
651 static void
652 g_dbus_connection_finalize (GObject *object)
653 {
654   GDBusConnection *connection = G_DBUS_CONNECTION (object);
655
656   connection->finalizing = TRUE;
657
658   purge_all_signal_subscriptions (connection);
659
660   purge_all_filters (connection);
661   g_ptr_array_unref (connection->filters);
662
663   if (connection->authentication_observer != NULL)
664     g_object_unref (connection->authentication_observer);
665
666   if (connection->auth != NULL)
667     g_object_unref (connection->auth);
668
669   if (connection->credentials)
670     g_object_unref (connection->credentials);
671
672   if (connection->stream != NULL)
673     {
674       g_object_unref (connection->stream);
675       connection->stream = NULL;
676     }
677
678   g_free (connection->address);
679
680   g_free (connection->guid);
681   g_free (connection->bus_unique_name);
682
683   if (connection->initialization_error != NULL)
684     g_error_free (connection->initialization_error);
685
686   g_hash_table_unref (connection->map_method_serial_to_send_message_data);
687
688   g_hash_table_unref (connection->map_rule_to_signal_data);
689   g_hash_table_unref (connection->map_id_to_signal_data);
690   g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
691
692   g_hash_table_unref (connection->map_id_to_ei);
693   g_hash_table_unref (connection->map_object_path_to_eo);
694   g_hash_table_unref (connection->map_id_to_es);
695   g_hash_table_unref (connection->map_object_path_to_es);
696
697   g_hash_table_unref (connection->map_thread_to_last_serial);
698
699   g_main_context_unref (connection->main_context_at_construction);
700
701   g_free (connection->machine_id);
702
703   g_mutex_clear (&connection->init_lock);
704   g_mutex_clear (&connection->lock);
705
706   G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
707 }
708
709 /* called in any user thread, with the connection's lock not held */
710 static void
711 g_dbus_connection_get_property (GObject    *object,
712                                 guint       prop_id,
713                                 GValue     *value,
714                                 GParamSpec *pspec)
715 {
716   GDBusConnection *connection = G_DBUS_CONNECTION (object);
717
718   switch (prop_id)
719     {
720     case PROP_STREAM:
721       g_value_set_object (value, g_dbus_connection_get_stream (connection));
722       break;
723
724     case PROP_GUID:
725       g_value_set_string (value, g_dbus_connection_get_guid (connection));
726       break;
727
728     case PROP_UNIQUE_NAME:
729       g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
730       break;
731
732     case PROP_CLOSED:
733       g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
734       break;
735
736     case PROP_EXIT_ON_CLOSE:
737       g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
738       break;
739
740     case PROP_CAPABILITY_FLAGS:
741       g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
742       break;
743
744     default:
745       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
746       break;
747     }
748 }
749
750 /* called in any user thread, with the connection's lock not held */
751 static void
752 g_dbus_connection_set_property (GObject      *object,
753                                 guint         prop_id,
754                                 const GValue *value,
755                                 GParamSpec   *pspec)
756 {
757   GDBusConnection *connection = G_DBUS_CONNECTION (object);
758
759   switch (prop_id)
760     {
761     case PROP_STREAM:
762       connection->stream = g_value_dup_object (value);
763       break;
764
765     case PROP_GUID:
766       connection->guid = g_value_dup_string (value);
767       break;
768
769     case PROP_ADDRESS:
770       connection->address = g_value_dup_string (value);
771       break;
772
773     case PROP_FLAGS:
774       connection->flags = g_value_get_flags (value);
775       break;
776
777     case PROP_EXIT_ON_CLOSE:
778       g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
779       break;
780
781     case PROP_AUTHENTICATION_OBSERVER:
782       connection->authentication_observer = g_value_dup_object (value);
783       break;
784
785     default:
786       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
787       break;
788     }
789 }
790
791 /* Base-class implementation of GDBusConnection::closed.
792  *
793  * Called in a user thread, by the main context that was thread-default when
794  * the object was constructed.
795  */
796 static void
797 g_dbus_connection_real_closed (GDBusConnection *connection,
798                                gboolean         remote_peer_vanished,
799                                GError          *error)
800 {
801   gint flags = g_atomic_int_get (&connection->atomic_flags);
802
803   /* Because atomic int access is a memory barrier, we can safely read
804    * initialization_error without a lock, as long as we do it afterwards.
805    */
806   if (remote_peer_vanished &&
807       (flags & FLAG_EXIT_ON_CLOSE) != 0 &&
808       (flags & FLAG_INITIALIZED) != 0 &&
809       connection->initialization_error == NULL)
810     {
811       if (error != NULL)
812         {
813           g_printerr ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
814                       G_STRFUNC,
815                       error->message,
816                       g_quark_to_string (error->domain), error->code);
817         }
818       else
819         {
820           g_printerr ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
821         }
822       raise (SIGTERM);
823     }
824 }
825
826 static void
827 g_dbus_connection_class_init (GDBusConnectionClass *klass)
828 {
829   GObjectClass *gobject_class;
830
831   gobject_class = G_OBJECT_CLASS (klass);
832
833   gobject_class->finalize     = g_dbus_connection_finalize;
834   gobject_class->dispose      = g_dbus_connection_dispose;
835   gobject_class->set_property = g_dbus_connection_set_property;
836   gobject_class->get_property = g_dbus_connection_get_property;
837
838   klass->closed = g_dbus_connection_real_closed;
839
840   /**
841    * GDBusConnection:stream:
842    *
843    * The underlying #GIOStream used for I/O.
844    *
845    * If this is passed on construction and is a #GSocketConnection,
846    * then the corresponding #GSocket will be put into non-blocking mode.
847    *
848    * While the #GDBusConnection is active, it will interact with this
849    * stream from a worker thread, so it is not safe to interact with
850    * the stream directly.
851    *
852    * Since: 2.26
853    */
854   g_object_class_install_property (gobject_class,
855                                    PROP_STREAM,
856                                    g_param_spec_object ("stream",
857                                                         P_("IO Stream"),
858                                                         P_("The underlying streams used for I/O"),
859                                                         G_TYPE_IO_STREAM,
860                                                         G_PARAM_READABLE |
861                                                         G_PARAM_WRITABLE |
862                                                         G_PARAM_CONSTRUCT_ONLY |
863                                                         G_PARAM_STATIC_NAME |
864                                                         G_PARAM_STATIC_BLURB |
865                                                         G_PARAM_STATIC_NICK));
866
867   /**
868    * GDBusConnection:address:
869    *
870    * A D-Bus address specifying potential endpoints that can be used
871    * when establishing the connection.
872    *
873    * Since: 2.26
874    */
875   g_object_class_install_property (gobject_class,
876                                    PROP_ADDRESS,
877                                    g_param_spec_string ("address",
878                                                         P_("Address"),
879                                                         P_("D-Bus address specifying potential socket endpoints"),
880                                                         NULL,
881                                                         G_PARAM_WRITABLE |
882                                                         G_PARAM_CONSTRUCT_ONLY |
883                                                         G_PARAM_STATIC_NAME |
884                                                         G_PARAM_STATIC_BLURB |
885                                                         G_PARAM_STATIC_NICK));
886
887   /**
888    * GDBusConnection:flags:
889    *
890    * Flags from the #GDBusConnectionFlags enumeration.
891    *
892    * Since: 2.26
893    */
894   g_object_class_install_property (gobject_class,
895                                    PROP_FLAGS,
896                                    g_param_spec_flags ("flags",
897                                                        P_("Flags"),
898                                                        P_("Flags"),
899                                                        G_TYPE_DBUS_CONNECTION_FLAGS,
900                                                        G_DBUS_CONNECTION_FLAGS_NONE,
901                                                        G_PARAM_WRITABLE |
902                                                        G_PARAM_CONSTRUCT_ONLY |
903                                                        G_PARAM_STATIC_NAME |
904                                                        G_PARAM_STATIC_BLURB |
905                                                        G_PARAM_STATIC_NICK));
906
907   /**
908    * GDBusConnection:guid:
909    *
910    * The GUID of the peer performing the role of server when
911    * authenticating.
912    *
913    * If you are constructing a #GDBusConnection and pass
914    * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
915    * #GDBusConnection:flags property then you MUST also set this
916    * property to a valid guid.
917    *
918    * If you are constructing a #GDBusConnection and pass
919    * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
920    * #GDBusConnection:flags property you will be able to read the GUID
921    * of the other peer here after the connection has been successfully
922    * initialized.
923    *
924    * Since: 2.26
925    */
926   g_object_class_install_property (gobject_class,
927                                    PROP_GUID,
928                                    g_param_spec_string ("guid",
929                                                         P_("GUID"),
930                                                         P_("GUID of the server peer"),
931                                                         NULL,
932                                                         G_PARAM_READABLE |
933                                                         G_PARAM_WRITABLE |
934                                                         G_PARAM_CONSTRUCT_ONLY |
935                                                         G_PARAM_STATIC_NAME |
936                                                         G_PARAM_STATIC_BLURB |
937                                                         G_PARAM_STATIC_NICK));
938
939   /**
940    * GDBusConnection:unique-name:
941    *
942    * The unique name as assigned by the message bus or %NULL if the
943    * connection is not open or not a message bus connection.
944    *
945    * Since: 2.26
946    */
947   g_object_class_install_property (gobject_class,
948                                    PROP_UNIQUE_NAME,
949                                    g_param_spec_string ("unique-name",
950                                                         P_("unique-name"),
951                                                         P_("Unique name of bus connection"),
952                                                         NULL,
953                                                         G_PARAM_READABLE |
954                                                         G_PARAM_STATIC_NAME |
955                                                         G_PARAM_STATIC_BLURB |
956                                                         G_PARAM_STATIC_NICK));
957
958   /**
959    * GDBusConnection:closed:
960    *
961    * A boolean specifying whether the connection has been closed.
962    *
963    * Since: 2.26
964    */
965   g_object_class_install_property (gobject_class,
966                                    PROP_CLOSED,
967                                    g_param_spec_boolean ("closed",
968                                                          P_("Closed"),
969                                                          P_("Whether the connection is closed"),
970                                                          FALSE,
971                                                          G_PARAM_READABLE |
972                                                          G_PARAM_STATIC_NAME |
973                                                          G_PARAM_STATIC_BLURB |
974                                                          G_PARAM_STATIC_NICK));
975
976   /**
977    * GDBusConnection:exit-on-close:
978    *
979    * A boolean specifying whether the process will be terminated (by
980    * calling `raise(SIGTERM)`) if the connection is closed by the
981    * remote peer.
982    *
983    * Note that #GDBusConnection objects returned by g_bus_get_finish()
984    * and g_bus_get_sync() will (usually) have this property set to %TRUE.
985    *
986    * Since: 2.26
987    */
988   g_object_class_install_property (gobject_class,
989                                    PROP_EXIT_ON_CLOSE,
990                                    g_param_spec_boolean ("exit-on-close",
991                                                          P_("Exit on close"),
992                                                          P_("Whether the process is terminated when the connection is closed"),
993                                                          FALSE,
994                                                          G_PARAM_READABLE |
995                                                          G_PARAM_WRITABLE |
996                                                          G_PARAM_STATIC_NAME |
997                                                          G_PARAM_STATIC_BLURB |
998                                                          G_PARAM_STATIC_NICK));
999
1000   /**
1001    * GDBusConnection:capabilities:
1002    *
1003    * Flags from the #GDBusCapabilityFlags enumeration
1004    * representing connection features negotiated with the other peer.
1005    *
1006    * Since: 2.26
1007    */
1008   g_object_class_install_property (gobject_class,
1009                                    PROP_CAPABILITY_FLAGS,
1010                                    g_param_spec_flags ("capabilities",
1011                                                        P_("Capabilities"),
1012                                                        P_("Capabilities"),
1013                                                        G_TYPE_DBUS_CAPABILITY_FLAGS,
1014                                                        G_DBUS_CAPABILITY_FLAGS_NONE,
1015                                                        G_PARAM_READABLE |
1016                                                        G_PARAM_STATIC_NAME |
1017                                                        G_PARAM_STATIC_BLURB |
1018                                                        G_PARAM_STATIC_NICK));
1019
1020   /**
1021    * GDBusConnection:authentication-observer:
1022    *
1023    * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
1024    *
1025    * Since: 2.26
1026    */
1027   g_object_class_install_property (gobject_class,
1028                                    PROP_AUTHENTICATION_OBSERVER,
1029                                    g_param_spec_object ("authentication-observer",
1030                                                         P_("Authentication Observer"),
1031                                                         P_("Object used to assist in the authentication process"),
1032                                                         G_TYPE_DBUS_AUTH_OBSERVER,
1033                                                         G_PARAM_WRITABLE |
1034                                                         G_PARAM_CONSTRUCT_ONLY |
1035                                                         G_PARAM_STATIC_NAME |
1036                                                         G_PARAM_STATIC_BLURB |
1037                                                         G_PARAM_STATIC_NICK));
1038
1039   /**
1040    * GDBusConnection::closed:
1041    * @connection: the #GDBusConnection emitting the signal
1042    * @remote_peer_vanished: %TRUE if @connection is closed because the
1043    *     remote peer closed its end of the connection
1044    * @error: (allow-none): a #GError with more details about the event or %NULL
1045    *
1046    * Emitted when the connection is closed.
1047    *
1048    * The cause of this event can be
1049    *
1050    * - If g_dbus_connection_close() is called. In this case
1051    *   @remote_peer_vanished is set to %FALSE and @error is %NULL.
1052    *
1053    * - If the remote peer closes the connection. In this case
1054    *   @remote_peer_vanished is set to %TRUE and @error is set.
1055    *
1056    * - If the remote peer sends invalid or malformed data. In this
1057    *   case @remote_peer_vanished is set to %FALSE and @error is set.
1058    *
1059    * Upon receiving this signal, you should give up your reference to
1060    * @connection. You are guaranteed that this signal is emitted only
1061    * once.
1062    *
1063    * Since: 2.26
1064    */
1065   signals[CLOSED_SIGNAL] = g_signal_new ("closed",
1066                                          G_TYPE_DBUS_CONNECTION,
1067                                          G_SIGNAL_RUN_LAST,
1068                                          G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1069                                          NULL,
1070                                          NULL,
1071                                          NULL,
1072                                          G_TYPE_NONE,
1073                                          2,
1074                                          G_TYPE_BOOLEAN,
1075                                          G_TYPE_ERROR);
1076 }
1077
1078 static void
1079 g_dbus_connection_init (GDBusConnection *connection)
1080 {
1081   g_mutex_init (&connection->lock);
1082   g_mutex_init (&connection->init_lock);
1083
1084   connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
1085
1086   connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1087                                                           g_str_equal);
1088   connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1089                                                         g_direct_equal);
1090   connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1091                                                                                    g_str_equal,
1092                                                                                    g_free,
1093                                                                                    (GDestroyNotify) g_ptr_array_unref);
1094
1095   connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1096                                                              g_str_equal,
1097                                                              NULL,
1098                                                              (GDestroyNotify) exported_object_free);
1099
1100   connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1101                                                g_direct_equal);
1102
1103   connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1104                                                              g_str_equal,
1105                                                              NULL,
1106                                                              (GDestroyNotify) exported_subtree_free);
1107
1108   connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1109                                                g_direct_equal);
1110
1111   connection->map_thread_to_last_serial = g_hash_table_new (g_direct_hash,
1112                                                             g_direct_equal);
1113
1114   connection->main_context_at_construction = g_main_context_ref_thread_default ();
1115
1116   connection->filters = g_ptr_array_new ();
1117 }
1118
1119 /**
1120  * g_dbus_connection_get_stream:
1121  * @connection: a #GDBusConnection
1122  *
1123  * Gets the underlying stream used for IO.
1124  *
1125  * While the #GDBusConnection is active, it will interact with this
1126  * stream from a worker thread, so it is not safe to interact with
1127  * the stream directly.
1128  *
1129  * Returns: (transfer none): the stream used for IO
1130  *
1131  * Since: 2.26
1132  */
1133 GIOStream *
1134 g_dbus_connection_get_stream (GDBusConnection *connection)
1135 {
1136   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1137
1138   /* do not use g_return_val_if_fail(), we want the memory barrier */
1139   if (!check_initialized (connection))
1140     return NULL;
1141
1142   return connection->stream;
1143 }
1144
1145 /**
1146  * g_dbus_connection_start_message_processing:
1147  * @connection: a #GDBusConnection
1148  *
1149  * If @connection was created with
1150  * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1151  * starts processing messages. Does nothing on if @connection wasn't
1152  * created with this flag or if the method has already been called.
1153  *
1154  * Since: 2.26
1155  */
1156 void
1157 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1158 {
1159   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1160
1161   /* do not use g_return_val_if_fail(), we want the memory barrier */
1162   if (!check_initialized (connection))
1163     return;
1164
1165   g_assert (connection->worker != NULL);
1166   _g_dbus_worker_unfreeze (connection->worker);
1167 }
1168
1169 /**
1170  * g_dbus_connection_is_closed:
1171  * @connection: a #GDBusConnection
1172  *
1173  * Gets whether @connection is closed.
1174  *
1175  * Returns: %TRUE if the connection is closed, %FALSE otherwise
1176  *
1177  * Since: 2.26
1178  */
1179 gboolean
1180 g_dbus_connection_is_closed (GDBusConnection *connection)
1181 {
1182   gint flags;
1183
1184   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1185
1186   flags = g_atomic_int_get (&connection->atomic_flags);
1187
1188   return (flags & FLAG_CLOSED) ? TRUE : FALSE;
1189 }
1190
1191 /**
1192  * g_dbus_connection_get_capabilities:
1193  * @connection: a #GDBusConnection
1194  *
1195  * Gets the capabilities negotiated with the remote peer
1196  *
1197  * Returns: zero or more flags from the #GDBusCapabilityFlags enumeration
1198  *
1199  * Since: 2.26
1200  */
1201 GDBusCapabilityFlags
1202 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1203 {
1204   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1205
1206   /* do not use g_return_val_if_fail(), we want the memory barrier */
1207   if (!check_initialized (connection))
1208     return G_DBUS_CAPABILITY_FLAGS_NONE;
1209
1210   return connection->capabilities;
1211 }
1212
1213 /* ---------------------------------------------------------------------------------------------------- */
1214
1215 /* Called in a temporary thread without holding locks. */
1216 static void
1217 flush_in_thread_func (GSimpleAsyncResult *res,
1218                       GObject            *object,
1219                       GCancellable       *cancellable)
1220 {
1221   GError *error;
1222
1223   error = NULL;
1224   if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
1225                                      cancellable,
1226                                      &error))
1227     g_simple_async_result_take_error (res, error);
1228 }
1229
1230 /**
1231  * g_dbus_connection_flush:
1232  * @connection: a #GDBusConnection
1233  * @cancellable: (allow-none): a #GCancellable or %NULL
1234  * @callback: (allow-none): a #GAsyncReadyCallback to call when the
1235  *     request is satisfied or %NULL if you don't care about the result
1236  * @user_data: The data to pass to @callback
1237  *
1238  * Asynchronously flushes @connection, that is, writes all queued
1239  * outgoing message to the transport and then flushes the transport
1240  * (using g_output_stream_flush_async()). This is useful in programs
1241  * that wants to emit a D-Bus signal and then exit immediately. Without
1242  * flushing the connection, there is no guaranteed that the message has
1243  * been sent to the networking buffers in the OS kernel.
1244  *
1245  * This is an asynchronous method. When the operation is finished,
1246  * @callback will be invoked in the
1247  * [thread-default main context][g-main-context-push-thread-default]
1248  * of the thread you are calling this method from. You can
1249  * then call g_dbus_connection_flush_finish() to get the result of the
1250  * operation. See g_dbus_connection_flush_sync() for the synchronous
1251  * version.
1252  *
1253  * Since: 2.26
1254  */
1255 void
1256 g_dbus_connection_flush (GDBusConnection     *connection,
1257                          GCancellable        *cancellable,
1258                          GAsyncReadyCallback  callback,
1259                          gpointer             user_data)
1260 {
1261   GSimpleAsyncResult *simple;
1262
1263   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1264
1265   simple = g_simple_async_result_new (G_OBJECT (connection),
1266                                       callback,
1267                                       user_data,
1268                                       g_dbus_connection_flush);
1269   g_simple_async_result_set_check_cancellable (simple, cancellable);
1270   g_simple_async_result_run_in_thread (simple,
1271                                        flush_in_thread_func,
1272                                        G_PRIORITY_DEFAULT,
1273                                        cancellable);
1274   g_object_unref (simple);
1275 }
1276
1277 /**
1278  * g_dbus_connection_flush_finish:
1279  * @connection: a #GDBusConnection
1280  * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1281  *     to g_dbus_connection_flush()
1282  * @error: return location for error or %NULL
1283  *
1284  * Finishes an operation started with g_dbus_connection_flush().
1285  *
1286  * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1287  *
1288  * Since: 2.26
1289  */
1290 gboolean
1291 g_dbus_connection_flush_finish (GDBusConnection  *connection,
1292                                 GAsyncResult     *res,
1293                                 GError          **error)
1294 {
1295   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1296   gboolean ret;
1297
1298   ret = FALSE;
1299
1300   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1301   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1302   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1303
1304   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1305
1306   if (g_simple_async_result_propagate_error (simple, error))
1307     goto out;
1308
1309   ret = TRUE;
1310
1311  out:
1312   return ret;
1313 }
1314
1315 /**
1316  * g_dbus_connection_flush_sync:
1317  * @connection: a #GDBusConnection
1318  * @cancellable: (allow-none): a #GCancellable or %NULL
1319  * @error: return location for error or %NULL
1320  *
1321  * Synchronously flushes @connection. The calling thread is blocked
1322  * until this is done. See g_dbus_connection_flush() for the
1323  * asynchronous version of this method and more details about what it
1324  * does.
1325  *
1326  * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1327  *
1328  * Since: 2.26
1329  */
1330 gboolean
1331 g_dbus_connection_flush_sync (GDBusConnection  *connection,
1332                               GCancellable     *cancellable,
1333                               GError          **error)
1334 {
1335   gboolean ret;
1336
1337   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1338   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1339
1340   ret = FALSE;
1341
1342   /* This is only a best-effort attempt to see whether the connection is
1343    * closed, so it doesn't need the lock. If the connection closes just
1344    * after this check, but before scheduling the flush operation, the
1345    * result will be more or less the same as if the connection closed while
1346    * the flush operation was pending - it'll fail with either CLOSED or
1347    * CANCELLED.
1348    */
1349   if (!check_unclosed (connection, 0, error))
1350     goto out;
1351
1352   g_assert (connection->worker != NULL);
1353
1354   ret = _g_dbus_worker_flush_sync (connection->worker,
1355                                    cancellable,
1356                                    error);
1357
1358  out:
1359   return ret;
1360 }
1361
1362 /* ---------------------------------------------------------------------------------------------------- */
1363
1364 typedef struct
1365 {
1366   GDBusConnection *connection;
1367   GError *error;
1368   gboolean remote_peer_vanished;
1369 } EmitClosedData;
1370
1371 static void
1372 emit_closed_data_free (EmitClosedData *data)
1373 {
1374   g_object_unref (data->connection);
1375   if (data->error != NULL)
1376     g_error_free (data->error);
1377   g_free (data);
1378 }
1379
1380 /* Called in a user thread that has acquired the main context that was
1381  * thread-default when the object was constructed
1382  */
1383 static gboolean
1384 emit_closed_in_idle (gpointer user_data)
1385 {
1386   EmitClosedData *data = user_data;
1387   gboolean result;
1388
1389   g_object_notify (G_OBJECT (data->connection), "closed");
1390   g_signal_emit (data->connection,
1391                  signals[CLOSED_SIGNAL],
1392                  0,
1393                  data->remote_peer_vanished,
1394                  data->error,
1395                  &result);
1396   return FALSE;
1397 }
1398
1399 /* Can be called from any thread, must hold lock.
1400  * FLAG_CLOSED must already have been set.
1401  */
1402 static void
1403 schedule_closed_unlocked (GDBusConnection *connection,
1404                           gboolean         remote_peer_vanished,
1405                           GError          *error)
1406 {
1407   GSource *idle_source;
1408   EmitClosedData *data;
1409
1410   CONNECTION_ENSURE_LOCK (connection);
1411
1412   data = g_new0 (EmitClosedData, 1);
1413   data->connection = g_object_ref (connection);
1414   data->remote_peer_vanished = remote_peer_vanished;
1415   data->error = error != NULL ? g_error_copy (error) : NULL;
1416
1417   idle_source = g_idle_source_new ();
1418   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1419   g_source_set_callback (idle_source,
1420                          emit_closed_in_idle,
1421                          data,
1422                          (GDestroyNotify) emit_closed_data_free);
1423   g_source_set_name (idle_source, "[gio] emit_closed_in_idle");
1424   g_source_attach (idle_source, connection->main_context_at_construction);
1425   g_source_unref (idle_source);
1426 }
1427
1428 /* ---------------------------------------------------------------------------------------------------- */
1429
1430 /**
1431  * g_dbus_connection_close:
1432  * @connection: a #GDBusConnection
1433  * @cancellable: (allow-none): a #GCancellable or %NULL
1434  * @callback: (allow-none): a #GAsyncReadyCallback to call when the request is
1435  *     satisfied or %NULL if you don't care about the result
1436  * @user_data: The data to pass to @callback
1437  *
1438  * Closes @connection. Note that this never causes the process to
1439  * exit (this might only happen if the other end of a shared message
1440  * bus connection disconnects, see #GDBusConnection:exit-on-close).
1441  *
1442  * Once the connection is closed, operations such as sending a message
1443  * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1444  * will not automatically flush the connection so queued messages may
1445  * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1446  *
1447  * If @connection is already closed, this method fails with
1448  * %G_IO_ERROR_CLOSED.
1449  *
1450  * When @connection has been closed, the #GDBusConnection::closed
1451  * signal is emitted in the
1452  * [thread-default main context][g-main-context-push-thread-default]
1453  * of the thread that @connection was constructed in.
1454  *
1455  * This is an asynchronous method. When the operation is finished,
1456  * @callback will be invoked in the 
1457  * [thread-default main context][g-main-context-push-thread-default]
1458  * of the thread you are calling this method from. You can
1459  * then call g_dbus_connection_close_finish() to get the result of the
1460  * operation. See g_dbus_connection_close_sync() for the synchronous
1461  * version.
1462  *
1463  * Since: 2.26
1464  */
1465 void
1466 g_dbus_connection_close (GDBusConnection     *connection,
1467                          GCancellable        *cancellable,
1468                          GAsyncReadyCallback  callback,
1469                          gpointer             user_data)
1470 {
1471   GSimpleAsyncResult *simple;
1472
1473   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1474
1475   /* do not use g_return_val_if_fail(), we want the memory barrier */
1476   if (!check_initialized (connection))
1477     return;
1478
1479   g_assert (connection->worker != NULL);
1480
1481   simple = g_simple_async_result_new (G_OBJECT (connection),
1482                                       callback,
1483                                       user_data,
1484                                       g_dbus_connection_close);
1485   g_simple_async_result_set_check_cancellable (simple, cancellable);
1486   _g_dbus_worker_close (connection->worker, cancellable, simple);
1487   g_object_unref (simple);
1488 }
1489
1490 /**
1491  * g_dbus_connection_close_finish:
1492  * @connection: a #GDBusConnection
1493  * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1494  *     to g_dbus_connection_close()
1495  * @error: return location for error or %NULL
1496  *
1497  * Finishes an operation started with g_dbus_connection_close().
1498  *
1499  * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1500  *
1501  * Since: 2.26
1502  */
1503 gboolean
1504 g_dbus_connection_close_finish (GDBusConnection  *connection,
1505                                 GAsyncResult     *res,
1506                                 GError          **error)
1507 {
1508   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1509   gboolean ret;
1510
1511   ret = FALSE;
1512
1513   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1514   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1515   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1516
1517   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1518
1519   if (g_simple_async_result_propagate_error (simple, error))
1520     goto out;
1521
1522   ret = TRUE;
1523
1524  out:
1525   return ret;
1526 }
1527
1528 typedef struct {
1529     GMainLoop *loop;
1530     GAsyncResult *result;
1531 } SyncCloseData;
1532
1533 /* Can be called by any thread, without the connection lock */
1534 static void
1535 sync_close_cb (GObject *source_object,
1536                GAsyncResult *res,
1537                gpointer user_data)
1538 {
1539   SyncCloseData *data = user_data;
1540
1541   data->result = g_object_ref (res);
1542   g_main_loop_quit (data->loop);
1543 }
1544
1545 /**
1546  * g_dbus_connection_close_sync:
1547  * @connection: a #GDBusConnection
1548  * @cancellable: (allow-none): a #GCancellable or %NULL
1549  * @error: return location for error or %NULL
1550  *
1551  * Synchronously closees @connection. The calling thread is blocked
1552  * until this is done. See g_dbus_connection_close() for the
1553  * asynchronous version of this method and more details about what it
1554  * does.
1555  *
1556  * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1557  *
1558  * Since: 2.26
1559  */
1560 gboolean
1561 g_dbus_connection_close_sync (GDBusConnection  *connection,
1562                               GCancellable     *cancellable,
1563                               GError          **error)
1564 {
1565   gboolean ret;
1566
1567   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1568   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1569
1570   ret = FALSE;
1571
1572   if (check_unclosed (connection, 0, error))
1573     {
1574       GMainContext *context;
1575       SyncCloseData data;
1576
1577       context = g_main_context_new ();
1578       g_main_context_push_thread_default (context);
1579       data.loop = g_main_loop_new (context, TRUE);
1580       data.result = NULL;
1581
1582       g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1583       g_main_loop_run (data.loop);
1584       ret = g_dbus_connection_close_finish (connection, data.result, error);
1585
1586       g_object_unref (data.result);
1587       g_main_loop_unref (data.loop);
1588       g_main_context_pop_thread_default (context);
1589       g_main_context_unref (context);
1590     }
1591
1592   return ret;
1593 }
1594
1595 /* ---------------------------------------------------------------------------------------------------- */
1596
1597 /**
1598  * g_dbus_request_name:
1599  * @connection: a #GDBusConnection
1600  * @name: well-known bus name (name to request)
1601  * @flags: a set of flags from the GBusNameOwnerFlags enumeration
1602  * @error: return location for error or %NULL
1603  *
1604  * Synchronously acquires name on the bus and returns status code.
1605  *
1606  * The calling thread is blocked until a reply is received.
1607  *
1608  * Returns: status code or %G_BUS_REQUEST_NAME_FLAGS_ERROR
1609  *     if @error is set.
1610  *
1611  * Since: 2.4x
1612  */
1613 GBusRequestNameReplyFlags
1614 g_dbus_request_name (GDBusConnection     *connection,
1615                      const gchar         *name,
1616                      GBusNameOwnerFlags   flags,
1617                      GError             **error)
1618 {
1619   GVariant *result;
1620   guint32 request_name_reply;
1621
1622   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_BUS_RELEASE_NAME_FLAGS_ERROR);
1623   g_return_val_if_fail (g_dbus_is_name (name) && !g_dbus_is_unique_name (name), G_BUS_RELEASE_NAME_FLAGS_ERROR);
1624   g_return_val_if_fail (error == NULL || *error == NULL, G_BUS_RELEASE_NAME_FLAGS_ERROR);
1625
1626   if (G_IS_KDBUS_CONNECTION (connection->stream))
1627     result = _g_kdbus_RequestName (connection, name, flags, error);
1628   else
1629     result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/org/freedesktop/DBus",
1630                                           "org.freedesktop.DBus", "RequestName",
1631                                           g_variant_new ("(su)", name, flags), G_VARIANT_TYPE ("(u)"),
1632                                           G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1633
1634   if (result != NULL)
1635     {
1636       g_variant_get (result, "(u)", &request_name_reply);
1637       g_variant_unref (result);
1638     }
1639   else
1640     request_name_reply = G_BUS_REQUEST_NAME_FLAGS_ERROR;
1641
1642   return (GBusRequestNameReplyFlags) request_name_reply;
1643 }
1644
1645 /**
1646  * g_dbus_release_name:
1647  * @connection: a #GDBusConnection
1648  * @name: well-known bus name (name to release)
1649  * @error: return location for error or %NULL
1650  *
1651  * Synchronously releases name on the bus and returns status code.
1652  *
1653  * The calling thread is blocked until a reply is received.
1654  *
1655  * Returns: status code or %G_BUS_RELEASE_NAME_FLAGS_ERROR
1656  *     if @error is set.
1657  *
1658  * Since: 2.4x
1659  */
1660 GBusReleaseNameReplyFlags
1661 g_dbus_release_name (GDBusConnection     *connection,
1662                      const gchar         *name,
1663                      GError             **error)
1664 {
1665   GVariant *result;
1666   guint32 release_name_reply;
1667
1668   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_BUS_RELEASE_NAME_FLAGS_ERROR);
1669   g_return_val_if_fail (g_dbus_is_name (name) && !g_dbus_is_unique_name (name), G_BUS_RELEASE_NAME_FLAGS_ERROR);
1670   g_return_val_if_fail (error == NULL || *error == NULL, G_BUS_RELEASE_NAME_FLAGS_ERROR);
1671
1672   if (G_IS_KDBUS_CONNECTION (connection->stream))
1673     result = _g_kdbus_ReleaseName (connection, name, error);
1674   else
1675     result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/org/freedesktop/DBus",
1676                                           "org.freedesktop.DBus", "ReleaseName",
1677                                           g_variant_new ("(s)", name), G_VARIANT_TYPE ("(u)"),
1678                                           G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1679
1680   if (result != NULL)
1681     {
1682       g_variant_get (result, "(u)", &release_name_reply);
1683       g_variant_unref (result);
1684     }
1685   else
1686     release_name_reply = G_BUS_RELEASE_NAME_FLAGS_ERROR;
1687
1688   return (GBusReleaseNameReplyFlags) release_name_reply;
1689 }
1690
1691 /**
1692  * g_dbus_get_bus_id:
1693  * @connection: a #GDBusConnection
1694  * @error: return location for error or %NULL
1695  *
1696  * Synchronously returns the unique ID of the bus.
1697  *
1698  * The calling thread is blocked until a reply is received.
1699  *
1700  * Returns: the unique ID of the bus or %NULL if @error is set.
1701  *     Free with g_free().
1702  *
1703  * Since: 2.4x
1704  */
1705 gchar *
1706 g_dbus_get_bus_id (GDBusConnection  *connection,
1707                    GError          **error)
1708 {
1709   GVariant *result;
1710   gchar *bus_id;
1711
1712   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1713   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1714
1715   result = NULL;
1716   bus_id = NULL;
1717
1718   if (G_IS_KDBUS_CONNECTION (connection->stream))
1719     {
1720       result = _g_kdbus_GetBusId (connection, error);
1721     }
1722   else
1723     {
1724       result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1725                                             "org.freedesktop.DBus", "GetId",
1726                                             NULL, G_VARIANT_TYPE ("(s)"),
1727                                             G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1728     }
1729
1730   if (result != NULL)
1731     {
1732       g_variant_get (result, "(s)", &bus_id);
1733       g_variant_unref (result);
1734     }
1735
1736   return bus_id;
1737 }
1738
1739 typedef enum
1740 {
1741   LIST_NAMES,
1742   LIST_ACTIVATABLE_NAMES,
1743   LIST_QUEUED_OWNERS
1744 } GDBusListNameType;
1745
1746 static gchar **
1747 _g_dbus_get_list_internal (GDBusConnection    *connection,
1748                            const gchar        *name,
1749                            GDBusListNameType   list_name_type,
1750                            GError            **error)
1751 {
1752   gchar **strv;
1753   GVariant *result;
1754   GVariantIter *iter;
1755   gchar *str;
1756   gsize n, i;
1757
1758   result = NULL;
1759   strv = NULL;
1760
1761   if (list_name_type == LIST_QUEUED_OWNERS)
1762     {
1763       if (G_IS_KDBUS_CONNECTION (connection->stream))
1764         result = _g_kdbus_GetListQueuedOwners (connection, name, error);
1765       else
1766         result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1767                                               "org.freedesktop.DBus", "ListQueuedOwners",
1768                                               g_variant_new ("(s)", name), G_VARIANT_TYPE ("(as)"),
1769                                               G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1770     }
1771   else
1772     {
1773       gchar *method_name;
1774
1775       if (list_name_type == LIST_NAMES)
1776         method_name = "ListNames";
1777       else
1778         method_name = "ListActivatableNames";
1779
1780       if (G_IS_KDBUS_CONNECTION (connection->stream))
1781         result = _g_kdbus_GetListNames (connection, list_name_type, error);
1782       else
1783         result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1784                                               "org.freedesktop.DBus", method_name,
1785                                               NULL, G_VARIANT_TYPE ("(as)"),
1786                                               G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1787     }
1788
1789   if (result != NULL)
1790     {
1791       g_variant_get (result, "(as)", &iter);
1792       n = g_variant_iter_n_children (iter);
1793       strv = g_new (gchar *, n + 1);
1794
1795       i = 0;
1796       while (g_variant_iter_loop (iter, "s", &str))
1797         {
1798           strv[i] = g_strdup (str);
1799           i++;
1800         }
1801       strv[i] = NULL;
1802
1803       g_variant_iter_free (iter);
1804       g_variant_unref (result);
1805     }
1806
1807   return strv;
1808 }
1809
1810 /**
1811  * g_dbus_get_list_names:
1812  * @connection: a #GDBusConnection
1813  * @error: return location for error or %NULL
1814  *
1815  * Synchronously returns a list of all currently-owned names on the bus.
1816  *
1817  * The calling thread is blocked until a reply is received.
1818  *
1819  * Returns: a list of all currently-owned names on the bus or %NULL if
1820  *     @error is set. Free with g_strfreev().
1821  *
1822  * Since: 2.4x
1823  */
1824 gchar **
1825 g_dbus_get_list_names (GDBusConnection  *connection,
1826                        GError          **error)
1827 {
1828   gchar **strv;
1829
1830   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1831   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1832
1833   strv = _g_dbus_get_list_internal (connection, NULL, LIST_NAMES, error);
1834
1835   return strv;
1836 }
1837
1838 /**
1839  * g_dbus_get_list_activatable_names:
1840  * @connection: a #GDBusConnection
1841  * @error: return location for error or %NULL
1842  *
1843  * Synchronously returns a list of all names that can be activated on the bus.
1844  *
1845  * The calling thread is blocked until a reply is received.
1846  *
1847  * Returns: a list of all names that can be activated on the bus or %NULL if
1848  *     @error is set. Free with g_strfreev().
1849  *
1850  * Since: 2.4x
1851  */
1852 gchar **
1853 g_dbus_get_list_activatable_names (GDBusConnection  *connection,
1854                                    GError          **error)
1855 {
1856   gchar **strv;
1857
1858   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1859   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1860
1861   strv = _g_dbus_get_list_internal (connection, NULL, LIST_ACTIVATABLE_NAMES, error);
1862
1863   return strv;
1864 }
1865
1866 /**
1867  * g_dbus_get_list_queued_names:
1868  * @connection: a #GDBusConnection
1869  * @name: a unique or well-known bus name
1870  * @error: return location for error or %NULL
1871  *
1872  * Synchronously returns the unique bus names of connections currently queued
1873  * for the @name.
1874  *
1875  * If @name contains a value not compatible with the D-Bus syntax and naming
1876  * conventions for bus names, the operation returns %NULL and @error is set.
1877  *
1878  * The calling thread is blocked until a reply is received.
1879  *
1880  * Returns: the unique bus names of connections currently queued for the @name
1881  *     or %NULL if @error is set. Free with g_strfreev().
1882  *
1883  * Since: 2.4x
1884  */
1885 gchar **
1886 g_dbus_get_list_queued_owners (GDBusConnection  *connection,
1887                                const gchar      *name,
1888                                GError          **error)
1889 {
1890   gchar **strv;
1891
1892   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1893   g_return_val_if_fail (name == NULL || g_dbus_is_name (name), NULL);
1894   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1895
1896   strv = _g_dbus_get_list_internal (connection, name, LIST_QUEUED_OWNERS, error);
1897
1898   return strv;
1899 }
1900
1901 /**
1902  * g_dbus_get_name_owner:
1903  * @connection: a #GDBusConnection
1904  * @name: well-known bus name to get the owner of
1905  * @error: return location for error or %NULL
1906  *
1907  * Synchronously returns the unique connection name of the primary owner of
1908  * the name given. If the requested name doesn't have an owner, an @error is
1909  * returned.
1910  *
1911  * If @name contains a value not compatible with the D-Bus syntax and naming
1912  * conventions for bus names, the operation returns %NULL and @error is set.
1913  *
1914  * The calling thread is blocked until a reply is received.
1915  *
1916  * Returns: the unique connection name of the primary owner of the
1917  *     name given. If the requested name doesn't have an owner, function
1918  *     returns %NULL and @error is set. Free with g_free().
1919  *
1920  * Since: 2.4x
1921  */
1922 gchar *
1923 g_dbus_get_name_owner (GDBusConnection  *connection,
1924                        const gchar      *name,
1925                        GError          **error)
1926 {
1927   GVariant *result;
1928   gchar *name_owner;
1929
1930   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1931   g_return_val_if_fail (name == NULL || g_dbus_is_name (name), NULL);
1932   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1933
1934   name_owner = NULL;
1935   result = NULL;
1936
1937   if (G_IS_KDBUS_CONNECTION (connection->stream))
1938     result = _g_kdbus_GetNameOwner (connection, name, error);
1939   else
1940     result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1941                                           "org.freedesktop.DBus", "GetNameOwner",
1942                                           g_variant_new ("(s)", name), G_VARIANT_TYPE ("(s)"),
1943                                           G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1944   if (result != NULL)
1945     {
1946       g_variant_get (result, "(s)", &name_owner);
1947       g_variant_unref (result);
1948     }
1949   else
1950     name_owner = NULL;
1951
1952   return name_owner;
1953 }
1954
1955 /**
1956  * g_dbus_name_has_owner:
1957  * @connection: a #GDBusConnection
1958  * @name: a unique or well-known bus name
1959  * @error: return location for error or %NULL
1960  *
1961  * Synchronously checks if the specified name exists (currently has an owner).
1962  *
1963  * If @name contains a value not compatible with the D-Bus syntax and naming
1964  * conventions for bus names, the operation returns %NULL and @error is set.
1965  *
1966  * The calling thread is blocked until a reply is received.
1967  *
1968  * Returns: %TRUE if specified name exists (currently has an owner)
1969  *     If the requested name doesn't have an owner or @error is set,
1970  *     function returns %FALSE.
1971  *
1972  * Since: 2.4x
1973  */
1974 gboolean
1975 g_dbus_name_has_owner (GDBusConnection  *connection,
1976                        const gchar      *name,
1977                        GError          **error)
1978 {
1979   GVariant *result;
1980   gboolean ret;
1981
1982   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1983   g_return_val_if_fail (name == NULL || g_dbus_is_name (name), NULL);
1984   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1985
1986   result = NULL;
1987
1988   if (G_IS_KDBUS_CONNECTION (connection->stream))
1989     result = _g_kdbus_NameHasOwner (connection, name, error);
1990   else
1991     result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1992                                           "org.freedesktop.DBus", "NameHasOwner",
1993                                           g_variant_new ("(s)", name), G_VARIANT_TYPE ("(b)"),
1994                                           G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1995   if (result != NULL)
1996     {
1997       g_variant_get (result, "(b)", &ret);
1998       g_variant_unref (result);
1999     }
2000   else
2001     ret = FALSE;
2002
2003   return ret;
2004 }
2005
2006 /**
2007  * g_dbus_get_connection_pid:
2008  * @connection: a #GDBusConnection
2009  * @name: a unique or well-known bus name of the connection to query
2010  * @error: return location for error or %NULL
2011  *
2012  * Synchronously returns the Unix process ID of the process connected to the
2013  * bus. If unable to determine it, an @error is returned.
2014  *
2015  * If @name contains a value not compatible with the D-Bus syntax and naming
2016  * conventions for bus names, the operation returns (guint32) -1 and @error
2017  * is set.
2018  *
2019  * The calling thread is blocked until a reply is received.
2020  *
2021  * Returns: the Unix process ID of the process connected to the bus or
2022  *     (guint32) -1 if @error is set.
2023  *
2024  * Since: 2.4x
2025  */
2026 guint32
2027 g_dbus_get_connection_pid (GDBusConnection  *connection,
2028                            const gchar      *name,
2029                            GError          **error)
2030 {
2031   GVariant *result;
2032   guint32 pid;
2033
2034   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), -1);
2035   g_return_val_if_fail (name == NULL || g_dbus_is_name (name), -1);
2036   g_return_val_if_fail (error == NULL || *error == NULL, -1);
2037
2038   result = NULL;
2039   pid = -1;
2040
2041   if (G_IS_KDBUS_CONNECTION (connection->stream))
2042     result = _g_kdbus_GetConnectionUnixProcessID (connection, name, error);
2043   else
2044     result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
2045                                           "org.freedesktop.DBus", "GetConnectionUnixProcessID",
2046                                           g_variant_new ("(s)", name), G_VARIANT_TYPE ("(u)"),
2047                                           G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
2048   if (result != NULL)
2049     {
2050       g_variant_get (result, "(u)", &pid);
2051       g_variant_unref (result);
2052     }
2053
2054   return pid;
2055 }
2056
2057 /**
2058  * g_dbus_get_connection_uid:
2059  * @connection: a #GDBusConnection
2060  * @name: a unique or well-known bus name of the connection to query
2061  * @error: return location for error or %NULL
2062  *
2063  * Synchronously returns the Unix user ID of the process connected to the
2064  * bus. If unable to determine it, an @error is returned.
2065  *
2066  * If @name contains a value not compatible with the D-Bus syntax and naming
2067  * conventions for bus names, the operation returns (guint32) -1 and @error
2068  * is set.
2069  *
2070  * The calling thread is blocked until a reply is received.
2071  *
2072  * Returns: the Unix user ID of the process connected to the bus or
2073  *     (guint32) -1 if @error is set.
2074  *
2075  * Since: 2.4x
2076  */
2077 guint32
2078 g_dbus_get_connection_uid (GDBusConnection  *connection,
2079                            const gchar      *name,
2080                            GError          **error)
2081 {
2082   GVariant *result;
2083   guint32 uid;
2084
2085   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), -1);
2086   g_return_val_if_fail (name == NULL || g_dbus_is_name (name), -1);
2087   g_return_val_if_fail (error == NULL || *error == NULL, -1);
2088
2089   result = NULL;
2090   uid = -1;
2091
2092   if (G_IS_KDBUS_CONNECTION (connection->stream))
2093     result = _g_kdbus_GetConnectionUnixUser (connection, name, error);
2094   else
2095     result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
2096                                           "org.freedesktop.DBus", "GetConnectionUnixUser",
2097                                           g_variant_new ("(s)", name), G_VARIANT_TYPE ("(u)"),
2098                                           G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
2099   if (result != NULL)
2100     {
2101       g_variant_get (result, "(u)", &uid);
2102       g_variant_unref (result);
2103     }
2104
2105   return uid;
2106 }
2107
2108 /* ---------------------------------------------------------------------------------------------------- */
2109
2110 /**
2111  * g_dbus_connection_get_last_serial:
2112  * @connection: a #GDBusConnection
2113  *
2114  * Retrieves the last serial number assigned to a #GDBusMessage on
2115  * the current thread. This includes messages sent via both low-level
2116  * API such as g_dbus_connection_send_message() as well as
2117  * high-level API such as g_dbus_connection_emit_signal(),
2118  * g_dbus_connection_call() or g_dbus_proxy_call().
2119  *
2120  * Returns: the last used serial or zero when no message has been sent
2121  *     within the current thread
2122  *
2123  * Since: 2.34
2124  */
2125 guint32
2126 g_dbus_connection_get_last_serial (GDBusConnection *connection)
2127 {
2128   guint32 ret;
2129
2130   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2131
2132   CONNECTION_LOCK (connection);
2133   ret = GPOINTER_TO_UINT (g_hash_table_lookup (connection->map_thread_to_last_serial,
2134                                                g_thread_self ()));
2135   CONNECTION_UNLOCK (connection);
2136
2137   return ret;
2138 }
2139
2140 /* ---------------------------------------------------------------------------------------------------- */
2141
2142 /* Can be called by any thread, with the connection lock held */
2143 static gboolean
2144 g_dbus_connection_send_message_unlocked (GDBusConnection   *connection,
2145                                          GDBusMessage      *message,
2146                                          GDBusSendMessageFlags flags,
2147                                          volatile guint32  *out_serial,
2148                                          GError           **error)
2149 {
2150   guchar *blob;
2151   gsize blob_size;
2152   guint32 serial_to_use;
2153   gboolean ret;
2154
2155   CONNECTION_ENSURE_LOCK (connection);
2156
2157   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2158   g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
2159
2160   /* TODO: check all necessary headers are present */
2161
2162   ret = FALSE;
2163   blob = NULL;
2164
2165   if (out_serial != NULL)
2166     *out_serial = 0;
2167
2168   /* If we're in initable_init(), don't check for being initialized, to avoid
2169    * chicken-and-egg problems. initable_init() is responsible for setting up
2170    * our prerequisites (mainly connection->worker), and only calling us
2171    * from its own thread (so no memory barrier is needed).
2172    */
2173   if (!check_unclosed (connection,
2174                        (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
2175                        error))
2176     goto out;
2177
2178   blob = g_dbus_message_to_blob (message,
2179                                  &blob_size,
2180                                  connection->capabilities,
2181                                  error);
2182   if (blob == NULL)
2183     goto out;
2184
2185   if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
2186     serial_to_use = g_dbus_message_get_serial (message);
2187   else
2188     serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
2189
2190   switch (blob[0])
2191     {
2192     case 'l':
2193       ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
2194       break;
2195     case 'B':
2196       ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
2197       break;
2198     default:
2199       g_assert_not_reached ();
2200       break;
2201     }
2202
2203 #if 0
2204   g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
2205               blob_size, serial_to_use, connection);
2206   g_printerr ("----\n");
2207   hexdump (blob, blob_size);
2208   g_printerr ("----\n");
2209 #endif
2210
2211   /* TODO: use connection->auth to encode the blob */
2212
2213   if (out_serial != NULL)
2214     *out_serial = serial_to_use;
2215
2216   /* store used serial for the current thread */
2217   /* TODO: watch the thread disposal and remove associated record
2218    *       from hashtable
2219    *  - see https://bugzilla.gnome.org/show_bug.cgi?id=676825#c7
2220    */
2221   g_hash_table_replace (connection->map_thread_to_last_serial,
2222                         g_thread_self (),
2223                         GUINT_TO_POINTER (serial_to_use));
2224
2225   if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
2226     g_dbus_message_set_serial (message, serial_to_use);
2227
2228   g_dbus_message_lock (message);
2229   _g_dbus_worker_send_message (connection->worker,
2230                                message,
2231                                (gchar*) blob,
2232                                blob_size);
2233   blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
2234
2235   ret = TRUE;
2236
2237  out:
2238   g_free (blob);
2239
2240   return ret;
2241 }
2242
2243 /**
2244  * g_dbus_connection_send_message:
2245  * @connection: a #GDBusConnection
2246  * @message: a #GDBusMessage
2247  * @flags: flags affecting how the message is sent
2248  * @out_serial: (out) (allow-none): return location for serial number assigned
2249  *     to @message when sending it or %NULL
2250  * @error: Return location for error or %NULL
2251  *
2252  * Asynchronously sends @message to the peer represented by @connection.
2253  *
2254  * Unless @flags contain the
2255  * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2256  * will be assigned by @connection and set on @message via
2257  * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2258  * serial number used will be written to this location prior to
2259  * submitting the message to the underlying transport.
2260  *
2261  * If @connection is closed then the operation will fail with
2262  * %G_IO_ERROR_CLOSED. If @message is not well-formed,
2263  * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2264  *
2265  * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2266  * for an example of how to use this low-level API to send and receive
2267  * UNIX file descriptors.
2268  *
2269  * Note that @message must be unlocked, unless @flags contain the
2270  * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2271  *
2272  * Returns: %TRUE if the message was well-formed and queued for
2273  *     transmission, %FALSE if @error is set
2274  *
2275  * Since: 2.26
2276  */
2277 gboolean
2278 g_dbus_connection_send_message (GDBusConnection        *connection,
2279                                 GDBusMessage           *message,
2280                                 GDBusSendMessageFlags   flags,
2281                                 volatile guint32       *out_serial,
2282                                 GError                **error)
2283 {
2284   gboolean ret;
2285
2286   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2287   g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
2288   g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
2289   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2290
2291   CONNECTION_LOCK (connection);
2292   ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
2293   CONNECTION_UNLOCK (connection);
2294   return ret;
2295 }
2296
2297 /* ---------------------------------------------------------------------------------------------------- */
2298
2299 typedef struct
2300 {
2301   volatile gint ref_count;
2302   GDBusConnection *connection;
2303   guint32 serial;
2304   GSimpleAsyncResult *simple;
2305
2306   GMainContext *main_context;
2307
2308   GCancellable *cancellable;
2309
2310   gulong cancellable_handler_id;
2311
2312   GSource *timeout_source;
2313
2314   gboolean delivered;
2315 } SendMessageData;
2316
2317 /* Can be called from any thread with or without lock held */
2318 static SendMessageData *
2319 send_message_data_ref (SendMessageData *data)
2320 {
2321   g_atomic_int_inc (&data->ref_count);
2322   return data;
2323 }
2324
2325 /* Can be called from any thread with or without lock held */
2326 static void
2327 send_message_data_unref (SendMessageData *data)
2328 {
2329   if (g_atomic_int_dec_and_test (&data->ref_count))
2330     {
2331       g_assert (data->timeout_source == NULL);
2332       g_assert (data->simple == NULL);
2333       g_assert (data->cancellable_handler_id == 0);
2334       g_object_unref (data->connection);
2335       if (data->cancellable != NULL)
2336         g_object_unref (data->cancellable);
2337       g_main_context_unref (data->main_context);
2338       g_free (data);
2339     }
2340 }
2341
2342 /* ---------------------------------------------------------------------------------------------------- */
2343
2344 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
2345 static void
2346 send_message_with_reply_deliver (SendMessageData *data, gboolean remove)
2347 {
2348   CONNECTION_ENSURE_LOCK (data->connection);
2349
2350   g_assert (!data->delivered);
2351
2352   data->delivered = TRUE;
2353
2354   g_simple_async_result_complete_in_idle (data->simple);
2355   g_object_unref (data->simple);
2356   data->simple = NULL;
2357
2358   if (data->timeout_source != NULL)
2359     {
2360       g_source_destroy (data->timeout_source);
2361       data->timeout_source = NULL;
2362     }
2363   if (data->cancellable_handler_id > 0)
2364     {
2365       g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
2366       data->cancellable_handler_id = 0;
2367     }
2368
2369   if (remove)
2370     {
2371       g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
2372                                            GUINT_TO_POINTER (data->serial)));
2373     }
2374
2375   send_message_data_unref (data);
2376 }
2377
2378 /* ---------------------------------------------------------------------------------------------------- */
2379
2380 /* Can be called from any thread with lock held */
2381 static void
2382 send_message_data_deliver_reply_unlocked (SendMessageData *data,
2383                                           GDBusMessage    *reply)
2384 {
2385   if (data->delivered)
2386     goto out;
2387
2388   g_simple_async_result_set_op_res_gpointer (data->simple,
2389                                              g_object_ref (reply),
2390                                              g_object_unref);
2391
2392   send_message_with_reply_deliver (data, TRUE);
2393
2394  out:
2395   ;
2396 }
2397
2398 /* ---------------------------------------------------------------------------------------------------- */
2399
2400 /* Called from a user thread, lock is not held */
2401 static gboolean
2402 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
2403 {
2404   SendMessageData *data = user_data;
2405
2406   CONNECTION_LOCK (data->connection);
2407   if (data->delivered)
2408     goto out;
2409
2410   g_simple_async_result_set_error (data->simple,
2411                                    G_IO_ERROR,
2412                                    G_IO_ERROR_CANCELLED,
2413                                    _("Operation was cancelled"));
2414
2415   send_message_with_reply_deliver (data, TRUE);
2416
2417  out:
2418   CONNECTION_UNLOCK (data->connection);
2419   return FALSE;
2420 }
2421
2422 /* Can be called from any thread with or without lock held */
2423 static void
2424 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
2425                                       gpointer      user_data)
2426 {
2427   SendMessageData *data = user_data;
2428   GSource *idle_source;
2429
2430   /* postpone cancellation to idle handler since we may be called directly
2431    * via g_cancellable_connect() (e.g. holding lock)
2432    */
2433   idle_source = g_idle_source_new ();
2434   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
2435   g_source_set_callback (idle_source,
2436                          send_message_with_reply_cancelled_idle_cb,
2437                          send_message_data_ref (data),
2438                          (GDestroyNotify) send_message_data_unref);
2439   g_source_set_name (idle_source, "[gio] send_message_with_reply_cancelled_idle_cb");
2440   g_source_attach (idle_source, data->main_context);
2441   g_source_unref (idle_source);
2442 }
2443
2444 /* ---------------------------------------------------------------------------------------------------- */
2445
2446 /* Called from a user thread, lock is not held */
2447 static gboolean
2448 send_message_with_reply_timeout_cb (gpointer user_data)
2449 {
2450   SendMessageData *data = user_data;
2451
2452   CONNECTION_LOCK (data->connection);
2453   if (data->delivered)
2454     goto out;
2455
2456   g_simple_async_result_set_error (data->simple,
2457                                    G_IO_ERROR,
2458                                    G_IO_ERROR_TIMED_OUT,
2459                                    _("Timeout was reached"));
2460
2461   send_message_with_reply_deliver (data, TRUE);
2462
2463  out:
2464   CONNECTION_UNLOCK (data->connection);
2465
2466   return FALSE;
2467 }
2468
2469 /* ---------------------------------------------------------------------------------------------------- */
2470
2471 /* Called from a user thread, connection's lock is held */
2472 static void
2473 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection     *connection,
2474                                                     GDBusMessage        *message,
2475                                                     GDBusSendMessageFlags flags,
2476                                                     gint                 timeout_msec,
2477                                                     volatile guint32    *out_serial,
2478                                                     GCancellable        *cancellable,
2479                                                     GAsyncReadyCallback  callback,
2480                                                     gpointer             user_data)
2481 {
2482   GSimpleAsyncResult *simple;
2483   SendMessageData *data;
2484   GError *error;
2485   volatile guint32 serial;
2486
2487   data = NULL;
2488
2489   if (out_serial == NULL)
2490     out_serial = &serial;
2491
2492   if (timeout_msec == -1)
2493     timeout_msec = 25 * 1000;
2494
2495   simple = g_simple_async_result_new (G_OBJECT (connection),
2496                                       callback,
2497                                       user_data,
2498                                       g_dbus_connection_send_message_with_reply);
2499   g_simple_async_result_set_check_cancellable (simple, cancellable);
2500
2501   if (g_cancellable_is_cancelled (cancellable))
2502     {
2503       g_simple_async_result_set_error (simple,
2504                                        G_IO_ERROR,
2505                                        G_IO_ERROR_CANCELLED,
2506                                        _("Operation was cancelled"));
2507       g_simple_async_result_complete_in_idle (simple);
2508       g_object_unref (simple);
2509       goto out;
2510     }
2511
2512   error = NULL;
2513   if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
2514     {
2515       g_simple_async_result_take_error (simple, error);
2516       g_simple_async_result_complete_in_idle (simple);
2517       g_object_unref (simple);
2518       goto out;
2519     }
2520
2521   data = g_new0 (SendMessageData, 1);
2522   data->ref_count = 1;
2523   data->connection = g_object_ref (connection);
2524   data->simple = simple;
2525   data->serial = *out_serial;
2526   data->main_context = g_main_context_ref_thread_default ();
2527
2528   if (cancellable != NULL)
2529     {
2530       data->cancellable = g_object_ref (cancellable);
2531       data->cancellable_handler_id = g_cancellable_connect (cancellable,
2532                                                             G_CALLBACK (send_message_with_reply_cancelled_cb),
2533                                                             send_message_data_ref (data),
2534                                                             (GDestroyNotify) send_message_data_unref);
2535     }
2536
2537   if (timeout_msec != G_MAXINT)
2538     {
2539       data->timeout_source = g_timeout_source_new (timeout_msec);
2540       g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
2541       g_source_set_callback (data->timeout_source,
2542                              send_message_with_reply_timeout_cb,
2543                              send_message_data_ref (data),
2544                              (GDestroyNotify) send_message_data_unref);
2545       g_source_attach (data->timeout_source, data->main_context);
2546       g_source_unref (data->timeout_source);
2547     }
2548
2549   g_hash_table_insert (connection->map_method_serial_to_send_message_data,
2550                        GUINT_TO_POINTER (*out_serial),
2551                        data);
2552
2553  out:
2554   ;
2555 }
2556
2557 /**
2558  * g_dbus_connection_send_message_with_reply:
2559  * @connection: a #GDBusConnection
2560  * @message: a #GDBusMessage
2561  * @flags: flags affecting how the message is sent
2562  * @timeout_msec: the timeout in milliseconds, -1 to use the default
2563  *     timeout or %G_MAXINT for no timeout
2564  * @out_serial: (out) (allow-none): return location for serial number assigned
2565  *     to @message when sending it or %NULL
2566  * @cancellable: (allow-none): a #GCancellable or %NULL
2567  * @callback: (allow-none): a #GAsyncReadyCallback to call when the request
2568  *     is satisfied or %NULL if you don't care about the result
2569  * @user_data: The data to pass to @callback
2570  *
2571  * Asynchronously sends @message to the peer represented by @connection.
2572  *
2573  * Unless @flags contain the
2574  * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2575  * will be assigned by @connection and set on @message via
2576  * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2577  * serial number used will be written to this location prior to
2578  * submitting the message to the underlying transport.
2579  *
2580  * If @connection is closed then the operation will fail with
2581  * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2582  * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2583  * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2584  *
2585  * This is an asynchronous method. When the operation is finished, @callback
2586  * will be invoked in the 
2587  * [thread-default main context][g-main-context-push-thread-default]
2588  * of the thread you are calling this method from. You can then call
2589  * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
2590  * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
2591  *
2592  * Note that @message must be unlocked, unless @flags contain the
2593  * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2594  *
2595  * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2596  * for an example of how to use this low-level API to send and receive
2597  * UNIX file descriptors.
2598  *
2599  * Since: 2.26
2600  */
2601 void
2602 g_dbus_connection_send_message_with_reply (GDBusConnection       *connection,
2603                                            GDBusMessage          *message,
2604                                            GDBusSendMessageFlags  flags,
2605                                            gint                   timeout_msec,
2606                                            volatile guint32      *out_serial,
2607                                            GCancellable          *cancellable,
2608                                            GAsyncReadyCallback    callback,
2609                                            gpointer               user_data)
2610 {
2611   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2612   g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2613   g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2614   g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2615
2616   CONNECTION_LOCK (connection);
2617   g_dbus_connection_send_message_with_reply_unlocked (connection,
2618                                                       message,
2619                                                       flags,
2620                                                       timeout_msec,
2621                                                       out_serial,
2622                                                       cancellable,
2623                                                       callback,
2624                                                       user_data);
2625   CONNECTION_UNLOCK (connection);
2626 }
2627
2628 /**
2629  * g_dbus_connection_send_message_with_reply_finish:
2630  * @connection: a #GDBusConnection
2631  * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
2632  *     g_dbus_connection_send_message_with_reply()
2633  * @error: teturn location for error or %NULL
2634  *
2635  * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2636  *
2637  * Note that @error is only set if a local in-process error
2638  * occurred. That is to say that the returned #GDBusMessage object may
2639  * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2640  * g_dbus_message_to_gerror() to transcode this to a #GError.
2641  *
2642  * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2643  * for an example of how to use this low-level API to send and receive
2644  * UNIX file descriptors.
2645  *
2646  * Returns: (transfer full): a locked #GDBusMessage or %NULL if @error is set
2647  *
2648  * Since: 2.26
2649  */
2650 GDBusMessage *
2651 g_dbus_connection_send_message_with_reply_finish (GDBusConnection  *connection,
2652                                                   GAsyncResult     *res,
2653                                                   GError          **error)
2654 {
2655   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2656   GDBusMessage *reply;
2657
2658   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2659   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2660
2661   reply = NULL;
2662
2663   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
2664
2665   if (g_simple_async_result_propagate_error (simple, error))
2666     goto out;
2667
2668   reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
2669
2670  out:
2671   return reply;
2672 }
2673
2674 /* ---------------------------------------------------------------------------------------------------- */
2675
2676 typedef struct
2677 {
2678   GAsyncResult *res;
2679   GMainContext *context;
2680   GMainLoop *loop;
2681 } SendMessageSyncData;
2682
2683 /* Called from a user thread, lock is not held */
2684 static void
2685 send_message_with_reply_sync_cb (GDBusConnection *connection,
2686                                  GAsyncResult    *res,
2687                                  gpointer         user_data)
2688 {
2689   SendMessageSyncData *data = user_data;
2690   data->res = g_object_ref (res);
2691   g_main_loop_quit (data->loop);
2692 }
2693
2694 /**
2695  * g_dbus_connection_send_message_with_reply_sync:
2696  * @connection: a #GDBusConnection
2697  * @message: a #GDBusMessage
2698  * @flags: flags affecting how the message is sent.
2699  * @timeout_msec: the timeout in milliseconds, -1 to use the default
2700  *     timeout or %G_MAXINT for no timeout
2701  * @out_serial: (out) (allow-none): return location for serial number
2702  *     assigned to @message when sending it or %NULL
2703  * @cancellable: (allow-none): a #GCancellable or %NULL
2704  * @error: return location for error or %NULL
2705  *
2706  * Synchronously sends @message to the peer represented by @connection
2707  * and blocks the calling thread until a reply is received or the
2708  * timeout is reached. See g_dbus_connection_send_message_with_reply()
2709  * for the asynchronous version of this method.
2710  *
2711  * Unless @flags contain the
2712  * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2713  * will be assigned by @connection and set on @message via
2714  * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2715  * serial number used will be written to this location prior to
2716  * submitting the message to the underlying transport.
2717  *
2718  * If @connection is closed then the operation will fail with
2719  * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2720  * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2721  * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2722  *
2723  * Note that @error is only set if a local in-process error
2724  * occurred. That is to say that the returned #GDBusMessage object may
2725  * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2726  * g_dbus_message_to_gerror() to transcode this to a #GError.
2727  *
2728  * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2729  * for an example of how to use this low-level API to send and receive
2730  * UNIX file descriptors.
2731  *
2732  * Note that @message must be unlocked, unless @flags contain the
2733  * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2734  *
2735  * Returns: (transfer full): a locked #GDBusMessage that is the reply
2736  *     to @message or %NULL if @error is set
2737  *
2738  * Since: 2.26
2739  */
2740 GDBusMessage *
2741 g_dbus_connection_send_message_with_reply_sync (GDBusConnection        *connection,
2742                                                 GDBusMessage           *message,
2743                                                 GDBusSendMessageFlags   flags,
2744                                                 gint                    timeout_msec,
2745                                                 volatile guint32       *out_serial,
2746                                                 GCancellable           *cancellable,
2747                                                 GError                **error)
2748 {
2749   SendMessageSyncData *data;
2750   GDBusMessage *reply;
2751
2752   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2753   g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2754   g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2755   g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2756   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2757
2758   data = g_new0 (SendMessageSyncData, 1);
2759   data->context = g_main_context_new ();
2760   data->loop = g_main_loop_new (data->context, FALSE);
2761
2762   g_main_context_push_thread_default (data->context);
2763
2764   g_dbus_connection_send_message_with_reply (connection,
2765                                              message,
2766                                              flags,
2767                                              timeout_msec,
2768                                              out_serial,
2769                                              cancellable,
2770                                              (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2771                                              data);
2772   g_main_loop_run (data->loop);
2773   reply = g_dbus_connection_send_message_with_reply_finish (connection,
2774                                                             data->res,
2775                                                             error);
2776
2777   g_main_context_pop_thread_default (data->context);
2778
2779   g_main_context_unref (data->context);
2780   g_main_loop_unref (data->loop);
2781   g_object_unref (data->res);
2782   g_free (data);
2783
2784   return reply;
2785 }
2786
2787 /* ---------------------------------------------------------------------------------------------------- */
2788
2789 typedef struct
2790 {
2791   GDBusMessageFilterFunction func;
2792   gpointer user_data;
2793 } FilterCallback;
2794
2795 typedef struct
2796 {
2797   guint                       id;
2798   GDBusMessageFilterFunction  filter_function;
2799   gpointer                    user_data;
2800   GDestroyNotify              user_data_free_func;
2801 } FilterData;
2802
2803 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2804 static void
2805 on_worker_message_received (GDBusWorker  *worker,
2806                             GDBusMessage *message,
2807                             gpointer      user_data)
2808 {
2809   GDBusConnection *connection;
2810   FilterCallback *filters;
2811   guint num_filters;
2812   guint n;
2813   gboolean alive;
2814
2815   G_LOCK (message_bus_lock);
2816   alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2817   if (!alive)
2818     {
2819       G_UNLOCK (message_bus_lock);
2820       return;
2821     }
2822   connection = G_DBUS_CONNECTION (user_data);
2823   g_object_ref (connection);
2824   G_UNLOCK (message_bus_lock);
2825
2826   //g_debug ("in on_worker_message_received");
2827
2828   g_object_ref (message);
2829   g_dbus_message_lock (message);
2830
2831   //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2832
2833   /* First collect the set of callback functions */
2834   CONNECTION_LOCK (connection);
2835   num_filters = connection->filters->len;
2836   filters = g_new0 (FilterCallback, num_filters);
2837   for (n = 0; n < num_filters; n++)
2838     {
2839       FilterData *data = connection->filters->pdata[n];
2840       filters[n].func = data->filter_function;
2841       filters[n].user_data = data->user_data;
2842     }
2843   CONNECTION_UNLOCK (connection);
2844
2845   /* then call the filters in order (without holding the lock) */
2846   for (n = 0; n < num_filters; n++)
2847     {
2848       message = filters[n].func (connection,
2849                                  message,
2850                                  TRUE,
2851                                  filters[n].user_data);
2852       if (message == NULL)
2853         break;
2854       g_dbus_message_lock (message);
2855     }
2856
2857   /* Standard dispatch unless the filter ate the message - no need to
2858    * do anything if the message was altered
2859    */
2860   if (message != NULL)
2861     {
2862       GDBusMessageType message_type;
2863
2864       message_type = g_dbus_message_get_message_type (message);
2865       if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2866         {
2867           guint32 reply_serial;
2868           SendMessageData *send_message_data;
2869
2870           reply_serial = g_dbus_message_get_reply_serial (message);
2871           CONNECTION_LOCK (connection);
2872           send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2873                                                    GUINT_TO_POINTER (reply_serial));
2874           if (send_message_data != NULL)
2875             {
2876               //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2877               send_message_data_deliver_reply_unlocked (send_message_data, message);
2878             }
2879           else
2880             {
2881               //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2882             }
2883           CONNECTION_UNLOCK (connection);
2884         }
2885       else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2886         {
2887           CONNECTION_LOCK (connection);
2888           distribute_signals (connection, message);
2889           CONNECTION_UNLOCK (connection);
2890         }
2891       else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2892         {
2893           CONNECTION_LOCK (connection);
2894           distribute_method_call (connection, message);
2895           CONNECTION_UNLOCK (connection);
2896         }
2897     }
2898
2899   if (message != NULL)
2900     g_object_unref (message);
2901   g_object_unref (connection);
2902   g_free (filters);
2903 }
2904
2905 /* Called in GDBusWorker's thread, lock is not held */
2906 static GDBusMessage *
2907 on_worker_message_about_to_be_sent (GDBusWorker  *worker,
2908                                     GDBusMessage *message,
2909                                     gpointer      user_data)
2910 {
2911   GDBusConnection *connection;
2912   FilterCallback *filters;
2913   guint num_filters;
2914   guint n;
2915   gboolean alive;
2916
2917   G_LOCK (message_bus_lock);
2918   alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2919   if (!alive)
2920     {
2921       G_UNLOCK (message_bus_lock);
2922       return message;
2923     }
2924   connection = G_DBUS_CONNECTION (user_data);
2925   g_object_ref (connection);
2926   G_UNLOCK (message_bus_lock);
2927
2928   //g_debug ("in on_worker_message_about_to_be_sent");
2929
2930   /* First collect the set of callback functions */
2931   CONNECTION_LOCK (connection);
2932   num_filters = connection->filters->len;
2933   filters = g_new0 (FilterCallback, num_filters);
2934   for (n = 0; n < num_filters; n++)
2935     {
2936       FilterData *data = connection->filters->pdata[n];
2937       filters[n].func = data->filter_function;
2938       filters[n].user_data = data->user_data;
2939     }
2940   CONNECTION_UNLOCK (connection);
2941
2942   /* then call the filters in order (without holding the lock) */
2943   for (n = 0; n < num_filters; n++)
2944     {
2945       g_dbus_message_lock (message);
2946       message = filters[n].func (connection,
2947                                  message,
2948                                  FALSE,
2949                                  filters[n].user_data);
2950       if (message == NULL)
2951         break;
2952     }
2953
2954   g_object_unref (connection);
2955   g_free (filters);
2956
2957   return message;
2958 }
2959
2960 /* called with connection lock held, in GDBusWorker thread */
2961 static gboolean
2962 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2963 {
2964   SendMessageData *data = value;
2965
2966   if (data->delivered)
2967     return FALSE;
2968
2969   g_simple_async_result_set_error (data->simple,
2970                                    G_IO_ERROR,
2971                                    G_IO_ERROR_CLOSED,
2972                                    _("The connection is closed"));
2973
2974   /* Ask send_message_with_reply_deliver not to remove the element from the
2975    * hash table - we're in the middle of a foreach; that would be unsafe.
2976    * Instead, return TRUE from this function so that it gets removed safely.
2977    */
2978   send_message_with_reply_deliver (data, FALSE);
2979   return TRUE;
2980 }
2981
2982 /* Called in GDBusWorker's thread - we must not block - without lock held */
2983 static void
2984 on_worker_closed (GDBusWorker *worker,
2985                   gboolean     remote_peer_vanished,
2986                   GError      *error,
2987                   gpointer     user_data)
2988 {
2989   GDBusConnection *connection;
2990   gboolean alive;
2991   guint old_atomic_flags;
2992
2993   G_LOCK (message_bus_lock);
2994   alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2995   if (!alive)
2996     {
2997       G_UNLOCK (message_bus_lock);
2998       return;
2999     }
3000   connection = G_DBUS_CONNECTION (user_data);
3001   g_object_ref (connection);
3002   G_UNLOCK (message_bus_lock);
3003
3004   //g_debug ("in on_worker_closed: %s", error->message);
3005
3006   CONNECTION_LOCK (connection);
3007   /* Even though this is atomic, we do it inside the lock to avoid breaking
3008    * assumptions in remove_match_rule(). We'd need the lock in a moment
3009    * anyway, so, no loss.
3010    */
3011   old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
3012
3013   if (!(old_atomic_flags & FLAG_CLOSED))
3014     {
3015       g_hash_table_foreach_remove (connection->map_method_serial_to_send_message_data, cancel_method_on_close, NULL);
3016       schedule_closed_unlocked (connection, remote_peer_vanished, error);
3017     }
3018   CONNECTION_UNLOCK (connection);
3019
3020   g_object_unref (connection);
3021 }
3022
3023 /* ---------------------------------------------------------------------------------------------------- */
3024
3025 /* Determines the biggest set of capabilities we can support on this
3026  * connection.
3027  *
3028  * Called with the init_lock held.
3029  */
3030 static GDBusCapabilityFlags
3031 get_offered_capabilities_max (GDBusConnection *connection)
3032 {
3033       GDBusCapabilityFlags ret;
3034       ret = G_DBUS_CAPABILITY_FLAGS_NONE;
3035 #ifdef G_OS_UNIX
3036       if (G_IS_UNIX_CONNECTION (connection->stream))
3037         ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
3038 #endif
3039       return ret;
3040 }
3041
3042 /* Called in a user thread, lock is not held */
3043 static gboolean
3044 initable_init (GInitable     *initable,
3045                GCancellable  *cancellable,
3046                GError       **error)
3047 {
3048   GDBusConnection *connection = G_DBUS_CONNECTION (initable);
3049   gboolean ret;
3050
3051   /* This method needs to be idempotent to work with the singleton
3052    * pattern. See the docs for g_initable_init(). We implement this by
3053    * locking.
3054    *
3055    * Unfortunately we can't use the main lock since the on_worker_*()
3056    * callbacks above needs the lock during initialization (for message
3057    * bus connections we do a synchronous Hello() call on the bus).
3058    */
3059   g_mutex_lock (&connection->init_lock);
3060
3061   ret = FALSE;
3062
3063   /* Make this a no-op if we're already initialized (successfully or
3064    * unsuccessfully)
3065    */
3066   if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
3067     {
3068       ret = (connection->initialization_error == NULL);
3069       goto out;
3070     }
3071
3072   /* Because of init_lock, we can't get here twice in different threads */
3073   g_assert (connection->initialization_error == NULL);
3074
3075   /* The user can pass multiple (but mutally exclusive) construct
3076    * properties:
3077    *
3078    *  - stream (of type GIOStream)
3079    *  - address (of type gchar*)
3080    *
3081    * At the end of the day we end up with a non-NULL GIOStream
3082    * object in connection->stream.
3083    */
3084   if (connection->address != NULL)
3085     {
3086       g_assert (connection->stream == NULL);
3087
3088       if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
3089           (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
3090         {
3091           g_set_error_literal (&connection->initialization_error,
3092                                G_IO_ERROR,
3093                                G_IO_ERROR_INVALID_ARGUMENT,
3094                                _("Unsupported flags encountered when constructing a client-side connection"));
3095           goto out;
3096         }
3097
3098       connection->stream = g_dbus_address_get_stream_sync (connection->address,
3099                                                            NULL, /* TODO: out_guid */
3100                                                            cancellable,
3101                                                            &connection->initialization_error);
3102       if (connection->stream == NULL)
3103         goto out;
3104     }
3105   else if (connection->stream != NULL)
3106     {
3107       /* nothing to do */
3108     }
3109   else
3110     {
3111       g_assert_not_reached ();
3112     }
3113
3114   /* [KDBUS] Skip authentication process for kdbus transport */
3115   if (G_IS_KDBUS_CONNECTION (connection->stream))
3116     {
3117       goto authenticated;
3118     }
3119
3120   /* Authenticate the connection */
3121   if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
3122     {
3123       g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
3124       g_assert (connection->guid != NULL);
3125       connection->auth = _g_dbus_auth_new (connection->stream);
3126       if (!_g_dbus_auth_run_server (connection->auth,
3127                                     connection->authentication_observer,
3128                                     connection->guid,
3129                                     (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
3130                                     get_offered_capabilities_max (connection),
3131                                     &connection->capabilities,
3132                                     &connection->credentials,
3133                                     cancellable,
3134                                     &connection->initialization_error))
3135         goto out;
3136     }
3137   else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
3138     {
3139       g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
3140       g_assert (connection->guid == NULL);
3141       connection->auth = _g_dbus_auth_new (connection->stream);
3142       connection->guid = _g_dbus_auth_run_client (connection->auth,
3143                                                   connection->authentication_observer,
3144                                                   get_offered_capabilities_max (connection),
3145                                                   &connection->capabilities,
3146                                                   cancellable,
3147                                                   &connection->initialization_error);
3148       if (connection->guid == NULL)
3149         goto out;
3150     }
3151
3152   if (connection->authentication_observer != NULL)
3153     {
3154       g_object_unref (connection->authentication_observer);
3155       connection->authentication_observer = NULL;
3156     }
3157
3158 authenticated:
3159
3160   //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
3161
3162   //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
3163
3164 #ifdef G_OS_UNIX
3165   /* We want all IO operations to be non-blocking since they happen in
3166    * the worker thread which is shared by _all_ connections.
3167    */
3168   if (G_IS_SOCKET_CONNECTION (connection->stream))
3169     {
3170       g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
3171     }
3172 #endif
3173
3174   G_LOCK (message_bus_lock);
3175   if (alive_connections == NULL)
3176     alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
3177   g_hash_table_insert (alive_connections, connection, connection);
3178   G_UNLOCK (message_bus_lock);
3179
3180   connection->worker = _g_dbus_worker_new (connection->stream,
3181                                            connection->capabilities,
3182                                            ((connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) != 0),
3183                                            on_worker_message_received,
3184                                            on_worker_message_about_to_be_sent,
3185                                            on_worker_closed,
3186                                            connection);
3187
3188   /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
3189   if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3190     {
3191       GVariant *hello_result;
3192
3193       /* we could lift this restriction by adding code in gdbusprivate.c */
3194       if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
3195         {
3196           g_set_error_literal (&connection->initialization_error,
3197                                G_IO_ERROR,
3198                                G_IO_ERROR_FAILED,
3199                                "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
3200           goto out;
3201         }
3202
3203       if (G_IS_KDBUS_CONNECTION (connection->stream))
3204         {
3205           hello_result = _g_kdbus_Hello (connection->stream, &connection->initialization_error);
3206         }
3207       else
3208         {
3209           hello_result = g_dbus_connection_call_sync (connection,
3210                                                       "org.freedesktop.DBus", /* name */
3211                                                       "/org/freedesktop/DBus", /* path */
3212                                                       "org.freedesktop.DBus", /* interface */
3213                                                       "Hello",
3214                                                       NULL, /* parameters */
3215                                                       G_VARIANT_TYPE ("(s)"),
3216                                                       CALL_FLAGS_INITIALIZING,
3217                                                       -1,
3218                                                       NULL, /* TODO: cancellable */
3219                                                       &connection->initialization_error);
3220         }
3221
3222       if (hello_result == NULL)
3223         goto out;
3224
3225       g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
3226       g_variant_unref (hello_result);
3227       //g_debug ("unique name is '%s'", connection->bus_unique_name);
3228     }
3229
3230   ret = TRUE;
3231  out:
3232   if (!ret)
3233     {
3234       g_assert (connection->initialization_error != NULL);
3235       g_propagate_error (error, g_error_copy (connection->initialization_error));
3236     }
3237
3238   g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
3239   g_mutex_unlock (&connection->init_lock);
3240
3241   return ret;
3242 }
3243
3244 static void
3245 initable_iface_init (GInitableIface *initable_iface)
3246 {
3247   initable_iface->init = initable_init;
3248 }
3249
3250 /* ---------------------------------------------------------------------------------------------------- */
3251
3252 static void
3253 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
3254 {
3255   /* Use default */
3256 }
3257
3258 /* ---------------------------------------------------------------------------------------------------- */
3259
3260 /**
3261  * g_dbus_connection_new:
3262  * @stream: a #GIOStream
3263  * @guid: (allow-none): the GUID to use if a authenticating as a server or %NULL
3264  * @flags: flags describing how to make the connection
3265  * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3266  * @cancellable: (allow-none): a #GCancellable or %NULL
3267  * @callback: a #GAsyncReadyCallback to call when the request is satisfied
3268  * @user_data: the data to pass to @callback
3269  *
3270  * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
3271  * with the end represented by @stream.
3272  *
3273  * If @stream is a #GSocketConnection, then the corresponding #GSocket
3274  * will be put into non-blocking mode.
3275  *
3276  * The D-Bus connection will interact with @stream from a worker thread.
3277  * As a result, the caller should not interact with @stream after this
3278  * method has been called, except by calling g_object_unref() on it.
3279  *
3280  * If @observer is not %NULL it may be used to control the
3281  * authentication process.
3282  *
3283  * When the operation is finished, @callback will be invoked. You can
3284  * then call g_dbus_connection_new_finish() to get the result of the
3285  * operation.
3286  *
3287  * This is a asynchronous failable constructor. See
3288  * g_dbus_connection_new_sync() for the synchronous
3289  * version.
3290  *
3291  * Since: 2.26
3292  */
3293 void
3294 g_dbus_connection_new (GIOStream            *stream,
3295                        const gchar          *guid,
3296                        GDBusConnectionFlags  flags,
3297                        GDBusAuthObserver    *observer,
3298                        GCancellable         *cancellable,
3299                        GAsyncReadyCallback   callback,
3300                        gpointer              user_data)
3301 {
3302   g_return_if_fail (G_IS_IO_STREAM (stream));
3303   g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
3304                               G_PRIORITY_DEFAULT,
3305                               cancellable,
3306                               callback,
3307                               user_data,
3308                               "stream", stream,
3309                               "guid", guid,
3310                               "flags", flags,
3311                               "authentication-observer", observer,
3312                               NULL);
3313 }
3314
3315 /**
3316  * g_dbus_connection_new_finish:
3317  * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback
3318  *     passed to g_dbus_connection_new().
3319  * @error: return location for error or %NULL
3320  *
3321  * Finishes an operation started with g_dbus_connection_new().
3322  *
3323  * Returns: a #GDBusConnection or %NULL if @error is set. Free
3324  *     with g_object_unref().
3325  *
3326  * Since: 2.26
3327  */
3328 GDBusConnection *
3329 g_dbus_connection_new_finish (GAsyncResult  *res,
3330                               GError       **error)
3331 {
3332   GObject *object;
3333   GObject *source_object;
3334
3335   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
3336   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3337
3338   source_object = g_async_result_get_source_object (res);
3339   g_assert (source_object != NULL);
3340   object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
3341                                         res,
3342                                         error);
3343   g_object_unref (source_object);
3344   if (object != NULL)
3345     return G_DBUS_CONNECTION (object);
3346   else
3347     return NULL;
3348 }
3349
3350 /**
3351  * g_dbus_connection_new_sync:
3352  * @stream: a #GIOStream
3353  * @guid: (allow-none): the GUID to use if a authenticating as a server or %NULL
3354  * @flags: flags describing how to make the connection
3355  * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3356  * @cancellable: (allow-none): a #GCancellable or %NULL
3357  * @error: return location for error or %NULL
3358  *
3359  * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
3360  * with the end represented by @stream.
3361  *
3362  * If @stream is a #GSocketConnection, then the corresponding #GSocket
3363  * will be put into non-blocking mode.
3364  *
3365  * The D-Bus connection will interact with @stream from a worker thread.
3366  * As a result, the caller should not interact with @stream after this
3367  * method has been called, except by calling g_object_unref() on it.
3368  *
3369  * If @observer is not %NULL it may be used to control the
3370  * authentication process.
3371  *
3372  * This is a synchronous failable constructor. See
3373  * g_dbus_connection_new() for the asynchronous version.
3374  *
3375  * Returns: a #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
3376  *
3377  * Since: 2.26
3378  */
3379 GDBusConnection *
3380 g_dbus_connection_new_sync (GIOStream             *stream,
3381                             const gchar           *guid,
3382                             GDBusConnectionFlags   flags,
3383                             GDBusAuthObserver     *observer,
3384                             GCancellable          *cancellable,
3385                             GError               **error)
3386 {
3387   g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
3388   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3389   return g_initable_new (G_TYPE_DBUS_CONNECTION,
3390                          cancellable,
3391                          error,
3392                          "stream", stream,
3393                          "guid", guid,
3394                          "flags", flags,
3395                          "authentication-observer", observer,
3396                          NULL);
3397 }
3398
3399 /* ---------------------------------------------------------------------------------------------------- */
3400
3401 /**
3402  * g_dbus_connection_new_for_address:
3403  * @address: a D-Bus address
3404  * @flags: flags describing how to make the connection
3405  * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3406  * @cancellable: (allow-none): a #GCancellable or %NULL
3407  * @callback: a #GAsyncReadyCallback to call when the request is satisfied
3408  * @user_data: the data to pass to @callback
3409  *
3410  * Asynchronously connects and sets up a D-Bus client connection for
3411  * exchanging D-Bus messages with an endpoint specified by @address
3412  * which must be in the D-Bus address format.
3413  *
3414  * This constructor can only be used to initiate client-side
3415  * connections - use g_dbus_connection_new() if you need to act as the
3416  * server. In particular, @flags cannot contain the
3417  * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
3418  * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
3419  *
3420  * When the operation is finished, @callback will be invoked. You can
3421  * then call g_dbus_connection_new_finish() to get the result of the
3422  * operation.
3423  *
3424  * If @observer is not %NULL it may be used to control the
3425  * authentication process.
3426  *
3427  * This is a asynchronous failable constructor. See
3428  * g_dbus_connection_new_for_address_sync() for the synchronous
3429  * version.
3430  *
3431  * Since: 2.26
3432  */
3433 void
3434 g_dbus_connection_new_for_address (const gchar          *address,
3435                                    GDBusConnectionFlags  flags,
3436                                    GDBusAuthObserver    *observer,
3437                                    GCancellable         *cancellable,
3438                                    GAsyncReadyCallback   callback,
3439                                    gpointer              user_data)
3440 {
3441   g_return_if_fail (address != NULL);
3442   g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
3443                               G_PRIORITY_DEFAULT,
3444                               cancellable,
3445                               callback,
3446                               user_data,
3447                               "address", address,
3448                               "flags", flags,
3449                               "authentication-observer", observer,
3450                               NULL);
3451 }
3452
3453 /**
3454  * g_dbus_connection_new_for_address_finish:
3455  * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
3456  *     to g_dbus_connection_new()
3457  * @error: return location for error or %NULL
3458  *
3459  * Finishes an operation started with g_dbus_connection_new_for_address().
3460  *
3461  * Returns: a #GDBusConnection or %NULL if @error is set. Free with
3462  *     g_object_unref().
3463  *
3464  * Since: 2.26
3465  */
3466 GDBusConnection *
3467 g_dbus_connection_new_for_address_finish (GAsyncResult  *res,
3468                                           GError       **error)
3469 {
3470   GObject *object;
3471   GObject *source_object;
3472
3473   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
3474   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3475
3476   source_object = g_async_result_get_source_object (res);
3477   g_assert (source_object != NULL);
3478   object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
3479                                         res,
3480                                         error);
3481   g_object_unref (source_object);
3482   if (object != NULL)
3483     return G_DBUS_CONNECTION (object);
3484   else
3485     return NULL;
3486 }
3487
3488 /**
3489  * g_dbus_connection_new_for_address_sync:
3490  * @address: a D-Bus address
3491  * @flags: flags describing how to make the connection
3492  * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3493  * @cancellable: (allow-none): a #GCancellable or %NULL
3494  * @error: return location for error or %NULL
3495  *
3496  * Synchronously connects and sets up a D-Bus client connection for
3497  * exchanging D-Bus messages with an endpoint specified by @address
3498  * which must be in the D-Bus address format.
3499  *
3500  * This constructor can only be used to initiate client-side
3501  * connections - use g_dbus_connection_new_sync() if you need to act
3502  * as the server. In particular, @flags cannot contain the
3503  * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
3504  * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
3505  *
3506  * This is a synchronous failable constructor. See
3507  * g_dbus_connection_new_for_address() for the asynchronous version.
3508  *
3509  * If @observer is not %NULL it may be used to control the
3510  * authentication process.
3511  *
3512  * Returns: a #GDBusConnection or %NULL if @error is set. Free with
3513  *     g_object_unref().
3514  *
3515  * Since: 2.26
3516  */
3517 GDBusConnection *
3518 g_dbus_connection_new_for_address_sync (const gchar           *address,
3519                                         GDBusConnectionFlags   flags,
3520                                         GDBusAuthObserver     *observer,
3521                                         GCancellable          *cancellable,
3522                                         GError               **error)
3523 {
3524   g_return_val_if_fail (address != NULL, NULL);
3525   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3526   return g_initable_new (G_TYPE_DBUS_CONNECTION,
3527                          cancellable,
3528                          error,
3529                          "address", address,
3530                          "flags", flags,
3531                          "authentication-observer", observer,
3532                          NULL);
3533 }
3534
3535 /* ---------------------------------------------------------------------------------------------------- */
3536
3537 /**
3538  * g_dbus_connection_set_exit_on_close:
3539  * @connection: a #GDBusConnection
3540  * @exit_on_close: whether the process should be terminated
3541  *     when @connection is closed by the remote peer
3542  *
3543  * Sets whether the process should be terminated when @connection is
3544  * closed by the remote peer. See #GDBusConnection:exit-on-close for
3545  * more details.
3546  *
3547  * Note that this function should be used with care. Most modern UNIX
3548  * desktops tie the notion of a user session the session bus, and expect
3549  * all of a users applications to quit when their bus connection goes away.
3550  * If you are setting @exit_on_close to %FALSE for the shared session
3551  * bus connection, you should make sure that your application exits
3552  * when the user session ends.
3553  *
3554  * Since: 2.26
3555  */
3556 void
3557 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
3558                                      gboolean         exit_on_close)
3559 {
3560   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3561
3562   if (exit_on_close)
3563     g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
3564   else
3565     g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
3566
3567 }
3568
3569 /**
3570  * g_dbus_connection_get_exit_on_close:
3571  * @connection: a #GDBusConnection
3572  *
3573  * Gets whether the process is terminated when @connection is
3574  * closed by the remote peer. See
3575  * #GDBusConnection:exit-on-close for more details.
3576  *
3577  * Returns: whether the process is terminated when @connection is
3578  *     closed by the remote peer
3579  *
3580  * Since: 2.26
3581  */
3582 gboolean
3583 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
3584 {
3585   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3586
3587   if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
3588     return TRUE;
3589   else
3590     return FALSE;
3591 }
3592
3593 /**
3594  * g_dbus_connection_get_guid:
3595  * @connection: a #GDBusConnection
3596  *
3597  * The GUID of the peer performing the role of server when
3598  * authenticating. See #GDBusConnection:guid for more details.
3599  *
3600  * Returns: The GUID. Do not free this string, it is owned by
3601  *     @connection.
3602  *
3603  * Since: 2.26
3604  */
3605 const gchar *
3606 g_dbus_connection_get_guid (GDBusConnection *connection)
3607 {
3608   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3609   return connection->guid;
3610 }
3611
3612 /**
3613  * g_dbus_connection_get_unique_name:
3614  * @connection: a #GDBusConnection
3615  *
3616  * Gets the unique name of @connection as assigned by the message
3617  * bus. This can also be used to figure out if @connection is a
3618  * message bus connection.
3619  *
3620  * Returns: the unique name or %NULL if @connection is not a message
3621  *     bus connection. Do not free this string, it is owned by
3622  *     @connection.
3623  *
3624  * Since: 2.26
3625  */
3626 const gchar *
3627 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3628 {
3629   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3630
3631   /* do not use g_return_val_if_fail(), we want the memory barrier */
3632   if (!check_initialized (connection))
3633     return NULL;
3634
3635   return connection->bus_unique_name;
3636 }
3637
3638 /**
3639  * g_dbus_connection_get_peer_credentials:
3640  * @connection: a #GDBusConnection
3641  *
3642  * Gets the credentials of the authenticated peer. This will always
3643  * return %NULL unless @connection acted as a server
3644  * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3645  * when set up and the client passed credentials as part of the
3646  * authentication process.
3647  *
3648  * In a message bus setup, the message bus is always the server and
3649  * each application is a client. So this method will always return
3650  * %NULL for message bus clients.
3651  *
3652  * Returns: (transfer none): a #GCredentials or %NULL if not available.
3653  *     Do not free this object, it is owned by @connection.
3654  *
3655  * Since: 2.26
3656  */
3657 GCredentials *
3658 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3659 {
3660   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3661
3662   /* do not use g_return_val_if_fail(), we want the memory barrier */
3663   if (!check_initialized (connection))
3664     return NULL;
3665
3666   return connection->credentials;
3667 }
3668
3669 /* ---------------------------------------------------------------------------------------------------- */
3670
3671 static guint _global_filter_id = 1;
3672
3673 /**
3674  * g_dbus_connection_add_filter:
3675  * @connection: a #GDBusConnection
3676  * @filter_function: a filter function
3677  * @user_data: user data to pass to @filter_function
3678  * @user_data_free_func: function to free @user_data with when filter
3679  *     is removed or %NULL
3680  *
3681  * Adds a message filter. Filters are handlers that are run on all
3682  * incoming and outgoing messages, prior to standard dispatch. Filters
3683  * are run in the order that they were added.  The same handler can be
3684  * added as a filter more than once, in which case it will be run more
3685  * than once.  Filters added during a filter callback won't be run on
3686  * the message being processed. Filter functions are allowed to modify
3687  * and even drop messages.
3688  *
3689  * Note that filters are run in a dedicated message handling thread so
3690  * they can't block and, generally, can't do anything but signal a
3691  * worker thread. Also note that filters are rarely needed - use API
3692  * such as g_dbus_connection_send_message_with_reply(),
3693  * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3694  *
3695  * If a filter consumes an incoming message the message is not
3696  * dispatched anywhere else - not even the standard dispatch machinery
3697  * (that API such as g_dbus_connection_signal_subscribe() and
3698  * g_dbus_connection_send_message_with_reply() relies on) will see the
3699  * message. Similary, if a filter consumes an outgoing message, the
3700  * message will not be sent to the other peer.
3701  *
3702  * Returns: a filter identifier that can be used with
3703  *     g_dbus_connection_remove_filter()
3704  *
3705  * Since: 2.26
3706  */
3707 guint
3708 g_dbus_connection_add_filter (GDBusConnection            *connection,
3709                               GDBusMessageFilterFunction  filter_function,
3710                               gpointer                    user_data,
3711                               GDestroyNotify              user_data_free_func)
3712 {
3713   FilterData *data;
3714
3715   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3716   g_return_val_if_fail (filter_function != NULL, 0);
3717   g_return_val_if_fail (check_initialized (connection), 0);
3718
3719   CONNECTION_LOCK (connection);
3720   data = g_new0 (FilterData, 1);
3721   data->id = _global_filter_id++; /* TODO: overflow etc. */
3722   data->filter_function = filter_function;
3723   data->user_data = user_data;
3724   data->user_data_free_func = user_data_free_func;
3725   g_ptr_array_add (connection->filters, data);
3726   CONNECTION_UNLOCK (connection);
3727
3728   return data->id;
3729 }
3730
3731 /* only called from finalize(), removes all filters */
3732 static void
3733 purge_all_filters (GDBusConnection *connection)
3734 {
3735   guint n;
3736   for (n = 0; n < connection->filters->len; n++)
3737     {
3738       FilterData *data = connection->filters->pdata[n];
3739       if (data->user_data_free_func != NULL)
3740         data->user_data_free_func (data->user_data);
3741       g_free (data);
3742     }
3743 }
3744
3745 /**
3746  * g_dbus_connection_remove_filter:
3747  * @connection: a #GDBusConnection
3748  * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3749  *
3750  * Removes a filter.
3751  *
3752  * Since: 2.26
3753  */
3754 void
3755 g_dbus_connection_remove_filter (GDBusConnection *connection,
3756                                  guint            filter_id)
3757 {
3758   guint n;
3759   FilterData *to_destroy;
3760
3761   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3762   g_return_if_fail (check_initialized (connection));
3763
3764   CONNECTION_LOCK (connection);
3765   to_destroy = NULL;
3766   for (n = 0; n < connection->filters->len; n++)
3767     {
3768       FilterData *data = connection->filters->pdata[n];
3769       if (data->id == filter_id)
3770         {
3771           g_ptr_array_remove_index (connection->filters, n);
3772           to_destroy = data;
3773           break;
3774         }
3775     }
3776   CONNECTION_UNLOCK (connection);
3777
3778   /* do free without holding lock */
3779   if (to_destroy != NULL)
3780     {
3781       if (to_destroy->user_data_free_func != NULL)
3782         to_destroy->user_data_free_func (to_destroy->user_data);
3783       g_free (to_destroy);
3784     }
3785   else
3786     {
3787       g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3788     }
3789 }
3790
3791 /* ---------------------------------------------------------------------------------------------------- */
3792
3793 typedef struct
3794 {
3795   gchar *rule;
3796   gchar *sender;
3797   gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3798   gchar *interface_name;
3799   gchar *member;
3800   gchar *object_path;
3801   gchar *arg0;
3802   GDBusSignalFlags flags;
3803   GArray *subscribers;
3804 } SignalData;
3805
3806 typedef struct
3807 {
3808   GDBusSignalCallback callback;
3809   gpointer user_data;
3810   GDestroyNotify user_data_free_func;
3811   guint id;
3812   GMainContext *context;
3813 } SignalSubscriber;
3814
3815 static void
3816 signal_data_free (SignalData *signal_data)
3817 {
3818   g_free (signal_data->rule);
3819   g_free (signal_data->sender);
3820   g_free (signal_data->sender_unique_name);
3821   g_free (signal_data->interface_name);
3822   g_free (signal_data->member);
3823   g_free (signal_data->object_path);
3824   g_free (signal_data->arg0);
3825   g_array_free (signal_data->subscribers, TRUE);
3826   g_free (signal_data);
3827 }
3828
3829 static gchar *
3830 args_to_rule (const gchar      *sender,
3831               const gchar      *interface_name,
3832               const gchar      *member,
3833               const gchar      *object_path,
3834               const gchar      *arg0,
3835               GDBusSignalFlags  flags)
3836 {
3837   GString *rule;
3838
3839   rule = g_string_new ("type='signal'");
3840   if (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE)
3841     g_string_prepend_c (rule, '-');
3842   if (sender != NULL)
3843     g_string_append_printf (rule, ",sender='%s'", sender);
3844   if (interface_name != NULL)
3845     g_string_append_printf (rule, ",interface='%s'", interface_name);
3846   if (member != NULL)
3847     g_string_append_printf (rule, ",member='%s'", member);
3848   if (object_path != NULL)
3849     g_string_append_printf (rule, ",path='%s'", object_path);
3850
3851   if (arg0 != NULL)
3852     {
3853       if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3854         g_string_append_printf (rule, ",arg0path='%s'", arg0);
3855       else if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3856         g_string_append_printf (rule, ",arg0namespace='%s'", arg0);
3857       else
3858         g_string_append_printf (rule, ",arg0='%s'", arg0);
3859     }
3860
3861   return g_string_free (rule, FALSE);
3862 }
3863
3864 static guint _global_subscriber_id = 1;
3865 static guint _global_registration_id = 1;
3866 static guint _global_subtree_registration_id = 1;
3867
3868 /* ---------------------------------------------------------------------------------------------------- */
3869
3870 /* Called in a user thread, lock is held */
3871 static void
3872 add_match_rule (GDBusConnection *connection,
3873                 const gchar     *match_rule)
3874 {
3875   GError *error;
3876   GDBusMessage *message;
3877
3878   if (match_rule[0] == '-')
3879     return;
3880
3881   message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3882                                             "/org/freedesktop/DBus", /* path */
3883                                             "org.freedesktop.DBus", /* interface */
3884                                             "AddMatch");
3885   g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3886   error = NULL;
3887   if (!g_dbus_connection_send_message_unlocked (connection,
3888                                                 message,
3889                                                 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3890                                                 NULL,
3891                                                 &error))
3892     {
3893       g_critical ("Error while sending AddMatch() message: %s", error->message);
3894       g_error_free (error);
3895     }
3896   g_object_unref (message);
3897 }
3898
3899 /* ---------------------------------------------------------------------------------------------------- */
3900
3901 /* Called in a user thread, lock is held */
3902 static void
3903 remove_match_rule (GDBusConnection *connection,
3904                    const gchar     *match_rule)
3905 {
3906   GError *error;
3907   GDBusMessage *message;
3908
3909   if (match_rule[0] == '-')
3910     return;
3911
3912   message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3913                                             "/org/freedesktop/DBus", /* path */
3914                                             "org.freedesktop.DBus", /* interface */
3915                                             "RemoveMatch");
3916   g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3917
3918   error = NULL;
3919   if (!g_dbus_connection_send_message_unlocked (connection,
3920                                                 message,
3921                                                 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3922                                                 NULL,
3923                                                 &error))
3924     {
3925       /* If we could get G_IO_ERROR_CLOSED here, it wouldn't be reasonable to
3926        * critical; but we're holding the lock, and our caller checked whether
3927        * we were already closed, so we can't get that error.
3928        */
3929       g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3930       g_error_free (error);
3931     }
3932   g_object_unref (message);
3933 }
3934
3935 /* ---------------------------------------------------------------------------------------------------- */
3936
3937 static gboolean
3938 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3939 {
3940   return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3941          g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3942          g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3943          (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3944           g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3945 }
3946
3947 /* ---------------------------------------------------------------------------------------------------- */
3948
3949 /**
3950  * g_dbus_connection_signal_subscribe:
3951  * @connection: a #GDBusConnection
3952  * @sender: (allow-none): sender name to match on (unique or well-known name)
3953  *     or %NULL to listen from all senders
3954  * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3955  *     match on all interfaces
3956  * @member: (allow-none): D-Bus signal name to match on or %NULL to match on
3957  *     all signals
3958  * @object_path: (allow-none): object path to match on or %NULL to match on
3959  *     all object paths
3960  * @arg0: (allow-none): contents of first string argument to match on or %NULL
3961  *     to match on all kinds of arguments
3962  * @flags: flags describing how to subscribe to the signal (currently unused)
3963  * @callback: callback to invoke when there is a signal matching the requested data
3964  * @user_data: user data to pass to @callback
3965  * @user_data_free_func: (allow-none): function to free @user_data with when
3966  *     subscription is removed or %NULL
3967  *
3968  * Subscribes to signals on @connection and invokes @callback with a whenever
3969  * the signal is received. Note that @callback will be invoked in the 
3970  * [thread-default main context][g-main-context-push-thread-default]
3971  * of the thread you are calling this method from.
3972  *
3973  * If @connection is not a message bus connection, @sender must be
3974  * %NULL.
3975  *
3976  * If @sender is a well-known name note that @callback is invoked with
3977  * the unique name for the owner of @sender, not the well-known name
3978  * as one would expect. This is because the message bus rewrites the
3979  * name. As such, to avoid certain race conditions, users should be
3980  * tracking the name owner of the well-known name and use that when
3981  * processing the received signal.
3982  *
3983  * If one of %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE or
3984  * %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH are given, @arg0 is
3985  * interpreted as part of a namespace or path.  The first argument
3986  * of a signal is matched against that part as specified by D-Bus.
3987  *
3988  * Returns: a subscription identifier that can be used with g_dbus_connection_signal_unsubscribe()
3989  *
3990  * Since: 2.26
3991  */
3992 guint
3993 g_dbus_connection_signal_subscribe (GDBusConnection     *connection,
3994                                     const gchar         *sender,
3995                                     const gchar         *interface_name,
3996                                     const gchar         *member,
3997                                     const gchar         *object_path,
3998                                     const gchar         *arg0,
3999                                     GDBusSignalFlags     flags,
4000                                     GDBusSignalCallback  callback,
4001                                     gpointer             user_data,
4002                                     GDestroyNotify       user_data_free_func)
4003 {
4004   gchar *rule;
4005   SignalData *signal_data;
4006   SignalSubscriber subscriber;
4007   GPtrArray *signal_data_array;
4008   const gchar *sender_unique_name;
4009
4010   /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
4011    * an OOM condition. We might want to change that but that would involve making
4012    * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
4013    * handle that. And there's really no sensible way of handling this short of retrying
4014    * to add the match rule... and then there's the little thing that, hey, maybe there's
4015    * a reason the bus in an OOM condition.
4016    *
4017    * Doable, but not really sure it's worth it...
4018    */
4019
4020   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4021   g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
4022   g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
4023   g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
4024   g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
4025   g_return_val_if_fail (callback != NULL, 0);
4026   g_return_val_if_fail (check_initialized (connection), 0);
4027   g_return_val_if_fail (!((flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH) && (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)), 0);
4028   g_return_val_if_fail (!(arg0 == NULL && (flags & (G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH | G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE))), 0);
4029
4030   CONNECTION_LOCK (connection);
4031
4032   /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
4033    * with a '-' character to prefix the rule (which will otherwise be
4034    * normal).
4035    *
4036    * This allows us to hash the rule and do our lifecycle tracking in
4037    * the usual way, but the '-' prevents the match rule from ever
4038    * actually being send to the bus (either for add or remove).
4039    */
4040   rule = args_to_rule (sender, interface_name, member, object_path, arg0, flags);
4041
4042   if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
4043     sender_unique_name = sender;
4044   else
4045     sender_unique_name = "";
4046
4047   subscriber.callback = callback;
4048   subscriber.user_data = user_data;
4049   subscriber.user_data_free_func = user_data_free_func;
4050   subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
4051   subscriber.context = g_main_context_ref_thread_default ();
4052
4053   /* see if we've already have this rule */
4054   signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
4055   if (signal_data != NULL)
4056     {
4057       g_array_append_val (signal_data->subscribers, subscriber);
4058       g_free (rule);
4059       goto out;
4060     }
4061
4062   signal_data = g_new0 (SignalData, 1);
4063   signal_data->rule                  = rule;
4064   signal_data->sender                = g_strdup (sender);
4065   signal_data->sender_unique_name    = g_strdup (sender_unique_name);
4066   signal_data->interface_name        = g_strdup (interface_name);
4067   signal_data->member                = g_strdup (member);
4068   signal_data->object_path           = g_strdup (object_path);
4069   signal_data->arg0                  = g_strdup (arg0);
4070   signal_data->flags                 = flags;
4071   signal_data->subscribers           = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
4072   g_array_append_val (signal_data->subscribers, subscriber);
4073
4074   g_hash_table_insert (connection->map_rule_to_signal_data,
4075                        signal_data->rule,
4076                        signal_data);
4077
4078   /* Add the match rule to the bus...
4079    *
4080    * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
4081    * always send such messages to us.
4082    */
4083   if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
4084     {
4085       if (!is_signal_data_for_name_lost_or_acquired (signal_data))
4086         add_match_rule (connection, signal_data->rule);
4087       else
4088         {
4089           if (G_IS_KDBUS_CONNECTION (connection->stream))
4090             {
4091               if (g_strcmp0 (signal_data->member, "NameAcquired") == 0)
4092                 _g_kdbus_subscribe_name_acquired (connection, arg0);
4093               else if (g_strcmp0 (signal_data->member, "NameLost") == 0)
4094                 _g_kdbus_subscribe_name_lost (connection, arg0);
4095             }
4096         }
4097     }
4098
4099   signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
4100                                            signal_data->sender_unique_name);
4101   if (signal_data_array == NULL)
4102     {
4103       signal_data_array = g_ptr_array_new ();
4104       g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
4105                            g_strdup (signal_data->sender_unique_name),
4106                            signal_data_array);
4107     }
4108   g_ptr_array_add (signal_data_array, signal_data);
4109
4110  out:
4111   g_hash_table_insert (connection->map_id_to_signal_data,
4112                        GUINT_TO_POINTER (subscriber.id),
4113                        signal_data);
4114
4115   CONNECTION_UNLOCK (connection);
4116
4117   return subscriber.id;
4118 }
4119
4120 /* ---------------------------------------------------------------------------------------------------- */
4121
4122 /* called in any thread */
4123 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
4124 static void
4125 unsubscribe_id_internal (GDBusConnection *connection,
4126                          guint            subscription_id,
4127                          GArray          *out_removed_subscribers)
4128 {
4129   SignalData *signal_data;
4130   GPtrArray *signal_data_array;
4131   guint n;
4132
4133   signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
4134                                      GUINT_TO_POINTER (subscription_id));
4135   if (signal_data == NULL)
4136     {
4137       /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
4138       goto out;
4139     }
4140
4141   for (n = 0; n < signal_data->subscribers->len; n++)
4142     {
4143       SignalSubscriber *subscriber;
4144
4145       subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
4146       if (subscriber->id != subscription_id)
4147         continue;
4148
4149       g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
4150                                            GUINT_TO_POINTER (subscription_id)));
4151       g_array_append_val (out_removed_subscribers, *subscriber);
4152       g_array_remove_index (signal_data->subscribers, n);
4153
4154       if (signal_data->subscribers->len == 0)
4155         {
4156           g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
4157
4158           signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
4159                                                    signal_data->sender_unique_name);
4160           g_warn_if_fail (signal_data_array != NULL);
4161           g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
4162
4163           if (signal_data_array->len == 0)
4164             {
4165               g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
4166                                                    signal_data->sender_unique_name));
4167             }
4168
4169           /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
4170           if ((connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION) &&
4171               !is_signal_data_for_name_lost_or_acquired (signal_data) &&
4172               !g_dbus_connection_is_closed (connection) &&
4173               !connection->finalizing)
4174             {
4175               /* The check for g_dbus_connection_is_closed() means that
4176                * sending the RemoveMatch message can't fail with
4177                * G_IO_ERROR_CLOSED, because we're holding the lock,
4178                * so on_worker_closed() can't happen between the check we just
4179                * did, and releasing the lock later.
4180                */
4181               remove_match_rule (connection, signal_data->rule);
4182             }
4183           else
4184             {
4185               if (G_IS_KDBUS_CONNECTION (connection->stream))
4186                 {
4187                   if (g_strcmp0 (signal_data->member, "NameAcquired") == 0)
4188                     _g_kdbus_unsubscribe_name_acquired (connection);
4189                   else if (g_strcmp0 (signal_data->member, "NameLost") == 0)
4190                     _g_kdbus_unsubscribe_name_lost (connection);
4191                 }
4192             }
4193
4194           signal_data_free (signal_data);
4195         }
4196
4197       goto out;
4198     }
4199
4200   g_assert_not_reached ();
4201
4202  out:
4203   ;
4204 }
4205
4206 /**
4207  * g_dbus_connection_signal_unsubscribe:
4208  * @connection: a #GDBusConnection
4209  * @subscription_id: a subscription id obtained from
4210  *     g_dbus_connection_signal_subscribe()
4211  *
4212  * Unsubscribes from signals.
4213  *
4214  * Since: 2.26
4215  */
4216 void
4217 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
4218                                       guint            subscription_id)
4219 {
4220   GArray *subscribers;
4221   guint n;
4222
4223   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4224   g_return_if_fail (check_initialized (connection));
4225
4226   subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
4227
4228   CONNECTION_LOCK (connection);
4229   unsubscribe_id_internal (connection,
4230                            subscription_id,
4231                            subscribers);
4232   CONNECTION_UNLOCK (connection);
4233
4234   /* invariant */
4235   g_assert (subscribers->len == 0 || subscribers->len == 1);
4236
4237   /* call GDestroyNotify without lock held */
4238   for (n = 0; n < subscribers->len; n++)
4239     {
4240       SignalSubscriber *subscriber;
4241       subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
4242       call_destroy_notify (subscriber->context,
4243                            subscriber->user_data_free_func,
4244                            subscriber->user_data);
4245       g_main_context_unref (subscriber->context);
4246     }
4247
4248   g_array_free (subscribers, TRUE);
4249 }
4250
4251 /* ---------------------------------------------------------------------------------------------------- */
4252
4253 typedef struct
4254 {
4255   guint                subscription_id;
4256   GDBusSignalCallback  callback;
4257   gpointer             user_data;
4258   GDBusMessage        *message;
4259   GDBusConnection     *connection;
4260   const gchar         *sender;
4261   const gchar         *path;
4262   const gchar         *interface;
4263   const gchar         *member;
4264 } SignalInstance;
4265
4266 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
4267  * no locks held
4268  */
4269 static gboolean
4270 emit_signal_instance_in_idle_cb (gpointer data)
4271 {
4272   SignalInstance *signal_instance = data;
4273   GVariant *parameters;
4274   gboolean has_subscription;
4275
4276   parameters = g_dbus_message_get_body (signal_instance->message);
4277   if (parameters == NULL)
4278     {
4279       parameters = g_variant_new ("()");
4280       g_variant_ref_sink (parameters);
4281     }
4282   else
4283     {
4284       g_variant_ref (parameters);
4285     }
4286
4287 #if 0
4288   g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
4289            signal_instance->subscription_id,
4290            signal_instance->sender,
4291            signal_instance->path,
4292            signal_instance->interface,
4293            signal_instance->member,
4294            g_variant_print (parameters, TRUE));
4295 #endif
4296
4297   /* Careful here, don't do the callback if we no longer has the subscription */
4298   CONNECTION_LOCK (signal_instance->connection);
4299   has_subscription = FALSE;
4300   if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
4301                            GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
4302     has_subscription = TRUE;
4303   CONNECTION_UNLOCK (signal_instance->connection);
4304
4305   if (has_subscription)
4306     signal_instance->callback (signal_instance->connection,
4307                                signal_instance->sender,
4308                                signal_instance->path,
4309                                signal_instance->interface,
4310                                signal_instance->member,
4311                                parameters,
4312                                signal_instance->user_data);
4313
4314   g_variant_unref (parameters);
4315
4316   return FALSE;
4317 }
4318
4319 static void
4320 signal_instance_free (SignalInstance *signal_instance)
4321 {
4322   g_object_unref (signal_instance->message);
4323   g_object_unref (signal_instance->connection);
4324   g_free (signal_instance);
4325 }
4326
4327 static gboolean
4328 namespace_rule_matches (const gchar *namespace,
4329                         const gchar *name)
4330 {
4331   gint len_namespace;
4332   gint len_name;
4333
4334   len_namespace = strlen (namespace);
4335   len_name = strlen (name);
4336
4337   if (len_name < len_namespace)
4338     return FALSE;
4339
4340   if (memcmp (namespace, name, len_namespace) != 0)
4341     return FALSE;
4342
4343   return len_namespace == len_name || name[len_namespace] == '.';
4344 }
4345
4346 static gboolean
4347 path_rule_matches (const gchar *path_a,
4348                    const gchar *path_b)
4349 {
4350   gint len_a, len_b;
4351
4352   len_a = strlen (path_a);
4353   len_b = strlen (path_b);
4354
4355   if (len_a < len_b && path_a[len_a - 1] != '/')
4356     return FALSE;
4357
4358   if (len_b < len_a && path_b[len_b - 1] != '/')
4359     return FALSE;
4360
4361   return memcmp (path_a, path_b, MIN (len_a, len_b)) == 0;
4362 }
4363
4364 /* called in GDBusWorker thread WITH lock held */
4365 static void
4366 schedule_callbacks (GDBusConnection *connection,
4367                     GPtrArray       *signal_data_array,
4368                     GDBusMessage    *message,
4369                     const gchar     *sender)
4370 {
4371   guint n, m;
4372   const gchar *interface;
4373   const gchar *member;
4374   const gchar *path;
4375   const gchar *arg0;
4376
4377   interface = NULL;
4378   member = NULL;
4379   path = NULL;
4380   arg0 = NULL;
4381
4382   interface = g_dbus_message_get_interface (message);
4383   member = g_dbus_message_get_member (message);
4384   path = g_dbus_message_get_path (message);
4385   arg0 = g_dbus_message_get_arg0 (message);
4386
4387 #if 0
4388   g_print ("In schedule_callbacks:\n"
4389            "  sender    = '%s'\n"
4390            "  interface = '%s'\n"
4391            "  member    = '%s'\n"
4392            "  path      = '%s'\n"
4393            "  arg0      = '%s'\n",
4394            sender,
4395            interface,
4396            member,
4397            path,
4398            arg0);
4399 #endif
4400
4401   /* TODO: if this is slow, then we can change signal_data_array into
4402    *       map_object_path_to_signal_data_array or something.
4403    */
4404   for (n = 0; n < signal_data_array->len; n++)
4405     {
4406       SignalData *signal_data = signal_data_array->pdata[n];
4407
4408       if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
4409         continue;
4410
4411       if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
4412         continue;
4413
4414       if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
4415         continue;
4416
4417       if (signal_data->arg0 != NULL)
4418         {
4419           if (arg0 == NULL)
4420             continue;
4421
4422           if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
4423             {
4424               if (!namespace_rule_matches (signal_data->arg0, arg0))
4425                 continue;
4426             }
4427           else if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
4428             {
4429               if (!path_rule_matches (signal_data->arg0, arg0))
4430                 continue;
4431             }
4432           else if (!g_str_equal (signal_data->arg0, arg0))
4433             continue;
4434         }
4435
4436       for (m = 0; m < signal_data->subscribers->len; m++)
4437         {
4438           SignalSubscriber *subscriber;
4439           GSource *idle_source;
4440           SignalInstance *signal_instance;
4441
4442           subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
4443
4444           signal_instance = g_new0 (SignalInstance, 1);
4445           signal_instance->subscription_id = subscriber->id;
4446           signal_instance->callback = subscriber->callback;
4447           signal_instance->user_data = subscriber->user_data;
4448           signal_instance->message = g_object_ref (message);
4449           signal_instance->connection = g_object_ref (connection);
4450           signal_instance->sender = sender;
4451           signal_instance->path = path;
4452           signal_instance->interface = interface;
4453           signal_instance->member = member;
4454
4455           idle_source = g_idle_source_new ();
4456           g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4457           g_source_set_callback (idle_source,
4458                                  emit_signal_instance_in_idle_cb,
4459                                  signal_instance,
4460                                  (GDestroyNotify) signal_instance_free);
4461           g_source_set_name (idle_source, "[gio] emit_signal_instance_in_idle_cb");
4462           g_source_attach (idle_source, subscriber->context);
4463           g_source_unref (idle_source);
4464         }
4465     }
4466 }
4467
4468 /* called in GDBusWorker thread with lock held */
4469 static void
4470 distribute_signals (GDBusConnection *connection,
4471                     GDBusMessage    *message)
4472 {
4473   GPtrArray *signal_data_array;
4474   const gchar *sender;
4475
4476   sender = g_dbus_message_get_sender (message);
4477
4478   if (G_UNLIKELY (_g_dbus_debug_signal ()))
4479     {
4480       _g_dbus_debug_print_lock ();
4481       g_print ("========================================================================\n"
4482                "GDBus-debug:Signal:\n"
4483                " <<<< RECEIVED SIGNAL %s.%s\n"
4484                "      on object %s\n"
4485                "      sent by name %s\n",
4486                g_dbus_message_get_interface (message),
4487                g_dbus_message_get_member (message),
4488                g_dbus_message_get_path (message),
4489                sender != NULL ? sender : "(none)");
4490       _g_dbus_debug_print_unlock ();
4491     }
4492
4493   /* collect subscribers that match on sender */
4494   if (sender != NULL)
4495     {
4496       signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
4497       if (signal_data_array != NULL)
4498         schedule_callbacks (connection, signal_data_array, message, sender);
4499     }
4500
4501   /* collect subscribers not matching on sender */
4502   signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
4503   if (signal_data_array != NULL)
4504     schedule_callbacks (connection, signal_data_array, message, sender);
4505 }
4506
4507 /* ---------------------------------------------------------------------------------------------------- */
4508
4509 /* only called from finalize(), removes all subscriptions */
4510 static void
4511 purge_all_signal_subscriptions (GDBusConnection *connection)
4512 {
4513   GHashTableIter iter;
4514   gpointer key;
4515   GArray *ids;
4516   GArray *subscribers;
4517   guint n;
4518
4519   ids = g_array_new (FALSE, FALSE, sizeof (guint));
4520   g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
4521   while (g_hash_table_iter_next (&iter, &key, NULL))
4522     {
4523       guint subscription_id = GPOINTER_TO_UINT (key);
4524       g_array_append_val (ids, subscription_id);
4525     }
4526
4527   subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
4528   for (n = 0; n < ids->len; n++)
4529     {
4530       guint subscription_id = g_array_index (ids, guint, n);
4531       unsubscribe_id_internal (connection,
4532                                subscription_id,
4533                                subscribers);
4534     }
4535   g_array_free (ids, TRUE);
4536
4537   /* call GDestroyNotify without lock held */
4538   for (n = 0; n < subscribers->len; n++)
4539     {
4540       SignalSubscriber *subscriber;
4541       subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
4542       call_destroy_notify (subscriber->context,
4543                            subscriber->user_data_free_func,
4544                            subscriber->user_data);
4545       g_main_context_unref (subscriber->context);
4546     }
4547
4548   g_array_free (subscribers, TRUE);
4549 }
4550
4551 /* ---------------------------------------------------------------------------------------------------- */
4552
4553 static GDBusInterfaceVTable *
4554 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
4555 {
4556   /* Don't waste memory by copying padding - remember to update this
4557    * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
4558    */
4559   return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4560 }
4561
4562 static void
4563 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
4564 {
4565   g_free (vtable);
4566 }
4567
4568 /* ---------------------------------------------------------------------------------------------------- */
4569
4570 static GDBusSubtreeVTable *
4571 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
4572 {
4573   /* Don't waste memory by copying padding - remember to update this
4574    * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
4575    */
4576   return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4577 }
4578
4579 static void
4580 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
4581 {
4582   g_free (vtable);
4583 }
4584
4585 /* ---------------------------------------------------------------------------------------------------- */
4586
4587 struct ExportedObject
4588 {
4589   gchar *object_path;
4590   GDBusConnection *connection;
4591
4592   /* maps gchar* -> ExportedInterface* */
4593   GHashTable *map_if_name_to_ei;
4594 };
4595
4596 /* only called with lock held */
4597 static void
4598 exported_object_free (ExportedObject *eo)
4599 {
4600   g_free (eo->object_path);
4601   g_hash_table_unref (eo->map_if_name_to_ei);
4602   g_free (eo);
4603 }
4604
4605 typedef struct
4606 {
4607   ExportedObject *eo;
4608
4609   guint                       id;
4610   gchar                      *interface_name;
4611   GDBusInterfaceVTable       *vtable;
4612   GDBusInterfaceInfo         *interface_info;
4613
4614   GMainContext               *context;
4615   gpointer                    user_data;
4616   GDestroyNotify              user_data_free_func;
4617 } ExportedInterface;
4618
4619 /* called with lock held */
4620 static void
4621 exported_interface_free (ExportedInterface *ei)
4622 {
4623   g_dbus_interface_info_cache_release (ei->interface_info);
4624   g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
4625
4626   call_destroy_notify (ei->context,
4627                        ei->user_data_free_func,
4628                        ei->user_data);
4629
4630   g_main_context_unref (ei->context);
4631
4632   g_free (ei->interface_name);
4633   _g_dbus_interface_vtable_free (ei->vtable);
4634   g_free (ei);
4635 }
4636
4637 /* ---------------------------------------------------------------------------------------------------- */
4638
4639 /* Convenience function to check if @registration_id (if not zero) or
4640  * @subtree_registration_id (if not zero) has been unregistered. If
4641  * so, returns %TRUE.
4642  *
4643  * May be called by any thread. Caller must *not* hold lock.
4644  */
4645 static gboolean
4646 has_object_been_unregistered (GDBusConnection  *connection,
4647                               guint             registration_id,
4648                               guint             subtree_registration_id)
4649 {
4650   gboolean ret;
4651
4652   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4653
4654   ret = FALSE;
4655
4656   CONNECTION_LOCK (connection);
4657   if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
4658                                                    GUINT_TO_POINTER (registration_id)) == NULL)
4659     {
4660       ret = TRUE;
4661     }
4662   else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
4663                                                                 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
4664     {
4665       ret = TRUE;
4666     }
4667   CONNECTION_UNLOCK (connection);
4668
4669   return ret;
4670 }
4671
4672 /* ---------------------------------------------------------------------------------------------------- */
4673
4674 typedef struct
4675 {
4676   GDBusConnection *connection;
4677   GDBusMessage *message;
4678   gpointer user_data;
4679   const gchar *property_name;
4680   const GDBusInterfaceVTable *vtable;
4681   GDBusInterfaceInfo *interface_info;
4682   const GDBusPropertyInfo *property_info;
4683   guint registration_id;
4684   guint subtree_registration_id;
4685 } PropertyData;
4686
4687 static void
4688 property_data_free (PropertyData *data)
4689 {
4690   g_object_unref (data->connection);
4691   g_object_unref (data->message);
4692   g_free (data);
4693 }
4694
4695 /* called in thread where object was registered - no locks held */
4696 static gboolean
4697 invoke_get_property_in_idle_cb (gpointer _data)
4698 {
4699   PropertyData *data = _data;
4700   GVariant *value;
4701   GError *error;
4702   GDBusMessage *reply;
4703
4704   if (has_object_been_unregistered (data->connection,
4705                                     data->registration_id,
4706                                     data->subtree_registration_id))
4707     {
4708       reply = g_dbus_message_new_method_error (data->message,
4709                                                "org.freedesktop.DBus.Error.UnknownMethod",
4710                                                _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4711                                                g_dbus_message_get_path (data->message));
4712       g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4713       g_object_unref (reply);
4714       goto out;
4715     }
4716
4717   error = NULL;
4718   value = data->vtable->get_property (data->connection,
4719                                       g_dbus_message_get_sender (data->message),
4720                                       g_dbus_message_get_path (data->message),
4721                                       data->interface_info->name,
4722                                       data->property_name,
4723                                       &error,
4724                                       data->user_data);
4725
4726
4727   if (value != NULL)
4728     {
4729       g_assert_no_error (error);
4730
4731       g_variant_take_ref (value);
4732       reply = g_dbus_message_new_method_reply (data->message);
4733       g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4734       g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4735       g_variant_unref (value);
4736       g_object_unref (reply);
4737     }
4738   else
4739     {
4740       gchar *dbus_error_name;
4741       g_assert (error != NULL);
4742       dbus_error_name = g_dbus_error_encode_gerror (error);
4743       reply = g_dbus_message_new_method_error_literal (data->message,
4744                                                        dbus_error_name,
4745                                                        error->message);
4746       g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4747       g_free (dbus_error_name);
4748       g_error_free (error);
4749       g_object_unref (reply);
4750     }
4751
4752  out:
4753   return FALSE;
4754 }
4755
4756 /* called in thread where object was registered - no locks held */
4757 static gboolean
4758 invoke_set_property_in_idle_cb (gpointer _data)
4759 {
4760   PropertyData *data = _data;
4761   GError *error;
4762   GDBusMessage *reply;
4763   GVariant *value;
4764
4765   error = NULL;
4766   value = NULL;
4767
4768   g_variant_get (g_dbus_message_get_body (data->message),
4769                  "(ssv)",
4770                  NULL,
4771                  NULL,
4772                  &value);
4773
4774   if (!data->vtable->set_property (data->connection,
4775                                    g_dbus_message_get_sender (data->message),
4776                                    g_dbus_message_get_path (data->message),
4777                                    data->interface_info->name,
4778                                    data->property_name,
4779                                    value,
4780                                    &error,
4781                                    data->user_data))
4782     {
4783       gchar *dbus_error_name;
4784       g_assert (error != NULL);
4785       dbus_error_name = g_dbus_error_encode_gerror (error);
4786       reply = g_dbus_message_new_method_error_literal (data->message,
4787                                                        dbus_error_name,
4788                                                        error->message);
4789       g_free (dbus_error_name);
4790       g_error_free (error);
4791     }
4792   else
4793     {
4794       reply = g_dbus_message_new_method_reply (data->message);
4795     }
4796
4797   g_assert (reply != NULL);
4798   g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4799   g_object_unref (reply);
4800   g_variant_unref (value);
4801
4802   return FALSE;
4803 }
4804
4805 /* called in any thread with connection's lock held */
4806 static gboolean
4807 validate_and_maybe_schedule_property_getset (GDBusConnection            *connection,
4808                                              GDBusMessage               *message,
4809                                              guint                       registration_id,
4810                                              guint                       subtree_registration_id,
4811                                              gboolean                    is_get,
4812                                              GDBusInterfaceInfo         *interface_info,
4813                                              const GDBusInterfaceVTable *vtable,
4814                                              GMainContext               *main_context,
4815                                              gpointer                    user_data)
4816 {
4817   gboolean handled;
4818   const char *interface_name;
4819   const char *property_name;
4820   const GDBusPropertyInfo *property_info;
4821   GSource *idle_source;
4822   PropertyData *property_data;
4823   GDBusMessage *reply;
4824
4825   handled = FALSE;
4826
4827   if (is_get)
4828     g_variant_get (g_dbus_message_get_body (message),
4829                    "(&s&s)",
4830                    &interface_name,
4831                    &property_name);
4832   else
4833     g_variant_get (g_dbus_message_get_body (message),
4834                    "(&s&sv)",
4835                    &interface_name,
4836                    &property_name,
4837                    NULL);
4838
4839   if (vtable == NULL)
4840     goto out;
4841
4842   /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4843    */
4844   property_info = NULL;
4845
4846   /* TODO: the cost of this is O(n) - it might be worth caching the result */
4847   property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4848   if (property_info == NULL)
4849     {
4850       reply = g_dbus_message_new_method_error (message,
4851                                                "org.freedesktop.DBus.Error.InvalidArgs",
4852                                                _("No such property '%s'"),
4853                                                property_name);
4854       g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4855       g_object_unref (reply);
4856       handled = TRUE;
4857       goto out;
4858     }
4859
4860   if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4861     {
4862       reply = g_dbus_message_new_method_error (message,
4863                                                "org.freedesktop.DBus.Error.InvalidArgs",
4864                                                _("Property '%s' is not readable"),
4865                                                property_name);
4866       g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4867       g_object_unref (reply);
4868       handled = TRUE;
4869       goto out;
4870     }
4871   else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4872     {
4873       reply = g_dbus_message_new_method_error (message,
4874                                                "org.freedesktop.DBus.Error.InvalidArgs",
4875                                                _("Property '%s' is not writable"),
4876                                                property_name);
4877       g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4878       g_object_unref (reply);
4879       handled = TRUE;
4880       goto out;
4881     }
4882
4883   if (!is_get)
4884     {
4885       GVariant *value;
4886
4887       /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4888        * of the given value is wrong
4889        */
4890       g_variant_get_child (g_dbus_message_get_body (message), 2, "v", &value);
4891       if (g_strcmp0 (g_variant_get_type_string (value), property_info->signature) != 0)
4892         {
4893           reply = g_dbus_message_new_method_error (message,
4894                                                    "org.freedesktop.DBus.Error.InvalidArgs",
4895                                                    _("Error setting property '%s': Expected type '%s' but got '%s'"),
4896                                                    property_name, property_info->signature,
4897                                                    g_variant_get_type_string (value));
4898           g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4899           g_variant_unref (value);
4900           g_object_unref (reply);
4901           handled = TRUE;
4902           goto out;
4903         }
4904
4905       g_variant_unref (value);
4906     }
4907
4908   /* If the vtable pointer for get_property() resp. set_property() is
4909    * NULL then dispatch the call via the method_call() handler.
4910    */
4911   if (is_get)
4912     {
4913       if (vtable->get_property == NULL)
4914         {
4915           schedule_method_call (connection, message, registration_id, subtree_registration_id,
4916                                 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4917                                 vtable, main_context, user_data);
4918           handled = TRUE;
4919           goto out;
4920         }
4921     }
4922   else
4923     {
4924       if (vtable->set_property == NULL)
4925         {
4926           schedule_method_call (connection, message, registration_id, subtree_registration_id,
4927                                 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4928                                 vtable, main_context, user_data);
4929           handled = TRUE;
4930           goto out;
4931         }
4932     }
4933
4934   /* ok, got the property info - call user code in an idle handler */
4935   property_data = g_new0 (PropertyData, 1);
4936   property_data->connection = g_object_ref (connection);
4937   property_data->message = g_object_ref (message);
4938   property_data->user_data = user_data;
4939   property_data->property_name = property_name;
4940   property_data->vtable = vtable;
4941   property_data->interface_info = interface_info;
4942   property_data->property_info = property_info;
4943   property_data->registration_id = registration_id;
4944   property_data->subtree_registration_id = subtree_registration_id;
4945
4946   idle_source = g_idle_source_new ();
4947   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4948   g_source_set_callback (idle_source,
4949                          is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4950                          property_data,
4951                          (GDestroyNotify) property_data_free);
4952   if (is_get)
4953     g_source_set_name (idle_source, "[gio] invoke_get_property_in_idle_cb");
4954   else
4955     g_source_set_name (idle_source, "[gio] invoke_set_property_in_idle_cb");
4956   g_source_attach (idle_source, main_context);
4957   g_source_unref (idle_source);
4958
4959   handled = TRUE;
4960
4961  out:
4962   return handled;
4963 }
4964
4965 /* called in GDBusWorker thread with connection's lock held */
4966 static gboolean
4967 handle_getset_property (GDBusConnection *connection,
4968                         ExportedObject  *eo,
4969                         GDBusMessage    *message,
4970                         gboolean         is_get)
4971 {
4972   ExportedInterface *ei;
4973   gboolean handled;
4974   const char *interface_name;
4975   const char *property_name;
4976
4977   handled = FALSE;
4978
4979   if (is_get)
4980     g_variant_get (g_dbus_message_get_body (message),
4981                    "(&s&s)",
4982                    &interface_name,
4983                    &property_name);
4984   else
4985     g_variant_get (g_dbus_message_get_body (message),
4986                    "(&s&sv)",
4987                    &interface_name,
4988                    &property_name,
4989                    NULL);
4990
4991   /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4992    * no such interface registered
4993    */
4994   ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4995   if (ei == NULL)
4996     {
4997       GDBusMessage *reply;
4998       reply = g_dbus_message_new_method_error (message,
4999                                                "org.freedesktop.DBus.Error.InvalidArgs",
5000                                                _("No such interface '%s'"),
5001                                                interface_name);
5002       g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5003       g_object_unref (reply);
5004       handled = TRUE;
5005       goto out;
5006     }
5007
5008   handled = validate_and_maybe_schedule_property_getset (eo->connection,
5009                                                          message,
5010                                                          ei->id,
5011                                                          0,
5012                                                          is_get,
5013                                                          ei->interface_info,
5014                                                          ei->vtable,
5015                                                          ei->context,
5016                                                          ei->user_data);
5017  out:
5018   return handled;
5019 }
5020
5021 /* ---------------------------------------------------------------------------------------------------- */
5022
5023 typedef struct
5024 {
5025   GDBusConnection *connection;
5026   GDBusMessage *message;
5027   gpointer user_data;
5028   const GDBusInterfaceVTable *vtable;
5029   GDBusInterfaceInfo *interface_info;
5030   guint registration_id;
5031   guint subtree_registration_id;
5032 } PropertyGetAllData;
5033
5034 static void
5035 property_get_all_data_free (PropertyData *data)
5036 {
5037   g_object_unref (data->connection);
5038   g_object_unref (data->message);
5039   g_free (data);
5040 }
5041
5042 /* called in thread where object was registered - no locks held */
5043 static gboolean
5044 invoke_get_all_properties_in_idle_cb (gpointer _data)
5045 {
5046   PropertyGetAllData *data = _data;
5047   GVariantBuilder builder;
5048   GDBusMessage *reply;
5049   guint n;
5050
5051   if (has_object_been_unregistered (data->connection,
5052                                     data->registration_id,
5053                                     data->subtree_registration_id))
5054     {
5055       reply = g_dbus_message_new_method_error (data->message,
5056                                                "org.freedesktop.DBus.Error.UnknownMethod",
5057                                                _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
5058                                                g_dbus_message_get_path (data->message));
5059       g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5060       g_object_unref (reply);
5061       goto out;
5062     }
5063
5064   /* TODO: Right now we never fail this call - we just omit values if
5065    *       a get_property() call is failing.
5066    *
5067    *       We could fail the whole call if just a single get_property() call
5068    *       returns an error. We need clarification in the D-Bus spec about this.
5069    */
5070   g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
5071   g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
5072   for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
5073     {
5074       const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
5075       GVariant *value;
5076
5077       if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
5078         continue;
5079
5080       value = data->vtable->get_property (data->connection,
5081                                           g_dbus_message_get_sender (data->message),
5082                                           g_dbus_message_get_path (data->message),
5083                                           data->interface_info->name,
5084                                           property_info->name,
5085                                           NULL,
5086                                           data->user_data);
5087
5088       if (value == NULL)
5089         continue;
5090
5091       g_variant_take_ref (value);
5092       g_variant_builder_add (&builder,
5093                              "{sv}",
5094                              property_info->name,
5095                              value);
5096       g_variant_unref (value);
5097     }
5098   g_variant_builder_close (&builder);
5099
5100   reply = g_dbus_message_new_method_reply (data->message);
5101   g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
5102   g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5103   g_object_unref (reply);
5104
5105  out:
5106   return FALSE;
5107 }
5108
5109 static gboolean
5110 interface_has_readable_properties (GDBusInterfaceInfo *interface_info)
5111 {
5112   gint i;
5113
5114   if (!interface_info->properties)
5115     return FALSE;
5116
5117   for (i = 0; interface_info->properties[i]; i++)
5118     if (interface_info->properties[i]->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE)
5119       return TRUE;
5120
5121   return FALSE;
5122 }
5123
5124 /* called in any thread with connection's lock held */
5125 static gboolean
5126 validate_and_maybe_schedule_property_get_all (GDBusConnection            *connection,
5127                                               GDBusMessage               *message,
5128                                               guint                       registration_id,
5129                                               guint                       subtree_registration_id,
5130                                               GDBusInterfaceInfo         *interface_info,
5131                                               const GDBusInterfaceVTable *vtable,
5132                                               GMainContext               *main_context,
5133                                               gpointer                    user_data)
5134 {
5135   gboolean handled;
5136   GSource *idle_source;
5137   PropertyGetAllData *property_get_all_data;
5138
5139   handled = FALSE;
5140
5141   if (vtable == NULL)
5142     goto out;
5143
5144   /* If the vtable pointer for get_property() is NULL but we have a
5145    * non-zero number of readable properties, then dispatch the call via
5146    * the method_call() handler.
5147    */
5148   if (vtable->get_property == NULL && interface_has_readable_properties (interface_info))
5149     {
5150       schedule_method_call (connection, message, registration_id, subtree_registration_id,
5151                             interface_info, NULL, NULL, g_dbus_message_get_body (message),
5152                             vtable, main_context, user_data);
5153       handled = TRUE;
5154       goto out;
5155     }
5156
5157   /* ok, got the property info - call user in an idle handler */
5158   property_get_all_data = g_new0 (PropertyGetAllData, 1);
5159   property_get_all_data->connection = g_object_ref (connection);
5160   property_get_all_data->message = g_object_ref (message);
5161   property_get_all_data->user_data = user_data;
5162   property_get_all_data->vtable = vtable;
5163   property_get_all_data->interface_info = interface_info;
5164   property_get_all_data->registration_id = registration_id;
5165   property_get_all_data->subtree_registration_id = subtree_registration_id;
5166
5167   idle_source = g_idle_source_new ();
5168   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
5169   g_source_set_callback (idle_source,
5170                          invoke_get_all_properties_in_idle_cb,
5171                          property_get_all_data,
5172                          (GDestroyNotify) property_get_all_data_free);
5173   g_source_set_name (idle_source, "[gio] invoke_get_all_properties_in_idle_cb");
5174   g_source_attach (idle_source, main_context);
5175   g_source_unref (idle_source);
5176
5177   handled = TRUE;
5178
5179  out:
5180   return handled;
5181 }
5182
5183 /* called in GDBusWorker thread with connection's lock held */
5184 static gboolean
5185 handle_get_all_properties (GDBusConnection *connection,
5186                            ExportedObject  *eo,
5187                            GDBusMessage    *message)
5188 {
5189   ExportedInterface *ei;
5190   gboolean handled;
5191   const char *interface_name;
5192
5193   handled = FALSE;
5194
5195   g_variant_get (g_dbus_message_get_body (message),
5196                  "(&s)",
5197                  &interface_name);
5198
5199   /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
5200    * no such interface registered
5201    */
5202   ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5203   if (ei == NULL)
5204     {
5205       GDBusMessage *reply;
5206       reply = g_dbus_message_new_method_error (message,
5207                                                "org.freedesktop.DBus.Error.InvalidArgs",
5208                                                _("No such interface"),
5209                                                interface_name);
5210       g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5211       g_object_unref (reply);
5212       handled = TRUE;
5213       goto out;
5214     }
5215
5216   handled = validate_and_maybe_schedule_property_get_all (eo->connection,
5217                                                           message,
5218                                                           ei->id,
5219                                                           0,
5220                                                           ei->interface_info,
5221                                                           ei->vtable,
5222                                                           ei->context,
5223                                                           ei->user_data);
5224  out:
5225   return handled;
5226 }
5227
5228 /* ---------------------------------------------------------------------------------------------------- */
5229
5230 static const gchar introspect_header[] =
5231   "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
5232   "                      \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
5233   "<!-- GDBus " PACKAGE_VERSION " -->\n"
5234   "<node>\n";
5235
5236 static const gchar introspect_tail[] =
5237   "</node>\n";
5238
5239 static const gchar introspect_properties_interface[] =
5240   "  <interface name=\"org.freedesktop.DBus.Properties\">\n"
5241   "    <method name=\"Get\">\n"
5242   "      <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
5243   "      <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
5244   "      <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
5245   "    </method>\n"
5246   "    <method name=\"GetAll\">\n"
5247   "      <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
5248   "      <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
5249   "    </method>\n"
5250   "    <method name=\"Set\">\n"
5251   "      <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
5252   "      <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
5253   "      <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
5254   "    </method>\n"
5255   "    <signal name=\"PropertiesChanged\">\n"
5256   "      <arg type=\"s\" name=\"interface_name\"/>\n"
5257   "      <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
5258   "      <arg type=\"as\" name=\"invalidated_properties\"/>\n"
5259   "    </signal>\n"
5260   "  </interface>\n";
5261
5262 static const gchar introspect_introspectable_interface[] =
5263   "  <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
5264   "    <method name=\"Introspect\">\n"
5265   "      <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
5266   "    </method>\n"
5267   "  </interface>\n"
5268   "  <interface name=\"org.freedesktop.DBus.Peer\">\n"
5269   "    <method name=\"Ping\"/>\n"
5270   "    <method name=\"GetMachineId\">\n"
5271   "      <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
5272   "    </method>\n"
5273   "  </interface>\n";
5274
5275 static void
5276 introspect_append_header (GString *s)
5277 {
5278   g_string_append (s, introspect_header);
5279 }
5280
5281 static void
5282 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
5283 {
5284   if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
5285     {
5286       const gchar *begin;
5287       const gchar *end;
5288       gchar *s;
5289
5290       begin = object_path + path_len;
5291       end = strchr (begin, '/');
5292       if (end != NULL)
5293         s = g_strndup (begin, end - begin);
5294       else
5295         s = g_strdup (begin);
5296
5297       if (g_hash_table_lookup (set, s) == NULL)
5298         g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
5299       else
5300         g_free (s);
5301     }
5302 }
5303
5304 /* TODO: we want a nicer public interface for this */
5305 /* called in any thread with connection's lock held */
5306 static gchar **
5307 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
5308                                             const gchar     *path)
5309 {
5310   GPtrArray *p;
5311   gchar **ret;
5312   GHashTableIter hash_iter;
5313   const gchar *object_path;
5314   gsize path_len;
5315   GHashTable *set;
5316   GList *keys;
5317   GList *l;
5318
5319   CONNECTION_ENSURE_LOCK (connection);
5320
5321   path_len = strlen (path);
5322   if (path_len > 1)
5323     path_len++;
5324
5325   set = g_hash_table_new (g_str_hash, g_str_equal);
5326
5327   g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
5328   while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
5329     maybe_add_path (path, path_len, object_path, set);
5330
5331   g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
5332   while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
5333     maybe_add_path (path, path_len, object_path, set);
5334
5335   p = g_ptr_array_new ();
5336   keys = g_hash_table_get_keys (set);
5337   for (l = keys; l != NULL; l = l->next)
5338     g_ptr_array_add (p, l->data);
5339   g_hash_table_unref (set);
5340   g_list_free (keys);
5341
5342   g_ptr_array_add (p, NULL);
5343   ret = (gchar **) g_ptr_array_free (p, FALSE);
5344   return ret;
5345 }
5346
5347 /* called in any thread with connection's lock not held */
5348 static gchar **
5349 g_dbus_connection_list_registered (GDBusConnection *connection,
5350                                    const gchar     *path)
5351 {
5352   gchar **ret;
5353   CONNECTION_LOCK (connection);
5354   ret = g_dbus_connection_list_registered_unlocked (connection, path);
5355   CONNECTION_UNLOCK (connection);
5356   return ret;
5357 }
5358
5359 /* called in GDBusWorker thread with connection's lock held */
5360 static gboolean
5361 handle_introspect (GDBusConnection *connection,
5362                    ExportedObject  *eo,
5363                    GDBusMessage    *message)
5364 {
5365   guint n;
5366   GString *s;
5367   GDBusMessage *reply;
5368   GHashTableIter hash_iter;
5369   ExportedInterface *ei;
5370   gchar **registered;
5371
5372   /* first the header with the standard interfaces */
5373   s = g_string_sized_new (sizeof (introspect_header) +
5374                           sizeof (introspect_properties_interface) +
5375                           sizeof (introspect_introspectable_interface) +
5376                           sizeof (introspect_tail));
5377   introspect_append_header (s);
5378   if (!g_hash_table_lookup (eo->map_if_name_to_ei,
5379                             "org.freedesktop.DBus.Properties"))
5380     g_string_append (s, introspect_properties_interface);
5381
5382   if (!g_hash_table_lookup (eo->map_if_name_to_ei,
5383                             "org.freedesktop.DBus.Introspectable"))
5384     g_string_append (s, introspect_introspectable_interface);
5385
5386   /* then include the registered interfaces */
5387   g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
5388   while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
5389     g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
5390
5391   /* finally include nodes registered below us */
5392   registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
5393   for (n = 0; registered != NULL && registered[n] != NULL; n++)
5394     g_string_append_printf (s, "  <node name=\"%s\"/>\n", registered[n]);
5395   g_strfreev (registered);
5396   g_string_append (s, introspect_tail);
5397
5398   reply = g_dbus_message_new_method_reply (message);
5399   g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5400   g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5401   g_object_unref (reply);
5402   g_string_free (s, TRUE);
5403
5404   return TRUE;
5405 }
5406
5407 /* called in thread where object was registered - no locks held */
5408 static gboolean
5409 call_in_idle_cb (gpointer user_data)
5410 {
5411   GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
5412   GDBusInterfaceVTable *vtable;
5413   guint registration_id;
5414   guint subtree_registration_id;
5415
5416   registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
5417   subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
5418
5419   if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
5420                                     registration_id,
5421                                     subtree_registration_id))
5422     {
5423       GDBusMessage *reply;
5424       reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
5425                                                "org.freedesktop.DBus.Error.UnknownMethod",
5426                                                _("No such interface '%s' on object at path %s"),
5427                                                g_dbus_method_invocation_get_interface_name (invocation),
5428                                                g_dbus_method_invocation_get_object_path (invocation));
5429       g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5430       g_object_unref (reply);
5431       goto out;
5432     }
5433
5434   vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
5435   g_assert (vtable != NULL && vtable->method_call != NULL);
5436
5437   vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
5438                        g_dbus_method_invocation_get_sender (invocation),
5439                        g_dbus_method_invocation_get_object_path (invocation),
5440                        g_dbus_method_invocation_get_interface_name (invocation),
5441                        g_dbus_method_invocation_get_method_name (invocation),
5442                        g_dbus_method_invocation_get_parameters (invocation),
5443                        g_object_ref (invocation),
5444                        g_dbus_method_invocation_get_user_data (invocation));
5445
5446  out:
5447   return FALSE;
5448 }
5449
5450 /* called in GDBusWorker thread with connection's lock held */
5451 static void
5452 schedule_method_call (GDBusConnection            *connection,
5453                       GDBusMessage               *message,
5454                       guint                       registration_id,
5455                       guint                       subtree_registration_id,
5456                       const GDBusInterfaceInfo   *interface_info,
5457                       const GDBusMethodInfo      *method_info,
5458                       const GDBusPropertyInfo    *property_info,
5459                       GVariant                   *parameters,
5460                       const GDBusInterfaceVTable *vtable,
5461                       GMainContext               *main_context,
5462                       gpointer                    user_data)
5463 {
5464   GDBusMethodInvocation *invocation;
5465   GSource *idle_source;
5466
5467   invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
5468                                               g_dbus_message_get_path (message),
5469                                               g_dbus_message_get_interface (message),
5470                                               g_dbus_message_get_member (message),
5471                                               method_info,
5472                                               property_info,
5473                                               connection,
5474                                               message,
5475                                               parameters,
5476                                               user_data);
5477
5478   /* TODO: would be nicer with a real MethodData like we already
5479    * have PropertyData and PropertyGetAllData... */
5480   g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
5481   g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
5482   g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
5483
5484   idle_source = g_idle_source_new ();
5485   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
5486   g_source_set_callback (idle_source,
5487                          call_in_idle_cb,
5488                          invocation,
5489                          g_object_unref);
5490   g_source_set_name (idle_source, "[gio] call_in_idle_cb");
5491   g_source_attach (idle_source, main_context);
5492   g_source_unref (idle_source);
5493 }
5494
5495 /* called in GDBusWorker thread with connection's lock held */
5496 static gboolean
5497 validate_and_maybe_schedule_method_call (GDBusConnection            *connection,
5498                                          GDBusMessage               *message,
5499                                          guint                       registration_id,
5500                                          guint                       subtree_registration_id,
5501                                          GDBusInterfaceInfo         *interface_info,
5502                                          const GDBusInterfaceVTable *vtable,
5503                                          GMainContext               *main_context,
5504                                          gpointer                    user_data)
5505 {
5506   GDBusMethodInfo *method_info;
5507   GDBusMessage *reply;
5508   GVariant *parameters;
5509   gboolean handled;
5510   GVariantType *in_type;
5511
5512   handled = FALSE;
5513
5514   /* TODO: the cost of this is O(n) - it might be worth caching the result */
5515   method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
5516
5517   /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
5518    * error to the caller
5519    */
5520   if (method_info == NULL)
5521     {
5522       reply = g_dbus_message_new_method_error (message,
5523                                                "org.freedesktop.DBus.Error.UnknownMethod",
5524                                                _("No such method '%s'"),
5525                                                g_dbus_message_get_member (message));
5526       g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5527       g_object_unref (reply);
5528       handled = TRUE;
5529       goto out;
5530     }
5531
5532   parameters = g_dbus_message_get_body (message);
5533   if (parameters == NULL)
5534     {
5535       parameters = g_variant_new ("()");
5536       g_variant_ref_sink (parameters);
5537     }
5538   else
5539     {
5540       g_variant_ref (parameters);
5541     }
5542
5543   /* Check that the incoming args are of the right type - if they are not, return
5544    * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
5545    */
5546   in_type = _g_dbus_compute_complete_signature (method_info->in_args);
5547   if (!g_variant_is_of_type (parameters, in_type))
5548     {
5549       gchar *type_string;
5550
5551       type_string = g_variant_type_dup_string (in_type);
5552
5553       reply = g_dbus_message_new_method_error (message,
5554                                                "org.freedesktop.DBus.Error.InvalidArgs",
5555                                                _("Type of message, '%s', does not match expected type '%s'"),
5556                                                g_variant_get_type_string (parameters),
5557                                                type_string);
5558       g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5559       g_variant_type_free (in_type);
5560       g_variant_unref (parameters);
5561       g_object_unref (reply);
5562       g_free (type_string);
5563       handled = TRUE;
5564       goto out;
5565     }
5566   g_variant_type_free (in_type);
5567
5568   /* schedule the call in idle */
5569   schedule_method_call (connection, message, registration_id, subtree_registration_id,
5570                         interface_info, method_info, NULL, parameters,
5571                         vtable, main_context, user_data);
5572   g_variant_unref (parameters);
5573   handled = TRUE;
5574
5575  out:
5576   return handled;
5577 }
5578
5579 /* ---------------------------------------------------------------------------------------------------- */
5580
5581 /* called in GDBusWorker thread with connection's lock held */
5582 static gboolean
5583 obj_message_func (GDBusConnection *connection,
5584                   ExportedObject  *eo,
5585                   GDBusMessage    *message)
5586 {
5587   const gchar *interface_name;
5588   const gchar *member;
5589   const gchar *signature;
5590   gboolean handled;
5591
5592   handled = FALSE;
5593
5594   interface_name = g_dbus_message_get_interface (message);
5595   member = g_dbus_message_get_member (message);
5596   signature = g_dbus_message_get_signature (message);
5597
5598   /* see if we have an interface for handling this call */
5599   if (interface_name != NULL)
5600     {
5601       ExportedInterface *ei;
5602       ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5603       if (ei != NULL)
5604         {
5605           /* we do - invoke the handler in idle in the right thread */
5606
5607           /* handle no vtable or handler being present */
5608           if (ei->vtable == NULL || ei->vtable->method_call == NULL)
5609             goto out;
5610
5611           handled = validate_and_maybe_schedule_method_call (connection,
5612                                                              message,
5613                                                              ei->id,
5614                                                              0,
5615                                                              ei->interface_info,
5616                                                              ei->vtable,
5617                                                              ei->context,
5618                                                              ei->user_data);
5619           goto out;
5620         }
5621     }
5622
5623   if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5624       g_strcmp0 (member, "Introspect") == 0 &&
5625       g_strcmp0 (signature, "") == 0)
5626     {
5627       handled = handle_introspect (connection, eo, message);
5628       goto out;
5629     }
5630   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5631            g_strcmp0 (member, "Get") == 0 &&
5632            g_strcmp0 (signature, "ss") == 0)
5633     {
5634       handled = handle_getset_property (connection, eo, message, TRUE);
5635       goto out;
5636     }
5637   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5638            g_strcmp0 (member, "Set") == 0 &&
5639            g_strcmp0 (signature, "ssv") == 0)
5640     {
5641       handled = handle_getset_property (connection, eo, message, FALSE);
5642       goto out;
5643     }
5644   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5645            g_strcmp0 (member, "GetAll") == 0 &&
5646            g_strcmp0 (signature, "s") == 0)
5647     {
5648       handled = handle_get_all_properties (connection, eo, message);
5649       goto out;
5650     }
5651
5652  out:
5653   return handled;
5654 }
5655
5656 /**
5657  * g_dbus_connection_register_object:
5658  * @connection: a #GDBusConnection
5659  * @object_path: the object path to register at
5660  * @interface_info: introspection data for the interface
5661  * @vtable: (allow-none): a #GDBusInterfaceVTable to call into or %NULL
5662  * @user_data: (allow-none): data to pass to functions in @vtable
5663  * @user_data_free_func: function to call when the object path is unregistered
5664  * @error: return location for error or %NULL
5665  *
5666  * Registers callbacks for exported objects at @object_path with the
5667  * D-Bus interface that is described in @interface_info.
5668  *
5669  * Calls to functions in @vtable (and @user_data_free_func) will happen
5670  * in the 
5671  * [thread-default main context][g-main-context-push-thread-default]
5672  * of the thread you are calling this method from.
5673  *
5674  * Note that all #GVariant values passed to functions in @vtable will match
5675  * the signature given in @interface_info - if a remote caller passes
5676  * incorrect values, the `org.freedesktop.DBus.Error.InvalidArgs`
5677  * is returned to the remote caller.
5678  *
5679  * Additionally, if the remote caller attempts to invoke methods or
5680  * access properties not mentioned in @interface_info the
5681  * `org.freedesktop.DBus.Error.UnknownMethod` resp.
5682  * `org.freedesktop.DBus.Error.InvalidArgs` errors
5683  * are returned to the caller.
5684  *
5685  * It is considered a programming error if the
5686  * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
5687  * #GVariant of incorrect type.
5688  *
5689  * If an existing callback is already registered at @object_path and
5690  * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
5691  *
5692  * GDBus automatically implements the standard D-Bus interfaces
5693  * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
5694  * and org.freedesktop.Peer, so you don't have to implement those for the
5695  * objects you export. You can implement org.freedesktop.DBus.Properties
5696  * yourself, e.g. to handle getting and setting of properties asynchronously.
5697  *
5698  * Note that the reference count on @interface_info will be
5699  * incremented by 1 (unless allocated statically, e.g. if the
5700  * reference count is -1, see g_dbus_interface_info_ref()) for as long
5701  * as the object is exported. Also note that @vtable will be copied.
5702  *
5703  * See this [server][gdbus-server] for an example of how to use this method.
5704  *
5705  * Returns: 0 if @error is set, otherwise a registration id (never 0)
5706  *     that can be used with g_dbus_connection_unregister_object()
5707  *
5708  * Since: 2.26
5709  */
5710 guint
5711 g_dbus_connection_register_object (GDBusConnection             *connection,
5712                                    const gchar                 *object_path,
5713                                    GDBusInterfaceInfo          *interface_info,
5714                                    const GDBusInterfaceVTable  *vtable,
5715                                    gpointer                     user_data,
5716                                    GDestroyNotify               user_data_free_func,
5717                                    GError                     **error)
5718 {
5719   ExportedObject *eo;
5720   ExportedInterface *ei;
5721   guint ret;
5722
5723   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5724   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5725   g_return_val_if_fail (interface_info != NULL, 0);
5726   g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
5727   g_return_val_if_fail (error == NULL || *error == NULL, 0);
5728   g_return_val_if_fail (check_initialized (connection), 0);
5729
5730   ret = 0;
5731
5732   CONNECTION_LOCK (connection);
5733
5734   eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
5735   if (eo == NULL)
5736     {
5737       eo = g_new0 (ExportedObject, 1);
5738       eo->object_path = g_strdup (object_path);
5739       eo->connection = connection;
5740       eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
5741                                                      g_str_equal,
5742                                                      NULL,
5743                                                      (GDestroyNotify) exported_interface_free);
5744       g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
5745     }
5746
5747   ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
5748   if (ei != NULL)
5749     {
5750       g_set_error (error,
5751                    G_IO_ERROR,
5752                    G_IO_ERROR_EXISTS,
5753                    _("An object is already exported for the interface %s at %s"),
5754                    interface_info->name,
5755                    object_path);
5756       goto out;
5757     }
5758
5759   ei = g_new0 (ExportedInterface, 1);
5760   ei->id = _global_registration_id++; /* TODO: overflow etc. */
5761   ei->eo = eo;
5762   ei->user_data = user_data;
5763   ei->user_data_free_func = user_data_free_func;
5764   ei->vtable = _g_dbus_interface_vtable_copy (vtable);
5765   ei->interface_info = g_dbus_interface_info_ref (interface_info);
5766   g_dbus_interface_info_cache_build (ei->interface_info);
5767   ei->interface_name = g_strdup (interface_info->name);
5768   ei->context = g_main_context_ref_thread_default ();
5769
5770   g_hash_table_insert (eo->map_if_name_to_ei,
5771                        (gpointer) ei->interface_name,
5772                        ei);
5773   g_hash_table_insert (connection->map_id_to_ei,
5774                        GUINT_TO_POINTER (ei->id),
5775                        ei);
5776
5777   ret = ei->id;
5778
5779  out:
5780   CONNECTION_UNLOCK (connection);
5781
5782   return ret;
5783 }
5784
5785 /**
5786  * g_dbus_connection_unregister_object:
5787  * @connection: a #GDBusConnection
5788  * @registration_id: a registration id obtained from
5789  *     g_dbus_connection_register_object()
5790  *
5791  * Unregisters an object.
5792  *
5793  * Returns: %TRUE if the object was unregistered, %FALSE otherwise
5794  *
5795  * Since: 2.26
5796  */
5797 gboolean
5798 g_dbus_connection_unregister_object (GDBusConnection *connection,
5799                                      guint            registration_id)
5800 {
5801   ExportedInterface *ei;
5802   ExportedObject *eo;
5803   gboolean ret;
5804
5805   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5806   g_return_val_if_fail (check_initialized (connection), FALSE);
5807
5808   ret = FALSE;
5809
5810   CONNECTION_LOCK (connection);
5811
5812   ei = g_hash_table_lookup (connection->map_id_to_ei,
5813                             GUINT_TO_POINTER (registration_id));
5814   if (ei == NULL)
5815     goto out;
5816
5817   eo = ei->eo;
5818
5819   g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5820   g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5821   /* unregister object path if we have no more exported interfaces */
5822   if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5823     g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5824                                          eo->object_path));
5825
5826   ret = TRUE;
5827
5828  out:
5829   CONNECTION_UNLOCK (connection);
5830
5831   return ret;
5832 }
5833
5834 /* ---------------------------------------------------------------------------------------------------- */
5835
5836 /**
5837  * g_dbus_connection_emit_signal:
5838  * @connection: a #GDBusConnection
5839  * @destination_bus_name: (allow-none): the unique bus name for the destination
5840  *     for the signal or %NULL to emit to all listeners
5841  * @object_path: path of remote object
5842  * @interface_name: D-Bus interface to emit a signal on
5843  * @signal_name: the name of the signal to emit
5844  * @parameters: (allow-none): a #GVariant tuple with parameters for the signal
5845  *              or %NULL if not passing parameters
5846  * @error: Return location for error or %NULL
5847  *
5848  * Emits a signal.
5849  *
5850  * If the parameters GVariant is floating, it is consumed.
5851  *
5852  * This can only fail if @parameters is not compatible with the D-Bus protocol.
5853  *
5854  * Returns: %TRUE unless @error is set
5855  *
5856  * Since: 2.26
5857  */
5858 gboolean
5859 g_dbus_connection_emit_signal (GDBusConnection  *connection,
5860                                const gchar      *destination_bus_name,
5861                                const gchar      *object_path,
5862                                const gchar      *interface_name,
5863                                const gchar      *signal_name,
5864                                GVariant         *parameters,
5865                                GError          **error)
5866 {
5867   GDBusMessage *message;
5868   gboolean ret;
5869
5870   message = NULL;
5871   ret = FALSE;
5872
5873   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5874   g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5875   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5876   g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5877   g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5878   g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5879   g_return_val_if_fail (check_initialized (connection), FALSE);
5880
5881   if (G_UNLIKELY (_g_dbus_debug_emission ()))
5882     {
5883       _g_dbus_debug_print_lock ();
5884       g_print ("========================================================================\n"
5885                "GDBus-debug:Emission:\n"
5886                " >>>> SIGNAL EMISSION %s.%s()\n"
5887                "      on object %s\n"
5888                "      destination %s\n",
5889                interface_name, signal_name,
5890                object_path,
5891                destination_bus_name != NULL ? destination_bus_name : "(none)");
5892       _g_dbus_debug_print_unlock ();
5893     }
5894
5895   message = g_dbus_message_new_signal (object_path,
5896                                        interface_name,
5897                                        signal_name);
5898
5899   if (destination_bus_name != NULL)
5900     g_dbus_message_set_header (message,
5901                                G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5902                                g_variant_new_string (destination_bus_name));
5903
5904   if (parameters != NULL)
5905     g_dbus_message_set_body (message, parameters);
5906
5907   ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5908   g_object_unref (message);
5909
5910   return ret;
5911 }
5912
5913 static void
5914 add_call_flags (GDBusMessage           *message,
5915                          GDBusCallFlags  flags)
5916 {
5917   if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5918     g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
5919 }
5920
5921 static GVariant *
5922 decode_method_reply (GDBusMessage        *reply,
5923                      const gchar         *method_name,
5924                      const GVariantType  *reply_type,
5925                      GUnixFDList        **out_fd_list,
5926                      GError             **error)
5927 {
5928   GVariant *result;
5929
5930   result = NULL;
5931   switch (g_dbus_message_get_message_type (reply))
5932     {
5933     case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5934       result = g_dbus_message_get_body (reply);
5935       if (result == NULL)
5936         {
5937           result = g_variant_new ("()");
5938           g_variant_ref_sink (result);
5939         }
5940       else
5941         {
5942           g_variant_ref (result);
5943         }
5944
5945       if (!g_variant_is_of_type (result, reply_type))
5946         {
5947           gchar *type_string = g_variant_type_dup_string (reply_type);
5948
5949           g_set_error (error,
5950                        G_IO_ERROR,
5951                        G_IO_ERROR_INVALID_ARGUMENT,
5952                        _("Method '%s' returned type '%s', but expected '%s'"),
5953                        method_name, g_variant_get_type_string (result), type_string);
5954
5955           g_variant_unref (result);
5956           g_free (type_string);
5957           result = NULL;
5958         }
5959
5960 #ifdef G_OS_UNIX
5961       if (result != NULL)
5962         {
5963           if (out_fd_list != NULL)
5964             {
5965               *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5966               if (*out_fd_list != NULL)
5967                 g_object_ref (*out_fd_list);
5968             }
5969         }
5970 #endif
5971       break;
5972
5973     case G_DBUS_MESSAGE_TYPE_ERROR:
5974       g_dbus_message_to_gerror (reply, error);
5975       break;
5976
5977     default:
5978       g_assert_not_reached ();
5979       break;
5980     }
5981
5982   return result;
5983 }
5984
5985
5986 typedef struct
5987 {
5988   GSimpleAsyncResult *simple;
5989   GVariantType *reply_type;
5990   gchar *method_name; /* for error message */
5991   guint32 serial;
5992
5993   GVariant *value;
5994   GUnixFDList *fd_list;
5995 } CallState;
5996
5997 static void
5998 call_state_free (CallState *state)
5999 {
6000   g_variant_type_free (state->reply_type);
6001   g_free (state->method_name);
6002
6003   if (state->value != NULL)
6004     g_variant_unref (state->value);
6005   if (state->fd_list != NULL)
6006     g_object_unref (state->fd_list);
6007   g_slice_free (CallState, state);
6008 }
6009
6010 /* called in any thread, with the connection's lock not held */
6011 static void
6012 g_dbus_connection_call_done (GObject      *source,
6013                              GAsyncResult *result,
6014                              gpointer      user_data)
6015 {
6016   GSimpleAsyncResult *simple;
6017   GDBusConnection *connection = G_DBUS_CONNECTION (source);
6018   CallState *state = user_data;
6019   GError *error;
6020   GDBusMessage *reply;
6021
6022   error = NULL;
6023   reply = g_dbus_connection_send_message_with_reply_finish (connection,
6024                                                             result,
6025                                                             &error);
6026
6027   if (G_UNLIKELY (_g_dbus_debug_call ()))
6028     {
6029       _g_dbus_debug_print_lock ();
6030       g_print ("========================================================================\n"
6031                "GDBus-debug:Call:\n"
6032                " <<<< ASYNC COMPLETE %s() (serial %d)\n"
6033                "      ",
6034                state->method_name,
6035                state->serial);
6036       if (reply != NULL)
6037         {
6038           g_print ("SUCCESS\n");
6039         }
6040       else
6041         {
6042           g_print ("FAILED: %s\n",
6043                    error->message);
6044         }
6045       _g_dbus_debug_print_unlock ();
6046     }
6047
6048   if (reply != NULL)
6049     state->value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
6050
6051   simple = state->simple; /* why? because state is freed before we unref simple.. */
6052   if (error != NULL)
6053     {
6054       g_simple_async_result_take_error (state->simple, error);
6055       g_simple_async_result_complete (state->simple);
6056       call_state_free (state);
6057     }
6058   else
6059     {
6060       g_simple_async_result_set_op_res_gpointer (state->simple, state, (GDestroyNotify) call_state_free);
6061       g_simple_async_result_complete (state->simple);
6062     }
6063   g_clear_object (&reply);
6064   g_object_unref (simple);
6065 }
6066
6067 /* called in any thread, with the connection's lock not held */
6068 static void
6069 g_dbus_connection_call_internal (GDBusConnection        *connection,
6070                                  const gchar            *bus_name,
6071                                  const gchar            *object_path,
6072                                  const gchar            *interface_name,
6073                                  const gchar            *method_name,
6074                                  GVariant               *parameters,
6075                                  const GVariantType     *reply_type,
6076                                  GDBusCallFlags          flags,
6077                                  gint                    timeout_msec,
6078                                  GUnixFDList            *fd_list,
6079                                  GCancellable           *cancellable,
6080                                  GAsyncReadyCallback     callback,
6081                                  gpointer                user_data)
6082 {
6083   GDBusMessage *message;
6084   guint32 serial;
6085
6086   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
6087   g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
6088   g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
6089   g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
6090   g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
6091   g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
6092   g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
6093   g_return_if_fail (check_initialized (connection));
6094 #ifdef G_OS_UNIX
6095   g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
6096 #else
6097   g_return_if_fail (fd_list == NULL);
6098 #endif
6099
6100   message = g_dbus_message_new_method_call (bus_name,
6101                                             object_path,
6102                                             interface_name,
6103                                             method_name);
6104   add_call_flags (message, flags);
6105   if (parameters != NULL)
6106     g_dbus_message_set_body (message, parameters);
6107
6108 #ifdef G_OS_UNIX
6109   if (fd_list != NULL)
6110     g_dbus_message_set_unix_fd_list (message, fd_list);
6111 #endif
6112
6113   /* If the user has no callback then we can just send the message with
6114    * the G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set and skip all
6115    * the logic for processing the reply.  If the service sends the reply
6116    * anyway then it will just be ignored.
6117    */
6118   if (callback != NULL)
6119     {
6120       CallState *state;
6121
6122       state = g_slice_new0 (CallState);
6123       state->simple = g_simple_async_result_new (G_OBJECT (connection),
6124                                                  callback, user_data,
6125                                                  g_dbus_connection_call_internal);
6126       g_simple_async_result_set_check_cancellable (state->simple, cancellable);
6127       state->method_name = g_strjoin (".", interface_name, method_name, NULL);
6128
6129       if (reply_type == NULL)
6130         reply_type = G_VARIANT_TYPE_ANY;
6131
6132       state->reply_type = g_variant_type_copy (reply_type);
6133
6134       g_dbus_connection_send_message_with_reply (connection,
6135                                                  message,
6136                                                  G_DBUS_SEND_MESSAGE_FLAGS_NONE,
6137                                                  timeout_msec,
6138                                                  &state->serial,
6139                                                  cancellable,
6140                                                  g_dbus_connection_call_done,
6141                                                  state);
6142       serial = state->serial;
6143     }
6144   else
6145     {
6146       GDBusMessageFlags flags;
6147
6148       flags = g_dbus_message_get_flags (message);
6149       flags |= G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
6150       g_dbus_message_set_flags (message, flags);
6151
6152       g_dbus_connection_send_message (connection,
6153                                       message,
6154                                       G_DBUS_SEND_MESSAGE_FLAGS_NONE,
6155                                       &serial, NULL);
6156     }
6157
6158   if (G_UNLIKELY (_g_dbus_debug_call ()))
6159     {
6160       _g_dbus_debug_print_lock ();
6161       g_print ("========================================================================\n"
6162                "GDBus-debug:Call:\n"
6163                " >>>> ASYNC %s.%s()\n"
6164                "      on object %s\n"
6165                "      owned by name %s (serial %d)\n",
6166                interface_name,
6167                method_name,
6168                object_path,
6169                bus_name != NULL ? bus_name : "(none)",
6170                serial);
6171       _g_dbus_debug_print_unlock ();
6172     }
6173
6174   if (message != NULL)
6175     g_object_unref (message);
6176 }
6177
6178 /* called in any thread, with the connection's lock not held */
6179 static GVariant *
6180 g_dbus_connection_call_finish_internal (GDBusConnection  *connection,
6181                                         GUnixFDList     **out_fd_list,
6182                                         GAsyncResult     *res,
6183                                         GError          **error)
6184 {
6185   GSimpleAsyncResult *simple;
6186   CallState *state;
6187
6188   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
6189   g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
6190                                                         g_dbus_connection_call_internal), NULL);
6191   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6192
6193   simple = G_SIMPLE_ASYNC_RESULT (res);
6194
6195   if (g_simple_async_result_propagate_error (simple, error))
6196     return NULL;
6197
6198   state = g_simple_async_result_get_op_res_gpointer (simple);
6199   if (out_fd_list != NULL)
6200     *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
6201   return g_variant_ref (state->value);
6202 }
6203
6204 /* called in any user thread, with the connection's lock not held */
6205 static GVariant *
6206 g_dbus_connection_call_sync_internal (GDBusConnection         *connection,
6207                                       const gchar             *bus_name,
6208                                       const gchar             *object_path,
6209                                       const gchar             *interface_name,
6210                                       const gchar             *method_name,
6211                                       GVariant                *parameters,
6212                                       const GVariantType      *reply_type,
6213                                       GDBusCallFlags           flags,
6214                                       gint                     timeout_msec,
6215                                       GUnixFDList             *fd_list,
6216                                       GUnixFDList            **out_fd_list,
6217                                       GCancellable            *cancellable,
6218                                       GError                 **error)
6219 {
6220   GDBusMessage *message;
6221   GDBusMessage *reply;
6222   GVariant *result;
6223   GError *local_error;
6224   GDBusSendMessageFlags send_flags;
6225
6226   message = NULL;
6227   reply = NULL;
6228   result = NULL;
6229
6230   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
6231   g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
6232   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
6233   g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
6234   g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
6235   g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
6236   g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
6237 #ifdef G_OS_UNIX
6238   g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
6239 #else
6240   g_return_val_if_fail (fd_list == NULL, NULL);
6241 #endif
6242   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6243
6244   if (!(flags & CALL_FLAGS_INITIALIZING))
6245     g_return_val_if_fail (check_initialized (connection), FALSE);
6246
6247   if (reply_type == NULL)
6248     reply_type = G_VARIANT_TYPE_ANY;
6249
6250   message = g_dbus_message_new_method_call (bus_name,
6251                                             object_path,
6252                                             interface_name,
6253                                             method_name);
6254   add_call_flags (message, flags);
6255   if (parameters != NULL)
6256     g_dbus_message_set_body (message, parameters);
6257
6258 #ifdef G_OS_UNIX
6259   if (fd_list != NULL)
6260     g_dbus_message_set_unix_fd_list (message, fd_list);
6261 #endif
6262
6263   if (G_UNLIKELY (_g_dbus_debug_call ()))
6264     {
6265       _g_dbus_debug_print_lock ();
6266       g_print ("========================================================================\n"
6267                "GDBus-debug:Call:\n"
6268                " >>>> SYNC %s.%s()\n"
6269                "      on object %s\n"
6270                "      owned by name %s\n",
6271                interface_name,
6272                method_name,
6273                object_path,
6274                bus_name != NULL ? bus_name : "(none)");
6275       _g_dbus_debug_print_unlock ();
6276     }
6277
6278   local_error = NULL;
6279
6280   send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
6281
6282   /* translate from one flavour of flags to another... */
6283   if (flags & CALL_FLAGS_INITIALIZING)
6284     send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
6285
6286   reply = g_dbus_connection_send_message_with_reply_sync (connection,
6287                                                           message,
6288                                                           send_flags,
6289                                                           timeout_msec,
6290                                                           NULL, /* volatile guint32 *out_serial */
6291                                                           cancellable,
6292                                                           &local_error);
6293
6294   if (G_UNLIKELY (_g_dbus_debug_call ()))
6295     {
6296       _g_dbus_debug_print_lock ();
6297       g_print ("========================================================================\n"
6298                "GDBus-debug:Call:\n"
6299                " <<<< SYNC COMPLETE %s.%s()\n"
6300                "      ",
6301                interface_name,
6302                method_name);
6303       if (reply != NULL)
6304         {
6305           g_print ("SUCCESS\n");
6306         }
6307       else
6308         {
6309           g_print ("FAILED: %s\n",
6310                    local_error->message);
6311         }
6312       _g_dbus_debug_print_unlock ();
6313     }
6314
6315   if (reply == NULL)
6316     {
6317       if (error != NULL)
6318         *error = local_error;
6319       else
6320         g_error_free (local_error);
6321       goto out;
6322     }
6323
6324   result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
6325
6326  out:
6327   if (message != NULL)
6328     g_object_unref (message);
6329   if (reply != NULL)
6330     g_object_unref (reply);
6331
6332   return result;
6333 }
6334
6335 /* ---------------------------------------------------------------------------------------------------- */
6336
6337 /**
6338  * g_dbus_connection_call:
6339  * @connection: a #GDBusConnection
6340  * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
6341  *     @connection is not a message bus connection
6342  * @object_path: path of remote object
6343  * @interface_name: D-Bus interface to invoke method on
6344  * @method_name: the name of the method to invoke
6345  * @parameters: (allow-none): a #GVariant tuple with parameters for the method
6346  *     or %NULL if not passing parameters
6347  * @reply_type: (allow-none): the expected type of the reply, or %NULL
6348  * @flags: flags from the #GDBusCallFlags enumeration
6349  * @timeout_msec: the timeout in milliseconds, -1 to use the default
6350  *     timeout or %G_MAXINT for no timeout
6351  * @cancellable: (allow-none): a #GCancellable or %NULL
6352  * @callback: (allow-none): a #GAsyncReadyCallback to call when the request
6353  *     is satisfied or %NULL if you don't care about the result of the
6354  *     method invocation
6355  * @user_data: the data to pass to @callback
6356  *
6357  * Asynchronously invokes the @method_name method on the
6358  * @interface_name D-Bus interface on the remote object at
6359  * @object_path owned by @bus_name.
6360  *
6361  * If @connection is closed then the operation will fail with
6362  * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
6363  * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
6364  * not compatible with the D-Bus protocol, the operation fails with
6365  * %G_IO_ERROR_INVALID_ARGUMENT.
6366  *
6367  * If @reply_type is non-%NULL then the reply will be checked for having this type and an
6368  * error will be raised if it does not match.  Said another way, if you give a @reply_type
6369  * then any non-%NULL return value will be of this type.
6370  *
6371  * If the @parameters #GVariant is floating, it is consumed. This allows
6372  * convenient 'inline' use of g_variant_new(), e.g.:
6373  * |[<!-- language="C" -->
6374  *  g_dbus_connection_call (connection,
6375  *                          "org.freedesktop.StringThings",
6376  *                          "/org/freedesktop/StringThings",
6377  *                          "org.freedesktop.StringThings",
6378  *                          "TwoStrings",
6379  *                          g_variant_new ("(ss)",
6380  *                                         "Thing One",
6381  *                                         "Thing Two"),
6382  *                          NULL,
6383  *                          G_DBUS_CALL_FLAGS_NONE,
6384  *                          -1,
6385  *                          NULL,
6386  *                          (GAsyncReadyCallback) two_strings_done,
6387  *                          NULL);
6388  * ]|
6389  *
6390  * This is an asynchronous method. When the operation is finished,
6391  * @callback will be invoked in the
6392  * [thread-default main context][g-main-context-push-thread-default]
6393  * of the thread you are calling this method from. You can then call
6394  * g_dbus_connection_call_finish() to get the result of the operation.
6395  * See g_dbus_connection_call_sync() for the synchronous version of this
6396  * function.
6397  *
6398  * If @callback is %NULL then the D-Bus method call message will be sent with
6399  * the %G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set.
6400  *
6401  * Since: 2.26
6402  */
6403 void
6404 g_dbus_connection_call (GDBusConnection     *connection,
6405                         const gchar         *bus_name,
6406                         const gchar         *object_path,
6407                         const gchar         *interface_name,
6408                         const gchar         *method_name,
6409                         GVariant            *parameters,
6410                         const GVariantType  *reply_type,
6411                         GDBusCallFlags       flags,
6412                         gint                 timeout_msec,
6413                         GCancellable        *cancellable,
6414                         GAsyncReadyCallback  callback,
6415                         gpointer             user_data)
6416 {
6417   g_dbus_connection_call_internal (connection, bus_name, object_path, interface_name, method_name, parameters, reply_type, flags, timeout_msec, NULL, cancellable, callback, user_data);
6418 }
6419
6420 /**
6421  * g_dbus_connection_call_finish:
6422  * @connection: a #GDBusConnection
6423  * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call()
6424  * @error: return location for error or %NULL
6425  *
6426  * Finishes an operation started with g_dbus_connection_call().
6427  *
6428  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6429  *     return values. Free with g_variant_unref().
6430  *
6431  * Since: 2.26
6432  */
6433 GVariant *
6434 g_dbus_connection_call_finish (GDBusConnection  *connection,
6435                                GAsyncResult     *res,
6436                                GError          **error)
6437 {
6438   return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
6439 }
6440
6441 /**
6442  * g_dbus_connection_call_sync:
6443  * @connection: a #GDBusConnection
6444  * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
6445  *     @connection is not a message bus connection
6446  * @object_path: path of remote object
6447  * @interface_name: D-Bus interface to invoke method on
6448  * @method_name: the name of the method to invoke
6449  * @parameters: (allow-none): a #GVariant tuple with parameters for the method
6450  *     or %NULL if not passing parameters
6451  * @reply_type: (allow-none): the expected type of the reply, or %NULL
6452  * @flags: flags from the #GDBusCallFlags enumeration
6453  * @timeout_msec: the timeout in milliseconds, -1 to use the default
6454  *     timeout or %G_MAXINT for no timeout
6455  * @cancellable: (allow-none): a #GCancellable or %NULL
6456  * @error: return location for error or %NULL
6457  *
6458  * Synchronously invokes the @method_name method on the
6459  * @interface_name D-Bus interface on the remote object at
6460  * @object_path owned by @bus_name.
6461  *
6462  * If @connection is closed then the operation will fail with
6463  * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
6464  * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
6465  * contains a value not compatible with the D-Bus protocol, the operation
6466  * fails with %G_IO_ERROR_INVALID_ARGUMENT.
6467
6468  * If @reply_type is non-%NULL then the reply will be checked for having
6469  * this type and an error will be raised if it does not match.  Said
6470  * another way, if you give a @reply_type then any non-%NULL return
6471  * value will be of this type.
6472  *
6473  * If the @parameters #GVariant is floating, it is consumed.
6474  * This allows convenient 'inline' use of g_variant_new(), e.g.:
6475  * |[<!-- language="C" -->
6476  *  g_dbus_connection_call_sync (connection,
6477  *                               "org.freedesktop.StringThings",
6478  *                               "/org/freedesktop/StringThings",
6479  *                               "org.freedesktop.StringThings",
6480  *                               "TwoStrings",
6481  *                               g_variant_new ("(ss)",
6482  *                                              "Thing One",
6483  *                                              "Thing Two"),
6484  *                               NULL,
6485  *                               G_DBUS_CALL_FLAGS_NONE,
6486  *                               -1,
6487  *                               NULL,
6488  *                               &error);
6489  * ]|
6490  *
6491  * The calling thread is blocked until a reply is received. See
6492  * g_dbus_connection_call() for the asynchronous version of
6493  * this method.
6494  *
6495  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6496  *     return values. Free with g_variant_unref().
6497  *
6498  * Since: 2.26
6499  */
6500 GVariant *
6501 g_dbus_connection_call_sync (GDBusConnection     *connection,
6502                              const gchar         *bus_name,
6503                              const gchar         *object_path,
6504                              const gchar         *interface_name,
6505                              const gchar         *method_name,
6506                              GVariant            *parameters,
6507                              const GVariantType  *reply_type,
6508                              GDBusCallFlags       flags,
6509                              gint                 timeout_msec,
6510                              GCancellable        *cancellable,
6511                              GError             **error)
6512 {
6513   return g_dbus_connection_call_sync_internal (connection, bus_name, object_path, interface_name, method_name, parameters, reply_type, flags, timeout_msec, NULL, NULL, cancellable, error);
6514 }
6515
6516 /* ---------------------------------------------------------------------------------------------------- */
6517
6518 #ifdef G_OS_UNIX
6519
6520 /**
6521  * g_dbus_connection_call_with_unix_fd_list:
6522  * @connection: a #GDBusConnection
6523  * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
6524  *     @connection is not a message bus connection
6525  * @object_path: path of remote object
6526  * @interface_name: D-Bus interface to invoke method on
6527  * @method_name: the name of the method to invoke
6528  * @parameters: (allow-none): a #GVariant tuple with parameters for the method
6529  *     or %NULL if not passing parameters
6530  * @reply_type: (allow-none): the expected type of the reply, or %NULL
6531  * @flags: flags from the #GDBusCallFlags enumeration
6532  * @timeout_msec: the timeout in milliseconds, -1 to use the default
6533  *     timeout or %G_MAXINT for no timeout
6534  * @fd_list: (allow-none): a #GUnixFDList or %NULL
6535  * @cancellable: (allow-none): a #GCancellable or %NULL
6536  * @callback: (allow-none): a #GAsyncReadyCallback to call when the request is
6537  *     satisfied or %NULL if you don't * care about the result of the
6538  *     method invocation
6539  * @user_data: The data to pass to @callback.
6540  *
6541  * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
6542  *
6543  * This method is only available on UNIX.
6544  *
6545  * Since: 2.30
6546  */
6547 void
6548 g_dbus_connection_call_with_unix_fd_list (GDBusConnection     *connection,
6549                                           const gchar         *bus_name,
6550                                           const gchar         *object_path,
6551                                           const gchar         *interface_name,
6552                                           const gchar         *method_name,
6553                                           GVariant            *parameters,
6554                                           const GVariantType  *reply_type,
6555                                           GDBusCallFlags       flags,
6556                                           gint                 timeout_msec,
6557                                           GUnixFDList         *fd_list,
6558                                           GCancellable        *cancellable,
6559                                           GAsyncReadyCallback  callback,
6560                                           gpointer             user_data)
6561 {
6562   g_dbus_connection_call_internal (connection, bus_name, object_path, interface_name, method_name, parameters, reply_type, flags, timeout_msec, fd_list, cancellable, callback, user_data);
6563 }
6564
6565 /**
6566  * g_dbus_connection_call_with_unix_fd_list_finish:
6567  * @connection: a #GDBusConnection
6568  * @out_fd_list: (out) (allow-none): return location for a #GUnixFDList or %NULL
6569  * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
6570  *     g_dbus_connection_call_with_unix_fd_list()
6571  * @error: return location for error or %NULL
6572  *
6573  * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
6574  *
6575  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6576  *     return values. Free with g_variant_unref().
6577  *
6578  * Since: 2.30
6579  */
6580 GVariant *
6581 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection  *connection,
6582                                                  GUnixFDList     **out_fd_list,
6583                                                  GAsyncResult     *res,
6584                                                  GError          **error)
6585 {
6586   return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
6587 }
6588
6589 /**
6590  * g_dbus_connection_call_with_unix_fd_list_sync:
6591  * @connection: a #GDBusConnection
6592  * @bus_name: (allow-none): a unique or well-known bus name or %NULL
6593  *     if @connection is not a message bus connection
6594  * @object_path: path of remote object
6595  * @interface_name: D-Bus interface to invoke method on
6596  * @method_name: the name of the method to invoke
6597  * @parameters: (allow-none): a #GVariant tuple with parameters for
6598  *     the method or %NULL if not passing parameters
6599  * @reply_type: (allow-none): the expected type of the reply, or %NULL
6600  * @flags: flags from the #GDBusCallFlags enumeration
6601  * @timeout_msec: the timeout in milliseconds, -1 to use the default
6602  *     timeout or %G_MAXINT for no timeout
6603  * @fd_list: (allow-none): a #GUnixFDList or %NULL
6604  * @out_fd_list: (out) (allow-none): return location for a #GUnixFDList or %NULL
6605  * @cancellable: (allow-none): a #GCancellable or %NULL
6606  * @error: return location for error or %NULL
6607  *
6608  * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
6609  *
6610  * This method is only available on UNIX.
6611  *
6612  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6613  *     return values. Free with g_variant_unref().
6614  *
6615  * Since: 2.30
6616  */
6617 GVariant *
6618 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection     *connection,
6619                                                const gchar         *bus_name,
6620                                                const gchar         *object_path,
6621                                                const gchar         *interface_name,
6622                                                const gchar         *method_name,
6623                                                GVariant            *parameters,
6624                                                const GVariantType  *reply_type,
6625                                                GDBusCallFlags       flags,
6626                                                gint                 timeout_msec,
6627                                                GUnixFDList         *fd_list,
6628                                                GUnixFDList        **out_fd_list,
6629                                                GCancellable        *cancellable,
6630                                                GError             **error)
6631 {
6632   return g_dbus_connection_call_sync_internal (connection, bus_name, object_path, interface_name, method_name, parameters, reply_type, flags, timeout_msec, fd_list, out_fd_list, cancellable, error);
6633 }
6634
6635 #endif /* G_OS_UNIX */
6636
6637 /* ---------------------------------------------------------------------------------------------------- */
6638
6639 struct ExportedSubtree
6640 {
6641   guint                     id;
6642   gchar                    *object_path;
6643   GDBusConnection          *connection;
6644   GDBusSubtreeVTable       *vtable;
6645   GDBusSubtreeFlags         flags;
6646
6647   GMainContext             *context;
6648   gpointer                  user_data;
6649   GDestroyNotify            user_data_free_func;
6650 };
6651
6652 static void
6653 exported_subtree_free (ExportedSubtree *es)
6654 {
6655   call_destroy_notify (es->context,
6656                        es->user_data_free_func,
6657                        es->user_data);
6658
6659   g_main_context_unref (es->context);
6660
6661   _g_dbus_subtree_vtable_free (es->vtable);
6662   g_free (es->object_path);
6663   g_free (es);
6664 }
6665
6666 /* called without lock held in the thread where the caller registered
6667  * the subtree
6668  */
6669 static gboolean
6670 handle_subtree_introspect (GDBusConnection *connection,
6671                            ExportedSubtree *es,
6672                            GDBusMessage    *message)
6673 {
6674   GString *s;
6675   gboolean handled;
6676   GDBusMessage *reply;
6677   gchar **children;
6678   gboolean is_root;
6679   const gchar *sender;
6680   const gchar *requested_object_path;
6681   const gchar *requested_node;
6682   GDBusInterfaceInfo **interfaces;
6683   guint n;
6684   gchar **subnode_paths;
6685   gboolean has_properties_interface;
6686   gboolean has_introspectable_interface;
6687
6688   handled = FALSE;
6689
6690   requested_object_path = g_dbus_message_get_path (message);
6691   sender = g_dbus_message_get_sender (message);
6692   is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6693
6694   s = g_string_new (NULL);
6695   introspect_append_header (s);
6696
6697   /* Strictly we don't need the children in dynamic mode, but we avoid the
6698    * conditionals to preserve code clarity
6699    */
6700   children = es->vtable->enumerate (es->connection,
6701                                     sender,
6702                                     es->object_path,
6703                                     es->user_data);
6704
6705   if (!is_root)
6706     {
6707       requested_node = strrchr (requested_object_path, '/') + 1;
6708
6709       /* Assert existence of object if we are not dynamic */
6710       if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
6711           !_g_strv_has_string ((const gchar * const *) children, requested_node))
6712         goto out;
6713     }
6714   else
6715     {
6716       requested_node = NULL;
6717     }
6718
6719   interfaces = es->vtable->introspect (es->connection,
6720                                        sender,
6721                                        es->object_path,
6722                                        requested_node,
6723                                        es->user_data);
6724   if (interfaces != NULL)
6725     {
6726       has_properties_interface = FALSE;
6727       has_introspectable_interface = FALSE;
6728
6729       for (n = 0; interfaces[n] != NULL; n++)
6730         {
6731           if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
6732             has_properties_interface = TRUE;
6733           else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
6734             has_introspectable_interface = TRUE;
6735         }
6736       if (!has_properties_interface)
6737         g_string_append (s, introspect_properties_interface);
6738       if (!has_introspectable_interface)
6739         g_string_append (s, introspect_introspectable_interface);
6740
6741       for (n = 0; interfaces[n] != NULL; n++)
6742         {
6743           g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
6744           g_dbus_interface_info_unref (interfaces[n]);
6745         }
6746       g_free (interfaces);
6747     }
6748
6749   /* then include <node> entries from the Subtree for the root */
6750   if (is_root)
6751     {
6752       for (n = 0; children != NULL && children[n] != NULL; n++)
6753         g_string_append_printf (s, "  <node name=\"%s\"/>\n", children[n]);
6754     }
6755
6756   /* finally include nodes registered below us */
6757   subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
6758   for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
6759     g_string_append_printf (s, "  <node name=\"%s\"/>\n", subnode_paths[n]);
6760   g_strfreev (subnode_paths);
6761
6762   g_string_append (s, "</node>\n");
6763
6764   reply = g_dbus_message_new_method_reply (message);
6765   g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6766   g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6767   g_object_unref (reply);
6768
6769   handled = TRUE;
6770
6771  out:
6772   g_string_free (s, TRUE);
6773   g_strfreev (children);
6774   return handled;
6775 }
6776
6777 /* called without lock held in the thread where the caller registered
6778  * the subtree
6779  */
6780 static gboolean
6781 handle_subtree_method_invocation (GDBusConnection *connection,
6782                                   ExportedSubtree *es,
6783                                   GDBusMessage    *message)
6784 {
6785   gboolean handled;
6786   const gchar *sender;
6787   const gchar *interface_name;
6788   const gchar *member;
6789   const gchar *signature;
6790   const gchar *requested_object_path;
6791   const gchar *requested_node;
6792   gboolean is_root;
6793   GDBusInterfaceInfo *interface_info;
6794   const GDBusInterfaceVTable *interface_vtable;
6795   gpointer interface_user_data;
6796   guint n;
6797   GDBusInterfaceInfo **interfaces;
6798   gboolean is_property_get;
6799   gboolean is_property_set;
6800   gboolean is_property_get_all;
6801
6802   handled = FALSE;
6803   interfaces = NULL;
6804
6805   requested_object_path = g_dbus_message_get_path (message);
6806   sender = g_dbus_message_get_sender (message);
6807   interface_name = g_dbus_message_get_interface (message);
6808   member = g_dbus_message_get_member (message);
6809   signature = g_dbus_message_get_signature (message);
6810   is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6811
6812   is_property_get = FALSE;
6813   is_property_set = FALSE;
6814   is_property_get_all = FALSE;
6815   if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6816     {
6817       if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6818         is_property_get = TRUE;
6819       else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6820         is_property_set = TRUE;
6821       else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6822         is_property_get_all = TRUE;
6823     }
6824
6825   if (!is_root)
6826     {
6827       requested_node = strrchr (requested_object_path, '/') + 1;
6828
6829       if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6830         {
6831           /* We don't want to dispatch to unenumerated
6832            * nodes, so ensure that the child exists.
6833            */
6834           gchar **children;
6835           gboolean exists;
6836
6837           children = es->vtable->enumerate (es->connection,
6838                                             sender,
6839                                             es->object_path,
6840                                             es->user_data);
6841
6842           exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6843           g_strfreev (children);
6844
6845           if (!exists)
6846             goto out;
6847         }
6848     }
6849   else
6850     {
6851       requested_node = NULL;
6852     }
6853
6854   /* get introspection data for the node */
6855   interfaces = es->vtable->introspect (es->connection,
6856                                        sender,
6857                                        requested_object_path,
6858                                        requested_node,
6859                                        es->user_data);
6860
6861   if (interfaces == NULL)
6862     goto out;
6863
6864   interface_info = NULL;
6865   for (n = 0; interfaces[n] != NULL; n++)
6866     {
6867       if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6868         interface_info = interfaces[n];
6869     }
6870
6871   /* dispatch the call if the user wants to handle it */
6872   if (interface_info != NULL)
6873     {
6874       /* figure out where to dispatch the method call */
6875       interface_user_data = NULL;
6876       interface_vtable = es->vtable->dispatch (es->connection,
6877                                                sender,
6878                                                es->object_path,
6879                                                interface_name,
6880                                                requested_node,
6881                                                &interface_user_data,
6882                                                es->user_data);
6883       if (interface_vtable == NULL)
6884         goto out;
6885
6886       CONNECTION_LOCK (connection);
6887       handled = validate_and_maybe_schedule_method_call (es->connection,
6888                                                          message,
6889                                                          0,
6890                                                          es->id,
6891                                                          interface_info,
6892                                                          interface_vtable,
6893                                                          es->context,
6894                                                          interface_user_data);
6895       CONNECTION_UNLOCK (connection);
6896     }
6897   /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6898   else if (is_property_get || is_property_set || is_property_get_all)
6899     {
6900       if (is_property_get)
6901         g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6902       else if (is_property_set)
6903         g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6904       else if (is_property_get_all)
6905         g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6906       else
6907         g_assert_not_reached ();
6908
6909       /* see if the object supports this interface at all */
6910       for (n = 0; interfaces[n] != NULL; n++)
6911         {
6912           if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6913             interface_info = interfaces[n];
6914         }
6915
6916       /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6917        * claims it won't support the interface
6918        */
6919       if (interface_info == NULL)
6920         {
6921           GDBusMessage *reply;
6922           reply = g_dbus_message_new_method_error (message,
6923                                                    "org.freedesktop.DBus.Error.InvalidArgs",
6924                                                    _("No such interface '%s'"),
6925                                                    interface_name);
6926           g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6927           g_object_unref (reply);
6928           handled = TRUE;
6929           goto out;
6930         }
6931
6932       /* figure out where to dispatch the property get/set/getall calls */
6933       interface_user_data = NULL;
6934       interface_vtable = es->vtable->dispatch (es->connection,
6935                                                sender,
6936                                                es->object_path,
6937                                                interface_name,
6938                                                requested_node,
6939                                                &interface_user_data,
6940                                                es->user_data);
6941       if (interface_vtable == NULL)
6942         {
6943           g_warning ("The subtree introspection function indicates that '%s' "
6944                      "is a valid interface name, but calling the dispatch "
6945                      "function on that interface gave us NULL", interface_name);
6946           goto out;
6947         }
6948
6949       if (is_property_get || is_property_set)
6950         {
6951           CONNECTION_LOCK (connection);
6952           handled = validate_and_maybe_schedule_property_getset (es->connection,
6953                                                                  message,
6954                                                                  0,
6955                                                                  es->id,
6956                                                                  is_property_get,
6957                                                                  interface_info,
6958                                                                  interface_vtable,
6959                                                                  es->context,
6960                                                                  interface_user_data);
6961           CONNECTION_UNLOCK (connection);
6962         }
6963       else if (is_property_get_all)
6964         {
6965           CONNECTION_LOCK (connection);
6966           handled = validate_and_maybe_schedule_property_get_all (es->connection,
6967                                                                   message,
6968                                                                   0,
6969                                                                   es->id,
6970                                                                   interface_info,
6971                                                                   interface_vtable,
6972                                                                   es->context,
6973                                                                   interface_user_data);
6974           CONNECTION_UNLOCK (connection);
6975         }
6976     }
6977
6978  out:
6979   if (interfaces != NULL)
6980     {
6981       for (n = 0; interfaces[n] != NULL; n++)
6982         g_dbus_interface_info_unref (interfaces[n]);
6983       g_free (interfaces);
6984     }
6985
6986   return handled;
6987 }
6988
6989 typedef struct
6990 {
6991   GDBusMessage *message;
6992   ExportedSubtree *es;
6993 } SubtreeDeferredData;
6994
6995 static void
6996 subtree_deferred_data_free (SubtreeDeferredData *data)
6997 {
6998   g_object_unref (data->message);
6999   g_free (data);
7000 }
7001
7002 /* called without lock held in the thread where the caller registered the subtree */
7003 static gboolean
7004 process_subtree_vtable_message_in_idle_cb (gpointer _data)
7005 {
7006   SubtreeDeferredData *data = _data;
7007   gboolean handled;
7008
7009   handled = FALSE;
7010
7011   if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
7012       g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
7013       g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
7014     handled = handle_subtree_introspect (data->es->connection,
7015                                          data->es,
7016                                          data->message);
7017   else
7018     handled = handle_subtree_method_invocation (data->es->connection,
7019                                                 data->es,
7020                                                 data->message);
7021
7022   if (!handled)
7023     {
7024       CONNECTION_LOCK (data->es->connection);
7025       handled = handle_generic_unlocked (data->es->connection, data->message);
7026       CONNECTION_UNLOCK (data->es->connection);
7027     }
7028
7029   /* if we couldn't handle the request, just bail with the UnknownMethod error */
7030   if (!handled)
7031     {
7032       GDBusMessage *reply;
7033       reply = g_dbus_message_new_method_error (data->message,
7034                                                "org.freedesktop.DBus.Error.UnknownMethod",
7035                                                _("Method '%s' on interface '%s' with signature '%s' does not exist"),
7036                                                g_dbus_message_get_member (data->message),
7037                                                g_dbus_message_get_interface (data->message),
7038                                                g_dbus_message_get_signature (data->message));
7039       g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7040       g_object_unref (reply);
7041     }
7042
7043   return FALSE;
7044 }
7045
7046 /* called in GDBusWorker thread with connection's lock held */
7047 static gboolean
7048 subtree_message_func (GDBusConnection *connection,
7049                       ExportedSubtree *es,
7050                       GDBusMessage    *message)
7051 {
7052   GSource *idle_source;
7053   SubtreeDeferredData *data;
7054
7055   data = g_new0 (SubtreeDeferredData, 1);
7056   data->message = g_object_ref (message);
7057   data->es = es;
7058
7059   /* defer this call to an idle handler in the right thread */
7060   idle_source = g_idle_source_new ();
7061   g_source_set_priority (idle_source, G_PRIORITY_HIGH);
7062   g_source_set_callback (idle_source,
7063                          process_subtree_vtable_message_in_idle_cb,
7064                          data,
7065                          (GDestroyNotify) subtree_deferred_data_free);
7066   g_source_set_name (idle_source, "[gio] process_subtree_vtable_message_in_idle_cb");
7067   g_source_attach (idle_source, es->context);
7068   g_source_unref (idle_source);
7069
7070   /* since we own the entire subtree, handlers for objects not in the subtree have been
7071    * tried already by libdbus-1 - so we just need to ensure that we're always going
7072    * to reply to the message
7073    */
7074   return TRUE;
7075 }
7076
7077 /**
7078  * g_dbus_connection_register_subtree:
7079  * @connection: a #GDBusConnection
7080  * @object_path: the object path to register the subtree at
7081  * @vtable: a #GDBusSubtreeVTable to enumerate, introspect and
7082  *     dispatch nodes in the subtree
7083  * @flags: flags used to fine tune the behavior of the subtree
7084  * @user_data: data to pass to functions in @vtable
7085  * @user_data_free_func: function to call when the subtree is unregistered
7086  * @error: return location for error or %NULL
7087  *
7088  * Registers a whole subtree of dynamic objects.
7089  *
7090  * The @enumerate and @introspection functions in @vtable are used to
7091  * convey, to remote callers, what nodes exist in the subtree rooted
7092  * by @object_path.
7093  *
7094  * When handling remote calls into any node in the subtree, first the
7095  * @enumerate function is used to check if the node exists. If the node exists
7096  * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
7097  * the @introspection function is used to check if the node supports the
7098  * requested method. If so, the @dispatch function is used to determine
7099  * where to dispatch the call. The collected #GDBusInterfaceVTable and
7100  * #gpointer will be used to call into the interface vtable for processing
7101  * the request.
7102  *
7103  * All calls into user-provided code will be invoked in the
7104  * [thread-default main context][g-main-context-push-thread-default]
7105  * of the thread you are calling this method from.
7106  *
7107  * If an existing subtree is already registered at @object_path or
7108  * then @error is set to #G_IO_ERROR_EXISTS.
7109  *
7110  * Note that it is valid to register regular objects (using
7111  * g_dbus_connection_register_object()) in a subtree registered with
7112  * g_dbus_connection_register_subtree() - if so, the subtree handler
7113  * is tried as the last resort. One way to think about a subtree
7114  * handler is to consider it a fallback handler for object paths not
7115  * registered via g_dbus_connection_register_object() or other bindings.
7116  *
7117  * Note that @vtable will be copied so you cannot change it after
7118  * registration.
7119  *
7120  * See this [server][gdbus-subtree-server] for an example of how to use
7121  * this method.
7122  *
7123  * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
7124  * that can be used with g_dbus_connection_unregister_subtree() .
7125  *
7126  * Since: 2.26
7127  */
7128 guint
7129 g_dbus_connection_register_subtree (GDBusConnection           *connection,
7130                                     const gchar               *object_path,
7131                                     const GDBusSubtreeVTable  *vtable,
7132                                     GDBusSubtreeFlags          flags,
7133                                     gpointer                   user_data,
7134                                     GDestroyNotify             user_data_free_func,
7135                                     GError                   **error)
7136 {
7137   guint ret;
7138   ExportedSubtree *es;
7139
7140   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
7141   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
7142   g_return_val_if_fail (vtable != NULL, 0);
7143   g_return_val_if_fail (error == NULL || *error == NULL, 0);
7144   g_return_val_if_fail (check_initialized (connection), 0);
7145
7146   ret = 0;
7147
7148   CONNECTION_LOCK (connection);
7149
7150   es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
7151   if (es != NULL)
7152     {
7153       g_set_error (error,
7154                    G_IO_ERROR,
7155                    G_IO_ERROR_EXISTS,
7156                    _("A subtree is already exported for %s"),
7157                    object_path);
7158       goto out;
7159     }
7160
7161   es = g_new0 (ExportedSubtree, 1);
7162   es->object_path = g_strdup (object_path);
7163   es->connection = connection;
7164
7165   es->vtable = _g_dbus_subtree_vtable_copy (vtable);
7166   es->flags = flags;
7167   es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
7168   es->user_data = user_data;
7169   es->user_data_free_func = user_data_free_func;
7170   es->context = g_main_context_ref_thread_default ();
7171
7172   g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
7173   g_hash_table_insert (connection->map_id_to_es,
7174                        GUINT_TO_POINTER (es->id),
7175                        es);
7176
7177   ret = es->id;
7178
7179  out:
7180   CONNECTION_UNLOCK (connection);
7181
7182   return ret;
7183 }
7184
7185 /* ---------------------------------------------------------------------------------------------------- */
7186
7187 /**
7188  * g_dbus_connection_unregister_subtree:
7189  * @connection: a #GDBusConnection
7190  * @registration_id: a subtree registration id obtained from
7191  *     g_dbus_connection_register_subtree()
7192  *
7193  * Unregisters a subtree.
7194  *
7195  * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise
7196  *
7197  * Since: 2.26
7198  */
7199 gboolean
7200 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
7201                                       guint            registration_id)
7202 {
7203   ExportedSubtree *es;
7204   gboolean ret;
7205
7206   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
7207   g_return_val_if_fail (check_initialized (connection), FALSE);
7208
7209   ret = FALSE;
7210
7211   CONNECTION_LOCK (connection);
7212
7213   es = g_hash_table_lookup (connection->map_id_to_es,
7214                             GUINT_TO_POINTER (registration_id));
7215   if (es == NULL)
7216     goto out;
7217
7218   g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
7219   g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
7220
7221   ret = TRUE;
7222
7223  out:
7224   CONNECTION_UNLOCK (connection);
7225
7226   return ret;
7227 }
7228
7229 /* ---------------------------------------------------------------------------------------------------- */
7230
7231 /* may be called in any thread, with connection's lock held */
7232 static void
7233 handle_generic_ping_unlocked (GDBusConnection *connection,
7234                               const gchar     *object_path,
7235                               GDBusMessage    *message)
7236 {
7237   GDBusMessage *reply;
7238   reply = g_dbus_message_new_method_reply (message);
7239   g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7240   g_object_unref (reply);
7241 }
7242
7243 /* may be called in any thread, with connection's lock held */
7244 static void
7245 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
7246                                         const gchar     *object_path,
7247                                         GDBusMessage    *message)
7248 {
7249   GDBusMessage *reply;
7250
7251   reply = NULL;
7252   if (connection->machine_id == NULL)
7253     {
7254       GError *error;
7255
7256       error = NULL;
7257       connection->machine_id = _g_dbus_get_machine_id (&error);
7258       if (connection->machine_id == NULL)
7259         {
7260           reply = g_dbus_message_new_method_error_literal (message,
7261                                                            "org.freedesktop.DBus.Error.Failed",
7262                                                            error->message);
7263           g_error_free (error);
7264         }
7265     }
7266
7267   if (reply == NULL)
7268     {
7269       reply = g_dbus_message_new_method_reply (message);
7270       g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
7271     }
7272   g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7273   g_object_unref (reply);
7274 }
7275
7276 /* may be called in any thread, with connection's lock held */
7277 static void
7278 handle_generic_introspect_unlocked (GDBusConnection *connection,
7279                                     const gchar     *object_path,
7280                                     GDBusMessage    *message)
7281 {
7282   guint n;
7283   GString *s;
7284   gchar **registered;
7285   GDBusMessage *reply;
7286
7287   /* first the header */
7288   s = g_string_new (NULL);
7289   introspect_append_header (s);
7290
7291   registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
7292   for (n = 0; registered != NULL && registered[n] != NULL; n++)
7293       g_string_append_printf (s, "  <node name=\"%s\"/>\n", registered[n]);
7294   g_strfreev (registered);
7295   g_string_append (s, "</node>\n");
7296
7297   reply = g_dbus_message_new_method_reply (message);
7298   g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
7299   g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7300   g_object_unref (reply);
7301   g_string_free (s, TRUE);
7302 }
7303
7304 /* may be called in any thread, with connection's lock held */
7305 static gboolean
7306 handle_generic_unlocked (GDBusConnection *connection,
7307                          GDBusMessage    *message)
7308 {
7309   gboolean handled;
7310   const gchar *interface_name;
7311   const gchar *member;
7312   const gchar *signature;
7313   const gchar *path;
7314
7315   CONNECTION_ENSURE_LOCK (connection);
7316
7317   handled = FALSE;
7318
7319   interface_name = g_dbus_message_get_interface (message);
7320   member = g_dbus_message_get_member (message);
7321   signature = g_dbus_message_get_signature (message);
7322   path = g_dbus_message_get_path (message);
7323
7324   if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
7325       g_strcmp0 (member, "Introspect") == 0 &&
7326       g_strcmp0 (signature, "") == 0)
7327     {
7328       handle_generic_introspect_unlocked (connection, path, message);
7329       handled = TRUE;
7330     }
7331   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7332            g_strcmp0 (member, "Ping") == 0 &&
7333            g_strcmp0 (signature, "") == 0)
7334     {
7335       handle_generic_ping_unlocked (connection, path, message);
7336       handled = TRUE;
7337     }
7338   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7339            g_strcmp0 (member, "GetMachineId") == 0 &&
7340            g_strcmp0 (signature, "") == 0)
7341     {
7342       handle_generic_get_machine_id_unlocked (connection, path, message);
7343       handled = TRUE;
7344     }
7345
7346   return handled;
7347 }
7348
7349 /* ---------------------------------------------------------------------------------------------------- */
7350
7351 /* called in GDBusWorker thread with connection's lock held */
7352 static void
7353 distribute_method_call (GDBusConnection *connection,
7354                         GDBusMessage    *message)
7355 {
7356   GDBusMessage *reply;
7357   ExportedObject *eo;
7358   ExportedSubtree *es;
7359   const gchar *object_path;
7360   const gchar *interface_name;
7361   const gchar *member;
7362   const gchar *path;
7363   gchar *subtree_path;
7364   gchar *needle;
7365
7366   g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
7367
7368   interface_name = g_dbus_message_get_interface (message);
7369   member = g_dbus_message_get_member (message);
7370   path = g_dbus_message_get_path (message);
7371   subtree_path = g_strdup (path);
7372   needle = strrchr (subtree_path, '/');
7373   if (needle != NULL && needle != subtree_path)
7374     {
7375       *needle = '\0';
7376     }
7377   else
7378     {
7379       g_free (subtree_path);
7380       subtree_path = NULL;
7381     }
7382
7383
7384   if (G_UNLIKELY (_g_dbus_debug_incoming ()))
7385     {
7386       _g_dbus_debug_print_lock ();
7387       g_print ("========================================================================\n"
7388                "GDBus-debug:Incoming:\n"
7389                " <<<< METHOD INVOCATION %s.%s()\n"
7390                "      on object %s\n"
7391                "      invoked by name %s\n"
7392                "      serial %d\n",
7393                interface_name, member,
7394                path,
7395                g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
7396                g_dbus_message_get_serial (message));
7397       _g_dbus_debug_print_unlock ();
7398     }
7399
7400   object_path = g_dbus_message_get_path (message);
7401   g_assert (object_path != NULL);
7402
7403   eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
7404   if (eo != NULL)
7405     {
7406       if (obj_message_func (connection, eo, message))
7407         goto out;
7408     }
7409
7410   es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
7411   if (es != NULL)
7412     {
7413       if (subtree_message_func (connection, es, message))
7414         goto out;
7415     }
7416
7417   if (subtree_path != NULL)
7418     {
7419       es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
7420       if (es != NULL)
7421         {
7422           if (subtree_message_func (connection, es, message))
7423             goto out;
7424         }
7425     }
7426
7427   if (handle_generic_unlocked (connection, message))
7428     goto out;
7429
7430   /* if we end up here, the message has not been not handled - so return an error saying this */
7431   reply = g_dbus_message_new_method_error (message,
7432                                            "org.freedesktop.DBus.Error.UnknownMethod",
7433                                            _("No such interface '%s' on object at path %s"),
7434                                            interface_name,
7435                                            object_path);
7436   g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7437   g_object_unref (reply);
7438
7439  out:
7440   g_free (subtree_path);
7441 }
7442
7443 /* ---------------------------------------------------------------------------------------------------- */
7444
7445 /* Called in any user thread, with the message_bus_lock held. */
7446 static GWeakRef *
7447 message_bus_get_singleton (GBusType   bus_type,
7448                            GError   **error)
7449 {
7450   GWeakRef *ret;
7451   const gchar *starter_bus;
7452
7453   ret = NULL;
7454
7455   switch (bus_type)
7456     {
7457     case G_BUS_TYPE_SESSION:
7458       ret = &the_session_bus;
7459       break;
7460
7461     case G_BUS_TYPE_SYSTEM:
7462       ret = &the_system_bus;
7463       break;
7464
7465     case G_BUS_TYPE_USER:
7466       ret = &the_user_bus;
7467       break;
7468
7469     case G_BUS_TYPE_MACHINE:
7470       ret = &the_machine_bus;
7471       break;
7472
7473     case G_BUS_TYPE_STARTER:
7474       starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
7475       if (g_strcmp0 (starter_bus, "session") == 0)
7476         {
7477           ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
7478           goto out;
7479         }
7480       else if (g_strcmp0 (starter_bus, "system") == 0)
7481         {
7482           ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
7483           goto out;
7484         }
7485       else
7486         {
7487           if (starter_bus != NULL)
7488             {
7489               g_set_error (error,
7490                            G_IO_ERROR,
7491                            G_IO_ERROR_INVALID_ARGUMENT,
7492                            _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
7493                              " - unknown value '%s'"),
7494                            starter_bus);
7495             }
7496           else
7497             {
7498               g_set_error_literal (error,
7499                                    G_IO_ERROR,
7500                                    G_IO_ERROR_INVALID_ARGUMENT,
7501                                    _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
7502                                      "variable is not set"));
7503             }
7504         }
7505       break;
7506
7507     default:
7508       g_assert_not_reached ();
7509       break;
7510     }
7511
7512  out:
7513   return ret;
7514 }
7515
7516 /* Called in any user thread, without holding locks. */
7517 static GDBusConnection *
7518 get_uninitialized_connection (GBusType       bus_type,
7519                               GCancellable  *cancellable,
7520                               GError       **error)
7521 {
7522   GWeakRef *singleton;
7523   GDBusConnection *ret;
7524
7525   ret = NULL;
7526
7527   G_LOCK (message_bus_lock);
7528   singleton = message_bus_get_singleton (bus_type, error);
7529   if (singleton == NULL)
7530     goto out;
7531
7532   ret = g_weak_ref_get (singleton);
7533
7534   if (ret == NULL)
7535     {
7536       gchar *address;
7537       address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
7538       if (address == NULL)
7539         goto out;
7540       ret = g_object_new (G_TYPE_DBUS_CONNECTION,
7541                           "address", address,
7542                           "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
7543                                    G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
7544                           "exit-on-close", TRUE,
7545                           NULL);
7546
7547       g_weak_ref_set (singleton, ret);
7548       g_free (address);
7549     }
7550
7551   g_assert (ret != NULL);
7552
7553  out:
7554   G_UNLOCK (message_bus_lock);
7555   return ret;
7556 }
7557
7558 /* May be called from any thread. Must not hold message_bus_lock. */
7559 GDBusConnection *
7560 _g_bus_get_singleton_if_exists (GBusType bus_type)
7561 {
7562   GWeakRef *singleton;
7563   GDBusConnection *ret = NULL;
7564
7565   G_LOCK (message_bus_lock);
7566   singleton = message_bus_get_singleton (bus_type, NULL);
7567   if (singleton == NULL)
7568     goto out;
7569
7570   ret = g_weak_ref_get (singleton);
7571
7572  out:
7573   G_UNLOCK (message_bus_lock);
7574   return ret;
7575 }
7576
7577 /**
7578  * g_bus_get_sync:
7579  * @bus_type: a #GBusType
7580  * @cancellable: (allow-none): a #GCancellable or %NULL
7581  * @error: return location for error or %NULL
7582  *
7583  * Synchronously connects to the message bus specified by @bus_type.
7584  * Note that the returned object may shared with other callers,
7585  * e.g. if two separate parts of a process calls this function with
7586  * the same @bus_type, they will share the same object.
7587  *
7588  * This is a synchronous failable function. See g_bus_get() and
7589  * g_bus_get_finish() for the asynchronous version.
7590  *
7591  * The returned object is a singleton, that is, shared with other
7592  * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7593  * event that you need a private message bus connection, use
7594  * g_dbus_address_get_for_bus_sync() and
7595  * g_dbus_connection_new_for_address().
7596  *
7597  * Note that the returned #GDBusConnection object will (usually) have
7598  * the #GDBusConnection:exit-on-close property set to %TRUE.
7599  *
7600  * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7601  *     Free with g_object_unref().
7602  *
7603  * Since: 2.26
7604  */
7605 GDBusConnection *
7606 g_bus_get_sync (GBusType       bus_type,
7607                 GCancellable  *cancellable,
7608                 GError       **error)
7609 {
7610   GDBusConnection *connection;
7611
7612   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7613
7614   connection = get_uninitialized_connection (bus_type, cancellable, error);
7615   if (connection == NULL)
7616     goto out;
7617
7618   if (!g_initable_init (G_INITABLE (connection), cancellable, error))
7619     {
7620       g_object_unref (connection);
7621       connection = NULL;
7622     }
7623
7624  out:
7625   return connection;
7626 }
7627
7628 static void
7629 bus_get_async_initable_cb (GObject      *source_object,
7630                            GAsyncResult *res,
7631                            gpointer      user_data)
7632 {
7633   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
7634   GError *error;
7635
7636   error = NULL;
7637   if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
7638                                      res,
7639                                      &error))
7640     {
7641       g_assert (error != NULL);
7642       g_simple_async_result_take_error (simple, error);
7643       g_object_unref (source_object);
7644     }
7645   else
7646     {
7647       g_simple_async_result_set_op_res_gpointer (simple,
7648                                                  source_object,
7649                                                  g_object_unref);
7650     }
7651   g_simple_async_result_complete_in_idle (simple);
7652   g_object_unref (simple);
7653 }
7654
7655 /**
7656  * g_bus_get:
7657  * @bus_type: a #GBusType
7658  * @cancellable: (allow-none): a #GCancellable or %NULL
7659  * @callback: a #GAsyncReadyCallback to call when the request is satisfied
7660  * @user_data: the data to pass to @callback
7661  *
7662  * Asynchronously connects to the message bus specified by @bus_type.
7663  *
7664  * When the operation is finished, @callback will be invoked. You can
7665  * then call g_bus_get_finish() to get the result of the operation.
7666  *
7667  * This is a asynchronous failable function. See g_bus_get_sync() for
7668  * the synchronous version.
7669  *
7670  * Since: 2.26
7671  */
7672 void
7673 g_bus_get (GBusType             bus_type,
7674            GCancellable        *cancellable,
7675            GAsyncReadyCallback  callback,
7676            gpointer             user_data)
7677 {
7678   GDBusConnection *connection;
7679   GSimpleAsyncResult *simple;
7680   GError *error;
7681
7682   simple = g_simple_async_result_new (NULL,
7683                                       callback,
7684                                       user_data,
7685                                       g_bus_get);
7686   g_simple_async_result_set_check_cancellable (simple, cancellable);
7687
7688   error = NULL;
7689   connection = get_uninitialized_connection (bus_type, cancellable, &error);
7690   if (connection == NULL)
7691     {
7692       g_assert (error != NULL);
7693       g_simple_async_result_take_error (simple, error);
7694       g_simple_async_result_complete_in_idle (simple);
7695       g_object_unref (simple);
7696     }
7697   else
7698     {
7699       g_async_initable_init_async (G_ASYNC_INITABLE (connection),
7700                                    G_PRIORITY_DEFAULT,
7701                                    cancellable,
7702                                    bus_get_async_initable_cb,
7703                                    simple);
7704     }
7705 }
7706
7707 /**
7708  * g_bus_get_finish:
7709  * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
7710  *     to g_bus_get()
7711  * @error: return location for error or %NULL
7712  *
7713  * Finishes an operation started with g_bus_get().
7714  *
7715  * The returned object is a singleton, that is, shared with other
7716  * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7717  * event that you need a private message bus connection, use
7718  * g_dbus_address_get_for_bus_sync() and
7719  * g_dbus_connection_new_for_address().
7720  *
7721  * Note that the returned #GDBusConnection object will (usually) have
7722  * the #GDBusConnection:exit-on-close property set to %TRUE.
7723  *
7724  * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7725  *     Free with g_object_unref().
7726  *
7727  * Since: 2.26
7728  */
7729 GDBusConnection *
7730 g_bus_get_finish (GAsyncResult  *res,
7731                   GError       **error)
7732 {
7733   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
7734   GObject *object;
7735   GDBusConnection *ret;
7736
7737   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7738
7739   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
7740
7741   ret = NULL;
7742
7743   if (g_simple_async_result_propagate_error (simple, error))
7744     goto out;
7745
7746   object = g_simple_async_result_get_op_res_gpointer (simple);
7747   g_assert (object != NULL);
7748   ret = g_object_ref (G_DBUS_CONNECTION (object));
7749
7750  out:
7751   return ret;
7752 }
7753
7754 /* ---------------------------------------------------------------------------------------------------- */