gdbusconnection.c 262 KB
Newer Older
1 2
/* GDBus - GLib D-Bus Library
 *
3
 * Copyright (C) 2008-2010 Red Hat, Inc.
4 5 6 7 8 9 10 11 12 13 14 15
 *
 * 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
 * version 2 of the License, or (at your option) any later version.
 *
 * 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 96 97 98 99
 *
 *  - use abstract sockets in test code
 *   - right now it doesn't work, dbus-daemon(1) fails with
 *
 *        /gdbus/connection/filter: Failed to start message bus: Failed to bind
 *        socket "/tmp/g-dbus-tests-pid-28531": Address already in use
 *        ** WARNING **: Error reading address from dbus daemon, 0 bytes read
 *
 *     or similar.
100 101 102 103 104
 */

#include "config.h"

#include <stdlib.h>
David Zeuthen's avatar
David Zeuthen committed
105
#include <string.h>
106 107 108 109 110 111 112 113 114 115 116 117

#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
118 119 120 121
#include "ginitable.h"
#include "gasyncinitable.h"
#include "giostream.h"
#include "gasyncresult.h"
122
#include "gtask.h"
David Zeuthen's avatar
David Zeuthen committed
123 124

#ifdef G_OS_UNIX
Matthias Clasen's avatar
Matthias Clasen committed
125 126
#include "gunixconnection.h"
#include "gunixfdmessage.h"
David Zeuthen's avatar
David Zeuthen committed
127 128 129
#endif

#include "glibintl.h"
130 131 132 133

/**
 * SECTION:gdbusconnection
 * @short_description: D-Bus Connections
David Zeuthen's avatar
David Zeuthen committed
134
 * @include: gio/gio.h
135 136
 *
 * The #GDBusConnection type is used for D-Bus connections to remote
137 138 139 140 141
 * 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
142
 * a D-Bus client, it is often easier to use the g_bus_own_name(),
143
 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
144
 *
145 146 147 148
 * 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.
149
 *
150 151 152 153
 * 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
154
 * g_initable_new() or g_async_initable_new_async(), which also initialize the
155 156 157 158
 * connection.
 *
 * If you construct an uninitialized #GDBusConnection, such as via
 * g_object_new(), you must initialize it via g_initable_init() or
159 160 161 162 163 164
 * 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().
165
 *
166
 * ## An example D-Bus server # {#gdbus-server}
167
 *
168 169
 * 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)
170
 *
171
 * ## An example for exporting a subtree # {#gdbus-subtree-server}
172
 *
173 174 175 176 177 178 179 180 181 182 183 184
 * 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:
 * [gdbus-unix-fd-client.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-unix-fd-client.c)
 *
 * ## 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)
185 186 187 188
 */

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

189 190
typedef struct _GDBusConnectionClass GDBusConnectionClass;

191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
/**
 * 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);
};

211 212
G_LOCK_DEFINE_STATIC (message_bus_lock);

213 214
static GWeakRef the_session_bus;
static GWeakRef the_system_bus;
215

216 217 218 219 220 221
/* 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.
 */
222
#define SEND_MESSAGE_FLAGS_INITIALIZING (1u << 31)
223 224

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

227 228
/* ---------------------------------------------------------------------------------------------------- */

229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
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>
254 255
 * @context: (allow-none): A #GMainContext or %NULL.
 * @callback: (allow-none): A #GDestroyNotify or %NULL.
256 257 258 259 260 261 262 263 264
 * @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)
{
265 266
  GSource *idle_source;
  CallDestroyNotifyData *data;
267

268 269 270
  if (callback == NULL)
    goto out;

271 272 273 274 275 276
  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);
277

278 279 280 281 282 283
  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);
284
  g_source_set_name (idle_source, "[gio] call_destroy_notify_data_in_idle");
285 286
  g_source_attach (idle_source, data->context);
  g_source_unref (idle_source);
287 288 289 290 291 292 293

 out:
  ;
}

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

294
static gboolean
Matthias Clasen's avatar
Matthias Clasen committed
295 296
_g_strv_has_string (const gchar* const *haystack,
                    const gchar        *needle)
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
{
  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 {                                \
315
    if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock)))                     \
316 317 318 319 320 321 322 323
      {                                                                 \
        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 {                                       \
324
    g_mutex_lock (&(obj)->lock);                                        \
325 326 327
  } while (FALSE)

#define CONNECTION_UNLOCK(obj) do {                                     \
328
    g_mutex_unlock (&(obj)->lock);                                      \
329 330
  } while (FALSE)

