gsocketclient.c 29.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
/*  GIO - GLib Input, Output and Streaming Library
 *
 * Copyright © 2008, 2009 codethink
 * Copyright © 2009 Red Hat, Inc
 *
 * 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.
 *
 * Authors: Ryan Lortie <desrt@desrt.ca>
 *          Alexander Larsson <alexl@redhat.com>
 */

#include "config.h"
#include "gsocketclient.h"

#include <stdlib.h>

#include <gio/gioenumtypes.h>
#include <gio/gsocketaddressenumerator.h>
#include <gio/gsocketconnectable.h>
#include <gio/gsocketconnection.h>
#include <gio/gsimpleasyncresult.h>
#include <gio/gcancellable.h>
#include <gio/gioerror.h>
#include <gio/gsocket.h>
#include <gio/gnetworkaddress.h>
39
#include <gio/gnetworkservice.h>
40 41 42 43 44 45
#include <gio/gsocketaddress.h>
#include "glibintl.h"


/**
 * SECTION:gsocketclient
46
 * @short_description: Helper for connecting to a network service
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
 * @include: gio/gio.h
 * @see_also: #GSocketConnection, #GSocketListener
 *
 * #GSocketClient is a high-level utility class for connecting to a
 * network host using a connection oriented socket type.
 *
 * You create a #GSocketClient object, set any options you want, then
 * call a sync or async connect operation, which returns a #GSocketConnection
 * subclass on success.
 *
 * The type of the #GSocketConnection object returned depends on the type of
 * the underlying socket that is in use. For instance, for a TCP/IP connection
 * it will be a #GTcpConnection.
 *
 * Since: 2.22
62
 */
63 64 65 66 67 68 69 70 71 72


G_DEFINE_TYPE (GSocketClient, g_socket_client, G_TYPE_OBJECT);

enum
{
  PROP_NONE,
  PROP_FAMILY,
  PROP_TYPE,
  PROP_PROTOCOL,
73 74
  PROP_LOCAL_ADDRESS,
  PROP_TIMEOUT
75 76 77 78 79 80
};

struct _GSocketClientPrivate
{
  GSocketFamily family;
  GSocketType type;
81
  GSocketProtocol protocol;
82
  GSocketAddress *local_address;
83
  guint timeout;
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
};

static GSocket *
create_socket (GSocketClient  *client,
	       GSocketAddress *dest_address,
	       GError        **error)
{
  GSocketFamily family;
  GSocket *socket;

  family = client->priv->family;
  if (family == G_SOCKET_FAMILY_INVALID &&
      client->priv->local_address != NULL)
    family = g_socket_address_get_family (client->priv->local_address);
  if (family == G_SOCKET_FAMILY_INVALID)
    family = g_socket_address_get_family (dest_address);

  socket = g_socket_new (family,
			 client->priv->type,
103
			 client->priv->protocol,
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
			 error);
  if (socket == NULL)
    return NULL;

  if (client->priv->local_address)
    {
      if (!g_socket_bind (socket,
			  client->priv->local_address,
			  FALSE,
			  error))
	{
	  g_object_unref (socket);
	  return NULL;
	}
    }

120 121 122
  if (client->priv->timeout)
    g_socket_set_timeout (socket, client->priv->timeout);

123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
  return socket;
}

static void
g_socket_client_init (GSocketClient *client)
{
  client->priv = G_TYPE_INSTANCE_GET_PRIVATE (client,
					      G_TYPE_SOCKET_CLIENT,
					      GSocketClientPrivate);
  client->priv->type = G_SOCKET_TYPE_STREAM;
}

/**
 * g_socket_client_new:
 *
 * Creates a new #GSocketClient with the default options.
 *
 * Returns: a #GSocketClient.
 *     Free the returned object with g_object_unref().
 *
 * Since: 2.22
144
 */
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
GSocketClient *
g_socket_client_new (void)
{
  return g_object_new (G_TYPE_SOCKET_CLIENT, NULL);
}

