gdbusnameowning.c 31.7 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 26 27 28 29 30
 *
 * Author: David Zeuthen <davidz@redhat.com>
 */

#include "config.h"

#include <stdlib.h>

#include "gdbusutils.h"
#include "gdbusnameowning.h"
#include "gdbuserror.h"
#include "gdbusprivate.h"
#include "gdbusconnection.h"

David Zeuthen's avatar
David Zeuthen committed
31 32
#include "glibintl.h"

33 34 35 36
/**
 * SECTION:gdbusnameowning
 * @title: Owning Bus Names
 * @short_description: Simple API for owning bus names
David Zeuthen's avatar
David Zeuthen committed
37
 * @include: gio/gio.h
38 39 40
 *
 * Convenience API for owning bus names.
 *
41 42
 * A simple example for owning a name can be found in
 * [gdbus-example-own-name.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-own-name.c) 
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
 */

G_LOCK_DEFINE_STATIC (lock);

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

typedef enum
{
  PREVIOUS_CALL_NONE = 0,
  PREVIOUS_CALL_ACQUIRED,
  PREVIOUS_CALL_LOST,
} PreviousCall;

typedef struct
{
  volatile gint             ref_count;
  guint                     id;
  GBusNameOwnerFlags        flags;
  gchar                    *name;
  GBusAcquiredCallback      bus_acquired_handler;
  GBusNameAcquiredCallback  name_acquired_handler;
  GBusNameLostCallback      name_lost_handler;
  gpointer                  user_data;
  GDestroyNotify            user_data_free_func;
  GMainContext             *main_context;

  PreviousCall              previous_call;

  GDBusConnection          *connection;
  gulong                    disconnected_signal_handler_id;
  guint                     name_acquired_subscription_id;
  guint                     name_lost_subscription_id;

76
  volatile gboolean         cancelled; /* must hold lock when reading or modifying */
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106

  gboolean                  needs_release;
} Client;

static guint next_global_id = 1;
static GHashTable *map_id_to_client = NULL;


static Client *
client_ref (Client *client)
{
  g_atomic_int_inc (&client->ref_count);
  return client;
}

static void
client_unref (Client *client)
{
  if (g_atomic_int_dec_and_test (&client->ref_count))
    {
      if (client->connection != NULL)
        {
          if (client->disconnected_signal_handler_id > 0)
            g_signal_handler_disconnect (client->connection, client->disconnected_signal_handler_id);
          if (client->name_acquired_subscription_id > 0)
            g_dbus_connection_signal_unsubscribe (client->connection, client->name_acquired_subscription_id);
          if (client->name_lost_subscription_id > 0)
            g_dbus_connection_signal_unsubscribe (client->connection, client->name_lost_subscription_id);
          g_object_unref (client->connection);
        }
107
      g_main_context_unref (client->main_context);
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
      g_free (client->name);
      if (client->user_data_free_func != NULL)
        client->user_data_free_func (client->user_data);
      g_free (client);
    }
}

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


typedef enum
{
  CALL_TYPE_NAME_ACQUIRED,
  CALL_TYPE_NAME_LOST
} CallType;

typedef struct
{
  Client *client;

  /* keep this separate because client->connection may
   * be set to NULL after scheduling the call
   */
  GDBusConnection *connection;

  /* set to TRUE to call acquired */
  CallType call_type;
} CallHandlerData;

static void
call_handler_data_free (CallHandlerData *data)
{
  if (data->connection != NULL)
    g_object_unref (data->connection);
  client_unref (data->client);
  g_free (data);
}

static void
actually_do_call (Client *client, GDBusConnection *connection, CallType call_type)
{
  switch (call_type)
    {
    case CALL_TYPE_NAME_ACQUIRED:
      if (client->name_acquired_handler != NULL)
        {
          client->name_acquired_handler (connection,
                                         client->name,
                                         client->user_data);
        }
      break;

    case CALL_TYPE_NAME_LOST:
      if (client->name_lost_handler != NULL)
        {
          client->name_lost_handler (connection,
                                     client->name,
                                     client->user_data);
        }
      break;

    default:
      g_assert_not_reached ();
      break;
    }
}

