hook gvariant vectors up to kdbus
[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_get_connection_pid:
1957  * @connection: a #GDBusConnection
1958  * @name: a unique or well-known bus name of the connection to query
1959  * @error: return location for error or %NULL
1960  *
1961  * Synchronously returns the Unix process ID of the process connected to the
1962  * bus. If unable to determine it, an @error is returned.
1963  *
1964  * If @name contains a value not compatible with the D-Bus syntax and naming
1965  * conventions for bus names, the operation returns (guint32) -1 and @error
1966  * is set.
1967  *
1968  * The calling thread is blocked until a reply is received.
1969  *
1970  * Returns: the Unix process ID of the process connected to the bus or
1971  *     (guint32) -1 if @error is set.
1972  *
1973  * Since: 2.4x
1974  */
1975 guint32
1976 g_dbus_get_connection_pid (GDBusConnection  *connection,
1977                            const gchar      *name,
1978                            GError          **error)
1979 {
1980   GVariant *result;
1981   guint32 pid;
1982
1983   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), -1);
1984   g_return_val_if_fail (name == NULL || g_dbus_is_name (name), -1);
1985   g_return_val_if_fail (error == NULL || *error == NULL, -1);
1986
1987   result = NULL;
1988   pid = -1;
1989
1990   if (G_IS_KDBUS_CONNECTION (connection->stream))
1991     result = _g_kdbus_GetConnectionUnixProcessID (connection, name, error);
1992   else
1993     result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
1994                                           "org.freedesktop.DBus", "GetConnectionUnixProcessID",
1995                                           g_variant_new ("(s)", name), G_VARIANT_TYPE ("(u)"),
1996                                           G_DBUS_CALL_FLAGS_NONE, -1, NULL, error);
1997   if (result != NULL)
1998     {
1999       g_variant_get (result, "(u)", &pid);
2000       g_variant_unref (result);
2001     }
2002
2003   return pid;
2004 }
2005
2006 /**
2007  * g_dbus_get_connection_uid:
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 user 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 user 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_uid (GDBusConnection  *connection,
2028                            const gchar      *name,
2029                            GError          **error)
2030 {
2031   GVariant *result;
2032   guint32 uid;
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   uid = -1;
2040
2041   if (G_IS_KDBUS_CONNECTION (connection->stream))
2042     result = _g_kdbus_GetConnectionUnixUser (connection, name, error);
2043   else
2044     result = g_dbus_connection_call_sync (connection, "org.freedesktop.DBus", "/",
2045                                           "org.freedesktop.DBus", "GetConnectionUnixUser",
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)", &uid);
2051       g_variant_unref (result);
2052     }
2053
2054   return uid;
2055 }
2056
2057 /* ---------------------------------------------------------------------------------------------------- */
2058
2059 /**
2060  * g_dbus_connection_get_last_serial:
2061  * @connection: a #GDBusConnection
2062  *
2063  * Retrieves the last serial number assigned to a #GDBusMessage on
2064  * the current thread. This includes messages sent via both low-level
2065  * API such as g_dbus_connection_send_message() as well as
2066  * high-level API such as g_dbus_connection_emit_signal(),
2067  * g_dbus_connection_call() or g_dbus_proxy_call().
2068  *
2069  * Returns: the last used serial or zero when no message has been sent
2070  *     within the current thread
2071  *
2072  * Since: 2.34
2073  */
2074 guint32
2075 g_dbus_connection_get_last_serial (GDBusConnection *connection)
2076 {
2077   guint32 ret;
2078
2079   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2080
2081   CONNECTION_LOCK (connection);
2082   ret = GPOINTER_TO_UINT (g_hash_table_lookup (connection->map_thread_to_last_serial,
2083                                                g_thread_self ()));
2084   CONNECTION_UNLOCK (connection);
2085
2086   return ret;
2087 }
2088
2089 /* ---------------------------------------------------------------------------------------------------- */
2090
2091 /* Can be called by any thread, with the connection lock held */
2092 static gboolean
2093 g_dbus_connection_send_message_unlocked (GDBusConnection   *connection,
2094                                          GDBusMessage      *message,
2095                                          GDBusSendMessageFlags flags,
2096                                          volatile guint32  *out_serial,
2097                                          GError           **error)
2098 {
2099   guchar *blob;
2100   gsize blob_size;
2101   guint32 serial_to_use;
2102   gboolean ret;
2103
2104   CONNECTION_ENSURE_LOCK (connection);
2105
2106   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2107   g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
2108
2109   /* TODO: check all necessary headers are present */
2110
2111   ret = FALSE;
2112   blob = NULL;
2113
2114   if (out_serial != NULL)
2115     *out_serial = 0;
2116
2117   /* If we're in initable_init(), don't check for being initialized, to avoid
2118    * chicken-and-egg problems. initable_init() is responsible for setting up
2119    * our prerequisites (mainly connection->worker), and only calling us
2120    * from its own thread (so no memory barrier is needed).
2121    */
2122   if (!check_unclosed (connection,
2123                        (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
2124                        error))
2125     goto out;
2126
2127   /* [KDBUS]
2128    * Setting protocol version, before invoking g_dbus_message_to_blob() will
2129    * be removed after preparing new function only for kdbus transport purposes
2130    * (this function will be able to create blob directly/unconditionally in memfd
2131    * object, without making copy)
2132    */
2133
2134   if (G_IS_KDBUS_CONNECTION (connection->stream))
2135     _g_dbus_message_set_protocol_ver (message,2);
2136   else
2137     _g_dbus_message_set_protocol_ver (message,1);
2138
2139   blob = g_dbus_message_to_blob (message,
2140                                  &blob_size,
2141                                  connection->capabilities,
2142                                  error);
2143   if (blob == NULL)
2144     goto out;
2145
2146   if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
2147     serial_to_use = g_dbus_message_get_serial (message);
2148   else
2149     serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
2150
2151   switch (blob[0])
2152     {
2153     case 'l':
2154       ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
2155       break;
2156     case 'B':
2157       ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
2158       break;
2159     default:
2160       g_assert_not_reached ();
2161       break;
2162     }
2163
2164 #if 0
2165   g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
2166               blob_size, serial_to_use, connection);
2167   g_printerr ("----\n");
2168   hexdump (blob, blob_size);
2169   g_printerr ("----\n");
2170 #endif
2171
2172   /* TODO: use connection->auth to encode the blob */
2173
2174   if (out_serial != NULL)
2175     *out_serial = serial_to_use;
2176
2177   /* store used serial for the current thread */
2178   /* TODO: watch the thread disposal and remove associated record
2179    *       from hashtable
2180    *  - see https://bugzilla.gnome.org/show_bug.cgi?id=676825#c7
2181    */
2182   g_hash_table_replace (connection->map_thread_to_last_serial,
2183                         g_thread_self (),
2184                         GUINT_TO_POINTER (serial_to_use));
2185
2186   if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
2187     g_dbus_message_set_serial (message, serial_to_use);
2188
2189   g_dbus_message_lock (message);
2190   _g_dbus_worker_send_message (connection->worker,
2191                                message,
2192                                (gchar*) blob,
2193                                blob_size);
2194   blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
2195
2196   ret = TRUE;
2197
2198  out:
2199   g_free (blob);
2200
2201   return ret;
2202 }
2203
2204 /**
2205  * g_dbus_connection_send_message:
2206  * @connection: a #GDBusConnection
2207  * @message: a #GDBusMessage
2208  * @flags: flags affecting how the message is sent
2209  * @out_serial: (out) (allow-none): return location for serial number assigned
2210  *     to @message when sending it or %NULL
2211  * @error: Return location for error or %NULL
2212  *
2213  * Asynchronously sends @message to the peer represented by @connection.
2214  *
2215  * Unless @flags contain the
2216  * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2217  * will be assigned by @connection and set on @message via
2218  * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2219  * serial number used will be written to this location prior to
2220  * submitting the message to the underlying transport.
2221  *
2222  * If @connection is closed then the operation will fail with
2223  * %G_IO_ERROR_CLOSED. If @message is not well-formed,
2224  * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2225  *
2226  * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2227  * for an example of how to use this low-level API to send and receive
2228  * UNIX file descriptors.
2229  *
2230  * Note that @message must be unlocked, unless @flags contain the
2231  * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2232  *
2233  * Returns: %TRUE if the message was well-formed and queued for
2234  *     transmission, %FALSE if @error is set
2235  *
2236  * Since: 2.26
2237  */
2238 gboolean
2239 g_dbus_connection_send_message (GDBusConnection        *connection,
2240                                 GDBusMessage           *message,
2241                                 GDBusSendMessageFlags   flags,
2242                                 volatile guint32       *out_serial,
2243                                 GError                **error)
2244 {
2245   gboolean ret;
2246
2247   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2248   g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
2249   g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
2250   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2251
2252   CONNECTION_LOCK (connection);
2253   ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
2254   CONNECTION_UNLOCK (connection);
2255   return ret;
2256 }
2257
2258 /* ---------------------------------------------------------------------------------------------------- */
2259
2260 typedef struct
2261 {
2262   volatile gint ref_count;
2263   GDBusConnection *connection;
2264   guint32 serial;
2265   GSimpleAsyncResult *simple;
2266
2267   GMainContext *main_context;
2268
2269   GCancellable *cancellable;
2270
2271   gulong cancellable_handler_id;
2272
2273   GSource *timeout_source;
2274
2275   gboolean delivered;
2276 } SendMessageData;
2277
2278 /* Can be called from any thread with or without lock held */
2279 static SendMessageData *
2280 send_message_data_ref (SendMessageData *data)
2281 {
2282   g_atomic_int_inc (&data->ref_count);
2283   return data;
2284 }
2285
2286 /* Can be called from any thread with or without lock held */
2287 static void
2288 send_message_data_unref (SendMessageData *data)
2289 {
2290   if (g_atomic_int_dec_and_test (&data->ref_count))
2291     {
2292       g_assert (data->timeout_source == NULL);
2293       g_assert (data->simple == NULL);
2294       g_assert (data->cancellable_handler_id == 0);
2295       g_object_unref (data->connection);
2296       if (data->cancellable != NULL)
2297         g_object_unref (data->cancellable);
2298       g_main_context_unref (data->main_context);
2299       g_free (data);
2300     }
2301 }
2302
2303 /* ---------------------------------------------------------------------------------------------------- */
2304
2305 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
2306 static void
2307 send_message_with_reply_deliver (SendMessageData *data, gboolean remove)
2308 {
2309   CONNECTION_ENSURE_LOCK (data->connection);
2310
2311   g_assert (!data->delivered);
2312
2313   data->delivered = TRUE;
2314
2315   g_simple_async_result_complete_in_idle (data->simple);
2316   g_object_unref (data->simple);
2317   data->simple = NULL;
2318
2319   if (data->timeout_source != NULL)
2320     {
2321       g_source_destroy (data->timeout_source);
2322       data->timeout_source = NULL;
2323     }
2324   if (data->cancellable_handler_id > 0)
2325     {
2326       g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
2327       data->cancellable_handler_id = 0;
2328     }
2329
2330   if (remove)
2331     {
2332       g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
2333                                            GUINT_TO_POINTER (data->serial)));
2334     }
2335
2336   send_message_data_unref (data);
2337 }
2338
2339 /* ---------------------------------------------------------------------------------------------------- */
2340
2341 /* Can be called from any thread with lock held */
2342 static void
2343 send_message_data_deliver_reply_unlocked (SendMessageData *data,
2344                                           GDBusMessage    *reply)
2345 {
2346   if (data->delivered)
2347     goto out;
2348
2349   g_simple_async_result_set_op_res_gpointer (data->simple,
2350                                              g_object_ref (reply),
2351                                              g_object_unref);
2352
2353   send_message_with_reply_deliver (data, TRUE);
2354
2355  out:
2356   ;
2357 }
2358
2359 /* ---------------------------------------------------------------------------------------------------- */
2360
2361 /* Called from a user thread, lock is not held */
2362 static gboolean
2363 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
2364 {
2365   SendMessageData *data = user_data;
2366
2367   CONNECTION_LOCK (data->connection);
2368   if (data->delivered)
2369     goto out;
2370
2371   g_simple_async_result_set_error (data->simple,
2372                                    G_IO_ERROR,
2373                                    G_IO_ERROR_CANCELLED,
2374                                    _("Operation was cancelled"));
2375
2376   send_message_with_reply_deliver (data, TRUE);
2377
2378  out:
2379   CONNECTION_UNLOCK (data->connection);
2380   return FALSE;
2381 }
2382
2383 /* Can be called from any thread with or without lock held */
2384 static void
2385 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
2386                                       gpointer      user_data)
2387 {
2388   SendMessageData *data = user_data;
2389   GSource *idle_source;
2390
2391   /* postpone cancellation to idle handler since we may be called directly
2392    * via g_cancellable_connect() (e.g. holding lock)
2393    */
2394   idle_source = g_idle_source_new ();
2395   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
2396   g_source_set_callback (idle_source,
2397                          send_message_with_reply_cancelled_idle_cb,
2398                          send_message_data_ref (data),
2399                          (GDestroyNotify) send_message_data_unref);
2400   g_source_set_name (idle_source, "[gio] send_message_with_reply_cancelled_idle_cb");
2401   g_source_attach (idle_source, data->main_context);
2402   g_source_unref (idle_source);
2403 }
2404
2405 /* ---------------------------------------------------------------------------------------------------- */
2406
2407 /* Called from a user thread, lock is not held */
2408 static gboolean
2409 send_message_with_reply_timeout_cb (gpointer user_data)
2410 {
2411   SendMessageData *data = user_data;
2412
2413   CONNECTION_LOCK (data->connection);
2414   if (data->delivered)
2415     goto out;
2416
2417   g_simple_async_result_set_error (data->simple,
2418                                    G_IO_ERROR,
2419                                    G_IO_ERROR_TIMED_OUT,
2420                                    _("Timeout was reached"));
2421
2422   send_message_with_reply_deliver (data, TRUE);
2423
2424  out:
2425   CONNECTION_UNLOCK (data->connection);
2426
2427   return FALSE;
2428 }
2429
2430 /* ---------------------------------------------------------------------------------------------------- */
2431
2432 /* Called from a user thread, connection's lock is held */
2433 static void
2434 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection     *connection,
2435                                                     GDBusMessage        *message,
2436                                                     GDBusSendMessageFlags flags,
2437                                                     gint                 timeout_msec,
2438                                                     volatile guint32    *out_serial,
2439                                                     GCancellable        *cancellable,
2440                                                     GAsyncReadyCallback  callback,
2441                                                     gpointer             user_data)
2442 {
2443   GSimpleAsyncResult *simple;
2444   SendMessageData *data;
2445   GError *error;
2446   volatile guint32 serial;
2447
2448   data = NULL;
2449
2450   if (out_serial == NULL)
2451     out_serial = &serial;
2452
2453   if (timeout_msec == -1)
2454     timeout_msec = 25 * 1000;
2455
2456   simple = g_simple_async_result_new (G_OBJECT (connection),
2457                                       callback,
2458                                       user_data,
2459                                       g_dbus_connection_send_message_with_reply);
2460   g_simple_async_result_set_check_cancellable (simple, cancellable);
2461
2462   if (g_cancellable_is_cancelled (cancellable))
2463     {
2464       g_simple_async_result_set_error (simple,
2465                                        G_IO_ERROR,
2466                                        G_IO_ERROR_CANCELLED,
2467                                        _("Operation was cancelled"));
2468       g_simple_async_result_complete_in_idle (simple);
2469       g_object_unref (simple);
2470       goto out;
2471     }
2472
2473   error = NULL;
2474   if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
2475     {
2476       g_simple_async_result_take_error (simple, error);
2477       g_simple_async_result_complete_in_idle (simple);
2478       g_object_unref (simple);
2479       goto out;
2480     }
2481
2482   data = g_new0 (SendMessageData, 1);
2483   data->ref_count = 1;
2484   data->connection = g_object_ref (connection);
2485   data->simple = simple;
2486   data->serial = *out_serial;
2487   data->main_context = g_main_context_ref_thread_default ();
2488
2489   if (cancellable != NULL)
2490     {
2491       data->cancellable = g_object_ref (cancellable);
2492       data->cancellable_handler_id = g_cancellable_connect (cancellable,
2493                                                             G_CALLBACK (send_message_with_reply_cancelled_cb),
2494                                                             send_message_data_ref (data),
2495                                                             (GDestroyNotify) send_message_data_unref);
2496     }
2497
2498   if (timeout_msec != G_MAXINT)
2499     {
2500       data->timeout_source = g_timeout_source_new (timeout_msec);
2501       g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
2502       g_source_set_callback (data->timeout_source,
2503                              send_message_with_reply_timeout_cb,
2504                              send_message_data_ref (data),
2505                              (GDestroyNotify) send_message_data_unref);
2506       g_source_attach (data->timeout_source, data->main_context);
2507       g_source_unref (data->timeout_source);
2508     }
2509
2510   g_hash_table_insert (connection->map_method_serial_to_send_message_data,
2511                        GUINT_TO_POINTER (*out_serial),
2512                        data);
2513
2514  out:
2515   ;
2516 }
2517
2518 /**
2519  * g_dbus_connection_send_message_with_reply:
2520  * @connection: a #GDBusConnection
2521  * @message: a #GDBusMessage
2522  * @flags: flags affecting how the message is sent
2523  * @timeout_msec: the timeout in milliseconds, -1 to use the default
2524  *     timeout or %G_MAXINT for no timeout
2525  * @out_serial: (out) (allow-none): return location for serial number assigned
2526  *     to @message when sending it or %NULL
2527  * @cancellable: (allow-none): a #GCancellable or %NULL
2528  * @callback: (allow-none): a #GAsyncReadyCallback to call when the request
2529  *     is satisfied or %NULL if you don't care about the result
2530  * @user_data: The data to pass to @callback
2531  *
2532  * Asynchronously sends @message to the peer represented by @connection.
2533  *
2534  * Unless @flags contain the
2535  * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2536  * will be assigned by @connection and set on @message via
2537  * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2538  * serial number used will be written to this location prior to
2539  * submitting the message to the underlying transport.
2540  *
2541  * If @connection is closed then the operation will fail with
2542  * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2543  * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2544  * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2545  *
2546  * This is an asynchronous method. When the operation is finished, @callback
2547  * will be invoked in the 
2548  * [thread-default main context][g-main-context-push-thread-default]
2549  * of the thread you are calling this method from. You can then call
2550  * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
2551  * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
2552  *
2553  * Note that @message must be unlocked, unless @flags contain the
2554  * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2555  *
2556  * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2557  * for an example of how to use this low-level API to send and receive
2558  * UNIX file descriptors.
2559  *
2560  * Since: 2.26
2561  */
2562 void
2563 g_dbus_connection_send_message_with_reply (GDBusConnection       *connection,
2564                                            GDBusMessage          *message,
2565                                            GDBusSendMessageFlags  flags,
2566                                            gint                   timeout_msec,
2567                                            volatile guint32      *out_serial,
2568                                            GCancellable          *cancellable,
2569                                            GAsyncReadyCallback    callback,
2570                                            gpointer               user_data)
2571 {
2572   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2573   g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2574   g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2575   g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2576
2577   CONNECTION_LOCK (connection);
2578   g_dbus_connection_send_message_with_reply_unlocked (connection,
2579                                                       message,
2580                                                       flags,
2581                                                       timeout_msec,
2582                                                       out_serial,
2583                                                       cancellable,
2584                                                       callback,
2585                                                       user_data);
2586   CONNECTION_UNLOCK (connection);
2587 }
2588
2589 /**
2590  * g_dbus_connection_send_message_with_reply_finish:
2591  * @connection: a #GDBusConnection
2592  * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
2593  *     g_dbus_connection_send_message_with_reply()
2594  * @error: teturn location for error or %NULL
2595  *
2596  * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2597  *
2598  * Note that @error is only set if a local in-process error
2599  * occurred. That is to say that the returned #GDBusMessage object may
2600  * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2601  * g_dbus_message_to_gerror() to transcode this to a #GError.
2602  *
2603  * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2604  * for an example of how to use this low-level API to send and receive
2605  * UNIX file descriptors.
2606  *
2607  * Returns: (transfer full): a locked #GDBusMessage or %NULL if @error is set
2608  *
2609  * Since: 2.26
2610  */
2611 GDBusMessage *
2612 g_dbus_connection_send_message_with_reply_finish (GDBusConnection  *connection,
2613                                                   GAsyncResult     *res,
2614                                                   GError          **error)
2615 {
2616   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2617   GDBusMessage *reply;
2618
2619   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2620   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2621
2622   reply = NULL;
2623
2624   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
2625
2626   if (g_simple_async_result_propagate_error (simple, error))
2627     goto out;
2628
2629   reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
2630
2631  out:
2632   return reply;
2633 }
2634
2635 /* ---------------------------------------------------------------------------------------------------- */
2636
2637 typedef struct
2638 {
2639   GAsyncResult *res;
2640   GMainContext *context;
2641   GMainLoop *loop;
2642 } SendMessageSyncData;
2643
2644 /* Called from a user thread, lock is not held */
2645 static void
2646 send_message_with_reply_sync_cb (GDBusConnection *connection,
2647                                  GAsyncResult    *res,
2648                                  gpointer         user_data)
2649 {
2650   SendMessageSyncData *data = user_data;
2651   data->res = g_object_ref (res);
2652   g_main_loop_quit (data->loop);
2653 }
2654
2655 /**
2656  * g_dbus_connection_send_message_with_reply_sync:
2657  * @connection: a #GDBusConnection
2658  * @message: a #GDBusMessage
2659  * @flags: flags affecting how the message is sent.
2660  * @timeout_msec: the timeout in milliseconds, -1 to use the default
2661  *     timeout or %G_MAXINT for no timeout
2662  * @out_serial: (out) (allow-none): return location for serial number
2663  *     assigned to @message when sending it or %NULL
2664  * @cancellable: (allow-none): a #GCancellable or %NULL
2665  * @error: return location for error or %NULL
2666  *
2667  * Synchronously sends @message to the peer represented by @connection
2668  * and blocks the calling thread until a reply is received or the
2669  * timeout is reached. See g_dbus_connection_send_message_with_reply()
2670  * for the asynchronous version of this method.
2671  *
2672  * Unless @flags contain the
2673  * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2674  * will be assigned by @connection and set on @message via
2675  * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2676  * serial number used will be written to this location prior to
2677  * submitting the message to the underlying transport.
2678  *
2679  * If @connection is closed then the operation will fail with
2680  * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2681  * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2682  * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2683  *
2684  * Note that @error is only set if a local in-process error
2685  * occurred. That is to say that the returned #GDBusMessage object may
2686  * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2687  * g_dbus_message_to_gerror() to transcode this to a #GError.
2688  *
2689  * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2690  * for an example of how to use this low-level API to send and receive
2691  * UNIX file descriptors.
2692  *
2693  * Note that @message must be unlocked, unless @flags contain the
2694  * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2695  *
2696  * Returns: (transfer full): a locked #GDBusMessage that is the reply
2697  *     to @message or %NULL if @error is set
2698  *
2699  * Since: 2.26
2700  */
2701 GDBusMessage *
2702 g_dbus_connection_send_message_with_reply_sync (GDBusConnection        *connection,
2703                                                 GDBusMessage           *message,
2704                                                 GDBusSendMessageFlags   flags,
2705                                                 gint                    timeout_msec,
2706                                                 volatile guint32       *out_serial,
2707                                                 GCancellable           *cancellable,
2708                                                 GError                **error)
2709 {
2710   SendMessageSyncData *data;
2711   GDBusMessage *reply;
2712
2713   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2714   g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2715   g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2716   g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2717   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2718
2719   data = g_new0 (SendMessageSyncData, 1);
2720   data->context = g_main_context_new ();
2721   data->loop = g_main_loop_new (data->context, FALSE);
2722
2723   g_main_context_push_thread_default (data->context);
2724
2725   g_dbus_connection_send_message_with_reply (connection,
2726                                              message,
2727                                              flags,
2728                                              timeout_msec,
2729                                              out_serial,
2730                                              cancellable,
2731                                              (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2732                                              data);
2733   g_main_loop_run (data->loop);
2734   reply = g_dbus_connection_send_message_with_reply_finish (connection,
2735                                                             data->res,
2736                                                             error);
2737
2738   g_main_context_pop_thread_default (data->context);
2739
2740   g_main_context_unref (data->context);
2741   g_main_loop_unref (data->loop);
2742   g_object_unref (data->res);
2743   g_free (data);
2744
2745   return reply;
2746 }
2747
2748 /* ---------------------------------------------------------------------------------------------------- */
2749
2750 typedef struct
2751 {
2752   GDBusMessageFilterFunction func;
2753   gpointer user_data;
2754 } FilterCallback;
2755
2756 typedef struct
2757 {
2758   guint                       id;
2759   GDBusMessageFilterFunction  filter_function;
2760   gpointer                    user_data;
2761   GDestroyNotify              user_data_free_func;
2762 } FilterData;
2763
2764 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2765 static void
2766 on_worker_message_received (GDBusWorker  *worker,
2767                             GDBusMessage *message,
2768                             gpointer      user_data)
2769 {
2770   GDBusConnection *connection;
2771   FilterCallback *filters;
2772   guint num_filters;
2773   guint n;
2774   gboolean alive;
2775
2776   G_LOCK (message_bus_lock);
2777   alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2778   if (!alive)
2779     {
2780       G_UNLOCK (message_bus_lock);
2781       return;
2782     }
2783   connection = G_DBUS_CONNECTION (user_data);
2784   g_object_ref (connection);
2785   G_UNLOCK (message_bus_lock);
2786
2787   //g_debug ("in on_worker_message_received");
2788
2789   g_object_ref (message);
2790   g_dbus_message_lock (message);
2791
2792   //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2793
2794   /* First collect the set of callback functions */
2795   CONNECTION_LOCK (connection);
2796   num_filters = connection->filters->len;
2797   filters = g_new0 (FilterCallback, num_filters);
2798   for (n = 0; n < num_filters; n++)
2799     {
2800       FilterData *data = connection->filters->pdata[n];
2801       filters[n].func = data->filter_function;
2802       filters[n].user_data = data->user_data;
2803     }
2804   CONNECTION_UNLOCK (connection);
2805
2806   /* then call the filters in order (without holding the lock) */
2807   for (n = 0; n < num_filters; n++)
2808     {
2809       message = filters[n].func (connection,
2810                                  message,
2811                                  TRUE,
2812                                  filters[n].user_data);
2813       if (message == NULL)
2814         break;
2815       g_dbus_message_lock (message);
2816     }
2817
2818   /* Standard dispatch unless the filter ate the message - no need to
2819    * do anything if the message was altered
2820    */
2821   if (message != NULL)
2822     {
2823       GDBusMessageType message_type;
2824
2825       message_type = g_dbus_message_get_message_type (message);
2826       if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2827         {
2828           guint32 reply_serial;
2829           SendMessageData *send_message_data;
2830
2831           reply_serial = g_dbus_message_get_reply_serial (message);
2832           CONNECTION_LOCK (connection);
2833           send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2834                                                    GUINT_TO_POINTER (reply_serial));
2835           if (send_message_data != NULL)
2836             {
2837               //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2838               send_message_data_deliver_reply_unlocked (send_message_data, message);
2839             }
2840           else
2841             {
2842               //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2843             }
2844           CONNECTION_UNLOCK (connection);
2845         }
2846       else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2847         {
2848           CONNECTION_LOCK (connection);
2849           distribute_signals (connection, message);
2850           CONNECTION_UNLOCK (connection);
2851         }
2852       else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2853         {
2854           CONNECTION_LOCK (connection);
2855           distribute_method_call (connection, message);
2856           CONNECTION_UNLOCK (connection);
2857         }
2858     }
2859
2860   if (message != NULL)
2861     g_object_unref (message);
2862   g_object_unref (connection);
2863   g_free (filters);
2864 }
2865
2866 /* Called in GDBusWorker's thread, lock is not held */
2867 static GDBusMessage *
2868 on_worker_message_about_to_be_sent (GDBusWorker  *worker,
2869                                     GDBusMessage *message,
2870                                     gpointer      user_data)
2871 {
2872   GDBusConnection *connection;
2873   FilterCallback *filters;
2874   guint num_filters;
2875   guint n;
2876   gboolean alive;
2877
2878   G_LOCK (message_bus_lock);
2879   alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2880   if (!alive)
2881     {
2882       G_UNLOCK (message_bus_lock);
2883       return message;
2884     }
2885   connection = G_DBUS_CONNECTION (user_data);
2886   g_object_ref (connection);
2887   G_UNLOCK (message_bus_lock);
2888
2889   //g_debug ("in on_worker_message_about_to_be_sent");
2890
2891   /* First collect the set of callback functions */
2892   CONNECTION_LOCK (connection);
2893   num_filters = connection->filters->len;
2894   filters = g_new0 (FilterCallback, num_filters);
2895   for (n = 0; n < num_filters; n++)
2896     {
2897       FilterData *data = connection->filters->pdata[n];
2898       filters[n].func = data->filter_function;
2899       filters[n].user_data = data->user_data;
2900     }
2901   CONNECTION_UNLOCK (connection);
2902
2903   /* then call the filters in order (without holding the lock) */
2904   for (n = 0; n < num_filters; n++)
2905     {
2906       g_dbus_message_lock (message);
2907       message = filters[n].func (connection,
2908                                  message,
2909                                  FALSE,
2910                                  filters[n].user_data);
2911       if (message == NULL)
2912         break;
2913     }
2914
2915   g_object_unref (connection);
2916   g_free (filters);
2917
2918   return message;
2919 }
2920
2921 /* called with connection lock held, in GDBusWorker thread */
2922 static gboolean
2923 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2924 {
2925   SendMessageData *data = value;
2926
2927   if (data->delivered)
2928     return FALSE;
2929
2930   g_simple_async_result_set_error (data->simple,
2931                                    G_IO_ERROR,
2932                                    G_IO_ERROR_CLOSED,
2933                                    _("The connection is closed"));
2934
2935   /* Ask send_message_with_reply_deliver not to remove the element from the
2936    * hash table - we're in the middle of a foreach; that would be unsafe.
2937    * Instead, return TRUE from this function so that it gets removed safely.
2938    */
2939   send_message_with_reply_deliver (data, FALSE);
2940   return TRUE;
2941 }
2942
2943 /* Called in GDBusWorker's thread - we must not block - without lock held */
2944 static void
2945 on_worker_closed (GDBusWorker *worker,
2946                   gboolean     remote_peer_vanished,
2947                   GError      *error,
2948                   gpointer     user_data)
2949 {
2950   GDBusConnection *connection;
2951   gboolean alive;
2952   guint old_atomic_flags;
2953
2954   G_LOCK (message_bus_lock);
2955   alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2956   if (!alive)
2957     {
2958       G_UNLOCK (message_bus_lock);
2959       return;
2960     }
2961   connection = G_DBUS_CONNECTION (user_data);
2962   g_object_ref (connection);
2963   G_UNLOCK (message_bus_lock);
2964
2965   //g_debug ("in on_worker_closed: %s", error->message);
2966
2967   CONNECTION_LOCK (connection);
2968   /* Even though this is atomic, we do it inside the lock to avoid breaking
2969    * assumptions in remove_match_rule(). We'd need the lock in a moment
2970    * anyway, so, no loss.
2971    */
2972   old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
2973
2974   if (!(old_atomic_flags & FLAG_CLOSED))
2975     {
2976       g_hash_table_foreach_remove (connection->map_method_serial_to_send_message_data, cancel_method_on_close, NULL);
2977       schedule_closed_unlocked (connection, remote_peer_vanished, error);
2978     }
2979   CONNECTION_UNLOCK (connection);
2980
2981   g_object_unref (connection);
2982 }
2983
2984 /* ---------------------------------------------------------------------------------------------------- */
2985
2986 /* Determines the biggest set of capabilities we can support on this
2987  * connection.
2988  *
2989  * Called with the init_lock held.
2990  */
2991 static GDBusCapabilityFlags
2992 get_offered_capabilities_max (GDBusConnection *connection)
2993 {
2994       GDBusCapabilityFlags ret;
2995       ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2996 #ifdef G_OS_UNIX
2997       if (G_IS_UNIX_CONNECTION (connection->stream))
2998         ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2999 #endif
3000       return ret;
3001 }
3002
3003 /* Called in a user thread, lock is not held */
3004 static gboolean
3005 initable_init (GInitable     *initable,
3006                GCancellable  *cancellable,
3007                GError       **error)
3008 {
3009   GDBusConnection *connection = G_DBUS_CONNECTION (initable);
3010   gboolean ret;
3011
3012   /* This method needs to be idempotent to work with the singleton
3013    * pattern. See the docs for g_initable_init(). We implement this by
3014    * locking.
3015    *
3016    * Unfortunately we can't use the main lock since the on_worker_*()
3017    * callbacks above needs the lock during initialization (for message
3018    * bus connections we do a synchronous Hello() call on the bus).
3019    */
3020   g_mutex_lock (&connection->init_lock);
3021
3022   ret = FALSE;
3023
3024   /* Make this a no-op if we're already initialized (successfully or
3025    * unsuccessfully)
3026    */
3027   if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
3028     {
3029       ret = (connection->initialization_error == NULL);
3030       goto out;
3031     }
3032
3033   /* Because of init_lock, we can't get here twice in different threads */
3034   g_assert (connection->initialization_error == NULL);
3035
3036   /* The user can pass multiple (but mutally exclusive) construct
3037    * properties:
3038    *
3039    *  - stream (of type GIOStream)
3040    *  - address (of type gchar*)
3041    *
3042    * At the end of the day we end up with a non-NULL GIOStream
3043    * object in connection->stream.
3044    */
3045   if (connection->address != NULL)
3046     {
3047       g_assert (connection->stream == NULL);
3048
3049       if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
3050           (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
3051         {
3052           g_set_error_literal (&connection->initialization_error,
3053                                G_IO_ERROR,
3054                                G_IO_ERROR_INVALID_ARGUMENT,
3055                                _("Unsupported flags encountered when constructing a client-side connection"));
3056           goto out;
3057         }
3058
3059       connection->stream = g_dbus_address_get_stream_sync (connection->address,
3060                                                            NULL, /* TODO: out_guid */
3061                                                            cancellable,
3062                                                            &connection->initialization_error);
3063       if (connection->stream == NULL)
3064         goto out;
3065     }
3066   else if (connection->stream != NULL)
3067     {
3068       /* nothing to do */
3069     }
3070   else
3071     {
3072       g_assert_not_reached ();
3073     }
3074
3075   /* [KDBUS] Skip authentication process for kdbus transport */
3076   if (G_IS_KDBUS_CONNECTION (connection->stream))
3077     {
3078       goto authenticated;
3079     }
3080
3081   /* Authenticate the connection */
3082   if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
3083     {
3084       g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
3085       g_assert (connection->guid != NULL);
3086       connection->auth = _g_dbus_auth_new (connection->stream);
3087       if (!_g_dbus_auth_run_server (connection->auth,
3088                                     connection->authentication_observer,
3089                                     connection->guid,
3090                                     (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
3091                                     get_offered_capabilities_max (connection),
3092                                     &connection->capabilities,
3093                                     &connection->credentials,
3094                                     cancellable,
3095                                     &connection->initialization_error))
3096         goto out;
3097     }
3098   else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
3099     {
3100       g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
3101       g_assert (connection->guid == NULL);
3102       connection->auth = _g_dbus_auth_new (connection->stream);
3103       connection->guid = _g_dbus_auth_run_client (connection->auth,
3104                                                   connection->authentication_observer,
3105                                                   get_offered_capabilities_max (connection),
3106                                                   &connection->capabilities,
3107                                                   cancellable,
3108                                                   &connection->initialization_error);
3109       if (connection->guid == NULL)
3110         goto out;
3111     }
3112
3113   if (connection->authentication_observer != NULL)
3114     {
3115       g_object_unref (connection->authentication_observer);
3116       connection->authentication_observer = NULL;
3117     }
3118
3119 authenticated:
3120
3121   //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
3122
3123   //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
3124
3125 #ifdef G_OS_UNIX
3126   /* We want all IO operations to be non-blocking since they happen in
3127    * the worker thread which is shared by _all_ connections.
3128    */
3129   if (G_IS_SOCKET_CONNECTION (connection->stream))
3130     {
3131       g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
3132     }
3133 #endif
3134
3135   G_LOCK (message_bus_lock);
3136   if (alive_connections == NULL)
3137     alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
3138   g_hash_table_insert (alive_connections, connection, connection);
3139   G_UNLOCK (message_bus_lock);
3140
3141   connection->worker = _g_dbus_worker_new (connection->stream,
3142                                            connection->capabilities,
3143                                            ((connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) != 0),
3144                                            on_worker_message_received,
3145                                            on_worker_message_about_to_be_sent,
3146                                            on_worker_closed,
3147                                            connection);
3148
3149   /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
3150   if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3151     {
3152       GVariant *hello_result;
3153
3154       /* we could lift this restriction by adding code in gdbusprivate.c */
3155       if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
3156         {
3157           g_set_error_literal (&connection->initialization_error,
3158                                G_IO_ERROR,
3159                                G_IO_ERROR_FAILED,
3160                                "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
3161           goto out;
3162         }
3163
3164       if (G_IS_KDBUS_CONNECTION (connection->stream))
3165         {
3166           hello_result = _g_kdbus_Hello (connection->stream, &connection->initialization_error);
3167         }
3168       else
3169         {
3170           hello_result = g_dbus_connection_call_sync (connection,
3171                                                       "org.freedesktop.DBus", /* name */
3172                                                       "/org/freedesktop/DBus", /* path */
3173                                                       "org.freedesktop.DBus", /* interface */
3174                                                       "Hello",
3175                                                       NULL, /* parameters */
3176                                                       G_VARIANT_TYPE ("(s)"),
3177                                                       CALL_FLAGS_INITIALIZING,
3178                                                       -1,
3179                                                       NULL, /* TODO: cancellable */
3180                                                       &connection->initialization_error);
3181         }
3182
3183       if (hello_result == NULL)
3184         goto out;
3185
3186       g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
3187       g_variant_unref (hello_result);
3188       //g_debug ("unique name is '%s'", connection->bus_unique_name);
3189     }
3190
3191   ret = TRUE;
3192  out:
3193   if (!ret)
3194     {
3195       g_assert (connection->initialization_error != NULL);
3196       g_propagate_error (error, g_error_copy (connection->initialization_error));
3197     }
3198
3199   g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
3200   g_mutex_unlock (&connection->init_lock);
3201
3202   return ret;
3203 }
3204
3205 static void
3206 initable_iface_init (GInitableIface *initable_iface)
3207 {
3208   initable_iface->init = initable_init;
3209 }
3210
3211 /* ---------------------------------------------------------------------------------------------------- */
3212
3213 static void
3214 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
3215 {
3216   /* Use default */
3217 }
3218
3219 /* ---------------------------------------------------------------------------------------------------- */
3220
3221 /**
3222  * g_dbus_connection_new:
3223  * @stream: a #GIOStream
3224  * @guid: (allow-none): the GUID to use if a authenticating as a server or %NULL
3225  * @flags: flags describing how to make the connection
3226  * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3227  * @cancellable: (allow-none): a #GCancellable or %NULL
3228  * @callback: a #GAsyncReadyCallback to call when the request is satisfied
3229  * @user_data: the data to pass to @callback
3230  *
3231  * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
3232  * with the end represented by @stream.
3233  *
3234  * If @stream is a #GSocketConnection, then the corresponding #GSocket
3235  * will be put into non-blocking mode.
3236  *
3237  * The D-Bus connection will interact with @stream from a worker thread.
3238  * As a result, the caller should not interact with @stream after this
3239  * method has been called, except by calling g_object_unref() on it.
3240  *
3241  * If @observer is not %NULL it may be used to control the
3242  * authentication process.
3243  *
3244  * When the operation is finished, @callback will be invoked. You can
3245  * then call g_dbus_connection_new_finish() to get the result of the
3246  * operation.
3247  *
3248  * This is a asynchronous failable constructor. See
3249  * g_dbus_connection_new_sync() for the synchronous
3250  * version.
3251  *
3252  * Since: 2.26
3253  */
3254 void
3255 g_dbus_connection_new (GIOStream            *stream,
3256                        const gchar          *guid,
3257                        GDBusConnectionFlags  flags,
3258                        GDBusAuthObserver    *observer,
3259                        GCancellable         *cancellable,
3260                        GAsyncReadyCallback   callback,
3261                        gpointer              user_data)
3262 {
3263   g_return_if_fail (G_IS_IO_STREAM (stream));
3264   g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
3265                               G_PRIORITY_DEFAULT,
3266                               cancellable,
3267                               callback,
3268                               user_data,
3269                               "stream", stream,
3270                               "guid", guid,
3271                               "flags", flags,
3272                               "authentication-observer", observer,
3273                               NULL);
3274 }
3275
3276 /**
3277  * g_dbus_connection_new_finish:
3278  * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback
3279  *     passed to g_dbus_connection_new().
3280  * @error: return location for error or %NULL
3281  *
3282  * Finishes an operation started with g_dbus_connection_new().
3283  *
3284  * Returns: a #GDBusConnection or %NULL if @error is set. Free
3285  *     with g_object_unref().
3286  *
3287  * Since: 2.26
3288  */
3289 GDBusConnection *
3290 g_dbus_connection_new_finish (GAsyncResult  *res,
3291                               GError       **error)
3292 {
3293   GObject *object;
3294   GObject *source_object;
3295
3296   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
3297   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3298
3299   source_object = g_async_result_get_source_object (res);
3300   g_assert (source_object != NULL);
3301   object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
3302                                         res,
3303                                         error);
3304   g_object_unref (source_object);
3305   if (object != NULL)
3306     return G_DBUS_CONNECTION (object);
3307   else
3308     return NULL;
3309 }
3310
3311 /**
3312  * g_dbus_connection_new_sync:
3313  * @stream: a #GIOStream
3314  * @guid: (allow-none): the GUID to use if a authenticating as a server or %NULL
3315  * @flags: flags describing how to make the connection
3316  * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3317  * @cancellable: (allow-none): a #GCancellable or %NULL
3318  * @error: return location for error or %NULL
3319  *
3320  * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
3321  * with the end represented by @stream.
3322  *
3323  * If @stream is a #GSocketConnection, then the corresponding #GSocket
3324  * will be put into non-blocking mode.
3325  *
3326  * The D-Bus connection will interact with @stream from a worker thread.
3327  * As a result, the caller should not interact with @stream after this
3328  * method has been called, except by calling g_object_unref() on it.
3329  *
3330  * If @observer is not %NULL it may be used to control the
3331  * authentication process.
3332  *
3333  * This is a synchronous failable constructor. See
3334  * g_dbus_connection_new() for the asynchronous version.
3335  *
3336  * Returns: a #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
3337  *
3338  * Since: 2.26
3339  */
3340 GDBusConnection *
3341 g_dbus_connection_new_sync (GIOStream             *stream,
3342                             const gchar           *guid,
3343                             GDBusConnectionFlags   flags,
3344                             GDBusAuthObserver     *observer,
3345                             GCancellable          *cancellable,
3346                             GError               **error)
3347 {
3348   g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
3349   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3350   return g_initable_new (G_TYPE_DBUS_CONNECTION,
3351                          cancellable,
3352                          error,
3353                          "stream", stream,
3354                          "guid", guid,
3355                          "flags", flags,
3356                          "authentication-observer", observer,
3357                          NULL);
3358 }
3359
3360 /* ---------------------------------------------------------------------------------------------------- */
3361
3362 /**
3363  * g_dbus_connection_new_for_address:
3364  * @address: a D-Bus address
3365  * @flags: flags describing how to make the connection
3366  * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3367  * @cancellable: (allow-none): a #GCancellable or %NULL
3368  * @callback: a #GAsyncReadyCallback to call when the request is satisfied
3369  * @user_data: the data to pass to @callback
3370  *
3371  * Asynchronously connects and sets up a D-Bus client connection for
3372  * exchanging D-Bus messages with an endpoint specified by @address
3373  * which must be in the D-Bus address format.
3374  *
3375  * This constructor can only be used to initiate client-side
3376  * connections - use g_dbus_connection_new() if you need to act as the
3377  * server. In particular, @flags cannot contain the
3378  * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
3379  * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
3380  *
3381  * When the operation is finished, @callback will be invoked. You can
3382  * then call g_dbus_connection_new_finish() to get the result of the
3383  * operation.
3384  *
3385  * If @observer is not %NULL it may be used to control the
3386  * authentication process.
3387  *
3388  * This is a asynchronous failable constructor. See
3389  * g_dbus_connection_new_for_address_sync() for the synchronous
3390  * version.
3391  *
3392  * Since: 2.26
3393  */
3394 void
3395 g_dbus_connection_new_for_address (const gchar          *address,
3396                                    GDBusConnectionFlags  flags,
3397                                    GDBusAuthObserver    *observer,
3398                                    GCancellable         *cancellable,
3399                                    GAsyncReadyCallback   callback,
3400                                    gpointer              user_data)
3401 {
3402   g_return_if_fail (address != NULL);
3403   g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
3404                               G_PRIORITY_DEFAULT,
3405                               cancellable,
3406                               callback,
3407                               user_data,
3408                               "address", address,
3409                               "flags", flags,
3410                               "authentication-observer", observer,
3411                               NULL);
3412 }
3413
3414 /**
3415  * g_dbus_connection_new_for_address_finish:
3416  * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
3417  *     to g_dbus_connection_new()
3418  * @error: return location for error or %NULL
3419  *
3420  * Finishes an operation started with g_dbus_connection_new_for_address().
3421  *
3422  * Returns: a #GDBusConnection or %NULL if @error is set. Free with
3423  *     g_object_unref().
3424  *
3425  * Since: 2.26
3426  */
3427 GDBusConnection *
3428 g_dbus_connection_new_for_address_finish (GAsyncResult  *res,
3429                                           GError       **error)
3430 {
3431   GObject *object;
3432   GObject *source_object;
3433
3434   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
3435   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3436
3437   source_object = g_async_result_get_source_object (res);
3438   g_assert (source_object != NULL);
3439   object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
3440                                         res,
3441                                         error);
3442   g_object_unref (source_object);
3443   if (object != NULL)
3444     return G_DBUS_CONNECTION (object);
3445   else
3446     return NULL;
3447 }
3448
3449 /**
3450  * g_dbus_connection_new_for_address_sync:
3451  * @address: a D-Bus address
3452  * @flags: flags describing how to make the connection
3453  * @observer: (allow-none): a #GDBusAuthObserver or %NULL
3454  * @cancellable: (allow-none): a #GCancellable or %NULL
3455  * @error: return location for error or %NULL
3456  *
3457  * Synchronously connects and sets up a D-Bus client connection for
3458  * exchanging D-Bus messages with an endpoint specified by @address
3459  * which must be in the D-Bus address format.
3460  *
3461  * This constructor can only be used to initiate client-side
3462  * connections - use g_dbus_connection_new_sync() if you need to act
3463  * as the server. In particular, @flags cannot contain the
3464  * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
3465  * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
3466  *
3467  * This is a synchronous failable constructor. See
3468  * g_dbus_connection_new_for_address() for the asynchronous version.
3469  *
3470  * If @observer is not %NULL it may be used to control the
3471  * authentication process.
3472  *
3473  * Returns: a #GDBusConnection or %NULL if @error is set. Free with
3474  *     g_object_unref().
3475  *
3476  * Since: 2.26
3477  */
3478 GDBusConnection *
3479 g_dbus_connection_new_for_address_sync (const gchar           *address,
3480                                         GDBusConnectionFlags   flags,
3481                                         GDBusAuthObserver     *observer,
3482                                         GCancellable          *cancellable,
3483                                         GError               **error)
3484 {
3485   g_return_val_if_fail (address != NULL, NULL);
3486   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3487   return g_initable_new (G_TYPE_DBUS_CONNECTION,
3488                          cancellable,
3489                          error,
3490                          "address", address,
3491                          "flags", flags,
3492                          "authentication-observer", observer,
3493                          NULL);
3494 }
3495
3496 /* ---------------------------------------------------------------------------------------------------- */
3497
3498 /**
3499  * g_dbus_connection_set_exit_on_close:
3500  * @connection: a #GDBusConnection
3501  * @exit_on_close: whether the process should be terminated
3502  *     when @connection is closed by the remote peer
3503  *
3504  * Sets whether the process should be terminated when @connection is
3505  * closed by the remote peer. See #GDBusConnection:exit-on-close for
3506  * more details.
3507  *
3508  * Note that this function should be used with care. Most modern UNIX
3509  * desktops tie the notion of a user session the session bus, and expect
3510  * all of a users applications to quit when their bus connection goes away.
3511  * If you are setting @exit_on_close to %FALSE for the shared session
3512  * bus connection, you should make sure that your application exits
3513  * when the user session ends.
3514  *
3515  * Since: 2.26
3516  */
3517 void
3518 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
3519                                      gboolean         exit_on_close)
3520 {
3521   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3522
3523   if (exit_on_close)
3524     g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
3525   else
3526     g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
3527
3528 }
3529
3530 /**
3531  * g_dbus_connection_get_exit_on_close:
3532  * @connection: a #GDBusConnection
3533  *
3534  * Gets whether the process is terminated when @connection is
3535  * closed by the remote peer. See
3536  * #GDBusConnection:exit-on-close for more details.
3537  *
3538  * Returns: whether the process is terminated when @connection is
3539  *     closed by the remote peer
3540  *
3541  * Since: 2.26
3542  */
3543 gboolean
3544 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
3545 {
3546   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3547
3548   if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
3549     return TRUE;
3550   else
3551     return FALSE;
3552 }
3553
3554 /**
3555  * g_dbus_connection_get_guid:
3556  * @connection: a #GDBusConnection
3557  *
3558  * The GUID of the peer performing the role of server when
3559  * authenticating. See #GDBusConnection:guid for more details.
3560  *
3561  * Returns: The GUID. Do not free this string, it is owned by
3562  *     @connection.
3563  *
3564  * Since: 2.26
3565  */
3566 const gchar *
3567 g_dbus_connection_get_guid (GDBusConnection *connection)
3568 {
3569   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3570   return connection->guid;
3571 }
3572
3573 /**
3574  * g_dbus_connection_get_unique_name:
3575  * @connection: a #GDBusConnection
3576  *
3577  * Gets the unique name of @connection as assigned by the message
3578  * bus. This can also be used to figure out if @connection is a
3579  * message bus connection.
3580  *
3581  * Returns: the unique name or %NULL if @connection is not a message
3582  *     bus connection. Do not free this string, it is owned by
3583  *     @connection.
3584  *
3585  * Since: 2.26
3586  */
3587 const gchar *
3588 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3589 {
3590   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3591
3592   /* do not use g_return_val_if_fail(), we want the memory barrier */
3593   if (!check_initialized (connection))
3594     return NULL;
3595
3596   return connection->bus_unique_name;
3597 }
3598
3599 /**
3600  * g_dbus_connection_get_peer_credentials:
3601  * @connection: a #GDBusConnection
3602  *
3603  * Gets the credentials of the authenticated peer. This will always
3604  * return %NULL unless @connection acted as a server
3605  * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3606  * when set up and the client passed credentials as part of the
3607  * authentication process.
3608  *
3609  * In a message bus setup, the message bus is always the server and
3610  * each application is a client. So this method will always return
3611  * %NULL for message bus clients.
3612  *
3613  * Returns: (transfer none): a #GCredentials or %NULL if not available.
3614  *     Do not free this object, it is owned by @connection.
3615  *
3616  * Since: 2.26
3617  */
3618 GCredentials *
3619 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3620 {
3621   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3622
3623   /* do not use g_return_val_if_fail(), we want the memory barrier */
3624   if (!check_initialized (connection))
3625     return NULL;
3626
3627   return connection->credentials;
3628 }
3629
3630 /* ---------------------------------------------------------------------------------------------------- */
3631
3632 static guint _global_filter_id = 1;
3633
3634 /**
3635  * g_dbus_connection_add_filter:
3636  * @connection: a #GDBusConnection
3637  * @filter_function: a filter function
3638  * @user_data: user data to pass to @filter_function
3639  * @user_data_free_func: function to free @user_data with when filter
3640  *     is removed or %NULL
3641  *
3642  * Adds a message filter. Filters are handlers that are run on all
3643  * incoming and outgoing messages, prior to standard dispatch. Filters
3644  * are run in the order that they were added.  The same handler can be
3645  * added as a filter more than once, in which case it will be run more
3646  * than once.  Filters added during a filter callback won't be run on
3647  * the message being processed. Filter functions are allowed to modify
3648  * and even drop messages.
3649  *
3650  * Note that filters are run in a dedicated message handling thread so
3651  * they can't block and, generally, can't do anything but signal a
3652  * worker thread. Also note that filters are rarely needed - use API
3653  * such as g_dbus_connection_send_message_with_reply(),
3654  * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3655  *
3656  * If a filter consumes an incoming message the message is not
3657  * dispatched anywhere else - not even the standard dispatch machinery
3658  * (that API such as g_dbus_connection_signal_subscribe() and
3659  * g_dbus_connection_send_message_with_reply() relies on) will see the
3660  * message. Similary, if a filter consumes an outgoing message, the
3661  * message will not be sent to the other peer.
3662  *
3663  * Returns: a filter identifier that can be used with
3664  *     g_dbus_connection_remove_filter()
3665  *
3666  * Since: 2.26
3667  */
3668 guint
3669 g_dbus_connection_add_filter (GDBusConnection            *connection,
3670                               GDBusMessageFilterFunction  filter_function,
3671                               gpointer                    user_data,
3672                               GDestroyNotify              user_data_free_func)
3673 {
3674   FilterData *data;
3675
3676   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3677   g_return_val_if_fail (filter_function != NULL, 0);
3678   g_return_val_if_fail (check_initialized (connection), 0);
3679
3680   CONNECTION_LOCK (connection);
3681   data = g_new0 (FilterData, 1);
3682   data->id = _global_filter_id++; /* TODO: overflow etc. */
3683   data->filter_function = filter_function;
3684   data->user_data = user_data;
3685   data->user_data_free_func = user_data_free_func;
3686   g_ptr_array_add (connection->filters, data);
3687   CONNECTION_UNLOCK (connection);
3688
3689   return data->id;
3690 }
3691
3692 /* only called from finalize(), removes all filters */
3693 static void
3694 purge_all_filters (GDBusConnection *connection)
3695 {
3696   guint n;
3697   for (n = 0; n < connection->filters->len; n++)
3698     {
3699       FilterData *data = connection->filters->pdata[n];
3700       if (data->user_data_free_func != NULL)
3701         data->user_data_free_func (data->user_data);
3702       g_free (data);
3703     }
3704 }
3705
3706 /**
3707  * g_dbus_connection_remove_filter:
3708  * @connection: a #GDBusConnection
3709  * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3710  *
3711  * Removes a filter.
3712  *
3713  * Since: 2.26
3714  */
3715 void
3716 g_dbus_connection_remove_filter (GDBusConnection *connection,
3717                                  guint            filter_id)
3718 {
3719   guint n;
3720   FilterData *to_destroy;
3721
3722   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3723   g_return_if_fail (check_initialized (connection));
3724
3725   CONNECTION_LOCK (connection);
3726   to_destroy = NULL;
3727   for (n = 0; n < connection->filters->len; n++)
3728     {
3729       FilterData *data = connection->filters->pdata[n];
3730       if (data->id == filter_id)
3731         {
3732           g_ptr_array_remove_index (connection->filters, n);
3733           to_destroy = data;
3734           break;
3735         }
3736     }
3737   CONNECTION_UNLOCK (connection);
3738
3739   /* do free without holding lock */
3740   if (to_destroy != NULL)
3741     {
3742       if (to_destroy->user_data_free_func != NULL)
3743         to_destroy->user_data_free_func (to_destroy->user_data);
3744       g_free (to_destroy);
3745     }
3746   else
3747     {
3748       g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3749     }
3750 }
3751
3752 /* ---------------------------------------------------------------------------------------------------- */
3753
3754 typedef struct
3755 {
3756   gchar *rule;
3757   gchar *sender;
3758   gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3759   gchar *interface_name;
3760   gchar *member;
3761   gchar *object_path;
3762   gchar *arg0;
3763   GDBusSignalFlags flags;
3764   GArray *subscribers;
3765 } SignalData;
3766
3767 typedef struct
3768 {
3769   GDBusSignalCallback callback;
3770   gpointer user_data;
3771   GDestroyNotify user_data_free_func;
3772   guint id;
3773   GMainContext *context;
3774 } SignalSubscriber;
3775
3776 static void
3777 signal_data_free (SignalData *signal_data)
3778 {
3779   g_free (signal_data->rule);
3780   g_free (signal_data->sender);
3781   g_free (signal_data->sender_unique_name);
3782   g_free (signal_data->interface_name);
3783   g_free (signal_data->member);
3784   g_free (signal_data->object_path);
3785   g_free (signal_data->arg0);
3786   g_array_free (signal_data->subscribers, TRUE);
3787   g_free (signal_data);
3788 }
3789
3790 static gchar *
3791 args_to_rule (const gchar      *sender,
3792               const gchar      *interface_name,
3793               const gchar      *member,
3794               const gchar      *object_path,
3795               const gchar      *arg0,
3796               GDBusSignalFlags  flags)
3797 {
3798   GString *rule;
3799
3800   rule = g_string_new ("type='signal'");
3801   if (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE)
3802     g_string_prepend_c (rule, '-');
3803   if (sender != NULL)
3804     g_string_append_printf (rule, ",sender='%s'", sender);
3805   if (interface_name != NULL)
3806     g_string_append_printf (rule, ",interface='%s'", interface_name);
3807   if (member != NULL)
3808     g_string_append_printf (rule, ",member='%s'", member);
3809   if (object_path != NULL)
3810     g_string_append_printf (rule, ",path='%s'", object_path);
3811
3812   if (arg0 != NULL)
3813     {
3814       if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3815         g_string_append_printf (rule, ",arg0path='%s'", arg0);
3816       else if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3817         g_string_append_printf (rule, ",arg0namespace='%s'", arg0);
3818       else
3819         g_string_append_printf (rule, ",arg0='%s'", arg0);
3820     }
3821
3822   return g_string_free (rule, FALSE);
3823 }
3824
3825 static guint _global_subscriber_id = 1;
3826 static guint _global_registration_id = 1;
3827 static guint _global_subtree_registration_id = 1;
3828
3829 /* ---------------------------------------------------------------------------------------------------- */
3830
3831 /* Called in a user thread, lock is held */
3832 static void
3833 add_match_rule (GDBusConnection *connection,
3834                 const gchar     *match_rule)
3835 {
3836   GError *error;
3837   GDBusMessage *message;
3838
3839   if (match_rule[0] == '-')
3840     return;
3841
3842   message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3843                                             "/org/freedesktop/DBus", /* path */
3844                                             "org.freedesktop.DBus", /* interface */
3845                                             "AddMatch");
3846   g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3847   error = NULL;
3848   if (!g_dbus_connection_send_message_unlocked (connection,
3849                                                 message,
3850                                                 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3851                                                 NULL,
3852                                                 &error))
3853     {
3854       g_critical ("Error while sending AddMatch() message: %s", error->message);
3855       g_error_free (error);
3856     }
3857   g_object_unref (message);
3858 }
3859
3860 /* ---------------------------------------------------------------------------------------------------- */
3861
3862 /* Called in a user thread, lock is held */
3863 static void
3864 remove_match_rule (GDBusConnection *connection,
3865                    const gchar     *match_rule)
3866 {
3867   GError *error;
3868   GDBusMessage *message;
3869
3870   if (match_rule[0] == '-')
3871     return;
3872
3873   message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3874                                             "/org/freedesktop/DBus", /* path */
3875                                             "org.freedesktop.DBus", /* interface */
3876                                             "RemoveMatch");
3877   g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3878
3879   error = NULL;
3880   if (!g_dbus_connection_send_message_unlocked (connection,
3881                                                 message,
3882                                                 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3883                                                 NULL,
3884                                                 &error))
3885     {
3886       /* If we could get G_IO_ERROR_CLOSED here, it wouldn't be reasonable to
3887        * critical; but we're holding the lock, and our caller checked whether
3888        * we were already closed, so we can't get that error.
3889        */
3890       g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3891       g_error_free (error);
3892     }
3893   g_object_unref (message);
3894 }
3895
3896 /* ---------------------------------------------------------------------------------------------------- */
3897
3898 static gboolean
3899 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3900 {
3901   return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3902          g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3903          g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3904          (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3905           g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3906 }
3907
3908 /* ---------------------------------------------------------------------------------------------------- */
3909
3910 /**
3911  * g_dbus_connection_signal_subscribe:
3912  * @connection: a #GDBusConnection
3913  * @sender: (allow-none): sender name to match on (unique or well-known name)
3914  *     or %NULL to listen from all senders
3915  * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3916  *     match on all interfaces
3917  * @member: (allow-none): D-Bus signal name to match on or %NULL to match on
3918  *     all signals
3919  * @object_path: (allow-none): object path to match on or %NULL to match on
3920  *     all object paths
3921  * @arg0: (allow-none): contents of first string argument to match on or %NULL
3922  *     to match on all kinds of arguments
3923  * @flags: flags describing how to subscribe to the signal (currently unused)
3924  * @callback: callback to invoke when there is a signal matching the requested data
3925  * @user_data: user data to pass to @callback
3926  * @user_data_free_func: (allow-none): function to free @user_data with when
3927  *     subscription is removed or %NULL
3928  *
3929  * Subscribes to signals on @connection and invokes @callback with a whenever
3930  * the signal is received. Note that @callback will be invoked in the 
3931  * [thread-default main context][g-main-context-push-thread-default]
3932  * of the thread you are calling this method from.
3933  *
3934  * If @connection is not a message bus connection, @sender must be
3935  * %NULL.
3936  *
3937  * If @sender is a well-known name note that @callback is invoked with
3938  * the unique name for the owner of @sender, not the well-known name
3939  * as one would expect. This is because the message bus rewrites the
3940  * name. As such, to avoid certain race conditions, users should be
3941  * tracking the name owner of the well-known name and use that when
3942  * processing the received signal.
3943  *
3944  * If one of %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE or
3945  * %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH are given, @arg0 is
3946  * interpreted as part of a namespace or path.  The first argument
3947  * of a signal is matched against that part as specified by D-Bus.
3948  *
3949  * Returns: a subscription identifier that can be used with g_dbus_connection_signal_unsubscribe()
3950  *
3951  * Since: 2.26
3952  */
3953 guint
3954 g_dbus_connection_signal_subscribe (GDBusConnection     *connection,
3955                                     const gchar         *sender,
3956                                     const gchar         *interface_name,
3957                                     const gchar         *member,
3958                                     const gchar         *object_path,
3959                                     const gchar         *arg0,
3960                                     GDBusSignalFlags     flags,
3961                                     GDBusSignalCallback  callback,
3962                                     gpointer             user_data,
3963                                     GDestroyNotify       user_data_free_func)
3964 {
3965   gchar *rule;
3966   SignalData *signal_data;
3967   SignalSubscriber subscriber;
3968   GPtrArray *signal_data_array;
3969   const gchar *sender_unique_name;
3970
3971   /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3972    * an OOM condition. We might want to change that but that would involve making
3973    * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3974    * handle that. And there's really no sensible way of handling this short of retrying
3975    * to add the match rule... and then there's the little thing that, hey, maybe there's
3976    * a reason the bus in an OOM condition.
3977    *
3978    * Doable, but not really sure it's worth it...
3979    */
3980
3981   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3982   g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3983   g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3984   g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3985   g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3986   g_return_val_if_fail (callback != NULL, 0);
3987   g_return_val_if_fail (check_initialized (connection), 0);
3988   g_return_val_if_fail (!((flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH) && (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)), 0);
3989   g_return_val_if_fail (!(arg0 == NULL && (flags & (G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH | G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE))), 0);
3990
3991   CONNECTION_LOCK (connection);
3992
3993   /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3994    * with a '-' character to prefix the rule (which will otherwise be
3995    * normal).
3996    *
3997    * This allows us to hash the rule and do our lifecycle tracking in
3998    * the usual way, but the '-' prevents the match rule from ever
3999    * actually being send to the bus (either for add or remove).
4000    */
4001   rule = args_to_rule (sender, interface_name, member, object_path, arg0, flags);
4002
4003   if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
4004     sender_unique_name = sender;
4005   else
4006     sender_unique_name = "";
4007
4008   subscriber.callback = callback;
4009   subscriber.user_data = user_data;
4010   subscriber.user_data_free_func = user_data_free_func;
4011   subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
4012   subscriber.context = g_main_context_ref_thread_default ();
4013
4014   /* see if we've already have this rule */
4015   signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
4016   if (signal_data != NULL)
4017     {
4018       g_array_append_val (signal_data->subscribers, subscriber);
4019       g_free (rule);
4020       goto out;
4021     }
4022
4023   signal_data = g_new0 (SignalData, 1);
4024   signal_data->rule                  = rule;
4025   signal_data->sender                = g_strdup (sender);
4026   signal_data->sender_unique_name    = g_strdup (sender_unique_name);
4027   signal_data->interface_name        = g_strdup (interface_name);
4028   signal_data->member                = g_strdup (member);
4029   signal_data->object_path           = g_strdup (object_path);
4030   signal_data->arg0                  = g_strdup (arg0);
4031   signal_data->flags                 = flags;
4032   signal_data->subscribers           = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
4033   g_array_append_val (signal_data->subscribers, subscriber);
4034
4035   g_hash_table_insert (connection->map_rule_to_signal_data,
4036                        signal_data->rule,
4037                        signal_data);
4038
4039   /* Add the match rule to the bus...
4040    *
4041    * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
4042    * always send such messages to us.
4043    */
4044   if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
4045     {
4046       if (!is_signal_data_for_name_lost_or_acquired (signal_data))
4047         add_match_rule (connection, signal_data->rule);
4048       else
4049         {
4050           if (G_IS_KDBUS_CONNECTION (connection->stream))
4051             {
4052               if (g_strcmp0 (signal_data->member, "NameAcquired") == 0)
4053                 _g_kdbus_subscribe_name_acquired (connection, arg0);
4054               else if (g_strcmp0 (signal_data->member, "NameLost") == 0)
4055                 _g_kdbus_subscribe_name_lost (connection, arg0);
4056             }
4057         }
4058     }
4059
4060   signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
4061                                            signal_data->sender_unique_name);
4062   if (signal_data_array == NULL)
4063     {
4064       signal_data_array = g_ptr_array_new ();
4065       g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
4066                            g_strdup (signal_data->sender_unique_name),
4067                            signal_data_array);
4068     }
4069   g_ptr_array_add (signal_data_array, signal_data);
4070
4071  out:
4072   g_hash_table_insert (connection->map_id_to_signal_data,
4073                        GUINT_TO_POINTER (subscriber.id),
4074                        signal_data);
4075
4076   CONNECTION_UNLOCK (connection);
4077
4078   return subscriber.id;
4079 }
4080
4081 /* ---------------------------------------------------------------------------------------------------- */
4082
4083 /* called in any thread */
4084 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
4085 static void
4086 unsubscribe_id_internal (GDBusConnection *connection,
4087                          guint            subscription_id,
4088                          GArray          *out_removed_subscribers)
4089 {
4090   SignalData *signal_data;
4091   GPtrArray *signal_data_array;
4092   guint n;
4093
4094   signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
4095                                      GUINT_TO_POINTER (subscription_id));
4096   if (signal_data == NULL)
4097     {
4098       /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
4099       goto out;
4100     }
4101
4102   for (n = 0; n < signal_data->subscribers->len; n++)
4103     {
4104       SignalSubscriber *subscriber;
4105
4106       subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
4107       if (subscriber->id != subscription_id)
4108         continue;
4109
4110       g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
4111                                            GUINT_TO_POINTER (subscription_id)));
4112       g_array_append_val (out_removed_subscribers, *subscriber);
4113       g_array_remove_index (signal_data->subscribers, n);
4114
4115       if (signal_data->subscribers->len == 0)
4116         {
4117           g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
4118
4119           signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
4120                                                    signal_data->sender_unique_name);
4121           g_warn_if_fail (signal_data_array != NULL);
4122           g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
4123
4124           if (signal_data_array->len == 0)
4125             {
4126               g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
4127                                                    signal_data->sender_unique_name));
4128             }
4129
4130           /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
4131           if ((connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION) &&
4132               !is_signal_data_for_name_lost_or_acquired (signal_data) &&
4133               !g_dbus_connection_is_closed (connection) &&
4134               !connection->finalizing)
4135             {
4136               /* The check for g_dbus_connection_is_closed() means that
4137                * sending the RemoveMatch message can't fail with
4138                * G_IO_ERROR_CLOSED, because we're holding the lock,
4139                * so on_worker_closed() can't happen between the check we just
4140                * did, and releasing the lock later.
4141                */
4142               remove_match_rule (connection, signal_data->rule);
4143             }
4144           else
4145             {
4146               if (G_IS_KDBUS_CONNECTION (connection->stream))
4147                 {
4148                   if (g_strcmp0 (signal_data->member, "NameAcquired") == 0)
4149                     _g_kdbus_unsubscribe_name_acquired (connection);
4150                   else if (g_strcmp0 (signal_data->member, "NameLost") == 0)
4151                     _g_kdbus_unsubscribe_name_lost (connection);
4152                 }
4153             }
4154
4155           signal_data_free (signal_data);
4156         }
4157
4158       goto out;
4159     }
4160
4161   g_assert_not_reached ();
4162
4163  out:
4164   ;
4165 }
4166
4167 /**
4168  * g_dbus_connection_signal_unsubscribe:
4169  * @connection: a #GDBusConnection
4170  * @subscription_id: a subscription id obtained from
4171  *     g_dbus_connection_signal_subscribe()
4172  *
4173  * Unsubscribes from signals.
4174  *
4175  * Since: 2.26
4176  */
4177 void
4178 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
4179                                       guint            subscription_id)
4180 {
4181   GArray *subscribers;
4182   guint n;
4183
4184   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4185   g_return_if_fail (check_initialized (connection));
4186
4187   subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
4188
4189   CONNECTION_LOCK (connection);
4190   unsubscribe_id_internal (connection,
4191                            subscription_id,
4192                            subscribers);
4193   CONNECTION_UNLOCK (connection);
4194
4195   /* invariant */
4196   g_assert (subscribers->len == 0 || subscribers->len == 1);
4197
4198   /* call GDestroyNotify without lock held */
4199   for (n = 0; n < subscribers->len; n++)
4200     {
4201       SignalSubscriber *subscriber;
4202       subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
4203       call_destroy_notify (subscriber->context,
4204                            subscriber->user_data_free_func,
4205                            subscriber->user_data);
4206       g_main_context_unref (subscriber->context);
4207     }
4208
4209   g_array_free (subscribers, TRUE);
4210 }
4211
4212 /* ---------------------------------------------------------------------------------------------------- */
4213
4214 typedef struct
4215 {
4216   guint                subscription_id;
4217   GDBusSignalCallback  callback;
4218   gpointer             user_data;
4219   GDBusMessage        *message;
4220   GDBusConnection     *connection;
4221   const gchar         *sender;
4222   const gchar         *path;
4223   const gchar         *interface;
4224   const gchar         *member;
4225 } SignalInstance;
4226
4227 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
4228  * no locks held
4229  */
4230 static gboolean
4231 emit_signal_instance_in_idle_cb (gpointer data)
4232 {
4233   SignalInstance *signal_instance = data;
4234   GVariant *parameters;
4235   gboolean has_subscription;
4236
4237   parameters = g_dbus_message_get_body (signal_instance->message);
4238   if (parameters == NULL)
4239     {
4240       parameters = g_variant_new ("()");
4241       g_variant_ref_sink (parameters);
4242     }
4243   else
4244     {
4245       g_variant_ref (parameters);
4246     }
4247
4248 #if 0
4249   g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
4250            signal_instance->subscription_id,
4251            signal_instance->sender,
4252            signal_instance->path,
4253            signal_instance->interface,
4254            signal_instance->member,
4255            g_variant_print (parameters, TRUE));
4256 #endif
4257
4258   /* Careful here, don't do the callback if we no longer has the subscription */
4259   CONNECTION_LOCK (signal_instance->connection);
4260   has_subscription = FALSE;
4261   if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
4262                            GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
4263     has_subscription = TRUE;
4264   CONNECTION_UNLOCK (signal_instance->connection);
4265
4266   if (has_subscription)
4267     signal_instance->callback (signal_instance->connection,
4268                                signal_instance->sender,
4269                                signal_instance->path,
4270                                signal_instance->interface,
4271                                signal_instance->member,
4272                                parameters,
4273                                signal_instance->user_data);
4274
4275   g_variant_unref (parameters);
4276
4277   return FALSE;
4278 }
4279
4280 static void
4281 signal_instance_free (SignalInstance *signal_instance)
4282 {
4283   g_object_unref (signal_instance->message);
4284   g_object_unref (signal_instance->connection);
4285   g_free (signal_instance);
4286 }
4287
4288 static gboolean
4289 namespace_rule_matches (const gchar *namespace,
4290                         const gchar *name)
4291 {
4292   gint len_namespace;
4293   gint len_name;
4294
4295   len_namespace = strlen (namespace);
4296   len_name = strlen (name);
4297
4298   if (len_name < len_namespace)
4299     return FALSE;
4300
4301   if (memcmp (namespace, name, len_namespace) != 0)
4302     return FALSE;
4303
4304   return len_namespace == len_name || name[len_namespace] == '.';
4305 }
4306
4307 static gboolean
4308 path_rule_matches (const gchar *path_a,
4309                    const gchar *path_b)
4310 {
4311   gint len_a, len_b;
4312
4313   len_a = strlen (path_a);
4314   len_b = strlen (path_b);
4315
4316   if (len_a < len_b && path_a[len_a - 1] != '/')
4317     return FALSE;
4318
4319   if (len_b < len_a && path_b[len_b - 1] != '/')
4320     return FALSE;
4321
4322   return memcmp (path_a, path_b, MIN (len_a, len_b)) == 0;
4323 }
4324
4325 /* called in GDBusWorker thread WITH lock held */
4326 static void
4327 schedule_callbacks (GDBusConnection *connection,
4328                     GPtrArray       *signal_data_array,
4329                     GDBusMessage    *message,
4330                     const gchar     *sender)
4331 {
4332   guint n, m;
4333   const gchar *interface;
4334   const gchar *member;
4335   const gchar *path;
4336   const gchar *arg0;
4337
4338   interface = NULL;
4339   member = NULL;
4340   path = NULL;
4341   arg0 = NULL;
4342
4343   interface = g_dbus_message_get_interface (message);
4344   member = g_dbus_message_get_member (message);
4345   path = g_dbus_message_get_path (message);
4346   arg0 = g_dbus_message_get_arg0 (message);
4347
4348 #if 0
4349   g_print ("In schedule_callbacks:\n"
4350            "  sender    = '%s'\n"
4351            "  interface = '%s'\n"
4352            "  member    = '%s'\n"
4353            "  path      = '%s'\n"
4354            "  arg0      = '%s'\n",
4355            sender,
4356            interface,
4357            member,
4358            path,
4359            arg0);
4360 #endif
4361
4362   /* TODO: if this is slow, then we can change signal_data_array into
4363    *       map_object_path_to_signal_data_array or something.
4364    */
4365   for (n = 0; n < signal_data_array->len; n++)
4366     {
4367       SignalData *signal_data = signal_data_array->pdata[n];
4368
4369       if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
4370         continue;
4371
4372       if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
4373         continue;
4374
4375       if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
4376         continue;
4377
4378       if (signal_data->arg0 != NULL)
4379         {
4380           if (arg0 == NULL)
4381             continue;
4382
4383           if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
4384             {
4385               if (!namespace_rule_matches (signal_data->arg0, arg0))
4386                 continue;
4387             }
4388           else if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
4389             {
4390               if (!path_rule_matches (signal_data->arg0, arg0))
4391                 continue;
4392             }
4393           else if (!g_str_equal (signal_data->arg0, arg0))
4394             continue;
4395         }
4396
4397       for (m = 0; m < signal_data->subscribers->len; m++)
4398         {
4399           SignalSubscriber *subscriber;
4400           GSource *idle_source;
4401           SignalInstance *signal_instance;
4402
4403           subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
4404
4405           signal_instance = g_new0 (SignalInstance, 1);
4406           signal_instance->subscription_id = subscriber->id;
4407           signal_instance->callback = subscriber->callback;
4408           signal_instance->user_data = subscriber->user_data;
4409           signal_instance->message = g_object_ref (message);
4410           signal_instance->connection = g_object_ref (connection);
4411           signal_instance->sender = sender;
4412           signal_instance->path = path;
4413           signal_instance->interface = interface;
4414           signal_instance->member = member;
4415
4416           idle_source = g_idle_source_new ();
4417           g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4418           g_source_set_callback (idle_source,
4419                                  emit_signal_instance_in_idle_cb,
4420                                  signal_instance,
4421                                  (GDestroyNotify) signal_instance_free);
4422           g_source_set_name (idle_source, "[gio] emit_signal_instance_in_idle_cb");
4423           g_source_attach (idle_source, subscriber->context);
4424           g_source_unref (idle_source);
4425         }
4426     }
4427 }
4428
4429 /* called in GDBusWorker thread with lock held */
4430 static void
4431 distribute_signals (GDBusConnection *connection,
4432                     GDBusMessage    *message)
4433 {
4434   GPtrArray *signal_data_array;
4435   const gchar *sender;
4436
4437   sender = g_dbus_message_get_sender (message);
4438
4439   if (G_UNLIKELY (_g_dbus_debug_signal ()))
4440     {
4441       _g_dbus_debug_print_lock ();
4442       g_print ("========================================================================\n"
4443                "GDBus-debug:Signal:\n"
4444                " <<<< RECEIVED SIGNAL %s.%s\n"
4445                "      on object %s\n"
4446                "      sent by name %s\n",
4447                g_dbus_message_get_interface (message),
4448                g_dbus_message_get_member (message),
4449                g_dbus_message_get_path (message),
4450                sender != NULL ? sender : "(none)");
4451       _g_dbus_debug_print_unlock ();
4452     }
4453
4454   /* collect subscribers that match on sender */
4455   if (sender != NULL)
4456     {
4457       signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
4458       if (signal_data_array != NULL)
4459         schedule_callbacks (connection, signal_data_array, message, sender);
4460     }
4461
4462   /* collect subscribers not matching on sender */
4463   signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
4464   if (signal_data_array != NULL)
4465     schedule_callbacks (connection, signal_data_array, message, sender);
4466 }
4467
4468 /* ---------------------------------------------------------------------------------------------------- */
4469
4470 /* only called from finalize(), removes all subscriptions */
4471 static void
4472 purge_all_signal_subscriptions (GDBusConnection *connection)
4473 {
4474   GHashTableIter iter;
4475   gpointer key;
4476   GArray *ids;
4477   GArray *subscribers;
4478   guint n;
4479
4480   ids = g_array_new (FALSE, FALSE, sizeof (guint));
4481   g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
4482   while (g_hash_table_iter_next (&iter, &key, NULL))
4483     {
4484       guint subscription_id = GPOINTER_TO_UINT (key);
4485       g_array_append_val (ids, subscription_id);
4486     }
4487
4488   subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
4489   for (n = 0; n < ids->len; n++)
4490     {
4491       guint subscription_id = g_array_index (ids, guint, n);
4492       unsubscribe_id_internal (connection,
4493                                subscription_id,
4494                                subscribers);
4495     }
4496   g_array_free (ids, TRUE);
4497
4498   /* call GDestroyNotify without lock held */
4499   for (n = 0; n < subscribers->len; n++)
4500     {
4501       SignalSubscriber *subscriber;
4502       subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
4503       call_destroy_notify (subscriber->context,
4504                            subscriber->user_data_free_func,
4505                            subscriber->user_data);
4506       g_main_context_unref (subscriber->context);
4507     }
4508
4509   g_array_free (subscribers, TRUE);
4510 }
4511
4512 /* ---------------------------------------------------------------------------------------------------- */
4513
4514 static GDBusInterfaceVTable *
4515 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
4516 {
4517   /* Don't waste memory by copying padding - remember to update this
4518    * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
4519    */
4520   return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4521 }
4522
4523 static void
4524 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
4525 {
4526   g_free (vtable);
4527 }
4528
4529 /* ---------------------------------------------------------------------------------------------------- */
4530
4531 static GDBusSubtreeVTable *
4532 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
4533 {
4534   /* Don't waste memory by copying padding - remember to update this
4535    * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
4536    */
4537   return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4538 }
4539
4540 static void
4541 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
4542 {
4543   g_free (vtable);
4544 }
4545
4546 /* ---------------------------------------------------------------------------------------------------- */
4547
4548 struct ExportedObject
4549 {
4550   gchar *object_path;
4551   GDBusConnection *connection;
4552
4553   /* maps gchar* -> ExportedInterface* */
4554   GHashTable *map_if_name_to_ei;
4555 };
4556
4557 /* only called with lock held */
4558 static void
4559 exported_object_free (ExportedObject *eo)
4560 {
4561   g_free (eo->object_path);
4562   g_hash_table_unref (eo->map_if_name_to_ei);
4563   g_free (eo);
4564 }
4565
4566 typedef struct
4567 {
4568   ExportedObject *eo;
4569
4570   guint                       id;
4571   gchar                      *interface_name;
4572   GDBusInterfaceVTable       *vtable;
4573   GDBusInterfaceInfo         *interface_info;
4574
4575   GMainContext               *context;
4576   gpointer                    user_data;
4577   GDestroyNotify              user_data_free_func;
4578 } ExportedInterface;
4579
4580 /* called with lock held */
4581 static void
4582 exported_interface_free (ExportedInterface *ei)
4583 {
4584   g_dbus_interface_info_cache_release (ei->interface_info);
4585   g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
4586
4587   call_destroy_notify (ei->context,
4588                        ei->user_data_free_func,
4589                        ei->user_data);
4590
4591   g_main_context_unref (ei->context);
4592
4593   g_free (ei->interface_name);
4594   _g_dbus_interface_vtable_free (ei->vtable);
4595   g_free (ei);
4596 }
4597
4598 /* ---------------------------------------------------------------------------------------------------- */
4599
4600 /* Convenience function to check if @registration_id (if not zero) or
4601  * @subtree_registration_id (if not zero) has been unregistered. If
4602  * so, returns %TRUE.
4603  *
4604  * May be called by any thread. Caller must *not* hold lock.
4605  */
4606 static gboolean
4607 has_object_been_unregistered (GDBusConnection  *connection,
4608                               guint             registration_id,
4609                               guint             subtree_registration_id)
4610 {
4611   gboolean ret;
4612
4613   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4614
4615   ret = FALSE;
4616
4617   CONNECTION_LOCK (connection);
4618   if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
4619                                                    GUINT_TO_POINTER (registration_id)) == NULL)
4620     {
4621       ret = TRUE;
4622     }
4623   else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
4624                                                                 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
4625     {
4626       ret = TRUE;
4627     }
4628   CONNECTION_UNLOCK (connection);
4629
4630   return ret;
4631 }
4632
4633 /* ---------------------------------------------------------------------------------------------------- */
4634
4635 typedef struct
4636 {
4637   GDBusConnection *connection;
4638   GDBusMessage *message;
4639   gpointer user_data;
4640   const gchar *property_name;
4641   const GDBusInterfaceVTable *vtable;
4642   GDBusInterfaceInfo *interface_info;
4643   const GDBusPropertyInfo *property_info;
4644   guint registration_id;
4645   guint subtree_registration_id;
4646 } PropertyData;
4647
4648 static void
4649 property_data_free (PropertyData *data)
4650 {
4651   g_object_unref (data->connection);
4652   g_object_unref (data->message);
4653   g_free (data);
4654 }
4655
4656 /* called in thread where object was registered - no locks held */
4657 static gboolean
4658 invoke_get_property_in_idle_cb (gpointer _data)
4659 {
4660   PropertyData *data = _data;
4661   GVariant *value;
4662   GError *error;
4663   GDBusMessage *reply;
4664
4665   if (has_object_been_unregistered (data->connection,
4666                                     data->registration_id,
4667                                     data->subtree_registration_id))
4668     {
4669       reply = g_dbus_message_new_method_error (data->message,
4670                                                "org.freedesktop.DBus.Error.UnknownMethod",
4671                                                _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4672                                                g_dbus_message_get_path (data->message));
4673       g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4674       g_object_unref (reply);
4675       goto out;
4676     }
4677
4678   error = NULL;
4679   value = data->vtable->get_property (data->connection,
4680                                       g_dbus_message_get_sender (data->message),
4681                                       g_dbus_message_get_path (data->message),
4682                                       data->interface_info->name,
4683                                       data->property_name,
4684                                       &error,
4685                                       data->user_data);
4686
4687
4688   if (value != NULL)
4689     {
4690       g_assert_no_error (error);
4691
4692       g_variant_take_ref (value);
4693       reply = g_dbus_message_new_method_reply (data->message);
4694       g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4695       g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4696       g_variant_unref (value);
4697       g_object_unref (reply);
4698     }
4699   else
4700     {
4701       gchar *dbus_error_name;
4702       g_assert (error != NULL);
4703       dbus_error_name = g_dbus_error_encode_gerror (error);
4704       reply = g_dbus_message_new_method_error_literal (data->message,
4705                                                        dbus_error_name,
4706                                                        error->message);
4707       g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4708       g_free (dbus_error_name);
4709       g_error_free (error);
4710       g_object_unref (reply);
4711     }
4712
4713  out:
4714   return FALSE;
4715 }
4716
4717 /* called in thread where object was registered - no locks held */
4718 static gboolean
4719 invoke_set_property_in_idle_cb (gpointer _data)
4720 {
4721   PropertyData *data = _data;
4722   GError *error;
4723   GDBusMessage *reply;
4724   GVariant *value;
4725
4726   error = NULL;
4727   value = NULL;
4728
4729   g_variant_get (g_dbus_message_get_body (data->message),
4730                  "(ssv)",
4731                  NULL,
4732                  NULL,
4733                  &value);
4734
4735   if (!data->vtable->set_property (data->connection,
4736                                    g_dbus_message_get_sender (data->message),
4737                                    g_dbus_message_get_path (data->message),
4738                                    data->interface_info->name,
4739                                    data->property_name,
4740                                    value,
4741                                    &error,
4742                                    data->user_data))
4743     {
4744       gchar *dbus_error_name;
4745       g_assert (error != NULL);
4746       dbus_error_name = g_dbus_error_encode_gerror (error);
4747       reply = g_dbus_message_new_method_error_literal (data->message,
4748                                                        dbus_error_name,
4749                                                        error->message);
4750       g_free (dbus_error_name);
4751       g_error_free (error);
4752     }
4753   else
4754     {
4755       reply = g_dbus_message_new_method_reply (data->message);
4756     }
4757
4758   g_assert (reply != NULL);
4759   g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4760   g_object_unref (reply);
4761   g_variant_unref (value);
4762
4763   return FALSE;
4764 }
4765
4766 /* called in any thread with connection's lock held */
4767 static gboolean
4768 validate_and_maybe_schedule_property_getset (GDBusConnection            *connection,
4769                                              GDBusMessage               *message,
4770                                              guint                       registration_id,
4771                                              guint                       subtree_registration_id,
4772                                              gboolean                    is_get,
4773                                              GDBusInterfaceInfo         *interface_info,
4774                                              const GDBusInterfaceVTable *vtable,
4775                                              GMainContext               *main_context,
4776                                              gpointer                    user_data)
4777 {
4778   gboolean handled;
4779   const char *interface_name;
4780   const char *property_name;
4781   const GDBusPropertyInfo *property_info;
4782   GSource *idle_source;
4783   PropertyData *property_data;
4784   GDBusMessage *reply;
4785
4786   handled = FALSE;
4787
4788   if (is_get)
4789     g_variant_get (g_dbus_message_get_body (message),
4790                    "(&s&s)",
4791                    &interface_name,
4792                    &property_name);
4793   else
4794     g_variant_get (g_dbus_message_get_body (message),
4795                    "(&s&sv)",
4796                    &interface_name,
4797                    &property_name,
4798                    NULL);
4799
4800   if (vtable == NULL)
4801     goto out;
4802
4803   /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4804    */
4805   property_info = NULL;
4806
4807   /* TODO: the cost of this is O(n) - it might be worth caching the result */
4808   property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4809   if (property_info == NULL)
4810     {
4811       reply = g_dbus_message_new_method_error (message,
4812                                                "org.freedesktop.DBus.Error.InvalidArgs",
4813                                                _("No such property '%s'"),
4814                                                property_name);
4815       g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4816       g_object_unref (reply);
4817       handled = TRUE;
4818       goto out;
4819     }
4820
4821   if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4822     {
4823       reply = g_dbus_message_new_method_error (message,
4824                                                "org.freedesktop.DBus.Error.InvalidArgs",
4825                                                _("Property '%s' is not readable"),
4826                                                property_name);
4827       g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4828       g_object_unref (reply);
4829       handled = TRUE;
4830       goto out;
4831     }
4832   else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4833     {
4834       reply = g_dbus_message_new_method_error (message,
4835                                                "org.freedesktop.DBus.Error.InvalidArgs",
4836                                                _("Property '%s' is not writable"),
4837                                                property_name);
4838       g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4839       g_object_unref (reply);
4840       handled = TRUE;
4841       goto out;
4842     }
4843
4844   if (!is_get)
4845     {
4846       GVariant *value;
4847
4848       /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4849        * of the given value is wrong
4850        */
4851       g_variant_get_child (g_dbus_message_get_body (message), 2, "v", &value);
4852       if (g_strcmp0 (g_variant_get_type_string (value), property_info->signature) != 0)
4853         {
4854           reply = g_dbus_message_new_method_error (message,
4855                                                    "org.freedesktop.DBus.Error.InvalidArgs",
4856                                                    _("Error setting property '%s': Expected type '%s' but got '%s'"),
4857                                                    property_name, property_info->signature,
4858                                                    g_variant_get_type_string (value));
4859           g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4860           g_variant_unref (value);
4861           g_object_unref (reply);
4862           handled = TRUE;
4863           goto out;
4864         }
4865
4866       g_variant_unref (value);
4867     }
4868
4869   /* If the vtable pointer for get_property() resp. set_property() is
4870    * NULL then dispatch the call via the method_call() handler.
4871    */
4872   if (is_get)
4873     {
4874       if (vtable->get_property == NULL)
4875         {
4876           schedule_method_call (connection, message, registration_id, subtree_registration_id,
4877                                 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4878                                 vtable, main_context, user_data);
4879           handled = TRUE;
4880           goto out;
4881         }
4882     }
4883   else
4884     {
4885       if (vtable->set_property == NULL)
4886         {
4887           schedule_method_call (connection, message, registration_id, subtree_registration_id,
4888                                 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4889                                 vtable, main_context, user_data);
4890           handled = TRUE;
4891           goto out;
4892         }
4893     }
4894
4895   /* ok, got the property info - call user code in an idle handler */
4896   property_data = g_new0 (PropertyData, 1);
4897   property_data->connection = g_object_ref (connection);
4898   property_data->message = g_object_ref (message);
4899   property_data->user_data = user_data;
4900   property_data->property_name = property_name;
4901   property_data->vtable = vtable;
4902   property_data->interface_info = interface_info;
4903   property_data->property_info = property_info;
4904   property_data->registration_id = registration_id;
4905   property_data->subtree_registration_id = subtree_registration_id;
4906
4907   idle_source = g_idle_source_new ();
4908   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4909   g_source_set_callback (idle_source,
4910                          is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4911                          property_data,
4912                          (GDestroyNotify) property_data_free);
4913   if (is_get)
4914     g_source_set_name (idle_source, "[gio] invoke_get_property_in_idle_cb");
4915   else
4916     g_source_set_name (idle_source, "[gio] invoke_set_property_in_idle_cb");
4917   g_source_attach (idle_source, main_context);
4918   g_source_unref (idle_source);
4919
4920   handled = TRUE;
4921
4922  out:
4923   return handled;
4924 }
4925
4926 /* called in GDBusWorker thread with connection's lock held */
4927 static gboolean
4928 handle_getset_property (GDBusConnection *connection,
4929                         ExportedObject  *eo,
4930                         GDBusMessage    *message,
4931                         gboolean         is_get)
4932 {
4933   ExportedInterface *ei;
4934   gboolean handled;
4935   const char *interface_name;
4936   const char *property_name;
4937
4938   handled = FALSE;
4939
4940   if (is_get)
4941     g_variant_get (g_dbus_message_get_body (message),
4942                    "(&s&s)",
4943                    &interface_name,
4944                    &property_name);
4945   else
4946     g_variant_get (g_dbus_message_get_body (message),
4947                    "(&s&sv)",
4948                    &interface_name,
4949                    &property_name,
4950                    NULL);
4951
4952   /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4953    * no such interface registered
4954    */
4955   ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4956   if (ei == NULL)
4957     {
4958       GDBusMessage *reply;
4959       reply = g_dbus_message_new_method_error (message,
4960                                                "org.freedesktop.DBus.Error.InvalidArgs",
4961                                                _("No such interface '%s'"),
4962                                                interface_name);
4963       g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4964       g_object_unref (reply);
4965       handled = TRUE;
4966       goto out;
4967     }
4968
4969   handled = validate_and_maybe_schedule_property_getset (eo->connection,
4970                                                          message,
4971                                                          ei->id,
4972                                                          0,
4973                                                          is_get,
4974                                                          ei->interface_info,
4975                                                          ei->vtable,
4976                                                          ei->context,
4977                                                          ei->user_data);
4978  out:
4979   return handled;
4980 }
4981
4982 /* ---------------------------------------------------------------------------------------------------- */
4983
4984 typedef struct
4985 {
4986   GDBusConnection *connection;
4987   GDBusMessage *message;
4988   gpointer user_data;
4989   const GDBusInterfaceVTable *vtable;
4990   GDBusInterfaceInfo *interface_info;
4991   guint registration_id;
4992   guint subtree_registration_id;
4993 } PropertyGetAllData;
4994
4995 static void
4996 property_get_all_data_free (PropertyData *data)
4997 {
4998   g_object_unref (data->connection);
4999   g_object_unref (data->message);
5000   g_free (data);
5001 }
5002
5003 /* called in thread where object was registered - no locks held */
5004 static gboolean
5005 invoke_get_all_properties_in_idle_cb (gpointer _data)
5006 {
5007   PropertyGetAllData *data = _data;
5008   GVariantBuilder builder;
5009   GDBusMessage *reply;
5010   guint n;
5011
5012   if (has_object_been_unregistered (data->connection,
5013                                     data->registration_id,
5014                                     data->subtree_registration_id))
5015     {
5016       reply = g_dbus_message_new_method_error (data->message,
5017                                                "org.freedesktop.DBus.Error.UnknownMethod",
5018                                                _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
5019                                                g_dbus_message_get_path (data->message));
5020       g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5021       g_object_unref (reply);
5022       goto out;
5023     }
5024
5025   /* TODO: Right now we never fail this call - we just omit values if
5026    *       a get_property() call is failing.
5027    *
5028    *       We could fail the whole call if just a single get_property() call
5029    *       returns an error. We need clarification in the D-Bus spec about this.
5030    */
5031   g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
5032   g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
5033   for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
5034     {
5035       const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
5036       GVariant *value;
5037
5038       if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
5039         continue;
5040
5041       value = data->vtable->get_property (data->connection,
5042                                           g_dbus_message_get_sender (data->message),
5043                                           g_dbus_message_get_path (data->message),
5044                                           data->interface_info->name,
5045                                           property_info->name,
5046                                           NULL,
5047                                           data->user_data);
5048
5049       if (value == NULL)
5050         continue;
5051
5052       g_variant_take_ref (value);
5053       g_variant_builder_add (&builder,
5054                              "{sv}",
5055                              property_info->name,
5056                              value);
5057       g_variant_unref (value);
5058     }
5059   g_variant_builder_close (&builder);
5060
5061   reply = g_dbus_message_new_method_reply (data->message);
5062   g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
5063   g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5064   g_object_unref (reply);
5065
5066  out:
5067   return FALSE;
5068 }
5069
5070 static gboolean
5071 interface_has_readable_properties (GDBusInterfaceInfo *interface_info)
5072 {
5073   gint i;
5074
5075   if (!interface_info->properties)
5076     return FALSE;
5077
5078   for (i = 0; interface_info->properties[i]; i++)
5079     if (interface_info->properties[i]->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE)
5080       return TRUE;
5081
5082   return FALSE;
5083 }
5084
5085 /* called in any thread with connection's lock held */
5086 static gboolean
5087 validate_and_maybe_schedule_property_get_all (GDBusConnection            *connection,
5088                                               GDBusMessage               *message,
5089                                               guint                       registration_id,
5090                                               guint                       subtree_registration_id,
5091                                               GDBusInterfaceInfo         *interface_info,
5092                                               const GDBusInterfaceVTable *vtable,
5093                                               GMainContext               *main_context,
5094                                               gpointer                    user_data)
5095 {
5096   gboolean handled;
5097   GSource *idle_source;
5098   PropertyGetAllData *property_get_all_data;
5099
5100   handled = FALSE;
5101
5102   if (vtable == NULL)
5103     goto out;
5104
5105   /* If the vtable pointer for get_property() is NULL but we have a
5106    * non-zero number of readable properties, then dispatch the call via
5107    * the method_call() handler.
5108    */
5109   if (vtable->get_property == NULL && interface_has_readable_properties (interface_info))
5110     {
5111       schedule_method_call (connection, message, registration_id, subtree_registration_id,
5112                             interface_info, NULL, NULL, g_dbus_message_get_body (message),
5113                             vtable, main_context, user_data);
5114       handled = TRUE;
5115       goto out;
5116     }
5117
5118   /* ok, got the property info - call user in an idle handler */
5119   property_get_all_data = g_new0 (PropertyGetAllData, 1);
5120   property_get_all_data->connection = g_object_ref (connection);
5121   property_get_all_data->message = g_object_ref (message);
5122   property_get_all_data->user_data = user_data;
5123   property_get_all_data->vtable = vtable;
5124   property_get_all_data->interface_info = interface_info;
5125   property_get_all_data->registration_id = registration_id;
5126   property_get_all_data->subtree_registration_id = subtree_registration_id;
5127
5128   idle_source = g_idle_source_new ();
5129   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
5130   g_source_set_callback (idle_source,
5131                          invoke_get_all_properties_in_idle_cb,
5132                          property_get_all_data,
5133                          (GDestroyNotify) property_get_all_data_free);
5134   g_source_set_name (idle_source, "[gio] invoke_get_all_properties_in_idle_cb");
5135   g_source_attach (idle_source, main_context);
5136   g_source_unref (idle_source);
5137
5138   handled = TRUE;
5139
5140  out:
5141   return handled;
5142 }
5143
5144 /* called in GDBusWorker thread with connection's lock held */
5145 static gboolean
5146 handle_get_all_properties (GDBusConnection *connection,
5147                            ExportedObject  *eo,
5148                            GDBusMessage    *message)
5149 {
5150   ExportedInterface *ei;
5151   gboolean handled;
5152   const char *interface_name;
5153
5154   handled = FALSE;
5155
5156   g_variant_get (g_dbus_message_get_body (message),
5157                  "(&s)",
5158                  &interface_name);
5159
5160   /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
5161    * no such interface registered
5162    */
5163   ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5164   if (ei == NULL)
5165     {
5166       GDBusMessage *reply;
5167       reply = g_dbus_message_new_method_error (message,
5168                                                "org.freedesktop.DBus.Error.InvalidArgs",
5169                                                _("No such interface"),
5170                                                interface_name);
5171       g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5172       g_object_unref (reply);
5173       handled = TRUE;
5174       goto out;
5175     }
5176
5177   handled = validate_and_maybe_schedule_property_get_all (eo->connection,
5178                                                           message,
5179                                                           ei->id,
5180                                                           0,
5181                                                           ei->interface_info,
5182                                                           ei->vtable,
5183                                                           ei->context,
5184                                                           ei->user_data);
5185  out:
5186   return handled;
5187 }
5188
5189 /* ---------------------------------------------------------------------------------------------------- */
5190
5191 static const gchar introspect_header[] =
5192   "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
5193   "                      \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
5194   "<!-- GDBus " PACKAGE_VERSION " -->\n"
5195   "<node>\n";
5196
5197 static const gchar introspect_tail[] =
5198   "</node>\n";
5199
5200 static const gchar introspect_properties_interface[] =
5201   "  <interface name=\"org.freedesktop.DBus.Properties\">\n"
5202   "    <method name=\"Get\">\n"
5203   "      <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
5204   "      <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
5205   "      <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
5206   "    </method>\n"
5207   "    <method name=\"GetAll\">\n"
5208   "      <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
5209   "      <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
5210   "    </method>\n"
5211   "    <method name=\"Set\">\n"
5212   "      <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
5213   "      <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
5214   "      <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
5215   "    </method>\n"
5216   "    <signal name=\"PropertiesChanged\">\n"
5217   "      <arg type=\"s\" name=\"interface_name\"/>\n"
5218   "      <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
5219   "      <arg type=\"as\" name=\"invalidated_properties\"/>\n"
5220   "    </signal>\n"
5221   "  </interface>\n";
5222
5223 static const gchar introspect_introspectable_interface[] =
5224   "  <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
5225   "    <method name=\"Introspect\">\n"
5226   "      <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
5227   "    </method>\n"
5228   "  </interface>\n"
5229   "  <interface name=\"org.freedesktop.DBus.Peer\">\n"
5230   "    <method name=\"Ping\"/>\n"
5231   "    <method name=\"GetMachineId\">\n"
5232   "      <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
5233   "    </method>\n"
5234   "  </interface>\n";
5235
5236 static void
5237 introspect_append_header (GString *s)
5238 {
5239   g_string_append (s, introspect_header);
5240 }
5241
5242 static void
5243 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
5244 {
5245   if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
5246     {
5247       const gchar *begin;
5248       const gchar *end;
5249       gchar *s;
5250
5251       begin = object_path + path_len;
5252       end = strchr (begin, '/');
5253       if (end != NULL)
5254         s = g_strndup (begin, end - begin);
5255       else
5256         s = g_strdup (begin);
5257
5258       if (g_hash_table_lookup (set, s) == NULL)
5259         g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
5260       else
5261         g_free (s);
5262     }
5263 }
5264
5265 /* TODO: we want a nicer public interface for this */
5266 /* called in any thread with connection's lock held */
5267 static gchar **
5268 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
5269                                             const gchar     *path)
5270 {
5271   GPtrArray *p;
5272   gchar **ret;
5273   GHashTableIter hash_iter;
5274   const gchar *object_path;
5275   gsize path_len;
5276   GHashTable *set;
5277   GList *keys;
5278   GList *l;
5279
5280   CONNECTION_ENSURE_LOCK (connection);
5281
5282   path_len = strlen (path);
5283   if (path_len > 1)
5284     path_len++;
5285
5286   set = g_hash_table_new (g_str_hash, g_str_equal);
5287
5288   g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
5289   while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
5290     maybe_add_path (path, path_len, object_path, set);
5291
5292   g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
5293   while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
5294     maybe_add_path (path, path_len, object_path, set);
5295
5296   p = g_ptr_array_new ();
5297   keys = g_hash_table_get_keys (set);
5298   for (l = keys; l != NULL; l = l->next)
5299     g_ptr_array_add (p, l->data);
5300   g_hash_table_unref (set);
5301   g_list_free (keys);
5302
5303   g_ptr_array_add (p, NULL);
5304   ret = (gchar **) g_ptr_array_free (p, FALSE);
5305   return ret;
5306 }
5307
5308 /* called in any thread with connection's lock not held */
5309 static gchar **
5310 g_dbus_connection_list_registered (GDBusConnection *connection,
5311                                    const gchar     *path)
5312 {
5313   gchar **ret;
5314   CONNECTION_LOCK (connection);
5315   ret = g_dbus_connection_list_registered_unlocked (connection, path);
5316   CONNECTION_UNLOCK (connection);
5317   return ret;
5318 }
5319
5320 /* called in GDBusWorker thread with connection's lock held */
5321 static gboolean
5322 handle_introspect (GDBusConnection *connection,
5323                    ExportedObject  *eo,
5324                    GDBusMessage    *message)
5325 {
5326   guint n;
5327   GString *s;
5328   GDBusMessage *reply;
5329   GHashTableIter hash_iter;
5330   ExportedInterface *ei;
5331   gchar **registered;
5332
5333   /* first the header with the standard interfaces */
5334   s = g_string_sized_new (sizeof (introspect_header) +
5335                           sizeof (introspect_properties_interface) +
5336                           sizeof (introspect_introspectable_interface) +
5337                           sizeof (introspect_tail));
5338   introspect_append_header (s);
5339   if (!g_hash_table_lookup (eo->map_if_name_to_ei,
5340                             "org.freedesktop.DBus.Properties"))
5341     g_string_append (s, introspect_properties_interface);
5342
5343   if (!g_hash_table_lookup (eo->map_if_name_to_ei,
5344                             "org.freedesktop.DBus.Introspectable"))
5345     g_string_append (s, introspect_introspectable_interface);
5346
5347   /* then include the registered interfaces */
5348   g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
5349   while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
5350     g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
5351
5352   /* finally include nodes registered below us */
5353   registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
5354   for (n = 0; registered != NULL && registered[n] != NULL; n++)
5355     g_string_append_printf (s, "  <node name=\"%s\"/>\n", registered[n]);
5356   g_strfreev (registered);
5357   g_string_append (s, introspect_tail);
5358
5359   reply = g_dbus_message_new_method_reply (message);
5360   g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5361   g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5362   g_object_unref (reply);
5363   g_string_free (s, TRUE);
5364
5365   return TRUE;
5366 }
5367
5368 /* called in thread where object was registered - no locks held */
5369 static gboolean
5370 call_in_idle_cb (gpointer user_data)
5371 {
5372   GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
5373   GDBusInterfaceVTable *vtable;
5374   guint registration_id;
5375   guint subtree_registration_id;
5376
5377   registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
5378   subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
5379
5380   if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
5381                                     registration_id,
5382                                     subtree_registration_id))
5383     {
5384       GDBusMessage *reply;
5385       reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
5386                                                "org.freedesktop.DBus.Error.UnknownMethod",
5387                                                _("No such interface '%s' on object at path %s"),
5388                                                g_dbus_method_invocation_get_interface_name (invocation),
5389                                                g_dbus_method_invocation_get_object_path (invocation));
5390       g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5391       g_object_unref (reply);
5392       goto out;
5393     }
5394
5395   vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
5396   g_assert (vtable != NULL && vtable->method_call != NULL);
5397
5398   vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
5399                        g_dbus_method_invocation_get_sender (invocation),
5400                        g_dbus_method_invocation_get_object_path (invocation),
5401                        g_dbus_method_invocation_get_interface_name (invocation),
5402                        g_dbus_method_invocation_get_method_name (invocation),
5403                        g_dbus_method_invocation_get_parameters (invocation),
5404                        g_object_ref (invocation),
5405                        g_dbus_method_invocation_get_user_data (invocation));
5406
5407  out:
5408   return FALSE;
5409 }
5410
5411 /* called in GDBusWorker thread with connection's lock held */
5412 static void
5413 schedule_method_call (GDBusConnection            *connection,
5414                       GDBusMessage               *message,
5415                       guint                       registration_id,
5416                       guint                       subtree_registration_id,
5417                       const GDBusInterfaceInfo   *interface_info,
5418                       const GDBusMethodInfo      *method_info,
5419                       const GDBusPropertyInfo    *property_info,
5420                       GVariant                   *parameters,
5421                       const GDBusInterfaceVTable *vtable,
5422                       GMainContext               *main_context,
5423                       gpointer                    user_data)
5424 {
5425   GDBusMethodInvocation *invocation;
5426   GSource *idle_source;
5427
5428   invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
5429                                               g_dbus_message_get_path (message),
5430                                               g_dbus_message_get_interface (message),
5431                                               g_dbus_message_get_member (message),
5432                                               method_info,
5433                                               property_info,
5434                                               connection,
5435                                               message,
5436                                               parameters,
5437                                               user_data);
5438
5439   /* TODO: would be nicer with a real MethodData like we already
5440    * have PropertyData and PropertyGetAllData... */
5441   g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
5442   g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
5443   g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
5444
5445   idle_source = g_idle_source_new ();
5446   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
5447   g_source_set_callback (idle_source,
5448                          call_in_idle_cb,
5449                          invocation,
5450                          g_object_unref);
5451   g_source_set_name (idle_source, "[gio] call_in_idle_cb");
5452   g_source_attach (idle_source, main_context);
5453   g_source_unref (idle_source);
5454 }
5455
5456 /* called in GDBusWorker thread with connection's lock held */
5457 static gboolean
5458 validate_and_maybe_schedule_method_call (GDBusConnection            *connection,
5459                                          GDBusMessage               *message,
5460                                          guint                       registration_id,
5461                                          guint                       subtree_registration_id,
5462                                          GDBusInterfaceInfo         *interface_info,
5463                                          const GDBusInterfaceVTable *vtable,
5464                                          GMainContext               *main_context,
5465                                          gpointer                    user_data)
5466 {
5467   GDBusMethodInfo *method_info;
5468   GDBusMessage *reply;
5469   GVariant *parameters;
5470   gboolean handled;
5471   GVariantType *in_type;
5472
5473   handled = FALSE;
5474
5475   /* TODO: the cost of this is O(n) - it might be worth caching the result */
5476   method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
5477
5478   /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
5479    * error to the caller
5480    */
5481   if (method_info == NULL)
5482     {
5483       reply = g_dbus_message_new_method_error (message,
5484                                                "org.freedesktop.DBus.Error.UnknownMethod",
5485                                                _("No such method '%s'"),
5486                                                g_dbus_message_get_member (message));
5487       g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5488       g_object_unref (reply);
5489       handled = TRUE;
5490       goto out;
5491     }
5492
5493   parameters = g_dbus_message_get_body (message);
5494   if (parameters == NULL)
5495     {
5496       parameters = g_variant_new ("()");
5497       g_variant_ref_sink (parameters);
5498     }
5499   else
5500     {
5501       g_variant_ref (parameters);
5502     }
5503
5504   /* Check that the incoming args are of the right type - if they are not, return
5505    * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
5506    */
5507   in_type = _g_dbus_compute_complete_signature (method_info->in_args);
5508   if (!g_variant_is_of_type (parameters, in_type))
5509     {
5510       gchar *type_string;
5511
5512       type_string = g_variant_type_dup_string (in_type);
5513
5514       reply = g_dbus_message_new_method_error (message,
5515                                                "org.freedesktop.DBus.Error.InvalidArgs",
5516                                                _("Type of message, '%s', does not match expected type '%s'"),
5517                                                g_variant_get_type_string (parameters),
5518                                                type_string);
5519       g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5520       g_variant_type_free (in_type);
5521       g_variant_unref (parameters);
5522       g_object_unref (reply);
5523       g_free (type_string);
5524       handled = TRUE;
5525       goto out;
5526     }
5527   g_variant_type_free (in_type);
5528
5529   /* schedule the call in idle */
5530   schedule_method_call (connection, message, registration_id, subtree_registration_id,
5531                         interface_info, method_info, NULL, parameters,
5532                         vtable, main_context, user_data);
5533   g_variant_unref (parameters);
5534   handled = TRUE;
5535
5536  out:
5537   return handled;
5538 }
5539
5540 /* ---------------------------------------------------------------------------------------------------- */
5541
5542 /* called in GDBusWorker thread with connection's lock held */
5543 static gboolean
5544 obj_message_func (GDBusConnection *connection,
5545                   ExportedObject  *eo,
5546                   GDBusMessage    *message)
5547 {
5548   const gchar *interface_name;
5549   const gchar *member;
5550   const gchar *signature;
5551   gboolean handled;
5552
5553   handled = FALSE;
5554
5555   interface_name = g_dbus_message_get_interface (message);
5556   member = g_dbus_message_get_member (message);
5557   signature = g_dbus_message_get_signature (message);
5558
5559   /* see if we have an interface for handling this call */
5560   if (interface_name != NULL)
5561     {
5562       ExportedInterface *ei;
5563       ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5564       if (ei != NULL)
5565         {
5566           /* we do - invoke the handler in idle in the right thread */
5567
5568           /* handle no vtable or handler being present */
5569           if (ei->vtable == NULL || ei->vtable->method_call == NULL)
5570             goto out;
5571
5572           handled = validate_and_maybe_schedule_method_call (connection,
5573                                                              message,
5574                                                              ei->id,
5575                                                              0,
5576                                                              ei->interface_info,
5577                                                              ei->vtable,
5578                                                              ei->context,
5579                                                              ei->user_data);
5580           goto out;
5581         }
5582     }
5583
5584   if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5585       g_strcmp0 (member, "Introspect") == 0 &&
5586       g_strcmp0 (signature, "") == 0)
5587     {
5588       handled = handle_introspect (connection, eo, message);
5589       goto out;
5590     }
5591   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5592            g_strcmp0 (member, "Get") == 0 &&
5593            g_strcmp0 (signature, "ss") == 0)
5594     {
5595       handled = handle_getset_property (connection, eo, message, TRUE);
5596       goto out;
5597     }
5598   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5599            g_strcmp0 (member, "Set") == 0 &&
5600            g_strcmp0 (signature, "ssv") == 0)
5601     {
5602       handled = handle_getset_property (connection, eo, message, FALSE);
5603       goto out;
5604     }
5605   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5606            g_strcmp0 (member, "GetAll") == 0 &&
5607            g_strcmp0 (signature, "s") == 0)
5608     {
5609       handled = handle_get_all_properties (connection, eo, message);
5610       goto out;
5611     }
5612
5613  out:
5614   return handled;
5615 }
5616
5617 /**
5618  * g_dbus_connection_register_object:
5619  * @connection: a #GDBusConnection
5620  * @object_path: the object path to register at
5621  * @interface_info: introspection data for the interface
5622  * @vtable: (allow-none): a #GDBusInterfaceVTable to call into or %NULL
5623  * @user_data: (allow-none): data to pass to functions in @vtable
5624  * @user_data_free_func: function to call when the object path is unregistered
5625  * @error: return location for error or %NULL
5626  *
5627  * Registers callbacks for exported objects at @object_path with the
5628  * D-Bus interface that is described in @interface_info.
5629  *
5630  * Calls to functions in @vtable (and @user_data_free_func) will happen
5631  * in the 
5632  * [thread-default main context][g-main-context-push-thread-default]
5633  * of the thread you are calling this method from.
5634  *
5635  * Note that all #GVariant values passed to functions in @vtable will match
5636  * the signature given in @interface_info - if a remote caller passes
5637  * incorrect values, the `org.freedesktop.DBus.Error.InvalidArgs`
5638  * is returned to the remote caller.
5639  *
5640  * Additionally, if the remote caller attempts to invoke methods or
5641  * access properties not mentioned in @interface_info the
5642  * `org.freedesktop.DBus.Error.UnknownMethod` resp.
5643  * `org.freedesktop.DBus.Error.InvalidArgs` errors
5644  * are returned to the caller.
5645  *
5646  * It is considered a programming error if the
5647  * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
5648  * #GVariant of incorrect type.
5649  *
5650  * If an existing callback is already registered at @object_path and
5651  * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
5652  *
5653  * GDBus automatically implements the standard D-Bus interfaces
5654  * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
5655  * and org.freedesktop.Peer, so you don't have to implement those for the
5656  * objects you export. You can implement org.freedesktop.DBus.Properties
5657  * yourself, e.g. to handle getting and setting of properties asynchronously.
5658  *
5659  * Note that the reference count on @interface_info will be
5660  * incremented by 1 (unless allocated statically, e.g. if the
5661  * reference count is -1, see g_dbus_interface_info_ref()) for as long
5662  * as the object is exported. Also note that @vtable will be copied.
5663  *
5664  * See this [server][gdbus-server] for an example of how to use this method.
5665  *
5666  * Returns: 0 if @error is set, otherwise a registration id (never 0)
5667  *     that can be used with g_dbus_connection_unregister_object()
5668  *
5669  * Since: 2.26
5670  */
5671 guint
5672 g_dbus_connection_register_object (GDBusConnection             *connection,
5673                                    const gchar                 *object_path,
5674                                    GDBusInterfaceInfo          *interface_info,
5675                                    const GDBusInterfaceVTable  *vtable,
5676                                    gpointer                     user_data,
5677                                    GDestroyNotify               user_data_free_func,
5678                                    GError                     **error)
5679 {
5680   ExportedObject *eo;
5681   ExportedInterface *ei;
5682   guint ret;
5683
5684   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5685   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5686   g_return_val_if_fail (interface_info != NULL, 0);
5687   g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
5688   g_return_val_if_fail (error == NULL || *error == NULL, 0);
5689   g_return_val_if_fail (check_initialized (connection), 0);
5690
5691   ret = 0;
5692
5693   CONNECTION_LOCK (connection);
5694
5695   eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
5696   if (eo == NULL)
5697     {
5698       eo = g_new0 (ExportedObject, 1);
5699       eo->object_path = g_strdup (object_path);
5700       eo->connection = connection;
5701       eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
5702                                                      g_str_equal,
5703                                                      NULL,
5704                                                      (GDestroyNotify) exported_interface_free);
5705       g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
5706     }
5707
5708   ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
5709   if (ei != NULL)
5710     {
5711       g_set_error (error,
5712                    G_IO_ERROR,
5713                    G_IO_ERROR_EXISTS,
5714                    _("An object is already exported for the interface %s at %s"),
5715                    interface_info->name,
5716                    object_path);
5717       goto out;
5718     }
5719
5720   ei = g_new0 (ExportedInterface, 1);
5721   ei->id = _global_registration_id++; /* TODO: overflow etc. */
5722   ei->eo = eo;
5723   ei->user_data = user_data;
5724   ei->user_data_free_func = user_data_free_func;
5725   ei->vtable = _g_dbus_interface_vtable_copy (vtable);
5726   ei->interface_info = g_dbus_interface_info_ref (interface_info);
5727   g_dbus_interface_info_cache_build (ei->interface_info);
5728   ei->interface_name = g_strdup (interface_info->name);
5729   ei->context = g_main_context_ref_thread_default ();
5730
5731   g_hash_table_insert (eo->map_if_name_to_ei,
5732                        (gpointer) ei->interface_name,
5733                        ei);
5734   g_hash_table_insert (connection->map_id_to_ei,
5735                        GUINT_TO_POINTER (ei->id),
5736                        ei);
5737
5738   ret = ei->id;
5739
5740  out:
5741   CONNECTION_UNLOCK (connection);
5742
5743   return ret;
5744 }
5745
5746 /**
5747  * g_dbus_connection_unregister_object:
5748  * @connection: a #GDBusConnection
5749  * @registration_id: a registration id obtained from
5750  *     g_dbus_connection_register_object()
5751  *
5752  * Unregisters an object.
5753  *
5754  * Returns: %TRUE if the object was unregistered, %FALSE otherwise
5755  *
5756  * Since: 2.26
5757  */
5758 gboolean
5759 g_dbus_connection_unregister_object (GDBusConnection *connection,
5760                                      guint            registration_id)
5761 {
5762   ExportedInterface *ei;
5763   ExportedObject *eo;
5764   gboolean ret;
5765
5766   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5767   g_return_val_if_fail (check_initialized (connection), FALSE);
5768
5769   ret = FALSE;
5770
5771   CONNECTION_LOCK (connection);
5772
5773   ei = g_hash_table_lookup (connection->map_id_to_ei,
5774                             GUINT_TO_POINTER (registration_id));
5775   if (ei == NULL)
5776     goto out;
5777
5778   eo = ei->eo;
5779
5780   g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5781   g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5782   /* unregister object path if we have no more exported interfaces */
5783   if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5784     g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5785                                          eo->object_path));
5786
5787   ret = TRUE;
5788
5789  out:
5790   CONNECTION_UNLOCK (connection);
5791
5792   return ret;
5793 }
5794
5795 /* ---------------------------------------------------------------------------------------------------- */
5796
5797 /**
5798  * g_dbus_connection_emit_signal:
5799  * @connection: a #GDBusConnection
5800  * @destination_bus_name: (allow-none): the unique bus name for the destination
5801  *     for the signal or %NULL to emit to all listeners
5802  * @object_path: path of remote object
5803  * @interface_name: D-Bus interface to emit a signal on
5804  * @signal_name: the name of the signal to emit
5805  * @parameters: (allow-none): a #GVariant tuple with parameters for the signal
5806  *              or %NULL if not passing parameters
5807  * @error: Return location for error or %NULL
5808  *
5809  * Emits a signal.
5810  *
5811  * If the parameters GVariant is floating, it is consumed.
5812  *
5813  * This can only fail if @parameters is not compatible with the D-Bus protocol.
5814  *
5815  * Returns: %TRUE unless @error is set
5816  *
5817  * Since: 2.26
5818  */
5819 gboolean
5820 g_dbus_connection_emit_signal (GDBusConnection  *connection,
5821                                const gchar      *destination_bus_name,
5822                                const gchar      *object_path,
5823                                const gchar      *interface_name,
5824                                const gchar      *signal_name,
5825                                GVariant         *parameters,
5826                                GError          **error)
5827 {
5828   GDBusMessage *message;
5829   gboolean ret;
5830
5831   message = NULL;
5832   ret = FALSE;
5833
5834   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5835   g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5836   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5837   g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5838   g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5839   g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5840   g_return_val_if_fail (check_initialized (connection), FALSE);
5841
5842   if (G_UNLIKELY (_g_dbus_debug_emission ()))
5843     {
5844       _g_dbus_debug_print_lock ();
5845       g_print ("========================================================================\n"
5846                "GDBus-debug:Emission:\n"
5847                " >>>> SIGNAL EMISSION %s.%s()\n"
5848                "      on object %s\n"
5849                "      destination %s\n",
5850                interface_name, signal_name,
5851                object_path,
5852                destination_bus_name != NULL ? destination_bus_name : "(none)");
5853       _g_dbus_debug_print_unlock ();
5854     }
5855
5856   message = g_dbus_message_new_signal (object_path,
5857                                        interface_name,
5858                                        signal_name);
5859
5860   if (destination_bus_name != NULL)
5861     g_dbus_message_set_header (message,
5862                                G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5863                                g_variant_new_string (destination_bus_name));
5864
5865   if (parameters != NULL)
5866     g_dbus_message_set_body (message, parameters);
5867
5868   ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5869   g_object_unref (message);
5870
5871   return ret;
5872 }
5873
5874 static void
5875 add_call_flags (GDBusMessage           *message,
5876                          GDBusCallFlags  flags)
5877 {
5878   if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5879     g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
5880 }
5881
5882 static GVariant *
5883 decode_method_reply (GDBusMessage        *reply,
5884                      const gchar         *method_name,
5885                      const GVariantType  *reply_type,
5886                      GUnixFDList        **out_fd_list,
5887                      GError             **error)
5888 {
5889   GVariant *result;
5890
5891   result = NULL;
5892   switch (g_dbus_message_get_message_type (reply))
5893     {
5894     case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5895       result = g_dbus_message_get_body (reply);
5896       if (result == NULL)
5897         {
5898           result = g_variant_new ("()");
5899           g_variant_ref_sink (result);
5900         }
5901       else
5902         {
5903           g_variant_ref (result);
5904         }
5905
5906       if (!g_variant_is_of_type (result, reply_type))
5907         {
5908           gchar *type_string = g_variant_type_dup_string (reply_type);
5909
5910           g_set_error (error,
5911                        G_IO_ERROR,
5912                        G_IO_ERROR_INVALID_ARGUMENT,
5913                        _("Method '%s' returned type '%s', but expected '%s'"),
5914                        method_name, g_variant_get_type_string (result), type_string);
5915
5916           g_variant_unref (result);
5917           g_free (type_string);
5918           result = NULL;
5919         }
5920
5921 #ifdef G_OS_UNIX
5922       if (result != NULL)
5923         {
5924           if (out_fd_list != NULL)
5925             {
5926               *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5927               if (*out_fd_list != NULL)
5928                 g_object_ref (*out_fd_list);
5929             }
5930         }
5931 #endif
5932       break;
5933
5934     case G_DBUS_MESSAGE_TYPE_ERROR:
5935       g_dbus_message_to_gerror (reply, error);
5936       break;
5937
5938     default:
5939       g_assert_not_reached ();
5940       break;
5941     }
5942
5943   return result;
5944 }
5945
5946
5947 typedef struct
5948 {
5949   GSimpleAsyncResult *simple;
5950   GVariantType *reply_type;
5951   gchar *method_name; /* for error message */
5952   guint32 serial;
5953
5954   GVariant *value;
5955   GUnixFDList *fd_list;
5956 } CallState;
5957
5958 static void
5959 call_state_free (CallState *state)
5960 {
5961   g_variant_type_free (state->reply_type);
5962   g_free (state->method_name);
5963
5964   if (state->value != NULL)
5965     g_variant_unref (state->value);
5966   if (state->fd_list != NULL)
5967     g_object_unref (state->fd_list);
5968   g_slice_free (CallState, state);
5969 }
5970
5971 /* called in any thread, with the connection's lock not held */
5972 static void
5973 g_dbus_connection_call_done (GObject      *source,
5974                              GAsyncResult *result,
5975                              gpointer      user_data)
5976 {
5977   GSimpleAsyncResult *simple;
5978   GDBusConnection *connection = G_DBUS_CONNECTION (source);
5979   CallState *state = user_data;
5980   GError *error;
5981   GDBusMessage *reply;
5982
5983   error = NULL;
5984   reply = g_dbus_connection_send_message_with_reply_finish (connection,
5985                                                             result,
5986                                                             &error);
5987
5988   if (G_UNLIKELY (_g_dbus_debug_call ()))
5989     {
5990       _g_dbus_debug_print_lock ();
5991       g_print ("========================================================================\n"
5992                "GDBus-debug:Call:\n"
5993                " <<<< ASYNC COMPLETE %s() (serial %d)\n"
5994                "      ",
5995                state->method_name,
5996                state->serial);
5997       if (reply != NULL)
5998         {
5999           g_print ("SUCCESS\n");
6000         }
6001       else
6002         {
6003           g_print ("FAILED: %s\n",
6004                    error->message);
6005         }
6006       _g_dbus_debug_print_unlock ();
6007     }
6008
6009   if (reply != NULL)
6010     state->value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
6011
6012   simple = state->simple; /* why? because state is freed before we unref simple.. */
6013   if (error != NULL)
6014     {
6015       g_simple_async_result_take_error (state->simple, error);
6016       g_simple_async_result_complete (state->simple);
6017       call_state_free (state);
6018     }
6019   else
6020     {
6021       g_simple_async_result_set_op_res_gpointer (state->simple, state, (GDestroyNotify) call_state_free);
6022       g_simple_async_result_complete (state->simple);
6023     }
6024   g_clear_object (&reply);
6025   g_object_unref (simple);
6026 }
6027
6028 /* called in any thread, with the connection's lock not held */
6029 static void
6030 g_dbus_connection_call_internal (GDBusConnection        *connection,
6031                                  const gchar            *bus_name,
6032                                  const gchar            *object_path,
6033                                  const gchar            *interface_name,
6034                                  const gchar            *method_name,
6035                                  GVariant               *parameters,
6036                                  const GVariantType     *reply_type,
6037                                  GDBusCallFlags          flags,
6038                                  gint                    timeout_msec,
6039                                  GUnixFDList            *fd_list,
6040                                  GCancellable           *cancellable,
6041                                  GAsyncReadyCallback     callback,
6042                                  gpointer                user_data)
6043 {
6044   GDBusMessage *message;
6045   guint32 serial;
6046
6047   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
6048   g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
6049   g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
6050   g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
6051   g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
6052   g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
6053   g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
6054   g_return_if_fail (check_initialized (connection));
6055 #ifdef G_OS_UNIX
6056   g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
6057 #else
6058   g_return_if_fail (fd_list == NULL);
6059 #endif
6060
6061   message = g_dbus_message_new_method_call (bus_name,
6062                                             object_path,
6063                                             interface_name,
6064                                             method_name);
6065   add_call_flags (message, flags);
6066   if (parameters != NULL)
6067     g_dbus_message_set_body (message, parameters);
6068
6069 #ifdef G_OS_UNIX
6070   if (fd_list != NULL)
6071     g_dbus_message_set_unix_fd_list (message, fd_list);
6072 #endif
6073
6074   /* If the user has no callback then we can just send the message with
6075    * the G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set and skip all
6076    * the logic for processing the reply.  If the service sends the reply
6077    * anyway then it will just be ignored.
6078    */
6079   if (callback != NULL)
6080     {
6081       CallState *state;
6082
6083       state = g_slice_new0 (CallState);
6084       state->simple = g_simple_async_result_new (G_OBJECT (connection),
6085                                                  callback, user_data,
6086                                                  g_dbus_connection_call_internal);
6087       g_simple_async_result_set_check_cancellable (state->simple, cancellable);
6088       state->method_name = g_strjoin (".", interface_name, method_name, NULL);
6089
6090       if (reply_type == NULL)
6091         reply_type = G_VARIANT_TYPE_ANY;
6092
6093       state->reply_type = g_variant_type_copy (reply_type);
6094
6095       g_dbus_connection_send_message_with_reply (connection,
6096                                                  message,
6097                                                  G_DBUS_SEND_MESSAGE_FLAGS_NONE,
6098                                                  timeout_msec,
6099                                                  &state->serial,
6100                                                  cancellable,
6101                                                  g_dbus_connection_call_done,
6102                                                  state);
6103       serial = state->serial;
6104     }
6105   else
6106     {
6107       GDBusMessageFlags flags;
6108
6109       flags = g_dbus_message_get_flags (message);
6110       flags |= G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
6111       g_dbus_message_set_flags (message, flags);
6112
6113       g_dbus_connection_send_message (connection,
6114                                       message,
6115                                       G_DBUS_SEND_MESSAGE_FLAGS_NONE,
6116                                       &serial, NULL);
6117     }
6118
6119   if (G_UNLIKELY (_g_dbus_debug_call ()))
6120     {
6121       _g_dbus_debug_print_lock ();
6122       g_print ("========================================================================\n"
6123                "GDBus-debug:Call:\n"
6124                " >>>> ASYNC %s.%s()\n"
6125                "      on object %s\n"
6126                "      owned by name %s (serial %d)\n",
6127                interface_name,
6128                method_name,
6129                object_path,
6130                bus_name != NULL ? bus_name : "(none)",
6131                serial);
6132       _g_dbus_debug_print_unlock ();
6133     }
6134
6135   if (message != NULL)
6136     g_object_unref (message);
6137 }
6138
6139 /* called in any thread, with the connection's lock not held */
6140 static GVariant *
6141 g_dbus_connection_call_finish_internal (GDBusConnection  *connection,
6142                                         GUnixFDList     **out_fd_list,
6143                                         GAsyncResult     *res,
6144                                         GError          **error)
6145 {
6146   GSimpleAsyncResult *simple;
6147   CallState *state;
6148
6149   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
6150   g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
6151                                                         g_dbus_connection_call_internal), NULL);
6152   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6153
6154   simple = G_SIMPLE_ASYNC_RESULT (res);
6155
6156   if (g_simple_async_result_propagate_error (simple, error))
6157     return NULL;
6158
6159   state = g_simple_async_result_get_op_res_gpointer (simple);
6160   if (out_fd_list != NULL)
6161     *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
6162   return g_variant_ref (state->value);
6163 }
6164
6165 /* called in any user thread, with the connection's lock not held */
6166 static GVariant *
6167 g_dbus_connection_call_sync_internal (GDBusConnection         *connection,
6168                                       const gchar             *bus_name,
6169                                       const gchar             *object_path,
6170                                       const gchar             *interface_name,
6171                                       const gchar             *method_name,
6172                                       GVariant                *parameters,
6173                                       const GVariantType      *reply_type,
6174                                       GDBusCallFlags           flags,
6175                                       gint                     timeout_msec,
6176                                       GUnixFDList             *fd_list,
6177                                       GUnixFDList            **out_fd_list,
6178                                       GCancellable            *cancellable,
6179                                       GError                 **error)
6180 {
6181   GDBusMessage *message;
6182   GDBusMessage *reply;
6183   GVariant *result;
6184   GError *local_error;
6185   GDBusSendMessageFlags send_flags;
6186
6187   message = NULL;
6188   reply = NULL;
6189   result = NULL;
6190
6191   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
6192   g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
6193   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
6194   g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
6195   g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
6196   g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
6197   g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
6198 #ifdef G_OS_UNIX
6199   g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
6200 #else
6201   g_return_val_if_fail (fd_list == NULL, NULL);
6202 #endif
6203   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6204
6205   if (!(flags & CALL_FLAGS_INITIALIZING))
6206     g_return_val_if_fail (check_initialized (connection), FALSE);
6207
6208   if (reply_type == NULL)
6209     reply_type = G_VARIANT_TYPE_ANY;
6210
6211   message = g_dbus_message_new_method_call (bus_name,
6212                                             object_path,
6213                                             interface_name,
6214                                             method_name);
6215   add_call_flags (message, flags);
6216   if (parameters != NULL)
6217     g_dbus_message_set_body (message, parameters);
6218
6219 #ifdef G_OS_UNIX
6220   if (fd_list != NULL)
6221     g_dbus_message_set_unix_fd_list (message, fd_list);
6222 #endif
6223
6224   if (G_UNLIKELY (_g_dbus_debug_call ()))
6225     {
6226       _g_dbus_debug_print_lock ();
6227       g_print ("========================================================================\n"
6228                "GDBus-debug:Call:\n"
6229                " >>>> SYNC %s.%s()\n"
6230                "      on object %s\n"
6231                "      owned by name %s\n",
6232                interface_name,
6233                method_name,
6234                object_path,
6235                bus_name != NULL ? bus_name : "(none)");
6236       _g_dbus_debug_print_unlock ();
6237     }
6238
6239   local_error = NULL;
6240
6241   send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
6242
6243   /* translate from one flavour of flags to another... */
6244   if (flags & CALL_FLAGS_INITIALIZING)
6245     send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
6246
6247   reply = g_dbus_connection_send_message_with_reply_sync (connection,
6248                                                           message,
6249                                                           send_flags,
6250                                                           timeout_msec,
6251                                                           NULL, /* volatile guint32 *out_serial */
6252                                                           cancellable,
6253                                                           &local_error);
6254
6255   if (G_UNLIKELY (_g_dbus_debug_call ()))
6256     {
6257       _g_dbus_debug_print_lock ();
6258       g_print ("========================================================================\n"
6259                "GDBus-debug:Call:\n"
6260                " <<<< SYNC COMPLETE %s.%s()\n"
6261                "      ",
6262                interface_name,
6263                method_name);
6264       if (reply != NULL)
6265         {
6266           g_print ("SUCCESS\n");
6267         }
6268       else
6269         {
6270           g_print ("FAILED: %s\n",
6271                    local_error->message);
6272         }
6273       _g_dbus_debug_print_unlock ();
6274     }
6275
6276   if (reply == NULL)
6277     {
6278       if (error != NULL)
6279         *error = local_error;
6280       else
6281         g_error_free (local_error);
6282       goto out;
6283     }
6284
6285   result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
6286
6287  out:
6288   if (message != NULL)
6289     g_object_unref (message);
6290   if (reply != NULL)
6291     g_object_unref (reply);
6292
6293   return result;
6294 }
6295
6296 /* ---------------------------------------------------------------------------------------------------- */
6297
6298 /**
6299  * g_dbus_connection_call:
6300  * @connection: a #GDBusConnection
6301  * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
6302  *     @connection is not a message bus connection
6303  * @object_path: path of remote object
6304  * @interface_name: D-Bus interface to invoke method on
6305  * @method_name: the name of the method to invoke
6306  * @parameters: (allow-none): a #GVariant tuple with parameters for the method
6307  *     or %NULL if not passing parameters
6308  * @reply_type: (allow-none): the expected type of the reply, or %NULL
6309  * @flags: flags from the #GDBusCallFlags enumeration
6310  * @timeout_msec: the timeout in milliseconds, -1 to use the default
6311  *     timeout or %G_MAXINT for no timeout
6312  * @cancellable: (allow-none): a #GCancellable or %NULL
6313  * @callback: (allow-none): a #GAsyncReadyCallback to call when the request
6314  *     is satisfied or %NULL if you don't care about the result of the
6315  *     method invocation
6316  * @user_data: the data to pass to @callback
6317  *
6318  * Asynchronously invokes the @method_name method on the
6319  * @interface_name D-Bus interface on the remote object at
6320  * @object_path owned by @bus_name.
6321  *
6322  * If @connection is closed then the operation will fail with
6323  * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
6324  * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
6325  * not compatible with the D-Bus protocol, the operation fails with
6326  * %G_IO_ERROR_INVALID_ARGUMENT.
6327  *
6328  * If @reply_type is non-%NULL then the reply will be checked for having this type and an
6329  * error will be raised if it does not match.  Said another way, if you give a @reply_type
6330  * then any non-%NULL return value will be of this type.
6331  *
6332  * If the @parameters #GVariant is floating, it is consumed. This allows
6333  * convenient 'inline' use of g_variant_new(), e.g.:
6334  * |[<!-- language="C" -->
6335  *  g_dbus_connection_call (connection,
6336  *                          "org.freedesktop.StringThings",
6337  *                          "/org/freedesktop/StringThings",
6338  *                          "org.freedesktop.StringThings",
6339  *                          "TwoStrings",
6340  *                          g_variant_new ("(ss)",
6341  *                                         "Thing One",
6342  *                                         "Thing Two"),
6343  *                          NULL,
6344  *                          G_DBUS_CALL_FLAGS_NONE,
6345  *                          -1,
6346  *                          NULL,
6347  *                          (GAsyncReadyCallback) two_strings_done,
6348  *                          NULL);
6349  * ]|
6350  *
6351  * This is an asynchronous method. When the operation is finished,
6352  * @callback will be invoked in the
6353  * [thread-default main context][g-main-context-push-thread-default]
6354  * of the thread you are calling this method from. You can then call
6355  * g_dbus_connection_call_finish() to get the result of the operation.
6356  * See g_dbus_connection_call_sync() for the synchronous version of this
6357  * function.
6358  *
6359  * If @callback is %NULL then the D-Bus method call message will be sent with
6360  * the %G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set.
6361  *
6362  * Since: 2.26
6363  */
6364 void
6365 g_dbus_connection_call (GDBusConnection     *connection,
6366                         const gchar         *bus_name,
6367                         const gchar         *object_path,
6368                         const gchar         *interface_name,
6369                         const gchar         *method_name,
6370                         GVariant            *parameters,
6371                         const GVariantType  *reply_type,
6372                         GDBusCallFlags       flags,
6373                         gint                 timeout_msec,
6374                         GCancellable        *cancellable,
6375                         GAsyncReadyCallback  callback,
6376                         gpointer             user_data)
6377 {
6378   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);
6379 }
6380
6381 /**
6382  * g_dbus_connection_call_finish:
6383  * @connection: a #GDBusConnection
6384  * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call()
6385  * @error: return location for error or %NULL
6386  *
6387  * Finishes an operation started with g_dbus_connection_call().
6388  *
6389  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6390  *     return values. Free with g_variant_unref().
6391  *
6392  * Since: 2.26
6393  */
6394 GVariant *
6395 g_dbus_connection_call_finish (GDBusConnection  *connection,
6396                                GAsyncResult     *res,
6397                                GError          **error)
6398 {
6399   return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
6400 }
6401
6402 /**
6403  * g_dbus_connection_call_sync:
6404  * @connection: a #GDBusConnection
6405  * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
6406  *     @connection is not a message bus connection
6407  * @object_path: path of remote object
6408  * @interface_name: D-Bus interface to invoke method on
6409  * @method_name: the name of the method to invoke
6410  * @parameters: (allow-none): a #GVariant tuple with parameters for the method
6411  *     or %NULL if not passing parameters
6412  * @reply_type: (allow-none): the expected type of the reply, or %NULL
6413  * @flags: flags from the #GDBusCallFlags enumeration
6414  * @timeout_msec: the timeout in milliseconds, -1 to use the default
6415  *     timeout or %G_MAXINT for no timeout
6416  * @cancellable: (allow-none): a #GCancellable or %NULL
6417  * @error: return location for error or %NULL
6418  *
6419  * Synchronously invokes the @method_name method on the
6420  * @interface_name D-Bus interface on the remote object at
6421  * @object_path owned by @bus_name.
6422  *
6423  * If @connection is closed then the operation will fail with
6424  * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
6425  * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
6426  * contains a value not compatible with the D-Bus protocol, the operation
6427  * fails with %G_IO_ERROR_INVALID_ARGUMENT.
6428
6429  * If @reply_type is non-%NULL then the reply will be checked for having
6430  * this type and an error will be raised if it does not match.  Said
6431  * another way, if you give a @reply_type then any non-%NULL return
6432  * value will be of this type.
6433  *
6434  * If the @parameters #GVariant is floating, it is consumed.
6435  * This allows convenient 'inline' use of g_variant_new(), e.g.:
6436  * |[<!-- language="C" -->
6437  *  g_dbus_connection_call_sync (connection,
6438  *                               "org.freedesktop.StringThings",
6439  *                               "/org/freedesktop/StringThings",
6440  *                               "org.freedesktop.StringThings",
6441  *                               "TwoStrings",
6442  *                               g_variant_new ("(ss)",
6443  *                                              "Thing One",
6444  *                                              "Thing Two"),
6445  *                               NULL,
6446  *                               G_DBUS_CALL_FLAGS_NONE,
6447  *                               -1,
6448  *                               NULL,
6449  *                               &error);
6450  * ]|
6451  *
6452  * The calling thread is blocked until a reply is received. See
6453  * g_dbus_connection_call() for the asynchronous version of
6454  * this method.
6455  *
6456  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6457  *     return values. Free with g_variant_unref().
6458  *
6459  * Since: 2.26
6460  */
6461 GVariant *
6462 g_dbus_connection_call_sync (GDBusConnection     *connection,
6463                              const gchar         *bus_name,
6464                              const gchar         *object_path,
6465                              const gchar         *interface_name,
6466                              const gchar         *method_name,
6467                              GVariant            *parameters,
6468                              const GVariantType  *reply_type,
6469                              GDBusCallFlags       flags,
6470                              gint                 timeout_msec,
6471                              GCancellable        *cancellable,
6472                              GError             **error)
6473 {
6474   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);
6475 }
6476
6477 /* ---------------------------------------------------------------------------------------------------- */
6478
6479 #ifdef G_OS_UNIX
6480
6481 /**
6482  * g_dbus_connection_call_with_unix_fd_list:
6483  * @connection: a #GDBusConnection
6484  * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
6485  *     @connection is not a message bus connection
6486  * @object_path: path of remote object
6487  * @interface_name: D-Bus interface to invoke method on
6488  * @method_name: the name of the method to invoke
6489  * @parameters: (allow-none): a #GVariant tuple with parameters for the method
6490  *     or %NULL if not passing parameters
6491  * @reply_type: (allow-none): the expected type of the reply, or %NULL
6492  * @flags: flags from the #GDBusCallFlags enumeration
6493  * @timeout_msec: the timeout in milliseconds, -1 to use the default
6494  *     timeout or %G_MAXINT for no timeout
6495  * @fd_list: (allow-none): a #GUnixFDList or %NULL
6496  * @cancellable: (allow-none): a #GCancellable or %NULL
6497  * @callback: (allow-none): a #GAsyncReadyCallback to call when the request is
6498  *     satisfied or %NULL if you don't * care about the result of the
6499  *     method invocation
6500  * @user_data: The data to pass to @callback.
6501  *
6502  * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
6503  *
6504  * This method is only available on UNIX.
6505  *
6506  * Since: 2.30
6507  */
6508 void
6509 g_dbus_connection_call_with_unix_fd_list (GDBusConnection     *connection,
6510                                           const gchar         *bus_name,
6511                                           const gchar         *object_path,
6512                                           const gchar         *interface_name,
6513                                           const gchar         *method_name,
6514                                           GVariant            *parameters,
6515                                           const GVariantType  *reply_type,
6516                                           GDBusCallFlags       flags,
6517                                           gint                 timeout_msec,
6518                                           GUnixFDList         *fd_list,
6519                                           GCancellable        *cancellable,
6520                                           GAsyncReadyCallback  callback,
6521                                           gpointer             user_data)
6522 {
6523   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);
6524 }
6525
6526 /**
6527  * g_dbus_connection_call_with_unix_fd_list_finish:
6528  * @connection: a #GDBusConnection
6529  * @out_fd_list: (out) (allow-none): return location for a #GUnixFDList or %NULL
6530  * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
6531  *     g_dbus_connection_call_with_unix_fd_list()
6532  * @error: return location for error or %NULL
6533  *
6534  * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
6535  *
6536  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6537  *     return values. Free with g_variant_unref().
6538  *
6539  * Since: 2.30
6540  */
6541 GVariant *
6542 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection  *connection,
6543                                                  GUnixFDList     **out_fd_list,
6544                                                  GAsyncResult     *res,
6545                                                  GError          **error)
6546 {
6547   return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
6548 }
6549
6550 /**
6551  * g_dbus_connection_call_with_unix_fd_list_sync:
6552  * @connection: a #GDBusConnection
6553  * @bus_name: (allow-none): a unique or well-known bus name or %NULL
6554  *     if @connection is not a message bus connection
6555  * @object_path: path of remote object
6556  * @interface_name: D-Bus interface to invoke method on
6557  * @method_name: the name of the method to invoke
6558  * @parameters: (allow-none): a #GVariant tuple with parameters for
6559  *     the method or %NULL if not passing parameters
6560  * @reply_type: (allow-none): the expected type of the reply, or %NULL
6561  * @flags: flags from the #GDBusCallFlags enumeration
6562  * @timeout_msec: the timeout in milliseconds, -1 to use the default
6563  *     timeout or %G_MAXINT for no timeout
6564  * @fd_list: (allow-none): a #GUnixFDList or %NULL
6565  * @out_fd_list: (out) (allow-none): return location for a #GUnixFDList or %NULL
6566  * @cancellable: (allow-none): a #GCancellable or %NULL
6567  * @error: return location for error or %NULL
6568  *
6569  * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
6570  *
6571  * This method is only available on UNIX.
6572  *
6573  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6574  *     return values. Free with g_variant_unref().
6575  *
6576  * Since: 2.30
6577  */
6578 GVariant *
6579 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection     *connection,
6580                                                const gchar         *bus_name,
6581                                                const gchar         *object_path,
6582                                                const gchar         *interface_name,
6583                                                const gchar         *method_name,
6584                                                GVariant            *parameters,
6585                                                const GVariantType  *reply_type,
6586                                                GDBusCallFlags       flags,
6587                                                gint                 timeout_msec,
6588                                                GUnixFDList         *fd_list,
6589                                                GUnixFDList        **out_fd_list,
6590                                                GCancellable        *cancellable,
6591                                                GError             **error)
6592 {
6593   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);
6594 }
6595
6596 #endif /* G_OS_UNIX */
6597
6598 /* ---------------------------------------------------------------------------------------------------- */
6599
6600 struct ExportedSubtree
6601 {
6602   guint                     id;
6603   gchar                    *object_path;
6604   GDBusConnection          *connection;
6605   GDBusSubtreeVTable       *vtable;
6606   GDBusSubtreeFlags         flags;
6607
6608   GMainContext             *context;
6609   gpointer                  user_data;
6610   GDestroyNotify            user_data_free_func;
6611 };
6612
6613 static void
6614 exported_subtree_free (ExportedSubtree *es)
6615 {
6616   call_destroy_notify (es->context,
6617                        es->user_data_free_func,
6618                        es->user_data);
6619
6620   g_main_context_unref (es->context);
6621
6622   _g_dbus_subtree_vtable_free (es->vtable);
6623   g_free (es->object_path);
6624   g_free (es);
6625 }
6626
6627 /* called without lock held in the thread where the caller registered
6628  * the subtree
6629  */
6630 static gboolean
6631 handle_subtree_introspect (GDBusConnection *connection,
6632                            ExportedSubtree *es,
6633                            GDBusMessage    *message)
6634 {
6635   GString *s;
6636   gboolean handled;
6637   GDBusMessage *reply;
6638   gchar **children;
6639   gboolean is_root;
6640   const gchar *sender;
6641   const gchar *requested_object_path;
6642   const gchar *requested_node;
6643   GDBusInterfaceInfo **interfaces;
6644   guint n;
6645   gchar **subnode_paths;
6646   gboolean has_properties_interface;
6647   gboolean has_introspectable_interface;
6648
6649   handled = FALSE;
6650
6651   requested_object_path = g_dbus_message_get_path (message);
6652   sender = g_dbus_message_get_sender (message);
6653   is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6654
6655   s = g_string_new (NULL);
6656   introspect_append_header (s);
6657
6658   /* Strictly we don't need the children in dynamic mode, but we avoid the
6659    * conditionals to preserve code clarity
6660    */
6661   children = es->vtable->enumerate (es->connection,
6662                                     sender,
6663                                     es->object_path,
6664                                     es->user_data);
6665
6666   if (!is_root)
6667     {
6668       requested_node = strrchr (requested_object_path, '/') + 1;
6669
6670       /* Assert existence of object if we are not dynamic */
6671       if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
6672           !_g_strv_has_string ((const gchar * const *) children, requested_node))
6673         goto out;
6674     }
6675   else
6676     {
6677       requested_node = NULL;
6678     }
6679
6680   interfaces = es->vtable->introspect (es->connection,
6681                                        sender,
6682                                        es->object_path,
6683                                        requested_node,
6684                                        es->user_data);
6685   if (interfaces != NULL)
6686     {
6687       has_properties_interface = FALSE;
6688       has_introspectable_interface = FALSE;
6689
6690       for (n = 0; interfaces[n] != NULL; n++)
6691         {
6692           if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
6693             has_properties_interface = TRUE;
6694           else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
6695             has_introspectable_interface = TRUE;
6696         }
6697       if (!has_properties_interface)
6698         g_string_append (s, introspect_properties_interface);
6699       if (!has_introspectable_interface)
6700         g_string_append (s, introspect_introspectable_interface);
6701
6702       for (n = 0; interfaces[n] != NULL; n++)
6703         {
6704           g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
6705           g_dbus_interface_info_unref (interfaces[n]);
6706         }
6707       g_free (interfaces);
6708     }
6709
6710   /* then include <node> entries from the Subtree for the root */
6711   if (is_root)
6712     {
6713       for (n = 0; children != NULL && children[n] != NULL; n++)
6714         g_string_append_printf (s, "  <node name=\"%s\"/>\n", children[n]);
6715     }
6716
6717   /* finally include nodes registered below us */
6718   subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
6719   for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
6720     g_string_append_printf (s, "  <node name=\"%s\"/>\n", subnode_paths[n]);
6721   g_strfreev (subnode_paths);
6722
6723   g_string_append (s, "</node>\n");
6724
6725   reply = g_dbus_message_new_method_reply (message);
6726   g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6727   g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6728   g_object_unref (reply);
6729
6730   handled = TRUE;
6731
6732  out:
6733   g_string_free (s, TRUE);
6734   g_strfreev (children);
6735   return handled;
6736 }
6737
6738 /* called without lock held in the thread where the caller registered
6739  * the subtree
6740  */
6741 static gboolean
6742 handle_subtree_method_invocation (GDBusConnection *connection,
6743                                   ExportedSubtree *es,
6744                                   GDBusMessage    *message)
6745 {
6746   gboolean handled;
6747   const gchar *sender;
6748   const gchar *interface_name;
6749   const gchar *member;
6750   const gchar *signature;
6751   const gchar *requested_object_path;
6752   const gchar *requested_node;
6753   gboolean is_root;
6754   GDBusInterfaceInfo *interface_info;
6755   const GDBusInterfaceVTable *interface_vtable;
6756   gpointer interface_user_data;
6757   guint n;
6758   GDBusInterfaceInfo **interfaces;
6759   gboolean is_property_get;
6760   gboolean is_property_set;
6761   gboolean is_property_get_all;
6762
6763   handled = FALSE;
6764   interfaces = NULL;
6765
6766   requested_object_path = g_dbus_message_get_path (message);
6767   sender = g_dbus_message_get_sender (message);
6768   interface_name = g_dbus_message_get_interface (message);
6769   member = g_dbus_message_get_member (message);
6770   signature = g_dbus_message_get_signature (message);
6771   is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6772
6773   is_property_get = FALSE;
6774   is_property_set = FALSE;
6775   is_property_get_all = FALSE;
6776   if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6777     {
6778       if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6779         is_property_get = TRUE;
6780       else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6781         is_property_set = TRUE;
6782       else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6783         is_property_get_all = TRUE;
6784     }
6785
6786   if (!is_root)
6787     {
6788       requested_node = strrchr (requested_object_path, '/') + 1;
6789
6790       if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6791         {
6792           /* We don't want to dispatch to unenumerated
6793            * nodes, so ensure that the child exists.
6794            */
6795           gchar **children;
6796           gboolean exists;
6797
6798           children = es->vtable->enumerate (es->connection,
6799                                             sender,
6800                                             es->object_path,
6801                                             es->user_data);
6802
6803           exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6804           g_strfreev (children);
6805
6806           if (!exists)
6807             goto out;
6808         }
6809     }
6810   else
6811     {
6812       requested_node = NULL;
6813     }
6814
6815   /* get introspection data for the node */
6816   interfaces = es->vtable->introspect (es->connection,
6817                                        sender,
6818                                        requested_object_path,
6819                                        requested_node,
6820                                        es->user_data);
6821
6822   if (interfaces == NULL)
6823     goto out;
6824
6825   interface_info = NULL;
6826   for (n = 0; interfaces[n] != NULL; n++)
6827     {
6828       if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6829         interface_info = interfaces[n];
6830     }
6831
6832   /* dispatch the call if the user wants to handle it */
6833   if (interface_info != NULL)
6834     {
6835       /* figure out where to dispatch the method call */
6836       interface_user_data = NULL;
6837       interface_vtable = es->vtable->dispatch (es->connection,
6838                                                sender,
6839                                                es->object_path,
6840                                                interface_name,
6841                                                requested_node,
6842                                                &interface_user_data,
6843                                                es->user_data);
6844       if (interface_vtable == NULL)
6845         goto out;
6846
6847       CONNECTION_LOCK (connection);
6848       handled = validate_and_maybe_schedule_method_call (es->connection,
6849                                                          message,
6850                                                          0,
6851                                                          es->id,
6852                                                          interface_info,
6853                                                          interface_vtable,
6854                                                          es->context,
6855                                                          interface_user_data);
6856       CONNECTION_UNLOCK (connection);
6857     }
6858   /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6859   else if (is_property_get || is_property_set || is_property_get_all)
6860     {
6861       if (is_property_get)
6862         g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6863       else if (is_property_set)
6864         g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6865       else if (is_property_get_all)
6866         g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6867       else
6868         g_assert_not_reached ();
6869
6870       /* see if the object supports this interface at all */
6871       for (n = 0; interfaces[n] != NULL; n++)
6872         {
6873           if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6874             interface_info = interfaces[n];
6875         }
6876
6877       /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6878        * claims it won't support the interface
6879        */
6880       if (interface_info == NULL)
6881         {
6882           GDBusMessage *reply;
6883           reply = g_dbus_message_new_method_error (message,
6884                                                    "org.freedesktop.DBus.Error.InvalidArgs",
6885                                                    _("No such interface '%s'"),
6886                                                    interface_name);
6887           g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6888           g_object_unref (reply);
6889           handled = TRUE;
6890           goto out;
6891         }
6892
6893       /* figure out where to dispatch the property get/set/getall calls */
6894       interface_user_data = NULL;
6895       interface_vtable = es->vtable->dispatch (es->connection,
6896                                                sender,
6897                                                es->object_path,
6898                                                interface_name,
6899                                                requested_node,
6900                                                &interface_user_data,
6901                                                es->user_data);
6902       if (interface_vtable == NULL)
6903         {
6904           g_warning ("The subtree introspection function indicates that '%s' "
6905                      "is a valid interface name, but calling the dispatch "
6906                      "function on that interface gave us NULL", interface_name);
6907           goto out;
6908         }
6909
6910       if (is_property_get || is_property_set)
6911         {
6912           CONNECTION_LOCK (connection);
6913           handled = validate_and_maybe_schedule_property_getset (es->connection,
6914                                                                  message,
6915                                                                  0,
6916                                                                  es->id,
6917                                                                  is_property_get,
6918                                                                  interface_info,
6919                                                                  interface_vtable,
6920                                                                  es->context,
6921                                                                  interface_user_data);
6922           CONNECTION_UNLOCK (connection);
6923         }
6924       else if (is_property_get_all)
6925         {
6926           CONNECTION_LOCK (connection);
6927           handled = validate_and_maybe_schedule_property_get_all (es->connection,
6928                                                                   message,
6929                                                                   0,
6930                                                                   es->id,
6931                                                                   interface_info,
6932                                                                   interface_vtable,
6933                                                                   es->context,
6934                                                                   interface_user_data);
6935           CONNECTION_UNLOCK (connection);
6936         }
6937     }
6938
6939  out:
6940   if (interfaces != NULL)
6941     {
6942       for (n = 0; interfaces[n] != NULL; n++)
6943         g_dbus_interface_info_unref (interfaces[n]);
6944       g_free (interfaces);
6945     }
6946
6947   return handled;
6948 }
6949
6950 typedef struct
6951 {
6952   GDBusMessage *message;
6953   ExportedSubtree *es;
6954 } SubtreeDeferredData;
6955
6956 static void
6957 subtree_deferred_data_free (SubtreeDeferredData *data)
6958 {
6959   g_object_unref (data->message);
6960   g_free (data);
6961 }
6962
6963 /* called without lock held in the thread where the caller registered the subtree */
6964 static gboolean
6965 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6966 {
6967   SubtreeDeferredData *data = _data;
6968   gboolean handled;
6969
6970   handled = FALSE;
6971
6972   if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6973       g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6974       g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6975     handled = handle_subtree_introspect (data->es->connection,
6976                                          data->es,
6977                                          data->message);
6978   else
6979     handled = handle_subtree_method_invocation (data->es->connection,
6980                                                 data->es,
6981                                                 data->message);
6982
6983   if (!handled)
6984     {
6985       CONNECTION_LOCK (data->es->connection);
6986       handled = handle_generic_unlocked (data->es->connection, data->message);
6987       CONNECTION_UNLOCK (data->es->connection);
6988     }
6989
6990   /* if we couldn't handle the request, just bail with the UnknownMethod error */
6991   if (!handled)
6992     {
6993       GDBusMessage *reply;
6994       reply = g_dbus_message_new_method_error (data->message,
6995                                                "org.freedesktop.DBus.Error.UnknownMethod",
6996                                                _("Method '%s' on interface '%s' with signature '%s' does not exist"),
6997                                                g_dbus_message_get_member (data->message),
6998                                                g_dbus_message_get_interface (data->message),
6999                                                g_dbus_message_get_signature (data->message));
7000       g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7001       g_object_unref (reply);
7002     }
7003
7004   return FALSE;
7005 }
7006
7007 /* called in GDBusWorker thread with connection's lock held */
7008 static gboolean
7009 subtree_message_func (GDBusConnection *connection,
7010                       ExportedSubtree *es,
7011                       GDBusMessage    *message)
7012 {
7013   GSource *idle_source;
7014   SubtreeDeferredData *data;
7015
7016   data = g_new0 (SubtreeDeferredData, 1);
7017   data->message = g_object_ref (message);
7018   data->es = es;
7019
7020   /* defer this call to an idle handler in the right thread */
7021   idle_source = g_idle_source_new ();
7022   g_source_set_priority (idle_source, G_PRIORITY_HIGH);
7023   g_source_set_callback (idle_source,
7024                          process_subtree_vtable_message_in_idle_cb,
7025                          data,
7026                          (GDestroyNotify) subtree_deferred_data_free);
7027   g_source_set_name (idle_source, "[gio] process_subtree_vtable_message_in_idle_cb");
7028   g_source_attach (idle_source, es->context);
7029   g_source_unref (idle_source);
7030
7031   /* since we own the entire subtree, handlers for objects not in the subtree have been
7032    * tried already by libdbus-1 - so we just need to ensure that we're always going
7033    * to reply to the message
7034    */
7035   return TRUE;
7036 }
7037
7038 /**
7039  * g_dbus_connection_register_subtree:
7040  * @connection: a #GDBusConnection
7041  * @object_path: the object path to register the subtree at
7042  * @vtable: a #GDBusSubtreeVTable to enumerate, introspect and
7043  *     dispatch nodes in the subtree
7044  * @flags: flags used to fine tune the behavior of the subtree
7045  * @user_data: data to pass to functions in @vtable
7046  * @user_data_free_func: function to call when the subtree is unregistered
7047  * @error: return location for error or %NULL
7048  *
7049  * Registers a whole subtree of dynamic objects.
7050  *
7051  * The @enumerate and @introspection functions in @vtable are used to
7052  * convey, to remote callers, what nodes exist in the subtree rooted
7053  * by @object_path.
7054  *
7055  * When handling remote calls into any node in the subtree, first the
7056  * @enumerate function is used to check if the node exists. If the node exists
7057  * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
7058  * the @introspection function is used to check if the node supports the
7059  * requested method. If so, the @dispatch function is used to determine
7060  * where to dispatch the call. The collected #GDBusInterfaceVTable and
7061  * #gpointer will be used to call into the interface vtable for processing
7062  * the request.
7063  *
7064  * All calls into user-provided code will be invoked in the
7065  * [thread-default main context][g-main-context-push-thread-default]
7066  * of the thread you are calling this method from.
7067  *
7068  * If an existing subtree is already registered at @object_path or
7069  * then @error is set to #G_IO_ERROR_EXISTS.
7070  *
7071  * Note that it is valid to register regular objects (using
7072  * g_dbus_connection_register_object()) in a subtree registered with
7073  * g_dbus_connection_register_subtree() - if so, the subtree handler
7074  * is tried as the last resort. One way to think about a subtree
7075  * handler is to consider it a fallback handler for object paths not
7076  * registered via g_dbus_connection_register_object() or other bindings.
7077  *
7078  * Note that @vtable will be copied so you cannot change it after
7079  * registration.
7080  *
7081  * See this [server][gdbus-subtree-server] for an example of how to use
7082  * this method.
7083  *
7084  * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
7085  * that can be used with g_dbus_connection_unregister_subtree() .
7086  *
7087  * Since: 2.26
7088  */
7089 guint
7090 g_dbus_connection_register_subtree (GDBusConnection           *connection,
7091                                     const gchar               *object_path,
7092                                     const GDBusSubtreeVTable  *vtable,
7093                                     GDBusSubtreeFlags          flags,
7094                                     gpointer                   user_data,
7095                                     GDestroyNotify             user_data_free_func,
7096                                     GError                   **error)
7097 {
7098   guint ret;
7099   ExportedSubtree *es;
7100
7101   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
7102   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
7103   g_return_val_if_fail (vtable != NULL, 0);
7104   g_return_val_if_fail (error == NULL || *error == NULL, 0);
7105   g_return_val_if_fail (check_initialized (connection), 0);
7106
7107   ret = 0;
7108
7109   CONNECTION_LOCK (connection);
7110
7111   es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
7112   if (es != NULL)
7113     {
7114       g_set_error (error,
7115                    G_IO_ERROR,
7116                    G_IO_ERROR_EXISTS,
7117                    _("A subtree is already exported for %s"),
7118                    object_path);
7119       goto out;
7120     }
7121
7122   es = g_new0 (ExportedSubtree, 1);
7123   es->object_path = g_strdup (object_path);
7124   es->connection = connection;
7125
7126   es->vtable = _g_dbus_subtree_vtable_copy (vtable);
7127   es->flags = flags;
7128   es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
7129   es->user_data = user_data;
7130   es->user_data_free_func = user_data_free_func;
7131   es->context = g_main_context_ref_thread_default ();
7132
7133   g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
7134   g_hash_table_insert (connection->map_id_to_es,
7135                        GUINT_TO_POINTER (es->id),
7136                        es);
7137
7138   ret = es->id;
7139
7140  out:
7141   CONNECTION_UNLOCK (connection);
7142
7143   return ret;
7144 }
7145
7146 /* ---------------------------------------------------------------------------------------------------- */
7147
7148 /**
7149  * g_dbus_connection_unregister_subtree:
7150  * @connection: a #GDBusConnection
7151  * @registration_id: a subtree registration id obtained from
7152  *     g_dbus_connection_register_subtree()
7153  *
7154  * Unregisters a subtree.
7155  *
7156  * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise
7157  *
7158  * Since: 2.26
7159  */
7160 gboolean
7161 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
7162                                       guint            registration_id)
7163 {
7164   ExportedSubtree *es;
7165   gboolean ret;
7166
7167   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
7168   g_return_val_if_fail (check_initialized (connection), FALSE);
7169
7170   ret = FALSE;
7171
7172   CONNECTION_LOCK (connection);
7173
7174   es = g_hash_table_lookup (connection->map_id_to_es,
7175                             GUINT_TO_POINTER (registration_id));
7176   if (es == NULL)
7177     goto out;
7178
7179   g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
7180   g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
7181
7182   ret = TRUE;
7183
7184  out:
7185   CONNECTION_UNLOCK (connection);
7186
7187   return ret;
7188 }
7189
7190 /* ---------------------------------------------------------------------------------------------------- */
7191
7192 /* may be called in any thread, with connection's lock held */
7193 static void
7194 handle_generic_ping_unlocked (GDBusConnection *connection,
7195                               const gchar     *object_path,
7196                               GDBusMessage    *message)
7197 {
7198   GDBusMessage *reply;
7199   reply = g_dbus_message_new_method_reply (message);
7200   g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7201   g_object_unref (reply);
7202 }
7203
7204 /* may be called in any thread, with connection's lock held */
7205 static void
7206 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
7207                                         const gchar     *object_path,
7208                                         GDBusMessage    *message)
7209 {
7210   GDBusMessage *reply;
7211
7212   reply = NULL;
7213   if (connection->machine_id == NULL)
7214     {
7215       GError *error;
7216
7217       error = NULL;
7218       connection->machine_id = _g_dbus_get_machine_id (&error);
7219       if (connection->machine_id == NULL)
7220         {
7221           reply = g_dbus_message_new_method_error_literal (message,
7222                                                            "org.freedesktop.DBus.Error.Failed",
7223                                                            error->message);
7224           g_error_free (error);
7225         }
7226     }
7227
7228   if (reply == NULL)
7229     {
7230       reply = g_dbus_message_new_method_reply (message);
7231       g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
7232     }
7233   g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7234   g_object_unref (reply);
7235 }
7236
7237 /* may be called in any thread, with connection's lock held */
7238 static void
7239 handle_generic_introspect_unlocked (GDBusConnection *connection,
7240                                     const gchar     *object_path,
7241                                     GDBusMessage    *message)
7242 {
7243   guint n;
7244   GString *s;
7245   gchar **registered;
7246   GDBusMessage *reply;
7247
7248   /* first the header */
7249   s = g_string_new (NULL);
7250   introspect_append_header (s);
7251
7252   registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
7253   for (n = 0; registered != NULL && registered[n] != NULL; n++)
7254       g_string_append_printf (s, "  <node name=\"%s\"/>\n", registered[n]);
7255   g_strfreev (registered);
7256   g_string_append (s, "</node>\n");
7257
7258   reply = g_dbus_message_new_method_reply (message);
7259   g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
7260   g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7261   g_object_unref (reply);
7262   g_string_free (s, TRUE);
7263 }
7264
7265 /* may be called in any thread, with connection's lock held */
7266 static gboolean
7267 handle_generic_unlocked (GDBusConnection *connection,
7268                          GDBusMessage    *message)
7269 {
7270   gboolean handled;
7271   const gchar *interface_name;
7272   const gchar *member;
7273   const gchar *signature;
7274   const gchar *path;
7275
7276   CONNECTION_ENSURE_LOCK (connection);
7277
7278   handled = FALSE;
7279
7280   interface_name = g_dbus_message_get_interface (message);
7281   member = g_dbus_message_get_member (message);
7282   signature = g_dbus_message_get_signature (message);
7283   path = g_dbus_message_get_path (message);
7284
7285   if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
7286       g_strcmp0 (member, "Introspect") == 0 &&
7287       g_strcmp0 (signature, "") == 0)
7288     {
7289       handle_generic_introspect_unlocked (connection, path, message);
7290       handled = TRUE;
7291     }
7292   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7293            g_strcmp0 (member, "Ping") == 0 &&
7294            g_strcmp0 (signature, "") == 0)
7295     {
7296       handle_generic_ping_unlocked (connection, path, message);
7297       handled = TRUE;
7298     }
7299   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7300            g_strcmp0 (member, "GetMachineId") == 0 &&
7301            g_strcmp0 (signature, "") == 0)
7302     {
7303       handle_generic_get_machine_id_unlocked (connection, path, message);
7304       handled = TRUE;
7305     }
7306
7307   return handled;
7308 }
7309
7310 /* ---------------------------------------------------------------------------------------------------- */
7311
7312 /* called in GDBusWorker thread with connection's lock held */
7313 static void
7314 distribute_method_call (GDBusConnection *connection,
7315                         GDBusMessage    *message)
7316 {
7317   GDBusMessage *reply;
7318   ExportedObject *eo;
7319   ExportedSubtree *es;
7320   const gchar *object_path;
7321   const gchar *interface_name;
7322   const gchar *member;
7323   const gchar *path;
7324   gchar *subtree_path;
7325   gchar *needle;
7326
7327   g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
7328
7329   interface_name = g_dbus_message_get_interface (message);
7330   member = g_dbus_message_get_member (message);
7331   path = g_dbus_message_get_path (message);
7332   subtree_path = g_strdup (path);
7333   needle = strrchr (subtree_path, '/');
7334   if (needle != NULL && needle != subtree_path)
7335     {
7336       *needle = '\0';
7337     }
7338   else
7339     {
7340       g_free (subtree_path);
7341       subtree_path = NULL;
7342     }
7343
7344
7345   if (G_UNLIKELY (_g_dbus_debug_incoming ()))
7346     {
7347       _g_dbus_debug_print_lock ();
7348       g_print ("========================================================================\n"
7349                "GDBus-debug:Incoming:\n"
7350                " <<<< METHOD INVOCATION %s.%s()\n"
7351                "      on object %s\n"
7352                "      invoked by name %s\n"
7353                "      serial %d\n",
7354                interface_name, member,
7355                path,
7356                g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
7357                g_dbus_message_get_serial (message));
7358       _g_dbus_debug_print_unlock ();
7359     }
7360
7361   object_path = g_dbus_message_get_path (message);
7362   g_assert (object_path != NULL);
7363
7364   eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
7365   if (eo != NULL)
7366     {
7367       if (obj_message_func (connection, eo, message))
7368         goto out;
7369     }
7370
7371   es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
7372   if (es != NULL)
7373     {
7374       if (subtree_message_func (connection, es, message))
7375         goto out;
7376     }
7377
7378   if (subtree_path != NULL)
7379     {
7380       es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
7381       if (es != NULL)
7382         {
7383           if (subtree_message_func (connection, es, message))
7384             goto out;
7385         }
7386     }
7387
7388   if (handle_generic_unlocked (connection, message))
7389     goto out;
7390
7391   /* if we end up here, the message has not been not handled - so return an error saying this */
7392   reply = g_dbus_message_new_method_error (message,
7393                                            "org.freedesktop.DBus.Error.UnknownMethod",
7394                                            _("No such interface '%s' on object at path %s"),
7395                                            interface_name,
7396                                            object_path);
7397   g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7398   g_object_unref (reply);
7399
7400  out:
7401   g_free (subtree_path);
7402 }
7403
7404 /* ---------------------------------------------------------------------------------------------------- */
7405
7406 /* Called in any user thread, with the message_bus_lock held. */
7407 static GWeakRef *
7408 message_bus_get_singleton (GBusType   bus_type,
7409                            GError   **error)
7410 {
7411   GWeakRef *ret;
7412   const gchar *starter_bus;
7413
7414   ret = NULL;
7415
7416   switch (bus_type)
7417     {
7418     case G_BUS_TYPE_SESSION:
7419       ret = &the_session_bus;
7420       break;
7421
7422     case G_BUS_TYPE_SYSTEM:
7423       ret = &the_system_bus;
7424       break;
7425
7426     case G_BUS_TYPE_USER:
7427       ret = &the_user_bus;
7428       break;
7429
7430     case G_BUS_TYPE_MACHINE:
7431       ret = &the_machine_bus;
7432       break;
7433
7434     case G_BUS_TYPE_STARTER:
7435       starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
7436       if (g_strcmp0 (starter_bus, "session") == 0)
7437         {
7438           ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
7439           goto out;
7440         }
7441       else if (g_strcmp0 (starter_bus, "system") == 0)
7442         {
7443           ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
7444           goto out;
7445         }
7446       else
7447         {
7448           if (starter_bus != NULL)
7449             {
7450               g_set_error (error,
7451                            G_IO_ERROR,
7452                            G_IO_ERROR_INVALID_ARGUMENT,
7453                            _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
7454                              " - unknown value '%s'"),
7455                            starter_bus);
7456             }
7457           else
7458             {
7459               g_set_error_literal (error,
7460                                    G_IO_ERROR,
7461                                    G_IO_ERROR_INVALID_ARGUMENT,
7462                                    _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
7463                                      "variable is not set"));
7464             }
7465         }
7466       break;
7467
7468     default:
7469       g_assert_not_reached ();
7470       break;
7471     }
7472
7473  out:
7474   return ret;
7475 }
7476
7477 /* Called in any user thread, without holding locks. */
7478 static GDBusConnection *
7479 get_uninitialized_connection (GBusType       bus_type,
7480                               GCancellable  *cancellable,
7481                               GError       **error)
7482 {
7483   GWeakRef *singleton;
7484   GDBusConnection *ret;
7485
7486   ret = NULL;
7487
7488   G_LOCK (message_bus_lock);
7489   singleton = message_bus_get_singleton (bus_type, error);
7490   if (singleton == NULL)
7491     goto out;
7492
7493   ret = g_weak_ref_get (singleton);
7494
7495   if (ret == NULL)
7496     {
7497       gchar *address;
7498       address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
7499       if (address == NULL)
7500         goto out;
7501       ret = g_object_new (G_TYPE_DBUS_CONNECTION,
7502                           "address", address,
7503                           "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
7504                                    G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
7505                           "exit-on-close", TRUE,
7506                           NULL);
7507
7508       g_weak_ref_set (singleton, ret);
7509       g_free (address);
7510     }
7511
7512   g_assert (ret != NULL);
7513
7514  out:
7515   G_UNLOCK (message_bus_lock);
7516   return ret;
7517 }
7518
7519 /* May be called from any thread. Must not hold message_bus_lock. */
7520 GDBusConnection *
7521 _g_bus_get_singleton_if_exists (GBusType bus_type)
7522 {
7523   GWeakRef *singleton;
7524   GDBusConnection *ret = NULL;
7525
7526   G_LOCK (message_bus_lock);
7527   singleton = message_bus_get_singleton (bus_type, NULL);
7528   if (singleton == NULL)
7529     goto out;
7530
7531   ret = g_weak_ref_get (singleton);
7532
7533  out:
7534   G_UNLOCK (message_bus_lock);
7535   return ret;
7536 }
7537
7538 /**
7539  * g_bus_get_sync:
7540  * @bus_type: a #GBusType
7541  * @cancellable: (allow-none): a #GCancellable or %NULL
7542  * @error: return location for error or %NULL
7543  *
7544  * Synchronously connects to the message bus specified by @bus_type.
7545  * Note that the returned object may shared with other callers,
7546  * e.g. if two separate parts of a process calls this function with
7547  * the same @bus_type, they will share the same object.
7548  *
7549  * This is a synchronous failable function. See g_bus_get() and
7550  * g_bus_get_finish() for the asynchronous version.
7551  *
7552  * The returned object is a singleton, that is, shared with other
7553  * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7554  * event that you need a private message bus connection, use
7555  * g_dbus_address_get_for_bus_sync() and
7556  * g_dbus_connection_new_for_address().
7557  *
7558  * Note that the returned #GDBusConnection object will (usually) have
7559  * the #GDBusConnection:exit-on-close property set to %TRUE.
7560  *
7561  * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7562  *     Free with g_object_unref().
7563  *
7564  * Since: 2.26
7565  */
7566 GDBusConnection *
7567 g_bus_get_sync (GBusType       bus_type,
7568                 GCancellable  *cancellable,
7569                 GError       **error)
7570 {
7571   GDBusConnection *connection;
7572
7573   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7574
7575   connection = get_uninitialized_connection (bus_type, cancellable, error);
7576   if (connection == NULL)
7577     goto out;
7578
7579   if (!g_initable_init (G_INITABLE (connection), cancellable, error))
7580     {
7581       g_object_unref (connection);
7582       connection = NULL;
7583     }
7584
7585  out:
7586   return connection;
7587 }
7588
7589 static void
7590 bus_get_async_initable_cb (GObject      *source_object,
7591                            GAsyncResult *res,
7592                            gpointer      user_data)
7593 {
7594   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
7595   GError *error;
7596
7597   error = NULL;
7598   if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
7599                                      res,
7600                                      &error))
7601     {
7602       g_assert (error != NULL);
7603       g_simple_async_result_take_error (simple, error);
7604       g_object_unref (source_object);
7605     }
7606   else
7607     {
7608       g_simple_async_result_set_op_res_gpointer (simple,
7609                                                  source_object,
7610                                                  g_object_unref);
7611     }
7612   g_simple_async_result_complete_in_idle (simple);
7613   g_object_unref (simple);
7614 }
7615
7616 /**
7617  * g_bus_get:
7618  * @bus_type: a #GBusType
7619  * @cancellable: (allow-none): a #GCancellable or %NULL
7620  * @callback: a #GAsyncReadyCallback to call when the request is satisfied
7621  * @user_data: the data to pass to @callback
7622  *
7623  * Asynchronously connects to the message bus specified by @bus_type.
7624  *
7625  * When the operation is finished, @callback will be invoked. You can
7626  * then call g_bus_get_finish() to get the result of the operation.
7627  *
7628  * This is a asynchronous failable function. See g_bus_get_sync() for
7629  * the synchronous version.
7630  *
7631  * Since: 2.26
7632  */
7633 void
7634 g_bus_get (GBusType             bus_type,
7635            GCancellable        *cancellable,
7636            GAsyncReadyCallback  callback,
7637            gpointer             user_data)
7638 {
7639   GDBusConnection *connection;
7640   GSimpleAsyncResult *simple;
7641   GError *error;
7642
7643   simple = g_simple_async_result_new (NULL,
7644                                       callback,
7645                                       user_data,
7646                                       g_bus_get);
7647   g_simple_async_result_set_check_cancellable (simple, cancellable);
7648
7649   error = NULL;
7650   connection = get_uninitialized_connection (bus_type, cancellable, &error);
7651   if (connection == NULL)
7652     {
7653       g_assert (error != NULL);
7654       g_simple_async_result_take_error (simple, error);
7655       g_simple_async_result_complete_in_idle (simple);
7656       g_object_unref (simple);
7657     }
7658   else
7659     {
7660       g_async_initable_init_async (G_ASYNC_INITABLE (connection),
7661                                    G_PRIORITY_DEFAULT,
7662                                    cancellable,
7663                                    bus_get_async_initable_cb,
7664                                    simple);
7665     }
7666 }
7667
7668 /**
7669  * g_bus_get_finish:
7670  * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
7671  *     to g_bus_get()
7672  * @error: return location for error or %NULL
7673  *
7674  * Finishes an operation started with g_bus_get().
7675  *
7676  * The returned object is a singleton, that is, shared with other
7677  * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7678  * event that you need a private message bus connection, use
7679  * g_dbus_address_get_for_bus_sync() and
7680  * g_dbus_connection_new_for_address().
7681  *
7682  * Note that the returned #GDBusConnection object will (usually) have
7683  * the #GDBusConnection:exit-on-close property set to %TRUE.
7684  *
7685  * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7686  *     Free with g_object_unref().
7687  *
7688  * Since: 2.26
7689  */
7690 GDBusConnection *
7691 g_bus_get_finish (GAsyncResult  *res,
7692                   GError       **error)
7693 {
7694   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
7695   GObject *object;
7696   GDBusConnection *ret;
7697
7698   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7699
7700   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
7701
7702   ret = NULL;
7703
7704   if (g_simple_async_result_propagate_error (simple, error))
7705     goto out;
7706
7707   object = g_simple_async_result_get_op_res_gpointer (simple);
7708   g_assert (object != NULL);
7709   ret = g_object_ref (G_DBUS_CONNECTION (object));
7710
7711  out:
7712   return ret;
7713 }
7714
7715 /* ---------------------------------------------------------------------------------------------------- */