gsocketclient.c 56.8 KB
Newer Older
1 2 3 4 5 6 7 8
/*  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
9
 * version 2.1 of the License, or (at your option) any later version.
10 11 12 13 14 15 16
 *
 * 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
17
 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
18 19 20 21 22 23 24 25 26
 *
 * Authors: Ryan Lortie <desrt@desrt.ca>
 *          Alexander Larsson <alexl@redhat.com>
 */

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

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

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


/**
 * SECTION:gsocketclient
55
 * @short_description: Helper for connecting to a network service
56 57 58
 * @include: gio/gio.h
 * @see_also: #GSocketConnection, #GSocketListener
 *
59 60
 * #GSocketClient is a lightweight high-level utility class for connecting to
 * a network host using a connection oriented socket type.
61
 *
62
 * You create a #GSocketClient object, set any options you want, and then
63 64 65 66 67 68 69
 * 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.
 *
70 71 72
 * 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.
 *
73
 * Since: 2.22
74
 */
75 76


77 78 79 80 81 82 83 84
enum
{
  EVENT,
  LAST_SIGNAL
};

static guint signals[LAST_SIGNAL] = { 0 };

85 86 87 88 89 90
enum
{
  PROP_NONE,
  PROP_FAMILY,
  PROP_TYPE,
  PROP_PROTOCOL,
91
  PROP_LOCAL_ADDRESS,
92 93
  PROP_TIMEOUT,
  PROP_ENABLE_PROXY,
94
  PROP_TLS,
95 96
  PROP_TLS_VALIDATION_FLAGS,
  PROP_PROXY_RESOLVER
97 98 99 100 101 102
};

struct _GSocketClientPrivate
{
  GSocketFamily family;
  GSocketType type;
103
  GSocketProtocol protocol;
104
  GSocketAddress *local_address;
105
  guint timeout;
106
  gboolean enable_proxy;
107
  GHashTable *app_proxies;
108 109
  gboolean tls;
  GTlsCertificateFlags tls_validation_flags;
110
  GProxyResolver *proxy_resolver;
111 112
};

113 114
G_DEFINE_TYPE_WITH_PRIVATE (GSocketClient, g_socket_client, G_TYPE_OBJECT)

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

149 150 151
  if (client->priv->timeout)
    g_socket_set_timeout (socket, client->priv->timeout);

152 153 154
  return socket;
}

Allison Karlitskaya's avatar
Allison Karlitskaya committed
155
static gboolean
156 157 158 159 160 161 162 163
can_use_proxy (GSocketClient *client)
{
  GSocketClientPrivate *priv = client->priv;

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

164 165 166 167 168 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
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);
}

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

/**
 * 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
218
 */
219 220 221 222 223 224 225 226 227 228 229
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);

230 231
  g_clear_object (&client->priv->local_address);
  g_clear_object (&client->priv->proxy_resolver);
232

233
  G_OBJECT_CLASS (g_socket_client_parent_class)->finalize (object);
234 235

  g_hash_table_unref (client->priv->app_proxies);
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
}

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:
257
	g_value_set_enum (value, client->priv->protocol);
258 259 260 261 262 263
	break;

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

264 265 266 267
      case PROP_TIMEOUT:
	g_value_set_uint (value, client->priv->timeout);
	break;

268 269 270 271
      case PROP_ENABLE_PROXY:
	g_value_set_boolean (value, client->priv->enable_proxy);
	break;

272 273 274 275 276 277 278 279
      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;

280 281 282 283
      case PROP_PROXY_RESOLVER:
	g_value_set_object (value, g_socket_client_get_proxy_resolver (client));
	break;

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

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

315 316 317 318
    case PROP_TIMEOUT:
      g_socket_client_set_timeout (client, g_value_get_uint (value));
      break;

319 320 321 322
    case PROP_ENABLE_PROXY:
      g_socket_client_set_enable_proxy (client, g_value_get_boolean (value));
      break;

323 324 325 326 327 328 329 330
    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;

331 332 333 334
    case PROP_PROXY_RESOLVER:
      g_socket_client_set_proxy_resolver (client, g_value_get_object (value));
      break;

335 336 337 338 339 340 341
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
    }
}

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

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

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

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

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

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

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

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

