services.c 35.8 KB
Newer Older
1
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 3 4
/* services.c  Service management
 *
 * Copyright (C) 2003  Red Hat, Inc.
5
 * Copyright (C) 2003  CodeFactory AB
6
 *
7
 * Licensed under the Academic Free License version 2.1
8 9 10 11 12 13 14 15 16 17 18 19 20
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
22 23
 *
 */
24 25

#include <config.h>
26 27 28
#include <dbus/dbus-hash.h>
#include <dbus/dbus-list.h>
#include <dbus/dbus-mempool.h>
29
#include <dbus/dbus-marshal-validate.h>
30

31 32 33 34
#include "driver.h"
#include "services.h"
#include "connection.h"
#include "utils.h"
35
#include "activation.h"
36
#include "policy.h"
37 38
#include "bus.h"
#include "selinux.h"
39
#include "apparmor.h"
40

41 42
struct BusService
{
43 44
  int refcount;

45
  BusRegistry *registry;
46 47
  char *name;
  DBusList *owners;
48 49 50 51 52 53 54 55 56 57 58
};

struct BusOwner
{
  int refcount;

  BusService *service;
  DBusConnection *conn;

  unsigned int allow_replacement : 1;
  unsigned int do_not_queue : 1;
59 60
};

61 62 63
struct BusRegistry
{
  int refcount;
64 65

  BusContext *context;
66 67 68
  
  DBusHashTable *service_hash;
  DBusMemPool   *service_pool;
69
  DBusMemPool   *owner_pool;
70 71

  DBusHashTable *service_sid_table;
72 73 74
};

BusRegistry*
75
bus_registry_new (BusContext *context)
76 77 78
{
  BusRegistry *registry;

79
  _dbus_assert (context);
80 81 82 83 84
  registry = dbus_new0 (BusRegistry, 1);
  if (registry == NULL)
    return NULL;

  registry->refcount = 1;
85 86
  registry->context = context;
  
87 88 89 90 91 92 93
  registry->service_hash = _dbus_hash_table_new (DBUS_HASH_STRING,
                                                 NULL, NULL);
  if (registry->service_hash == NULL)
    goto failed;
  
  registry->service_pool = _dbus_mem_pool_new (sizeof (BusService),
                                               TRUE);
94

95 96 97
  if (registry->service_pool == NULL)
    goto failed;

98 99 100 101 102 103
  registry->owner_pool = _dbus_mem_pool_new (sizeof (BusOwner),
                                             TRUE);

  if (registry->owner_pool == NULL)
    goto failed;

104 105
  registry->service_sid_table = NULL;
  
106 107 108 109 110 111 112
  return registry;

 failed:
  bus_registry_unref (registry);
  return NULL;
}

113
BusRegistry *
114 115 116 117
bus_registry_ref (BusRegistry *registry)
{
  _dbus_assert (registry->refcount > 0);
  registry->refcount += 1;
118 119

  return registry;
120
}
121

122 123
void
bus_registry_unref  (BusRegistry *registry)
124
{
125 126 127 128
  _dbus_assert (registry->refcount > 0);
  registry->refcount -= 1;

  if (registry->refcount == 0)
129
    {
130 131 132 133
      if (registry->service_hash)
        _dbus_hash_table_unref (registry->service_hash);
      if (registry->service_pool)
        _dbus_mem_pool_free (registry->service_pool);
134 135
      if (registry->owner_pool)
        _dbus_mem_pool_free (registry->owner_pool);
136 137 138
      if (registry->service_sid_table)
        _dbus_hash_table_unref (registry->service_sid_table);
      
139
      dbus_free (registry);
140
    }
141 142 143
}

BusService*
144 145
bus_registry_lookup (BusRegistry      *registry,
                     const DBusString *service_name)
146 147
{
  BusService *service;
148

149
  service = _dbus_hash_table_lookup_string (registry->service_hash,
150
                                            _dbus_string_get_const_data (service_name));
151

152 153 154
  return service;
}

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 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
static DBusList *
_bus_service_find_owner_link (BusService *service,
                              DBusConnection *connection)
{
  DBusList *link;
  
  link = _dbus_list_get_first_link (&service->owners);

  while (link != NULL)
    {
      BusOwner *bus_owner;

      bus_owner = (BusOwner *) link->data;
      if (bus_owner->conn == connection) 
        break;

      link = _dbus_list_get_next_link (&service->owners, link);
    }

  return link;
}

static void
bus_owner_set_flags (BusOwner *owner,
                     dbus_uint32_t flags)
{
   owner->allow_replacement = 
        (flags & DBUS_NAME_FLAG_ALLOW_REPLACEMENT) != FALSE;

   owner->do_not_queue =
        (flags & DBUS_NAME_FLAG_DO_NOT_QUEUE) != FALSE;
}

