gdbusconnection.c 264 KB
Newer Older
1 2
/* GDBus - GLib D-Bus Library
 *
3
 * Copyright (C) 2008-2010 Red Hat, Inc.
4 5 6 7
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
8
 * version 2.1 of the License, or (at your option) any later version.
9 10 11 12 13 14 15
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
16
 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
17 18 19 20 21 22 23 24 25
 *
 * Author: David Zeuthen <davidz@redhat.com>
 */

/*
 * TODO for GDBus:
 *
 * - would be nice to expose GDBusAuthMechanism and an extension point
 *
26 27 28
 * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
 *   the mechanism VFuncs need to be able to set an error.
 *
Matthias Clasen's avatar
Matthias Clasen committed
29
 * - Need to document other mechanisms/sources for determining the D-Bus
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
 *   address of a well-known bus.
 *
 *   - e.g. on Win32 we need code like from here
 *
 *     http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
 *
 *     that was never copied over here because it originally was copy-paste
 *     from the GPLv2 / AFL 2.1 libdbus sources.
 *
 *   - on OS X we need to look in launchd for the address
 *
 *     https://bugs.freedesktop.org/show_bug.cgi?id=14259
 *
 *   - on X11 we need to look in a X11 property on the X server
 *     - (we can also just use dbus-launch(1) from the D-Bus
 *        distribution)
 *
 *   - (ideally) this requires D-Bus spec work because none of
Matthias Clasen's avatar
Matthias Clasen committed
48
 *     this has never really been specced out properly (except
49 50 51 52 53 54
 *     the X11 bits)
 *
 * - Related to the above, we also need to be able to launch a message bus
 *   instance.... Since we don't want to write our own bus daemon we should
 *   launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
 *
55 56 57
 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
 *   to specify where the nonce is stored. This will allow people to use
 *   G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
Matthias Clasen's avatar
Matthias Clasen committed
58
 *   to easily achieve secure RPC via nonce-tcp.
59
 *
60 61 62 63 64 65 66
 * - need to expose an extension point for resolving D-Bus address and
 *   turning them into GIOStream objects. This will allow us to implement
 *   e.g. X11 D-Bus transports without dlopen()'ing or linking against
 *   libX11 from libgio.
 *   - see g_dbus_address_connect() in gdbusaddress.c
 *
 * - would be cute to use kernel-specific APIs to resolve fds for
67
 *   debug output when using G_DBUS_DEBUG=message, e.g. in addition to
68 69 70 71 72 73 74 75 76 77 78
 *
 *     fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
 *
 *   maybe we can show more information about what fd 21 really is.
 *   Ryan suggests looking in /proc/self/fd for clues / symlinks!
 *   Initial experiments on Linux 2.6 suggests that the symlink looks
 *   like this:
 *
 *    3 -> /proc/18068/fd
 *
 *   e.g. not of much use.
David Zeuthen's avatar
David Zeuthen committed
79 80 81 82 83 84 85 86 87 88 89 90
 *
 *  - GDBus High-Level docs
 *    - Proxy: properties, signals...
 *    - Connection: IOStream based, ::close, connection setup steps
 *                  mainloop integration, threading
 *    - Differences from libdbus (extend "Migrating from")
 *      - the message handling thread
 *      - Using GVariant instead of GValue
 *    - Explain why the high-level API is a good thing and what
 *      kind of pitfalls it avoids
 *      - Export objects before claiming names
 *    - Talk about auto-starting services (cf. GBusNameWatcherFlags)
91 92 93 94 95
 */

#include "config.h"

#include <stdlib.h>
David Zeuthen's avatar
David Zeuthen committed
96
#include <string.h>
97 98 99 100 101 102 103 104 105 106 107 108

#include "gdbusauth.h"
#include "gdbusutils.h"
#include "gdbusaddress.h"
#include "gdbusmessage.h"
#include "gdbusconnection.h"
#include "gdbuserror.h"
#include "gioenumtypes.h"
#include "gdbusintrospection.h"
#include "gdbusmethodinvocation.h"
#include "gdbusprivate.h"
#include "gdbusauthobserver.h"
David Zeuthen's avatar
David Zeuthen committed
109 110 111 112
#include "ginitable.h"
#include "gasyncinitable.h"
#include "giostream.h"
#include "gasyncresult.h"
113
#include "gtask.h"
David Zeuthen's avatar
David Zeuthen committed
114 115

#ifdef G_OS_UNIX
Matthias Clasen's avatar
Matthias Clasen committed
116 117
#include "gunixconnection.h"
#include "gunixfdmessage.h"
David Zeuthen's avatar
David Zeuthen committed
118 119 120
#endif

#include "glibintl.h"
121 122 123 124

/**
 * SECTION:gdbusconnection
 * @short_description: D-Bus Connections
David Zeuthen's avatar
David Zeuthen committed
125
 * @include: gio/gio.h
126 127
 *
 * The #GDBusConnection type is used for D-Bus connections to remote
128 129 130 131 132
 * peers such as a message buses. It is a low-level API that offers a
 * lot of flexibility. For instance, it lets you establish a connection
 * over any transport that can by represented as an #GIOStream.
 *
 * This class is rarely used directly in D-Bus clients. If you are writing
Michael Catanzaro's avatar
Michael Catanzaro committed
133
 * a D-Bus client, it is often easier to use the g_bus_own_name(),
134
 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
135
 *
136 137 138 139
 * As an exception to the usual GLib rule that a particular object must not
 * be used by two threads at the same time, #GDBusConnection's methods may be
 * called from any thread. This is so that g_bus_get() and g_bus_get_sync()
 * can safely return the same #GDBusConnection when called from any thread.
140
 *
141 142 143 144
 * Most of the ways to obtain a #GDBusConnection automatically initialize it
 * (i.e. connect to D-Bus): for instance, g_dbus_connection_new() and
 * g_bus_get(), and the synchronous versions of those methods, give you an
 * initialized connection. Language bindings for GIO should use
145
 * g_initable_new() or g_async_initable_new_async(), which also initialize the
146 147 148 149
 * connection.
 *
 * If you construct an uninitialized #GDBusConnection, such as via
 * g_object_new(), you must initialize it via g_initable_init() or
150 151 152 153 154 155
 * g_async_initable_init_async() before using its methods or properties.
 * Calling methods or accessing properties on a #GDBusConnection that has not
 * completed initialization successfully is considered to be invalid, and leads
 * to undefined behaviour. In particular, if initialization fails with a
 * #GError, the only valid thing you can do with that #GDBusConnection is to
 * free it with g_object_unref().
156
 *
157
 * ## An example D-Bus server # {#gdbus-server}
158
 *
159 160
 * Here is an example for a D-Bus server:
 * [gdbus-example-server.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-server.c)
161
 *
162
 * ## An example for exporting a subtree # {#gdbus-subtree-server}
163
 *
164 165 166 167 168 169
 * Here is an example for exporting a subtree:
 * [gdbus-example-subtree.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-subtree.c)
 *
 * ## An example for file descriptor passing # {#gdbus-unix-fd-client}
 *
 * Here is an example for passing UNIX file descriptors:
170
 * [gdbus-unix-fd-client.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-unix-fd-client.c)
171 172 173 174 175
 *
 * ## An example for exporting a GObject # {#gdbus-export}
 *
 * Here is an example for exporting a #GObject:
 * [gdbus-example-export.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-export.c)
176 177 178 179
 */