467
  client->priv->protocol = protocol;
468 469 470 471 472
  g_object_notify (G_OBJECT (client), "protocol");
}

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

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

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

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

563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
/**
 * 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.
 *
589 590
 * See also g_socket_client_set_proxy_resolver().
 *
591 592 593 594 595 596 597 598 599 600 601 602 603 604
 * 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");
}

605 606 607 608 609 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
/**
 * 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.
 *
638 639 640 641 642 643 644 645
 * 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.
 *
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
 * 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");
    }
}

698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
/**
 * 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.
723
 * @proxy_resolver: (nullable): a #GProxyResolver, or %NULL for the
724 725 726 727 728 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
 *   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);
}

756 757 758 759 760 761 762 763 764
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;

765 766 767 768 769
  /**
   * GSocketClient::event:
   * @client: the #GSocketClient
   * @event: the event that is occurring
   * @connectable: the #GSocketConnectable that @event is occurring on
770
   * @connection: (nullable): the current representation of the connection
771 772 773 774 775 776
   *
   * 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:
   *
777 778 779 780 781 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
   * - %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).
811 812 813 814
   *
   * 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
815
   * one address). However, if @client emits the #GSocketClient::event
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
   * 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);

836 837 838 839 840 841
  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,
842 843 844
						      G_PARAM_CONSTRUCT |
                                                      G_PARAM_READWRITE |
                                                      G_PARAM_STATIC_STRINGS));
845 846 847 848 849 850 851

  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,
852 853 854
						      G_PARAM_CONSTRUCT |
                                                      G_PARAM_READWRITE |
                                                      G_PARAM_STATIC_STRINGS));
855 856

  g_object_class_install_property (gobject_class, PROP_PROTOCOL,
857 858 859 860 861
				   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,
862 863 864
						      G_PARAM_CONSTRUCT |
                                                      G_PARAM_READWRITE |
                                                      G_PARAM_STATIC_STRINGS));
865 866 867 868 869 870

  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,
871 872 873
							G_PARAM_CONSTRUCT |
                                                        G_PARAM_READWRITE |
                                                        G_PARAM_STATIC_STRINGS));
874 875 876 877 878 879 880 881 882 883

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

884 885 886 887 888 889 890 891 892
   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));

893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
  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));
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925

  /**
   * 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));
926 927
}

928 929 930 931 932 933 934 935 936 937
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);
}

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

  last_error = NULL;
979 980

  if (can_use_proxy (client))
981 982 983 984 985
    {
      enumerator = g_socket_connectable_proxy_enumerate (connectable);
      if (client->priv->proxy_resolver &&
          G_IS_PROXY_ADDRESS_ENUMERATOR (enumerator))
        {
986 987 988
          g_object_set (G_OBJECT (enumerator),
                        "proxy-resolver", client->priv->proxy_resolver,
                        NULL);
989 990
        }
    }
991 992 993
  else
    enumerator = g_socket_connectable_enumerate (connectable);

994 995
  while (connection == NULL)
    {
996
      GSocketAddress *address = NULL;
997
      gboolean application_proxy = FALSE;
998
      GSocket *socket;
999
      gboolean using_proxy;
1000 1001 1002 1003 1004 1005 1006 1007 1008

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

      tmp_error = NULL;
1009 1010
      g_socket_client_emit_event (client, G_SOCKET_CLIENT_RESOLVING,
				  connectable, NULL);
1011
      address = g_socket_address_enumerator_next (enumerator, cancellable,
1012 1013
	      					  &tmp_error);

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

      using_proxy = (G_IS_PROXY_ADDRESS (address) &&
		     client->priv->enable_proxy);
1035 1036 1037 1038 1039

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

      socket = create_socket (client, address, &last_error);
1040
      if (socket == NULL)
1041
	{
1042 1043
	  g_object_unref (address);
	  continue;
1044 1045
	}

1046
      connection = (GIOStream *)g_socket_connection_factory_create_connection (socket);
1047
      g_socket_connection_set_cached_remote_address ((GSocketConnection*)connection, address);
1048 1049 1050 1051 1052
      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))
	{
1053
          g_socket_connection_set_cached_remote_address ((GSocketConnection*)connection, NULL);
1054 1055 1056
	  g_socket_client_emit_event (client, G_SOCKET_CLIENT_CONNECTED, connectable, connection);
	}
      else
1057 1058 1059 1060 1061
	{
	  clarify_connect_error (last_error, connectable, address);
	  g_object_unref (connection);
	  connection = NULL;
	}
1062

1063
      if (connection && using_proxy)
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
	{
	  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,
1081
                  _("Proxying over a non-TCP connection is not supported."));
1082 1083 1084 1085

	      g_object_unref (connection);
	      connection = NULL;
            }
1086 1087 1088 1089 1090
	  else if (g_hash_table_contains (client->priv->app_proxies, protocol))
	    {
	      application_proxy = TRUE;
	    }
          else if ((proxy = g_proxy_get_default_for_protocol (protocol)))
1091
	    {
1092
	      GIOStream *proxy_connection;
1093

1094
	      g_socket_client_emit_event (client, G_SOCKET_CLIENT_PROXY_NEGOTIATING, connectable, connection);
1095 1096 1097 1098 1099
	      proxy_connection = g_proxy_connect (proxy,
						  connection,
						  proxy_addr,
						  cancellable,
						  &last_error);
1100
	      g_object_unref (connection);
1101
	      connection = proxy_connection;
1102
	      g_object_unref (proxy);
1103 1104 1105

	      if (connection)
		g_socket_client_emit_event (client, G_SOCKET_CLIENT_PROXY_NEGOTIATED, connectable, connection);
1106
	    }
1107
	  else
1108 1109
	    {
	      g_set_error (&last_error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1110
			   _("Proxy protocol “%s” is not supported."),
1111 1112 1113 1114 1115 1116
			   protocol);
	      g_object_unref (connection);
	      connection = NULL;
	    }
	}

1117
      if (!application_proxy && connection && client->priv->tls)
1118
	{
1119
	  GIOStream *tlsconn;
1120 1121 1122

	  tlsconn = g_tls_client_connection_new (connection, connectable, &last_error);
	  g_object_unref (connection);
1123
	  connection = tlsconn;
1124 1125 1126

	  if (tlsconn)
	    {
1127 1128
	      g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (tlsconn),
                                                            client->priv->tls_validation_flags);
1129 1130 1131 1132 1133 1134 1135
	      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
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
		{
		  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;
	}

1152
      g_object_unref (socket);
1153 1154 1155 1156
      g_object_unref (address);
    }
  g_object_unref (enumerator);

1157
  g_socket_client_emit_event (client, G_SOCKET_CLIENT_COMPLETE, connectable, connection);
1158
  return G_SOCKET_CONNECTION (connection);
1159 1160 1161 1162
}

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

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

1268 1269 1270 1271 1272
/**
 * g_socket_client_connect_to_uri:
 * @client: a #GSocketClient
 * @uri: A network URI
 * @default_port: the default port to connect to
1273
 * @cancellable: (nullable): a #GCancellable, or %NULL
1274 1275 1276 1277 1278 1279 1280 1281
 * @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
1282 1283 1284
 * will be used. TLS will be negotiated if #GSocketClient:tls is %TRUE.
 * (#GSocketClient does not know to automatically assume TLS for
 * certain URI schemes.)
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
 *
 * 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.
 *
1298
 * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
 *
 * 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;
}

1323 1324
typedef struct
{
1325
  GTask *task;
1326 1327
  GSocketClient *client;

1328
  GSocketConnectable *connectable;
1329
  GSocketAddressEnumerator *enumerator;
1330
  GProxyAddress *proxy_addr;
1331
  GSocketAddress *current_addr;
1332
  GSocket *current_socket;
1333
  GIOStream *connection;
1334 1335 1336 1337 1338

  GError *last_error;
} GSocketClientAsyncConnectData;

static void
1339
g_socket_client_async_connect_data_free (GSocketClientAsyncConnectData *data)
1340
{
1341 1342 1343 1344 1345 1346
  g_clear_object (&data->connectable);
  g_clear_object (&data->enumerator);
  g_clear_object (&data->proxy_addr);
  g_clear_object (&data->current_addr);
  g_clear_object (&data->current_socket);
  g_clear_object (&data->connection);
1347

1348
  g_clear_error (&data->last_error);
1349

1350 1351
  g_slice_free (GSocketClientAsyncConnectData, data);
}
1352

1353 1354 1355 1356 1357 1358 1359 1360
static void
g_socket_client_async_connect_complete (GSocketClientAsyncConnectData *data)
{
  g_assert (data->connection);

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

1362 1363 1364 1365
      wrapper_connection = g_tcp_wrapper_connection_new (data->connection,
							 data->current_socket);
      g_object_unref (data->connection);
      data->connection = (GIOStream *)wrapper_connection;
1366 1367
    }

1368 1369 1370 1371
  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);
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
}


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

1388 1389 1390
static void
enumerator_next_async (GSocketClientAsyncConnectData *data)
{
1391 1392 1393 1394 1395 1396
  /* We need to cleanup the state */
  g_clear_object (&data->current_socket);
  g_clear_object (&data->current_addr);
  g_clear_object (&data->proxy_addr);
  g_clear_object (&data->connection);

