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