dbus-server.c 35.3 KB
Newer Older
1
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 3
/* dbus-server.c DBusServer object
 *
4
 * Copyright (C) 2002, 2003, 2004, 2005 Red Hat Inc.
5
 *
6
 * Licensed under the Academic Free License version 2.1
7 8 9 10 11 12 13 14 15 16 17 18 19
 * 
 * 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
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
21
 *
22
 */ 
Mikael Hallendal's avatar
Mikael Hallendal committed
23

24
#include <config.h>
25 26
#include "dbus-server.h"
#include "dbus-server-unix.h"
27
#include "dbus-server-socket.h"
28
#include "dbus-string.h"
29
#ifdef DBUS_ENABLE_EMBEDDED_TESTS
30
#include "dbus-server-debug-pipe.h"
31
#endif
32
#include "dbus-address.h"
33
#include "dbus-protocol.h"
34 35 36 37 38 39 40 41

/**
 * @defgroup DBusServer DBusServer
 * @ingroup  DBus
 * @brief Server that listens for new connections.
 *
 * A DBusServer represents a server that other applications
 * can connect to. Each connection from another application
42
 * is represented by a #DBusConnection.
43
 *
44
 * @todo Thread safety hasn't been tested much for #DBusServer
45
 * @todo Need notification to apps of disconnection, may matter for some transports
46 47 48 49 50 51 52 53 54 55
 */

/**
 * @defgroup DBusServerInternals DBusServer implementation details
 * @ingroup  DBusInternals
 * @brief Implementation details of DBusServer
 *
 * @{
 */

56 57 58 59 60 61 62 63 64 65 66 67 68 69
#ifndef _dbus_server_trace_ref
void
_dbus_server_trace_ref (DBusServer *server,
    int old_refcount,
    int new_refcount,
    const char *why)
{
  static int enabled = -1;

  _dbus_trace_ref ("DBusServer", server, old_refcount, new_refcount, why,
      "DBUS_SERVER_TRACE", &enabled);
}
#endif

70 71 72 73 74
/* this is a little fragile since it assumes the address doesn't
 * already have a guid, but it shouldn't
 */
static char*
copy_address_with_guid_appended (const DBusString *address,
75
                                 const DBusString *guid_hex)
76 77 78 79 80 81 82
{
  DBusString with_guid;
  char *retval;
  
  if (!_dbus_string_init (&with_guid))
    return NULL;

83 84
  if (!_dbus_string_copy (address, 0, &with_guid,
                          _dbus_string_get_length (&with_guid)) ||
85
      !_dbus_string_append (&with_guid, ",guid=") ||
86 87
      !_dbus_string_copy (guid_hex, 0,
                          &with_guid, _dbus_string_get_length (&with_guid)))
88 89 90 91 92 93
    {
      _dbus_string_free (&with_guid);
      return NULL;
    }

  retval = NULL;
94
  _dbus_string_steal_data (&with_guid, &retval);
95 96 97

  _dbus_string_free (&with_guid);
      
98
  return retval; /* may be NULL if steal_data failed */
99 100
}

101 102 103 104 105 106
/**
 * Initializes the members of the DBusServer base class.
 * Chained up to by subclass constructors.
 *
 * @param server the server.
 * @param vtable the vtable for the subclass.
107
 * @param address the server's address
108
 * @param error location to store reason for failure
109 110 111 112
 * @returns #TRUE on success.
 */
dbus_bool_t
_dbus_server_init_base (DBusServer             *server,
113
                        const DBusServerVTable *vtable,
114 115
                        const DBusString       *address,
                        DBusError              *error)
116
{
117
  server->vtable = vtable;
118 119 120 121 122 123 124 125 126 127

#ifdef DBUS_DISABLE_ASSERT
  _dbus_atomic_inc (&server->refcount);
#else
    {
      dbus_int32_t old_refcount = _dbus_atomic_inc (&server->refcount);

      _dbus_assert (old_refcount == 0);
    }
#endif
128

129 130 131
  server->address = NULL;
  server->watches = NULL;
  server->timeouts = NULL;
132
  server->published_address = FALSE;
133

134
  if (!_dbus_string_init (&server->guid_hex))
135 136 137 138
    {
      _DBUS_SET_OOM (error);
      return FALSE;
    }
139

140 141
  if (!_dbus_generate_uuid (&server->guid, error))
    goto failed;
142

143
  if (!_dbus_uuid_encode (&server->guid, &server->guid_hex))
144
    goto oom;
145
  
146
  server->address = copy_address_with_guid_appended (address,
147
                                                     &server->guid_hex);
148
  if (server->address == NULL)
149
    goto oom;
150
  
151
  _dbus_rmutex_new_at_location (&server->mutex);
152
  if (server->mutex == NULL)
153
    goto oom;
154
  
155 156
  server->watches = _dbus_watch_list_new ();
  if (server->watches == NULL)
157
    goto oom;
158

159 160
  server->timeouts = _dbus_timeout_list_new ();
  if (server->timeouts == NULL)
161
    goto oom;
162 163 164 165 166 167 168

  _dbus_data_slot_list_init (&server->slot_list);

  _dbus_verbose ("Initialized server on address %s\n", server->address);
  
  return TRUE;

169 170
 oom:
  _DBUS_SET_OOM (error);
171
 failed:
172
  _dbus_rmutex_free_at_location (&server->mutex);
173
  server->mutex = NULL;
174
  if (server->watches)
175 176 177
    {
      _dbus_watch_list_free (server->watches);
      server->watches = NULL;
178 179 180
    }
  if (server->timeouts)
    {
181 182
      _dbus_timeout_list_free (server->timeouts);
      server->timeouts = NULL;
183
    }
184 185 186 187 188
  if (server->address)
    {
      dbus_free (server->address);
      server->address = NULL;
    }
189
  _dbus_string_free (&server->guid_hex);
190
  
191
  return FALSE;
192 193 194 195 196 197 198 199 200 201
}

