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