/* ---------------------------------------------------------------------------------------------------- */

180 181
typedef struct _GDBusConnectionClass GDBusConnectionClass;

182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
/**
 * GDBusConnectionClass:
 * @closed: Signal class handler for the #GDBusConnection::closed signal.
 *
 * Class structure for #GDBusConnection.
 *
 * Since: 2.26
 */
struct _GDBusConnectionClass
{
  /*< private >*/
  GObjectClass parent_class;

  /*< public >*/
  /* Signals */
  void (*closed) (GDBusConnection *connection,
                  gboolean         remote_peer_vanished,
                  GError          *error);
};

202 203
G_LOCK_DEFINE_STATIC (message_bus_lock);

204 205
static GWeakRef the_session_bus;
static GWeakRef the_system_bus;
206

207 208 209 210 211 212
/* Extra pseudo-member of GDBusSendMessageFlags.
 * Set by initable_init() to indicate that despite not being initialized yet,
 * enough of the only-valid-after-init members are set that we can send a
 * message, and we're being called from its thread, so no memory barrier is
 * required before accessing them.
 */
213
#define SEND_MESSAGE_FLAGS_INITIALIZING (1u << 31)
214 215

/* Same as SEND_MESSAGE_FLAGS_INITIALIZING, but in GDBusCallFlags */
216
#define CALL_FLAGS_INITIALIZING (1u << 31)
217

218 219
/* ---------------------------------------------------------------------------------------------------- */

220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
typedef struct
{
  GDestroyNotify              callback;
  gpointer                    user_data;
  GMainContext               *context;
} CallDestroyNotifyData;

static gboolean
call_destroy_notify_data_in_idle (gpointer user_data)
{
  CallDestroyNotifyData *data = user_data;
  data->callback (data->user_data);
  return FALSE;
}

static void
call_destroy_notify_data_free (CallDestroyNotifyData *data)
{
  if (data->context != NULL)
    g_main_context_unref (data->context);
  g_free (data);
}

/*
 * call_destroy_notify: <internal>
245 246
 * @context: (nullable): A #GMainContext or %NULL.
 * @callback: (nullable): A #GDestroyNotify or %NULL.
247 248 249 250 251 252 253 254 255
 * @user_data: Data to pass to @callback.
 *
 * Schedules @callback to run in @context.
 */
static void
call_destroy_notify (GMainContext  *context,
                     GDestroyNotify callback,
                     gpointer       user_data)
{
256 257
  GSource *idle_source;
  CallDestroyNotifyData *data;
258

259 260 261
  if (callback == NULL)
    goto out;

262 263 264 265 266 267
  data = g_new0 (CallDestroyNotifyData, 1);
  data->callback = callback;
  data->user_data = user_data;
  data->context = context;
  if (data->context != NULL)
    g_main_context_ref (data->context);
268

269 270 271 272 273 274
  idle_source = g_idle_source_new ();
  g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
  g_source_set_callback (idle_source,
                         call_destroy_notify_data_in_idle,
                         data,
                         (GDestroyNotify) call_destroy_notify_data_free);
275
  g_source_set_name (idle_source, "[gio] call_destroy_notify_data_in_idle");
276 277
  g_source_attach (idle_source, data->context);
  g_source_unref (idle_source);
278 279 280 281 282 283 284

 out:
  ;
}

/* ---------------------------------------------------------------------------------------------------- */

285
static gboolean
Matthias Clasen's avatar
Matthias Clasen committed
286 287
_g_strv_has_string (const gchar* const *haystack,
                    const gchar        *needle)
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
{
  guint n;

  for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
    {
      if (g_strcmp0 (haystack[n], needle) == 0)
        return TRUE;
    }
  return FALSE;
}

/* ---------------------------------------------------------------------------------------------------- */

#ifdef G_OS_WIN32
#define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
#else
// TODO: for some reason this doesn't work on Windows
#define CONNECTION_ENSURE_LOCK(obj) do {                                \
306
    if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock)))                     \
307 308 309 310 311 312 313 314
      {                                                                 \
        g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
                             "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
      }                                                                 \
  } while (FALSE)
#endif

#define CONNECTION_LOCK(obj) do {                                       \
315
    g_mutex_lock (&(obj)->lock);                                        \
316 317 318
  } while (FALSE)

#define CONNECTION_UNLOCK(obj) do {                                     \
319
    g_mutex_unlock (&(obj)->lock);                                      \
320 321
  } while (FALSE)

322 323
/* Flags in connection->atomic_flags */
enum {
324
    FLAG_INITIALIZED = 1 << 0,
325 326
    FLAG_EXIT_ON_CLOSE = 1 << 1,
    FLAG_CLOSED = 1 << 2
327 328
};

329 330 331 332 333 334 335 336 337
/**
 * GDBusConnection:
 *
 * The #GDBusConnection structure contains only private data and
 * should only be accessed using the provided API.
 *
 * Since: 2.26
 */
struct _GDBusConnection
338
{
339 340 341
  /*< private >*/
  GObject parent_instance;

342 343 344 345
  /* ------------------------------------------------------------------------ */
  /* -- General object state ------------------------------------------------ */
  /* ------------------------------------------------------------------------ */

346
  /* General-purpose lock for most fields */
347
  GMutex lock;
348 349

  /* A lock used in the init() method of the GInitable interface - see comments
350 351 352
   * in initable_init() for why a separate lock is needed.
   *
   * If you need both @lock and @init_lock, you must take @init_lock first.
353
   */
354
  GMutex init_lock;
355 356

  /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
357
   * someone calls org.freedesktop.DBus.Peer.GetMachineId(). Protected by @lock.
358 359 360
   */
  gchar *machine_id;

361 362 363 364
  /* The underlying stream used for communication
   * Read-only after initable_init(), so it may be read if you either
   * hold @init_lock or check for initialization first.
   */
365 366
  GIOStream *stream;

367 368 369 370
  /* The object used for authentication (if any).
   * Read-only after initable_init(), so it may be read if you either
   * hold @init_lock or check for initialization first.
   */
371 372
  GDBusAuth *auth;

373
  /* Last serial used. Protected by @lock. */
374 375
  guint32 last_serial;

376 377 378 379
  /* The object used to send/receive messages.
   * Read-only after initable_init(), so it may be read if you either
   * hold @init_lock or check for initialization first.
   */
380 381 382
  GDBusWorker *worker;

  /* If connected to a message bus, this contains the unique name assigned to
383 384 385
   * us by the bus (e.g. ":1.42").
   * Read-only after initable_init(), so it may be read if you either
   * hold @init_lock or check for initialization first.
386 387 388 389
   */
  gchar *bus_unique_name;

  /* The GUID returned by the other side if we authenticed as a client or
390 391 392
   * the GUID to use if authenticating as a server.
   * Read-only after initable_init(), so it may be read if you either
   * hold @init_lock or check for initialization first.
393 394 395
   */
  gchar *guid;

396 397
  /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
   * Inspect @initialization_error to see whether it succeeded or failed.
398 399
   *
   * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
400 401 402
   *
   * FLAG_CLOSED is the closed property. It may be read at any time, but
   * may only be written while holding @lock.
403 404
   */
  volatile gint atomic_flags;
405

406 407 408 409 410
  /* If the connection could not be established during initable_init(),
   * this GError will be set.
   * Read-only after initable_init(), so it may be read if you either
   * hold @init_lock or check for initialization first.
   */
411 412
  GError *initialization_error;

413
  /* The result of g_main_context_ref_thread_default() when the object
414 415
   * was created (the GObject _init() function) - this is used for delivery
   * of the :closed GObject signal.
416 417
   *
   * Only set in the GObject init function, so no locks are needed.
418 419 420
   */
  GMainContext *main_context_at_construction;

421
  /* Read-only construct properties, no locks needed */
422 423 424
  gchar *address;
  GDBusConnectionFlags flags;

425
  /* Map used for managing method replies, protected by @lock */
426
  GHashTable *map_method_serial_to_task;  /* guint32 -> GTask* */
427

428
  /* Maps used for managing signal subscription, protected by @lock */
429 430 431
  GHashTable *map_rule_to_signal_data;                      /* match rule (gchar*)    -> SignalData */
  GHashTable *map_id_to_signal_data;                        /* id (guint)             -> SignalData */
  GHashTable *map_sender_unique_name_to_signal_data_array;  /* unique sender (gchar*) -> GPtrArray* of SignalData */
432

433 434 435
  /* Maps used for managing exported objects and subtrees,
   * protected by @lock
   */
436 437 438 439 440
  GHashTable *map_object_path_to_eo;  /* gchar* -> ExportedObject* */
  GHashTable *map_id_to_ei;           /* guint  -> ExportedInterface* */
  GHashTable *map_object_path_to_es;  /* gchar* -> ExportedSubtree* */
  GHashTable *map_id_to_es;           /* guint  -> ExportedSubtree* */

441 442 443
  /* Map used for storing last used serials for each thread, protected by @lock */
  GHashTable *map_thread_to_last_serial;

444
  /* Structure used for message filters, protected by @lock */
445 446
  GPtrArray *filters;

447 448 449 450
  /* Capabilities negotiated during authentication
   * Read-only after initable_init(), so it may be read without holding a
   * lock, if you check for initialization first.
   */
451 452
  GDBusCapabilityFlags capabilities;

453
  /* Protected by @init_lock */
454
  GDBusAuthObserver *authentication_observer;
455 456 457 458

  /* Read-only after initable_init(), so it may be read if you either
   * hold @init_lock or check for initialization first.
   */
Matthias Clasen's avatar
Matthias Clasen committed
459
  GCredentials *credentials;
460 461 462

  /* set to TRUE when finalizing */
  gboolean finalizing;
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
};

