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