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