static gboolean
call_in_idle_cb (gpointer _data)
{
  CallHandlerData *data = _data;
  actually_do_call (data->client, data->connection, data->call_type);
  return FALSE;
}

static void
schedule_call_in_idle (Client *client, CallType  call_type)
{
  CallHandlerData *data;
  GSource *idle_source;

  data = g_new0 (CallHandlerData, 1);
  data->client = client_ref (client);
  data->connection = client->connection != NULL ? g_object_ref (client->connection) : NULL;
  data->call_type = call_type;

  idle_source = g_idle_source_new ();
  g_source_set_priority (idle_source, G_PRIORITY_HIGH);
  g_source_set_callback (idle_source,
                         call_in_idle_cb,
                         data,
                         (GDestroyNotify) call_handler_data_free);
200
  g_source_set_name (idle_source, "[gio, gdbusnameowning.c] call_in_idle_cb");
201 202 203 204 205 206 207
  g_source_attach (idle_source, client->main_context);
  g_source_unref (idle_source);
}

static void
do_call (Client *client, CallType call_type)
{
208 209
  GMainContext *current_context;

210
  /* only schedule in idle if we're not in the right thread */
211 212
  current_context = g_main_context_ref_thread_default ();
  if (current_context != client->main_context)
213 214 215
    schedule_call_in_idle (client, call_type);
  else
    actually_do_call (client, client->connection, call_type);
216
  g_main_context_unref (current_context);
217 218 219 220 221
}

static void
call_acquired_handler (Client *client)
{
222
  G_LOCK (lock);
223 224 225 226 227
  if (client->previous_call != PREVIOUS_CALL_ACQUIRED)
    {
      client->previous_call = PREVIOUS_CALL_ACQUIRED;
      if (!client->cancelled)
        {
228
          G_UNLOCK (lock);
229
          do_call (client, CALL_TYPE_NAME_ACQUIRED);
230
          goto out;
231 232
        }
    }
233 234 235
  G_UNLOCK (lock);
 out:
  ;
236 237 238 239 240
}

static void
call_lost_handler (Client  *client)
{
241
  G_LOCK (lock);
242 243 244 245 246
  if (client->previous_call != PREVIOUS_CALL_LOST)
    {
      client->previous_call = PREVIOUS_CALL_LOST;
      if (!client->cancelled)
        {
247
          G_UNLOCK (lock);
248
          do_call (client, CALL_TYPE_NAME_LOST);
249
          goto out;
250 251
        }
    }
252 253 254
  G_UNLOCK (lock);
 out:
  ;
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
}

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

static void
on_name_lost_or_acquired (GDBusConnection  *connection,
                          const gchar      *sender_name,
                          const gchar      *object_path,
                          const gchar      *interface_name,
                          const gchar      *signal_name,
                          GVariant         *parameters,
                          gpointer          user_data)
{
  Client *client = user_data;
  const gchar *name;

  if (g_strcmp0 (object_path, "/org/freedesktop/DBus") != 0 ||
      g_strcmp0 (interface_name, "org.freedesktop.DBus") != 0 ||
      g_strcmp0 (sender_name, "org.freedesktop.DBus") != 0)
    goto out;

276 277 278 279 280 281 282
  if (!g_variant_is_of_type (parameters, G_VARIANT_TYPE ("(s)")))
    {
      g_warning ("%s signal had unexpected signature %s", signal_name,
                 g_variant_get_type_string (parameters));
      goto out;
    }

283 284
  if (g_strcmp0 (signal_name, "NameLost") == 0)
    {
Christian Persch's avatar
Christian Persch committed
285
      g_variant_get (parameters, "(&s)", &name);
286 287 288 289 290 291 292
      if (g_strcmp0 (name, client->name) == 0)
        {
          call_lost_handler (client);
        }
    }
  else if (g_strcmp0 (signal_name, "NameAcquired") == 0)
    {
Christian Persch's avatar
Christian Persch committed
293
      g_variant_get (parameters, "(&s)", &name);
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
      if (g_strcmp0 (name, client->name) == 0)
        {
          call_acquired_handler (client);
        }
    }
 out:
  ;
}

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

