gdbusserver.c 34.8 KB
Newer Older
1 2
/* GDBus - GLib D-Bus Library
 *
3
 * Copyright (C) 2008-2010 Red Hat, Inc.
4 5 6 7 8 9 10 11 12 13 14 15
 *
 * 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
16
 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
17 18 19 20 21 22 23
 *
 * Author: David Zeuthen <davidz@redhat.com>
 */

#include "config.h"

#include <stdlib.h>
David Zeuthen's avatar
David Zeuthen committed
24
#include <string.h>
25 26 27
#include <errno.h>

#include "giotypes.h"
28
#include "gioerror.h"
29 30 31 32 33 34 35
#include "gdbusaddress.h"
#include "gdbusutils.h"
#include "gdbusconnection.h"
#include "gdbusserver.h"
#include "gioenumtypes.h"
#include "gdbusprivate.h"
#include "gdbusauthobserver.h"
David Zeuthen's avatar
David Zeuthen committed
36 37
#include "ginitable.h"
#include "gsocketservice.h"
38 39
#include "gthreadedsocketservice.h"
#include "gresolver.h"
Colin Walters's avatar
Colin Walters committed
40
#include "glib/gstdio.h"
41 42 43 44
#include "ginetaddress.h"
#include "ginetsocketaddress.h"
#include "ginputstream.h"
#include "giostream.h"
David Zeuthen's avatar
David Zeuthen committed
45

46 47 48 49 50 51 52
#ifdef G_OS_UNIX
#include <unistd.h>
#endif
#ifdef G_OS_WIN32
#include <io.h>
#endif

David Zeuthen's avatar
David Zeuthen committed
53 54 55 56 57
#ifdef G_OS_UNIX
#include "gunixsocketaddress.h"
#endif

#include "glibintl.h"
58 59 60 61

/**
 * SECTION:gdbusserver
 * @short_description: Helper for accepting connections
David Zeuthen's avatar
David Zeuthen committed
62
 * @include: gio/gio.h
63 64
 *
 * #GDBusServer is a helper for listening to and accepting D-Bus
65 66 67 68 69 70 71
 * connections. This can be used to create a new D-Bus server, allowing two
 * peers to use the D-Bus protocol for their own specialized communication.
 * A server instance provided in this way will not perform message routing or
 * implement the org.freedesktop.DBus interface.
 *
 * To just export an object on a well-known name on a message bus, such as the
 * session or system bus, you should instead use g_bus_own_name().
72
 *
73 74
 * An example of peer-to-peer communication with G-DBus can be found
 * in [gdbus-example-peer.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-peer.c).
75 76
 */

77
/**
78
 * GDBusServer:
79
 *
80 81
 * The #GDBusServer structure contains only private data and
 * should only be accessed using the provided API.
82 83 84
 *
 * Since: 2.26
 */
85
struct _GDBusServer
86 87
{
  /*< private >*/
88
  GObject parent_instance;
89

90 91 92 93 94 95 96 97 98 99 100
  GDBusServerFlags flags;
  gchar *address;
  gchar *guid;

  guchar *nonce;
  gchar *nonce_file;

  gchar *client_address;

  GSocketListener *listener;
  gboolean is_using_listener;
101
  gulong run_signal_handler_id;
102

103
  /* The result of g_main_context_ref_thread_default() when the object
104 105 106 107 108 109 110 111 112 113
   * was created (the GObject _init() function) - this is used for delivery
   * of the :new-connection GObject signal.
   */
  GMainContext *main_context_at_construction;

  gboolean active;

  GDBusAuthObserver *authentication_observer;
};

114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
typedef struct _GDBusServerClass GDBusServerClass;

/**
 * GDBusServerClass:
 * @new_connection: Signal class handler for the #GDBusServer::new-connection signal.
 *
 * Class structure for #GDBusServer.
 *
 * Since: 2.26
 */
struct _GDBusServerClass
{
  /*< private >*/
  GObjectClass parent_class;

  /*< public >*/
  /* Signals */
131 132
  gboolean (*new_connection) (GDBusServer      *server,
                              GDBusConnection  *connection);
133 134
};

135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
enum
{
  PROP_0,
  PROP_ADDRESS,
  PROP_CLIENT_ADDRESS,
  PROP_FLAGS,
  PROP_GUID,
  PROP_ACTIVE,
  PROP_AUTHENTICATION_OBSERVER,
};

enum
{
  NEW_CONNECTION_SIGNAL,
  LAST_SIGNAL,
};

152
static guint _signals[LAST_SIGNAL] = {0};
153 154 155 156 157 158 159 160 161 162 163 164

static void initable_iface_init       (GInitableIface *initable_iface);

