gdbus-peer.c 61.5 KB
Newer Older
1 2
/* GLib testing framework examples and tests
 *
3
 * Copyright (C) 2008-2010 Red Hat, Inc.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 * Author: David Zeuthen <davidz@redhat.com>
 */

Dan Winship's avatar
Dan Winship committed
23 24
#include "config.h"

25 26 27 28 29 30 31 32
#include <gio/gio.h>
#include <unistd.h>
#include <string.h>

/* for open(2) */
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
33
#include <string.h>
34

35 36 37
/* for g_unlink() */
#include <glib/gstdio.h>

Dan Winship's avatar
Dan Winship committed
38
#include <gio/gnetworking.h>
39
#include <gio/gunixsocketaddress.h>
40
#include <gio/gunixfdlist.h>
41

42 43 44
/* used in test_overflow */
#ifdef G_OS_UNIX
#include <gio/gunixconnection.h>
45
#include <errno.h>
46
#endif
47

48
#include "gdbus-tests.h"
49

50 51
#include "gdbus-example-objectmanager-generated.h"

52 53 54 55 56 57
#ifdef G_OS_UNIX
static gboolean is_unix = TRUE;
#else
static gboolean is_unix = FALSE;
#endif

58
static gchar *tmp_address = NULL;
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
static gchar *test_guid = NULL;
static GMainLoop *service_loop = NULL;
static GDBusServer *server = NULL;
static GMainLoop *loop = NULL;

/* ---------------------------------------------------------------------------------------------------- */
/* Test that peer-to-peer connections work */
/* ---------------------------------------------------------------------------------------------------- */


typedef struct
{
  gboolean accept_connection;
  gint num_connection_attempts;
  GPtrArray *current_connections;
  guint num_method_calls;
  gboolean signal_received;
} PeerData;

static const gchar *test_interface_introspection_xml =
  "<node>"
  "  <interface name='org.gtk.GDBus.PeerTestInterface'>"
  "    <method name='HelloPeer'>"
  "      <arg type='s' name='greeting' direction='in'/>"
  "      <arg type='s' name='response' direction='out'/>"
  "    </method>"
  "    <method name='EmitSignal'/>"
86
  "    <method name='EmitSignalWithNameSet'/>"
87 88 89 90 91 92 93 94 95
  "    <method name='OpenFile'>"
  "      <arg type='s' name='path' direction='in'/>"
  "    </method>"
  "    <signal name='PeerSignal'>"
  "      <arg type='s' name='a_string'/>"
  "    </signal>"
  "    <property type='s' name='PeerProperty' access='read'/>"
  "  </interface>"
  "</node>";
96
static GDBusInterfaceInfo *test_interface_introspection_data = NULL;
97 98 99 100 101 102 103 104 105 106 107 108

static void
test_interface_method_call (GDBusConnection       *connection,
                            const gchar           *sender,
                            const gchar           *object_path,
                            const gchar           *interface_name,
                            const gchar           *method_name,
                            GVariant              *parameters,
                            GDBusMethodInvocation *invocation,
                            gpointer               user_data)
{
  PeerData *data = user_data;
109
  const GDBusMethodInfo *info;
110 111 112 113 114 115

  data->num_method_calls++;

  g_assert_cmpstr (object_path, ==, "/org/gtk/GDBus/PeerTestObject");
  g_assert_cmpstr (interface_name, ==, "org.gtk.GDBus.PeerTestInterface");

116 117 118
  info = g_dbus_method_invocation_get_method_info (invocation);
  g_assert_cmpstr (info->name, ==, method_name);

119 120 121 122 123
  if (g_strcmp0 (method_name, "HelloPeer") == 0)
    {
      const gchar *greeting;
      gchar *response;

124
      g_variant_get (parameters, "(&s)", &greeting);
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144

      response = g_strdup_printf ("You greeted me with '%s'.",
                                  greeting);
      g_dbus_method_invocation_return_value (invocation,
                                             g_variant_new ("(s)", response));
      g_free (response);
    }
  else if (g_strcmp0 (method_name, "EmitSignal") == 0)
    {
      GError *error;

      error = NULL;
      g_dbus_connection_emit_signal (connection,
                                     NULL,
                                     "/org/gtk/GDBus/PeerTestObject",
                                     "org.gtk.GDBus.PeerTestInterface",
                                     "PeerSignal",
                                     NULL,
                                     &error);
      g_assert_no_error (error);
145 146 147 148 149 150 151 152 153 154 155 156 157 158
      g_dbus_method_invocation_return_value (invocation, NULL);
    }
  else if (g_strcmp0 (method_name, "EmitSignalWithNameSet") == 0)
    {
      GError *error;
      gboolean ret;
      GDBusMessage *message;

      message = g_dbus_message_new_signal ("/org/gtk/GDBus/PeerTestObject",
                                           "org.gtk.GDBus.PeerTestInterface",
                                           "PeerSignalWithNameSet");
      g_dbus_message_set_sender (message, ":1.42");

      error = NULL;
159
      ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, &error);
160 161 162 163
      g_assert_no_error (error);
      g_assert (ret);
      g_object_unref (message);

164 165 166 167
      g_dbus_method_invocation_return_value (invocation, NULL);
    }
  else if (g_strcmp0 (method_name, "OpenFile") == 0)
    {
168
#ifdef G_OS_UNIX
169 170 171 172 173 174
      const gchar *path;
      GDBusMessage *reply;
      GError *error;
      gint fd;
      GUnixFDList *fd_list;

175
      g_variant_get (parameters, "(&s)", &path);
176 177 178 179 180

      fd_list = g_unix_fd_list_new ();

      error = NULL;

181
      fd = g_open (path, O_RDONLY, 0);
182 183 184 185 186 187
      g_unix_fd_list_append (fd_list, fd, &error);
      g_assert_no_error (error);
      close (fd);

      reply = g_dbus_message_new_method_reply (g_dbus_method_invocation_get_message (invocation));
      g_dbus_message_set_unix_fd_list (reply, fd_list);
188
      g_object_unref (fd_list);
189 190 191 192 193
      g_object_unref (invocation);

      error = NULL;
      g_dbus_connection_send_message (connection,
                                      reply,
194
                                      G_DBUS_SEND_MESSAGE_FLAGS_NONE,
195 196 197 198
                                      NULL, /* out_serial */
                                      &error);
      g_assert_no_error (error);
      g_object_unref (reply);
199 200 201 202 203
#else
      g_dbus_method_invocation_return_dbus_error (invocation,
                                                  "org.gtk.GDBus.NotOnUnix",
                                                  "Your OS does not support file descriptor passing");
#endif
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 242 243 244 245 246 247 248 249 250
    }
  else
    {
      g_assert_not_reached ();
    }
}

static GVariant *
test_interface_get_property (GDBusConnection  *connection,
                             const gchar      *sender,
                             const gchar      *object_path,
                             const gchar      *interface_name,
                             const gchar      *property_name,
                             GError          **error,
                             gpointer          user_data)
{
  g_assert_cmpstr (object_path, ==, "/org/gtk/GDBus/PeerTestObject");
  g_assert_cmpstr (interface_name, ==, "org.gtk.GDBus.PeerTestInterface");
  g_assert_cmpstr (property_name, ==, "PeerProperty");

  return g_variant_new_string ("ThePropertyValue");
}


static const GDBusInterfaceVTable test_interface_vtable =
{
  test_interface_method_call,
  test_interface_get_property,
  NULL  /* set_property */
};

static void
on_proxy_signal_received (GDBusProxy *proxy,
                          gchar      *sender_name,
                          gchar      *signal_name,
                          GVariant   *parameters,
                          gpointer    user_data)
{
  PeerData *data = user_data;

  data->signal_received = TRUE;

  g_assert (sender_name == NULL);
  g_assert_cmpstr (signal_name, ==, "PeerSignal");
  g_main_loop_quit (loop);
}