static BusOwner *
bus_owner_new (BusService *service, 
               DBusConnection *conn, 
	       dbus_uint32_t flags)
{
  BusOwner *result;

  result = _dbus_mem_pool_alloc (service->registry->owner_pool);
  if (result != NULL)
    {
      result->refcount = 1;
      /* don't ref the connection because we don't want
         to block the connection from going away.
         transactions take care of reffing the connection
         but we need to use refcounting on the owner
         so that the owner does not get freed before
         we can deref the connection in the transaction
       */
      result->conn = conn;
      result->service = service;

      if (!bus_connection_add_owned_service (conn, service))
        {
          _dbus_mem_pool_dealloc (service->registry->owner_pool, result);
          return NULL;
        }
        
      bus_owner_set_flags (result, flags);
    }
  return result;
}

static BusOwner *
bus_owner_ref (BusOwner *owner)
{
  _dbus_assert (owner->refcount > 0);
  owner->refcount += 1;

  return owner;
}

static void
bus_owner_unref  (BusOwner *owner)
{
  _dbus_assert (owner->refcount > 0);
  owner->refcount -= 1;

  if (owner->refcount == 0)
    {
      bus_connection_remove_owned_service (owner->conn, owner->service);
      _dbus_mem_pool_dealloc (owner->service->registry->owner_pool, owner);
    }
}

242
BusService*
243 244
bus_registry_ensure (BusRegistry               *registry,
                     const DBusString          *service_name,
245 246
                     DBusConnection            *owner_connection_if_created,
                     dbus_uint32_t              flags,
247 248
                     BusTransaction            *transaction,
                     DBusError                 *error)
249 250 251
{
  BusService *service;

252 253
  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
  
254
  _dbus_assert (owner_connection_if_created != NULL);
255 256
  _dbus_assert (transaction != NULL);

257
  service = _dbus_hash_table_lookup_string (registry->service_hash,
258
                                            _dbus_string_get_const_data (service_name));
259 260 261
  if (service != NULL)
    return service;
  
262
  service = _dbus_mem_pool_alloc (registry->service_pool);
263
  if (service == NULL)
264 265 266 267
    {
      BUS_SET_OOM (error);
      return NULL;
    }
268

269
  service->registry = registry;  
270
  service->refcount = 1;
271 272 273

  _dbus_verbose ("copying string %p '%s' to service->name\n",
                 service_name, _dbus_string_get_const_data (service_name));
274
  if (!_dbus_string_copy_data (service_name, &service->name))
275
    {
276
      _dbus_mem_pool_dealloc (registry->service_pool, service);
277
      BUS_SET_OOM (error);
278 279
      return NULL;
    }
280 281 282
  _dbus_verbose ("copied string %p '%s' to '%s'\n",
                 service_name, _dbus_string_get_const_data (service_name),
                 service->name);
283

284 285
  if (!bus_driver_send_service_owner_changed (service->name, 
					      NULL,
286
					      bus_connection_get_name (owner_connection_if_created),
287
					      transaction, error))
288
    {
289
      bus_service_unref (service);
290 291 292
      return NULL;
    }

293
  if (!bus_activation_service_created (bus_context_get_activation (registry->context),
294
				       service->name, transaction, error))
295
    {
296
      bus_service_unref (service);
297 298 299
      return NULL;
    }
  
300 301
  if (!bus_service_add_owner (service, owner_connection_if_created, flags,
                                              transaction, error))
302
    {
303
      bus_service_unref (service);
304 305 306
      return NULL;
    }
  
307
  if (!_dbus_hash_table_insert_string (registry->service_hash,
308 309 310
                                       service->name,
                                       service))
    {
311
      /* The add_owner gets reverted on transaction cancel */
312
      BUS_SET_OOM (error);
313 314
      return NULL;
    }
315
  
316 317 318
  return service;
}

319 320 321 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 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
void
bus_registry_foreach (BusRegistry               *registry,
                      BusServiceForeachFunction  function,
                      void                      *data)
{
  DBusHashIter iter;
  
  _dbus_hash_iter_init (registry->service_hash, &iter);
  while (_dbus_hash_iter_next (&iter))
    {
      BusService *service = _dbus_hash_iter_get_value (&iter);

      (* function) (service, data);
    }
}

dbus_bool_t
bus_registry_list_services (BusRegistry *registry,
                            char      ***listp,
                            int         *array_len)
{
  int i, j, len;
  char **retval;
  DBusHashIter iter;
   
  len = _dbus_hash_table_get_n_entries (registry->service_hash);
  retval = dbus_new (char *, len + 1);

  if (retval == NULL)
    return FALSE;

  _dbus_hash_iter_init (registry->service_hash, &iter);
  i = 0;
  while (_dbus_hash_iter_next (&iter))
    {
      BusService *service = _dbus_hash_iter_get_value (&iter);

      retval[i] = _dbus_strdup (service->name);
      if (retval[i] == NULL)
	goto error;

      i++;
    }

  retval[i] = NULL;
  
  if (array_len)
    *array_len = len;
  
  *listp = retval;
  return TRUE;
  
 error:
  for (j = 0; j < i; j++)
373
    dbus_free (retval[j]);
374 375 376 377 378
  dbus_free (retval);

  return FALSE;
}

