gsocketclient.c 54.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
/*  GIO - GLib Input, Output and Streaming Library
 *
 * Copyright © 2008, 2009 codethink
 * Copyright © 2009 Red Hat, Inc
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 * Authors: Ryan Lortie <desrt@desrt.ca>
 *          Alexander Larsson <alexl@redhat.com>
 */

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

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

#include <gio/gioenumtypes.h>
#include <gio/gsocketaddressenumerator.h>
#include <gio/gsocketconnectable.h>
#include <gio/gsocketconnection.h>
35 36
#include <gio/gproxyaddressenumerator.h>
#include <gio/gproxyaddress.h>
37 38 39 40 41
#include <gio/gsimpleasyncresult.h>
#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/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


G_DEFINE_TYPE (GSocketClient, g_socket_client, G_TYPE_OBJECT);

79 80 81 82 83 84 85 86
enum
{
  EVENT,
  LAST_SIGNAL
};

static guint signals[LAST_SIGNAL] = { 0 };

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

struct _GSocketClientPrivate
{
  GSocketFamily family;
  GSocketType type;
104
  GSocketProtocol protocol;
105
  GSocketAddress *local_address;
106
  guint timeout;
107
  gboolean enable_proxy;
108
  GHashTable *app_proxies;
109 110
  gboolean tls;
  GTlsCertificateFlags tls_validation_flags;
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
};

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,
130
			 client->priv->protocol,
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
			 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;
	}
    }

147 148 149
  if (client->priv->timeout)
    g_socket_set_timeout (socket, client->priv->timeout);

150 151 152
  return socket;
}

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

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

162 163 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
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);
}

196 197 198 199 200 201 202
static void
g_socket_client_init (GSocketClient *client)
{
  client->priv = G_TYPE_INSTANCE_GET_PRIVATE (client,
					      G_TYPE_SOCKET_CLIENT,
					      GSocketClientPrivate);
  client->priv->type = G_SOCKET_TYPE_STREAM;
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 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);

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

  if (G_OBJECT_CLASS (g_socket_client_parent_class)->finalize)
    (*G_OBJECT_CLASS (g_socket_client_parent_class)->finalize) (object);
235 236

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

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

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

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

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

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

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

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

312 313 314 315
    case PROP_TIMEOUT:
      g_socket_client_set_timeout (client, g_value_get_uint (value));
      break;

316 317 318 319
    case PROP_ENABLE_PROXY:
      g_socket_client_set_enable_proxy (client, g_value_get_boolean (value));
      break;

320 321 322 323 324 325 326 327
    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;

328 329 330 331 332 333 334
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
    }
}

/**
 * g_socket_client_get_family:
335
 * @client: a #GSocketClient.
336 337 338 339 340 341 342 343
 *
 * Gets the socket family of the socket client.
 *
 * See g_socket_client_set_family() for details.
 *
 * Returns: a #GSocketFamily
 *
 * Since: 2.22
344
 */
345 346 347 348 349 350 351 352
GSocketFamily
g_socket_client_get_family (GSocketClient *client)
{
  return client->priv->family;
}

/**
 * g_socket_client_set_family:
353
 * @client: a #GSocketClient.
354 355 356 357 358 359 360 361 362 363 364 365
 * @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
366
 */
367 368
void
g_socket_client_set_family (GSocketClient *client,
369
			    GSocketFamily  family)