G_DEFINE_TYPE_WITH_CODE (GDBusServer, g_dbus_server, G_TYPE_OBJECT,
                         G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
                         );

static void
g_dbus_server_finalize (GObject *object)
{
  GDBusServer *server = G_DBUS_SERVER (object);

165 166
  if (server->authentication_observer != NULL)
    g_object_unref (server->authentication_observer);
167

168 169 170
  if (server->run_signal_handler_id > 0)
    g_signal_handler_disconnect (server->listener, server->run_signal_handler_id);

171 172
  if (server->listener != NULL)
    g_object_unref (server->listener);
173

174 175 176 177
  g_free (server->address);
  g_free (server->guid);
  g_free (server->client_address);
  if (server->nonce != NULL)
178
    {
179 180
      memset (server->nonce, '\0', 16);
      g_free (server->nonce);
181 182 183 184
    }
  /* we could unlink the nonce file but I don't
   * think it's really worth the effort/risk
   */
185
  g_free (server->nonce_file);
186

187
  g_main_context_unref (server->main_context_at_construction);
188

Matthias Clasen's avatar
Matthias Clasen committed
189
  G_OBJECT_CLASS (g_dbus_server_parent_class)->finalize (object);
190 191 192 193 194 195 196 197 198 199 200 201 202
}

static void
g_dbus_server_get_property (GObject    *object,
                            guint       prop_id,
                            GValue     *value,
                            GParamSpec *pspec)
{
  GDBusServer *server = G_DBUS_SERVER (object);

  switch (prop_id)
    {
    case PROP_FLAGS:
203
      g_value_set_flags (value, server->flags);
204 205 206
      break;

    case PROP_GUID:
207
      g_value_set_string (value, server->guid);
208 209 210
      break;

    case PROP_ADDRESS:
211
      g_value_set_string (value, server->address);
212 213 214
      break;

    case PROP_CLIENT_ADDRESS:
215
      g_value_set_string (value, server->client_address);
216 217 218
      break;

    case PROP_ACTIVE:
219
      g_value_set_boolean (value, server->active);
220 221 222
      break;

    case PROP_AUTHENTICATION_OBSERVER:
223
      g_value_set_object (value, server->authentication_observer);
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
      break;

    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
    }
}

static void
g_dbus_server_set_property (GObject      *object,
                            guint         prop_id,
                            const GValue *value,
                            GParamSpec   *pspec)
{
  GDBusServer *server = G_DBUS_SERVER (object);

  switch (prop_id)
    {
    case PROP_FLAGS:
243
      server->flags = g_value_get_flags (value);
244 245 246
      break;

    case PROP_GUID:
247
      server->guid = g_value_dup_string (value);
248 249 250
      break;

    case PROP_ADDRESS:
251
      server->address = g_value_dup_string (value);
252 253 254
      break;

    case PROP_AUTHENTICATION_OBSERVER:
255
      server->authentication_observer = g_value_dup_object (value);
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
      break;

    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
    }
}