251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
static void
on_proxy_signal_received_with_name_set (GDBusProxy *proxy,
                                        gchar      *sender_name,
                                        gchar      *signal_name,
                                        GVariant   *parameters,
                                        gpointer    user_data)
{
  PeerData *data = user_data;

  data->signal_received = TRUE;

  g_assert_cmpstr (sender_name, ==, ":1.42");
  g_assert_cmpstr (signal_name, ==, "PeerSignalWithNameSet");
  g_main_loop_quit (loop);
}

267 268 269
/* ---------------------------------------------------------------------------------------------------- */

static gboolean
270 271 272 273
on_authorize_authenticated_peer (GDBusAuthObserver *observer,
                                 GIOStream         *stream,
                                 GCredentials      *credentials,
                                 gpointer           user_data)
274 275
{
  PeerData *data = user_data;
276
  gboolean authorized;
277 278 279

  data->num_connection_attempts++;

280
  authorized = TRUE;
281 282
  if (!data->accept_connection)
    {
283
      authorized = FALSE;
284 285 286
      g_main_loop_quit (loop);
    }

287
  return authorized;
288 289 290
}

/* Runs in thread we created GDBusServer in (since we didn't pass G_DBUS_SERVER_FLAGS_RUN_IN_THREAD) */
291
static gboolean
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
on_new_connection (GDBusServer *server,
                   GDBusConnection *connection,
                   gpointer user_data)
{
  PeerData *data = user_data;
  GError *error;
  guint reg_id;

  //g_print ("Client connected.\n"
  //         "Negotiated capabilities: unix-fd-passing=%d\n",
  //         g_dbus_connection_get_capabilities (connection) & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);

  g_ptr_array_add (data->current_connections, g_object_ref (connection));

  /* export object on the newly established connection */
  error = NULL;
  reg_id = g_dbus_connection_register_object (connection,
                                              "/org/gtk/GDBus/PeerTestObject",
                                              test_interface_introspection_data,
                                              &test_interface_vtable,
                                              data,
                                              NULL, /* GDestroyNotify for data */
                                              &error);
  g_assert_no_error (error);
  g_assert (reg_id > 0);

  g_main_loop_quit (loop);
319 320

  return TRUE;
321 322 323 324 325 326 327
}

static gpointer
service_thread_func (gpointer user_data)
{
  PeerData *data = user_data;
  GMainContext *service_context;
328
  GDBusAuthObserver *observer, *o;
329
  GError *error;
330 331 332
  GDBusServerFlags f;
  gchar *a, *g;
  gboolean b;
333 334 335 336 337 338

  service_context = g_main_context_new ();
  g_main_context_push_thread_default (service_context);

  error = NULL;
  observer = g_dbus_auth_observer_new ();
339
  server = g_dbus_server_new_sync (tmp_address,
340 341 342 343 344 345 346 347 348 349 350 351
                                   G_DBUS_SERVER_FLAGS_NONE,
                                   test_guid,
                                   observer,
                                   NULL, /* cancellable */
                                   &error);
  g_assert_no_error (error);

  g_signal_connect (server,
                    "new-connection",
                    G_CALLBACK (on_new_connection),
                    data);
  g_signal_connect (observer,
352 353
                    "authorize-authenticated-peer",
                    G_CALLBACK (on_authorize_authenticated_peer),
354
                    data);
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373

  g_assert_cmpint (g_dbus_server_get_flags (server), ==, G_DBUS_SERVER_FLAGS_NONE);
  g_assert_cmpstr (g_dbus_server_get_guid (server), ==, test_guid);
  g_object_get (server,
                "flags", &f,
                "address", &a,
                "guid", &g,
                "active", &b,
                "authentication-observer", &o,
                NULL);
  g_assert_cmpint (f, ==, G_DBUS_SERVER_FLAGS_NONE);
  g_assert_cmpstr (a, ==, tmp_address);
  g_assert_cmpstr (g, ==, test_guid);
  g_assert (!b);
  g_assert (o == observer);
  g_free (a);
  g_free (g);
  g_object_unref (o);

374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
  g_object_unref (observer);

  g_dbus_server_start (server);

  service_loop = g_main_loop_new (service_context, FALSE);
  g_main_loop_run (service_loop);

  g_main_context_pop_thread_default (service_context);

  g_main_loop_unref (service_loop);
  g_main_context_unref (service_context);

  /* test code specifically unrefs the server - see below */
  g_assert (server == NULL);

  return NULL;
}

#if 0
static gboolean
on_incoming_connection (GSocketService     *service,
                        GSocketConnection  *socket_connection,
                        GObject            *source_object,
                        gpointer           user_data)
{
  PeerData *data = user_data;

  if (data->accept_connection)
    {
      GError *error;
      guint reg_id;
      GDBusConnection *connection;

      error = NULL;
      connection = g_dbus_connection_new_sync (G_IO_STREAM (socket_connection),
                                               test_guid,
                                               G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER,
                                               NULL, /* cancellable */
                                               &error);
      g_assert_no_error (error);

      g_ptr_array_add (data->current_connections, connection);

      /* export object on the newly established connection */
      error = NULL;
      reg_id = g_dbus_connection_register_object (connection,
                                                  "/org/gtk/GDBus/PeerTestObject",
                                                  &test_interface_introspection_data,
                                                  &test_interface_vtable,
                                                  data,
                                                  NULL, /* GDestroyNotify for data */
                                                  &error);
      g_assert_no_error (error);
      g_assert (reg_id > 0);

    }
  else
    {
      /* don't do anything */
    }

  data->num_connection_attempts++;

  g_main_loop_quit (loop);

  /* stops other signal handlers from being invoked */
  return TRUE;
}

static gpointer
service_thread_func (gpointer data)
{
  GMainContext *service_context;
  gchar *socket_path;
  GSocketAddress *address;
  GError *error;

  service_context = g_main_context_new ();
  g_main_context_push_thread_default (service_context);

  socket_path = g_strdup_printf ("/tmp/gdbus-test-pid-%d", getpid ());
  address = g_unix_socket_address_new (socket_path);

  service = g_socket_service_new ();
  error = NULL;
  g_socket_listener_add_address (G_SOCKET_LISTENER (service),
                                 address,
                                 G_SOCKET_TYPE_STREAM,
                                 G_SOCKET_PROTOCOL_DEFAULT,
                                 NULL, /* source_object */
                                 NULL, /* effective_address */
                                 &error);
  g_assert_no_error (error);
  g_signal_connect (service,
                    "incoming",
                    G_CALLBACK (on_incoming_connection),
                    data);
  g_socket_service_start (service);

  service_loop = g_main_loop_new (service_context, FALSE);
  g_main_loop_run (service_loop);

  g_main_context_pop_thread_default (service_context);

  g_main_loop_unref (service_loop);
  g_main_context_unref (service_context);

  g_object_unref (address);
  g_free (socket_path);
  return NULL;
}
#endif

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

