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