static void
g_dbus_server_class_init (GDBusServerClass *klass)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (klass);

  gobject_class->finalize     = g_dbus_server_finalize;
  gobject_class->set_property = g_dbus_server_set_property;
  gobject_class->get_property = g_dbus_server_get_property;

  /**
   * GDBusServer:flags:
   *
   * Flags from the #GDBusServerFlags enumeration.
277 278
   *
   * Since: 2.26
279 280 281 282
   */
  g_object_class_install_property (gobject_class,
                                   PROP_FLAGS,
                                   g_param_spec_flags ("flags",
Matthias Clasen's avatar
Matthias Clasen committed
283 284
                                                       P_("Flags"),
                                                       P_("Flags for the server"),
285 286 287 288 289 290 291 292 293 294 295 296 297
                                                       G_TYPE_DBUS_SERVER_FLAGS,
                                                       G_DBUS_SERVER_FLAGS_NONE,
                                                       G_PARAM_READABLE |
                                                       G_PARAM_WRITABLE |
                                                       G_PARAM_CONSTRUCT_ONLY |
                                                       G_PARAM_STATIC_NAME |
                                                       G_PARAM_STATIC_BLURB |
                                                       G_PARAM_STATIC_NICK));

  /**
   * GDBusServer:guid:
   *
   * The guid of the server.
298 299
   *
   * Since: 2.26
300 301 302 303
   */
  g_object_class_install_property (gobject_class,
                                   PROP_GUID,
                                   g_param_spec_string ("guid",
Matthias Clasen's avatar
Matthias Clasen committed
304 305
                                                        P_("GUID"),
                                                        P_("The guid of the server"),
306 307 308 309 310 311 312 313 314 315 316 317
                                                        NULL,
                                                        G_PARAM_READABLE |
                                                        G_PARAM_WRITABLE |
                                                        G_PARAM_CONSTRUCT_ONLY |
                                                        G_PARAM_STATIC_NAME |
                                                        G_PARAM_STATIC_BLURB |
                                                        G_PARAM_STATIC_NICK));

  /**
   * GDBusServer:address:
   *
   * The D-Bus address to listen on.
318 319
   *
   * Since: 2.26
320 321 322 323
   */
  g_object_class_install_property (gobject_class,
                                   PROP_ADDRESS,
                                   g_param_spec_string ("address",
Matthias Clasen's avatar
Matthias Clasen committed
324 325
                                                        P_("Address"),
                                                        P_("The address to listen on"),
326 327 328 329 330 331 332 333 334 335 336 337
                                                        NULL,
                                                        G_PARAM_READABLE |
                                                        G_PARAM_WRITABLE |
                                                        G_PARAM_CONSTRUCT_ONLY |
                                                        G_PARAM_STATIC_NAME |
                                                        G_PARAM_STATIC_BLURB |
                                                        G_PARAM_STATIC_NICK));

  /**
   * GDBusServer:client-address:
   *
   * The D-Bus address that clients can use.
338 339
   *
   * Since: 2.26
340 341 342 343
   */
  g_object_class_install_property (gobject_class,
                                   PROP_CLIENT_ADDRESS,
                                   g_param_spec_string ("client-address",
Matthias Clasen's avatar
Matthias Clasen committed
344 345
                                                        P_("Client Address"),
                                                        P_("The address clients can use"),
346 347 348 349 350 351 352 353 354 355
                                                        NULL,
                                                        G_PARAM_READABLE |
                                                        G_PARAM_STATIC_NAME |
                                                        G_PARAM_STATIC_BLURB |
                                                        G_PARAM_STATIC_NICK));

  /**
   * GDBusServer:active:
   *
   * Whether the server is currently active.
356 357
   *
   * Since: 2.26
358 359 360
   */
  g_object_class_install_property (gobject_class,
                                   PROP_ACTIVE,
361 362 363 364 365 366 367 368
                                   g_param_spec_boolean ("active",
                                                         P_("Active"),
                                                         P_("Whether the server is currently active"),
                                                         FALSE,
                                                         G_PARAM_READABLE |
                                                         G_PARAM_STATIC_NAME |
                                                         G_PARAM_STATIC_BLURB |
                                                         G_PARAM_STATIC_NICK));
369 370 371 372 373

  /**
   * GDBusServer:authentication-observer:
   *
   * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
374 375
   *
   * Since: 2.26
376 377 378 379
   */
  g_object_class_install_property (gobject_class,
                                   PROP_AUTHENTICATION_OBSERVER,
                                   g_param_spec_object ("authentication-observer",
Matthias Clasen's avatar
Matthias Clasen committed
380 381
                                                        P_("Authentication Observer"),
                                                        P_("Object used to assist in the authentication process"),
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
                                                        G_TYPE_DBUS_AUTH_OBSERVER,
                                                        G_PARAM_READABLE |
                                                        G_PARAM_WRITABLE |
                                                        G_PARAM_CONSTRUCT_ONLY |
                                                        G_PARAM_STATIC_NAME |
                                                        G_PARAM_STATIC_BLURB |
                                                        G_PARAM_STATIC_NICK));

  /**
   * GDBusServer::new-connection:
   * @server: The #GDBusServer emitting the signal.
   * @connection: A #GDBusConnection for the new connection.
   *
   * Emitted when a new authenticated connection has been made. Use
   * g_dbus_connection_get_peer_credentials() to figure out what
   * identity (if any), was authenticated.
   *
399 400 401 402 403 404
   * If you want to accept the connection, take a reference to the
   * @connection object and return %TRUE. When you are done with the
   * connection call g_dbus_connection_close() and give up your
   * reference. Note that the other peer may disconnect at any time -
   * a typical thing to do when accepting a connection is to listen to
   * the #GDBusConnection::closed signal.
405 406 407
   *
   * If #GDBusServer:flags contains %G_DBUS_SERVER_FLAGS_RUN_IN_THREAD
   * then the signal is emitted in a new thread dedicated to the
408 409 410
   * connection. Otherwise the signal is emitted in the
   * [thread-default main context][g-main-context-push-thread-default]
   * of the thread that @server was constructed in.
411
   *
412 413 414 415 416
   * You are guaranteed that signal handlers for this signal runs
   * before incoming messages on @connection are processed. This means
   * that it's suitable to call g_dbus_connection_register_object() or
   * similar from the signal handler.
   *
417 418 419
   * Returns: %TRUE to claim @connection, %FALSE to let other handlers
   * run.
   *
420
   * Since: 2.26
421
   */
