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