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