1397
  g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_RESOLVING, data->connectable, NULL);
1398
  g_socket_address_enumerator_next_async (data->enumerator,
1399
					  g_task_get_cancellable (data->task),
1400 1401 1402 1403 1404
					  g_socket_client_enumerator_callback,
					  data);
}

static void
1405
g_socket_client_tls_handshake_callback (GObject      *object,
1406 1407 1408 1409 1410
					GAsyncResult *result,
					gpointer      user_data)
{
  GSocketClientAsyncConnectData *data = user_data;

1411 1412 1413 1414 1415 1416
  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);
1417

1418
      g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_TLS_HANDSHAKED, data->connectable, data->connection);
1419
      g_socket_client_async_connect_complete (data);
1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
    }
  else
    {
      g_object_unref (object);
      enumerator_next_async (data);
    }
}

static void
g_socket_client_tls_handshake (GSocketClientAsyncConnectData *data)
{
1431
  GIOStream *tlsconn;
1432 1433

  if (!data->client->priv->tls)
1434
    {
1435 1436 1437 1438 1439 1440 1441 1442 1443
      g_socket_client_async_connect_complete (data);
      return;
    }

  tlsconn = g_tls_client_connection_new (data->connection,
					 data->connectable,
					 &data->last_error);
  if (tlsconn)
    {
1444 1445
      g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (tlsconn),
                                                    data->client->priv->tls_validation_flags);
1446
      g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_TLS_HANDSHAKING, data->connectable, G_IO_STREAM (tlsconn));
