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