static void
request_name_cb (GObject      *source_object,
                 GAsyncResult *res,
                 gpointer      user_data)
{
  Client *client = user_data;
  GVariant *result;
  guint32 request_name_reply;
  gboolean subscribe;

  request_name_reply = 0;
  result = NULL;

318 319
  /* don't use client->connection - it may be NULL already */
  result = g_dbus_connection_call_finish (G_DBUS_CONNECTION (source_object),
320 321
                                          res,
                                          NULL);
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
  if (result != NULL)
    {
      g_variant_get (result, "(u)", &request_name_reply);
      g_variant_unref (result);
    }

  subscribe = FALSE;

  switch (request_name_reply)
    {
    case 1: /* DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER */
      /* We got the name - now listen for NameLost and NameAcquired */
      call_acquired_handler (client);
      subscribe = TRUE;
      client->needs_release = TRUE;
      break;

    case 2: /* DBUS_REQUEST_NAME_REPLY_IN_QUEUE */
      /* Waiting in line - listen for NameLost and NameAcquired */
      call_lost_handler (client);
      subscribe = TRUE;
      client->needs_release = TRUE;
      break;

    default:
      /* assume we couldn't get the name - explicit fallthrough */
    case 3: /* DBUS_REQUEST_NAME_REPLY_EXISTS */
    case 4: /* DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER */
      /* Some other part of the process is already owning the name */
      call_lost_handler (client);
      break;
    }

355

356 357
  if (subscribe)
    {
358 359 360 361 362 363 364 365 366 367 368
      GDBusConnection *connection = NULL;

      /* if cancelled, there is no point in subscribing to signals - if not, make sure
       * we use a known good Connection object since it may be set to NULL at any point
       * after being cancelled
       */
      G_LOCK (lock);
      if (!client->cancelled)
        connection = g_object_ref (client->connection);
      G_UNLOCK (lock);

369
      /* start listening to NameLost and NameAcquired messages */
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
      if (connection != NULL)
        {
          client->name_lost_subscription_id =
            g_dbus_connection_signal_subscribe (connection,
                                                "org.freedesktop.DBus",
                                                "org.freedesktop.DBus",
                                                "NameLost",
                                                "/org/freedesktop/DBus",
                                                client->name,
                                                G_DBUS_SIGNAL_FLAGS_NONE,
                                                on_name_lost_or_acquired,
                                                client,
                                                NULL);
          client->name_acquired_subscription_id =
            g_dbus_connection_signal_subscribe (connection,
                                                "org.freedesktop.DBus",
                                                "org.freedesktop.DBus",
                                                "NameAcquired",
                                                "/org/freedesktop/DBus",
                                                client->name,
                                                G_DBUS_SIGNAL_FLAGS_NONE,
                                                on_name_lost_or_acquired,
                                                client,
                                                NULL);
          g_object_unref (connection);
        }
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
    }

  client_unref (client);
}

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

static void
on_connection_disconnected (GDBusConnection *connection,
                            gboolean         remote_peer_vanished,
                            GError          *error,
                            gpointer         user_data)
{
  Client *client = user_data;

  if (client->disconnected_signal_handler_id > 0)
    g_signal_handler_disconnect (client->connection, client->disconnected_signal_handler_id);
  if (client->name_acquired_subscription_id > 0)
    g_dbus_connection_signal_unsubscribe (client->connection, client->name_acquired_subscription_id);
  if (client->name_lost_subscription_id > 0)
    g_dbus_connection_signal_unsubscribe (client->connection, client->name_lost_subscription_id);
  g_object_unref (client->connection);
  client->disconnected_signal_handler_id = 0;
  client->name_acquired_subscription_id = 0;
  client->name_lost_subscription_id = 0;
  client->connection = NULL;

  call_lost_handler (client);
}

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