379 380 381 382 383 384 385 386 387 388
dbus_bool_t
bus_registry_acquire_service (BusRegistry      *registry,
                              DBusConnection   *connection,
                              const DBusString *service_name,
                              dbus_uint32_t     flags,
                              dbus_uint32_t    *result,
                              BusTransaction   *transaction,
                              DBusError        *error)
{
  dbus_bool_t retval;
389
  DBusConnection *old_owner_conn;
390
  BusClientPolicy *policy;
391
  BusService *service;
392
  BusActivation  *activation;
393
  BusSELinuxID *sid;
394
  BusOwner *primary_owner;
395 396
  int limit;

397 398
  retval = FALSE;

399 400
  if (!_dbus_validate_bus_name (service_name, 0,
                                _dbus_string_get_length (service_name)))
401
    {
402 403 404
      dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
                      "Requested bus name \"%s\" is not valid",
                      _dbus_string_get_const_data (service_name));
405
      
406
      _dbus_verbose ("Attempt to acquire invalid service name\n");
407 408 409 410 411 412 413
      
      goto out;
    }
  
  if (_dbus_string_get_byte (service_name, 0) == ':')
    {
      /* Not allowed; only base services can start with ':' */
414
      dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
415 416 417 418 419 420 421 422
                      "Cannot acquire a service starting with ':' such as \"%s\"",
                      _dbus_string_get_const_data (service_name));
      
      _dbus_verbose ("Attempt to acquire invalid base service name \"%s\"",
                     _dbus_string_get_const_data (service_name));
      
      goto out;
    }
423

424 425 426 427 428 429 430 431 432 433 434 435
  if (_dbus_string_equal_c_str (service_name, DBUS_SERVICE_DBUS))
    {
      dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
                      "Connection \"%s\" is not allowed to own the service \"%s\"because "
                      "it is reserved for D-Bus' use only",
                      bus_connection_is_active (connection) ?
                      bus_connection_get_name (connection) :
                      "(inactive)",
                      DBUS_SERVICE_DBUS);
      goto out;
    }

436 437
  policy = bus_connection_get_policy (connection);
  _dbus_assert (policy != NULL);
438

439 440 441 442 443 444
  /* Note that if sid is #NULL then the bus's own context gets used
   * in bus_connection_selinux_allows_acquire_service()
   */
  sid = bus_selinux_id_table_lookup (registry->service_sid_table,
                                     service_name);

445
  if (!bus_selinux_allows_acquire_service (connection, sid,
446
					   _dbus_string_get_const_data (service_name), error))
447
    {
448 449 450 451 452 453 454

      if (dbus_error_is_set (error) &&
	  dbus_error_has_name (error, DBUS_ERROR_NO_MEMORY))
	{
	  goto out;
	}

455 456 457 458 459 460
      dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
                      "Connection \"%s\" is not allowed to own the service \"%s\" due "
                      "to SELinux policy",
                      bus_connection_is_active (connection) ?
                      bus_connection_get_name (connection) :
                      "(inactive)",
461
                      _dbus_string_get_const_data (service_name));
462 463
      goto out;
    }
464 465

  if (!bus_apparmor_allows_acquire_service (connection,
466
                                            bus_context_get_type (registry->context),
467 468
                                            _dbus_string_get_const_data (service_name), error))
    goto out;
469
  
470
  if (!bus_client_policy_check_can_own (policy, service_name))
471 472 473 474 475 476
    {
      dbus_set_error (error, DBUS_ERROR_ACCESS_DENIED,
                      "Connection \"%s\" is not allowed to own the service \"%s\" due "
                      "to security policies in the configuration file",
                      bus_connection_is_active (connection) ?
                      bus_connection_get_name (connection) :
477
                      "(inactive)",
478
                      _dbus_string_get_const_data (service_name));
479 480 481
      goto out;
    }

482 483 484
  limit = bus_context_get_max_services_per_connection (registry->context);

  if (bus_connection_get_n_services_owned (connection) >= limit)
485
    {
486 487 488 489
      DBusError tmp_error;

      dbus_error_init (&tmp_error);
      dbus_set_error (&tmp_error, DBUS_ERROR_LIMITS_EXCEEDED,
490
                      "Connection \"%s\" is not allowed to own more services "
491 492
                      "(increase limits in configuration file if required; "
                      "max_names_per_connection=%d)",
493 494
                      bus_connection_is_active (connection) ?
                      bus_connection_get_name (connection) :
495 496 497 498 499
                      "(inactive)",
                      limit);
      bus_context_log (registry->context, DBUS_SYSTEM_LOG_WARNING,
          "%s", tmp_error.message);
      dbus_move_error (&tmp_error, error);
500 501
      goto out;
    }