422
  _signals[NEW_CONNECTION_SIGNAL] = g_signal_new (I_("new-connection"),
423 424 425
                                                  G_TYPE_DBUS_SERVER,
                                                  G_SIGNAL_RUN_LAST,
                                                  G_STRUCT_OFFSET (GDBusServerClass, new_connection),
426 427
                                                  g_signal_accumulator_true_handled,
                                                  NULL, /* accu_data */
428
                                                  NULL,
429
                                                  G_TYPE_BOOLEAN,
430 431 432 433 434 435 436
                                                  1,
                                                  G_TYPE_DBUS_CONNECTION);
}

static void
g_dbus_server_init (GDBusServer *server)
{
437
  server->main_context_at_construction = g_main_context_ref_thread_default ();
438 439 440 441 442 443 444 445 446 447 448 449 450
}

static gboolean
on_run (GSocketService    *service,
        GSocketConnection *socket_connection,
        GObject           *source_object,
        gpointer           user_data);

/**
 * g_dbus_server_new_sync:
 * @address: A D-Bus address.
 * @flags: Flags from the #GDBusServerFlags enumeration.
 * @guid: A D-Bus GUID.
451
 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
452
 * @cancellable: (allow-none): A #GCancellable or %NULL.
453 454 455 456 457 458 459 460 461 462 463 464 465 466
 * @error: Return location for server or %NULL.
 *
 * Creates a new D-Bus server that listens on the first address in
 * @address that works.
 *
 * Once constructed, you can use g_dbus_server_get_client_address() to
 * get a D-Bus address string that clients can use to connect.
 *
 * Connect to the #GDBusServer::new-connection signal to handle
 * incoming connections.
 *
 * The returned #GDBusServer isn't active - you have to start it with
 * g_dbus_server_start().
 *
467
 * #GDBusServer is used in this [example][gdbus-peer-to-peer].
468 469 470 471 472 473
 *
 * This is a synchronous failable constructor. See
 * g_dbus_server_new() for the asynchronous version.
 *
 * Returns: A #GDBusServer or %NULL if @error is set. Free with
 * g_object_unref().
474 475
 *
 * Since: 2.26
476 477
 */
GDBusServer *
Matthias Clasen's avatar
Matthias Clasen committed
478 479 480 481 482 483
g_dbus_server_new_sync (const gchar        *address,
                        GDBusServerFlags    flags,
                        const gchar        *guid,
                        GDBusAuthObserver  *observer,
                        GCancellable       *cancellable,
                        GError            **error)
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
{
  GDBusServer *server;

  g_return_val_if_fail (address != NULL, NULL);
  g_return_val_if_fail (g_dbus_is_guid (guid), NULL);
  g_return_val_if_fail (error == NULL || *error == NULL, NULL);

  server = g_initable_new (G_TYPE_DBUS_SERVER,
                           cancellable,
                           error,
                           "address", address,
                           "flags", flags,
                           "guid", guid,
                           "authentication-observer", observer,
                           NULL);

  return server;
}

/**
 * g_dbus_server_get_client_address:
 * @server: A #GDBusServer.
 *
 * Gets a D-Bus address string that can be used by clients to connect
 * to @server.
 *
 * Returns: A D-Bus address string. Do not free, the string is owned
 * by @server.
512 513
 *
 * Since: 2.26
514 515 516 517 518
 */
const gchar *
g_dbus_server_get_client_address (GDBusServer *server)
{
  g_return_val_if_fail (G_IS_DBUS_SERVER (server), NULL);
519
  return server->client_address;
520 521 522 523 524 525 526 527 528
}

/**
 * g_dbus_server_get_guid:
 * @server: A #GDBusServer.
 *
 * Gets the GUID for @server.
 *
 * Returns: A D-Bus GUID. Do not free this string, it is owned by @server.
529 530
 *
 * Since: 2.26
531 532 533 534 535
 */
const gchar *
g_dbus_server_get_guid (GDBusServer *server)
{
  g_return_val_if_fail (G_IS_DBUS_SERVER (server), NULL);
536
  return server->guid;
537 538 539 540 541 542 543 544 545
}

/**
 * g_dbus_server_get_flags:
 * @server: A #GDBusServer.
 *
 * Gets the flags for @server.
 *
 * Returns: A set of flags from the #GDBusServerFlags enumeration.
546 547
 *
 * Since: 2.26
548 549 550 551 552
 */
