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