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