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