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