370 371 372 373 374 375 376 377 378 379
{
  if (client->priv->family == family)
    return;

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

/**
 * g_socket_client_get_socket_type:
380
 * @client: a #GSocketClient.
381 382 383 384 385 386 387 388
 *
 * Gets the socket type of the socket client.
 *
 * See g_socket_client_set_socket_type() for details.
 *
 * Returns: a #GSocketFamily
 *
 * Since: 2.22
389
 */
390 391 392 393 394 395 396 397
GSocketType
g_socket_client_get_socket_type (GSocketClient *client)
{
  return client->priv->type;
}

/**
 * g_socket_client_set_socket_type:
398
 * @client: a #GSocketClient.
399 400 401 402 403 404 405 406 407 408
 * @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
409
 */
410 411
void
g_socket_client_set_socket_type (GSocketClient *client,
412
				 GSocketType    type)
413 414 415 416 417 418 419 420 421 422
{
  if (client->priv->type == type)
    return;

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

/**
 * g_socket_client_get_protocol:
423
 * @client: a #GSocketClient
424 425 426 427 428
 *
 * Gets the protocol name type of the socket client.
 *
 * See g_socket_client_set_protocol() for details.
 *
429
 * Returns: a #GSocketProtocol
430 431
 *
 * Since: 2.22
432
 */
433
GSocketProtocol
434 435 436 437 438 439 440
g_socket_client_get_protocol (GSocketClient *client)
{
  return client->priv->protocol;
}

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

460
  client->priv->protocol = protocol;
461 462 463 464 465
  g_object_notify (G_OBJECT (client), "protocol");
}

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

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

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

512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
/**
 * 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");
}

556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
/**
 * 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.
 *
 * 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");
}

596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
/**
 * 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.
 *
629 630 631 632 633 634 635 636
 * 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.
 *
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
 * 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");
    }
}

689 690 691 692 693 694 695 696 697 698 699
static void
g_socket_client_class_init (GSocketClientClass *class)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (class);

  g_type_class_add_private (class, sizeof (GSocketClientPrivate));

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

700 701 702 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 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 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
  /**
   * GSocketClient::event:
   * @client: the #GSocketClient
   * @event: the event that is occurring
   * @connectable: the #GSocketConnectable that @event is occurring on
   * @connection: the current representation of the connection
   *
   * 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:
   *
   * <variablelist>
   *   <varlistentry>
   *     <term>%G_SOCKET_CLIENT_RESOLVING:</term>
   *     <listitem><para>
   *       @client is about to look up @connectable in DNS.
   *       @connection will be %NULL.
   *     </para></listitem>
   *   </varlistentry>
   *   <varlistentry>
   *     <term>%G_SOCKET_CLIENT_RESOLVED:</term>
   *     <listitem><para>
   *       @client has successfully resolved @connectable in DNS.
   *       @connection will be %NULL.
   *     </para></listitem>
   *   </varlistentry>
   *   <varlistentry>
   *     <term>%G_SOCKET_CLIENT_CONNECTING:</term>
   *     <listitem><para>
   *       @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.
   *     </para></listitem>
   *   </varlistentry>
   *   <varlistentry>
   *     <term>%G_SOCKET_CLIENT_CONNECTED:</term>
   *     <listitem><para>
   *       @client has successfully connected to a remote host.
   *       @connection is the connected #GSocketConnection.
   *     </para></listitem>
   *   </varlistentry>
   *   <varlistentry>
   *     <term>%G_SOCKET_CLIENT_PROXY_NEGOTIATING:</term>
   *     <listitem><para>
   *       @client is about to negotiate with a proxy to get it to
   *       connect to @connectable. @connection is the
   *       #GSocketConnection to the proxy server.
   *     </para></listitem>
   *   </varlistentry>
   *   <varlistentry>
   *     <term>%G_SOCKET_CLIENT_PROXY_NEGOTIATED:</term>
   *     <listitem><para>
   *       @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.
   *     </para></listitem>
   *   </varlistentry>
   *   <varlistentry>
   *     <term>%G_SOCKET_CLIENT_TLS_HANDSHAKING:</term>
   *     <listitem><para>
   *       @client is about to begin a TLS handshake. @connection is a
   *       #GTlsClientConnection.
   *     </para></listitem>
   *   </varlistentry>
   *   <varlistentry>
   *     <term>%G_SOCKET_CLIENT_TLS_HANDSHAKED:</term>
   *     <listitem><para>
   *       @client has successfully completed the TLS handshake.
   *       @connection is a #GTlsClientConnection.
   *     </para></listitem>
   *   </varlistentry>
   *   <varlistentry>
   *     <term>%G_SOCKET_CLIENT_COMPLETE:</term>
   *     <listitem><para>
   *       @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).
   *     </para></listitem>
   *   </varlistentry>
   * </variablelist>
   *
   * 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
789
   * one address). However, if @client emits the #GSocketClient::event
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
   * 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);

810 811 812 813 814 815
  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,
816 817 818
						      G_PARAM_CONSTRUCT |
                                                      G_PARAM_READWRITE |
                                                      G_PARAM_STATIC_STRINGS));
819 820 821 822 823 824 825

  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,
826 827 828
						      G_PARAM_CONSTRUCT |
                                                      G_PARAM_READWRITE |
                                                      G_PARAM_STATIC_STRINGS));
829 830

  g_object_class_install_property (gobject_class, PROP_PROTOCOL,
831 832 833 834 835
				   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,
836 837 838
						      G_PARAM_CONSTRUCT |
                                                      G_PARAM_READWRITE |
                                                      G_PARAM_STATIC_STRINGS));
839 840 841 842 843 844

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

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

858 859 860 861 862 863 864 865 866
   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));

867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
  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));
884 885
}

886 887 888 889 890 891 892 893 894 895
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);
}

896 897 898 899
/**
 * g_socket_client_connect:
 * @client: a #GSocketClient.
 * @connectable: a #GSocketConnectable specifying the remote address.
900
 * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
901 902
 * @error: #GError for error reporting, or %NULL to ignore.
 *
903
 * Tries to resolve the @connectable and make a network connection to it.
904 905 906 907 908 909 910 911 912
 *
 * 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.
 *
913
 * The socket created will be the same family as the address that the
914 915 916 917 918 919 920 921
 * @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.
 *
922
 * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
923 924
 *
 * Since: 2.22
925
 */
926 927 928 929 930 931
GSocketConnection *
g_socket_client_connect (GSocketClient       *client,
			 GSocketConnectable  *connectable,
			 GCancellable        *cancellable,
			 GError             **error)
{
932
  GIOStream *connection = NULL;
933
  GSocketAddressEnumerator *enumerator = NULL;
934 935 936
  GError *last_error, *tmp_error;

  last_error = NULL;
937 938 939 940 941 942

  if (can_use_proxy (client))
    enumerator = g_socket_connectable_proxy_enumerate (connectable);
  else
    enumerator = g_socket_connectable_enumerate (connectable);

943 944
  while (connection == NULL)
    {
945
      GSocketAddress *address = NULL;
946
      gboolean application_proxy = FALSE;
947
      GSocket *socket;
948
      gboolean using_proxy;
949 950 951 952 953 954 955 956 957

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

      tmp_error = NULL;
958 959
      g_socket_client_emit_event (client, G_SOCKET_CLIENT_RESOLVING,
				  connectable, NULL);
960
      address = g_socket_address_enumerator_next (enumerator, cancellable,
961 962
	      					  &tmp_error);

963 964 965 966 967 968 969 970 971
      if (address == NULL)
	{
	  if (tmp_error)
	    {
	      g_clear_error (&last_error);
	      g_propagate_error (error, tmp_error);
	    }
	  else if (last_error)
	    {
972
	      g_propagate_error (error, last_error);
973 974
	    }
	  else
975 976
            g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
                                 _("Unknown error on connect"));
977 978
	  break;
	}
979 980 981 982 983
      g_socket_client_emit_event (client, G_SOCKET_CLIENT_RESOLVED,
				  connectable, NULL);

      using_proxy = (G_IS_PROXY_ADDRESS (address) &&
		     client->priv->enable_proxy);
984 985 986 987 988

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

      socket = create_socket (client, address, &last_error);
989
      if (socket == NULL)
990
	{
991 992
	  g_object_unref (address);
	  continue;
993 994
	}

995
      connection = (GIOStream *)g_socket_connection_factory_create_connection (socket);
996 997 998 999 1000 1001 1002 1003
      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))
	{
	  g_socket_client_emit_event (client, G_SOCKET_CLIENT_CONNECTED, connectable, connection);
	}
      else