static void
g_socket_client_finalize (GObject *object)
{
  GSocketClient *client = G_SOCKET_CLIENT (object);

  if (client->priv->local_address)
    g_object_unref (client->priv->local_address);

  if (G_OBJECT_CLASS (g_socket_client_parent_class)->finalize)
    (*G_OBJECT_CLASS (g_socket_client_parent_class)->finalize) (object);
}

static void
g_socket_client_get_property (GObject    *object,
			      guint       prop_id,
			      GValue     *value,
			      GParamSpec *pspec)
{
  GSocketClient *client = G_SOCKET_CLIENT (object);

  switch (prop_id)
    {
      case PROP_FAMILY:
	g_value_set_enum (value, client->priv->family);
	break;

      case PROP_TYPE:
	g_value_set_enum (value, client->priv->type);
	break;

      case PROP_PROTOCOL:
182
	g_value_set_enum (value, client->priv->protocol);
183 184 185 186 187 188
	break;

      case PROP_LOCAL_ADDRESS:
	g_value_set_object (value, client->priv->local_address);
	break;

189 190 191 192
      case PROP_TIMEOUT:
	g_value_set_uint (value, client->priv->timeout);
	break;

193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
      default:
	G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
    }
}

static void
g_socket_client_set_property (GObject      *object,
			      guint         prop_id,
			      const GValue *value,
			      GParamSpec   *pspec)
{
  GSocketClient *client = G_SOCKET_CLIENT (object);

  switch (prop_id)
    {
    case PROP_FAMILY:
      g_socket_client_set_family (client, g_value_get_enum (value));
      break;

    case PROP_TYPE:
      g_socket_client_set_socket_type (client, g_value_get_enum (value));
      break;

    case PROP_PROTOCOL:
217
      g_socket_client_set_protocol (client, g_value_get_enum (value));
218 219 220 221 222 223
      break;

    case PROP_LOCAL_ADDRESS:
      g_socket_client_set_local_address (client, g_value_get_object (value));
      break;

224 225 226 227
    case PROP_TIMEOUT:
      g_socket_client_set_timeout (client, g_value_get_uint (value));
      break;

228 229 230 231 232 233 234
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
    }
}

/**
 * g_socket_client_get_family:
235
 * @client: a #GSocketClient.
236 237 238 239 240 241 242 243
 *
 * Gets the socket family of the socket client.
 *
 * See g_socket_client_set_family() for details.
 *
 * Returns: a #GSocketFamily
 *
 * Since: 2.22
244
 */
245 246 247 248 249 250 251 252
GSocketFamily
g_socket_client_get_family (GSocketClient *client)
{
  return client->priv->family;
}

/**
 * g_socket_client_set_family:
253
 * @client: a #GSocketClient.
254 255 256 257 258 259 260 261 262 263 264 265
 * @family: a #GSocketFamily
 *
 * Sets the socket family of the socket client.
 * If this is set to something other than %G_SOCKET_FAMILY_INVALID
 * then the sockets created by this object will be of the specified
 * family.
 *
 * This might be useful for instance if you want to force the local
 * connection to be an ipv4 socket, even though the address might
 * be an ipv6 mapped to ipv4 address.
 *
 * Since: 2.22
266
 */
267 268
void
g_socket_client_set_family (GSocketClient *client,
269
			    GSocketFamily  family)
270 271 272 273 274 275 276 277 278 279
{
  if (client->priv->family == family)
    return;

  client->priv->family = family;
  g_object_notify (G_OBJECT (client), "family");
}

/**
 * g_socket_client_get_socket_type:
280
 * @client: a #GSocketClient.
281 282 283 284 285 286 287 288
 *
 * Gets the socket type of the socket client.
 *
 * See g_socket_client_set_socket_type() for details.
 *
 * Returns: a #GSocketFamily
 *
 * Since: 2.22
289
 */
290 291 292 293 294 295 296 297
GSocketType
g_socket_client_get_socket_type (GSocketClient *client)
{
  return client->priv->type;
}

/**
 * g_socket_client_set_socket_type:
298
 * @client: a #GSocketClient.
299 300 301 302 303 304 305 306 307 308
 * @type: a #GSocketType
 *
 * Sets the socket type of the socket client.
 * The sockets created by this object will be of the specified
 * type.
 *
 * It doesn't make sense to specify a type of %G_SOCKET_TYPE_DATAGRAM,
 * as GSocketClient is used for connection oriented services.
 *
 * Since: 2.22
309
 */