GDBusServerFlags
g_dbus_server_get_flags (GDBusServer *server)
{
  g_return_val_if_fail (G_IS_DBUS_SERVER (server), G_DBUS_SERVER_FLAGS_NONE);
553
  return server->flags;
554 555 556 557 558 559 560 561 562
}

/**
 * g_dbus_server_is_active:
 * @server: A #GDBusServer.
 *
 * Gets whether @server is active.
 *
 * Returns: %TRUE if server is active, %FALSE otherwise.
563 564
 *
 * Since: 2.26
565 566 567 568 569
 */
gboolean
g_dbus_server_is_active (GDBusServer *server)
{
  g_return_val_if_fail (G_IS_DBUS_SERVER (server), G_DBUS_SERVER_FLAGS_NONE);
570
  return server->active;
571 572 573 574 575 576 577
}

/**
 * g_dbus_server_start:
 * @server: A #GDBusServer.
 *
 * Starts @server.
578 579
 *
 * Since: 2.26
580 581 582 583 584
 */
void
g_dbus_server_start (GDBusServer *server)
{
  g_return_if_fail (G_IS_DBUS_SERVER (server));
585
  if (server->active)
586 587
    return;
  /* Right now we don't have any transport not using the listener... */
588 589 590
  g_assert (server->is_using_listener);
  g_socket_service_start (G_SOCKET_SERVICE (server->listener));
  server->active = TRUE;
591 592 593 594 595 596 597 598
  g_object_notify (G_OBJECT (server), "active");
}

/**
 * g_dbus_server_stop:
 * @server: A #GDBusServer.
 *
 * Stops @server.
599 600
 *
 * Since: 2.26
601 602 603 604 605
 */
void
g_dbus_server_stop (GDBusServer *server)
{
  g_return_if_fail (G_IS_DBUS_SERVER (server));
606
  if (!server->active)
607 608
    return;
  /* Right now we don't have any transport not using the listener... */
609
  g_assert (server->is_using_listener);
610 611 612
  g_assert (server->run_signal_handler_id > 0);
  g_signal_handler_disconnect (server->listener, server->run_signal_handler_id);
  server->run_signal_handler_id = 0;
613 614
  g_socket_service_stop (G_SOCKET_SERVICE (server->listener));
  server->active = FALSE;
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
  g_object_notify (G_OBJECT (server), "active");
}

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

#ifdef G_OS_UNIX

static gint
random_ascii (void)
{
  gint ret;
  ret = g_random_int_range (0, 60);
  if (ret < 25)
    ret += 'A';
  else if (ret < 50)
    ret += 'a' - 25;
  else
    ret += '0' - 50;
  return ret;
}

/* note that address_entry has already been validated => exactly one of path, tmpdir or abstract keys are set */
static gboolean
try_unix (GDBusServer  *server,
          const gchar  *address_entry,
          GHashTable   *key_value_pairs,
          GError      **error)
{
  gboolean ret;
  const gchar *path;
  const gchar *tmpdir;
  const gchar *abstract;
  GSocketAddress *address;

  ret = FALSE;
  address = NULL;

  path = g_hash_table_lookup (key_value_pairs, "path");
  tmpdir = g_hash_table_lookup (key_value_pairs, "tmpdir");
  abstract = g_hash_table_lookup (key_value_pairs, "abstract");

  if (path != NULL)
    {
      address = g_unix_socket_address_new (path);
    }
  else if (tmpdir != NULL)
    {
      gint n;
      GString *s;
      GError *local_error;

    retry:
      s = g_string_new (tmpdir);
      g_string_append (s, "/dbus-");
      for (n = 0; n < 8; n++)
        g_string_append_c (s, random_ascii ());

      /* prefer abstract namespace if available */
      if (g_unix_socket_address_abstract_names_supported ())
        address = g_unix_socket_address_new_with_type (s->str,
                                                       -1,
                                                       G_UNIX_SOCKET_ADDRESS_ABSTRACT);
      else
        address = g_unix_socket_address_new (s->str);
      g_string_free (s, TRUE);

      local_error = NULL;
682
      if (!g_socket_listener_add_address (server->listener,
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
                                          address,
                                          G_SOCKET_TYPE_STREAM,
                                          G_SOCKET_PROTOCOL_DEFAULT,
                                          NULL, /* source_object */
                                          NULL, /* effective_address */
                                          &local_error))
        {
          if (local_error->domain == G_IO_ERROR && local_error->code == G_IO_ERROR_ADDRESS_IN_USE)
            {
              g_error_free (local_error);
              goto retry;
            }
          g_propagate_error (error, local_error);
          goto out;
        }
      ret = TRUE;
      goto out;
    }
  else if (abstract != NULL)
    {
      if (!g_unix_socket_address_abstract_names_supported ())
        {
          g_set_error_literal (error,
                               G_IO_ERROR,
                               G_IO_ERROR_NOT_SUPPORTED,
                               _("Abstract name space not supported"));
          goto out;
        }
      address = g_unix_socket_address_new_with_type (abstract,
                                                     -1,
                                                     G_UNIX_SOCKET_ADDRESS_ABSTRACT);
    }
  else
    {
      g_assert_not_reached ();
    }

720
  if (!g_socket_listener_add_address (server->listener,
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
                                      address,
                                      G_SOCKET_TYPE_STREAM,
                                      G_SOCKET_PROTOCOL_DEFAULT,
                                      NULL, /* source_object */
                                      NULL, /* effective_address */
                                      error))
    goto out;

  ret = TRUE;

 out:

  if (address != NULL)
    {
      /* Fill out client_address if the connection attempt worked */
      if (ret)
        {
738
          server->is_using_listener = TRUE;
739 740 741 742

          switch (g_unix_socket_address_get_address_type (G_UNIX_SOCKET_ADDRESS (address)))
            {
            case G_UNIX_SOCKET_ADDRESS_ABSTRACT:
743 744
              server->client_address = g_strdup_printf ("unix:abstract=%s",
                                                        g_unix_socket_address_get_path (G_UNIX_SOCKET_ADDRESS (address)));
745 746 747
              break;

            case G_UNIX_SOCKET_ADDRESS_PATH:
748 749
              server->client_address = g_strdup_printf ("unix:path=%s",
                                                        g_unix_socket_address_get_path (G_UNIX_SOCKET_ADDRESS (address)));
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
              break;

            default:
              g_assert_not_reached ();
              break;
            }
        }
      g_object_unref (address);
    }
  return ret;
}
#endif

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

