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