310 311
void
g_socket_client_set_socket_type (GSocketClient *client,
312
				 GSocketType    type)
313 314 315 316 317 318 319 320 321 322
{
  if (client->priv->type == type)
    return;

  client->priv->type = type;
  g_object_notify (G_OBJECT (client), "type");
}

/**
 * g_socket_client_get_protocol:
323
 * @client: a #GSocketClient
324 325 326 327 328
 *
 * Gets the protocol name type of the socket client.
 *
 * See g_socket_client_set_protocol() for details.
 *
329
 * Returns: a #GSocketProtocol
330 331
 *
 * Since: 2.22
332
 */
333
GSocketProtocol
334 335 336 337 338 339 340
g_socket_client_get_protocol (GSocketClient *client)
{
  return client->priv->protocol;
}

/**
 * g_socket_client_set_protocol:
341
 * @client: a #GSocketClient.
342
 * @protocol: a #GSocketProtocol
343 344 345 346 347
 *
 * Sets the protocol of the socket client.
 * The sockets created by this object will use of the specified
 * protocol.
 *
348
 * If @protocol is %0 that means to use the default
349 350 351
 * protocol for the socket family and type.
 *
 * Since: 2.22
352
 */
353
void
354 355
g_socket_client_set_protocol (GSocketClient   *client,
			      GSocketProtocol  protocol)
356
{
357
  if (client->priv->protocol == protocol)
358 359
    return;

360
  client->priv->protocol = protocol;
361 362 363 364 365
  g_object_notify (G_OBJECT (client), "protocol");
}

/**
 * g_socket_client_get_local_address:
366
 * @client: a #GSocketClient.
367 368 369 370 371
 *
 * Gets the local address of the socket client.
 *
 * See g_socket_client_set_local_address() for details.
 *
372
 * Returns: (transfer none): a #GSocketAddres or %NULL. don't free
373 374
 *
 * Since: 2.22
375
 */
376 377 378 379 380 381 382 383
GSocketAddress *
g_socket_client_get_local_address (GSocketClient *client)
{
  return client->priv->local_address;
}

/**
 * g_socket_client_set_local_address:
384 385
 * @client: a #GSocketClient.
 * @address: a #GSocketAddress, or %NULL
386 387 388 389 390 391 392 393 394 395
 *
 * Sets the local address of the socket client.
 * The sockets created by this object will bound to the
 * specified address (if not %NULL) before connecting.
 *
 * This is useful if you want to ensure the the local
 * side of the connection is on a specific port, or on
 * a specific interface.
 *
 * Since: 2.22
396
 */
397
void
398 399
g_socket_client_set_local_address (GSocketClient  *client,
				   GSocketAddress *address)
400 401 402 403 404 405 406 407 408 409 410 411
{
  if (address)
  g_object_ref (address);

  if (client->priv->local_address)
    {
      g_object_unref (client->priv->local_address);
    }
  client->priv->local_address = address;
  g_object_notify (G_OBJECT (client), "local-address");
}

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
/**
 * g_socket_client_get_timeout:
 * @client: a #GSocketClient
 *
 * Gets the I/O timeout time for sockets created by @client.
 *
 * See g_socket_client_set_timeout() for details.
 *
 * Returns: the timeout in seconds
 *
 * Since: 2.26
 */
guint
g_socket_client_get_timeout (GSocketClient *client)
{
  return client->priv->timeout;
}


/**
 * g_socket_client_set_timeout:
 * @client: a #GSocketClient.
 * @timeout: the timeout
 *
 * Sets the I/O timeout for sockets created by @client. @timeout is a
 * time in seconds, or 0 for no timeout (the default).
 *
 * The timeout value affects the initial connection attempt as well,
 * so setting this may cause calls to g_socket_client_connect(), etc,
 * to fail with %G_IO_ERROR_TIMED_OUT.
 *
 * Since: 2.26
 */
void
g_socket_client_set_timeout (GSocketClient *client,
			     guint          timeout)
{
  if (client->priv->timeout == timeout)
    return;

  client->priv->timeout = timeout;
  g_object_notify (G_OBJECT (client), "timeout");
}