331 332
/* Flags in connection->atomic_flags */
enum {
333
    FLAG_INITIALIZED = 1 << 0,
334 335
    FLAG_EXIT_ON_CLOSE = 1 << 1,
    FLAG_CLOSED = 1 << 2
336 337
};

338 339 340 341 342 343 344 345 346
/**
 * GDBusConnection:
 *
 * The #GDBusConnection structure contains only private data and
 * should only be accessed using the provided API.
 *
 * Since: 2.26
 */
struct _GDBusConnection
347
{
348 349 350
  /*< private >*/
  GObject parent_instance;

351 352 353 354
  /* ------------------------------------------------------------------------ */
  /* -- General object state ------------------------------------------------ */
  /* ------------------------------------------------------------------------ */

355
  /* General-purpose lock for most fields */
356
  GMutex lock;
357 358

  /* A lock used in the init() method of the GInitable interface - see comments
359 360 361
   * in initable_init() for why a separate lock is needed.
   *
   * If you need both @lock and @init_lock, you must take @init_lock first.
362
   */
363
  GMutex init_lock;
364 365

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

370 371 372 373
  /* 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.
   */
374 375
  GIOStream *stream;

376 377 378 379
  /* 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.
   */
380 381
  GDBusAuth *auth;

382
  /* Last serial used. Protected by @lock. */
383 384
  guint32 last_serial;

385 386 387 388
  /* 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.
   */
389 390 391
  GDBusWorker *worker;

  /* If connected to a message bus, this contains the unique name assigned to
392 393 394
   * 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.
395 396 397 398
   */
  gchar *bus_unique_name;

  /* The GUID returned by the other side if we authenticed as a client or
399 400 401
   * 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.
402 403 404
   */
  gchar *guid;

405 406
  /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
   * Inspect @initialization_error to see whether it succeeded or failed.
407 408
   *
   * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
409 410 411
   *
   * FLAG_CLOSED is the closed property. It may be read at any time, but
   * may only be written while holding @lock.
412 413
   */
  volatile gint atomic_flags;
414

415 416 417 418 419
  /* 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.
   */
420 421
  GError *initialization_error;

422
  /* The result of g_main_context_ref_thread_default() when the object
423 424
   * was created (the GObject _init() function) - this is used for delivery
   * of the :closed GObject signal.
425 426
   *
   * Only set in the GObject init function, so no locks are needed.
427 428 429
   */
  GMainContext *main_context_at_construction;

430
  /* Read-only construct properties, no locks needed */
431 432 433
  gchar *address;
  GDBusConnectionFlags flags;

434
  /* Map used for managing method replies, protected by @lock */
435
  GHashTable *map_method_serial_to_task;  /* guint32 -> GTask* */
436

437
  /* Maps used for managing signal subscription, protected by @lock */
438 439 440
  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 */
441

442 443 444
  /* Maps used for managing exported objects and subtrees,
   * protected by @lock
   */
445 446 447 448 449
  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* */

450 451 452
  /* Map used for storing last used serials for each thread, protected by @lock */
  GHashTable *map_thread_to_last_serial;

453
  /* Structure used for message filters, protected by @lock */
454 455
  GPtrArray *filters;

456 457 458 459
  /* Capabilities negotiated during authentication
   * Read-only after initable_init(), so it may be read without holding a
   * lock, if you check for initialization first.
   */
460 461
  GDBusCapabilityFlags capabilities;

462
  /* Protected by @init_lock */
463
  GDBusAuthObserver *authentication_observer;
464 465 466 467

  /* 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
468
  GCredentials *credentials;
469 470 471

  /* set to TRUE when finalizing */
  gboolean finalizing;
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 504 505 506 507 508 509 510 511 512
};

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

513 514 515 516 517 518 519 520 521 522 523 524
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);

525 526 527 528
#define _G_ENSURE_LOCK(name) do {                                       \
    if (G_UNLIKELY (G_TRYLOCK(name)))                                   \
      {                                                                 \
        g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
529
                             "_G_ENSURE_LOCK: Lock '" #name "' is not locked"); \
530 531 532 533 534
      }                                                                 \
  } while (FALSE)                                                       \

static guint signals[LAST_SIGNAL] = { 0 };