1004 1005 1006 1007 1008
	{
	  clarify_connect_error (last_error, connectable, address);
	  g_object_unref (connection);
	  connection = NULL;
	}
1009

1010
      if (connection && using_proxy)
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
	{
	  GProxyAddress *proxy_addr = G_PROXY_ADDRESS (address);
	  const gchar *protocol;
	  GProxy *proxy;

	  protocol = g_proxy_address_get_protocol (proxy_addr);
	  proxy = g_proxy_get_default_for_protocol (protocol);

          /* 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,
                  _("Trying to proxy over non-TCP connection is not supported."));

	      g_object_unref (connection);
	      connection = NULL;
            }
          else if (proxy)
	    {
1036
	      GIOStream *proxy_connection;
1037

1038
	      g_socket_client_emit_event (client, G_SOCKET_CLIENT_PROXY_NEGOTIATING, connectable, connection);
1039 1040 1041 1042 1043
	      proxy_connection = g_proxy_connect (proxy,
						  connection,
						  proxy_addr,
						  cancellable,
						  &last_error);
1044
	      g_object_unref (connection);
1045
	      connection = proxy_connection;
1046
	      g_object_unref (proxy);
1047 1048 1049

	      if (connection)
		g_socket_client_emit_event (client, G_SOCKET_CLIENT_PROXY_NEGOTIATED, connectable, connection);
1050
	    }
1051 1052
	  else if (!g_hash_table_lookup_extended (client->priv->app_proxies,
						  protocol, NULL, NULL))
1053 1054 1055 1056 1057 1058 1059
	    {
	      g_set_error (&last_error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
			   _("Proxy protocol '%s' is not supported."),
			   protocol);
	      g_object_unref (connection);
	      connection = NULL;
	    }
1060 1061 1062 1063
	  else
	    {
	      application_proxy = TRUE;
	    }
1064 1065
	}

1066
      if (!application_proxy && connection && client->priv->tls)
1067
	{
1068
	  GIOStream *tlsconn;
1069 1070 1071

	  tlsconn = g_tls_client_connection_new (connection, connectable, &last_error);
	  g_object_unref (connection);
1072
	  connection = tlsconn;
1073 1074 1075

	  if (tlsconn)
	    {
1076 1077
	      g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (tlsconn),
                                                            client->priv->tls_validation_flags);
1078 1079 1080 1081 1082 1083 1084
	      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
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
		{
		  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;
	}

1101
      g_object_unref (socket);
1102 1103 1104 1105
      g_object_unref (address);
    }
  g_object_unref (enumerator);

1106
  g_socket_client_emit_event (client, G_SOCKET_CLIENT_COMPLETE, connectable, connection);
1107
  return G_SOCKET_CONNECTION (connection);
1108 1109 1110 1111
}

/**
 * g_socket_client_connect_to_host:
1112
 * @client: a #GSocketClient
1113 1114
 * @host_and_port: the name and optionally port of the host to connect to
 * @default_port: the default port to connect to
1115
 * @cancellable: (allow-none): a #GCancellable, or %NULL
1116 1117 1118 1119 1120 1121
 * @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.
 *
1122
 * @host_and_port may be in any of a number of recognized formats; an IPv6
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
 * 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
1133
 * them to give the hostname, and a port override if necessary) and
1134
 * @default_port is expected to be provided by the application.
1135
 *
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
 * 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.
 *
1149
 * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
1150 1151
 *
 * Since: 2.22
1152
 */
1153
GSocketConnection *
1154 1155
g_socket_client_connect_to_host (GSocketClient  *client,
				 const gchar    *host_and_port,
1156
				 guint16         default_port,
1157 1158
				 GCancellable   *cancellable,
				 GError        **error)
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
{
  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;
}

1174 1175 1176 1177 1178
/**
 * g_socket_client_connect_to_service:
 * @client: a #GSocketConnection
 * @domain: a domain name
 * @service: the name of the service to connect to
1179
 * @cancellable: (allow-none): a #GCancellable, or %NULL
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
 * @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.
1196 1197
 *
 * Returns: (transfer full): a #GSocketConnection if successful, or %NULL on error
1198
 */
1199 1200
GSocketConnection *
g_socket_client_connect_to_service (GSocketClient  *client,
1201 1202
				    const gchar    *domain,
				    const gchar    *service,
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
				    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;
}

1217 1218 1219 1220 1221
/**
 * g_socket_client_connect_to_uri:
 * @client: a #GSocketClient
 * @uri: A network URI
 * @default_port: the default port to connect to
1222
 * @cancellable: (allow-none): a #GCancellable, or %NULL
1223 1224 1225 1226 1227 1228 1229 1230
 * @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
1231 1232 1233
 * will be used. TLS will be negotiated if #GSocketClient:tls is %TRUE.
 * (#GSocketClient does not know to automatically assume TLS for
 * certain URI schemes.)
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
 *
 * 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.
 *
1247
 * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
 *
 * 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;
}

1272 1273 1274 1275 1276 1277
typedef struct
{
  GSimpleAsyncResult *result;
  GCancellable *cancellable;
  GSocketClient *client;

1278
  GSocketConnectable *connectable;
1279
  GSocketAddressEnumerator *enumerator;
1280
  GProxyAddress *proxy_addr;
1281
  GSocketAddress *current_addr;
1282
  GSocket *current_socket;
1283
  GIOStream *connection;
1284 1285 1286 1287 1288 1289 1290

  GError *last_error;
} GSocketClientAsyncConnectData;

static void
g_socket_client_async_connect_complete (GSocketClientAsyncConnectData *data)
{
1291 1292
  g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_COMPLETE, data->connectable, data->connection);

1293 1294
  if (data->last_error)
    {
1295
      g_simple_async_result_take_error (data->result, data->last_error);
1296 1297 1298
    }
  else
    {
1299
      g_assert (data->connection);
1300

1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
      if (!G_IS_SOCKET_CONNECTION (data->connection))
	{
	  GSocketConnection *wrapper_connection;

	  wrapper_connection = g_tcp_wrapper_connection_new (data->connection,
							     data->current_socket);
	  g_object_unref (data->connection);
	  data->connection = (GIOStream *)wrapper_connection;
	}

1311
      g_simple_async_result_set_op_res_gpointer (data->result,
1312
						 data->connection,
1313 1314 1315 1316 1317
						 g_object_unref);
    }

  g_simple_async_result_complete (data->result);
  g_object_unref (data->result);
1318
  g_object_unref (data->connectable);
1319
  g_object_unref (data->enumerator);
1320 1321
  if (data->cancellable)
    g_object_unref (data->cancellable);
1322 1323
  if (data->current_addr)
    g_object_unref (data->current_addr);
1324 1325 1326 1327
  if (data->current_socket)
    g_object_unref (data->current_socket);
  if (data->proxy_addr)
    g_object_unref (data->proxy_addr);
1328
  g_slice_free (GSocketClientAsyncConnectData, data);
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
}


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

1345 1346 1347
static void
enumerator_next_async (GSocketClientAsyncConnectData *data)
{
1348 1349 1350 1351 1352 1353
  /* 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);

1354
  g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_RESOLVING, data->connectable, NULL);
1355 1356 1357 1358 1359 1360 1361
  g_socket_address_enumerator_next_async (data->enumerator,
					  data->cancellable,
					  g_socket_client_enumerator_callback,
					  data);
}

static void
1362
g_socket_client_tls_handshake_callback (GObject      *object,
1363 1364 1365 1366 1367
					GAsyncResult *result,
					gpointer      user_data)
{
  GSocketClientAsyncConnectData *data = user_data;

1368 1369 1370 1371 1372 1373
  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);
1374

1375
      g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_TLS_HANDSHAKED, data->connectable, data->connection);
1376
      g_socket_client_async_connect_complete (data);
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
    }
  else
    {
      g_object_unref (object);
      enumerator_next_async (data);
    }
}

static void
g_socket_client_tls_handshake (GSocketClientAsyncConnectData *data)
{
1388
  GIOStream *tlsconn;
1389 1390

  if (!data->client->priv->tls)
1391
    {
1392 1393 1394 1395 1396 1397 1398 1399 1400
      g_socket_client_async_connect_complete (data);
      return;
    }

  tlsconn = g_tls_client_connection_new (data->connection,
					 data->connectable,
					 &data->last_error);
  if (tlsconn)
    {
1401 1402
      g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (tlsconn),
                                                    data->client->priv->tls_validation_flags);
1403
      g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_TLS_HANDSHAKING, data->connectable, G_IO_STREAM (tlsconn));
1404 1405 1406 1407 1408
      g_tls_connection_handshake_async (G_TLS_CONNECTION (tlsconn),
					G_PRIORITY_DEFAULT,
					data->cancellable,
					g_socket_client_tls_handshake_callback,
					data);
1409 1410 1411
    }
  else
    {
1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
      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);
1427 1428 1429 1430 1431
  if (data->connection)
    {
      g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_PROXY_NEGOTIATED, data->connectable, data->connection);
    }
  else
1432 1433 1434
    {
      enumerator_next_async (data);
      return;
1435 1436
    }

1437
  g_socket_client_tls_handshake (data);
1438 1439 1440
}

static void
1441 1442 1443
g_socket_client_connected_callback (GObject      *source,
				    GAsyncResult *result,
				    gpointer      user_data)
1444
{
1445 1446
  GSocketClientAsyncConnectData *data = user_data;
  GError *error = NULL;
1447
  GProxy *proxy;
1448
  const gchar *protocol;
1449

1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
  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;
    }

1462 1463
  g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_CONNECTED, data->connectable, data->connection);

1464 1465 1466
  /* wrong, but backward compatible */
  g_socket_set_blocking (data->current_socket, TRUE);

1467 1468 1469 1470 1471 1472
  if (!data->proxy_addr)
    {
      g_socket_client_tls_handshake (data);
      return;
    }

1473
  protocol = g_proxy_address_get_protocol (data->proxy_addr);
1474 1475
  proxy = g_proxy_get_default_for_protocol (protocol);

1476
  /* The connection should not be anything other than TCP,
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
   * 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,
          _("Trying to proxy over non-TCP connection is not supported."));

      enumerator_next_async (data);
    }
  else if (proxy)
    {
1492
      g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_PROXY_NEGOTIATING, data->connectable, data->connection);
1493
      g_proxy_connect_async (proxy,
1494
                             data->connection,
1495 1496 1497 1498 1499 1500
                             data->proxy_addr,
                             data->cancellable,
                             g_socket_client_proxy_connect_callback,
                             data);
      g_object_unref (proxy);
    }
1501 1502
  else if (!g_hash_table_lookup_extended (data->client->priv->app_proxies,
					  protocol, NULL, NULL))
1503 1504 1505 1506 1507 1508 1509 1510 1511
    {
      g_clear_error (&data->last_error);

      g_set_error (&data->last_error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
          _("Proxy protocol '%s' is not supported."),
          protocol);

      enumerator_next_async (data);
    }
1512 1513 1514 1515 1516 1517
  else
    {
      /* 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);
    }
1518 1519
}

1520 1521 1522 1523 1524 1525
static void
g_socket_client_enumerator_callback (GObject      *object,
				     GAsyncResult *result,
				     gpointer      user_data)
{
  GSocketClientAsyncConnectData *data = user_data;
1526
  GSocketAddress *address = NULL;
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
  GSocket *socket;
  GError *tmp_error = NULL;

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

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

  if (address == NULL)
    {
      if (tmp_error)
	set_last_error (data, tmp_error);
      else if (data->last_error == NULL)
1546 1547
        g_set_error_literal (&data->last_error, G_IO_ERROR, G_IO_ERROR_FAILED,
                             _("Unknown error on connect"));
1548 1549 1550 1551 1552

      g_socket_client_async_connect_complete (data);
      return;
    }

1553 1554 1555
  g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_RESOLVED,
			      data->connectable, NULL);

1556 1557 1558 1559
  if (G_IS_PROXY_ADDRESS (address) &&
      data->client->priv->enable_proxy)
    data->proxy_addr = g_object_ref (G_PROXY_ADDRESS (address));

1560 1561 1562
  g_clear_error (&data->last_error);

  socket = create_socket (data->client, address, &data->last_error);
1563
  if (socket == NULL)
1564
    {
1565 1566 1567
      g_object_unref (address);
      enumerator_next_async (data);
      return;
1568 1569
    }

1570 1571 1572 1573
  data->current_socket = socket;
  data->current_addr = address;
  data->connection = (GIOStream *) g_socket_connection_factory_create_connection (socket);

1574
  g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_CONNECTING, data->connectable, data->connection);
1575 1576 1577
  g_socket_connection_connect_async (G_SOCKET_CONNECTION (data->connection),
				     address, data->cancellable,
				     g_socket_client_connected_callback, data);
1578 1579 1580
}

/**
1581
 * g_socket_client_connect_async:
Matthias Clasen's avatar
Matthias Clasen committed
1582
 * @client: a #GSocketClient
1583
 * @connectable: a #GSocketConnectable specifying the remote address.
1584 1585 1586
 * @cancellable: (allow-none): a #GCancellable, or %NULL
 * @callback: (scope async): a #GAsyncReadyCallback
 * @user_data: (closure): user data for the callback
1587 1588 1589 1590 1591 1592 1593 1594
 *
 * 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
1595
 */
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
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));

