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