/* note that address_entry has already been validated =>
Matthias Clasen's avatar
Matthias Clasen committed
766
 *  both host and port (guaranteed to be a number in [0, 65535]) are set (family is optional)
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
 */
static gboolean
try_tcp (GDBusServer  *server,
         const gchar  *address_entry,
         GHashTable   *key_value_pairs,
         gboolean      do_nonce,
         GError      **error)
{
  gboolean ret;
  const gchar *host;
  const gchar *port;
  gint port_num;
  GResolver *resolver;
  GList *resolved_addresses;
  GList *l;

  ret = FALSE;
  resolver = NULL;
  resolved_addresses = NULL;

  host = g_hash_table_lookup (key_value_pairs, "host");
  port = g_hash_table_lookup (key_value_pairs, "port");
789
  /* family = g_hash_table_lookup (key_value_pairs, "family"); */
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
  if (g_hash_table_lookup (key_value_pairs, "noncefile") != NULL)
    {
      g_set_error_literal (error,
                           G_IO_ERROR,
                           G_IO_ERROR_INVALID_ARGUMENT,
                           _("Cannot specify nonce file when creating a server"));
      goto out;
    }

  if (host == NULL)
    host = "localhost";
  if (port == NULL)
    port = "0";
  port_num = strtol (port, NULL, 10);

  resolver = g_resolver_get_default ();
  resolved_addresses = g_resolver_lookup_by_name (resolver,
                                                  host,
                                                  NULL,
                                                  error);
  if (resolved_addresses == NULL)
Matthias Clasen's avatar
Matthias Clasen committed
811 812
    goto out;

813 814 815 816 817 818 819 820
  /* TODO: handle family */
  for (l = resolved_addresses; l != NULL; l = l->next)
    {
      GInetAddress *address = G_INET_ADDRESS (l->data);
      GSocketAddress *socket_address;
      GSocketAddress *effective_address;

      socket_address = g_inet_socket_address_new (address, port_num);
821
      if (!g_socket_listener_add_address (server->listener,
822 823 824 825 826 827 828 829 830 831 832
                                          socket_address,
                                          G_SOCKET_TYPE_STREAM,
                                          G_SOCKET_PROTOCOL_TCP,
                                          NULL, /* GObject *source_object */
                                          &effective_address,
                                          error))
        {
          g_object_unref (socket_address);
          goto out;
        }
      if (port_num == 0)
Matthias Clasen's avatar
Matthias Clasen committed
833 834 835
        /* make sure we allocate the same port number for other listeners */
        port_num = g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (effective_address));

836 837 838 839 840 841 842 843 844 845
      g_object_unref (effective_address);
      g_object_unref (socket_address);
    }

  if (do_nonce)
    {
      gint fd;
      guint n;
      gsize bytes_written;
      gsize bytes_remaining;
846
      char *file_escaped;
847

848
      server->nonce = g_new0 (guchar, 16);
849
      for (n = 0; n < 16; n++)
850
        server->nonce[n] = g_random_int_range (0, 256);
851
      fd = g_file_open_tmp ("gdbus-nonce-file-XXXXXX",
852
                            &server->nonce_file,
853 854 855
                            error);
      if (fd == -1)
        {
856
          g_socket_listener_close (server->listener);
857 858 859 860 861 862 863 864
          goto out;
        }
    again:
      bytes_written = 0;
      bytes_remaining = 16;
      while (bytes_remaining > 0)
        {
          gssize ret;
865
          ret = write (fd, server->nonce + bytes_written, bytes_remaining);
866 867 868 869 870 871 872
          if (ret == -1)
            {
              if (errno == EINTR)
                goto again;
              g_set_error (error,
                           G_IO_ERROR,
                           g_io_error_from_errno (errno),
873
                           _("Error writing nonce file at “%s”: %s"),
874
                           server->nonce_file,
875 876 877 878 879 880
                           strerror (errno));
              goto out;
            }
          bytes_written += ret;
          bytes_remaining -= ret;
        }
Colin Walters's avatar
Colin Walters committed
881 882
      if (!g_close (fd, error))
        goto out;
883
      file_escaped = g_uri_escape_string (server->nonce_file, "/\\", FALSE);
884 885 886
      server->client_address = g_strdup_printf ("nonce-tcp:host=%s,port=%d,noncefile=%s",
                                                host,
                                                port_num,
887 888
                                                file_escaped);
      g_free (file_escaped);
889 890 891
    }
  else
    {
892
      server->client_address = g_strdup_printf ("tcp:host=%s,port=%d", host, port_num);
893
    }