Matthias Clasen's avatar
Matthias Clasen committed
535
static void initable_iface_init       (GInitableIface      *initable_iface);
536 537 538 539 540 541 542
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)
                         );

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 568 569 570 571 572 573 574 575 576
/*
 * 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;
}

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 610 611 612 613 614 615 616 617 618
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;
}

619 620
static GHashTable *alive_connections = NULL;

621 622 623 624 625 626
static void
g_dbus_connection_dispose (GObject *object)
{
  GDBusConnection *connection = G_DBUS_CONNECTION (object);

  G_LOCK (message_bus_lock);
627
  CONNECTION_LOCK (connection);
628
  if (connection->worker != NULL)
629
    {
630 631
      _g_dbus_worker_stop (connection->worker);
      connection->worker = NULL;
632 633 634 635 636 637 638
      if (alive_connections != NULL)
        g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
    }
  else
    {
      if (alive_connections != NULL)
        g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
639
    }
640
  CONNECTION_UNLOCK (connection);
641 642 643 644 645 646 647 648 649 650 651
  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);

652 653 654 655 656 657 658
  connection->finalizing = TRUE;

  purge_all_signal_subscriptions (connection);

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

659 660
  if (connection->authentication_observer != NULL)
    g_object_unref (connection->authentication_observer);
661

662 663
  if (connection->auth != NULL)
    g_object_unref (connection->auth);
664

665 666 667
  if (connection->credentials)
    g_object_unref (connection->credentials);

668
  if (connection->stream != NULL)
669
    {
670 671
      g_object_unref (connection->stream);
      connection->stream = NULL;
672 673
    }

674
  g_free (connection->address);
675

676 677
  g_free (connection->guid);
  g_free (connection->bus_unique_name);
678

679 680
  if (connection->initialization_error != NULL)
    g_error_free (connection->initialization_error);
681

682
  g_hash_table_unref (connection->map_method_serial_to_task);
683

684 685 686
  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);
687

688 689 690 691
  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);
692

693 694
  g_hash_table_unref (connection->map_thread_to_last_serial);

695
  g_main_context_unref (connection->main_context_at_construction);
696

697
  g_free (connection->machine_id);
698

699 700
  g_mutex_clear (&connection->init_lock);
  g_mutex_clear (&connection->lock);
701

Matthias Clasen's avatar
Matthias Clasen committed
702
  G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
703 704
}

705
/* called in any user thread, with the connection's lock not held */
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 737 738 739 740 741 742 743 744 745
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;
    }
}

746
/* called in any user thread, with the connection's lock not held */
747 748 749 750 751 752 753 754 755 756 757
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:
758
      connection->stream = g_value_dup_object (value);
759 760 761
      break;

    case PROP_GUID:
762
      connection->guid = g_value_dup_string (value);
763 764 765
      break;

    case PROP_ADDRESS:
766
      connection->address = g_value_dup_string (value);
767 768 769
      break;

    case PROP_FLAGS:
770
      connection->flags = g_value_get_flags (value);
771 772 773 774 775 776 777
      break;

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

    case PROP_AUTHENTICATION_OBSERVER:
778
      connection->authentication_observer = g_value_dup_object (value);
779 780 781 782 783 784 785 786
      break;

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

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

static void
g_dbus_connection_init (GDBusConnection *connection)
{
1066 1067
  g_mutex_init (&connection->lock);
  g_mutex_init (&connection->init_lock);
1068

1069
  connection->map_method_serial_to_task = g_hash_table_new (g_direct_hash, g_direct_equal);
1070

1071 1072 1073 1074 1075 1076 1077
  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
1078
                                                                                   (GDestroyNotify) g_ptr_array_unref);
1079

1080 1081 1082 1083
  connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
                                                             g_str_equal,
                                                             NULL,
                                                             (GDestroyNotify) exported_object_free);
1084

1085 1086
  connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
                                               g_direct_equal);
1087

1088 1089 1090 1091
  connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
                                                             g_str_equal,
                                                             NULL,
                                                             (GDestroyNotify) exported_subtree_free);
1092

1093 1094
  connection->map_id_to_es = g_hash_table_new (g_direct_hash,
                                               g_direct_equal);
1095

1096 1097 1098
  connection->map_thread_to_last_serial = g_hash_table_new (g_direct_hash,
                                                            g_direct_equal);

1099
  connection->main_context_at_construction = g_main_context_ref_thread_default ();
1100

1101
  connection->filters = g_ptr_array_new ();
1102 1103
}

