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