908dfeab792e9d3d099b36807b2d53307f0d16eb
[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=message, 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   if (G_UNLIKELY (_g_dbus_debug_signal ()))
3011     {
3012       _g_dbus_debug_print_lock ();
3013       g_print ("========================================================================\n"
3014                "GDBus-debug:Signal:\n"
3015                " >>>> SIGNAL %s.%s\n"
3016                "      on object %s\n"
3017                "      sent by name %s\n",
3018                g_dbus_message_get_interface (message),
3019                g_dbus_message_get_member (message),
3020                g_dbus_message_get_path (message),
3021                sender != NULL ? sender : "(none)");
3022       _g_dbus_debug_print_unlock ();
3023     }
3024
3025   /* collect subscribers that match on sender */
3026   if (sender != NULL)
3027     {
3028       signal_data_array = g_hash_table_lookup (connection->priv->map_sender_unique_name_to_signal_data_array, sender);
3029       if (signal_data_array != NULL)
3030         schedule_callbacks (connection, signal_data_array, message, sender);
3031     }
3032
3033   /* collect subscribers not matching on sender */
3034   signal_data_array = g_hash_table_lookup (connection->priv->map_sender_unique_name_to_signal_data_array, "");
3035   if (signal_data_array != NULL)
3036     schedule_callbacks (connection, signal_data_array, message, sender);
3037 }
3038
3039 /* ---------------------------------------------------------------------------------------------------- */
3040
3041 /* only called from finalize(), removes all subscriptions */
3042 static void
3043 purge_all_signal_subscriptions (GDBusConnection *connection)
3044 {
3045   GHashTableIter iter;
3046   gpointer key;
3047   GArray *ids;
3048   GArray *subscribers;
3049   guint n;
3050
3051   ids = g_array_new (FALSE, FALSE, sizeof (guint));
3052   g_hash_table_iter_init (&iter, connection->priv->map_id_to_signal_data);
3053   while (g_hash_table_iter_next (&iter, &key, NULL))
3054     {
3055       guint subscription_id = GPOINTER_TO_UINT (key);
3056       g_array_append_val (ids, subscription_id);
3057     }
3058
3059   subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3060   for (n = 0; n < ids->len; n++)
3061     {
3062       guint subscription_id = g_array_index (ids, guint, n);
3063       unsubscribe_id_internal (connection,
3064                                subscription_id,
3065                                subscribers);
3066     }
3067   g_array_free (ids, TRUE);
3068
3069   /* call GDestroyNotify without lock held */
3070   for (n = 0; n < subscribers->len; n++)
3071     {
3072       SignalSubscriber *subscriber;
3073       subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3074       if (subscriber->user_data_free_func != NULL)
3075         subscriber->user_data_free_func (subscriber->user_data);
3076       if (subscriber->context != NULL)
3077         g_main_context_unref (subscriber->context);
3078     }
3079
3080   g_array_free (subscribers, TRUE);
3081 }
3082
3083 /* ---------------------------------------------------------------------------------------------------- */
3084
3085 struct ExportedObject
3086 {
3087   gchar *object_path;
3088   GDBusConnection *connection;
3089
3090   /* maps gchar* -> ExportedInterface* */
3091   GHashTable *map_if_name_to_ei;
3092 };
3093
3094 /* only called with lock held */
3095 static void
3096 exported_object_free (ExportedObject *eo)
3097 {
3098   g_free (eo->object_path);
3099   g_hash_table_unref (eo->map_if_name_to_ei);
3100   g_free (eo);
3101 }
3102
3103 typedef struct
3104 {
3105   ExportedObject *eo;
3106
3107   guint                       id;
3108   gchar                      *interface_name;
3109   const GDBusInterfaceVTable *vtable;
3110   const GDBusInterfaceInfo   *interface_info;
3111
3112   GMainContext               *context;
3113   gpointer                    user_data;
3114   GDestroyNotify              user_data_free_func;
3115 } ExportedInterface;
3116
3117 /* called with lock held */
3118 static void
3119 exported_interface_free (ExportedInterface *ei)
3120 {
3121   g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
3122
3123   if (ei->user_data_free_func != NULL)
3124     /* TODO: push to thread-default mainloop */
3125     ei->user_data_free_func (ei->user_data);
3126
3127   if (ei->context != NULL)
3128     g_main_context_unref (ei->context);
3129
3130   g_free (ei->interface_name);
3131   g_free (ei);
3132 }
3133
3134 /* ---------------------------------------------------------------------------------------------------- */
3135
3136 /* Convenience function to check if @registration_id (if not zero) or
3137  * @subtree_registration_id (if not zero) has been unregistered. If
3138  * so, returns %TRUE.
3139  *
3140  * Caller must *not* hold lock.
3141  */
3142 static gboolean
3143 has_object_been_unregistered (GDBusConnection  *connection,
3144                               guint             registration_id,
3145                               guint             subtree_registration_id)
3146 {
3147   gboolean ret;
3148
3149   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3150
3151   ret = FALSE;
3152
3153   CONNECTION_LOCK (connection);
3154   if (registration_id != 0 && g_hash_table_lookup (connection->priv->map_id_to_ei,
3155                                                    GUINT_TO_POINTER (registration_id)) == NULL)
3156     {
3157       ret = TRUE;
3158     }
3159   else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->priv->map_id_to_es,
3160                                                                 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
3161     {
3162       ret = TRUE;
3163     }
3164   CONNECTION_UNLOCK (connection);
3165
3166   return ret;
3167 }
3168
3169 /* ---------------------------------------------------------------------------------------------------- */
3170
3171 typedef struct
3172 {
3173   GDBusConnection *connection;
3174   GDBusMessage *message;
3175   gpointer user_data;
3176   const gchar *property_name;
3177   const GDBusInterfaceVTable *vtable;
3178   const GDBusInterfaceInfo *interface_info;
3179   const GDBusPropertyInfo *property_info;
3180   guint registration_id;
3181   guint subtree_registration_id;
3182 } PropertyData;
3183
3184 static void
3185 property_data_free (PropertyData *data)
3186 {
3187   g_object_unref (data->connection);
3188   g_object_unref (data->message);
3189   g_free (data);
3190 }
3191
3192 /* called in thread where object was registered - no locks held */
3193 static gboolean
3194 invoke_get_property_in_idle_cb (gpointer _data)
3195 {
3196   PropertyData *data = _data;
3197   GVariant *value;
3198   GError *error;
3199   GDBusMessage *reply;
3200
3201   if (has_object_been_unregistered (data->connection,
3202                                     data->registration_id,
3203                                     data->subtree_registration_id))
3204     {
3205       reply = g_dbus_message_new_method_error (data->message,
3206                                                "org.freedesktop.DBus.Error.UnknownMethod",
3207                                                _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
3208                                                g_dbus_message_get_path (data->message));
3209       g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3210       g_object_unref (reply);
3211       goto out;
3212     }
3213
3214   error = NULL;
3215   value = data->vtable->get_property (data->connection,
3216                                       g_dbus_message_get_sender (data->message),
3217                                       g_dbus_message_get_path (data->message),
3218                                       data->interface_info->name,
3219                                       data->property_name,
3220                                       &error,
3221                                       data->user_data);
3222
3223
3224   if (value != NULL)
3225     {
3226       g_assert_no_error (error);
3227
3228       g_variant_ref_sink (value);
3229       reply = g_dbus_message_new_method_reply (data->message);
3230       g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
3231       g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3232       g_variant_unref (value);
3233       g_object_unref (reply);
3234     }
3235   else
3236     {
3237       gchar *dbus_error_name;
3238       g_assert (error != NULL);
3239       dbus_error_name = g_dbus_error_encode_gerror (error);
3240       reply = g_dbus_message_new_method_error_literal (data->message,
3241                                                        dbus_error_name,
3242                                                        error->message);
3243       g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3244       g_free (dbus_error_name);
3245       g_error_free (error);
3246       g_object_unref (reply);
3247     }
3248
3249  out:
3250   return FALSE;
3251 }
3252
3253 /* called in thread where object was registered - no locks held */
3254 static gboolean
3255 invoke_set_property_in_idle_cb (gpointer _data)
3256 {
3257   PropertyData *data = _data;
3258   GError *error;
3259   GDBusMessage *reply;
3260   GVariant *value;
3261
3262   error = NULL;
3263   value = NULL;
3264
3265   g_variant_get (g_dbus_message_get_body (data->message),
3266                  "(ssv)",
3267                  NULL,
3268                  NULL,
3269                  &value);
3270
3271   /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
3272    * of the given value is wrong
3273    */
3274   if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
3275     {
3276       reply = g_dbus_message_new_method_error (data->message,
3277                                                "org.freedesktop.DBus.Error.InvalidArgs",
3278                                                _("Error setting property `%s': Expected type `%s' but got `%s'"),
3279                                                data->property_info->name,
3280                                                data->property_info->signature,
3281                                                g_variant_get_type_string (value));
3282       goto out;
3283     }
3284
3285   if (!data->vtable->set_property (data->connection,
3286                                    g_dbus_message_get_sender (data->message),
3287                                    g_dbus_message_get_path (data->message),
3288                                    data->interface_info->name,
3289                                    data->property_name,
3290                                    value,
3291                                    &error,
3292                                    data->user_data))
3293     {
3294       gchar *dbus_error_name;
3295       g_assert (error != NULL);
3296       dbus_error_name = g_dbus_error_encode_gerror (error);
3297       reply = g_dbus_message_new_method_error_literal (data->message,
3298                                                        dbus_error_name,
3299                                                        error->message);
3300       g_free (dbus_error_name);
3301       g_error_free (error);
3302     }
3303   else
3304     {
3305       reply = g_dbus_message_new_method_reply (data->message);
3306     }
3307
3308  out:
3309   g_assert (reply != NULL);
3310   g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3311   g_object_unref (reply);
3312
3313   return FALSE;
3314 }
3315
3316 /* called with lock held */
3317 static gboolean
3318 validate_and_maybe_schedule_property_getset (GDBusConnection            *connection,
3319                                              GDBusMessage               *message,
3320                                              guint                       registration_id,
3321                                              guint                       subtree_registration_id,
3322                                              gboolean                    is_get,
3323                                              const GDBusInterfaceInfo   *interface_info,
3324                                              const GDBusInterfaceVTable *vtable,
3325                                              GMainContext               *main_context,
3326                                              gpointer                    user_data)
3327 {
3328   gboolean handled;
3329   const char *interface_name;
3330   const char *property_name;
3331   const GDBusPropertyInfo *property_info;
3332   GSource *idle_source;
3333   PropertyData *property_data;
3334   GDBusMessage *reply;
3335
3336   handled = FALSE;
3337
3338   if (is_get)
3339     g_variant_get (g_dbus_message_get_body (message),
3340                    "(&s&s)",
3341                    &interface_name,
3342                    &property_name);
3343   else
3344     g_variant_get (g_dbus_message_get_body (message),
3345                    "(&s&sv)",
3346                    &interface_name,
3347                    &property_name,
3348                    NULL);
3349
3350
3351   if (is_get)
3352     {
3353       if (vtable == NULL || vtable->get_property == NULL)
3354         goto out;
3355     }
3356   else
3357     {
3358       if (vtable == NULL || vtable->set_property == NULL)
3359         goto out;
3360     }
3361
3362   /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
3363    */
3364   property_info = NULL;
3365
3366   /* TODO: the cost of this is O(n) - it might be worth caching the result */
3367   property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
3368   if (property_info == NULL)
3369     {
3370       reply = g_dbus_message_new_method_error (message,
3371                                                "org.freedesktop.DBus.Error.InvalidArgs",
3372                                                _("No such property `%s'"),
3373                                                property_name);
3374       g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3375       g_object_unref (reply);
3376       handled = TRUE;
3377       goto out;
3378     }
3379
3380   if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3381     {
3382       reply = g_dbus_message_new_method_error (message,
3383                                                "org.freedesktop.DBus.Error.InvalidArgs",
3384                                                _("Property `%s' is not readable"),
3385                                                property_name);
3386       g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3387       g_object_unref (reply);
3388       handled = TRUE;
3389       goto out;
3390     }
3391   else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
3392     {
3393       reply = g_dbus_message_new_method_error (message,
3394                                                "org.freedesktop.DBus.Error.InvalidArgs",
3395                                                _("Property `%s' is not writable"),
3396                                                property_name);
3397       g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3398       g_object_unref (reply);
3399       handled = TRUE;
3400       goto out;
3401     }
3402
3403   /* ok, got the property info - call user code in an idle handler */
3404   property_data = g_new0 (PropertyData, 1);
3405   property_data->connection = g_object_ref (connection);
3406   property_data->message = g_object_ref (message);
3407   property_data->user_data = user_data;
3408   property_data->property_name = property_name;
3409   property_data->vtable = vtable;
3410   property_data->interface_info = interface_info;
3411   property_data->property_info = property_info;
3412   property_data->registration_id = registration_id;
3413   property_data->subtree_registration_id = subtree_registration_id;
3414
3415   idle_source = g_idle_source_new ();
3416   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3417   g_source_set_callback (idle_source,
3418                          is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
3419                          property_data,
3420                          (GDestroyNotify) property_data_free);
3421   g_source_attach (idle_source, main_context);
3422   g_source_unref (idle_source);
3423
3424   handled = TRUE;
3425
3426  out:
3427   return handled;
3428 }
3429
3430 /* called with lock held */
3431 static gboolean
3432 handle_getset_property (GDBusConnection *connection,
3433                         ExportedObject  *eo,
3434                         GDBusMessage    *message,
3435                         gboolean         is_get)
3436 {
3437   ExportedInterface *ei;
3438   gboolean handled;
3439   const char *interface_name;
3440   const char *property_name;
3441
3442   handled = FALSE;
3443
3444   if (is_get)
3445     g_variant_get (g_dbus_message_get_body (message),
3446                    "(&s&s)",
3447                    &interface_name,
3448                    &property_name);
3449   else
3450     g_variant_get (g_dbus_message_get_body (message),
3451                    "(&s&sv)",
3452                    &interface_name,
3453                    &property_name,
3454                    NULL);
3455
3456   /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3457    * no such interface registered
3458    */
3459   ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3460   if (ei == NULL)
3461     {
3462       GDBusMessage *reply;
3463       reply = g_dbus_message_new_method_error (message,
3464                                                "org.freedesktop.DBus.Error.InvalidArgs",
3465                                                _("No such interface `%s'"),
3466                                                interface_name);
3467       g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3468       g_object_unref (reply);
3469       handled = TRUE;
3470       goto out;
3471     }
3472
3473   handled = validate_and_maybe_schedule_property_getset (eo->connection,
3474                                                          message,
3475                                                          ei->id,
3476                                                          0,
3477                                                          is_get,
3478                                                          ei->interface_info,
3479                                                          ei->vtable,
3480                                                          ei->context,
3481                                                          ei->user_data);
3482  out:
3483   return handled;
3484 }
3485
3486 /* ---------------------------------------------------------------------------------------------------- */
3487
3488 typedef struct
3489 {
3490   GDBusConnection *connection;
3491   GDBusMessage *message;
3492   gpointer user_data;
3493   const GDBusInterfaceVTable *vtable;
3494   const GDBusInterfaceInfo *interface_info;
3495   guint registration_id;
3496   guint subtree_registration_id;
3497 } PropertyGetAllData;
3498
3499 static void
3500 property_get_all_data_free (PropertyData *data)
3501 {
3502   g_object_unref (data->connection);
3503   g_object_unref (data->message);
3504   g_free (data);
3505 }
3506
3507 /* called in thread where object was registered - no locks held */
3508 static gboolean
3509 invoke_get_all_properties_in_idle_cb (gpointer _data)
3510 {
3511   PropertyGetAllData *data = _data;
3512   GVariantBuilder builder;
3513   GError *error;
3514   GDBusMessage *reply;
3515   guint n;
3516
3517   if (has_object_been_unregistered (data->connection,
3518                                     data->registration_id,
3519                                     data->subtree_registration_id))
3520     {
3521       reply = g_dbus_message_new_method_error (data->message,
3522                                                "org.freedesktop.DBus.Error.UnknownMethod",
3523                                                _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
3524                                                g_dbus_message_get_path (data->message));
3525       g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3526       g_object_unref (reply);
3527       goto out;
3528     }
3529
3530   error = NULL;
3531
3532   /* TODO: Right now we never fail this call - we just omit values if
3533    *       a get_property() call is failing.
3534    *
3535    *       We could fail the whole call if just a single get_property() call
3536    *       returns an error. We need clarification in the D-Bus spec about this.
3537    */
3538   g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
3539   g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
3540   for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
3541     {
3542       const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
3543       GVariant *value;
3544
3545       if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3546         continue;
3547
3548       value = data->vtable->get_property (data->connection,
3549                                           g_dbus_message_get_sender (data->message),
3550                                           g_dbus_message_get_path (data->message),
3551                                           data->interface_info->name,
3552                                           property_info->name,
3553                                           NULL,
3554                                           data->user_data);
3555
3556       if (value == NULL)
3557         continue;
3558
3559       g_variant_builder_add (&builder,
3560                              "{sv}",
3561                              property_info->name,
3562                              value);
3563     }
3564   g_variant_builder_close (&builder);
3565
3566   reply = g_dbus_message_new_method_reply (data->message);
3567   g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
3568   g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3569   g_object_unref (reply);
3570
3571  out:
3572   return FALSE;
3573 }
3574
3575 /* called with lock held */
3576 static gboolean
3577 validate_and_maybe_schedule_property_get_all (GDBusConnection            *connection,
3578                                               GDBusMessage               *message,
3579                                               guint                       registration_id,
3580                                               guint                       subtree_registration_id,
3581                                               const GDBusInterfaceInfo   *interface_info,
3582                                               const GDBusInterfaceVTable *vtable,
3583                                               GMainContext               *main_context,
3584                                               gpointer                    user_data)
3585 {
3586   gboolean handled;
3587   const char *interface_name;
3588   GSource *idle_source;
3589   PropertyGetAllData *property_get_all_data;
3590
3591   handled = FALSE;
3592
3593   g_variant_get (g_dbus_message_get_body (message),
3594                  "(&s)",
3595                  &interface_name);
3596
3597   if (vtable == NULL || vtable->get_property == NULL)
3598     goto out;
3599
3600   /* ok, got the property info - call user in an idle handler */
3601   property_get_all_data = g_new0 (PropertyGetAllData, 1);
3602   property_get_all_data->connection = g_object_ref (connection);
3603   property_get_all_data->message = g_object_ref (message);
3604   property_get_all_data->user_data = user_data;
3605   property_get_all_data->vtable = vtable;
3606   property_get_all_data->interface_info = interface_info;
3607   property_get_all_data->registration_id = registration_id;
3608   property_get_all_data->subtree_registration_id = subtree_registration_id;
3609
3610   idle_source = g_idle_source_new ();
3611   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3612   g_source_set_callback (idle_source,
3613                          invoke_get_all_properties_in_idle_cb,
3614                          property_get_all_data,
3615                          (GDestroyNotify) property_get_all_data_free);
3616   g_source_attach (idle_source, main_context);
3617   g_source_unref (idle_source);
3618
3619   handled = TRUE;
3620
3621  out:
3622   return handled;
3623 }
3624
3625 /* called with lock held */
3626 static gboolean
3627 handle_get_all_properties (GDBusConnection *connection,
3628                            ExportedObject  *eo,
3629                            GDBusMessage    *message)
3630 {
3631   ExportedInterface *ei;
3632   gboolean handled;
3633   const char *interface_name;
3634
3635   handled = FALSE;
3636
3637   g_variant_get (g_dbus_message_get_body (message),
3638                  "(&s)",
3639                  &interface_name);
3640
3641   /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3642    * no such interface registered
3643    */
3644   ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3645   if (ei == NULL)
3646     {
3647       GDBusMessage *reply;
3648       reply = g_dbus_message_new_method_error (message,
3649                                                "org.freedesktop.DBus.Error.InvalidArgs",
3650                                                _("No such interface"),
3651                                                interface_name);
3652       g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3653       g_object_unref (reply);
3654       handled = TRUE;
3655       goto out;
3656     }
3657
3658   handled = validate_and_maybe_schedule_property_get_all (eo->connection,
3659                                                           message,
3660                                                           ei->id,
3661                                                           0,
3662                                                           ei->interface_info,
3663                                                           ei->vtable,
3664                                                           ei->context,
3665                                                           ei->user_data);
3666  out:
3667   return handled;
3668 }
3669
3670 /* ---------------------------------------------------------------------------------------------------- */
3671
3672 static const gchar introspect_header[] =
3673   "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
3674   "                      \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
3675   "<!-- GDBus " PACKAGE_VERSION " -->\n"
3676   "<node>\n";
3677
3678 static const gchar introspect_tail[] =
3679   "</node>\n";
3680
3681 static const gchar introspect_standard_interfaces[] =
3682   "  <interface name=\"org.freedesktop.DBus.Properties\">\n"
3683   "    <method name=\"Get\">\n"
3684   "      <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3685   "      <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3686   "      <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
3687   "    </method>\n"
3688   "    <method name=\"GetAll\">\n"
3689   "      <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3690   "      <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
3691   "    </method>\n"
3692   "    <method name=\"Set\">\n"
3693   "      <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3694   "      <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3695   "      <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
3696   "    </method>\n"
3697   "    <signal name=\"PropertiesChanged\">\n"
3698   "      <arg type=\"s\" name=\"interface_name\"/>\n"
3699   "      <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
3700   "      <arg type=\"as\" name=\"invalidated_properties\"/>\n"
3701   "    </signal>\n"
3702   "  </interface>\n"
3703   "  <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
3704   "    <method name=\"Introspect\">\n"
3705   "      <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
3706   "    </method>\n"
3707   "  </interface>\n"
3708   "  <interface name=\"org.freedesktop.DBus.Peer\">\n"
3709   "    <method name=\"Ping\"/>\n"
3710   "    <method name=\"GetMachineId\">\n"
3711   "      <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
3712   "    </method>\n"
3713   "  </interface>\n";
3714
3715 static void
3716 introspect_append_header (GString *s)
3717 {
3718   g_string_append (s, introspect_header);
3719 }
3720
3721 static void
3722 introspect_append_standard_interfaces (GString *s)
3723 {
3724   g_string_append (s, introspect_standard_interfaces);
3725 }
3726
3727 static void
3728 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
3729 {
3730   if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
3731     {
3732       const gchar *begin;
3733       const gchar *end;
3734       gchar *s;
3735
3736       begin = object_path + path_len;
3737       end = strchr (begin, '/');
3738       if (end != NULL)
3739         s = g_strndup (begin, end - begin);
3740       else
3741         s = g_strdup (begin);
3742
3743       if (g_hash_table_lookup (set, s) == NULL)
3744         g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
3745       else
3746         g_free (s);
3747     }
3748 }
3749
3750 /* TODO: we want a nicer public interface for this */
3751 static gchar **
3752 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
3753                                             const gchar     *path)
3754 {
3755   GPtrArray *p;
3756   gchar **ret;
3757   GHashTableIter hash_iter;
3758   const gchar *object_path;
3759   gsize path_len;
3760   GHashTable *set;
3761   GList *keys;
3762   GList *l;
3763
3764   CONNECTION_ENSURE_LOCK (connection);
3765
3766   path_len = strlen (path);
3767   if (path_len > 1)
3768     path_len++;
3769
3770   set = g_hash_table_new (g_str_hash, g_str_equal);
3771
3772   g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_eo);
3773   while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3774     maybe_add_path (path, path_len, object_path, set);
3775
3776   g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_es);
3777   while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3778     maybe_add_path (path, path_len, object_path, set);
3779
3780   p = g_ptr_array_new ();
3781   keys = g_hash_table_get_keys (set);
3782   for (l = keys; l != NULL; l = l->next)
3783     g_ptr_array_add (p, l->data);
3784   g_hash_table_unref (set);
3785   g_list_free (keys);
3786
3787   g_ptr_array_add (p, NULL);
3788   ret = (gchar **) g_ptr_array_free (p, FALSE);
3789   return ret;
3790 }
3791
3792 static gchar **
3793 g_dbus_connection_list_registered (GDBusConnection *connection,
3794                                    const gchar     *path)
3795 {
3796   gchar **ret;
3797   CONNECTION_LOCK (connection);
3798   ret = g_dbus_connection_list_registered_unlocked (connection, path);
3799   CONNECTION_UNLOCK (connection);
3800   return ret;
3801 }
3802
3803 /* called in message handler thread with lock held */
3804 static gboolean
3805 handle_introspect (GDBusConnection *connection,
3806                    ExportedObject  *eo,
3807                    GDBusMessage    *message)
3808 {
3809   guint n;
3810   GString *s;
3811   GDBusMessage *reply;
3812   GHashTableIter hash_iter;
3813   ExportedInterface *ei;
3814   gchar **registered;
3815
3816   /* first the header with the standard interfaces */
3817   s = g_string_sized_new (sizeof (introspect_header) +
3818                           sizeof (introspect_standard_interfaces) +
3819                           sizeof (introspect_tail));
3820   introspect_append_header (s);
3821   introspect_append_standard_interfaces (s);
3822
3823   /* then include the registered interfaces */
3824   g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
3825   while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
3826     g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
3827
3828   /* finally include nodes registered below us */
3829   registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
3830   for (n = 0; registered != NULL && registered[n] != NULL; n++)
3831     g_string_append_printf (s, "  <node name=\"%s\"/>\n", registered[n]);
3832   g_strfreev (registered);
3833   g_string_append (s, introspect_tail);
3834
3835   reply = g_dbus_message_new_method_reply (message);
3836   g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
3837   g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3838   g_object_unref (reply);
3839   g_string_free (s, TRUE);
3840
3841   return TRUE;
3842 }
3843
3844 /* called in thread where object was registered - no locks held */
3845 static gboolean
3846 call_in_idle_cb (gpointer user_data)
3847 {
3848   GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
3849   GDBusInterfaceVTable *vtable;
3850   guint registration_id;
3851   guint subtree_registration_id;
3852
3853   vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
3854   g_assert (vtable != NULL && vtable->method_call != NULL);
3855
3856   registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
3857   subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
3858
3859   if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
3860                                     registration_id,
3861                                     subtree_registration_id))
3862     {
3863       GDBusMessage *reply;
3864       reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
3865                                                "org.freedesktop.DBus.Error.UnknownMethod",
3866                                                _("No such interface `%s' on object at path %s"),
3867                                                g_dbus_method_invocation_get_interface_name (invocation),
3868                                                g_dbus_method_invocation_get_object_path (invocation));
3869       g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, NULL, NULL);
3870       g_object_unref (reply);
3871       goto out;
3872     }
3873
3874   vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
3875                        g_dbus_method_invocation_get_sender (invocation),
3876                        g_dbus_method_invocation_get_object_path (invocation),
3877                        g_dbus_method_invocation_get_interface_name (invocation),
3878                        g_dbus_method_invocation_get_method_name (invocation),
3879                        g_dbus_method_invocation_get_parameters (invocation),
3880                        g_object_ref (invocation),
3881                        g_dbus_method_invocation_get_user_data (invocation));
3882
3883  out:
3884   return FALSE;
3885 }
3886
3887 /* called in message handler thread with lock held */
3888 static gboolean
3889 validate_and_maybe_schedule_method_call (GDBusConnection            *connection,
3890                                          GDBusMessage               *message,
3891                                          guint                       registration_id,
3892                                          guint                       subtree_registration_id,
3893                                          const GDBusInterfaceInfo   *interface_info,
3894                                          const GDBusInterfaceVTable *vtable,
3895                                          GMainContext               *main_context,
3896                                          gpointer                    user_data)
3897 {
3898   GDBusMethodInvocation *invocation;
3899   const GDBusMethodInfo *method_info;
3900   GDBusMessage *reply;
3901   GVariant *parameters;
3902   GSource *idle_source;
3903   gboolean handled;
3904   GVariantType *in_type;
3905
3906   handled = FALSE;
3907
3908   /* TODO: the cost of this is O(n) - it might be worth caching the result */
3909   method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
3910
3911   /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
3912    * error to the caller
3913    */
3914   if (method_info == NULL)
3915     {
3916       reply = g_dbus_message_new_method_error (message,
3917                                                "org.freedesktop.DBus.Error.UnknownMethod",
3918                                                _("No such method `%s'"),
3919                                                g_dbus_message_get_member (message));
3920       g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3921       g_object_unref (reply);
3922       handled = TRUE;
3923       goto out;
3924     }
3925
3926   parameters = g_dbus_message_get_body (message);
3927   if (parameters == NULL)
3928     {
3929       parameters = g_variant_new ("()");
3930       g_variant_ref_sink (parameters);
3931     }
3932   else
3933     {
3934       g_variant_ref (parameters);
3935     }
3936
3937   /* Check that the incoming args are of the right type - if they are not, return
3938    * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
3939    */
3940   in_type = _g_dbus_compute_complete_signature (method_info->in_args);
3941   if (!g_variant_is_of_type (parameters, in_type))
3942     {
3943       gchar *type_string;
3944
3945       type_string = g_variant_type_dup_string (in_type);
3946
3947       reply = g_dbus_message_new_method_error (message,
3948                                                "org.freedesktop.DBus.Error.InvalidArgs",
3949                                                _("Type of message, `%s', does not match expected type `%s'"),
3950                                                g_variant_get_type_string (parameters),
3951                                                type_string);
3952       g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3953       g_variant_type_free (in_type);
3954       g_variant_unref (parameters);
3955       g_object_unref (reply);
3956       g_free (type_string);
3957       handled = TRUE;
3958       goto out;
3959     }
3960   g_variant_type_free (in_type);
3961
3962   /* schedule the call in idle */
3963   invocation = g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
3964                                              g_dbus_message_get_path (message),
3965                                              g_dbus_message_get_interface (message),
3966                                              g_dbus_message_get_member (message),
3967                                              method_info,
3968                                              connection,
3969                                              message,
3970                                              parameters,
3971                                              user_data);
3972   g_variant_unref (parameters);
3973
3974   /* TODO: would be nicer with a real MethodData like we already
3975    * have PropertyData and PropertyGetAllData... */
3976   g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
3977   g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
3978   g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
3979
3980   idle_source = g_idle_source_new ();
3981   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3982   g_source_set_callback (idle_source,
3983                          call_in_idle_cb,
3984                          invocation,
3985                          g_object_unref);
3986   g_source_attach (idle_source, main_context);
3987   g_source_unref (idle_source);
3988
3989   handled = TRUE;
3990
3991  out:
3992   return handled;
3993 }
3994
3995 /* ---------------------------------------------------------------------------------------------------- */
3996
3997 /* called in message handler thread with lock held */
3998 static gboolean
3999 obj_message_func (GDBusConnection *connection,
4000                   ExportedObject  *eo,
4001                   GDBusMessage    *message)
4002 {
4003   const gchar *interface_name;
4004   const gchar *member;
4005   const gchar *signature;
4006   gboolean handled;
4007
4008   handled = FALSE;
4009
4010   interface_name = g_dbus_message_get_interface (message);
4011   member = g_dbus_message_get_member (message);
4012   signature = g_dbus_message_get_signature (message);
4013
4014   /* see if we have an interface for handling this call */
4015   if (interface_name != NULL)
4016     {
4017       ExportedInterface *ei;
4018       ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4019       if (ei != NULL)
4020         {
4021           /* we do - invoke the handler in idle in the right thread */
4022
4023           /* handle no vtable or handler being present */
4024           if (ei->vtable == NULL || ei->vtable->method_call == NULL)
4025             goto out;
4026
4027           handled = validate_and_maybe_schedule_method_call (connection,
4028                                                              message,
4029                                                              ei->id,
4030                                                              0,
4031                                                              ei->interface_info,
4032                                                              ei->vtable,
4033                                                              ei->context,
4034                                                              ei->user_data);
4035           goto out;
4036         }
4037     }
4038
4039   if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4040       g_strcmp0 (member, "Introspect") == 0 &&
4041       g_strcmp0 (signature, "") == 0)
4042     {
4043       handled = handle_introspect (connection, eo, message);
4044       goto out;
4045     }
4046   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4047            g_strcmp0 (member, "Get") == 0 &&
4048            g_strcmp0 (signature, "ss") == 0)
4049     {
4050       handled = handle_getset_property (connection, eo, message, TRUE);
4051       goto out;
4052     }
4053   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4054            g_strcmp0 (member, "Set") == 0 &&
4055            g_strcmp0 (signature, "ssv") == 0)
4056     {
4057       handled = handle_getset_property (connection, eo, message, FALSE);
4058       goto out;
4059     }
4060   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4061            g_strcmp0 (member, "GetAll") == 0 &&
4062            g_strcmp0 (signature, "s") == 0)
4063     {
4064       handled = handle_get_all_properties (connection, eo, message);
4065       goto out;
4066     }
4067
4068  out:
4069   return handled;
4070 }
4071
4072 /**
4073  * g_dbus_connection_register_object:
4074  * @connection: A #GDBusConnection.
4075  * @object_path: The object path to register at.
4076  * @interface_info: Introspection data for the interface.
4077  * @vtable: A #GDBusInterfaceVTable to call into or %NULL.
4078  * @user_data: Data to pass to functions in @vtable.
4079  * @user_data_free_func: Function to call when the object path is unregistered.
4080  * @error: Return location for error or %NULL.
4081  *
4082  * Registers callbacks for exported objects at @object_path with the
4083  * D-Bus interface that is described in @interface_info.
4084  *
4085  * Calls to functions in @vtable (and @user_data_free_func) will
4086  * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
4087  * loop</link> of the thread you are calling this method from.
4088  *
4089  * Note that all #GVariant values passed to functions in @vtable will match
4090  * the signature given in @interface_info - if a remote caller passes
4091  * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
4092  * is returned to the remote caller.
4093  *
4094  * Additionally, if the remote caller attempts to invoke methods or
4095  * access properties not mentioned in @interface_info the
4096  * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
4097  * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
4098  * are returned to the caller.
4099  *
4100  * It is considered a programming error if the
4101  * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
4102  * #GVariant of incorrect type.
4103  *
4104  * If an existing callback is already registered at @object_path and
4105  * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
4106  *
4107  * Note that @vtable is not copied, so the struct you pass must exist until
4108  * the path is unregistered. One possibility is to free @vtable at the
4109  * same time as @user_data when @user_data_free_func is called.
4110  *
4111  * GDBus automatically implements the standard D-Bus interfaces
4112  * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
4113  * and org.freedesktop.Peer, so you don't have to implement those for
4114  * the objects you export. You <emphasis>can</emphasis> implement
4115  * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
4116  * and setting of properties asynchronously.
4117  *
4118  * See <xref linkend="gdbus-server"/> for an example of how to use this method.
4119  *
4120  * Returns: 0 if @error is set, otherwise a registration id (never 0)
4121  * that can be used with g_dbus_connection_unregister_object() .
4122  *
4123  * Since: 2.26
4124  */
4125 guint
4126 g_dbus_connection_register_object (GDBusConnection            *connection,
4127                                    const gchar                *object_path,
4128                                    const GDBusInterfaceInfo   *interface_info,
4129                                    const GDBusInterfaceVTable *vtable,
4130                                    gpointer                    user_data,
4131                                    GDestroyNotify              user_data_free_func,
4132                                    GError                    **error)
4133 {
4134   ExportedObject *eo;
4135   ExportedInterface *ei;
4136   guint ret;
4137
4138   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4139   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4140   g_return_val_if_fail (interface_info != NULL, 0);
4141   g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
4142   g_return_val_if_fail (error == NULL || *error == NULL, 0);
4143
4144   ret = 0;
4145
4146   CONNECTION_LOCK (connection);
4147
4148   eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
4149   if (eo == NULL)
4150     {
4151       eo = g_new0 (ExportedObject, 1);
4152       eo->object_path = g_strdup (object_path);
4153       eo->connection = connection;
4154       eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
4155                                                      g_str_equal,
4156                                                      NULL,
4157                                                      (GDestroyNotify) exported_interface_free);
4158       g_hash_table_insert (connection->priv->map_object_path_to_eo, eo->object_path, eo);
4159     }
4160
4161   ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
4162   if (ei != NULL)
4163     {
4164       g_set_error (error,
4165                    G_IO_ERROR,
4166                    G_IO_ERROR_EXISTS,
4167                    _("An object is already exported for the interface %s at %s"),
4168                    interface_info->name,
4169                    object_path);
4170       goto out;
4171     }
4172
4173   ei = g_new0 (ExportedInterface, 1);
4174   ei->id = _global_registration_id++; /* TODO: overflow etc. */
4175   ei->eo = eo;
4176   ei->user_data = user_data;
4177   ei->user_data_free_func = user_data_free_func;
4178   ei->vtable = vtable;
4179   ei->interface_info = g_dbus_interface_info_ref ((GDBusInterfaceInfo *) interface_info);
4180   ei->interface_name = g_strdup (interface_info->name);
4181   ei->context = g_main_context_get_thread_default ();
4182   if (ei->context != NULL)
4183     g_main_context_ref (ei->context);
4184
4185   g_hash_table_insert (eo->map_if_name_to_ei,
4186                        (gpointer) ei->interface_name,
4187                        ei);
4188   g_hash_table_insert (connection->priv->map_id_to_ei,
4189                        GUINT_TO_POINTER (ei->id),
4190                        ei);
4191
4192   ret = ei->id;
4193
4194  out:
4195   CONNECTION_UNLOCK (connection);
4196
4197   return ret;
4198 }
4199
4200 /**
4201  * g_dbus_connection_unregister_object:
4202  * @connection: A #GDBusConnection.
4203  * @registration_id: A registration id obtained from g_dbus_connection_register_object().
4204  *
4205  * Unregisters an object.
4206  *
4207  * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
4208  *
4209  * Since: 2.26
4210  */
4211 gboolean
4212 g_dbus_connection_unregister_object (GDBusConnection *connection,
4213                                      guint            registration_id)
4214 {
4215   ExportedInterface *ei;
4216   ExportedObject *eo;
4217   gboolean ret;
4218
4219   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4220
4221   ret = FALSE;
4222
4223   CONNECTION_LOCK (connection);
4224
4225   ei = g_hash_table_lookup (connection->priv->map_id_to_ei,
4226                             GUINT_TO_POINTER (registration_id));
4227   if (ei == NULL)
4228     goto out;
4229
4230   eo = ei->eo;
4231
4232   g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
4233   g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
4234   /* unregister object path if we have no more exported interfaces */
4235   if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
4236     g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_eo,
4237                                          eo->object_path));
4238
4239   ret = TRUE;
4240
4241  out:
4242   CONNECTION_UNLOCK (connection);
4243
4244   return ret;
4245 }
4246
4247 /* ---------------------------------------------------------------------------------------------------- */
4248
4249 /**
4250  * g_dbus_connection_emit_signal:
4251  * @connection: A #GDBusConnection.
4252  * @destination_bus_name: The unique bus name for the destination for the signal or %NULL to emit to all listeners.
4253  * @object_path: Path of remote object.
4254  * @interface_name: D-Bus interface to emit a signal on.
4255  * @signal_name: The name of the signal to emit.
4256  * @parameters: A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
4257  * @error: Return location for error or %NULL.
4258  *
4259  * Emits a signal.
4260  *
4261  * If the parameters GVariant is floating, it is consumed.
4262  *
4263  * This can only fail if @parameters is not compatible with the D-Bus protocol.
4264  *
4265  * Returns: %TRUE unless @error is set.
4266  *
4267  * Since: 2.26
4268  */
4269 gboolean
4270 g_dbus_connection_emit_signal (GDBusConnection  *connection,
4271                                const gchar      *destination_bus_name,
4272                                const gchar      *object_path,
4273                                const gchar      *interface_name,
4274                                const gchar      *signal_name,
4275                                GVariant         *parameters,
4276                                GError          **error)
4277 {
4278   GDBusMessage *message;
4279   gboolean ret;
4280
4281   message = NULL;
4282   ret = FALSE;
4283
4284   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4285   g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
4286   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
4287   g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
4288   g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
4289   g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
4290
4291   if (G_UNLIKELY (_g_dbus_debug_emission ()))
4292     {
4293       _g_dbus_debug_print_lock ();
4294       g_print ("========================================================================\n"
4295                "GDBus-debug:Emission:\n"
4296                " >>>> SIGNAL EMISSION %s.%s()\n"
4297                "      on object %s\n"
4298                "      destination %s\n",
4299                interface_name, signal_name,
4300                object_path,
4301                destination_bus_name != NULL ? destination_bus_name : "(none)");
4302       _g_dbus_debug_print_unlock ();
4303     }
4304
4305   message = g_dbus_message_new_signal (object_path,
4306                                        interface_name,
4307                                        signal_name);
4308
4309   if (destination_bus_name != NULL)
4310     g_dbus_message_set_header (message,
4311                                G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
4312                                g_variant_new_string (destination_bus_name));
4313
4314   if (parameters != NULL)
4315     g_dbus_message_set_body (message, parameters);
4316
4317   ret = g_dbus_connection_send_message (connection, message, NULL, error);
4318   g_object_unref (message);
4319
4320   return ret;
4321 }
4322
4323 static void
4324 add_call_flags (GDBusMessage           *message,
4325                          GDBusCallFlags  flags)
4326 {
4327   if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
4328     g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
4329 }
4330
4331 static GVariant *
4332 decode_method_reply (GDBusMessage        *reply,
4333                      const gchar         *method_name,
4334                      const GVariantType  *reply_type,
4335                      GError             **error)
4336 {
4337   GVariant *result;
4338
4339   result = NULL;
4340   switch (g_dbus_message_get_message_type (reply))
4341     {
4342     case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
4343       result = g_dbus_message_get_body (reply);
4344       if (result == NULL)
4345         {
4346           result = g_variant_new ("()");
4347           g_variant_ref_sink (result);
4348         }
4349       else
4350         {
4351           g_variant_ref (result);
4352         }
4353
4354       if (!g_variant_is_of_type (result, reply_type))
4355         {
4356           gchar *type_string = g_variant_type_dup_string (reply_type);
4357
4358           g_set_error (error,
4359                        G_IO_ERROR,
4360                        G_IO_ERROR_INVALID_ARGUMENT,
4361                        _("Method `%s' returned type `%s', but expected `%s'"),
4362                        method_name, g_variant_get_type_string (result), type_string);
4363
4364           g_variant_unref (result);
4365           g_free (type_string);
4366           result = NULL;
4367         }
4368       break;
4369
4370     case G_DBUS_MESSAGE_TYPE_ERROR:
4371       g_dbus_message_to_gerror (reply, error);
4372       break;
4373
4374     default:
4375       g_assert_not_reached ();
4376       break;
4377     }
4378
4379   return result;
4380 }
4381
4382
4383 typedef struct
4384 {
4385   GSimpleAsyncResult *simple;
4386   GVariantType *reply_type;
4387   gchar *method_name; /* for error message */
4388   guint32 serial;
4389 } CallState;
4390
4391 static void
4392 g_dbus_connection_call_done (GObject      *source,
4393                              GAsyncResult *result,
4394                              gpointer      user_data)
4395 {
4396   GDBusConnection *connection = G_DBUS_CONNECTION (source);
4397   CallState *state = user_data;
4398   GError *error;
4399   GDBusMessage *reply;
4400   GVariant *value;
4401
4402   error = NULL;
4403   reply = g_dbus_connection_send_message_with_reply_finish (connection,
4404                                                             result,
4405                                                             &error);
4406
4407   if (G_UNLIKELY (_g_dbus_debug_call ()))
4408     {
4409       _g_dbus_debug_print_lock ();
4410       g_print ("========================================================================\n"
4411                "GDBus-debug:Call:\n"
4412                " >>>> ASYNC COMPLETE %s() (serial %d)\n"
4413                "      ",
4414                state->method_name,
4415                state->serial);
4416       if (reply != NULL)
4417         {
4418           g_print ("SUCCESS\n");
4419         }
4420       else
4421         {
4422           g_print ("FAILED: %s\n",
4423                    error->message);
4424         }
4425       _g_dbus_debug_print_unlock ();
4426     }
4427
4428
4429   if (reply != NULL)
4430     {
4431       value = decode_method_reply (reply, state->method_name,
4432                                    state->reply_type, &error);
4433       g_object_unref (reply);
4434     }
4435   else
4436     value = NULL;
4437
4438   if (value == NULL)
4439     {
4440       g_simple_async_result_set_from_error (state->simple, error);
4441       g_error_free (error);
4442     }
4443   else
4444     g_simple_async_result_set_op_res_gpointer (state->simple, value,
4445                                                (GDestroyNotify) g_variant_unref);
4446
4447   g_simple_async_result_complete (state->simple);
4448   g_variant_type_free (state->reply_type);
4449   g_object_unref (state->simple);
4450   g_free (state->method_name);
4451
4452   g_slice_free (CallState, state);
4453 }
4454
4455 /**
4456  * g_dbus_connection_call:
4457  * @connection: A #GDBusConnection.
4458  * @bus_name: A unique or well-known bus name or %NULL if @connection is not a message bus connection.
4459  * @object_path: Path of remote object.
4460  * @interface_name: D-Bus interface to invoke method on.
4461  * @method_name: The name of the method to invoke.
4462  * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4463  * @reply_type: The expected type of the reply, or %NULL.
4464  * @flags: Flags from the #GDBusCallFlags enumeration.
4465  * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4466  * @cancellable: A #GCancellable or %NULL.
4467  * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
4468  * care about the result of the method invocation.
4469  * @user_data: The data to pass to @callback.
4470  *
4471  * Asynchronously invokes the @method_name method on the
4472  * @interface_name D-Bus interface on the remote object at
4473  * @object_path owned by @bus_name.
4474  *
4475  * If @connection is closed then the operation will fail with
4476  * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
4477  * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
4478  * not compatible with the D-Bus protocol, the operation fails with
4479  * %G_IO_ERROR_INVALID_ARGUMENT.
4480  *
4481  * If @reply_type is non-%NULL then the reply will be checked for having this type and an
4482  * error will be raised if it does not match.  Said another way, if you give a @reply_type
4483  * then any non-%NULL return value will be of this type.
4484  *
4485  * If the @parameters #GVariant is floating, it is consumed. This allows
4486  * convenient 'inline' use of g_variant_new(), e.g.:
4487  * |[
4488  *  g_dbus_connection_call (connection,
4489  *                          "org.freedesktop.StringThings",
4490  *                          "/org/freedesktop/StringThings",
4491  *                          "org.freedesktop.StringThings",
4492  *                          "TwoStrings",
4493  *                          g_variant_new ("(ss)",
4494  *                                         "Thing One",
4495  *                                         "Thing Two"),
4496  *                          NULL,
4497  *                          G_DBUS_CALL_FLAGS_NONE,
4498  *                          -1,
4499  *                          NULL,
4500  *                          (GAsyncReadyCallback) two_strings_done,
4501  *                          NULL);
4502  * ]|
4503  *
4504  * This is an asynchronous method. When the operation is finished, @callback will be invoked
4505  * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
4506  * of the thread you are calling this method from. You can then call
4507  * g_dbus_connection_call_finish() to get the result of the operation.
4508  * See g_dbus_connection_call_sync() for the synchronous version of this
4509  * function.
4510  *
4511  * Since: 2.26
4512  */
4513 void
4514 g_dbus_connection_call (GDBusConnection        *connection,
4515                         const gchar            *bus_name,
4516                         const gchar            *object_path,
4517                         const gchar            *interface_name,
4518                         const gchar            *method_name,
4519                         GVariant               *parameters,
4520                         const GVariantType     *reply_type,
4521                         GDBusCallFlags          flags,
4522                         gint                    timeout_msec,
4523                         GCancellable           *cancellable,
4524                         GAsyncReadyCallback     callback,
4525                         gpointer                user_data)
4526 {
4527   GDBusMessage *message;
4528   CallState *state;
4529
4530   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4531   g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
4532   g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
4533   g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
4534   g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
4535   g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
4536   g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
4537
4538   state = g_slice_new (CallState);
4539   state->simple = g_simple_async_result_new (G_OBJECT (connection),
4540                                              callback, user_data,
4541                                              g_dbus_connection_call);
4542   state->method_name = g_strjoin (".", interface_name, method_name, NULL);
4543
4544   if (reply_type == NULL)
4545     reply_type = G_VARIANT_TYPE_ANY;
4546
4547   state->reply_type = g_variant_type_copy (reply_type);
4548
4549   message = g_dbus_message_new_method_call (bus_name,
4550                                             object_path,
4551                                             interface_name,
4552                                             method_name);
4553   add_call_flags (message, flags);
4554   if (parameters != NULL)
4555     g_dbus_message_set_body (message, parameters);
4556
4557   g_dbus_connection_send_message_with_reply (connection,
4558                                              message,
4559                                              timeout_msec,
4560                                              &state->serial,
4561                                              cancellable,
4562                                              g_dbus_connection_call_done,
4563                                              state);
4564
4565   if (G_UNLIKELY (_g_dbus_debug_call ()))
4566     {
4567       _g_dbus_debug_print_lock ();
4568       g_print ("========================================================================\n"
4569                "GDBus-debug:Call:\n"
4570                " >>>> ASYNC %s.%s()\n"
4571                "      on object %s\n"
4572                "      owned by name %s (serial %d)\n",
4573                interface_name,
4574                method_name,
4575                object_path,
4576                bus_name != NULL ? bus_name : "(none)",
4577                state->serial);
4578       _g_dbus_debug_print_unlock ();
4579     }
4580
4581   if (message != NULL)
4582     g_object_unref (message);
4583 }
4584
4585 /**
4586  * g_dbus_connection_call_finish:
4587  * @connection: A #GDBusConnection.
4588  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
4589  * @error: Return location for error or %NULL.
4590  *
4591  * Finishes an operation started with g_dbus_connection_call().
4592  *
4593  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4594  * return values. Free with g_variant_unref().
4595  *
4596  * Since: 2.26
4597  */
4598 GVariant *
4599 g_dbus_connection_call_finish (GDBusConnection  *connection,
4600                                GAsyncResult     *res,
4601                                GError          **error)
4602 {
4603   GSimpleAsyncResult *simple;
4604
4605   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4606   g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
4607                                                         g_dbus_connection_call), NULL);
4608   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4609
4610   simple = G_SIMPLE_ASYNC_RESULT (res);
4611
4612   if (g_simple_async_result_propagate_error (simple, error))
4613     return FALSE;
4614
4615   return g_variant_ref (g_simple_async_result_get_op_res_gpointer (simple));
4616 }
4617
4618 /* ---------------------------------------------------------------------------------------------------- */
4619
4620 /**
4621  * g_dbus_connection_call_sync:
4622  * @connection: A #GDBusConnection.
4623  * @bus_name: A unique or well-known bus name.
4624  * @object_path: Path of remote object.
4625  * @interface_name: D-Bus interface to invoke method on.
4626  * @method_name: The name of the method to invoke.
4627  * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4628  * @reply_type: The expected type of the reply, or %NULL.
4629  * @flags: Flags from the #GDBusCallFlags enumeration.
4630  * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4631  * @cancellable: A #GCancellable or %NULL.
4632  * @error: Return location for error or %NULL.
4633  *
4634  * Synchronously invokes the @method_name method on the
4635  * @interface_name D-Bus interface on the remote object at
4636  * @object_path owned by @bus_name.
4637  *
4638  * If @connection is closed then the operation will fail with
4639  * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
4640  * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
4641  * contains a value not compatible with the D-Bus protocol, the operation
4642  * fails with %G_IO_ERROR_INVALID_ARGUMENT.
4643
4644  * If @reply_type is non-%NULL then the reply will be checked for having
4645  * this type and an error will be raised if it does not match.  Said
4646  * another way, if you give a @reply_type then any non-%NULL return
4647  * value will be of this type.
4648  *
4649  * If the @parameters #GVariant is floating, it is consumed.
4650  * This allows convenient 'inline' use of g_variant_new(), e.g.:
4651  * |[
4652  *  g_dbus_connection_call_sync (connection,
4653  *                               "org.freedesktop.StringThings",
4654  *                               "/org/freedesktop/StringThings",
4655  *                               "org.freedesktop.StringThings",
4656  *                               "TwoStrings",
4657  *                               g_variant_new ("(ss)",
4658  *                                              "Thing One",
4659  *                                              "Thing Two"),
4660  *                               NULL,
4661  *                               G_DBUS_CALL_FLAGS_NONE,
4662  *                               -1,
4663  *                               NULL,
4664  *                               &amp;error);
4665  * ]|
4666  *
4667  * The calling thread is blocked until a reply is received. See
4668  * g_dbus_connection_call() for the asynchronous version of
4669  * this method.
4670  *
4671  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4672  * return values. Free with g_variant_unref().
4673  *
4674  * Since: 2.26
4675  */
4676 GVariant *
4677 g_dbus_connection_call_sync (GDBusConnection         *connection,
4678                              const gchar             *bus_name,
4679                              const gchar             *object_path,
4680                              const gchar             *interface_name,
4681                              const gchar             *method_name,
4682                              GVariant                *parameters,
4683                              const GVariantType      *reply_type,
4684                              GDBusCallFlags           flags,
4685                              gint                     timeout_msec,
4686                              GCancellable            *cancellable,
4687                              GError                 **error)
4688 {
4689   GDBusMessage *message;
4690   GDBusMessage *reply;
4691   GVariant *result;
4692   GError *local_error;
4693
4694   message = NULL;
4695   reply = NULL;
4696   result = NULL;
4697
4698   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4699   g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
4700   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
4701   g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
4702   g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
4703   g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
4704   g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
4705
4706   if (reply_type == NULL)
4707     reply_type = G_VARIANT_TYPE_ANY;
4708
4709   message = g_dbus_message_new_method_call (bus_name,
4710                                             object_path,
4711                                             interface_name,
4712                                             method_name);
4713   add_call_flags (message, flags);
4714   if (parameters != NULL)
4715     g_dbus_message_set_body (message, parameters);
4716
4717   if (G_UNLIKELY (_g_dbus_debug_call ()))
4718     {
4719       _g_dbus_debug_print_lock ();
4720       g_print ("========================================================================\n"
4721                "GDBus-debug:Call:\n"
4722                " >>>> SYNC %s.%s()\n"
4723                "      on object %s\n"
4724                "      owned by name %s\n",
4725                interface_name,
4726                method_name,
4727                object_path,
4728                bus_name != NULL ? bus_name : "(none)");
4729       _g_dbus_debug_print_unlock ();
4730     }
4731
4732   local_error = NULL;
4733   reply = g_dbus_connection_send_message_with_reply_sync (connection,
4734                                                           message,
4735                                                           timeout_msec,
4736                                                           NULL, /* volatile guint32 *out_serial */
4737                                                           cancellable,
4738                                                           &local_error);
4739
4740   if (G_UNLIKELY (_g_dbus_debug_call ()))
4741     {
4742       _g_dbus_debug_print_lock ();
4743       g_print ("========================================================================\n"
4744                "GDBus-debug:Call:\n"
4745                " <<<< SYNC COMPLETE %s.%s()\n"
4746                "      ",
4747                interface_name,
4748                method_name);
4749       if (reply != NULL)
4750         {
4751           g_print ("SUCCESS\n");
4752         }
4753       else
4754         {
4755           g_print ("FAILED: %s\n",
4756                    local_error->message);
4757         }
4758       _g_dbus_debug_print_unlock ();
4759     }
4760
4761   if (reply == NULL)
4762     {
4763       if (error != NULL)
4764         *error = local_error;
4765       else
4766         g_error_free (local_error);
4767       goto out;
4768     }
4769
4770   result = decode_method_reply (reply, method_name, reply_type, error);
4771
4772  out:
4773   if (message != NULL)
4774     g_object_unref (message);
4775   if (reply != NULL)
4776     g_object_unref (reply);
4777
4778   return result;
4779 }
4780
4781 /* ---------------------------------------------------------------------------------------------------- */
4782
4783 struct ExportedSubtree
4784 {
4785   guint                     id;
4786   gchar                    *object_path;
4787   GDBusConnection          *connection;
4788   const GDBusSubtreeVTable *vtable;
4789   GDBusSubtreeFlags         flags;
4790
4791   GMainContext             *context;
4792   gpointer                  user_data;
4793   GDestroyNotify            user_data_free_func;
4794 };
4795
4796 static void
4797 exported_subtree_free (ExportedSubtree *es)
4798 {
4799   if (es->user_data_free_func != NULL)
4800     /* TODO: push to thread-default mainloop */
4801     es->user_data_free_func (es->user_data);
4802
4803   if (es->context != NULL)
4804     g_main_context_unref (es->context);
4805
4806   g_free (es->object_path);
4807   g_free (es);
4808 }
4809
4810 /* called without lock held */
4811 static gboolean
4812 handle_subtree_introspect (GDBusConnection *connection,
4813                            ExportedSubtree *es,
4814                            GDBusMessage    *message)
4815 {
4816   GString *s;
4817   gboolean handled;
4818   GDBusMessage *reply;
4819   gchar **children;
4820   gboolean is_root;
4821   const gchar *sender;
4822   const gchar *requested_object_path;
4823   const gchar *requested_node;
4824   GPtrArray *interfaces;
4825   guint n;
4826   gchar **subnode_paths;
4827
4828   handled = FALSE;
4829
4830   requested_object_path = g_dbus_message_get_path (message);
4831   sender = g_dbus_message_get_sender (message);
4832   is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4833
4834   s = g_string_new (NULL);
4835   introspect_append_header (s);
4836
4837   /* Strictly we don't need the children in dynamic mode, but we avoid the
4838    * conditionals to preserve code clarity
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       /* Assert existence of object if we are not dynamic */
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   interfaces = es->vtable->introspect (es->connection,
4860                                        sender,
4861                                        es->object_path,
4862                                        requested_node,
4863                                        es->user_data);
4864   if (interfaces != NULL)
4865     {
4866       if (interfaces->len > 0)
4867         {
4868           /* we're in business */
4869           introspect_append_standard_interfaces (s);
4870
4871           for (n = 0; n < interfaces->len; n++)
4872             {
4873               const GDBusInterfaceInfo *interface_info = interfaces->pdata[n];
4874               g_dbus_interface_info_generate_xml (interface_info, 2, s);
4875             }
4876         }
4877       g_ptr_array_unref (interfaces);
4878     }
4879
4880   /* then include <node> entries from the Subtree for the root */
4881   if (is_root)
4882     {
4883       for (n = 0; children != NULL && children[n] != NULL; n++)
4884         g_string_append_printf (s, "  <node name=\"%s\"/>\n", children[n]);
4885     }
4886
4887   /* finally include nodes registered below us */
4888   subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
4889   for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
4890     g_string_append_printf (s, "  <node name=\"%s\"/>\n", subnode_paths[n]);
4891   g_strfreev (subnode_paths);
4892
4893   g_string_append (s, "</node>\n");
4894
4895   reply = g_dbus_message_new_method_reply (message);
4896   g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4897   g_dbus_connection_send_message (connection, reply, NULL, NULL);
4898   g_object_unref (reply);
4899
4900   handled = TRUE;
4901
4902  out:
4903   g_string_free (s, TRUE);
4904   g_strfreev (children);
4905   return handled;
4906 }
4907
4908 /* called without lock held */
4909 static gboolean
4910 handle_subtree_method_invocation (GDBusConnection *connection,
4911                                   ExportedSubtree *es,
4912                                   GDBusMessage    *message)
4913 {
4914   gboolean handled;
4915   const gchar *sender;
4916   const gchar *interface_name;
4917   const gchar *member;
4918   const gchar *signature;
4919   const gchar *requested_object_path;
4920   const gchar *requested_node;
4921   gboolean is_root;
4922   gchar **children;
4923   const GDBusInterfaceInfo *interface_info;
4924   const GDBusInterfaceVTable *interface_vtable;
4925   gpointer interface_user_data;
4926   guint n;
4927   GPtrArray *interfaces;
4928   gboolean is_property_get;
4929   gboolean is_property_set;
4930   gboolean is_property_get_all;
4931
4932   handled = FALSE;
4933   interfaces = NULL;
4934
4935   requested_object_path = g_dbus_message_get_path (message);
4936   sender = g_dbus_message_get_sender (message);
4937   interface_name = g_dbus_message_get_interface (message);
4938   member = g_dbus_message_get_member (message);
4939   signature = g_dbus_message_get_signature (message);
4940   is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4941
4942   is_property_get = FALSE;
4943   is_property_set = FALSE;
4944   is_property_get_all = FALSE;
4945   if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
4946     {
4947       if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
4948         is_property_get = TRUE;
4949       else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
4950         is_property_set = TRUE;
4951       else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
4952         is_property_get_all = TRUE;
4953     }
4954
4955   children = es->vtable->enumerate (es->connection,
4956                                     sender,
4957                                     es->object_path,
4958                                     es->user_data);
4959
4960   if (!is_root)
4961     {
4962       requested_node = strrchr (requested_object_path, '/') + 1;
4963
4964       /* If not dynamic, skip if requested node is not part of children */
4965       if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4966           !_g_strv_has_string ((const gchar * const *) children, requested_node))
4967         goto out;
4968     }
4969   else
4970     {
4971       requested_node = "/";
4972     }
4973
4974   /* get introspection data for the node */
4975   interfaces = es->vtable->introspect (es->connection,
4976                                        sender,
4977                                        requested_object_path,
4978                                        requested_node,
4979                                        es->user_data);
4980   g_assert (interfaces != NULL);
4981   interface_info = NULL;
4982   for (n = 0; n < interfaces->len; n++)
4983     {
4984       const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4985       if (g_strcmp0 (id_n->name, interface_name) == 0)
4986         interface_info = id_n;
4987     }
4988
4989   /* dispatch the call if the user wants to handle it */
4990   if (interface_info != NULL)
4991     {
4992       /* figure out where to dispatch the method call */
4993       interface_user_data = NULL;
4994       interface_vtable = es->vtable->dispatch (es->connection,
4995                                                sender,
4996                                                es->object_path,
4997                                                interface_name,
4998                                                requested_node,
4999                                                &interface_user_data,
5000                                                es->user_data);
5001       if (interface_vtable == NULL)
5002         goto out;
5003
5004       CONNECTION_LOCK (connection);
5005       handled = validate_and_maybe_schedule_method_call (es->connection,
5006                                                          message,
5007                                                          0,
5008                                                          es->id,
5009                                                          interface_info,
5010                                                          interface_vtable,
5011                                                          es->context,
5012                                                          interface_user_data);
5013       CONNECTION_UNLOCK (connection);
5014     }
5015   /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
5016   else if (is_property_get || is_property_set || is_property_get_all)
5017     {
5018       if (is_property_get)
5019         g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
5020       else if (is_property_set)
5021         g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
5022       else if (is_property_get_all)
5023         g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
5024       else
5025         g_assert_not_reached ();
5026
5027       /* see if the object supports this interface at all */
5028       for (n = 0; n < interfaces->len; n++)
5029         {
5030           const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
5031           if (g_strcmp0 (id_n->name, interface_name) == 0)
5032             interface_info = id_n;
5033         }
5034
5035       /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
5036        * claims it won't support the interface
5037        */
5038       if (interface_info == NULL)
5039         {
5040           GDBusMessage *reply;
5041           reply = g_dbus_message_new_method_error (message,
5042                                                    "org.freedesktop.DBus.Error.InvalidArgs",
5043                                                    _("No such interface `%s'"),
5044                                                    interface_name);
5045           g_dbus_connection_send_message (es->connection, reply, NULL, NULL);
5046           g_object_unref (reply);
5047           handled = TRUE;
5048           goto out;
5049         }
5050
5051       /* figure out where to dispatch the property get/set/getall calls */
5052       interface_user_data = NULL;
5053       interface_vtable = es->vtable->dispatch (es->connection,
5054                                                sender,
5055                                                es->object_path,
5056                                                interface_name,
5057                                                requested_node,
5058                                                &interface_user_data,
5059                                                es->user_data);
5060       if (interface_vtable == NULL)
5061         goto out;
5062
5063       if (is_property_get || is_property_set)
5064         {
5065           CONNECTION_LOCK (connection);
5066           handled = validate_and_maybe_schedule_property_getset (es->connection,
5067                                                                  message,
5068                                                                  0,
5069                                                                  es->id,
5070                                                                  is_property_get,
5071                                                                  interface_info,
5072                                                                  interface_vtable,
5073                                                                  es->context,
5074                                                                  interface_user_data);
5075           CONNECTION_UNLOCK (connection);
5076         }
5077       else if (is_property_get_all)
5078         {
5079           CONNECTION_LOCK (connection);
5080           handled = validate_and_maybe_schedule_property_get_all (es->connection,
5081                                                                   message,
5082                                                                   0,
5083                                                                   es->id,
5084                                                                   interface_info,
5085                                                                   interface_vtable,
5086                                                                   es->context,
5087                                                                   interface_user_data);
5088           CONNECTION_UNLOCK (connection);
5089         }
5090     }
5091
5092  out:
5093   if (interfaces != NULL)
5094     g_ptr_array_unref (interfaces);
5095   g_strfreev (children);
5096   return handled;
5097 }
5098
5099 typedef struct
5100 {
5101   GDBusMessage *message;
5102   ExportedSubtree *es;
5103 } SubtreeDeferredData;
5104
5105 static void
5106 subtree_deferred_data_free (SubtreeDeferredData *data)
5107 {
5108   g_object_unref (data->message);
5109   g_free (data);
5110 }
5111
5112 /* called without lock held in the thread where the caller registered the subtree */
5113 static gboolean
5114 process_subtree_vtable_message_in_idle_cb (gpointer _data)
5115 {
5116   SubtreeDeferredData *data = _data;
5117   gboolean handled;
5118
5119   handled = FALSE;
5120
5121   if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
5122       g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
5123       g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
5124     handled = handle_subtree_introspect (data->es->connection,
5125                                          data->es,
5126                                          data->message);
5127   else
5128     handled = handle_subtree_method_invocation (data->es->connection,
5129                                                 data->es,
5130                                                 data->message);
5131
5132   if (!handled)
5133     {
5134       CONNECTION_LOCK (data->es->connection);
5135       handled = handle_generic_unlocked (data->es->connection, data->message);
5136       CONNECTION_UNLOCK (data->es->connection);
5137     }
5138
5139   /* if we couldn't handle the request, just bail with the UnknownMethod error */
5140   if (!handled)
5141     {
5142       GDBusMessage *reply;
5143       reply = g_dbus_message_new_method_error (data->message,
5144                                                "org.freedesktop.DBus.Error.UnknownMethod",
5145                                                _("Method `%s' on interface `%s' with signature `%s' does not exist"),
5146                                                g_dbus_message_get_member (data->message),
5147                                                g_dbus_message_get_interface (data->message),
5148                                                g_dbus_message_get_signature (data->message));
5149       g_dbus_connection_send_message (data->es->connection, reply, NULL, NULL);
5150       g_object_unref (reply);
5151     }
5152
5153   return FALSE;
5154 }
5155
5156 /* called in message handler thread with lock held */
5157 static gboolean
5158 subtree_message_func (GDBusConnection *connection,
5159                       ExportedSubtree *es,
5160                       GDBusMessage    *message)
5161 {
5162   GSource *idle_source;
5163   SubtreeDeferredData *data;
5164
5165   data = g_new0 (SubtreeDeferredData, 1);
5166   data->message = g_object_ref (message);
5167   data->es = es;
5168
5169   /* defer this call to an idle handler in the right thread */
5170   idle_source = g_idle_source_new ();
5171   g_source_set_priority (idle_source, G_PRIORITY_HIGH);
5172   g_source_set_callback (idle_source,
5173                          process_subtree_vtable_message_in_idle_cb,
5174                          data,
5175                          (GDestroyNotify) subtree_deferred_data_free);
5176   g_source_attach (idle_source, es->context);
5177   g_source_unref (idle_source);
5178
5179   /* since we own the entire subtree, handlers for objects not in the subtree have been
5180    * tried already by libdbus-1 - so we just need to ensure that we're always going
5181    * to reply to the message
5182    */
5183   return TRUE;
5184 }
5185
5186 /**
5187  * g_dbus_connection_register_subtree:
5188  * @connection: A #GDBusConnection.
5189  * @object_path: The object path to register the subtree at.
5190  * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
5191  * @flags: Flags used to fine tune the behavior of the subtree.
5192  * @user_data: Data to pass to functions in @vtable.
5193  * @user_data_free_func: Function to call when the subtree is unregistered.
5194  * @error: Return location for error or %NULL.
5195  *
5196  * Registers a whole subtree of <quote>dynamic</quote> objects.
5197  *
5198  * The @enumerate and @introspection functions in @vtable are used to
5199  * convey, to remote callers, what nodes exist in the subtree rooted
5200  * by @object_path.
5201  *
5202  * When handling remote calls into any node in the subtree, first the
5203  * @enumerate function is used to check if the node exists. If the node exists
5204  * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
5205  * the @introspection function is used to check if the node supports the
5206  * requested method. If so, the @dispatch function is used to determine
5207  * where to dispatch the call. The collected #GDBusInterfaceVTable and
5208  * #gpointer will be used to call into the interface vtable for processing
5209  * the request.
5210  *
5211  * All calls into user-provided code will be invoked in the <link
5212  * linkend="g-main-context-push-thread-default">thread-default main
5213  * loop</link> of the thread you are calling this method from.
5214  *
5215  * If an existing subtree is already registered at @object_path or
5216  * then @error is set to #G_IO_ERROR_EXISTS.
5217  *
5218  * Note that it is valid to register regular objects (using
5219  * g_dbus_connection_register_object()) in a subtree registered with
5220  * g_dbus_connection_register_subtree() - if so, the subtree handler
5221  * is tried as the last resort. One way to think about a subtree
5222  * handler is to consider it a <quote>fallback handler</quote>
5223  * for object paths not registered via g_dbus_connection_register_object()
5224  * or other bindings.
5225  *
5226  * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
5227  *
5228  * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
5229  * that can be used with g_dbus_connection_unregister_subtree() .
5230  *
5231  * Since: 2.26
5232  */
5233 guint
5234 g_dbus_connection_register_subtree (GDBusConnection           *connection,
5235                                     const gchar               *object_path,
5236                                     const GDBusSubtreeVTable  *vtable,
5237                                     GDBusSubtreeFlags          flags,
5238                                     gpointer                   user_data,
5239                                     GDestroyNotify             user_data_free_func,
5240                                     GError                   **error)
5241 {
5242   guint ret;
5243   ExportedSubtree *es;
5244
5245   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5246   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5247   g_return_val_if_fail (vtable != NULL, 0);
5248   g_return_val_if_fail (error == NULL || *error == NULL, 0);
5249
5250   ret = 0;
5251
5252   CONNECTION_LOCK (connection);
5253
5254   es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
5255   if (es != NULL)
5256     {
5257       g_set_error (error,
5258                    G_IO_ERROR,
5259                    G_IO_ERROR_EXISTS,
5260                    _("A subtree is already exported for %s"),
5261                    object_path);
5262       goto out;
5263     }
5264
5265   es = g_new0 (ExportedSubtree, 1);
5266   es->object_path = g_strdup (object_path);
5267   es->connection = connection;
5268
5269   es->vtable = vtable;
5270   es->flags = flags;
5271   es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
5272   es->user_data = user_data;
5273   es->user_data_free_func = user_data_free_func;
5274   es->context = g_main_context_get_thread_default ();
5275   if (es->context != NULL)
5276     g_main_context_ref (es->context);
5277
5278   g_hash_table_insert (connection->priv->map_object_path_to_es, es->object_path, es);
5279   g_hash_table_insert (connection->priv->map_id_to_es,
5280                        GUINT_TO_POINTER (es->id),
5281                        es);
5282
5283   ret = es->id;
5284
5285  out:
5286   CONNECTION_UNLOCK (connection);
5287
5288   return ret;
5289 }
5290
5291 /* ---------------------------------------------------------------------------------------------------- */
5292
5293 /**
5294  * g_dbus_connection_unregister_subtree:
5295  * @connection: A #GDBusConnection.
5296  * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
5297  *
5298  * Unregisters a subtree.
5299  *
5300  * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
5301  *
5302  * Since: 2.26
5303  */
5304 gboolean
5305 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
5306                                       guint            registration_id)
5307 {
5308   ExportedSubtree *es;
5309   gboolean ret;
5310
5311   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5312
5313   ret = FALSE;
5314
5315   CONNECTION_LOCK (connection);
5316
5317   es = g_hash_table_lookup (connection->priv->map_id_to_es,
5318                             GUINT_TO_POINTER (registration_id));
5319   if (es == NULL)
5320     goto out;
5321
5322   g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_es, GUINT_TO_POINTER (es->id)));
5323   g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_es, es->object_path));
5324
5325   ret = TRUE;
5326
5327  out:
5328   CONNECTION_UNLOCK (connection);
5329
5330   return ret;
5331 }
5332
5333 /* ---------------------------------------------------------------------------------------------------- */
5334
5335 /* must be called with lock held */
5336 static void
5337 handle_generic_ping_unlocked (GDBusConnection *connection,
5338                               const gchar     *object_path,
5339                               GDBusMessage    *message)
5340 {
5341   GDBusMessage *reply;
5342   reply = g_dbus_message_new_method_reply (message);
5343   g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
5344   g_object_unref (reply);
5345 }
5346
5347 /* must be called with lock held */
5348 static void
5349 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
5350                                         const gchar     *object_path,
5351                                         GDBusMessage    *message)
5352 {
5353   GDBusMessage *reply;
5354
5355   reply = NULL;
5356   if (connection->priv->machine_id == NULL)
5357     {
5358       GError *error;
5359       error = NULL;
5360       /* TODO: use PACKAGE_LOCALSTATEDIR ? */
5361       if (!g_file_get_contents ("/var/lib/dbus/machine-id",
5362                                 &connection->priv->machine_id,
5363                                 NULL,
5364                                 &error))
5365         {
5366           reply = g_dbus_message_new_method_error (message,
5367                                                    "org.freedesktop.DBus.Error.Failed",
5368                                                    _("Unable to load /var/lib/dbus/machine-id: %s"),
5369                                                    error->message);
5370           g_error_free (error);
5371         }
5372       else
5373         {
5374           g_strstrip (connection->priv->machine_id);
5375           /* TODO: validate value */
5376         }
5377     }
5378
5379   if (reply == NULL)
5380     {
5381       reply = g_dbus_message_new_method_reply (message);
5382       g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->priv->machine_id));
5383     }
5384   g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
5385   g_object_unref (reply);
5386 }
5387
5388 /* must be called with lock held */
5389 static void
5390 handle_generic_introspect_unlocked (GDBusConnection *connection,
5391                                     const gchar     *object_path,
5392                                     GDBusMessage    *message)
5393 {
5394   guint n;
5395   GString *s;
5396   gchar **registered;
5397   GDBusMessage *reply;
5398
5399   /* first the header */
5400   s = g_string_new (NULL);
5401   introspect_append_header (s);
5402
5403   registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
5404   for (n = 0; registered != NULL && registered[n] != NULL; n++)
5405       g_string_append_printf (s, "  <node name=\"%s\"/>\n", registered[n]);
5406   g_strfreev (registered);
5407   g_string_append (s, "</node>\n");
5408
5409   reply = g_dbus_message_new_method_reply (message);
5410   g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5411   g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
5412   g_object_unref (reply);
5413   g_string_free (s, TRUE);
5414 }
5415
5416 /* must be called with lock held */
5417 static gboolean
5418 handle_generic_unlocked (GDBusConnection *connection,
5419                          GDBusMessage    *message)
5420 {
5421   gboolean handled;
5422   const gchar *interface_name;
5423   const gchar *member;
5424   const gchar *signature;
5425   const gchar *path;
5426
5427   CONNECTION_ENSURE_LOCK (connection);
5428
5429   handled = FALSE;
5430
5431   interface_name = g_dbus_message_get_interface (message);
5432   member = g_dbus_message_get_member (message);
5433   signature = g_dbus_message_get_signature (message);
5434   path = g_dbus_message_get_path (message);
5435
5436   if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5437       g_strcmp0 (member, "Introspect") == 0 &&
5438       g_strcmp0 (signature, "") == 0)
5439     {
5440       handle_generic_introspect_unlocked (connection, path, message);
5441       handled = TRUE;
5442     }
5443   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5444            g_strcmp0 (member, "Ping") == 0 &&
5445            g_strcmp0 (signature, "") == 0)
5446     {
5447       handle_generic_ping_unlocked (connection, path, message);
5448       handled = TRUE;
5449     }
5450   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5451            g_strcmp0 (member, "GetMachineId") == 0 &&
5452            g_strcmp0 (signature, "") == 0)
5453     {
5454       handle_generic_get_machine_id_unlocked (connection, path, message);
5455       handled = TRUE;
5456     }
5457
5458   return handled;
5459 }
5460
5461 /* ---------------------------------------------------------------------------------------------------- */
5462
5463 /* called in message handler thread with lock held */
5464 static void
5465 distribute_method_call (GDBusConnection *connection,
5466                         GDBusMessage    *message)
5467 {
5468   GDBusMessage *reply;
5469   ExportedObject *eo;
5470   ExportedSubtree *es;
5471   const gchar *object_path;
5472   const gchar *interface_name;
5473   const gchar *member;
5474   const gchar *signature;
5475   const gchar *path;
5476   gchar *subtree_path;
5477   gchar *needle;
5478
5479   g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
5480
5481   interface_name = g_dbus_message_get_interface (message);
5482   member = g_dbus_message_get_member (message);
5483   signature = g_dbus_message_get_signature (message);
5484   path = g_dbus_message_get_path (message);
5485   subtree_path = g_strdup (path);
5486   needle = strrchr (subtree_path, '/');
5487   if (needle != NULL && needle != subtree_path)
5488     {
5489       *needle = '\0';
5490     }
5491   else
5492     {
5493       g_free (subtree_path);
5494       subtree_path = NULL;
5495     }
5496
5497
5498   if (G_UNLIKELY (_g_dbus_debug_incoming ()))
5499     {
5500       _g_dbus_debug_print_lock ();
5501       g_print ("========================================================================\n"
5502                "GDBus-debug:Incoming:\n"
5503                " >>>> METHOD INVOCATION %s.%s()\n"
5504                "      on object %s\n"
5505                "      invoked by name %s\n",
5506                interface_name, member,
5507                path,
5508                g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)");
5509       _g_dbus_debug_print_unlock ();
5510     }
5511
5512 #if 0
5513   g_debug ("interface    = `%s'", interface_name);
5514   g_debug ("member       = `%s'", member);
5515   g_debug ("signature    = `%s'", signature);
5516   g_debug ("path         = `%s'", path);
5517   g_debug ("subtree_path = `%s'", subtree_path != NULL ? subtree_path : "N/A");
5518 #endif
5519
5520   object_path = g_dbus_message_get_path (message);
5521   g_assert (object_path != NULL);
5522
5523   eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
5524   if (eo != NULL)
5525     {
5526       if (obj_message_func (connection, eo, message))
5527         goto out;
5528     }
5529
5530   es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
5531   if (es != NULL)
5532     {
5533       if (subtree_message_func (connection, es, message))
5534         goto out;
5535     }
5536
5537   if (subtree_path != NULL)
5538     {
5539       es = g_hash_table_lookup (connection->priv->map_object_path_to_es, subtree_path);
5540       if (es != NULL)
5541         {
5542           if (subtree_message_func (connection, es, message))
5543             goto out;
5544         }
5545     }
5546
5547   if (handle_generic_unlocked (connection, message))
5548     goto out;
5549
5550   /* if we end up here, the message has not been not handled - so return an error saying this */
5551   reply = g_dbus_message_new_method_error (message,
5552                                            "org.freedesktop.DBus.Error.UnknownMethod",
5553                                            _("No such interface `%s' on object at path %s"),
5554                                            interface_name,
5555                                            object_path);
5556   g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
5557   g_object_unref (reply);
5558
5559  out:
5560   g_free (subtree_path);
5561 }
5562
5563 /* ---------------------------------------------------------------------------------------------------- */
5564
5565 static GDBusConnection **
5566 message_bus_get_singleton (GBusType   bus_type,
5567                            GError   **error)
5568 {
5569   GDBusConnection **ret;
5570   const gchar *starter_bus;
5571
5572   ret = NULL;
5573
5574   switch (bus_type)
5575     {
5576     case G_BUS_TYPE_SESSION:
5577       ret = &the_session_bus;
5578       break;
5579
5580     case G_BUS_TYPE_SYSTEM:
5581       ret = &the_system_bus;
5582       break;
5583
5584     case G_BUS_TYPE_STARTER:
5585       starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
5586       if (g_strcmp0 (starter_bus, "session") == 0)
5587         {
5588           ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
5589           goto out;
5590         }
5591       else if (g_strcmp0 (starter_bus, "system") == 0)
5592         {
5593           ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
5594           goto out;
5595         }
5596       else
5597         {
5598           if (starter_bus != NULL)
5599             {
5600               g_set_error (error,
5601                            G_IO_ERROR,
5602                            G_IO_ERROR_INVALID_ARGUMENT,
5603                            _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
5604                              " - unknown value `%s'"),
5605                            starter_bus);
5606             }
5607           else
5608             {
5609               g_set_error_literal (error,
5610                                    G_IO_ERROR,
5611                                    G_IO_ERROR_INVALID_ARGUMENT,
5612                                    _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
5613                                      "variable is not set"));
5614             }
5615         }
5616       break;
5617
5618     default:
5619       g_assert_not_reached ();
5620       break;
5621     }
5622
5623  out:
5624   return ret;
5625 }
5626
5627 static GDBusConnection *
5628 get_uninitialized_connection (GBusType       bus_type,
5629                               GCancellable  *cancellable,
5630                               GError       **error)
5631 {
5632   GDBusConnection **singleton;
5633   GDBusConnection *ret;
5634
5635   ret = NULL;
5636
5637   G_LOCK (message_bus_lock);
5638   singleton = message_bus_get_singleton (bus_type, error);
5639   if (singleton == NULL)
5640     goto out;
5641
5642   if (*singleton == NULL)
5643     {
5644       gchar *address;
5645       address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
5646       if (address == NULL)
5647         goto out;
5648       ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
5649                                        "address", address,
5650                                        "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
5651                                                 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
5652                                        "exit-on-close", TRUE,
5653                                        NULL);
5654       g_free (address);
5655     }
5656   else
5657     {
5658       ret = g_object_ref (*singleton);
5659     }
5660
5661   g_assert (ret != NULL);
5662
5663  out:
5664   G_UNLOCK (message_bus_lock);
5665   return ret;
5666 }
5667
5668 /**
5669  * g_bus_get_sync:
5670  * @bus_type: A #GBusType.
5671  * @cancellable: A #GCancellable or %NULL.
5672  * @error: Return location for error or %NULL.
5673  *
5674  * Synchronously connects to the message bus specified by @bus_type.
5675  * Note that the returned object may shared with other callers,
5676  * e.g. if two separate parts of a process calls this function with
5677  * the same @bus_type, they will share the same object.
5678  *
5679  * This is a synchronous failable function. See g_bus_get() and
5680  * g_bus_get_finish() for the asynchronous version.
5681  *
5682  * The returned object is a singleton, that is, shared with other
5683  * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5684  * event that you need a private message bus connection, use
5685  * g_dbus_address_get_for_bus_sync() and
5686  * g_dbus_connection_new_for_address().
5687  *
5688  * Note that the returned #GDBusConnection object will (usually) have
5689  * the #GDBusConnection:exit-on-close property set to %TRUE.
5690  *
5691  * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5692  *
5693  * Since: 2.26
5694  */
5695 GDBusConnection *
5696 g_bus_get_sync (GBusType       bus_type,
5697                 GCancellable  *cancellable,
5698                 GError       **error)
5699 {
5700   GDBusConnection *connection;
5701
5702   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5703
5704   connection = get_uninitialized_connection (bus_type, cancellable, error);
5705   if (connection == NULL)
5706     goto out;
5707
5708   if (!g_initable_init (G_INITABLE (connection), cancellable, error))
5709     {
5710       g_object_unref (connection);
5711       connection = NULL;
5712     }
5713
5714  out:
5715   return connection;
5716 }
5717
5718 static void
5719 bus_get_async_initable_cb (GObject      *source_object,
5720                            GAsyncResult *res,
5721                            gpointer      user_data)
5722 {
5723   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
5724   GError *error;
5725
5726   error = NULL;
5727   if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
5728                                      res,
5729                                      &error))
5730     {
5731       g_assert (error != NULL);
5732       g_simple_async_result_set_from_error (simple, error);
5733       g_error_free (error);
5734       g_object_unref (source_object);
5735     }
5736   else
5737     {
5738       g_simple_async_result_set_op_res_gpointer (simple,
5739                                                  source_object,
5740                                                  g_object_unref);
5741     }
5742   g_simple_async_result_complete_in_idle (simple);
5743   g_object_unref (simple);
5744 }
5745
5746 /**
5747  * g_bus_get:
5748  * @bus_type: A #GBusType.
5749  * @cancellable: A #GCancellable or %NULL.
5750  * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
5751  * @user_data: The data to pass to @callback.
5752  *
5753  * Asynchronously connects to the message bus specified by @bus_type.
5754  *
5755  * When the operation is finished, @callback will be invoked. You can
5756  * then call g_bus_get_finish() to get the result of the operation.
5757  *
5758  * This is a asynchronous failable function. See g_bus_get_sync() for
5759  * the synchronous version.
5760  *
5761  * Since: 2.26
5762  */
5763 void
5764 g_bus_get (GBusType             bus_type,
5765            GCancellable        *cancellable,
5766            GAsyncReadyCallback  callback,
5767            gpointer             user_data)
5768 {
5769   GDBusConnection *connection;
5770   GSimpleAsyncResult *simple;
5771   GError *error;
5772
5773   simple = g_simple_async_result_new (NULL,
5774                                       callback,
5775                                       user_data,
5776                                       g_bus_get);
5777
5778   error = NULL;
5779   connection = get_uninitialized_connection (bus_type, cancellable, &error);
5780   if (connection == NULL)
5781     {
5782       g_assert (error != NULL);
5783       g_simple_async_result_set_from_error (simple, error);
5784       g_error_free (error);
5785       g_simple_async_result_complete_in_idle (simple);
5786       g_object_unref (simple);
5787     }
5788   else
5789     {
5790       g_async_initable_init_async (G_ASYNC_INITABLE (connection),
5791                                    G_PRIORITY_DEFAULT,
5792                                    cancellable,
5793                                    bus_get_async_initable_cb,
5794                                    simple);
5795     }
5796 }
5797
5798 /**
5799  * g_bus_get_finish:
5800  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
5801  * @error: Return location for error or %NULL.
5802  *
5803  * Finishes an operation started with g_bus_get().
5804  *
5805  * The returned object is a singleton, that is, shared with other
5806  * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5807  * event that you need a private message bus connection, use
5808  * g_dbus_address_get_for_bus() and
5809  * g_dbus_connection_new_for_address().
5810  *
5811  * Note that the returned #GDBusConnection object will (usually) have
5812  * the #GDBusConnection:exit-on-close property set to %TRUE.
5813  *
5814  * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5815  *
5816  * Since: 2.26
5817  */
5818 GDBusConnection *
5819 g_bus_get_finish (GAsyncResult  *res,
5820                   GError       **error)
5821 {
5822   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
5823   GObject *object;
5824   GDBusConnection *ret;
5825
5826   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5827
5828   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
5829
5830   ret = NULL;
5831
5832   if (g_simple_async_result_propagate_error (simple, error))
5833     goto out;
5834
5835   object = g_simple_async_result_get_op_res_gpointer (simple);
5836   g_assert (object != NULL);
5837   ret = g_object_ref (G_DBUS_CONNECTION (object));
5838
5839  out:
5840   return ret;
5841 }
5842
5843 /* ---------------------------------------------------------------------------------------------------- */
5844
5845 #define __G_DBUS_CONNECTION_C__
5846 #include "gioaliasdef.c"