typedef struct ExportedObject ExportedObject;
static void exported_object_free (ExportedObject *eo);

typedef struct ExportedSubtree ExportedSubtree;
static void exported_subtree_free (ExportedSubtree *es);

enum
{
  CLOSED_SIGNAL,
  LAST_SIGNAL,
};

enum
{
  PROP_0,
  PROP_STREAM,
  PROP_ADDRESS,
  PROP_FLAGS,
  PROP_GUID,
  PROP_UNIQUE_NAME,
  PROP_CLOSED,
  PROP_EXIT_ON_CLOSE,
  PROP_CAPABILITY_FLAGS,
  PROP_AUTHENTICATION_OBSERVER,
};

static void distribute_signals (GDBusConnection  *connection,
                                GDBusMessage     *message);

static void distribute_method_call (GDBusConnection  *connection,
                                    GDBusMessage     *message);

static gboolean handle_generic_unlocked (GDBusConnection *connection,
                                         GDBusMessage    *message);


static void purge_all_signal_subscriptions (GDBusConnection *connection);
static void purge_all_filters (GDBusConnection *connection);

504 505 506 507 508 509 510 511 512 513 514 515
static void schedule_method_call (GDBusConnection            *connection,
                                  GDBusMessage               *message,
                                  guint                       registration_id,
                                  guint                       subtree_registration_id,
                                  const GDBusInterfaceInfo   *interface_info,
                                  const GDBusMethodInfo      *method_info,
                                  const GDBusPropertyInfo    *property_info,
                                  GVariant                   *parameters,
                                  const GDBusInterfaceVTable *vtable,
                                  GMainContext               *main_context,
                                  gpointer                    user_data);

516 517 518 519
#define _G_ENSURE_LOCK(name) do {                                       \
    if (G_UNLIKELY (G_TRYLOCK(name)))                                   \
      {                                                                 \
        g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
520
                             "_G_ENSURE_LOCK: Lock '" #name "' is not locked"); \
521 522 523 524 525
      }                                                                 \
  } while (FALSE)                                                       \

static guint signals[LAST_SIGNAL] = { 0 };

Matthias Clasen's avatar
Matthias Clasen committed
526
static void initable_iface_init       (GInitableIface      *initable_iface);
527 528 529 530 531 532 533
static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);

G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
                         G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
                         G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
                         );

534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
/*
 * Check that all members of @connection that can only be accessed after
 * the connection is initialized can safely be accessed. If not,
 * log a critical warning. This function is a memory barrier.
 *
 * Returns: %TRUE if initialized
 */
static gboolean
check_initialized (GDBusConnection *connection)
{
  /* The access to @atomic_flags isn't conditional, so that this function
   * provides a memory barrier for thread-safety even if checks are disabled.
   * (If you don't want this stricter guarantee, you can call
   * g_return_if_fail (check_initialized (c)).)
   *
   * This isn't strictly necessary now that we've decided use of an
   * uninitialized GDBusConnection is undefined behaviour, but it seems
   * better to be as deterministic as is feasible.
   *
   * (Anything that could suffer a crash from seeing undefined values
   * must have a race condition - thread A initializes the connection while
   * thread B calls a method without initialization, hoping that thread A will
   * win the race - so its behaviour is undefined anyway.)
   */
  gint flags = g_atomic_int_get (&connection->atomic_flags);

  g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);

  /* We can safely access this, due to the memory barrier above */
  g_return_val_if_fail (connection->initialization_error == NULL, FALSE);

  return TRUE;
}

568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
typedef enum {
    MAY_BE_UNINITIALIZED = (1<<1)
} CheckUnclosedFlags;

/*
 * Check the same thing as check_initialized(), and also that the
 * connection is not closed. If the connection is uninitialized,
 * raise a critical warning (it's programmer error); if it's closed,
 * raise a recoverable GError (it's a runtime error).
 *
 * This function is a memory barrier.
 *
 * Returns: %TRUE if initialized and not closed
 */
static gboolean
check_unclosed (GDBusConnection     *connection,
                CheckUnclosedFlags   check,
                GError             **error)
{
  /* check_initialized() is effectively inlined, so we don't waste time
   * doing two memory barriers
   */
  gint flags = g_atomic_int_get (&connection->atomic_flags);

  if (!(check & MAY_BE_UNINITIALIZED))
    {
      g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
      g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
    }

  if (flags & FLAG_CLOSED)
    {
      g_set_error_literal (error,
                           G_IO_ERROR,
                           G_IO_ERROR_CLOSED,
                           _("The connection is closed"));
      return FALSE;
    }

  return TRUE;
}

610 611
static GHashTable *alive_connections = NULL;

612 613 614 615 616 617
static void
g_dbus_connection_dispose (GObject *object)
{
  GDBusConnection *connection = G_DBUS_CONNECTION (object);

  G_LOCK (message_bus_lock);
618
  CONNECTION_LOCK (connection);
619
  if (connection->worker != NULL)
620
    {
621 622
      _g_dbus_worker_stop (connection->worker);
      connection->worker = NULL;
623 624 625 626 627 628
      if (alive_connections != NULL)
        g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
    }
  else
    {
      if (alive_connections != NULL)
629
        g_warn_if_fail (!g_hash_table_contains (alive_connections, connection));
630
    }
631
  CONNECTION_UNLOCK (connection);
632 633 634 635 636 637 638 639 640 641 642
  G_UNLOCK (message_bus_lock);

  if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
    G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
}