/**
 * Finalizes the members of the DBusServer base class.
 * Chained up to by subclass finalizers.
 *
 * @param server the server.
 */
void
_dbus_server_finalize_base (DBusServer *server)
202 203 204 205 206 207 208 209 210
{
  /* We don't have the lock, but nobody should be accessing
   * concurrently since they don't have a ref
   */
#ifndef DBUS_DISABLE_CHECKS
  _dbus_assert (!server->have_server_lock);
#endif
  _dbus_assert (server->disconnected);
  
211 212 213
  /* calls out to application code... */
  _dbus_data_slot_list_free (&server->slot_list);

214 215 216
  dbus_server_set_new_connection_function (server, NULL, NULL, NULL);

  _dbus_watch_list_free (server->watches);
217
  _dbus_timeout_list_free (server->timeouts);
218

219
  _dbus_rmutex_free_at_location (&server->mutex);
220
  
221
  dbus_free (server->address);
222 223

  dbus_free_string_array (server->auth_mechanisms);
224 225

  _dbus_string_free (&server->guid_hex);
226 227
}

228

229
/** Function to be called in protected_change_watch() with refcount held */
230 231
typedef dbus_bool_t (* DBusWatchAddFunction)     (DBusWatchList *list,
                                                  DBusWatch     *watch);
232
/** Function to be called in protected_change_watch() with refcount held */
233 234
typedef void        (* DBusWatchRemoveFunction)  (DBusWatchList *list,
                                                  DBusWatch     *watch);
235
/** Function to be called in protected_change_watch() with refcount held */
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
typedef void        (* DBusWatchToggleFunction)  (DBusWatchList *list,
                                                  DBusWatch     *watch,
                                                  dbus_bool_t    enabled);

static dbus_bool_t
protected_change_watch (DBusServer             *server,
                        DBusWatch              *watch,
                        DBusWatchAddFunction    add_function,
                        DBusWatchRemoveFunction remove_function,
                        DBusWatchToggleFunction toggle_function,
                        dbus_bool_t             enabled)
{
  DBusWatchList *watches;
  dbus_bool_t retval;
  
  HAVE_LOCK_CHECK (server);

253 254 255
  /* This isn't really safe or reasonable; a better pattern is the "do
   * everything, then drop lock and call out" one; but it has to be
   * propagated up through all callers
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
   */
  
  watches = server->watches;
  if (watches)
    {
      server->watches = NULL;
      _dbus_server_ref_unlocked (server);
      SERVER_UNLOCK (server);

      if (add_function)
        retval = (* add_function) (watches, watch);
      else if (remove_function)
        {
          retval = TRUE;
          (* remove_function) (watches, watch);
        }
      else
        {
          retval = TRUE;
          (* toggle_function) (watches, watch, enabled);
        }
      
      SERVER_LOCK (server);
      server->watches = watches;
      _dbus_server_unref_unlocked (server);

      return retval;
    }
  else
    return FALSE;
}

288 289 290 291 292 293 294 295 296 297 298
/**
 * Adds a watch for this server, chaining out to application-provided
 * watch handlers.
 *
 * @param server the server.
 * @param watch the watch to add.
 */
dbus_bool_t
_dbus_server_add_watch (DBusServer *server,
                        DBusWatch  *watch)
{
299
  HAVE_LOCK_CHECK (server);
300 301 302
  return protected_change_watch (server, watch,
                                 _dbus_watch_list_add_watch,
                                 NULL, NULL, FALSE);
303 304 305 306 307 308 309 310 311 312 313 314
}

/**
 * Removes a watch previously added with _dbus_server_remove_watch().
 *
 * @param server the server.
 * @param watch the watch to remove.
 */
void
_dbus_server_remove_watch  (DBusServer *server,
                            DBusWatch  *watch)
{
315
  HAVE_LOCK_CHECK (server);
316 317 318 319
  protected_change_watch (server, watch,
                          NULL,
                          _dbus_watch_list_remove_watch,
                          NULL, FALSE);
320 321
}

322
/**
323 324
 * Toggles all watch and notifies app via server's
 * DBusWatchToggledFunction if available.
325 326 327 328 329
 *
 * @param server the server.
 * @param enabled whether to enable or disable
 */