static void
has_connection (Client *client)
{
  /* listen for disconnection */
  client->disconnected_signal_handler_id = g_signal_connect (client->connection,
                                                             "closed",
                                                             G_CALLBACK (on_connection_disconnected),
                                                             client);

  /* attempt to acquire the name */
438 439 440 441 442 443 444 445
  g_dbus_connection_call (client->connection,
                          "org.freedesktop.DBus",  /* bus name */
                          "/org/freedesktop/DBus", /* object path */
                          "org.freedesktop.DBus",  /* interface name */
                          "RequestName",           /* method name */
                          g_variant_new ("(su)",
                                         client->name,
                                         client->flags),
446
                          G_VARIANT_TYPE ("(u)"),
447 448 449 450 451
                          G_DBUS_CALL_FLAGS_NONE,
                          -1,
                          NULL,
                          (GAsyncReadyCallback) request_name_cb,
                          client_ref (client));
452 453 454 455 456 457 458 459 460 461
}


static void
connection_get_cb (GObject      *source_object,
                   GAsyncResult *res,
                   gpointer      user_data)
{
  Client *client = user_data;

462 463 464 465 466 467 468 469 470
  /* must not do anything if already cancelled */
  G_LOCK (lock);
  if (client->cancelled)
    {
      G_UNLOCK (lock);
      goto out;
    }
  G_UNLOCK (lock);

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
  client->connection = g_bus_get_finish (res, NULL);
  if (client->connection == NULL)
    {
      call_lost_handler (client);
      goto out;
    }

  /* No need to schedule this in idle as we're already in the thread
   * that the user called g_bus_own_name() from. This is because
   * g_bus_get() guarantees that.
   *
   * Also, we need to ensure that the handler is invoked *before*
   * we call RequestName(). Otherwise there is a race.
   */
  if (client->bus_acquired_handler != NULL)
    {
      client->bus_acquired_handler (client->connection,
                                    client->name,
                                    client->user_data);
    }

  has_connection (client);

 out:
  client_unref (client);
}

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

/**
 * g_bus_own_name_on_connection:
502 503 504
 * @connection: a #GDBusConnection
 * @name: the well-known name to own
 * @flags: a set of flags from the #GBusNameOwnerFlags enumeration
505 506
 * @name_acquired_handler: (nullable): handler to invoke when @name is acquired or %NULL
 * @name_lost_handler: (nullable): handler to invoke when @name is lost or %NULL
507
 * @user_data: user data to pass to handlers
508
 * @user_data_free_func: (nullable): function for freeing @user_data or %NULL
509 510 511 512
 *
 * Like g_bus_own_name() but takes a #GDBusConnection instead of a
 * #GBusType.
 *
513 514
 * Returns: an identifier (never 0) that an be used with
 *     g_bus_unown_name() to stop owning the name
515 516 517
 *
 * Since: 2.26
 */
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
guint
g_bus_own_name_on_connection (GDBusConnection          *connection,
                              const gchar              *name,
                              GBusNameOwnerFlags        flags,
                              GBusNameAcquiredCallback  name_acquired_handler,
                              GBusNameLostCallback      name_lost_handler,
                              gpointer                  user_data,
                              GDestroyNotify            user_data_free_func)
{
  Client *client;

  g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
  g_return_val_if_fail (g_dbus_is_name (name) && !g_dbus_is_unique_name (name), 0);

  G_LOCK (lock);

  client = g_new0 (Client, 1);
  client->ref_count = 1;
  client->id = next_global_id++; /* TODO: uh oh, handle overflow */
  client->name = g_strdup (name);
  client->flags = flags;
  client->name_acquired_handler = name_acquired_handler;
  client->name_lost_handler = name_lost_handler;
  client->user_data = user_data;
  client->user_data_free_func = user_data_free_func;
543
  client->main_context = g_main_context_ref_thread_default ();
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563

  client->connection = g_object_ref (connection);

  if (map_id_to_client == NULL)
    {
      map_id_to_client = g_hash_table_new (g_direct_hash, g_direct_equal);
    }
  g_hash_table_insert (map_id_to_client,
                       GUINT_TO_POINTER (client->id),
                       client);

  G_UNLOCK (lock);

  has_connection (client);

  return client->id;
}

