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