void
330 331
_dbus_server_toggle_all_watches (DBusServer  *server,
                                dbus_bool_t  enabled)
332
{
333
  _dbus_watch_list_toggle_all_watches (server->watches, enabled);
334 335
}

336
/** Function to be called in protected_change_timeout() with refcount held */
337 338
typedef dbus_bool_t (* DBusTimeoutAddFunction)    (DBusTimeoutList *list,
                                                   DBusTimeout     *timeout);
339
/** Function to be called in protected_change_timeout() with refcount held */
340 341
typedef void        (* DBusTimeoutRemoveFunction) (DBusTimeoutList *list,
                                                   DBusTimeout     *timeout);
342
/** Function to be called in protected_change_timeout() with refcount held */
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
typedef void        (* DBusTimeoutToggleFunction) (DBusTimeoutList *list,
                                                   DBusTimeout     *timeout,
                                                   dbus_bool_t      enabled);


static dbus_bool_t
protected_change_timeout (DBusServer               *server,
                          DBusTimeout              *timeout,
                          DBusTimeoutAddFunction    add_function,
                          DBusTimeoutRemoveFunction remove_function,
                          DBusTimeoutToggleFunction toggle_function,
                          dbus_bool_t               enabled)
{
  DBusTimeoutList *timeouts;
  dbus_bool_t retval;
  
359
  HAVE_LOCK_CHECK (server);
360 361 362 363

  /* This isn't really safe or reasonable; a better pattern is the "do everything, then
   * drop lock and call out" one; but it has to be propagated up through all callers
   */
364
  
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
  timeouts = server->timeouts;
  if (timeouts)
    {
      server->timeouts = NULL;
      _dbus_server_ref_unlocked (server);
      SERVER_UNLOCK (server);

      if (add_function)
        retval = (* add_function) (timeouts, timeout);
      else if (remove_function)
        {
          retval = TRUE;
          (* remove_function) (timeouts, timeout);
        }
      else
        {
          retval = TRUE;
          (* toggle_function) (timeouts, timeout, enabled);
        }
      
      SERVER_LOCK (server);
      server->timeouts = timeouts;
      _dbus_server_unref_unlocked (server);

      return retval;
    }
  else
    return FALSE;
393 394
}

395
/**
396 397 398 399
 * Adds a timeout for this server, chaining out to
 * application-provided timeout handlers. The timeout should be
 * repeatedly handled with dbus_timeout_handle() at its given interval
 * until it is removed.
400 401 402 403
 *
 * @param server the server.
 * @param timeout the timeout to add.
 */
404 405 406 407
dbus_bool_t
_dbus_server_add_timeout (DBusServer  *server,
			  DBusTimeout *timeout)
{
408 409 410
  return protected_change_timeout (server, timeout,
                                   _dbus_timeout_list_add_timeout,
                                   NULL, NULL, FALSE);
411 412
}

413 414 415 416 417 418
/**
 * Removes a timeout previously added with _dbus_server_add_timeout().
 *
 * @param server the server.
 * @param timeout the timeout to remove.
 */
419 420 421 422
void
_dbus_server_remove_timeout (DBusServer  *server,
			     DBusTimeout *timeout)
{
423 424 425 426
  protected_change_timeout (server, timeout,
                            NULL,
                            _dbus_timeout_list_remove_timeout,
                            NULL, FALSE);
427
}
428

429 430 431 432 433 434 435 436 437 438 439 440 441 442
/**
 * Toggles a timeout and notifies app via server's
 * DBusTimeoutToggledFunction if available. It's an error to call this
 * function on a timeout that was not previously added.
 *
 * @param server the server.
 * @param timeout the timeout to toggle.
 * @param enabled whether to enable or disable
 */
void
_dbus_server_toggle_timeout (DBusServer  *server,
                             DBusTimeout *timeout,
                             dbus_bool_t  enabled)
{
443 444 445 446
  protected_change_timeout (server, timeout,
                            NULL, NULL,
                            _dbus_timeout_list_toggle_timeout,
                            enabled);
447 448
}

449 450 451 452 453 454 455 456 457

/**
 * Like dbus_server_ref() but does not acquire the lock (must already be held)
 *
 * @param server the server.
 */
void
_dbus_server_ref_unlocked (DBusServer *server)
{
458 459
  dbus_int32_t old_refcount;

460 461 462
  _dbus_assert (server != NULL);
  HAVE_LOCK_CHECK (server);

463 464 465 466
  old_refcount = _dbus_atomic_inc (&server->refcount);
  _dbus_assert (old_refcount > 0);
  _dbus_server_trace_ref (server, old_refcount, old_refcount + 1,
      "ref_unlocked");
467 468 469 470 471 472 473 474 475 476
}

/**
 * Like dbus_server_unref() but does not acquire the lock (must already be held)
 *
 * @param server the server.
 */
