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