1607
  data = g_slice_new0 (GSocketClientAsyncConnectData);
1608 1609 1610 1611 1612 1613 1614

  data->result = g_simple_async_result_new (G_OBJECT (client),
					    callback, user_data,
					    g_socket_client_connect_async);
  data->client = client;
  if (cancellable)
    data->cancellable = g_object_ref (cancellable);
1615 1616 1617 1618
  else
    data->cancellable = NULL;
  data->last_error = NULL;
  data->connectable = g_object_ref (connectable);
1619 1620 1621

  if (can_use_proxy (client))
      data->enumerator = g_socket_connectable_proxy_enumerate (connectable);
1622
  else
1623
      data->enumerator = g_socket_connectable_enumerate (connectable);
1624

1625
  enumerator_next_async (data);
1626 1627 1628 1629
}

/**
 * g_socket_client_connect_to_host_async:
Matthias Clasen's avatar
Matthias Clasen committed
1630
 * @client: a #GSocketClient
1631 1632
 * @host_and_port: the name and optionally the port of the host to connect to
 * @default_port: the default port to connect to
1633 1634 1635
 * @cancellable: (allow-none): a #GCancellable, or %NULL
 * @callback: (scope async): a #GAsyncReadyCallback
 * @user_data: (closure): user data for the callback
1636 1637 1638 1639 1640 1641 1642 1643
 *
 * 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
1644
 */