/**
 * g_bus_own_name:
564 565 566
 * @bus_type: the type of bus to own a name on
 * @name: the well-known name to own
 * @flags: a set of flags from the #GBusNameOwnerFlags enumeration
567 568 569
 * @bus_acquired_handler: (nullable): handler to invoke when connected to the bus of type @bus_type or %NULL
 * @name_acquired_handler: (nullable): handler to invoke when @name is acquired or %NULL
 * @name_lost_handler: (nullable): handler to invoke when @name is lost or %NULL
570
 * @user_data: user data to pass to handlers
571
 * @user_data_free_func: (nullable): function for freeing @user_data or %NULL
572 573 574
 *
 * Starts acquiring @name on the bus specified by @bus_type and calls
 * @name_acquired_handler and @name_lost_handler when the name is
575 576 577
 * acquired respectively lost. Callbacks will be invoked in the 
 * [thread-default main context][g-main-context-push-thread-default]
 * of the thread you are calling this function from.
578 579 580 581
 *
 * You are guaranteed that one of the @name_acquired_handler and @name_lost_handler
 * callbacks will be invoked after calling this function - there are three
 * possible cases:
582 583 584 585 586 587 588 589 590 591
 * 
 * - @name_lost_handler with a %NULL connection (if a connection to the bus
 *   can't be made).
 *
 * - @bus_acquired_handler then @name_lost_handler (if the name can't be
 *   obtained)
 *
 * - @bus_acquired_handler then @name_acquired_handler (if the name was
 *   obtained).
 *
592 593 594 595 596
 * When you are done owning the name, just call g_bus_unown_name()
 * with the owner id this function returns.
 *
 * If the name is acquired or lost (for example another application
 * could acquire the name if you allow replacement or the application
597 598 599 600
 * currently owning the name exits), the handlers are also invoked.
 * If the #GDBusConnection that is used for attempting to own the name
 * closes, then @name_lost_handler is invoked since it is no longer
 * possible for other processes to access the process.
601
 *
602 603 604
 * You cannot use g_bus_own_name() several times for the same name (unless
 * interleaved with calls to g_bus_unown_name()) - only the first call
 * will work.
605 606 607 608 609 610 611
 *
 * Another guarantee is that invocations of @name_acquired_handler
 * and @name_lost_handler are guaranteed to alternate; that
 * is, if @name_acquired_handler is invoked then you are
 * guaranteed that the next time one of the handlers is invoked, it
 * will be @name_lost_handler. The reverse is also true.
 *
612 613 614 615 616
 * If you plan on exporting objects (using e.g.
 * g_dbus_connection_register_object()), note that it is generally too late
 * to export the objects in @name_acquired_handler. Instead, you can do this
 * in @bus_acquired_handler since you are guaranteed that this will run
 * before @name is requested from the bus.
617 618
 *
 * This behavior makes it very simple to write applications that wants
619
 * to [own names][gdbus-owning-names] and export objects.
620
 * Simply register objects to be exported in @bus_acquired_handler and
621 622
 * unregister the objects (if any) in @name_lost_handler.
 *
623 624
 * Returns: an identifier (never 0) that an be used with
 *     g_bus_unown_name() to stop owning the name.
625 626 627
 *
 * Since: 2.26
 */
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
guint
g_bus_own_name (GBusType                  bus_type,
                const gchar              *name,
                GBusNameOwnerFlags        flags,
                GBusAcquiredCallback      bus_acquired_handler,
                GBusNameAcquiredCallback  name_acquired_handler,
                GBusNameLostCallback      name_lost_handler,
                gpointer                  user_data,
                GDestroyNotify            user_data_free_func)
{
  Client *client;

  g_return_val_if_fail (g_dbus_is_name (name) && !g_dbus_is_unique_name (name), 0);

  G_LOCK (lock);

  client = g_new0 (Client, 1);
  client->ref_count = 1;
  client->id = next_global_id++; /* TODO: uh oh, handle overflow */
  client->name = g_strdup (name);
  client->flags = flags;
  client->bus_acquired_handler = bus_acquired_handler;
  client->name_acquired_handler = name_acquired_handler;
  client->name_lost_handler = name_lost_handler;
  client->user_data = user_data;
  client->user_data_free_func = user_data_free_func;
654
  client->main_context = g_main_context_ref_thread_default ();
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673

  if (map_id_to_client == NULL)
    {
      map_id_to_client = g_hash_table_new (g_direct_hash, g_direct_equal);
    }
  g_hash_table_insert (map_id_to_client,
                       GUINT_TO_POINTER (client->id),
                       client);

  g_bus_get (bus_type,
             NULL,
             connection_get_cb,
             client_ref (client));

  G_UNLOCK (lock);

  return client->id;
}