void
_dbus_server_unref_unlocked (DBusServer *server)
{
477
  dbus_int32_t old_refcount;
478 479

  /* Keep this in sync with dbus_server_unref */
480

481 482 483 484
  _dbus_assert (server != NULL);

  HAVE_LOCK_CHECK (server);

485 486 487
  old_refcount = _dbus_atomic_dec (&server->refcount);
  _dbus_assert (old_refcount > 0);

488 489 490
  _dbus_server_trace_ref (server, old_refcount, old_refcount - 1,
      "unref_unlocked");

491
  if (old_refcount == 1)
492 493 494 495 496 497 498 499 500 501 502
    {
      _dbus_assert (server->disconnected);
      
      SERVER_UNLOCK (server);
      
      _dbus_assert (server->vtable->finalize != NULL);
      
      (* server->vtable->finalize) (server);
    }
}

503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
/** @} */

/**
 * @addtogroup DBusServer
 *
 * @{
 */


/**
 * @typedef DBusServer
 *
 * An opaque object representing a server that listens for
 * connections from other applications. Each time a connection
 * is made, a new DBusConnection is created and made available
 * via an application-provided DBusNewConnectionFunction.
 * The DBusNewConnectionFunction is provided with
 * dbus_server_set_new_connection_function().
 * 
 */

524 525 526 527 528
static const struct {
  DBusServerListenResult (* func) (DBusAddressEntry *entry,
                                   DBusServer      **server_p,
                                   DBusError        *error);
} listen_funcs[] = {
529 530
  { _dbus_server_listen_socket }
  , { _dbus_server_listen_platform_specific }
531
#ifdef DBUS_ENABLE_EMBEDDED_TESTS
532 533 534 535
  , { _dbus_server_listen_debug_pipe }
#endif
};

536
/**
537 538 539
 * Listens for new connections on the given address.  If there are
 * multiple semicolon-separated address entries in the address, tries
 * each one and listens on the first one that works.
540 541
 * 
 * Returns #NULL and sets error if listening fails for any reason.
542
 * Otherwise returns a new #DBusServer.
543 544 545 546 547 548 549
 * dbus_server_set_new_connection_function(),
 * dbus_server_set_watch_functions(), and
 * dbus_server_set_timeout_functions() should be called immediately to
 * render the server fully functional.
 *
 * To free the server, applications must call first
 * dbus_server_disconnect() and then dbus_server_unref().
550
 * 
551
 * @param address the address of this server.
552 553
 * @param error location to store reason for failure.
 * @returns a new #DBusServer, or #NULL on failure.
554 555 556 557
 * 
 */
DBusServer*
dbus_server_listen (const char     *address,
558
                    DBusError      *error)
559 560
{
  DBusServer *server;
561 562
  DBusAddressEntry **entries;
  int len, i;
563
  DBusError first_connect_error = DBUS_ERROR_INIT;
564 565
  dbus_bool_t handled_once;
  
566 567
  _dbus_return_val_if_fail (address != NULL, NULL);
  _dbus_return_val_if_error_is_set (error, NULL);
568
  
569
  if (!dbus_parse_address (address, &entries, &len, error))
570
    return NULL;
571

572
  server = NULL;
573
  handled_once = FALSE;
574

575 576
  for (i = 0; i < len; i++)
    {
577
      int j;
578

579 580 581
      for (j = 0; j < (int) _DBUS_N_ELEMENTS (listen_funcs); ++j)
        {
          DBusServerListenResult result;
582 583
          DBusError tmp_error = DBUS_ERROR_INIT;

584 585 586
          result = (* listen_funcs[j].func) (entries[i],
                                             &server,
                                             &tmp_error);
587

588
          if (result == DBUS_SERVER_LISTEN_OK)
589
            {
590 591 592 593
              _dbus_assert (server != NULL);
              _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
              handled_once = TRUE;
              goto out;
594
            }
595 596 597 598 599 600 601 602 603 604
          else if (result == DBUS_SERVER_LISTEN_ADDRESS_ALREADY_USED)
            {
              _dbus_assert (server == NULL);
              dbus_set_error (error,
                       DBUS_ERROR_ADDRESS_IN_USE,
                       "Address '%s' already used",
                       dbus_address_entry_get_method (entries[0]));
              handled_once = TRUE;
              goto out;
            }
605
          else if (result == DBUS_SERVER_LISTEN_BAD_ADDRESS)
606
            {
607 608 609 610 611
              _dbus_assert (server == NULL);
              _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
              dbus_move_error (&tmp_error, error);
              handled_once = TRUE;
              goto out;
612
            }
613
          else if (result == DBUS_SERVER_LISTEN_NOT_HANDLED)
614
            {
615 616
              _dbus_assert (server == NULL);
              _DBUS_ASSERT_ERROR_IS_CLEAR (&tmp_error);
617

618
              /* keep trying addresses */
619
            }
620
          else if (result == DBUS_SERVER_LISTEN_DID_NOT_CONNECT)
621
            {
622 623 624 625
              _dbus_assert (server == NULL);
              _DBUS_ASSERT_ERROR_IS_SET (&tmp_error);
              if (!dbus_error_is_set (&first_connect_error))
                dbus_move_error (&tmp_error, &first_connect_error);
626
              else
627
                dbus_error_free (&tmp_error);
628

629 630 631
              handled_once = TRUE;
              
              /* keep trying addresses */
632
            }
633
        }
634

635 636 637
      _dbus_assert (server == NULL);
      _DBUS_ASSERT_ERROR_IS_CLEAR (error);
    }
638

639
 out:
640

641 642 643 644 645 646 647 648
  if (!handled_once)
    {
      _DBUS_ASSERT_ERROR_IS_CLEAR (error);
      if (len > 0)
        dbus_set_error (error,
                       DBUS_ERROR_BAD_ADDRESS,
                       "Unknown address type '%s'",
                       dbus_address_entry_get_method (entries[0]));
649
      else
650 651 652 653
        dbus_set_error (error,
                        DBUS_ERROR_BAD_ADDRESS,
                        "Empty address '%s'",
                        address);
654
    }
655
  
656 657
  dbus_address_entries_free (entries);

658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
  if (server == NULL)
    {
      _dbus_assert (error == NULL || dbus_error_is_set (&first_connect_error) ||
                   dbus_error_is_set (error));
      
      if (error && dbus_error_is_set (error))
        {
          /* already set the error */
        }
      else
        {
          /* didn't set the error but either error should be
           * NULL or first_connect_error should be set.
           */
          _dbus_assert (error == NULL || dbus_error_is_set (&first_connect_error));
          dbus_move_error (&first_connect_error, error);
        }

      _DBUS_ASSERT_ERROR_IS_CLEAR (&first_connect_error); /* be sure we freed it */
      _DBUS_ASSERT_ERROR_IS_SET (error);
678

679 680 681 682 683 684 685
      return NULL;
    }
  else
    {
      _DBUS_ASSERT_ERROR_IS_CLEAR (error);
      return server;
    }
686 687 688 689 690 691
}

