test-utils-glib.c 15.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
/* Utility functions for tests that rely on GLib
 *
 * Copyright © 2010-2011 Nokia Corporation
 * Copyright © 2013-2015 Collabora Ltd.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation files
 * (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge,
 * publish, distribute, sublicense, and/or sell copies of the Software,
 * and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <config.h>
#include "test-utils-glib.h"

30
#include <errno.h>
31 32 33 34 35 36 37 38 39
#include <string.h>

#ifdef DBUS_WIN
# include <io.h>
# include <windows.h>
#else
# include <signal.h>
# include <unistd.h>
# include <sys/types.h>
40
# include <pwd.h>
41 42 43 44 45 46 47
#endif

#include <glib.h>
#include <glib/gstdio.h>

#include <dbus/dbus.h>

48 49 50 51
#ifdef G_OS_WIN
# define isatty(x) _isatty(x)
#endif

52 53 54 55 56 57 58 59 60 61
void
_test_assert_no_error (const DBusError *e,
    const char *file,
    int line)
{
  if (G_UNLIKELY (dbus_error_is_set (e)))
    g_error ("%s:%d: expected success but got error: %s: %s",
        file, line, e->name, e->message);
}

62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
#ifdef DBUS_UNIX
static void
child_setup (gpointer user_data)
{
  const struct passwd *pwd = user_data;
  uid_t uid = geteuid ();

  if (pwd == NULL || (pwd->pw_uid == uid && getuid () == uid))
    return;

  if (uid != 0)
    g_error ("not currently euid 0: %lu", (unsigned long) uid);

  if (setuid (pwd->pw_uid) != 0)
    g_error ("could not setuid (%lu): %s",
        (unsigned long) pwd->pw_uid, g_strerror (errno));

  uid = getuid ();

  if (uid != pwd->pw_uid)
    g_error ("after successful setuid (%lu) my uid is %ld",
        (unsigned long) pwd->pw_uid, (unsigned long) uid);

  uid = geteuid ();

  if (uid != pwd->pw_uid)
    g_error ("after successful setuid (%lu) my euid is %ld",
        (unsigned long) pwd->pw_uid, (unsigned long) uid);
}
#endif

93 94 95
static gchar *
spawn_dbus_daemon (const gchar *binary,
    const gchar *configuration,
96
    const gchar *listen_address,
97
    TestUser user,
98
    const gchar *runtime_dir,
99 100 101 102 103
    GPid *daemon_pid)
{
  GError *error = NULL;
  GString *address;
  gint address_fd;
104
  GPtrArray *argv;
105
  gchar **envp;
106 107 108 109
#ifdef DBUS_UNIX
  const struct passwd *pwd = NULL;
#endif

110
  if (user != TEST_USER_ME)
111 112 113 114
    {
#ifdef DBUS_UNIX
      if (getuid () != 0)
        {
115
          g_test_skip ("cannot use alternative uid when not uid 0");
116 117 118 119 120 121 122 123 124 125 126 127 128
          return NULL;
        }

      switch (user)
        {
          case TEST_USER_ROOT:
            break;

          case TEST_USER_MESSAGEBUS:
            pwd = getpwnam (DBUS_USER);

            if (pwd == NULL)
              {
129 130 131 132 133
                gchar *message = g_strdup_printf ("user '%s' does not exist",
                    DBUS_USER);

                g_test_skip (message);
                g_free (message);
134 135 136 137 138 139 140 141 142 143
                return NULL;
              }

            break;

          case TEST_USER_OTHER:
            pwd = getpwnam (DBUS_TEST_USER);

            if (pwd == NULL)
              {
144 145 146 147 148
                gchar *message = g_strdup_printf ("user '%s' does not exist",
                    DBUS_TEST_USER);

                g_test_skip (message);
                g_free (message);
149 150 151 152 153
                return NULL;
              }

            break;

154 155
          case TEST_USER_ME:
            /* cannot get here, fall through */
156 157 158 159
          default:
            g_assert_not_reached ();
        }
#else
160
      g_test_skip ("cannot use alternative uid on Windows");
161 162 163
      return NULL;
#endif
    }
164

165 166 167 168 169
  envp = g_get_environ ();

  if (runtime_dir != NULL)
    envp = g_environ_setenv (envp, "XDG_RUNTIME_DIR", runtime_dir, TRUE);