1447 1448
      g_tls_connection_handshake_async (G_TLS_CONNECTION (tlsconn),
					G_PRIORITY_DEFAULT,
1449
					g_task_get_cancellable (data->task),
1450 1451
					g_socket_client_tls_handshake_callback,
					data);
1452 1453 1454
    }
  else
    {
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469
      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);
1470 1471 1472 1473 1474
  if (data->connection)
    {
      g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_PROXY_NEGOTIATED, data->connectable, data->connection);
    }
  else
1475 1476 1477
    {
      enumerator_next_async (data);
      return;
1478 1479
    }

1480
  g_socket_client_tls_handshake (data);
1481 1482 1483
}

static void
1484 1485 1486
g_socket_client_connected_callback (GObject      *source,
				    GAsyncResult *result,
				    gpointer      user_data)
1487
{
1488 1489
  GSocketClientAsyncConnectData *data = user_data;
  GError *error = NULL;
1490
  GProxy *proxy;
1491
  const gchar *protocol;
1492

1493 1494 1495 1496 1497 1498
  if (g_task_return_error_if_cancelled (data->task))
    {
      g_object_unref (data->task);
      return;
    }

1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
  if (!g_socket_connection_connect_finish (G_SOCKET_CONNECTION (source),
					   result, &error))
    {
      clarify_connect_error (error, data->connectable,
			     data->current_addr);
      set_last_error (data, error);

      /* try next one */
      enumerator_next_async (data);
      return;
    }

1511
  g_socket_connection_set_cached_remote_address ((GSocketConnection*)data->connection, NULL);
1512 1513
  g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_CONNECTED, data->connectable, data->connection);

1514 1515 1516
  /* wrong, but backward compatible */
  g_socket_set_blocking (data->current_socket, TRUE);

