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