gsocketclient.c 60.5 KB
Newer Older
1 2 3 4
/*  GIO - GLib Input, Output and Streaming Library
 *
 * Copyright © 2008, 2009 codethink
 * Copyright © 2009 Red Hat, Inc
5
 * Copyright © 2018 Igalia S.L.
6 7 8 9
 *
 * 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
10
 * version 2.1 of the License, or (at your option) any later version.
11 12 13 14 15 16 17
 *
 * 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
18
 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
19 20 21 22 23 24 25 26 27
 *
 * Authors: Ryan Lortie <desrt@desrt.ca>
 *          Alexander Larsson <alexl@redhat.com>
 */

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

#include <stdlib.h>
28
#include <string.h>
29 30 31 32 33

#include <gio/gioenumtypes.h>
#include <gio/gsocketaddressenumerator.h>
#include <gio/gsocketconnectable.h>
#include <gio/gsocketconnection.h>
34
#include <gio/gioprivate.h>
35 36
#include <gio/gproxyaddressenumerator.h>
#include <gio/gproxyaddress.h>
37
#include <gio/gtask.h>
38 39 40 41
#include <gio/gcancellable.h>
#include <gio/gioerror.h>
#include <gio/gsocket.h>
#include <gio/gnetworkaddress.h>
42
#include <gio/gnetworkservice.h>
43
#include <gio/gproxy.h>
44
#include <gio/gproxyresolver.h>
45
#include <gio/gsocketaddress.h>
46
#include <gio/gtcpconnection.h>
47
#include <gio/gtcpwrapperconnection.h>
48 49
#include <gio/gtlscertificate.h>
#include <gio/gtlsclientconnection.h>
50
#include <gio/ginetaddress.h>
51 52
#include "glibintl.h"

53 54 55 56
/* As recommended by RFC 8305 this is the time it waits
 * on a connection before starting another concurrent attempt.
 */
#define HAPPY_EYEBALLS_CONNECTION_ATTEMPT_TIMEOUT_MS 250
57 58 59

/**
 * SECTION:gsocketclient
60
 * @short_description: Helper for connecting to a network service
61 62 63
 * @include: gio/gio.h
 * @see_also: #GSocketConnection, #GSocketListener
 *
64 65
 * #GSocketClient is a lightweight high-level utility class for connecting to
 * a network host using a connection oriented socket type.
66
 *
67
 * You create a #GSocketClient object, set any options you want, and then
68 69 70 71 72 73 74
 * 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.
 *
75 76 77
 * As #GSocketClient is a lightweight object, you don't need to cache it. You
 * can just create a new one any time you need one.
 *
78
 * Since: 2.22
79
 */
80 81


82 83 84 85 86 87 88 89
enum
{
  EVENT,
  LAST_SIGNAL
};

static guint signals[LAST_SIGNAL] = { 0 };

90 91 92 93 94 95
enum
{
  PROP_NONE,
  PROP_FAMILY,
  PROP_TYPE,
  PROP_PROTOCOL,
96
  PROP_LOCAL_ADDRESS,
97 98
  PROP_TIMEOUT,
  PROP_ENABLE_PROXY,
99
  PROP_TLS,
100 101
  PROP_TLS_VALIDATION_FLAGS,
  PROP_PROXY_RESOLVER
102 103 104 105 106 107
};

struct _GSocketClientPrivate
{
  GSocketFamily family;
  GSocketType type;
108
  GSocketProtocol protocol;
109
  GSocketAddress *local_address;
110
  guint timeout;
111
  gboolean enable_proxy;
112
  GHashTable *app_proxies;
113 114
  gboolean tls;
  GTlsCertificateFlags tls_validation_flags;
115
  GProxyResolver *proxy_resolver;
116 117
};

118 119
G_DEFINE_TYPE_WITH_PRIVATE (GSocketClient, g_socket_client, G_TYPE_OBJECT)

120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
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,
137
			 client->priv->protocol,
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
			 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;
	}
    }

154 155 156
  if (client->priv->timeout)
    g_socket_set_timeout (socket, client->priv->timeout);

157 158 159
  return socket;
}

Allison Karlitskaya's avatar
Allison Karlitskaya committed
160
static gboolean
161 162 163 164 165 166 167 168
can_use_proxy (GSocketClient *client)
{
  GSocketClientPrivate *priv = client->priv;

  return priv->enable_proxy
          && priv->type == G_SOCKET_TYPE_STREAM;
}

169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
static void
clarify_connect_error (GError             *error,
		       GSocketConnectable *connectable,
		       GSocketAddress     *address)
{
  const char *name;
  char *tmp_name = NULL;

  if (G_IS_PROXY_ADDRESS (address))
    {
      name = tmp_name = g_inet_address_to_string (g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (address)));

      g_prefix_error (&error, _("Could not connect to proxy server %s: "), name);
    }
  else
    {
      if (G_IS_NETWORK_ADDRESS (connectable))
	name = g_network_address_get_hostname (G_NETWORK_ADDRESS (connectable));
      else if (G_IS_NETWORK_SERVICE (connectable))
	name = g_network_service_get_domain (G_NETWORK_SERVICE (connectable));
      else if (G_IS_INET_SOCKET_ADDRESS (connectable))
	name = tmp_name = g_inet_address_to_string (g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (connectable)));
      else
	name = NULL;

      if (name)
	g_prefix_error (&error, _("Could not connect to %s: "), name);
      else
	g_prefix_error (&error, _("Could not connect: "));
    }

  g_free (tmp_name);
}

203 204 205
static void
g_socket_client_init (GSocketClient *client)
{
206
  client->priv = g_socket_client_get_instance_private (client);
207
  client->priv->type = G_SOCKET_TYPE_STREAM;
208 209 210 211
  client->priv->app_proxies = g_hash_table_new_full (g_str_hash,
						     g_str_equal,
						     g_free,
						     NULL);
212 213 214 215 216 217 218 219 220 221 222
}

/**
 * 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
223
 */
224 225 226 227 228 229 230 231 232 233 234
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);

235 236
  g_clear_object (&client->priv->local_address);
  g_clear_object (&client->priv->proxy_resolver);
237

238
  G_OBJECT_CLASS (g_socket_client_parent_class)->finalize (object);
239 240

  g_hash_table_unref (client->priv->app_proxies);
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
}

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:
262
	g_value_set_enum (value, client->priv->protocol);
263 264 265 266 267 268
	break;

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