1517 1518 1519 1520 1521 1522
  if (!data->proxy_addr)
    {
      g_socket_client_tls_handshake (data);
      return;
    }

1523
  protocol = g_proxy_address_get_protocol (data->proxy_addr);
1524

1525
  /* The connection should not be anything other than TCP,
1526 1527 1528 1529 1530 1531 1532 1533 1534
   * 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,
1535
          _("Proxying over a non-TCP connection is not supported."));
1536 1537 1538

      enumerator_next_async (data);
    }
1539 1540 1541 1542 1543 1544 1545
  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)))
1546
    {
1547
      g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_PROXY_NEGOTIATING, data->connectable, data->connection);
1548
      g_proxy_connect_async (proxy,
1549
                             data->connection,
1550
                             data->proxy_addr,
1551
                             g_task_get_cancellable (data->task),
1552 1553 1554 1555
                             g_socket_client_proxy_connect_callback,
                             data);
      g_object_unref (proxy);
    }
1556
  else
1557 1558 1559 1560
    {
      g_clear_error (&data->last_error);

      g_set_error (&data->last_error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1561
          _("Proxy protocol “%s” is not supported."),
1562 1563 1564 1565 1566 1567
          protocol);

      enumerator_next_async (data);
    }
}

1568 1569 1570 1571 1572 1573
static void
g_socket_client_enumerator_callback (GObject      *object,
				     GAsyncResult *result,
				     gpointer      user_data)
{
  GSocketClientAsyncConnectData *data = user_data;
1574
  GSocketAddress *address = NULL;
1575
  GSocket *socket;
1576
  GError *error = NULL;
1577

1578
  if (g_task_return_error_if_cancelled (data->task))
Olivier Crête's avatar
Olivier Crête committed
1579 1580 1581 1582
    {
      g_object_unref (data->task);
      return;
    }
1583 1584

  address = g_socket_address_enumerator_next_finish (data->enumerator,
1585
						     result, &error);
1586 1587
  if (address == NULL)
    {
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603
      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);
1604 1605 1606
      return;
    }

1607 1608 1609
  g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_RESOLVED,
			      data->connectable, NULL);

1610 1611 1612 1613
  if (G_IS_PROXY_ADDRESS (address) &&
      data->client->priv->enable_proxy)
    data->proxy_addr = g_object_ref (G_PROXY_ADDRESS (address));

1614 1615 1616
  g_clear_error (&data->last_error);

  socket = create_socket (data->client, address, &data->last_error);
1617
  if (socket == NULL)
1618
    {
1619 1620 1621
      g_object_unref (address);
      enumerator_next_async (data);
      return;
1622 1623
    }

1624 1625 1626 1627
  data->current_socket = socket;
  data->current_addr = address;
  data->connection = (GIOStream *) g_socket_connection_factory_create_connection (socket);

1628
  g_socket_connection_set_cached_remote_address ((GSocketConnection*)data->connection, address);
1629
  g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_CONNECTING, data->connectable, data->connection);
1630
  g_socket_connection_connect_async (G_SOCKET_CONNECTION (data->connection),
1631 1632
				     address,
				     g_task_get_cancellable (data->task),
1633
				     g_socket_client_connected_callback, data);
1634 1635 1636
}

/**
1637
 * g_socket_client_connect_async:
Matthias Clasen's avatar
Matthias Clasen committed
1638
 * @client: a #GSocketClient
1639
 * @connectable: a #GSocketConnectable specifying the remote address.
1640
 * @cancellable: (nullable): a #GCancellable, or %NULL
1641 1642
 * @callback: (scope async): a #GAsyncReadyCallback
 * @user_data: (closure): user data for the callback
1643 1644 1645 1646 1647 1648 1649 1650
 *
 * 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
1651
 */
1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662
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));

1663
  data = g_slice_new0 (GSocketClientAsyncConnectData);
1664
  data->client = client;
1665
  data->connectable = g_object_ref (connectable);
1666 1667

  if (can_use_proxy (client))