1645 1646
void
g_socket_client_connect_to_host_async (GSocketClient        *client,
1647
				       const gchar          *host_and_port,
1648
				       guint16               default_port,
1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
				       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)
    {
1661
      g_simple_async_report_take_gerror_in_idle (G_OBJECT (client),
1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
					    callback, user_data, error);
    }
  else
    {
      g_socket_client_connect_async (client,
				     connectable, cancellable,
				     callback, user_data);
      g_object_unref (connectable);
    }
}

1673 1674 1675 1676 1677
/**
 * g_socket_client_connect_to_service_async:
 * @client: a #GSocketClient
 * @domain: a domain name
 * @service: the name of the service to connect to
1678 1679 1680
 * @cancellable: (allow-none): a #GCancellable, or %NULL
 * @callback: (scope async): a #GAsyncReadyCallback
 * @user_data: (closure): user data for the callback
1681 1682 1683
 *
 * This is the asynchronous version of
 * g_socket_client_connect_to_service().
1684 1685 1686
 *
 * Since: 2.22
 */
1687 1688
void
g_socket_client_connect_to_service_async (GSocketClient       *client,
1689 1690
					  const gchar         *domain,
					  const gchar         *service,
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703
					  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);
}

1704 1705 1706 1707 1708
/**
 * g_socket_client_connect_to_uri_async:
 * @client: a #GSocketClient
 * @uri: a network uri
 * @default_port: the default port to connect to
1709 1710 1711
 * @cancellable: (allow-none): a #GCancellable, or %NULL
 * @callback: (scope async): a #GAsyncReadyCallback
 * @user_data: (closure): user data for the callback
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735
 *
 * 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)
    {
1736
      g_simple_async_report_take_gerror_in_idle (G_OBJECT (client),
1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748
					    callback, user_data, error);
    }
  else
    {
      g_socket_client_connect_async (client,
				     connectable, cancellable,
				     callback, user_data);
      g_object_unref (connectable);
    }
}


1749 1750 1751 1752
/**
 * g_socket_client_connect_finish:
 * @client: a #GSocketClient.
 * @result: a #GAsyncResult.
1753
 * @error: a #GError location to store the error occurring, or %NULL to
1754 1755 1756 1757
 * ignore.
 *
 * Finishes an async connect operation. See g_socket_client_connect_async()
 *
1758
 * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
1759 1760
 *
 * Since: 2.22
1761
 */
