gdbusnamewatching.c 28.6 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
 *
 * Author: David Zeuthen <davidz@redhat.com>
 */

#include "config.h"

#include <stdlib.h>
David Zeuthen's avatar
David Zeuthen committed
24
#include <string.h>
25 26 27 28 29 30 31

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

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

34 35 36 37
/**
 * SECTION:gdbusnamewatching
 * @title: Watching Bus Names
 * @short_description: Simple API for watching bus names
David Zeuthen's avatar
David Zeuthen committed
38
 * @include: gio/gio.h
39 40 41
 *
 * Convenience API for watching bus names.
 *
42 43
 * A simple example for watching a name can be found in
 * [gdbus-example-watch-name.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-watch-name.c)
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 76 77 78 79
 */

G_LOCK_DEFINE_STATIC (lock);

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

typedef enum
{
  PREVIOUS_CALL_NONE = 0,
  PREVIOUS_CALL_APPEARED,
  PREVIOUS_CALL_VANISHED,
} PreviousCall;

typedef struct
{
  volatile gint             ref_count;
  guint                     id;
  gchar                    *name;
  GBusNameWatcherFlags      flags;
  gchar                    *name_owner;
  GBusNameAppearedCallback  name_appeared_handler;
  GBusNameVanishedCallback  name_vanished_handler;
  gpointer                  user_data;
  GDestroyNotify            user_data_free_func;
  GMainContext             *main_context;

  GDBusConnection          *connection;
  gulong                    disconnected_signal_handler_id;
  guint                     name_owner_changed_subscription_id;

  PreviousCall              previous_call;

  gboolean                  cancelled;
  gboolean                  initialized;
} Client;

80 81 82 83
/* Must be accessed atomically. */
static volatile guint next_global_id = 1;

/* Must be accessed with @lock held. */
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
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->name_owner_changed_subscription_id > 0)
            g_dbus_connection_signal_unsubscribe (client->connection, client->name_owner_changed_subscription_id);
          if (client->disconnected_signal_handler_id > 0)
            g_signal_handler_disconnect (client->connection, client->disconnected_signal_handler_id);
          g_object_unref (client->connection);
        }
      g_free (client->name);
      g_free (client->name_owner);
108
      g_main_context_unref (client->main_context);
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 200 201 202 203
      if (client->user_data_free_func != NULL)
        client->user_data_free_func (client->user_data);
      g_free (client);
    }
}

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

typedef enum
{
  CALL_TYPE_NAME_APPEARED,
  CALL_TYPE_NAME_VANISHED
} CallType;

typedef struct
{
  Client *client;

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

  /* ditto */
  gchar *name_owner;

  CallType call_type;
} CallHandlerData;

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

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

    case CALL_TYPE_NAME_VANISHED:
      if (client->name_vanished_handler != NULL)
        {
          client->name_vanished_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->name_owner, 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->name_owner = g_strdup (client->name_owner);
  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);
204
  g_source_set_name (idle_source, "[gio, gdbusnamewatching.c] call_in_idle_cb");
205 206 207 208 209 210 211
  g_source_attach (idle_source, client->main_context);
  g_source_unref (idle_source);
}

static void
do_call (Client *client, CallType call_type)
{
212 213
  GMainContext *current_context;

214
  /* only schedule in idle if we're not in the right thread */
215 216
  current_context = g_main_context_ref_thread_default ();
  if (current_context != client->main_context)
217 218 219
    schedule_call_in_idle (client, call_type);
  else
    actually_do_call (client, client->connection, client->name_owner, call_type);
220
  g_main_context_unref (current_context);
221 222 223 224 225 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
}

static void
call_appeared_handler (Client *client)
{
  if (client->previous_call != PREVIOUS_CALL_APPEARED)
    {
      client->previous_call = PREVIOUS_CALL_APPEARED;
      if (!client->cancelled && client->name_appeared_handler != NULL)
        {
          do_call (client, CALL_TYPE_NAME_APPEARED);
        }
    }
}

static void
call_vanished_handler (Client  *client,
                       gboolean ignore_cancelled)
{
  if (client->previous_call != PREVIOUS_CALL_VANISHED)
    {
      client->previous_call = PREVIOUS_CALL_VANISHED;
      if (((!client->cancelled) || ignore_cancelled) && client->name_vanished_handler != NULL)
        {
          do_call (client, CALL_TYPE_NAME_VANISHED);
        }
    }
}

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

252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
/* Return a reference to the #Client for @watcher_id, or %NULL if it’s been
 * unwatched. This is safe to call from any thread. */