894
  server->is_using_listener = TRUE;
895 896 897
  ret = TRUE;

 out:
898
  g_list_free_full (resolved_addresses, g_object_unref);
899 900
  if (resolver)
    g_object_unref (resolver);
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
  return ret;
}

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

typedef struct
{
  GDBusServer *server;
  GDBusConnection *connection;
} EmitIdleData;

static void
emit_idle_data_free (EmitIdleData *data)
{
  g_object_unref (data->server);
  g_object_unref (data->connection);
  g_free (data);
}

static gboolean
emit_new_connection_in_idle (gpointer user_data)
{
  EmitIdleData *data = user_data;
924
  gboolean claimed;
925

926
  claimed = FALSE;
927 928 929
  g_signal_emit (data->server,
                 _signals[NEW_CONNECTION_SIGNAL],
                 0,
930 931 932 933 934
                 data->connection,
                 &claimed);

  if (claimed)
    g_dbus_connection_start_message_processing (data->connection);
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
  g_object_unref (data->connection);

  return FALSE;
}

/* Called in new thread */
static gboolean
on_run (GSocketService    *service,
        GSocketConnection *socket_connection,
        GObject           *source_object,
        gpointer           user_data)
{
  GDBusServer *server = G_DBUS_SERVER (user_data);
  GDBusConnection *connection;
  GDBusConnectionFlags connection_flags;

951
  if (server->nonce != NULL)
952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
    {
      gchar buf[16];
      gsize bytes_read;

      if (!g_input_stream_read_all (g_io_stream_get_input_stream (G_IO_STREAM (socket_connection)),
                                    buf,
                                    16,
                                    &bytes_read,
                                    NULL,  /* GCancellable */
                                    NULL)) /* GError */
        goto out;

      if (bytes_read != 16)
        goto out;

967
      if (memcmp (buf, server->nonce, 16) != 0)
968 969 970
        goto out;
    }

971 972 973
  connection_flags =
    G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER |
    G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING;
974
  if (server->flags & G_DBUS_SERVER_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS)
975 976 977
    connection_flags |= G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS;

  connection = g_dbus_connection_new_sync (G_IO_STREAM (socket_connection),
978
                                           server->guid,
979
                                           connection_flags,
980
                                           server->authentication_observer,
981 982 983 984 985
                                           NULL,  /* GCancellable */
                                           NULL); /* GError */
  if (connection == NULL)
      goto out;

986
  if (server->flags & G_DBUS_SERVER_FLAGS_RUN_IN_THREAD)
987
    {
988 989 990
      gboolean claimed;

      claimed = FALSE;
991 992 993
      g_signal_emit (server,
                     _signals[NEW_CONNECTION_SIGNAL],
                     0,
994 995 996 997
                     connection,
                     &claimed);
      if (claimed)
        g_dbus_connection_start_message_processing (connection);
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
      g_object_unref (connection);
    }
  else
    {
      GSource *idle_source;
      EmitIdleData *data;

      data = g_new0 (EmitIdleData, 1);
      data->server = g_object_ref (server);
      data->connection = g_object_ref (connection);

      idle_source = g_idle_source_new ();
      g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
      g_source_set_callback (idle_source,
                             emit_new_connection_in_idle,
                             data,
                             (GDestroyNotify) emit_idle_data_free);
1015
      g_source_set_name (idle_source, "[gio] emit_new_connection_in_idle");
1016
      g_source_attach (idle_source, server->main_context_at_construction);
1017 1018 1019 1020 1021 1022 1023 1024
      g_source_unref (idle_source);
    }

 out:
  return TRUE;
}

