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