502 503 504 505
  
  service = bus_registry_lookup (registry, service_name);

  if (service != NULL)
506 507 508 509 510 511 512
    {
      primary_owner = bus_service_get_primary_owner (service);
      if (primary_owner != NULL)
        old_owner_conn = primary_owner->conn;
      else
        old_owner_conn = NULL;
    }
513
  else
514
    old_owner_conn = NULL;
515 516 517 518
      
  if (service == NULL)
    {
      service = bus_registry_ensure (registry,
519 520
                                     service_name, connection, flags,
                                     transaction, error);
521 522 523 524
      if (service == NULL)
        goto out;
    }

525 526 527
  primary_owner = bus_service_get_primary_owner (service);
  if (primary_owner == NULL)
    goto out;
528

529
  if (old_owner_conn == NULL)
530
    {
531
      _dbus_assert (primary_owner->conn == connection);
532

533
      *result = DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER;      
534
    }
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
  else if (old_owner_conn == connection)
    {
      bus_owner_set_flags (primary_owner, flags);
      *result = DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER;
    }
  else if (((flags & DBUS_NAME_FLAG_DO_NOT_QUEUE) &&
           !(bus_service_get_allow_replacement (service))) ||
	   ((flags & DBUS_NAME_FLAG_DO_NOT_QUEUE) &&
           !(flags & DBUS_NAME_FLAG_REPLACE_EXISTING))) 
    {
      DBusList *link;
      BusOwner *temp_owner;
    /* Since we can't be queued if we are already in the queue
       remove us */

      link = _bus_service_find_owner_link (service, connection);
      if (link != NULL)
        {
          _dbus_list_unlink (&service->owners, link);
          temp_owner = (BusOwner *)link->data;
          bus_owner_unref (temp_owner); 
          _dbus_list_free_link (link);
        }
      
      *result = DBUS_REQUEST_NAME_REPLY_EXISTS;
    }
  else if (!(flags & DBUS_NAME_FLAG_DO_NOT_QUEUE) &&
           (!(flags & DBUS_NAME_FLAG_REPLACE_EXISTING) ||
	    !(bus_service_get_allow_replacement (service))))
564 565
    {
      /* Queue the connection */
566 567
      if (!bus_service_add_owner (service, connection, 
                                  flags,
568 569 570
                                  transaction, error))
        goto out;
      
571
      *result = DBUS_REQUEST_NAME_REPLY_IN_QUEUE;
572 573 574 575 576 577
    }
  else
    {
      /* Replace the current owner */

      /* We enqueue the new owner and remove the first one because
578
       * that will cause NameAcquired and NameLost messages to
579 580 581 582
       * be sent.
       */
      
      if (!bus_service_add_owner (service, connection,
583
                                  flags,
584 585 586
                                  transaction, error))
        goto out;

587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
      if (primary_owner->do_not_queue)
        {
          if (!bus_service_remove_owner (service, old_owner_conn,
                                         transaction, error))
            goto out;
        }
      else
        {
          if (!bus_service_swap_owner (service, old_owner_conn,
                                       transaction, error))
            goto out;
        }
        
    
      _dbus_assert (connection == bus_service_get_primary_owner (service)->conn);
602
      *result = DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER;
603 604
    }

605 606 607
  activation = bus_context_get_activation (registry->context);
  retval = bus_activation_send_pending_auto_activation_messages (activation,
								 service,
608 609 610
								 transaction);
  if (!retval)
    BUS_SET_OOM (error);
611 612 613 614 615
  
 out:
  return retval;
}

616 617 618 619 620 621 622 623 624 625 626 627 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
dbus_bool_t
bus_registry_release_service (BusRegistry      *registry,
                              DBusConnection   *connection,
                              const DBusString *service_name,
                              dbus_uint32_t    *result,
                              BusTransaction   *transaction,
                              DBusError        *error)
{
  dbus_bool_t retval;
  BusService *service;

  retval = FALSE;

  if (!_dbus_validate_bus_name (service_name, 0,
                                _dbus_string_get_length (service_name)))
    {
      dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
                      "Given bus name \"%s\" is not valid",
                      _dbus_string_get_const_data (service_name));

      _dbus_verbose ("Attempt to release invalid service name\n");

      goto out;
    }

  if (_dbus_string_get_byte (service_name, 0) == ':')
    {
      /* Not allowed; the base service name cannot be created or released */
      dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
                      "Cannot release a service starting with ':' such as \"%s\"",
                      _dbus_string_get_const_data (service_name));

      _dbus_verbose ("Attempt to release invalid base service name \"%s\"",
                     _dbus_string_get_const_data (service_name));

      goto out;
    }

654 655 656 657 658 659 660 661 662 663 664 665 666
   if (_dbus_string_equal_c_str (service_name, DBUS_SERVICE_DBUS))
    {
      /* Not allowed; the base service name cannot be created or released */
      dbus_set_error (error, DBUS_ERROR_INVALID_ARGS,
                      "Cannot release the %s service because it is owned by the bus",
                     DBUS_SERVICE_DBUS);

      _dbus_verbose ("Attempt to release service name \"%s\"",
                     DBUS_SERVICE_DBUS);

      goto out;
    }

