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