static Client *
dup_client (guint watcher_id)
{
  Client *client;

  G_LOCK (lock);

  g_assert (watcher_id != 0);
  g_assert (map_id_to_client != NULL);

  client = g_hash_table_lookup (map_id_to_client, GUINT_TO_POINTER (watcher_id));

  if (client != NULL)
    client_ref (client);

  G_UNLOCK (lock);

  return client;
}

/* Could be called from any thread, so it could be called after client_unref()
 * has started finalising the #Client. Avoid that by looking up the #Client
 * atomically. */
277 278 279 280 281 282
static void
on_connection_disconnected (GDBusConnection *connection,
                            gboolean         remote_peer_vanished,
                            GError          *error,
                            gpointer         user_data)
{
283 284 285 286 287 288
  guint watcher_id = GPOINTER_TO_UINT (user_data);
  Client *client = NULL;

  client = dup_client (watcher_id);
  if (client == NULL)
    return;
289 290 291 292 293 294 295 296 297 298 299

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

  call_vanished_handler (client, FALSE);
300 301

  client_unref (client);
302 303 304 305
}

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

306
/* Will always be called from the thread which acquired client->main_context. */
307 308 309 310 311 312 313 314 315
static void
on_name_owner_changed (GDBusConnection *connection,
                       const gchar      *sender_name,
                       const gchar      *object_path,
                       const gchar      *interface_name,
                       const gchar      *signal_name,
                       GVariant         *parameters,
                       gpointer          user_data)
{
316 317
  guint watcher_id = GPOINTER_TO_UINT (user_data);
  Client *client = NULL;
318 319 320 321
  const gchar *name;
  const gchar *old_owner;
  const gchar *new_owner;

322 323 324 325
  client = dup_client (watcher_id);
  if (client == NULL)
    return;

326 327 328 329 330 331 332 333 334
  if (!client->initialized)
    goto out;

  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;

  g_variant_get (parameters,
335
                 "(&s&s&s)",
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
                 &name,
                 &old_owner,
                 &new_owner);

  /* we only care about a specific name */
  if (g_strcmp0 (name, client->name) != 0)
    goto out;

  if ((old_owner != NULL && strlen (old_owner) > 0) && client->name_owner != NULL)
    {
      g_free (client->name_owner);
      client->name_owner = NULL;
      call_vanished_handler (client, FALSE);
    }

  if (new_owner != NULL && strlen (new_owner) > 0)
    {
      g_warn_if_fail (client->name_owner == NULL);
      g_free (client->name_owner);
      client->name_owner = g_strdup (new_owner);
      call_appeared_handler (client);
    }

 out:
360
  client_unref (client);
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
}

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

static void
get_name_owner_cb (GObject      *source_object,
                   GAsyncResult *res,
                   gpointer      user_data)
{
  Client *client = user_data;
  GVariant *result;
  const char *name_owner;

  name_owner = NULL;
  result = NULL;

377 378 379
  result = g_dbus_connection_call_finish (client->connection,
                                          res,
                                          NULL);
380 381
  if (result != NULL)
    {
382
      g_variant_get (result, "(&s)", &name_owner);
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
    }

  if (name_owner != NULL)
    {
      g_warn_if_fail (client->name_owner == NULL);
      client->name_owner = g_strdup (name_owner);
      call_appeared_handler (client);
    }
  else
    {
      call_vanished_handler (client, FALSE);
    }

  client->initialized = TRUE;

  if (result != NULL)
    g_variant_unref (result);
  client_unref (client);
}

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

static void
invoke_get_name_owner (Client *client)
{
408 409 410 411 412 413
  g_dbus_connection_call (client->connection,
                          "org.freedesktop.DBus",  /* bus name */
                          "/org/freedesktop/DBus", /* object path */
                          "org.freedesktop.DBus",  /* interface name */
                          "GetNameOwner",          /* method name */
                          g_variant_new ("(s)", client->name),
414
                          G_VARIANT_TYPE ("(s)"),
415 416 417 418 419
                          G_DBUS_CALL_FLAGS_NONE,
                          -1,
                          NULL,
                          (GAsyncReadyCallback) get_name_owner_cb,
                          client_ref (client));
420 421 422 423 424 425 426 427 428 429 430 431 432 433
}

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

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

  result = NULL;