667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
  service = bus_registry_lookup (registry, service_name);

  if (service == NULL)
    {
      *result = DBUS_RELEASE_NAME_REPLY_NON_EXISTENT;
    }
  else if (!bus_service_has_owner (service, connection))
    {
      *result = DBUS_RELEASE_NAME_REPLY_NOT_OWNER;
    }
  else
    {
      if (!bus_service_remove_owner (service, connection,
                                     transaction, error))
        goto out;

      _dbus_assert (!bus_service_has_owner (service, connection));
      *result = DBUS_RELEASE_NAME_REPLY_RELEASED;
    }

  retval = TRUE;

 out:
  return retval;
}

693 694 695
dbus_bool_t
bus_registry_set_service_context_table (BusRegistry   *registry,
					DBusHashTable *table)
696
{
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
  DBusHashTable *new_table;
  DBusHashIter iter;
  
  new_table = bus_selinux_id_table_new ();
  if (!new_table)
    return FALSE;

  _dbus_hash_iter_init (table, &iter);
  while (_dbus_hash_iter_next (&iter))
    {
      const char *service = _dbus_hash_iter_get_string_key (&iter);
      const char *context = _dbus_hash_iter_get_value (&iter);

      if (!bus_selinux_id_table_insert (new_table,
					service,
					context))
	return FALSE;
    }
715 716 717
  
  if (registry->service_sid_table)
    _dbus_hash_table_unref (registry->service_sid_table);
718 719
  registry->service_sid_table = new_table;
  return TRUE;
720 721
}

722 723
static void
bus_service_unlink_owner (BusService      *service,
724
                          BusOwner        *owner)
725 726
{
  _dbus_list_remove_last (&service->owners, owner);
727
  bus_owner_unref (owner);
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
}

static void
bus_service_unlink (BusService *service)
{
  _dbus_assert (service->owners == NULL);

  /* the service may not be in the hash, if
   * the failure causing transaction cancel
   * was in the right place, but that's OK
   */
  _dbus_hash_table_remove_string (service->registry->service_hash,
                                  service->name);
  
  bus_service_unref (service);
}

static void
bus_service_relink (BusService           *service,
                    DBusPreallocatedHash *preallocated)
{
  _dbus_assert (service->owners == NULL);
  _dbus_assert (preallocated != NULL);

  _dbus_hash_table_insert_string_preallocated (service->registry->service_hash,
                                               preallocated,
                                               service->name,
                                               service);
  
  bus_service_ref (service);
}

760 761 762 763
/**
 * Data used to represent an ownership cancellation in
 * a bus transaction.
 */
764 765
typedef struct
{
766
  BusOwner *owner;            /**< the owner */
767
  BusService *service;        /**< service to cancel ownership of */
768 769 770 771 772 773 774 775 776 777 778
} OwnershipCancelData;

static void
cancel_ownership (void *data)
{
  OwnershipCancelData *d = data;

  /* We don't need to send messages notifying of these
   * changes, since we're reverting something that was
   * cancelled (effectively never really happened)
   */
779
  bus_service_unlink_owner (d->service, d->owner);
780 781 782 783 784 785 786 787 788 789
  
  if (d->service->owners == NULL)
    bus_service_unlink (d->service);
}

static void
free_ownership_cancel_data (void *data)
{
  OwnershipCancelData *d = data;

790 791
  dbus_connection_unref (d->owner->conn);
  bus_owner_unref (d->owner);
792 793 794 795 796 797 798 799
  bus_service_unref (d->service);
  
  dbus_free (d);
}

static dbus_bool_t
add_cancel_ownership_to_transaction (BusTransaction *transaction,
                                     BusService     *service,
800
                                     BusOwner       *owner)
801 802 803 804 805 806 807 808
{
  OwnershipCancelData *d;

  d = dbus_new (OwnershipCancelData, 1);
  if (d == NULL)
    return FALSE;
  
  d->service = service;
809
  d->owner = owner;
810 811 812 813 814 815 816 817 818

  if (!bus_transaction_add_cancel_hook (transaction, cancel_ownership, d,
                                        free_ownership_cancel_data))
    {
      dbus_free (d);
      return FALSE;
    }

  bus_service_ref (d->service);
819 820 821
  bus_owner_ref (owner);
  dbus_connection_ref (d->owner->conn);
 
822 823 824 825
  return TRUE;
}

/* this function is self-cancelling if you cancel the transaction */
826 827
dbus_bool_t
bus_service_add_owner (BusService     *service,
828 829
                       DBusConnection *connection,
                       dbus_uint32_t  flags,
830 831
                       BusTransaction *transaction,
                       DBusError      *error)