170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
  argv = g_ptr_array_new_with_free_func (g_free);
  g_ptr_array_add (argv, g_strdup (binary));
  g_ptr_array_add (argv, g_strdup (configuration));
  g_ptr_array_add (argv, g_strdup ("--nofork"));
  g_ptr_array_add (argv, g_strdup ("--print-address=1")); /* stdout */

  if (listen_address != NULL)
    g_ptr_array_add (argv, g_strdup (listen_address));

#ifdef DBUS_UNIX
  g_ptr_array_add (argv, g_strdup ("--systemd-activation"));
#endif

  g_ptr_array_add (argv, NULL);

185
  g_spawn_async_with_pipes (NULL, /* working directory */
186
      (gchar **) argv->pdata,
187
      envp,
188
      G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_SEARCH_PATH,
189 190 191 192 193
#ifdef DBUS_UNIX
      child_setup, (gpointer) pwd,
#else
      NULL, NULL,
#endif
194 195 196 197 198 199 200
      daemon_pid,
      NULL, /* child's stdin = /dev/null */
      &address_fd,
      NULL, /* child's stderr = our stderr */
      &error);
  g_assert_no_error (error);

201
  g_ptr_array_free (argv, TRUE);
202
  g_strfreev (envp);
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
  address = g_string_new (NULL);

  /* polling until the dbus-daemon writes out its address is a bit stupid,
   * but at least it's simple, unlike dbus-launch... in principle we could
   * use select() here, but life's too short */
  while (1)
    {
      gssize bytes;
      gchar buf[4096];
      gchar *newline;

      bytes = read (address_fd, buf, sizeof (buf));

      if (bytes > 0)
        g_string_append_len (address, buf, bytes);

      newline = strchr (address->str, '\n');

      if (newline != NULL)
        {
          if ((newline > address->str) && ('\r' == newline[-1]))
            newline -= 1;
          g_string_truncate (address, newline - address->str);
          break;
        }

      g_usleep (G_USEC_PER_SEC / 10);
    }

  g_close (address_fd, NULL);

  return g_string_free (address, FALSE);
}

gchar *
test_get_dbus_daemon (const gchar *config_file,
240
                      TestUser     user,
241
                      const gchar *runtime_dir,
242 243 244 245
                      GPid        *daemon_pid)
{
  gchar *dbus_daemon;
  gchar *arg;
246
  const gchar *listen_address = NULL;
247 248
  gchar *address;

249 250 251 252 253
  /* we often have to override this because on Windows, the default may be
   * autolaunch:, which is globally-scoped and hence unsuitable for
   * regression tests */
  listen_address = "--address=" TEST_LISTEN;

254 255 256 257 258
  if (config_file != NULL)
    {

      if (g_getenv ("DBUS_TEST_DATA") == NULL)
        {
259
          g_test_message ("set DBUS_TEST_DATA to a directory containing %s",
260
              config_file);
261
          g_test_skip ("DBUS_TEST_DATA not set");
262 263 264 265 266 267
          return NULL;
        }

      arg = g_strdup_printf (
          "--config-file=%s/%s",
          g_getenv ("DBUS_TEST_DATA"), config_file);
268 269 270 271

      /* The configuration file is expected to give a suitable address,
       * do not override it */
      listen_address = NULL;
272
    }
273
  else if (g_getenv ("DBUS_TEST_DATADIR") != NULL)
274 275
    {
      arg = g_strdup_printf ("--config-file=%s/dbus-1/session.conf",
276
          g_getenv ("DBUS_TEST_DATADIR"));
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
    }
  else if (g_getenv ("DBUS_TEST_DATA") != NULL)
    {
      arg = g_strdup_printf (
          "--config-file=%s/valid-config-files/session.conf",
          g_getenv ("DBUS_TEST_DATA"));
    }
  else
    {
      arg = g_strdup ("--session");
    }

  dbus_daemon = g_strdup (g_getenv ("DBUS_TEST_DAEMON"));

  if (dbus_daemon == NULL)
    dbus_daemon = g_strdup ("dbus-daemon");

  if (g_getenv ("DBUS_TEST_DAEMON_ADDRESS") != NULL)
    {
296 297
      if (config_file != NULL || user != TEST_USER_ME)
        {
298
          g_test_skip ("cannot use DBUS_TEST_DAEMON_ADDRESS for "
299 300 301 302 303 304 305
              "unusally-configured dbus-daemon");
          address = NULL;
        }
      else
        {
          address = g_strdup (g_getenv ("DBUS_TEST_DAEMON_ADDRESS"));
        }
306 307 308
    }
  else
    {
309
      address = spawn_dbus_daemon (dbus_daemon, arg,
310
          listen_address, user, runtime_dir, daemon_pid);
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
    }

  g_free (dbus_daemon);
  g_free (arg);
  return address;
}