269 270 271 272
      case PROP_TIMEOUT:
	g_value_set_uint (value, client->priv->timeout);
	break;

273 274 275 276
      case PROP_ENABLE_PROXY:
	g_value_set_boolean (value, client->priv->enable_proxy);
	break;

277 278 279 280 281 282 283 284
      case PROP_TLS:
	g_value_set_boolean (value, g_socket_client_get_tls (client));
	break;

      case PROP_TLS_VALIDATION_FLAGS:
	g_value_set_flags (value, g_socket_client_get_tls_validation_flags (client));
	break;

285 286 287 288
      case PROP_PROXY_RESOLVER:
	g_value_set_object (value, g_socket_client_get_proxy_resolver (client));
	break;

289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
      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:
313
      g_socket_client_set_protocol (client, g_value_get_enum (value));
314 315 316 317 318 319
      break;

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

320 321 322 323
    case PROP_TIMEOUT:
      g_socket_client_set_timeout (client, g_value_get_uint (value));
      break;

324 325 326 327
    case PROP_ENABLE_PROXY:
      g_socket_client_set_enable_proxy (client, g_value_get_boolean (value));
      break;

328 329 330 331 332 333 334 335
    case PROP_TLS:
      g_socket_client_set_tls (client, g_value_get_boolean (value));
      break;

    case PROP_TLS_VALIDATION_FLAGS:
      g_socket_client_set_tls_validation_flags (client, g_value_get_flags (value));
      break;

336 337 338 339
    case PROP_PROXY_RESOLVER:
      g_socket_client_set_proxy_resolver (client, g_value_get_object (value));
      break;

340 341 342 343 344 345 346
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
    }
}

/**
 * g_socket_client_get_family:
347
 * @client: a #GSocketClient.
348 349 350 351 352 353 354 355
 *
 * Gets the socket family of the socket client.
 *
 * See g_socket_client_set_family() for details.
 *
 * Returns: a #GSocketFamily
 *
 * Since: 2.22
356
 */
357 358 359 360 361 362 363 364
GSocketFamily
g_socket_client_get_family (GSocketClient *client)
{
  return client->priv->family;
}

/**
 * g_socket_client_set_family:
365
 * @client: a #GSocketClient.
366 367 368 369 370 371 372 373 374 375 376 377
 * @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
378
 */
379 380
void
g_socket_client_set_family (GSocketClient *client,
381
			    GSocketFamily  family)