832
{
833 834 835
  BusOwner *bus_owner;
  DBusList *bus_owner_link;
  
836 837
  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
  
838 839 840 841 842
 /* Send service acquired message first, OOM will result
  * in cancelling the transaction
  */
  if (service->owners == NULL)
    {
843
      if (!bus_driver_send_service_acquired (connection, service->name, transaction, error))
844 845 846
        return FALSE;
    }
  
847 848 849
  bus_owner_link = _bus_service_find_owner_link (service, connection);
  
  if (bus_owner_link == NULL)
850
    {
851 852 853 854 855 856
      bus_owner = bus_owner_new (service, connection, flags);
      if (bus_owner == NULL)
        {
          BUS_SET_OOM (error);
          return FALSE;
        }
857

858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
      bus_owner_set_flags (bus_owner, flags);
      if (!(flags & DBUS_NAME_FLAG_REPLACE_EXISTING) || service->owners == NULL)
        {
          if (!_dbus_list_append (&service->owners,
                                  bus_owner))
            {
              bus_owner_unref (bus_owner);
              BUS_SET_OOM (error);
              return FALSE;
            }
        }
      else
        {
          if (!_dbus_list_insert_after (&service->owners,
                                         _dbus_list_get_first_link (&service->owners),
                                         bus_owner))
            {
              bus_owner_unref (bus_owner);
              BUS_SET_OOM (error);
              return FALSE;
            }
        }      
    } 
  else 
882
    {
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
      /* Update the link since we are already in the queue
       * No need for operations that can produce OOM
       */

      bus_owner = (BusOwner *) bus_owner_link->data;
      if (flags & DBUS_NAME_FLAG_REPLACE_EXISTING)
        {
	  DBusList *link;
          _dbus_list_unlink (&service->owners, bus_owner_link);
	  link = _dbus_list_get_first_link (&service->owners);
	  _dbus_assert (link != NULL);
	  
          _dbus_list_insert_after_link (&service->owners, link, bus_owner_link);
        }
      
      bus_owner_set_flags (bus_owner, flags);
      return TRUE;
900
    }
901 902 903

  if (!add_cancel_ownership_to_transaction (transaction,
                                            service,
904
                                            bus_owner))
905
    {
906
      bus_service_unlink_owner (service, bus_owner);
907 908 909
      BUS_SET_OOM (error);
      return FALSE;
    }
910

911 912 913
  return TRUE;
}

914 915
typedef struct
{
916
  BusOwner       *owner;
917
  BusService     *service;
918 919
  BusOwner       *before_owner; /* restore to position before this connection in owners list */
  DBusList       *owner_link;
920 921 922 923 924 925 926 927 928 929 930
  DBusList       *service_link;
  DBusPreallocatedHash *hash_entry;
} OwnershipRestoreData;

static void
restore_ownership (void *data)
{
  OwnershipRestoreData *d = data;
  DBusList *link;

  _dbus_assert (d->service_link != NULL);
931
  _dbus_assert (d->owner_link != NULL);
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
  
  if (d->service->owners == NULL)
    {
      _dbus_assert (d->hash_entry != NULL);
      bus_service_relink (d->service, d->hash_entry);
    }
  else
    {
      _dbus_assert (d->hash_entry == NULL);
    }
  
  /* We don't need to send messages notifying of these
   * changes, since we're reverting something that was
   * cancelled (effectively never really happened)
   */
  link = _dbus_list_get_first_link (&d->service->owners);
  while (link != NULL)
    {
950
      if (link->data == d->before_owner)
951 952 953 954 955
        break;

      link = _dbus_list_get_next_link (&d->service->owners, link);
    }
  
956
  _dbus_list_insert_before_link (&d->service->owners, link, d->owner_link);
957 958 959 960 961 962 963

  /* Note that removing then restoring this changes the order in which
   * ServiceDeleted messages are sent on destruction of the
   * connection.  This should be OK as the only guarantee there is
   * that the base service is destroyed last, and we never even
   * tentatively remove the base service.
   */
964
  bus_connection_add_owned_service_link (d->owner->conn, d->service_link);
965 966 967
  
  d->hash_entry = NULL;
  d->service_link = NULL;
968
  d->owner_link = NULL;
969 970 971 972 973 974 975 976 977
}

static void
free_ownership_restore_data (void *data)
{
  OwnershipRestoreData *d = data;

  if (d->service_link)
    _dbus_list_free_link (d->service_link);
978 979
  if (d->owner_link)
    _dbus_list_free_link (d->owner_link);
980 981 982 983
  if (d->hash_entry)
    _dbus_hash_table_free_preallocated_entry (d->service->registry->service_hash,
                                              d->hash_entry);

984 985
  dbus_connection_unref (d->owner->conn);
  bus_owner_unref (d->owner);
986 987 988 989 990 991 992 993
  bus_service_unref (d->service);
  
  dbus_free (d);
}

static dbus_bool_t
add_restore_ownership_to_transaction (BusTransaction *transaction,
                                      BusService     *service,
994
                                      BusOwner       *owner)