456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
static void
g_socket_client_class_init (GSocketClientClass *class)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (class);

  g_type_class_add_private (class, sizeof (GSocketClientPrivate));

  gobject_class->finalize = g_socket_client_finalize;
  gobject_class->set_property = g_socket_client_set_property;
  gobject_class->get_property = g_socket_client_get_property;

  g_object_class_install_property (gobject_class, PROP_FAMILY,
				   g_param_spec_enum ("family",
						      P_("Socket family"),
						      P_("The sockets address family to use for socket construction"),
						      G_TYPE_SOCKET_FAMILY,
						      G_SOCKET_FAMILY_INVALID,
473 474 475
						      G_PARAM_CONSTRUCT |
                                                      G_PARAM_READWRITE |
                                                      G_PARAM_STATIC_STRINGS));
476 477 478 479 480 481 482

  g_object_class_install_property (gobject_class, PROP_TYPE,
				   g_param_spec_enum ("type",
						      P_("Socket type"),
						      P_("The sockets type to use for socket construction"),
						      G_TYPE_SOCKET_TYPE,
						      G_SOCKET_TYPE_STREAM,
483 484 485
						      G_PARAM_CONSTRUCT |
                                                      G_PARAM_READWRITE |
                                                      G_PARAM_STATIC_STRINGS));
486 487

  g_object_class_install_property (gobject_class, PROP_PROTOCOL,
488 489 490 491 492
				   g_param_spec_enum ("protocol",
						      P_("Socket protocol"),
						      P_("The protocol to use for socket construction, or 0 for default"),
						      G_TYPE_SOCKET_PROTOCOL,
						      G_SOCKET_PROTOCOL_DEFAULT,
493 494 495
						      G_PARAM_CONSTRUCT |
                                                      G_PARAM_READWRITE |
                                                      G_PARAM_STATIC_STRINGS));
496 497 498 499 500 501

  g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
				   g_param_spec_object ("local-address",
							P_("Local address"),
							P_("The local address constructed sockets will be bound to"),
							G_TYPE_SOCKET_ADDRESS,
502 503 504
							G_PARAM_CONSTRUCT |
                                                        G_PARAM_READWRITE |
                                                        G_PARAM_STATIC_STRINGS));
505 506 507 508 509 510 511 512 513 514

  g_object_class_install_property (gobject_class, PROP_TIMEOUT,
				   g_param_spec_uint ("timeout",
						      P_("Socket timeout"),
						      P_("The I/O timeout for sockets, or 0 for none"),
						      0, G_MAXUINT, 0,
						      G_PARAM_CONSTRUCT |
                                                      G_PARAM_READWRITE |
                                                      G_PARAM_STATIC_STRINGS));

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_socket_client_connect:
 * @client: a #GSocketClient.
 * @connectable: a #GSocketConnectable specifying the remote address.
 * @cancellable: optional #GCancellable object, %NULL to ignore.
 * @error: #GError for error reporting, or %NULL to ignore.
 *
 * Tries to resolve the @connectable and make a network connection to it..
 *
 * Upon a successful connection, a new #GSocketConnection is constructed
 * and returned.  The caller owns this new object and must drop their
 * reference to it when finished with it.
 *
 * The type of the #GSocketConnection object returned depends on the type of
 * the underlying socket that is used. For instance, for a TCP/IP connection
 * it will be a #GTcpConnection.
 *
 * The socket created will be the same family as the the address that the
 * @connectable resolves to, unless family is set with g_socket_client_set_family()
 * or indirectly via g_socket_client_set_local_address(). The socket type
 * defaults to %G_SOCKET_TYPE_STREAM but can be set with
 * g_socket_client_set_socket_type().
 *
 * If a local address is specified with g_socket_client_set_local_address() the
 * socket will be bound to this address before connecting.
 *
 * Returns: a #GSocketConnection on success, %NULL on error.
 *
 * Since: 2.22
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
GSocketConnection *
g_socket_client_connect (GSocketClient       *client,
			 GSocketConnectable  *connectable,
			 GCancellable        *cancellable,
			 GError             **error)
{
  GSocketConnection *connection = NULL;
  GSocketAddressEnumerator *enumerator;
  GError *last_error, *tmp_error;

  last_error = NULL;
  enumerator = g_socket_connectable_enumerate (connectable);
  while (connection == NULL)
    {
      GSocketAddress *address;
      GSocket *socket;

      if (g_cancellable_is_cancelled (cancellable))
	{
	  g_clear_error (error);
	  g_cancellable_set_error_if_cancelled (cancellable, error);
	  break;
	}

      tmp_error = NULL;
      address = g_socket_address_enumerator_next (enumerator, cancellable,
						  &tmp_error);
      if (address == NULL)
	{
	  if (tmp_error)
	    {
	      g_clear_error (&last_error);
	      g_propagate_error (error, tmp_error);
	    }
	  else if (last_error)
	    {
Benjamin Otte's avatar
Benjamin Otte committed
583
	      g_propagate_error (error, last_error);
584 585
	    }
	  else
Christian Persch's avatar
Christian Persch committed
586 587
            g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                                 _("Unknown error on connect"));
588 589 590 591 592 593 594 595 596
	  break;
	}

      /* clear error from previous attempt */
      g_clear_error (&last_error);

      socket = create_socket (client, address, &last_error);
      if (socket != NULL)
	{
Dan Winship's avatar
Dan Winship committed
597
	  if (g_socket_connect (socket, address, cancellable, &last_error))
598 599 600 601 602 603 604 605 606 607 608 609 610 611
	    connection = g_socket_connection_factory_create_connection (socket);

	  g_object_unref (socket);
	}

      g_object_unref (address);
    }
  g_object_unref (enumerator);

  return connection;
}

