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