1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778
GSocketConnection *
g_socket_client_connect_finish (GSocketClient  *client,
				GAsyncResult   *result,
				GError        **error)
{
  GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);

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

  return g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
}

/**
 * g_socket_client_connect_to_host_finish:
 * @client: a #GSocketClient.
 * @result: a #GAsyncResult.
1779
 * @error: a #GError location to store the error occurring, or %NULL to
1780 1781 1782 1783
 * ignore.
 *
 * Finishes an async connect operation. See g_socket_client_connect_to_host_async()
 *
1784
 * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
1785 1786
 *
 * Since: 2.22
1787
 */
1788
GSocketConnection *
1789 1790 1791
g_socket_client_connect_to_host_finish (GSocketClient  *client,
					GAsyncResult   *result,
					GError        **error)
1792 1793 1794 1795
{
  return g_socket_client_connect_finish (client, result, error);
}

1796 1797 1798 1799
/**
 * g_socket_client_connect_to_service_finish:
 * @client: a #GSocketClient.
 * @result: a #GAsyncResult.
1800
 * @error: a #GError location to store the error occurring, or %NULL to
1801 1802 1803 1804
 * ignore.
 *
 * Finishes an async connect operation. See g_socket_client_connect_to_service_async()
 *
1805
 * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
1806 1807
 *
 * Since: 2.22
1808
 */
