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