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