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