#if 0
static gboolean
check_connection (gpointer user_data)
{
  PeerData *data = user_data;
  guint n;

  for (n = 0; n < data->current_connections->len; n++)
    {
      GDBusConnection *c;
      GIOStream *stream;

      c = G_DBUS_CONNECTION (data->current_connections->pdata[n]);
      stream = g_dbus_connection_get_stream (c);

      g_debug ("In check_connection for %d: connection %p, stream %p", n, c, stream);
      g_debug ("closed = %d", g_io_stream_is_closed (stream));

      GSocket *socket;
      socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (stream));
      g_debug ("socket_closed = %d", g_socket_is_closed (socket));
      g_debug ("socket_condition_check = %d", g_socket_condition_check (socket, G_IO_IN|G_IO_OUT|G_IO_ERR|G_IO_HUP));

      gchar buf[128];
      GError *error;
      gssize num_read;
      error = NULL;
      num_read = g_input_stream_read (g_io_stream_get_input_stream (stream),
                                      buf,
                                      128,
                                      NULL,
                                      &error);
      if (num_read < 0)
        {
          g_debug ("error: %s", error->message);
          g_error_free (error);
        }
      else
        {
          g_debug ("no error, read %d bytes", (gint) num_read);
        }
    }

  return FALSE;
}

static gboolean
on_do_disconnect_in_idle (gpointer data)
{
  GDBusConnection *c = G_DBUS_CONNECTION (data);
  g_debug ("GDC %p has ref_count %d", c, G_OBJECT (c)->ref_count);
  g_dbus_connection_disconnect (c);
  g_object_unref (c);
  return FALSE;
}
#endif

546 547 548 549 550 551 552 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
#ifdef G_OS_UNIX
static gchar *
read_all_from_fd (gint fd, gsize *out_len, GError **error)
{
  GString *str;
  gchar buf[64];
  gssize num_read;

  str = g_string_new (NULL);

  do
    {
      num_read = read (fd, buf, sizeof (buf));
      if (num_read == -1)
        {
          if (errno == EAGAIN || errno == EWOULDBLOCK)
            continue;
          g_set_error (error,
                       G_IO_ERROR,
                       g_io_error_from_errno (errno),
                       "Failed reading %d bytes into offset %d: %s",
                       (gint) sizeof (buf),
                       (gint) str->len,
                       strerror (errno));
          goto error;
        }
      else if (num_read > 0)
        {
          g_string_append_len (str, buf, num_read);
        }
      else if (num_read == 0)
        {
          break;
        }
    }
  while (TRUE);

  if (out_len != NULL)
    *out_len = str->len;
  return g_string_free (str, FALSE);

 error:
  if (out_len != NULL)
    out_len = 0;
  g_string_free (str, TRUE);
  return NULL;
}
#endif

595 596 597 598 599 600 601 602 603 604 605 606
static void
test_peer (void)
{
  GDBusConnection *c;
  GDBusConnection *c2;
  GDBusProxy *proxy;
  GError *error;
  PeerData data;
  GVariant *value;
  GVariant *result;
  const gchar *s;
  GThread *service_thread;
607
  gulong signal_handler_id;
608 609 610 611 612 613 614 615 616 617 618

  memset (&data, '\0', sizeof (PeerData));
  data.current_connections = g_ptr_array_new_with_free_func (g_object_unref);

  /* first try to connect when there is no server */
  error = NULL;
  c = g_dbus_connection_new_for_address_sync (is_unix ? "unix:path=/tmp/gdbus-test-does-not-exist-pid" :
                                              /* NOTE: Even if something is listening on port 12345 the connection
                                               * will fail because the nonce file doesn't exist */
                                              "nonce-tcp:host=localhost,port=12345,noncefile=this-does-not-exist-gdbus",
                                              G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
619
                                              NULL, /* GDBusAuthObserver */
620 621 622 623 624 625 626 627
                                              NULL, /* cancellable */
                                              &error);
  _g_assert_error_domain (error, G_IO_ERROR);
  g_assert (!g_dbus_error_is_remote_error (error));
  g_clear_error (&error);
  g_assert (c == NULL);

  /* bring up a server - we run the server in a different thread to avoid deadlocks */
628
  service_loop = NULL;
629 630
  service_thread = g_thread_new ("test_peer",
                                 service_thread_func,
631
                                 &data);
632 633 634 635 636 637 638 639 640
  while (service_loop == NULL)
    g_thread_yield ();
  g_assert (server != NULL);

  /* bring up a connection and accept it */
  data.accept_connection = TRUE;
  error = NULL;
  c = g_dbus_connection_new_for_address_sync (g_dbus_server_get_client_address (server),
                                              G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
641
                                              NULL, /* GDBusAuthObserver */
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
                                              NULL, /* cancellable */
                                              &error);
  g_assert_no_error (error);
  g_assert (c != NULL);
  while (data.current_connections->len < 1)
    g_main_loop_run (loop);
  g_assert_cmpint (data.current_connections->len, ==, 1);
  g_assert_cmpint (data.num_connection_attempts, ==, 1);
  g_assert (g_dbus_connection_get_unique_name (c) == NULL);
  g_assert_cmpstr (g_dbus_connection_get_guid (c), ==, test_guid);

  /* check that we create a proxy, read properties, receive signals and invoke
   * the HelloPeer() method. Since the server runs in another thread it's fine
   * to use synchronous blocking API here.
   */
  error = NULL;
  proxy = g_dbus_proxy_new_sync (c,
                                 G_DBUS_PROXY_FLAGS_NONE,
                                 NULL,
                                 NULL, /* bus_name */
                                 "/org/gtk/GDBus/PeerTestObject",
                                 "org.gtk.GDBus.PeerTestInterface",
                                 NULL, /* GCancellable */
                                 &error);
  g_assert_no_error (error);
  g_assert (proxy != NULL);
  error = NULL;
669
  value = g_dbus_proxy_get_cached_property (proxy, "PeerProperty");
670 671 672 673
  g_assert_cmpstr (g_variant_get_string (value, NULL), ==, "ThePropertyValue");

  /* try invoking a method */
  error = NULL;
674 675 676 677 678 679 680
  result = g_dbus_proxy_call_sync (proxy,
                                   "HelloPeer",
                                   g_variant_new ("(s)", "Hey Peer!"),
                                   G_DBUS_CALL_FLAGS_NONE,
                                   -1,
                                   NULL,  /* GCancellable */
                                   &error);
681
  g_assert_no_error (error);
682
  g_variant_get (result, "(&s)", &s);
683 684 685 686 687
  g_assert_cmpstr (s, ==, "You greeted me with 'Hey Peer!'.");
  g_variant_unref (result);
  g_assert_cmpint (data.num_method_calls, ==, 1);

  /* make the other peer emit a signal - catch it */
688 689 690 691
  signal_handler_id = g_signal_connect (proxy,
                                        "g-signal",
                                        G_CALLBACK (on_proxy_signal_received),
                                        &data);
692
  g_assert (!data.signal_received);
693 694 695 696 697 698 699 700
  g_dbus_proxy_call (proxy,
                     "EmitSignal",
                     NULL,  /* no arguments */
                     G_DBUS_CALL_FLAGS_NONE,
                     -1,
                     NULL,  /* GCancellable */
                     NULL,  /* GAsyncReadyCallback - we don't care about the result */
                     NULL); /* user_data */
701 702 703
  g_main_loop_run (loop);
  g_assert (data.signal_received);
  g_assert_cmpint (data.num_method_calls, ==, 2);
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
  g_signal_handler_disconnect (proxy, signal_handler_id);

  /* Also ensure that messages with the sender header-field set gets
   * delivered to the proxy - note that this doesn't really make sense
   * e.g. names are meaning-less in a peer-to-peer case... but we
   * support it because it makes sense in certain bridging
   * applications - see e.g. #623815.
   */
  signal_handler_id = g_signal_connect (proxy,
                                        "g-signal",
                                        G_CALLBACK (on_proxy_signal_received_with_name_set),
                                        &data);
  data.signal_received = FALSE;
  g_dbus_proxy_call (proxy,
                     "EmitSignalWithNameSet",
                     NULL,  /* no arguments */
                     G_DBUS_CALL_FLAGS_NONE,
                     -1,
                     NULL,  /* GCancellable */
                     NULL,  /* GAsyncReadyCallback - we don't care about the result */
                     NULL); /* user_data */
  g_main_loop_run (loop);
  g_assert (data.signal_received);
  g_assert_cmpint (data.num_method_calls, ==, 3);
  g_signal_handler_disconnect (proxy, signal_handler_id);
729 730 731 732 733 734 735 736

  /* check for UNIX fd passing */
#ifdef G_OS_UNIX
  {
    GDBusMessage *method_call_message;
    GDBusMessage *method_reply_message;
    GUnixFDList *fd_list;
    gint fd;
737 738
    gchar *buf;
    gsize len;
739 740 741 742 743 744 745 746 747 748 749
    gchar *buf2;
    gsize len2;

    method_call_message = g_dbus_message_new_method_call (NULL, /* name */
                                                          "/org/gtk/GDBus/PeerTestObject",
                                                          "org.gtk.GDBus.PeerTestInterface",
                                                          "OpenFile");
    g_dbus_message_set_body (method_call_message, g_variant_new ("(s)", "/etc/hosts"));
    error = NULL;
    method_reply_message = g_dbus_connection_send_message_with_reply_sync (c,
                                                                           method_call_message,
750
                                                                           G_DBUS_SEND_MESSAGE_FLAGS_NONE,
751 752 753 754 755
                                                                           -1,
                                                                           NULL, /* out_serial */
                                                                           NULL, /* cancellable */
                                                                           &error);
    g_assert_no_error (error);
756
    g_assert (g_dbus_message_get_message_type (method_reply_message) == G_DBUS_MESSAGE_TYPE_METHOD_RETURN);
757 758 759 760 761 762 763 764 765
    fd_list = g_dbus_message_get_unix_fd_list (method_reply_message);
    g_assert (fd_list != NULL);
    g_assert_cmpint (g_unix_fd_list_get_length (fd_list), ==, 1);
    error = NULL;
    fd = g_unix_fd_list_get (fd_list, 0, &error);
    g_assert_no_error (error);
    g_object_unref (method_call_message);
    g_object_unref (method_reply_message);

766
    error = NULL;
767
    len = 0;
768 769 770
    buf = read_all_from_fd (fd, &len, &error);
    g_assert_no_error (error);
    g_assert (buf != NULL);
771 772 773 774 775 776 777 778
    close (fd);

    error = NULL;
    g_file_get_contents ("/etc/hosts",
                         &buf2,
                         &len2,
                         &error);
    g_assert_no_error (error);
779 780
    g_assert_cmpint (len, ==, len2);
    g_assert (memcmp (buf, buf2, len) == 0);
781
    g_free (buf2);
782
    g_free (buf);
783
  }
784 785 786 787 788 789 790 791 792 793 794 795
#else
  error = NULL;
  result = g_dbus_proxy_call_sync (proxy,
                                   "OpenFile",
                                   g_variant_new ("(s)", "boo"),
                                   G_DBUS_CALL_FLAGS_NONE,
                                   -1,
                                   NULL,  /* GCancellable */
                                   &error);
  g_assert_error (error, G_IO_ERROR, G_IO_ERROR_DBUS_ERROR);
  g_assert (result == NULL);
  g_error_free (error);
796 797
#endif /* G_OS_UNIX */

798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
  /* Check that g_socket_get_credentials() work - this really should
   * be in a GSocket-specific test suite but no such test suite exists
   * right now.
   */
  {
    GSocket *socket;
    GCredentials *credentials;
    socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (g_dbus_connection_get_stream (c)));
    g_assert (G_IS_SOCKET (socket));
    error = NULL;
    credentials = g_socket_get_credentials (socket, &error);
#ifdef __linux__
    {
      struct ucred *native_creds;
      g_assert_no_error (error);
      g_assert (G_IS_CREDENTIALS (credentials));
      native_creds = g_credentials_get_native (credentials, G_CREDENTIALS_TYPE_LINUX_UCRED);
      g_assert (native_creds != NULL);
      g_assert (native_creds->uid == getuid ());
      g_assert (native_creds->gid == getgid ());
      g_assert (native_creds->pid == getpid ());
    }
    g_object_unref (credentials);
821 822 823 824 825 826 827 828 829 830 831 832
#elif defined (__OpenBSD__)
    {
      struct sockpeercred *native_creds;
      g_assert_no_error (error);
      g_assert (G_IS_CREDENTIALS (credentials));
      native_creds = g_credentials_get_native (credentials, G_CREDENTIALS_TYPE_OPENBSD_SOCKPEERCRED);
      g_assert (native_creds != NULL);
      g_assert (native_creds->uid == getuid ());
      g_assert (native_creds->gid == getgid ());
      g_assert (native_creds->pid == getpid ());
    }
    g_object_unref (credentials);
833 834 835 836 837 838
#else
    g_assert_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED);
    g_assert (credentials == NULL);
