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