DBusConnection *
test_connect_to_bus (TestMainContext *ctx,
    const gchar *address)
{
  DBusConnection *conn;
  DBusError error = DBUS_ERROR_INIT;
  dbus_bool_t ok;

  conn = dbus_connection_open_private (address, &error);
  test_assert_no_error (&error);
  g_assert (conn != NULL);

  ok = dbus_bus_register (conn, &error);
  test_assert_no_error (&error);
  g_assert (ok);
  g_assert (dbus_bus_get_unique_name (conn) != NULL);

  test_connection_setup (ctx, conn);
  return conn;
}

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 373 374 375 376 377
DBusConnection *
test_connect_to_bus_as_user (TestMainContext *ctx,
    const char *address,
    TestUser user)
{
  /* For now we only do tests like this on Linux, because I don't know how
   * safe this use of setresuid() is on other platforms */
#if defined(HAVE_GETRESUID) && defined(HAVE_SETRESUID) && defined(__linux__)
  uid_t ruid, euid, suid;
  const struct passwd *pwd;
  DBusConnection *conn;
  const char *username;

  switch (user)
    {
      case TEST_USER_ME:
        return test_connect_to_bus (ctx, address);

      case TEST_USER_ROOT:
        username = "root";
        break;

      case TEST_USER_MESSAGEBUS:
        username = DBUS_USER;
        break;

      case TEST_USER_OTHER:
        username = DBUS_TEST_USER;
        break;

      default:
        g_return_val_if_reached (NULL);
    }

  if (getresuid (&ruid, &euid, &suid) != 0)
    g_error ("getresuid: %s", g_strerror (errno));

  if (ruid != 0 || euid != 0 || suid != 0)
    {
378
      g_test_message ("not uid 0 (ruid=%ld euid=%ld suid=%ld)",
379
          (unsigned long) ruid, (unsigned long) euid, (unsigned long) suid);
380
      g_test_skip ("not uid 0");
381 382 383 384 385 386 387
      return NULL;
    }

  pwd = getpwnam (username);

  if (pwd == NULL)
    {
388 389
      g_test_message ("getpwnam(\"%s\"): %s", username, g_strerror (errno));
      g_test_skip ("not uid 0");
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
      return NULL;
    }

  /* Impersonate the desired user while we connect to the bus.
   * This should work, because we're root. */
  if (setresuid (pwd->pw_uid, pwd->pw_uid, 0) != 0)
    g_error ("setresuid(%ld, (same), 0): %s",
        (unsigned long) pwd->pw_uid, g_strerror (errno));

  conn = test_connect_to_bus (ctx, address);

  /* go back to our saved uid */
  if (setresuid (0, 0, 0) != 0)
    g_error ("setresuid(0, 0, 0): %s", g_strerror (errno));

  return conn;

#else

  switch (user)
    {
      case TEST_USER_ME:
        return test_connect_to_bus (ctx, address);

414 415 416
      case TEST_USER_ROOT:
      case TEST_USER_MESSAGEBUS:
      case TEST_USER_OTHER:
417
        g_test_skip ("setresuid() not available, or unsure about "
418 419
            "credentials-passing semantics on this platform");
        return NULL;
420 421 422

      default:
        g_return_val_if_reached (NULL);
423 424 425 426 427
    }

#endif
}

428 429 430 431 432 433 434 435 436 437 438 439
static void
pid_died (GPid pid,
          gint status,
          gpointer user_data)
{
  gboolean *result = user_data;

  g_assert (result != NULL);
  g_assert (!*result);
  *result = TRUE;
}

440 441 442
void
test_kill_pid (GPid pid)
{
443 444 445 446
  gint died = FALSE;

  g_child_watch_add (pid, pid_died, &died);

447 448 449 450 451 452 453
#ifdef DBUS_WIN
  if (pid != NULL)
    TerminateProcess (pid, 1);
#else
  if (pid > 0)
    kill (pid, SIGTERM);
#endif
454 455 456

  while (!died)
    g_main_context_iteration (NULL, TRUE);
457
}
458 459 460 461

static gboolean
time_out (gpointer data)
{
462 463 464
  puts ("Bail out! Test timed out (GLib main loop timeout callback reached)");
  fflush (stdout);
  abort ();
465 466 467
  return FALSE;
}

