1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright © 2008, 2009 codethink
4 * Copyright © 2009 Red Hat, Inc
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.
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.
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.
21 * Authors: Ryan Lortie <desrt@desrt.ca>
22 * Alexander Larsson <alexl@redhat.com>
26 #include "gsocketclient.h"
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>
45 * SECTION:gsocketclient
46 * @short_description: Helper for connecting to a network service
48 * @see_also: #GSocketConnection, #GSocketListener
50 * #GSocketClient is a high-level utility class for connecting to a
51 * network host using a connection oriented socket type.
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.
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.
65 G_DEFINE_TYPE (GSocketClient, g_socket_client, G_TYPE_OBJECT);
76 struct _GSocketClientPrivate
80 GSocketProtocol protocol;
81 GSocketAddress *local_address;
85 create_socket (GSocketClient *client,
86 GSocketAddress *dest_address,
92 family = client->priv->family;
93 if (family == G_SOCKET_FAMILY_INVALID &&
94 client->priv->local_address != NULL)
95 family = g_socket_address_get_family (client->priv->local_address);
96 if (family == G_SOCKET_FAMILY_INVALID)
97 family = g_socket_address_get_family (dest_address);
99 socket = g_socket_new (family,
101 client->priv->protocol,
106 if (client->priv->local_address)
108 if (!g_socket_bind (socket,
109 client->priv->local_address,
113 g_object_unref (socket);
122 g_socket_client_init (GSocketClient *client)
124 client->priv = G_TYPE_INSTANCE_GET_PRIVATE (client,
125 G_TYPE_SOCKET_CLIENT,
126 GSocketClientPrivate);
127 client->priv->type = G_SOCKET_TYPE_STREAM;
131 * g_socket_client_new:
133 * Creates a new #GSocketClient with the default options.
135 * Returns: a #GSocketClient.
136 * Free the returned object with g_object_unref().
141 g_socket_client_new (void)
143 return g_object_new (G_TYPE_SOCKET_CLIENT, NULL);
147 g_socket_client_finalize (GObject *object)
149 GSocketClient *client = G_SOCKET_CLIENT (object);
151 if (client->priv->local_address)
152 g_object_unref (client->priv->local_address);
154 if (G_OBJECT_CLASS (g_socket_client_parent_class)->finalize)
155 (*G_OBJECT_CLASS (g_socket_client_parent_class)->finalize) (object);
159 g_socket_client_get_property (GObject *object,
164 GSocketClient *client = G_SOCKET_CLIENT (object);
169 g_value_set_enum (value, client->priv->family);
173 g_value_set_enum (value, client->priv->type);
177 g_value_set_enum (value, client->priv->protocol);
180 case PROP_LOCAL_ADDRESS:
181 g_value_set_object (value, client->priv->local_address);
185 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
190 g_socket_client_set_property (GObject *object,
195 GSocketClient *client = G_SOCKET_CLIENT (object);
200 g_socket_client_set_family (client, g_value_get_enum (value));
204 g_socket_client_set_socket_type (client, g_value_get_enum (value));
208 g_socket_client_set_protocol (client, g_value_get_enum (value));
211 case PROP_LOCAL_ADDRESS:
212 g_socket_client_set_local_address (client, g_value_get_object (value));
216 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
221 * g_socket_client_get_family:
222 * @client: a #GSocketClient.
224 * Gets the socket family of the socket client.
226 * See g_socket_client_set_family() for details.
228 * Returns: a #GSocketFamily
233 g_socket_client_get_family (GSocketClient *client)
235 return client->priv->family;
239 * g_socket_client_set_family:
240 * @client: a #GSocketClient.
241 * @family: a #GSocketFamily
243 * Sets the socket family of the socket client.
244 * If this is set to something other than %G_SOCKET_FAMILY_INVALID
245 * then the sockets created by this object will be of the specified
248 * This might be useful for instance if you want to force the local
249 * connection to be an ipv4 socket, even though the address might
250 * be an ipv6 mapped to ipv4 address.
255 g_socket_client_set_family (GSocketClient *client,
256 GSocketFamily family)
258 if (client->priv->family == family)
261 client->priv->family = family;
262 g_object_notify (G_OBJECT (client), "family");
266 * g_socket_client_get_socket_type:
267 * @client: a #GSocketClient.
269 * Gets the socket type of the socket client.
271 * See g_socket_client_set_socket_type() for details.
273 * Returns: a #GSocketFamily
278 g_socket_client_get_socket_type (GSocketClient *client)
280 return client->priv->type;
284 * g_socket_client_set_socket_type:
285 * @client: a #GSocketClient.
286 * @type: a #GSocketType
288 * Sets the socket type of the socket client.
289 * The sockets created by this object will be of the specified
292 * It doesn't make sense to specify a type of %G_SOCKET_TYPE_DATAGRAM,
293 * as GSocketClient is used for connection oriented services.
298 g_socket_client_set_socket_type (GSocketClient *client,
301 if (client->priv->type == type)
304 client->priv->type = type;
305 g_object_notify (G_OBJECT (client), "type");
309 * g_socket_client_get_protocol:
310 * @client: a #GSocketClient
312 * Gets the protocol name type of the socket client.
314 * See g_socket_client_set_protocol() for details.
316 * Returns: a #GSocketProtocol
321 g_socket_client_get_protocol (GSocketClient *client)
323 return client->priv->protocol;
327 * g_socket_client_set_protocol:
328 * @client: a #GSocketClient.
329 * @protocol: a #GSocketProtocol
331 * Sets the protocol of the socket client.
332 * The sockets created by this object will use of the specified
335 * If @protocol is %0 that means to use the default
336 * protocol for the socket family and type.
341 g_socket_client_set_protocol (GSocketClient *client,
342 GSocketProtocol protocol)
344 if (client->priv->protocol == protocol)
347 client->priv->protocol = protocol;
348 g_object_notify (G_OBJECT (client), "protocol");
352 * g_socket_client_get_local_address:
353 * @client: a #GSocketClient.
355 * Gets the local address of the socket client.
357 * See g_socket_client_set_local_address() for details.
359 * Returns: (transfer none): a #GSocketAddres or %NULL. don't free
364 g_socket_client_get_local_address (GSocketClient *client)
366 return client->priv->local_address;
370 * g_socket_client_set_local_address:
371 * @client: a #GSocketClient.
372 * @address: a #GSocketAddress, or %NULL
374 * Sets the local address of the socket client.
375 * The sockets created by this object will bound to the
376 * specified address (if not %NULL) before connecting.
378 * This is useful if you want to ensure the the local
379 * side of the connection is on a specific port, or on
380 * a specific interface.
385 g_socket_client_set_local_address (GSocketClient *client,
386 GSocketAddress *address)
389 g_object_ref (address);
391 if (client->priv->local_address)
393 g_object_unref (client->priv->local_address);
395 client->priv->local_address = address;
396 g_object_notify (G_OBJECT (client), "local-address");
400 g_socket_client_class_init (GSocketClientClass *class)
402 GObjectClass *gobject_class = G_OBJECT_CLASS (class);
404 g_type_class_add_private (class, sizeof (GSocketClientPrivate));
406 gobject_class->finalize = g_socket_client_finalize;
407 gobject_class->set_property = g_socket_client_set_property;
408 gobject_class->get_property = g_socket_client_get_property;
410 g_object_class_install_property (gobject_class, PROP_FAMILY,
411 g_param_spec_enum ("family",
413 P_("The sockets address family to use for socket construction"),
414 G_TYPE_SOCKET_FAMILY,
415 G_SOCKET_FAMILY_INVALID,
418 G_PARAM_STATIC_STRINGS));
420 g_object_class_install_property (gobject_class, PROP_TYPE,
421 g_param_spec_enum ("type",
423 P_("The sockets type to use for socket construction"),
425 G_SOCKET_TYPE_STREAM,
428 G_PARAM_STATIC_STRINGS));
430 g_object_class_install_property (gobject_class, PROP_PROTOCOL,
431 g_param_spec_enum ("protocol",
432 P_("Socket protocol"),
433 P_("The protocol to use for socket construction, or 0 for default"),
434 G_TYPE_SOCKET_PROTOCOL,
435 G_SOCKET_PROTOCOL_DEFAULT,
438 G_PARAM_STATIC_STRINGS));
440 g_object_class_install_property (gobject_class, PROP_LOCAL_ADDRESS,
441 g_param_spec_object ("local-address",
443 P_("The local address constructed sockets will be bound to"),
444 G_TYPE_SOCKET_ADDRESS,
447 G_PARAM_STATIC_STRINGS));
451 * g_socket_client_connect:
452 * @client: a #GSocketClient.
453 * @connectable: a #GSocketConnectable specifying the remote address.
454 * @cancellable: optional #GCancellable object, %NULL to ignore.
455 * @error: #GError for error reporting, or %NULL to ignore.
457 * Tries to resolve the @connectable and make a network connection to it..
459 * Upon a successful connection, a new #GSocketConnection is constructed
460 * and returned. The caller owns this new object and must drop their
461 * reference to it when finished with it.
463 * The type of the #GSocketConnection object returned depends on the type of
464 * the underlying socket that is used. For instance, for a TCP/IP connection
465 * it will be a #GTcpConnection.
467 * The socket created will be the same family as the the address that the
468 * @connectable resolves to, unless family is set with g_socket_client_set_family()
469 * or indirectly via g_socket_client_set_local_address(). The socket type
470 * defaults to %G_SOCKET_TYPE_STREAM but can be set with
471 * g_socket_client_set_socket_type().
473 * If a local address is specified with g_socket_client_set_local_address() the
474 * socket will be bound to this address before connecting.
476 * Returns: a #GSocketConnection on success, %NULL on error.
481 g_socket_client_connect (GSocketClient *client,
482 GSocketConnectable *connectable,
483 GCancellable *cancellable,
486 GSocketConnection *connection = NULL;
487 GSocketAddressEnumerator *enumerator;
488 GError *last_error, *tmp_error;
491 enumerator = g_socket_connectable_enumerate (connectable);
492 while (connection == NULL)
494 GSocketAddress *address;
497 if (g_cancellable_is_cancelled (cancellable))
499 g_clear_error (error);
500 g_cancellable_set_error_if_cancelled (cancellable, error);
505 address = g_socket_address_enumerator_next (enumerator, cancellable,
511 g_clear_error (&last_error);
512 g_propagate_error (error, tmp_error);
516 g_propagate_error (error, last_error);
519 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
520 _("Unknown error on connect"));
524 /* clear error from previous attempt */
525 g_clear_error (&last_error);
527 socket = create_socket (client, address, &last_error);
530 if (g_socket_connect (socket, address, cancellable, &last_error))
531 connection = g_socket_connection_factory_create_connection (socket);
533 g_object_unref (socket);
536 g_object_unref (address);
538 g_object_unref (enumerator);
544 * g_socket_client_connect_to_host:
545 * @client: a #SocketClient
546 * @host_and_port: the name and optionally port of the host to connect to
547 * @default_port: the default port to connect to
548 * @cancellable: a #GCancellable, or %NULL
549 * @error: a pointer to a #GError, or %NULL
551 * This is a helper function for g_socket_client_connect().
553 * Attempts to create a TCP connection to the named host.
555 * @host_and_port may be in any of a number of recognised formats: an IPv6
556 * address, an IPv4 address, or a domain name (in which case a DNS
557 * lookup is performed). Quoting with [] is supported for all address
558 * types. A port override may be specified in the usual way with a
559 * colon. Ports may be given as decimal numbers or symbolic names (in
560 * which case an /etc/services lookup is performed).
562 * If no port override is given in @host_and_port then @default_port will be
563 * used as the port number to connect to.
565 * In general, @host_and_port is expected to be provided by the user (allowing
566 * them to give the hostname, and a port overide if necessary) and
567 * @default_port is expected to be provided by the application.
569 * In the case that an IP address is given, a single connection
570 * attempt is made. In the case that a name is given, multiple
571 * connection attempts may be made, in turn and according to the
572 * number of address records in DNS, until a connection succeeds.
574 * Upon a successful connection, a new #GSocketConnection is constructed
575 * and returned. The caller owns this new object and must drop their
576 * reference to it when finished with it.
578 * In the event of any failure (DNS error, service not found, no hosts
579 * connectable) %NULL is returned and @error (if non-%NULL) is set
582 Returns: a #GSocketConnection on success, %NULL on error.
587 g_socket_client_connect_to_host (GSocketClient *client,
588 const gchar *host_and_port,
589 guint16 default_port,
590 GCancellable *cancellable,
593 GSocketConnectable *connectable;
594 GSocketConnection *connection;
596 connectable = g_network_address_parse (host_and_port, default_port, error);
597 if (connectable == NULL)
600 connection = g_socket_client_connect (client, connectable,
602 g_object_unref (connectable);
608 * g_socket_client_connect_to_service:
609 * @client: a #GSocketConnection
610 * @domain: a domain name
611 * @service: the name of the service to connect to
612 * @cancellable: a #GCancellable, or %NULL
613 * @error: a pointer to a #GError, or %NULL
614 * @returns: a #GSocketConnection if successful, or %NULL on error
616 * Attempts to create a TCP connection to a service.
618 * This call looks up the SRV record for @service at @domain for the
619 * "tcp" protocol. It then attempts to connect, in turn, to each of
620 * the hosts providing the service until either a connection succeeds
621 * or there are no hosts remaining.
623 * Upon a successful connection, a new #GSocketConnection is constructed
624 * and returned. The caller owns this new object and must drop their
625 * reference to it when finished with it.
627 * In the event of any failure (DNS error, service not found, no hosts
628 * connectable) %NULL is returned and @error (if non-%NULL) is set
632 g_socket_client_connect_to_service (GSocketClient *client,
634 const gchar *service,
635 GCancellable *cancellable,
638 GSocketConnectable *connectable;
639 GSocketConnection *connection;
641 connectable = g_network_service_new (service, "tcp", domain);
642 connection = g_socket_client_connect (client, connectable,
644 g_object_unref (connectable);
651 GSimpleAsyncResult *result;
652 GCancellable *cancellable;
653 GSocketClient *client;
655 GSocketAddressEnumerator *enumerator;
656 GSocket *current_socket;
659 } GSocketClientAsyncConnectData;
662 g_socket_client_async_connect_complete (GSocketClientAsyncConnectData *data)
664 GSocketConnection *connection;
666 if (data->last_error)
668 g_simple_async_result_set_from_error (data->result, data->last_error);
669 g_error_free (data->last_error);
673 g_assert (data->current_socket);
675 g_socket_set_blocking (data->current_socket, TRUE);
677 connection = g_socket_connection_factory_create_connection (data->current_socket);
678 g_object_unref (data->current_socket);
679 g_simple_async_result_set_op_res_gpointer (data->result,
684 g_simple_async_result_complete (data->result);
685 g_object_unref (data->result);
686 g_object_unref (data->enumerator);
687 g_slice_free (GSocketClientAsyncConnectData, data);
692 g_socket_client_enumerator_callback (GObject *object,
693 GAsyncResult *result,
697 set_last_error (GSocketClientAsyncConnectData *data,
700 g_clear_error (&data->last_error);
701 data->last_error = error;
705 g_socket_client_socket_callback (GSocket *socket,
706 GIOCondition condition,
707 GSocketClientAsyncConnectData *data)
709 GError *error = NULL;
711 if (g_cancellable_is_cancelled (data->cancellable))
713 /* Cancelled, return done with last error being cancelled */
714 g_clear_error (&data->last_error);
715 g_object_unref (data->current_socket);
716 data->current_socket = NULL;
717 g_cancellable_set_error_if_cancelled (data->cancellable,
722 /* socket is ready for writing means connect done, did it succeed? */
723 if (!g_socket_check_connect_result (data->current_socket, &error))
725 set_last_error (data, error);
728 g_socket_address_enumerator_next_async (data->enumerator,
730 g_socket_client_enumerator_callback,
737 g_socket_client_async_connect_complete (data);
743 g_socket_client_enumerator_callback (GObject *object,
744 GAsyncResult *result,
747 GSocketClientAsyncConnectData *data = user_data;
748 GSocketAddress *address;
750 GError *tmp_error = NULL;
752 if (g_cancellable_is_cancelled (data->cancellable))
754 g_clear_error (&data->last_error);
755 g_cancellable_set_error_if_cancelled (data->cancellable, &data->last_error);
756 g_socket_client_async_connect_complete (data);
760 address = g_socket_address_enumerator_next_finish (data->enumerator,
766 set_last_error (data, tmp_error);
767 else if (data->last_error == NULL)
768 g_set_error_literal (&data->last_error, G_IO_ERROR, G_IO_ERROR_FAILED,
769 _("Unknown error on connect"));
771 g_socket_client_async_connect_complete (data);
775 g_clear_error (&data->last_error);
777 socket = create_socket (data->client, address, &data->last_error);
780 g_socket_set_blocking (socket, FALSE);
781 if (g_socket_connect (socket, address, data->cancellable, &tmp_error))
783 data->current_socket = socket;
784 g_socket_client_async_connect_complete (data);
786 g_object_unref (address);
789 else if (g_error_matches (tmp_error, G_IO_ERROR, G_IO_ERROR_PENDING))
793 data->current_socket = socket;
794 g_error_free (tmp_error);
796 source = g_socket_create_source (socket, G_IO_OUT,
798 g_source_set_callback (source,
799 (GSourceFunc) g_socket_client_socket_callback,
801 g_source_attach (source, g_main_context_get_thread_default ());
802 g_source_unref (source);
804 g_object_unref (address);
809 data->last_error = tmp_error;
810 g_object_unref (socket);
812 g_object_unref (address);
815 g_socket_address_enumerator_next_async (data->enumerator,
817 g_socket_client_enumerator_callback,
822 * g_socket_client_connect_async:
823 * @client: a #GTcpClient
824 * @connectable: a #GSocketConnectable specifying the remote address.
825 * @cancellable: a #GCancellable, or %NULL
826 * @callback: a #GAsyncReadyCallback
827 * @user_data: user data for the callback
829 * This is the asynchronous version of g_socket_client_connect().
831 * When the operation is finished @callback will be
832 * called. You can then call g_socket_client_connect_finish() to get
833 * the result of the operation.
838 g_socket_client_connect_async (GSocketClient *client,
839 GSocketConnectable *connectable,
840 GCancellable *cancellable,
841 GAsyncReadyCallback callback,
844 GSocketClientAsyncConnectData *data;
846 g_return_if_fail (G_IS_SOCKET_CLIENT (client));
848 data = g_slice_new (GSocketClientAsyncConnectData);
850 data->result = g_simple_async_result_new (G_OBJECT (client),
852 g_socket_client_connect_async);
853 data->client = client;
855 data->cancellable = g_object_ref (cancellable);
857 data->cancellable = NULL;
858 data->last_error = NULL;
859 data->enumerator = g_socket_connectable_enumerate (connectable);
861 g_socket_address_enumerator_next_async (data->enumerator, cancellable,
862 g_socket_client_enumerator_callback,
867 * g_socket_client_connect_to_host_async:
868 * @client: a #GTcpClient
869 * @host_and_port: the name and optionally the port of the host to connect to
870 * @default_port: the default port to connect to
871 * @cancellable: a #GCancellable, or %NULL
872 * @callback: a #GAsyncReadyCallback
873 * @user_data: user data for the callback
875 * This is the asynchronous version of g_socket_client_connect_to_host().
877 * When the operation is finished @callback will be
878 * called. You can then call g_socket_client_connect_to_host_finish() to get
879 * the result of the operation.
884 g_socket_client_connect_to_host_async (GSocketClient *client,
885 const gchar *host_and_port,
886 guint16 default_port,
887 GCancellable *cancellable,
888 GAsyncReadyCallback callback,
891 GSocketConnectable *connectable;
895 connectable = g_network_address_parse (host_and_port, default_port,
897 if (connectable == NULL)
899 g_simple_async_report_gerror_in_idle (G_OBJECT (client),
900 callback, user_data, error);
901 g_error_free (error);
905 g_socket_client_connect_async (client,
906 connectable, cancellable,
907 callback, user_data);
908 g_object_unref (connectable);
913 * g_socket_client_connect_to_service_async:
914 * @client: a #GSocketClient
915 * @domain: a domain name
916 * @service: the name of the service to connect to
917 * @cancellable: a #GCancellable, or %NULL
918 * @callback: a #GAsyncReadyCallback
919 * @user_data: user data for the callback
921 * This is the asynchronous version of
922 * g_socket_client_connect_to_service().
927 g_socket_client_connect_to_service_async (GSocketClient *client,
929 const gchar *service,
930 GCancellable *cancellable,
931 GAsyncReadyCallback callback,
934 GSocketConnectable *connectable;
936 connectable = g_network_service_new (service, "tcp", domain);
937 g_socket_client_connect_async (client,
938 connectable, cancellable,
939 callback, user_data);
940 g_object_unref (connectable);
944 * g_socket_client_connect_finish:
945 * @client: a #GSocketClient.
946 * @result: a #GAsyncResult.
947 * @error: a #GError location to store the error occuring, or %NULL to
950 * Finishes an async connect operation. See g_socket_client_connect_async()
952 * Returns: a #GSocketConnection on success, %NULL on error.
957 g_socket_client_connect_finish (GSocketClient *client,
958 GAsyncResult *result,
961 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
963 if (g_simple_async_result_propagate_error (simple, error))
966 return g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
970 * g_socket_client_connect_to_host_finish:
971 * @client: a #GSocketClient.
972 * @result: a #GAsyncResult.
973 * @error: a #GError location to store the error occuring, or %NULL to
976 * Finishes an async connect operation. See g_socket_client_connect_to_host_async()
978 * Returns: a #GSocketConnection on success, %NULL on error.
983 g_socket_client_connect_to_host_finish (GSocketClient *client,
984 GAsyncResult *result,
987 return g_socket_client_connect_finish (client, result, error);
991 * g_socket_client_connect_to_service_finish:
992 * @client: a #GSocketClient.
993 * @result: a #GAsyncResult.
994 * @error: a #GError location to store the error occuring, or %NULL to
997 * Finishes an async connect operation. See g_socket_client_connect_to_service_async()
999 * Returns: a #GSocketConnection on success, %NULL on error.
1004 g_socket_client_connect_to_service_finish (GSocketClient *client,
1005 GAsyncResult *result,
1008 return g_socket_client_connect_finish (client, result, error);