static void
g_dbus_connection_finalize (GObject *object)
{
  GDBusConnection *connection = G_DBUS_CONNECTION (object);

643 644 645 646 647 648 649
  connection->finalizing = TRUE;

  purge_all_signal_subscriptions (connection);

  purge_all_filters (connection);
  g_ptr_array_unref (connection->filters);

650 651
  if (connection->authentication_observer != NULL)
    g_object_unref (connection->authentication_observer);
652

653 654
  if (connection->auth != NULL)
    g_object_unref (connection->auth);
655

656 657 658
  if (connection->credentials)
    g_object_unref (connection->credentials);

659
  if (connection->stream != NULL)
660
    {
661 662
      g_object_unref (connection->stream);
      connection->stream = NULL;
663 664
    }

665
  g_free (connection->address);
666

667 668
  g_free (connection->guid);
  g_free (connection->bus_unique_name);
669

670 671
  if (connection->initialization_error != NULL)
    g_error_free (connection->initialization_error);
672

673
  g_hash_table_unref (connection->map_method_serial_to_task);
674

675 676 677
  g_hash_table_unref (connection->map_rule_to_signal_data);
  g_hash_table_unref (connection->map_id_to_signal_data);
  g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
678

679 680 681 682
  g_hash_table_unref (connection->map_id_to_ei);
  g_hash_table_unref (connection->map_object_path_to_eo);
  g_hash_table_unref (connection->map_id_to_es);
  g_hash_table_unref (connection->map_object_path_to_es);
683

684 685
  g_hash_table_unref (connection->map_thread_to_last_serial);

686
  g_main_context_unref (connection->main_context_at_construction);
687

688
  g_free (connection->machine_id);
689

690 691
  g_mutex_clear (&connection->init_lock);
  g_mutex_clear (&connection->lock);
692

Matthias Clasen's avatar
Matthias Clasen committed
693
  G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
694 695
}

696
/* called in any user thread, with the connection's lock not held */
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
static void
g_dbus_connection_get_property (GObject    *object,
                                guint       prop_id,
                                GValue     *value,
                                GParamSpec *pspec)
{
  GDBusConnection *connection = G_DBUS_CONNECTION (object);

  switch (prop_id)
    {
    case PROP_STREAM:
      g_value_set_object (value, g_dbus_connection_get_stream (connection));
      break;

    case PROP_GUID:
      g_value_set_string (value, g_dbus_connection_get_guid (connection));
      break;

    case PROP_UNIQUE_NAME:
      g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
      break;

    case PROP_CLOSED:
      g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
      break;

    case PROP_EXIT_ON_CLOSE:
      g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
      break;

    case PROP_CAPABILITY_FLAGS:
      g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
      break;

731 732 733 734
    case PROP_FLAGS:
      g_value_set_flags (value, g_dbus_connection_get_flags (connection));
      break;

735 736 737 738 739 740
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
    }
}

741
/* called in any user thread, with the connection's lock not held */
742 743 744 745 746 747 748 749 750 751 752
static void
g_dbus_connection_set_property (GObject      *object,
                                guint         prop_id,
                                const GValue *value,
                                GParamSpec   *pspec)
{
  GDBusConnection *connection = G_DBUS_CONNECTION (object);

  switch (prop_id)
    {
    case PROP_STREAM:
753
      connection->stream = g_value_dup_object (value);
754 755 756
      break;

    case PROP_GUID:
757
      connection->guid = g_value_dup_string (value);
758 759 760
      break;

    case PROP_ADDRESS:
761
      connection->address = g_value_dup_string (value);
762 763 764
      break;

    case PROP_FLAGS:
765
      connection->flags = g_value_get_flags (value);
766 767 768 769 770 771 772
      break;

    case PROP_EXIT_ON_CLOSE:
      g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
      break;

    case PROP_AUTHENTICATION_OBSERVER:
773
      connection->authentication_observer = g_value_dup_object (value);
774 775 776 777 778 779 780 781
      break;

    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
    }
}

782 783 784 785 786
/* Base-class implementation of GDBusConnection::closed.
 *
 * Called in a user thread, by the main context that was thread-default when
 * the object was constructed.
 */
787 788 789 790 791
static void
g_dbus_connection_real_closed (GDBusConnection *connection,
                               gboolean         remote_peer_vanished,
                               GError          *error)
{
792 793 794 795 796
  gint flags = g_atomic_int_get (&connection->atomic_flags);

  /* Because atomic int access is a memory barrier, we can safely read
   * initialization_error without a lock, as long as we do it afterwards.
   */
797 798
  if (remote_peer_vanished &&
      (flags & FLAG_EXIT_ON_CLOSE) != 0 &&
799 800
      (flags & FLAG_INITIALIZED) != 0 &&
      connection->initialization_error == NULL)
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
    {
      raise (SIGTERM);
    }
}

