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