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