static void
g_dbus_connection_class_init (GDBusConnectionClass *klass)
{
  GObjectClass *gobject_class;

  gobject_class = G_OBJECT_CLASS (klass);

  gobject_class->finalize     = g_dbus_connection_finalize;
  gobject_class->dispose      = g_dbus_connection_dispose;
  gobject_class->set_property = g_dbus_connection_set_property;
  gobject_class->get_property = g_dbus_connection_get_property;

  klass->closed = g_dbus_connection_real_closed;

  /**
   * GDBusConnection:stream:
   *
   * The underlying #GIOStream used for I/O.
824
   *
825 826 827
   * If this is passed on construction and is a #GSocketConnection,
   * then the corresponding #GSocket will be put into non-blocking mode.
   *
828 829 830 831
   * While the #GDBusConnection is active, it will interact with this
   * stream from a worker thread, so it is not safe to interact with
   * the stream directly.
   *
832
   * Since: 2.26
833 834 835 836
   */
  g_object_class_install_property (gobject_class,
                                   PROP_STREAM,
                                   g_param_spec_object ("stream",
Matthias Clasen's avatar
Matthias Clasen committed
837 838
                                                        P_("IO Stream"),
                                                        P_("The underlying streams used for I/O"),
839 840 841 842 843 844 845 846 847 848 849 850 851
                                                        G_TYPE_IO_STREAM,
                                                        G_PARAM_READABLE |
                                                        G_PARAM_WRITABLE |
                                                        G_PARAM_CONSTRUCT_ONLY |
                                                        G_PARAM_STATIC_NAME |
                                                        G_PARAM_STATIC_BLURB |
                                                        G_PARAM_STATIC_NICK));

  /**
   * GDBusConnection:address:
   *
   * A D-Bus address specifying potential endpoints that can be used
   * when establishing the connection.
852 853
   *
   * Since: 2.26
854 855 856 857
   */
  g_object_class_install_property (gobject_class,
                                   PROP_ADDRESS,
                                   g_param_spec_string ("address",
Matthias Clasen's avatar
Matthias Clasen committed
858 859
                                                        P_("Address"),
                                                        P_("D-Bus address specifying potential socket endpoints"),
860 861 862 863 864 865 866 867 868 869 870
                                                        NULL,
                                                        G_PARAM_WRITABLE |
                                                        G_PARAM_CONSTRUCT_ONLY |
                                                        G_PARAM_STATIC_NAME |
                                                        G_PARAM_STATIC_BLURB |
                                                        G_PARAM_STATIC_NICK));

  /**
   * GDBusConnection:flags:
   *
   * Flags from the #GDBusConnectionFlags enumeration.
871 872
   *
   * Since: 2.26
873 874 875 876
   */
  g_object_class_install_property (gobject_class,
                                   PROP_FLAGS,
                                   g_param_spec_flags ("flags",
Matthias Clasen's avatar
Matthias Clasen committed
877 878
                                                       P_("Flags"),
                                                       P_("Flags"),
879 880
                                                       G_TYPE_DBUS_CONNECTION_FLAGS,
                                                       G_DBUS_CONNECTION_FLAGS_NONE,
881
                                                       G_PARAM_READABLE |
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
                                                       G_PARAM_WRITABLE |
                                                       G_PARAM_CONSTRUCT_ONLY |
                                                       G_PARAM_STATIC_NAME |
                                                       G_PARAM_STATIC_BLURB |
                                                       G_PARAM_STATIC_NICK));

  /**
   * GDBusConnection:guid:
   *
   * The GUID of the peer performing the role of server when
   * authenticating.
   *
   * If you are constructing a #GDBusConnection and pass
   * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
   * #GDBusConnection:flags property then you MUST also set this
   * property to a valid guid.
   *
   * If you are constructing a #GDBusConnection and pass
   * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
   * #GDBusConnection:flags property you will be able to read the GUID
Matthias Clasen's avatar
Matthias Clasen committed
902
   * of the other peer here after the connection has been successfully
903
   * initialized.
904 905
   *
   * Since: 2.26
906 907 908 909
   */
  g_object_class_install_property (gobject_class,
                                   PROP_GUID,
                                   g_param_spec_string ("guid",
Matthias Clasen's avatar
Matthias Clasen committed
910 911
                                                        P_("GUID"),
                                                        P_("GUID of the server peer"),
912 913 914 915 916 917 918 919 920 921 922 923 924
                                                        NULL,
                                                        G_PARAM_READABLE |
                                                        G_PARAM_WRITABLE |
                                                        G_PARAM_CONSTRUCT_ONLY |
                                                        G_PARAM_STATIC_NAME |
                                                        G_PARAM_STATIC_BLURB |
                                                        G_PARAM_STATIC_NICK));

  /**
   * GDBusConnection:unique-name:
   *
   * The unique name as assigned by the message bus or %NULL if the
   * connection is not open or not a message bus connection.
925 926
   *
   * Since: 2.26
927 928 929 930
   */
  g_object_class_install_property (gobject_class,
                                   PROP_UNIQUE_NAME,
                                   g_param_spec_string ("unique-name",
Matthias Clasen's avatar
Matthias Clasen committed
931 932
                                                        P_("unique-name"),
                                                        P_("Unique name of bus connection"),
933 934 935 936 937 938 939 940 941 942
                                                        NULL,
                                                        G_PARAM_READABLE |
                                                        G_PARAM_STATIC_NAME |
                                                        G_PARAM_STATIC_BLURB |
                                                        G_PARAM_STATIC_NICK));

  /**
   * GDBusConnection:closed:
   *
   * A boolean specifying whether the connection has been closed.
943 944
   *
   * Since: 2.26
945 946 947 948
   */
  g_object_class_install_property (gobject_class,
                                   PROP_CLOSED,
                                   g_param_spec_boolean ("closed",
Matthias Clasen's avatar
Matthias Clasen committed
949 950
                                                         P_("Closed"),
                                                         P_("Whether the connection is closed"),
951 952 953 954 955 956 957 958 959 960
                                                         FALSE,
                                                         G_PARAM_READABLE |
                                                         G_PARAM_STATIC_NAME |
                                                         G_PARAM_STATIC_BLURB |
                                                         G_PARAM_STATIC_NICK));

  /**
   * GDBusConnection:exit-on-close:
   *
   * A boolean specifying whether the process will be terminated (by
961 962
   * calling `raise(SIGTERM)`) if the connection is closed by the
   * remote peer.
963
   *
964 965
   * Note that #GDBusConnection objects returned by g_bus_get_finish()
   * and g_bus_get_sync() will (usually) have this property set to %TRUE.
966
   *
967
   * Since: 2.26
968 969 970 971
   */
  g_object_class_install_property (gobject_class,
                                   PROP_EXIT_ON_CLOSE,
                                   g_param_spec_boolean ("exit-on-close",
Matthias Clasen's avatar
Matthias Clasen committed
972 973
                                                         P_("Exit on close"),
                                                         P_("Whether the process is terminated when the connection is closed"),
974 975 976 977 978 979 980 981 982 983 984 985
                                                         FALSE,
                                                         G_PARAM_READABLE |
                                                         G_PARAM_WRITABLE |
                                                         G_PARAM_STATIC_NAME |
                                                         G_PARAM_STATIC_BLURB |
                                                         G_PARAM_STATIC_NICK));

  /**
   * GDBusConnection:capabilities:
   *
   * Flags from the #GDBusCapabilityFlags enumeration
   * representing connection features negotiated with the other peer.
986 987
   *
   * Since: 2.26
988 989 990 991
   */
  g_object_class_install_property (gobject_class,
                                   PROP_CAPABILITY_FLAGS,
                                   g_param_spec_flags ("capabilities",
Matthias Clasen's avatar
Matthias Clasen committed
992 993
                                                       P_("Capabilities"),
                                                       P_("Capabilities"),
994 995 996 997 998 999 1000 1001 1002 1003 1004
                                                       G_TYPE_DBUS_CAPABILITY_FLAGS,
                                                       G_DBUS_CAPABILITY_FLAGS_NONE,
                                                       G_PARAM_READABLE |
                                                       G_PARAM_STATIC_NAME |
                                                       G_PARAM_STATIC_BLURB |
                                                       G_PARAM_STATIC_NICK));

  /**
   * GDBusConnection:authentication-observer:
   *
   * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
1005 1006
   *
   * Since: 2.26
1007 1008 1009 1010
   */
  g_object_class_install_property (gobject_class,
                                   PROP_AUTHENTICATION_OBSERVER,
                                   g_param_spec_object ("authentication-observer",
Matthias Clasen's avatar
Matthias Clasen committed
1011 1012
                                                        P_("Authentication Observer"),
                                                        P_("Object used to assist in the authentication process"),
1013 1014 1015 1016 1017 1018 1019 1020 1021
                                                        G_TYPE_DBUS_AUTH_OBSERVER,
                                                        G_PARAM_WRITABLE |
                                                        G_PARAM_CONSTRUCT_ONLY |
                                                        G_PARAM_STATIC_NAME |
                                                        G_PARAM_STATIC_BLURB |
                                                        G_PARAM_STATIC_NICK));

  /**
   * GDBusConnection::closed:
1022
   * @connection: the #GDBusConnection emitting the signal
1023
   * @remote_peer_vanished: %TRUE if @connection is closed because the
1024
   *     remote peer closed its end of the connection
1025
   * @error: (nullable): a #GError with more details about the event or %NULL
1026 1027 1028 1029
   *
   * Emitted when the connection is closed.
   *
   * The cause of this event can be
1030 1031 1032 1033 1034 1035 1036 1037 1038
   *
   * - If g_dbus_connection_close() is called. In this case
   *   @remote_peer_vanished is set to %FALSE and @error is %NULL.
   *
   * - If the remote peer closes the connection. In this case
   *   @remote_peer_vanished is set to %TRUE and @error is set.
   *
   * - If the remote peer sends invalid or malformed data. In this
   *   case @remote_peer_vanished is set to %FALSE and @error is set.
1039 1040 1041 1042
   *
   * Upon receiving this signal, you should give up your reference to
   * @connection. You are guaranteed that this signal is emitted only
   * once.
1043 1044
   *
   * Since: 2.26
1045
   */
1046
  signals[CLOSED_SIGNAL] = g_signal_new (I_("closed"),
1047 1048 1049 1050 1051
                                         G_TYPE_DBUS_CONNECTION,
                                         G_SIGNAL_RUN_LAST,
                                         G_STRUCT_OFFSET (GDBusConnectionClass, closed),
                                         NULL,
                                         NULL,
1052
                                         NULL,
1053 1054 1055 1056 1057 1058 1059 1060 1061
                                         G_TYPE_NONE,
                                         2,
                                         G_TYPE_BOOLEAN,
                                         G_TYPE_ERROR);
}