#endif
  }

839 840 841 842 843 844 845

  /* bring up a connection - don't accept it - this should fail
   */
  data.accept_connection = FALSE;
  error = NULL;
  c2 = g_dbus_connection_new_for_address_sync (g_dbus_server_get_client_address (server),
                                               G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
846
                                               NULL, /* GDBusAuthObserver */
847 848 849
                                               NULL, /* cancellable */
                                               &error);
  _g_assert_error_domain (error, G_IO_ERROR);
850
  g_error_free (error);
851 852 853 854 855 856 857 858 859 860 861 862
  g_assert (c2 == NULL);

#if 0
  /* TODO: THIS TEST DOESN'T WORK YET */

  /* bring up a connection - accept it.. then disconnect from the client side - check
   * that the server side gets the disconnect signal.
   */
  error = NULL;
  data.accept_connection = TRUE;
  c2 = g_dbus_connection_new_for_address_sync (g_dbus_server_get_client_address (server),
                                               G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
863
                                               NULL, /* GDBusAuthObserver */
864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
                                               NULL, /* cancellable */
                                               &error);
  g_assert_no_error (error);
  g_assert (c2 != NULL);
  g_assert (!g_dbus_connection_get_is_disconnected (c2));
  while (data.num_connection_attempts < 3)
    g_main_loop_run (loop);
  g_assert_cmpint (data.current_connections->len, ==, 2);
  g_assert_cmpint (data.num_connection_attempts, ==, 3);
  g_assert (!g_dbus_connection_get_is_disconnected (G_DBUS_CONNECTION (data.current_connections->pdata[1])));
  g_idle_add (on_do_disconnect_in_idle, c2);
  g_debug ("==================================================");
  g_debug ("==================================================");
  g_debug ("==================================================");
  g_debug ("waiting for disconnect on connection %p, stream %p",
           data.current_connections->pdata[1],
           g_dbus_connection_get_stream (data.current_connections->pdata[1]));

  g_timeout_add (2000, check_connection, &data);
  //_g_assert_signal_received (G_DBUS_CONNECTION (data.current_connections->pdata[1]), "closed");
  g_main_loop_run (loop);
  g_assert (g_dbus_connection_get_is_disconnected (G_DBUS_CONNECTION (data.current_connections->pdata[1])));
  g_ptr_array_set_size (data.current_connections, 1); /* remove disconnected connection object */
#endif

  /* unref the server and stop listening for new connections
   *
   * This won't bring down the established connections - check that c is still connected
   * by invoking a method
   */
  //g_socket_service_stop (service);
  //g_object_unref (service);
  g_dbus_server_stop (server);
  g_object_unref (server);
  server = NULL;

  error = NULL;