/**
 * Increments the reference count of a DBusServer.
 *
 * @param server the server.
692
 * @returns the server
693
 */
694
DBusServer *
695 696
dbus_server_ref (DBusServer *server)
{
697
  dbus_int32_t old_refcount;
698

699
  _dbus_return_val_if_fail (server != NULL, NULL);
700

701
  old_refcount = _dbus_atomic_inc (&server->refcount);
702

703 704 705 706 707 708 709 710
#ifndef DBUS_DISABLE_CHECKS
  if (_DBUS_UNLIKELY (old_refcount <= 0))
    {
      _dbus_atomic_dec (&server->refcount);
      _dbus_warn_check_failed (_dbus_return_if_fail_warning_format,
                               _DBUS_FUNCTION_NAME, "old_refcount > 0",
                               __FILE__, __LINE__);
      return NULL;
711
    }
712
#endif
713

714 715
  _dbus_server_trace_ref (server, old_refcount, old_refcount + 1, "ref");

716
  return server;
717 718 719 720
}

/**
 * Decrements the reference count of a DBusServer.  Finalizes the
721 722 723
 * server if the reference count reaches zero.
 *
 * The server must be disconnected before the refcount reaches zero.
724 725 726 727 728 729
 *
 * @param server the server.
 */
void
dbus_server_unref (DBusServer *server)
{
730
  dbus_int32_t old_refcount;
731 732

  /* keep this in sync with unref_unlocked */
733

734 735
  _dbus_return_if_fail (server != NULL);

736
  old_refcount = _dbus_atomic_dec (&server->refcount);
737

738 739 740
#ifndef DBUS_DISABLE_CHECKS
  if (_DBUS_UNLIKELY (old_refcount <= 0))
    {
741 742 743 744 745 746 747
      /* undo side-effect first
       * please do not try to simplify the code here by using
       * _dbus_atomic_get(), why we don't use it is
       * because it issues another atomic operation even though
       * DBUS_DISABLE_CHECKS defined.
       * Bug: https://bugs.freedesktop.org/show_bug.cgi?id=68303
       */
748 749 750 751 752 753
      _dbus_atomic_inc (&server->refcount);
      _dbus_warn_check_failed (_dbus_return_if_fail_warning_format,
                               _DBUS_FUNCTION_NAME, "old_refcount > 0",
                               __FILE__, __LINE__);
      return;
    }
754
#endif
755

756 757
  _dbus_server_trace_ref (server, old_refcount, old_refcount - 1, "unref");

758
  if (old_refcount == 1)
759
    {
760 761 762
      /* lock not held! */
      _dbus_assert (server->disconnected);
      
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
      _dbus_assert (server->vtable->finalize != NULL);
      
      (* server->vtable->finalize) (server);
    }
}

/**
 * Releases the server's address and stops listening for
 * new clients. If called more than once, only the first
 * call has an effect. Does not modify the server's
 * reference count.
 * 
 * @param server the server.
 */
