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