901 902 903 904 905 906 907
  result = g_dbus_proxy_call_sync (proxy,
                                   "HelloPeer",
                                   g_variant_new ("(s)", "Hey Again Peer!"),
                                   G_DBUS_CALL_FLAGS_NONE,
                                   -1,
                                   NULL,  /* GCancellable */
                                   &error);
908
  g_assert_no_error (error);
909
  g_variant_get (result, "(&s)", &s);
910 911
  g_assert_cmpstr (s, ==, "You greeted me with 'Hey Again Peer!'.");
  g_variant_unref (result);
912
  g_assert_cmpint (data.num_method_calls, ==, 5);
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935

#if 0
  /* TODO: THIS TEST DOESN'T WORK YET */

  /* now disconnect from the server side - check that the client side gets the signal */
  g_assert_cmpint (data.current_connections->len, ==, 1);
  g_assert (G_DBUS_CONNECTION (data.current_connections->pdata[0]) != c);
  g_dbus_connection_disconnect (G_DBUS_CONNECTION (data.current_connections->pdata[0]));
  if (!g_dbus_connection_get_is_disconnected (c))
    _g_assert_signal_received (c, "closed");
  g_assert (g_dbus_connection_get_is_disconnected (c));
#endif

  g_object_unref (c);
  g_ptr_array_unref (data.current_connections);
  g_object_unref (proxy);

  g_main_loop_quit (service_loop);
  g_thread_join (service_thread);
}

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

936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
typedef struct
{
  GDBusServer *server;
  GMainContext *context;
  GMainLoop *loop;

  GList *connections;
} DmpData;

static void
dmp_data_free (DmpData *data)
{
  g_main_loop_unref (data->loop);
  g_main_context_unref (data->context);
  g_object_unref (data->server);
951
  g_list_free_full (data->connections, g_object_unref);
952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
  g_free (data);
}

static void
dmp_on_method_call (GDBusConnection       *connection,
                    const gchar           *sender,
                    const gchar           *object_path,
                    const gchar           *interface_name,
                    const gchar           *method_name,
                    GVariant              *parameters,
                    GDBusMethodInvocation *invocation,
                    gpointer               user_data)
{
  //DmpData *data = user_data;
  gint32 first;
  gint32 second;
  g_variant_get (parameters,
                 "(ii)",
                 &first,
                 &second);
  g_dbus_method_invocation_return_value (invocation,
                                         g_variant_new ("(i)", first + second));
}

static const GDBusInterfaceVTable dmp_interface_vtable =
{
  dmp_on_method_call,
  NULL,  /* get_property */
  NULL   /* set_property */
};


/* Runs in thread we created GDBusServer in (since we didn't pass G_DBUS_SERVER_FLAGS_RUN_IN_THREAD) */
985
static gboolean
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
dmp_on_new_connection (GDBusServer     *server,
                       GDBusConnection *connection,
                       gpointer         user_data)
{
  DmpData *data = user_data;
  GDBusNodeInfo *node;
  GError *error;

  /* accept the connection */
  data->connections = g_list_prepend (data->connections, g_object_ref (connection));

  error = NULL;
  node = g_dbus_node_info_new_for_xml ("<node>"
                                       "  <interface name='org.gtk.GDBus.DmpInterface'>"
                                       "    <method name='AddPair'>"
                                       "      <arg type='i' name='first' direction='in'/>"
                                       "      <arg type='i' name='second' direction='in'/>"
                                       "      <arg type='i' name='sum' direction='out'/>"
                                       "    </method>"
                                       "  </interface>"
                                       "</node>",
                                       &error);
  g_assert_no_error (error);

  /* sleep 100ms before exporting an object - this is to test that
   * G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING really works
   * (GDBusServer uses this feature).
   */
  usleep (100 * 1000);

  /* export an object */
  error = NULL;
  g_dbus_connection_register_object (connection,
                                     "/dmp/test",
                                     node->interfaces[0],
                                     &dmp_interface_vtable,
                                     data,
                                     NULL,
                                     &error);
1025
  g_dbus_node_info_unref (node);
1026 1027

  return TRUE;
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
}

static gpointer
dmp_thread_func (gpointer user_data)
{
  DmpData *data = user_data;
  GError *error;
  gchar *guid;

  data->context = g_main_context_new ();
  g_main_context_push_thread_default (data->context);

  error = NULL;
  guid = g_dbus_generate_guid ();
1042
  data->server = g_dbus_server_new_sync (tmp_address,
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
                                         G_DBUS_SERVER_FLAGS_NONE,
                                         guid,
                                         NULL, /* GDBusAuthObserver */
                                         NULL, /* GCancellable */
                                         &error);
  g_assert_no_error (error);
  g_signal_connect (data->server,
                    "new-connection",
                    G_CALLBACK (dmp_on_new_connection),
                    data);

  g_dbus_server_start (data->server);

  data->loop = g_main_loop_new (data->context, FALSE);
  g_main_loop_run (data->loop);

  g_main_context_pop_thread_default (data->context);

  g_free (guid);
  return NULL;
}

static void
delayed_message_processing (void)
{
  GError *error;
  DmpData *data;
  GThread *service_thread;
  guint n;

  data = g_new0 (DmpData, 1);

1075 1076
  service_thread = g_thread_new ("dmp",
                                 dmp_thread_func,
1077
                                 data);
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 1120
  while (data->server == NULL || !g_dbus_server_is_active (data->server))
    g_thread_yield ();

  for (n = 0; n < 5; n++)
    {
      GDBusConnection *c;
      GVariant *res;
      gint32 val;

      error = NULL;
      c = g_dbus_connection_new_for_address_sync (g_dbus_server_get_client_address (data->server),
                                                  G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
                                                  NULL, /* GDBusAuthObserver */
                                                  NULL, /* GCancellable */
                                                  &error);
      g_assert_no_error (error);

      error = NULL;
      res = g_dbus_connection_call_sync (c,
                                         NULL,    /* bus name */
                                         "/dmp/test",
                                         "org.gtk.GDBus.DmpInterface",
                                         "AddPair",
                                         g_variant_new ("(ii)", 2, n),
                                         G_VARIANT_TYPE ("(i)"),
                                         G_DBUS_CALL_FLAGS_NONE,
                                         -1, /* timeout_msec */
                                         NULL, /* GCancellable */
                                         &error);
      g_assert_no_error (error);
      g_variant_get (res, "(i)", &val);
      g_assert_cmpint (val, ==, 2 + n);
      g_variant_unref (res);
      g_object_unref (c);
  }

  g_main_loop_quit (data->loop);
  g_thread_join (service_thread);
  dmp_data_free (data);
}

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

1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
static gboolean
nonce_tcp_on_authorize_authenticated_peer (GDBusAuthObserver *observer,
                                           GIOStream         *stream,
                                           GCredentials      *credentials,
                                           gpointer           user_data)
{
  PeerData *data = user_data;
  gboolean authorized;

  data->num_connection_attempts++;

  authorized = TRUE;
  if (!data->accept_connection)
    {
      authorized = FALSE;
      g_main_loop_quit (loop);
    }

  return authorized;
}

/* Runs in thread we created GDBusServer in (since we didn't pass G_DBUS_SERVER_FLAGS_RUN_IN_THREAD) */
1143
static gboolean
1144 1145 1146 1147 1148 1149 1150 1151 1152
nonce_tcp_on_new_connection (GDBusServer *server,
                             GDBusConnection *connection,
                             gpointer user_data)
{
  PeerData *data = user_data;

  g_ptr_array_add (data->current_connections, g_object_ref (connection));

  g_main_loop_quit (loop);
1153 1154

  return TRUE;
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
}