434 435 436
  result = g_dbus_connection_call_finish (client->connection,
                                          res,
                                          NULL);
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
  if (result != NULL)
    {
      guint32 start_service_result;
      g_variant_get (result, "(u)", &start_service_result);

      if (start_service_result == 1) /* DBUS_START_REPLY_SUCCESS */
        {
          invoke_get_name_owner (client);
        }
      else if (start_service_result == 2) /* DBUS_START_REPLY_ALREADY_RUNNING */
        {
          invoke_get_name_owner (client);
        }
      else
        {
          g_warning ("Unexpected reply %d from StartServiceByName() method", start_service_result);
          call_vanished_handler (client, FALSE);
          client->initialized = TRUE;
        }
    }
  else
    {
      /* Errors are not unexpected; the bus will reply e.g.
       *
       *   org.freedesktop.DBus.Error.ServiceUnknown: The name org.gnome.Epiphany2
       *   was not provided by any .service files
       *
464 465 466
       * This doesn't mean that the name doesn't have an owner, just
       * that it's not provided by a .service file. So proceed to
       * invoke GetNameOwner().
467
       */
468
      invoke_get_name_owner (client);
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
    }

  if (result != NULL)
    g_variant_unref (result);
  client_unref (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),
485
                                                             GUINT_TO_POINTER (client->id));
486 487 488 489 490 491 492 493

  /* start listening to NameOwnerChanged messages immediately */
  client->name_owner_changed_subscription_id = g_dbus_connection_signal_subscribe (client->connection,
                                                                                   "org.freedesktop.DBus",  /* name */
                                                                                   "org.freedesktop.DBus",  /* if */
                                                                                   "NameOwnerChanged",      /* signal */
                                                                                   "/org/freedesktop/DBus", /* path */
                                                                                   client->name,
494
                                                                                   G_DBUS_SIGNAL_FLAGS_NONE,
495
                                                                                   on_name_owner_changed,
496
                                                                                   GUINT_TO_POINTER (client->id),
497 498 499 500
                                                                                   NULL);

  if (client->flags & G_BUS_NAME_WATCHER_FLAGS_AUTO_START)
    {
501 502 503 504 505 506
      g_dbus_connection_call (client->connection,
                              "org.freedesktop.DBus",  /* bus name */
                              "/org/freedesktop/DBus", /* object path */
                              "org.freedesktop.DBus",  /* interface name */
                              "StartServiceByName",    /* method name */
                              g_variant_new ("(su)", client->name, 0),
507
                              G_VARIANT_TYPE ("(u)"),
508 509 510 511 512
                              G_DBUS_CALL_FLAGS_NONE,
                              -1,
                              NULL,
                              (GAsyncReadyCallback) start_service_by_name_cb,
                              client_ref (client));
513 514 515 516 517 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 543 544 545 546 547 548
    }
  else
    {
      /* check owner */
      invoke_get_name_owner (client);
    }
}


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

  client->connection = g_bus_get_finish (res, NULL);
  if (client->connection == NULL)
    {
      call_vanished_handler (client, FALSE);
      goto out;
    }

  has_connection (client);

 out:
  client_unref (client);
}

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