995 996 997 998 999 1000 1001 1002 1003
{
  OwnershipRestoreData *d;
  DBusList *link;

  d = dbus_new (OwnershipRestoreData, 1);
  if (d == NULL)
    return FALSE;
  
  d->service = service;
1004
  d->owner = owner;
1005
  d->service_link = _dbus_list_alloc_link (service);
1006
  d->owner_link = _dbus_list_alloc_link (owner);
1007 1008 1009
  d->hash_entry = _dbus_hash_table_preallocate_entry (service->registry->service_hash);
  
  bus_service_ref (d->service);
1010 1011
  bus_owner_ref (d->owner);
  dbus_connection_ref (d->owner->conn);
1012

1013
  d->before_owner = NULL;
1014 1015 1016
  link = _dbus_list_get_first_link (&service->owners);
  while (link != NULL)
    {
1017
      if (link->data == owner)
1018 1019 1020 1021
        {
          link = _dbus_list_get_next_link (&service->owners, link);

          if (link)
1022
            d->before_owner = link->data;
1023 1024 1025 1026 1027 1028 1029 1030

          break;
        }
      
      link = _dbus_list_get_next_link (&service->owners, link);
    }
  
  if (d->service_link == NULL ||
1031
      d->owner_link == NULL ||
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
      d->hash_entry == NULL ||
      !bus_transaction_add_cancel_hook (transaction, restore_ownership, d,
                                        free_ownership_restore_data))
    {
      free_ownership_restore_data (d);
      return FALSE;
    }
  
  return TRUE;
}

1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
dbus_bool_t
bus_service_swap_owner (BusService     *service,
                        DBusConnection *connection,
                        BusTransaction *transaction,
                        DBusError      *error)
{
  DBusList *swap_link;
  BusOwner *primary_owner;

  _DBUS_ASSERT_ERROR_IS_CLEAR (error);

  /* We send out notifications before we do any work we
   * might have to undo if the notification-sending failed
   */
  
  /* Send service lost message */
  primary_owner = bus_service_get_primary_owner (service);
  if (primary_owner == NULL || primary_owner->conn != connection)
    _dbus_assert_not_reached ("Tried to swap a non primary owner");

    
  if (!bus_driver_send_service_lost (connection, service->name,
                                     transaction, error))
    return FALSE;

  if (service->owners == NULL)
    {
      _dbus_assert_not_reached ("Tried to swap owner of a service that has no owners");
    }
  else if (_dbus_list_length_is_one (&service->owners))
    {
      _dbus_assert_not_reached ("Tried to swap owner of a service that has no other owners in the queue");
    }
  else
    {
      DBusList *link;
      BusOwner *new_owner;
      DBusConnection *new_owner_conn;
      link = _dbus_list_get_first_link (&service->owners);
      _dbus_assert (link != NULL);
      link = _dbus_list_get_next_link (&service->owners, link);
      _dbus_assert (link != NULL);

      new_owner = (BusOwner *)link->data;
      new_owner_conn = new_owner->conn;

      if (!bus_driver_send_service_owner_changed (service->name,
 						  bus_connection_get_name (connection),
 						  bus_connection_get_name (new_owner_conn),
 						  transaction, error))
        return FALSE;

      /* This will be our new owner */
      if (!bus_driver_send_service_acquired (new_owner_conn,
                                             service->name,
                                             transaction,
                                             error))
        return FALSE;
    }

  if (!add_restore_ownership_to_transaction (transaction, service, primary_owner))
    {
      BUS_SET_OOM (error);
      return FALSE;
    }

  /* unlink the primary and make it the second link */
  swap_link = _dbus_list_get_first_link (&service->owners);
  _dbus_list_unlink (&service->owners, swap_link);

  _dbus_list_insert_after_link (&service->owners,
                                _dbus_list_get_first_link (&service->owners),
				swap_link);

  return TRUE;
}

1120
/* this function is self-cancelling if you cancel the transaction */
1121
dbus_bool_t
1122
bus_service_remove_owner (BusService     *service,
1123
                          DBusConnection *connection,
1124 1125
                          BusTransaction *transaction,
                          DBusError      *error)