static gpointer
nonce_tcp_service_thread_func (gpointer user_data)
{
  PeerData *data = user_data;
  GMainContext *service_context;
  GDBusAuthObserver *observer;
  GError *error;

  service_context = g_main_context_new ();
  g_main_context_push_thread_default (service_context);

  error = NULL;
  observer = g_dbus_auth_observer_new ();
  server = g_dbus_server_new_sync ("nonce-tcp:",
                                   G_DBUS_SERVER_FLAGS_NONE,
                                   test_guid,
                                   observer,
                                   NULL, /* cancellable */
                                   &error);
  g_assert_no_error (error);

  g_signal_connect (server,
                    "new-connection",
                    G_CALLBACK (nonce_tcp_on_new_connection),
                    data);
  g_signal_connect (observer,
                    "authorize-authenticated-peer",
                    G_CALLBACK (nonce_tcp_on_authorize_authenticated_peer),
                    data);
  g_object_unref (observer);

  g_dbus_server_start (server);

  service_loop = g_main_loop_new (service_context, FALSE);
  g_main_loop_run (service_loop);

  g_main_context_pop_thread_default (service_context);

  g_main_loop_unref (service_loop);
  g_main_context_unref (service_context);

  /* test code specifically unrefs the server - see below */
  g_assert (server == NULL);

  return NULL;
}

static void
test_nonce_tcp (void)
{
  PeerData data;
  GError *error;
  GThread *service_thread;
  GDBusConnection *c;
  gchar *s;
  gchar *nonce_file;
  gboolean res;
  const gchar *address;

  memset (&data, '\0', sizeof (PeerData));
  data.current_connections = g_ptr_array_new_with_free_func (g_object_unref);

  error = NULL;
  server = NULL;
  service_loop = NULL;
1222 1223
  service_thread = g_thread_new ("nonce-tcp-service",
                                 nonce_tcp_service_thread_func,
1224
                                 &data);
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
  while (service_loop == NULL)
    g_thread_yield ();
  g_assert (server != NULL);


  /* bring up a connection and accept it */
  data.accept_connection = TRUE;
  error = NULL;
  c = g_dbus_connection_new_for_address_sync (g_dbus_server_get_client_address (server),
                                              G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
                                              NULL, /* GDBusAuthObserver */
                                              NULL, /* cancellable */
                                              &error);
  g_assert_no_error (error);
  g_assert (c != NULL);
  while (data.current_connections->len < 1)
1241
    g_thread_yield ();
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
  g_assert_cmpint (data.current_connections->len, ==, 1);
  g_assert_cmpint (data.num_connection_attempts, ==, 1);
  g_assert (g_dbus_connection_get_unique_name (c) == NULL);
  g_assert_cmpstr (g_dbus_connection_get_guid (c), ==, test_guid);
  g_object_unref (c);

  /* now, try to subvert the nonce file (this assumes noncefile is the last key/value pair)
   */

  address = g_dbus_server_get_client_address (server);

  s = strstr (address, "noncefile=");
  g_assert (s != NULL);
  s += sizeof "noncefile=" - 1;
  nonce_file = g_strdup (s);

  /* First try invalid data in the nonce file - this will actually
   * make the client send this and the server will reject it. The way
   * it works is that if the nonce doesn't match, the server will
   * simply close the connection. So, from the client point of view,
   * we can see a variety of errors.
   */
  error = NULL;
  res = g_file_set_contents (nonce_file,
                             "0123456789012345",
                             -1,
                             &error);
  g_assert_no_error (error);
  g_assert (res);
  c = g_dbus_connection_new_for_address_sync (address,
                                              G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
                                              NULL, /* GDBusAuthObserver */
                                              NULL, /* cancellable */
                                              &error);
  _g_assert_error_domain (error, G_IO_ERROR);
1277
  g_error_free (error);
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
  g_assert (c == NULL);

  /* Then try with a nonce-file of incorrect length - this will make
   * the client complain - we won't even try connecting to the server
   * for this
   */
  error = NULL;
  res = g_file_set_contents (nonce_file,
                             "0123456789012345_",
                             -1,
                             &error);
  g_assert_no_error (error);
  g_assert (res);
  c = g_dbus_connection_new_for_address_sync (address,
                                              G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
                                              NULL, /* GDBusAuthObserver */
                                              NULL, /* cancellable */
                                              &error);
  g_assert_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT);
1297
  g_error_free (error);
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
  g_assert (c == NULL);

  /* Finally try with no nonce-file at all */
  g_assert_cmpint (g_unlink (nonce_file), ==, 0);
  error = NULL;
  c = g_dbus_connection_new_for_address_sync (address,
                                              G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
                                              NULL, /* GDBusAuthObserver */
                                              NULL, /* cancellable */
                                              &error);
  g_assert_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT);
1309
  g_error_free (error);
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
  g_assert (c == NULL);

  g_free (nonce_file);

  g_dbus_server_stop (server);
  g_object_unref (server);
  server = NULL;

  g_main_loop_quit (service_loop);
  g_thread_join (service_thread);
}

1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
static void
test_credentials (void)
{
  GCredentials *c1, *c2;
  GError *error;
  gchar *desc;

  c1 = g_credentials_new ();
  c2 = g_credentials_new ();

  error = NULL;
  if (g_credentials_set_unix_user (c2, getuid (), &error))
    g_assert_no_error (error);

  g_clear_error (&error);
  g_assert (g_credentials_is_same_user (c1, c2, &error));
  g_assert_no_error (error);

  desc = g_credentials_to_string (c1);
  g_assert (desc != NULL);
  g_free (desc);

  g_object_unref (c1);
  g_object_unref (c2);
}

1348 1349
/* ---------------------------------------------------------------------------------------------------- */

1350 1351 1352 1353 1354 1355
#ifdef G_OS_UNIX

/* Chosen to be big enough to overflow the socket buffer */
#define OVERFLOW_NUM_SIGNALS 5000
#define OVERFLOW_TIMEOUT_SEC 10

1356
static GDBusMessage *
1357 1358 1359 1360
overflow_filter_func (GDBusConnection *connection,
                      GDBusMessage    *message,
                      gboolean         incoming,
                      gpointer         user_data)
1361
{
1362 1363
  volatile gint *counter = user_data;
  *counter += 1;
1364
  return message;
1365 1366 1367 1368 1369 1370 1371
}

static gboolean
overflow_on_500ms_later_func (gpointer user_data)
{
  g_main_loop_quit (loop);
  return FALSE; /* don't keep the idle */
1372 1373 1374 1375 1376
}