1809
GSocketConnection *
1810 1811 1812
g_socket_client_connect_to_service_finish (GSocketClient  *client,
					   GAsyncResult   *result,
					   GError        **error)
1813 1814 1815
{
  return g_socket_client_connect_finish (client, result, error);
}
1816 1817 1818 1819 1820

/**
 * g_socket_client_connect_to_uri_finish:
 * @client: a #GSocketClient.
 * @result: a #GAsyncResult.
1821
 * @error: a #GError location to store the error occurring, or %NULL to
1822 1823 1824 1825
 * ignore.
 *
 * Finishes an async connect operation. See g_socket_client_connect_to_uri_async()
 *
1826
 * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
1827 1828 1829 1830 1831 1832 1833 1834 1835 1836
 *
 * Since: 2.26
 */
GSocketConnection *
g_socket_client_connect_to_uri_finish (GSocketClient  *client,
				       GAsyncResult   *result,
				       GError        **error)
{
  return g_socket_client_connect_finish (client, result, error);
}
1837 1838 1839 1840 1841 1842 1843 1844 1845

/**
 * g_socket_client_add_application_proxy:
 * @client: a #GSocketClient
 * @protocol: The proxy protocol
 *
 * Enable proxy protocols to be handled by the application. When the
 * indicated proxy protocol is returned by the #GProxyResolver,
 * #GSocketClient will consider this protocol as supported but will
1846
 * not try to find a #GProxy instance to handle handshaking. The
1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857
 * application must check for this case by calling
 * g_socket_connection_get_remote_address() on the returned
 * #GSocketConnection, and seeing if it's a #GProxyAddress of the
 * appropriate type, to determine whether or not it needs to handle
 * the proxy handshaking itself.
 *
 * This should be used for proxy protocols that are dialects of
 * another protocol such as HTTP proxy. It also allows cohabitation of
 * proxy protocols that are reused between protocols. A good example
 * is HTTP. It can be used to proxy HTTP, FTP and Gopher and can also
 * be use as generic socket proxy through the HTTP CONNECT method.
1858 1859 1860 1861
 *
 * When the proxy is detected as being an application proxy, TLS handshake
 * will be skipped. This is required to let the application do the proxy
 * specific handshake.
1862 1863 1864 1865 1866 1867 1868
 */
void
g_socket_client_add_application_proxy (GSocketClient *client,
			               const gchar   *protocol)
{
  g_hash_table_insert (client->priv->app_proxies, g_strdup (protocol), NULL);
}