static void
g_dbus_connection_init (GDBusConnection *connection)
{
1062 1063
  g_mutex_init (&connection->lock);
  g_mutex_init (&connection->init_lock);
1064

1065
  connection->map_method_serial_to_task = g_hash_table_new (g_direct_hash, g_direct_equal);
1066

1067 1068 1069 1070 1071 1072 1073
  connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
                                                          g_str_equal);
  connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
                                                        g_direct_equal);
  connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
                                                                                   g_str_equal,
                                                                                   g_free,
Christian Persch's avatar
Christian Persch committed
1074
                                                                                   (GDestroyNotify) g_ptr_array_unref);
1075

1076 1077 1078 1079
  connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
                                                             g_str_equal,
                                                             NULL,
                                                             (GDestroyNotify) exported_object_free);
1080

1081 1082
  connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
                                               g_direct_equal);
1083

1084 1085 1086 1087
  connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
                                                             g_str_equal,
                                                             NULL,
                                                             (GDestroyNotify) exported_subtree_free);
1088

1089 1090
  connection->map_id_to_es = g_hash_table_new (g_direct_hash,
                                               g_direct_equal);
1091

1092 1093 1094
  connection->map_thread_to_last_serial = g_hash_table_new (g_direct_hash,
                                                            g_direct_equal);

1095
  connection->main_context_at_construction = g_main_context_ref_thread_default ();
1096

1097
  connection->filters = g_ptr_array_new ();
1098 1099
}

Matthias Clasen's avatar
Matthias Clasen committed
1100 1101 1102 1103 1104 1105
/**
 * g_dbus_connection_get_stream:
 * @connection: a #GDBusConnection
 *
 * Gets the underlying stream used for IO.
 *
1106 1107 1108 1109
 * While the #GDBusConnection is active, it will interact with this
 * stream from a worker thread, so it is not safe to interact with
 * the stream directly.
 *
1110
 * Returns: (transfer none): the stream used for IO
Matthias Clasen's avatar
Matthias Clasen committed
1111 1112 1113
 *
 * Since: 2.26
 */
1114 1115 1116 1117
GIOStream *
g_dbus_connection_get_stream (GDBusConnection *connection)
{
  g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1118 1119 1120 1121 1122

  /* do not use g_return_val_if_fail(), we want the memory barrier */
  if (!check_initialized (connection))
    return NULL;

1123
  return connection->stream;
1124 1125
}

1126 1127
/**
 * g_dbus_connection_start_message_processing:
1128
 * @connection: a #GDBusConnection
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
 *
 * If @connection was created with
 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
 * starts processing messages. Does nothing on if @connection wasn't
 * created with this flag or if the method has already been called.
 *
 * Since: 2.26
 */
void
g_dbus_connection_start_message_processing (GDBusConnection *connection)
{
  g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1141 1142 1143 1144 1145 1146

  /* do not use g_return_val_if_fail(), we want the memory barrier */
  if (!check_initialized (connection))
    return;

  g_assert (connection->worker != NULL);
1147
  _g_dbus_worker_unfreeze (connection->worker);
1148
}
1149 1150 1151

/**
 * g_dbus_connection_is_closed:
1152
 * @connection: a #GDBusConnection
1153 1154 1155
 *
 * Gets whether @connection is closed.
 *
1156
 * Returns: %TRUE if the connection is closed, %FALSE otherwise
1157 1158 1159
 *
 * Since: 2.26
 */
1160 1161 1162
gboolean
g_dbus_connection_is_closed (GDBusConnection *connection)
{
1163 1164
  gint flags;

1165
  g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1166 1167 1168 1169

  flags = g_atomic_int_get (&connection->atomic_flags);

  return (flags & FLAG_CLOSED) ? TRUE : FALSE;
1170 1171 1172 1173
}

/**
 * g_dbus_connection_get_capabilities:
1174
 * @connection: a #GDBusConnection
1175 1176 1177
 *
 * Gets the capabilities negotiated with the remote peer
 *
1178
 * Returns: zero or more flags from the #GDBusCapabilityFlags enumeration
1179 1180
 *
 * Since: 2.26
1181 1182 1183 1184 1185
 */
GDBusCapabilityFlags
g_dbus_connection_get_capabilities (GDBusConnection *connection)
{
  g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1186 1187 1188 1189 1190

  /* do not use g_return_val_if_fail(), we want the memory barrier */
  if (!check_initialized (connection))
    return G_DBUS_CAPABILITY_FLAGS_NONE;

1191
  return connection->capabilities;
1192 1193
}

1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
/**
 * g_dbus_connection_get_flags:
 * @connection: a #GDBusConnection
 *
 * Gets the flags used to construct this connection
 *
 * Returns: zero or more flags from the #GDBusConnectionFlags enumeration
 *
 * Since: 2.60
 */
GDBusConnectionFlags
g_dbus_connection_get_flags (GDBusConnection *connection)
{
  g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CONNECTION_FLAGS_NONE);

  /* do not use g_return_val_if_fail(), we want the memory barrier */
  if (!check_initialized (connection))
    return G_DBUS_CONNECTION_FLAGS_NONE;

  return connection->flags;
}

1216 1217
/* ---------------------------------------------------------------------------------------------------- */

1218
/* Called in a temporary thread without holding locks. */
1219
static void
1220 1221 1222 1223
flush_in_thread_func (GTask         *task,
                      gpointer       source_object,
                      gpointer       task_data,
                      GCancellable  *cancellable)
1224
{
1225
  GError *error = NULL;
1226

1227 1228 1229 1230 1231 1232
  if (g_dbus_connection_flush_sync (source_object,
                                    cancellable,
                                    &error))
    g_task_return_boolean (task, TRUE);
  else
    g_task_return_error (task, error);
1233 1234 1235 1236
}