1668
    {
1669
      data->enumerator = g_socket_connectable_proxy_enumerate (connectable);
1670 1671 1672
      if (client->priv->proxy_resolver &&
          G_IS_PROXY_ADDRESS_ENUMERATOR (data->enumerator))
        {
1673 1674 1675
          g_object_set (G_OBJECT (data->enumerator),
                        "proxy-resolver", client->priv->proxy_resolver,
                        NULL);
1676 1677
        }
    }
1678
  else
1679
    data->enumerator = g_socket_connectable_enumerate (connectable);
1680

1681
  data->task = g_task_new (client, cancellable, callback, user_data);
1682
  g_task_set_source_tag (data->task, g_socket_client_connect_async);
1683 1684
  g_task_set_task_data (data->task, data, (GDestroyNotify)g_socket_client_async_connect_data_free);

1685
  enumerator_next_async (data);
1686 1687 1688 1689
}

/**
 * g_socket_client_connect_to_host_async:
Matthias Clasen's avatar
Matthias Clasen committed
1690
 * @client: a #GSocketClient
1691 1692
 * @host_and_port: the name and optionally the port of the host to connect to
 * @default_port: the default port to connect to
1693
 * @cancellable: (nullable): a #GCancellable, or %NULL
1694 1695
 * @callback: (scope async): a #GAsyncReadyCallback
 * @user_data: (closure): user data for the callback
1696 1697 1698 1699 1700 1701 1702 1703
 *
 * 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
1704
 */
1705 1706
void
g_socket_client_connect_to_host_async (GSocketClient        *client,
1707
				       const gchar          *host_and_port,
1708
				       guint16               default_port,
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720
				       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)
    {
1721 1722 1723
      g_task_report_error (client, callback, user_data,
                           g_socket_client_connect_to_host_async,
                           error);
1724 1725 1726 1727 1728 1729 1730 1731 1732 1733
    }
  else
    {
      g_socket_client_connect_async (client,
				     connectable, cancellable,
				     callback, user_data);
      g_object_unref (connectable);
    }
}

1734 1735 1736 1737 1738
/**
 * g_socket_client_connect_to_service_async:
 * @client: a #GSocketClient
 * @domain: a domain name
 * @service: the name of the service to connect to
1739
 * @cancellable: (nullable): a #GCancellable, or %NULL
1740 1741
 * @callback: (scope async): a #GAsyncReadyCallback
 * @user_data: (closure): user data for the callback
1742 1743 1744
 *
 * This is the asynchronous version of
 * g_socket_client_connect_to_service().
1745 1746 1747
 *
 * Since: 2.22
 */
1748 1749
void
g_socket_client_connect_to_service_async (GSocketClient       *client,
1750 1751
					  const gchar         *domain,
					  const gchar         *service,
1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764
					  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);
}

1765 1766 1767 1768 1769
/**
 * g_socket_client_connect_to_uri_async:
 * @client: a #GSocketClient
 * @uri: a network uri
 * @default_port: the default port to connect to
1770
 * @cancellable: (nullable): a #GCancellable, or %NULL
1771 1772
 * @callback: (scope async): a #GAsyncReadyCallback
 * @user_data: (closure): user data for the callback
1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796
 *
 * This is the asynchronous version of g_socket_client_connect_to_uri().
 *
 * When the operation is finished @callback will be
 * called. You can then call g_socket_client_connect_to_uri_finish() to get
 * the result of the operation.
 *
 * Since: 2.26
 */
void
g_socket_client_connect_to_uri_async (GSocketClient        *client,
				      const gchar          *uri,
				      guint16               default_port,
				      GCancellable         *cancellable,
				      GAsyncReadyCallback   callback,
				      gpointer              user_data)
{
  GSocketConnectable *connectable;
  GError *error;

  error = NULL;
  connectable = g_network_address_parse_uri (uri, default_port, &error);
  if (connectable == NULL)
    {
1797 1798 1799
      g_task_report_error (client, callback, user_data,
                           g_socket_client_connect_to_uri_async,
                           error);
1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810
    }
  else
    {
      g_socket_client_connect_async (client,
				     connectable, cancellable,
				     callback, user_data);
      g_object_unref (connectable);
    }
}


1811 1812 1813 1814
/**
 * g_socket_client_connect_finish:
 * @client: a #GSocketClient.
 * @result: a #GAsyncResult.
1815
 * @error: a #GError location to store the error occurring, or %NULL to