/**
 * g_socket_client_connect_to_host:
612
 * @client: a #SocketClient
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
 * @host_and_port: the name and optionally port of the host to connect to
 * @default_port: the default port to connect to
 * @cancellable: a #GCancellable, or %NULL
 * @error: a pointer to a #GError, or %NULL
 *
 * This is a helper function for g_socket_client_connect().
 *
 * Attempts to create a TCP connection to the named host.
 *
 * @host_and_port may be in any of a number of recognised formats: an IPv6
 * address, an IPv4 address, or a domain name (in which case a DNS
 * lookup is performed).  Quoting with [] is supported for all address
 * types.  A port override may be specified in the usual way with a
 * colon.  Ports may be given as decimal numbers or symbolic names (in
 * which case an /etc/services lookup is performed).
 *
 * If no port override is given in @host_and_port then @default_port will be
 * used as the port number to connect to.
 *
 * In general, @host_and_port is expected to be provided by the user (allowing
 * them to give the hostname, and a port overide if necessary) and
 * @default_port is expected to be provided by the application.
635
 *
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
 * In the case that an IP address is given, a single connection
 * attempt is made.  In the case that a name is given, multiple
 * connection attempts may be made, in turn and according to the
 * number of address records in DNS, until a connection succeeds.
 *
 * Upon a successful connection, a new #GSocketConnection is constructed
 * and returned.  The caller owns this new object and must drop their
 * reference to it when finished with it.
 *
 * In the event of any failure (DNS error, service not found, no hosts
 * connectable) %NULL is returned and @error (if non-%NULL) is set
 * accordingly.
 *
 Returns: a #GSocketConnection on success, %NULL on error.
 *
 * Since: 2.22
652
 */
653
GSocketConnection *
654 655
g_socket_client_connect_to_host (GSocketClient  *client,
				 const gchar    *host_and_port,
656
				 guint16         default_port,
657 658
				 GCancellable   *cancellable,
				 GError        **error)
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
{
  GSocketConnectable *connectable;
  GSocketConnection *connection;

  connectable = g_network_address_parse (host_and_port, default_port, error);
  if (connectable == NULL)
    return NULL;

  connection = g_socket_client_connect (client, connectable,
					cancellable, error);
  g_object_unref (connectable);

  return connection;
}

