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