void
dbus_server_disconnect (DBusServer *server)
{
780
  _dbus_return_if_fail (server != NULL);
781

782
  dbus_server_ref (server);
783
  SERVER_LOCK (server);
784

785 786
  _dbus_assert (server->vtable->disconnect != NULL);

787
  if (!server->disconnected)
788
    {
789 790 791 792
      /* this has to be first so recursive calls to disconnect don't happen */
      server->disconnected = TRUE;
      
      (* server->vtable->disconnect) (server);
793
    }
794 795

  SERVER_UNLOCK (server);
796
  dbus_server_unref (server);
797 798 799 800 801 802 803 804 805 806
}

/**
 * Returns #TRUE if the server is still listening for new connections.
 *
 * @param server the server.
 */
dbus_bool_t
dbus_server_get_is_connected (DBusServer *server)
{
807
  dbus_bool_t retval;
808
  
809 810 811 812 813 814 815
  _dbus_return_val_if_fail (server != NULL, FALSE);

  SERVER_LOCK (server);
  retval = !server->disconnected;
  SERVER_UNLOCK (server);

  return retval;
816 817
}

818 819 820 821 822 823 824 825 826 827
/**
 * Returns the address of the server, as a newly-allocated
 * string which must be freed by the caller.
 *
 * @param server the server
 * @returns the address or #NULL if no memory
 */
char*
dbus_server_get_address (DBusServer *server)
{
828
  char *retval;
829
  
830 831 832 833 834 835 836
  _dbus_return_val_if_fail (server != NULL, NULL);

  SERVER_LOCK (server);
  retval = _dbus_strdup (server->address);
  SERVER_UNLOCK (server);

  return retval;
837 838
}

839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
/**
 * Returns the unique ID of the server, as a newly-allocated
 * string which must be freed by the caller. This ID is
 * normally used by clients to tell when two #DBusConnection
 * would be equivalent (because the server address passed
 * to dbus_connection_open() will have the same guid in the
 * two cases). dbus_connection_open() can re-use an existing
 * connection with the same ID instead of opening a new
 * connection.
 *
 * This is an ID unique to each #DBusServer. Remember that
 * a #DBusServer represents only one mode of connecting,
 * so e.g. a bus daemon can listen on multiple addresses
 * which will mean it has multiple #DBusServer each with
 * their own ID.
 *
 * The ID is not a UUID in the sense of RFC4122; the details
 * are explained in the D-Bus specification.
 *
 * @param server the server
 * @returns the id of the server or #NULL if no memory
 */
char*
dbus_server_get_id (DBusServer *server)
{
  char *retval;
  
  _dbus_return_val_if_fail (server != NULL, NULL);

  SERVER_LOCK (server);
  retval = NULL;
  _dbus_string_copy_data (&server->guid_hex, &retval);
  SERVER_UNLOCK (server);

  return retval;
}

876 877 878 879 880
/**
 * Sets a function to be used for handling new connections.  The given
 * function is passed each new connection as the connection is
 * created. If the new connection function increments the connection's
 * reference count, the connection will stay alive. Otherwise, the
881 882 883 884 885 886 887 888 889
 * connection will be unreferenced and closed. The new connection
 * function may also close the connection itself, which is considered
 * good form if the connection is not wanted.
 *
 * The connection here is private in the sense of
 * dbus_connection_open_private(), so if the new connection function
 * keeps a reference it must arrange for the connection to be closed.
 * i.e. libdbus does not own this connection once the new connection
 * function takes a reference.
890 891 892 893 894 895 896 897 898 899 900 901
 *
 * @param server the server.
 * @param function a function to handle new connections.
 * @param data data to pass to the new connection handler.
 * @param free_data_function function to free the data.
 */
void
dbus_server_set_new_connection_function (DBusServer                *server,
                                         DBusNewConnectionFunction  function,
                                         void                      *data,
                                         DBusFreeFunction           free_data_function)
{
902 903
  DBusFreeFunction old_free_function;
  void *old_data;
904
  
905 906 907 908 909
  _dbus_return_if_fail (server != NULL);

  SERVER_LOCK (server);
  old_free_function = server->new_connection_free_data_function;
  old_data = server->new_connection_data;
910 911 912 913
  
  server->new_connection_function = function;
  server->new_connection_data = data;
  server->new_connection_free_data_function = free_data_function;
914 915 916 917
  SERVER_UNLOCK (server);
    
  if (old_free_function != NULL)
    (* old_free_function) (old_data);
918 919 920
}

/**
921
 * Sets the watch functions for the server. These functions are
922 923 924 925 926 927 928 929 930
 * responsible for making the application's main loop aware of file
 * descriptors that need to be monitored for events.
 *
 * This function behaves exactly like dbus_connection_set_watch_functions();
 * see the documentation for that routine.
 *
 * @param server the server.
 * @param add_function function to begin monitoring a new descriptor.
 * @param remove_function function to stop monitoring a descriptor.
931
 * @param toggled_function function to notify when the watch is enabled/disabled
932 933
 * @param data data to pass to add_function and remove_function.
 * @param free_data_function function to be called to free the data.
934
 * @returns #FALSE on failure (no memory)
935
 */