382 383 384 385 386 387 388 389 390 391
{
  if (client->priv->family == family)
    return;

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

/**
 * g_socket_client_get_socket_type:
392
 * @client: a #GSocketClient.
393 394 395 396 397 398 399 400
 *
 * Gets the socket type of the socket client.
 *
 * See g_socket_client_set_socket_type() for details.
 *
 * Returns: a #GSocketFamily
 *
 * Since: 2.22
401
 */
402 403 404 405 406 407 408 409
GSocketType
g_socket_client_get_socket_type (GSocketClient *client)
{
  return client->priv->type;
}

/**
 * g_socket_client_set_socket_type:
410
 * @client: a #GSocketClient.
411 412 413 414 415 416 417 418 419 420
 * @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
421
 */
422 423
void
g_socket_client_set_socket_type (GSocketClient *client,
424
				 GSocketType    type)
425 426 427 428 429 430 431 432 433 434
{
  if (client->priv->type == type)
    return;

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

/**
 * g_socket_client_get_protocol:
435
 * @client: a #GSocketClient
436 437 438 439 440
 *
 * Gets the protocol name type of the socket client.
 *
 * See g_socket_client_set_protocol() for details.
 *
441
 * Returns: a #GSocketProtocol
442 443
 *
 * Since: 2.22
444
 */
445
GSocketProtocol
446 447 448 449 450 451 452
g_socket_client_get_protocol (GSocketClient *client)
{
  return client->priv->protocol;
}

/**
 * g_socket_client_set_protocol:
453
 * @client: a #GSocketClient.
454
 * @protocol: a #GSocketProtocol
455 456 457 458 459
 *
 * Sets the protocol of the socket client.
 * The sockets created by this object will use of the specified
 * protocol.
 *
460
 * If @protocol is %0 that means to use the default
461 462 463
 * protocol for the socket family and type.
 *
 * Since: 2.22
464
 */
465
void
466 467
g_socket_client_set_protocol (GSocketClient   *client,
			      GSocketProtocol  protocol)
468
{
469
  if (client->priv->protocol == protocol)
470 471
    return;

472
  client->priv->protocol = protocol;
473 474 475 476 477
  g_object_notify (G_OBJECT (client), "protocol");
}

/**
 * g_socket_client_get_local_address:
478
 * @client: a #GSocketClient.
479 480 481 482 483
 *
 * Gets the local address of the socket client.
 *
 * See g_socket_client_set_local_address() for details.
 *
Matthias Clasen's avatar
Matthias Clasen committed
484
 * Returns: (transfer none): a #GSocketAddress or %NULL. Do not free.
485 486
 *
 * Since: 2.22
487
 */
488 489 490 491 492 493 494 495
GSocketAddress *
g_socket_client_get_local_address (GSocketClient *client)
{
  return client->priv->local_address;
}

/**
 * g_socket_client_set_local_address:
496
 * @client: a #GSocketClient.
497
 * @address: (nullable): a #GSocketAddress, or %NULL
498 499 500 501 502
 *
 * 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.
 *
503
 * This is useful if you want to ensure that the local
504 505 506 507
 * side of the connection is on a specific port, or on
 * a specific interface.
 *
 * Since: 2.22
508
 */
509
void
510 511
g_socket_client_set_local_address (GSocketClient  *client,
				   GSocketAddress *address)
512 513
{
  if (address)
514
    g_object_ref (address);
515 516 517 518 519 520 521 522 523

  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");
}

524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
/**
 * 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");
}

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
/**
 * g_socket_client_get_enable_proxy:
 * @client: a #GSocketClient.
 *
 * Gets the proxy enable state; see g_socket_client_set_enable_proxy()
 *
 * Returns: whether proxying is enabled
 *
 * Since: 2.26
 */
gboolean
g_socket_client_get_enable_proxy (GSocketClient *client)
{
  return client->priv->enable_proxy;
}

/**
 * g_socket_client_set_enable_proxy:
 * @client: a #GSocketClient.
 * @enable: whether to enable proxies
 *
 * Sets whether or not @client attempts to make connections via a
 * proxy server. When enabled (the default), #GSocketClient will use a
 * #GProxyResolver to determine if a proxy protocol such as SOCKS is
 * needed, and automatically do the necessary proxy negotiation.
 *
594 595
 * See also g_socket_client_set_proxy_resolver().
 *
596 597 598 599 600 601 602 603 604 605 606 607 608 609
 * Since: 2.26
 */
void
g_socket_client_set_enable_proxy (GSocketClient *client,
				  gboolean       enable)
{
  enable = !!enable;
  if (client->priv->enable_proxy == enable)
    return;

  client->priv->enable_proxy = enable;
  g_object_notify (G_OBJECT (client), "enable-proxy");
}

610 611 612 613 614 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
/**
 * g_socket_client_get_tls:
 * @client: a #GSocketClient.
 *
 * Gets whether @client creates TLS connections. See
 * g_socket_client_set_tls() for details.
 *
 * Returns: whether @client uses TLS
 *
 * Since: 2.28
 */
gboolean
g_socket_client_get_tls (GSocketClient *client)
{
  return client->priv->tls;
}

/**
 * g_socket_client_set_tls:
 * @client: a #GSocketClient.
 * @tls: whether to use TLS
 *
 * Sets whether @client creates TLS (aka SSL) connections. If @tls is
 * %TRUE, @client will wrap its connections in a #GTlsClientConnection
 * and perform a TLS handshake when connecting.
 *
 * Note that since #GSocketClient must return a #GSocketConnection,
 * but #GTlsClientConnection is not a #GSocketConnection, this
 * actually wraps the resulting #GTlsClientConnection in a
 * #GTcpWrapperConnection when returning it. You can use
 * g_tcp_wrapper_connection_get_base_io_stream() on the return value
 * to extract the #GTlsClientConnection.
 *
643 644 645 646 647 648 649 650
 * If you need to modify the behavior of the TLS handshake (eg, by
 * setting a client-side certificate to use, or connecting to the
 * #GTlsConnection::accept-certificate signal), you can connect to
 * @client's #GSocketClient::event signal and wait for it to be
 * emitted with %G_SOCKET_CLIENT_TLS_HANDSHAKING, which will give you
 * a chance to see the #GTlsClientConnection before the handshake
 * starts.
 *
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 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
 * Since: 2.28
 */
void
g_socket_client_set_tls (GSocketClient *client,
			 gboolean       tls)
{
  tls = !!tls;
  if (tls == client->priv->tls)
    return;

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

/**
 * g_socket_client_get_tls_validation_flags:
 * @client: a #GSocketClient.
 *
 * Gets the TLS validation flags used creating TLS connections via
 * @client.
 *
 * Returns: the TLS validation flags
 *
 * Since: 2.28
 */
GTlsCertificateFlags
g_socket_client_get_tls_validation_flags (GSocketClient *client)
{
  return client->priv->tls_validation_flags;
}

/**
 * g_socket_client_set_tls_validation_flags:
 * @client: a #GSocketClient.
 * @flags: the validation flags
 *
 * Sets the TLS validation flags used when creating TLS connections
 * via @client. The default value is %G_TLS_CERTIFICATE_VALIDATE_ALL.
 *
 * Since: 2.28
 */
void
g_socket_client_set_tls_validation_flags (GSocketClient        *client,
					  GTlsCertificateFlags  flags)
{
  if (client->priv->tls_validation_flags != flags)
    {
      client->priv->tls_validation_flags = flags;
      g_object_notify (G_OBJECT (client), "tls-validation-flags");
    }
}

703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
/**
 * g_socket_client_get_proxy_resolver:
 * @client: a #GSocketClient.
 *
 * Gets the #GProxyResolver being used by @client. Normally, this will
 * be the resolver returned by g_proxy_resolver_get_default(), but you
 * can override it with g_socket_client_set_proxy_resolver().
 *
 * Returns: (transfer none): The #GProxyResolver being used by
 *   @client.
 *
 * Since: 2.36
 */
GProxyResolver *
g_socket_client_get_proxy_resolver (GSocketClient *client)
{
  if (client->priv->proxy_resolver)
    return client->priv->proxy_resolver;
  else
    return g_proxy_resolver_get_default ();
}

/**
 * g_socket_client_set_proxy_resolver:
 * @client: a #GSocketClient.
728
 * @proxy_resolver: (nullable): a #GProxyResolver, or %NULL for the
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
 *   default.
 *
 * Overrides the #GProxyResolver used by @client. You can call this if
 * you want to use specific proxies, rather than using the system
 * default proxy settings.
 *
 * Note that whether or not the proxy resolver is actually used
 * depends on the setting of #GSocketClient:enable-proxy, which is not
 * changed by this function (but which is %TRUE by default)
 *
 * Since: 2.36
 */
void
g_socket_client_set_proxy_resolver (GSocketClient  *client,
                                    GProxyResolver *proxy_resolver)
{
  /* We have to be careful to avoid calling
   * g_proxy_resolver_get_default() until we're sure we need it,
   * because trying to load the default proxy resolver module will
   * break some test programs that aren't expecting it (eg,
   * tests/gsettings).
   */

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

  client->priv->proxy_resolver = proxy_resolver;

  if (client->priv->proxy_resolver)
    g_object_ref (client->priv->proxy_resolver);
}

761 762 763 764 765 766 767 768 769
static void
g_socket_client_class_init (GSocketClientClass *class)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (class);

  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;

770 771 772 773 774
  /**
   * GSocketClient::event:
   * @client: the #GSocketClient
   * @event: the event that is occurring
   * @connectable: the #GSocketConnectable that @event is occurring on
775
   * @connection: (nullable): the current representation of the connection
776 777 778 779 780 781
   *
   * Emitted when @client's activity on @connectable changes state.
   * Among other things, this can be used to provide progress
   * information about a network connection in the UI. The meanings of
   * the different @event values are as follows:
   *
782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
   * - %G_SOCKET_CLIENT_RESOLVING: @client is about to look up @connectable
   *   in DNS. @connection will be %NULL.
   *
   * - %G_SOCKET_CLIENT_RESOLVED:  @client has successfully resolved
   *   @connectable in DNS. @connection will be %NULL.
   *
   * - %G_SOCKET_CLIENT_CONNECTING: @client is about to make a connection
   *   to a remote host; either a proxy server or the destination server
   *   itself. @connection is the #GSocketConnection, which is not yet
   *   connected.  Since GLib 2.40, you can access the remote
   *   address via g_socket_connection_get_remote_address().
   *
   * - %G_SOCKET_CLIENT_CONNECTED: @client has successfully connected
   *   to a remote host. @connection is the connected #GSocketConnection.
   *
   * - %G_SOCKET_CLIENT_PROXY_NEGOTIATING: @client is about to negotiate
   *   with a proxy to get it to connect to @connectable. @connection is
   *   the #GSocketConnection to the proxy server.
   *
   * - %G_SOCKET_CLIENT_PROXY_NEGOTIATED: @client has negotiated a
   *   connection to @connectable through a proxy server. @connection is
   *   the stream returned from g_proxy_connect(), which may or may not
   *   be a #GSocketConnection.
   *
   * - %G_SOCKET_CLIENT_TLS_HANDSHAKING: @client is about to begin a TLS
   *   handshake. @connection is a #GTlsClientConnection.
   *
   * - %G_SOCKET_CLIENT_TLS_HANDSHAKED: @client has successfully completed
   *   the TLS handshake. @connection is a #GTlsClientConnection.
   *
   * - %G_SOCKET_CLIENT_COMPLETE: @client has either successfully connected
   *   to @connectable (in which case @connection is the #GSocketConnection
   *   that it will be returning to the caller) or has failed (in which
   *   case @connection is %NULL and the client is about to return an error).
816 817 818 819
   *
   * Each event except %G_SOCKET_CLIENT_COMPLETE may be emitted
   * multiple times (or not at all) for a given connectable (in
   * particular, if @client ends up attempting to connect to more than
820
   * one address). However, if @client emits the #GSocketClient::event
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
   * signal at all for a given connectable, that it will always emit
   * it with %G_SOCKET_CLIENT_COMPLETE when it is done.
   *
   * Note that there may be additional #GSocketClientEvent values in
   * the future; unrecognized @event values should be ignored.
   *
   * Since: 2.32
   */
  signals[EVENT] =
    g_signal_new (I_("event"),
		  G_TYPE_FROM_CLASS (gobject_class),
		  G_SIGNAL_RUN_LAST,
		  G_STRUCT_OFFSET (GSocketClientClass, event),
		  NULL, NULL,
		  NULL,
		  G_TYPE_NONE, 3,
		  G_TYPE_SOCKET_CLIENT_EVENT,
		  G_TYPE_SOCKET_CONNECTABLE,
		  G_TYPE_IO_STREAM);

841 842 843 844 845 846
  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,
847 848 849
						      G_PARAM_CONSTRUCT |
                                                      G_PARAM_READWRITE |
                                                      G_PARAM_STATIC_STRINGS));
850 851 852 853 854 855 856

  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,
857 858 859
						      G_PARAM_CONSTRUCT |
                                                      G_PARAM_READWRITE |
                                                      G_PARAM_STATIC_STRINGS));