/**
 * g_bus_watch_name:
 * @bus_type: The type of bus to watch a name on.
 * @name: The name (well-known or unique) to watch.
 * @flags: Flags from the #GBusNameWatcherFlags enumeration.
549 550
 * @name_appeared_handler: (nullable): Handler to invoke when @name is known to exist or %NULL.
 * @name_vanished_handler: (nullable): Handler to invoke when @name is known to not exist or %NULL.
551
 * @user_data: User data to pass to handlers.
552
 * @user_data_free_func: (nullable): Function for freeing @user_data or %NULL.
553 554 555 556
 *
 * Starts watching @name on the bus specified by @bus_type and calls
 * @name_appeared_handler and @name_vanished_handler when the name is
 * known to have a owner respectively known to lose its
557 558 559
 * owner. 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.
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
 *
 * You are guaranteed that one of the handlers will be invoked after
 * calling this function. When you are done watching the name, just
 * call g_bus_unwatch_name() with the watcher id this function
 * returns.
 *
 * If the name vanishes or appears (for example the application owning
 * the name could restart), the handlers are also invoked. If the
 * #GDBusConnection that is used for watching the name disconnects, then
 * @name_vanished_handler is invoked since it is no longer
 * possible to access the name.
 *
 * Another guarantee is that invocations of @name_appeared_handler
 * and @name_vanished_handler are guaranteed to alternate; that
 * is, if @name_appeared_handler is invoked then you are
 * guaranteed that the next time one of the handlers is invoked, it
 * will be @name_vanished_handler. The reverse is also true.
 *
578 579 580 581 582
 * This behavior makes it very simple to write applications that want
 * to take action when a certain [name exists][gdbus-watching-names].
 * Basically, the application should create object proxies in
 * @name_appeared_handler and destroy them again (if any) in
 * @name_vanished_handler.
583 584 585
 *
 * Returns: An identifier (never 0) that an be used with
 * g_bus_unwatch_name() to stop watching the name.
586 587 588
 *
 * Since: 2.26
 */
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
guint
g_bus_watch_name (GBusType                  bus_type,
                  const gchar              *name,
                  GBusNameWatcherFlags      flags,
                  GBusNameAppearedCallback  name_appeared_handler,
                  GBusNameVanishedCallback  name_vanished_handler,
                  gpointer                  user_data,
                  GDestroyNotify            user_data_free_func)
{
  Client *client;

  g_return_val_if_fail (g_dbus_is_name (name), 0);

  G_LOCK (lock);

  client = g_new0 (Client, 1);
  client->ref_count = 1;
606
  client->id = g_atomic_int_add (&next_global_id, 1); /* TODO: uh oh, handle overflow */
607 608 609 610 611 612
  client->name = g_strdup (name);
  client->flags = flags;
  client->name_appeared_handler = name_appeared_handler;
  client->name_vanished_handler = name_vanished_handler;
  client->user_data = user_data;
  client->user_data_free_func = user_data_free_func;
613
  client->main_context = g_main_context_ref_thread_default ();
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632

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

633 634
/**
 * g_bus_watch_name_on_connection:
635
 * @connection: A #GDBusConnection.
636 637
 * @name: The name (well-known or unique) to watch.
 * @flags: Flags from the #GBusNameWatcherFlags enumeration.
638 639
 * @name_appeared_handler: (nullable): Handler to invoke when @name is known to exist or %NULL.
 * @name_vanished_handler: (nullable): Handler to invoke when @name is known to not exist or %NULL.
640
 * @user_data: User data to pass to handlers.
641
 * @user_data_free_func: (nullable): Function for freeing @user_data or %NULL.
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
 *
 * Like g_bus_watch_name() but takes a #GDBusConnection instead of a
 * #GBusType.
 *
 * Returns: An identifier (never 0) that an be used with
 * g_bus_unwatch_name() to stop watching the name.
 *
 * Since: 2.26
 */
guint g_bus_watch_name_on_connection (GDBusConnection          *connection,
                                      const gchar              *name,
                                      GBusNameWatcherFlags      flags,
                                      GBusNameAppearedCallback  name_appeared_handler,
                                      GBusNameVanishedCallback  name_vanished_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), 0);

  G_LOCK (lock);

  client = g_new0 (Client, 1);
  client->ref_count = 1;
668
  client->id = g_atomic_int_add (&next_global_id, 1); /* TODO: uh oh, handle overflow */
669 670 671 672 673 674
  client->name = g_strdup (name);
  client->flags = flags;
  client->name_appeared_handler = name_appeared_handler;
  client->name_vanished_handler = name_vanished_handler;
  client->user_data = user_data;
  client->user_data_free_func = user_data_free_func;
675
  client->main_context = g_main_context_ref_thread_default ();
676 677

  if (map_id_to_client == NULL)
678 679
    map_id_to_client = g_hash_table_new (g_direct_hash, g_direct_equal);

680 681 682 683 684 685 686 687 688 689 690 691
  g_hash_table_insert (map_id_to_client,
                       GUINT_TO_POINTER (client->id),
                       client);

  client->connection = g_object_ref (connection);
  G_UNLOCK (lock);

  has_connection (client);

  return client->id;
}

692 693 694 695 696
typedef struct {
  GClosure *name_appeared_closure;
  GClosure *name_vanished_closure;
} WatchNameData;

697 698 699 700 701 702 703 704 705 706 707 708 709
static WatchNameData *
watch_name_data_new (GClosure *name_appeared_closure,
                     GClosure *name_vanished_closure)
{
  WatchNameData *data;

  data = g_new0 (WatchNameData, 1);

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

  if (name_vanished_closure != NULL)
    {
      data->name_vanished_closure = g_closure_ref (name_vanished_closure);
      g_closure_sink (name_vanished_closure);
      if (G_CLOSURE_NEEDS_MARSHAL (name_vanished_closure))
718
        g_closure_set_marshal (name_vanished_closure, g_cclosure_marshal_generic);
719 720 721 722 723
    }

  return data;
}

