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