860 861

  g_object_class_install_property (gobject_class, PROP_PROTOCOL,
862 863 864 865 866
				   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,
867 868 869
						      G_PARAM_CONSTRUCT |
                                                      G_PARAM_READWRITE |
                                                      G_PARAM_STATIC_STRINGS));
870 871 872 873 874 875

  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,
876 877 878
							G_PARAM_CONSTRUCT |
                                                        G_PARAM_READWRITE |
                                                        G_PARAM_STATIC_STRINGS));
879 880 881 882 883 884 885 886 887 888

  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));

889 890 891 892 893 894 895 896 897
   g_object_class_install_property (gobject_class, PROP_ENABLE_PROXY,
				    g_param_spec_boolean ("enable-proxy",
							  P_("Enable proxy"),
							  P_("Enable proxy support"),
							  TRUE,
							  G_PARAM_CONSTRUCT |
							  G_PARAM_READWRITE |
							  G_PARAM_STATIC_STRINGS));

898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
  g_object_class_install_property (gobject_class, PROP_TLS,
				   g_param_spec_boolean ("tls",
							 P_("TLS"),
							 P_("Whether to create TLS connections"),
							 FALSE,
							 G_PARAM_CONSTRUCT |
							 G_PARAM_READWRITE |
							 G_PARAM_STATIC_STRINGS));
  g_object_class_install_property (gobject_class, PROP_TLS_VALIDATION_FLAGS,
				   g_param_spec_flags ("tls-validation-flags",
						       P_("TLS validation flags"),
						       P_("TLS validation flags to use"),
						       G_TYPE_TLS_CERTIFICATE_FLAGS,
						       G_TLS_CERTIFICATE_VALIDATE_ALL,
						       G_PARAM_CONSTRUCT |
						       G_PARAM_READWRITE |
						       G_PARAM_STATIC_STRINGS));
915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930

  /**
   * GSocketClient:proxy-resolver:
   *
   * The proxy resolver to use
   *
   * Since: 2.36
   */
  g_object_class_install_property (gobject_class, PROP_PROXY_RESOLVER,
                                   g_param_spec_object ("proxy-resolver",
                                                        P_("Proxy resolver"),
                                                        P_("The proxy resolver to use"),
                                                        G_TYPE_PROXY_RESOLVER,
                                                        G_PARAM_CONSTRUCT |
                                                        G_PARAM_READWRITE |
                                                        G_PARAM_STATIC_STRINGS));
931 932
}

933 934 935 936 937 938 939 940 941 942
static void
g_socket_client_emit_event (GSocketClient       *client,
			    GSocketClientEvent  event,
			    GSocketConnectable  *connectable,
			    GIOStream           *connection)
{
  g_signal_emit (client, signals[EVENT], 0,
		 event, connectable, connection);
}

943 944 945 946
/**
 * g_socket_client_connect:
 * @client: a #GSocketClient.
 * @connectable: a #GSocketConnectable specifying the remote address.
947
 * @cancellable: (nullable): optional #GCancellable object, %NULL to ignore.
948 949
 * @error: #GError for error reporting, or %NULL to ignore.
 *
950
 * Tries to resolve the @connectable and make a network connection to it.
951 952 953 954 955 956 957 958 959
 *
 * 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.
 *
960
 * The socket created will be the same family as the address that the
961 962 963 964 965 966 967 968
 * @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.
 *
969
 * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
970 971
 *
 * Since: 2.22
972
 */
