1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright © 2008, 2009 codethink
4 * Copyright © 2009 Red Hat, Inc
5 * Copyright © 2018 Igalia S.L.
7 * SPDX-License-Identifier: LGPL-2.1-or-later
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General
20 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
22 * Authors: Ryan Lortie <desrt@desrt.ca>
23 * Alexander Larsson <alexl@redhat.com>
27 #include "gsocketclient.h"
30 #include <netinet/in.h>
36 #include <gio/gioenumtypes.h>
37 #include <gio/gsocketaddressenumerator.h>
38 #include <gio/gsocketconnectable.h>
39 #include <gio/gsocketconnection.h>
40 #include <gio/gioprivate.h>
41 #include <gio/gproxyaddressenumerator.h>
42 #include <gio/gproxyaddress.h>
43 #include <gio/gtask.h>
44 #include <gio/gcancellable.h>
45 #include <gio/gioerror.h>
46 #include <gio/gsocket.h>
47 #include <gio/gnetworkaddress.h>
48 #include <gio/gnetworking.h>
49 #include <gio/gnetworkservice.h>
50 #include <gio/gproxy.h>
51 #include <gio/gproxyresolver.h>
52 #include <gio/gsocketaddress.h>
53 #include <gio/gtcpconnection.h>
54 #include <gio/gtcpwrapperconnection.h>
55 #include <gio/gtlscertificate.h>
56 #include <gio/gtlsclientconnection.h>
57 #include <gio/ginetaddress.h>
59 #include "gmarshal-internal.h"
61 /* As recommended by RFC 8305 this is the time it waits
62 * on a connection before starting another concurrent attempt.
64 #define HAPPY_EYEBALLS_CONNECTION_ATTEMPT_TIMEOUT_MS 250
67 * SECTION:gsocketclient
68 * @short_description: Helper for connecting to a network service
70 * @see_also: #GSocketConnection, #GSocketListener
72 * #GSocketClient is a lightweight high-level utility class for connecting to
73 * a network host using a connection oriented socket type.
75 * You create a #GSocketClient object, set any options you want, and then
76 * call a sync or async connect operation, which returns a #GSocketConnection
77 * subclass on success.
79 * The type of the #GSocketConnection object returned depends on the type of
80 * the underlying socket that is in use. For instance, for a TCP/IP connection
81 * it will be a #GTcpConnection.
83 * As #GSocketClient is a lightweight object, you don't need to cache it. You
84 * can just create a new one any time you need one.
96 static guint signals[LAST_SIGNAL] = { 0 };
108 PROP_TLS_VALIDATION_FLAGS,
112 struct _GSocketClientPrivate
114 GSocketFamily family;
116 GSocketProtocol protocol;
117 GSocketAddress *local_address;
119 gboolean enable_proxy;
120 GHashTable *app_proxies;
122 GTlsCertificateFlags tls_validation_flags;
123 GProxyResolver *proxy_resolver;
126 G_DEFINE_TYPE_WITH_PRIVATE (GSocketClient, g_socket_client, G_TYPE_OBJECT)
129 create_socket (GSocketClient *client,
130 GSocketAddress *dest_address,
133 GSocketFamily family;
136 family = client->priv->family;
137 if (family == G_SOCKET_FAMILY_INVALID &&
138 client->priv->local_address != NULL)
139 family = g_socket_address_get_family (client->priv->local_address);
140 if (family == G_SOCKET_FAMILY_INVALID)
141 family = g_socket_address_get_family (dest_address);
143 socket = g_socket_new (family,
145 client->priv->protocol,
150 if (client->priv->local_address)
152 #ifdef IP_BIND_ADDRESS_NO_PORT
153 g_socket_set_option (socket, IPPROTO_IP, IP_BIND_ADDRESS_NO_PORT, 1, NULL);
156 if (!g_socket_bind (socket,
157 client->priv->local_address,
161 g_object_unref (socket);
166 if (client->priv->timeout)
167 g_socket_set_timeout (socket, client->priv->timeout);
173 can_use_proxy (GSocketClient *client)
175 GSocketClientPrivate *priv = client->priv;
177 return priv->enable_proxy
178 && priv->type == G_SOCKET_TYPE_STREAM;
182 clarify_connect_error (GError *error,
183 GSocketConnectable *connectable,
184 GSocketAddress *address)
187 char *tmp_name = NULL;
189 if (G_IS_PROXY_ADDRESS (address))
191 name = tmp_name = g_inet_address_to_string (g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (address)));
193 g_prefix_error (&error, _("Could not connect to proxy server %s: "), name);
197 if (G_IS_NETWORK_ADDRESS (connectable))
198 name = g_network_address_get_hostname (G_NETWORK_ADDRESS (connectable));
199 else if (G_IS_NETWORK_SERVICE (connectable))
200 name = g_network_service_get_domain (G_NETWORK_SERVICE (connectable));
201 else if (G_IS_INET_SOCKET_ADDRESS (connectable))
202 name = tmp_name = g_inet_address_to_string (g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (connectable)));
207 g_prefix_error (&error, _("Could not connect to %s: "), name);
209 g_prefix_error (&error, _("Could not connect: "));
216 g_socket_client_init (GSocketClient *client)
218 client->priv = g_socket_client_get_instance_private (client);
219 client->priv->type = G_SOCKET_TYPE_STREAM;
220 client->priv->app_proxies = g_hash_table_new_full (g_str_hash,
227 * g_socket_client_new:
229 * Creates a new #GSocketClient with the default options.
231 * Returns: a #GSocketClient.
232 * Free the returned object with g_object_unref().
237 g_socket_client_new (void)
239 return g_object_new (G_TYPE_SOCKET_CLIENT, NULL);
243 g_socket_client_finalize (GObject *object)
245 GSocketClient *client = G_SOCKET_CLIENT (object);
247 g_clear_object (&client->priv->local_address);
248 g_clear_object (&client->priv->proxy_resolver);
250 G_OBJECT_CLASS (g_socket_client_parent_class)->finalize (object);
252 g_hash_table_unref (client->priv->app_proxies);
256 g_socket_client_get_property (GObject *object,
261 GSocketClient *client = G_SOCKET_CLIENT (object);
266 g_value_set_enum (value, client->priv->family);
270 g_value_set_enum (value, client->priv->type);
274 g_value_set_enum (value, client->priv->protocol);
277 case PROP_LOCAL_ADDRESS:
278 g_value_set_object (value, client->priv->local_address);
282 g_value_set_uint (value, client->priv->timeout);
285 case PROP_ENABLE_PROXY:
286 g_value_set_boolean (value, client->priv->enable_proxy);
290 g_value_set_boolean (value, g_socket_client_get_tls (client));
293 case PROP_TLS_VALIDATION_FLAGS:
294 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
295 g_value_set_flags (value, g_socket_client_get_tls_validation_flags (client));
296 G_GNUC_END_IGNORE_DEPRECATIONS
299 case PROP_PROXY_RESOLVER:
300 g_value_set_object (value, g_socket_client_get_proxy_resolver (client));
304 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
309 g_socket_client_set_property (GObject *object,
314 GSocketClient *client = G_SOCKET_CLIENT (object);
319 g_socket_client_set_family (client, g_value_get_enum (value));
323 g_socket_client_set_socket_type (client, g_value_get_enum (value));
327 g_socket_client_set_protocol (client, g_value_get_enum (value));
330 case PROP_LOCAL_ADDRESS:
331 g_socket_client_set_local_address (client, g_value_get_object (value));
335 g_socket_client_set_timeout (client, g_value_get_uint (value));
338 case PROP_ENABLE_PROXY:
339 g_socket_client_set_enable_proxy (client, g_value_get_boolean (value));
343 g_socket_client_set_tls (client, g_value_get_boolean (value));
346 case PROP_TLS_VALIDATION_FLAGS:
347 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
348 g_socket_client_set_tls_validation_flags (client, g_value_get_flags (value));
349 G_GNUC_END_IGNORE_DEPRECATIONS
352 case PROP_PROXY_RESOLVER:
353 g_socket_client_set_proxy_resolver (client, g_value_get_object (value));
357 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
362 * g_socket_client_get_family:
363 * @client: a #GSocketClient.
365 * Gets the socket family of the socket client.
367 * See g_socket_client_set_family() for details.
369 * Returns: a #GSocketFamily
374 g_socket_client_get_family (GSocketClient *client)
376 return client->priv->family;
380 * g_socket_client_set_family:
381 * @client: a #GSocketClient.
382 * @family: a #GSocketFamily
384 * Sets the socket family of the socket client.
385 * If this is set to something other than %G_SOCKET_FAMILY_INVALID
386 * then the sockets created by this object will be of the specified
389 * This might be useful for instance if you want to force the local
390 * connection to be an ipv4 socket, even though the address might
391 * be an ipv6 mapped to ipv4 address.
396 g_socket_client_set_family (GSocketClient *client,
397 GSocketFamily family)
399 if (client->priv->family == family)
402 client->priv->family = family;
403 g_object_notify (G_OBJECT (client), "family");
407 * g_socket_client_get_socket_type:
408 * @client: a #GSocketClient.
410 * Gets the socket type of the socket client.
412 * See g_socket_client_set_socket_type() for details.
414 * Returns: a #GSocketFamily
419 g_socket_client_get_socket_type (GSocketClient *client)
421 return client->priv->type;
425 * g_socket_client_set_socket_type:
426 * @client: a #GSocketClient.
427 * @type: a #GSocketType
429 * Sets the socket type of the socket client.
430 * The sockets created by this object will be of the specified
433 * It doesn't make sense to specify a type of %G_SOCKET_TYPE_DATAGRAM,
434 * as GSocketClient is used for connection oriented services.
439 g_socket_client_set_socket_type (GSocketClient *client,
442 if (client->priv->type == type)
445 client->priv->type = type;
446 g_object_notify (G_OBJECT (client), "type");
450 * g_socket_client_get_protocol:
451 * @client: a #GSocketClient
453 * Gets the protocol name type of the socket client.
455 * See g_socket_client_set_protocol() for details.
457 * Returns: a #GSocketProtocol
462 g_socket_client_get_protocol (GSocketClient *client)
464 return client->priv->protocol;
468 * g_socket_client_set_protocol:
469 * @client: a #GSocketClient.
470 * @protocol: a #GSocketProtocol
472 * Sets the protocol of the socket client.
473 * The sockets created by this object will use of the specified
476 * If @protocol is %G_SOCKET_PROTOCOL_DEFAULT that means to use the default
477 * protocol for the socket family and type.
482 g_socket_client_set_protocol (GSocketClient *client,
483 GSocketProtocol protocol)
485 if (client->priv->protocol == protocol)
488 client->priv->protocol = protocol;
489 g_object_notify (G_OBJECT (client), "protocol");
493 * g_socket_client_get_local_address:
494 * @client: a #GSocketClient.
496 * Gets the local address of the socket client.
498 * See g_socket_client_set_local_address() for details.
500 * Returns: (nullable) (transfer none): a #GSocketAddress or %NULL. Do not free.
505 g_socket_client_get_local_address (GSocketClient *client)
507 return client->priv->local_address;
511 * g_socket_client_set_local_address:
512 * @client: a #GSocketClient.
513 * @address: (nullable): a #GSocketAddress, or %NULL
515 * Sets the local address of the socket client.
516 * The sockets created by this object will bound to the
517 * specified address (if not %NULL) before connecting.
519 * This is useful if you want to ensure that the local
520 * side of the connection is on a specific port, or on
521 * a specific interface.
526 g_socket_client_set_local_address (GSocketClient *client,
527 GSocketAddress *address)
530 g_object_ref (address);
532 if (client->priv->local_address)
534 g_object_unref (client->priv->local_address);
536 client->priv->local_address = address;
537 g_object_notify (G_OBJECT (client), "local-address");
541 * g_socket_client_get_timeout:
542 * @client: a #GSocketClient
544 * Gets the I/O timeout time for sockets created by @client.
546 * See g_socket_client_set_timeout() for details.
548 * Returns: the timeout in seconds
553 g_socket_client_get_timeout (GSocketClient *client)
555 return client->priv->timeout;
560 * g_socket_client_set_timeout:
561 * @client: a #GSocketClient.
562 * @timeout: the timeout
564 * Sets the I/O timeout for sockets created by @client. @timeout is a
565 * time in seconds, or 0 for no timeout (the default).
567 * The timeout value affects the initial connection attempt as well,
568 * so setting this may cause calls to g_socket_client_connect(), etc,
569 * to fail with %G_IO_ERROR_TIMED_OUT.
574 g_socket_client_set_timeout (GSocketClient *client,
577 if (client->priv->timeout == timeout)
580 client->priv->timeout = timeout;
581 g_object_notify (G_OBJECT (client), "timeout");
585 * g_socket_client_get_enable_proxy:
586 * @client: a #GSocketClient.
588 * Gets the proxy enable state; see g_socket_client_set_enable_proxy()
590 * Returns: whether proxying is enabled
595 g_socket_client_get_enable_proxy (GSocketClient *client)
597 return client->priv->enable_proxy;
601 * g_socket_client_set_enable_proxy:
602 * @client: a #GSocketClient.
603 * @enable: whether to enable proxies
605 * Sets whether or not @client attempts to make connections via a
606 * proxy server. When enabled (the default), #GSocketClient will use a
607 * #GProxyResolver to determine if a proxy protocol such as SOCKS is
608 * needed, and automatically do the necessary proxy negotiation.
610 * See also g_socket_client_set_proxy_resolver().
615 g_socket_client_set_enable_proxy (GSocketClient *client,
619 if (client->priv->enable_proxy == enable)
622 client->priv->enable_proxy = enable;
623 g_object_notify (G_OBJECT (client), "enable-proxy");
627 * g_socket_client_get_tls:
628 * @client: a #GSocketClient.
630 * Gets whether @client creates TLS connections. See
631 * g_socket_client_set_tls() for details.
633 * Returns: whether @client uses TLS
638 g_socket_client_get_tls (GSocketClient *client)
640 return client->priv->tls;
644 * g_socket_client_set_tls:
645 * @client: a #GSocketClient.
646 * @tls: whether to use TLS
648 * Sets whether @client creates TLS (aka SSL) connections. If @tls is
649 * %TRUE, @client will wrap its connections in a #GTlsClientConnection
650 * and perform a TLS handshake when connecting.
652 * Note that since #GSocketClient must return a #GSocketConnection,
653 * but #GTlsClientConnection is not a #GSocketConnection, this
654 * actually wraps the resulting #GTlsClientConnection in a
655 * #GTcpWrapperConnection when returning it. You can use
656 * g_tcp_wrapper_connection_get_base_io_stream() on the return value
657 * to extract the #GTlsClientConnection.
659 * If you need to modify the behavior of the TLS handshake (eg, by
660 * setting a client-side certificate to use, or connecting to the
661 * #GTlsConnection::accept-certificate signal), you can connect to
662 * @client's #GSocketClient::event signal and wait for it to be
663 * emitted with %G_SOCKET_CLIENT_TLS_HANDSHAKING, which will give you
664 * a chance to see the #GTlsClientConnection before the handshake
670 g_socket_client_set_tls (GSocketClient *client,
674 if (tls == client->priv->tls)
677 client->priv->tls = tls;
678 g_object_notify (G_OBJECT (client), "tls");
682 * g_socket_client_get_tls_validation_flags:
683 * @client: a #GSocketClient.
685 * Gets the TLS validation flags used creating TLS connections via
688 * This function does not work as originally designed and is impossible
689 * to use correctly. See #GSocketClient:tls-validation-flags for more
692 * Returns: the TLS validation flags
696 * Deprecated: 2.72: Do not attempt to ignore validation errors.
699 g_socket_client_get_tls_validation_flags (GSocketClient *client)
701 return client->priv->tls_validation_flags;
705 * g_socket_client_set_tls_validation_flags:
706 * @client: a #GSocketClient.
707 * @flags: the validation flags
709 * Sets the TLS validation flags used when creating TLS connections
710 * via @client. The default value is %G_TLS_CERTIFICATE_VALIDATE_ALL.
712 * This function does not work as originally designed and is impossible
713 * to use correctly. See #GSocketClient:tls-validation-flags for more
718 * Deprecated: 2.72: Do not attempt to ignore validation errors.
721 g_socket_client_set_tls_validation_flags (GSocketClient *client,
722 GTlsCertificateFlags flags)
724 if (client->priv->tls_validation_flags != flags)
726 client->priv->tls_validation_flags = flags;
727 g_object_notify (G_OBJECT (client), "tls-validation-flags");
732 * g_socket_client_get_proxy_resolver:
733 * @client: a #GSocketClient.
735 * Gets the #GProxyResolver being used by @client. Normally, this will
736 * be the resolver returned by g_proxy_resolver_get_default(), but you
737 * can override it with g_socket_client_set_proxy_resolver().
739 * Returns: (transfer none): The #GProxyResolver being used by
745 g_socket_client_get_proxy_resolver (GSocketClient *client)
747 if (client->priv->proxy_resolver)
748 return client->priv->proxy_resolver;
750 return g_proxy_resolver_get_default ();
754 * g_socket_client_set_proxy_resolver:
755 * @client: a #GSocketClient.
756 * @proxy_resolver: (nullable): a #GProxyResolver, or %NULL for the
759 * Overrides the #GProxyResolver used by @client. You can call this if
760 * you want to use specific proxies, rather than using the system
761 * default proxy settings.
763 * Note that whether or not the proxy resolver is actually used
764 * depends on the setting of #GSocketClient:enable-proxy, which is not
765 * changed by this function (but which is %TRUE by default)
770 g_socket_client_set_proxy_resolver (GSocketClient *client,
771 GProxyResolver *proxy_resolver)
773 /* We have to be careful to avoid calling
774 * g_proxy_resolver_get_default() until we're sure we need it,
775 * because trying to load the default proxy resolver module will
776 * break some test programs that aren't expecting it (eg,
780 if (client->priv->proxy_resolver)
781 g_object_unref (client->priv->proxy_resolver);
783 client->priv->proxy_resolver = proxy_resolver;
785 if (client->priv->proxy_resolver)
786 g_object_ref (client->priv->proxy_resolver);
790 g_socket_client_class_init (GSocketClientClass *class)
792 GObjectClass *gobject_class = G_OBJECT_CLASS (class);
794 gobject_class->finalize = g_socket_client_finalize;
795 gobject_class->set_property = g_socket_client_set_property;
796 gobject_class->get_property = g_socket_client_get_property;
799 * GSocketClient::event:
800 * @client: the #GSocketClient
801 * @event: the event that is occurring
802 * @connectable: the #GSocketConnectable that @event is occurring on
803 * @connection: (nullable): the current representation of the connection
805 * Emitted when @client's activity on @connectable changes state.
806 * Among other things, this can be used to provide progress
807 * information about a network connection in the UI. The meanings of
808 * the different @event values are as follows:
810 * - %G_SOCKET_CLIENT_RESOLVING: @client is about to look up @connectable
811 * in DNS. @connection will be %NULL.
813 * - %G_SOCKET_CLIENT_RESOLVED: @client has successfully resolved
814 * @connectable in DNS. @connection will be %NULL.
816 * - %G_SOCKET_CLIENT_CONNECTING: @client is about to make a connection
817 * to a remote host; either a proxy server or the destination server
818 * itself. @connection is the #GSocketConnection, which is not yet
819 * connected. Since GLib 2.40, you can access the remote
820 * address via g_socket_connection_get_remote_address().
822 * - %G_SOCKET_CLIENT_CONNECTED: @client has successfully connected
823 * to a remote host. @connection is the connected #GSocketConnection.
825 * - %G_SOCKET_CLIENT_PROXY_NEGOTIATING: @client is about to negotiate
826 * with a proxy to get it to connect to @connectable. @connection is
827 * the #GSocketConnection to the proxy server.
829 * - %G_SOCKET_CLIENT_PROXY_NEGOTIATED: @client has negotiated a
830 * connection to @connectable through a proxy server. @connection is
831 * the stream returned from g_proxy_connect(), which may or may not
832 * be a #GSocketConnection.
834 * - %G_SOCKET_CLIENT_TLS_HANDSHAKING: @client is about to begin a TLS
835 * handshake. @connection is a #GTlsClientConnection.
837 * - %G_SOCKET_CLIENT_TLS_HANDSHAKED: @client has successfully completed
838 * the TLS handshake. @connection is a #GTlsClientConnection.
840 * - %G_SOCKET_CLIENT_COMPLETE: @client has either successfully connected
841 * to @connectable (in which case @connection is the #GSocketConnection
842 * that it will be returning to the caller) or has failed (in which
843 * case @connection is %NULL and the client is about to return an error).
845 * Each event except %G_SOCKET_CLIENT_COMPLETE may be emitted
846 * multiple times (or not at all) for a given connectable (in
847 * particular, if @client ends up attempting to connect to more than
848 * one address). However, if @client emits the #GSocketClient::event
849 * signal at all for a given connectable, then it will always emit
850 * it with %G_SOCKET_CLIENT_COMPLETE when it is done.
852 * Note that there may be additional #GSocketClientEvent values in
853 * the future; unrecognized @event values should be ignored.
858 g_signal_new (I_("event"),
859 G_TYPE_FROM_CLASS (gobject_class),
861 G_STRUCT_OFFSET (GSocketClientClass, event),
863 _g_cclosure_marshal_VOID__ENUM_OBJECT_OBJECT,
865 G_TYPE_SOCKET_CLIENT_EVENT,
866 G_TYPE_SOCKET_CONNECTABLE,
868 g_signal_set_va_marshaller (signals[EVENT],
869 G_TYPE_FROM_CLASS (class),
870 _g_cclosure_marshal_VOID__ENUM_OBJECT_OBJECTv);
872 g_object_class_install_property (gobject_class, PROP_FAMILY,
873 g_param_spec_enum ("family",
875 P_("The sockets address family to use for socket construction"),
876 G_TYPE_SOCKET_FAMILY,
877 G_SOCKET_FAMILY_INVALID,
880 G_PARAM_STATIC_STRINGS));
882 g_object_class_install_property (gobject_class, PROP_TYPE,
883 g_param_spec_enum ("type",
885 P_("The sockets type to use for socket construction"),
887 G_SOCKET_TYPE_STREAM,
890 G_PARAM_STATIC_STRINGS));
892 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
893 g_param_spec_enum ("protocol",
894 P_("Socket protocol"),
895 P_("The protocol to use for socket construction, or 0 for default"),
896 G_TYPE_SOCKET_PROTOCOL,
897 G_SOCKET_PROTOCOL_DEFAULT,
900 G_PARAM_STATIC_STRINGS));
902 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
903 g_param_spec_object ("local-address",
905 P_("The local address constructed sockets will be bound to"),
906 G_TYPE_SOCKET_ADDRESS,
909 G_PARAM_STATIC_STRINGS));
911 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
912 g_param_spec_uint ("timeout",
913 P_("Socket timeout"),
914 P_("The I/O timeout for sockets, or 0 for none"),
918 G_PARAM_STATIC_STRINGS));
920 g_object_class_install_property (gobject_class, PROP_ENABLE_PROXY,
921 g_param_spec_boolean ("enable-proxy",
923 P_("Enable proxy support"),
927 G_PARAM_STATIC_STRINGS));
929 g_object_class_install_property (gobject_class, PROP_TLS,
930 g_param_spec_boolean ("tls",
932 P_("Whether to create TLS connections"),
936 G_PARAM_STATIC_STRINGS));
939 * GSocketClient:tls-validation-flags:
941 * The TLS validation flags used when creating TLS connections. The
942 * default value is %G_TLS_CERTIFICATE_VALIDATE_ALL.
944 * GLib guarantees that if certificate verification fails, at least one
945 * flag will be set, but it does not guarantee that all possible flags
946 * will be set. Accordingly, you may not safely decide to ignore any
947 * particular type of error. For example, it would be incorrect to mask
948 * %G_TLS_CERTIFICATE_EXPIRED if you want to allow expired certificates,
949 * because this could potentially be the only error flag set even if
950 * other problems exist with the certificate. Therefore, there is no
951 * safe way to use this property. This is not a horrible problem,
952 * though, because you should not be attempting to ignore validation
953 * errors anyway. If you really must ignore TLS certificate errors,
954 * connect to the #GSocketClient::event signal, wait for it to be
955 * emitted with %G_SOCKET_CLIENT_TLS_HANDSHAKING, and use that to
956 * connect to #GTlsConnection::accept-certificate.
958 * Deprecated: 2.72: Do not attempt to ignore validation errors.
960 g_object_class_install_property (gobject_class, PROP_TLS_VALIDATION_FLAGS,
961 g_param_spec_flags ("tls-validation-flags",
962 P_("TLS validation flags"),
963 P_("TLS validation flags to use"),
964 G_TYPE_TLS_CERTIFICATE_FLAGS,
965 G_TLS_CERTIFICATE_VALIDATE_ALL,
968 G_PARAM_STATIC_STRINGS |
969 G_PARAM_DEPRECATED));
972 * GSocketClient:proxy-resolver:
974 * The proxy resolver to use
978 g_object_class_install_property (gobject_class, PROP_PROXY_RESOLVER,
979 g_param_spec_object ("proxy-resolver",
980 P_("Proxy resolver"),
981 P_("The proxy resolver to use"),
982 G_TYPE_PROXY_RESOLVER,
985 G_PARAM_STATIC_STRINGS));
989 g_socket_client_emit_event (GSocketClient *client,
990 GSocketClientEvent event,
991 GSocketConnectable *connectable,
992 GIOStream *connection)
994 g_signal_emit (client, signals[EVENT], 0,
995 event, connectable, connection);
998 /* Originally, GSocketClient returned whatever error occured last. Turns
999 * out this doesn't work well in practice. Consider the following case:
1000 * DNS returns an IPv4 and IPv6 address. First we'll connect() to the
1001 * IPv4 address, and say that succeeds, but TLS is enabled and the TLS
1002 * handshake fails. Then we try the IPv6 address and receive ENETUNREACH
1003 * because IPv6 isn't supported. We wind up returning NETWORK_UNREACHABLE
1004 * even though the address can be pinged and a TLS error would be more
1005 * appropriate. So instead, we now try to return the error corresponding
1006 * to the latest attempted GSocketClientEvent in the connection process.
1007 * TLS errors take precedence over proxy errors, which take precedence
1008 * over connect() errors, which take precedence over DNS errors.
1010 * Note that the example above considers a sync codepath, but this is an
1011 * issue for the async codepath too, where events and errors may occur
1012 * in confusing orders.
1018 GSocketClientEvent best_error_event;
1019 } SocketClientErrorInfo;
1021 static SocketClientErrorInfo *
1022 socket_client_error_info_new (void)
1024 return g_new0 (SocketClientErrorInfo, 1);
1028 socket_client_error_info_free (SocketClientErrorInfo *info)
1030 g_assert (info->tmp_error == NULL);
1031 g_clear_error (&info->best_error);
1036 consider_tmp_error (SocketClientErrorInfo *info,
1037 GSocketClientEvent event)
1039 if (info->tmp_error == NULL)
1042 /* If we ever add more GSocketClientEvents in the future, then we'll
1043 * no longer be able to use >= for this comparison, because future
1044 * events will compare greater than G_SOCKET_CLIENT_COMPLETE. Until
1045 * then, this is convenient. Note G_SOCKET_CLIENT_RESOLVING is 0 so we
1046 * need to use >= here or those errors would never be set. That means
1047 * if we get two errors on the same GSocketClientEvent, we wind up
1048 * preferring the last one, which is fine.
1050 g_assert (event <= G_SOCKET_CLIENT_COMPLETE);
1051 if (event >= info->best_error_event)
1053 g_clear_error (&info->best_error);
1054 info->best_error = info->tmp_error;
1055 info->tmp_error = NULL;
1056 info->best_error_event = event;
1060 g_clear_error (&info->tmp_error);
1065 * g_socket_client_connect:
1066 * @client: a #GSocketClient.
1067 * @connectable: a #GSocketConnectable specifying the remote address.
1068 * @cancellable: (nullable): optional #GCancellable object, %NULL to ignore.
1069 * @error: #GError for error reporting, or %NULL to ignore.
1071 * Tries to resolve the @connectable and make a network connection to it.
1073 * Upon a successful connection, a new #GSocketConnection is constructed
1074 * and returned. The caller owns this new object and must drop their
1075 * reference to it when finished with it.
1077 * The type of the #GSocketConnection object returned depends on the type of
1078 * the underlying socket that is used. For instance, for a TCP/IP connection
1079 * it will be a #GTcpConnection.
1081 * The socket created will be the same family as the address that the
1082 * @connectable resolves to, unless family is set with g_socket_client_set_family()
1083 * or indirectly via g_socket_client_set_local_address(). The socket type
1084 * defaults to %G_SOCKET_TYPE_STREAM but can be set with
1085 * g_socket_client_set_socket_type().
1087 * If a local address is specified with g_socket_client_set_local_address() the
1088 * socket will be bound to this address before connecting.
1090 * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
1095 g_socket_client_connect (GSocketClient *client,
1096 GSocketConnectable *connectable,
1097 GCancellable *cancellable,
1100 GIOStream *connection = NULL;
1101 GSocketAddressEnumerator *enumerator = NULL;
1102 SocketClientErrorInfo *error_info;
1103 gboolean ever_resolved = FALSE;
1105 error_info = socket_client_error_info_new ();
1107 if (can_use_proxy (client))
1109 enumerator = g_socket_connectable_proxy_enumerate (connectable);
1110 if (client->priv->proxy_resolver &&
1111 G_IS_PROXY_ADDRESS_ENUMERATOR (enumerator))
1113 g_object_set (G_OBJECT (enumerator),
1114 "proxy-resolver", client->priv->proxy_resolver,
1119 enumerator = g_socket_connectable_enumerate (connectable);
1121 while (connection == NULL)
1123 GSocketAddress *address = NULL;
1124 gboolean application_proxy = FALSE;
1126 gboolean using_proxy;
1128 if (g_cancellable_is_cancelled (cancellable))
1130 g_clear_error (&error_info->best_error);
1131 g_cancellable_set_error_if_cancelled (cancellable, &error_info->best_error);
1137 g_socket_client_emit_event (client, G_SOCKET_CLIENT_RESOLVING,
1140 address = g_socket_address_enumerator_next (enumerator, cancellable,
1141 &error_info->tmp_error);
1142 consider_tmp_error (error_info, G_SOCKET_CLIENT_RESOLVING);
1145 g_socket_client_emit_event (client, G_SOCKET_CLIENT_RESOLVED,
1147 ever_resolved = TRUE;
1150 if (address == NULL)
1152 /* Enumeration is finished. */
1153 g_assert (&error_info->best_error != NULL);
1157 using_proxy = (G_IS_PROXY_ADDRESS (address) &&
1158 client->priv->enable_proxy);
1160 socket = create_socket (client, address, &error_info->tmp_error);
1161 consider_tmp_error (error_info, G_SOCKET_CLIENT_CONNECTING);
1164 g_object_unref (address);
1168 connection = (GIOStream *)g_socket_connection_factory_create_connection (socket);
1169 g_socket_connection_set_cached_remote_address ((GSocketConnection*)connection, address);
1170 g_socket_client_emit_event (client, G_SOCKET_CLIENT_CONNECTING, connectable, connection);
1172 if (g_socket_connection_connect (G_SOCKET_CONNECTION (connection),
1173 address, cancellable, &error_info->tmp_error))
1175 g_socket_connection_set_cached_remote_address ((GSocketConnection*)connection, NULL);
1176 g_socket_client_emit_event (client, G_SOCKET_CLIENT_CONNECTED, connectable, connection);
1180 clarify_connect_error (error_info->tmp_error, connectable, address);
1181 consider_tmp_error (error_info, G_SOCKET_CLIENT_CONNECTING);
1182 g_object_unref (connection);
1186 if (connection && using_proxy)
1188 GProxyAddress *proxy_addr = G_PROXY_ADDRESS (address);
1189 const gchar *protocol;
1192 protocol = g_proxy_address_get_protocol (proxy_addr);
1194 /* The connection should not be anything else then TCP Connection,
1195 * but let's put a safety guard in case
1197 if (!G_IS_TCP_CONNECTION (connection))
1199 g_critical ("Trying to proxy over non-TCP connection, this is "
1200 "most likely a bug in GLib IO library.");
1202 g_set_error_literal (&error_info->tmp_error,
1203 G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1204 _("Proxying over a non-TCP connection is not supported."));
1205 consider_tmp_error (error_info, G_SOCKET_CLIENT_PROXY_NEGOTIATING);
1207 g_object_unref (connection);
1210 else if (g_hash_table_contains (client->priv->app_proxies, protocol))
1212 application_proxy = TRUE;
1214 else if ((proxy = g_proxy_get_default_for_protocol (protocol)))
1216 GIOStream *proxy_connection;
1218 g_socket_client_emit_event (client, G_SOCKET_CLIENT_PROXY_NEGOTIATING, connectable, connection);
1219 proxy_connection = g_proxy_connect (proxy,
1223 &error_info->tmp_error);
1224 consider_tmp_error (error_info, G_SOCKET_CLIENT_PROXY_NEGOTIATING);
1226 g_object_unref (connection);
1227 connection = proxy_connection;
1228 g_object_unref (proxy);
1231 g_socket_client_emit_event (client, G_SOCKET_CLIENT_PROXY_NEGOTIATED, connectable, connection);
1235 g_set_error (&error_info->tmp_error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1236 _("Proxy protocol “%s” is not supported."),
1238 consider_tmp_error (error_info, G_SOCKET_CLIENT_PROXY_NEGOTIATING);
1239 g_object_unref (connection);
1244 if (!application_proxy && connection && client->priv->tls)
1248 tlsconn = g_tls_client_connection_new (connection, connectable, &error_info->tmp_error);
1249 g_object_unref (connection);
1250 connection = tlsconn;
1254 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
1255 g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (tlsconn),
1256 client->priv->tls_validation_flags);
1257 G_GNUC_END_IGNORE_DEPRECATIONS
1258 g_socket_client_emit_event (client, G_SOCKET_CLIENT_TLS_HANDSHAKING, connectable, connection);
1259 if (g_tls_connection_handshake (G_TLS_CONNECTION (tlsconn),
1260 cancellable, &error_info->tmp_error))
1262 g_socket_client_emit_event (client, G_SOCKET_CLIENT_TLS_HANDSHAKED, connectable, connection);
1266 consider_tmp_error (error_info, G_SOCKET_CLIENT_TLS_HANDSHAKING);
1267 g_object_unref (tlsconn);
1273 consider_tmp_error (error_info, G_SOCKET_CLIENT_TLS_HANDSHAKING);
1277 if (connection && !G_IS_SOCKET_CONNECTION (connection))
1279 GSocketConnection *wrapper_connection;
1281 wrapper_connection = g_tcp_wrapper_connection_new (connection, socket);
1282 g_object_unref (connection);
1283 connection = (GIOStream *)wrapper_connection;
1286 g_object_unref (socket);
1287 g_object_unref (address);
1289 g_object_unref (enumerator);
1292 g_propagate_error (error, g_steal_pointer (&error_info->best_error));
1293 socket_client_error_info_free (error_info);
1295 g_socket_client_emit_event (client, G_SOCKET_CLIENT_COMPLETE, connectable, connection);
1296 return G_SOCKET_CONNECTION (connection);
1300 * g_socket_client_connect_to_host:
1301 * @client: a #GSocketClient
1302 * @host_and_port: the name and optionally port of the host to connect to
1303 * @default_port: the default port to connect to
1304 * @cancellable: (nullable): a #GCancellable, or %NULL
1305 * @error: a pointer to a #GError, or %NULL
1307 * This is a helper function for g_socket_client_connect().
1309 * Attempts to create a TCP connection to the named host.
1311 * @host_and_port may be in any of a number of recognized formats; an IPv6
1312 * address, an IPv4 address, or a domain name (in which case a DNS
1313 * lookup is performed). Quoting with [] is supported for all address
1314 * types. A port override may be specified in the usual way with a
1315 * colon. Ports may be given as decimal numbers or symbolic names (in
1316 * which case an /etc/services lookup is performed).
1318 * If no port override is given in @host_and_port then @default_port will be
1319 * used as the port number to connect to.
1321 * In general, @host_and_port is expected to be provided by the user (allowing
1322 * them to give the hostname, and a port override if necessary) and
1323 * @default_port is expected to be provided by the application.
1325 * In the case that an IP address is given, a single connection
1326 * attempt is made. In the case that a name is given, multiple
1327 * connection attempts may be made, in turn and according to the
1328 * number of address records in DNS, until a connection succeeds.
1330 * Upon a successful connection, a new #GSocketConnection is constructed
1331 * and returned. The caller owns this new object and must drop their
1332 * reference to it when finished with it.
1334 * In the event of any failure (DNS error, service not found, no hosts
1335 * connectable) %NULL is returned and @error (if non-%NULL) is set
1338 * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
1343 g_socket_client_connect_to_host (GSocketClient *client,
1344 const gchar *host_and_port,
1345 guint16 default_port,
1346 GCancellable *cancellable,
1349 GSocketConnectable *connectable;
1350 GSocketConnection *connection;
1352 connectable = g_network_address_parse (host_and_port, default_port, error);
1353 if (connectable == NULL)
1356 connection = g_socket_client_connect (client, connectable,
1357 cancellable, error);
1358 g_object_unref (connectable);
1364 * g_socket_client_connect_to_service:
1365 * @client: a #GSocketConnection
1366 * @domain: a domain name
1367 * @service: the name of the service to connect to
1368 * @cancellable: (nullable): a #GCancellable, or %NULL
1369 * @error: a pointer to a #GError, or %NULL
1371 * Attempts to create a TCP connection to a service.
1373 * This call looks up the SRV record for @service at @domain for the
1374 * "tcp" protocol. It then attempts to connect, in turn, to each of
1375 * the hosts providing the service until either a connection succeeds
1376 * or there are no hosts remaining.
1378 * Upon a successful connection, a new #GSocketConnection is constructed
1379 * and returned. The caller owns this new object and must drop their
1380 * reference to it when finished with it.
1382 * In the event of any failure (DNS error, service not found, no hosts
1383 * connectable) %NULL is returned and @error (if non-%NULL) is set
1386 * Returns: (transfer full): a #GSocketConnection if successful, or %NULL on error
1389 g_socket_client_connect_to_service (GSocketClient *client,
1390 const gchar *domain,
1391 const gchar *service,
1392 GCancellable *cancellable,
1395 GSocketConnectable *connectable;
1396 GSocketConnection *connection;
1398 connectable = g_network_service_new (service, "tcp", domain);
1399 connection = g_socket_client_connect (client, connectable,
1400 cancellable, error);
1401 g_object_unref (connectable);
1407 * g_socket_client_connect_to_uri:
1408 * @client: a #GSocketClient
1409 * @uri: A network URI
1410 * @default_port: the default port to connect to
1411 * @cancellable: (nullable): a #GCancellable, or %NULL
1412 * @error: a pointer to a #GError, or %NULL
1414 * This is a helper function for g_socket_client_connect().
1416 * Attempts to create a TCP connection with a network URI.
1418 * @uri may be any valid URI containing an "authority" (hostname/port)
1419 * component. If a port is not specified in the URI, @default_port
1420 * will be used. TLS will be negotiated if #GSocketClient:tls is %TRUE.
1421 * (#GSocketClient does not know to automatically assume TLS for
1422 * certain URI schemes.)
1424 * Using this rather than g_socket_client_connect() or
1425 * g_socket_client_connect_to_host() allows #GSocketClient to
1426 * determine when to use application-specific proxy protocols.
1428 * Upon a successful connection, a new #GSocketConnection is constructed
1429 * and returned. The caller owns this new object and must drop their
1430 * reference to it when finished with it.
1432 * In the event of any failure (DNS error, service not found, no hosts
1433 * connectable) %NULL is returned and @error (if non-%NULL) is set
1436 * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
1441 g_socket_client_connect_to_uri (GSocketClient *client,
1443 guint16 default_port,
1444 GCancellable *cancellable,
1447 GSocketConnectable *connectable;
1448 GSocketConnection *connection;
1450 connectable = g_network_address_parse_uri (uri, default_port, error);
1451 if (connectable == NULL)
1454 connection = g_socket_client_connect (client, connectable,
1455 cancellable, error);
1456 g_object_unref (connectable);
1463 GTask *task; /* unowned */
1464 GSocketClient *client;
1466 GSocketConnectable *connectable;
1467 GSocketAddressEnumerator *enumerator;
1468 GCancellable *enumeration_cancellable;
1469 GCancellable *enumeration_parent_cancellable; /* (nullable) (owned) */
1470 gulong enumeration_cancelled_id;
1472 GSList *connection_attempts; /* (element-type ConnectionAttempt) (owned) */
1473 GSList *successful_connections;
1474 SocketClientErrorInfo *error_info;
1476 gboolean enumerated_at_least_once;
1477 gboolean enumeration_completed;
1478 gboolean connection_in_progress;
1480 } GSocketClientAsyncConnectData;
1482 static void connection_attempt_unref (gpointer attempt);
1485 g_socket_client_async_connect_data_free (GSocketClientAsyncConnectData *data)
1488 g_clear_object (&data->connectable);
1489 g_clear_object (&data->enumerator);
1491 g_cancellable_disconnect (data->enumeration_parent_cancellable, data->enumeration_cancelled_id);
1492 g_clear_object (&data->enumeration_parent_cancellable);
1493 data->enumeration_cancelled_id = 0;
1494 g_clear_object (&data->enumeration_cancellable);
1496 g_slist_free_full (data->connection_attempts, connection_attempt_unref);
1497 g_slist_free_full (data->successful_connections, connection_attempt_unref);
1499 g_clear_pointer (&data->error_info, socket_client_error_info_free);
1501 g_slice_free (GSocketClientAsyncConnectData, data);
1506 GSocketAddress *address;
1508 GIOStream *connection;
1509 GProxyAddress *proxy_addr;
1510 GSocketClientAsyncConnectData *data; /* unowned */
1511 GSource *timeout_source;
1512 GCancellable *cancellable;
1513 GCancellable *task_cancellable; /* (owned); this is equal to g_task_get_cancellable (ConnectionAttempt.data->task), but with a longer lifetime */
1514 gulong cancelled_id;
1516 } ConnectionAttempt;
1518 static ConnectionAttempt *
1519 connection_attempt_new (void)
1521 ConnectionAttempt *attempt = g_new0 (ConnectionAttempt, 1);
1522 g_ref_count_init (&attempt->ref);
1526 static ConnectionAttempt *
1527 connection_attempt_ref (ConnectionAttempt *attempt)
1529 g_ref_count_inc (&attempt->ref);
1534 connection_attempt_unref (gpointer pointer)
1536 ConnectionAttempt *attempt = pointer;
1537 if (g_ref_count_dec (&attempt->ref))
1539 g_clear_object (&attempt->address);
1540 g_clear_object (&attempt->socket);
1541 g_clear_object (&attempt->connection);
1542 g_cancellable_disconnect (attempt->task_cancellable, attempt->cancelled_id);
1543 g_clear_object (&attempt->task_cancellable);
1544 attempt->cancelled_id = 0;
1545 g_clear_object (&attempt->cancellable);
1546 g_clear_object (&attempt->proxy_addr);
1547 if (attempt->timeout_source)
1549 g_source_destroy (attempt->timeout_source);
1550 g_source_unref (attempt->timeout_source);
1557 connection_attempt_remove (ConnectionAttempt *attempt)
1559 attempt->data->connection_attempts = g_slist_remove (attempt->data->connection_attempts, attempt);
1560 connection_attempt_unref (attempt);
1564 cancel_all_attempts (GSocketClientAsyncConnectData *data)
1568 for (l = data->connection_attempts; l; l = g_slist_next (l))
1570 ConnectionAttempt *attempt_entry = l->data;
1571 g_cancellable_cancel (attempt_entry->cancellable);
1572 connection_attempt_unref (attempt_entry);
1574 g_slist_free (data->connection_attempts);
1575 data->connection_attempts = NULL;
1577 g_slist_free_full (data->successful_connections, connection_attempt_unref);
1578 data->successful_connections = NULL;
1580 g_cancellable_cancel (data->enumeration_cancellable);
1584 g_socket_client_async_connect_complete (ConnectionAttempt *attempt)
1586 GSocketClientAsyncConnectData *data = attempt->data;
1587 GError *error = NULL;
1588 g_assert (attempt->connection);
1589 g_assert (!data->completed);
1591 if (!G_IS_SOCKET_CONNECTION (attempt->connection))
1593 GSocketConnection *wrapper_connection;
1595 wrapper_connection = g_tcp_wrapper_connection_new (attempt->connection, attempt->socket);
1596 g_object_unref (attempt->connection);
1597 attempt->connection = (GIOStream *)wrapper_connection;
1600 data->completed = TRUE;
1601 cancel_all_attempts (data);
1603 if (g_cancellable_set_error_if_cancelled (g_task_get_cancellable (data->task), &error))
1605 g_debug ("GSocketClient: Connection cancelled!");
1606 g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_COMPLETE, data->connectable, NULL);
1607 g_task_return_error (data->task, g_steal_pointer (&error));
1611 g_debug ("GSocketClient: Connection successful!");
1612 g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_COMPLETE, data->connectable, attempt->connection);
1613 g_task_return_pointer (data->task, g_steal_pointer (&attempt->connection), g_object_unref);
1616 connection_attempt_unref (attempt);
1617 g_object_unref (data->task);
1622 g_socket_client_enumerator_callback (GObject *object,
1623 GAsyncResult *result,
1624 gpointer user_data);
1627 enumerator_next_async (GSocketClientAsyncConnectData *data,
1628 gboolean add_task_ref)
1630 /* Each enumeration takes a ref. This arg just avoids repeated unrefs when
1631 an enumeration starts another enumeration */
1633 g_object_ref (data->task);
1635 if (!data->enumerated_at_least_once)
1636 g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_RESOLVING, data->connectable, NULL);
1637 g_debug ("GSocketClient: Starting new address enumeration");
1638 g_socket_address_enumerator_next_async (data->enumerator,
1639 data->enumeration_cancellable,
1640 g_socket_client_enumerator_callback,
1644 static void try_next_connection_or_finish (GSocketClientAsyncConnectData *, gboolean);
1647 g_socket_client_tls_handshake_callback (GObject *object,
1648 GAsyncResult *result,
1651 ConnectionAttempt *attempt = user_data;
1652 GSocketClientAsyncConnectData *data = attempt->data;
1654 if (g_tls_connection_handshake_finish (G_TLS_CONNECTION (object),
1656 &data->error_info->tmp_error))
1658 g_object_unref (attempt->connection);
1659 attempt->connection = G_IO_STREAM (object);
1661 g_debug ("GSocketClient: TLS handshake succeeded");
1662 g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_TLS_HANDSHAKED, data->connectable, attempt->connection);
1663 g_socket_client_async_connect_complete (attempt);
1667 g_object_unref (object);
1668 connection_attempt_unref (attempt);
1670 g_debug ("GSocketClient: TLS handshake failed: %s", data->error_info->tmp_error->message);
1671 consider_tmp_error (data->error_info, G_SOCKET_CLIENT_TLS_HANDSHAKING);
1672 try_next_connection_or_finish (data, TRUE);
1677 g_socket_client_tls_handshake (ConnectionAttempt *attempt)
1679 GSocketClientAsyncConnectData *data = attempt->data;
1682 if (!data->client->priv->tls)
1684 g_socket_client_async_connect_complete (attempt);
1688 g_debug ("GSocketClient: Starting TLS handshake");
1689 tlsconn = g_tls_client_connection_new (attempt->connection,
1691 &data->error_info->tmp_error);
1694 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
1695 g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (tlsconn),
1696 data->client->priv->tls_validation_flags);
1697 G_GNUC_END_IGNORE_DEPRECATIONS
1698 g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_TLS_HANDSHAKING, data->connectable, G_IO_STREAM (tlsconn));
1699 g_tls_connection_handshake_async (G_TLS_CONNECTION (tlsconn),
1701 g_task_get_cancellable (data->task),
1702 g_socket_client_tls_handshake_callback,
1707 connection_attempt_unref (attempt);
1709 consider_tmp_error (data->error_info, G_SOCKET_CLIENT_TLS_HANDSHAKING);
1710 try_next_connection_or_finish (data, TRUE);
1715 g_socket_client_proxy_connect_callback (GObject *object,
1716 GAsyncResult *result,
1719 ConnectionAttempt *attempt = user_data;
1720 GSocketClientAsyncConnectData *data = attempt->data;
1722 g_object_unref (attempt->connection);
1723 attempt->connection = g_proxy_connect_finish (G_PROXY (object),
1725 &data->error_info->tmp_error);
1726 if (attempt->connection)
1728 g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_PROXY_NEGOTIATED, data->connectable, attempt->connection);
1729 g_socket_client_tls_handshake (attempt);
1733 connection_attempt_unref (attempt);
1735 consider_tmp_error (data->error_info, G_SOCKET_CLIENT_PROXY_NEGOTIATING);
1736 try_next_connection_or_finish (data, TRUE);
1741 complete_connection_with_error (GSocketClientAsyncConnectData *data,
1744 g_debug ("GSocketClient: Connection failed: %s", error->message);
1745 g_assert (!data->completed);
1747 g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_COMPLETE, data->connectable, NULL);
1748 data->completed = TRUE;
1749 cancel_all_attempts (data);
1750 g_task_return_error (data->task, error);
1754 task_completed_or_cancelled (GSocketClientAsyncConnectData *data)
1756 GTask *task = data->task;
1757 GCancellable *cancellable = g_task_get_cancellable (task);
1758 GError *error = NULL;
1760 if (data->completed)
1762 else if (g_cancellable_set_error_if_cancelled (cancellable, &error))
1764 complete_connection_with_error (data, g_steal_pointer (&error));
1772 try_next_successful_connection (GSocketClientAsyncConnectData *data)
1774 ConnectionAttempt *attempt;
1775 const gchar *protocol;
1778 if (data->connection_in_progress)
1781 g_assert (data->successful_connections != NULL);
1782 attempt = data->successful_connections->data;
1783 g_assert (attempt != NULL);
1784 data->successful_connections = g_slist_remove (data->successful_connections, attempt);
1785 data->connection_in_progress = TRUE;
1787 g_debug ("GSocketClient: Starting application layer connection");
1789 if (!attempt->proxy_addr)
1791 g_socket_client_tls_handshake (g_steal_pointer (&attempt));
1795 protocol = g_proxy_address_get_protocol (attempt->proxy_addr);
1797 /* The connection should not be anything other than TCP,
1798 * but let's put a safety guard in case
1800 if (!G_IS_TCP_CONNECTION (attempt->connection))
1802 g_critical ("Trying to proxy over non-TCP connection, this is "
1803 "most likely a bug in GLib IO library.");
1805 g_set_error_literal (&data->error_info->tmp_error,
1806 G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1807 _("Proxying over a non-TCP connection is not supported."));
1808 consider_tmp_error (data->error_info, G_SOCKET_CLIENT_PROXY_NEGOTIATING);
1810 else if (g_hash_table_contains (data->client->priv->app_proxies, protocol))
1812 /* Simply complete the connection, we don't want to do TLS handshake
1813 * as the application proxy handling may need proxy handshake first */
1814 g_socket_client_async_connect_complete (g_steal_pointer (&attempt));
1817 else if ((proxy = g_proxy_get_default_for_protocol (protocol)))
1819 GIOStream *connection = attempt->connection;
1820 GProxyAddress *proxy_addr = attempt->proxy_addr;
1822 g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_PROXY_NEGOTIATING, data->connectable, attempt->connection);
1823 g_debug ("GSocketClient: Starting proxy connection");
1824 g_proxy_connect_async (proxy,
1827 g_task_get_cancellable (data->task),
1828 g_socket_client_proxy_connect_callback,
1829 g_steal_pointer (&attempt));
1830 g_object_unref (proxy);
1835 g_set_error (&data->error_info->tmp_error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1836 _("Proxy protocol “%s” is not supported."),
1838 consider_tmp_error (data->error_info, G_SOCKET_CLIENT_PROXY_NEGOTIATING);
1841 data->connection_in_progress = FALSE;
1842 g_clear_pointer (&attempt, connection_attempt_unref);
1843 return FALSE; /* All non-return paths are failures */
1847 try_next_connection_or_finish (GSocketClientAsyncConnectData *data,
1848 gboolean end_current_connection)
1850 if (end_current_connection)
1851 data->connection_in_progress = FALSE;
1853 if (data->connection_in_progress)
1856 /* Keep trying successful connections until one works, each iteration pops one */
1857 while (data->successful_connections)
1859 if (try_next_successful_connection (data))
1863 if (!data->enumeration_completed)
1865 enumerator_next_async (data, FALSE);
1869 complete_connection_with_error (data, g_steal_pointer (&data->error_info->best_error));
1873 g_socket_client_connected_callback (GObject *source,
1874 GAsyncResult *result,
1877 ConnectionAttempt *attempt = g_steal_pointer (&user_data);
1878 GSocketClientAsyncConnectData *data = attempt->data;
1880 if (task_completed_or_cancelled (data) || g_cancellable_is_cancelled (attempt->cancellable))
1882 g_object_unref (data->task);
1883 connection_attempt_unref (attempt);
1887 if (attempt->timeout_source)
1889 g_source_destroy (attempt->timeout_source);
1890 g_clear_pointer (&attempt->timeout_source, g_source_unref);
1893 if (!g_socket_connection_connect_finish (G_SOCKET_CONNECTION (source),
1894 result, &data->error_info->tmp_error))
1896 if (!g_cancellable_is_cancelled (attempt->cancellable))
1898 g_debug ("GSocketClient: Connection attempt failed: %s", data->error_info->tmp_error->message);
1899 clarify_connect_error (data->error_info->tmp_error, data->connectable, attempt->address);
1900 consider_tmp_error (data->error_info, G_SOCKET_CLIENT_CONNECTING);
1901 connection_attempt_remove (attempt);
1902 connection_attempt_unref (attempt);
1903 try_next_connection_or_finish (data, FALSE);
1905 else /* Silently ignore cancelled attempts */
1907 g_clear_error (&data->error_info->tmp_error);
1908 g_object_unref (data->task);
1909 connection_attempt_unref (attempt);
1915 g_socket_connection_set_cached_remote_address ((GSocketConnection*)attempt->connection, NULL);
1916 g_debug ("GSocketClient: TCP connection successful");
1917 g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_CONNECTED, data->connectable, attempt->connection);
1919 /* wrong, but backward compatible */
1920 g_socket_set_blocking (attempt->socket, TRUE);
1922 /* This ends the parallel "happy eyeballs" portion of connecting.
1923 Now that we have a successful tcp connection we will attempt to connect
1924 at the TLS/Proxy layer. If those layers fail we will move on to the next
1927 connection_attempt_remove (attempt);
1928 data->successful_connections = g_slist_append (data->successful_connections, g_steal_pointer (&attempt));
1929 try_next_connection_or_finish (data, FALSE);
1933 on_connection_attempt_timeout (gpointer data)
1935 ConnectionAttempt *attempt = data;
1937 if (!attempt->data->enumeration_completed)
1939 g_debug ("GSocketClient: Timeout reached, trying another enumeration");
1940 enumerator_next_async (attempt->data, TRUE);
1943 g_clear_pointer (&attempt->timeout_source, g_source_unref);
1944 return G_SOURCE_REMOVE;
1948 on_connection_cancelled (GCancellable *cancellable,
1951 GCancellable *linked_cancellable = G_CANCELLABLE (data);
1953 g_cancellable_cancel (linked_cancellable);
1957 g_socket_client_enumerator_callback (GObject *object,
1958 GAsyncResult *result,
1961 GSocketClientAsyncConnectData *data = user_data;
1962 GSocketAddress *address = NULL;
1964 ConnectionAttempt *attempt;
1966 if (task_completed_or_cancelled (data))
1968 g_object_unref (data->task);
1972 address = g_socket_address_enumerator_next_finish (data->enumerator,
1973 result, &data->error_info->tmp_error);
1974 if (address == NULL)
1976 if (G_UNLIKELY (data->enumeration_completed))
1979 data->enumeration_completed = TRUE;
1980 g_debug ("GSocketClient: Address enumeration completed (out of addresses)");
1982 /* As per API docs: We only care about error if it's the first call,
1983 after that the enumerator is done.
1985 Note that we don't care about cancellation errors because
1986 task_completed_or_cancelled() above should handle that.
1988 If this fails and nothing is in progress then we will complete task here.
1990 if ((data->enumerated_at_least_once && !data->connection_attempts && !data->connection_in_progress) ||
1991 !data->enumerated_at_least_once)
1993 g_debug ("GSocketClient: Address enumeration failed: %s",
1994 data->error_info->tmp_error ? data->error_info->tmp_error->message : NULL);
1995 consider_tmp_error (data->error_info, G_SOCKET_CLIENT_RESOLVING);
1996 g_assert (data->error_info->best_error);
1997 complete_connection_with_error (data, g_steal_pointer (&data->error_info->best_error));
2000 /* Enumeration should never trigger again, drop our ref */
2001 g_object_unref (data->task);
2005 g_debug ("GSocketClient: Address enumeration succeeded");
2006 if (!data->enumerated_at_least_once)
2008 g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_RESOLVED,
2009 data->connectable, NULL);
2010 data->enumerated_at_least_once = TRUE;
2013 socket = create_socket (data->client, address, &data->error_info->tmp_error);
2016 g_object_unref (address);
2017 consider_tmp_error (data->error_info, G_SOCKET_CLIENT_CONNECTING);
2018 enumerator_next_async (data, FALSE);
2022 attempt = connection_attempt_new ();
2023 attempt->data = data;
2024 attempt->socket = socket;
2025 attempt->address = address;
2026 attempt->cancellable = g_cancellable_new ();
2027 attempt->connection = (GIOStream *)g_socket_connection_factory_create_connection (socket);
2028 attempt->timeout_source = g_timeout_source_new (HAPPY_EYEBALLS_CONNECTION_ATTEMPT_TIMEOUT_MS);
2030 if (G_IS_PROXY_ADDRESS (address) && data->client->priv->enable_proxy)
2031 attempt->proxy_addr = g_object_ref (G_PROXY_ADDRESS (address));
2033 g_source_set_callback (attempt->timeout_source, on_connection_attempt_timeout, attempt, NULL);
2034 g_source_attach (attempt->timeout_source, g_task_get_context (data->task));
2035 data->connection_attempts = g_slist_append (data->connection_attempts, connection_attempt_ref (attempt));
2037 if (g_task_get_cancellable (data->task))
2039 attempt->task_cancellable = g_object_ref (g_task_get_cancellable (data->task));
2040 attempt->cancelled_id =
2041 g_cancellable_connect (attempt->task_cancellable, G_CALLBACK (on_connection_cancelled),
2042 g_object_ref (attempt->cancellable), g_object_unref);
2045 g_socket_connection_set_cached_remote_address ((GSocketConnection *)attempt->connection, address);
2046 g_debug ("GSocketClient: Starting TCP connection attempt");
2047 g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_CONNECTING, data->connectable, attempt->connection);
2048 g_socket_connection_connect_async (G_SOCKET_CONNECTION (attempt->connection),
2050 attempt->cancellable,
2051 g_socket_client_connected_callback, attempt /* transfer full */);
2055 * g_socket_client_connect_async:
2056 * @client: a #GSocketClient
2057 * @connectable: a #GSocketConnectable specifying the remote address.
2058 * @cancellable: (nullable): a #GCancellable, or %NULL
2059 * @callback: (scope async): a #GAsyncReadyCallback
2060 * @user_data: user data for the callback
2062 * This is the asynchronous version of g_socket_client_connect().
2064 * You may wish to prefer the asynchronous version even in synchronous
2065 * command line programs because, since 2.60, it implements
2066 * [RFC 8305](https://tools.ietf.org/html/rfc8305) "Happy Eyeballs"
2067 * recommendations to work around long connection timeouts in networks
2068 * where IPv6 is broken by performing an IPv4 connection simultaneously
2069 * without waiting for IPv6 to time out, which is not supported by the
2070 * synchronous call. (This is not an API guarantee, and may change in
2073 * When the operation is finished @callback will be
2074 * called. You can then call g_socket_client_connect_finish() to get
2075 * the result of the operation.
2080 g_socket_client_connect_async (GSocketClient *client,
2081 GSocketConnectable *connectable,
2082 GCancellable *cancellable,
2083 GAsyncReadyCallback callback,
2086 GSocketClientAsyncConnectData *data;
2088 g_return_if_fail (G_IS_SOCKET_CLIENT (client));
2090 data = g_slice_new0 (GSocketClientAsyncConnectData);
2091 data->client = client;
2092 data->connectable = g_object_ref (connectable);
2093 data->error_info = socket_client_error_info_new ();
2095 if (can_use_proxy (client))
2097 data->enumerator = g_socket_connectable_proxy_enumerate (connectable);
2098 if (client->priv->proxy_resolver &&
2099 G_IS_PROXY_ADDRESS_ENUMERATOR (data->enumerator))
2101 g_object_set (G_OBJECT (data->enumerator),
2102 "proxy-resolver", client->priv->proxy_resolver,
2107 data->enumerator = g_socket_connectable_enumerate (connectable);
2109 /* This function tries to match the behavior of g_socket_client_connect ()
2110 which is simple enough but much of it is done in parallel to be as responsive
2111 as possible as per Happy Eyeballs (RFC 8305). This complicates flow quite a
2112 bit but we can describe it in 3 sections:
2114 Firstly we have address enumeration (DNS):
2115 - This may be triggered multiple times by enumerator_next_async().
2116 - It also has its own cancellable (data->enumeration_cancellable).
2117 - Enumeration is done lazily because GNetworkAddressAddressEnumerator
2118 also does work in parallel and may lazily add new addresses.
2119 - If the first enumeration errors then the task errors. Otherwise all enumerations
2120 will potentially be used (until task or enumeration is cancelled).
2122 Then we start attempting connections (TCP):
2123 - Each connection is independent and kept in a ConnectionAttempt object.
2124 - They each hold a ref on the main task and have their own cancellable.
2125 - Multiple attempts may happen in parallel as per Happy Eyeballs.
2126 - Upon failure or timeouts more connection attempts are made.
2127 - If no connections succeed the task errors.
2128 - Upon success they are kept in a list of successful connections.
2130 Lastly we connect at the application layer (TLS, Proxies):
2131 - These are done in serial.
2132 - The reasoning here is that Happy Eyeballs is about making bad connections responsive
2133 at the IP/TCP layers. Issues at the application layer are generally not due to
2134 connectivity issues but rather misconfiguration.
2135 - Upon failure it will try the next TCP connection until it runs out and
2137 - Upon success it cancels everything remaining (enumeration and connections)
2138 and returns the connection.
2141 data->task = g_task_new (client, cancellable, callback, user_data);
2142 g_task_set_check_cancellable (data->task, FALSE); /* We handle this manually */
2143 g_task_set_source_tag (data->task, g_socket_client_connect_async);
2144 g_task_set_task_data (data->task, data, (GDestroyNotify)g_socket_client_async_connect_data_free);
2146 data->enumeration_cancellable = g_cancellable_new ();
2149 data->enumeration_parent_cancellable = g_object_ref (cancellable);
2150 data->enumeration_cancelled_id =
2151 g_cancellable_connect (cancellable, G_CALLBACK (on_connection_cancelled),
2152 g_object_ref (data->enumeration_cancellable), g_object_unref);
2155 enumerator_next_async (data, FALSE);
2159 * g_socket_client_connect_to_host_async:
2160 * @client: a #GSocketClient
2161 * @host_and_port: the name and optionally the port of the host to connect to
2162 * @default_port: the default port to connect to
2163 * @cancellable: (nullable): a #GCancellable, or %NULL
2164 * @callback: (scope async): a #GAsyncReadyCallback
2165 * @user_data: user data for the callback
2167 * This is the asynchronous version of g_socket_client_connect_to_host().
2169 * When the operation is finished @callback will be
2170 * called. You can then call g_socket_client_connect_to_host_finish() to get
2171 * the result of the operation.
2176 g_socket_client_connect_to_host_async (GSocketClient *client,
2177 const gchar *host_and_port,
2178 guint16 default_port,
2179 GCancellable *cancellable,
2180 GAsyncReadyCallback callback,
2183 GSocketConnectable *connectable;
2187 connectable = g_network_address_parse (host_and_port, default_port,
2189 if (connectable == NULL)
2191 g_task_report_error (client, callback, user_data,
2192 g_socket_client_connect_to_host_async,
2197 g_socket_client_connect_async (client,
2198 connectable, cancellable,
2199 callback, user_data);
2200 g_object_unref (connectable);
2205 * g_socket_client_connect_to_service_async:
2206 * @client: a #GSocketClient
2207 * @domain: a domain name
2208 * @service: the name of the service to connect to
2209 * @cancellable: (nullable): a #GCancellable, or %NULL
2210 * @callback: (scope async): a #GAsyncReadyCallback
2211 * @user_data: user data for the callback
2213 * This is the asynchronous version of
2214 * g_socket_client_connect_to_service().
2219 g_socket_client_connect_to_service_async (GSocketClient *client,
2220 const gchar *domain,
2221 const gchar *service,
2222 GCancellable *cancellable,
2223 GAsyncReadyCallback callback,
2226 GSocketConnectable *connectable;
2228 connectable = g_network_service_new (service, "tcp", domain);
2229 g_socket_client_connect_async (client,
2230 connectable, cancellable,
2231 callback, user_data);
2232 g_object_unref (connectable);
2236 * g_socket_client_connect_to_uri_async:
2237 * @client: a #GSocketClient
2238 * @uri: a network uri
2239 * @default_port: the default port to connect to
2240 * @cancellable: (nullable): a #GCancellable, or %NULL
2241 * @callback: (scope async): a #GAsyncReadyCallback
2242 * @user_data: user data for the callback
2244 * This is the asynchronous version of g_socket_client_connect_to_uri().
2246 * When the operation is finished @callback will be
2247 * called. You can then call g_socket_client_connect_to_uri_finish() to get
2248 * the result of the operation.
2253 g_socket_client_connect_to_uri_async (GSocketClient *client,
2255 guint16 default_port,
2256 GCancellable *cancellable,
2257 GAsyncReadyCallback callback,
2260 GSocketConnectable *connectable;
2264 connectable = g_network_address_parse_uri (uri, default_port, &error);
2265 if (connectable == NULL)
2267 g_task_report_error (client, callback, user_data,
2268 g_socket_client_connect_to_uri_async,
2273 g_debug("g_socket_client_connect_to_uri_async");
2274 g_socket_client_connect_async (client,
2275 connectable, cancellable,
2276 callback, user_data);
2277 g_object_unref (connectable);
2283 * g_socket_client_connect_finish:
2284 * @client: a #GSocketClient.
2285 * @result: a #GAsyncResult.
2286 * @error: a #GError location to store the error occurring, or %NULL to
2289 * Finishes an async connect operation. See g_socket_client_connect_async()
2291 * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
2296 g_socket_client_connect_finish (GSocketClient *client,
2297 GAsyncResult *result,
2300 g_return_val_if_fail (g_task_is_valid (result, client), NULL);
2302 return g_task_propagate_pointer (G_TASK (result), error);
2306 * g_socket_client_connect_to_host_finish:
2307 * @client: a #GSocketClient.
2308 * @result: a #GAsyncResult.
2309 * @error: a #GError location to store the error occurring, or %NULL to
2312 * Finishes an async connect operation. See g_socket_client_connect_to_host_async()
2314 * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
2319 g_socket_client_connect_to_host_finish (GSocketClient *client,
2320 GAsyncResult *result,
2323 return g_socket_client_connect_finish (client, result, error);
2327 * g_socket_client_connect_to_service_finish:
2328 * @client: a #GSocketClient.
2329 * @result: a #GAsyncResult.
2330 * @error: a #GError location to store the error occurring, or %NULL to
2333 * Finishes an async connect operation. See g_socket_client_connect_to_service_async()
2335 * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
2340 g_socket_client_connect_to_service_finish (GSocketClient *client,
2341 GAsyncResult *result,
2344 return g_socket_client_connect_finish (client, result, error);
2348 * g_socket_client_connect_to_uri_finish:
2349 * @client: a #GSocketClient.
2350 * @result: a #GAsyncResult.
2351 * @error: a #GError location to store the error occurring, or %NULL to
2354 * Finishes an async connect operation. See g_socket_client_connect_to_uri_async()
2356 * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
2361 g_socket_client_connect_to_uri_finish (GSocketClient *client,
2362 GAsyncResult *result,
2365 return g_socket_client_connect_finish (client, result, error);
2369 * g_socket_client_add_application_proxy:
2370 * @client: a #GSocketClient
2371 * @protocol: The proxy protocol
2373 * Enable proxy protocols to be handled by the application. When the
2374 * indicated proxy protocol is returned by the #GProxyResolver,
2375 * #GSocketClient will consider this protocol as supported but will
2376 * not try to find a #GProxy instance to handle handshaking. The
2377 * application must check for this case by calling
2378 * g_socket_connection_get_remote_address() on the returned
2379 * #GSocketConnection, and seeing if it's a #GProxyAddress of the
2380 * appropriate type, to determine whether or not it needs to handle
2381 * the proxy handshaking itself.
2383 * This should be used for proxy protocols that are dialects of
2384 * another protocol such as HTTP proxy. It also allows cohabitation of
2385 * proxy protocols that are reused between protocols. A good example
2386 * is HTTP. It can be used to proxy HTTP, FTP and Gopher and can also
2387 * be use as generic socket proxy through the HTTP CONNECT method.
2389 * When the proxy is detected as being an application proxy, TLS handshake
2390 * will be skipped. This is required to let the application do the proxy
2391 * specific handshake.
2394 g_socket_client_add_application_proxy (GSocketClient *client,
2395 const gchar *protocol)
2397 g_hash_table_add (client->priv->app_proxies, g_strdup (protocol));