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