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