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