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