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