674 675 676 677 678 679
typedef struct {
  GClosure *bus_acquired_closure;
  GClosure *name_acquired_closure;
  GClosure *name_lost_closure;
} OwnNameData;

680 681 682 683 684 685 686 687 688 689 690 691 692 693
static OwnNameData *
own_name_data_new (GClosure *bus_acquired_closure,
                   GClosure *name_acquired_closure,
                   GClosure *name_lost_closure)
{
  OwnNameData *data;

  data = g_new0 (OwnNameData, 1);

  if (bus_acquired_closure != NULL)
    {
      data->bus_acquired_closure = g_closure_ref (bus_acquired_closure);
      g_closure_sink (bus_acquired_closure);
      if (G_CLOSURE_NEEDS_MARSHAL (bus_acquired_closure))
694
        g_closure_set_marshal (bus_acquired_closure, g_cclosure_marshal_generic);
695 696 697 698 699 700 701
    }

  if (name_acquired_closure != NULL)
    {
      data->name_acquired_closure = g_closure_ref (name_acquired_closure);
      g_closure_sink (name_acquired_closure);
      if (G_CLOSURE_NEEDS_MARSHAL (name_acquired_closure))
702
        g_closure_set_marshal (name_acquired_closure, g_cclosure_marshal_generic);
703 704 705 706 707 708 709
    }

  if (name_lost_closure != NULL)
    {
      data->name_lost_closure = g_closure_ref (name_lost_closure);
      g_closure_sink (name_lost_closure);
      if (G_CLOSURE_NEEDS_MARSHAL (name_lost_closure))
710
        g_closure_set_marshal (name_lost_closure, g_cclosure_marshal_generic);
711 712 713 714 715
    }

  return data;
}

716 717 718 719 720 721
static void
own_with_closures_on_bus_acquired (GDBusConnection *connection,
                                   const gchar     *name,
                                   gpointer         user_data)
{
  OwnNameData *data = user_data;
Javier Jardón's avatar
Javier Jardón committed
722
  GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
723 724 725 726 727 728 729 730

  g_value_init (&params[0], G_TYPE_DBUS_CONNECTION);
  g_value_set_object (&params[0], connection);

  g_value_init (&params[1], G_TYPE_STRING);
  g_value_set_string (&params[1], name);

  g_closure_invoke (data->bus_acquired_closure, NULL, 2, params, NULL);
731 732 733

  g_value_unset (params + 0);
  g_value_unset (params + 1);
734 735 736 737 738 739 740 741
}

static void
own_with_closures_on_name_acquired (GDBusConnection *connection,
                                    const gchar     *name,
                                    gpointer         user_data)
{
  OwnNameData *data = user_data;
Javier Jardón's avatar
Javier Jardón committed
742
  GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
743 744 745 746 747 748 749 750

  g_value_init (&params[0], G_TYPE_DBUS_CONNECTION);
  g_value_set_object (&params[0], connection);

  g_value_init (&params[1], G_TYPE_STRING);
  g_value_set_string (&params[1], name);

  g_closure_invoke (data->name_acquired_closure, NULL, 2, params, NULL);
751 752 753

  g_value_unset (params + 0);
  g_value_unset (params + 1);
754 755 756 757 758 759 760 761
}

