gdbusconnection.c 263 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 731 732 733 734 735 736
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;

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

737
/* called in any user thread, with the connection's lock not held */
738 739 740 741 742 743 744 745 746 747 748
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:
749
      connection->stream = g_value_dup_object (value);
750 751 752
      break;

    case PROP_GUID:
753
      connection->guid = g_value_dup_string (value);
754 755 756
      break;

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

    case PROP_FLAGS:
761
      connection->flags = g_value_get_flags (value);
762 763 764 765 766 767 768
      break;

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

    case PROP_AUTHENTICATION_OBSERVER:
769
      connection->authentication_observer = g_value_dup_object (value);
770 771 772 773 774 775 776 777
      break;

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

778 779 780 781 782
/* Base-class implementation of GDBusConnection::closed.
 *
 * Called in a user thread, by the main context that was thread-default when
 * the object was constructed.
 */
783 784 785 786 787
static void
g_dbus_connection_real_closed (GDBusConnection *connection,
                               gboolean         remote_peer_vanished,
                               GError          *error)
{
788 789 790 791 792
  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.
   */
793 794
  if (remote_peer_vanished &&
      (flags & FLAG_EXIT_ON_CLOSE) != 0 &&
795 796
      (flags & FLAG_INITIALIZED) != 0 &&
      connection->initialization_error == NULL)
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
    {
      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.
820
   *
821 822 823
   * If this is passed on construction and is a #GSocketConnection,
   * then the corresponding #GSocket will be put into non-blocking mode.
   *
824 825 826 827
   * 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.
   *
828
   * Since: 2.26
829 830 831 832
   */
  g_object_class_install_property (gobject_class,
                                   PROP_STREAM,
                                   g_param_spec_object ("stream",
Matthias Clasen's avatar
Matthias Clasen committed
833 834
                                                        P_("IO Stream"),
                                                        P_("The underlying streams used for I/O"),
835 836 837 838 839 840 841 842 843 844 845 846 847
                                                        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.
848 849
   *
   * Since: 2.26
850 851 852 853
   */
  g_object_class_install_property (gobject_class,
                                   PROP_ADDRESS,
                                   g_param_spec_string ("address",
Matthias Clasen's avatar
Matthias Clasen committed
854 855
                                                        P_("Address"),
                                                        P_("D-Bus address specifying potential socket endpoints"),
856 857 858 859 860 861 862 863 864 865 866
                                                        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.
867 868
   *
   * Since: 2.26
869 870 871 872
   */
  g_object_class_install_property (gobject_class,
                                   PROP_FLAGS,
                                   g_param_spec_flags ("flags",
Matthias Clasen's avatar
Matthias Clasen committed
873 874
                                                       P_("Flags"),
                                                       P_("Flags"),
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
                                                       G_TYPE_DBUS_CONNECTION_FLAGS,
                                                       G_DBUS_CONNECTION_FLAGS_NONE,
                                                       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
897
   * of the other peer here after the connection has been successfully
898
   * initialized.
899 900
   *
   * Since: 2.26
901 902 903 904
   */
  g_object_class_install_property (gobject_class,
                                   PROP_GUID,
                                   g_param_spec_string ("guid",
Matthias Clasen's avatar
Matthias Clasen committed
905 906
                                                        P_("GUID"),
                                                        P_("GUID of the server peer"),
907 908 909 910 911 912 913 914 915 916 917 918 919
                                                        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.
920 921
   *
   * Since: 2.26
922 923 924 925
   */
  g_object_class_install_property (gobject_class,
                                   PROP_UNIQUE_NAME,
                                   g_param_spec_string ("unique-name",
Matthias Clasen's avatar
Matthias Clasen committed
926 927
                                                        P_("unique-name"),
                                                        P_("Unique name of bus connection"),
928 929 930 931 932 933 934 935 936 937
                                                        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.
938 939
   *
   * Since: 2.26
940 941 942 943
   */
  g_object_class_install_property (gobject_class,
                                   PROP_CLOSED,
                                   g_param_spec_boolean ("closed",
Matthias Clasen's avatar
Matthias Clasen committed
944 945
                                                         P_("Closed"),
                                                         P_("Whether the connection is closed"),
946 947 948 949 950 951 952 953 954 955
                                                         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
956 957
   * calling `raise(SIGTERM)`) if the connection is closed by the
   * remote peer.
958
   *
959 960
   * Note that #GDBusConnection objects returned by g_bus_get_finish()
   * and g_bus_get_sync() will (usually) have this property set to %TRUE.
961
   *
962
   * Since: 2.26
963 964 965 966
   */
  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
967 968
                                                         P_("Exit on close"),
                                                         P_("Whether the process is terminated when the connection is closed"),
969 970 971 972 973 974 975 976 977 978 979 980
                                                         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.
981 982
   *
   * Since: 2.26
983 984 985 986
   */
  g_object_class_install_property (gobject_class,
                                   PROP_CAPABILITY_FLAGS,
                                   g_param_spec_flags ("capabilities",
Matthias Clasen's avatar
Matthias Clasen committed
987 988
                                                       P_("Capabilities"),
                                                       P_("Capabilities"),
989 990 991 992 993 994 995 996 997 998 999
                                                       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.
1000 1001
   *
   * Since: 2.26
1002 1003 1004 1005
   */
  g_object_class_install_property (gobject_class,
                                   PROP_AUTHENTICATION_OBSERVER,
                                   g_param_spec_object ("authentication-observer",
Matthias Clasen's avatar
Matthias Clasen committed
1006 1007
                                                        P_("Authentication Observer"),
                                                        P_("Object used to assist in the authentication process"),
1008 1009 1010 1011 1012 1013 1014 1015 1016
                                                        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:
1017
   * @connection: the #GDBusConnection emitting the signal
1018
   * @remote_peer_vanished: %TRUE if @connection is closed because the
1019
   *     remote peer closed its end of the connection
1020
   * @error: (nullable): a #GError with more details about the event or %NULL
1021 1022 1023 1024
   *
   * Emitted when the connection is closed.
   *
   * The cause of this event can be
1025 1026 1027 1028 1029 1030 1031 1032 1033
   *
   * - 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.
1034 1035 1036 1037
   *
   * Upon receiving this signal, you should give up your reference to
   * @connection. You are guaranteed that this signal is emitted only
   * once.
1038 1039
   *
   * Since: 2.26
1040
   */
1041
  signals[CLOSED_SIGNAL] = g_signal_new (I_("closed"),
1042 1043 1044 1045 1046
                                         G_TYPE_DBUS_CONNECTION,
                                         G_SIGNAL_RUN_LAST,
                                         G_STRUCT_OFFSET (GDBusConnectionClass, closed),
                                         NULL,
                                         NULL,
1047
                                         NULL,
1048 1049 1050 1051 1052 1053 1054 1055 1056
                                         G_TYPE_NONE,
                                         2,
                                         G_TYPE_BOOLEAN,
                                         G_TYPE_ERROR);
}

static void
g_dbus_connection_init (GDBusConnection *connection)
{
1057 1058
  g_mutex_init (&connection->lock);
  g_mutex_init (&connection->init_lock);
1059

1060
  connection->map_method_serial_to_task = g_hash_table_new (g_direct_hash, g_direct_equal);
1061

1062 1063 1064 1065 1066 1067 1068
  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
1069
                                                                                   (GDestroyNotify) g_ptr_array_unref);
1070

1071 1072 1073 1074
  connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
                                                             g_str_equal,
                                                             NULL,
                                                             (GDestroyNotify) exported_object_free);
1075

1076 1077
  connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
                                               g_direct_equal);
1078

1079 1080 1081 1082
  connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
                                                             g_str_equal,
                                                             NULL,
                                                             (GDestroyNotify) exported_subtree_free);
1083

1084 1085
  connection->map_id_to_es = g_hash_table_new (g_direct_hash,
                                               g_direct_equal);
1086

1087 1088 1089
  connection->map_thread_to_last_serial = g_hash_table_new (g_direct_hash,
                                                            g_direct_equal);

1090
  connection->main_context_at_construction = g_main_context_ref_thread_default ();
1091

1092
  connection->filters = g_ptr_array_new ();
1093 1094
}

Matthias Clasen's avatar
Matthias Clasen committed
1095 1096 1097 1098 1099 1100
/**
 * g_dbus_connection_get_stream:
 * @connection: a #GDBusConnection
 *
 * Gets the underlying stream used for IO.
 *
1101 1102 1103 1104
 * 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.
 *
1105
 * Returns: (transfer none): the stream used for IO
Matthias Clasen's avatar
Matthias Clasen committed
1106 1107 1108
 *
 * Since: 2.26
 */
1109 1110 1111 1112
GIOStream *
g_dbus_connection_get_stream (GDBusConnection *connection)
{
  g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1113 1114 1115 1116 1117

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

1118
  return connection->stream;
1119 1120
}

1121 1122
/**
 * g_dbus_connection_start_message_processing:
1123
 * @connection: a #GDBusConnection
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
 *
 * 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));
1136 1137 1138 1139 1140 1141

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

  g_assert (connection->worker != NULL);
1142
  _g_dbus_worker_unfreeze (connection->worker);
1143
}
1144 1145 1146

/**
 * g_dbus_connection_is_closed:
1147
 * @connection: a #GDBusConnection
1148 1149 1150
 *
 * Gets whether @connection is closed.
 *
1151
 * Returns: %TRUE if the connection is closed, %FALSE otherwise
1152 1153 1154
 *
 * Since: 2.26
 */
1155 1156 1157
gboolean
g_dbus_connection_is_closed (GDBusConnection *connection)
{
1158 1159
  gint flags;

1160
  g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1161 1162 1163 1164

  flags = g_atomic_int_get (&connection->atomic_flags);

  return (flags & FLAG_CLOSED) ? TRUE : FALSE;
1165 1166 1167 1168
}

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

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

1186
  return connection->capabilities;
1187 1188
}

1189 1190
/* ---------------------------------------------------------------------------------------------------- */

1191
/* Called in a temporary thread without holding locks. */
1192
static void
1193 1194 1195 1196
flush_in_thread_func (GTask         *task,
                      gpointer       source_object,
                      gpointer       task_data,
                      GCancellable  *cancellable)
1197
{
1198
  GError *error = NULL;
1199

1200 1201 1202 1203 1204 1205
  if (g_dbus_connection_flush_sync (source_object,
                                    cancellable,
                                    &error))
    g_task_return_boolean (task, TRUE);
  else
    g_task_return_error (task, error);
1206 1207 1208 1209
}

/**
 * g_dbus_connection_flush:
1210
 * @connection: a #GDBusConnection
1211 1212
 * @cancellable: (nullable): a #GCancellable or %NULL
 * @callback: (nullable): a #GAsyncReadyCallback to call when the
1213 1214
 *     request is satisfied or %NULL if you don't care about the result
 * @user_data: The data to pass to @callback
1215 1216 1217 1218
 *
 * 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
1219 1220 1221
 * 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.
1222 1223
 *
 * This is an asynchronous method. When the operation is finished,
1224 1225 1226
 * @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
1227
 * then call g_dbus_connection_flush_finish() to get the result of the
1228
 * operation. See g_dbus_connection_flush_sync() for the synchronous
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
 * version.
 *
 * Since: 2.26
 */
void
g_dbus_connection_flush (GDBusConnection     *connection,
                         GCancellable        *cancellable,
                         GAsyncReadyCallback  callback,
                         gpointer             user_data)
{
1239
  GTask *task;
1240 1241 1242

  g_return_if_fail (G_IS_DBUS_CONNECTION (connection));

1243
  task = g_task_new (connection, cancellable, callback, user_data);
1244
  g_task_set_source_tag (task, g_dbus_connection_flush);
1245 1246
  g_task_run_in_thread (task, flush_in_thread_func);
  g_object_unref (task);
1247 1248 1249 1250
}

/**
 * g_dbus_connection_flush_finish:
1251 1252 1253 1254
 * @connection: a #GDBusConnection
 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
 *     to g_dbus_connection_flush()
 * @error: return location for error or %NULL
1255 1256 1257
 *
 * Finishes an operation started with g_dbus_connection_flush().
 *
1258
 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1259 1260 1261 1262 1263 1264 1265 1266 1267
 *
 * 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);
1268
  g_return_val_if_fail (g_task_is_valid (res, connection), FALSE);
1269 1270
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

1271
  return g_task_propagate_boolean (G_TASK (res), error);
1272 1273 1274 1275
}

/**
 * g_dbus_connection_flush_sync:
1276
 * @connection: a #GDBusConnection
1277
 * @cancellable: (nullable): a #GCancellable or %NULL
1278
 * @error: return location for error or %NULL
1279 1280 1281 1282 1283 1284
 *
 * 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.
 *
1285
 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
 *
 * 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);
1297
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1298 1299 1300

  ret = FALSE;

1301 1302 1303 1304 1305 1306 1307 1308
  /* 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))
1309 1310 1311 1312
    goto out;

  g_assert (connection->worker != NULL);

1313
  ret = _g_dbus_worker_flush_sync (connection->worker,
1314 1315 1316 1317 1318 1319
                                   cancellable,
                                   error);

 out:
  return ret;
}
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338

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

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);
}

1339 1340 1341
/* Called in a user thread that has acquired the main context that was
 * thread-default when the object was constructed
 */
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
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;
}

1358 1359 1360
/* Can be called from any thread, must hold lock.
 * FLAG_CLOSED must already have been set.
 */
1361
static void
1362 1363 1364
schedule_closed_unlocked (GDBusConnection *connection,
                          gboolean         remote_peer_vanished,
                          GError          *error)
1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
{
  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);
1382
  g_source_set_name (idle_source, "[gio] emit_closed_in_idle");
1383
  g_source_attach (idle_source, connection->main_context_at_construction);
1384 1385 1386 1387 1388 1389 1390
  g_source_unref (idle_source);
}

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

/**
 * g_dbus_connection_close:
1391
 * @connection: a #GDBusConnection
1392 1393
 * @cancellable: (nullable): a #GCancellable or %NULL
 * @callback: (nullable): a #GAsyncReadyCallback to call when the request is
1394 1395
 *     satisfied or %NULL if you don't care about the result
 * @user_data: The data to pass to @callback
1396 1397 1398
 *
 * Closes @connection. Note that this never causes the process to
 * exit (this might only happen if the other end of a shared message
1399 1400
 * bus connection disconnects, see #GDBusConnection:exit-on-close).
 *
1401 1402 1403 1404 1405 1406
 * 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
1407 1408
 * %G_IO_ERROR_CLOSED.
 *
1409
 * When @connection has been closed, the #GDBusConnection::closed
1410 1411 1412
 * signal is emitted in the
 * [thread-default main context][g-main-context-push-thread-default]
 * of the thread that @connection was constructed in.
1413
 *
1414
 * This is an asynchronous method. When the operation is finished,
1415 1416 1417
 * @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
1418
 * then call g_dbus_connection_close_finish() to get the result of the
1419
 * operation. See g_dbus_connection_close_sync() for the synchronous
1420
 * version.
1421 1422
 *
 * Since: 2.26
1423 1424
 */
void
1425 1426 1427 1428
g_dbus_connection_close (GDBusConnection     *connection,
                         GCancellable        *cancellable,
                         GAsyncReadyCallback  callback,
                         gpointer             user_data)
1429
{
1430
  GTask *task;
1431

1432 1433
  g_return_if_fail (G_IS_DBUS_CONNECTION (connection));

1434 1435 1436 1437 1438 1439
  /* do not use g_return_val_if_fail(), we want the memory barrier */
  if (!check_initialized (connection))
    return;

  g_assert (connection->worker != NULL);

1440
  task = g_task_new (connection, cancellable, callback, user_data);
1441
  g_task_set_source_tag (task, g_dbus_connection_close);
1442 1443
  _g_dbus_worker_close (connection->worker, task);
  g_object_unref (task);
1444 1445 1446 1447
}

/**
 * g_dbus_connection_close_finish:
1448 1449 1450 1451
 * @connection: a #GDBusConnection
 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
 *     to g_dbus_connection_close()
 * @error: return location for error or %NULL
1452 1453 1454
 *
 * Finishes an operation started with g_dbus_connection_close().
 *
1455
 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1456 1457 1458 1459 1460 1461 1462 1463 1464
 *
 * 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);
1465
  g_return_val_if_fail (g_task_is_valid (res, connection), FALSE);
1466 1467
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

1468
  return g_task_propagate_boolean (G_TASK (res), error);
1469 1470
}

1471 1472 1473 1474 1475
typedef struct {
    GMainLoop *loop;
    GAsyncResult *result;
} SyncCloseData;

1476
/* Can be called by any thread, without the connection lock */
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
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);
}

1488 1489
/**
 * g_dbus_connection_close_sync:
1490
 * @connection: a #GDBusConnection
1491
 * @cancellable: (nullable): a #GCancellable or %NULL
1492
 * @error: return location for error or %NULL
1493
 *
1494
 * Synchronously closes @connection. The calling thread is blocked
1495 1496 1497 1498
 * until this is done. See g_dbus_connection_close() for the
 * asynchronous version of this method and more details about what it
 * does.
 *
1499
 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1500 1501 1502 1503
 *
 * Since: 2.26
 */
gboolean
1504 1505 1506
g_dbus_connection_close_sync (GDBusConnection  *connection,
                              GCancellable     *cancellable,
                              GError          **error)
1507 1508 1509 1510 1511 1512 1513 1514
{
  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;

1515
  if (check_unclosed (connection, 0, error))
Matthias Clasen's avatar
Matthias Clasen committed
1516
    {
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
      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);
1533 1534 1535
    }

  return ret;
1536 1537 1538 1539
}

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

1540 1541
/**
 * g_dbus_connection_get_last_serial:
1542
 * @connection: a #GDBusConnection
1543 1544 1545 1546 1547 1548 1549 1550
 *
 * 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
1551
 *     within the current thread
1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571
 *
 * 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;
}

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

1572
/* Can be called by any thread, with the connection lock held */
1573
static gboolean
Matthias Clasen's avatar
Matthias Clasen committed
1574 1575
g_dbus_connection_send_message_unlocked (GDBusConnection   *connection,
                                         GDBusMessage      *message,
1576
                                         GDBusSendMessageFlags flags,
Matthias Clasen's avatar
Matthias Clasen committed
1577 1578
                                         volatile guint32  *out_serial,
                                         GError           **error)
1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597
{
  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;

1598 1599 1600 1601 1602
  /* 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).
   */
1603 1604 1605
  if (!check_unclosed (connection,
                       (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
                       error))
1606 1607
    goto out;

1608 1609
  blob = g_dbus_message_to_blob (message,
                                 &blob_size,
1610
                                 connection->capabilities,
1611 1612 1613 1614
                                 error);
  if (blob == NULL)
    goto out;

1615 1616 1617 1618
  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 */
1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640

  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

1641
  /* TODO: use connection->auth to encode the blob */
1642 1643

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

1646 1647 1648 1649 1650 1651 1652 1653 1654
  /* 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));

1655 1656
  if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
    g_dbus_message_set_serial (message, serial_to_use);
1657

1658
  g_dbus_message_lock (message);
1659
  _g_dbus_worker_send_message (connection->worker,
1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674
                               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:
1675 1676 1677
 * @connection: a #GDBusConnection
 * @message: a #GDBusMessage
 * @flags: flags affecting how the message is sent
1678
 * @out_serial: (out) (optional): return location for serial number assigned
1679 1680
 *     to @message when sending it or %NULL
 * @error: Return location for error or %NULL
1681 1682 1683
 *
 * Asynchronously sends @message to the peer represented by @connection.
 *
1684 1685 1686 1687 1688
 * Unless @flags contain the
 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
 * will be assigned by @connection and set on @message via
 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
 * serial number used will be written to this location prior to
1689 1690 1691
 * submitting the message to the underlying transport.
 *
 * If @connection is closed then the operation will fail with
1692
 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1693 1694
 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
 *
1695 1696 1697
 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
 * for an example of how to use this low-level API to send and receive
 * UNIX file descriptors.
1698
 *
1699 1700 1701