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