Coverage Report

Created: 2026-04-01 06:53

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