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