/**
 * g_dbus_connection_flush:
1237
 * @connection: a #GDBusConnection
1238 1239
 * @cancellable: (nullable): a #GCancellable or %NULL
 * @callback: (nullable): a #GAsyncReadyCallback to call when the
1240 1241
 *     request is satisfied or %NULL if you don't care about the result
 * @user_data: The data to pass to @callback
1242 1243 1244 1245
 *
 * Asynchronously flushes @connection, that is, writes all queued
 * outgoing message to the transport and then flushes the transport
 * (using g_output_stream_flush_async()). This is useful in programs
1246 1247 1248
 * that wants to emit a D-Bus signal and then exit immediately. Without
 * flushing the connection, there is no guaranteed that the message has
 * been sent to the networking buffers in the OS kernel.
1249 1250
 *
 * This is an asynchronous method. When the operation is finished,
1251 1252 1253
 * @callback will be invoked in the
 * [thread-default main context][g-main-context-push-thread-default]
 * of the thread you are calling this method from. You can
1254
 * then call g_dbus_connection_flush_finish() to get the result of the
1255
 * operation. See g_dbus_connection_flush_sync() for the synchronous
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
 * version.
 *
 * Since: 2.26
 */
void
g_dbus_connection_flush (GDBusConnection     *connection,
                         GCancellable        *cancellable,
                         GAsyncReadyCallback  callback,
                         gpointer             user_data)
{
1266
  GTask *task;
1267 1268 1269

  g_return_if_fail (G_IS_DBUS_CONNECTION (connection));

1270
  task = g_task_new (connection, cancellable, callback, user_data);
1271
  g_task_set_source_tag (task, g_dbus_connection_flush);
1272 1273
  g_task_run_in_thread (task, flush_in_thread_func);
  g_object_unref (task);
1274 1275 1276 1277
}

/**
 * g_dbus_connection_flush_finish:
1278 1279 1280 1281
 * @connection: a #GDBusConnection
 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
 *     to g_dbus_connection_flush()
 * @error: return location for error or %NULL
1282 1283 1284
 *
 * Finishes an operation started with g_dbus_connection_flush().
 *
1285
 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1286 1287 1288 1289 1290 1291 1292 1293 1294
 *
 * Since: 2.26
 */
gboolean
g_dbus_connection_flush_finish (GDBusConnection  *connection,
                                GAsyncResult     *res,
                                GError          **error)
{
  g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1295
  g_return_val_if_fail (g_task_is_valid (res, connection), FALSE);
1296 1297
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

1298
  return g_task_propagate_boolean (G_TASK (res), error);
1299 1300 1301 1302
}

/**
 * g_dbus_connection_flush_sync:
1303
 * @connection: a #GDBusConnection
1304
 * @cancellable: (nullable): a #GCancellable or %NULL
1305
 * @error: return location for error or %NULL
1306 1307 1308 1309 1310 1311
 *
 * Synchronously flushes @connection. The calling thread is blocked
 * until this is done. See g_dbus_connection_flush() for the
 * asynchronous version of this method and more details about what it
 * does.
 *
1312
 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
 *
 * Since: 2.26
 */
gboolean
g_dbus_connection_flush_sync (GDBusConnection  *connection,
                              GCancellable     *cancellable,
                              GError          **error)
{
  gboolean ret;

  g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1324
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1325 1326 1327

  ret = FALSE;

1328 1329 1330 1331 1332 1333 1334 1335
  /* This is only a best-effort attempt to see whether the connection is
   * closed, so it doesn't need the lock. If the connection closes just
   * after this check, but before scheduling the flush operation, the
   * result will be more or less the same as if the connection closed while
   * the flush operation was pending - it'll fail with either CLOSED or
   * CANCELLED.
   */
  if (!check_unclosed (connection, 0, error))
1336 1337 1338 1339
    goto out;

  g_assert (connection->worker != NULL);

1340
  ret = _g_dbus_worker_flush_sync (connection->worker,
1341 1342 1343 1344 1345 1346
                                   cancellable,
                                   error);

 out:
  return ret;
}
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365

/* ---------------------------------------------------------------------------------------------------- */

typedef struct
{
  GDBusConnection *connection;
  GError *error;
  gboolean remote_peer_vanished;
} EmitClosedData;

static void
emit_closed_data_free (EmitClosedData *data)
{
  g_object_unref (data->connection);
  if (data->error != NULL)
    g_error_free (data->error);
  g_free (data);
}

1366 1367 1368
/* Called in a user thread that has acquired the main context that was
 * thread-default when the object was constructed
 */
1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
static gboolean
emit_closed_in_idle (gpointer user_data)
{
  EmitClosedData *data = user_data;
  gboolean result;

  g_object_notify (G_OBJECT (data->connection), "closed");
  g_signal_emit (data->connection,
                 signals[CLOSED_SIGNAL],
                 0,
                 data->remote_peer_vanished,
                 data->error,
                 &result);
  return FALSE;
}

1385 1386 1387
/* Can be called from any thread, must hold lock.
 * FLAG_CLOSED must already have been set.
 */
1388
static void
1389 1390 1391
schedule_closed_unlocked (GDBusConnection *connection,
                          gboolean         remote_peer_vanished,
                          GError          *error)
1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408
{
  GSource *idle_source;
  EmitClosedData *data;

  CONNECTION_ENSURE_LOCK (connection);

  data = g_new0 (EmitClosedData, 1);
  data->connection = g_object_ref (connection);
  data->remote_peer_vanished = remote_peer_vanished;
  data->error = error != NULL ? g_error_copy (error) : NULL;

  idle_source = g_idle_source_new ();
  g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
  g_source_set_callback (idle_source,
                         emit_closed_in_idle,
                         data,
                         (GDestroyNotify) emit_closed_data_free);
1409
  g_source_set_name (idle_source, "[gio] emit_closed_in_idle");
1410
  g_source_attach (idle_source, connection->main_context_at_construction);
1411 1412 1413 1414 1415 1416 1417
  g_source_unref (idle_source);
}

/* ---------------------------------------------------------------------------------------------------- */

/**
 * g_dbus_connection_close:
1418
 * @connection: a #GDBusConnection
1419 1420
 * @cancellable: (nullable): a #GCancellable or %NULL
 * @callback: (nullable): a #GAsyncReadyCallback to call when the request is
1421 1422
 *     satisfied or %NULL if you don't care about the result
 * @user_data: The data to pass to @callback
1423 1424 1425
 *
 * Closes @connection. Note that this never causes the process to
 * exit (this might only happen if the other end of a shared message
1426 1427
 * bus connection disconnects, see #GDBusConnection:exit-on-close).
 *
1428 1429 1430 1431 1432 1433
 * Once the connection is closed, operations such as sending a message
 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
 * will not automatically flush the connection so queued messages may
 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
 *
 * If @connection is already closed, this method fails with
1434 1435
 * %G_IO_ERROR_CLOSED.
 *
1436
 * When @connection has been closed, the #GDBusConnection::closed
1437 1438 1439
 * signal is emitted in the
 * [thread-default main context][g-main-context-push-thread-default]
 * of the thread that @connection was constructed in.
1440
 *
1441
 * This is an asynchronous method. When the operation is finished,
1442 1443 1444
 * @callback will be invoked in the 
 * [thread-default main context][g-main-context-push-thread-default]
 * of the thread you are calling this method from. You can
1445
 * then call g_dbus_connection_close_finish() to get the result of the
1446
 * operation. See g_dbus_connection_close_sync() for the synchronous
1447
 * version.
1448 1449
 *
 * Since: 2.26
1450 1451
 */
void
1452 1453 1454 1455
g_dbus_connection_close (GDBusConnection     *connection,
                         GCancellable        *cancellable,
                         GAsyncReadyCallback  callback,
                         gpointer             user_data)