static void
own_with_closures_on_name_lost (GDBusConnection *connection,
                                const gchar     *name,
                                gpointer         user_data)
{
  OwnNameData *data = user_data;
Javier Jardón's avatar
Javier Jardón committed
762
  GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
763 764 765 766 767 768 769 770

  g_value_init (&params[0], G_TYPE_DBUS_CONNECTION);
  g_value_set_object (&params[0], connection);

  g_value_init (&params[1], G_TYPE_STRING);
  g_value_set_string (&params[1], name);

  g_closure_invoke (data->name_lost_closure, NULL, 2, params, NULL);
771 772 773

  g_value_unset (params + 0);
  g_value_unset (params + 1);
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
}

static void
bus_own_name_free_func (gpointer user_data)
{
  OwnNameData *data = user_data;

  if (data->bus_acquired_closure != NULL)
    g_closure_unref (data->bus_acquired_closure);

  if (data->name_acquired_closure != NULL)
    g_closure_unref (data->name_acquired_closure);

  if (data->name_lost_closure != NULL)
    g_closure_unref (data->name_lost_closure);

  g_free (data);
}

/**
794
 * g_bus_own_name_with_closures: (rename-to g_bus_own_name)
795 796 797
 * @bus_type: the type of bus to own a name on
 * @name: the well-known name to own
 * @flags: a set of flags from the #GBusNameOwnerFlags enumeration
798
 * @bus_acquired_closure: (nullable): #GClosure to invoke when connected to
799
 *     the bus of type @bus_type or %NULL
800
 * @name_acquired_closure: (nullable): #GClosure to invoke when @name is
801
 *     acquired or %NULL
802
 * @name_lost_closure: (nullable): #GClosure to invoke when @name is lost or
803
 *     %NULL
804 805 806 807
 *
 * Version of g_bus_own_name() using closures instead of callbacks for
 * easier binding in other languages.
 *
808 809
 * Returns: an identifier (never 0) that an be used with
 *     g_bus_unown_name() to stop owning the name.
810 811 812 813
 *
 * Since: 2.26
 */
guint
814 815 816 817 818 819
g_bus_own_name_with_closures (GBusType            bus_type,
                              const gchar        *name,
                              GBusNameOwnerFlags  flags,
                              GClosure           *bus_acquired_closure,
                              GClosure           *name_acquired_closure,
                              GClosure           *name_lost_closure)
820 821 822 823 824 825 826
{
  return g_bus_own_name (bus_type,
          name,
          flags,
          bus_acquired_closure != NULL ? own_with_closures_on_bus_acquired : NULL,
          name_acquired_closure != NULL ? own_with_closures_on_name_acquired : NULL,
          name_lost_closure != NULL ? own_with_closures_on_name_lost : NULL,
827 828 829
          own_name_data_new (bus_acquired_closure,
                             name_acquired_closure,
                             name_lost_closure),
830 831 832 833
          bus_own_name_free_func);
}

/**
834
 * g_bus_own_name_on_connection_with_closures: (rename-to g_bus_own_name_on_connection)
835 836 837
 * @connection: a #GDBusConnection
 * @name: the well-known name to own
 * @flags: a set of flags from the #GBusNameOwnerFlags enumeration
838
 * @name_acquired_closure: (nullable): #GClosure to invoke when @name is
839
 *     acquired or %NULL
840
 * @name_lost_closure: (nullable): #GClosure to invoke when @name is lost
841
 *     or %NULL
842
 *
843 844
 * Version of g_bus_own_name_on_connection() using closures instead of
 * callbacks for easier binding in other languages.
845
 *
846 847
 * Returns: an identifier (never 0) that an be used with
 *     g_bus_unown_name() to stop owning the name.
848 849 850 851
 *
 * Since: 2.26
 */
