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