GSocketClient: add proxy-resolver property
[platform/upstream/glib.git] / gio / gsocketclient.c
1 /*  GIO - GLib Input, Output and Streaming Library
2  *
3  * Copyright © 2008, 2009 codethink
4  * Copyright © 2009 Red Hat, Inc
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General
17  * Public License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
19  * Boston, MA 02111-1307, USA.
20  *
21  * Authors: Ryan Lortie <desrt@desrt.ca>
22  *          Alexander Larsson <alexl@redhat.com>
23  */
24
25 #include "config.h"
26 #include "gsocketclient.h"
27
28 #include <stdlib.h>
29 #include <string.h>
30
31 #include <gio/gioenumtypes.h>
32 #include <gio/gsocketaddressenumerator.h>
33 #include <gio/gsocketconnectable.h>
34 #include <gio/gsocketconnection.h>
35 #include <gio/gproxyaddressenumerator.h>
36 #include <gio/gproxyaddress.h>
37 #include <gio/gtask.h>
38 #include <gio/gcancellable.h>
39 #include <gio/gioerror.h>
40 #include <gio/gsocket.h>
41 #include <gio/gnetworkaddress.h>
42 #include <gio/gnetworkservice.h>
43 #include <gio/gproxy.h>
44 #include <gio/gproxyresolver.h>
45 #include <gio/gsocketaddress.h>
46 #include <gio/gtcpconnection.h>
47 #include <gio/gtcpwrapperconnection.h>
48 #include <gio/gtlscertificate.h>
49 #include <gio/gtlsclientconnection.h>
50 #include <gio/ginetaddress.h>
51 #include "glibintl.h"
52
53
54 /**
55  * SECTION:gsocketclient
56  * @short_description: Helper for connecting to a network service
57  * @include: gio/gio.h
58  * @see_also: #GSocketConnection, #GSocketListener
59  *
60  * #GSocketClient is a lightweight high-level utility class for connecting to
61  * a network host using a connection oriented socket type.
62  *
63  * You create a #GSocketClient object, set any options you want, and then
64  * call a sync or async connect operation, which returns a #GSocketConnection
65  * subclass on success.
66  *
67  * The type of the #GSocketConnection object returned depends on the type of
68  * the underlying socket that is in use. For instance, for a TCP/IP connection
69  * it will be a #GTcpConnection.
70  *
71  * As #GSocketClient is a lightweight object, you don't need to cache it. You
72  * can just create a new one any time you need one.
73  *
74  * Since: 2.22
75  */
76
77
78 G_DEFINE_TYPE (GSocketClient, g_socket_client, G_TYPE_OBJECT);
79
80 enum
81 {
82   EVENT,
83   LAST_SIGNAL
84 };
85
86 static guint signals[LAST_SIGNAL] = { 0 };
87
88 enum
89 {
90   PROP_NONE,
91   PROP_FAMILY,
92   PROP_TYPE,
93   PROP_PROTOCOL,
94   PROP_LOCAL_ADDRESS,
95   PROP_TIMEOUT,
96   PROP_ENABLE_PROXY,
97   PROP_TLS,
98   PROP_TLS_VALIDATION_FLAGS,
99   PROP_PROXY_RESOLVER
100 };
101
102 struct _GSocketClientPrivate
103 {
104   GSocketFamily family;
105   GSocketType type;
106   GSocketProtocol protocol;
107   GSocketAddress *local_address;
108   guint timeout;
109   gboolean enable_proxy;
110   GHashTable *app_proxies;
111   gboolean tls;
112   GTlsCertificateFlags tls_validation_flags;
113   GProxyResolver *proxy_resolver;
114 };
115
116 static GSocket *
117 create_socket (GSocketClient  *client,
118                GSocketAddress *dest_address,
119                GError        **error)
120 {
121   GSocketFamily family;
122   GSocket *socket;
123
124   family = client->priv->family;
125   if (family == G_SOCKET_FAMILY_INVALID &&
126       client->priv->local_address != NULL)
127     family = g_socket_address_get_family (client->priv->local_address);
128   if (family == G_SOCKET_FAMILY_INVALID)
129     family = g_socket_address_get_family (dest_address);
130
131   socket = g_socket_new (family,
132                          client->priv->type,
133                          client->priv->protocol,
134                          error);
135   if (socket == NULL)
136     return NULL;
137
138   if (client->priv->local_address)
139     {
140       if (!g_socket_bind (socket,
141                           client->priv->local_address,
142                           FALSE,
143                           error))
144         {
145           g_object_unref (socket);
146           return NULL;
147         }
148     }
149
150   if (client->priv->timeout)
151     g_socket_set_timeout (socket, client->priv->timeout);
152
153   return socket;
154 }
155
156 static gboolean
157 can_use_proxy (GSocketClient *client)
158 {
159   GSocketClientPrivate *priv = client->priv;
160
161   return priv->enable_proxy
162           && priv->type == G_SOCKET_TYPE_STREAM;
163 }
164
165 static void
166 clarify_connect_error (GError             *error,
167                        GSocketConnectable *connectable,
168                        GSocketAddress     *address)
169 {
170   const char *name;
171   char *tmp_name = NULL;
172
173   if (G_IS_PROXY_ADDRESS (address))
174     {
175       name = tmp_name = g_inet_address_to_string (g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (address)));
176
177       g_prefix_error (&error, _("Could not connect to proxy server %s: "), name);
178     }
179   else
180     {
181       if (G_IS_NETWORK_ADDRESS (connectable))
182         name = g_network_address_get_hostname (G_NETWORK_ADDRESS (connectable));
183       else if (G_IS_NETWORK_SERVICE (connectable))
184         name = g_network_service_get_domain (G_NETWORK_SERVICE (connectable));
185       else if (G_IS_INET_SOCKET_ADDRESS (connectable))
186         name = tmp_name = g_inet_address_to_string (g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (connectable)));
187       else
188         name = NULL;
189
190       if (name)
191         g_prefix_error (&error, _("Could not connect to %s: "), name);
192       else
193         g_prefix_error (&error, _("Could not connect: "));
194     }
195
196   g_free (tmp_name);
197 }
198
199 static void
200 g_socket_client_init (GSocketClient *client)
201 {
202   client->priv = G_TYPE_INSTANCE_GET_PRIVATE (client,
203                                               G_TYPE_SOCKET_CLIENT,
204                                               GSocketClientPrivate);
205   client->priv->type = G_SOCKET_TYPE_STREAM;
206   client->priv->app_proxies = g_hash_table_new_full (g_str_hash,
207                                                      g_str_equal,
208                                                      g_free,
209                                                      NULL);
210 }
211
212 /**
213  * g_socket_client_new:
214  *
215  * Creates a new #GSocketClient with the default options.
216  *
217  * Returns: a #GSocketClient.
218  *     Free the returned object with g_object_unref().
219  *
220  * Since: 2.22
221  */
222 GSocketClient *
223 g_socket_client_new (void)
224 {
225   return g_object_new (G_TYPE_SOCKET_CLIENT, NULL);
226 }
227
228 static void
229 g_socket_client_finalize (GObject *object)
230 {
231   GSocketClient *client = G_SOCKET_CLIENT (object);
232
233   g_clear_object (&client->priv->local_address);
234   g_clear_object (&client->priv->proxy_resolver);
235
236   if (G_OBJECT_CLASS (g_socket_client_parent_class)->finalize)
237     (*G_OBJECT_CLASS (g_socket_client_parent_class)->finalize) (object);
238
239   g_hash_table_unref (client->priv->app_proxies);
240 }
241
242 static void
243 g_socket_client_get_property (GObject    *object,
244                               guint       prop_id,
245                               GValue     *value,
246                               GParamSpec *pspec)
247 {
248   GSocketClient *client = G_SOCKET_CLIENT (object);
249
250   switch (prop_id)
251     {
252       case PROP_FAMILY:
253         g_value_set_enum (value, client->priv->family);
254         break;
255
256       case PROP_TYPE:
257         g_value_set_enum (value, client->priv->type);
258         break;
259
260       case PROP_PROTOCOL:
261         g_value_set_enum (value, client->priv->protocol);
262         break;
263
264       case PROP_LOCAL_ADDRESS:
265         g_value_set_object (value, client->priv->local_address);
266         break;
267
268       case PROP_TIMEOUT:
269         g_value_set_uint (value, client->priv->timeout);
270         break;
271
272       case PROP_ENABLE_PROXY:
273         g_value_set_boolean (value, client->priv->enable_proxy);
274         break;
275
276       case PROP_TLS:
277         g_value_set_boolean (value, g_socket_client_get_tls (client));
278         break;
279
280       case PROP_TLS_VALIDATION_FLAGS:
281         g_value_set_flags (value, g_socket_client_get_tls_validation_flags (client));
282         break;
283
284       case PROP_PROXY_RESOLVER:
285         g_value_set_object (value, g_socket_client_get_proxy_resolver (client));
286         break;
287
288       default:
289         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
290     }
291 }
292
293 static void
294 g_socket_client_set_property (GObject      *object,
295                               guint         prop_id,
296                               const GValue *value,
297                               GParamSpec   *pspec)
298 {
299   GSocketClient *client = G_SOCKET_CLIENT (object);
300
301   switch (prop_id)
302     {
303     case PROP_FAMILY:
304       g_socket_client_set_family (client, g_value_get_enum (value));
305       break;
306
307     case PROP_TYPE:
308       g_socket_client_set_socket_type (client, g_value_get_enum (value));
309       break;
310
311     case PROP_PROTOCOL:
312       g_socket_client_set_protocol (client, g_value_get_enum (value));
313       break;
314
315     case PROP_LOCAL_ADDRESS:
316       g_socket_client_set_local_address (client, g_value_get_object (value));
317       break;
318
319     case PROP_TIMEOUT:
320       g_socket_client_set_timeout (client, g_value_get_uint (value));
321       break;
322
323     case PROP_ENABLE_PROXY:
324       g_socket_client_set_enable_proxy (client, g_value_get_boolean (value));
325       break;
326
327     case PROP_TLS:
328       g_socket_client_set_tls (client, g_value_get_boolean (value));
329       break;
330
331     case PROP_TLS_VALIDATION_FLAGS:
332       g_socket_client_set_tls_validation_flags (client, g_value_get_flags (value));
333       break;
334
335     case PROP_PROXY_RESOLVER:
336       g_socket_client_set_proxy_resolver (client, g_value_get_object (value));
337       break;
338
339     default:
340       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
341     }
342 }
343
344 /**
345  * g_socket_client_get_family:
346  * @client: a #GSocketClient.
347  *
348  * Gets the socket family of the socket client.
349  *
350  * See g_socket_client_set_family() for details.
351  *
352  * Returns: a #GSocketFamily
353  *
354  * Since: 2.22
355  */
356 GSocketFamily
357 g_socket_client_get_family (GSocketClient *client)
358 {
359   return client->priv->family;
360 }
361
362 /**
363  * g_socket_client_set_family:
364  * @client: a #GSocketClient.
365  * @family: a #GSocketFamily
366  *
367  * Sets the socket family of the socket client.
368  * If this is set to something other than %G_SOCKET_FAMILY_INVALID
369  * then the sockets created by this object will be of the specified
370  * family.
371  *
372  * This might be useful for instance if you want to force the local
373  * connection to be an ipv4 socket, even though the address might
374  * be an ipv6 mapped to ipv4 address.
375  *
376  * Since: 2.22
377  */
378 void
379 g_socket_client_set_family (GSocketClient *client,
380                             GSocketFamily  family)
381 {
382   if (client->priv->family == family)
383     return;
384
385   client->priv->family = family;
386   g_object_notify (G_OBJECT (client), "family");
387 }
388
389 /**
390  * g_socket_client_get_socket_type:
391  * @client: a #GSocketClient.
392  *
393  * Gets the socket type of the socket client.
394  *
395  * See g_socket_client_set_socket_type() for details.
396  *
397  * Returns: a #GSocketFamily
398  *
399  * Since: 2.22
400  */
401 GSocketType
402 g_socket_client_get_socket_type (GSocketClient *client)
403 {
404   return client->priv->type;
405 }
406
407 /**
408  * g_socket_client_set_socket_type:
409  * @client: a #GSocketClient.
410  * @type: a #GSocketType
411  *
412  * Sets the socket type of the socket client.
413  * The sockets created by this object will be of the specified
414  * type.
415  *
416  * It doesn't make sense to specify a type of %G_SOCKET_TYPE_DATAGRAM,
417  * as GSocketClient is used for connection oriented services.
418  *
419  * Since: 2.22
420  */
421 void
422 g_socket_client_set_socket_type (GSocketClient *client,
423                                  GSocketType    type)
424 {
425   if (client->priv->type == type)
426     return;
427
428   client->priv->type = type;
429   g_object_notify (G_OBJECT (client), "type");
430 }
431
432 /**
433  * g_socket_client_get_protocol:
434  * @client: a #GSocketClient
435  *
436  * Gets the protocol name type of the socket client.
437  *
438  * See g_socket_client_set_protocol() for details.
439  *
440  * Returns: a #GSocketProtocol
441  *
442  * Since: 2.22
443  */
444 GSocketProtocol
445 g_socket_client_get_protocol (GSocketClient *client)
446 {
447   return client->priv->protocol;
448 }
449
450 /**
451  * g_socket_client_set_protocol:
452  * @client: a #GSocketClient.
453  * @protocol: a #GSocketProtocol
454  *
455  * Sets the protocol of the socket client.
456  * The sockets created by this object will use of the specified
457  * protocol.
458  *
459  * If @protocol is %0 that means to use the default
460  * protocol for the socket family and type.
461  *
462  * Since: 2.22
463  */
464 void
465 g_socket_client_set_protocol (GSocketClient   *client,
466                               GSocketProtocol  protocol)
467 {
468   if (client->priv->protocol == protocol)
469     return;
470
471   client->priv->protocol = protocol;
472   g_object_notify (G_OBJECT (client), "protocol");
473 }
474
475 /**
476  * g_socket_client_get_local_address:
477  * @client: a #GSocketClient.
478  *
479  * Gets the local address of the socket client.
480  *
481  * See g_socket_client_set_local_address() for details.
482  *
483  * Returns: (transfer none): a #GSocketAddress or %NULL. Do not free.
484  *
485  * Since: 2.22
486  */
487 GSocketAddress *
488 g_socket_client_get_local_address (GSocketClient *client)
489 {
490   return client->priv->local_address;
491 }
492
493 /**
494  * g_socket_client_set_local_address:
495  * @client: a #GSocketClient.
496  * @address: (allow-none): a #GSocketAddress, or %NULL
497  *
498  * Sets the local address of the socket client.
499  * The sockets created by this object will bound to the
500  * specified address (if not %NULL) before connecting.
501  *
502  * This is useful if you want to ensure that the local
503  * side of the connection is on a specific port, or on
504  * a specific interface.
505  *
506  * Since: 2.22
507  */
508 void
509 g_socket_client_set_local_address (GSocketClient  *client,
510                                    GSocketAddress *address)
511 {
512   if (address)
513     g_object_ref (address);
514
515   if (client->priv->local_address)
516     {
517       g_object_unref (client->priv->local_address);
518     }
519   client->priv->local_address = address;
520   g_object_notify (G_OBJECT (client), "local-address");
521 }
522
523 /**
524  * g_socket_client_get_timeout:
525  * @client: a #GSocketClient
526  *
527  * Gets the I/O timeout time for sockets created by @client.
528  *
529  * See g_socket_client_set_timeout() for details.
530  *
531  * Returns: the timeout in seconds
532  *
533  * Since: 2.26
534  */
535 guint
536 g_socket_client_get_timeout (GSocketClient *client)
537 {
538   return client->priv->timeout;
539 }
540
541
542 /**
543  * g_socket_client_set_timeout:
544  * @client: a #GSocketClient.
545  * @timeout: the timeout
546  *
547  * Sets the I/O timeout for sockets created by @client. @timeout is a
548  * time in seconds, or 0 for no timeout (the default).
549  *
550  * The timeout value affects the initial connection attempt as well,
551  * so setting this may cause calls to g_socket_client_connect(), etc,
552  * to fail with %G_IO_ERROR_TIMED_OUT.
553  *
554  * Since: 2.26
555  */
556 void
557 g_socket_client_set_timeout (GSocketClient *client,
558                              guint          timeout)
559 {
560   if (client->priv->timeout == timeout)
561     return;
562
563   client->priv->timeout = timeout;
564   g_object_notify (G_OBJECT (client), "timeout");
565 }
566
567 /**
568  * g_socket_client_get_enable_proxy:
569  * @client: a #GSocketClient.
570  *
571  * Gets the proxy enable state; see g_socket_client_set_enable_proxy()
572  *
573  * Returns: whether proxying is enabled
574  *
575  * Since: 2.26
576  */
577 gboolean
578 g_socket_client_get_enable_proxy (GSocketClient *client)
579 {
580   return client->priv->enable_proxy;
581 }
582
583 /**
584  * g_socket_client_set_enable_proxy:
585  * @client: a #GSocketClient.
586  * @enable: whether to enable proxies
587  *
588  * Sets whether or not @client attempts to make connections via a
589  * proxy server. When enabled (the default), #GSocketClient will use a
590  * #GProxyResolver to determine if a proxy protocol such as SOCKS is
591  * needed, and automatically do the necessary proxy negotiation.
592  *
593  * See also g_socket_client_set_proxy_resolver().
594  *
595  * Since: 2.26
596  */
597 void
598 g_socket_client_set_enable_proxy (GSocketClient *client,
599                                   gboolean       enable)
600 {
601   enable = !!enable;
602   if (client->priv->enable_proxy == enable)
603     return;
604
605   client->priv->enable_proxy = enable;
606   g_object_notify (G_OBJECT (client), "enable-proxy");
607 }
608
609 /**
610  * g_socket_client_get_tls:
611  * @client: a #GSocketClient.
612  *
613  * Gets whether @client creates TLS connections. See
614  * g_socket_client_set_tls() for details.
615  *
616  * Returns: whether @client uses TLS
617  *
618  * Since: 2.28
619  */
620 gboolean
621 g_socket_client_get_tls (GSocketClient *client)
622 {
623   return client->priv->tls;
624 }
625
626 /**
627  * g_socket_client_set_tls:
628  * @client: a #GSocketClient.
629  * @tls: whether to use TLS
630  *
631  * Sets whether @client creates TLS (aka SSL) connections. If @tls is
632  * %TRUE, @client will wrap its connections in a #GTlsClientConnection
633  * and perform a TLS handshake when connecting.
634  *
635  * Note that since #GSocketClient must return a #GSocketConnection,
636  * but #GTlsClientConnection is not a #GSocketConnection, this
637  * actually wraps the resulting #GTlsClientConnection in a
638  * #GTcpWrapperConnection when returning it. You can use
639  * g_tcp_wrapper_connection_get_base_io_stream() on the return value
640  * to extract the #GTlsClientConnection.
641  *
642  * If you need to modify the behavior of the TLS handshake (eg, by
643  * setting a client-side certificate to use, or connecting to the
644  * #GTlsConnection::accept-certificate signal), you can connect to
645  * @client's #GSocketClient::event signal and wait for it to be
646  * emitted with %G_SOCKET_CLIENT_TLS_HANDSHAKING, which will give you
647  * a chance to see the #GTlsClientConnection before the handshake
648  * starts.
649  *
650  * Since: 2.28
651  */
652 void
653 g_socket_client_set_tls (GSocketClient *client,
654                          gboolean       tls)
655 {
656   tls = !!tls;
657   if (tls == client->priv->tls)
658     return;
659
660   client->priv->tls = tls;
661   g_object_notify (G_OBJECT (client), "tls");
662 }
663
664 /**
665  * g_socket_client_get_tls_validation_flags:
666  * @client: a #GSocketClient.
667  *
668  * Gets the TLS validation flags used creating TLS connections via
669  * @client.
670  *
671  * Returns: the TLS validation flags
672  *
673  * Since: 2.28
674  */
675 GTlsCertificateFlags
676 g_socket_client_get_tls_validation_flags (GSocketClient *client)
677 {
678   return client->priv->tls_validation_flags;
679 }
680
681 /**
682  * g_socket_client_set_tls_validation_flags:
683  * @client: a #GSocketClient.
684  * @flags: the validation flags
685  *
686  * Sets the TLS validation flags used when creating TLS connections
687  * via @client. The default value is %G_TLS_CERTIFICATE_VALIDATE_ALL.
688  *
689  * Since: 2.28
690  */
691 void
692 g_socket_client_set_tls_validation_flags (GSocketClient        *client,
693                                           GTlsCertificateFlags  flags)
694 {
695   if (client->priv->tls_validation_flags != flags)
696     {
697       client->priv->tls_validation_flags = flags;
698       g_object_notify (G_OBJECT (client), "tls-validation-flags");
699     }
700 }
701
702 /**
703  * g_socket_client_get_proxy_resolver:
704  * @client: a #GSocketClient.
705  *
706  * Gets the #GProxyResolver being used by @client. Normally, this will
707  * be the resolver returned by g_proxy_resolver_get_default(), but you
708  * can override it with g_socket_client_set_proxy_resolver().
709  *
710  * Returns: (transfer none): The #GProxyResolver being used by
711  *   @client.
712  *
713  * Since: 2.36
714  */
715 GProxyResolver *
716 g_socket_client_get_proxy_resolver (GSocketClient *client)
717 {
718   if (client->priv->proxy_resolver)
719     return client->priv->proxy_resolver;
720   else
721     return g_proxy_resolver_get_default ();
722 }
723
724 /**
725  * g_socket_client_set_proxy_resolver:
726  * @client: a #GSocketClient.
727  * @proxy_resolver: (allow-none): a #GProxyResolver, or %NULL for the
728  *   default.
729  *
730  * Overrides the #GProxyResolver used by @client. You can call this if
731  * you want to use specific proxies, rather than using the system
732  * default proxy settings.
733  *
734  * Note that whether or not the proxy resolver is actually used
735  * depends on the setting of #GSocketClient:enable-proxy, which is not
736  * changed by this function (but which is %TRUE by default)
737  *
738  * Since: 2.36
739  */
740 void
741 g_socket_client_set_proxy_resolver (GSocketClient  *client,
742                                     GProxyResolver *proxy_resolver)
743 {
744   /* We have to be careful to avoid calling
745    * g_proxy_resolver_get_default() until we're sure we need it,
746    * because trying to load the default proxy resolver module will
747    * break some test programs that aren't expecting it (eg,
748    * tests/gsettings).
749    */
750
751   if (client->priv->proxy_resolver)
752     g_object_unref (client->priv->proxy_resolver);
753
754   client->priv->proxy_resolver = proxy_resolver;
755
756   if (client->priv->proxy_resolver)
757     g_object_ref (client->priv->proxy_resolver);
758 }
759
760 static void
761 g_socket_client_class_init (GSocketClientClass *class)
762 {
763   GObjectClass *gobject_class = G_OBJECT_CLASS (class);
764
765   g_type_class_add_private (class, sizeof (GSocketClientPrivate));
766
767   gobject_class->finalize = g_socket_client_finalize;
768   gobject_class->set_property = g_socket_client_set_property;
769   gobject_class->get_property = g_socket_client_get_property;
770
771   /**
772    * GSocketClient::event:
773    * @client: the #GSocketClient
774    * @event: the event that is occurring
775    * @connectable: the #GSocketConnectable that @event is occurring on
776    * @connection: the current representation of the connection
777    *
778    * Emitted when @client's activity on @connectable changes state.
779    * Among other things, this can be used to provide progress
780    * information about a network connection in the UI. The meanings of
781    * the different @event values are as follows:
782    *
783    * <variablelist>
784    *   <varlistentry>
785    *     <term>%G_SOCKET_CLIENT_RESOLVING:</term>
786    *     <listitem><para>
787    *       @client is about to look up @connectable in DNS.
788    *       @connection will be %NULL.
789    *     </para></listitem>
790    *   </varlistentry>
791    *   <varlistentry>
792    *     <term>%G_SOCKET_CLIENT_RESOLVED:</term>
793    *     <listitem><para>
794    *       @client has successfully resolved @connectable in DNS.
795    *       @connection will be %NULL.
796    *     </para></listitem>
797    *   </varlistentry>
798    *   <varlistentry>
799    *     <term>%G_SOCKET_CLIENT_CONNECTING:</term>
800    *     <listitem><para>
801    *       @client is about to make a connection to a remote host;
802    *       either a proxy server or the destination server itself.
803    *       @connection is the #GSocketConnection, which is not yet
804    *       connected.
805    *     </para></listitem>
806    *   </varlistentry>
807    *   <varlistentry>
808    *     <term>%G_SOCKET_CLIENT_CONNECTED:</term>
809    *     <listitem><para>
810    *       @client has successfully connected to a remote host.
811    *       @connection is the connected #GSocketConnection.
812    *     </para></listitem>
813    *   </varlistentry>
814    *   <varlistentry>
815    *     <term>%G_SOCKET_CLIENT_PROXY_NEGOTIATING:</term>
816    *     <listitem><para>
817    *       @client is about to negotiate with a proxy to get it to
818    *       connect to @connectable. @connection is the
819    *       #GSocketConnection to the proxy server.
820    *     </para></listitem>
821    *   </varlistentry>
822    *   <varlistentry>
823    *     <term>%G_SOCKET_CLIENT_PROXY_NEGOTIATED:</term>
824    *     <listitem><para>
825    *       @client has negotiated a connection to @connectable through
826    *       a proxy server. @connection is the stream returned from
827    *       g_proxy_connect(), which may or may not be a
828    *       #GSocketConnection.
829    *     </para></listitem>
830    *   </varlistentry>
831    *   <varlistentry>
832    *     <term>%G_SOCKET_CLIENT_TLS_HANDSHAKING:</term>
833    *     <listitem><para>
834    *       @client is about to begin a TLS handshake. @connection is a
835    *       #GTlsClientConnection.
836    *     </para></listitem>
837    *   </varlistentry>
838    *   <varlistentry>
839    *     <term>%G_SOCKET_CLIENT_TLS_HANDSHAKED:</term>
840    *     <listitem><para>
841    *       @client has successfully completed the TLS handshake.
842    *       @connection is a #GTlsClientConnection.
843    *     </para></listitem>
844    *   </varlistentry>
845    *   <varlistentry>
846    *     <term>%G_SOCKET_CLIENT_COMPLETE:</term>
847    *     <listitem><para>
848    *       @client has either successfully connected to @connectable
849    *       (in which case @connection is the #GSocketConnection that
850    *       it will be returning to the caller) or has failed (in which
851    *       case @connection is %NULL and the client is about to return
852    *       an error).
853    *     </para></listitem>
854    *   </varlistentry>
855    * </variablelist>
856    *
857    * Each event except %G_SOCKET_CLIENT_COMPLETE may be emitted
858    * multiple times (or not at all) for a given connectable (in
859    * particular, if @client ends up attempting to connect to more than
860    * one address). However, if @client emits the #GSocketClient::event
861    * signal at all for a given connectable, that it will always emit
862    * it with %G_SOCKET_CLIENT_COMPLETE when it is done.
863    *
864    * Note that there may be additional #GSocketClientEvent values in
865    * the future; unrecognized @event values should be ignored.
866    *
867    * Since: 2.32
868    */
869   signals[EVENT] =
870     g_signal_new (I_("event"),
871                   G_TYPE_FROM_CLASS (gobject_class),
872                   G_SIGNAL_RUN_LAST,
873                   G_STRUCT_OFFSET (GSocketClientClass, event),
874                   NULL, NULL,
875                   NULL,
876                   G_TYPE_NONE, 3,
877                   G_TYPE_SOCKET_CLIENT_EVENT,
878                   G_TYPE_SOCKET_CONNECTABLE,
879                   G_TYPE_IO_STREAM);
880
881   g_object_class_install_property (gobject_class, PROP_FAMILY,
882                                    g_param_spec_enum ("family",
883                                                       P_("Socket family"),
884                                                       P_("The sockets address family to use for socket construction"),
885                                                       G_TYPE_SOCKET_FAMILY,
886                                                       G_SOCKET_FAMILY_INVALID,
887                                                       G_PARAM_CONSTRUCT |
888                                                       G_PARAM_READWRITE |
889                                                       G_PARAM_STATIC_STRINGS));
890
891   g_object_class_install_property (gobject_class, PROP_TYPE,
892                                    g_param_spec_enum ("type",
893                                                       P_("Socket type"),
894                                                       P_("The sockets type to use for socket construction"),
895                                                       G_TYPE_SOCKET_TYPE,
896                                                       G_SOCKET_TYPE_STREAM,
897                                                       G_PARAM_CONSTRUCT |
898                                                       G_PARAM_READWRITE |
899                                                       G_PARAM_STATIC_STRINGS));
900
901   g_object_class_install_property (gobject_class, PROP_PROTOCOL,
902                                    g_param_spec_enum ("protocol",
903                                                       P_("Socket protocol"),
904                                                       P_("The protocol to use for socket construction, or 0 for default"),
905                                                       G_TYPE_SOCKET_PROTOCOL,
906                                                       G_SOCKET_PROTOCOL_DEFAULT,
907                                                       G_PARAM_CONSTRUCT |
908                                                       G_PARAM_READWRITE |
909                                                       G_PARAM_STATIC_STRINGS));
910
911   g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
912                                    g_param_spec_object ("local-address",
913                                                         P_("Local address"),
914                                                         P_("The local address constructed sockets will be bound to"),
915                                                         G_TYPE_SOCKET_ADDRESS,
916                                                         G_PARAM_CONSTRUCT |
917                                                         G_PARAM_READWRITE |
918                                                         G_PARAM_STATIC_STRINGS));
919
920   g_object_class_install_property (gobject_class, PROP_TIMEOUT,
921                                    g_param_spec_uint ("timeout",
922                                                       P_("Socket timeout"),
923                                                       P_("The I/O timeout for sockets, or 0 for none"),
924                                                       0, G_MAXUINT, 0,
925                                                       G_PARAM_CONSTRUCT |
926                                                       G_PARAM_READWRITE |
927                                                       G_PARAM_STATIC_STRINGS));
928
929    g_object_class_install_property (gobject_class, PROP_ENABLE_PROXY,
930                                     g_param_spec_boolean ("enable-proxy",
931                                                           P_("Enable proxy"),
932                                                           P_("Enable proxy support"),
933                                                           TRUE,
934                                                           G_PARAM_CONSTRUCT |
935                                                           G_PARAM_READWRITE |
936                                                           G_PARAM_STATIC_STRINGS));
937
938   g_object_class_install_property (gobject_class, PROP_TLS,
939                                    g_param_spec_boolean ("tls",
940                                                          P_("TLS"),
941                                                          P_("Whether to create TLS connections"),
942                                                          FALSE,
943                                                          G_PARAM_CONSTRUCT |
944                                                          G_PARAM_READWRITE |
945                                                          G_PARAM_STATIC_STRINGS));
946   g_object_class_install_property (gobject_class, PROP_TLS_VALIDATION_FLAGS,
947                                    g_param_spec_flags ("tls-validation-flags",
948                                                        P_("TLS validation flags"),
949                                                        P_("TLS validation flags to use"),
950                                                        G_TYPE_TLS_CERTIFICATE_FLAGS,
951                                                        G_TLS_CERTIFICATE_VALIDATE_ALL,
952                                                        G_PARAM_CONSTRUCT |
953                                                        G_PARAM_READWRITE |
954                                                        G_PARAM_STATIC_STRINGS));
955
956   /**
957    * GSocketClient:proxy-resolver:
958    *
959    * The proxy resolver to use
960    *
961    * Since: 2.36
962    */
963   g_object_class_install_property (gobject_class, PROP_PROXY_RESOLVER,
964                                    g_param_spec_object ("proxy-resolver",
965                                                         P_("Proxy resolver"),
966                                                         P_("The proxy resolver to use"),
967                                                         G_TYPE_PROXY_RESOLVER,
968                                                         G_PARAM_CONSTRUCT |
969                                                         G_PARAM_READWRITE |
970                                                         G_PARAM_STATIC_STRINGS));
971 }
972
973 static void
974 g_socket_client_emit_event (GSocketClient       *client,
975                             GSocketClientEvent  event,
976                             GSocketConnectable  *connectable,
977                             GIOStream           *connection)
978 {
979   g_signal_emit (client, signals[EVENT], 0,
980                  event, connectable, connection);
981 }
982
983 /**
984  * g_socket_client_connect:
985  * @client: a #GSocketClient.
986  * @connectable: a #GSocketConnectable specifying the remote address.
987  * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore.
988  * @error: #GError for error reporting, or %NULL to ignore.
989  *
990  * Tries to resolve the @connectable and make a network connection to it.
991  *
992  * Upon a successful connection, a new #GSocketConnection is constructed
993  * and returned.  The caller owns this new object and must drop their
994  * reference to it when finished with it.
995  *
996  * The type of the #GSocketConnection object returned depends on the type of
997  * the underlying socket that is used. For instance, for a TCP/IP connection
998  * it will be a #GTcpConnection.
999  *
1000  * The socket created will be the same family as the address that the
1001  * @connectable resolves to, unless family is set with g_socket_client_set_family()
1002  * or indirectly via g_socket_client_set_local_address(). The socket type
1003  * defaults to %G_SOCKET_TYPE_STREAM but can be set with
1004  * g_socket_client_set_socket_type().
1005  *
1006  * If a local address is specified with g_socket_client_set_local_address() the
1007  * socket will be bound to this address before connecting.
1008  *
1009  * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
1010  *
1011  * Since: 2.22
1012  */
1013 GSocketConnection *
1014 g_socket_client_connect (GSocketClient       *client,
1015                          GSocketConnectable  *connectable,
1016                          GCancellable        *cancellable,
1017                          GError             **error)
1018 {
1019   GIOStream *connection = NULL;
1020   GSocketAddressEnumerator *enumerator = NULL;
1021   GError *last_error, *tmp_error;
1022
1023   last_error = NULL;
1024
1025   if (can_use_proxy (client))
1026     {
1027       enumerator = g_socket_connectable_proxy_enumerate (connectable);
1028       if (client->priv->proxy_resolver &&
1029           G_IS_PROXY_ADDRESS_ENUMERATOR (enumerator))
1030         {
1031           g_object_set (G_OBJECT (enumerator), "proxy-resolver",
1032                         client->priv->proxy_resolver);
1033         }
1034     }
1035   else
1036     enumerator = g_socket_connectable_enumerate (connectable);
1037
1038   while (connection == NULL)
1039     {
1040       GSocketAddress *address = NULL;
1041       gboolean application_proxy = FALSE;
1042       GSocket *socket;
1043       gboolean using_proxy;
1044
1045       if (g_cancellable_is_cancelled (cancellable))
1046         {
1047           g_clear_error (error);
1048           g_cancellable_set_error_if_cancelled (cancellable, error);
1049           break;
1050         }
1051
1052       tmp_error = NULL;
1053       g_socket_client_emit_event (client, G_SOCKET_CLIENT_RESOLVING,
1054                                   connectable, NULL);
1055       address = g_socket_address_enumerator_next (enumerator, cancellable,
1056                                                   &tmp_error);
1057
1058       if (address == NULL)
1059         {
1060           if (tmp_error)
1061             {
1062               g_clear_error (&last_error);
1063               g_propagate_error (error, tmp_error);
1064             }
1065           else if (last_error)
1066             {
1067               g_propagate_error (error, last_error);
1068             }
1069           else
1070             g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1071                                  _("Unknown error on connect"));
1072           break;
1073         }
1074       g_socket_client_emit_event (client, G_SOCKET_CLIENT_RESOLVED,
1075                                   connectable, NULL);
1076
1077       using_proxy = (G_IS_PROXY_ADDRESS (address) &&
1078                      client->priv->enable_proxy);
1079
1080       /* clear error from previous attempt */
1081       g_clear_error (&last_error);
1082
1083       socket = create_socket (client, address, &last_error);
1084       if (socket == NULL)
1085         {
1086           g_object_unref (address);
1087           continue;
1088         }
1089
1090       connection = (GIOStream *)g_socket_connection_factory_create_connection (socket);
1091       g_socket_client_emit_event (client, G_SOCKET_CLIENT_CONNECTING, connectable, connection);
1092
1093       if (g_socket_connection_connect (G_SOCKET_CONNECTION (connection),
1094                                        address, cancellable, &last_error))
1095         {
1096           g_socket_client_emit_event (client, G_SOCKET_CLIENT_CONNECTED, connectable, connection);
1097         }
1098       else
1099         {
1100           clarify_connect_error (last_error, connectable, address);
1101           g_object_unref (connection);
1102           connection = NULL;
1103         }
1104
1105       if (connection && using_proxy)
1106         {
1107           GProxyAddress *proxy_addr = G_PROXY_ADDRESS (address);
1108           const gchar *protocol;
1109           GProxy *proxy;
1110
1111           protocol = g_proxy_address_get_protocol (proxy_addr);
1112           proxy = g_proxy_get_default_for_protocol (protocol);
1113
1114           /* The connection should not be anything else then TCP Connection,
1115            * but let's put a safety guard in case
1116            */
1117           if (!G_IS_TCP_CONNECTION (connection))
1118             {
1119               g_critical ("Trying to proxy over non-TCP connection, this is "
1120                           "most likely a bug in GLib IO library.");
1121
1122               g_set_error_literal (&last_error,
1123                   G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1124                   _("Proxying over a non-TCP connection is not supported."));
1125
1126               g_object_unref (connection);
1127               connection = NULL;
1128             }
1129           else if (proxy)
1130             {
1131               GIOStream *proxy_connection;
1132
1133               g_socket_client_emit_event (client, G_SOCKET_CLIENT_PROXY_NEGOTIATING, connectable, connection);
1134               proxy_connection = g_proxy_connect (proxy,
1135                                                   connection,
1136                                                   proxy_addr,
1137                                                   cancellable,
1138                                                   &last_error);
1139               g_object_unref (connection);
1140               connection = proxy_connection;
1141               g_object_unref (proxy);
1142
1143               if (connection)
1144                 g_socket_client_emit_event (client, G_SOCKET_CLIENT_PROXY_NEGOTIATED, connectable, connection);
1145             }
1146           else if (!g_hash_table_lookup_extended (client->priv->app_proxies,
1147                                                   protocol, NULL, NULL))
1148             {
1149               g_set_error (&last_error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1150                            _("Proxy protocol '%s' is not supported."),
1151                            protocol);
1152               g_object_unref (connection);
1153               connection = NULL;
1154             }
1155           else
1156             {
1157               application_proxy = TRUE;
1158             }
1159         }
1160
1161       if (!application_proxy && connection && client->priv->tls)
1162         {
1163           GIOStream *tlsconn;
1164
1165           tlsconn = g_tls_client_connection_new (connection, connectable, &last_error);
1166           g_object_unref (connection);
1167           connection = tlsconn;
1168
1169           if (tlsconn)
1170             {
1171               g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (tlsconn),
1172                                                             client->priv->tls_validation_flags);
1173               g_socket_client_emit_event (client, G_SOCKET_CLIENT_TLS_HANDSHAKING, connectable, connection);
1174               if (g_tls_connection_handshake (G_TLS_CONNECTION (tlsconn),
1175                                               cancellable, &last_error))
1176                 {
1177                   g_socket_client_emit_event (client, G_SOCKET_CLIENT_TLS_HANDSHAKED, connectable, connection);
1178                 }
1179               else
1180                 {
1181                   g_object_unref (tlsconn);
1182                   connection = NULL;
1183                 }
1184             }
1185         }
1186
1187       if (connection && !G_IS_SOCKET_CONNECTION (connection))
1188         {
1189           GSocketConnection *wrapper_connection;
1190
1191           wrapper_connection = g_tcp_wrapper_connection_new (connection, socket);
1192           g_object_unref (connection);
1193           connection = (GIOStream *)wrapper_connection;
1194         }
1195
1196       g_object_unref (socket);
1197       g_object_unref (address);
1198     }
1199   g_object_unref (enumerator);
1200
1201   g_socket_client_emit_event (client, G_SOCKET_CLIENT_COMPLETE, connectable, connection);
1202   return G_SOCKET_CONNECTION (connection);
1203 }
1204
1205 /**
1206  * g_socket_client_connect_to_host:
1207  * @client: a #GSocketClient
1208  * @host_and_port: the name and optionally port of the host to connect to
1209  * @default_port: the default port to connect to
1210  * @cancellable: (allow-none): a #GCancellable, or %NULL
1211  * @error: a pointer to a #GError, or %NULL
1212  *
1213  * This is a helper function for g_socket_client_connect().
1214  *
1215  * Attempts to create a TCP connection to the named host.
1216  *
1217  * @host_and_port may be in any of a number of recognized formats; an IPv6
1218  * address, an IPv4 address, or a domain name (in which case a DNS
1219  * lookup is performed).  Quoting with [] is supported for all address
1220  * types.  A port override may be specified in the usual way with a
1221  * colon.  Ports may be given as decimal numbers or symbolic names (in
1222  * which case an /etc/services lookup is performed).
1223  *
1224  * If no port override is given in @host_and_port then @default_port will be
1225  * used as the port number to connect to.
1226  *
1227  * In general, @host_and_port is expected to be provided by the user (allowing
1228  * them to give the hostname, and a port override if necessary) and
1229  * @default_port is expected to be provided by the application.
1230  *
1231  * In the case that an IP address is given, a single connection
1232  * attempt is made.  In the case that a name is given, multiple
1233  * connection attempts may be made, in turn and according to the
1234  * number of address records in DNS, until a connection succeeds.
1235  *
1236  * Upon a successful connection, a new #GSocketConnection is constructed
1237  * and returned.  The caller owns this new object and must drop their
1238  * reference to it when finished with it.
1239  *
1240  * In the event of any failure (DNS error, service not found, no hosts
1241  * connectable) %NULL is returned and @error (if non-%NULL) is set
1242  * accordingly.
1243  *
1244  * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
1245  *
1246  * Since: 2.22
1247  */
1248 GSocketConnection *
1249 g_socket_client_connect_to_host (GSocketClient  *client,
1250                                  const gchar    *host_and_port,
1251                                  guint16         default_port,
1252                                  GCancellable   *cancellable,
1253                                  GError        **error)
1254 {
1255   GSocketConnectable *connectable;
1256   GSocketConnection *connection;
1257
1258   connectable = g_network_address_parse (host_and_port, default_port, error);
1259   if (connectable == NULL)
1260     return NULL;
1261
1262   connection = g_socket_client_connect (client, connectable,
1263                                         cancellable, error);
1264   g_object_unref (connectable);
1265
1266   return connection;
1267 }
1268
1269 /**
1270  * g_socket_client_connect_to_service:
1271  * @client: a #GSocketConnection
1272  * @domain: a domain name
1273  * @service: the name of the service to connect to
1274  * @cancellable: (allow-none): a #GCancellable, or %NULL
1275  * @error: a pointer to a #GError, or %NULL
1276  *
1277  * Attempts to create a TCP connection to a service.
1278  *
1279  * This call looks up the SRV record for @service at @domain for the
1280  * "tcp" protocol.  It then attempts to connect, in turn, to each of
1281  * the hosts providing the service until either a connection succeeds
1282  * or there are no hosts remaining.
1283  *
1284  * Upon a successful connection, a new #GSocketConnection is constructed
1285  * and returned.  The caller owns this new object and must drop their
1286  * reference to it when finished with it.
1287  *
1288  * In the event of any failure (DNS error, service not found, no hosts
1289  * connectable) %NULL is returned and @error (if non-%NULL) is set
1290  * accordingly.
1291  *
1292  * Returns: (transfer full): a #GSocketConnection if successful, or %NULL on error
1293  */
1294 GSocketConnection *
1295 g_socket_client_connect_to_service (GSocketClient  *client,
1296                                     const gchar    *domain,
1297                                     const gchar    *service,
1298                                     GCancellable   *cancellable,
1299                                     GError        **error)
1300 {
1301   GSocketConnectable *connectable;
1302   GSocketConnection *connection;
1303
1304   connectable = g_network_service_new (service, "tcp", domain);
1305   connection = g_socket_client_connect (client, connectable,
1306                                         cancellable, error);
1307   g_object_unref (connectable);
1308
1309   return connection;
1310 }
1311
1312 /**
1313  * g_socket_client_connect_to_uri:
1314  * @client: a #GSocketClient
1315  * @uri: A network URI
1316  * @default_port: the default port to connect to
1317  * @cancellable: (allow-none): a #GCancellable, or %NULL
1318  * @error: a pointer to a #GError, or %NULL
1319  *
1320  * This is a helper function for g_socket_client_connect().
1321  *
1322  * Attempts to create a TCP connection with a network URI.
1323  *
1324  * @uri may be any valid URI containing an "authority" (hostname/port)
1325  * component. If a port is not specified in the URI, @default_port
1326  * will be used. TLS will be negotiated if #GSocketClient:tls is %TRUE.
1327  * (#GSocketClient does not know to automatically assume TLS for
1328  * certain URI schemes.)
1329  *
1330  * Using this rather than g_socket_client_connect() or
1331  * g_socket_client_connect_to_host() allows #GSocketClient to
1332  * determine when to use application-specific proxy protocols.
1333  *
1334  * Upon a successful connection, a new #GSocketConnection is constructed
1335  * and returned.  The caller owns this new object and must drop their
1336  * reference to it when finished with it.
1337  *
1338  * In the event of any failure (DNS error, service not found, no hosts
1339  * connectable) %NULL is returned and @error (if non-%NULL) is set
1340  * accordingly.
1341  *
1342  * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
1343  *
1344  * Since: 2.26
1345  */
1346 GSocketConnection *
1347 g_socket_client_connect_to_uri (GSocketClient  *client,
1348                                 const gchar    *uri,
1349                                 guint16         default_port,
1350                                 GCancellable   *cancellable,
1351                                 GError        **error)
1352 {
1353   GSocketConnectable *connectable;
1354   GSocketConnection *connection;
1355
1356   connectable = g_network_address_parse_uri (uri, default_port, error);
1357   if (connectable == NULL)
1358     return NULL;
1359
1360   connection = g_socket_client_connect (client, connectable,
1361                                         cancellable, error);
1362   g_object_unref (connectable);
1363
1364   return connection;
1365 }
1366
1367 typedef struct
1368 {
1369   GTask *task;
1370   GSocketClient *client;
1371
1372   GSocketConnectable *connectable;
1373   GSocketAddressEnumerator *enumerator;
1374   GProxyAddress *proxy_addr;
1375   GSocketAddress *current_addr;
1376   GSocket *current_socket;
1377   GIOStream *connection;
1378
1379   GError *last_error;
1380 } GSocketClientAsyncConnectData;
1381
1382 static void
1383 g_socket_client_async_connect_data_free (GSocketClientAsyncConnectData *data)
1384 {
1385   g_clear_object (&data->connectable);
1386   g_clear_object (&data->enumerator);
1387   g_clear_object (&data->proxy_addr);
1388   g_clear_object (&data->current_addr);
1389   g_clear_object (&data->current_socket);
1390   g_clear_object (&data->connection);
1391
1392   g_clear_error (&data->last_error);
1393
1394   g_slice_free (GSocketClientAsyncConnectData, data);
1395 }
1396
1397 static void
1398 g_socket_client_async_connect_complete (GSocketClientAsyncConnectData *data)
1399 {
1400   g_assert (data->connection);
1401
1402   if (!G_IS_SOCKET_CONNECTION (data->connection))
1403     {
1404       GSocketConnection *wrapper_connection;
1405
1406       wrapper_connection = g_tcp_wrapper_connection_new (data->connection,
1407                                                          data->current_socket);
1408       g_object_unref (data->connection);
1409       data->connection = (GIOStream *)wrapper_connection;
1410     }
1411
1412   g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_COMPLETE, data->connectable, data->connection);
1413   g_task_return_pointer (data->task, data->connection, g_object_unref);
1414   data->connection = NULL;
1415   g_object_unref (data->task);
1416 }
1417
1418
1419 static void
1420 g_socket_client_enumerator_callback (GObject      *object,
1421                                      GAsyncResult *result,
1422                                      gpointer      user_data);
1423
1424 static void
1425 set_last_error (GSocketClientAsyncConnectData *data,
1426                 GError *error)
1427 {
1428   g_clear_error (&data->last_error);
1429   data->last_error = error;
1430 }
1431
1432 static void
1433 enumerator_next_async (GSocketClientAsyncConnectData *data)
1434 {
1435   /* We need to cleanup the state */
1436   g_clear_object (&data->current_socket);
1437   g_clear_object (&data->current_addr);
1438   g_clear_object (&data->proxy_addr);
1439   g_clear_object (&data->connection);
1440
1441   g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_RESOLVING, data->connectable, NULL);
1442   g_socket_address_enumerator_next_async (data->enumerator,
1443                                           g_task_get_cancellable (data->task),
1444                                           g_socket_client_enumerator_callback,
1445                                           data);
1446 }
1447
1448 static void
1449 g_socket_client_tls_handshake_callback (GObject      *object,
1450                                         GAsyncResult *result,
1451                                         gpointer      user_data)
1452 {
1453   GSocketClientAsyncConnectData *data = user_data;
1454
1455   if (g_tls_connection_handshake_finish (G_TLS_CONNECTION (object),
1456                                          result,
1457                                          &data->last_error))
1458     {
1459       g_object_unref (data->connection);
1460       data->connection = G_IO_STREAM (object);
1461
1462       g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_TLS_HANDSHAKED, data->connectable, data->connection);
1463       g_socket_client_async_connect_complete (data);
1464     }
1465   else
1466     {
1467       g_object_unref (object);
1468       enumerator_next_async (data);
1469     }
1470 }
1471
1472 static void
1473 g_socket_client_tls_handshake (GSocketClientAsyncConnectData *data)
1474 {
1475   GIOStream *tlsconn;
1476
1477   if (!data->client->priv->tls)
1478     {
1479       g_socket_client_async_connect_complete (data);
1480       return;
1481     }
1482
1483   tlsconn = g_tls_client_connection_new (data->connection,
1484                                          data->connectable,
1485                                          &data->last_error);
1486   if (tlsconn)
1487     {
1488       g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (tlsconn),
1489                                                     data->client->priv->tls_validation_flags);
1490       g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_TLS_HANDSHAKING, data->connectable, G_IO_STREAM (tlsconn));
1491       g_tls_connection_handshake_async (G_TLS_CONNECTION (tlsconn),
1492                                         G_PRIORITY_DEFAULT,
1493                                         g_task_get_cancellable (data->task),
1494                                         g_socket_client_tls_handshake_callback,
1495                                         data);
1496     }
1497   else
1498     {
1499       enumerator_next_async (data);
1500     }
1501 }
1502
1503 static void
1504 g_socket_client_proxy_connect_callback (GObject      *object,
1505                                         GAsyncResult *result,
1506                                         gpointer      user_data)
1507 {
1508   GSocketClientAsyncConnectData *data = user_data;
1509
1510   g_object_unref (data->connection);
1511   data->connection = g_proxy_connect_finish (G_PROXY (object),
1512                                              result,
1513                                              &data->last_error);
1514   if (data->connection)
1515     {
1516       g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_PROXY_NEGOTIATED, data->connectable, data->connection);
1517     }
1518   else
1519     {
1520       enumerator_next_async (data);
1521       return;
1522     }
1523
1524   g_socket_client_tls_handshake (data);
1525 }
1526
1527 static void
1528 g_socket_client_connected_callback (GObject      *source,
1529                                     GAsyncResult *result,
1530                                     gpointer      user_data)
1531 {
1532   GSocketClientAsyncConnectData *data = user_data;
1533   GError *error = NULL;
1534   GProxy *proxy;
1535   const gchar *protocol;
1536
1537   if (!g_socket_connection_connect_finish (G_SOCKET_CONNECTION (source),
1538                                            result, &error))
1539     {
1540       clarify_connect_error (error, data->connectable,
1541                              data->current_addr);
1542       set_last_error (data, error);
1543
1544       /* try next one */
1545       enumerator_next_async (data);
1546       return;
1547     }
1548
1549   g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_CONNECTED, data->connectable, data->connection);
1550
1551   /* wrong, but backward compatible */
1552   g_socket_set_blocking (data->current_socket, TRUE);
1553
1554   if (!data->proxy_addr)
1555     {
1556       g_socket_client_tls_handshake (data);
1557       return;
1558     }
1559
1560   protocol = g_proxy_address_get_protocol (data->proxy_addr);
1561   proxy = g_proxy_get_default_for_protocol (protocol);
1562
1563   /* The connection should not be anything other than TCP,
1564    * but let's put a safety guard in case
1565    */
1566   if (!G_IS_TCP_CONNECTION (data->connection))
1567     {
1568       g_critical ("Trying to proxy over non-TCP connection, this is "
1569           "most likely a bug in GLib IO library.");
1570
1571       g_set_error_literal (&data->last_error,
1572           G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1573           _("Proxying over a non-TCP connection is not supported."));
1574
1575       enumerator_next_async (data);
1576     }
1577   else if (proxy)
1578     {
1579       g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_PROXY_NEGOTIATING, data->connectable, data->connection);
1580       g_proxy_connect_async (proxy,
1581                              data->connection,
1582                              data->proxy_addr,
1583                              g_task_get_cancellable (data->task),
1584                              g_socket_client_proxy_connect_callback,
1585                              data);
1586       g_object_unref (proxy);
1587     }
1588   else if (!g_hash_table_lookup_extended (data->client->priv->app_proxies,
1589                                           protocol, NULL, NULL))
1590     {
1591       g_clear_error (&data->last_error);
1592
1593       g_set_error (&data->last_error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
1594           _("Proxy protocol '%s' is not supported."),
1595           protocol);
1596
1597       enumerator_next_async (data);
1598     }
1599   else
1600     {
1601       /* Simply complete the connection, we don't want to do TLS handshake
1602        * as the application proxy handling may need proxy handshake first */
1603       g_socket_client_async_connect_complete (data);
1604     }
1605 }
1606
1607 static void
1608 g_socket_client_enumerator_callback (GObject      *object,
1609                                      GAsyncResult *result,
1610                                      gpointer      user_data)
1611 {
1612   GSocketClientAsyncConnectData *data = user_data;
1613   GSocketAddress *address = NULL;
1614   GSocket *socket;
1615   GError *error = NULL;
1616
1617   if (g_task_return_error_if_cancelled (data->task))
1618     return;
1619
1620   address = g_socket_address_enumerator_next_finish (data->enumerator,
1621                                                      result, &error);
1622   if (address == NULL)
1623     {
1624       g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_COMPLETE, data->connectable, NULL);
1625       if (!error)
1626         {
1627           if (data->last_error)
1628             {
1629               error = data->last_error;
1630               data->last_error = NULL;
1631             }
1632           else
1633             {
1634               g_set_error_literal (&error, G_IO_ERROR, G_IO_ERROR_FAILED,
1635                                    _("Unknown error on connect"));
1636             }
1637         }
1638       g_task_return_error (data->task, error);
1639       g_object_unref (data->task);
1640       return;
1641     }
1642
1643   g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_RESOLVED,
1644                               data->connectable, NULL);
1645
1646   if (G_IS_PROXY_ADDRESS (address) &&
1647       data->client->priv->enable_proxy)
1648     data->proxy_addr = g_object_ref (G_PROXY_ADDRESS (address));
1649
1650   g_clear_error (&data->last_error);
1651
1652   socket = create_socket (data->client, address, &data->last_error);
1653   if (socket == NULL)
1654     {
1655       g_object_unref (address);
1656       enumerator_next_async (data);
1657       return;
1658     }
1659
1660   data->current_socket = socket;
1661   data->current_addr = address;
1662   data->connection = (GIOStream *) g_socket_connection_factory_create_connection (socket);
1663
1664   g_socket_client_emit_event (data->client, G_SOCKET_CLIENT_CONNECTING, data->connectable, data->connection);
1665   g_socket_connection_connect_async (G_SOCKET_CONNECTION (data->connection),
1666                                      address,
1667                                      g_task_get_cancellable (data->task),
1668                                      g_socket_client_connected_callback, data);
1669 }
1670
1671 /**
1672  * g_socket_client_connect_async:
1673  * @client: a #GSocketClient
1674  * @connectable: a #GSocketConnectable specifying the remote address.
1675  * @cancellable: (allow-none): a #GCancellable, or %NULL
1676  * @callback: (scope async): a #GAsyncReadyCallback
1677  * @user_data: (closure): user data for the callback
1678  *
1679  * This is the asynchronous version of g_socket_client_connect().
1680  *
1681  * When the operation is finished @callback will be
1682  * called. You can then call g_socket_client_connect_finish() to get
1683  * the result of the operation.
1684  *
1685  * Since: 2.22
1686  */
1687 void
1688 g_socket_client_connect_async (GSocketClient       *client,
1689                                GSocketConnectable  *connectable,
1690                                GCancellable        *cancellable,
1691                                GAsyncReadyCallback  callback,
1692                                gpointer             user_data)
1693 {
1694   GSocketClientAsyncConnectData *data;
1695
1696   g_return_if_fail (G_IS_SOCKET_CLIENT (client));
1697
1698   data = g_slice_new0 (GSocketClientAsyncConnectData);
1699   data->client = client;
1700   data->connectable = g_object_ref (connectable);
1701
1702   if (can_use_proxy (client))
1703     {
1704       data->enumerator = g_socket_connectable_proxy_enumerate (connectable);
1705       if (client->priv->proxy_resolver &&
1706           G_IS_PROXY_ADDRESS_ENUMERATOR (data->enumerator))
1707         {
1708           g_object_set (G_OBJECT (data->enumerator), "proxy-resolver",
1709                         client->priv->proxy_resolver);
1710         }
1711     }
1712   else
1713     data->enumerator = g_socket_connectable_enumerate (connectable);
1714
1715   data->task = g_task_new (client, cancellable, callback, user_data);
1716   g_task_set_task_data (data->task, data, (GDestroyNotify)g_socket_client_async_connect_data_free);
1717
1718   enumerator_next_async (data);
1719 }
1720
1721 /**
1722  * g_socket_client_connect_to_host_async:
1723  * @client: a #GSocketClient
1724  * @host_and_port: the name and optionally the port of the host to connect to
1725  * @default_port: the default port to connect to
1726  * @cancellable: (allow-none): a #GCancellable, or %NULL
1727  * @callback: (scope async): a #GAsyncReadyCallback
1728  * @user_data: (closure): user data for the callback
1729  *
1730  * This is the asynchronous version of g_socket_client_connect_to_host().
1731  *
1732  * When the operation is finished @callback will be
1733  * called. You can then call g_socket_client_connect_to_host_finish() to get
1734  * the result of the operation.
1735  *
1736  * Since: 2.22
1737  */
1738 void
1739 g_socket_client_connect_to_host_async (GSocketClient        *client,
1740                                        const gchar          *host_and_port,
1741                                        guint16               default_port,
1742                                        GCancellable         *cancellable,
1743                                        GAsyncReadyCallback   callback,
1744                                        gpointer              user_data)
1745 {
1746   GSocketConnectable *connectable;
1747   GError *error;
1748
1749   error = NULL;
1750   connectable = g_network_address_parse (host_and_port, default_port,
1751                                          &error);
1752   if (connectable == NULL)
1753     {
1754       g_task_report_error (client, callback, user_data,
1755                            g_socket_client_connect_to_host_async,
1756                            error);
1757     }
1758   else
1759     {
1760       g_socket_client_connect_async (client,
1761                                      connectable, cancellable,
1762                                      callback, user_data);
1763       g_object_unref (connectable);
1764     }
1765 }
1766
1767 /**
1768  * g_socket_client_connect_to_service_async:
1769  * @client: a #GSocketClient
1770  * @domain: a domain name
1771  * @service: the name of the service to connect to
1772  * @cancellable: (allow-none): a #GCancellable, or %NULL
1773  * @callback: (scope async): a #GAsyncReadyCallback
1774  * @user_data: (closure): user data for the callback
1775  *
1776  * This is the asynchronous version of
1777  * g_socket_client_connect_to_service().
1778  *
1779  * Since: 2.22
1780  */
1781 void
1782 g_socket_client_connect_to_service_async (GSocketClient       *client,
1783                                           const gchar         *domain,
1784                                           const gchar         *service,
1785                                           GCancellable        *cancellable,
1786                                           GAsyncReadyCallback  callback,
1787                                           gpointer             user_data)
1788 {
1789   GSocketConnectable *connectable;
1790
1791   connectable = g_network_service_new (service, "tcp", domain);
1792   g_socket_client_connect_async (client,
1793                                  connectable, cancellable,
1794                                  callback, user_data);
1795   g_object_unref (connectable);
1796 }
1797
1798 /**
1799  * g_socket_client_connect_to_uri_async:
1800  * @client: a #GSocketClient
1801  * @uri: a network uri
1802  * @default_port: the default port to connect to
1803  * @cancellable: (allow-none): a #GCancellable, or %NULL
1804  * @callback: (scope async): a #GAsyncReadyCallback
1805  * @user_data: (closure): user data for the callback
1806  *
1807  * This is the asynchronous version of g_socket_client_connect_to_uri().
1808  *
1809  * When the operation is finished @callback will be
1810  * called. You can then call g_socket_client_connect_to_uri_finish() to get
1811  * the result of the operation.
1812  *
1813  * Since: 2.26
1814  */
1815 void
1816 g_socket_client_connect_to_uri_async (GSocketClient        *client,
1817                                       const gchar          *uri,
1818                                       guint16               default_port,
1819                                       GCancellable         *cancellable,
1820                                       GAsyncReadyCallback   callback,
1821                                       gpointer              user_data)
1822 {
1823   GSocketConnectable *connectable;
1824   GError *error;
1825
1826   error = NULL;
1827   connectable = g_network_address_parse_uri (uri, default_port, &error);
1828   if (connectable == NULL)
1829     {
1830       g_task_report_error (client, callback, user_data,
1831                            g_socket_client_connect_to_uri_async,
1832                            error);
1833     }
1834   else
1835     {
1836       g_socket_client_connect_async (client,
1837                                      connectable, cancellable,
1838                                      callback, user_data);
1839       g_object_unref (connectable);
1840     }
1841 }
1842
1843
1844 /**
1845  * g_socket_client_connect_finish:
1846  * @client: a #GSocketClient.
1847  * @result: a #GAsyncResult.
1848  * @error: a #GError location to store the error occurring, or %NULL to
1849  * ignore.
1850  *
1851  * Finishes an async connect operation. See g_socket_client_connect_async()
1852  *
1853  * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
1854  *
1855  * Since: 2.22
1856  */
1857 GSocketConnection *
1858 g_socket_client_connect_finish (GSocketClient  *client,
1859                                 GAsyncResult   *result,
1860                                 GError        **error)
1861 {
1862   g_return_val_if_fail (g_task_is_valid (result, client), NULL);
1863
1864   return g_task_propagate_pointer (G_TASK (result), error);
1865 }
1866
1867 /**
1868  * g_socket_client_connect_to_host_finish:
1869  * @client: a #GSocketClient.
1870  * @result: a #GAsyncResult.
1871  * @error: a #GError location to store the error occurring, or %NULL to
1872  * ignore.
1873  *
1874  * Finishes an async connect operation. See g_socket_client_connect_to_host_async()
1875  *
1876  * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
1877  *
1878  * Since: 2.22
1879  */
1880 GSocketConnection *
1881 g_socket_client_connect_to_host_finish (GSocketClient  *client,
1882                                         GAsyncResult   *result,
1883                                         GError        **error)
1884 {
1885   return g_socket_client_connect_finish (client, result, error);
1886 }
1887
1888 /**
1889  * g_socket_client_connect_to_service_finish:
1890  * @client: a #GSocketClient.
1891  * @result: a #GAsyncResult.
1892  * @error: a #GError location to store the error occurring, or %NULL to
1893  * ignore.
1894  *
1895  * Finishes an async connect operation. See g_socket_client_connect_to_service_async()
1896  *
1897  * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
1898  *
1899  * Since: 2.22
1900  */
1901 GSocketConnection *
1902 g_socket_client_connect_to_service_finish (GSocketClient  *client,
1903                                            GAsyncResult   *result,
1904                                            GError        **error)
1905 {
1906   return g_socket_client_connect_finish (client, result, error);
1907 }
1908
1909 /**
1910  * g_socket_client_connect_to_uri_finish:
1911  * @client: a #GSocketClient.
1912  * @result: a #GAsyncResult.
1913  * @error: a #GError location to store the error occurring, or %NULL to
1914  * ignore.
1915  *
1916  * Finishes an async connect operation. See g_socket_client_connect_to_uri_async()
1917  *
1918  * Returns: (transfer full): a #GSocketConnection on success, %NULL on error.
1919  *
1920  * Since: 2.26
1921  */
1922 GSocketConnection *
1923 g_socket_client_connect_to_uri_finish (GSocketClient  *client,
1924                                        GAsyncResult   *result,
1925                                        GError        **error)
1926 {
1927   return g_socket_client_connect_finish (client, result, error);
1928 }
1929
1930 /**
1931  * g_socket_client_add_application_proxy:
1932  * @client: a #GSocketClient
1933  * @protocol: The proxy protocol
1934  *
1935  * Enable proxy protocols to be handled by the application. When the
1936  * indicated proxy protocol is returned by the #GProxyResolver,
1937  * #GSocketClient will consider this protocol as supported but will
1938  * not try to find a #GProxy instance to handle handshaking. The
1939  * application must check for this case by calling
1940  * g_socket_connection_get_remote_address() on the returned
1941  * #GSocketConnection, and seeing if it's a #GProxyAddress of the
1942  * appropriate type, to determine whether or not it needs to handle
1943  * the proxy handshaking itself.
1944  *
1945  * This should be used for proxy protocols that are dialects of
1946  * another protocol such as HTTP proxy. It also allows cohabitation of
1947  * proxy protocols that are reused between protocols. A good example
1948  * is HTTP. It can be used to proxy HTTP, FTP and Gopher and can also
1949  * be use as generic socket proxy through the HTTP CONNECT method.
1950  *
1951  * When the proxy is detected as being an application proxy, TLS handshake
1952  * will be skipped. This is required to let the application do the proxy
1953  * specific handshake.
1954  */
1955 void
1956 g_socket_client_add_application_proxy (GSocketClient *client,
1957                                        const gchar   *protocol)
1958 {
1959   g_hash_table_insert (client->priv->app_proxies, g_strdup (protocol), NULL);
1960 }