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