674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
/**
 * g_socket_client_connect_to_service:
 * @client: a #GSocketConnection
 * @domain: a domain name
 * @service: the name of the service to connect to
 * @cancellable: a #GCancellable, or %NULL
 * @error: a pointer to a #GError, or %NULL
 * @returns: a #GSocketConnection if successful, or %NULL on error
 *
 * Attempts to create a TCP connection to a service.
 *
 * This call looks up the SRV record for @service at @domain for the
 * "tcp" protocol.  It then attempts to connect, in turn, to each of
 * the hosts providing the service until either a connection succeeds
 * or there are no hosts remaining.
 *
 * Upon a successful connection, a new #GSocketConnection is constructed
 * and returned.  The caller owns this new object and must drop their
 * reference to it when finished with it.
 *
 * In the event of any failure (DNS error, service not found, no hosts
 * connectable) %NULL is returned and @error (if non-%NULL) is set
 * accordingly.
697
 */
698 699
GSocketConnection *
g_socket_client_connect_to_service (GSocketClient  *client,
700 701
				    const gchar    *domain,
				    const gchar    *service,
702 703 704 705 706 707 708 709 710 711 712 713 714 715
				    GCancellable   *cancellable,
				    GError        **error)
{
  GSocketConnectable *connectable;
  GSocketConnection *connection;

  connectable = g_network_service_new (service, "tcp", domain);
  connection = g_socket_client_connect (client, connectable,
					cancellable, error);
  g_object_unref (connectable);

  return connection;
}

716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
typedef struct
{
  GSimpleAsyncResult *result;
  GCancellable *cancellable;
  GSocketClient *client;

  GSocketAddressEnumerator *enumerator;
  GSocket *current_socket;

  GError *last_error;
} GSocketClientAsyncConnectData;

static void
g_socket_client_async_connect_complete (GSocketClientAsyncConnectData *data)
{
  GSocketConnection *connection;

  if (data->last_error)
    {
      g_simple_async_result_set_from_error (data->result, data->last_error);
      g_error_free (data->last_error);
    }
  else
    {
      g_assert (data->current_socket);

      g_socket_set_blocking (data->current_socket, TRUE);

      connection = g_socket_connection_factory_create_connection (data->current_socket);
745
      g_object_unref (data->current_socket);
746 747 748 749 750 751 752
      g_simple_async_result_set_op_res_gpointer (data->result,
						 connection,
						 g_object_unref);
    }

  g_simple_async_result_complete (data->result);
  g_object_unref (data->result);
753
  g_object_unref (data->enumerator);
Dan Winship's avatar
Dan Winship committed
754 755
  if (data->cancellable)
    g_object_unref (data->cancellable);
756
  g_slice_free (GSocketClientAsyncConnectData, data);
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791
}


static void
g_socket_client_enumerator_callback (GObject      *object,
				     GAsyncResult *result,
				     gpointer      user_data);

static void
set_last_error (GSocketClientAsyncConnectData *data,
		GError *error)
{
  g_clear_error (&data->last_error);
  data->last_error = error;
}

static gboolean
g_socket_client_socket_callback (GSocket *socket,
				 GIOCondition condition,
				 GSocketClientAsyncConnectData *data)
{
  GError *error = NULL;

  if (g_cancellable_is_cancelled (data->cancellable))
    {
      /* Cancelled, return done with last error being cancelled */
      g_clear_error (&data->last_error);
      g_object_unref (data->current_socket);
      data->current_socket = NULL;
      g_cancellable_set_error_if_cancelled (data->cancellable,
					    &data->last_error);
    }
  else
    {
      /* socket is ready for writing means connect done, did it succeed? */
792
      if (!g_socket_check_connect_result (data->current_socket, &error))
793 794
	{
	  set_last_error (data, error);
Dan Winship's avatar
Dan Winship committed
795 796
	  g_object_unref (data->current_socket);
	  data->current_socket = NULL;
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838

	  /* try next one */
	  g_socket_address_enumerator_next_async (data->enumerator,
						  data->cancellable,
						  g_socket_client_enumerator_callback,
						  data);

	  return FALSE;
	}
    }

  g_socket_client_async_connect_complete (data);

  return FALSE;
}