Matthias Clasen's avatar
Matthias Clasen committed
1104 1105 1106 1107 1108 1109
/**
 * g_dbus_connection_get_stream:
 * @connection: a #GDBusConnection
 *
 * Gets the underlying stream used for IO.
 *
1110 1111 1112 1113
 * 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.
 *
1114
 * Returns: (transfer none): the stream used for IO
Matthias Clasen's avatar
Matthias Clasen committed
1115 1116 1117
 *
 * Since: 2.26
 */
1118 1119 1120 1121
GIOStream *
g_dbus_connection_get_stream (GDBusConnection *connection)
{
  g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1122 1123 1124 1125 1126

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

1127
  return connection->stream;
1128 1129
}

1130 1131
/**
 * g_dbus_connection_start_message_processing:
1132
 * @connection: a #GDBusConnection
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
 *
 * 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));
1145 1146 1147 1148 1149 1150

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

  g_assert (connection->worker != NULL);
1151
  _g_dbus_worker_unfreeze (connection->worker);
1152
}
1153 1154 1155

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

1169
  g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1170 1171 1172 1173

  flags = g_atomic_int_get (&connection->atomic_flags);

  return (flags & FLAG_CLOSED) ? TRUE : FALSE;
1174 1175 1176 1177
}

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

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

1195
  return connection->capabilities;
1196 1197
}

1198 1199
/* ---------------------------------------------------------------------------------------------------- */

1200
/* Called in a temporary thread without holding locks. */
1201
static void
1202 1203 1204 1205
flush_in_thread_func (GTask         *task,
                      gpointer       source_object,
                      gpointer       task_data,
                      GCancellable  *cancellable)
1206
{
1207
  GError *error = NULL;
1208

1209 1210 1211 1212 1213 1214
  if (g_dbus_connection_flush_sync (source_object,
                                    cancellable,
                                    &error))
    g_task_return_boolean (task, TRUE);
  else
    g_task_return_error (task, error);
1215 1216 1217 1218
}

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

  g_return_if_fail (G_IS_DBUS_CONNECTION (connection));

1252
  task = g_task_new (connection, cancellable, callback, user_data);
1253
  g_task_set_source_tag (task, g_dbus_connection_flush);
1254 1255
  g_task_run_in_thread (task, flush_in_thread_func);
  g_object_unref (task);
1256 1257 1258 1259
}

/**
 * g_dbus_connection_flush_finish:
1260 1261 1262 1263
 * @connection: a #GDBusConnection
 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
 *     to g_dbus_connection_flush()
 * @error: return location for error or %NULL
1264 1265 1266
 *
 * Finishes an operation started with g_dbus_connection_flush().
 *
1267
 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1268 1269 1270 1271 1272 1273 1274 1275 1276
 *
 * 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);
1277
  g_return_val_if_fail (g_task_is_valid (res, connection), FALSE);
1278 1279
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

1280
  return g_task_propagate_boolean (G_TASK (res), error);
1281 1282 1283 1284
}

/**
 * g_dbus_connection_flush_sync:
1285 1286 1287
 * @connection: a #GDBusConnection
 * @cancellable: (allow-none): a #GCancellable or %NULL
 * @error: return location for error or %NULL
1288 1289 1290 1291 1292 1293
 *
 * 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.
 *
1294
 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
 *
 * 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);
1306
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1307 1308 1309

  ret = FALSE;

1310 1311 1312 1313 1314 1315 1316 1317
  /* 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))
1318 1319 1320 1321
    goto out;

  g_assert (connection->worker != NULL);

1322
  ret = _g_dbus_worker_flush_sync (connection->worker,
1323 1324 1325 1326 1327 1328
                                   cancellable,
                                   error);

 out:
  return ret;
}
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347

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

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

1348 1349 1350
/* Called in a user thread that has acquired the main context that was
 * thread-default when the object was constructed
 */
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
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;
}

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

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

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

1441 1442
  g_return_if_fail (G_IS_DBUS_CONNECTION (connection));

1443 1444 1445 1446 1447 1448
  /* do not use g_return_val_if_fail(), we want the memory barrier */
  if (!check_initialized (connection))
    return;

  g_assert (connection->worker != NULL);

1449
  task = g_task_new (connection, cancellable, callback, user_data);
1450
  g_task_set_source_tag (task, g_dbus_connection_close);
1451 1452
  _g_dbus_worker_close (connection->worker, task);
  g_object_unref (task);
1453 1454 1455 1456
}

