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