973 974 975 976 977 978
GSocketConnection *
g_socket_client_connect (GSocketClient       *client,
			 GSocketConnectable  *connectable,
			 GCancellable        *cancellable,
			 GError             **error)
{
979
  GIOStream *connection = NULL;
980
  GSocketAddressEnumerator *enumerator = NULL;
981 982 983
  GError *last_error, *tmp_error;

  last_error = NULL;
984 985

  if (can_use_proxy (client))
986 987 988 989 990
    {
      enumerator = g_socket_connectable_proxy_enumerate (connectable);
      if (client->priv->proxy_resolver &&
          G_IS_PROXY_ADDRESS_ENUMERATOR (enumerator))
        {
991 992 993
          g_object_set (G_OBJECT (enumerator),
                        "proxy-resolver", client->priv->proxy_resolver,
                        NULL);
994 995
        }
    }
996 997 998
  else
    enumerator = g_socket_connectable_enumerate (connectable);

999 1000
  while (connection == NULL)
    {
1001
      GSocketAddress *address = NULL;
1002
      gboolean application_proxy = FALSE;
1003
      GSocket *socket;
1004
      gboolean using_proxy;
1005 1006 1007 1008 1009 1010 1011 1012 1013

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

      tmp_error = NULL;
1014 1015
      g_socket_client_emit_event (client, G_SOCKET_CLIENT_RESOLVING,
				  connectable, NULL);
1016
      address = g_socket_address_enumerator_next (enumerator, cancellable,
1017 1018
	      					  &tmp_error);

1019 1020 1021 1022 1023 1024 1025 1026 1027
      if (address == NULL)
	{
	  if (tmp_error)
	    {
	      g_clear_error (&last_error);
	      g_propagate_error (error, tmp_error);
	    }
	  else if (last_error)
	    {
1028
	      g_propagate_error (error, last_error);
1029 1030
	    }
	  else
1031 1032
            g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                                 _("Unknown error on connect"));
1033 1034
	  break;
	}
1035 1036 1037 1038 1039
      g_socket_client_emit_event (client, G_SOCKET_CLIENT_RESOLVED,
				  connectable, NULL);

      using_proxy = (G_IS_PROXY_ADDRESS (address) &&
		     client->priv->enable_proxy);
1040 1041 1042 1043 1044

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

      socket = create_socket (client, address, &last_error);
1045
      if (socket == NULL)
1046
	{
1047 1048
	  g_object_unref (address);
	  continue;
1049 1050
	}

1051
      connection = (GIOStream *)g_socket_connection_factory_create_connection (socket);
1052
      g_socket_connection_set_cached_remote_address ((GSocketConnection*)connection, address);
1053 1054 1055 1056 1057
      g_socket_client_emit_event (client, G_SOCKET_CLIENT_CONNECTING, connectable, connection);

      if (g_socket_connection_connect (G_SOCKET_CONNECTION (connection),
				       address, cancellable, &last_error))
	{
1058
          g_socket_connection_set_cached_remote_address ((GSocketConnection*)connection, NULL);
1059 1060 1061
	  g_socket_client_emit_event (client, G_SOCKET_CLIENT_CONNECTED, connectable, connection);
	}
      else
1062 1063 1064 1065 1066
	{
	  clarify_connect_error (last_error, connectable, address);
	  g_object_unref (connection);
	  connection = NULL;
	}
1067

1068
      if (connection && using_proxy)
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
	{
	  GProxyAddress *proxy_addr = G_PROXY_ADDRESS (address);
	  const gchar *protocol;
	  GProxy *proxy;

	  protocol = g_proxy_address_get_protocol (proxy_addr);

          /* The connection should not be anything else then TCP Connection,
           * but let's put a safety guard in case
	   */
          if (!G_IS_TCP_CONNECTION (connection))
            {
              g_critical ("Trying to proxy over non-TCP connection, this is "
                          "most likely a bug in GLib IO library.");

              g_set_error_literal (&last_error,
                  G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1086
                  _("Proxying over a non-TCP connection is not supported."));
1087 1088 1089 1090

	      g_object_unref (connection);
	      connection = NULL;
            }
1091 1092 1093 1094 1095
	  else if (g_hash_table_contains (client->priv->app_proxies, protocol))
	    {
	      application_proxy = TRUE;
	    }
          else if ((proxy = g_proxy_get_default_for_protocol (protocol)))
1096
	    {
1097
	      GIOStream *proxy_connection;
1098

1099
	      g_socket_client_emit_event (client, G_SOCKET_CLIENT_PROXY_NEGOTIATING, connectable, connection);
1100 1101 1102 1103 1104
	      proxy_connection = g_proxy_connect (proxy,
						  connection,
						  proxy_addr,
						  cancellable,
						  &last_error);
1105
	      g_object_unref (connection);
1106
	      connection = proxy_connection;
1107
	      g_object_unref (proxy);
1108 1109 1110

	      if (connection)
		g_socket_client_emit_event (client, G_SOCKET_CLIENT_PROXY_NEGOTIATED, connectable, connection);
1111
	    }
1112
	  else
1113 1114
	    {
	      g_set_error (&last_error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1115
			   _("Proxy protocol “%s” is not supported."),
1116 1117 1118 1119 1120 1121
			   protocol);
	      g_object_unref (connection);
	      connection = NULL;
	    }
	}

1122
      if (!application_proxy && connection && client->priv->tls)
1123
	{
1124
	  GIOStream *tlsconn;
1125 1126 1127

	  tlsconn = g_tls_client_connection_new (connection, connectable, &last_error);
	  g_object_unref (connection);
1128
	  connection = tlsconn;
1129 1130 1131

	  if (tlsconn)
	    {
1132 1133
	      g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (tlsconn),
                                                            client->priv->tls_validation_flags);
1134 1135 1136 1137 1138 1139 1140
	      g_socket_client_emit_event (client, G_SOCKET_CLIENT_TLS_HANDSHAKING, connectable, connection);
	      if (g_tls_connection_handshake (G_TLS_CONNECTION (tlsconn),
					      cancellable, &last_error))
		{
		  g_socket_client_emit_event (client, G_SOCKET_CLIENT_TLS_HANDSHAKED, connectable, connection);
		}
	      else
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
		{
		  g_object_unref (tlsconn);
		  connection = NULL;
		}
	    }
	}

      if (connection && !G_IS_SOCKET_CONNECTION (connection))
	{
	  GSocketConnection *wrapper_connection;

	  wrapper_connection = g_tcp_wrapper_connection_new (connection, socket);
	  g_object_unref (connection);
	  connection = (GIOStream *)wrapper_connection;
	}

