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