static void
g_socket_client_enumerator_callback (GObject      *object,
				     GAsyncResult *result,
				     gpointer      user_data)
{
  GSocketClientAsyncConnectData *data = user_data;
  GSocketAddress *address;
  GSocket *socket;
  GError *tmp_error = NULL;

  if (g_cancellable_is_cancelled (data->cancellable))
    {
      g_clear_error (&data->last_error);
      g_cancellable_set_error_if_cancelled (data->cancellable, &data->last_error);
      g_socket_client_async_connect_complete (data);
      return;
    }

  address = g_socket_address_enumerator_next_finish (data->enumerator,
						     result, &tmp_error);

  if (address == NULL)
    {
      if (tmp_error)
	set_last_error (data, tmp_error);
      else if (data->last_error == NULL)
Christian Persch's avatar
Christian Persch committed
839 840
        g_set_error_literal (&data->last_error, G_IO_ERROR, G_IO_ERROR_FAILED,
                             _("Unknown error on connect"));
841 842 843 844 845 846 847 848 849 850 851

      g_socket_client_async_connect_complete (data);
      return;
    }

  g_clear_error (&data->last_error);

  socket = create_socket (data->client, address, &data->last_error);
  if (socket != NULL)
    {
      g_socket_set_blocking (socket, FALSE);
Dan Winship's avatar
Dan Winship committed
852
      if (g_socket_connect (socket, address, data->cancellable, &tmp_error))
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
	{
	  data->current_socket = socket;
	  g_socket_client_async_connect_complete (data);

	  g_object_unref (address);
	  return;
	}
      else if (g_error_matches (tmp_error, G_IO_ERROR, G_IO_ERROR_PENDING))
	{
	  GSource *source;

	  data->current_socket = socket;
	  g_error_free (tmp_error);

	  source = g_socket_create_source (socket, G_IO_OUT,
					   data->cancellable);
	  g_source_set_callback (source,
				 (GSourceFunc) g_socket_client_socket_callback,
				 data, NULL);
872
	  g_source_attach (source, g_main_context_get_thread_default ());
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
	  g_source_unref (source);

	  g_object_unref (address);
	  return;
	}
      else
	{
	  data->last_error = tmp_error;
	  g_object_unref (socket);
	}
      g_object_unref (address);
    }

  g_socket_address_enumerator_next_async (data->enumerator,
					  data->cancellable,
					  g_socket_client_enumerator_callback,
					  data);
}

/**
893
 * g_socket_client_connect_async:
894 895 896 897 898 899 900 901 902 903 904 905 906
 * @client: a #GTcpClient
 * @connectable: a #GSocketConnectable specifying the remote address.
 * @cancellable: a #GCancellable, or %NULL
 * @callback: a #GAsyncReadyCallback
 * @user_data: user data for the callback
 *
 * This is the asynchronous version of g_socket_client_connect().
 *
 * When the operation is finished @callback will be
 * called. You can then call g_socket_client_connect_finish() to get
 * the result of the operation.
 *
 * Since: 2.22
907
 */
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
void
g_socket_client_connect_async (GSocketClient       *client,
			       GSocketConnectable  *connectable,
			       GCancellable        *cancellable,
			       GAsyncReadyCallback  callback,
			       gpointer             user_data)
{
  GSocketClientAsyncConnectData *data;

  g_return_if_fail (G_IS_SOCKET_CLIENT (client));

  data = g_slice_new (GSocketClientAsyncConnectData);

  data->result = g_simple_async_result_new (G_OBJECT (client),
					    callback, user_data,
					    g_socket_client_connect_async);
  data->client = client;
  if (cancellable)
    data->cancellable = g_object_ref (cancellable);
  else
    data->cancellable = NULL;
  data->last_error = NULL;
  data->enumerator = g_socket_connectable_enumerate (connectable);

  g_socket_address_enumerator_next_async (data->enumerator, cancellable,
					  g_socket_client_enumerator_callback,
					  data);
}