static void
test_overflow (void)
{
1377 1378
  gint sv[2];
  gint n;
1379 1380 1381 1382 1383
  GSocket *socket;
  GSocketConnection *socket_connection;
  GDBusConnection *producer, *consumer;
  GError *error;
  GTimer *timer;
1384 1385
  volatile gint n_messages_received;
  volatile gint n_messages_sent;
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398

  g_assert_cmpint (socketpair (AF_UNIX, SOCK_STREAM, 0, sv), ==, 0);

  error = NULL;
  socket = g_socket_new_from_fd (sv[0], &error);
  g_assert_no_error (error);
  socket_connection = g_socket_connection_factory_create_connection (socket);
  g_assert (socket_connection != NULL);
  g_object_unref (socket);
  producer = g_dbus_connection_new_sync (G_IO_STREAM (socket_connection),
					 NULL, /* guid */
					 G_DBUS_CONNECTION_FLAGS_NONE,
					 NULL, /* GDBusAuthObserver */
1399
					 NULL, /* GCancellable */
1400 1401 1402 1403
					 &error);
  g_dbus_connection_set_exit_on_close (producer, TRUE);
  g_assert_no_error (error);
  g_object_unref (socket_connection);
1404 1405
  n_messages_sent = 0;
  g_dbus_connection_add_filter (producer, overflow_filter_func, (gpointer) &n_messages_sent, NULL);
1406 1407

  /* send enough data that we get an EAGAIN */
1408
  for (n = 0; n < OVERFLOW_NUM_SIGNALS; n++)
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
    {
      error = NULL;
      g_dbus_connection_emit_signal (producer,
                                     NULL, /* destination */
                                     "/org/foo/Object",
                                     "org.foo.Interface",
                                     "Member",
                                     g_variant_new ("(s)", "a string"),
                                     &error);
      g_assert_no_error (error);
    }

1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
  /* sleep for 0.5 sec (to allow the GDBus IO thread to fill up the
   * kernel buffers) and verify that n_messages_sent <
   * OVERFLOW_NUM_SIGNALS
   *
   * This is to verify that not all the submitted messages have been
   * sent to the underlying transport.
   */
  g_timeout_add (500, overflow_on_500ms_later_func, NULL);
  g_main_loop_run (loop);
  g_assert_cmpint (n_messages_sent, <, OVERFLOW_NUM_SIGNALS);

1432 1433 1434 1435 1436 1437 1438
  /* now suck it all out as a client, and add it up */
  socket = g_socket_new_from_fd (sv[1], &error);
  g_assert_no_error (error);
  socket_connection = g_socket_connection_factory_create_connection (socket);
  g_assert (socket_connection != NULL);
  g_object_unref (socket);
  consumer = g_dbus_connection_new_sync (G_IO_STREAM (socket_connection),
1439
					 NULL, /* guid */
1440 1441
					 G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING,
					 NULL, /* GDBusAuthObserver */
1442
					 NULL, /* GCancellable */
1443 1444 1445
					 &error);
  g_assert_no_error (error);
  g_object_unref (socket_connection);
1446 1447 1448
  n_messages_received = 0;
  g_dbus_connection_add_filter (consumer, overflow_filter_func, (gpointer) &n_messages_received, NULL);
  g_dbus_connection_start_message_processing (consumer);
1449 1450 1451 1452

  timer = g_timer_new ();
  g_timer_start (timer);

1453
  while (n_messages_received < OVERFLOW_NUM_SIGNALS && g_timer_elapsed (timer, NULL) < OVERFLOW_TIMEOUT_SEC)
1454 1455
      g_main_context_iteration (NULL, FALSE);

1456 1457
  g_assert_cmpint (n_messages_sent, ==, OVERFLOW_NUM_SIGNALS);
  g_assert_cmpint (n_messages_received, ==, OVERFLOW_NUM_SIGNALS);
1458 1459 1460 1461 1462 1463 1464 1465 1466

  g_timer_destroy (timer);
  g_object_unref (consumer);
  g_object_unref (producer);
}
#else
static void
test_overflow (void)
{
1467
  /* TODO: test this with e.g. GWin32InputStream/GWin32OutputStream */
1468 1469 1470 1471 1472
}
#endif

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

1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
static gboolean
tcp_anonymous_on_new_connection (GDBusServer     *server,
                                 GDBusConnection *connection,
                                 gpointer         user_data)
{
  gboolean *seen_connection = user_data;
  *seen_connection = TRUE;
  return TRUE;
}

static gpointer
tcp_anonymous_service_thread_func (gpointer user_data)
{
  gboolean *seen_connection = user_data;
  GMainContext *service_context;
  GError *error;

  service_context = g_main_context_new ();
  g_main_context_push_thread_default (service_context);

  error = NULL;
  server = g_dbus_server_new_sync ("tcp:",
                                   G_DBUS_SERVER_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS,
                                   test_guid,
                                   NULL, /* GDBusObserver* */
                                   NULL, /* GCancellable* */
                                   &error);
  g_assert_no_error (error);

  g_signal_connect (server,
                    "new-connection",
                    G_CALLBACK (tcp_anonymous_on_new_connection),
                    seen_connection);

  g_dbus_server_start (server);

  service_loop = g_main_loop_new (service_context, FALSE);
  g_main_loop_run (service_loop);

  g_main_context_pop_thread_default (service_context);

  g_main_loop_unref (service_loop);
  g_main_context_unref (service_context);

  return NULL;
}

static void
test_tcp_anonymous (void)
{
  gboolean seen_connection;
  GThread *service_thread;
  GDBusConnection *connection;
  GError *error;

  seen_connection = FALSE;
  service_loop = NULL;
1530 1531
  service_thread = g_thread_new ("tcp-anon-service",
                                 tcp_anonymous_service_thread_func,
1532
                                 &seen_connection);
1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
  while (service_loop == NULL)
    g_thread_yield ();
  g_assert (server != NULL);

  error = NULL;
  connection = g_dbus_connection_new_for_address_sync (g_dbus_server_get_client_address (server),
                                                       G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
                                                       NULL, /* GDBusAuthObserver* */
                                                       NULL, /* GCancellable */
                                                       &error);
  g_assert_no_error (error);
  g_assert (connection != NULL);

  while (!seen_connection)
    g_thread_yield ();

  g_object_unref (connection);

  g_main_loop_quit (service_loop);
  g_dbus_server_stop (server);
  g_object_unref (server);
  server = NULL;

  g_thread_join (service_thread);
}

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

1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
static GDBusServer *codegen_server = NULL;

static gboolean
codegen_on_animal_poke (ExampleAnimal          *animal,
                        GDBusMethodInvocation  *invocation,
                        gboolean                make_sad,
                        gboolean                make_happy,
                        gpointer                user_data)
{
  if ((make_sad && make_happy) || (!make_sad && !make_happy))
    {
      g_main_loop_quit (service_loop);

      g_dbus_method_invocation_return_dbus_error (invocation,
                                                  "org.gtk.GDBus.Examples.ObjectManager.Error.Failed",
                                                  "Exactly one of make_sad or make_happy must be TRUE");
      goto out;
    }

  if (make_sad)
    {
      if (g_strcmp0 (example_animal_get_mood (animal), "Sad") == 0)
        {
          g_dbus_method_invocation_return_dbus_error (invocation,
                                                      "org.gtk.GDBus.Examples.ObjectManager.Error.SadAnimalIsSad",
                                                      "Sad animal is already sad");
          goto out;
        }

      example_animal_set_mood (animal, "Sad");
      example_animal_complete_poke (animal, invocation);
      goto out;
    }

  if (make_happy)
    {
      if (g_strcmp0 (example_animal_get_mood (animal), "Happy") == 0)
        {
          g_dbus_method_invocation_return_dbus_error (invocation,
                                                      "org.gtk.GDBus.Examples.ObjectManager.Error.HappyAnimalIsHappy",
                                                      "Happy animal is already happy");
          goto out;
        }

      example_animal_set_mood (animal, "Happy");
      example_animal_complete_poke (animal, invocation);
      goto out;
    }

  g_assert_not_reached ();

 out:
  return TRUE; /* to indicate that the method was handled */
}

/* Runs in thread we created GDBusServer in (since we didn't pass G_DBUS_SERVER_FLAGS_RUN_IN_THREAD) */
static gboolean
codegen_on_new_connection (GDBusServer *server,
                           GDBusConnection *connection,
                           gpointer user_data)
{
  ExampleAnimal *animal = user_data;
  GError        *error = NULL;

  /* g_print ("Client connected.\n" */
  /*          "Negotiated capabilities: unix-fd-passing=%d\n", */
  /*          g_dbus_connection_get_capabilities (connection) & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING); */

  g_dbus_interface_skeleton_export (G_DBUS_INTERFACE_SKELETON (animal), connection,
                                    "/Example/Animals/000", &error);
  g_assert_no_error (error);

  return TRUE;
}

