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