GDBus: Use call() instead of invoke_method()
[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, write to the
17  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18  * Boston, MA 02111-1307, USA.
19  *
20  * Author: David Zeuthen <davidz@redhat.com>
21  */
22
23 /*
24  * TODO for GDBus:
25  *
26  * - would be nice to expose GDBusAuthMechanism and an extension point
27  *
28  * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
29  *   the mechanism VFuncs need to be able to set an error.
30  *
31  * - The GDBusProxy::g-properties-changed signal currently looks like this
32  *
33  *      void user_function (GDBusProxy *proxy,
34  *                          GHashTable *changed_properties,
35  *                          gpointer    user_data);
36  *
37  *   which is problematic because some people frown upon GHashTable
38  *   usage in public API (in particular some of the JS people). Maybe we
39  *   need to rework it, maybe it doesn't matter since GDBusProxy is
40  *   a low-level API and, for C code, we expect code generators to
41  *   spit out subclasses that automatically hook up to this signal
42  *   and does g_object_notify() anyway? Hmm...
43  *
44  * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
45  *   to specify where the nonce is stored. This will allow people to use
46  *   G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
47  *   to easily acheive secure RPC via nonce-tcp.
48  *
49  * - need to expose an extension point for resolving D-Bus address and
50  *   turning them into GIOStream objects. This will allow us to implement
51  *   e.g. X11 D-Bus transports without dlopen()'ing or linking against
52  *   libX11 from libgio.
53  *   - see g_dbus_address_connect() in gdbusaddress.c
54  *
55  * - would be cute to use kernel-specific APIs to resolve fds for
56  *   debug output when using G_DBUS_DEBUG=messages, e.g. in addition to
57  *
58  *     fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
59  *
60  *   maybe we can show more information about what fd 21 really is.
61  *   Ryan suggests looking in /proc/self/fd for clues / symlinks!
62  *   Initial experiments on Linux 2.6 suggests that the symlink looks
63  *   like this:
64  *
65  *    3 -> /proc/18068/fd
66  *
67  *   e.g. not of much use.
68  */
69
70 #include "config.h"
71
72 #include <stdlib.h>
73 #include <string.h>
74
75 #include "gdbusauth.h"
76 #include "gdbusutils.h"
77 #include "gdbusaddress.h"
78 #include "gdbusmessage.h"
79 #include "gdbusconnection.h"
80 #include "gdbuserror.h"
81 #include "gioenumtypes.h"
82 #include "gdbusintrospection.h"
83 #include "gdbusmethodinvocation.h"
84 #include "gdbusprivate.h"
85 #include "gdbusauthobserver.h"
86 #include "gio-marshal.h"
87 #include "ginitable.h"
88 #include "gasyncinitable.h"
89 #include "giostream.h"
90 #include "gasyncresult.h"
91 #include "gsimpleasyncresult.h"
92
93 #ifdef G_OS_UNIX
94 #include <gio/gunixconnection.h>
95 #include <gio/gunixfdmessage.h>
96 #include <unistd.h>
97 #include <sys/types.h>
98 #endif
99
100 #include "glibintl.h"
101 #include "gioalias.h"
102
103 /**
104  * SECTION:gdbusconnection
105  * @short_description: D-Bus Connections
106  * @include: gio/gio.h
107  *
108  * The #GDBusConnection type is used for D-Bus connections to remote
109  * peers such as a message buses. It is a low-level API that offers a
110  * lot of flexibility. For instance, it lets you establish a connection
111  * over any transport that can by represented as an #GIOStream.
112  *
113  * This class is rarely used directly in D-Bus clients. If you are writing
114  * an D-Bus client, it is often easier to use the g_bus_own_name(),
115  * g_bus_watch_name() or g_bus_watch_proxy() APIs.
116  *
117  * <example id="gdbus-server"><title>D-Bus server example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-server.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
118  *
119  * <example id="gdbus-subtree-server"><title>D-Bus subtree example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-subtree.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
120  *
121  * <example id="gdbus-unix-fd-client"><title>D-Bus UNIX File Descriptor example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-unix-fd-client.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
122  */
123
124 /* ---------------------------------------------------------------------------------------------------- */
125
126 G_LOCK_DEFINE_STATIC (message_bus_lock);
127
128 static GDBusConnection *the_session_bus = NULL;
129 static GDBusConnection *the_system_bus = NULL;
130
131 /* ---------------------------------------------------------------------------------------------------- */
132
133 static gboolean
134 _g_strv_has_string (const gchar* const *haystack,
135                     const gchar        *needle)
136 {
137   guint n;
138
139   for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
140     {
141       if (g_strcmp0 (haystack[n], needle) == 0)
142         return TRUE;
143     }
144   return FALSE;
145 }
146
147 /* ---------------------------------------------------------------------------------------------------- */
148
149 #ifdef G_OS_WIN32
150 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
151 #else
152 // TODO: for some reason this doesn't work on Windows
153 #define CONNECTION_ENSURE_LOCK(obj) do {                                \
154     if (G_UNLIKELY (g_mutex_trylock((obj)->priv->lock)))                \
155       {                                                                 \
156         g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
157                              "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
158       }                                                                 \
159   } while (FALSE)
160 #endif
161
162 #define CONNECTION_LOCK(obj) do {                                       \
163     g_mutex_lock ((obj)->priv->lock);                                   \
164   } while (FALSE)
165
166 #define CONNECTION_UNLOCK(obj) do {                                     \
167     g_mutex_unlock ((obj)->priv->lock);                                 \
168   } while (FALSE)
169
170 struct _GDBusConnectionPrivate
171 {
172   /* ------------------------------------------------------------------------ */
173   /* -- General object state ------------------------------------------------ */
174   /* ------------------------------------------------------------------------ */
175
176   /* object-wide lock */
177   GMutex *lock;
178
179   /* A lock used in the init() method of the GInitable interface - see comments
180    * in initable_init() for why a separate lock is needed
181    */
182   GMutex *init_lock;
183
184   /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
185    * someone calls org.freedesktop.DBus.GetMachineId()
186    */
187   gchar *machine_id;
188
189   /* The underlying stream used for communication */
190   GIOStream *stream;
191
192   /* The object used for authentication (if any) */
193   GDBusAuth *auth;
194
195   /* Set to TRUE if the connection has been closed */
196   gboolean closed;
197
198   /* Last serial used */
199   guint32 last_serial;
200
201   /* The object used to send/receive message */
202   GDBusWorker *worker;
203
204   /* If connected to a message bus, this contains the unique name assigned to
205    * us by the bus (e.g. ":1.42")
206    */
207   gchar *bus_unique_name;
208
209   /* The GUID returned by the other side if we authenticed as a client or
210    * the GUID to use if authenticating as a server
211    */
212   gchar *guid;
213
214   /* set to TRUE exactly when initable_init() has finished running */
215   gboolean is_initialized;
216
217   /* If the connection could not be established during initable_init(), this GError will set */
218   GError *initialization_error;
219
220   /* The result of g_main_context_get_thread_default() when the object
221    * was created (the GObject _init() function) - this is used for delivery
222    * of the :closed GObject signal.
223    */
224   GMainContext *main_context_at_construction;
225
226   /* construct properties */
227   gchar *address;
228   GDBusConnectionFlags flags;
229
230   /* Map used for managing method replies */
231   GHashTable *map_method_serial_to_send_message_data;  /* guint32 -> SendMessageData* */
232
233   /* Maps used for managing signal subscription */
234   GHashTable *map_rule_to_signal_data;          /* gchar* -> SignalData */
235   GHashTable *map_id_to_signal_data;            /* guint  -> SignalData */
236   GHashTable *map_sender_to_signal_data_array;  /* gchar* -> GPtrArray* of SignalData */
237
238   /* Maps used for managing exported objects and subtrees */
239   GHashTable *map_object_path_to_eo;  /* gchar* -> ExportedObject* */
240   GHashTable *map_id_to_ei;           /* guint  -> ExportedInterface* */
241   GHashTable *map_object_path_to_es;  /* gchar* -> ExportedSubtree* */
242   GHashTable *map_id_to_es;           /* guint  -> ExportedSubtree* */
243
244   /* Structure used for message filters */
245   GPtrArray *filters;
246
247   /* Whether to exit on close */
248   gboolean exit_on_close;
249
250   /* Capabilities negotiated during authentication */
251   GDBusCapabilityFlags capabilities;
252
253   GDBusAuthObserver *authentication_observer;
254   GCredentials *crendentials;
255 };
256
257 typedef struct ExportedObject ExportedObject;
258 static void exported_object_free (ExportedObject *eo);
259
260 typedef struct ExportedSubtree ExportedSubtree;
261 static void exported_subtree_free (ExportedSubtree *es);
262
263 enum
264 {
265   CLOSED_SIGNAL,
266   LAST_SIGNAL,
267 };
268
269 enum
270 {
271   PROP_0,
272   PROP_STREAM,
273   PROP_ADDRESS,
274   PROP_FLAGS,
275   PROP_GUID,
276   PROP_UNIQUE_NAME,
277   PROP_CLOSED,
278   PROP_EXIT_ON_CLOSE,
279   PROP_CAPABILITY_FLAGS,
280   PROP_AUTHENTICATION_OBSERVER,
281 };
282
283 static void distribute_signals (GDBusConnection  *connection,
284                                 GDBusMessage     *message);
285
286 static void distribute_method_call (GDBusConnection  *connection,
287                                     GDBusMessage     *message);
288
289 static gboolean handle_generic_unlocked (GDBusConnection *connection,
290                                          GDBusMessage    *message);
291
292
293 static void purge_all_signal_subscriptions (GDBusConnection *connection);
294 static void purge_all_filters (GDBusConnection *connection);
295
296 #define _G_ENSURE_LOCK(name) do {                                       \
297     if (G_UNLIKELY (G_TRYLOCK(name)))                                   \
298       {                                                                 \
299         g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
300                              "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
301       }                                                                 \
302   } while (FALSE)                                                       \
303
304 static guint signals[LAST_SIGNAL] = { 0 };
305
306 static void initable_iface_init       (GInitableIface      *initable_iface);
307 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
308
309 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
310                          G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
311                          G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
312                          );
313
314 static void
315 g_dbus_connection_dispose (GObject *object)
316 {
317   GDBusConnection *connection = G_DBUS_CONNECTION (object);
318
319   G_LOCK (message_bus_lock);
320   //g_debug ("disposing %p", connection);
321   if (connection == the_session_bus)
322     {
323       the_session_bus = NULL;
324     }
325   else if (connection == the_system_bus)
326     {
327       the_system_bus = NULL;
328     }
329   if (connection->priv->worker != NULL)
330     {
331       _g_dbus_worker_stop (connection->priv->worker);
332       connection->priv->worker = NULL;
333     }
334   G_UNLOCK (message_bus_lock);
335
336   if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
337     G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
338 }
339
340 static void
341 g_dbus_connection_finalize (GObject *object)
342 {
343   GDBusConnection *connection = G_DBUS_CONNECTION (object);
344
345   if (connection->priv->authentication_observer != NULL)
346     g_object_unref (connection->priv->authentication_observer);
347
348   if (connection->priv->auth != NULL)
349     g_object_unref (connection->priv->auth);
350
351   //g_debug ("finalizing %p", connection);
352   if (connection->priv->stream != NULL)
353     {
354       /* We don't really care if closing the stream succeeds or not */
355       g_io_stream_close_async (connection->priv->stream,
356                                G_PRIORITY_DEFAULT,
357                                NULL,  /* GCancellable */
358                                NULL,  /* GAsyncReadyCallback */
359                                NULL); /* userdata */
360       g_object_unref (connection->priv->stream);
361       connection->priv->stream = NULL;
362     }
363
364   g_free (connection->priv->address);
365
366   g_free (connection->priv->guid);
367   g_free (connection->priv->bus_unique_name);
368
369   if (connection->priv->initialization_error != NULL)
370     g_error_free (connection->priv->initialization_error);
371
372   g_hash_table_unref (connection->priv->map_method_serial_to_send_message_data);
373
374   purge_all_signal_subscriptions (connection);
375   g_hash_table_unref (connection->priv->map_rule_to_signal_data);
376   g_hash_table_unref (connection->priv->map_id_to_signal_data);
377   g_hash_table_unref (connection->priv->map_sender_to_signal_data_array);
378
379   g_hash_table_unref (connection->priv->map_id_to_ei);
380   g_hash_table_unref (connection->priv->map_object_path_to_eo);
381   g_hash_table_unref (connection->priv->map_id_to_es);
382   g_hash_table_unref (connection->priv->map_object_path_to_es);
383
384   purge_all_filters (connection);
385   g_ptr_array_unref (connection->priv->filters);
386
387   if (connection->priv->main_context_at_construction != NULL)
388     g_main_context_unref (connection->priv->main_context_at_construction);
389
390   g_free (connection->priv->machine_id);
391
392   g_mutex_free (connection->priv->init_lock);
393   g_mutex_free (connection->priv->lock);
394
395   G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
396 }
397
398 static void
399 g_dbus_connection_get_property (GObject    *object,
400                                 guint       prop_id,
401                                 GValue     *value,
402                                 GParamSpec *pspec)
403 {
404   GDBusConnection *connection = G_DBUS_CONNECTION (object);
405
406   switch (prop_id)
407     {
408     case PROP_STREAM:
409       g_value_set_object (value, g_dbus_connection_get_stream (connection));
410       break;
411
412     case PROP_GUID:
413       g_value_set_string (value, g_dbus_connection_get_guid (connection));
414       break;
415
416     case PROP_UNIQUE_NAME:
417       g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
418       break;
419
420     case PROP_CLOSED:
421       g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
422       break;
423
424     case PROP_EXIT_ON_CLOSE:
425       g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
426       break;
427
428     case PROP_CAPABILITY_FLAGS:
429       g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
430       break;
431
432     default:
433       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
434       break;
435     }
436 }
437
438 static void
439 g_dbus_connection_set_property (GObject      *object,
440                                 guint         prop_id,
441                                 const GValue *value,
442                                 GParamSpec   *pspec)
443 {
444   GDBusConnection *connection = G_DBUS_CONNECTION (object);
445
446   switch (prop_id)
447     {
448     case PROP_STREAM:
449       connection->priv->stream = g_value_dup_object (value);
450       break;
451
452     case PROP_GUID:
453       connection->priv->guid = g_value_dup_string (value);
454       break;
455
456     case PROP_ADDRESS:
457       connection->priv->address = g_value_dup_string (value);
458       break;
459
460     case PROP_FLAGS:
461       connection->priv->flags = g_value_get_flags (value);
462       break;
463
464     case PROP_EXIT_ON_CLOSE:
465       g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
466       break;
467
468     case PROP_AUTHENTICATION_OBSERVER:
469       connection->priv->authentication_observer = g_value_dup_object (value);
470       break;
471
472     default:
473       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
474       break;
475     }
476 }
477
478 static void
479 g_dbus_connection_real_closed (GDBusConnection *connection,
480                                gboolean         remote_peer_vanished,
481                                GError          *error)
482 {
483   if (remote_peer_vanished && connection->priv->exit_on_close)
484     {
485       g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
486       raise (SIGTERM);
487     }
488 }
489
490 static void
491 g_dbus_connection_class_init (GDBusConnectionClass *klass)
492 {
493   GObjectClass *gobject_class;
494
495   g_type_class_add_private (klass, sizeof (GDBusConnectionPrivate));
496
497   gobject_class = G_OBJECT_CLASS (klass);
498
499   gobject_class->finalize     = g_dbus_connection_finalize;
500   gobject_class->dispose      = g_dbus_connection_dispose;
501   gobject_class->set_property = g_dbus_connection_set_property;
502   gobject_class->get_property = g_dbus_connection_get_property;
503
504   klass->closed = g_dbus_connection_real_closed;
505
506   /**
507    * GDBusConnection:stream:
508    *
509    * The underlying #GIOStream used for I/O.
510    *
511    * Since: 2.26
512    */
513   g_object_class_install_property (gobject_class,
514                                    PROP_STREAM,
515                                    g_param_spec_object ("stream",
516                                                         P_("IO Stream"),
517                                                         P_("The underlying streams used for I/O"),
518                                                         G_TYPE_IO_STREAM,
519                                                         G_PARAM_READABLE |
520                                                         G_PARAM_WRITABLE |
521                                                         G_PARAM_CONSTRUCT_ONLY |
522                                                         G_PARAM_STATIC_NAME |
523                                                         G_PARAM_STATIC_BLURB |
524                                                         G_PARAM_STATIC_NICK));
525
526   /**
527    * GDBusConnection:address:
528    *
529    * A D-Bus address specifying potential endpoints that can be used
530    * when establishing the connection.
531    *
532    * Since: 2.26
533    */
534   g_object_class_install_property (gobject_class,
535                                    PROP_ADDRESS,
536                                    g_param_spec_string ("address",
537                                                         P_("Address"),
538                                                         P_("D-Bus address specifying potential socket endpoints"),
539                                                         NULL,
540                                                         G_PARAM_WRITABLE |
541                                                         G_PARAM_CONSTRUCT_ONLY |
542                                                         G_PARAM_STATIC_NAME |
543                                                         G_PARAM_STATIC_BLURB |
544                                                         G_PARAM_STATIC_NICK));
545
546   /**
547    * GDBusConnection:flags:
548    *
549    * Flags from the #GDBusConnectionFlags enumeration.
550    *
551    * Since: 2.26
552    */
553   g_object_class_install_property (gobject_class,
554                                    PROP_FLAGS,
555                                    g_param_spec_flags ("flags",
556                                                        P_("Flags"),
557                                                        P_("Flags"),
558                                                        G_TYPE_DBUS_CONNECTION_FLAGS,
559                                                        G_DBUS_CONNECTION_FLAGS_NONE,
560                                                        G_PARAM_WRITABLE |
561                                                        G_PARAM_CONSTRUCT_ONLY |
562                                                        G_PARAM_STATIC_NAME |
563                                                        G_PARAM_STATIC_BLURB |
564                                                        G_PARAM_STATIC_NICK));
565
566   /**
567    * GDBusConnection:guid:
568    *
569    * The GUID of the peer performing the role of server when
570    * authenticating.
571    *
572    * If you are constructing a #GDBusConnection and pass
573    * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
574    * #GDBusConnection:flags property then you MUST also set this
575    * property to a valid guid.
576    *
577    * If you are constructing a #GDBusConnection and pass
578    * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
579    * #GDBusConnection:flags property you will be able to read the GUID
580    * of the other peer here after the connection has been successfully
581    * initialized.
582    *
583    * Since: 2.26
584    */
585   g_object_class_install_property (gobject_class,
586                                    PROP_GUID,
587                                    g_param_spec_string ("guid",
588                                                         P_("GUID"),
589                                                         P_("GUID of the server peer"),
590                                                         NULL,
591                                                         G_PARAM_READABLE |
592                                                         G_PARAM_WRITABLE |
593                                                         G_PARAM_CONSTRUCT_ONLY |
594                                                         G_PARAM_STATIC_NAME |
595                                                         G_PARAM_STATIC_BLURB |
596                                                         G_PARAM_STATIC_NICK));
597
598   /**
599    * GDBusConnection:unique-name:
600    *
601    * The unique name as assigned by the message bus or %NULL if the
602    * connection is not open or not a message bus connection.
603    *
604    * Since: 2.26
605    */
606   g_object_class_install_property (gobject_class,
607                                    PROP_UNIQUE_NAME,
608                                    g_param_spec_string ("unique-name",
609                                                         P_("unique-name"),
610                                                         P_("Unique name of bus connection"),
611                                                         NULL,
612                                                         G_PARAM_READABLE |
613                                                         G_PARAM_STATIC_NAME |
614                                                         G_PARAM_STATIC_BLURB |
615                                                         G_PARAM_STATIC_NICK));
616
617   /**
618    * GDBusConnection:closed:
619    *
620    * A boolean specifying whether the connection has been closed.
621    *
622    * Since: 2.26
623    */
624   g_object_class_install_property (gobject_class,
625                                    PROP_CLOSED,
626                                    g_param_spec_boolean ("closed",
627                                                          P_("Closed"),
628                                                          P_("Whether the connection is closed"),
629                                                          FALSE,
630                                                          G_PARAM_READABLE |
631                                                          G_PARAM_STATIC_NAME |
632                                                          G_PARAM_STATIC_BLURB |
633                                                          G_PARAM_STATIC_NICK));
634
635   /**
636    * GDBusConnection:exit-on-close:
637    *
638    * A boolean specifying whether the process will be terminated (by
639    * calling <literal>raise(SIGTERM)</literal>) if the connection
640    * is closed by the remote peer.
641    *
642    * Since: 2.26
643    */
644   g_object_class_install_property (gobject_class,
645                                    PROP_EXIT_ON_CLOSE,
646                                    g_param_spec_boolean ("exit-on-close",
647                                                          P_("Exit on close"),
648                                                          P_("Whether the process is terminated when the connection is closed"),
649                                                          FALSE,
650                                                          G_PARAM_READABLE |
651                                                          G_PARAM_WRITABLE |
652                                                          G_PARAM_STATIC_NAME |
653                                                          G_PARAM_STATIC_BLURB |
654                                                          G_PARAM_STATIC_NICK));
655
656   /**
657    * GDBusConnection:capabilities:
658    *
659    * Flags from the #GDBusCapabilityFlags enumeration
660    * representing connection features negotiated with the other peer.
661    *
662    * Since: 2.26
663    */
664   g_object_class_install_property (gobject_class,
665                                    PROP_CAPABILITY_FLAGS,
666                                    g_param_spec_flags ("capabilities",
667                                                        P_("Capabilities"),
668                                                        P_("Capabilities"),
669                                                        G_TYPE_DBUS_CAPABILITY_FLAGS,
670                                                        G_DBUS_CAPABILITY_FLAGS_NONE,
671                                                        G_PARAM_READABLE |
672                                                        G_PARAM_STATIC_NAME |
673                                                        G_PARAM_STATIC_BLURB |
674                                                        G_PARAM_STATIC_NICK));
675
676   /**
677    * GDBusConnection:authentication-observer:
678    *
679    * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
680    *
681    * Since: 2.26
682    */
683   g_object_class_install_property (gobject_class,
684                                    PROP_AUTHENTICATION_OBSERVER,
685                                    g_param_spec_object ("authentication-observer",
686                                                         P_("Authentication Observer"),
687                                                         P_("Object used to assist in the authentication process"),
688                                                         G_TYPE_DBUS_AUTH_OBSERVER,
689                                                         G_PARAM_WRITABLE |
690                                                         G_PARAM_CONSTRUCT_ONLY |
691                                                         G_PARAM_STATIC_NAME |
692                                                         G_PARAM_STATIC_BLURB |
693                                                         G_PARAM_STATIC_NICK));
694
695   /**
696    * GDBusConnection::closed:
697    * @connection: The #GDBusConnection emitting the signal.
698    * @remote_peer_vanished: %TRUE if @connection is closed because the
699    * remote peer closed its end of the connection.
700    * @error: A #GError with more details about the event or %NULL.
701    *
702    * Emitted when the connection is closed.
703    *
704    * The cause of this event can be
705    * <itemizedlist>
706    * <listitem><para>
707    *    If g_dbus_connection_close() is called. In this case
708    *    @remote_peer_vanished is set to %FALSE and @error is %NULL.
709    * </para></listitem>
710    * <listitem><para>
711    *    If the remote peer closes the connection. In this case
712    *    @remote_peer_vanished is set to %TRUE and @error is set.
713    * </para></listitem>
714    * <listitem><para>
715    *    If the remote peer sends invalid or malformed data. In this
716    *    case @remote_peer_vanished is set to %FALSE and @error
717    *    is set.
718    * </para></listitem>
719    * </itemizedlist>
720    *
721    * Upon receiving this signal, you should give up your reference to
722    * @connection. You are guaranteed that this signal is emitted only
723    * once.
724    *
725    * Since: 2.26
726    */
727   signals[CLOSED_SIGNAL] = g_signal_new ("closed",
728                                          G_TYPE_DBUS_CONNECTION,
729                                          G_SIGNAL_RUN_LAST,
730                                          G_STRUCT_OFFSET (GDBusConnectionClass, closed),
731                                          NULL,
732                                          NULL,
733                                          _gio_marshal_VOID__BOOLEAN_BOXED,
734                                          G_TYPE_NONE,
735                                          2,
736                                          G_TYPE_BOOLEAN,
737                                          G_TYPE_ERROR);
738 }
739
740 static void
741 g_dbus_connection_init (GDBusConnection *connection)
742 {
743   connection->priv = G_TYPE_INSTANCE_GET_PRIVATE (connection, G_TYPE_DBUS_CONNECTION, GDBusConnectionPrivate);
744
745   connection->priv->lock = g_mutex_new ();
746   connection->priv->init_lock = g_mutex_new ();
747
748   connection->priv->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
749
750   connection->priv->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
751                                                                 g_str_equal);
752   connection->priv->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
753                                                               g_direct_equal);
754   connection->priv->map_sender_to_signal_data_array = g_hash_table_new_full (g_str_hash,
755                                                                              g_str_equal,
756                                                                              g_free,
757                                                                              NULL);
758
759   connection->priv->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
760                                                                    g_str_equal,
761                                                                    NULL,
762                                                                    (GDestroyNotify) exported_object_free);
763
764   connection->priv->map_id_to_ei = g_hash_table_new (g_direct_hash,
765                                                      g_direct_equal);
766
767   connection->priv->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
768                                                                    g_str_equal,
769                                                                    NULL,
770                                                                    (GDestroyNotify) exported_subtree_free);
771
772   connection->priv->map_id_to_es = g_hash_table_new (g_direct_hash,
773                                                      g_direct_equal);
774
775   connection->priv->main_context_at_construction = g_main_context_get_thread_default ();
776   if (connection->priv->main_context_at_construction != NULL)
777     g_main_context_ref (connection->priv->main_context_at_construction);
778
779   connection->priv->filters = g_ptr_array_new ();
780 }
781
782 /**
783  * g_dbus_connection_get_stream:
784  * @connection: a #GDBusConnection
785  *
786  * Gets the underlying stream used for IO.
787  *
788  * Returns: the stream used for IO
789  *
790  * Since: 2.26
791  */
792 GIOStream *
793 g_dbus_connection_get_stream (GDBusConnection *connection)
794 {
795   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
796   return connection->priv->stream;
797 }
798
799
800 /**
801  * g_dbus_connection_is_closed:
802  * @connection: A #GDBusConnection.
803  *
804  * Gets whether @connection is closed.
805  *
806  * Returns: %TRUE if the connection is closed, %FALSE otherwise.
807  *
808  * Since: 2.26
809  */
810 gboolean
811 g_dbus_connection_is_closed (GDBusConnection *connection)
812 {
813   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
814   return connection->priv->closed;
815 }
816
817 /**
818  * g_dbus_connection_get_capabilities:
819  * @connection: A #GDBusConnection.
820  *
821  * Gets the capabilities negotiated with the remote peer
822  *
823  * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
824  *
825  * Since: 2.26
826  */
827 GDBusCapabilityFlags
828 g_dbus_connection_get_capabilities (GDBusConnection *connection)
829 {
830   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
831   return connection->priv->capabilities;
832 }
833
834
835 /* ---------------------------------------------------------------------------------------------------- */
836
837 typedef struct
838 {
839   GDBusConnection *connection;
840   GError *error;
841   gboolean remote_peer_vanished;
842 } EmitClosedData;
843
844 static void
845 emit_closed_data_free (EmitClosedData *data)
846 {
847   g_object_unref (data->connection);
848   if (data->error != NULL)
849     g_error_free (data->error);
850   g_free (data);
851 }
852
853 static gboolean
854 emit_closed_in_idle (gpointer user_data)
855 {
856   EmitClosedData *data = user_data;
857   gboolean result;
858
859   g_object_notify (G_OBJECT (data->connection), "closed");
860   g_signal_emit (data->connection,
861                  signals[CLOSED_SIGNAL],
862                  0,
863                  data->remote_peer_vanished,
864                  data->error,
865                  &result);
866   return FALSE;
867 }
868
869 /* Can be called from any thread, must hold lock */
870 static void
871 set_closed_unlocked (GDBusConnection *connection,
872                      gboolean         remote_peer_vanished,
873                      GError          *error)
874 {
875   GSource *idle_source;
876   EmitClosedData *data;
877
878   CONNECTION_ENSURE_LOCK (connection);
879
880   g_assert (!connection->priv->closed);
881
882   connection->priv->closed = TRUE;
883
884   data = g_new0 (EmitClosedData, 1);
885   data->connection = g_object_ref (connection);
886   data->remote_peer_vanished = remote_peer_vanished;
887   data->error = error != NULL ? g_error_copy (error) : NULL;
888
889   idle_source = g_idle_source_new ();
890   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
891   g_source_set_callback (idle_source,
892                          emit_closed_in_idle,
893                          data,
894                          (GDestroyNotify) emit_closed_data_free);
895   g_source_attach (idle_source, connection->priv->main_context_at_construction);
896   g_source_unref (idle_source);
897 }
898
899 /* ---------------------------------------------------------------------------------------------------- */
900
901 /**
902  * g_dbus_connection_close:
903  * @connection: A #GDBusConnection.
904  *
905  * Closes @connection. Note that this never causes the process to
906  * exit (this might only happen if the other end of a shared message
907  * bus connection disconnects).
908  *
909  * If @connection is already closed, this method does nothing.
910  *
911  * Since: 2.26
912  */
913 void
914 g_dbus_connection_close (GDBusConnection *connection)
915 {
916   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
917
918   CONNECTION_LOCK (connection);
919   if (!connection->priv->closed)
920     {
921       GError *error = NULL;
922
923       /* TODO: do this async */
924       //g_debug ("closing connection %p's stream %p", connection, connection->priv->stream);
925       if (!g_io_stream_close (connection->priv->stream, NULL, &error))
926         {
927           g_warning ("Error closing stream: %s", error->message);
928           g_error_free (error);
929         }
930
931       set_closed_unlocked (connection, FALSE, NULL);
932     }
933   CONNECTION_UNLOCK (connection);
934 }
935
936 /* ---------------------------------------------------------------------------------------------------- */
937
938 static gboolean
939 g_dbus_connection_send_message_unlocked (GDBusConnection   *connection,
940                                          GDBusMessage      *message,
941                                          volatile guint32  *out_serial,
942                                          GError           **error)
943 {
944   guchar *blob;
945   gsize blob_size;
946   guint32 serial_to_use;
947   gboolean ret;
948
949   CONNECTION_ENSURE_LOCK (connection);
950
951   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
952   g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
953
954   /* TODO: check all necessary headers are present */
955
956   ret = FALSE;
957   blob = NULL;
958
959   if (out_serial != NULL)
960     *out_serial = 0;
961
962   if (connection->priv->closed)
963     {
964       g_set_error_literal (error,
965                            G_IO_ERROR,
966                            G_IO_ERROR_CLOSED,
967                            _("The connection is closed"));
968       goto out;
969     }
970
971   blob = g_dbus_message_to_blob (message,
972                                  &blob_size,
973                                  error);
974   if (blob == NULL)
975     goto out;
976
977   serial_to_use = ++connection->priv->last_serial; /* TODO: handle overflow */
978
979   switch (blob[0])
980     {
981     case 'l':
982       ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
983       break;
984     case 'B':
985       ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
986       break;
987     default:
988       g_assert_not_reached ();
989       break;
990     }
991
992 #if 0
993   g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
994               blob_size, serial_to_use, connection);
995   g_printerr ("----\n");
996   hexdump (blob, blob_size);
997   g_printerr ("----\n");
998 #endif
999
1000   /* TODO: use connection->priv->auth to encode the blob */
1001
1002   if (out_serial != NULL)
1003     *out_serial = serial_to_use;
1004
1005   g_dbus_message_set_serial (message, serial_to_use);
1006
1007   _g_dbus_worker_send_message (connection->priv->worker,
1008                                message,
1009                                (gchar*) blob,
1010                                blob_size);
1011   blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1012
1013   ret = TRUE;
1014
1015  out:
1016   g_free (blob);
1017
1018   return ret;
1019 }
1020
1021 /**
1022  * g_dbus_connection_send_message:
1023  * @connection: A #GDBusConnection.
1024  * @message: A #GDBusMessage
1025  * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1026  * @error: Return location for error or %NULL.
1027  *
1028  * Asynchronously sends @message to the peer represented by @connection.
1029  *
1030  * If @out_serial is not %NULL, then the serial number assigned to
1031  * @message by @connection will be written to this location prior to
1032  * submitting the message to the underlying transport.
1033  *
1034  * If @connection is closed then the operation will fail with
1035  * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1036  * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1037  * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1038  *
1039  * See <xref linkend="gdbus-server"/> and <xref
1040  * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1041  * low-level API to send and receive UNIX file descriptors.
1042  *
1043  * Returns: %TRUE if the message was well-formed and queued for
1044  * transmission, %FALSE if @error is set.
1045  *
1046  * Since: 2.26
1047  */
1048 gboolean
1049 g_dbus_connection_send_message (GDBusConnection   *connection,
1050                                 GDBusMessage      *message,
1051                                 volatile guint32  *out_serial,
1052                                 GError           **error)
1053 {
1054   gboolean ret;
1055
1056   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1057   g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1058   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1059
1060   CONNECTION_LOCK (connection);
1061   ret = g_dbus_connection_send_message_unlocked (connection, message, out_serial, error);
1062   CONNECTION_UNLOCK (connection);
1063   return ret;
1064 }
1065
1066 /* ---------------------------------------------------------------------------------------------------- */
1067
1068 typedef struct
1069 {
1070   volatile gint ref_count;
1071   GDBusConnection *connection;
1072   guint32 serial;
1073   GSimpleAsyncResult *simple;
1074
1075   GMainContext *main_context;
1076
1077   GCancellable *cancellable;
1078
1079   gulong cancellable_handler_id;
1080
1081   GSource *timeout_source;
1082
1083   gboolean delivered;
1084 } SendMessageData;
1085
1086 static SendMessageData *
1087 send_message_data_ref (SendMessageData *data)
1088 {
1089   g_atomic_int_inc (&data->ref_count);
1090   return data;
1091 }
1092
1093 static void
1094 send_message_data_unref (SendMessageData *data)
1095 {
1096   if (g_atomic_int_dec_and_test (&data->ref_count))
1097     {
1098       g_assert (data->timeout_source == NULL);
1099       g_assert (data->simple == NULL);
1100       g_assert (data->cancellable_handler_id == 0);
1101       g_object_unref (data->connection);
1102       if (data->cancellable != NULL)
1103         g_object_unref (data->cancellable);
1104       if (data->main_context != NULL)
1105         g_main_context_unref (data->main_context);
1106       g_free (data);
1107     }
1108 }
1109
1110 /* ---------------------------------------------------------------------------------------------------- */
1111
1112 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1113 static void
1114 send_message_with_reply_deliver (SendMessageData *data)
1115 {
1116   CONNECTION_ENSURE_LOCK (data->connection);
1117
1118   g_assert (!data->delivered);
1119
1120   data->delivered = TRUE;
1121
1122   g_simple_async_result_complete_in_idle (data->simple);
1123   g_object_unref (data->simple);
1124   data->simple = NULL;
1125
1126   if (data->timeout_source != NULL)
1127     {
1128       g_source_destroy (data->timeout_source);
1129       data->timeout_source = NULL;
1130     }
1131   if (data->cancellable_handler_id > 0)
1132     {
1133       g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1134       data->cancellable_handler_id = 0;
1135     }
1136
1137   g_warn_if_fail (g_hash_table_remove (data->connection->priv->map_method_serial_to_send_message_data,
1138                                        GUINT_TO_POINTER (data->serial)));
1139
1140   send_message_data_unref (data);
1141 }
1142
1143 /* ---------------------------------------------------------------------------------------------------- */
1144
1145 /* must hold lock */
1146 static void
1147 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1148                                           GDBusMessage    *reply)
1149 {
1150   if (data->delivered)
1151     goto out;
1152
1153   g_simple_async_result_set_op_res_gpointer (data->simple,
1154                                              g_object_ref (reply),
1155                                              g_object_unref);
1156
1157   send_message_with_reply_deliver (data);
1158
1159  out:
1160   ;
1161 }
1162
1163 /* ---------------------------------------------------------------------------------------------------- */
1164
1165 static gboolean
1166 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1167 {
1168   SendMessageData *data = user_data;
1169
1170   CONNECTION_LOCK (data->connection);
1171   if (data->delivered)
1172     goto out;
1173
1174   g_simple_async_result_set_error (data->simple,
1175                                    G_IO_ERROR,
1176                                    G_IO_ERROR_CANCELLED,
1177                                    _("Operation was cancelled"));
1178
1179   send_message_with_reply_deliver (data);
1180
1181  out:
1182   CONNECTION_UNLOCK (data->connection);
1183   return FALSE;
1184 }
1185
1186 /* Can be called from any thread with or without lock held */
1187 static void
1188 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1189                                       gpointer      user_data)
1190 {
1191   SendMessageData *data = user_data;
1192   GSource *idle_source;
1193
1194   /* postpone cancellation to idle handler since we may be called directly
1195    * via g_cancellable_connect() (e.g. holding lock)
1196    */
1197   idle_source = g_idle_source_new ();
1198   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1199   g_source_set_callback (idle_source,
1200                          send_message_with_reply_cancelled_idle_cb,
1201                          send_message_data_ref (data),
1202                          (GDestroyNotify) send_message_data_unref);
1203   g_source_attach (idle_source, data->main_context);
1204   g_source_unref (idle_source);
1205 }
1206
1207 /* ---------------------------------------------------------------------------------------------------- */
1208
1209 static gboolean
1210 send_message_with_reply_timeout_cb (gpointer user_data)
1211 {
1212   SendMessageData *data = user_data;
1213
1214   CONNECTION_LOCK (data->connection);
1215   if (data->delivered)
1216     goto out;
1217
1218   g_simple_async_result_set_error (data->simple,
1219                                    G_IO_ERROR,
1220                                    G_IO_ERROR_TIMED_OUT,
1221                                    _("Timeout was reached"));
1222
1223   send_message_with_reply_deliver (data);
1224
1225  out:
1226   CONNECTION_UNLOCK (data->connection);
1227
1228   return FALSE;
1229 }
1230
1231 /* ---------------------------------------------------------------------------------------------------- */
1232
1233 static void
1234 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection     *connection,
1235                                                     GDBusMessage        *message,
1236                                                     gint                 timeout_msec,
1237                                                     volatile guint32    *out_serial,
1238                                                     GCancellable        *cancellable,
1239                                                     GAsyncReadyCallback  callback,
1240                                                     gpointer             user_data)
1241 {
1242   GSimpleAsyncResult *simple;
1243   SendMessageData *data;
1244   GError *error;
1245   volatile guint32 serial;
1246
1247   data = NULL;
1248
1249   if (out_serial == NULL)
1250     out_serial = &serial;
1251
1252   if (timeout_msec == -1)
1253     timeout_msec = 30 * 1000; /* TODO: check 30 secs is the default timeout */
1254
1255   simple = g_simple_async_result_new (G_OBJECT (connection),
1256                                       callback,
1257                                       user_data,
1258                                       g_dbus_connection_send_message_with_reply);
1259
1260   if (g_cancellable_is_cancelled (cancellable))
1261     {
1262       g_simple_async_result_set_error (simple,
1263                                        G_IO_ERROR,
1264                                        G_IO_ERROR_CANCELLED,
1265                                        _("Operation was cancelled"));
1266       g_simple_async_result_complete_in_idle (simple);
1267       g_object_unref (simple);
1268       goto out;
1269     }
1270
1271   if (connection->priv->closed)
1272     {
1273       g_simple_async_result_set_error (simple,
1274                                        G_IO_ERROR,
1275                                        G_IO_ERROR_CLOSED,
1276                                        _("The connection is closed"));
1277       g_simple_async_result_complete_in_idle (simple);
1278       g_object_unref (simple);
1279       goto out;
1280     }
1281
1282   error = NULL;
1283   if (!g_dbus_connection_send_message_unlocked (connection, message, out_serial, &error))
1284     {
1285       g_simple_async_result_set_from_error (simple, error);
1286       g_simple_async_result_complete_in_idle (simple);
1287       g_object_unref (simple);
1288       goto out;
1289     }
1290
1291   data = g_new0 (SendMessageData, 1);
1292   data->ref_count = 1;
1293   data->connection = g_object_ref (connection);
1294   data->simple = simple;
1295   data->serial = *out_serial;
1296   data->main_context = g_main_context_get_thread_default ();
1297   if (data->main_context != NULL)
1298     g_main_context_ref (data->main_context);
1299
1300   if (cancellable != NULL)
1301     {
1302       data->cancellable = g_object_ref (cancellable);
1303       data->cancellable_handler_id = g_cancellable_connect (cancellable,
1304                                                             G_CALLBACK (send_message_with_reply_cancelled_cb),
1305                                                             send_message_data_ref (data),
1306                                                             (GDestroyNotify) send_message_data_unref);
1307       g_object_set_data_full (G_OBJECT (simple),
1308                               "cancellable",
1309                               g_object_ref (cancellable),
1310                               (GDestroyNotify) g_object_unref);
1311     }
1312
1313   data->timeout_source = g_timeout_source_new (timeout_msec);
1314   g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1315   g_source_set_callback (data->timeout_source,
1316                          send_message_with_reply_timeout_cb,
1317                          send_message_data_ref (data),
1318                          (GDestroyNotify) send_message_data_unref);
1319   g_source_attach (data->timeout_source, data->main_context);
1320   g_source_unref (data->timeout_source);
1321
1322   g_hash_table_insert (connection->priv->map_method_serial_to_send_message_data,
1323                        GUINT_TO_POINTER (*out_serial),
1324                        data);
1325
1326  out:
1327   ;
1328 }
1329
1330 /**
1331  * g_dbus_connection_send_message_with_reply:
1332  * @connection: A #GDBusConnection.
1333  * @message: A #GDBusMessage.
1334  * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1335  * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1336  * @cancellable: A #GCancellable or %NULL.
1337  * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
1338  * care about the result.
1339  * @user_data: The data to pass to @callback.
1340  *
1341  * Asynchronously sends @message to the peer represented by @connection.
1342  *
1343  * If @out_serial is not %NULL, then the serial number assigned to
1344  * @message by @connection will be written to this location prior to
1345  * submitting the message to the underlying transport.
1346  *
1347  * If @connection is closed then the operation will fail with
1348  * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1349  * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1350  * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1351  *
1352  * This is an asynchronous method. When the operation is finished, @callback will be invoked
1353  * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
1354  * of the thread you are calling this method from. You can then call
1355  * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1356  * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
1357  *
1358  * See <xref linkend="gdbus-server"/> and <xref
1359  * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1360  * low-level API to send and receive UNIX file descriptors.
1361  *
1362  * Since: 2.26
1363  */
1364 void
1365 g_dbus_connection_send_message_with_reply (GDBusConnection     *connection,
1366                                            GDBusMessage        *message,
1367                                            gint                 timeout_msec,
1368                                            volatile guint32    *out_serial,
1369                                            GCancellable        *cancellable,
1370                                            GAsyncReadyCallback  callback,
1371                                            gpointer             user_data)
1372 {
1373   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1374   g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1375   g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
1376
1377   CONNECTION_LOCK (connection);
1378   g_dbus_connection_send_message_with_reply_unlocked (connection,
1379                                                       message,
1380                                                       timeout_msec,
1381                                                       out_serial,
1382                                                       cancellable,
1383                                                       callback,
1384                                                       user_data);
1385   CONNECTION_UNLOCK (connection);
1386 }
1387
1388 /**
1389  * g_dbus_connection_send_message_with_reply_finish:
1390  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
1391  * @error: Return location for error or %NULL.
1392  *
1393  * Finishes an operation started with g_dbus_connection_send_message_with_reply().
1394  *
1395  * Note that @error is only set if a local in-process error
1396  * occured. That is to say that the returned #GDBusMessage object may
1397  * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1398  * g_dbus_message_to_gerror() to transcode this to a #GError.
1399  *
1400  * See <xref linkend="gdbus-server"/> and <xref
1401  * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1402  * low-level API to send and receive UNIX file descriptors.
1403  *
1404  * Returns: A #GDBusMessage or %NULL if @error is set.
1405  *
1406  * Since: 2.26
1407  */
1408 GDBusMessage *
1409 g_dbus_connection_send_message_with_reply_finish (GDBusConnection  *connection,
1410                                                   GAsyncResult     *res,
1411                                                   GError          **error)
1412 {
1413   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1414   GDBusMessage *reply;
1415   GCancellable *cancellable;
1416
1417   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1418   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1419
1420   reply = NULL;
1421
1422   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
1423
1424   if (g_simple_async_result_propagate_error (simple, error))
1425     goto out;
1426
1427   reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
1428   cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
1429   if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
1430     {
1431       g_object_unref (reply);
1432       reply = NULL;
1433       g_set_error_literal (error,
1434                            G_IO_ERROR,
1435                            G_IO_ERROR_CANCELLED,
1436                            _("Operation was cancelled"));
1437     }
1438  out:
1439   return reply;
1440 }
1441
1442 /* ---------------------------------------------------------------------------------------------------- */
1443
1444 typedef struct
1445 {
1446   GAsyncResult *res;
1447   GMainContext *context;
1448   GMainLoop *loop;
1449 } SendMessageSyncData;
1450
1451 static void
1452 send_message_with_reply_sync_cb (GDBusConnection *connection,
1453                                  GAsyncResult    *res,
1454                                  gpointer         user_data)
1455 {
1456   SendMessageSyncData *data = user_data;
1457   data->res = g_object_ref (res);
1458   g_main_loop_quit (data->loop);
1459 }
1460
1461 /**
1462  * g_dbus_connection_send_message_with_reply_sync:
1463  * @connection: A #GDBusConnection.
1464  * @message: A #GDBusMessage.
1465  * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1466  * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1467  * @cancellable: A #GCancellable or %NULL.
1468  * @error: Return location for error or %NULL.
1469  *
1470  * Synchronously sends @message to the peer represented by @connection
1471  * and blocks the calling thread until a reply is received or the
1472  * timeout is reached. See g_dbus_connection_send_message_with_reply()
1473  * for the asynchronous version of this method.
1474  *
1475  * If @out_serial is not %NULL, then the serial number assigned to
1476  * @message by @connection will be written to this location prior to
1477  * submitting the message to the underlying transport.
1478  *
1479  * If @connection is closed then the operation will fail with
1480  * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1481  * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1482  * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1483  *
1484  * Note that @error is only set if a local in-process error
1485  * occured. That is to say that the returned #GDBusMessage object may
1486  * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1487  * g_dbus_message_to_gerror() to transcode this to a #GError.
1488  *
1489  * See <xref linkend="gdbus-server"/> and <xref
1490  * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1491  * low-level API to send and receive UNIX file descriptors.
1492  *
1493  * Returns: A #GDBusMessage that is the reply to @message or %NULL if @error is set.
1494  *
1495  * Since: 2.26
1496  */
1497 GDBusMessage *
1498 g_dbus_connection_send_message_with_reply_sync (GDBusConnection   *connection,
1499                                                 GDBusMessage      *message,
1500                                                 gint               timeout_msec,
1501                                                 volatile guint32  *out_serial,
1502                                                 GCancellable      *cancellable,
1503                                                 GError           **error)
1504 {
1505   SendMessageSyncData *data;
1506   GDBusMessage *reply;
1507
1508   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1509   g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
1510   g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1511   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1512
1513   data = g_new0 (SendMessageSyncData, 1);
1514   data->context = g_main_context_new ();
1515   data->loop = g_main_loop_new (data->context, FALSE);
1516
1517   g_main_context_push_thread_default (data->context);
1518
1519   g_dbus_connection_send_message_with_reply (connection,
1520                                              message,
1521                                              timeout_msec,
1522                                              out_serial,
1523                                              cancellable,
1524                                              (GAsyncReadyCallback) send_message_with_reply_sync_cb,
1525                                              data);
1526   g_main_loop_run (data->loop);
1527   reply = g_dbus_connection_send_message_with_reply_finish (connection,
1528                                                             data->res,
1529                                                             error);
1530
1531   g_main_context_pop_thread_default (data->context);
1532
1533   g_main_context_unref (data->context);
1534   g_main_loop_unref (data->loop);
1535   g_object_unref (data->res);
1536   g_free (data);
1537
1538   return reply;
1539 }
1540
1541 /* ---------------------------------------------------------------------------------------------------- */
1542
1543 typedef struct
1544 {
1545   GDBusMessageFilterFunction func;
1546   gpointer user_data;
1547 } FilterCallback;
1548
1549 typedef struct
1550 {
1551   guint                       id;
1552   GDBusMessageFilterFunction  filter_function;
1553   gpointer                    user_data;
1554   GDestroyNotify              user_data_free_func;
1555 } FilterData;
1556
1557 /* Called in worker's thread - we must not block */
1558 static void
1559 on_worker_message_received (GDBusWorker  *worker,
1560                             GDBusMessage *message,
1561                             gpointer      user_data)
1562 {
1563   GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1564   FilterCallback *filters;
1565   gboolean consumed_by_filter;
1566   guint num_filters;
1567   guint n;
1568
1569   //g_debug ("in on_worker_message_received");
1570
1571   g_object_ref (connection);
1572
1573   /* First collect the set of callback functions */
1574   CONNECTION_LOCK (connection);
1575   num_filters = connection->priv->filters->len;
1576   filters = g_new0 (FilterCallback, num_filters);
1577   for (n = 0; n < num_filters; n++)
1578     {
1579       FilterData *data = connection->priv->filters->pdata[n];
1580       filters[n].func = data->filter_function;
1581       filters[n].user_data = data->user_data;
1582     }
1583   CONNECTION_UNLOCK (connection);
1584
1585   /* the call the filters in order (without holding the lock) */
1586   consumed_by_filter = FALSE;
1587   for (n = 0; n < num_filters; n++)
1588     {
1589       consumed_by_filter = filters[n].func (connection,
1590                                             message,
1591                                             filters[n].user_data);
1592       if (consumed_by_filter)
1593         break;
1594     }
1595
1596   /* Standard dispatch unless the filter ate the message */
1597   if (!consumed_by_filter)
1598     {
1599       GDBusMessageType message_type;
1600
1601       message_type = g_dbus_message_get_message_type (message);
1602       if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
1603         {
1604           guint32 reply_serial;
1605           SendMessageData *send_message_data;
1606
1607           reply_serial = g_dbus_message_get_reply_serial (message);
1608           CONNECTION_LOCK (connection);
1609           send_message_data = g_hash_table_lookup (connection->priv->map_method_serial_to_send_message_data,
1610                                                    GUINT_TO_POINTER (reply_serial));
1611           if (send_message_data != NULL)
1612             {
1613               //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
1614               send_message_data_deliver_reply_unlocked (send_message_data, message);
1615             }
1616           else
1617             {
1618               //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
1619             }
1620           CONNECTION_UNLOCK (connection);
1621         }
1622       else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
1623         {
1624           CONNECTION_LOCK (connection);
1625           distribute_signals (connection, message);
1626           CONNECTION_UNLOCK (connection);
1627         }
1628       else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
1629         {
1630           CONNECTION_LOCK (connection);
1631           distribute_method_call (connection, message);
1632           CONNECTION_UNLOCK (connection);
1633         }
1634     }
1635
1636   g_object_unref (connection);
1637   g_free (filters);
1638 }
1639
1640 /* Called in worker's thread - we must not block */
1641 static void
1642 on_worker_closed (GDBusWorker *worker,
1643                   gboolean     remote_peer_vanished,
1644                   GError      *error,
1645                   gpointer     user_data)
1646 {
1647   GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1648
1649   //g_debug ("in on_worker_closed: %s", error->message);
1650
1651   CONNECTION_LOCK (connection);
1652   if (!connection->priv->closed)
1653     set_closed_unlocked (connection, remote_peer_vanished, error);
1654   CONNECTION_UNLOCK (connection);
1655 }
1656
1657 /* ---------------------------------------------------------------------------------------------------- */
1658
1659 /* Determines the biggest set of capabilities we can support on this connection */
1660 static GDBusCapabilityFlags
1661 get_offered_capabilities_max (GDBusConnection *connection)
1662 {
1663       GDBusCapabilityFlags ret;
1664       ret = G_DBUS_CAPABILITY_FLAGS_NONE;
1665 #ifdef G_OS_UNIX
1666       if (G_IS_UNIX_CONNECTION (connection->priv->stream))
1667         ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
1668 #endif
1669       return ret;
1670 }
1671
1672 static gboolean
1673 initable_init (GInitable     *initable,
1674                GCancellable  *cancellable,
1675                GError       **error)
1676 {
1677   GDBusConnection *connection = G_DBUS_CONNECTION (initable);
1678   gboolean ret;
1679
1680   /* This method needs to be idempotent to work with the singleton
1681    * pattern. See the docs for g_initable_init(). We implement this by
1682    * locking.
1683    *
1684    * Unfortunately we can't use the main lock since the on_worker_*()
1685    * callbacks above needs the lock during initialization (for message
1686    * bus connections we do a synchronous Hello() call on the bus).
1687    */
1688   g_mutex_lock (connection->priv->init_lock);
1689
1690   ret = FALSE;
1691
1692   if (connection->priv->is_initialized)
1693     {
1694       if (connection->priv->stream != NULL)
1695         ret = TRUE;
1696       else
1697         g_assert (connection->priv->initialization_error != NULL);
1698       goto out;
1699     }
1700   g_assert (connection->priv->initialization_error == NULL);
1701
1702   /* The user can pass multiple (but mutally exclusive) construct
1703    * properties:
1704    *
1705    *  - stream (of type GIOStream)
1706    *  - address (of type gchar*)
1707    *
1708    * At the end of the day we end up with a non-NULL GIOStream
1709    * object in connection->priv->stream.
1710    */
1711   if (connection->priv->address != NULL)
1712     {
1713       g_assert (connection->priv->stream == NULL);
1714
1715       if ((connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
1716           (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
1717         {
1718           g_set_error_literal (error,
1719                                G_IO_ERROR,
1720                                G_IO_ERROR_INVALID_ARGUMENT,
1721                                _("Unsupported flags encountered when constructing a client-side connection"));
1722           goto out;
1723         }
1724
1725       connection->priv->stream = g_dbus_address_get_stream_sync (connection->priv->address,
1726                                                                  NULL, /* TODO: out_guid */
1727                                                                  cancellable,
1728                                                                  &connection->priv->initialization_error);
1729       if (connection->priv->stream == NULL)
1730         goto out;
1731     }
1732   else if (connection->priv->stream != NULL)
1733     {
1734       /* nothing to do */
1735     }
1736   else
1737     {
1738       g_assert_not_reached ();
1739     }
1740
1741   /* Authenticate the connection */
1742   if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
1743     {
1744       g_assert (!(connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
1745       g_assert (connection->priv->guid != NULL);
1746       connection->priv->auth = _g_dbus_auth_new (connection->priv->stream);
1747       if (!_g_dbus_auth_run_server (connection->priv->auth,
1748                                     connection->priv->authentication_observer,
1749                                     connection->priv->guid,
1750                                     (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
1751                                     get_offered_capabilities_max (connection),
1752                                     &connection->priv->capabilities,
1753                                     &connection->priv->crendentials,
1754                                     cancellable,
1755                                     &connection->priv->initialization_error))
1756         goto out;
1757     }
1758   else if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
1759     {
1760       g_assert (!(connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
1761       g_assert (connection->priv->guid == NULL);
1762       connection->priv->auth = _g_dbus_auth_new (connection->priv->stream);
1763       connection->priv->guid = _g_dbus_auth_run_client (connection->priv->auth,
1764                                                         get_offered_capabilities_max (connection),
1765                                                         &connection->priv->capabilities,
1766                                                         cancellable,
1767                                                         &connection->priv->initialization_error);
1768       if (connection->priv->guid == NULL)
1769         goto out;
1770     }
1771
1772   if (connection->priv->authentication_observer != NULL)
1773     {
1774       g_object_unref (connection->priv->authentication_observer);
1775       connection->priv->authentication_observer = NULL;
1776     }
1777
1778   //g_output_stream_flush (G_SOCKET_CONNECTION (connection->priv->stream)
1779
1780   //g_debug ("haz unix fd passing powers: %d", connection->priv->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
1781
1782   /* Hack used until
1783    *
1784    *  https://bugzilla.gnome.org/show_bug.cgi?id=616458
1785    *
1786    * has been resolved
1787    */
1788   if (G_IS_SOCKET_CONNECTION (connection->priv->stream))
1789     {
1790       g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->priv->stream)), FALSE);
1791     }
1792
1793   connection->priv->worker = _g_dbus_worker_new (connection->priv->stream,
1794                                                  connection->priv->capabilities,
1795                                                  on_worker_message_received,
1796                                                  on_worker_closed,
1797                                                  connection);
1798
1799   /* if a bus connection, invoke org.freedesktop.DBus.Hello - this is how we're getting a name */
1800   if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
1801     {
1802       GVariant *hello_result;
1803       const gchar *s;
1804
1805       hello_result = g_dbus_connection_call_sync (connection,
1806                                                   "org.freedesktop.DBus", /* name */
1807                                                   "/org/freedesktop/DBus", /* path */
1808                                                   "org.freedesktop.DBus", /* interface */
1809                                                   "Hello",
1810                                                   NULL, /* parameters */
1811                                                   G_DBUS_CALL_FLAGS_NONE,
1812                                                   -1,
1813                                                   NULL, /* TODO: cancellable */
1814                                                   &connection->priv->initialization_error);
1815       if (hello_result == NULL)
1816         goto out;
1817
1818       g_variant_get (hello_result, "(s)", &s);
1819       connection->priv->bus_unique_name = g_strdup (s);
1820       g_variant_unref (hello_result);
1821       //g_debug ("unique name is `%s'", connection->priv->bus_unique_name);
1822     }
1823
1824   connection->priv->is_initialized = TRUE;
1825
1826   ret = TRUE;
1827  out:
1828   if (!ret)
1829     {
1830       g_assert (connection->priv->initialization_error != NULL);
1831       g_propagate_error (error, g_error_copy (connection->priv->initialization_error));
1832     }
1833
1834   g_mutex_unlock (connection->priv->init_lock);
1835
1836   return ret;
1837 }
1838
1839 static void
1840 initable_iface_init (GInitableIface *initable_iface)
1841 {
1842   initable_iface->init = initable_init;
1843 }
1844
1845 /* ---------------------------------------------------------------------------------------------------- */
1846
1847 static void
1848 async_init_thread (GSimpleAsyncResult *res,
1849                    GObject            *object,
1850                    GCancellable       *cancellable)
1851 {
1852   GError *error = NULL;
1853
1854   if (!g_initable_init (G_INITABLE (object), cancellable, &error))
1855     {
1856       g_simple_async_result_set_from_error (res, error);
1857       g_error_free (error);
1858     }
1859 }
1860
1861 static void
1862 async_initable_init_async (GAsyncInitable      *initable,
1863                            gint                 io_priority,
1864                            GCancellable        *cancellable,
1865                            GAsyncReadyCallback  callback,
1866                            gpointer             user_data)
1867 {
1868   GSimpleAsyncResult *res;
1869
1870   g_return_if_fail (G_IS_INITABLE (initable));
1871
1872   res = g_simple_async_result_new (G_OBJECT (initable), callback, user_data,
1873                                    async_initable_init_async);
1874   g_simple_async_result_run_in_thread (res, async_init_thread,
1875                                        io_priority, cancellable);
1876   g_object_unref (res);
1877 }
1878
1879 static gboolean
1880 async_initable_init_finish (GAsyncInitable  *initable,
1881                             GAsyncResult    *res,
1882                             GError         **error)
1883 {
1884   return TRUE; /* Errors handled by base impl */
1885 }
1886
1887 static void
1888 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
1889 {
1890   /* We basically just want to use GIO's default implementation - though that one is
1891    * unfortunately broken, see #615111. So we copy-paste a fixed-up version.
1892    */
1893   async_initable_iface->init_async = async_initable_init_async;
1894   async_initable_iface->init_finish = async_initable_init_finish;
1895 }
1896
1897 /* ---------------------------------------------------------------------------------------------------- */
1898
1899 /**
1900  * g_dbus_connection_new:
1901  * @stream: A #GIOStream.
1902  * @guid: The GUID to use if a authenticating as a server or %NULL.
1903  * @flags: Flags describing how to make the connection.
1904  * @authentication_observer: A #GDBusAuthObserver or %NULL.
1905  * @cancellable: A #GCancellable or %NULL.
1906  * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
1907  * @user_data: The data to pass to @callback.
1908  *
1909  * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
1910  * with the end represented by @stream.
1911  *
1912  * If %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER is set in @flags,
1913  * @auth_observer (if not %NULL) is used to assist in the client
1914  * authentication process.
1915  *
1916  * When the operation is finished, @callback will be invoked. You can
1917  * then call g_dbus_connection_new_finish() to get the result of the
1918  * operation.
1919  *
1920  * This is a asynchronous failable constructor. See
1921  * g_dbus_connection_new_sync() for the synchronous
1922  * version.
1923  *
1924  * Since: 2.26
1925  */
1926 void
1927 g_dbus_connection_new (GIOStream            *stream,
1928                        const gchar          *guid,
1929                        GDBusConnectionFlags  flags,
1930                        GDBusAuthObserver    *authentication_observer,
1931                        GCancellable         *cancellable,
1932                        GAsyncReadyCallback   callback,
1933                        gpointer              user_data)
1934 {
1935   g_return_if_fail (G_IS_IO_STREAM (stream));
1936   g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
1937                               G_PRIORITY_DEFAULT,
1938                               cancellable,
1939                               callback,
1940                               user_data,
1941                               "stream", stream,
1942                               "guid", guid,
1943                               "flags", flags,
1944                               "authentication-observer", authentication_observer,
1945                               NULL);
1946 }
1947
1948 /**
1949  * g_dbus_connection_new_finish:
1950  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
1951  * @error: Return location for error or %NULL.
1952  *
1953  * Finishes an operation started with g_dbus_connection_new().
1954  *
1955  * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
1956  *
1957  * Since: 2.26
1958  */
1959 GDBusConnection *
1960 g_dbus_connection_new_finish (GAsyncResult  *res,
1961                               GError       **error)
1962 {
1963   GObject *object;
1964   GObject *source_object;
1965
1966   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
1967   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1968
1969   source_object = g_async_result_get_source_object (res);
1970   g_assert (source_object != NULL);
1971   object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
1972                                         res,
1973                                         error);
1974   g_object_unref (source_object);
1975   if (object != NULL)
1976     return G_DBUS_CONNECTION (object);
1977   else
1978     return NULL;
1979 }
1980
1981 /**
1982  * g_dbus_connection_new_sync:
1983  * @stream: A #GIOStream.
1984  * @guid: The GUID to use if a authenticating as a server or %NULL.
1985  * @flags: Flags describing how to make the connection.
1986  * @authentication_observer: A #GDBusAuthObserver or %NULL.
1987  * @cancellable: A #GCancellable or %NULL.
1988  * @error: Return location for error or %NULL.
1989  *
1990  * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
1991  * with the end represented by @stream.
1992  *
1993  * If %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER is set in @flags,
1994  * @auth_observer (if not %NULL) is used to assist in the client
1995  * authentication process.
1996  *
1997  * This is a synchronous failable constructor. See
1998  * g_dbus_connection_new() for the asynchronous version.
1999  *
2000  * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2001  *
2002  * Since: 2.26
2003  */
2004 GDBusConnection *
2005 g_dbus_connection_new_sync (GIOStream             *stream,
2006                             const gchar           *guid,
2007                             GDBusConnectionFlags   flags,
2008                             GDBusAuthObserver     *authentication_observer,
2009                             GCancellable          *cancellable,
2010                             GError               **error)
2011 {
2012   g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2013   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2014   return g_initable_new (G_TYPE_DBUS_CONNECTION,
2015                          cancellable,
2016                          error,
2017                          "stream", stream,
2018                          "guid", guid,
2019                          "flags", flags,
2020                          "authentication-observer", authentication_observer,
2021                          NULL);
2022 }
2023
2024 /* ---------------------------------------------------------------------------------------------------- */
2025
2026 /**
2027  * g_dbus_connection_new_for_address:
2028  * @address: A D-Bus address.
2029  * @flags: Flags describing how to make the connection.
2030  * @cancellable: A #GCancellable or %NULL.
2031  * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2032  * @user_data: The data to pass to @callback.
2033  *
2034  * Asynchronously connects and sets up a D-Bus client connection for
2035  * exchanging D-Bus messages with an endpoint specified by @address
2036  * which must be in the D-Bus address format.
2037  *
2038  * This constructor can only be used to initiate client-side
2039  * connections - use g_dbus_connection_new() if you need to act as the
2040  * server. In particular, @flags cannot contain the
2041  * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2042  * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2043  *
2044  * When the operation is finished, @callback will be invoked. You can
2045  * then call g_dbus_connection_new_finish() to get the result of the
2046  * operation.
2047  *
2048  * This is a asynchronous failable constructor. See
2049  * g_dbus_connection_new_for_address_sync() for the synchronous
2050  * version.
2051  *
2052  * Since: 2.26
2053  */
2054 void
2055 g_dbus_connection_new_for_address (const gchar          *address,
2056                                    GDBusConnectionFlags  flags,
2057                                    GCancellable         *cancellable,
2058                                    GAsyncReadyCallback   callback,
2059                                    gpointer              user_data)
2060 {
2061   g_return_if_fail (address != NULL);
2062   g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2063                               G_PRIORITY_DEFAULT,
2064                               cancellable,
2065                               callback,
2066                               user_data,
2067                               "address", address,
2068                               "flags", flags,
2069                               NULL);
2070 }
2071
2072 /**
2073  * g_dbus_connection_new_for_address_finish:
2074  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2075  * @error: Return location for error or %NULL.
2076  *
2077  * Finishes an operation started with g_dbus_connection_new_for_address().
2078  *
2079  * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2080  *
2081  * Since: 2.26
2082  */
2083 GDBusConnection *
2084 g_dbus_connection_new_for_address_finish (GAsyncResult  *res,
2085                                           GError       **error)
2086 {
2087   GObject *object;
2088   GObject *source_object;
2089
2090   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2091   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2092
2093   source_object = g_async_result_get_source_object (res);
2094   g_assert (source_object != NULL);
2095   object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2096                                         res,
2097                                         error);
2098   g_object_unref (source_object);
2099   if (object != NULL)
2100     return G_DBUS_CONNECTION (object);
2101   else
2102     return NULL;
2103 }
2104
2105 /**
2106  * g_dbus_connection_new_for_address_sync:
2107  * @address: A D-Bus address.
2108  * @flags: Flags describing how to make the connection.
2109  * @cancellable: A #GCancellable or %NULL.
2110  * @error: Return location for error or %NULL.
2111  *
2112  * Synchronously connects and sets up a D-Bus client connection for
2113  * exchanging D-Bus messages with an endpoint specified by @address
2114  * which must be in the D-Bus address format.
2115  *
2116  * This constructor can only be used to initiate client-side
2117  * connections - use g_dbus_connection_new_sync() if you need to act
2118  * as the server. In particular, @flags cannot contain the
2119  * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2120  * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2121  *
2122  * This is a synchronous failable constructor. See
2123  * g_dbus_connection_new_for_address() for the asynchronous version.
2124  *
2125  * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2126  *
2127  * Since: 2.26
2128  */
2129 GDBusConnection *
2130 g_dbus_connection_new_for_address_sync (const gchar           *address,
2131                                         GDBusConnectionFlags   flags,
2132                                         GCancellable          *cancellable,
2133                                         GError               **error)
2134 {
2135   g_return_val_if_fail (address != NULL, NULL);
2136   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2137   return g_initable_new (G_TYPE_DBUS_CONNECTION,
2138                          cancellable,
2139                          error,
2140                          "address", address,
2141                          "flags", flags,
2142                          NULL);
2143 }
2144
2145 /* ---------------------------------------------------------------------------------------------------- */
2146
2147 /**
2148  * g_dbus_connection_set_exit_on_close:
2149  * @connection: A #GDBusConnection.
2150  * @exit_on_close: Whether the process should be terminated
2151  * when @connection is closed by the remote peer.
2152  *
2153  * Sets whether the process should be terminated when @connection is
2154  * closed by the remote peer. See #GDBusConnection:exit-on-close for
2155  * more details.
2156  *
2157  * Since: 2.26
2158  */
2159 void
2160 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2161                                      gboolean         exit_on_close)
2162 {
2163   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2164   connection->priv->exit_on_close = exit_on_close;
2165 }
2166
2167 /**
2168  * g_dbus_connection_get_exit_on_close:
2169  * @connection: A #GDBusConnection.
2170  *
2171  * Gets whether the process is terminated when @connection is
2172  * closed by the remote peer. See
2173  * #GDBusConnection:exit-on-close for more details.
2174  *
2175  * Returns: Whether the process is terminated when @connection is
2176  * closed by the remote peer.
2177  *
2178  * Since: 2.26
2179  */
2180 gboolean
2181 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2182 {
2183   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2184   return connection->priv->exit_on_close;
2185 }
2186
2187 /**
2188  * g_dbus_connection_get_guid:
2189  * @connection: A #GDBusConnection.
2190  *
2191  * The GUID of the peer performing the role of server when
2192  * authenticating. See #GDBusConnection:guid for more details.
2193  *
2194  * Returns: The GUID. Do not free this string, it is owned by
2195  * @connection.
2196  *
2197  * Since: 2.26
2198  */
2199 const gchar *
2200 g_dbus_connection_get_guid (GDBusConnection *connection)
2201 {
2202   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2203   return connection->priv->guid;
2204 }
2205
2206 /**
2207  * g_dbus_connection_get_unique_name:
2208  * @connection: A #GDBusConnection.
2209  *
2210  * Gets the unique name of @connection as assigned by the message
2211  * bus. This can also be used to figure out if @connection is a
2212  * message bus connection.
2213  *
2214  * Returns: The unique name or %NULL if @connection is not a message
2215  * bus connection. Do not free this string, it is owned by
2216  * @connection.
2217  *
2218  * Since: 2.26
2219  */
2220 const gchar *
2221 g_dbus_connection_get_unique_name (GDBusConnection *connection)
2222 {
2223   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2224   return connection->priv->bus_unique_name;
2225 }
2226
2227 /**
2228  * g_dbus_connection_get_peer_credentials:
2229  * @connection: A #GDBusConnection.
2230  *
2231  * Gets the credentials of the authenticated peer. This will always
2232  * return %NULL unless @connection acted as a server
2233  * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
2234  * when set up and the client passed credentials as part of the
2235  * authentication process.
2236  *
2237  * In a message bus setup, the message bus is always the server and
2238  * each application is a client. So this method will always return
2239  * %NULL for message bus clients.
2240  *
2241  * Returns: A #GCredentials or %NULL if not available. Do not free
2242  * this object, it is owned by @connection.
2243  *
2244  * Since: 2.26
2245  */
2246 GCredentials *
2247 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
2248 {
2249   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2250   return connection->priv->crendentials;
2251 }
2252
2253 /* ---------------------------------------------------------------------------------------------------- */
2254
2255 static guint _global_filter_id = 1;
2256
2257 /**
2258  * g_dbus_connection_add_filter:
2259  * @connection: A #GDBusConnection.
2260  * @filter_function: A filter function.
2261  * @user_data: User data to pass to @filter_function.
2262  * @user_data_free_func: Function to free @user_data with when filter
2263  * is removed or %NULL.
2264  *
2265  * Adds a message filter. Filters are handlers that are run on all
2266  * incoming messages, prior to standard dispatch. Filters are run in
2267  * the order that they were added.  The same handler can be added as a
2268  * filter more than once, in which case it will be run more than once.
2269  * Filters added during a filter callback won't be run on the message
2270  * being processed.
2271  *
2272  * Note that filters are run in a dedicated message handling thread so
2273  * they can't block and, generally, can't do anything but signal a
2274  * worker thread. Also note that filters are rarely needed - use API
2275  * such as g_dbus_connection_send_message_with_reply(),
2276  * g_dbus_connection_signal_subscribe() or
2277  * g_dbus_connection_call() instead.
2278  *
2279  * Returns: A filter identifier that can be used with
2280  * g_dbus_connection_remove_filter().
2281  *
2282  * Since: 2.26
2283  */
2284 guint
2285 g_dbus_connection_add_filter (GDBusConnection            *connection,
2286                               GDBusMessageFilterFunction  filter_function,
2287                               gpointer                    user_data,
2288                               GDestroyNotify              user_data_free_func)
2289 {
2290   FilterData *data;
2291
2292   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2293   g_return_val_if_fail (filter_function != NULL, 0);
2294
2295   CONNECTION_LOCK (connection);
2296   data = g_new0 (FilterData, 1);
2297   data->id = _global_filter_id++; /* TODO: overflow etc. */
2298   data->filter_function = filter_function;
2299   data->user_data = user_data;
2300   data->user_data_free_func = user_data_free_func;
2301   g_ptr_array_add (connection->priv->filters, data);
2302   CONNECTION_UNLOCK (connection);
2303
2304   return data->id;
2305 }
2306
2307 /* only called from finalize(), removes all filters */
2308 static void
2309 purge_all_filters (GDBusConnection *connection)
2310 {
2311   guint n;
2312   for (n = 0; n < connection->priv->filters->len; n++)
2313     {
2314       FilterData *data = connection->priv->filters->pdata[n];
2315       if (data->user_data_free_func != NULL)
2316         data->user_data_free_func (data->user_data);
2317       g_free (data);
2318     }
2319 }
2320
2321 void
2322 g_dbus_connection_remove_filter (GDBusConnection *connection,
2323                                  guint            filter_id)
2324 {
2325   guint n;
2326   FilterData *to_destroy;
2327
2328   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2329
2330   CONNECTION_LOCK (connection);
2331   to_destroy = NULL;
2332   for (n = 0; n < connection->priv->filters->len; n++)
2333     {
2334       FilterData *data = connection->priv->filters->pdata[n];
2335       if (data->id == filter_id)
2336         {
2337           g_ptr_array_remove_index (connection->priv->filters, n);
2338           to_destroy = data;
2339           break;
2340         }
2341     }
2342   CONNECTION_UNLOCK (connection);
2343
2344   /* do free without holding lock */
2345   if (to_destroy != NULL)
2346     {
2347       if (to_destroy->user_data_free_func != NULL)
2348         to_destroy->user_data_free_func (to_destroy->user_data);
2349       g_free (to_destroy);
2350     }
2351   else
2352     {
2353       g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
2354     }
2355 }
2356
2357 /* ---------------------------------------------------------------------------------------------------- */
2358
2359 typedef struct
2360 {
2361   gchar *rule;
2362   gchar *sender;
2363   gchar *interface_name;
2364   gchar *member;
2365   gchar *object_path;
2366   gchar *arg0;
2367   GArray *subscribers;
2368 } SignalData;
2369
2370 typedef struct
2371 {
2372   GDBusSignalCallback callback;
2373   gpointer user_data;
2374   GDestroyNotify user_data_free_func;
2375   guint id;
2376   GMainContext *context;
2377 } SignalSubscriber;
2378
2379 static void
2380 signal_data_free (SignalData *data)
2381 {
2382   g_free (data->rule);
2383   g_free (data->sender);
2384   g_free (data->interface_name);
2385   g_free (data->member);
2386   g_free (data->object_path);
2387   g_free (data->arg0);
2388   g_array_free (data->subscribers, TRUE);
2389   g_free (data);
2390 }
2391
2392 static gchar *
2393 args_to_rule (const gchar *sender,
2394               const gchar *interface_name,
2395               const gchar *member,
2396               const gchar *object_path,
2397               const gchar *arg0)
2398 {
2399   GString *rule;
2400
2401   rule = g_string_new ("type='signal'");
2402   if (sender != NULL)
2403     g_string_append_printf (rule, ",sender='%s'", sender);
2404   if (interface_name != NULL)
2405     g_string_append_printf (rule, ",interface='%s'", interface_name);
2406   if (member != NULL)
2407     g_string_append_printf (rule, ",member='%s'", member);
2408   if (object_path != NULL)
2409     g_string_append_printf (rule, ",path='%s'", object_path);
2410   if (arg0 != NULL)
2411     g_string_append_printf (rule, ",arg0='%s'", arg0);
2412
2413   return g_string_free (rule, FALSE);
2414 }
2415
2416 static guint _global_subscriber_id = 1;
2417 static guint _global_registration_id = 1;
2418 static guint _global_subtree_registration_id = 1;
2419
2420 /* ---------------------------------------------------------------------------------------------------- */
2421
2422 /* must hold lock when calling */
2423 static void
2424 add_match_rule (GDBusConnection *connection,
2425                 const gchar     *match_rule)
2426 {
2427   GError *error;
2428   GDBusMessage *message;
2429
2430   message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2431                                             "/org/freedesktop/DBus", /* path */
2432                                             "org.freedesktop.DBus", /* interface */
2433                                             "AddMatch");
2434   g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2435
2436   error = NULL;
2437   if (!g_dbus_connection_send_message_unlocked (connection,
2438                                                 message,
2439                                                 NULL,
2440                                                 &error))
2441     {
2442       g_critical ("Error while sending AddMatch() message: %s", error->message);
2443       g_error_free (error);
2444     }
2445   g_object_unref (message);
2446 }
2447
2448 /* ---------------------------------------------------------------------------------------------------- */
2449
2450 /* must hold lock when calling */
2451 static void
2452 remove_match_rule (GDBusConnection *connection,
2453                    const gchar     *match_rule)
2454 {
2455   GError *error;
2456   GDBusMessage *message;
2457
2458   message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2459                                             "/org/freedesktop/DBus", /* path */
2460                                             "org.freedesktop.DBus", /* interface */
2461                                             "RemoveMatch");
2462   g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2463
2464   error = NULL;
2465   if (!g_dbus_connection_send_message_unlocked (connection,
2466                                                 message,
2467                                                 NULL,
2468                                                 &error))
2469     {
2470       g_critical ("Error while sending RemoveMatch() message: %s", error->message);
2471       g_error_free (error);
2472     }
2473   g_object_unref (message);
2474 }
2475
2476 /* ---------------------------------------------------------------------------------------------------- */
2477
2478 static gboolean
2479 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
2480 {
2481   return g_strcmp0 (signal_data->sender, "org.freedesktop.DBus") == 0 &&
2482          g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
2483          g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
2484          (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
2485           g_strcmp0 (signal_data->member, "NameAcquired") == 0);
2486 }
2487
2488 /* ---------------------------------------------------------------------------------------------------- */
2489
2490 /**
2491  * g_dbus_connection_signal_subscribe:
2492  * @connection: A #GDBusConnection.
2493  * @sender: Sender name to match on. Must be either <literal>org.freedesktop.DBus</literal> (for listening to signals from the message bus daemon) or a unique name or %NULL to listen from all senders.
2494  * @interface_name: D-Bus interface name to match on or %NULL to match on all interfaces.
2495  * @member: D-Bus signal name to match on or %NULL to match on all signals.
2496  * @object_path: Object path to match on or %NULL to match on all object paths.
2497  * @arg0: Contents of first string argument to match on or %NULL to match on all kinds of arguments.
2498  * @callback: Callback to invoke when there is a signal matching the requested data.
2499  * @user_data: User data to pass to @callback.
2500  * @user_data_free_func: Function to free @user_data with when subscription is removed or %NULL.
2501  *
2502  * Subscribes to signals on @connection and invokes @callback with a
2503  * whenever the signal is received. Note that @callback
2504  * will be invoked in the <link
2505  * linkend="g-main-context-push-thread-default">thread-default main
2506  * loop</link> of the thread you are calling this method from.
2507  *
2508  * It is considered a programming error to use this function if @connection is closed.
2509  *
2510  * Note that if @sender is not <literal>org.freedesktop.DBus</literal> (for listening to signals from the
2511  * message bus daemon), then it needs to be a unique bus name or %NULL (for listening to signals from any
2512  * name) - you cannot pass a name like <literal>com.example.MyApp</literal>.
2513  * Use e.g. g_bus_watch_name() to find the unique name for the owner of the name you are interested in. Also note
2514  * that this function does not remove a subscription if @sender vanishes from the bus. You have to manually
2515  * call g_dbus_connection_signal_unsubscribe() to remove a subscription.
2516  *
2517  * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
2518  *
2519  * Since: 2.26
2520  */
2521 guint
2522 g_dbus_connection_signal_subscribe (GDBusConnection     *connection,
2523                                     const gchar         *sender,
2524                                     const gchar         *interface_name,
2525                                     const gchar         *member,
2526                                     const gchar         *object_path,
2527                                     const gchar         *arg0,
2528                                     GDBusSignalCallback  callback,
2529                                     gpointer             user_data,
2530                                     GDestroyNotify       user_data_free_func)
2531 {
2532   gchar *rule;
2533   SignalData *signal_data;
2534   SignalSubscriber subscriber;
2535   GPtrArray *signal_data_array;
2536
2537   /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
2538    * an OOM condition. We might want to change that but that would involve making
2539    * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
2540    * handle that. And there's really no sensible way of handling this short of retrying
2541    * to add the match rule... and then there's the little thing that, hey, maybe there's
2542    * a reason the bus in an OOM condition.
2543    *
2544    * Doable, but not really sure it's worth it...
2545    */
2546
2547   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2548   g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
2549   g_return_val_if_fail (sender == NULL || ((strcmp (sender, "org.freedesktop.DBus") == 0 || sender[0] == ':') &&
2550                                            (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
2551   g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
2552   g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
2553   g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
2554   g_return_val_if_fail (callback != NULL, 0);
2555
2556   CONNECTION_LOCK (connection);
2557
2558   rule = args_to_rule (sender, interface_name, member, object_path, arg0);
2559
2560   if (sender == NULL)
2561     sender = "";
2562
2563   subscriber.callback = callback;
2564   subscriber.user_data = user_data;
2565   subscriber.user_data_free_func = user_data_free_func;
2566   subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
2567   subscriber.context = g_main_context_get_thread_default ();
2568   if (subscriber.context != NULL)
2569     g_main_context_ref (subscriber.context);
2570
2571   /* see if we've already have this rule */
2572   signal_data = g_hash_table_lookup (connection->priv->map_rule_to_signal_data, rule);
2573   if (signal_data != NULL)
2574     {
2575       g_array_append_val (signal_data->subscribers, subscriber);
2576       g_free (rule);
2577       goto out;
2578     }
2579
2580   signal_data = g_new0 (SignalData, 1);
2581   signal_data->rule           = rule;
2582   signal_data->sender         = g_strdup (sender);
2583   signal_data->interface_name = g_strdup (interface_name);
2584   signal_data->member         = g_strdup (member);
2585   signal_data->object_path    = g_strdup (object_path);
2586   signal_data->arg0           = g_strdup (arg0);
2587   signal_data->subscribers    = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2588   g_array_append_val (signal_data->subscribers, subscriber);
2589
2590   g_hash_table_insert (connection->priv->map_rule_to_signal_data,
2591                        signal_data->rule,
2592                        signal_data);
2593
2594   /* Add the match rule to the bus...
2595    *
2596    * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
2597    * always send such messages to us.
2598    */
2599   if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2600     {
2601       if (!is_signal_data_for_name_lost_or_acquired (signal_data))
2602         add_match_rule (connection, signal_data->rule);
2603     }
2604
2605  out:
2606   g_hash_table_insert (connection->priv->map_id_to_signal_data,
2607                        GUINT_TO_POINTER (subscriber.id),
2608                        signal_data);
2609
2610   signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array,
2611                                            signal_data->sender);
2612   if (signal_data_array == NULL)
2613     {
2614       signal_data_array = g_ptr_array_new ();
2615       g_hash_table_insert (connection->priv->map_sender_to_signal_data_array,
2616                            g_strdup (signal_data->sender),
2617                            signal_data_array);
2618     }
2619   g_ptr_array_add (signal_data_array, signal_data);
2620
2621   CONNECTION_UNLOCK (connection);
2622
2623   return subscriber.id;
2624 }
2625
2626 /* ---------------------------------------------------------------------------------------------------- */
2627
2628 /* must hold lock when calling this */
2629 static void
2630 unsubscribe_id_internal (GDBusConnection *connection,
2631                          guint            subscription_id,
2632                          GArray          *out_removed_subscribers)
2633 {
2634   SignalData *signal_data;
2635   GPtrArray *signal_data_array;
2636   guint n;
2637
2638   signal_data = g_hash_table_lookup (connection->priv->map_id_to_signal_data,
2639                                      GUINT_TO_POINTER (subscription_id));
2640   if (signal_data == NULL)
2641     {
2642       /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
2643       goto out;
2644     }
2645
2646   for (n = 0; n < signal_data->subscribers->len; n++)
2647     {
2648       SignalSubscriber *subscriber;
2649
2650       subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
2651       if (subscriber->id != subscription_id)
2652         continue;
2653
2654       g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_signal_data,
2655                                            GUINT_TO_POINTER (subscription_id)));
2656       g_array_append_val (out_removed_subscribers, *subscriber);
2657       g_array_remove_index (signal_data->subscribers, n);
2658
2659       if (signal_data->subscribers->len == 0)
2660         g_warn_if_fail (g_hash_table_remove (connection->priv->map_rule_to_signal_data, signal_data->rule));
2661
2662       signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array,
2663                                                signal_data->sender);
2664       g_warn_if_fail (signal_data_array != NULL);
2665       g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
2666
2667       if (signal_data_array->len == 0)
2668         {
2669           g_warn_if_fail (g_hash_table_remove (connection->priv->map_sender_to_signal_data_array, signal_data->sender));
2670
2671           /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
2672           if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2673             {
2674               if (!is_signal_data_for_name_lost_or_acquired (signal_data))
2675                 remove_match_rule (connection, signal_data->rule);
2676             }
2677
2678           signal_data_free (signal_data);
2679         }
2680
2681       goto out;
2682     }
2683
2684   g_assert_not_reached ();
2685
2686  out:
2687   ;
2688 }
2689
2690 /**
2691  * g_dbus_connection_signal_unsubscribe:
2692  * @connection: A #GDBusConnection.
2693  * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
2694  *
2695  * Unsubscribes from signals.
2696  *
2697  * Since: 2.26
2698  */
2699 void
2700 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
2701                                       guint            subscription_id)
2702 {
2703   GArray *subscribers;
2704   guint n;
2705
2706   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2707
2708   subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2709
2710   CONNECTION_LOCK (connection);
2711   unsubscribe_id_internal (connection,
2712                            subscription_id,
2713                            subscribers);
2714   CONNECTION_UNLOCK (connection);
2715
2716   /* invariant */
2717   g_assert (subscribers->len == 0 || subscribers->len == 1);
2718
2719   /* call GDestroyNotify without lock held */
2720   for (n = 0; n < subscribers->len; n++)
2721     {
2722       SignalSubscriber *subscriber;
2723       subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
2724       if (subscriber->user_data_free_func != NULL)
2725         subscriber->user_data_free_func (subscriber->user_data);
2726       if (subscriber->context != NULL)
2727         g_main_context_unref (subscriber->context);
2728     }
2729
2730   g_array_free (subscribers, TRUE);
2731 }
2732
2733 /* ---------------------------------------------------------------------------------------------------- */
2734
2735 typedef struct
2736 {
2737   guint                subscription_id;
2738   GDBusSignalCallback  callback;
2739   gpointer             user_data;
2740   GDBusMessage        *message;
2741   GDBusConnection     *connection;
2742   const gchar         *sender;
2743   const gchar         *path;
2744   const gchar         *interface;
2745   const gchar         *member;
2746 } SignalInstance;
2747
2748 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
2749  * no locks held
2750  */
2751 static gboolean
2752 emit_signal_instance_in_idle_cb (gpointer data)
2753 {
2754   SignalInstance *signal_instance = data;
2755   GVariant *parameters;
2756   gboolean has_subscription;
2757
2758   parameters = g_dbus_message_get_body (signal_instance->message);
2759   if (parameters == NULL)
2760     {
2761       parameters = g_variant_new ("()");
2762       g_variant_ref_sink (parameters);
2763     }
2764   else
2765     {
2766       g_variant_ref_sink (parameters);
2767     }
2768
2769 #if 0
2770   g_debug ("in emit_signal_instance_in_idle_cb (sender=%s path=%s interface=%s member=%s params=%s)",
2771            signal_instance->sender,
2772            signal_instance->path,
2773            signal_instance->interface,
2774            signal_instance->member,
2775            g_variant_print (parameters, TRUE));
2776 #endif
2777
2778   /* Careful here, don't do the callback if we no longer has the subscription */
2779   CONNECTION_LOCK (signal_instance->connection);
2780   has_subscription = FALSE;
2781   if (g_hash_table_lookup (signal_instance->connection->priv->map_id_to_signal_data,
2782                            GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
2783     has_subscription = TRUE;
2784   CONNECTION_UNLOCK (signal_instance->connection);
2785
2786   if (has_subscription)
2787     signal_instance->callback (signal_instance->connection,
2788                                signal_instance->sender,
2789                                signal_instance->path,
2790                                signal_instance->interface,
2791                                signal_instance->member,
2792                                parameters,
2793                                signal_instance->user_data);
2794
2795   if (parameters != NULL)
2796     g_variant_unref (parameters);
2797
2798   return FALSE;
2799 }
2800
2801 static void
2802 signal_instance_free (SignalInstance *signal_instance)
2803 {
2804   g_object_unref (signal_instance->message);
2805   g_object_unref (signal_instance->connection);
2806   g_free (signal_instance);
2807 }
2808
2809 /* called in message handler thread WITH lock held */
2810 static void
2811 schedule_callbacks (GDBusConnection *connection,
2812                     GPtrArray       *signal_data_array,
2813                     GDBusMessage    *message,
2814                     const gchar     *sender)
2815 {
2816   guint n, m;
2817   const gchar *interface;
2818   const gchar *member;
2819   const gchar *path;
2820   const gchar *arg0;
2821
2822   interface = NULL;
2823   member = NULL;
2824   path = NULL;
2825   arg0 = NULL;
2826
2827   interface = g_dbus_message_get_interface (message);
2828   member = g_dbus_message_get_member (message);
2829   path = g_dbus_message_get_path (message);
2830   arg0 = g_dbus_message_get_arg0 (message);
2831
2832 #if 0
2833   g_debug ("sender    = `%s'", sender);
2834   g_debug ("interface = `%s'", interface);
2835   g_debug ("member    = `%s'", member);
2836   g_debug ("path      = `%s'", path);
2837   g_debug ("arg0      = `%s'", arg0);
2838 #endif
2839
2840   /* TODO: if this is slow, then we can change signal_data_array into
2841    *       map_object_path_to_signal_data_array or something.
2842    */
2843   for (n = 0; n < signal_data_array->len; n++)
2844     {
2845       SignalData *signal_data = signal_data_array->pdata[n];
2846
2847       if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
2848         continue;
2849
2850       if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
2851         continue;
2852
2853       if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
2854         continue;
2855
2856       if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
2857         continue;
2858
2859       for (m = 0; m < signal_data->subscribers->len; m++)
2860         {
2861           SignalSubscriber *subscriber;
2862           GSource *idle_source;
2863           SignalInstance *signal_instance;
2864
2865           subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
2866
2867           signal_instance = g_new0 (SignalInstance, 1);
2868           signal_instance->subscription_id = subscriber->id;
2869           signal_instance->callback = subscriber->callback;
2870           signal_instance->user_data = subscriber->user_data;
2871           signal_instance->message = g_object_ref (message);
2872           signal_instance->connection = g_object_ref (connection);
2873           signal_instance->sender = sender;
2874           signal_instance->path = path;
2875           signal_instance->interface = interface;
2876           signal_instance->member = member;
2877
2878           idle_source = g_idle_source_new ();
2879           g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
2880           g_source_set_callback (idle_source,
2881                                  emit_signal_instance_in_idle_cb,
2882                                  signal_instance,
2883                                  (GDestroyNotify) signal_instance_free);
2884           g_source_attach (idle_source, subscriber->context);
2885           g_source_unref (idle_source);
2886         }
2887     }
2888 }
2889
2890 /* called in message handler thread with lock held */
2891 static void
2892 distribute_signals (GDBusConnection *connection,
2893                     GDBusMessage    *message)
2894 {
2895   GPtrArray *signal_data_array;
2896   const gchar *sender;
2897
2898   sender = g_dbus_message_get_sender (message);
2899
2900   /* collect subscribers that match on sender */
2901   if (sender != NULL)
2902     {
2903       signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array, sender);
2904       if (signal_data_array != NULL)
2905         schedule_callbacks (connection, signal_data_array, message, sender);
2906     }
2907
2908   /* collect subscribers not matching on sender */
2909   signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array, "");
2910   if (signal_data_array != NULL)
2911     schedule_callbacks (connection, signal_data_array, message, sender);
2912 }
2913
2914 /* ---------------------------------------------------------------------------------------------------- */
2915
2916 /* only called from finalize(), removes all subscriptions */
2917 static void
2918 purge_all_signal_subscriptions (GDBusConnection *connection)
2919 {
2920   GHashTableIter iter;
2921   gpointer key;
2922   GArray *ids;
2923   GArray *subscribers;
2924   guint n;
2925
2926   ids = g_array_new (FALSE, FALSE, sizeof (guint));
2927   g_hash_table_iter_init (&iter, connection->priv->map_id_to_signal_data);
2928   while (g_hash_table_iter_next (&iter, &key, NULL))
2929     {
2930       guint subscription_id = GPOINTER_TO_UINT (key);
2931       g_array_append_val (ids, subscription_id);
2932     }
2933
2934   subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2935   for (n = 0; n < ids->len; n++)
2936     {
2937       guint subscription_id = g_array_index (ids, guint, n);
2938       unsubscribe_id_internal (connection,
2939                                subscription_id,
2940                                subscribers);
2941     }
2942   g_array_free (ids, TRUE);
2943
2944   /* call GDestroyNotify without lock held */
2945   for (n = 0; n < subscribers->len; n++)
2946     {
2947       SignalSubscriber *subscriber;
2948       subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
2949       if (subscriber->user_data_free_func != NULL)
2950         subscriber->user_data_free_func (subscriber->user_data);
2951       if (subscriber->context != NULL)
2952         g_main_context_unref (subscriber->context);
2953     }
2954
2955   g_array_free (subscribers, TRUE);
2956 }
2957
2958 /* ---------------------------------------------------------------------------------------------------- */
2959
2960 struct ExportedObject
2961 {
2962   gchar *object_path;
2963   GDBusConnection *connection;
2964
2965   /* maps gchar* -> ExportedInterface* */
2966   GHashTable *map_if_name_to_ei;
2967 };
2968
2969 /* only called with lock held */
2970 static void
2971 exported_object_free (ExportedObject *eo)
2972 {
2973   g_free (eo->object_path);
2974   g_hash_table_unref (eo->map_if_name_to_ei);
2975   g_free (eo);
2976 }
2977
2978 typedef struct
2979 {
2980   ExportedObject *eo;
2981
2982   guint                       id;
2983   gchar                      *interface_name;
2984   const GDBusInterfaceVTable *vtable;
2985   const GDBusInterfaceInfo   *introspection_data;
2986
2987   GMainContext               *context;
2988   gpointer                    user_data;
2989   GDestroyNotify              user_data_free_func;
2990 } ExportedInterface;
2991
2992 /* called with lock held */
2993 static void
2994 exported_interface_free (ExportedInterface *ei)
2995 {
2996   if (ei->user_data_free_func != NULL)
2997     /* TODO: push to thread-default mainloop */
2998     ei->user_data_free_func (ei->user_data);
2999
3000   if (ei->context != NULL)
3001     g_main_context_unref (ei->context);
3002
3003   g_free (ei->interface_name);
3004   g_free (ei);
3005 }
3006
3007 /* ---------------------------------------------------------------------------------------------------- */
3008
3009 typedef struct
3010 {
3011   GDBusConnection *connection;
3012   GDBusMessage *message;
3013   gpointer user_data;
3014   const char *property_name;
3015   const GDBusInterfaceVTable *vtable;
3016   const GDBusInterfaceInfo *interface_info;
3017   const GDBusPropertyInfo *property_info;
3018 } PropertyData;
3019
3020 static void
3021 property_data_free (PropertyData *data)
3022 {
3023   g_object_unref (data->connection);
3024   g_object_unref (data->message);
3025   g_free (data);
3026 }
3027
3028 /* called in thread where object was registered - no locks held */
3029 static gboolean
3030 invoke_get_property_in_idle_cb (gpointer _data)
3031 {
3032   PropertyData *data = _data;
3033   GVariant *value;
3034   GError *error;
3035   GDBusMessage *reply;
3036
3037   error = NULL;
3038   value = data->vtable->get_property (data->connection,
3039                                       g_dbus_message_get_sender (data->message),
3040                                       g_dbus_message_get_path (data->message),
3041                                       data->interface_info->name,
3042                                       data->property_name,
3043                                       &error,
3044                                       data->user_data);
3045
3046
3047   if (value != NULL)
3048     {
3049       g_assert_no_error (error);
3050
3051       g_variant_ref_sink (value);
3052       reply = g_dbus_message_new_method_reply (data->message);
3053       g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
3054       g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3055       g_variant_unref (value);
3056       g_object_unref (reply);
3057     }
3058   else
3059     {
3060       gchar *dbus_error_name;
3061
3062       g_assert (error != NULL);
3063
3064       dbus_error_name = g_dbus_error_encode_gerror (error);
3065       reply = g_dbus_message_new_method_error_literal (data->message,
3066                                                        dbus_error_name,
3067                                                        error->message);
3068       g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3069       g_free (dbus_error_name);
3070       g_error_free (error);
3071       g_object_unref (reply);
3072     }
3073
3074   return FALSE;
3075 }
3076
3077 /* called in thread where object was registered - no locks held */
3078 static gboolean
3079 invoke_set_property_in_idle_cb (gpointer _data)
3080 {
3081   PropertyData *data = _data;
3082   GError *error;
3083   GDBusMessage *reply;
3084   GVariant *value;
3085
3086   error = NULL;
3087   value = NULL;
3088
3089   g_variant_get (g_dbus_message_get_body (data->message),
3090                  "(ssv)",
3091                  NULL,
3092                  NULL,
3093                  &value);
3094
3095   /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
3096    * of the given value is wrong
3097    */
3098   if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
3099     {
3100       reply = g_dbus_message_new_method_error (data->message,
3101                                                "org.freedesktop.DBus.Error.InvalidArgs",
3102                                                _("Error setting property `%s': Expected type `%s' but got `%s'"),
3103                                                data->property_info->name,
3104                                                data->property_info->signature,
3105                                                g_variant_get_type_string (value));
3106       goto out;
3107     }
3108
3109   if (!data->vtable->set_property (data->connection,
3110                                    g_dbus_message_get_sender (data->message),
3111                                    g_dbus_message_get_path (data->message),
3112                                    data->interface_info->name,
3113                                    data->property_name,
3114                                    value,
3115                                    &error,
3116                                    data->user_data))
3117     {
3118       gchar *dbus_error_name;
3119       g_assert (error != NULL);
3120       dbus_error_name = g_dbus_error_encode_gerror (error);
3121       reply = g_dbus_message_new_method_error_literal (data->message,
3122                                                        dbus_error_name,
3123                                                        error->message);
3124       g_free (dbus_error_name);
3125       g_error_free (error);
3126     }
3127   else
3128     {
3129       reply = g_dbus_message_new_method_reply (data->message);
3130     }
3131
3132  out:
3133   g_assert (reply != NULL);
3134   g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3135   g_object_unref (reply);
3136
3137   return FALSE;
3138 }
3139
3140 /* called with lock held */
3141 static gboolean
3142 validate_and_maybe_schedule_property_getset (GDBusConnection            *connection,
3143                                              GDBusMessage               *message,
3144                                              gboolean                    is_get,
3145                                              const GDBusInterfaceInfo   *introspection_data,
3146                                              const GDBusInterfaceVTable *vtable,
3147                                              GMainContext               *main_context,
3148                                              gpointer                    user_data)
3149 {
3150   gboolean handled;
3151   const char *interface_name;
3152   const char *property_name;
3153   const GDBusPropertyInfo *property_info;
3154   GSource *idle_source;
3155   PropertyData *property_data;
3156   GDBusMessage *reply;
3157
3158   handled = FALSE;
3159
3160   if (is_get)
3161     g_variant_get (g_dbus_message_get_body (message),
3162                    "(ss)",
3163                    &interface_name,
3164                    &property_name);
3165   else
3166     g_variant_get (g_dbus_message_get_body (message),
3167                    "(ssv)",
3168                    &interface_name,
3169                    &property_name,
3170                    NULL);
3171
3172
3173   if (is_get)
3174     {
3175       if (vtable == NULL || vtable->get_property == NULL)
3176         goto out;
3177     }
3178   else
3179     {
3180       if (vtable == NULL || vtable->set_property == NULL)
3181         goto out;
3182     }
3183
3184   /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
3185    */
3186   property_info = NULL;
3187
3188   /* TODO: the cost of this is O(n) - it might be worth caching the result */
3189   property_info = g_dbus_interface_info_lookup_property (introspection_data, property_name);
3190   if (property_info == NULL)
3191     {
3192       reply = g_dbus_message_new_method_error (message,
3193                                                "org.freedesktop.DBus.Error.InvalidArgs",
3194                                                _("No such property `%s'"),
3195                                                property_name);
3196       g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3197       g_object_unref (reply);
3198       handled = TRUE;
3199       goto out;
3200     }
3201
3202   if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3203     {
3204       reply = g_dbus_message_new_method_error (message,
3205                                                "org.freedesktop.DBus.Error.InvalidArgs",
3206                                                _("Property `%s' is not readable"),
3207                                                property_name);
3208       g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3209       g_object_unref (reply);
3210       handled = TRUE;
3211       goto out;
3212     }
3213   else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
3214     {
3215       reply = g_dbus_message_new_method_error (message,
3216                                                "org.freedesktop.DBus.Error.InvalidArgs",
3217                                                _("Property `%s' is not writable"),
3218                                                property_name);
3219       g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3220       g_object_unref (reply);
3221       handled = TRUE;
3222       goto out;
3223     }
3224
3225   /* ok, got the property info - call user code in an idle handler */
3226   property_data = g_new0 (PropertyData, 1);
3227   property_data->connection = g_object_ref (connection);
3228   property_data->message = g_object_ref (message);
3229   property_data->user_data = user_data;
3230   property_data->property_name = property_name;
3231   property_data->vtable = vtable;
3232   property_data->interface_info = introspection_data;
3233   property_data->property_info = property_info;
3234
3235   idle_source = g_idle_source_new ();
3236   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3237   g_source_set_callback (idle_source,
3238                          is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
3239                          property_data,
3240                          (GDestroyNotify) property_data_free);
3241   g_source_attach (idle_source, main_context);
3242   g_source_unref (idle_source);
3243
3244   handled = TRUE;
3245
3246  out:
3247   return handled;
3248 }
3249
3250 /* called with lock held */
3251 static gboolean
3252 handle_getset_property (GDBusConnection *connection,
3253                         ExportedObject  *eo,
3254                         GDBusMessage    *message,
3255                         gboolean         is_get)
3256 {
3257   ExportedInterface *ei;
3258   gboolean handled;
3259   const char *interface_name;
3260   const char *property_name;
3261
3262   handled = FALSE;
3263
3264   if (is_get)
3265     g_variant_get (g_dbus_message_get_body (message),
3266                    "(ss)",
3267                    &interface_name,
3268                    &property_name);
3269   else
3270     g_variant_get (g_dbus_message_get_body (message),
3271                    "(ssv)",
3272                    &interface_name,
3273                    &property_name,
3274                    NULL);
3275
3276   /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3277    * no such interface registered
3278    */
3279   ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3280   if (ei == NULL)
3281     {
3282       GDBusMessage *reply;
3283       reply = g_dbus_message_new_method_error (message,
3284                                                "org.freedesktop.DBus.Error.InvalidArgs",
3285                                                _("No such interface `%s'"),
3286                                                interface_name);
3287       g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3288       g_object_unref (reply);
3289       handled = TRUE;
3290       goto out;
3291     }
3292
3293   handled = validate_and_maybe_schedule_property_getset (eo->connection,
3294                                                          message,
3295                                                          is_get,
3296                                                          ei->introspection_data,
3297                                                          ei->vtable,
3298                                                          ei->context,
3299                                                          ei->user_data);
3300  out:
3301   return handled;
3302 }
3303
3304 /* ---------------------------------------------------------------------------------------------------- */
3305
3306 typedef struct
3307 {
3308   GDBusConnection *connection;
3309   GDBusMessage *message;
3310   gpointer user_data;
3311   const GDBusInterfaceVTable *vtable;
3312   const GDBusInterfaceInfo *interface_info;
3313 } PropertyGetAllData;
3314
3315 static void
3316 property_get_all_data_free (PropertyData *data)
3317 {
3318   g_object_unref (data->connection);
3319   g_object_unref (data->message);
3320   g_free (data);
3321 }
3322
3323 /* called in thread where object was registered - no locks held */
3324 static gboolean
3325 invoke_get_all_properties_in_idle_cb (gpointer _data)
3326 {
3327   PropertyGetAllData *data = _data;
3328   GVariantBuilder *builder;
3329   GVariant *packed;
3330   GVariant *result;
3331   GError *error;
3332   GDBusMessage *reply;
3333   guint n;
3334
3335   error = NULL;
3336
3337   /* TODO: Right now we never fail this call - we just omit values if
3338    *       a get_property() call is failing.
3339    *
3340    *       We could fail the whole call if just a single get_property() call
3341    *       returns an error. We need clarification in the D-Bus spec about this.
3342    */
3343   builder = g_variant_builder_new (G_VARIANT_TYPE_ARRAY);
3344   for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
3345     {
3346       const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
3347       GVariant *value;
3348
3349       if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3350         continue;
3351
3352       value = data->vtable->get_property (data->connection,
3353                                           g_dbus_message_get_sender (data->message),
3354                                           g_dbus_message_get_path (data->message),
3355                                           data->interface_info->name,
3356                                           property_info->name,
3357                                           NULL,
3358                                           data->user_data);
3359
3360       if (value == NULL)
3361         continue;
3362
3363       g_variant_ref_sink (value);
3364       g_variant_builder_add (builder,
3365                              "{sv}",
3366                              property_info->name,
3367                              value);
3368       g_variant_unref (value);
3369     }
3370   result = g_variant_builder_end (builder);
3371
3372   builder = g_variant_builder_new (G_VARIANT_TYPE_TUPLE);
3373   g_variant_builder_add_value (builder, result); /* steals result since result is floating */
3374   packed = g_variant_builder_end (builder);
3375
3376   reply = g_dbus_message_new_method_reply (data->message);
3377   g_dbus_message_set_body (reply, packed);
3378   g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3379   g_object_unref (reply);
3380
3381   return FALSE;
3382 }
3383
3384 /* called with lock held */
3385 static gboolean
3386 validate_and_maybe_schedule_property_get_all (GDBusConnection            *connection,
3387                                               GDBusMessage               *message,
3388                                               const GDBusInterfaceInfo   *introspection_data,
3389                                               const GDBusInterfaceVTable *vtable,
3390                                               GMainContext               *main_context,
3391                                               gpointer                    user_data)
3392 {
3393   gboolean handled;
3394   const char *interface_name;
3395   GSource *idle_source;
3396   PropertyGetAllData *property_get_all_data;
3397
3398   handled = FALSE;
3399
3400   g_variant_get (g_dbus_message_get_body (message),
3401                  "(s)",
3402                  &interface_name);
3403
3404   if (vtable == NULL || vtable->get_property == NULL)
3405     goto out;
3406
3407   /* ok, got the property info - call user in an idle handler */
3408   property_get_all_data = g_new0 (PropertyGetAllData, 1);
3409   property_get_all_data->connection = g_object_ref (connection);
3410   property_get_all_data->message = g_object_ref (message);
3411   property_get_all_data->user_data = user_data;
3412   property_get_all_data->vtable = vtable;
3413   property_get_all_data->interface_info = introspection_data;
3414
3415   idle_source = g_idle_source_new ();
3416   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3417   g_source_set_callback (idle_source,
3418                          invoke_get_all_properties_in_idle_cb,
3419                          property_get_all_data,
3420                          (GDestroyNotify) property_get_all_data_free);
3421   g_source_attach (idle_source, main_context);
3422   g_source_unref (idle_source);
3423
3424   handled = TRUE;
3425
3426  out:
3427   return handled;
3428 }
3429
3430 /* called with lock held */
3431 static gboolean
3432 handle_get_all_properties (GDBusConnection *connection,
3433                            ExportedObject  *eo,
3434                            GDBusMessage    *message)
3435 {
3436   ExportedInterface *ei;
3437   gboolean handled;
3438   const char *interface_name;
3439
3440   handled = FALSE;
3441
3442   g_variant_get (g_dbus_message_get_body (message),
3443                  "(s)",
3444                  &interface_name);
3445
3446   /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3447    * no such interface registered
3448    */
3449   ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3450   if (ei == NULL)
3451     {
3452       GDBusMessage *reply;
3453       reply = g_dbus_message_new_method_error (message,
3454                                                "org.freedesktop.DBus.Error.InvalidArgs",
3455                                                _("No such interface"),
3456                                                interface_name);
3457       g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3458       g_object_unref (reply);
3459       handled = TRUE;
3460       goto out;
3461     }
3462
3463   handled = validate_and_maybe_schedule_property_get_all (eo->connection,
3464                                                           message,
3465                                                           ei->introspection_data,
3466                                                           ei->vtable,
3467                                                           ei->context,
3468                                                           ei->user_data);
3469  out:
3470   return handled;
3471 }
3472
3473 /* ---------------------------------------------------------------------------------------------------- */
3474
3475 static const gchar introspect_header[] =
3476   "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
3477   "                      \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
3478   "<!-- GDBus " PACKAGE_VERSION " -->\n"
3479   "<node>\n";
3480
3481 static const gchar introspect_tail[] =
3482   "</node>\n";
3483
3484 static const gchar introspect_standard_interfaces[] =
3485   "  <interface name=\"org.freedesktop.DBus.Properties\">\n"
3486   "    <method name=\"Get\">\n"
3487   "      <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3488   "      <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3489   "      <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
3490   "    </method>\n"
3491   "    <method name=\"GetAll\">\n"
3492   "      <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3493   "      <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
3494   "    </method>\n"
3495   "    <method name=\"Set\">\n"
3496   "      <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3497   "      <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3498   "      <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
3499   "    </method>\n"
3500   "    <signal name=\"PropertiesChanged\">\n"
3501   "      <arg type=\"s\" name=\"interface_name\"/>\n"
3502   "      <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
3503   "    </signal>\n"
3504   "  </interface>\n"
3505   "  <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
3506   "    <method name=\"Introspect\">\n"
3507   "      <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
3508   "    </method>\n"
3509   "  </interface>\n"
3510   "  <interface name=\"org.freedesktop.DBus.Peer\">\n"
3511   "    <method name=\"Ping\"/>\n"
3512   "    <method name=\"GetMachineId\">\n"
3513   "      <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
3514   "    </method>\n"
3515   "  </interface>\n";
3516
3517 static void
3518 introspect_append_header (GString *s)
3519 {
3520   g_string_append (s, introspect_header);
3521 }
3522
3523 static void
3524 introspect_append_standard_interfaces (GString *s)
3525 {
3526   g_string_append (s, introspect_standard_interfaces);
3527 }
3528
3529 static void
3530 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
3531 {
3532   if (g_str_has_prefix (object_path, path) && strlen (object_path) >= path_len)
3533     {
3534       const gchar *begin;
3535       const gchar *end;
3536       gchar *s;
3537
3538       begin = object_path + path_len;
3539       end = strchr (begin, '/');
3540
3541       if (end != NULL)
3542         s = g_strndup (begin, end - begin);
3543       else
3544         s = g_strdup (begin);
3545
3546       if (g_hash_table_lookup (set, s) == NULL)
3547         g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
3548       else
3549         g_free (s);
3550     }
3551 }
3552
3553 /* TODO: we want a nicer public interface for this */
3554 static gchar **
3555 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
3556                                             const gchar     *path)
3557 {
3558   GPtrArray *p;
3559   gchar **ret;
3560   GHashTableIter hash_iter;
3561   const gchar *object_path;
3562   gsize path_len;
3563   GHashTable *set;
3564   GList *keys;
3565   GList *l;
3566
3567   CONNECTION_ENSURE_LOCK (connection);
3568
3569   path_len = strlen (path);
3570   if (path_len > 1)
3571     path_len++;
3572
3573   set = g_hash_table_new (g_str_hash, g_str_equal);
3574
3575   g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_eo);
3576   while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3577     maybe_add_path (path, path_len, object_path, set);
3578
3579   g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_es);
3580   while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3581     maybe_add_path (path, path_len, object_path, set);
3582
3583   p = g_ptr_array_new ();
3584   keys = g_hash_table_get_keys (set);
3585   for (l = keys; l != NULL; l = l->next)
3586     g_ptr_array_add (p, l->data);
3587   g_hash_table_unref (set);
3588   g_list_free (keys);
3589
3590   g_ptr_array_add (p, NULL);
3591   ret = (gchar **) g_ptr_array_free (p, FALSE);
3592   return ret;
3593 }
3594
3595 static gchar **
3596 g_dbus_connection_list_registered (GDBusConnection *connection,
3597                                    const gchar     *path)
3598 {
3599   gchar **ret;
3600   CONNECTION_LOCK (connection);
3601   ret = g_dbus_connection_list_registered_unlocked (connection, path);
3602   CONNECTION_UNLOCK (connection);
3603   return ret;
3604 }
3605
3606 /* called in message handler thread with lock held */
3607 static gboolean
3608 handle_introspect (GDBusConnection *connection,
3609                    ExportedObject  *eo,
3610                    GDBusMessage    *message)
3611 {
3612   guint n;
3613   GString *s;
3614   GDBusMessage *reply;
3615   GHashTableIter hash_iter;
3616   ExportedInterface *ei;
3617   gchar **registered;
3618
3619   /* first the header with the standard interfaces */
3620   s = g_string_sized_new (sizeof (introspect_header) +
3621                           sizeof (introspect_standard_interfaces) +
3622                           sizeof (introspect_tail));
3623   introspect_append_header (s);
3624   introspect_append_standard_interfaces (s);
3625
3626   /* then include the registered interfaces */
3627   g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
3628   while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
3629     g_dbus_interface_info_generate_xml (ei->introspection_data, 2, s);
3630
3631   /* finally include nodes registered below us */
3632   registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
3633   for (n = 0; registered != NULL && registered[n] != NULL; n++)
3634     g_string_append_printf (s, "  <node name=\"%s\"/>\n", registered[n]);
3635   g_strfreev (registered);
3636   g_string_append (s, introspect_tail);
3637
3638   reply = g_dbus_message_new_method_reply (message);
3639   g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
3640   g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3641   g_object_unref (reply);
3642   g_string_free (s, TRUE);
3643
3644   return TRUE;
3645 }
3646
3647 /* called in thread where object was registered - no locks held */
3648 static gboolean
3649 call_in_idle_cb (gpointer user_data)
3650 {
3651   GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
3652   GDBusInterfaceVTable *vtable;
3653
3654   vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
3655   g_assert (vtable != NULL && vtable->method_call != NULL);
3656
3657   vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
3658                        g_dbus_method_invocation_get_sender (invocation),
3659                        g_dbus_method_invocation_get_object_path (invocation),
3660                        g_dbus_method_invocation_get_interface_name (invocation),
3661                        g_dbus_method_invocation_get_method_name (invocation),
3662                        g_dbus_method_invocation_get_parameters (invocation),
3663                        g_object_ref (invocation),
3664                        g_dbus_method_invocation_get_user_data (invocation));
3665
3666   return FALSE;
3667 }
3668
3669 /* called in message handler thread with lock held */
3670 static gboolean
3671 validate_and_maybe_schedule_method_call (GDBusConnection            *connection,
3672                                          GDBusMessage               *message,
3673                                          const GDBusInterfaceInfo   *introspection_data,
3674                                          const GDBusInterfaceVTable *vtable,
3675                                          GMainContext               *main_context,
3676                                          gpointer                    user_data)
3677 {
3678   GDBusMethodInvocation *invocation;
3679   const GDBusMethodInfo *method_info;
3680   GDBusMessage *reply;
3681   GVariant *parameters;
3682   GSource *idle_source;
3683   gboolean handled;
3684   gchar *in_signature;
3685
3686   handled = FALSE;
3687
3688   /* TODO: the cost of this is O(n) - it might be worth caching the result */
3689   method_info = g_dbus_interface_info_lookup_method (introspection_data, g_dbus_message_get_member (message));
3690
3691   /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
3692    * error to the caller
3693    */
3694   if (method_info == NULL)
3695     {
3696       reply = g_dbus_message_new_method_error (message,
3697                                                "org.freedesktop.DBus.Error.UnknownMethod",
3698                                                _("No such method `%s'"),
3699                                                g_dbus_message_get_member (message));
3700       g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3701       g_object_unref (reply);
3702       handled = TRUE;
3703       goto out;
3704     }
3705
3706   /* Check that the incoming args are of the right type - if they are not, return
3707    * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
3708    *
3709    * TODO: might also be worth caching the combined signature.
3710    */
3711   in_signature = _g_dbus_compute_complete_signature (method_info->in_args, FALSE);
3712   if (g_strcmp0 (g_dbus_message_get_signature (message), in_signature) != 0)
3713     {
3714       reply = g_dbus_message_new_method_error (message,
3715                                                "org.freedesktop.DBus.Error.InvalidArgs",
3716                                                _("Signature of message, `%s', does not match expected signature `%s'"),
3717                                                g_dbus_message_get_signature (message),
3718                                                in_signature);
3719       g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3720       g_object_unref (reply);
3721       g_free (in_signature);
3722       handled = TRUE;
3723       goto out;
3724     }
3725   g_free (in_signature);
3726
3727   parameters = g_dbus_message_get_body (message);
3728   if (parameters == NULL)
3729     {
3730       parameters = g_variant_new ("()");
3731       g_variant_ref_sink (parameters);
3732     }
3733   else
3734     {
3735       g_variant_ref (parameters);
3736     }
3737
3738   /* schedule the call in idle */
3739   invocation = g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
3740                                              g_dbus_message_get_path (message),
3741                                              g_dbus_message_get_interface (message),
3742                                              g_dbus_message_get_member (message),
3743                                              method_info,
3744                                              connection,
3745                                              message,
3746                                              parameters,
3747                                              user_data);
3748   g_variant_unref (parameters);
3749   g_object_set_data (G_OBJECT (invocation),
3750                      "g-dbus-interface-vtable",
3751                      (gpointer) vtable);
3752
3753   idle_source = g_idle_source_new ();
3754   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3755   g_source_set_callback (idle_source,
3756                          call_in_idle_cb,
3757                          invocation,
3758                          g_object_unref);
3759   g_source_attach (idle_source, main_context);
3760   g_source_unref (idle_source);
3761
3762   handled = TRUE;
3763
3764  out:
3765   return handled;
3766 }
3767
3768 /* ---------------------------------------------------------------------------------------------------- */
3769
3770 /* called in message handler thread with lock held */
3771 static gboolean
3772 obj_message_func (GDBusConnection *connection,
3773                   ExportedObject  *eo,
3774                   GDBusMessage    *message)
3775 {
3776   const gchar *interface_name;
3777   const gchar *member;
3778   const gchar *signature;
3779   gboolean handled;
3780
3781   handled = FALSE;
3782
3783   interface_name = g_dbus_message_get_interface (message);
3784   member = g_dbus_message_get_member (message);
3785   signature = g_dbus_message_get_signature (message);
3786
3787   /* see if we have an interface for handling this call */
3788   if (interface_name != NULL)
3789     {
3790       ExportedInterface *ei;
3791       ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3792       if (ei != NULL)
3793         {
3794           /* we do - invoke the handler in idle in the right thread */
3795
3796           /* handle no vtable or handler being present */
3797           if (ei->vtable == NULL || ei->vtable->method_call == NULL)
3798             goto out;
3799
3800           handled = validate_and_maybe_schedule_method_call (connection,
3801                                                              message,
3802                                                              ei->introspection_data,
3803                                                              ei->vtable,
3804                                                              ei->context,
3805                                                              ei->user_data);
3806           goto out;
3807         }
3808     }
3809
3810   if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
3811       g_strcmp0 (member, "Introspect") == 0 &&
3812       g_strcmp0 (signature, "") == 0)
3813     {
3814       handled = handle_introspect (connection, eo, message);
3815       goto out;
3816     }
3817   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3818            g_strcmp0 (member, "Get") == 0 &&
3819            g_strcmp0 (signature, "ss") == 0)
3820     {
3821       handled = handle_getset_property (connection, eo, message, TRUE);
3822       goto out;
3823     }
3824   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3825            g_strcmp0 (member, "Set") == 0 &&
3826            g_strcmp0 (signature, "ssv") == 0)
3827     {
3828       handled = handle_getset_property (connection, eo, message, FALSE);
3829       goto out;
3830     }
3831   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3832            g_strcmp0 (member, "GetAll") == 0 &&
3833            g_strcmp0 (signature, "s") == 0)
3834     {
3835       handled = handle_get_all_properties (connection, eo, message);
3836       goto out;
3837     }
3838
3839  out:
3840   return handled;
3841 }
3842
3843 /**
3844  * g_dbus_connection_register_object:
3845  * @connection: A #GDBusConnection.
3846  * @object_path: The object path to register at.
3847  * @interface_name: The D-Bus interface to register.
3848  * @introspection_data: Introspection data for the interface.
3849  * @vtable: A #GDBusInterfaceVTable to call into or %NULL.
3850  * @user_data: Data to pass to functions in @vtable.
3851  * @user_data_free_func: Function to call when the object path is unregistered.
3852  * @error: Return location for error or %NULL.
3853  *
3854  * Registers callbacks for exported objects at @object_path with the
3855  * D-Bus interface @interface_name.
3856  *
3857  * Calls to functions in @vtable (and @user_data_free_func) will
3858  * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
3859  * loop</link> of the thread you are calling this method from.
3860  *
3861  * Note that all #GVariant values passed to functions in @vtable will match
3862  * the signature given in @introspection_data - if a remote caller passes
3863  * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
3864  * is returned to the remote caller.
3865  *
3866  * Additionally, if the remote caller attempts to invoke methods or
3867  * access properties not mentioned in @introspection_data the
3868  * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
3869  * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
3870  * are returned to the caller.
3871  *
3872  * It is considered a programming error if the
3873  * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
3874  * #GVariant of incorrect type.
3875  *
3876  * If an existing callback is already registered at @object_path and
3877  * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
3878  *
3879  * See <xref linkend="gdbus-server"/> for an example of how to use this method.
3880  *
3881  * Returns: 0 if @error is set, otherwise a registration id (never 0)
3882  * that can be used with g_dbus_connection_unregister_object() .
3883  *
3884  * Since: 2.26
3885  */
3886 guint
3887 g_dbus_connection_register_object (GDBusConnection            *connection,
3888                                    const gchar                *object_path,
3889                                    const gchar                *interface_name,
3890                                    const GDBusInterfaceInfo   *introspection_data,
3891                                    const GDBusInterfaceVTable *vtable,
3892                                    gpointer                    user_data,
3893                                    GDestroyNotify              user_data_free_func,
3894                                    GError                    **error)
3895 {
3896   ExportedObject *eo;
3897   ExportedInterface *ei;
3898   guint ret;
3899
3900   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3901   g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
3902   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
3903   g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3904   g_return_val_if_fail (introspection_data != NULL, 0);
3905   g_return_val_if_fail (error == NULL || *error == NULL, 0);
3906
3907   ret = 0;
3908
3909   CONNECTION_LOCK (connection);
3910
3911   eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
3912   if (eo == NULL)
3913     {
3914       eo = g_new0 (ExportedObject, 1);
3915       eo->object_path = g_strdup (object_path);
3916       eo->connection = connection;
3917       eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
3918                                                      g_str_equal,
3919                                                      NULL,
3920                                                      (GDestroyNotify) exported_interface_free);
3921       g_hash_table_insert (connection->priv->map_object_path_to_eo, eo->object_path, eo);
3922     }
3923
3924   ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3925   if (ei != NULL)
3926     {
3927       g_set_error (error,
3928                    G_IO_ERROR,
3929                    G_IO_ERROR_EXISTS,
3930                    _("An object is already exported for the interface %s at %s"),
3931                    interface_name,
3932                    object_path);
3933       goto out;
3934     }
3935
3936   ei = g_new0 (ExportedInterface, 1);
3937   ei->id = _global_registration_id++; /* TODO: overflow etc. */
3938   ei->eo = eo;
3939   ei->user_data = user_data;
3940   ei->user_data_free_func = user_data_free_func;
3941   ei->vtable = vtable;
3942   ei->introspection_data = introspection_data;
3943   ei->interface_name = g_strdup (interface_name);
3944   ei->context = g_main_context_get_thread_default ();
3945   if (ei->context != NULL)
3946     g_main_context_ref (ei->context);
3947
3948   g_hash_table_insert (eo->map_if_name_to_ei,
3949                        (gpointer) ei->interface_name,
3950                        ei);
3951   g_hash_table_insert (connection->priv->map_id_to_ei,
3952                        GUINT_TO_POINTER (ei->id),
3953                        ei);
3954
3955   ret = ei->id;
3956
3957  out:
3958   CONNECTION_UNLOCK (connection);
3959
3960   return ret;
3961 }
3962
3963 /**
3964  * g_dbus_connection_unregister_object:
3965  * @connection: A #GDBusConnection.
3966  * @registration_id: A registration id obtained from g_dbus_connection_register_object().
3967  *
3968  * Unregisters an object.
3969  *
3970  * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
3971  *
3972  * Since: 2.26
3973  */
3974 gboolean
3975 g_dbus_connection_unregister_object (GDBusConnection *connection,
3976                                      guint            registration_id)
3977 {
3978   ExportedInterface *ei;
3979   ExportedObject *eo;
3980   gboolean ret;
3981
3982   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3983
3984   ret = FALSE;
3985
3986   CONNECTION_LOCK (connection);
3987
3988   ei = g_hash_table_lookup (connection->priv->map_id_to_ei,
3989                             GUINT_TO_POINTER (registration_id));
3990   if (ei == NULL)
3991     goto out;
3992
3993   eo = ei->eo;
3994
3995   g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
3996   g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
3997   /* unregister object path if we have no more exported interfaces */
3998   if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
3999     g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_eo,
4000                                          eo->object_path));
4001
4002   ret = TRUE;
4003
4004  out:
4005   CONNECTION_UNLOCK (connection);
4006
4007   return ret;
4008 }
4009
4010 /* ---------------------------------------------------------------------------------------------------- */
4011
4012 /**
4013  * g_dbus_connection_emit_signal:
4014  * @connection: A #GDBusConnection.
4015  * @destination_bus_name: The unique bus name for the destination for the signal or %NULL to emit to all listeners.
4016  * @object_path: Path of remote object.
4017  * @interface_name: D-Bus interface to emit a signal on.
4018  * @signal_name: The name of the signal to emit.
4019  * @parameters: A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
4020  * @error: Return location for error or %NULL.
4021  *
4022  * Emits a signal.
4023  *
4024  * This can only fail if @parameters is not compatible with the D-Bus protocol.
4025  *
4026  * Returns: %TRUE unless @error is set.
4027  *
4028  * Since: 2.26
4029  */
4030 gboolean
4031 g_dbus_connection_emit_signal (GDBusConnection  *connection,
4032                                const gchar      *destination_bus_name,
4033                                const gchar      *object_path,
4034                                const gchar      *interface_name,
4035                                const gchar      *signal_name,
4036                                GVariant         *parameters,
4037                                GError          **error)
4038 {
4039   GDBusMessage *message;
4040   gboolean ret;
4041
4042   message = NULL;
4043   ret = FALSE;
4044
4045   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4046   g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
4047   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
4048   g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
4049   g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
4050   g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
4051
4052   message = g_dbus_message_new_signal (object_path,
4053                                        interface_name,
4054                                        signal_name);
4055
4056   if (destination_bus_name != NULL)
4057     g_dbus_message_set_header (message,
4058                                G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
4059                                g_variant_new_string (destination_bus_name));
4060
4061   if (parameters != NULL)
4062     g_dbus_message_set_body (message, parameters);
4063
4064   ret = g_dbus_connection_send_message (connection, message, NULL, error);
4065   g_object_unref (message);
4066
4067   return ret;
4068 }
4069
4070 static void
4071 add_call_flags (GDBusMessage           *message,
4072                          GDBusCallFlags  flags)
4073 {
4074   if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
4075     g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
4076 }
4077
4078 /**
4079  * g_dbus_connection_call:
4080  * @connection: A #GDBusConnection.
4081  * @bus_name: A unique or well-known bus name or %NULL if @connection is not a message bus connection.
4082  * @object_path: Path of remote object.
4083  * @interface_name: D-Bus interface to invoke method on.
4084  * @method_name: The name of the method to invoke.
4085  * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4086  * @flags: Flags from the #GDBusCallFlags enumeration.
4087  * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4088  * @cancellable: A #GCancellable or %NULL.
4089  * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
4090  * care about the result of the method invocation.
4091  * @user_data: The data to pass to @callback.
4092  *
4093  * Asynchronously invokes the @method_name method on the
4094  * @interface_name D-Bus interface on the remote object at
4095  * @object_path owned by @bus_name.
4096  *
4097  * If @connection is closed then the operation will fail with
4098  * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
4099  * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
4100  * not compatible with the D-Bus protocol, the operation fails with
4101  * %G_IO_ERROR_INVALID_ARGUMENT.
4102  *
4103  * This is an asynchronous method. When the operation is finished, @callback will be invoked
4104  * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
4105  * of the thread you are calling this method from. You can then call
4106  * g_dbus_connection_call_finish() to get the result of the operation.
4107  * See g_dbus_connection_call_sync() for the synchronous version of this
4108  * function.
4109  *
4110  * Since: 2.26
4111  */
4112 void
4113 g_dbus_connection_call (GDBusConnection        *connection,
4114                         const gchar            *bus_name,
4115                         const gchar            *object_path,
4116                         const gchar            *interface_name,
4117                         const gchar            *method_name,
4118                         GVariant               *parameters,
4119                         GDBusCallFlags          flags,
4120                         gint                    timeout_msec,
4121                         GCancellable           *cancellable,
4122                         GAsyncReadyCallback     callback,
4123                         gpointer                user_data)
4124 {
4125   GDBusMessage *message;
4126
4127   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4128   g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
4129   g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
4130   g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
4131   g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
4132   g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
4133   g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
4134
4135   message = g_dbus_message_new_method_call (bus_name,
4136                                             object_path,
4137                                             interface_name,
4138                                             method_name);
4139   add_call_flags (message, flags);
4140   if (parameters != NULL)
4141     g_dbus_message_set_body (message, parameters);
4142
4143   g_dbus_connection_send_message_with_reply (connection,
4144                                              message,
4145                                              timeout_msec,
4146                                              NULL, /* volatile guint32 *out_serial */
4147                                              cancellable,
4148                                              callback,
4149                                              user_data);
4150
4151   if (message != NULL)
4152     g_object_unref (message);
4153 }
4154
4155 static GVariant *
4156 decode_method_reply (GDBusMessage  *reply,
4157                      GError       **error)
4158 {
4159   GVariant *result;
4160
4161   result = NULL;
4162   switch (g_dbus_message_get_message_type (reply))
4163     {
4164     case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
4165       result = g_dbus_message_get_body (reply);
4166       if (result == NULL)
4167         {
4168           result = g_variant_new ("()");
4169           g_variant_ref_sink (result);
4170         }
4171       else
4172         {
4173           g_variant_ref (result);
4174         }
4175       break;
4176
4177     case G_DBUS_MESSAGE_TYPE_ERROR:
4178       g_dbus_message_to_gerror (reply, error);
4179       break;
4180
4181     default:
4182       g_assert_not_reached ();
4183       break;
4184     }
4185
4186   return result;
4187 }
4188
4189 /**
4190  * g_dbus_connection_call_finish:
4191  * @connection: A #GDBusConnection.
4192  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
4193  * @error: Return location for error or %NULL.
4194  *
4195  * Finishes an operation started with g_dbus_connection_call().
4196  *
4197  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4198  * return values. Free with g_variant_unref().
4199  *
4200  * Since: 2.26
4201  */
4202 GVariant *
4203 g_dbus_connection_call_finish (GDBusConnection  *connection,
4204                                GAsyncResult     *res,
4205                                GError          **error)
4206 {
4207   GDBusMessage *reply;
4208   GVariant *result;
4209
4210   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4211   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
4212   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4213
4214   result = NULL;
4215
4216   reply = g_dbus_connection_send_message_with_reply_finish (connection, res, error);
4217   if (reply == NULL)
4218     goto out;
4219
4220   result = decode_method_reply (reply, error);
4221
4222   g_object_unref (reply);
4223
4224  out:
4225   return result;
4226 }
4227
4228 /* ---------------------------------------------------------------------------------------------------- */
4229
4230 /**
4231  * g_dbus_connection_call_sync:
4232  * @connection: A #GDBusConnection.
4233  * @bus_name: A unique or well-known bus name.
4234  * @object_path: Path of remote object.
4235  * @interface_name: D-Bus interface to invoke method on.
4236  * @method_name: The name of the method to invoke.
4237  * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4238  * @flags: Flags from the #GDBusCallFlags enumeration.
4239  * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4240  * @cancellable: A #GCancellable or %NULL.
4241  * @error: Return location for error or %NULL.
4242  *
4243  * Synchronously invokes the @method_name method on the
4244  * @interface_name D-Bus interface on the remote object at
4245  * @object_path owned by @bus_name.
4246  *
4247  * If @connection is closed then the operation will fail with
4248  * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
4249  * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
4250  * contains a value not compatible with the D-Bus protocol, the operation
4251  * fails with %G_IO_ERROR_INVALID_ARGUMENT.
4252  *
4253  * The calling thread is blocked until a reply is received. See
4254  * g_dbus_connection_call() for the asynchronous version of
4255  * this method.
4256  *
4257  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4258  * return values. Free with g_variant_unref().
4259  *
4260  * Since: 2.26
4261  */
4262 GVariant *
4263 g_dbus_connection_call_sync (GDBusConnection         *connection,
4264                              const gchar             *bus_name,
4265                              const gchar             *object_path,
4266                              const gchar             *interface_name,
4267                              const gchar             *method_name,
4268                              GVariant                *parameters,
4269                              GDBusCallFlags           flags,
4270                              gint                     timeout_msec,
4271                              GCancellable            *cancellable,
4272                              GError                 **error)
4273 {
4274   GDBusMessage *message;
4275   GDBusMessage *reply;
4276   GVariant *result;
4277
4278   message = NULL;
4279   reply = NULL;
4280   result = NULL;
4281
4282   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4283   g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
4284   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
4285   g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
4286   g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
4287   g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
4288   g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
4289
4290   message = g_dbus_message_new_method_call (bus_name,
4291                                             object_path,
4292                                             interface_name,
4293                                             method_name);
4294   add_call_flags (message, flags);
4295   if (parameters != NULL)
4296     g_dbus_message_set_body (message, parameters);
4297
4298   reply = g_dbus_connection_send_message_with_reply_sync (connection,
4299                                                           message,
4300                                                           timeout_msec,
4301                                                           NULL, /* volatile guint32 *out_serial */
4302                                                           cancellable,
4303                                                           error);
4304
4305   if (reply == NULL)
4306     goto out;
4307
4308   result = decode_method_reply (reply, error);
4309
4310  out:
4311   if (message != NULL)
4312     g_object_unref (message);
4313   if (reply != NULL)
4314     g_object_unref (reply);
4315
4316   return result;
4317 }
4318
4319 /* ---------------------------------------------------------------------------------------------------- */
4320
4321 struct ExportedSubtree
4322 {
4323   guint                     id;
4324   gchar                    *object_path;
4325   GDBusConnection          *connection;
4326   const GDBusSubtreeVTable *vtable;
4327   GDBusSubtreeFlags         flags;
4328
4329   GMainContext             *context;
4330   gpointer                  user_data;
4331   GDestroyNotify            user_data_free_func;
4332 };
4333
4334 static void
4335 exported_subtree_free (ExportedSubtree *es)
4336 {
4337   if (es->user_data_free_func != NULL)
4338     /* TODO: push to thread-default mainloop */
4339     es->user_data_free_func (es->user_data);
4340
4341   if (es->context != NULL)
4342     g_main_context_unref (es->context);
4343
4344   g_free (es->object_path);
4345   g_free (es);
4346 }
4347
4348 /* called without lock held */
4349 static gboolean
4350 handle_subtree_introspect (GDBusConnection *connection,
4351                            ExportedSubtree *es,
4352                            GDBusMessage    *message)
4353 {
4354   GString *s;
4355   gboolean handled;
4356   GDBusMessage *reply;
4357   gchar **children;
4358   gboolean is_root;
4359   const gchar *sender;
4360   const gchar *requested_object_path;
4361   const gchar *requested_node;
4362   GPtrArray *interfaces;
4363   guint n;
4364   gchar **subnode_paths;
4365
4366   handled = FALSE;
4367
4368   requested_object_path = g_dbus_message_get_path (message);
4369   sender = g_dbus_message_get_sender (message);
4370   is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4371
4372   s = g_string_new (NULL);
4373   introspect_append_header (s);
4374
4375   /* Strictly we don't need the children in dynamic mode, but we avoid the
4376    * conditionals to preserve code clarity
4377    */
4378   children = es->vtable->enumerate (es->connection,
4379                                     sender,
4380                                     es->object_path,
4381                                     es->user_data);
4382
4383   if (!is_root)
4384     {
4385       requested_node = strrchr (requested_object_path, '/') + 1;
4386
4387       /* Assert existence of object if we are not dynamic */
4388       if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4389           !_g_strv_has_string ((const gchar * const *) children, requested_node))
4390         goto out;
4391     }
4392   else
4393     {
4394       requested_node = "/";
4395     }
4396
4397   interfaces = es->vtable->introspect (es->connection,
4398                                        sender,
4399                                        es->object_path,
4400                                        requested_node,
4401                                        es->user_data);
4402   if (interfaces != NULL)
4403     {
4404       if (interfaces->len > 0)
4405         {
4406           /* we're in business */
4407           introspect_append_standard_interfaces (s);
4408
4409           for (n = 0; n < interfaces->len; n++)
4410             {
4411               const GDBusInterfaceInfo *interface_info = interfaces->pdata[n];
4412               g_dbus_interface_info_generate_xml (interface_info, 2, s);
4413             }
4414         }
4415       g_ptr_array_unref (interfaces);
4416     }
4417
4418   /* then include <node> entries from the Subtree for the root */
4419   if (is_root)
4420     {
4421       for (n = 0; children != NULL && children[n] != NULL; n++)
4422         g_string_append_printf (s, "  <node name=\"%s\"/>\n", children[n]);
4423     }
4424
4425   /* finally include nodes registered below us */
4426   subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
4427   for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
4428     g_string_append_printf (s, "  <node name=\"%s\"/>\n", subnode_paths[n]);
4429   g_strfreev (subnode_paths);
4430
4431   g_string_append (s, "</node>\n");
4432
4433   reply = g_dbus_message_new_method_reply (message);
4434   g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4435   g_dbus_connection_send_message (connection, reply, NULL, NULL);
4436   g_object_unref (reply);
4437
4438   handled = TRUE;
4439
4440  out:
4441   g_string_free (s, TRUE);
4442   g_strfreev (children);
4443   return handled;
4444 }
4445
4446 /* called without lock held */
4447 static gboolean
4448 handle_subtree_method_invocation (GDBusConnection *connection,
4449                                   ExportedSubtree *es,
4450                                   GDBusMessage    *message)
4451 {
4452   gboolean handled;;
4453   const gchar *sender;
4454   const gchar *interface_name;
4455   const gchar *member;
4456   const gchar *signature;
4457   const gchar *requested_object_path;
4458   const gchar *requested_node;
4459   gboolean is_root;
4460   gchar **children;
4461   const GDBusInterfaceInfo *introspection_data;
4462   const GDBusInterfaceVTable *interface_vtable;
4463   gpointer interface_user_data;
4464   guint n;
4465   GPtrArray *interfaces;
4466   gboolean is_property_get;
4467   gboolean is_property_set;
4468   gboolean is_property_get_all;
4469
4470   handled = FALSE;
4471   interfaces = NULL;
4472
4473   requested_object_path = g_dbus_message_get_path (message);
4474   sender = g_dbus_message_get_sender (message);
4475   interface_name = g_dbus_message_get_interface (message);
4476   member = g_dbus_message_get_member (message);
4477   signature = g_dbus_message_get_signature (message);
4478   is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4479
4480   is_property_get = FALSE;
4481   is_property_set = FALSE;
4482   is_property_get_all = FALSE;
4483   if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
4484     {
4485       if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
4486         is_property_get = TRUE;
4487       else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
4488         is_property_set = TRUE;
4489       else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
4490         is_property_get_all = TRUE;
4491     }
4492
4493   children = es->vtable->enumerate (es->connection,
4494                                     sender,
4495                                     es->object_path,
4496                                     es->user_data);
4497
4498   if (!is_root)
4499     {
4500       requested_node = strrchr (requested_object_path, '/') + 1;
4501
4502       /* If not dynamic, skip if requested node is not part of children */
4503       if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4504           !_g_strv_has_string ((const gchar * const *) children, requested_node))
4505         goto out;
4506     }
4507   else
4508     {
4509       requested_node = "/";
4510     }
4511
4512   /* get introspection data for the node */
4513   interfaces = es->vtable->introspect (es->connection,
4514                                        sender,
4515                                        requested_object_path,
4516                                        requested_node,
4517                                        es->user_data);
4518   g_assert (interfaces != NULL);
4519   introspection_data = NULL;
4520   for (n = 0; n < interfaces->len; n++)
4521     {
4522       const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4523       if (g_strcmp0 (id_n->name, interface_name) == 0)
4524         introspection_data = id_n;
4525     }
4526
4527   /* dispatch the call if the user wants to handle it */
4528   if (introspection_data != NULL)
4529     {
4530       /* figure out where to dispatch the method call */
4531       interface_user_data = NULL;
4532       interface_vtable = es->vtable->dispatch (es->connection,
4533                                                sender,
4534                                                es->object_path,
4535                                                interface_name,
4536                                                requested_node,
4537                                                &interface_user_data,
4538                                                es->user_data);
4539       if (interface_vtable == NULL)
4540         goto out;
4541
4542       CONNECTION_LOCK (connection);
4543       handled = validate_and_maybe_schedule_method_call (es->connection,
4544                                                          message,
4545                                                          introspection_data,
4546                                                          interface_vtable,
4547                                                          es->context,
4548                                                          interface_user_data);
4549       CONNECTION_UNLOCK (connection);
4550     }
4551   /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
4552   else if (is_property_get || is_property_set || is_property_get_all)
4553     {
4554       if (is_property_get)
4555         g_variant_get (g_dbus_message_get_body (message), "(ss)", &interface_name, NULL);
4556       else if (is_property_set)
4557         g_variant_get (g_dbus_message_get_body (message), "(ssv)", &interface_name, NULL, NULL);
4558       else if (is_property_get_all)
4559         g_variant_get (g_dbus_message_get_body (message), "(s)", &interface_name, NULL, NULL);
4560       else
4561         g_assert_not_reached ();
4562
4563       /* see if the object supports this interface at all */
4564       for (n = 0; n < interfaces->len; n++)
4565         {
4566           const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4567           if (g_strcmp0 (id_n->name, interface_name) == 0)
4568             introspection_data = id_n;
4569         }
4570
4571       /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
4572        * claims it won't support the interface
4573        */
4574       if (introspection_data == NULL)
4575         {
4576           GDBusMessage *reply;
4577           reply = g_dbus_message_new_method_error (message,
4578                                                    "org.freedesktop.DBus.Error.InvalidArgs",
4579                                                    _("No such interface `%s'"),
4580                                                    interface_name);
4581           g_dbus_connection_send_message (es->connection, reply, NULL, NULL);
4582           g_object_unref (reply);
4583           handled = TRUE;
4584           goto out;
4585         }
4586
4587       /* figure out where to dispatch the property get/set/getall calls */
4588       interface_user_data = NULL;
4589       interface_vtable = es->vtable->dispatch (es->connection,
4590                                                sender,
4591                                                es->object_path,
4592                                                interface_name,
4593                                                requested_node,
4594                                                &interface_user_data,
4595                                                es->user_data);
4596       if (interface_vtable == NULL)
4597         goto out;
4598
4599       if (is_property_get || is_property_set)
4600         {
4601           CONNECTION_LOCK (connection);
4602           handled = validate_and_maybe_schedule_property_getset (es->connection,
4603                                                                  message,
4604                                                                  is_property_get,
4605                                                                  introspection_data,
4606                                                                  interface_vtable,
4607                                                                  es->context,
4608                                                                  interface_user_data);
4609           CONNECTION_UNLOCK (connection);
4610         }
4611       else if (is_property_get_all)
4612         {
4613           CONNECTION_LOCK (connection);
4614           handled = validate_and_maybe_schedule_property_get_all (es->connection,
4615                                                                   message,
4616                                                                   introspection_data,
4617                                                                   interface_vtable,
4618                                                                   es->context,
4619                                                                   interface_user_data);
4620           CONNECTION_UNLOCK (connection);
4621         }
4622     }
4623
4624  out:
4625   if (interfaces != NULL)
4626     g_ptr_array_unref (interfaces);
4627   g_strfreev (children);
4628   return handled;
4629 }
4630
4631 typedef struct
4632 {
4633   GDBusMessage *message;
4634   ExportedSubtree *es;
4635 } SubtreeDeferredData;
4636
4637 static void
4638 subtree_deferred_data_free (SubtreeDeferredData *data)
4639 {
4640   g_object_unref (data->message);
4641   g_free (data);
4642 }
4643
4644 /* called without lock held in the thread where the caller registered the subtree */
4645 static gboolean
4646 process_subtree_vtable_message_in_idle_cb (gpointer _data)
4647 {
4648   SubtreeDeferredData *data = _data;
4649   gboolean handled;
4650
4651   handled = FALSE;
4652
4653   if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
4654       g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
4655       g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
4656     handled = handle_subtree_introspect (data->es->connection,
4657                                          data->es,
4658                                          data->message);
4659   else
4660     handled = handle_subtree_method_invocation (data->es->connection,
4661                                                 data->es,
4662                                                 data->message);
4663
4664   if (!handled)
4665     {
4666       CONNECTION_LOCK (data->es->connection);
4667       handled = handle_generic_unlocked (data->es->connection, data->message);
4668       CONNECTION_UNLOCK (data->es->connection);
4669     }
4670
4671   /* if we couldn't handle the request, just bail with the UnknownMethod error */
4672   if (!handled)
4673     {
4674       GDBusMessage *reply;
4675       reply = g_dbus_message_new_method_error (data->message,
4676                                                "org.freedesktop.DBus.Error.UnknownMethod",
4677                                                _("Method `%s' on interface `%s' with signature `%s' does not exist"),
4678                                                g_dbus_message_get_member (data->message),
4679                                                g_dbus_message_get_interface (data->message),
4680                                                g_dbus_message_get_signature (data->message));
4681       g_dbus_connection_send_message (data->es->connection, reply, NULL, NULL);
4682       g_object_unref (reply);
4683     }
4684
4685   return FALSE;
4686 }
4687
4688 /* called in message handler thread with lock held */
4689 static gboolean
4690 subtree_message_func (GDBusConnection *connection,
4691                       ExportedSubtree *es,
4692                       GDBusMessage    *message)
4693 {
4694   GSource *idle_source;
4695   SubtreeDeferredData *data;
4696
4697   data = g_new0 (SubtreeDeferredData, 1);
4698   data->message = g_object_ref (message);
4699   data->es = es;
4700
4701   /* defer this call to an idle handler in the right thread */
4702   idle_source = g_idle_source_new ();
4703   g_source_set_priority (idle_source, G_PRIORITY_HIGH);
4704   g_source_set_callback (idle_source,
4705                          process_subtree_vtable_message_in_idle_cb,
4706                          data,
4707                          (GDestroyNotify) subtree_deferred_data_free);
4708   g_source_attach (idle_source, es->context);
4709   g_source_unref (idle_source);
4710
4711   /* since we own the entire subtree, handlers for objects not in the subtree have been
4712    * tried already by libdbus-1 - so we just need to ensure that we're always going
4713    * to reply to the message
4714    */
4715   return TRUE;
4716 }
4717
4718 /**
4719  * g_dbus_connection_register_subtree:
4720  * @connection: A #GDBusConnection.
4721  * @object_path: The object path to register the subtree at.
4722  * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
4723  * @flags: Flags used to fine tune the behavior of the subtree.
4724  * @user_data: Data to pass to functions in @vtable.
4725  * @user_data_free_func: Function to call when the subtree is unregistered.
4726  * @error: Return location for error or %NULL.
4727  *
4728  * Registers a whole subtree of <quote>dynamic</quote> objects.
4729  *
4730  * The @enumerate and @introspection functions in @vtable are used to
4731  * convey, to remote callers, what nodes exist in the subtree rooted
4732  * by @object_path.
4733  *
4734  * When handling remote calls into any node in the subtree, first the
4735  * @enumerate function is used to check if the node exists. If the node exists
4736  * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
4737  * the @introspection function is used to check if the node supports the
4738  * requested method. If so, the @dispatch function is used to determine
4739  * where to dispatch the call. The collected #GDBusInterfaceVTable and
4740  * #gpointer will be used to call into the interface vtable for processing
4741  * the request.
4742  *
4743  * All calls into user-provided code will be invoked in the <link
4744  * linkend="g-main-context-push-thread-default">thread-default main
4745  * loop</link> of the thread you are calling this method from.
4746  *
4747  * If an existing subtree is already registered at @object_path or
4748  * then @error is set to #G_IO_ERROR_EXISTS.
4749  *
4750  * Note that it is valid to register regular objects (using
4751  * g_dbus_connection_register_object()) in a subtree registered with
4752  * g_dbus_connection_register_subtree() - if so, the subtree handler
4753  * is tried as the last resort. One way to think about a subtree
4754  * handler is to consider it a <quote>fallback handler</quote>
4755  * for object paths not registered via g_dbus_connection_register_object()
4756  * or other bindings.
4757  *
4758  * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
4759  *
4760  * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
4761  * that can be used with g_dbus_connection_unregister_subtree() .
4762  *
4763  * Since: 2.26
4764  */
4765 guint
4766 g_dbus_connection_register_subtree (GDBusConnection           *connection,
4767                                     const gchar               *object_path,
4768                                     const GDBusSubtreeVTable  *vtable,
4769                                     GDBusSubtreeFlags          flags,
4770                                     gpointer                   user_data,
4771                                     GDestroyNotify             user_data_free_func,
4772                                     GError                   **error)
4773 {
4774   guint ret;
4775   ExportedSubtree *es;
4776
4777   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4778   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4779   g_return_val_if_fail (vtable != NULL, 0);
4780   g_return_val_if_fail (error == NULL || *error == NULL, 0);
4781
4782   ret = 0;
4783
4784   CONNECTION_LOCK (connection);
4785
4786   es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
4787   if (es != NULL)
4788     {
4789       g_set_error (error,
4790                    G_IO_ERROR,
4791                    G_IO_ERROR_EXISTS,
4792                    _("A subtree is already exported for %s"),
4793                    object_path);
4794       goto out;
4795     }
4796
4797   es = g_new0 (ExportedSubtree, 1);
4798   es->object_path = g_strdup (object_path);
4799   es->connection = connection;
4800
4801   es->vtable = vtable;
4802   es->flags = flags;
4803   es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
4804   es->user_data = user_data;
4805   es->user_data_free_func = user_data_free_func;
4806   es->context = g_main_context_get_thread_default ();
4807   if (es->context != NULL)
4808     g_main_context_ref (es->context);
4809
4810   g_hash_table_insert (connection->priv->map_object_path_to_es, es->object_path, es);
4811   g_hash_table_insert (connection->priv->map_id_to_es,
4812                        GUINT_TO_POINTER (es->id),
4813                        es);
4814
4815   ret = es->id;
4816
4817  out:
4818   CONNECTION_UNLOCK (connection);
4819
4820   return ret;
4821 }
4822
4823 /* ---------------------------------------------------------------------------------------------------- */
4824
4825 /**
4826  * g_dbus_connection_unregister_subtree:
4827  * @connection: A #GDBusConnection.
4828  * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
4829  *
4830  * Unregisters a subtree.
4831  *
4832  * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
4833  *
4834  * Since: 2.26
4835  */
4836 gboolean
4837 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
4838                                       guint            registration_id)
4839 {
4840   ExportedSubtree *es;
4841   gboolean ret;
4842
4843   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4844
4845   ret = FALSE;
4846
4847   CONNECTION_LOCK (connection);
4848
4849   es = g_hash_table_lookup (connection->priv->map_id_to_es,
4850                             GUINT_TO_POINTER (registration_id));
4851   if (es == NULL)
4852     goto out;
4853
4854   g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_es, GUINT_TO_POINTER (es->id)));
4855   g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_es, es->object_path));
4856
4857   ret = TRUE;
4858
4859  out:
4860   CONNECTION_UNLOCK (connection);
4861
4862   return ret;
4863 }
4864
4865 /* ---------------------------------------------------------------------------------------------------- */
4866
4867 /* must be called with lock held */
4868 static void
4869 handle_generic_ping_unlocked (GDBusConnection *connection,
4870                               const gchar     *object_path,
4871                               GDBusMessage    *message)
4872 {
4873   GDBusMessage *reply;
4874   reply = g_dbus_message_new_method_reply (message);
4875   g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4876   g_object_unref (reply);
4877 }
4878
4879 /* must be called with lock held */
4880 static void
4881 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
4882                                         const gchar     *object_path,
4883                                         GDBusMessage    *message)
4884 {
4885   GDBusMessage *reply;
4886
4887   reply = NULL;
4888   if (connection->priv->machine_id == NULL)
4889     {
4890       GError *error;
4891       error = NULL;
4892       /* TODO: use PACKAGE_LOCALSTATEDIR ? */
4893       if (!g_file_get_contents ("/var/lib/dbus/machine-id",
4894                                 &connection->priv->machine_id,
4895                                 NULL,
4896                                 &error))
4897         {
4898           reply = g_dbus_message_new_method_error (message,
4899                                                    "org.freedesktop.DBus.Error.Failed",
4900                                                    _("Unable to load /var/lib/dbus/machine-id: %s"),
4901                                                    error->message);
4902           g_error_free (error);
4903         }
4904       else
4905         {
4906           g_strstrip (connection->priv->machine_id);
4907           /* TODO: validate value */
4908         }
4909     }
4910
4911   if (reply == NULL)
4912     {
4913       reply = g_dbus_message_new_method_reply (message);
4914       g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->priv->machine_id));
4915     }
4916   g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4917   g_object_unref (reply);
4918 }
4919
4920 /* must be called with lock held */
4921 static void
4922 handle_generic_introspect_unlocked (GDBusConnection *connection,
4923                                     const gchar     *object_path,
4924                                     GDBusMessage    *message)
4925 {
4926   guint n;
4927   GString *s;
4928   gchar **registered;
4929   GDBusMessage *reply;
4930
4931   /* first the header */
4932   s = g_string_new (NULL);
4933   introspect_append_header (s);
4934
4935   registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
4936   for (n = 0; registered != NULL && registered[n] != NULL; n++)
4937       g_string_append_printf (s, "  <node name=\"%s\"/>\n", registered[n]);
4938   g_strfreev (registered);
4939   g_string_append (s, "</node>\n");
4940
4941   reply = g_dbus_message_new_method_reply (message);
4942   g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4943   g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4944   g_object_unref (reply);
4945   g_string_free (s, TRUE);
4946 }
4947
4948 /* must be called with lock held */
4949 static gboolean
4950 handle_generic_unlocked (GDBusConnection *connection,
4951                          GDBusMessage    *message)
4952 {
4953   gboolean handled;
4954   const gchar *interface_name;
4955   const gchar *member;
4956   const gchar *signature;
4957   const gchar *path;
4958
4959   CONNECTION_ENSURE_LOCK (connection);
4960
4961   handled = FALSE;
4962
4963   interface_name = g_dbus_message_get_interface (message);
4964   member = g_dbus_message_get_member (message);
4965   signature = g_dbus_message_get_signature (message);
4966   path = g_dbus_message_get_path (message);
4967
4968   if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4969       g_strcmp0 (member, "Introspect") == 0 &&
4970       g_strcmp0 (signature, "") == 0)
4971     {
4972       handle_generic_introspect_unlocked (connection, path, message);
4973       handled = TRUE;
4974     }
4975   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
4976            g_strcmp0 (member, "Ping") == 0 &&
4977            g_strcmp0 (signature, "") == 0)
4978     {
4979       handle_generic_ping_unlocked (connection, path, message);
4980       handled = TRUE;
4981     }
4982   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
4983            g_strcmp0 (member, "GetMachineId") == 0 &&
4984            g_strcmp0 (signature, "") == 0)
4985     {
4986       handle_generic_get_machine_id_unlocked (connection, path, message);
4987       handled = TRUE;
4988     }
4989
4990   return handled;
4991 }
4992
4993 /* ---------------------------------------------------------------------------------------------------- */
4994
4995 /* called in message handler thread with lock held */
4996 static void
4997 distribute_method_call (GDBusConnection *connection,
4998                         GDBusMessage    *message)
4999 {
5000   ExportedObject *eo;
5001   ExportedSubtree *es;
5002   const gchar *object_path;
5003   const gchar *interface_name;
5004   const gchar *member;
5005   const gchar *signature;
5006   const gchar *path;
5007   gchar *subtree_path;
5008   gchar *needle;
5009
5010   g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
5011
5012   interface_name = g_dbus_message_get_interface (message);
5013   member = g_dbus_message_get_member (message);
5014   signature = g_dbus_message_get_signature (message);
5015   path = g_dbus_message_get_path (message);
5016   subtree_path = g_strdup (path);
5017   needle = strrchr (subtree_path, '/');
5018   if (needle != NULL && needle != subtree_path)
5019     {
5020       *needle = '\0';
5021     }
5022   else
5023     {
5024       g_free (subtree_path);
5025       subtree_path = NULL;
5026     }
5027
5028 #if 0
5029   g_debug ("interface    = `%s'", interface_name);
5030   g_debug ("member       = `%s'", member);
5031   g_debug ("signature    = `%s'", signature);
5032   g_debug ("path         = `%s'", path);
5033   g_debug ("subtree_path = `%s'", subtree_path != NULL ? subtree_path : "N/A");
5034 #endif
5035
5036   object_path = g_dbus_message_get_path (message);
5037   g_assert (object_path != NULL);
5038
5039   eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
5040   if (eo != NULL)
5041     {
5042       if (obj_message_func (connection, eo, message))
5043         goto out;
5044     }
5045
5046   es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
5047   if (es != NULL)
5048     {
5049       if (subtree_message_func (connection, es, message))
5050         goto out;
5051     }
5052
5053   if (subtree_path != NULL)
5054     {
5055       es = g_hash_table_lookup (connection->priv->map_object_path_to_es, subtree_path);
5056       if (es != NULL)
5057         {
5058           if (subtree_message_func (connection, es, message))
5059             goto out;
5060         }
5061     }
5062
5063   if (handle_generic_unlocked (connection, message))
5064     goto out;
5065
5066   /* if we end up here, the message has not been not handled */
5067
5068  out:
5069   g_free (subtree_path);
5070 }
5071
5072 /* ---------------------------------------------------------------------------------------------------- */
5073
5074 static GDBusConnection **
5075 message_bus_get_singleton (GBusType   bus_type,
5076                            GError   **error)
5077 {
5078   GDBusConnection **ret;
5079   const gchar *starter_bus;
5080
5081   ret = NULL;
5082
5083   switch (bus_type)
5084     {
5085     case G_BUS_TYPE_SESSION:
5086       ret = &the_session_bus;
5087       break;
5088
5089     case G_BUS_TYPE_SYSTEM:
5090       ret = &the_system_bus;
5091       break;
5092
5093     case G_BUS_TYPE_STARTER:
5094       starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
5095       if (g_strcmp0 (starter_bus, "session") == 0)
5096         {
5097           ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
5098           goto out;
5099         }
5100       else if (g_strcmp0 (starter_bus, "system") == 0)
5101         {
5102           ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
5103           goto out;
5104         }
5105       else
5106         {
5107           if (starter_bus != NULL)
5108             {
5109               g_set_error (error,
5110                            G_IO_ERROR,
5111                            G_IO_ERROR_INVALID_ARGUMENT,
5112                            _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
5113                              " - unknown value `%s'"),
5114                            starter_bus);
5115             }
5116           else
5117             {
5118               g_set_error_literal (error,
5119                                    G_IO_ERROR,
5120                                    G_IO_ERROR_INVALID_ARGUMENT,
5121                                    _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
5122                                      "variable is not set"));
5123             }
5124         }
5125       break;
5126
5127     default:
5128       g_assert_not_reached ();
5129       break;
5130     }
5131
5132  out:
5133   return ret;
5134 }
5135
5136 static GDBusConnection *
5137 get_uninitialized_connection (GBusType       bus_type,
5138                               GCancellable  *cancellable,
5139                               GError       **error)
5140 {
5141   GDBusConnection **singleton;
5142   GDBusConnection *ret;
5143
5144   ret = NULL;
5145
5146   G_LOCK (message_bus_lock);
5147   singleton = message_bus_get_singleton (bus_type, error);
5148   if (singleton == NULL)
5149     goto out;
5150
5151   if (*singleton == NULL)
5152     {
5153       gchar *address;
5154       address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
5155       if (address == NULL)
5156         goto out;
5157       ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
5158                                        "address", address,
5159                                        "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
5160                                                 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
5161                                        "exit-on-close", TRUE,
5162                                        NULL);
5163     }
5164   else
5165     {
5166       ret = g_object_ref (*singleton);
5167     }
5168
5169   g_assert (ret != NULL);
5170
5171  out:
5172   G_UNLOCK (message_bus_lock);
5173   return ret;
5174 }
5175
5176 /**
5177  * g_bus_get_sync:
5178  * @bus_type: A #GBusType.
5179  * @cancellable: A #GCancellable or %NULL.
5180  * @error: Return location for error or %NULL.
5181  *
5182  * Synchronously connects to the message bus specified by @bus_type.
5183  * Note that the returned object may shared with other callers,
5184  * e.g. if two separate parts of a process calls this function with
5185  * the same @bus_type, they will share the same object.
5186  *
5187  * This is a synchronous failable function. See g_bus_get() and
5188  * g_bus_get_finish() for the asynchronous version.
5189  *
5190  * The returned object is a singleton, that is, shared with other
5191  * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5192  * event that you need a private message bus connection, use
5193  * g_dbus_address_get_for_bus() and
5194  * g_dbus_connection_new_for_address().
5195  *
5196  * Note that the returned #GDBusConnection object will (usually) have
5197  * the #GDBusConnection:exit-on-close property set to %TRUE.
5198  *
5199  * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5200  *
5201  * Since: 2.26
5202  */
5203 GDBusConnection *
5204 g_bus_get_sync (GBusType       bus_type,
5205                 GCancellable  *cancellable,
5206                 GError       **error)
5207 {
5208   GDBusConnection *connection;
5209
5210   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5211
5212   connection = get_uninitialized_connection (bus_type, cancellable, error);
5213   if (connection == NULL)
5214     goto out;
5215
5216   if (!g_initable_init (G_INITABLE (connection), cancellable, error))
5217     {
5218       g_object_unref (connection);
5219       connection = NULL;
5220     }
5221
5222  out:
5223   return connection;
5224 }
5225
5226 static void
5227 bus_get_async_initable_cb (GObject      *source_object,
5228                            GAsyncResult *res,
5229                            gpointer      user_data)
5230 {
5231   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
5232   GError *error;
5233
5234   error = NULL;
5235   if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
5236                                      res,
5237                                      &error))
5238     {
5239       g_assert (error != NULL);
5240       g_simple_async_result_set_from_error (simple, error);
5241       g_error_free (error);
5242       g_object_unref (source_object);
5243     }
5244   else
5245     {
5246       g_simple_async_result_set_op_res_gpointer (simple,
5247                                                  source_object,
5248                                                  g_object_unref);
5249     }
5250   g_simple_async_result_complete_in_idle (simple);
5251   g_object_unref (simple);
5252 }
5253
5254 /**
5255  * g_bus_get:
5256  * @bus_type: A #GBusType.
5257  * @cancellable: A #GCancellable or %NULL.
5258  * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
5259  * @user_data: The data to pass to @callback.
5260  *
5261  * Asynchronously connects to the message bus specified by @bus_type.
5262  *
5263  * When the operation is finished, @callback will be invoked. You can
5264  * then call g_bus_get_finish() to get the result of the operation.
5265  *
5266  * This is a asynchronous failable function. See g_bus_get_sync() for
5267  * the synchronous version.
5268  *
5269  * Since: 2.26
5270  */
5271 void
5272 g_bus_get (GBusType             bus_type,
5273            GCancellable        *cancellable,
5274            GAsyncReadyCallback  callback,
5275            gpointer             user_data)
5276 {
5277   GDBusConnection *connection;
5278   GSimpleAsyncResult *simple;
5279   GError *error;
5280
5281   simple = g_simple_async_result_new (NULL,
5282                                       callback,
5283                                       user_data,
5284                                       g_bus_get);
5285
5286   error = NULL;
5287   connection = get_uninitialized_connection (bus_type, cancellable, &error);
5288   if (connection == NULL)
5289     {
5290       g_assert (error != NULL);
5291       g_simple_async_result_set_from_error (simple, error);
5292       g_error_free (error);
5293       g_simple_async_result_complete_in_idle (simple);
5294       g_object_unref (simple);
5295     }
5296   else
5297     {
5298       g_async_initable_init_async (G_ASYNC_INITABLE (connection),
5299                                    G_PRIORITY_DEFAULT,
5300                                    cancellable,
5301                                    bus_get_async_initable_cb,
5302                                    simple);
5303     }
5304 }
5305
5306 /**
5307  * g_bus_get_finish:
5308  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
5309  * @error: Return location for error or %NULL.
5310  *
5311  * Finishes an operation started with g_bus_get().
5312  *
5313  * The returned object is a singleton, that is, shared with other
5314  * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5315  * event that you need a private message bus connection, use
5316  * g_dbus_address_get_for_bus() and
5317  * g_dbus_connection_new_for_address().
5318  *
5319  * Note that the returned #GDBusConnection object will (usually) have
5320  * the #GDBusConnection:exit-on-close property set to %TRUE.
5321  *
5322  * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5323  *
5324  * Since: 2.26
5325  */
5326 GDBusConnection *
5327 g_bus_get_finish (GAsyncResult  *res,
5328                   GError       **error)
5329 {
5330   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
5331   GObject *object;
5332   GDBusConnection *ret;
5333
5334   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5335
5336   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
5337
5338   ret = NULL;
5339
5340   if (g_simple_async_result_propagate_error (simple, error))
5341     goto out;
5342
5343   object = g_simple_async_result_get_op_res_gpointer (simple);
5344   g_assert (object != NULL);
5345   ret = g_object_ref (G_DBUS_CONNECTION (object));
5346
5347  out:
5348   return ret;
5349 }
5350
5351 /* ---------------------------------------------------------------------------------------------------- */
5352
5353 #define __G_DBUS_CONNECTION_C__
5354 #include "gioaliasdef.c"