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