GSocketClient: plug two leaks
[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
30 #include <gio/gioenumtypes.h>
31 #include <gio/gsocketaddressenumerator.h>
32 #include <gio/gsocketconnectable.h>
33 #include <gio/gsocketconnection.h>
34 #include <gio/gsimpleasyncresult.h>
35 #include <gio/gcancellable.h>
36 #include <gio/gioerror.h>
37 #include <gio/gsocket.h>
38 #include <gio/gnetworkaddress.h>
39 #include <gio/gnetworkservice.h>
40 #include <gio/gsocketaddress.h>
41 #include "glibintl.h"
42
43
44 /**
45  * SECTION:gsocketclient
46  * @short_description: Helper for connecting to a network service
47  * @include: gio/gio.h
48  * @see_also: #GSocketConnection, #GSocketListener
49  *
50  * #GSocketClient is a high-level utility class for connecting to a
51  * network host using a connection oriented socket type.
52  *
53  * You create a #GSocketClient object, set any options you want, then
54  * call a sync or async connect operation, which returns a #GSocketConnection
55  * subclass on success.
56  *
57  * The type of the #GSocketConnection object returned depends on the type of
58  * the underlying socket that is in use. For instance, for a TCP/IP connection
59  * it will be a #GTcpConnection.
60  *
61  * Since: 2.22
62  */
63
64
65 G_DEFINE_TYPE (GSocketClient, g_socket_client, G_TYPE_OBJECT);
66
67 enum
68 {
69   PROP_NONE,
70   PROP_FAMILY,
71   PROP_TYPE,
72   PROP_PROTOCOL,
73   PROP_LOCAL_ADDRESS,
74   PROP_TIMEOUT
75 };
76
77 struct _GSocketClientPrivate
78 {
79   GSocketFamily family;
80   GSocketType type;
81   GSocketProtocol protocol;
82   GSocketAddress *local_address;
83   guint timeout;
84 };
85
86 static GSocket *
87 create_socket (GSocketClient  *client,
88                GSocketAddress *dest_address,
89                GError        **error)
90 {
91   GSocketFamily family;
92   GSocket *socket;
93
94   family = client->priv->family;
95   if (family == G_SOCKET_FAMILY_INVALID &&
96       client->priv->local_address != NULL)
97     family = g_socket_address_get_family (client->priv->local_address);
98   if (family == G_SOCKET_FAMILY_INVALID)
99     family = g_socket_address_get_family (dest_address);
100
101   socket = g_socket_new (family,
102                          client->priv->type,
103                          client->priv->protocol,
104                          error);
105   if (socket == NULL)
106     return NULL;
107
108   if (client->priv->local_address)
109     {
110       if (!g_socket_bind (socket,
111                           client->priv->local_address,
112                           FALSE,
113                           error))
114         {
115           g_object_unref (socket);
116           return NULL;
117         }
118     }
119
120   if (client->priv->timeout)
121     g_socket_set_timeout (socket, client->priv->timeout);
122
123   return socket;
124 }
125
126 static void
127 g_socket_client_init (GSocketClient *client)
128 {
129   client->priv = G_TYPE_INSTANCE_GET_PRIVATE (client,
130                                               G_TYPE_SOCKET_CLIENT,
131                                               GSocketClientPrivate);
132   client->priv->type = G_SOCKET_TYPE_STREAM;
133 }
134
135 /**
136  * g_socket_client_new:
137  *
138  * Creates a new #GSocketClient with the default options.
139  *
140  * Returns: a #GSocketClient.
141  *     Free the returned object with g_object_unref().
142  *
143  * Since: 2.22
144  */
145 GSocketClient *
146 g_socket_client_new (void)
147 {
148   return g_object_new (G_TYPE_SOCKET_CLIENT, NULL);
149 }
150
151 static void
152 g_socket_client_finalize (GObject *object)
153 {
154   GSocketClient *client = G_SOCKET_CLIENT (object);
155
156   if (client->priv->local_address)
157     g_object_unref (client->priv->local_address);
158
159   if (G_OBJECT_CLASS (g_socket_client_parent_class)->finalize)
160     (*G_OBJECT_CLASS (g_socket_client_parent_class)->finalize) (object);
161 }
162
163 static void
164 g_socket_client_get_property (GObject    *object,
165                               guint       prop_id,
166                               GValue     *value,
167                               GParamSpec *pspec)
168 {
169   GSocketClient *client = G_SOCKET_CLIENT (object);
170
171   switch (prop_id)
172     {
173       case PROP_FAMILY:
174         g_value_set_enum (value, client->priv->family);
175         break;
176
177       case PROP_TYPE:
178         g_value_set_enum (value, client->priv->type);
179         break;
180
181       case PROP_PROTOCOL:
182         g_value_set_enum (value, client->priv->protocol);
183         break;
184
185       case PROP_LOCAL_ADDRESS:
186         g_value_set_object (value, client->priv->local_address);
187         break;
188
189       case PROP_TIMEOUT:
190         g_value_set_uint (value, client->priv->timeout);
191         break;
192
193       default:
194         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
195     }
196 }
197
198 static void
199 g_socket_client_set_property (GObject      *object,
200                               guint         prop_id,
201                               const GValue *value,
202                               GParamSpec   *pspec)
203 {
204   GSocketClient *client = G_SOCKET_CLIENT (object);
205
206   switch (prop_id)
207     {
208     case PROP_FAMILY:
209       g_socket_client_set_family (client, g_value_get_enum (value));
210       break;
211
212     case PROP_TYPE:
213       g_socket_client_set_socket_type (client, g_value_get_enum (value));
214       break;
215
216     case PROP_PROTOCOL:
217       g_socket_client_set_protocol (client, g_value_get_enum (value));
218       break;
219
220     case PROP_LOCAL_ADDRESS:
221       g_socket_client_set_local_address (client, g_value_get_object (value));
222       break;
223
224     case PROP_TIMEOUT:
225       g_socket_client_set_timeout (client, g_value_get_uint (value));
226       break;
227
228     default:
229       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
230     }
231 }
232
233 /**
234  * g_socket_client_get_family:
235  * @client: a #GSocketClient.
236  *
237  * Gets the socket family of the socket client.
238  *
239  * See g_socket_client_set_family() for details.
240  *
241  * Returns: a #GSocketFamily
242  *
243  * Since: 2.22
244  */
245 GSocketFamily
246 g_socket_client_get_family (GSocketClient *client)
247 {
248   return client->priv->family;
249 }
250
251 /**
252  * g_socket_client_set_family:
253  * @client: a #GSocketClient.
254  * @family: a #GSocketFamily
255  *
256  * Sets the socket family of the socket client.
257  * If this is set to something other than %G_SOCKET_FAMILY_INVALID
258  * then the sockets created by this object will be of the specified
259  * family.
260  *
261  * This might be useful for instance if you want to force the local
262  * connection to be an ipv4 socket, even though the address might
263  * be an ipv6 mapped to ipv4 address.
264  *
265  * Since: 2.22
266  */
267 void
268 g_socket_client_set_family (GSocketClient *client,
269                             GSocketFamily  family)
270 {
271   if (client->priv->family == family)
272     return;
273
274   client->priv->family = family;
275   g_object_notify (G_OBJECT (client), "family");
276 }
277
278 /**
279  * g_socket_client_get_socket_type:
280  * @client: a #GSocketClient.
281  *
282  * Gets the socket type of the socket client.
283  *
284  * See g_socket_client_set_socket_type() for details.
285  *
286  * Returns: a #GSocketFamily
287  *
288  * Since: 2.22
289  */
290 GSocketType
291 g_socket_client_get_socket_type (GSocketClient *client)
292 {
293   return client->priv->type;
294 }
295
296 /**
297  * g_socket_client_set_socket_type:
298  * @client: a #GSocketClient.
299  * @type: a #GSocketType
300  *
301  * Sets the socket type of the socket client.
302  * The sockets created by this object will be of the specified
303  * type.
304  *
305  * It doesn't make sense to specify a type of %G_SOCKET_TYPE_DATAGRAM,
306  * as GSocketClient is used for connection oriented services.
307  *
308  * Since: 2.22
309  */
310 void
311 g_socket_client_set_socket_type (GSocketClient *client,
312                                  GSocketType    type)
313 {
314   if (client->priv->type == type)
315     return;
316
317   client->priv->type = type;
318   g_object_notify (G_OBJECT (client), "type");
319 }
320
321 /**
322  * g_socket_client_get_protocol:
323  * @client: a #GSocketClient
324  *
325  * Gets the protocol name type of the socket client.
326  *
327  * See g_socket_client_set_protocol() for details.
328  *
329  * Returns: a #GSocketProtocol
330  *
331  * Since: 2.22
332  */
333 GSocketProtocol
334 g_socket_client_get_protocol (GSocketClient *client)
335 {
336   return client->priv->protocol;
337 }
338
339 /**
340  * g_socket_client_set_protocol:
341  * @client: a #GSocketClient.
342  * @protocol: a #GSocketProtocol
343  *
344  * Sets the protocol of the socket client.
345  * The sockets created by this object will use of the specified
346  * protocol.
347  *
348  * If @protocol is %0 that means to use the default
349  * protocol for the socket family and type.
350  *
351  * Since: 2.22
352  */
353 void
354 g_socket_client_set_protocol (GSocketClient   *client,
355                               GSocketProtocol  protocol)
356 {
357   if (client->priv->protocol == protocol)
358     return;
359
360   client->priv->protocol = protocol;
361   g_object_notify (G_OBJECT (client), "protocol");
362 }
363
364 /**
365  * g_socket_client_get_local_address:
366  * @client: a #GSocketClient.
367  *
368  * Gets the local address of the socket client.
369  *
370  * See g_socket_client_set_local_address() for details.
371  *
372  * Returns: (transfer none): a #GSocketAddres or %NULL. don't free
373  *
374  * Since: 2.22
375  */
376 GSocketAddress *
377 g_socket_client_get_local_address (GSocketClient *client)
378 {
379   return client->priv->local_address;
380 }
381
382 /**
383  * g_socket_client_set_local_address:
384  * @client: a #GSocketClient.
385  * @address: a #GSocketAddress, or %NULL
386  *
387  * Sets the local address of the socket client.
388  * The sockets created by this object will bound to the
389  * specified address (if not %NULL) before connecting.
390  *
391  * This is useful if you want to ensure the the local
392  * side of the connection is on a specific port, or on
393  * a specific interface.
394  *
395  * Since: 2.22
396  */
397 void
398 g_socket_client_set_local_address (GSocketClient  *client,
399                                    GSocketAddress *address)
400 {
401   if (address)
402   g_object_ref (address);
403
404   if (client->priv->local_address)
405     {
406       g_object_unref (client->priv->local_address);
407     }
408   client->priv->local_address = address;
409   g_object_notify (G_OBJECT (client), "local-address");
410 }
411
412 /**
413  * g_socket_client_get_timeout:
414  * @client: a #GSocketClient
415  *
416  * Gets the I/O timeout time for sockets created by @client.
417  *
418  * See g_socket_client_set_timeout() for details.
419  *
420  * Returns: the timeout in seconds
421  *
422  * Since: 2.26
423  */
424 guint
425 g_socket_client_get_timeout (GSocketClient *client)
426 {
427   return client->priv->timeout;
428 }
429
430
431 /**
432  * g_socket_client_set_timeout:
433  * @client: a #GSocketClient.
434  * @timeout: the timeout
435  *
436  * Sets the I/O timeout for sockets created by @client. @timeout is a
437  * time in seconds, or 0 for no timeout (the default).
438  *
439  * The timeout value affects the initial connection attempt as well,
440  * so setting this may cause calls to g_socket_client_connect(), etc,
441  * to fail with %G_IO_ERROR_TIMED_OUT.
442  *
443  * Since: 2.26
444  */
445 void
446 g_socket_client_set_timeout (GSocketClient *client,
447                              guint          timeout)
448 {
449   if (client->priv->timeout == timeout)
450     return;
451
452   client->priv->timeout = timeout;
453   g_object_notify (G_OBJECT (client), "timeout");
454 }
455
456 static void
457 g_socket_client_class_init (GSocketClientClass *class)
458 {
459   GObjectClass *gobject_class = G_OBJECT_CLASS (class);
460
461   g_type_class_add_private (class, sizeof (GSocketClientPrivate));
462
463   gobject_class->finalize = g_socket_client_finalize;
464   gobject_class->set_property = g_socket_client_set_property;
465   gobject_class->get_property = g_socket_client_get_property;
466
467   g_object_class_install_property (gobject_class, PROP_FAMILY,
468                                    g_param_spec_enum ("family",
469                                                       P_("Socket family"),
470                                                       P_("The sockets address family to use for socket construction"),
471                                                       G_TYPE_SOCKET_FAMILY,
472                                                       G_SOCKET_FAMILY_INVALID,
473                                                       G_PARAM_CONSTRUCT |
474                                                       G_PARAM_READWRITE |
475                                                       G_PARAM_STATIC_STRINGS));
476
477   g_object_class_install_property (gobject_class, PROP_TYPE,
478                                    g_param_spec_enum ("type",
479                                                       P_("Socket type"),
480                                                       P_("The sockets type to use for socket construction"),
481                                                       G_TYPE_SOCKET_TYPE,
482                                                       G_SOCKET_TYPE_STREAM,
483                                                       G_PARAM_CONSTRUCT |
484                                                       G_PARAM_READWRITE |
485                                                       G_PARAM_STATIC_STRINGS));
486
487   g_object_class_install_property (gobject_class, PROP_PROTOCOL,
488                                    g_param_spec_enum ("protocol",
489                                                       P_("Socket protocol"),
490                                                       P_("The protocol to use for socket construction, or 0 for default"),
491                                                       G_TYPE_SOCKET_PROTOCOL,
492                                                       G_SOCKET_PROTOCOL_DEFAULT,
493                                                       G_PARAM_CONSTRUCT |
494                                                       G_PARAM_READWRITE |
495                                                       G_PARAM_STATIC_STRINGS));
496
497   g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
498                                    g_param_spec_object ("local-address",
499                                                         P_("Local address"),
500                                                         P_("The local address constructed sockets will be bound to"),
501                                                         G_TYPE_SOCKET_ADDRESS,
502                                                         G_PARAM_CONSTRUCT |
503                                                         G_PARAM_READWRITE |
504                                                         G_PARAM_STATIC_STRINGS));
505
506   g_object_class_install_property (gobject_class, PROP_TIMEOUT,
507                                    g_param_spec_uint ("timeout",
508                                                       P_("Socket timeout"),
509                                                       P_("The I/O timeout for sockets, or 0 for none"),
510                                                       0, G_MAXUINT, 0,
511                                                       G_PARAM_CONSTRUCT |
512                                                       G_PARAM_READWRITE |
513                                                       G_PARAM_STATIC_STRINGS));
514
515 }
516
517 /**
518  * g_socket_client_connect:
519  * @client: a #GSocketClient.
520  * @connectable: a #GSocketConnectable specifying the remote address.
521  * @cancellable: optional #GCancellable object, %NULL to ignore.
522  * @error: #GError for error reporting, or %NULL to ignore.
523  *
524  * Tries to resolve the @connectable and make a network connection to it..
525  *
526  * Upon a successful connection, a new #GSocketConnection is constructed
527  * and returned.  The caller owns this new object and must drop their
528  * reference to it when finished with it.
529  *
530  * The type of the #GSocketConnection object returned depends on the type of
531  * the underlying socket that is used. For instance, for a TCP/IP connection
532  * it will be a #GTcpConnection.
533  *
534  * The socket created will be the same family as the the address that the
535  * @connectable resolves to, unless family is set with g_socket_client_set_family()
536  * or indirectly via g_socket_client_set_local_address(). The socket type
537  * defaults to %G_SOCKET_TYPE_STREAM but can be set with
538  * g_socket_client_set_socket_type().
539  *
540  * If a local address is specified with g_socket_client_set_local_address() the
541  * socket will be bound to this address before connecting.
542  *
543  * Returns: a #GSocketConnection on success, %NULL on error.
544  *
545  * Since: 2.22
546  */
547 GSocketConnection *
548 g_socket_client_connect (GSocketClient       *client,
549                          GSocketConnectable  *connectable,
550                          GCancellable        *cancellable,
551                          GError             **error)
552 {
553   GSocketConnection *connection = NULL;
554   GSocketAddressEnumerator *enumerator;
555   GError *last_error, *tmp_error;
556
557   last_error = NULL;
558   enumerator = g_socket_connectable_enumerate (connectable);
559   while (connection == NULL)
560     {
561       GSocketAddress *address;
562       GSocket *socket;
563
564       if (g_cancellable_is_cancelled (cancellable))
565         {
566           g_clear_error (error);
567           g_cancellable_set_error_if_cancelled (cancellable, error);
568           break;
569         }
570
571       tmp_error = NULL;
572       address = g_socket_address_enumerator_next (enumerator, cancellable,
573                                                   &tmp_error);
574       if (address == NULL)
575         {
576           if (tmp_error)
577             {
578               g_clear_error (&last_error);
579               g_propagate_error (error, tmp_error);
580             }
581           else if (last_error)
582             {
583               g_propagate_error (error, last_error);
584             }
585           else
586             g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
587                                  _("Unknown error on connect"));
588           break;
589         }
590
591       /* clear error from previous attempt */
592       g_clear_error (&last_error);
593
594       socket = create_socket (client, address, &last_error);
595       if (socket != NULL)
596         {
597           if (g_socket_connect (socket, address, cancellable, &last_error))
598             connection = g_socket_connection_factory_create_connection (socket);
599
600           g_object_unref (socket);
601         }
602
603       g_object_unref (address);
604     }
605   g_object_unref (enumerator);
606
607   return connection;
608 }
609
610 /**
611  * g_socket_client_connect_to_host:
612  * @client: a #SocketClient
613  * @host_and_port: the name and optionally port of the host to connect to
614  * @default_port: the default port to connect to
615  * @cancellable: a #GCancellable, or %NULL
616  * @error: a pointer to a #GError, or %NULL
617  *
618  * This is a helper function for g_socket_client_connect().
619  *
620  * Attempts to create a TCP connection to the named host.
621  *
622  * @host_and_port may be in any of a number of recognised formats: an IPv6
623  * address, an IPv4 address, or a domain name (in which case a DNS
624  * lookup is performed).  Quoting with [] is supported for all address
625  * types.  A port override may be specified in the usual way with a
626  * colon.  Ports may be given as decimal numbers or symbolic names (in
627  * which case an /etc/services lookup is performed).
628  *
629  * If no port override is given in @host_and_port then @default_port will be
630  * used as the port number to connect to.
631  *
632  * In general, @host_and_port is expected to be provided by the user (allowing
633  * them to give the hostname, and a port overide if necessary) and
634  * @default_port is expected to be provided by the application.
635  *
636  * In the case that an IP address is given, a single connection
637  * attempt is made.  In the case that a name is given, multiple
638  * connection attempts may be made, in turn and according to the
639  * number of address records in DNS, until a connection succeeds.
640  *
641  * Upon a successful connection, a new #GSocketConnection is constructed
642  * and returned.  The caller owns this new object and must drop their
643  * reference to it when finished with it.
644  *
645  * In the event of any failure (DNS error, service not found, no hosts
646  * connectable) %NULL is returned and @error (if non-%NULL) is set
647  * accordingly.
648  *
649  Returns: a #GSocketConnection on success, %NULL on error.
650  *
651  * Since: 2.22
652  */
653 GSocketConnection *
654 g_socket_client_connect_to_host (GSocketClient  *client,
655                                  const gchar    *host_and_port,
656                                  guint16         default_port,
657                                  GCancellable   *cancellable,
658                                  GError        **error)
659 {
660   GSocketConnectable *connectable;
661   GSocketConnection *connection;
662
663   connectable = g_network_address_parse (host_and_port, default_port, error);
664   if (connectable == NULL)
665     return NULL;
666
667   connection = g_socket_client_connect (client, connectable,
668                                         cancellable, error);
669   g_object_unref (connectable);
670
671   return connection;
672 }
673
674 /**
675  * g_socket_client_connect_to_service:
676  * @client: a #GSocketConnection
677  * @domain: a domain name
678  * @service: the name of the service to connect to
679  * @cancellable: a #GCancellable, or %NULL
680  * @error: a pointer to a #GError, or %NULL
681  * @returns: a #GSocketConnection if successful, or %NULL on error
682  *
683  * Attempts to create a TCP connection to a service.
684  *
685  * This call looks up the SRV record for @service at @domain for the
686  * "tcp" protocol.  It then attempts to connect, in turn, to each of
687  * the hosts providing the service until either a connection succeeds
688  * or there are no hosts remaining.
689  *
690  * Upon a successful connection, a new #GSocketConnection is constructed
691  * and returned.  The caller owns this new object and must drop their
692  * reference to it when finished with it.
693  *
694  * In the event of any failure (DNS error, service not found, no hosts
695  * connectable) %NULL is returned and @error (if non-%NULL) is set
696  * accordingly.
697  */
698 GSocketConnection *
699 g_socket_client_connect_to_service (GSocketClient  *client,
700                                     const gchar    *domain,
701                                     const gchar    *service,
702                                     GCancellable   *cancellable,
703                                     GError        **error)
704 {
705   GSocketConnectable *connectable;
706   GSocketConnection *connection;
707
708   connectable = g_network_service_new (service, "tcp", domain);
709   connection = g_socket_client_connect (client, connectable,
710                                         cancellable, error);
711   g_object_unref (connectable);
712
713   return connection;
714 }
715
716 typedef struct
717 {
718   GSimpleAsyncResult *result;
719   GCancellable *cancellable;
720   GSocketClient *client;
721
722   GSocketAddressEnumerator *enumerator;
723   GSocket *current_socket;
724
725   GError *last_error;
726 } GSocketClientAsyncConnectData;
727
728 static void
729 g_socket_client_async_connect_complete (GSocketClientAsyncConnectData *data)
730 {
731   GSocketConnection *connection;
732
733   if (data->last_error)
734     {
735       g_simple_async_result_set_from_error (data->result, data->last_error);
736       g_error_free (data->last_error);
737     }
738   else
739     {
740       g_assert (data->current_socket);
741
742       g_socket_set_blocking (data->current_socket, TRUE);
743
744       connection = g_socket_connection_factory_create_connection (data->current_socket);
745       g_object_unref (data->current_socket);
746       g_simple_async_result_set_op_res_gpointer (data->result,
747                                                  connection,
748                                                  g_object_unref);
749     }
750
751   g_simple_async_result_complete (data->result);
752   g_object_unref (data->result);
753   g_object_unref (data->enumerator);
754   if (data->cancellable)
755     g_object_unref (data->cancellable);
756   g_slice_free (GSocketClientAsyncConnectData, data);
757 }
758
759
760 static void
761 g_socket_client_enumerator_callback (GObject      *object,
762                                      GAsyncResult *result,
763                                      gpointer      user_data);
764
765 static void
766 set_last_error (GSocketClientAsyncConnectData *data,
767                 GError *error)
768 {
769   g_clear_error (&data->last_error);
770   data->last_error = error;
771 }
772
773 static gboolean
774 g_socket_client_socket_callback (GSocket *socket,
775                                  GIOCondition condition,
776                                  GSocketClientAsyncConnectData *data)
777 {
778   GError *error = NULL;
779
780   if (g_cancellable_is_cancelled (data->cancellable))
781     {
782       /* Cancelled, return done with last error being cancelled */
783       g_clear_error (&data->last_error);
784       g_object_unref (data->current_socket);
785       data->current_socket = NULL;
786       g_cancellable_set_error_if_cancelled (data->cancellable,
787                                             &data->last_error);
788     }
789   else
790     {
791       /* socket is ready for writing means connect done, did it succeed? */
792       if (!g_socket_check_connect_result (data->current_socket, &error))
793         {
794           set_last_error (data, error);
795           g_object_unref (data->current_socket);
796           data->current_socket = NULL;
797
798           /* try next one */
799           g_socket_address_enumerator_next_async (data->enumerator,
800                                                   data->cancellable,
801                                                   g_socket_client_enumerator_callback,
802                                                   data);
803
804           return FALSE;
805         }
806     }
807
808   g_socket_client_async_connect_complete (data);
809
810   return FALSE;
811 }
812
813 static void
814 g_socket_client_enumerator_callback (GObject      *object,
815                                      GAsyncResult *result,
816                                      gpointer      user_data)
817 {
818   GSocketClientAsyncConnectData *data = user_data;
819   GSocketAddress *address;
820   GSocket *socket;
821   GError *tmp_error = NULL;
822
823   if (g_cancellable_is_cancelled (data->cancellable))
824     {
825       g_clear_error (&data->last_error);
826       g_cancellable_set_error_if_cancelled (data->cancellable, &data->last_error);
827       g_socket_client_async_connect_complete (data);
828       return;
829     }
830
831   address = g_socket_address_enumerator_next_finish (data->enumerator,
832                                                      result, &tmp_error);
833
834   if (address == NULL)
835     {
836       if (tmp_error)
837         set_last_error (data, tmp_error);
838       else if (data->last_error == NULL)
839         g_set_error_literal (&data->last_error, G_IO_ERROR, G_IO_ERROR_FAILED,
840                              _("Unknown error on connect"));
841
842       g_socket_client_async_connect_complete (data);
843       return;
844     }
845
846   g_clear_error (&data->last_error);
847
848   socket = create_socket (data->client, address, &data->last_error);
849   if (socket != NULL)
850     {
851       g_socket_set_blocking (socket, FALSE);
852       if (g_socket_connect (socket, address, data->cancellable, &tmp_error))
853         {
854           data->current_socket = socket;
855           g_socket_client_async_connect_complete (data);
856
857           g_object_unref (address);
858           return;
859         }
860       else if (g_error_matches (tmp_error, G_IO_ERROR, G_IO_ERROR_PENDING))
861         {
862           GSource *source;
863
864           data->current_socket = socket;
865           g_error_free (tmp_error);
866
867           source = g_socket_create_source (socket, G_IO_OUT,
868                                            data->cancellable);
869           g_source_set_callback (source,
870                                  (GSourceFunc) g_socket_client_socket_callback,
871                                  data, NULL);
872           g_source_attach (source, g_main_context_get_thread_default ());
873           g_source_unref (source);
874
875           g_object_unref (address);
876           return;
877         }
878       else
879         {
880           data->last_error = tmp_error;
881           g_object_unref (socket);
882         }
883       g_object_unref (address);
884     }
885
886   g_socket_address_enumerator_next_async (data->enumerator,
887                                           data->cancellable,
888                                           g_socket_client_enumerator_callback,
889                                           data);
890 }
891
892 /**
893  * g_socket_client_connect_async:
894  * @client: a #GTcpClient
895  * @connectable: a #GSocketConnectable specifying the remote address.
896  * @cancellable: a #GCancellable, or %NULL
897  * @callback: a #GAsyncReadyCallback
898  * @user_data: user data for the callback
899  *
900  * This is the asynchronous version of g_socket_client_connect().
901  *
902  * When the operation is finished @callback will be
903  * called. You can then call g_socket_client_connect_finish() to get
904  * the result of the operation.
905  *
906  * Since: 2.22
907  */
908 void
909 g_socket_client_connect_async (GSocketClient       *client,
910                                GSocketConnectable  *connectable,
911                                GCancellable        *cancellable,
912                                GAsyncReadyCallback  callback,
913                                gpointer             user_data)
914 {
915   GSocketClientAsyncConnectData *data;
916
917   g_return_if_fail (G_IS_SOCKET_CLIENT (client));
918
919   data = g_slice_new (GSocketClientAsyncConnectData);
920
921   data->result = g_simple_async_result_new (G_OBJECT (client),
922                                             callback, user_data,
923                                             g_socket_client_connect_async);
924   data->client = client;
925   if (cancellable)
926     data->cancellable = g_object_ref (cancellable);
927   else
928     data->cancellable = NULL;
929   data->last_error = NULL;
930   data->enumerator = g_socket_connectable_enumerate (connectable);
931
932   g_socket_address_enumerator_next_async (data->enumerator, cancellable,
933                                           g_socket_client_enumerator_callback,
934                                           data);
935 }
936
937 /**
938  * g_socket_client_connect_to_host_async:
939  * @client: a #GTcpClient
940  * @host_and_port: the name and optionally the port of the host to connect to
941  * @default_port: the default port to connect to
942  * @cancellable: a #GCancellable, or %NULL
943  * @callback: a #GAsyncReadyCallback
944  * @user_data: user data for the callback
945  *
946  * This is the asynchronous version of g_socket_client_connect_to_host().
947  *
948  * When the operation is finished @callback will be
949  * called. You can then call g_socket_client_connect_to_host_finish() to get
950  * the result of the operation.
951  *
952  * Since: 2.22
953  */
954 void
955 g_socket_client_connect_to_host_async (GSocketClient        *client,
956                                        const gchar          *host_and_port,
957                                        guint16               default_port,
958                                        GCancellable         *cancellable,
959                                        GAsyncReadyCallback   callback,
960                                        gpointer              user_data)
961 {
962   GSocketConnectable *connectable;
963   GError *error;
964
965   error = NULL;
966   connectable = g_network_address_parse (host_and_port, default_port,
967                                          &error);
968   if (connectable == NULL)
969     {
970       g_simple_async_report_gerror_in_idle (G_OBJECT (client),
971                                             callback, user_data, error);
972       g_error_free (error);
973     }
974   else
975     {
976       g_socket_client_connect_async (client,
977                                      connectable, cancellable,
978                                      callback, user_data);
979       g_object_unref (connectable);
980     }
981 }
982
983 /**
984  * g_socket_client_connect_to_service_async:
985  * @client: a #GSocketClient
986  * @domain: a domain name
987  * @service: the name of the service to connect to
988  * @cancellable: a #GCancellable, or %NULL
989  * @callback: a #GAsyncReadyCallback
990  * @user_data: user data for the callback
991  *
992  * This is the asynchronous version of
993  * g_socket_client_connect_to_service().
994  *
995  * Since: 2.22
996  */
997 void
998 g_socket_client_connect_to_service_async (GSocketClient       *client,
999                                           const gchar         *domain,
1000                                           const gchar         *service,
1001                                           GCancellable        *cancellable,
1002                                           GAsyncReadyCallback  callback,
1003                                           gpointer             user_data)
1004 {
1005   GSocketConnectable *connectable;
1006
1007   connectable = g_network_service_new (service, "tcp", domain);
1008   g_socket_client_connect_async (client,
1009                                  connectable, cancellable,
1010                                  callback, user_data);
1011   g_object_unref (connectable);
1012 }
1013
1014 /**
1015  * g_socket_client_connect_finish:
1016  * @client: a #GSocketClient.
1017  * @result: a #GAsyncResult.
1018  * @error: a #GError location to store the error occuring, or %NULL to
1019  * ignore.
1020  *
1021  * Finishes an async connect operation. See g_socket_client_connect_async()
1022  *
1023  * Returns: a #GSocketConnection on success, %NULL on error.
1024  *
1025  * Since: 2.22
1026  */
1027 GSocketConnection *
1028 g_socket_client_connect_finish (GSocketClient  *client,
1029                                 GAsyncResult   *result,
1030                                 GError        **error)
1031 {
1032   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
1033
1034   if (g_simple_async_result_propagate_error (simple, error))
1035     return NULL;
1036
1037   return g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
1038 }
1039
1040 /**
1041  * g_socket_client_connect_to_host_finish:
1042  * @client: a #GSocketClient.
1043  * @result: a #GAsyncResult.
1044  * @error: a #GError location to store the error occuring, or %NULL to
1045  * ignore.
1046  *
1047  * Finishes an async connect operation. See g_socket_client_connect_to_host_async()
1048  *
1049  * Returns: a #GSocketConnection on success, %NULL on error.
1050  *
1051  * Since: 2.22
1052  */
1053 GSocketConnection *
1054 g_socket_client_connect_to_host_finish (GSocketClient  *client,
1055                                         GAsyncResult   *result,
1056                                         GError        **error)
1057 {
1058   return g_socket_client_connect_finish (client, result, error);
1059 }
1060
1061 /**
1062  * g_socket_client_connect_to_service_finish:
1063  * @client: a #GSocketClient.
1064  * @result: a #GAsyncResult.
1065  * @error: a #GError location to store the error occuring, or %NULL to
1066  * ignore.
1067  *
1068  * Finishes an async connect operation. See g_socket_client_connect_to_service_async()
1069  *
1070  * Returns: a #GSocketConnection on success, %NULL on error.
1071  *
1072  * Since: 2.22
1073  */
1074 GSocketConnection *
1075 g_socket_client_connect_to_service_finish (GSocketClient  *client,
1076                                            GAsyncResult   *result,
1077                                            GError        **error)
1078 {
1079   return g_socket_client_connect_finish (client, result, error);
1080 }