724 725 726 727 728 729 730
static void
watch_with_closures_on_name_appeared (GDBusConnection *connection,
                                      const gchar     *name,
                                      const gchar     *name_owner,
                                      gpointer         user_data)
{
  WatchNameData *data = user_data;
Javier Jardón's avatar
Javier Jardón committed
731
  GValue params[3] = { G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT };
732 733 734 735 736 737 738 739 740 741 742

  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_value_init (&params[2], G_TYPE_STRING);
  g_value_set_string (&params[2], name_owner);

  g_closure_invoke (data->name_appeared_closure, NULL, 3, params, NULL);
743 744 745 746

  g_value_unset (params + 0);
  g_value_unset (params + 1);
  g_value_unset (params + 2);
747 748 749 750 751 752 753 754
}

static void
watch_with_closures_on_name_vanished (GDBusConnection *connection,
                                      const gchar     *name,
                                      gpointer         user_data)
{
  WatchNameData *data = user_data;
Javier Jardón's avatar
Javier Jardón committed
755
  GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
756 757 758 759 760 761 762 763

  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_vanished_closure, NULL, 2, params, NULL);
764 765 766

  g_value_unset (params + 0);
  g_value_unset (params + 1);
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
}

static void
bus_watch_name_free_func (gpointer user_data)
{
  WatchNameData *data = user_data;

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

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

  g_free (data);
}

/**
784
 * g_bus_watch_name_with_closures: (rename-to g_bus_watch_name)
785 786 787
 * @bus_type: The type of bus to watch a name on.
 * @name: The name (well-known or unique) to watch.
 * @flags: Flags from the #GBusNameWatcherFlags enumeration.
788
 * @name_appeared_closure: (nullable): #GClosure to invoke when @name is known
789
 * to exist or %NULL.
790
 * @name_vanished_closure: (nullable): #GClosure to invoke when @name is known
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
 * to not exist or %NULL.
 *
 * Version of g_bus_watch_name() using closures instead of callbacks for
 * easier binding in other languages.
 *
 * Returns: An identifier (never 0) that an be used with
 * g_bus_unwatch_name() to stop watching the name.
 *
 * Since: 2.26
 */
guint
g_bus_watch_name_with_closures (GBusType                 bus_type,
                                const gchar             *name,
                                GBusNameWatcherFlags     flags,
                                GClosure                *name_appeared_closure,
                                GClosure                *name_vanished_closure)
{
  return g_bus_watch_name (bus_type,
          name,
          flags,
          name_appeared_closure != NULL ? watch_with_closures_on_name_appeared : NULL,
          name_vanished_closure != NULL ? watch_with_closures_on_name_vanished : NULL,
813
          watch_name_data_new (name_appeared_closure, name_vanished_closure),
814 815 816 817
          bus_watch_name_free_func);
}

/**
818
 * g_bus_watch_name_on_connection_with_closures: (rename-to g_bus_watch_name_on_connection)
819
 * @connection: A #GDBusConnection.
820 821
 * @name: The name (well-known or unique) to watch.
 * @flags: Flags from the #GBusNameWatcherFlags enumeration.
822
 * @name_appeared_closure: (nullable): #GClosure to invoke when @name is known
823
 * to exist or %NULL.
824
 * @name_vanished_closure: (nullable): #GClosure to invoke when @name is known
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
 * to not exist or %NULL.
 *
 * Version of g_bus_watch_name_on_connection() using closures instead of callbacks for
 * easier binding in other languages.
 *
 * Returns: An identifier (never 0) that an be used with
 * g_bus_unwatch_name() to stop watching the name.
 *
 * Since: 2.26
 */
guint g_bus_watch_name_on_connection_with_closures (
                                      GDBusConnection          *connection,
                                      const gchar              *name,
                                      GBusNameWatcherFlags      flags,
                                      GClosure                 *name_appeared_closure,
                                      GClosure                 *name_vanished_closure)
{
  return g_bus_watch_name_on_connection (connection,
          name,
          flags,
          name_appeared_closure != NULL ? watch_with_closures_on_name_appeared : NULL,
          name_vanished_closure != NULL ? watch_with_closures_on_name_vanished : NULL,
847
          watch_name_data_new (name_appeared_closure, name_vanished_closure),
848 849 850
          bus_watch_name_free_func);
}

851 852 853 854 855
/**
 * g_bus_unwatch_name:
 * @watcher_id: An identifier obtained from g_bus_watch_name()
 *
 * Stops watching a name.
856 857 858
 *
 * Since: 2.26
 */
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
void
g_bus_unwatch_name (guint watcher_id)
{
  Client *client;

  g_return_if_fail (watcher_id > 0);

  client = NULL;

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

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

 out:
  G_UNLOCK (lock);

  /* do callback without holding lock */
  if (client != NULL)
    {
      client_unref (client);
    }
}