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