936
dbus_bool_t
937 938 939
dbus_server_set_watch_functions (DBusServer              *server,
                                 DBusAddWatchFunction     add_function,
                                 DBusRemoveWatchFunction  remove_function,
940
                                 DBusWatchToggledFunction toggled_function,
941 942 943
                                 void                    *data,
                                 DBusFreeFunction         free_data_function)
{
944 945 946
  dbus_bool_t result;
  DBusWatchList *watches;
  
947
  _dbus_return_val_if_fail (server != NULL, FALSE);
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964

  SERVER_LOCK (server);
  watches = server->watches;
  server->watches = NULL;
  if (watches)
    {
      SERVER_UNLOCK (server);
      result = _dbus_watch_list_set_functions (watches,
                                               add_function,
                                               remove_function,
                                               toggled_function,
                                               data,
                                               free_data_function);
      SERVER_LOCK (server);
    }
  else
    {
965
      _dbus_warn_check_failed ("Re-entrant call to %s", _DBUS_FUNCTION_NAME);
966 967 968 969
      result = FALSE;
    }
  server->watches = watches;
  SERVER_UNLOCK (server);
970
  
971
  return result;
972 973
}

974
/**
975
 * Sets the timeout functions for the server. These functions are
976 977 978 979 980 981 982 983
 * responsible for making the application's main loop aware of timeouts.
 *
 * This function behaves exactly like dbus_connection_set_timeout_functions();
 * see the documentation for that routine.
 *
 * @param server the server.
 * @param add_function function to add a timeout.
 * @param remove_function function to remove a timeout.
984
 * @param toggled_function function to notify when the timeout is enabled/disabled
985 986
 * @param data data to pass to add_function and remove_function.
 * @param free_data_function function to be called to free the data.
987
 * @returns #FALSE on failure (no memory)
988
 */
989
dbus_bool_t
990 991 992
dbus_server_set_timeout_functions (DBusServer                *server,
				   DBusAddTimeoutFunction     add_function,
				   DBusRemoveTimeoutFunction  remove_function,
993
                                   DBusTimeoutToggledFunction toggled_function,
994 995 996
				   void                      *data,
				   DBusFreeFunction           free_data_function)
{
997 998 999
  dbus_bool_t result;
  DBusTimeoutList *timeouts;
  
1000
  _dbus_return_val_if_fail (server != NULL, FALSE);
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017

  SERVER_LOCK (server);
  timeouts = server->timeouts;
  server->timeouts = NULL;
  if (timeouts)
    {
      SERVER_UNLOCK (server);
      result = _dbus_timeout_list_set_functions (timeouts,
                                                 add_function,
                                                 remove_function,
                                                 toggled_function,
                                                 data,
                                                 free_data_function);
      SERVER_LOCK (server);
    }
  else
    {
1018
      _dbus_warn_check_failed ("Re-entrant call to %s", _DBUS_FUNCTION_NAME);
1019 1020 1021 1022
      result = FALSE;
    }
  server->timeouts = timeouts;
  SERVER_UNLOCK (server);
1023
  
1024
  return result;
1025 1026
}

1027
/**
1028 1029 1030 1031 1032 1033 1034
 * Sets the authentication mechanisms that this server offers to
 * clients, as a #NULL-terminated array of mechanism names. This
 * function only affects connections created <em>after</em> it is
 * called.  Pass #NULL instead of an array to use all available
 * mechanisms (this is the default behavior).
 *
 * The D-Bus specification describes some of the supported mechanisms.
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
 *
 * @param server the server
 * @param mechanisms #NULL-terminated array of mechanisms
 * @returns #FALSE if no memory
 */
dbus_bool_t
dbus_server_set_auth_mechanisms (DBusServer  *server,
                                 const char **mechanisms)
{
  char **copy;

1046
  _dbus_return_val_if_fail (server != NULL, FALSE);
1047 1048

  SERVER_LOCK (server);
1049
  
1050 1051 1052 1053
  if (mechanisms != NULL)
    {
      copy = _dbus_dup_string_array (mechanisms);
      if (copy == NULL)
1054 1055 1056 1057
        {
          SERVER_UNLOCK (server);
          return FALSE;
        }
1058 1059 1060 1061 1062 1063 1064
    }
  else
    copy = NULL;

  dbus_free_string_array (server->auth_mechanisms);
  server->auth_mechanisms = copy;

1065 1066
  SERVER_UNLOCK (server);
  
1067 1068 1069
  return TRUE;
}

1070 1071
static DBusDataSlotAllocator slot_allocator =
  _DBUS_DATA_SLOT_ALLOCATOR_INIT (_DBUS_LOCK_NAME (server_slots));
1072 1073 1074 1075 1076

/**
 * Allocates an integer ID to be used for storing application-specific
 * data on any DBusServer. The allocated ID may then be used
 * with dbus_server_set_data() and dbus_server_get_data().
1077 1078 1079 1080 1081 1082 1083 1084 1085
 * The slot must be initialized with -1. If a nonnegative
 * slot is passed in, the refcount is incremented on that
 * slot, rather than creating a new slot.
 *  
 * The allocated slot is global, i.e. all DBusServer objects will have
 * a slot with the given integer ID reserved.
 *
 * @param slot_p address of global variable storing the slot ID
 * @returns #FALSE on no memory
1086
 */