guint
852 853 854 855 856
g_bus_own_name_on_connection_with_closures (GDBusConnection    *connection,
                                            const gchar        *name,
                                            GBusNameOwnerFlags  flags,
                                            GClosure           *name_acquired_closure,
                                            GClosure           *name_lost_closure)
857 858 859 860 861 862
{
  return g_bus_own_name_on_connection (connection,
          name,
          flags,
          name_acquired_closure != NULL ? own_with_closures_on_name_acquired : NULL,
          name_lost_closure != NULL ? own_with_closures_on_name_lost : NULL,
863 864 865
          own_name_data_new (NULL,
                             name_acquired_closure,
                             name_lost_closure),
866 867 868
          bus_own_name_free_func);
}

869 870
/**
 * g_bus_unown_name:
871
 * @owner_id: an identifier obtained from g_bus_own_name()
872 873
 *
 * Stops owning a name.
874 875
 *
 * Since: 2.26
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
 */
void
g_bus_unown_name (guint owner_id)
{
  Client *client;

  g_return_if_fail (owner_id > 0);

  client = NULL;

  G_LOCK (lock);
  if (owner_id == 0 || map_id_to_client == NULL ||
      (client = g_hash_table_lookup (map_id_to_client, GUINT_TO_POINTER (owner_id))) == NULL)
    {
      g_warning ("Invalid id %d passed to g_bus_unown_name()", owner_id);
      goto out;
    }

  client->cancelled = TRUE;
  g_warn_if_fail (g_hash_table_remove (map_id_to_client, GUINT_TO_POINTER (owner_id)));

 out:
  G_UNLOCK (lock);

  /* do callback without holding lock */
  if (client != NULL)
    {
      /* Release the name if needed */
904 905 906
      if (client->needs_release &&
          client->connection != NULL &&
          !g_dbus_connection_is_closed (client->connection))
907 908 909 910 911 912 913 914 915 916 917 918
        {
          GVariant *result;
          GError *error;
          guint32 release_name_reply;

          /* TODO: it kinda sucks having to do a sync call to release the name - but if
           * we don't, then a subsequent grab of the name will make the bus daemon return
           * IN_QUEUE which will trigger name_lost().
           *
           * I believe this is a bug in the bus daemon.
           */
          error = NULL;
919 920 921 922 923 924
          result = g_dbus_connection_call_sync (client->connection,
                                                "org.freedesktop.DBus",  /* bus name */
                                                "/org/freedesktop/DBus", /* object path */
                                                "org.freedesktop.DBus",  /* interface name */
                                                "ReleaseName",           /* method name */
                                                g_variant_new ("(s)", client->name),
925
                                                G_VARIANT_TYPE ("(u)"),
926 927 928 929
                                                G_DBUS_CALL_FLAGS_NONE,
                                                -1,
                                                NULL,
                                                &error);
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
          if (result == NULL)
            {
              g_warning ("Error releasing name %s: %s", client->name, error->message);
              g_error_free (error);
            }
          else
            {
              g_variant_get (result, "(u)", &release_name_reply);
              if (release_name_reply != 1 /* DBUS_RELEASE_NAME_REPLY_RELEASED */)
                {
                  g_warning ("Unexpected reply %d when releasing name %s", release_name_reply, client->name);
                }
              g_variant_unref (result);
            }
        }

      if (client->disconnected_signal_handler_id > 0)
        g_signal_handler_disconnect (client->connection, client->disconnected_signal_handler_id);
      if (client->name_acquired_subscription_id > 0)
        g_dbus_connection_signal_unsubscribe (client->connection, client->name_acquired_subscription_id);
      if (client->name_lost_subscription_id > 0)
        g_dbus_connection_signal_unsubscribe (client->connection, client->name_lost_subscription_id);
      client->disconnected_signal_handler_id = 0;
      client->name_acquired_subscription_id = 0;
      client->name_lost_subscription_id = 0;
      if (client->connection != NULL)
        {
          g_object_unref (client->connection);
          client->connection = NULL;
        }

      client_unref (client);
    }
}