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