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