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