/**
 * g_socket_client_connect_to_host_async:
 * @client: a #GTcpClient
 * @host_and_port: the name and optionally the port of the host to connect to
 * @default_port: the default port to connect to
 * @cancellable: a #GCancellable, or %NULL
 * @callback: a #GAsyncReadyCallback
 * @user_data: user data for the callback
 *
 * This is the asynchronous version of g_socket_client_connect_to_host().
 *
 * When the operation is finished @callback will be
 * called. You can then call g_socket_client_connect_to_host_finish() to get
 * the result of the operation.
 *
 * Since: 2.22
953
 */
954 955
void
g_socket_client_connect_to_host_async (GSocketClient        *client,
956
				       const gchar          *host_and_port,
957
				       guint16               default_port,
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
				       GCancellable         *cancellable,
				       GAsyncReadyCallback   callback,
				       gpointer              user_data)
{
  GSocketConnectable *connectable;
  GError *error;

  error = NULL;
  connectable = g_network_address_parse (host_and_port, default_port,
					 &error);
  if (connectable == NULL)
    {
      g_simple_async_report_gerror_in_idle (G_OBJECT (client),
					    callback, user_data, error);
      g_error_free (error);
    }
  else
    {
      g_socket_client_connect_async (client,
				     connectable, cancellable,
				     callback, user_data);
      g_object_unref (connectable);
    }
}

983 984 985 986 987 988 989 990 991 992 993
/**
 * g_socket_client_connect_to_service_async:
 * @client: a #GSocketClient
 * @domain: a domain name
 * @service: the name of the service to connect to
 * @cancellable: a #GCancellable, or %NULL
 * @callback: a #GAsyncReadyCallback
 * @user_data: user data for the callback
 *
 * This is the asynchronous version of
 * g_socket_client_connect_to_service().
994 995 996
 *
 * Since: 2.22
 */
997 998
void
g_socket_client_connect_to_service_async (GSocketClient       *client,
999 1000
					  const gchar         *domain,
					  const gchar         *service,
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
					  GCancellable        *cancellable,
					  GAsyncReadyCallback  callback,
					  gpointer             user_data)
{
  GSocketConnectable *connectable;

  connectable = g_network_service_new (service, "tcp", domain);
  g_socket_client_connect_async (client,
				 connectable, cancellable,
				 callback, user_data);
  g_object_unref (connectable);
}

1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
/**
 * g_socket_client_connect_finish:
 * @client: a #GSocketClient.
 * @result: a #GAsyncResult.
 * @error: a #GError location to store the error occuring, or %NULL to
 * ignore.
 *
 * Finishes an async connect operation. See g_socket_client_connect_async()
 *
 * Returns: a #GSocketConnection on success, %NULL on error.
 *
 * Since: 2.22
1026
 */
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
GSocketConnection *
g_socket_client_connect_finish (GSocketClient  *client,
				GAsyncResult   *result,
				GError        **error)
{
  GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);

  if (g_simple_async_result_propagate_error (simple, error))
    return NULL;

  return g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
}

/**
 * g_socket_client_connect_to_host_finish:
 * @client: a #GSocketClient.
 * @result: a #GAsyncResult.
 * @error: a #GError location to store the error occuring, or %NULL to
 * ignore.
 *
 * Finishes an async connect operation. See g_socket_client_connect_to_host_async()
 *
 * Returns: a #GSocketConnection on success, %NULL on error.
 *
 * Since: 2.22
1052
 */
1053
GSocketConnection *
1054 1055 1056
g_socket_client_connect_to_host_finish (GSocketClient  *client,
					GAsyncResult   *result,
					GError        **error)
1057 1058 1059 1060
{
  return g_socket_client_connect_finish (client, result, error);
}

1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
/**
 * g_socket_client_connect_to_service_finish:
 * @client: a #GSocketClient.
 * @result: a #GAsyncResult.
 * @error: a #GError location to store the error occuring, or %NULL to
 * ignore.
 *
 * Finishes an async connect operation. See g_socket_client_connect_to_service_async()
 *
 * Returns: a #GSocketConnection on success, %NULL on error.
 *
 * Since: 2.22
1073
 */
1074
GSocketConnection *
1075 1076 1077
g_socket_client_connect_to_service_finish (GSocketClient  *client,
					   GAsyncResult   *result,
					   GError        **error)
1078 1079 1080
{
  return g_socket_client_connect_finish (client, result, error);
}