468
#ifdef G_OS_UNIX
469 470
static void wrap_abort (int signal) _DBUS_GNUC_NORETURN;

471 472 473
static void
wrap_abort (int signal)
{
474 475 476 477 478 479 480 481 482 483
  /* We might be halfway through writing out something else, so force this
   * onto its own line */
  const char message [] = "\nBail out! Test timed out (SIGALRM received)\n";

  if (write (STDOUT_FILENO, message, sizeof (message) - 1) <
      (ssize_t) sizeof (message) - 1)
    {
      /* ignore short write - what would we do about it? */
    }

484 485 486 487
  abort ();
}
#endif

488 489
static void
set_timeout (void)
490
{
491
  static guint timeout = 0;
492 493 494 495 496 497

  /* Prevent tests from hanging forever. This is intended to be long enough
   * that any reasonable regression test on any reasonable hardware would
   * have finished. */
#define TIMEOUT 60

498 499 500 501
  if (timeout != 0)
    g_source_remove (timeout);

  timeout = g_timeout_add_seconds (TIMEOUT, time_out, NULL);
502 503 504 505
#ifdef G_OS_UNIX
  /* The GLib main loop might not be running (we don't use it in every
   * test). Die with SIGALRM shortly after if necessary. */
  alarm (TIMEOUT + 10);
506

507
  /* Get a log message and a core dump from the SIGALRM. */
508 509 510 511 512 513 514
    {
      struct sigaction act = { };

      act.sa_handler = wrap_abort;

      sigaction (SIGALRM, &act, NULL);
    }
515 516
#endif
}
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
void
test_init (int *argcp, char ***argvp)
{
  g_test_init (argcp, argvp, NULL);
  g_test_bug_base ("https://bugs.freedesktop.org/show_bug.cgi?id=");
  set_timeout ();
}

static void
report_and_destroy (gpointer p)
{
  GTimer *timer = p;

  g_test_message ("Time since timeout reset %p: %.3f seconds",
      timer, g_timer_elapsed (timer, NULL));
  g_timer_destroy (timer);
}

void
test_timeout_reset (void)
{
  GTimer *timer = g_timer_new ();

  g_test_message ("Resetting test timeout (reference: %p)", timer);
  set_timeout ();

  g_test_queue_destroy (report_and_destroy, timer);
}

547 548 549 550 551 552
void
test_progress (char symbol)
{
  if (g_test_verbose () && isatty (1))
    g_print ("%c", symbol);
}
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598

/*
 * Delete @path, with a retry loop if the system call is interrupted by
 * an async signal. If @path does not exist, ignore; otherwise, it is
 * required to be a non-directory.
 */
void
test_remove_if_exists (const gchar *path)
{
  while (g_remove (path) != 0)
    {
      int saved_errno = errno;

      if (saved_errno == ENOENT)
        return;

#ifdef G_OS_UNIX
      if (saved_errno == EINTR)
        continue;
#endif

      g_error ("Unable to remove file \"%s\": %s", path,
               g_strerror (saved_errno));
    }
}

/*
 * Delete empty directory @path, with a retry loop if the system call is
 * interrupted by an async signal. @path is required to exist.
 */
void
test_rmdir_must_exist (const gchar *path)
{
  while (g_remove (path) != 0)
    {
      int saved_errno = errno;

#ifdef G_OS_UNIX
      if (saved_errno == EINTR)
        continue;
#endif

      g_error ("Unable to remove directory \"%s\": %s", path,
               g_strerror (saved_errno));
    }
}
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622

/*
 * Delete empty directory @path, with a retry loop if the system call is
 * interrupted by an async signal. If @path does not exist, ignore.
 */
void
test_rmdir_if_exists (const gchar *path)
{
  while (g_remove (path) != 0)
    {
      int saved_errno = errno;

      if (saved_errno == ENOENT)
        return;

#ifdef G_OS_UNIX
      if (saved_errno == EINTR)
        continue;
#endif

      g_error ("Unable to remove directory \"%s\": %s", path,
               g_strerror (saved_errno));
    }
}
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644

/*
 * Create directory @path, with a retry loop if the system call is
 * interrupted by an async signal.
 */
void
test_mkdir (const gchar *path,
            gint mode)
{
  while (g_mkdir (path, mode) != 0)
    {
      int saved_errno = errno;

#ifdef G_OS_UNIX
      if (saved_errno == EINTR)
        continue;
#endif

      g_error ("Unable to create directory \"%s\": %s", path,
               g_strerror (saved_errno));
    }
}