static gpointer
codegen_service_thread_func (gpointer user_data)
{
  GMainContext   *service_context;
  ExampleAnimal  *animal;
  GError         *error = NULL;

  service_context = g_main_context_new ();
  g_main_context_push_thread_default (service_context);

  /* Create the animal in the right thread context */
  animal = example_animal_skeleton_new ();

  /* Handle Poke() D-Bus method invocations on the .Animal interface */
  g_signal_connect (animal, "handle-poke",
                    G_CALLBACK (codegen_on_animal_poke),
                    NULL); /* user_data */

  codegen_server = g_dbus_server_new_sync (tmp_address,
                                           G_DBUS_SERVER_FLAGS_NONE,
                                           test_guid,
                                           NULL, /* observer */
                                           NULL, /* cancellable */
                                           &error);
  g_assert_no_error (error);
  g_dbus_server_start (codegen_server);

  g_signal_connect (codegen_server, "new-connection",
                    G_CALLBACK (codegen_on_new_connection),
                    animal);

  service_loop = g_main_loop_new (service_context, FALSE);
  g_main_loop_run (service_loop);

  g_object_unref (animal);

  g_main_context_pop_thread_default (service_context);

  g_main_loop_unref (service_loop);
  g_main_context_unref (service_context);

  g_dbus_server_stop (codegen_server);
  g_object_unref (codegen_server);
  codegen_server = NULL;

  return NULL;
}


1685
static gboolean
1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
codegen_quit_mainloop_timeout (gpointer data)
{
  g_main_loop_quit (loop);
  return FALSE;
}

static void
codegen_test_peer (void)
{
  GDBusConnection     *connection;
  ExampleAnimal       *animal1, *animal2;
  GThread             *service_thread;
  GError              *error = NULL;
  GVariant            *value;

  /* bring up a server - we run the server in a different thread to avoid deadlocks */
1702
  service_loop = NULL;
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795
  service_thread = g_thread_new ("codegen_test_peer",
                                 codegen_service_thread_func,
                                 NULL);
  while (service_loop == NULL)
    g_thread_yield ();
  g_assert (codegen_server != NULL);

  /* Get an animal 1 ...  */
  connection = g_dbus_connection_new_for_address_sync (g_dbus_server_get_client_address (codegen_server),
                                                       G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
                                                       NULL, /* GDBusAuthObserver */
                                                       NULL, /* cancellable */
                                                       &error);
  g_assert_no_error (error);
  g_assert (connection != NULL);

  animal1 = example_animal_proxy_new_sync (connection, 0, NULL,
                                           "/Example/Animals/000", NULL, &error);
  g_assert_no_error (error);
  g_assert (animal1 != NULL);
  g_object_unref (connection);

  /* Get animal 2 ...  */
  connection = g_dbus_connection_new_for_address_sync (g_dbus_server_get_client_address (codegen_server),
                                                       G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
                                                       NULL, /* GDBusAuthObserver */
                                                       NULL, /* cancellable */
                                                       &error);
  g_assert_no_error (error);
  g_assert (connection != NULL);

  animal2 = example_animal_proxy_new_sync (connection, 0, NULL,
                                           "/Example/Animals/000", NULL, &error);
  g_assert_no_error (error);
  g_assert (animal2 != NULL);
  g_object_unref (connection);

  /* Make animal sad via animal1  */
  example_animal_call_poke_sync (animal1, TRUE, FALSE, NULL, &error);
  g_assert_no_error (error);

  /* Poke server and make sure animal is updated */
  value = g_dbus_proxy_call_sync (G_DBUS_PROXY (animal1),
                                  "org.freedesktop.DBus.Peer.Ping",
                                  NULL, G_DBUS_CALL_FLAGS_NONE, -1,
                                  NULL, &error);
  g_assert_no_error (error);
  g_assert (value != NULL);
  g_variant_unref (value);

  /* Give the proxies a chance to refresh in the defaul main loop */
  g_timeout_add (100, codegen_quit_mainloop_timeout, NULL);
  g_main_loop_run (loop);

  /* Assert animals are sad */
  g_assert_cmpstr (example_animal_get_mood (animal1), ==, "Sad");
  g_assert_cmpstr (example_animal_get_mood (animal2), ==, "Sad");

  /* Make animal happy via animal2  */
  example_animal_call_poke_sync (animal2, FALSE, TRUE, NULL, &error);
  g_assert_no_error (error);

  /* Poke server and make sure animal is updated */
  value = g_dbus_proxy_call_sync (G_DBUS_PROXY (animal2),
                                  "org.freedesktop.DBus.Peer.Ping",
                                  NULL, G_DBUS_CALL_FLAGS_NONE, -1,
                                  NULL, &error);
  g_assert_no_error (error);
  g_assert (value != NULL);
  g_variant_unref (value);

  /* Give the proxies a chance to refresh in the defaul main loop */
  g_timeout_add (1000, codegen_quit_mainloop_timeout, NULL);
  g_main_loop_run (loop);

  /* Assert animals are happy */
  g_assert_cmpstr (example_animal_get_mood (animal1), ==, "Happy");
  g_assert_cmpstr (example_animal_get_mood (animal2), ==, "Happy");

  /* This final call making the animal happy and sad will cause
   * the server to quit, when the server quits we dont get property
   * change notifications anyway because those are done from an idle handler
   */
  example_animal_call_poke_sync (animal2, TRUE, TRUE, NULL, &error);

  g_object_unref (animal1);
  g_object_unref (animal2);
  g_thread_join (service_thread);
}

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


1796 1797 1798 1799 1800 1801
int
main (int   argc,
      char *argv[])
{
  gint ret;
  GDBusNodeInfo *introspection_data = NULL;
1802
  gchar *tmpdir = NULL;
1803 1804 1805 1806 1807 1808 1809 1810 1811

  g_test_init (&argc, &argv, NULL);

  introspection_data = g_dbus_node_info_new_for_xml (test_interface_introspection_xml, NULL);
  g_assert (introspection_data != NULL);
  test_interface_introspection_data = introspection_data->interfaces[0];

  test_guid = g_dbus_generate_guid ();

1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824
  if (is_unix)
    {
      if (g_unix_socket_address_abstract_names_supported ())
	tmp_address = g_strdup ("unix:tmpdir=/tmp/gdbus-test-");
      else
	{
	  tmpdir = g_dir_make_tmp ("gdbus-test-XXXXXX", NULL);
	  tmp_address = g_strdup_printf ("unix:tmpdir=%s", tmpdir);
	}
    }
  else
    tmp_address = g_strdup ("nonce-tcp:");

1825 1826 1827 1828
  /* all the tests rely on a shared main loop */
  loop = g_main_loop_new (NULL, FALSE);

  g_test_add_func ("/gdbus/peer-to-peer", test_peer);
1829
  g_test_add_func ("/gdbus/delayed-message-processing", delayed_message_processing);
1830
  g_test_add_func ("/gdbus/nonce-tcp", test_nonce_tcp);
1831
  g_test_add_func ("/gdbus/tcp-anonymous", test_tcp_anonymous);
1832
  g_test_add_func ("/gdbus/credentials", test_credentials);
1833
  g_test_add_func ("/gdbus/overflow", test_overflow);
1834
  g_test_add_func ("/gdbus/codegen-peer-to-peer", codegen_test_peer);
1835 1836 1837 1838 1839 1840

  ret = g_test_run();

  g_main_loop_unref (loop);
  g_free (test_guid);
  g_dbus_node_info_unref (introspection_data);
1841 1842 1843 1844 1845 1846 1847
  if (is_unix)
    g_free (tmp_address);
  if (tmpdir)
    {
      g_rmdir (tmpdir);
      g_free (tmpdir);
    }
1848 1849 1850

  return ret;
}