GDBusMethodInvocation: nuke constructor
[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   gboolean altered_by_filter;
1948   guint num_filters;
1949   guint n;
1950
1951   //g_debug ("in on_worker_message_received");
1952
1953   g_object_ref (connection);
1954
1955   /* First collect the set of callback functions */
1956   CONNECTION_LOCK (connection);
1957   num_filters = connection->filters->len;
1958   filters = g_new0 (FilterCallback, num_filters);
1959   for (n = 0; n < num_filters; n++)
1960     {
1961       FilterData *data = connection->filters->pdata[n];
1962       filters[n].func = data->filter_function;
1963       filters[n].user_data = data->user_data;
1964     }
1965   CONNECTION_UNLOCK (connection);
1966
1967   /* the call the filters in order (without holding the lock) */
1968   consumed_by_filter = FALSE;
1969   altered_by_filter = FALSE;
1970   for (n = 0; n < num_filters; n++)
1971     {
1972       GDBusMessageFilterResult result;
1973       result = filters[n].func (connection,
1974                                 message,
1975                                 TRUE,
1976                                 filters[n].user_data);
1977       switch (result)
1978         {
1979         case G_DBUS_MESSAGE_FILTER_RESULT_NO_EFFECT:
1980           /* do nothing */
1981           break;
1982
1983         default:
1984           g_warning ("Treating unknown value %d for GDBusMessageFilterResult from filter "
1985                      "function on incoming message as MESSAGE_CONSUMED.", result);
1986           /* explicit fallthrough */
1987         case G_DBUS_MESSAGE_FILTER_RESULT_MESSAGE_CONSUMED:
1988           consumed_by_filter = TRUE;
1989           break;
1990
1991         case G_DBUS_MESSAGE_FILTER_RESULT_MESSAGE_ALTERED:
1992           altered_by_filter = TRUE;
1993           break;
1994         }
1995       if (consumed_by_filter)
1996         break;
1997     }
1998
1999   /* Standard dispatch unless the filter ate the message - no need to
2000    * do anything if the message was altered
2001    */
2002   if (!consumed_by_filter)
2003     {
2004       GDBusMessageType message_type;
2005
2006       message_type = g_dbus_message_get_message_type (message);
2007       if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2008         {
2009           guint32 reply_serial;
2010           SendMessageData *send_message_data;
2011
2012           reply_serial = g_dbus_message_get_reply_serial (message);
2013           CONNECTION_LOCK (connection);
2014           send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2015                                                    GUINT_TO_POINTER (reply_serial));
2016           if (send_message_data != NULL)
2017             {
2018               //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2019               send_message_data_deliver_reply_unlocked (send_message_data, message);
2020             }
2021           else
2022             {
2023               //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2024             }
2025           CONNECTION_UNLOCK (connection);
2026         }
2027       else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2028         {
2029           CONNECTION_LOCK (connection);
2030           distribute_signals (connection, message);
2031           CONNECTION_UNLOCK (connection);
2032         }
2033       else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2034         {
2035           CONNECTION_LOCK (connection);
2036           distribute_method_call (connection, message);
2037           CONNECTION_UNLOCK (connection);
2038         }
2039     }
2040
2041   g_object_unref (connection);
2042   g_free (filters);
2043 }
2044
2045 /* Called in worker's thread */
2046 static GDBusMessageFilterResult
2047 on_worker_message_about_to_be_sent (GDBusWorker  *worker,
2048                                     GDBusMessage *message,
2049                                     gpointer      user_data)
2050 {
2051   GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
2052   FilterCallback *filters;
2053   guint num_filters;
2054   guint n;
2055   GDBusMessageFilterResult ret;
2056
2057   //g_debug ("in on_worker_message_about_to_be_sent");
2058
2059   ret = G_DBUS_MESSAGE_FILTER_RESULT_NO_EFFECT;
2060
2061   g_object_ref (connection);
2062
2063   /* First collect the set of callback functions */
2064   CONNECTION_LOCK (connection);
2065   num_filters = connection->filters->len;
2066   filters = g_new0 (FilterCallback, num_filters);
2067   for (n = 0; n < num_filters; n++)
2068     {
2069       FilterData *data = connection->filters->pdata[n];
2070       filters[n].func = data->filter_function;
2071       filters[n].user_data = data->user_data;
2072     }
2073   CONNECTION_UNLOCK (connection);
2074
2075   /* then call the filters in order (without holding the lock) */
2076   for (n = 0; n < num_filters; n++)
2077     {
2078       GDBusMessageFilterResult result;
2079       result = filters[n].func (connection,
2080                                 message,
2081                                 FALSE,
2082                                 filters[n].user_data);
2083       switch (result)
2084         {
2085         case G_DBUS_MESSAGE_FILTER_RESULT_NO_EFFECT:
2086           /* do nothing, ret might already be _ALTERED */
2087           break;
2088
2089         default:
2090           g_warning ("Treating unknown value %d for GDBusMessageFilterResult from filter "
2091                      "function on outgoing message as MESSAGE_CONSUMED.", result);
2092           /* explicit fallthrough */
2093         case G_DBUS_MESSAGE_FILTER_RESULT_MESSAGE_CONSUMED:
2094           ret = G_DBUS_MESSAGE_FILTER_RESULT_MESSAGE_CONSUMED;
2095           goto out;
2096
2097         case G_DBUS_MESSAGE_FILTER_RESULT_MESSAGE_ALTERED:
2098           ret = G_DBUS_MESSAGE_FILTER_RESULT_MESSAGE_ALTERED;
2099           break;
2100         }
2101     }
2102
2103  out:
2104   g_object_unref (connection);
2105   g_free (filters);
2106
2107   return ret;
2108 }
2109
2110 /* Called in worker's thread - we must not block */
2111 static void
2112 on_worker_closed (GDBusWorker *worker,
2113                   gboolean     remote_peer_vanished,
2114                   GError      *error,
2115                   gpointer     user_data)
2116 {
2117   GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
2118
2119   //g_debug ("in on_worker_closed: %s", error->message);
2120
2121   CONNECTION_LOCK (connection);
2122   if (!connection->closed)
2123     set_closed_unlocked (connection, remote_peer_vanished, error);
2124   CONNECTION_UNLOCK (connection);
2125 }
2126
2127 /* ---------------------------------------------------------------------------------------------------- */
2128
2129 /* Determines the biggest set of capabilities we can support on this connection */
2130 static GDBusCapabilityFlags
2131 get_offered_capabilities_max (GDBusConnection *connection)
2132 {
2133       GDBusCapabilityFlags ret;
2134       ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2135 #ifdef G_OS_UNIX
2136       if (G_IS_UNIX_CONNECTION (connection->stream))
2137         ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2138 #endif
2139       return ret;
2140 }
2141
2142 static gboolean
2143 initable_init (GInitable     *initable,
2144                GCancellable  *cancellable,
2145                GError       **error)
2146 {
2147   GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2148   gboolean ret;
2149
2150   /* This method needs to be idempotent to work with the singleton
2151    * pattern. See the docs for g_initable_init(). We implement this by
2152    * locking.
2153    *
2154    * Unfortunately we can't use the main lock since the on_worker_*()
2155    * callbacks above needs the lock during initialization (for message
2156    * bus connections we do a synchronous Hello() call on the bus).
2157    */
2158   g_mutex_lock (connection->init_lock);
2159
2160   ret = FALSE;
2161
2162   if (connection->is_initialized)
2163     {
2164       if (connection->stream != NULL)
2165         ret = TRUE;
2166       else
2167         g_assert (connection->initialization_error != NULL);
2168       goto out;
2169     }
2170   g_assert (connection->initialization_error == NULL);
2171
2172   /* The user can pass multiple (but mutally exclusive) construct
2173    * properties:
2174    *
2175    *  - stream (of type GIOStream)
2176    *  - address (of type gchar*)
2177    *
2178    * At the end of the day we end up with a non-NULL GIOStream
2179    * object in connection->stream.
2180    */
2181   if (connection->address != NULL)
2182     {
2183       g_assert (connection->stream == NULL);
2184
2185       if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2186           (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2187         {
2188           g_set_error_literal (error,
2189                                G_IO_ERROR,
2190                                G_IO_ERROR_INVALID_ARGUMENT,
2191                                _("Unsupported flags encountered when constructing a client-side connection"));
2192           goto out;
2193         }
2194
2195       connection->stream = g_dbus_address_get_stream_sync (connection->address,
2196                                                            NULL, /* TODO: out_guid */
2197                                                            cancellable,
2198                                                            &connection->initialization_error);
2199       if (connection->stream == NULL)
2200         goto out;
2201     }
2202   else if (connection->stream != NULL)
2203     {
2204       /* nothing to do */
2205     }
2206   else
2207     {
2208       g_assert_not_reached ();
2209     }
2210
2211   /* Authenticate the connection */
2212   if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2213     {
2214       g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2215       g_assert (connection->guid != NULL);
2216       connection->auth = _g_dbus_auth_new (connection->stream);
2217       if (!_g_dbus_auth_run_server (connection->auth,
2218                                     connection->authentication_observer,
2219                                     connection->guid,
2220                                     (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2221                                     get_offered_capabilities_max (connection),
2222                                     &connection->capabilities,
2223                                     &connection->credentials,
2224                                     cancellable,
2225                                     &connection->initialization_error))
2226         goto out;
2227     }
2228   else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2229     {
2230       g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2231       g_assert (connection->guid == NULL);
2232       connection->auth = _g_dbus_auth_new (connection->stream);
2233       connection->guid = _g_dbus_auth_run_client (connection->auth,
2234                                                   get_offered_capabilities_max (connection),
2235                                                   &connection->capabilities,
2236                                                   cancellable,
2237                                                   &connection->initialization_error);
2238       if (connection->guid == NULL)
2239         goto out;
2240     }
2241
2242   if (connection->authentication_observer != NULL)
2243     {
2244       g_object_unref (connection->authentication_observer);
2245       connection->authentication_observer = NULL;
2246     }
2247
2248   //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2249
2250   //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2251
2252 #ifdef G_OS_UNIX
2253   /* Hack used until
2254    *
2255    *  https://bugzilla.gnome.org/show_bug.cgi?id=616458
2256    *
2257    * has been resolved
2258    */
2259   if (G_IS_SOCKET_CONNECTION (connection->stream))
2260     {
2261       g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2262     }
2263 #endif
2264
2265   connection->worker = _g_dbus_worker_new (connection->stream,
2266                                            connection->capabilities,
2267                                            (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING),
2268                                            on_worker_message_received,
2269                                            on_worker_message_about_to_be_sent,
2270                                            on_worker_closed,
2271                                            connection);
2272
2273   /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2274   if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2275     {
2276       GVariant *hello_result;
2277
2278       /* we could lift this restriction by adding code in gdbusprivate.c */
2279       if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2280         {
2281           g_set_error_literal (&connection->initialization_error,
2282                                G_IO_ERROR,
2283                                G_IO_ERROR_FAILED,
2284                                "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2285           goto out;
2286         }
2287
2288       hello_result = g_dbus_connection_call_sync (connection,
2289                                                   "org.freedesktop.DBus", /* name */
2290                                                   "/org/freedesktop/DBus", /* path */
2291                                                   "org.freedesktop.DBus", /* interface */
2292                                                   "Hello",
2293                                                   NULL, /* parameters */
2294                                                   G_VARIANT_TYPE ("(s)"),
2295                                                   G_DBUS_CALL_FLAGS_NONE,
2296                                                   -1,
2297                                                   NULL, /* TODO: cancellable */
2298                                                   &connection->initialization_error);
2299       if (hello_result == NULL)
2300         goto out;
2301
2302       g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2303       g_variant_unref (hello_result);
2304       //g_debug ("unique name is `%s'", connection->bus_unique_name);
2305     }
2306
2307   connection->is_initialized = TRUE;
2308
2309   ret = TRUE;
2310  out:
2311   if (!ret)
2312     {
2313       g_assert (connection->initialization_error != NULL);
2314       g_propagate_error (error, g_error_copy (connection->initialization_error));
2315     }
2316
2317   g_mutex_unlock (connection->init_lock);
2318
2319   return ret;
2320 }
2321
2322 static void
2323 initable_iface_init (GInitableIface *initable_iface)
2324 {
2325   initable_iface->init = initable_init;
2326 }
2327
2328 /* ---------------------------------------------------------------------------------------------------- */
2329
2330 static void
2331 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2332 {
2333   /* Use default */
2334 }
2335
2336 /* ---------------------------------------------------------------------------------------------------- */
2337
2338 /**
2339  * g_dbus_connection_new:
2340  * @stream: A #GIOStream.
2341  * @guid: The GUID to use if a authenticating as a server or %NULL.
2342  * @flags: Flags describing how to make the connection.
2343  * @observer: A #GDBusAuthObserver or %NULL.
2344  * @cancellable: A #GCancellable or %NULL.
2345  * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2346  * @user_data: The data to pass to @callback.
2347  *
2348  * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2349  * with the end represented by @stream.
2350  *
2351  * If @observer is not %NULL it may be used to control the
2352  * authentication process.
2353  *
2354  * When the operation is finished, @callback will be invoked. You can
2355  * then call g_dbus_connection_new_finish() to get the result of the
2356  * operation.
2357  *
2358  * This is a asynchronous failable constructor. See
2359  * g_dbus_connection_new_sync() for the synchronous
2360  * version.
2361  *
2362  * Since: 2.26
2363  */
2364 void
2365 g_dbus_connection_new (GIOStream            *stream,
2366                        const gchar          *guid,
2367                        GDBusConnectionFlags  flags,
2368                        GDBusAuthObserver    *observer,
2369                        GCancellable         *cancellable,
2370                        GAsyncReadyCallback   callback,
2371                        gpointer              user_data)
2372 {
2373   g_return_if_fail (G_IS_IO_STREAM (stream));
2374   g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2375                               G_PRIORITY_DEFAULT,
2376                               cancellable,
2377                               callback,
2378                               user_data,
2379                               "stream", stream,
2380                               "guid", guid,
2381                               "flags", flags,
2382                               "authentication-observer", observer,
2383                               NULL);
2384 }
2385
2386 /**
2387  * g_dbus_connection_new_finish:
2388  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2389  * @error: Return location for error or %NULL.
2390  *
2391  * Finishes an operation started with g_dbus_connection_new().
2392  *
2393  * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2394  *
2395  * Since: 2.26
2396  */
2397 GDBusConnection *
2398 g_dbus_connection_new_finish (GAsyncResult  *res,
2399                               GError       **error)
2400 {
2401   GObject *object;
2402   GObject *source_object;
2403
2404   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2405   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2406
2407   source_object = g_async_result_get_source_object (res);
2408   g_assert (source_object != NULL);
2409   object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2410                                         res,
2411                                         error);
2412   g_object_unref (source_object);
2413   if (object != NULL)
2414     return G_DBUS_CONNECTION (object);
2415   else
2416     return NULL;
2417 }
2418
2419 /**
2420  * g_dbus_connection_new_sync:
2421  * @stream: A #GIOStream.
2422  * @guid: The GUID to use if a authenticating as a server or %NULL.
2423  * @flags: Flags describing how to make the connection.
2424  * @observer: A #GDBusAuthObserver or %NULL.
2425  * @cancellable: A #GCancellable or %NULL.
2426  * @error: Return location for error or %NULL.
2427  *
2428  * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2429  * with the end represented by @stream.
2430  *
2431  * If @observer is not %NULL it may be used to control the
2432  * authentication process.
2433  *
2434  * This is a synchronous failable constructor. See
2435  * g_dbus_connection_new() for the asynchronous version.
2436  *
2437  * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2438  *
2439  * Since: 2.26
2440  */
2441 GDBusConnection *
2442 g_dbus_connection_new_sync (GIOStream             *stream,
2443                             const gchar           *guid,
2444                             GDBusConnectionFlags   flags,
2445                             GDBusAuthObserver     *observer,
2446                             GCancellable          *cancellable,
2447                             GError               **error)
2448 {
2449   g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2450   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2451   return g_initable_new (G_TYPE_DBUS_CONNECTION,
2452                          cancellable,
2453                          error,
2454                          "stream", stream,
2455                          "guid", guid,
2456                          "flags", flags,
2457                          "authentication-observer", observer,
2458                          NULL);
2459 }
2460
2461 /* ---------------------------------------------------------------------------------------------------- */
2462
2463 /**
2464  * g_dbus_connection_new_for_address:
2465  * @address: A D-Bus address.
2466  * @flags: Flags describing how to make the connection.
2467  * @observer: A #GDBusAuthObserver or %NULL.
2468  * @cancellable: A #GCancellable or %NULL.
2469  * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2470  * @user_data: The data to pass to @callback.
2471  *
2472  * Asynchronously connects and sets up a D-Bus client connection for
2473  * exchanging D-Bus messages with an endpoint specified by @address
2474  * which must be in the D-Bus address format.
2475  *
2476  * This constructor can only be used to initiate client-side
2477  * connections - use g_dbus_connection_new() if you need to act as the
2478  * server. In particular, @flags cannot contain the
2479  * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2480  * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2481  *
2482  * When the operation is finished, @callback will be invoked. You can
2483  * then call g_dbus_connection_new_finish() to get the result of the
2484  * operation.
2485  *
2486  * If @observer is not %NULL it may be used to control the
2487  * authentication process.
2488  *
2489  * This is a asynchronous failable constructor. See
2490  * g_dbus_connection_new_for_address_sync() for the synchronous
2491  * version.
2492  *
2493  * Since: 2.26
2494  */
2495 void
2496 g_dbus_connection_new_for_address (const gchar          *address,
2497                                    GDBusConnectionFlags  flags,
2498                                    GDBusAuthObserver    *observer,
2499                                    GCancellable         *cancellable,
2500                                    GAsyncReadyCallback   callback,
2501                                    gpointer              user_data)
2502 {
2503   g_return_if_fail (address != NULL);
2504   g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2505                               G_PRIORITY_DEFAULT,
2506                               cancellable,
2507                               callback,
2508                               user_data,
2509                               "address", address,
2510                               "flags", flags,
2511                               "authentication-observer", observer,
2512                               NULL);
2513 }
2514
2515 /**
2516  * g_dbus_connection_new_for_address_finish:
2517  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2518  * @error: Return location for error or %NULL.
2519  *
2520  * Finishes an operation started with g_dbus_connection_new_for_address().
2521  *
2522  * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2523  *
2524  * Since: 2.26
2525  */
2526 GDBusConnection *
2527 g_dbus_connection_new_for_address_finish (GAsyncResult  *res,
2528                                           GError       **error)
2529 {
2530   GObject *object;
2531   GObject *source_object;
2532
2533   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2534   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2535
2536   source_object = g_async_result_get_source_object (res);
2537   g_assert (source_object != NULL);
2538   object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2539                                         res,
2540                                         error);
2541   g_object_unref (source_object);
2542   if (object != NULL)
2543     return G_DBUS_CONNECTION (object);
2544   else
2545     return NULL;
2546 }
2547
2548 /**
2549  * g_dbus_connection_new_for_address_sync:
2550  * @address: A D-Bus address.
2551  * @flags: Flags describing how to make the connection.
2552  * @observer: A #GDBusAuthObserver or %NULL.
2553  * @cancellable: A #GCancellable or %NULL.
2554  * @error: Return location for error or %NULL.
2555  *
2556  * Synchronously connects and sets up a D-Bus client connection for
2557  * exchanging D-Bus messages with an endpoint specified by @address
2558  * which must be in the D-Bus address format.
2559  *
2560  * This constructor can only be used to initiate client-side
2561  * connections - use g_dbus_connection_new_sync() if you need to act
2562  * as the server. In particular, @flags cannot contain the
2563  * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2564  * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2565  *
2566  * This is a synchronous failable constructor. See
2567  * g_dbus_connection_new_for_address() for the asynchronous version.
2568  *
2569  * If @observer is not %NULL it may be used to control the
2570  * authentication process.
2571  *
2572  * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2573  *
2574  * Since: 2.26
2575  */
2576 GDBusConnection *
2577 g_dbus_connection_new_for_address_sync (const gchar           *address,
2578                                         GDBusConnectionFlags   flags,
2579                                         GDBusAuthObserver     *observer,
2580                                         GCancellable          *cancellable,
2581                                         GError               **error)
2582 {
2583   g_return_val_if_fail (address != NULL, NULL);
2584   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2585   return g_initable_new (G_TYPE_DBUS_CONNECTION,
2586                          cancellable,
2587                          error,
2588                          "address", address,
2589                          "flags", flags,
2590                          "authentication-observer", observer,
2591                          NULL);
2592 }
2593
2594 /* ---------------------------------------------------------------------------------------------------- */
2595
2596 /**
2597  * g_dbus_connection_set_exit_on_close:
2598  * @connection: A #GDBusConnection.
2599  * @exit_on_close: Whether the process should be terminated
2600  * when @connection is closed by the remote peer.
2601  *
2602  * Sets whether the process should be terminated when @connection is
2603  * closed by the remote peer. See #GDBusConnection:exit-on-close for
2604  * more details.
2605  *
2606  * Since: 2.26
2607  */
2608 void
2609 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2610                                      gboolean         exit_on_close)
2611 {
2612   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2613   connection->exit_on_close = exit_on_close;
2614 }
2615
2616 /**
2617  * g_dbus_connection_get_exit_on_close:
2618  * @connection: A #GDBusConnection.
2619  *
2620  * Gets whether the process is terminated when @connection is
2621  * closed by the remote peer. See
2622  * #GDBusConnection:exit-on-close for more details.
2623  *
2624  * Returns: Whether the process is terminated when @connection is
2625  * closed by the remote peer.
2626  *
2627  * Since: 2.26
2628  */
2629 gboolean
2630 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2631 {
2632   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2633   return connection->exit_on_close;
2634 }
2635
2636 /**
2637  * g_dbus_connection_get_guid:
2638  * @connection: A #GDBusConnection.
2639  *
2640  * The GUID of the peer performing the role of server when
2641  * authenticating. See #GDBusConnection:guid for more details.
2642  *
2643  * Returns: The GUID. Do not free this string, it is owned by
2644  * @connection.
2645  *
2646  * Since: 2.26
2647  */
2648 const gchar *
2649 g_dbus_connection_get_guid (GDBusConnection *connection)
2650 {
2651   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2652   return connection->guid;
2653 }
2654
2655 /**
2656  * g_dbus_connection_get_unique_name:
2657  * @connection: A #GDBusConnection.
2658  *
2659  * Gets the unique name of @connection as assigned by the message
2660  * bus. This can also be used to figure out if @connection is a
2661  * message bus connection.
2662  *
2663  * Returns: The unique name or %NULL if @connection is not a message
2664  * bus connection. Do not free this string, it is owned by
2665  * @connection.
2666  *
2667  * Since: 2.26
2668  */
2669 const gchar *
2670 g_dbus_connection_get_unique_name (GDBusConnection *connection)
2671 {
2672   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2673   return connection->bus_unique_name;
2674 }
2675
2676 /**
2677  * g_dbus_connection_get_peer_credentials:
2678  * @connection: A #GDBusConnection.
2679  *
2680  * Gets the credentials of the authenticated peer. This will always
2681  * return %NULL unless @connection acted as a server
2682  * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
2683  * when set up and the client passed credentials as part of the
2684  * authentication process.
2685  *
2686  * In a message bus setup, the message bus is always the server and
2687  * each application is a client. So this method will always return
2688  * %NULL for message bus clients.
2689  *
2690  * Returns: A #GCredentials or %NULL if not available. Do not free
2691  * this object, it is owned by @connection.
2692  *
2693  * Since: 2.26
2694  */
2695 GCredentials *
2696 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
2697 {
2698   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2699   return connection->credentials;
2700 }
2701
2702 /* ---------------------------------------------------------------------------------------------------- */
2703
2704 static guint _global_filter_id = 1;
2705
2706 /**
2707  * g_dbus_connection_add_filter:
2708  * @connection: A #GDBusConnection.
2709  * @filter_function: A filter function.
2710  * @user_data: User data to pass to @filter_function.
2711  * @user_data_free_func: Function to free @user_data with when filter
2712  * is removed or %NULL.
2713  *
2714  * Adds a message filter. Filters are handlers that are run on all
2715  * incoming and outgoing messages, prior to standard dispatch. Filters
2716  * are run in the order that they were added.  The same handler can be
2717  * added as a filter more than once, in which case it will be run more
2718  * than once.  Filters added during a filter callback won't be run on
2719  * the message being processed. Filter functions are allowed to modify
2720  * and even drop messages - see the #GDBusMessageFilterResult
2721  * enumeration for details.
2722  *
2723  * Note that filters are run in a dedicated message handling thread so
2724  * they can't block and, generally, can't do anything but signal a
2725  * worker thread. Also note that filters are rarely needed - use API
2726  * such as g_dbus_connection_send_message_with_reply(),
2727  * g_dbus_connection_signal_subscribe() or
2728  * g_dbus_connection_call() instead.
2729  *
2730  * If a filter consumes an incoming message the message is not
2731  * dispatched anywhere else - not even the standard dispatch machinery
2732  * (that API such as g_dbus_connection_signal_subscribe() and
2733  * g_dbus_connection_send_message_with_reply() relies on) will see the
2734  * message. Similary, if a filter consumes an outgoing message, the
2735  * message will not be sent to the other peer.
2736  *
2737  * Returns: A filter identifier that can be used with
2738  * g_dbus_connection_remove_filter().
2739  *
2740  * Since: 2.26
2741  */
2742 guint
2743 g_dbus_connection_add_filter (GDBusConnection            *connection,
2744                               GDBusMessageFilterFunction  filter_function,
2745                               gpointer                    user_data,
2746                               GDestroyNotify              user_data_free_func)
2747 {
2748   FilterData *data;
2749
2750   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2751   g_return_val_if_fail (filter_function != NULL, 0);
2752
2753   CONNECTION_LOCK (connection);
2754   data = g_new0 (FilterData, 1);
2755   data->id = _global_filter_id++; /* TODO: overflow etc. */
2756   data->filter_function = filter_function;
2757   data->user_data = user_data;
2758   data->user_data_free_func = user_data_free_func;
2759   g_ptr_array_add (connection->filters, data);
2760   CONNECTION_UNLOCK (connection);
2761
2762   return data->id;
2763 }
2764
2765 /* only called from finalize(), removes all filters */
2766 static void
2767 purge_all_filters (GDBusConnection *connection)
2768 {
2769   guint n;
2770   for (n = 0; n < connection->filters->len; n++)
2771     {
2772       FilterData *data = connection->filters->pdata[n];
2773       if (data->user_data_free_func != NULL)
2774         data->user_data_free_func (data->user_data);
2775       g_free (data);
2776     }
2777 }
2778
2779 /**
2780  * g_dbus_connection_remove_filter:
2781  * @connection: a #GDBusConnection
2782  * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
2783  *
2784  * Removes a filter.
2785  *
2786  * Since: 2.26
2787  */
2788 void
2789 g_dbus_connection_remove_filter (GDBusConnection *connection,
2790                                  guint            filter_id)
2791 {
2792   guint n;
2793   FilterData *to_destroy;
2794
2795   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2796
2797   CONNECTION_LOCK (connection);
2798   to_destroy = NULL;
2799   for (n = 0; n < connection->filters->len; n++)
2800     {
2801       FilterData *data = connection->filters->pdata[n];
2802       if (data->id == filter_id)
2803         {
2804           g_ptr_array_remove_index (connection->filters, n);
2805           to_destroy = data;
2806           break;
2807         }
2808     }
2809   CONNECTION_UNLOCK (connection);
2810
2811   /* do free without holding lock */
2812   if (to_destroy != NULL)
2813     {
2814       if (to_destroy->user_data_free_func != NULL)
2815         to_destroy->user_data_free_func (to_destroy->user_data);
2816       g_free (to_destroy);
2817     }
2818   else
2819     {
2820       g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
2821     }
2822 }
2823
2824 /* ---------------------------------------------------------------------------------------------------- */
2825
2826 typedef struct
2827 {
2828   gchar *rule;
2829   gchar *sender;
2830   gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
2831   gchar *interface_name;
2832   gchar *member;
2833   gchar *object_path;
2834   gchar *arg0;
2835   GArray *subscribers;
2836 } SignalData;
2837
2838 typedef struct
2839 {
2840   GDBusSignalCallback callback;
2841   gpointer user_data;
2842   GDestroyNotify user_data_free_func;
2843   guint id;
2844   GMainContext *context;
2845 } SignalSubscriber;
2846
2847 static void
2848 signal_data_free (SignalData *signal_data)
2849 {
2850   g_free (signal_data->rule);
2851   g_free (signal_data->sender);
2852   g_free (signal_data->sender_unique_name);
2853   g_free (signal_data->interface_name);
2854   g_free (signal_data->member);
2855   g_free (signal_data->object_path);
2856   g_free (signal_data->arg0);
2857   g_array_free (signal_data->subscribers, TRUE);
2858   g_free (signal_data);
2859 }
2860
2861 static gchar *
2862 args_to_rule (const gchar *sender,
2863               const gchar *interface_name,
2864               const gchar *member,
2865               const gchar *object_path,
2866               const gchar *arg0)
2867 {
2868   GString *rule;
2869
2870   rule = g_string_new ("type='signal'");
2871   if (sender != NULL)
2872     g_string_append_printf (rule, ",sender='%s'", sender);
2873   if (interface_name != NULL)
2874     g_string_append_printf (rule, ",interface='%s'", interface_name);
2875   if (member != NULL)
2876     g_string_append_printf (rule, ",member='%s'", member);
2877   if (object_path != NULL)
2878     g_string_append_printf (rule, ",path='%s'", object_path);
2879   if (arg0 != NULL)
2880     g_string_append_printf (rule, ",arg0='%s'", arg0);
2881
2882   return g_string_free (rule, FALSE);
2883 }
2884
2885 static guint _global_subscriber_id = 1;
2886 static guint _global_registration_id = 1;
2887 static guint _global_subtree_registration_id = 1;
2888
2889 /* ---------------------------------------------------------------------------------------------------- */
2890
2891 /* must hold lock when calling */
2892 static void
2893 add_match_rule (GDBusConnection *connection,
2894                 const gchar     *match_rule)
2895 {
2896   GError *error;
2897   GDBusMessage *message;
2898
2899   message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2900                                             "/org/freedesktop/DBus", /* path */
2901                                             "org.freedesktop.DBus", /* interface */
2902                                             "AddMatch");
2903   g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2904   error = NULL;
2905   if (!g_dbus_connection_send_message_unlocked (connection,
2906                                                 message,
2907                                                 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
2908                                                 NULL,
2909                                                 &error))
2910     {
2911       g_critical ("Error while sending AddMatch() message: %s", error->message);
2912       g_error_free (error);
2913     }
2914   g_object_unref (message);
2915 }
2916
2917 /* ---------------------------------------------------------------------------------------------------- */
2918
2919 /* must hold lock when calling */
2920 static void
2921 remove_match_rule (GDBusConnection *connection,
2922                    const gchar     *match_rule)
2923 {
2924   GError *error;
2925   GDBusMessage *message;
2926
2927   message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2928                                             "/org/freedesktop/DBus", /* path */
2929                                             "org.freedesktop.DBus", /* interface */
2930                                             "RemoveMatch");
2931   g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2932
2933   error = NULL;
2934   if (!g_dbus_connection_send_message_unlocked (connection,
2935                                                 message,
2936                                                 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
2937                                                 NULL,
2938                                                 &error))
2939     {
2940       g_critical ("Error while sending RemoveMatch() message: %s", error->message);
2941       g_error_free (error);
2942     }
2943   g_object_unref (message);
2944 }
2945
2946 /* ---------------------------------------------------------------------------------------------------- */
2947
2948 static gboolean
2949 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
2950 {
2951   return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
2952          g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
2953          g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
2954          (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
2955           g_strcmp0 (signal_data->member, "NameAcquired") == 0);
2956 }
2957
2958 /* ---------------------------------------------------------------------------------------------------- */
2959
2960 /**
2961  * g_dbus_connection_signal_subscribe:
2962  * @connection: A #GDBusConnection.
2963  * @sender: Sender name to match on (unique or well-known name) or %NULL to listen from all senders.
2964  * @interface_name: D-Bus interface name to match on or %NULL to match on all interfaces.
2965  * @member: D-Bus signal name to match on or %NULL to match on all signals.
2966  * @object_path: Object path to match on or %NULL to match on all object paths.
2967  * @arg0: Contents of first string argument to match on or %NULL to match on all kinds of arguments.
2968  * @flags: Flags describing how to subscribe to the signal (currently unused).
2969  * @callback: Callback to invoke when there is a signal matching the requested data.
2970  * @user_data: User data to pass to @callback.
2971  * @user_data_free_func: Function to free @user_data with when subscription is removed or %NULL.
2972  *
2973  * Subscribes to signals on @connection and invokes @callback with a
2974  * whenever the signal is received. Note that @callback
2975  * will be invoked in the <link
2976  * linkend="g-main-context-push-thread-default">thread-default main
2977  * loop</link> of the thread you are calling this method from.
2978  *
2979  * If @connection is not a message bus connection, @sender must be
2980  * %NULL.
2981  *
2982  * If @sender is a well-known name note that @callback is invoked with
2983  * the unique name for the owner of @sender, not the well-known name
2984  * as one would expect. This is because the message bus rewrites the
2985  * name. As such, to avoid certain race conditions, users should be
2986  * tracking the name owner of the well-known name and use that when
2987  * processing the received signal.
2988  *
2989  * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
2990  *
2991  * Since: 2.26
2992  */
2993 guint
2994 g_dbus_connection_signal_subscribe (GDBusConnection     *connection,
2995                                     const gchar         *sender,
2996                                     const gchar         *interface_name,
2997                                     const gchar         *member,
2998                                     const gchar         *object_path,
2999                                     const gchar         *arg0,
3000                                     GDBusSignalFlags     flags,
3001                                     GDBusSignalCallback  callback,
3002                                     gpointer             user_data,
3003                                     GDestroyNotify       user_data_free_func)
3004 {
3005   gchar *rule;
3006   SignalData *signal_data;
3007   SignalSubscriber subscriber;
3008   GPtrArray *signal_data_array;
3009   const gchar *sender_unique_name;
3010
3011   /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3012    * an OOM condition. We might want to change that but that would involve making
3013    * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3014    * handle that. And there's really no sensible way of handling this short of retrying
3015    * to add the match rule... and then there's the little thing that, hey, maybe there's
3016    * a reason the bus in an OOM condition.
3017    *
3018    * Doable, but not really sure it's worth it...
3019    */
3020
3021   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3022   g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3023   g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3024   g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3025   g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3026   g_return_val_if_fail (callback != NULL, 0);
3027
3028   CONNECTION_LOCK (connection);
3029
3030   rule = args_to_rule (sender, interface_name, member, object_path, arg0);
3031
3032   if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3033     sender_unique_name = sender;
3034   else
3035     sender_unique_name = "";
3036
3037   subscriber.callback = callback;
3038   subscriber.user_data = user_data;
3039   subscriber.user_data_free_func = user_data_free_func;
3040   subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
3041   subscriber.context = g_main_context_get_thread_default ();
3042   if (subscriber.context != NULL)
3043     g_main_context_ref (subscriber.context);
3044
3045   /* see if we've already have this rule */
3046   signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3047   if (signal_data != NULL)
3048     {
3049       g_array_append_val (signal_data->subscribers, subscriber);
3050       g_free (rule);
3051       goto out;
3052     }
3053
3054   signal_data = g_new0 (SignalData, 1);
3055   signal_data->rule                  = rule;
3056   signal_data->sender                = g_strdup (sender);
3057   signal_data->sender_unique_name    = g_strdup (sender_unique_name);
3058   signal_data->interface_name        = g_strdup (interface_name);
3059   signal_data->member                = g_strdup (member);
3060   signal_data->object_path           = g_strdup (object_path);
3061   signal_data->arg0                  = g_strdup (arg0);
3062   signal_data->subscribers           = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3063   g_array_append_val (signal_data->subscribers, subscriber);
3064
3065   g_hash_table_insert (connection->map_rule_to_signal_data,
3066                        signal_data->rule,
3067                        signal_data);
3068
3069   /* Add the match rule to the bus...
3070    *
3071    * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3072    * always send such messages to us.
3073    */
3074   if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3075     {
3076       if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3077         add_match_rule (connection, signal_data->rule);
3078     }
3079
3080   signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3081                                            signal_data->sender_unique_name);
3082   if (signal_data_array == NULL)
3083     {
3084       signal_data_array = g_ptr_array_new ();
3085       g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3086                            g_strdup (signal_data->sender_unique_name),
3087                            signal_data_array);
3088     }
3089   g_ptr_array_add (signal_data_array, signal_data);
3090
3091  out:
3092   g_hash_table_insert (connection->map_id_to_signal_data,
3093                        GUINT_TO_POINTER (subscriber.id),
3094                        signal_data);
3095
3096   CONNECTION_UNLOCK (connection);
3097
3098   return subscriber.id;
3099 }
3100
3101 /* ---------------------------------------------------------------------------------------------------- */
3102
3103 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3104 static void
3105 unsubscribe_id_internal (GDBusConnection *connection,
3106                          guint            subscription_id,
3107                          GArray          *out_removed_subscribers)
3108 {
3109   SignalData *signal_data;
3110   GPtrArray *signal_data_array;
3111   guint n;
3112
3113   signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3114                                      GUINT_TO_POINTER (subscription_id));
3115   if (signal_data == NULL)
3116     {
3117       /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3118       goto out;
3119     }
3120
3121   for (n = 0; n < signal_data->subscribers->len; n++)
3122     {
3123       SignalSubscriber *subscriber;
3124
3125       subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3126       if (subscriber->id != subscription_id)
3127         continue;
3128
3129       g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3130                                            GUINT_TO_POINTER (subscription_id)));
3131       g_array_append_val (out_removed_subscribers, *subscriber);
3132       g_array_remove_index (signal_data->subscribers, n);
3133
3134       if (signal_data->subscribers->len == 0)
3135         {
3136           g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3137
3138           signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3139                                                    signal_data->sender_unique_name);
3140           g_warn_if_fail (signal_data_array != NULL);
3141           g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3142
3143           if (signal_data_array->len == 0)
3144             {
3145               g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3146                                                    signal_data->sender_unique_name));
3147             }
3148
3149           /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3150           if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3151             {
3152               if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3153                 if (!connection->closed && !connection->finalizing)
3154                   remove_match_rule (connection, signal_data->rule);
3155             }
3156           signal_data_free (signal_data);
3157         }
3158
3159       goto out;
3160     }
3161
3162   g_assert_not_reached ();
3163
3164  out:
3165   ;
3166 }
3167
3168 /**
3169  * g_dbus_connection_signal_unsubscribe:
3170  * @connection: A #GDBusConnection.
3171  * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
3172  *
3173  * Unsubscribes from signals.
3174  *
3175  * Since: 2.26
3176  */
3177 void
3178 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3179                                       guint            subscription_id)
3180 {
3181   GArray *subscribers;
3182   guint n;
3183
3184   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3185
3186   subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3187
3188   CONNECTION_LOCK (connection);
3189   unsubscribe_id_internal (connection,
3190                            subscription_id,
3191                            subscribers);
3192   CONNECTION_UNLOCK (connection);
3193
3194   /* invariant */
3195   g_assert (subscribers->len == 0 || subscribers->len == 1);
3196
3197   /* call GDestroyNotify without lock held */
3198   for (n = 0; n < subscribers->len; n++)
3199     {
3200       SignalSubscriber *subscriber;
3201       subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3202       if (subscriber->user_data_free_func != NULL)
3203         subscriber->user_data_free_func (subscriber->user_data);
3204       if (subscriber->context != NULL)
3205         g_main_context_unref (subscriber->context);
3206     }
3207
3208   g_array_free (subscribers, TRUE);
3209 }
3210
3211 /* ---------------------------------------------------------------------------------------------------- */
3212
3213 typedef struct
3214 {
3215   guint                subscription_id;
3216   GDBusSignalCallback  callback;
3217   gpointer             user_data;
3218   GDBusMessage        *message;
3219   GDBusConnection     *connection;
3220   const gchar         *sender;
3221   const gchar         *path;
3222   const gchar         *interface;
3223   const gchar         *member;
3224 } SignalInstance;
3225
3226 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3227  * no locks held
3228  */
3229 static gboolean
3230 emit_signal_instance_in_idle_cb (gpointer data)
3231 {
3232   SignalInstance *signal_instance = data;
3233   GVariant *parameters;
3234   gboolean has_subscription;
3235
3236   parameters = g_dbus_message_get_body (signal_instance->message);
3237   if (parameters == NULL)
3238     {
3239       parameters = g_variant_new ("()");
3240       g_variant_ref_sink (parameters);
3241     }
3242   else
3243     {
3244       g_variant_ref_sink (parameters);
3245     }
3246
3247 #if 0
3248   g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3249            signal_instance->subscription_id,
3250            signal_instance->sender,
3251            signal_instance->path,
3252            signal_instance->interface,
3253            signal_instance->member,
3254            g_variant_print (parameters, TRUE));
3255 #endif
3256
3257   /* Careful here, don't do the callback if we no longer has the subscription */
3258   CONNECTION_LOCK (signal_instance->connection);
3259   has_subscription = FALSE;
3260   if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3261                            GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3262     has_subscription = TRUE;
3263   CONNECTION_UNLOCK (signal_instance->connection);
3264
3265   if (has_subscription)
3266     signal_instance->callback (signal_instance->connection,
3267                                signal_instance->sender,
3268                                signal_instance->path,
3269                                signal_instance->interface,
3270                                signal_instance->member,
3271                                parameters,
3272                                signal_instance->user_data);
3273
3274   if (parameters != NULL)
3275     g_variant_unref (parameters);
3276
3277   return FALSE;
3278 }
3279
3280 static void
3281 signal_instance_free (SignalInstance *signal_instance)
3282 {
3283   g_object_unref (signal_instance->message);
3284   g_object_unref (signal_instance->connection);
3285   g_free (signal_instance);
3286 }
3287
3288 /* called in message handler thread WITH lock held */
3289 static void
3290 schedule_callbacks (GDBusConnection *connection,
3291                     GPtrArray       *signal_data_array,
3292                     GDBusMessage    *message,
3293                     const gchar     *sender)
3294 {
3295   guint n, m;
3296   const gchar *interface;
3297   const gchar *member;
3298   const gchar *path;
3299   const gchar *arg0;
3300
3301   interface = NULL;
3302   member = NULL;
3303   path = NULL;
3304   arg0 = NULL;
3305
3306   interface = g_dbus_message_get_interface (message);
3307   member = g_dbus_message_get_member (message);
3308   path = g_dbus_message_get_path (message);
3309   arg0 = g_dbus_message_get_arg0 (message);
3310
3311 #if 0
3312   g_print ("In schedule_callbacks:\n"
3313            "  sender    = `%s'\n"
3314            "  interface = `%s'\n"
3315            "  member    = `%s'\n"
3316            "  path      = `%s'\n"
3317            "  arg0      = `%s'\n",
3318            sender,
3319            interface,
3320            member,
3321            path,
3322            arg0);
3323 #endif
3324
3325   /* TODO: if this is slow, then we can change signal_data_array into
3326    *       map_object_path_to_signal_data_array or something.
3327    */
3328   for (n = 0; n < signal_data_array->len; n++)
3329     {
3330       SignalData *signal_data = signal_data_array->pdata[n];
3331
3332       if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3333         continue;
3334
3335       if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3336         continue;
3337
3338       if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3339         continue;
3340
3341       if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
3342         continue;
3343
3344       for (m = 0; m < signal_data->subscribers->len; m++)
3345         {
3346           SignalSubscriber *subscriber;
3347           GSource *idle_source;
3348           SignalInstance *signal_instance;
3349
3350           subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3351
3352           signal_instance = g_new0 (SignalInstance, 1);
3353           signal_instance->subscription_id = subscriber->id;
3354           signal_instance->callback = subscriber->callback;
3355           signal_instance->user_data = subscriber->user_data;
3356           signal_instance->message = g_object_ref (message);
3357           signal_instance->connection = g_object_ref (connection);
3358           signal_instance->sender = sender;
3359           signal_instance->path = path;
3360           signal_instance->interface = interface;
3361           signal_instance->member = member;
3362
3363           idle_source = g_idle_source_new ();
3364           g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3365           g_source_set_callback (idle_source,
3366                                  emit_signal_instance_in_idle_cb,
3367                                  signal_instance,
3368                                  (GDestroyNotify) signal_instance_free);
3369           g_source_attach (idle_source, subscriber->context);
3370           g_source_unref (idle_source);
3371         }
3372     }
3373 }
3374
3375 /* called in message handler thread with lock held */
3376 static void
3377 distribute_signals (GDBusConnection *connection,
3378                     GDBusMessage    *message)
3379 {
3380   GPtrArray *signal_data_array;
3381   const gchar *sender;
3382
3383   sender = g_dbus_message_get_sender (message);
3384
3385   if (G_UNLIKELY (_g_dbus_debug_signal ()))
3386     {
3387       _g_dbus_debug_print_lock ();
3388       g_print ("========================================================================\n"
3389                "GDBus-debug:Signal:\n"
3390                " <<<< RECEIVED SIGNAL %s.%s\n"
3391                "      on object %s\n"
3392                "      sent by name %s\n",
3393                g_dbus_message_get_interface (message),
3394                g_dbus_message_get_member (message),
3395                g_dbus_message_get_path (message),
3396                sender != NULL ? sender : "(none)");
3397       _g_dbus_debug_print_unlock ();
3398     }
3399
3400   /* collect subscribers that match on sender */
3401   if (sender != NULL)
3402     {
3403       signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3404       if (signal_data_array != NULL)
3405         schedule_callbacks (connection, signal_data_array, message, sender);
3406     }
3407
3408   /* collect subscribers not matching on sender */
3409   signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3410   if (signal_data_array != NULL)
3411     schedule_callbacks (connection, signal_data_array, message, sender);
3412 }
3413
3414 /* ---------------------------------------------------------------------------------------------------- */
3415
3416 /* only called from finalize(), removes all subscriptions */
3417 static void
3418 purge_all_signal_subscriptions (GDBusConnection *connection)
3419 {
3420   GHashTableIter iter;
3421   gpointer key;
3422   GArray *ids;
3423   GArray *subscribers;
3424   guint n;
3425
3426   ids = g_array_new (FALSE, FALSE, sizeof (guint));
3427   g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3428   while (g_hash_table_iter_next (&iter, &key, NULL))
3429     {
3430       guint subscription_id = GPOINTER_TO_UINT (key);
3431       g_array_append_val (ids, subscription_id);
3432     }
3433
3434   subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3435   for (n = 0; n < ids->len; n++)
3436     {
3437       guint subscription_id = g_array_index (ids, guint, n);
3438       unsubscribe_id_internal (connection,
3439                                subscription_id,
3440                                subscribers);
3441     }
3442   g_array_free (ids, TRUE);
3443
3444   /* call GDestroyNotify without lock held */
3445   for (n = 0; n < subscribers->len; n++)
3446     {
3447       SignalSubscriber *subscriber;
3448       subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3449       if (subscriber->user_data_free_func != NULL)
3450         subscriber->user_data_free_func (subscriber->user_data);
3451       if (subscriber->context != NULL)
3452         g_main_context_unref (subscriber->context);
3453     }
3454
3455   g_array_free (subscribers, TRUE);
3456 }
3457
3458 /* ---------------------------------------------------------------------------------------------------- */
3459
3460 static GDBusInterfaceVTable *
3461 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3462 {
3463   /* Don't waste memory by copying padding - remember to update this
3464    * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3465    */
3466   return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3467 }
3468
3469 static void
3470 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
3471 {
3472   g_free (vtable);
3473 }
3474
3475 /* ---------------------------------------------------------------------------------------------------- */
3476
3477 static GDBusSubtreeVTable *
3478 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
3479 {
3480   /* Don't waste memory by copying padding - remember to update this
3481    * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
3482    */
3483   return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3484 }
3485
3486 static void
3487 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
3488 {
3489   g_free (vtable);
3490 }
3491
3492 /* ---------------------------------------------------------------------------------------------------- */
3493
3494 struct ExportedObject
3495 {
3496   gchar *object_path;
3497   GDBusConnection *connection;
3498
3499   /* maps gchar* -> ExportedInterface* */
3500   GHashTable *map_if_name_to_ei;
3501 };
3502
3503 /* only called with lock held */
3504 static void
3505 exported_object_free (ExportedObject *eo)
3506 {
3507   g_free (eo->object_path);
3508   g_hash_table_unref (eo->map_if_name_to_ei);
3509   g_free (eo);
3510 }
3511
3512 typedef struct
3513 {
3514   ExportedObject *eo;
3515
3516   guint                       id;
3517   gchar                      *interface_name;
3518   GDBusInterfaceVTable       *vtable;
3519   GDBusInterfaceInfo         *interface_info;
3520
3521   GMainContext               *context;
3522   gpointer                    user_data;
3523   GDestroyNotify              user_data_free_func;
3524 } ExportedInterface;
3525
3526 /* called with lock held */
3527 static void
3528 exported_interface_free (ExportedInterface *ei)
3529 {
3530   g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
3531
3532   if (ei->user_data_free_func != NULL)
3533     /* TODO: push to thread-default mainloop */
3534     ei->user_data_free_func (ei->user_data);
3535
3536   if (ei->context != NULL)
3537     g_main_context_unref (ei->context);
3538
3539   g_free (ei->interface_name);
3540   _g_dbus_interface_vtable_free (ei->vtable);
3541   g_free (ei);
3542 }
3543
3544 /* ---------------------------------------------------------------------------------------------------- */
3545
3546 /* Convenience function to check if @registration_id (if not zero) or
3547  * @subtree_registration_id (if not zero) has been unregistered. If
3548  * so, returns %TRUE.
3549  *
3550  * Caller must *not* hold lock.
3551  */
3552 static gboolean
3553 has_object_been_unregistered (GDBusConnection  *connection,
3554                               guint             registration_id,
3555                               guint             subtree_registration_id)
3556 {
3557   gboolean ret;
3558
3559   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3560
3561   ret = FALSE;
3562
3563   CONNECTION_LOCK (connection);
3564   if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
3565                                                    GUINT_TO_POINTER (registration_id)) == NULL)
3566     {
3567       ret = TRUE;
3568     }
3569   else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
3570                                                                 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
3571     {
3572       ret = TRUE;
3573     }
3574   CONNECTION_UNLOCK (connection);
3575
3576   return ret;
3577 }
3578
3579 /* ---------------------------------------------------------------------------------------------------- */
3580
3581 typedef struct
3582 {
3583   GDBusConnection *connection;
3584   GDBusMessage *message;
3585   gpointer user_data;
3586   const gchar *property_name;
3587   const GDBusInterfaceVTable *vtable;
3588   GDBusInterfaceInfo *interface_info;
3589   const GDBusPropertyInfo *property_info;
3590   guint registration_id;
3591   guint subtree_registration_id;
3592 } PropertyData;
3593
3594 static void
3595 property_data_free (PropertyData *data)
3596 {
3597   g_object_unref (data->connection);
3598   g_object_unref (data->message);
3599   g_free (data);
3600 }
3601
3602 /* called in thread where object was registered - no locks held */
3603 static gboolean
3604 invoke_get_property_in_idle_cb (gpointer _data)
3605 {
3606   PropertyData *data = _data;
3607   GVariant *value;
3608   GError *error;
3609   GDBusMessage *reply;
3610
3611   if (has_object_been_unregistered (data->connection,
3612                                     data->registration_id,
3613                                     data->subtree_registration_id))
3614     {
3615       reply = g_dbus_message_new_method_error (data->message,
3616                                                "org.freedesktop.DBus.Error.UnknownMethod",
3617                                                _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
3618                                                g_dbus_message_get_path (data->message));
3619       g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3620       g_object_unref (reply);
3621       goto out;
3622     }
3623
3624   error = NULL;
3625   value = data->vtable->get_property (data->connection,
3626                                       g_dbus_message_get_sender (data->message),
3627                                       g_dbus_message_get_path (data->message),
3628                                       data->interface_info->name,
3629                                       data->property_name,
3630                                       &error,
3631                                       data->user_data);
3632
3633
3634   if (value != NULL)
3635     {
3636       g_assert_no_error (error);
3637
3638       g_variant_ref_sink (value);
3639       reply = g_dbus_message_new_method_reply (data->message);
3640       g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
3641       g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3642       g_variant_unref (value);
3643       g_object_unref (reply);
3644     }
3645   else
3646     {
3647       gchar *dbus_error_name;
3648       g_assert (error != NULL);
3649       dbus_error_name = g_dbus_error_encode_gerror (error);
3650       reply = g_dbus_message_new_method_error_literal (data->message,
3651                                                        dbus_error_name,
3652                                                        error->message);
3653       g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3654       g_free (dbus_error_name);
3655       g_error_free (error);
3656       g_object_unref (reply);
3657     }
3658
3659  out:
3660   return FALSE;
3661 }
3662
3663 /* called in thread where object was registered - no locks held */
3664 static gboolean
3665 invoke_set_property_in_idle_cb (gpointer _data)
3666 {
3667   PropertyData *data = _data;
3668   GError *error;
3669   GDBusMessage *reply;
3670   GVariant *value;
3671
3672   error = NULL;
3673   value = NULL;
3674
3675   g_variant_get (g_dbus_message_get_body (data->message),
3676                  "(ssv)",
3677                  NULL,
3678                  NULL,
3679                  &value);
3680
3681   /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
3682    * of the given value is wrong
3683    */
3684   if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
3685     {
3686       reply = g_dbus_message_new_method_error (data->message,
3687                                                "org.freedesktop.DBus.Error.InvalidArgs",
3688                                                _("Error setting property `%s': Expected type `%s' but got `%s'"),
3689                                                data->property_info->name,
3690                                                data->property_info->signature,
3691                                                g_variant_get_type_string (value));
3692       goto out;
3693     }
3694
3695   if (!data->vtable->set_property (data->connection,
3696                                    g_dbus_message_get_sender (data->message),
3697                                    g_dbus_message_get_path (data->message),
3698                                    data->interface_info->name,
3699                                    data->property_name,
3700                                    value,
3701                                    &error,
3702                                    data->user_data))
3703     {
3704       gchar *dbus_error_name;
3705       g_assert (error != NULL);
3706       dbus_error_name = g_dbus_error_encode_gerror (error);
3707       reply = g_dbus_message_new_method_error_literal (data->message,
3708                                                        dbus_error_name,
3709                                                        error->message);
3710       g_free (dbus_error_name);
3711       g_error_free (error);
3712     }
3713   else
3714     {
3715       reply = g_dbus_message_new_method_reply (data->message);
3716     }
3717
3718  out:
3719   g_assert (reply != NULL);
3720   g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3721   g_object_unref (reply);
3722
3723   return FALSE;
3724 }
3725
3726 /* called with lock held */
3727 static gboolean
3728 validate_and_maybe_schedule_property_getset (GDBusConnection            *connection,
3729                                              GDBusMessage               *message,
3730                                              guint                       registration_id,
3731                                              guint                       subtree_registration_id,
3732                                              gboolean                    is_get,
3733                                              GDBusInterfaceInfo         *interface_info,
3734                                              const GDBusInterfaceVTable *vtable,
3735                                              GMainContext               *main_context,
3736                                              gpointer                    user_data)
3737 {
3738   gboolean handled;
3739   const char *interface_name;
3740   const char *property_name;
3741   const GDBusPropertyInfo *property_info;
3742   GSource *idle_source;
3743   PropertyData *property_data;
3744   GDBusMessage *reply;
3745
3746   handled = FALSE;
3747
3748   if (is_get)
3749     g_variant_get (g_dbus_message_get_body (message),
3750                    "(&s&s)",
3751                    &interface_name,
3752                    &property_name);
3753   else
3754     g_variant_get (g_dbus_message_get_body (message),
3755                    "(&s&sv)",
3756                    &interface_name,
3757                    &property_name,
3758                    NULL);
3759
3760
3761   if (is_get)
3762     {
3763       if (vtable == NULL || vtable->get_property == NULL)
3764         goto out;
3765     }
3766   else
3767     {
3768       if (vtable == NULL || vtable->set_property == NULL)
3769         goto out;
3770     }
3771
3772   /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
3773    */
3774   property_info = NULL;
3775
3776   /* TODO: the cost of this is O(n) - it might be worth caching the result */
3777   property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
3778   if (property_info == NULL)
3779     {
3780       reply = g_dbus_message_new_method_error (message,
3781                                                "org.freedesktop.DBus.Error.InvalidArgs",
3782                                                _("No such property `%s'"),
3783                                                property_name);
3784       g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3785       g_object_unref (reply);
3786       handled = TRUE;
3787       goto out;
3788     }
3789
3790   if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3791     {
3792       reply = g_dbus_message_new_method_error (message,
3793                                                "org.freedesktop.DBus.Error.InvalidArgs",
3794                                                _("Property `%s' is not readable"),
3795                                                property_name);
3796       g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3797       g_object_unref (reply);
3798       handled = TRUE;
3799       goto out;
3800     }
3801   else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
3802     {
3803       reply = g_dbus_message_new_method_error (message,
3804                                                "org.freedesktop.DBus.Error.InvalidArgs",
3805                                                _("Property `%s' is not writable"),
3806                                                property_name);
3807       g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3808       g_object_unref (reply);
3809       handled = TRUE;
3810       goto out;
3811     }
3812
3813   /* ok, got the property info - call user code in an idle handler */
3814   property_data = g_new0 (PropertyData, 1);
3815   property_data->connection = g_object_ref (connection);
3816   property_data->message = g_object_ref (message);
3817   property_data->user_data = user_data;
3818   property_data->property_name = property_name;
3819   property_data->vtable = vtable;
3820   property_data->interface_info = interface_info;
3821   property_data->property_info = property_info;
3822   property_data->registration_id = registration_id;
3823   property_data->subtree_registration_id = subtree_registration_id;
3824
3825   idle_source = g_idle_source_new ();
3826   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3827   g_source_set_callback (idle_source,
3828                          is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
3829                          property_data,
3830                          (GDestroyNotify) property_data_free);
3831   g_source_attach (idle_source, main_context);
3832   g_source_unref (idle_source);
3833
3834   handled = TRUE;
3835
3836  out:
3837   return handled;
3838 }
3839
3840 /* called with lock held */
3841 static gboolean
3842 handle_getset_property (GDBusConnection *connection,
3843                         ExportedObject  *eo,
3844                         GDBusMessage    *message,
3845                         gboolean         is_get)
3846 {
3847   ExportedInterface *ei;
3848   gboolean handled;
3849   const char *interface_name;
3850   const char *property_name;
3851
3852   handled = FALSE;
3853
3854   if (is_get)
3855     g_variant_get (g_dbus_message_get_body (message),
3856                    "(&s&s)",
3857                    &interface_name,
3858                    &property_name);
3859   else
3860     g_variant_get (g_dbus_message_get_body (message),
3861                    "(&s&sv)",
3862                    &interface_name,
3863                    &property_name,
3864                    NULL);
3865
3866   /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3867    * no such interface registered
3868    */
3869   ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3870   if (ei == NULL)
3871     {
3872       GDBusMessage *reply;
3873       reply = g_dbus_message_new_method_error (message,
3874                                                "org.freedesktop.DBus.Error.InvalidArgs",
3875                                                _("No such interface `%s'"),
3876                                                interface_name);
3877       g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3878       g_object_unref (reply);
3879       handled = TRUE;
3880       goto out;
3881     }
3882
3883   handled = validate_and_maybe_schedule_property_getset (eo->connection,
3884                                                          message,
3885                                                          ei->id,
3886                                                          0,
3887                                                          is_get,
3888                                                          ei->interface_info,
3889                                                          ei->vtable,
3890                                                          ei->context,
3891                                                          ei->user_data);
3892  out:
3893   return handled;
3894 }
3895
3896 /* ---------------------------------------------------------------------------------------------------- */
3897
3898 typedef struct
3899 {
3900   GDBusConnection *connection;
3901   GDBusMessage *message;
3902   gpointer user_data;
3903   const GDBusInterfaceVTable *vtable;
3904   GDBusInterfaceInfo *interface_info;
3905   guint registration_id;
3906   guint subtree_registration_id;
3907 } PropertyGetAllData;
3908
3909 static void
3910 property_get_all_data_free (PropertyData *data)
3911 {
3912   g_object_unref (data->connection);
3913   g_object_unref (data->message);
3914   g_free (data);
3915 }
3916
3917 /* called in thread where object was registered - no locks held */
3918 static gboolean
3919 invoke_get_all_properties_in_idle_cb (gpointer _data)
3920 {
3921   PropertyGetAllData *data = _data;
3922   GVariantBuilder builder;
3923   GError *error;
3924   GDBusMessage *reply;
3925   guint n;
3926
3927   if (has_object_been_unregistered (data->connection,
3928                                     data->registration_id,
3929                                     data->subtree_registration_id))
3930     {
3931       reply = g_dbus_message_new_method_error (data->message,
3932                                                "org.freedesktop.DBus.Error.UnknownMethod",
3933                                                _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
3934                                                g_dbus_message_get_path (data->message));
3935       g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3936       g_object_unref (reply);
3937       goto out;
3938     }
3939
3940   error = NULL;
3941
3942   /* TODO: Right now we never fail this call - we just omit values if
3943    *       a get_property() call is failing.
3944    *
3945    *       We could fail the whole call if just a single get_property() call
3946    *       returns an error. We need clarification in the D-Bus spec about this.
3947    */
3948   g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
3949   g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
3950   for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
3951     {
3952       const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
3953       GVariant *value;
3954
3955       if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3956         continue;
3957
3958       value = data->vtable->get_property (data->connection,
3959                                           g_dbus_message_get_sender (data->message),
3960                                           g_dbus_message_get_path (data->message),
3961                                           data->interface_info->name,
3962                                           property_info->name,
3963                                           NULL,
3964                                           data->user_data);
3965
3966       if (value == NULL)
3967         continue;
3968
3969       g_variant_builder_add (&builder,
3970                              "{sv}",
3971                              property_info->name,
3972                              value);
3973     }
3974   g_variant_builder_close (&builder);
3975
3976   reply = g_dbus_message_new_method_reply (data->message);
3977   g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
3978   g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3979   g_object_unref (reply);
3980
3981  out:
3982   return FALSE;
3983 }
3984
3985 /* called with lock held */
3986 static gboolean
3987 validate_and_maybe_schedule_property_get_all (GDBusConnection            *connection,
3988                                               GDBusMessage               *message,
3989                                               guint                       registration_id,
3990                                               guint                       subtree_registration_id,
3991                                               GDBusInterfaceInfo         *interface_info,
3992                                               const GDBusInterfaceVTable *vtable,
3993                                               GMainContext               *main_context,
3994                                               gpointer                    user_data)
3995 {
3996   gboolean handled;
3997   const char *interface_name;
3998   GSource *idle_source;
3999   PropertyGetAllData *property_get_all_data;
4000
4001   handled = FALSE;
4002
4003   g_variant_get (g_dbus_message_get_body (message),
4004                  "(&s)",
4005                  &interface_name);
4006
4007   if (vtable == NULL || vtable->get_property == NULL)
4008     goto out;
4009
4010   /* ok, got the property info - call user in an idle handler */
4011   property_get_all_data = g_new0 (PropertyGetAllData, 1);
4012   property_get_all_data->connection = g_object_ref (connection);
4013   property_get_all_data->message = g_object_ref (message);
4014   property_get_all_data->user_data = user_data;
4015   property_get_all_data->vtable = vtable;
4016   property_get_all_data->interface_info = interface_info;
4017   property_get_all_data->registration_id = registration_id;
4018   property_get_all_data->subtree_registration_id = subtree_registration_id;
4019
4020   idle_source = g_idle_source_new ();
4021   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4022   g_source_set_callback (idle_source,
4023                          invoke_get_all_properties_in_idle_cb,
4024                          property_get_all_data,
4025                          (GDestroyNotify) property_get_all_data_free);
4026   g_source_attach (idle_source, main_context);
4027   g_source_unref (idle_source);
4028
4029   handled = TRUE;
4030
4031  out:
4032   return handled;
4033 }
4034
4035 /* called with lock held */
4036 static gboolean
4037 handle_get_all_properties (GDBusConnection *connection,
4038                            ExportedObject  *eo,
4039                            GDBusMessage    *message)
4040 {
4041   ExportedInterface *ei;
4042   gboolean handled;
4043   const char *interface_name;
4044
4045   handled = FALSE;
4046
4047   g_variant_get (g_dbus_message_get_body (message),
4048                  "(&s)",
4049                  &interface_name);
4050
4051   /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4052    * no such interface registered
4053    */
4054   ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4055   if (ei == NULL)
4056     {
4057       GDBusMessage *reply;
4058       reply = g_dbus_message_new_method_error (message,
4059                                                "org.freedesktop.DBus.Error.InvalidArgs",
4060                                                _("No such interface"),
4061                                                interface_name);
4062       g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4063       g_object_unref (reply);
4064       handled = TRUE;
4065       goto out;
4066     }
4067
4068   handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4069                                                           message,
4070                                                           ei->id,
4071                                                           0,
4072                                                           ei->interface_info,
4073                                                           ei->vtable,
4074                                                           ei->context,
4075                                                           ei->user_data);
4076  out:
4077   return handled;
4078 }
4079
4080 /* ---------------------------------------------------------------------------------------------------- */
4081
4082 static const gchar introspect_header[] =
4083   "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4084   "                      \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4085   "<!-- GDBus " PACKAGE_VERSION " -->\n"
4086   "<node>\n";
4087
4088 static const gchar introspect_tail[] =
4089   "</node>\n";
4090
4091 static const gchar introspect_standard_interfaces[] =
4092   "  <interface name=\"org.freedesktop.DBus.Properties\">\n"
4093   "    <method name=\"Get\">\n"
4094   "      <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4095   "      <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4096   "      <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4097   "    </method>\n"
4098   "    <method name=\"GetAll\">\n"
4099   "      <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4100   "      <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4101   "    </method>\n"
4102   "    <method name=\"Set\">\n"
4103   "      <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4104   "      <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4105   "      <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4106   "    </method>\n"
4107   "    <signal name=\"PropertiesChanged\">\n"
4108   "      <arg type=\"s\" name=\"interface_name\"/>\n"
4109   "      <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4110   "      <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4111   "    </signal>\n"
4112   "  </interface>\n"
4113   "  <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4114   "    <method name=\"Introspect\">\n"
4115   "      <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4116   "    </method>\n"
4117   "  </interface>\n"
4118   "  <interface name=\"org.freedesktop.DBus.Peer\">\n"
4119   "    <method name=\"Ping\"/>\n"
4120   "    <method name=\"GetMachineId\">\n"
4121   "      <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4122   "    </method>\n"
4123   "  </interface>\n";
4124
4125 static void
4126 introspect_append_header (GString *s)
4127 {
4128   g_string_append (s, introspect_header);
4129 }
4130
4131 static void
4132 introspect_append_standard_interfaces (GString *s)
4133 {
4134   g_string_append (s, introspect_standard_interfaces);
4135 }
4136
4137 static void
4138 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4139 {
4140   if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4141     {
4142       const gchar *begin;
4143       const gchar *end;
4144       gchar *s;
4145
4146       begin = object_path + path_len;
4147       end = strchr (begin, '/');
4148       if (end != NULL)
4149         s = g_strndup (begin, end - begin);
4150       else
4151         s = g_strdup (begin);
4152
4153       if (g_hash_table_lookup (set, s) == NULL)
4154         g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
4155       else
4156         g_free (s);
4157     }
4158 }
4159
4160 /* TODO: we want a nicer public interface for this */
4161 static gchar **
4162 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4163                                             const gchar     *path)
4164 {
4165   GPtrArray *p;
4166   gchar **ret;
4167   GHashTableIter hash_iter;
4168   const gchar *object_path;
4169   gsize path_len;
4170   GHashTable *set;
4171   GList *keys;
4172   GList *l;
4173
4174   CONNECTION_ENSURE_LOCK (connection);
4175
4176   path_len = strlen (path);
4177   if (path_len > 1)
4178     path_len++;
4179
4180   set = g_hash_table_new (g_str_hash, g_str_equal);
4181
4182   g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4183   while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4184     maybe_add_path (path, path_len, object_path, set);
4185
4186   g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4187   while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4188     maybe_add_path (path, path_len, object_path, set);
4189
4190   p = g_ptr_array_new ();
4191   keys = g_hash_table_get_keys (set);
4192   for (l = keys; l != NULL; l = l->next)
4193     g_ptr_array_add (p, l->data);
4194   g_hash_table_unref (set);
4195   g_list_free (keys);
4196
4197   g_ptr_array_add (p, NULL);
4198   ret = (gchar **) g_ptr_array_free (p, FALSE);
4199   return ret;
4200 }
4201
4202 static gchar **
4203 g_dbus_connection_list_registered (GDBusConnection *connection,
4204                                    const gchar     *path)
4205 {
4206   gchar **ret;
4207   CONNECTION_LOCK (connection);
4208   ret = g_dbus_connection_list_registered_unlocked (connection, path);
4209   CONNECTION_UNLOCK (connection);
4210   return ret;
4211 }
4212
4213 /* called in message handler thread with lock held */
4214 static gboolean
4215 handle_introspect (GDBusConnection *connection,
4216                    ExportedObject  *eo,
4217                    GDBusMessage    *message)
4218 {
4219   guint n;
4220   GString *s;
4221   GDBusMessage *reply;
4222   GHashTableIter hash_iter;
4223   ExportedInterface *ei;
4224   gchar **registered;
4225
4226   /* first the header with the standard interfaces */
4227   s = g_string_sized_new (sizeof (introspect_header) +
4228                           sizeof (introspect_standard_interfaces) +
4229                           sizeof (introspect_tail));
4230   introspect_append_header (s);
4231   introspect_append_standard_interfaces (s);
4232
4233   /* then include the registered interfaces */
4234   g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4235   while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4236     g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4237
4238   /* finally include nodes registered below us */
4239   registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4240   for (n = 0; registered != NULL && registered[n] != NULL; n++)
4241     g_string_append_printf (s, "  <node name=\"%s\"/>\n", registered[n]);
4242   g_strfreev (registered);
4243   g_string_append (s, introspect_tail);
4244
4245   reply = g_dbus_message_new_method_reply (message);
4246   g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4247   g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4248   g_object_unref (reply);
4249   g_string_free (s, TRUE);
4250
4251   return TRUE;
4252 }
4253
4254 /* called in thread where object was registered - no locks held */
4255 static gboolean
4256 call_in_idle_cb (gpointer user_data)
4257 {
4258   GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4259   GDBusInterfaceVTable *vtable;
4260   guint registration_id;
4261   guint subtree_registration_id;
4262
4263   vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4264   g_assert (vtable != NULL && vtable->method_call != NULL);
4265
4266   registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4267   subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4268
4269   if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4270                                     registration_id,
4271                                     subtree_registration_id))
4272     {
4273       GDBusMessage *reply;
4274       reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4275                                                "org.freedesktop.DBus.Error.UnknownMethod",
4276                                                _("No such interface `%s' on object at path %s"),
4277                                                g_dbus_method_invocation_get_interface_name (invocation),
4278                                                g_dbus_method_invocation_get_object_path (invocation));
4279       g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4280       g_object_unref (reply);
4281       goto out;
4282     }
4283
4284   vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4285                        g_dbus_method_invocation_get_sender (invocation),
4286                        g_dbus_method_invocation_get_object_path (invocation),
4287                        g_dbus_method_invocation_get_interface_name (invocation),
4288                        g_dbus_method_invocation_get_method_name (invocation),
4289                        g_dbus_method_invocation_get_parameters (invocation),
4290                        g_object_ref (invocation),
4291                        g_dbus_method_invocation_get_user_data (invocation));
4292
4293  out:
4294   return FALSE;
4295 }
4296
4297 /* called in message handler thread with lock held */
4298 static gboolean
4299 validate_and_maybe_schedule_method_call (GDBusConnection            *connection,
4300                                          GDBusMessage               *message,
4301                                          guint                       registration_id,
4302                                          guint                       subtree_registration_id,
4303                                          GDBusInterfaceInfo         *interface_info,
4304                                          const GDBusInterfaceVTable *vtable,
4305                                          GMainContext               *main_context,
4306                                          gpointer                    user_data)
4307 {
4308   GDBusMethodInvocation *invocation;
4309   const GDBusMethodInfo *method_info;
4310   GDBusMessage *reply;
4311   GVariant *parameters;
4312   GSource *idle_source;
4313   gboolean handled;
4314   GVariantType *in_type;
4315
4316   handled = FALSE;
4317
4318   /* TODO: the cost of this is O(n) - it might be worth caching the result */
4319   method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4320
4321   /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4322    * error to the caller
4323    */
4324   if (method_info == NULL)
4325     {
4326       reply = g_dbus_message_new_method_error (message,
4327                                                "org.freedesktop.DBus.Error.UnknownMethod",
4328                                                _("No such method `%s'"),
4329                                                g_dbus_message_get_member (message));
4330       g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4331       g_object_unref (reply);
4332       handled = TRUE;
4333       goto out;
4334     }
4335
4336   parameters = g_dbus_message_get_body (message);
4337   if (parameters == NULL)
4338     {
4339       parameters = g_variant_new ("()");
4340       g_variant_ref_sink (parameters);
4341     }
4342   else
4343     {
4344       g_variant_ref (parameters);
4345     }
4346
4347   /* Check that the incoming args are of the right type - if they are not, return
4348    * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4349    */
4350   in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4351   if (!g_variant_is_of_type (parameters, in_type))
4352     {
4353       gchar *type_string;
4354
4355       type_string = g_variant_type_dup_string (in_type);
4356
4357       reply = g_dbus_message_new_method_error (message,
4358                                                "org.freedesktop.DBus.Error.InvalidArgs",
4359                                                _("Type of message, `%s', does not match expected type `%s'"),
4360                                                g_variant_get_type_string (parameters),
4361                                                type_string);
4362       g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4363       g_variant_type_free (in_type);
4364       g_variant_unref (parameters);
4365       g_object_unref (reply);
4366       g_free (type_string);
4367       handled = TRUE;
4368       goto out;
4369     }
4370   g_variant_type_free (in_type);
4371
4372   /* schedule the call in idle */
4373   invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4374                                               g_dbus_message_get_path (message),
4375                                               g_dbus_message_get_interface (message),
4376                                               g_dbus_message_get_member (message),
4377                                               method_info,
4378                                               connection,
4379                                               message,
4380                                               parameters,
4381                                               user_data);
4382   g_variant_unref (parameters);
4383
4384   /* TODO: would be nicer with a real MethodData like we already
4385    * have PropertyData and PropertyGetAllData... */
4386   g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4387   g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4388   g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4389
4390   idle_source = g_idle_source_new ();
4391   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4392   g_source_set_callback (idle_source,
4393                          call_in_idle_cb,
4394                          invocation,
4395                          g_object_unref);
4396   g_source_attach (idle_source, main_context);
4397   g_source_unref (idle_source);
4398
4399   handled = TRUE;
4400
4401  out:
4402   return handled;
4403 }
4404
4405 /* ---------------------------------------------------------------------------------------------------- */
4406
4407 /* called in message handler thread with lock held */
4408 static gboolean
4409 obj_message_func (GDBusConnection *connection,
4410                   ExportedObject  *eo,
4411                   GDBusMessage    *message)
4412 {
4413   const gchar *interface_name;
4414   const gchar *member;
4415   const gchar *signature;
4416   gboolean handled;
4417
4418   handled = FALSE;
4419
4420   interface_name = g_dbus_message_get_interface (message);
4421   member = g_dbus_message_get_member (message);
4422   signature = g_dbus_message_get_signature (message);
4423
4424   /* see if we have an interface for handling this call */
4425   if (interface_name != NULL)
4426     {
4427       ExportedInterface *ei;
4428       ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4429       if (ei != NULL)
4430         {
4431           /* we do - invoke the handler in idle in the right thread */
4432
4433           /* handle no vtable or handler being present */
4434           if (ei->vtable == NULL || ei->vtable->method_call == NULL)
4435             goto out;
4436
4437           handled = validate_and_maybe_schedule_method_call (connection,
4438                                                              message,
4439                                                              ei->id,
4440                                                              0,
4441                                                              ei->interface_info,
4442                                                              ei->vtable,
4443                                                              ei->context,
4444                                                              ei->user_data);
4445           goto out;
4446         }
4447     }
4448
4449   if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4450       g_strcmp0 (member, "Introspect") == 0 &&
4451       g_strcmp0 (signature, "") == 0)
4452     {
4453       handled = handle_introspect (connection, eo, message);
4454       goto out;
4455     }
4456   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4457            g_strcmp0 (member, "Get") == 0 &&
4458            g_strcmp0 (signature, "ss") == 0)
4459     {
4460       handled = handle_getset_property (connection, eo, message, TRUE);
4461       goto out;
4462     }
4463   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4464            g_strcmp0 (member, "Set") == 0 &&
4465            g_strcmp0 (signature, "ssv") == 0)
4466     {
4467       handled = handle_getset_property (connection, eo, message, FALSE);
4468       goto out;
4469     }
4470   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4471            g_strcmp0 (member, "GetAll") == 0 &&
4472            g_strcmp0 (signature, "s") == 0)
4473     {
4474       handled = handle_get_all_properties (connection, eo, message);
4475       goto out;
4476     }
4477
4478  out:
4479   return handled;
4480 }
4481
4482 /**
4483  * g_dbus_connection_register_object:
4484  * @connection: A #GDBusConnection.
4485  * @object_path: The object path to register at.
4486  * @interface_info: Introspection data for the interface.
4487  * @vtable: A #GDBusInterfaceVTable to call into or %NULL.
4488  * @user_data: Data to pass to functions in @vtable.
4489  * @user_data_free_func: Function to call when the object path is unregistered.
4490  * @error: Return location for error or %NULL.
4491  *
4492  * Registers callbacks for exported objects at @object_path with the
4493  * D-Bus interface that is described in @interface_info.
4494  *
4495  * Calls to functions in @vtable (and @user_data_free_func) will
4496  * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
4497  * loop</link> of the thread you are calling this method from.
4498  *
4499  * Note that all #GVariant values passed to functions in @vtable will match
4500  * the signature given in @interface_info - if a remote caller passes
4501  * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
4502  * is returned to the remote caller.
4503  *
4504  * Additionally, if the remote caller attempts to invoke methods or
4505  * access properties not mentioned in @interface_info the
4506  * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
4507  * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
4508  * are returned to the caller.
4509  *
4510  * It is considered a programming error if the
4511  * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
4512  * #GVariant of incorrect type.
4513  *
4514  * If an existing callback is already registered at @object_path and
4515  * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
4516  *
4517  * GDBus automatically implements the standard D-Bus interfaces
4518  * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
4519  * and org.freedesktop.Peer, so you don't have to implement those for
4520  * the objects you export. You <emphasis>can</emphasis> implement
4521  * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
4522  * and setting of properties asynchronously.
4523  *
4524  * Note that the reference count on @interface_info will be
4525  * incremented by 1 (unless allocated statically, e.g. if the
4526  * reference count is -1, see g_dbus_interface_info_ref()) for as long
4527  * as the object is exported. Also note that @vtable will be copied.
4528  *
4529  * See <xref linkend="gdbus-server"/> for an example of how to use this method.
4530  *
4531  * Returns: 0 if @error is set, otherwise a registration id (never 0)
4532  * that can be used with g_dbus_connection_unregister_object() .
4533  *
4534  * Since: 2.26
4535  */
4536 guint
4537 g_dbus_connection_register_object (GDBusConnection            *connection,
4538                                    const gchar                *object_path,
4539                                    GDBusInterfaceInfo         *interface_info,
4540                                    const GDBusInterfaceVTable *vtable,
4541                                    gpointer                    user_data,
4542                                    GDestroyNotify              user_data_free_func,
4543                                    GError                    **error)
4544 {
4545   ExportedObject *eo;
4546   ExportedInterface *ei;
4547   guint ret;
4548
4549   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4550   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4551   g_return_val_if_fail (interface_info != NULL, 0);
4552   g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
4553   g_return_val_if_fail (error == NULL || *error == NULL, 0);
4554
4555   ret = 0;
4556
4557   CONNECTION_LOCK (connection);
4558
4559   eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
4560   if (eo == NULL)
4561     {
4562       eo = g_new0 (ExportedObject, 1);
4563       eo->object_path = g_strdup (object_path);
4564       eo->connection = connection;
4565       eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
4566                                                      g_str_equal,
4567                                                      NULL,
4568                                                      (GDestroyNotify) exported_interface_free);
4569       g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
4570     }
4571
4572   ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
4573   if (ei != NULL)
4574     {
4575       g_set_error (error,
4576                    G_IO_ERROR,
4577                    G_IO_ERROR_EXISTS,
4578                    _("An object is already exported for the interface %s at %s"),
4579                    interface_info->name,
4580                    object_path);
4581       goto out;
4582     }
4583
4584   ei = g_new0 (ExportedInterface, 1);
4585   ei->id = _global_registration_id++; /* TODO: overflow etc. */
4586   ei->eo = eo;
4587   ei->user_data = user_data;
4588   ei->user_data_free_func = user_data_free_func;
4589   ei->vtable = _g_dbus_interface_vtable_copy (vtable);
4590   ei->interface_info = g_dbus_interface_info_ref (interface_info);
4591   ei->interface_name = g_strdup (interface_info->name);
4592   ei->context = g_main_context_get_thread_default ();
4593   if (ei->context != NULL)
4594     g_main_context_ref (ei->context);
4595
4596   g_hash_table_insert (eo->map_if_name_to_ei,
4597                        (gpointer) ei->interface_name,
4598                        ei);
4599   g_hash_table_insert (connection->map_id_to_ei,
4600                        GUINT_TO_POINTER (ei->id),
4601                        ei);
4602
4603   ret = ei->id;
4604
4605  out:
4606   CONNECTION_UNLOCK (connection);
4607
4608   return ret;
4609 }
4610
4611 /**
4612  * g_dbus_connection_unregister_object:
4613  * @connection: A #GDBusConnection.
4614  * @registration_id: A registration id obtained from g_dbus_connection_register_object().
4615  *
4616  * Unregisters an object.
4617  *
4618  * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
4619  *
4620  * Since: 2.26
4621  */
4622 gboolean
4623 g_dbus_connection_unregister_object (GDBusConnection *connection,
4624                                      guint            registration_id)
4625 {
4626   ExportedInterface *ei;
4627   ExportedObject *eo;
4628   gboolean ret;
4629
4630   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4631
4632   ret = FALSE;
4633
4634   CONNECTION_LOCK (connection);
4635
4636   ei = g_hash_table_lookup (connection->map_id_to_ei,
4637                             GUINT_TO_POINTER (registration_id));
4638   if (ei == NULL)
4639     goto out;
4640
4641   eo = ei->eo;
4642
4643   g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
4644   g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
4645   /* unregister object path if we have no more exported interfaces */
4646   if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
4647     g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
4648                                          eo->object_path));
4649
4650   ret = TRUE;
4651
4652  out:
4653   CONNECTION_UNLOCK (connection);
4654
4655   return ret;
4656 }
4657
4658 /* ---------------------------------------------------------------------------------------------------- */
4659
4660 /**
4661  * g_dbus_connection_emit_signal:
4662  * @connection: A #GDBusConnection.
4663  * @destination_bus_name: The unique bus name for the destination for the signal or %NULL to emit to all listeners.
4664  * @object_path: Path of remote object.
4665  * @interface_name: D-Bus interface to emit a signal on.
4666  * @signal_name: The name of the signal to emit.
4667  * @parameters: A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
4668  * @error: Return location for error or %NULL.
4669  *
4670  * Emits a signal.
4671  *
4672  * If the parameters GVariant is floating, it is consumed.
4673  *
4674  * This can only fail if @parameters is not compatible with the D-Bus protocol.
4675  *
4676  * Returns: %TRUE unless @error is set.
4677  *
4678  * Since: 2.26
4679  */
4680 gboolean
4681 g_dbus_connection_emit_signal (GDBusConnection  *connection,
4682                                const gchar      *destination_bus_name,
4683                                const gchar      *object_path,
4684                                const gchar      *interface_name,
4685                                const gchar      *signal_name,
4686                                GVariant         *parameters,
4687                                GError          **error)
4688 {
4689   GDBusMessage *message;
4690   gboolean ret;
4691
4692   message = NULL;
4693   ret = FALSE;
4694
4695   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4696   g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
4697   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
4698   g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
4699   g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
4700   g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
4701
4702   if (G_UNLIKELY (_g_dbus_debug_emission ()))
4703     {
4704       _g_dbus_debug_print_lock ();
4705       g_print ("========================================================================\n"
4706                "GDBus-debug:Emission:\n"
4707                " >>>> SIGNAL EMISSION %s.%s()\n"
4708                "      on object %s\n"
4709                "      destination %s\n",
4710                interface_name, signal_name,
4711                object_path,
4712                destination_bus_name != NULL ? destination_bus_name : "(none)");
4713       _g_dbus_debug_print_unlock ();
4714     }
4715
4716   message = g_dbus_message_new_signal (object_path,
4717                                        interface_name,
4718                                        signal_name);
4719
4720   if (destination_bus_name != NULL)
4721     g_dbus_message_set_header (message,
4722                                G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
4723                                g_variant_new_string (destination_bus_name));
4724
4725   if (parameters != NULL)
4726     g_dbus_message_set_body (message, parameters);
4727
4728   ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
4729   g_object_unref (message);
4730
4731   return ret;
4732 }
4733
4734 static void
4735 add_call_flags (GDBusMessage           *message,
4736                          GDBusCallFlags  flags)
4737 {
4738   if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
4739     g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
4740 }
4741
4742 static GVariant *
4743 decode_method_reply (GDBusMessage        *reply,
4744                      const gchar         *method_name,
4745                      const GVariantType  *reply_type,
4746                      GError             **error)
4747 {
4748   GVariant *result;
4749
4750   result = NULL;
4751   switch (g_dbus_message_get_message_type (reply))
4752     {
4753     case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
4754       result = g_dbus_message_get_body (reply);
4755       if (result == NULL)
4756         {
4757           result = g_variant_new ("()");
4758           g_variant_ref_sink (result);
4759         }
4760       else
4761         {
4762           g_variant_ref (result);
4763         }
4764
4765       if (!g_variant_is_of_type (result, reply_type))
4766         {
4767           gchar *type_string = g_variant_type_dup_string (reply_type);
4768
4769           g_set_error (error,
4770                        G_IO_ERROR,
4771                        G_IO_ERROR_INVALID_ARGUMENT,
4772                        _("Method `%s' returned type `%s', but expected `%s'"),
4773                        method_name, g_variant_get_type_string (result), type_string);
4774
4775           g_variant_unref (result);
4776           g_free (type_string);
4777           result = NULL;
4778         }
4779       break;
4780
4781     case G_DBUS_MESSAGE_TYPE_ERROR:
4782       g_dbus_message_to_gerror (reply, error);
4783       break;
4784
4785     default:
4786       g_assert_not_reached ();
4787       break;
4788     }
4789
4790   return result;
4791 }
4792
4793
4794 typedef struct
4795 {
4796   GSimpleAsyncResult *simple;
4797   GVariantType *reply_type;
4798   gchar *method_name; /* for error message */
4799   guint32 serial;
4800 } CallState;
4801
4802 static void
4803 g_dbus_connection_call_done (GObject      *source,
4804                              GAsyncResult *result,
4805                              gpointer      user_data)
4806 {
4807   GDBusConnection *connection = G_DBUS_CONNECTION (source);
4808   CallState *state = user_data;
4809   GError *error;
4810   GDBusMessage *reply;
4811   GVariant *value;
4812
4813   error = NULL;
4814   reply = g_dbus_connection_send_message_with_reply_finish (connection,
4815                                                             result,
4816                                                             &error);
4817
4818   if (G_UNLIKELY (_g_dbus_debug_call ()))
4819     {
4820       _g_dbus_debug_print_lock ();
4821       g_print ("========================================================================\n"
4822                "GDBus-debug:Call:\n"
4823                " <<<< ASYNC COMPLETE %s() (serial %d)\n"
4824                "      ",
4825                state->method_name,
4826                state->serial);
4827       if (reply != NULL)
4828         {
4829           g_print ("SUCCESS\n");
4830         }
4831       else
4832         {
4833           g_print ("FAILED: %s\n",
4834                    error->message);
4835         }
4836       _g_dbus_debug_print_unlock ();
4837     }
4838
4839
4840   if (reply != NULL)
4841     {
4842       value = decode_method_reply (reply, state->method_name,
4843                                    state->reply_type, &error);
4844       g_object_unref (reply);
4845     }
4846   else
4847     value = NULL;
4848
4849   if (value == NULL)
4850     {
4851       g_simple_async_result_set_from_error (state->simple, error);
4852       g_error_free (error);
4853     }
4854   else
4855     g_simple_async_result_set_op_res_gpointer (state->simple, value,
4856                                                (GDestroyNotify) g_variant_unref);
4857
4858   g_simple_async_result_complete (state->simple);
4859   g_variant_type_free (state->reply_type);
4860   g_object_unref (state->simple);
4861   g_free (state->method_name);
4862
4863   g_slice_free (CallState, state);
4864 }
4865
4866 /**
4867  * g_dbus_connection_call:
4868  * @connection: A #GDBusConnection.
4869  * @bus_name: A unique or well-known bus name or %NULL if @connection is not a message bus connection.
4870  * @object_path: Path of remote object.
4871  * @interface_name: D-Bus interface to invoke method on.
4872  * @method_name: The name of the method to invoke.
4873  * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4874  * @reply_type: The expected type of the reply, or %NULL.
4875  * @flags: Flags from the #GDBusCallFlags enumeration.
4876  * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4877  * @cancellable: A #GCancellable or %NULL.
4878  * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
4879  * care about the result of the method invocation.
4880  * @user_data: The data to pass to @callback.
4881  *
4882  * Asynchronously invokes the @method_name method on the
4883  * @interface_name D-Bus interface on the remote object at
4884  * @object_path owned by @bus_name.
4885  *
4886  * If @connection is closed then the operation will fail with
4887  * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
4888  * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
4889  * not compatible with the D-Bus protocol, the operation fails with
4890  * %G_IO_ERROR_INVALID_ARGUMENT.
4891  *
4892  * If @reply_type is non-%NULL then the reply will be checked for having this type and an
4893  * error will be raised if it does not match.  Said another way, if you give a @reply_type
4894  * then any non-%NULL return value will be of this type.
4895  *
4896  * If the @parameters #GVariant is floating, it is consumed. This allows
4897  * convenient 'inline' use of g_variant_new(), e.g.:
4898  * |[
4899  *  g_dbus_connection_call (connection,
4900  *                          "org.freedesktop.StringThings",
4901  *                          "/org/freedesktop/StringThings",
4902  *                          "org.freedesktop.StringThings",
4903  *                          "TwoStrings",
4904  *                          g_variant_new ("(ss)",
4905  *                                         "Thing One",
4906  *                                         "Thing Two"),
4907  *                          NULL,
4908  *                          G_DBUS_CALL_FLAGS_NONE,
4909  *                          -1,
4910  *                          NULL,
4911  *                          (GAsyncReadyCallback) two_strings_done,
4912  *                          NULL);
4913  * ]|
4914  *
4915  * This is an asynchronous method. When the operation is finished, @callback will be invoked
4916  * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
4917  * of the thread you are calling this method from. You can then call
4918  * g_dbus_connection_call_finish() to get the result of the operation.
4919  * See g_dbus_connection_call_sync() for the synchronous version of this
4920  * function.
4921  *
4922  * Since: 2.26
4923  */
4924 void
4925 g_dbus_connection_call (GDBusConnection        *connection,
4926                         const gchar            *bus_name,
4927                         const gchar            *object_path,
4928                         const gchar            *interface_name,
4929                         const gchar            *method_name,
4930                         GVariant               *parameters,
4931                         const GVariantType     *reply_type,
4932                         GDBusCallFlags          flags,
4933                         gint                    timeout_msec,
4934                         GCancellable           *cancellable,
4935                         GAsyncReadyCallback     callback,
4936                         gpointer                user_data)
4937 {
4938   GDBusMessage *message;
4939   CallState *state;
4940
4941   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4942   g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
4943   g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
4944   g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
4945   g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
4946   g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
4947   g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
4948
4949   state = g_slice_new (CallState);
4950   state->simple = g_simple_async_result_new (G_OBJECT (connection),
4951                                              callback, user_data,
4952                                              g_dbus_connection_call);
4953   state->method_name = g_strjoin (".", interface_name, method_name, NULL);
4954
4955   if (reply_type == NULL)
4956     reply_type = G_VARIANT_TYPE_ANY;
4957
4958   state->reply_type = g_variant_type_copy (reply_type);
4959
4960   message = g_dbus_message_new_method_call (bus_name,
4961                                             object_path,
4962                                             interface_name,
4963                                             method_name);
4964   add_call_flags (message, flags);
4965   if (parameters != NULL)
4966     g_dbus_message_set_body (message, parameters);
4967
4968   g_dbus_connection_send_message_with_reply (connection,
4969                                              message,
4970                                              G_DBUS_SEND_MESSAGE_FLAGS_NONE,
4971                                              timeout_msec,
4972                                              &state->serial,
4973                                              cancellable,
4974                                              g_dbus_connection_call_done,
4975                                              state);
4976
4977   if (G_UNLIKELY (_g_dbus_debug_call ()))
4978     {
4979       _g_dbus_debug_print_lock ();
4980       g_print ("========================================================================\n"
4981                "GDBus-debug:Call:\n"
4982                " >>>> ASYNC %s.%s()\n"
4983                "      on object %s\n"
4984                "      owned by name %s (serial %d)\n",
4985                interface_name,
4986                method_name,
4987                object_path,
4988                bus_name != NULL ? bus_name : "(none)",
4989                state->serial);
4990       _g_dbus_debug_print_unlock ();
4991     }
4992
4993   if (message != NULL)
4994     g_object_unref (message);
4995 }
4996
4997 /**
4998  * g_dbus_connection_call_finish:
4999  * @connection: A #GDBusConnection.
5000  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
5001  * @error: Return location for error or %NULL.
5002  *
5003  * Finishes an operation started with g_dbus_connection_call().
5004  *
5005  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5006  * return values. Free with g_variant_unref().
5007  *
5008  * Since: 2.26
5009  */
5010 GVariant *
5011 g_dbus_connection_call_finish (GDBusConnection  *connection,
5012                                GAsyncResult     *res,
5013                                GError          **error)
5014 {
5015   GSimpleAsyncResult *simple;
5016
5017   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5018   g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
5019                                                         g_dbus_connection_call), NULL);
5020   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5021
5022   simple = G_SIMPLE_ASYNC_RESULT (res);
5023
5024   if (g_simple_async_result_propagate_error (simple, error))
5025     return NULL;
5026
5027   return g_variant_ref (g_simple_async_result_get_op_res_gpointer (simple));
5028 }
5029
5030 /* ---------------------------------------------------------------------------------------------------- */
5031
5032 /**
5033  * g_dbus_connection_call_sync:
5034  * @connection: A #GDBusConnection.
5035  * @bus_name: A unique or well-known bus name.
5036  * @object_path: Path of remote object.
5037  * @interface_name: D-Bus interface to invoke method on.
5038  * @method_name: The name of the method to invoke.
5039  * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
5040  * @reply_type: The expected type of the reply, or %NULL.
5041  * @flags: Flags from the #GDBusCallFlags enumeration.
5042  * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
5043  * @cancellable: A #GCancellable or %NULL.
5044  * @error: Return location for error or %NULL.
5045  *
5046  * Synchronously invokes the @method_name method on the
5047  * @interface_name D-Bus interface on the remote object at
5048  * @object_path owned by @bus_name.
5049  *
5050  * If @connection is closed then the operation will fail with
5051  * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
5052  * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
5053  * contains a value not compatible with the D-Bus protocol, the operation
5054  * fails with %G_IO_ERROR_INVALID_ARGUMENT.
5055
5056  * If @reply_type is non-%NULL then the reply will be checked for having
5057  * this type and an error will be raised if it does not match.  Said
5058  * another way, if you give a @reply_type then any non-%NULL return
5059  * value will be of this type.
5060  *
5061  * If the @parameters #GVariant is floating, it is consumed.
5062  * This allows convenient 'inline' use of g_variant_new(), e.g.:
5063  * |[
5064  *  g_dbus_connection_call_sync (connection,
5065  *                               "org.freedesktop.StringThings",
5066  *                               "/org/freedesktop/StringThings",
5067  *                               "org.freedesktop.StringThings",
5068  *                               "TwoStrings",
5069  *                               g_variant_new ("(ss)",
5070  *                                              "Thing One",
5071  *                                              "Thing Two"),
5072  *                               NULL,
5073  *                               G_DBUS_CALL_FLAGS_NONE,
5074  *                               -1,
5075  *                               NULL,
5076  *                               &amp;error);
5077  * ]|
5078  *
5079  * The calling thread is blocked until a reply is received. See
5080  * g_dbus_connection_call() for the asynchronous version of
5081  * this method.
5082  *
5083  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5084  * return values. Free with g_variant_unref().
5085  *
5086  * Since: 2.26
5087  */
5088 GVariant *
5089 g_dbus_connection_call_sync (GDBusConnection         *connection,
5090                              const gchar             *bus_name,
5091                              const gchar             *object_path,
5092                              const gchar             *interface_name,
5093                              const gchar             *method_name,
5094                              GVariant                *parameters,
5095                              const GVariantType      *reply_type,
5096                              GDBusCallFlags           flags,
5097                              gint                     timeout_msec,
5098                              GCancellable            *cancellable,
5099                              GError                 **error)
5100 {
5101   GDBusMessage *message;
5102   GDBusMessage *reply;
5103   GVariant *result;
5104   GError *local_error;
5105
5106   message = NULL;
5107   reply = NULL;
5108   result = NULL;
5109
5110   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5111   g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5112   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5113   g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5114   g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5115   g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5116   g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5117
5118   if (reply_type == NULL)
5119     reply_type = G_VARIANT_TYPE_ANY;
5120
5121   message = g_dbus_message_new_method_call (bus_name,
5122                                             object_path,
5123                                             interface_name,
5124                                             method_name);
5125   add_call_flags (message, flags);
5126   if (parameters != NULL)
5127     g_dbus_message_set_body (message, parameters);
5128
5129   if (G_UNLIKELY (_g_dbus_debug_call ()))
5130     {
5131       _g_dbus_debug_print_lock ();
5132       g_print ("========================================================================\n"
5133                "GDBus-debug:Call:\n"
5134                " >>>> SYNC %s.%s()\n"
5135                "      on object %s\n"
5136                "      owned by name %s\n",
5137                interface_name,
5138                method_name,
5139                object_path,
5140                bus_name != NULL ? bus_name : "(none)");
5141       _g_dbus_debug_print_unlock ();
5142     }
5143
5144   local_error = NULL;
5145   reply = g_dbus_connection_send_message_with_reply_sync (connection,
5146                                                           message,
5147                                                           G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5148                                                           timeout_msec,
5149                                                           NULL, /* volatile guint32 *out_serial */
5150                                                           cancellable,
5151                                                           &local_error);
5152
5153   if (G_UNLIKELY (_g_dbus_debug_call ()))
5154     {
5155       _g_dbus_debug_print_lock ();
5156       g_print ("========================================================================\n"
5157                "GDBus-debug:Call:\n"
5158                " <<<< SYNC COMPLETE %s.%s()\n"
5159                "      ",
5160                interface_name,
5161                method_name);
5162       if (reply != NULL)
5163         {
5164           g_print ("SUCCESS\n");
5165         }
5166       else
5167         {
5168           g_print ("FAILED: %s\n",
5169                    local_error->message);
5170         }
5171       _g_dbus_debug_print_unlock ();
5172     }
5173
5174   if (reply == NULL)
5175     {
5176       if (error != NULL)
5177         *error = local_error;
5178       else
5179         g_error_free (local_error);
5180       goto out;
5181     }
5182
5183   result = decode_method_reply (reply, method_name, reply_type, error);
5184
5185  out:
5186   if (message != NULL)
5187     g_object_unref (message);
5188   if (reply != NULL)
5189     g_object_unref (reply);
5190
5191   return result;
5192 }
5193
5194 /* ---------------------------------------------------------------------------------------------------- */
5195
5196 struct ExportedSubtree
5197 {
5198   guint                     id;
5199   gchar                    *object_path;
5200   GDBusConnection          *connection;
5201   GDBusSubtreeVTable       *vtable;
5202   GDBusSubtreeFlags         flags;
5203
5204   GMainContext             *context;
5205   gpointer                  user_data;
5206   GDestroyNotify            user_data_free_func;
5207 };
5208
5209 static void
5210 exported_subtree_free (ExportedSubtree *es)
5211 {
5212   if (es->user_data_free_func != NULL)
5213     /* TODO: push to thread-default mainloop */
5214     es->user_data_free_func (es->user_data);
5215
5216   if (es->context != NULL)
5217     g_main_context_unref (es->context);
5218
5219   _g_dbus_subtree_vtable_free (es->vtable);
5220   g_free (es->object_path);
5221   g_free (es);
5222 }
5223
5224 /* called without lock held */
5225 static gboolean
5226 handle_subtree_introspect (GDBusConnection *connection,
5227                            ExportedSubtree *es,
5228                            GDBusMessage    *message)
5229 {
5230   GString *s;
5231   gboolean handled;
5232   GDBusMessage *reply;
5233   gchar **children;
5234   gboolean is_root;
5235   const gchar *sender;
5236   const gchar *requested_object_path;
5237   const gchar *requested_node;
5238   GDBusInterfaceInfo **interfaces;
5239   guint n;
5240   gchar **subnode_paths;
5241
5242   handled = FALSE;
5243
5244   requested_object_path = g_dbus_message_get_path (message);
5245   sender = g_dbus_message_get_sender (message);
5246   is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5247
5248   s = g_string_new (NULL);
5249   introspect_append_header (s);
5250
5251   /* Strictly we don't need the children in dynamic mode, but we avoid the
5252    * conditionals to preserve code clarity
5253    */
5254   children = es->vtable->enumerate (es->connection,
5255                                     sender,
5256                                     es->object_path,
5257                                     es->user_data);
5258
5259   if (!is_root)
5260     {
5261       requested_node = strrchr (requested_object_path, '/') + 1;
5262
5263       /* Assert existence of object if we are not dynamic */
5264       if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
5265           !_g_strv_has_string ((const gchar * const *) children, requested_node))
5266         goto out;
5267     }
5268   else
5269     {
5270       requested_node = NULL;
5271     }
5272
5273   interfaces = es->vtable->introspect (es->connection,
5274                                        sender,
5275                                        es->object_path,
5276                                        requested_node,
5277                                        es->user_data);
5278   if (interfaces != NULL)
5279     {
5280       introspect_append_standard_interfaces (s);
5281
5282       for (n = 0; interfaces[n] != NULL; n++)
5283         {
5284           g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
5285           g_dbus_interface_info_unref (interfaces[n]);
5286         }
5287       g_free (interfaces);
5288     }
5289
5290   /* then include <node> entries from the Subtree for the root */
5291   if (is_root)
5292     {
5293       for (n = 0; children != NULL && children[n] != NULL; n++)
5294         g_string_append_printf (s, "  <node name=\"%s\"/>\n", children[n]);
5295     }
5296
5297   /* finally include nodes registered below us */
5298   subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
5299   for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
5300     g_string_append_printf (s, "  <node name=\"%s\"/>\n", subnode_paths[n]);
5301   g_strfreev (subnode_paths);
5302
5303   g_string_append (s, "</node>\n");
5304
5305   reply = g_dbus_message_new_method_reply (message);
5306   g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5307   g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5308   g_object_unref (reply);
5309
5310   handled = TRUE;
5311
5312  out:
5313   g_string_free (s, TRUE);
5314   g_strfreev (children);
5315   return handled;
5316 }
5317
5318 /* called without lock held */
5319 static gboolean
5320 handle_subtree_method_invocation (GDBusConnection *connection,
5321                                   ExportedSubtree *es,
5322                                   GDBusMessage    *message)
5323 {
5324   gboolean handled;
5325   const gchar *sender;
5326   const gchar *interface_name;
5327   const gchar *member;
5328   const gchar *signature;
5329   const gchar *requested_object_path;
5330   const gchar *requested_node;
5331   gboolean is_root;
5332   GDBusInterfaceInfo *interface_info;
5333   const GDBusInterfaceVTable *interface_vtable;
5334   gpointer interface_user_data;
5335   guint n;
5336   GDBusInterfaceInfo **interfaces;
5337   gboolean is_property_get;
5338   gboolean is_property_set;
5339   gboolean is_property_get_all;
5340
5341   handled = FALSE;
5342   interfaces = NULL;
5343
5344   requested_object_path = g_dbus_message_get_path (message);
5345   sender = g_dbus_message_get_sender (message);
5346   interface_name = g_dbus_message_get_interface (message);
5347   member = g_dbus_message_get_member (message);
5348   signature = g_dbus_message_get_signature (message);
5349   is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5350
5351   is_property_get = FALSE;
5352   is_property_set = FALSE;
5353   is_property_get_all = FALSE;
5354   if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
5355     {
5356       if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
5357         is_property_get = TRUE;
5358       else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
5359         is_property_set = TRUE;
5360       else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
5361         is_property_get_all = TRUE;
5362     }
5363
5364   if (!is_root)
5365     {
5366       requested_node = strrchr (requested_object_path, '/') + 1;
5367
5368       if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
5369         {
5370           /* We don't want to dispatch to unenumerated
5371            * nodes, so ensure that the child exists.
5372            */
5373           gchar **children;
5374           gboolean exists;
5375
5376           children = es->vtable->enumerate (es->connection,
5377                                             sender,
5378                                             es->object_path,
5379                                             es->user_data);
5380
5381           exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
5382           g_strfreev (children);
5383
5384           if (!exists)
5385             goto out;
5386         }
5387     }
5388   else
5389     {
5390       requested_node = NULL;
5391     }
5392
5393   /* get introspection data for the node */
5394   interfaces = es->vtable->introspect (es->connection,
5395                                        sender,
5396                                        requested_object_path,
5397                                        requested_node,
5398                                        es->user_data);
5399
5400   if (interfaces == NULL)
5401     goto out;
5402
5403   interface_info = NULL;
5404   for (n = 0; interfaces[n] != NULL; n++)
5405     {
5406       if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
5407         interface_info = interfaces[n];
5408     }
5409
5410   /* dispatch the call if the user wants to handle it */
5411   if (interface_info != NULL)
5412     {
5413       /* figure out where to dispatch the method call */
5414       interface_user_data = NULL;
5415       interface_vtable = es->vtable->dispatch (es->connection,
5416                                                sender,
5417                                                es->object_path,
5418                                                interface_name,
5419                                                requested_node,
5420                                                &interface_user_data,
5421                                                es->user_data);
5422       if (interface_vtable == NULL)
5423         goto out;
5424
5425       CONNECTION_LOCK (connection);
5426       handled = validate_and_maybe_schedule_method_call (es->connection,
5427                                                          message,
5428                                                          0,
5429                                                          es->id,
5430                                                          interface_info,
5431                                                          interface_vtable,
5432                                                          es->context,
5433                                                          interface_user_data);
5434       CONNECTION_UNLOCK (connection);
5435     }
5436   /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
5437   else if (is_property_get || is_property_set || is_property_get_all)
5438     {
5439       if (is_property_get)
5440         g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
5441       else if (is_property_set)
5442         g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
5443       else if (is_property_get_all)
5444         g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
5445       else
5446         g_assert_not_reached ();
5447
5448       /* see if the object supports this interface at all */
5449       for (n = 0; interfaces[n] != NULL; n++)
5450         {
5451           if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
5452             interface_info = interfaces[n];
5453         }
5454
5455       /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
5456        * claims it won't support the interface
5457        */
5458       if (interface_info == NULL)
5459         {
5460           GDBusMessage *reply;
5461           reply = g_dbus_message_new_method_error (message,
5462                                                    "org.freedesktop.DBus.Error.InvalidArgs",
5463                                                    _("No such interface `%s'"),
5464                                                    interface_name);
5465           g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5466           g_object_unref (reply);
5467           handled = TRUE;
5468           goto out;
5469         }
5470
5471       /* figure out where to dispatch the property get/set/getall calls */
5472       interface_user_data = NULL;
5473       interface_vtable = es->vtable->dispatch (es->connection,
5474                                                sender,
5475                                                es->object_path,
5476                                                interface_name,
5477                                                requested_node,
5478                                                &interface_user_data,
5479                                                es->user_data);
5480       if (interface_vtable == NULL)
5481         {
5482           g_warning ("The subtree introspection function indicates that '%s' "
5483                      "is a valid interface name, but calling the dispatch "
5484                      "function on that interface gave us NULL", interface_name);
5485           goto out;
5486         }
5487
5488       if (is_property_get || is_property_set)
5489         {
5490           CONNECTION_LOCK (connection);
5491           handled = validate_and_maybe_schedule_property_getset (es->connection,
5492                                                                  message,
5493                                                                  0,
5494                                                                  es->id,
5495                                                                  is_property_get,
5496                                                                  interface_info,
5497                                                                  interface_vtable,
5498                                                                  es->context,
5499                                                                  interface_user_data);
5500           CONNECTION_UNLOCK (connection);
5501         }
5502       else if (is_property_get_all)
5503         {
5504           CONNECTION_LOCK (connection);
5505           handled = validate_and_maybe_schedule_property_get_all (es->connection,
5506                                                                   message,
5507                                                                   0,
5508                                                                   es->id,
5509                                                                   interface_info,
5510                                                                   interface_vtable,
5511                                                                   es->context,
5512                                                                   interface_user_data);
5513           CONNECTION_UNLOCK (connection);
5514         }
5515     }
5516
5517  out:
5518   if (interfaces != NULL)
5519     {
5520       for (n = 0; interfaces[n] != NULL; n++)
5521         g_dbus_interface_info_unref (interfaces[n]);
5522       g_free (interfaces);
5523     }
5524
5525   return handled;
5526 }
5527
5528 typedef struct
5529 {
5530   GDBusMessage *message;
5531   ExportedSubtree *es;
5532 } SubtreeDeferredData;
5533
5534 static void
5535 subtree_deferred_data_free (SubtreeDeferredData *data)
5536 {
5537   g_object_unref (data->message);
5538   g_free (data);
5539 }
5540
5541 /* called without lock held in the thread where the caller registered the subtree */
5542 static gboolean
5543 process_subtree_vtable_message_in_idle_cb (gpointer _data)
5544 {
5545   SubtreeDeferredData *data = _data;
5546   gboolean handled;
5547
5548   handled = FALSE;
5549
5550   if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
5551       g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
5552       g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
5553     handled = handle_subtree_introspect (data->es->connection,
5554                                          data->es,
5555                                          data->message);
5556   else
5557     handled = handle_subtree_method_invocation (data->es->connection,
5558                                                 data->es,
5559                                                 data->message);
5560
5561   if (!handled)
5562     {
5563       CONNECTION_LOCK (data->es->connection);
5564       handled = handle_generic_unlocked (data->es->connection, data->message);
5565       CONNECTION_UNLOCK (data->es->connection);
5566     }
5567
5568   /* if we couldn't handle the request, just bail with the UnknownMethod error */
5569   if (!handled)
5570     {
5571       GDBusMessage *reply;
5572       reply = g_dbus_message_new_method_error (data->message,
5573                                                "org.freedesktop.DBus.Error.UnknownMethod",
5574                                                _("Method `%s' on interface `%s' with signature `%s' does not exist"),
5575                                                g_dbus_message_get_member (data->message),
5576                                                g_dbus_message_get_interface (data->message),
5577                                                g_dbus_message_get_signature (data->message));
5578       g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5579       g_object_unref (reply);
5580     }
5581
5582   return FALSE;
5583 }
5584
5585 /* called in message handler thread with lock held */
5586 static gboolean
5587 subtree_message_func (GDBusConnection *connection,
5588                       ExportedSubtree *es,
5589                       GDBusMessage    *message)
5590 {
5591   GSource *idle_source;
5592   SubtreeDeferredData *data;
5593
5594   data = g_new0 (SubtreeDeferredData, 1);
5595   data->message = g_object_ref (message);
5596   data->es = es;
5597
5598   /* defer this call to an idle handler in the right thread */
5599   idle_source = g_idle_source_new ();
5600   g_source_set_priority (idle_source, G_PRIORITY_HIGH);
5601   g_source_set_callback (idle_source,
5602                          process_subtree_vtable_message_in_idle_cb,
5603                          data,
5604                          (GDestroyNotify) subtree_deferred_data_free);
5605   g_source_attach (idle_source, es->context);
5606   g_source_unref (idle_source);
5607
5608   /* since we own the entire subtree, handlers for objects not in the subtree have been
5609    * tried already by libdbus-1 - so we just need to ensure that we're always going
5610    * to reply to the message
5611    */
5612   return TRUE;
5613 }
5614
5615 /**
5616  * g_dbus_connection_register_subtree:
5617  * @connection: A #GDBusConnection.
5618  * @object_path: The object path to register the subtree at.
5619  * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
5620  * @flags: Flags used to fine tune the behavior of the subtree.
5621  * @user_data: Data to pass to functions in @vtable.
5622  * @user_data_free_func: Function to call when the subtree is unregistered.
5623  * @error: Return location for error or %NULL.
5624  *
5625  * Registers a whole subtree of <quote>dynamic</quote> objects.
5626  *
5627  * The @enumerate and @introspection functions in @vtable are used to
5628  * convey, to remote callers, what nodes exist in the subtree rooted
5629  * by @object_path.
5630  *
5631  * When handling remote calls into any node in the subtree, first the
5632  * @enumerate function is used to check if the node exists. If the node exists
5633  * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
5634  * the @introspection function is used to check if the node supports the
5635  * requested method. If so, the @dispatch function is used to determine
5636  * where to dispatch the call. The collected #GDBusInterfaceVTable and
5637  * #gpointer will be used to call into the interface vtable for processing
5638  * the request.
5639  *
5640  * All calls into user-provided code will be invoked in the <link
5641  * linkend="g-main-context-push-thread-default">thread-default main
5642  * loop</link> of the thread you are calling this method from.
5643  *
5644  * If an existing subtree is already registered at @object_path or
5645  * then @error is set to #G_IO_ERROR_EXISTS.
5646  *
5647  * Note that it is valid to register regular objects (using
5648  * g_dbus_connection_register_object()) in a subtree registered with
5649  * g_dbus_connection_register_subtree() - if so, the subtree handler
5650  * is tried as the last resort. One way to think about a subtree
5651  * handler is to consider it a <quote>fallback handler</quote>
5652  * for object paths not registered via g_dbus_connection_register_object()
5653  * or other bindings.
5654  *
5655  * Note that @vtable will be copied so you cannot change it after
5656  * registration.
5657  *
5658  * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
5659  *
5660  * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
5661  * that can be used with g_dbus_connection_unregister_subtree() .
5662  *
5663  * Since: 2.26
5664  */
5665 guint
5666 g_dbus_connection_register_subtree (GDBusConnection           *connection,
5667                                     const gchar               *object_path,
5668                                     const GDBusSubtreeVTable  *vtable,
5669                                     GDBusSubtreeFlags          flags,
5670                                     gpointer                   user_data,
5671                                     GDestroyNotify             user_data_free_func,
5672                                     GError                   **error)
5673 {
5674   guint ret;
5675   ExportedSubtree *es;
5676
5677   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5678   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5679   g_return_val_if_fail (vtable != NULL, 0);
5680   g_return_val_if_fail (error == NULL || *error == NULL, 0);
5681
5682   ret = 0;
5683
5684   CONNECTION_LOCK (connection);
5685
5686   es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
5687   if (es != NULL)
5688     {
5689       g_set_error (error,
5690                    G_IO_ERROR,
5691                    G_IO_ERROR_EXISTS,
5692                    _("A subtree is already exported for %s"),
5693                    object_path);
5694       goto out;
5695     }
5696
5697   es = g_new0 (ExportedSubtree, 1);
5698   es->object_path = g_strdup (object_path);
5699   es->connection = connection;
5700
5701   es->vtable = _g_dbus_subtree_vtable_copy (vtable);
5702   es->flags = flags;
5703   es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
5704   es->user_data = user_data;
5705   es->user_data_free_func = user_data_free_func;
5706   es->context = g_main_context_get_thread_default ();
5707   if (es->context != NULL)
5708     g_main_context_ref (es->context);
5709
5710   g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
5711   g_hash_table_insert (connection->map_id_to_es,
5712                        GUINT_TO_POINTER (es->id),
5713                        es);
5714
5715   ret = es->id;
5716
5717  out:
5718   CONNECTION_UNLOCK (connection);
5719
5720   return ret;
5721 }
5722
5723 /* ---------------------------------------------------------------------------------------------------- */
5724
5725 /**
5726  * g_dbus_connection_unregister_subtree:
5727  * @connection: A #GDBusConnection.
5728  * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
5729  *
5730  * Unregisters a subtree.
5731  *
5732  * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
5733  *
5734  * Since: 2.26
5735  */
5736 gboolean
5737 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
5738                                       guint            registration_id)
5739 {
5740   ExportedSubtree *es;
5741   gboolean ret;
5742
5743   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5744
5745   ret = FALSE;
5746
5747   CONNECTION_LOCK (connection);
5748
5749   es = g_hash_table_lookup (connection->map_id_to_es,
5750                             GUINT_TO_POINTER (registration_id));
5751   if (es == NULL)
5752     goto out;
5753
5754   g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
5755   g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
5756
5757   ret = TRUE;
5758
5759  out:
5760   CONNECTION_UNLOCK (connection);
5761
5762   return ret;
5763 }
5764
5765 /* ---------------------------------------------------------------------------------------------------- */
5766
5767 /* must be called with lock held */
5768 static void
5769 handle_generic_ping_unlocked (GDBusConnection *connection,
5770                               const gchar     *object_path,
5771                               GDBusMessage    *message)
5772 {
5773   GDBusMessage *reply;
5774   reply = g_dbus_message_new_method_reply (message);
5775   g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5776   g_object_unref (reply);
5777 }
5778
5779 /* must be called with lock held */
5780 static void
5781 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
5782                                         const gchar     *object_path,
5783                                         GDBusMessage    *message)
5784 {
5785   GDBusMessage *reply;
5786
5787   reply = NULL;
5788   if (connection->machine_id == NULL)
5789     {
5790       GError *error;
5791
5792       error = NULL;
5793       connection->machine_id = _g_dbus_get_machine_id (&error);
5794       if (connection->machine_id == NULL)
5795         {
5796           reply = g_dbus_message_new_method_error_literal (message,
5797                                                            "org.freedesktop.DBus.Error.Failed",
5798                                                            error->message);
5799           g_error_free (error);
5800         }
5801     }
5802
5803   if (reply == NULL)
5804     {
5805       reply = g_dbus_message_new_method_reply (message);
5806       g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
5807     }
5808   g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5809   g_object_unref (reply);
5810 }
5811
5812 /* must be called with lock held */
5813 static void
5814 handle_generic_introspect_unlocked (GDBusConnection *connection,
5815                                     const gchar     *object_path,
5816                                     GDBusMessage    *message)
5817 {
5818   guint n;
5819   GString *s;
5820   gchar **registered;
5821   GDBusMessage *reply;
5822
5823   /* first the header */
5824   s = g_string_new (NULL);
5825   introspect_append_header (s);
5826
5827   registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
5828   for (n = 0; registered != NULL && registered[n] != NULL; n++)
5829       g_string_append_printf (s, "  <node name=\"%s\"/>\n", registered[n]);
5830   g_strfreev (registered);
5831   g_string_append (s, "</node>\n");
5832
5833   reply = g_dbus_message_new_method_reply (message);
5834   g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5835   g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5836   g_object_unref (reply);
5837   g_string_free (s, TRUE);
5838 }
5839
5840 /* must be called with lock held */
5841 static gboolean
5842 handle_generic_unlocked (GDBusConnection *connection,
5843                          GDBusMessage    *message)
5844 {
5845   gboolean handled;
5846   const gchar *interface_name;
5847   const gchar *member;
5848   const gchar *signature;
5849   const gchar *path;
5850
5851   CONNECTION_ENSURE_LOCK (connection);
5852
5853   handled = FALSE;
5854
5855   interface_name = g_dbus_message_get_interface (message);
5856   member = g_dbus_message_get_member (message);
5857   signature = g_dbus_message_get_signature (message);
5858   path = g_dbus_message_get_path (message);
5859
5860   if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5861       g_strcmp0 (member, "Introspect") == 0 &&
5862       g_strcmp0 (signature, "") == 0)
5863     {
5864       handle_generic_introspect_unlocked (connection, path, message);
5865       handled = TRUE;
5866     }
5867   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5868            g_strcmp0 (member, "Ping") == 0 &&
5869            g_strcmp0 (signature, "") == 0)
5870     {
5871       handle_generic_ping_unlocked (connection, path, message);
5872       handled = TRUE;
5873     }
5874   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5875            g_strcmp0 (member, "GetMachineId") == 0 &&
5876            g_strcmp0 (signature, "") == 0)
5877     {
5878       handle_generic_get_machine_id_unlocked (connection, path, message);
5879       handled = TRUE;
5880     }
5881
5882   return handled;
5883 }
5884
5885 /* ---------------------------------------------------------------------------------------------------- */
5886
5887 /* called in message handler thread with lock held */
5888 static void
5889 distribute_method_call (GDBusConnection *connection,
5890                         GDBusMessage    *message)
5891 {
5892   GDBusMessage *reply;
5893   ExportedObject *eo;
5894   ExportedSubtree *es;
5895   const gchar *object_path;
5896   const gchar *interface_name;
5897   const gchar *member;
5898   const gchar *signature;
5899   const gchar *path;
5900   gchar *subtree_path;
5901   gchar *needle;
5902
5903   g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
5904
5905   interface_name = g_dbus_message_get_interface (message);
5906   member = g_dbus_message_get_member (message);
5907   signature = g_dbus_message_get_signature (message);
5908   path = g_dbus_message_get_path (message);
5909   subtree_path = g_strdup (path);
5910   needle = strrchr (subtree_path, '/');
5911   if (needle != NULL && needle != subtree_path)
5912     {
5913       *needle = '\0';
5914     }
5915   else
5916     {
5917       g_free (subtree_path);
5918       subtree_path = NULL;
5919     }
5920
5921
5922   if (G_UNLIKELY (_g_dbus_debug_incoming ()))
5923     {
5924       _g_dbus_debug_print_lock ();
5925       g_print ("========================================================================\n"
5926                "GDBus-debug:Incoming:\n"
5927                " <<<< METHOD INVOCATION %s.%s()\n"
5928                "      on object %s\n"
5929                "      invoked by name %s\n"
5930                "      serial %d\n",
5931                interface_name, member,
5932                path,
5933                g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
5934                g_dbus_message_get_serial (message));
5935       _g_dbus_debug_print_unlock ();
5936     }
5937
5938 #if 0
5939   g_debug ("interface    = `%s'", interface_name);
5940   g_debug ("member       = `%s'", member);
5941   g_debug ("signature    = `%s'", signature);
5942   g_debug ("path         = `%s'", path);
5943   g_debug ("subtree_path = `%s'", subtree_path != NULL ? subtree_path : "N/A");
5944 #endif
5945
5946   object_path = g_dbus_message_get_path (message);
5947   g_assert (object_path != NULL);
5948
5949   eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
5950   if (eo != NULL)
5951     {
5952       if (obj_message_func (connection, eo, message))
5953         goto out;
5954     }
5955
5956   es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
5957   if (es != NULL)
5958     {
5959       if (subtree_message_func (connection, es, message))
5960         goto out;
5961     }
5962
5963   if (subtree_path != NULL)
5964     {
5965       es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
5966       if (es != NULL)
5967         {
5968           if (subtree_message_func (connection, es, message))
5969             goto out;
5970         }
5971     }
5972
5973   if (handle_generic_unlocked (connection, message))
5974     goto out;
5975
5976   /* if we end up here, the message has not been not handled - so return an error saying this */
5977   reply = g_dbus_message_new_method_error (message,
5978                                            "org.freedesktop.DBus.Error.UnknownMethod",
5979                                            _("No such interface `%s' on object at path %s"),
5980                                            interface_name,
5981                                            object_path);
5982   g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5983   g_object_unref (reply);
5984
5985  out:
5986   g_free (subtree_path);
5987 }
5988
5989 /* ---------------------------------------------------------------------------------------------------- */
5990
5991 static GDBusConnection **
5992 message_bus_get_singleton (GBusType   bus_type,
5993                            GError   **error)
5994 {
5995   GDBusConnection **ret;
5996   const gchar *starter_bus;
5997
5998   ret = NULL;
5999
6000   switch (bus_type)
6001     {
6002     case G_BUS_TYPE_SESSION:
6003       ret = &the_session_bus;
6004       break;
6005
6006     case G_BUS_TYPE_SYSTEM:
6007       ret = &the_system_bus;
6008       break;
6009
6010     case G_BUS_TYPE_STARTER:
6011       starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
6012       if (g_strcmp0 (starter_bus, "session") == 0)
6013         {
6014           ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
6015           goto out;
6016         }
6017       else if (g_strcmp0 (starter_bus, "system") == 0)
6018         {
6019           ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
6020           goto out;
6021         }
6022       else
6023         {
6024           if (starter_bus != NULL)
6025             {
6026               g_set_error (error,
6027                            G_IO_ERROR,
6028                            G_IO_ERROR_INVALID_ARGUMENT,
6029                            _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
6030                              " - unknown value `%s'"),
6031                            starter_bus);
6032             }
6033           else
6034             {
6035               g_set_error_literal (error,
6036                                    G_IO_ERROR,
6037                                    G_IO_ERROR_INVALID_ARGUMENT,
6038                                    _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
6039                                      "variable is not set"));
6040             }
6041         }
6042       break;
6043
6044     default:
6045       g_assert_not_reached ();
6046       break;
6047     }
6048
6049  out:
6050   return ret;
6051 }
6052
6053 static GDBusConnection *
6054 get_uninitialized_connection (GBusType       bus_type,
6055                               GCancellable  *cancellable,
6056                               GError       **error)
6057 {
6058   GDBusConnection **singleton;
6059   GDBusConnection *ret;
6060
6061   ret = NULL;
6062
6063   G_LOCK (message_bus_lock);
6064   singleton = message_bus_get_singleton (bus_type, error);
6065   if (singleton == NULL)
6066     goto out;
6067
6068   if (*singleton == NULL)
6069     {
6070       gchar *address;
6071       address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
6072       if (address == NULL)
6073         goto out;
6074       ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
6075                                        "address", address,
6076                                        "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
6077                                                 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
6078                                        "exit-on-close", TRUE,
6079                                        NULL);
6080       g_free (address);
6081     }
6082   else
6083     {
6084       ret = g_object_ref (*singleton);
6085     }
6086
6087   g_assert (ret != NULL);
6088
6089  out:
6090   G_UNLOCK (message_bus_lock);
6091   return ret;
6092 }
6093
6094 /**
6095  * g_bus_get_sync:
6096  * @bus_type: A #GBusType.
6097  * @cancellable: A #GCancellable or %NULL.
6098  * @error: Return location for error or %NULL.
6099  *
6100  * Synchronously connects to the message bus specified by @bus_type.
6101  * Note that the returned object may shared with other callers,
6102  * e.g. if two separate parts of a process calls this function with
6103  * the same @bus_type, they will share the same object.
6104  *
6105  * This is a synchronous failable function. See g_bus_get() and
6106  * g_bus_get_finish() for the asynchronous version.
6107  *
6108  * The returned object is a singleton, that is, shared with other
6109  * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6110  * event that you need a private message bus connection, use
6111  * g_dbus_address_get_for_bus_sync() and
6112  * g_dbus_connection_new_for_address().
6113  *
6114  * Note that the returned #GDBusConnection object will (usually) have
6115  * the #GDBusConnection:exit-on-close property set to %TRUE.
6116  *
6117  * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6118  *
6119  * Since: 2.26
6120  */
6121 GDBusConnection *
6122 g_bus_get_sync (GBusType       bus_type,
6123                 GCancellable  *cancellable,
6124                 GError       **error)
6125 {
6126   GDBusConnection *connection;
6127
6128   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6129
6130   connection = get_uninitialized_connection (bus_type, cancellable, error);
6131   if (connection == NULL)
6132     goto out;
6133
6134   if (!g_initable_init (G_INITABLE (connection), cancellable, error))
6135     {
6136       g_object_unref (connection);
6137       connection = NULL;
6138     }
6139
6140  out:
6141   return connection;
6142 }
6143
6144 static void
6145 bus_get_async_initable_cb (GObject      *source_object,
6146                            GAsyncResult *res,
6147                            gpointer      user_data)
6148 {
6149   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
6150   GError *error;
6151
6152   error = NULL;
6153   if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
6154                                      res,
6155                                      &error))
6156     {
6157       g_assert (error != NULL);
6158       g_simple_async_result_set_from_error (simple, error);
6159       g_error_free (error);
6160       g_object_unref (source_object);
6161     }
6162   else
6163     {
6164       g_simple_async_result_set_op_res_gpointer (simple,
6165                                                  source_object,
6166                                                  g_object_unref);
6167     }
6168   g_simple_async_result_complete_in_idle (simple);
6169   g_object_unref (simple);
6170 }
6171
6172 /**
6173  * g_bus_get:
6174  * @bus_type: A #GBusType.
6175  * @cancellable: A #GCancellable or %NULL.
6176  * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
6177  * @user_data: The data to pass to @callback.
6178  *
6179  * Asynchronously connects to the message bus specified by @bus_type.
6180  *
6181  * When the operation is finished, @callback will be invoked. You can
6182  * then call g_bus_get_finish() to get the result of the operation.
6183  *
6184  * This is a asynchronous failable function. See g_bus_get_sync() for
6185  * the synchronous version.
6186  *
6187  * Since: 2.26
6188  */
6189 void
6190 g_bus_get (GBusType             bus_type,
6191            GCancellable        *cancellable,
6192            GAsyncReadyCallback  callback,
6193            gpointer             user_data)
6194 {
6195   GDBusConnection *connection;
6196   GSimpleAsyncResult *simple;
6197   GError *error;
6198
6199   simple = g_simple_async_result_new (NULL,
6200                                       callback,
6201                                       user_data,
6202                                       g_bus_get);
6203
6204   error = NULL;
6205   connection = get_uninitialized_connection (bus_type, cancellable, &error);
6206   if (connection == NULL)
6207     {
6208       g_assert (error != NULL);
6209       g_simple_async_result_set_from_error (simple, error);
6210       g_error_free (error);
6211       g_simple_async_result_complete_in_idle (simple);
6212       g_object_unref (simple);
6213     }
6214   else
6215     {
6216       g_async_initable_init_async (G_ASYNC_INITABLE (connection),
6217                                    G_PRIORITY_DEFAULT,
6218                                    cancellable,
6219                                    bus_get_async_initable_cb,
6220                                    simple);
6221     }
6222 }
6223
6224 /**
6225  * g_bus_get_finish:
6226  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
6227  * @error: Return location for error or %NULL.
6228  *
6229  * Finishes an operation started with g_bus_get().
6230  *
6231  * The returned object is a singleton, that is, shared with other
6232  * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6233  * event that you need a private message bus connection, use
6234  * g_dbus_address_get_for_bus() and
6235  * g_dbus_connection_new_for_address().
6236  *
6237  * Note that the returned #GDBusConnection object will (usually) have
6238  * the #GDBusConnection:exit-on-close property set to %TRUE.
6239  *
6240  * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6241  *
6242  * Since: 2.26
6243  */
6244 GDBusConnection *
6245 g_bus_get_finish (GAsyncResult  *res,
6246                   GError       **error)
6247 {
6248   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
6249   GObject *object;
6250   GDBusConnection *ret;
6251
6252   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6253
6254   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
6255
6256   ret = NULL;
6257
6258   if (g_simple_async_result_propagate_error (simple, error))
6259     goto out;
6260
6261   object = g_simple_async_result_get_op_res_gpointer (simple);
6262   g_assert (object != NULL);
6263   ret = g_object_ref (G_DBUS_CONNECTION (object));
6264
6265  out:
6266   return ret;
6267 }
6268
6269 /* ---------------------------------------------------------------------------------------------------- */