static gboolean
Matthias Clasen's avatar
Matthias Clasen committed
1025 1026 1027
initable_init (GInitable     *initable,
               GCancellable  *cancellable,
               GError       **error)
1028 1029 1030 1031 1032 1033 1034 1035
{
  GDBusServer *server = G_DBUS_SERVER (initable);
  gboolean ret;
  guint n;
  gchar **addr_array;
  GError *last_error;

  ret = FALSE;
1036
  addr_array = NULL;
1037 1038
  last_error = NULL;

1039
  if (!g_dbus_is_guid (server->guid))
1040 1041 1042 1043
    {
      g_set_error (&last_error,
                   G_IO_ERROR,
                   G_IO_ERROR_INVALID_ARGUMENT,
1044
                   _("The string “%s” is not a valid D-Bus GUID"),
1045
                   server->guid);
1046 1047 1048
      goto out;
    }

1049
  server->listener = G_SOCKET_LISTENER (g_threaded_socket_service_new (-1));
1050

1051
  addr_array = g_strsplit (server->address, ";", 0);
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
  last_error = NULL;
  for (n = 0; addr_array != NULL && addr_array[n] != NULL; n++)
    {
      const gchar *address_entry = addr_array[n];
      GHashTable *key_value_pairs;
      gchar *transport_name;
      GError *this_error;

      this_error = NULL;
      if (g_dbus_is_supported_address (address_entry,
                                       &this_error) &&
          _g_dbus_address_parse_entry (address_entry,
                                       &transport_name,
                                       &key_value_pairs,
                                       &this_error))
        {

          if (FALSE)
            {
            }
#ifdef G_OS_UNIX
          else if (g_strcmp0 (transport_name, "unix") == 0)
Matthias Clasen's avatar
Matthias Clasen committed
1074
            ret = try_unix (server, address_entry, key_value_pairs, &this_error);
1075 1076
#endif
          else if (g_strcmp0 (transport_name, "tcp") == 0)
Matthias Clasen's avatar
Matthias Clasen committed
1077
            ret = try_tcp (server, address_entry, key_value_pairs, FALSE, &this_error);
1078
          else if (g_strcmp0 (transport_name, "nonce-tcp") == 0)
Matthias Clasen's avatar
Matthias Clasen committed
1079
            ret = try_tcp (server, address_entry, key_value_pairs, TRUE, &this_error);
1080
          else
Matthias Clasen's avatar
Matthias Clasen committed
1081 1082 1083
            g_set_error (&this_error,
                         G_IO_ERROR,
                         G_IO_ERROR_INVALID_ARGUMENT,
1084
                         _("Cannot listen on unsupported transport “%s”"),
Matthias Clasen's avatar
Matthias Clasen committed
1085
                         transport_name);
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106

          g_free (transport_name);
          if (key_value_pairs != NULL)
            g_hash_table_unref (key_value_pairs);

          if (ret)
            {
              g_assert (this_error == NULL);
              goto out;
            }
        }

      if (this_error != NULL)
        {
          if (last_error != NULL)
            g_error_free (last_error);
          last_error = this_error;
        }
    }

 out:
Christian Persch's avatar
Christian Persch committed
1107 1108 1109

  g_strfreev (addr_array);

1110 1111 1112 1113
  if (ret)
    {
      if (last_error != NULL)
        g_error_free (last_error);
1114 1115 1116 1117 1118 1119 1120

      /* Right now we don't have any transport not using the listener... */
      g_assert (server->is_using_listener);
      server->run_signal_handler_id = g_signal_connect (G_SOCKET_SERVICE (server->listener),
                                                        "run",
                                                        G_CALLBACK (on_run),
                                                        server);
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
    }
  else
    {
      g_assert (last_error != NULL);
      g_propagate_error (error, last_error);
    }
  return ret;
}


static void
initable_iface_init (GInitableIface *initable_iface)
{
  initable_iface->init = initable_init;
}

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