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