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