1157
      g_object_unref (socket);
1158 1159 1160 1161
      g_object_unref (address);
    }
  g_object_unref (enumerator);

1162
  g_socket_client_emit_event (client, G_SOCKET_CLIENT_COMPLETE, connectable, connection);
1163
  return G_SOCKET_CONNECTION (connection);
1164 1165 1166 1167
}

/**
 * g_socket_client_connect_to_host:
1168
 * @client: a #GSocketClient
1169 1170
 * @host_and_port: the name and optionally port of the host to connect to
 * @default_port: the default port to connect to
1171
 * @cancellable: (nullable): a #GCancellable, or %NULL
1172 1173 1174 1175 1176 1177
 * @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.
 *
1178
 * @host_and_port may be in any of a number of recognized formats; an IPv6
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
 * 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
1189
 * them to give the hostname, and a port override if necessary) and
1190
 * @default_port is expected to be provided by the application.
1191
 *
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
 * 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.
 *
1205
 * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
1206 1207
 *
 * Since: 2.22
1208
 */
1209
GSocketConnection *
1210 1211
g_socket_client_connect_to_host (GSocketClient  *client,
				 const gchar    *host_and_port,
1212
				 guint16         default_port,
1213 1214
				 GCancellable   *cancellable,
				 GError        **error)
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
{
  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;
}

1230 1231 1232 1233 1234
/**
 * g_socket_client_connect_to_service:
 * @client: a #GSocketConnection
 * @domain: a domain name
 * @service: the name of the service to connect to
1235
 * @cancellable: (nullable): a #GCancellable, or %NULL
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
 * @error: a pointer to a #GError, or %NULL
 *
 * 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.
1252 1253
 *
 * Returns: (transfer full): a #GSocketConnection if successful, or %NULL on error
1254
 */
1255 1256
GSocketConnection *
g_socket_client_connect_to_service (GSocketClient  *client,
1257 1258
				    const gchar    *domain,
				    const gchar    *service,
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
				    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;
}

1273 1274 1275 1276 1277
/**
 * g_socket_client_connect_to_uri:
 * @client: a #GSocketClient
 * @uri: A network URI
 * @default_port: the default port to connect to
1278
 * @cancellable: (nullable): a #GCancellable, or %NULL
1279 1280 1281 1282 1283 1284 1285 1286
 * @error: a pointer to a #GError, or %NULL
 *
 * This is a helper function for g_socket_client_connect().
 *
 * Attempts to create a TCP connection with a network URI.
 *
 * @uri may be any valid URI containing an "authority" (hostname/port)
 * component. If a port is not specified in the URI, @default_port
1287 1288 1289
 * will be used. TLS will be negotiated if #GSocketClient:tls is %TRUE.
 * (#GSocketClient does not know to automatically assume TLS for
 * certain URI schemes.)
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
 *
 * Using this rather than g_socket_client_connect() or
 * g_socket_client_connect_to_host() allows #GSocketClient to
 * determine when to use application-specific proxy protocols.
 *
 * 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.
 *
1303
 * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
 *
 * Since: 2.26
 */
GSocketConnection *
g_socket_client_connect_to_uri (GSocketClient  *client,
				const gchar    *uri,
				guint16         default_port,
				GCancellable   *cancellable,
				GError        **error)
{
  GSocketConnectable *connectable;
  GSocketConnection *connection;

  connectable = g_network_address_parse_uri (uri, default_port, error);
  if (connectable == NULL)
    return NULL;

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

  return connection;
}

1328 1329
typedef struct
{
1330
  GTask *task;
1331 1332
  GSocketClient *client;

1333
  GSocketConnectable *connectable;
1334
  GSocketAddressEnumerator *enumerator;
1335
  GProxyAddress *proxy_addr;
1336
  GSocket *socket;
1337
  GIOStream *connection;
1338

1339
  GSList *connection_attempts;
1340 1341 1342
  GError *last_error;
} GSocketClientAsyncConnectData;

1343 1344
static void connection_attempt_unref (gpointer attempt);

1345
static void
1346
g_socket_client_async_connect_data_free (GSocketClientAsyncConnectData *data)
1347
{
1348 1349 1350
  g_clear_object (&data->connectable);
  g_clear_object (&data->enumerator);
  g_clear_object (&data->proxy_addr);
1351
  g_clear_object (&data->socket);
1352
  g_clear_object (&data->connection);
1353
  g_slist_free_full (data->connection_attempts, connection_attempt_unref);
1354

1355
  g_clear_error (&data->last_error);
1356

1357 1358
  g_slice_free (GSocketClientAsyncConnectData, data);
}
1359

1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
typedef struct
{
  GSocketAddress *address;
  GSocket *socket;
  GIOStream *connection;
  GSocketClientAsyncConnectData *data; /* unowned */
  GSource *timeout_source;
  GCancellable *cancellable;
  grefcount ref;
} ConnectionAttempt;

static ConnectionAttempt *
connection_attempt_new (void)
{
  ConnectionAttempt *attempt = g_new0 (ConnectionAttempt, 1);
  g_ref_count_init (&attempt->ref);
  return attempt;
}

static ConnectionAttempt *
connection_attempt_ref (ConnectionAttempt *attempt)
{
  g_ref_count_inc (&attempt->ref);
  return attempt;
}

static void
connection_attempt_unref (gpointer pointer)
{
  ConnectionAttempt *attempt = pointer;
  if (g_ref_count_dec (&attempt->ref))
    {
      g_clear_object (&attempt->address);
      g_clear_object (&attempt->socket);
      g_clear_object (&attempt->connection);
      g_clear_object (&attempt->cancellable);
      if (attempt->timeout_source)
        {
          g_source_destroy (attempt->timeout_source);
          g_source_unref (attempt->timeout_source);
        }
      g_free (attempt);
    }
}

static void
connection_attempt_remove (ConnectionAttempt *attempt)
{
  attempt->data->connection_attempts = g_slist_remove (attempt->data->connection_attempts, attempt);
  connection_attempt_unref (attempt);
}

1412 1413 1414 1415 1416 1417 1418 1419
static void
g_socket_client_async_connect_complete (GSocketClientAsyncConnectData *data)
{
  g_assert (data->connection);

  if (!G_IS_SOCKET_CONNECTION (data->connection))
    {
      GSocketConnection *wrapper_connection;
1420

1421
      wrapper_connection = g_tcp_wrapper_connection_new (data->connection, data->socket);
1422 1423
      g_object_unref (data->connection);
      data->connection = (GIOStream *)wrapper_connection;
1424 1425
    }

1426 1427 1428 1429
  g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_COMPLETE, data->connectable, data->connection);
  g_task_return_pointer (data->task, data->connection, g_object_unref);
  data->connection = NULL;
  g_object_unref (data->task);
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
}


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;
}

