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