1087 1088
dbus_bool_t
dbus_server_allocate_data_slot (dbus_int32_t *slot_p)
1089
{
1090
  return _dbus_data_slot_allocator_alloc (&slot_allocator,
1091
                                          slot_p);
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
}

/**
 * Deallocates a global ID for server data slots.
 * dbus_server_get_data() and dbus_server_set_data()
 * may no longer be used with this slot.
 * Existing data stored on existing DBusServer objects
 * will be freed when the server is finalized,
 * but may not be retrieved (and may only be replaced
 * if someone else reallocates the slot).
 *
1103
 * @param slot_p address of the slot to deallocate
1104 1105
 */
void
1106
dbus_server_free_data_slot (dbus_int32_t *slot_p)
1107
{
1108
  _dbus_return_if_fail (*slot_p >= 0);
1109
  
1110
  _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
}

/**
 * Stores a pointer on a DBusServer, along
 * with an optional function to be used for freeing
 * the data when the data is set again, or when
 * the server is finalized. The slot number
 * must have been allocated with dbus_server_allocate_data_slot().
 *
 * @param server the server
 * @param slot the slot number
 * @param data the data to store
 * @param free_data_func finalizer function for the data
 * @returns #TRUE if there was enough memory to store the data
 */
dbus_bool_t
1127
dbus_server_set_data (DBusServer       *server,
1128 1129 1130 1131 1132 1133 1134 1135
                      int               slot,
                      void             *data,
                      DBusFreeFunction  free_data_func)
{
  DBusFreeFunction old_free_func;
  void *old_data;
  dbus_bool_t retval;

1136
  _dbus_return_val_if_fail (server != NULL, FALSE);
1137 1138

  SERVER_LOCK (server);
1139 1140 1141 1142 1143 1144
  
  retval = _dbus_data_slot_list_set (&slot_allocator,
                                     &server->slot_list,
                                     slot, data, free_data_func,
                                     &old_free_func, &old_data);

1145 1146

  SERVER_UNLOCK (server);
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
  
  if (retval)
    {
      /* Do the actual free outside the server lock */
      if (old_free_func)
        (* old_free_func) (old_data);
    }

  return retval;
}

/**
 * Retrieves data previously set with dbus_server_set_data().
 * The slot must still be allocated (must not have been freed).
 *
 * @param server the server
 * @param slot the slot to get data from
 * @returns the data, or #NULL if not found
 */
void*
dbus_server_get_data (DBusServer   *server,
1168
                      int           slot)
1169 1170
{
  void *res;
1171 1172

  _dbus_return_val_if_fail (server != NULL, NULL);
1173
  
1174
  SERVER_LOCK (server);
1175 1176 1177 1178 1179
  
  res = _dbus_data_slot_list_get (&slot_allocator,
                                  &server->slot_list,
                                  slot);

1180
  SERVER_UNLOCK (server);
1181 1182 1183 1184
  
  return res;
}

1185 1186
/** @} */

1187
#ifdef DBUS_ENABLE_EMBEDDED_TESTS
1188
#include "dbus-test.h"
1189
#include <string.h>
1190 1191 1192 1193 1194 1195 1196 1197

dbus_bool_t
_dbus_server_test (void)
{
  const char *valid_addresses[] = {
    "tcp:port=1234",
    "tcp:host=localhost,port=1234",
    "tcp:host=localhost,port=1234;tcp:port=5678",
1198 1199
#ifdef DBUS_UNIX
    "unix:path=./boogie",
1200
    "tcp:port=1234;unix:path=./boogie",
1201
#endif
1202 1203 1204 1205 1206 1207 1208
  };

  DBusServer *server;
  int i;
  
  for (i = 0; i < _DBUS_N_ELEMENTS (valid_addresses); i++)
    {
1209
      DBusError error = DBUS_ERROR_INIT;
1210 1211
      char *address;
      char *id;
1212

1213
      server = dbus_server_listen (valid_addresses[i], &error);
1214
      if (server == NULL)
1215
        {
1216
          _dbus_warn ("server listen error: %s: %s", error.name, error.message);
1217 1218 1219
          dbus_error_free (&error);
          _dbus_assert_not_reached ("Failed to listen for valid address.");
        }
1220

1221 1222 1223 1224
      id = dbus_server_get_id (server);
      _dbus_assert (id != NULL);
      address = dbus_server_get_address (server);
      _dbus_assert (address != NULL);
1225

1226
      if (strstr (address, id) == NULL)
1227
        {
1228
          _dbus_warn ("server id '%s' is not in the server address '%s'",
1229 1230
                      id, address);
          _dbus_assert_not_reached ("bad server id or address");
1231
        }
1232

1233 1234 1235
      dbus_free (id);
      dbus_free (address);
      
1236 1237 1238 1239 1240 1241 1242
      dbus_server_disconnect (server);
      dbus_server_unref (server);
    }

  return TRUE;
}

1243
#endif /* DBUS_ENABLE_EMBEDDED_TESTS */