1446 1447 1448
static void
enumerator_next_async (GSocketClientAsyncConnectData *data)
{
1449
  /* We need to cleanup the state */
1450
  g_clear_object (&data->socket);
1451 1452 1453
  g_clear_object (&data->proxy_addr);
  g_clear_object (&data->connection);

1454
  g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_RESOLVING, data->connectable, NULL);
1455
  g_socket_address_enumerator_next_async (data->enumerator,
1456
					  g_task_get_cancellable (data->task),
1457 1458 1459 1460 1461
					  g_socket_client_enumerator_callback,
					  data);
}

static void
1462
g_socket_client_tls_handshake_callback (GObject      *object,
1463 1464 1465 1466 1467
					GAsyncResult *result,
					gpointer      user_data)
{
  GSocketClientAsyncConnectData *data = user_data;

1468 1469 1470 1471 1472 1473
  if (g_tls_connection_handshake_finish (G_TLS_CONNECTION (object),
					 result,
					 &data->last_error))
    {
      g_object_unref (data->connection);
      data->connection = G_IO_STREAM (object);
1474

1475
      g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_TLS_HANDSHAKED, data->connectable, data->connection);
1476
      g_socket_client_async_connect_complete (data);
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
    }
  else
    {
      g_object_unref (object);
      enumerator_next_async (data);
    }
}

static void
g_socket_client_tls_handshake (GSocketClientAsyncConnectData *data)
{
1488
  GIOStream *tlsconn;
1489 1490

  if (!data->client->priv->tls)
1491
    {
1492 1493 1494 1495 1496 1497 1498 1499 1500
      g_socket_client_async_connect_complete (data);
      return;
    }

  tlsconn = g_tls_client_connection_new (data->connection,
					 data->connectable,
					 &data->last_error);
  if (tlsconn)
    {
1501 1502
      g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (tlsconn),
                                                    data->client->priv->tls_validation_flags);
1503
      g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_TLS_HANDSHAKING, data->connectable, G_IO_STREAM (tlsconn));
1504 1505
      g_tls_connection_handshake_async (G_TLS_CONNECTION (tlsconn),
					G_PRIORITY_DEFAULT,
1506
					g_task_get_cancellable (data->task),
1507 1508
					g_socket_client_tls_handshake_callback,
					data);
1509 1510 1511
    }
  else
    {
1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
      enumerator_next_async (data);
    }
}

static void
g_socket_client_proxy_connect_callback (GObject      *object,
					GAsyncResult *result,
					gpointer      user_data)
{
  GSocketClientAsyncConnectData *data = user_data;

  g_object_unref (data->connection);
  data->connection = g_proxy_connect_finish (G_PROXY (object),
					     result,
					     &data->last_error);
1527 1528 1529 1530 1531
  if (data->connection)
    {
      g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_PROXY_NEGOTIATED, data->connectable, data->connection);
    }
  else
1532 1533 1534
    {
      enumerator_next_async (data);
      return;
1535 1536
    }

1537
  g_socket_client_tls_handshake (data);
1538 1539 1540
}

static void
1541 1542 1543
g_socket_client_connected_callback (GObject      *source,
				    GAsyncResult *result,
				    gpointer      user_data)
1544
{
1545 1546 1547
  ConnectionAttempt *attempt = user_data;
  GSocketClientAsyncConnectData *data = attempt->data;
  GSList *l;
1548
  GError *error = NULL;
1549
  GProxy *proxy;
1550
  const gchar *protocol;
1551

1552 1553
  /* data is NULL once the task is completed */
  if (data && g_task_return_error_if_cancelled (data->task))
1554 1555
    {
      g_object_unref (data->task);
1556
      connection_attempt_unref (attempt);
1557 1558 1559
      return;
    }

1560 1561 1562 1563 1564 1565
  if (attempt->timeout_source)
    {
      g_source_destroy (attempt->timeout_source);
      g_clear_pointer (&attempt->timeout_source, g_source_unref);
    }

1566 1567 1568
  if (!g_socket_connection_connect_finish (G_SOCKET_CONNECTION (source),
					   result, &error))
    {
1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583
      if (!g_cancellable_is_cancelled (attempt->cancellable))
        {
          clarify_connect_error (error, data->connectable, attempt->address);
          set_last_error (data, error);
        }
      else
        g_clear_error (&error);

      if (data)
        {
          connection_attempt_remove (attempt);
          enumerator_next_async (data);
        }
      else
        connection_attempt_unref (attempt);
1584 1585 1586 1587

      return;
    }

1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601
  data->socket = g_steal_pointer (&attempt->socket);
  data->connection = g_steal_pointer (&attempt->connection);

  for (l = data->connection_attempts; l; l = g_slist_next (l))
    {
      ConnectionAttempt *attempt_entry = l->data;
      g_cancellable_cancel (attempt_entry->cancellable);
      attempt_entry->data = NULL;
      connection_attempt_unref (attempt_entry);
    }
  g_slist_free (data->connection_attempts);
  data->connection_attempts = NULL;
  connection_attempt_unref (attempt);

1602
  g_socket_connection_set_cached_remote_address ((GSocketConnection*)data->connection, NULL);
1603 1604
  g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_CONNECTED, data->connectable, data->connection);

1605
  /* wrong, but backward compatible */
1606
  g_socket_set_blocking (data->socket, TRUE);
1607

1608 1609 1610 1611 1612 1613
  if (!data->proxy_addr)
    {
      g_socket_client_tls_handshake (data);
      return;
    }

1614
  protocol = g_proxy_address_get_protocol (data->proxy_addr);
1615

1616
  /* The connection should not be anything other than TCP,
1617 1618 1619 1620 1621 1622 1623 1624 1625
   * but let's put a safety guard in case
   */
  if (!G_IS_TCP_CONNECTION (data->connection))
    {
      g_critical ("Trying to proxy over non-TCP connection, this is "
          "most likely a bug in GLib IO library.");

      g_set_error_literal (&data->last_error,
          G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1626
          _("Proxying over a non-TCP connection is not supported."));
1627 1628 1629

      enumerator_next_async (data);
    }