/**
 * g_dbus_connection_close_finish:
1457 1458 1459 1460
 * @connection: a #GDBusConnection
 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
 *     to g_dbus_connection_close()
 * @error: return location for error or %NULL
1461 1462 1463
 *
 * Finishes an operation started with g_dbus_connection_close().
 *
1464
 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1465 1466 1467 1468 1469 1470 1471 1472 1473
 *
 * 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);
1474
  g_return_val_if_fail (g_task_is_valid (res, connection), FALSE);
1475 1476
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

1477
  return g_task_propagate_boolean (G_TASK (res), error);
1478 1479
}

1480 1481 1482 1483 1484
typedef struct {
    GMainLoop *loop;
    GAsyncResult *result;
} SyncCloseData;

1485
/* Can be called by any thread, without the connection lock */
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
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);
}

1497 1498
/**
 * g_dbus_connection_close_sync:
1499 1500 1501
 * @connection: a #GDBusConnection
 * @cancellable: (allow-none): a #GCancellable or %NULL
 * @error: return location for error or %NULL
1502 1503 1504 1505 1506 1507
 *
 * Synchronously closees @connection. The calling thread is blocked
 * until this is done. See g_dbus_connection_close() for the
 * asynchronous version of this method and more details about what it
 * does.
 *
1508
 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1509 1510 1511 1512
 *
 * Since: 2.26
 */
gboolean
1513 1514 1515
g_dbus_connection_close_sync (GDBusConnection  *connection,
                              GCancellable     *cancellable,
                              GError          **error)
1516 1517 1518 1519 1520 1521 1522 1523
{
  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;

1524
  if (check_unclosed (connection, 0, error))
Matthias Clasen's avatar
Matthias Clasen committed
1525
    {
1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
      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);
1542 1543 1544
    }

  return ret;
1545 1546 1547 1548
}

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

1549 1550
/**
 * g_dbus_connection_get_last_serial:
1551
 * @connection: a #GDBusConnection
1552 1553 1554 1555 1556 1557 1558 1559
 *
 * 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
1560
 *     within the current thread
1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
 *
 * 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;
}

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

1581
/* Can be called by any thread, with the connection lock held */
1582
static gboolean
Matthias Clasen's avatar
Matthias Clasen committed
1583 1584
g_dbus_connection_send_message_unlocked (GDBusConnection   *connection,
                                         GDBusMessage      *message,
1585
                                         GDBusSendMessageFlags flags,
Matthias Clasen's avatar
Matthias Clasen committed
1586 1587
                                         volatile guint32  *out_serial,
                                         GError           **error)
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
{
  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;

1607 1608 1609 1610 1611
  /* 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).
   */
1612 1613 1614
  if (!check_unclosed (connection,
                       (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
                       error))
1615 1616
    goto out;

1617 1618
  blob = g_dbus_message_to_blob (message,
                                 &blob_size,
1619
                                 connection->capabilities,
1620 1621 1622 1623
                                 error);
  if (blob == NULL)
    goto out;

1624 1625 1626 1627
  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 */
1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649

  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

1650
  /* TODO: use connection->auth to encode the blob */
1651 1652

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

1655 1656 1657 1658 1659 1660 1661 1662 1663
  /* 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));

1664 1665
  if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
    g_dbus_message_set_serial (message, serial_to_use);
1666

1667
  g_dbus_message_lock (message);
1668
  _g_dbus_worker_send_message (connection->worker,
1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
                               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:
1684 1685 1686 1687 1688 1689
 * @connection: a #GDBusConnection
 * @message: a #GDBusMessage
 * @flags: flags affecting how the message is sent
 * @out_serial: (out) (allow-none): return location for serial number assigned
 *     to @message when sending it or %NULL
 * @error: Return location for error or %NULL
1690 1691 1692
 *
 * Asynchronously sends @message to the peer represented by @connection.
 *
1693 1694 1695 1696 1697
 * 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
1698 1699 1700
 * submitting the message to the underlying transport.
 *
 * If @connection is closed then the operation will fail with
1701
 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1702 1703
 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
 *
1704 1705 1706
 * 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.
1707
 *
1708 1709 1710
 * Note that @message must be unlocked, unless @flags contain the
 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
 *
1711
 * Returns: %TRUE if the message was well-formed and queued for
1712
 *     transmission, %FALSE if @error is set
1713 1714
 *
 * Since: 2.26
1715 1716
 */
gboolean
1717 1718 1719 1720 1721
g_dbus_connection_send_message (GDBusConnection        *connection,
                                GDBusMessage           *message,
                                GDBusSendMessageFlags   flags,
                                volatile guint32       *out_serial,
                                GError                **error)
1722 1723 1724 1725 1726
{
  gboolean ret;

  g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
  g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1727
  g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);