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