1456
{
1457
  GTask *task;
1458

1459 1460
  g_return_if_fail (G_IS_DBUS_CONNECTION (connection));

1461 1462 1463 1464 1465 1466
  /* do not use g_return_val_if_fail(), we want the memory barrier */
  if (!check_initialized (connection))
    return;

  g_assert (connection->worker != NULL);

1467
  task = g_task_new (connection, cancellable, callback, user_data);
1468
  g_task_set_source_tag (task, g_dbus_connection_close);
1469 1470
  _g_dbus_worker_close (connection->worker, task);
  g_object_unref (task);
1471 1472 1473 1474
}

/**
 * g_dbus_connection_close_finish:
1475 1476 1477 1478
 * @connection: a #GDBusConnection
 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
 *     to g_dbus_connection_close()
 * @error: return location for error or %NULL
1479 1480 1481
 *
 * Finishes an operation started with g_dbus_connection_close().
 *
1482
 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1483 1484 1485 1486 1487 1488 1489 1490 1491
 *
 * Since: 2.26
 */
gboolean
g_dbus_connection_close_finish (GDBusConnection  *connection,
                                GAsyncResult     *res,
                                GError          **error)
{
  g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1492
  g_return_val_if_fail (g_task_is_valid (res, connection), FALSE);
1493 1494
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

1495
  return g_task_propagate_boolean (G_TASK (res), error);
1496 1497
}

1498 1499 1500 1501 1502
typedef struct {
    GMainLoop *loop;
    GAsyncResult *result;
} SyncCloseData;

1503
/* Can be called by any thread, without the connection lock */
1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
static void
sync_close_cb (GObject *source_object,
               GAsyncResult *res,
               gpointer user_data)
{
  SyncCloseData *data = user_data;

  data->result = g_object_ref (res);
  g_main_loop_quit (data->loop);
}

1515 1516
/**
 * g_dbus_connection_close_sync:
1517
 * @connection: a #GDBusConnection
1518
 * @cancellable: (nullable): a #GCancellable or %NULL
1519
 * @error: return location for error or %NULL
1520
 *
1521
 * Synchronously closes @connection. The calling thread is blocked
1522 1523 1524 1525
 * until this is done. See g_dbus_connection_close() for the
 * asynchronous version of this method and more details about what it
 * does.
 *
1526
 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1527 1528 1529 1530
 *
 * Since: 2.26
 */
gboolean
1531 1532 1533
g_dbus_connection_close_sync (GDBusConnection  *connection,
                              GCancellable     *cancellable,
                              GError          **error)
1534 1535 1536 1537 1538 1539 1540 1541
{
  gboolean ret;

  g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

  ret = FALSE;

1542
  if (check_unclosed (connection, 0, error))
Matthias Clasen's avatar
Matthias Clasen committed
1543
    {
1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559
      GMainContext *context;
      SyncCloseData data;

      context = g_main_context_new ();
      g_main_context_push_thread_default (context);
      data.loop = g_main_loop_new (context, TRUE);
      data.result = NULL;

      g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
      g_main_loop_run (data.loop);
      ret = g_dbus_connection_close_finish (connection, data.result, error);

      g_object_unref (data.result);
      g_main_loop_unref (data.loop);
      g_main_context_pop_thread_default (context);
      g_main_context_unref (context);
1560 1561 1562
    }

  return ret;
1563 1564 1565 1566
}

/* ---------------------------------------------------------------------------------------------------- */

1567 1568
/**
 * g_dbus_connection_get_last_serial:
1569
 * @connection: a #GDBusConnection
1570 1571 1572 1573 1574 1575 1576 1577
 *
 * Retrieves the last serial number assigned to a #GDBusMessage on
 * the current thread. This includes messages sent via both low-level
 * API such as g_dbus_connection_send_message() as well as
 * high-level API such as g_dbus_connection_emit_signal(),
 * g_dbus_connection_call() or g_dbus_proxy_call().
 *
 * Returns: the last used serial or zero when no message has been sent
1578
 *     within the current thread
1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
 *
 * Since: 2.34
 */
guint32
g_dbus_connection_get_last_serial (GDBusConnection *connection)
{
  guint32 ret;

  g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);

  CONNECTION_LOCK (connection);
  ret = GPOINTER_TO_UINT (g_hash_table_lookup (connection->map_thread_to_last_serial,
                                               g_thread_self ()));
  CONNECTION_UNLOCK (connection);

  return ret;
}

/* ---------------------------------------------------------------------------------------------------- */

1599
/* Can be called by any thread, with the connection lock held */
1600
static gboolean
Matthias Clasen's avatar
Matthias Clasen committed
1601 1602
g_dbus_connection_send_message_unlocked (GDBusConnection   *connection,
                                         GDBusMessage      *message,
1603
                                         GDBusSendMessageFlags flags,
Matthias Clasen's avatar
Matthias Clasen committed
1604 1605
                                         volatile guint32  *out_serial,
                                         GError           **error)
1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624
{
  guchar *blob;
  gsize blob_size;
  guint32 serial_to_use;
  gboolean ret;

  CONNECTION_ENSURE_LOCK (connection);

  g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
  g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);

  /* TODO: check all necessary headers are present */

  ret = FALSE;
  blob = NULL;

  if (out_serial != NULL)
    *out_serial = 0;

1625 1626 1627 1628 1629
  /* If we're in initable_init(), don't check for being initialized, to avoid
   * chicken-and-egg problems. initable_init() is responsible for setting up
   * our prerequisites (mainly connection->worker), and only calling us
   * from its own thread (so no memory barrier is needed).
   */
1630 1631 1632
  if (!check_unclosed (connection,
                       (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
                       error))
1633 1634
    goto out;

1635 1636
  blob = g_dbus_message_to_blob (message,
                                 &blob_size,
1637
                                 connection->capabilities,
1638 1639 1640 1641
                                 error);
  if (blob == NULL)
    goto out;

1642 1643 1644 1645
  if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
    serial_to_use = g_dbus_message_get_serial (message);
  else
    serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667

  switch (blob[0])
    {
    case 'l':
      ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
      break;
    case 'B':
      ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
      break;
    default:
      g_assert_not_reached ();
      break;
    }

#if 0
  g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
              blob_size, serial_to_use, connection);
  g_printerr ("----\n");
  hexdump (blob, blob_size);
  g_printerr ("----\n");
#endif

1668
  /* TODO: use connection->auth to encode the blob */
1669 1670

  if (out_serial != NULL)
Matthias Clasen's avatar
Matthias Clasen committed
1671 1672
    *out_serial = serial_to_use;

1673 1674 1675 1676 1677 1678 1679 1680 1681
  /* store used serial for the current thread */
  /* TODO: watch the thread disposal and remove associated record
   *       from hashtable
   *  - see https://bugzilla.gnome.org/show_bug.cgi?id=676825#c7
   */
  g_hash_table_replace (connection->map_thread_to_last_serial,
                        g_thread_self (),
                        GUINT_TO_POINTER (serial_to_use));

1682 1683
  if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
    g_dbus_message_set_serial (message, serial_to_use);
1684

1685
  g_dbus_message_lock (message);
1686
  _g_dbus_worker_send_message (connection->worker,
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
                               message,
                               (gchar*) blob,
                               blob_size);
  blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */

  ret = TRUE;

 out:
  g_free (blob);

  return ret;
}

/**
 * g_dbus_connection_send_message:
1702 1703 1704
 * @connection: a #GDBusConnection
 * @message: a #GDBusMessage
 * @flags: flags affecting how the message is sent
1705
 * @out_serial: (out) (optional): return location for serial number assigned