1126
{
1127 1128
  BusOwner *primary_owner;
  
1129 1130
  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
  
1131 1132 1133 1134
  /* We send out notifications before we do any work we
   * might have to undo if the notification-sending failed
   */
  
1135
  /* Send service lost message */
1136 1137
  primary_owner = bus_service_get_primary_owner (service);
  if (primary_owner != NULL && primary_owner->conn == connection)
1138
    {
1139
      if (!bus_driver_send_service_lost (connection, service->name,
1140 1141 1142
                                         transaction, error))
        return FALSE;
    }
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
  else
    {
      /* if we are not the primary owner then just remove us from the queue */
      DBusList *link;
      BusOwner *temp_owner;

      link = _bus_service_find_owner_link (service, connection);
      _dbus_list_unlink (&service->owners, link);
      temp_owner = (BusOwner *)link->data;
      bus_owner_unref (temp_owner); 
      _dbus_list_free_link (link);

      return TRUE; 
    }
1157

1158 1159 1160 1161 1162
  if (service->owners == NULL)
    {
      _dbus_assert_not_reached ("Tried to remove owner of a service that has no owners");
    }
  else if (_dbus_list_length_is_one (&service->owners))
1163
    {
1164
      if (!bus_driver_send_service_owner_changed (service->name,
1165
 						  bus_connection_get_name (connection),
1166 1167
 						  NULL,
 						  transaction, error))
1168 1169 1170 1171 1172
        return FALSE;
    }
  else
    {
      DBusList *link;
1173 1174
      BusOwner *new_owner;
      DBusConnection *new_owner_conn;
1175
      link = _dbus_list_get_first_link (&service->owners);
1176
      _dbus_assert (link != NULL);
1177
      link = _dbus_list_get_next_link (&service->owners, link);
1178 1179
      _dbus_assert (link != NULL);

1180 1181
      new_owner = (BusOwner *)link->data;
      new_owner_conn = new_owner->conn;
1182 1183

      if (!bus_driver_send_service_owner_changed (service->name,
1184 1185
 						  bus_connection_get_name (connection),
 						  bus_connection_get_name (new_owner_conn),
1186 1187 1188
 						  transaction, error))
        return FALSE;

1189
      /* This will be our new owner */
1190
      if (!bus_driver_send_service_acquired (new_owner_conn,
1191 1192 1193 1194 1195 1196
                                             service->name,
                                             transaction,
                                             error))
        return FALSE;
    }

1197
  if (!add_restore_ownership_to_transaction (transaction, service, primary_owner))
1198 1199 1200
    {
      BUS_SET_OOM (error);
      return FALSE;
1201
    }
1202 1203
 
  bus_service_unlink_owner (service, primary_owner);
1204 1205

  if (service->owners == NULL)
1206 1207 1208 1209 1210
    bus_service_unlink (service);

  return TRUE;
}

1211
BusService *
1212 1213 1214 1215 1216
bus_service_ref (BusService *service)
{
  _dbus_assert (service->refcount > 0);
  
  service->refcount += 1;
1217 1218

  return service;
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
}

void
bus_service_unref (BusService *service)
{
  _dbus_assert (service->refcount > 0);
  
  service->refcount -= 1;

  if (service->refcount == 0)
1229
    {
1230
      _dbus_assert (service->owners == NULL);
1231 1232
      
      dbus_free (service->name);
1233
      _dbus_mem_pool_dealloc (service->registry->service_pool, service);
1234
    }
1235 1236
}

1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
DBusConnection *
bus_service_get_primary_owners_connection (BusService *service)
{
  BusOwner *owner;

  owner = bus_service_get_primary_owner (service);

  if (owner != NULL)
    return owner->conn;
  else
    return NULL;
}

BusOwner*
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
bus_service_get_primary_owner (BusService *service)
{
  return _dbus_list_get_first (&service->owners);
}

const char*
bus_service_get_name (BusService *service)
{
  return service->name;
}

1262 1263
dbus_bool_t
bus_service_get_allow_replacement (BusService *service)
1264
{
1265 1266 1267 1268 1269 1270 1271 1272 1273
  BusOwner *owner;
  DBusList *link;
 
  _dbus_assert (service->owners != NULL);

  link = _dbus_list_get_first_link (&service->owners);
  owner = (BusOwner *) link->data;

  return owner->allow_replacement;
1274 1275 1276
}

dbus_bool_t
1277 1278
bus_service_has_owner (BusService     *service,
		       DBusConnection *connection)
1279
{
1280 1281 1282 1283 1284 1285 1286 1287
  DBusList *link;

  link = _bus_service_find_owner_link (service, connection);
 
  if (link == NULL)
    return FALSE;
  else
    return TRUE;
1288 1289
}

1290 1291
dbus_bool_t 
bus_service_list_queued_owners (BusService *service,
1292
                                DBusList  **return_list)
1293 1294 1295
{
  DBusList *link;

1296 1297
  _dbus_assert (*return_list == NULL);

1298
  link = _dbus_list_get_first_link (&service->owners);
1299
  _dbus_assert (link != NULL);
1300 1301 1302
  
  while (link != NULL)
    {
1303 1304 1305 1306 1307 1308
      BusOwner *owner;
      const char *uname;

      owner = (BusOwner *) link->data;
      uname = bus_connection_get_name (owner->conn);

1309
      if (!_dbus_list_append (return_list, (char *)uname))
1310 1311
        goto oom;

1312 1313
      link = _dbus_list_get_next_link (&service->owners, link);
    }
1314 1315 1316 1317 1318
  
  return TRUE;
  
 oom:
  _dbus_list_clear (return_list);
1319 1320
  return FALSE;
}