1630 1631 1632 1633 1634 1635 1636
  else if (g_hash_table_contains (data->client->priv->app_proxies, protocol))
    {
      /* Simply complete the connection, we don't want to do TLS handshake
       * as the application proxy handling may need proxy handshake first */
      g_socket_client_async_connect_complete (data);
    }
  else if ((proxy = g_proxy_get_default_for_protocol (protocol)))
1637
    {
1638
      g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_PROXY_NEGOTIATING, data->connectable, data->connection);
1639
      g_proxy_connect_async (proxy,
1640
                             data->connection,
1641
                             data->proxy_addr,
1642
                             g_task_get_cancellable (data->task),
1643 1644 1645 1646
                             g_socket_client_proxy_connect_callback,
                             data);
      g_object_unref (proxy);
    }
1647
  else
1648 1649 1650 1651
    {
      g_clear_error (&data->last_error);

      g_set_error (&data->last_error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1652
          _("Proxy protocol “%s” is not supported."),
1653 1654 1655 1656 1657 1658
          protocol);

      enumerator_next_async (data);
    }
}

1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678
static gboolean
on_connection_attempt_timeout (gpointer data)
{
  ConnectionAttempt *attempt = data;

  enumerator_next_async (attempt->data);

  g_clear_pointer (&attempt->timeout_source, g_source_unref);
  return G_SOURCE_REMOVE;
}

static void
on_connection_cancelled (GCancellable *cancellable,
                         gpointer      data)
{
  GCancellable *attempt_cancellable = data;

  g_cancellable_cancel (attempt_cancellable);
}

1679 1680 1681 1682 1683 1684
static void
g_socket_client_enumerator_callback (GObject      *object,
				     GAsyncResult *result,
				     gpointer      user_data)
{
  GSocketClientAsyncConnectData *data = user_data;
1685
  GSocketAddress *address = NULL;
1686
  GSocket *socket;
1687
  ConnectionAttempt *attempt;
1688
  GError *error = NULL;
1689

1690
  if (g_task_return_error_if_cancelled (data->task))
Olivier Crête's avatar
Olivier Crête committed
1691 1692 1693 1694
    {
      g_object_unref (data->task);
      return;
    }
1695 1696

  address = g_socket_address_enumerator_next_finish (data->enumerator,
1697
						     result, &error);
1698 1699
  if (address == NULL)
    {
1700 1701 1702
      if (data->connection_attempts)
        return;

1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718
      g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_COMPLETE, data->connectable, NULL);
      if (!error)
	{
	  if (data->last_error)
	    {
	      error = data->last_error;
	      data->last_error = NULL;
	    }
	  else
	    {
	      g_set_error_literal (&error, G_IO_ERROR, G_IO_ERROR_FAILED,
				   _("Unknown error on connect"));
	    }
	}
      g_task_return_error (data->task, error);
      g_object_unref (data->task);
1719 1720 1721
      return;
    }

1722 1723 1724
  g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_RESOLVED,
			      data->connectable, NULL);

1725 1726 1727 1728
  if (G_IS_PROXY_ADDRESS (address) &&
      data->client->priv->enable_proxy)
    data->proxy_addr = g_object_ref (G_PROXY_ADDRESS (address));

1729 1730 1731
  g_clear_error (&data->last_error);

  socket = create_socket (data->client, address, &data->last_error);
1732
  if (socket == NULL)
1733
    {
1734 1735 1736
      g_object_unref (address);
      enumerator_next_async (data);
      return;
1737 1738
    }

1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756
  attempt = connection_attempt_new ();
  attempt->data = data;
  attempt->socket = socket;
  attempt->address = address;
  attempt->cancellable = g_cancellable_new ();
  attempt->connection = (GIOStream *)g_socket_connection_factory_create_connection (socket);
  attempt->timeout_source = g_timeout_source_new (HAPPY_EYEBALLS_CONNECTION_ATTEMPT_TIMEOUT_MS);
  g_source_set_callback (attempt->timeout_source, on_connection_attempt_timeout, attempt, NULL);
  g_source_attach (attempt->timeout_source, g_main_context_get_thread_default ());
  data->connection_attempts = g_slist_append (data->connection_attempts, attempt);

  if (g_task_get_cancellable (data->task))
    g_cancellable_connect (g_task_get_cancellable (data->task), G_CALLBACK (on_connection_cancelled),
                           g_object_ref (attempt->cancellable), g_object_unref);

  g_socket_connection_set_cached_remote_address ((GSocketConnection *)attempt->connection, address);
  g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_CONNECTING, data->connectable, attempt->connection);
  g_socket_connection_connect_async (G_SOCKET_CONNECTION (attempt->connection),
1757
				     address,
1758 1759
				     attempt->cancellable,
				     g_socket_client_connected_callback, connection_attempt_ref (attempt));
1760 1761 1762
}

/**
1763
 * g_socket_client_connect_async:
Matthias Clasen's avatar
Matthias Clasen committed
1764
 * @client: a #GSocketClient
1765
 * @connectable: a #GSocketConnectable specifying the remote address.
1766
 * @cancellable: (nullable): a #GCancellable, or %NULL
1767 1768
 * @callback: (scope async): a #GAsyncReadyCallback
 * @user_data: (closure): user data for the callback
1769 1770 1771 1772 1773 1774 1775 1776
 *
 * 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
1777
 */
1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788
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));

1789
  data = g_slice_new0 (GSocketClientAsyncConnectData);
1790
  data->client = client;
1791
  data->connectable = g_object_ref (connectable);
1792 1793

  if (can_use_proxy (client))
1794
    {
1795
      data->enumerator = g_socket_connectable_proxy_enumerate (connectable);
1796 1797 1798
      if (client->priv->proxy_resolver &&
          G_IS_PROXY_ADDRESS_ENUMERATOR (data->enumerator))
        {
1799 1800 1801
          g_object_set (G_OBJECT (data->enumerator),
                        "proxy-resolver", client->priv->proxy_resolver,
                        NULL);
1802 1803
        }
    }
1804
  else
1805
    data->enumerator = g_socket_connectable_enumerate (connectable);
1806

1807
  data->task = g_task_new (client, cancellable, callback, user_data);
1808
  g_task_set_source_tag (data->task, g_socket_client_connect_async);
1809 1810
  g_task_set_task_data (data->task, data, (GDestroyNotify)g_socket_client_async_connect_data_free);