1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
3 /* GIO - GLib Input, Output and Streaming Library
5 * Copyright (C) 2008 Red Hat, Inc.
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General
18 * Public License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
20 * Boston, MA 02111-1307, USA.
28 #include "gnetworkaddress.h"
29 #include "gasyncresult.h"
30 #include "ginetaddress.h"
31 #include "ginetsocketaddress.h"
32 #include "gnetworkingprivate.h"
33 #include "gproxyaddressenumerator.h"
34 #include "gresolver.h"
36 #include "gsocketaddressenumerator.h"
38 #include "gsocketconnectable.h"
44 * SECTION:gnetworkaddress
45 * @short_description: A GSocketConnectable for resolving hostnames
48 * #GNetworkAddress provides an easy way to resolve a hostname and
49 * then attempt to connect to that host, handling the possibility of
50 * multiple IP addresses and multiple address families.
52 * See #GSocketConnectable for and example of using the connectable
59 * A #GSocketConnectable for resolving a hostname and connecting to
63 struct _GNetworkAddressPrivate {
77 static void g_network_address_set_property (GObject *object,
81 static void g_network_address_get_property (GObject *object,
86 static void g_network_address_connectable_iface_init (GSocketConnectableIface *iface);
87 static GSocketAddressEnumerator *g_network_address_connectable_enumerate (GSocketConnectable *connectable);
88 static GSocketAddressEnumerator *g_network_address_connectable_proxy_enumerate (GSocketConnectable *connectable);
90 G_DEFINE_TYPE_WITH_CODE (GNetworkAddress, g_network_address, G_TYPE_OBJECT,
91 G_IMPLEMENT_INTERFACE (G_TYPE_SOCKET_CONNECTABLE,
92 g_network_address_connectable_iface_init))
95 g_network_address_finalize (GObject *object)
97 GNetworkAddress *addr = G_NETWORK_ADDRESS (object);
99 g_free (addr->priv->hostname);
100 g_free (addr->priv->scheme);
102 if (addr->priv->sockaddrs)
106 for (a = addr->priv->sockaddrs; a; a = a->next)
107 g_object_unref (a->data);
108 g_list_free (addr->priv->sockaddrs);
111 G_OBJECT_CLASS (g_network_address_parent_class)->finalize (object);
115 g_network_address_class_init (GNetworkAddressClass *klass)
117 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
119 g_type_class_add_private (klass, sizeof (GNetworkAddressPrivate));
121 gobject_class->set_property = g_network_address_set_property;
122 gobject_class->get_property = g_network_address_get_property;
123 gobject_class->finalize = g_network_address_finalize;
125 g_object_class_install_property (gobject_class, PROP_HOSTNAME,
126 g_param_spec_string ("hostname",
128 P_("Hostname to resolve"),
131 G_PARAM_CONSTRUCT_ONLY |
132 G_PARAM_STATIC_STRINGS));
133 g_object_class_install_property (gobject_class, PROP_PORT,
134 g_param_spec_uint ("port",
139 G_PARAM_CONSTRUCT_ONLY |
140 G_PARAM_STATIC_STRINGS));
142 g_object_class_install_property (gobject_class, PROP_SCHEME,
143 g_param_spec_string ("scheme",
148 G_PARAM_CONSTRUCT_ONLY |
149 G_PARAM_STATIC_STRINGS));
153 g_network_address_connectable_iface_init (GSocketConnectableIface *connectable_iface)
155 connectable_iface->enumerate = g_network_address_connectable_enumerate;
156 connectable_iface->proxy_enumerate = g_network_address_connectable_proxy_enumerate;
160 g_network_address_init (GNetworkAddress *addr)
162 addr->priv = G_TYPE_INSTANCE_GET_PRIVATE (addr, G_TYPE_NETWORK_ADDRESS,
163 GNetworkAddressPrivate);
167 g_network_address_set_property (GObject *object,
172 GNetworkAddress *addr = G_NETWORK_ADDRESS (object);
177 g_free (addr->priv->hostname);
178 addr->priv->hostname = g_value_dup_string (value);
182 addr->priv->port = g_value_get_uint (value);
186 if (addr->priv->scheme)
187 g_free (addr->priv->scheme);
188 addr->priv->scheme = g_value_dup_string (value);
192 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
199 g_network_address_get_property (GObject *object,
204 GNetworkAddress *addr = G_NETWORK_ADDRESS (object);
209 g_value_set_string (value, addr->priv->hostname);
213 g_value_set_uint (value, addr->priv->port);
217 g_value_set_string (value, addr->priv->scheme);
221 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
228 g_network_address_set_addresses (GNetworkAddress *addr,
232 GSocketAddress *sockaddr;
234 g_return_if_fail (addresses != NULL && addr->priv->sockaddrs == NULL);
236 for (a = addresses; a; a = a->next)
238 sockaddr = g_inet_socket_address_new (a->data, addr->priv->port);
239 addr->priv->sockaddrs = g_list_prepend (addr->priv->sockaddrs, sockaddr);
240 g_object_unref (a->data);
242 g_list_free (addresses);
243 addr->priv->sockaddrs = g_list_reverse (addr->priv->sockaddrs);
247 g_network_address_parse_sockaddr (GNetworkAddress *addr)
249 struct addrinfo hints, *res = NULL;
250 GSocketAddress *sockaddr;
253 memset (&hints, 0, sizeof (hints));
254 hints.ai_flags = AI_NUMERICHOST
255 #ifdef AI_NUMERICSERV
259 g_snprintf (port, sizeof (port), "%u", addr->priv->port);
261 if (getaddrinfo (addr->priv->hostname, port, &hints, &res) != 0)
264 sockaddr = g_socket_address_new_from_native (res->ai_addr, res->ai_addrlen);
266 if (!sockaddr || !G_IS_INET_SOCKET_ADDRESS (sockaddr))
269 addr->priv->sockaddrs = g_list_prepend (addr->priv->sockaddrs, sockaddr);
274 * g_network_address_new:
275 * @hostname: the hostname
278 * Creates a new #GSocketConnectable for connecting to the given
279 * @hostname and @port.
281 * Return value: (transfer full) (type GNetworkAddress): the new #GNetworkAddress
286 g_network_address_new (const gchar *hostname,
289 return g_object_new (G_TYPE_NETWORK_ADDRESS,
290 "hostname", hostname,
296 * g_network_address_parse:
297 * @host_and_port: the hostname and optionally a port
298 * @default_port: the default port if not in @host_and_port
299 * @error: a pointer to a #GError, or %NULL
301 * Creates a new #GSocketConnectable for connecting to the given
302 * @hostname and @port. May fail and return %NULL in case
303 * parsing @host_and_port fails.
305 * @host_and_port may be in any of a number of recognised formats; an IPv6
306 * address, an IPv4 address, or a domain name (in which case a DNS
307 * lookup is performed). Quoting with [] is supported for all address
308 * types. A port override may be specified in the usual way with a
311 * If no port is specified in @host_and_port then @default_port will be
312 * used as the port number to connect to.
314 * In general, @host_and_port is expected to be provided by the user
315 * (allowing them to give the hostname, and a port overide if necessary)
316 * and @default_port is expected to be provided by the application.
318 * (The port component of @host_and_port can also be specified as a
319 * service name rather than as a numeric port, but this functionality
320 * is deprecated, because it depends on the contents of /etc/services,
321 * which is generally quite sparse on platforms other than Linux.)
323 * Return value: (transfer full): the new #GNetworkAddress, or %NULL on error
328 g_network_address_parse (const gchar *host_and_port,
329 guint16 default_port,
332 GSocketConnectable *connectable;
337 g_return_val_if_fail (host_and_port != NULL, NULL);
340 if (host_and_port[0] == '[')
341 /* escaped host part (to allow, eg. "[2001:db8::1]:888") */
345 end = strchr (host_and_port, ']');
348 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
349 _("Hostname '%s' contains '[' but not ']'"), host_and_port);
355 else if (end[1] == ':')
359 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
360 "The ']' character (in hostname '%s') must come at the"
361 " end or be immediately followed by ':' and a port",
366 name = g_strndup (host_and_port + 1, end - host_and_port - 1);
369 else if ((port = strchr (host_and_port, ':')))
370 /* string has a ':' in it */
375 if (strchr (port, ':'))
376 /* more than one ':' in string */
378 /* this is actually an unescaped IPv6 address */
379 name = g_strdup (host_and_port);
383 name = g_strndup (host_and_port, port - host_and_port - 1);
387 /* plain hostname, no port */
388 name = g_strdup (host_and_port);
394 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
395 "If a ':' character is given, it must be followed by a "
396 "port (in hostname '%s').", host_and_port);
401 else if ('0' <= port[0] && port[0] <= '9')
406 value = strtol (port, &end, 10);
407 if (*end != '\0' || value < 0 || value > G_MAXUINT16)
409 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
410 "Invalid numeric port '%s' specified in hostname '%s'",
411 port, host_and_port);
421 struct servent *entry;
423 entry = getservbyname (port, "tcp");
426 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
427 "Unknown service '%s' specified in hostname '%s'",
428 port, host_and_port);
429 #ifdef HAVE_ENDSERVENT
436 portnum = g_ntohs (entry->s_port);
438 #ifdef HAVE_ENDSERVENT
445 /* No port in host_and_port */
446 portnum = default_port;
449 connectable = g_network_address_new (name, portnum);
455 /* Allowed characters outside alphanumeric for unreserved. */
456 #define G_URI_OTHER_UNRESERVED "-._~"
458 /* This or something equivalent will eventually go into glib/guri.h */
460 _g_uri_parse_authority (const char *uri,
466 const char *start, *p;
469 g_return_val_if_fail (uri != NULL, FALSE);
480 /* From RFC 3986 Decodes:
481 * URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
482 * hier-part = "//" authority path-abempty
483 * path-abempty = *( "/" segment )
484 * authority = [ userinfo "@" ] host [ ":" port ]
487 /* Check we have a valid scheme */
488 tmp_str = g_uri_parse_scheme (uri);
496 * hier-part = "//" authority path-abempty
499 start = strstr (p, "//");
506 if (strchr (start, '@') != NULL)
509 * userinfo = *( unreserved / pct-encoded / sub-delims / ":" )
510 * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
511 * pct-encoded = "%" HEXDIG HEXDIG
524 if (!(g_ascii_isxdigit (p[0]) ||
525 g_ascii_isxdigit (p[1])))
533 /* unreserved / sub-delims / : */
534 if (!(g_ascii_isalnum (c) ||
535 strchr (G_URI_OTHER_UNRESERVED, c) ||
536 strchr (G_URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS, c) ||
542 *userinfo = g_strndup (start, p - start - 1);
553 * host = IP-literal / IPv4address / reg-name
554 * reg-name = *( unreserved / pct-encoded / sub-delims )
557 /* If IPv6 or IPvFuture */
569 /* unreserved / sub-delims */
570 if (!(g_ascii_isalnum (c) ||
571 strchr (G_URI_OTHER_UNRESERVED, c) ||
572 strchr (G_URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS, c) ||
594 if (!(g_ascii_isxdigit (p[0]) ||
595 g_ascii_isxdigit (p[1])))
603 /* unreserved / sub-delims */
604 if (!(g_ascii_isalnum (c) ||
605 strchr (G_URI_OTHER_UNRESERVED, c) ||
606 strchr (G_URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS, c)))
612 *host = g_uri_unescape_segment (start, p - 1, NULL);
631 if (!g_ascii_isdigit (c))
634 tmp = (tmp * 10) + (c - '0');
640 *port = (guint16) tmp;
652 if (userinfo && *userinfo)
662 _g_uri_from_authority (const gchar *protocol,
665 const gchar *userinfo)
669 uri = g_string_new (protocol);
670 g_string_append (uri, "://");
674 g_string_append_uri_escaped (uri, userinfo, G_URI_RESERVED_CHARS_ALLOWED_IN_USERINFO, FALSE);
675 g_string_append_c (uri, '@');
678 if (g_hostname_is_non_ascii (host))
680 gchar *ace_encoded = g_hostname_to_ascii (host);
684 g_string_free (uri, TRUE);
687 g_string_append (uri, ace_encoded);
688 g_free (ace_encoded);
690 else if (strchr (host, ':'))
691 g_string_append_printf (uri, "[%s]", host);
693 g_string_append (uri, host);
696 g_string_append_printf (uri, ":%u", port);
698 return g_string_free (uri, FALSE);
702 * g_network_address_parse_uri:
703 * @uri: the hostname and optionally a port
704 * @default_port: The default port if none is found in the URI
705 * @error: a pointer to a #GError, or %NULL
707 * Creates a new #GSocketConnectable for connecting to the given
708 * @uri. May fail and return %NULL in case parsing @uri fails.
710 * Using this rather than g_network_address_new() or
711 * g_network_address_parse() allows #GSocketClient to determine
712 * when to use application-specific proxy protocols.
714 * Return value: (transfer full): the new #GNetworkAddress, or %NULL on error
719 g_network_address_parse_uri (const gchar *uri,
720 guint16 default_port,
723 GSocketConnectable *conn;
728 if (!_g_uri_parse_authority (uri, &hostname, &port, NULL))
730 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
739 scheme = g_uri_parse_scheme (uri);
741 conn = g_object_new (G_TYPE_NETWORK_ADDRESS,
742 "hostname", hostname,
754 * g_network_address_get_hostname:
755 * @addr: a #GNetworkAddress
757 * Gets @addr's hostname. This might be either UTF-8 or ASCII-encoded,
758 * depending on what @addr was created with.
760 * Return value: @addr's hostname
765 g_network_address_get_hostname (GNetworkAddress *addr)
767 g_return_val_if_fail (G_IS_NETWORK_ADDRESS (addr), NULL);
769 return addr->priv->hostname;
773 * g_network_address_get_port:
774 * @addr: a #GNetworkAddress
776 * Gets @addr's port number
778 * Return value: @addr's port (which may be 0)
783 g_network_address_get_port (GNetworkAddress *addr)
785 g_return_val_if_fail (G_IS_NETWORK_ADDRESS (addr), 0);
787 return addr->priv->port;
791 * g_network_address_get_scheme:
792 * @addr: a #GNetworkAddress
794 * Gets @addr's scheme
796 * Return value: @addr's scheme (%NULL if not built from URI)
801 g_network_address_get_scheme (GNetworkAddress *addr)
803 g_return_val_if_fail (G_IS_NETWORK_ADDRESS (addr), NULL);
805 return addr->priv->scheme;
808 #define G_TYPE_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (_g_network_address_address_enumerator_get_type ())
809 #define G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), G_TYPE_NETWORK_ADDRESS_ADDRESS_ENUMERATOR, GNetworkAddressAddressEnumerator))
812 GSocketAddressEnumerator parent_instance;
814 GNetworkAddress *addr;
817 } GNetworkAddressAddressEnumerator;
820 GSocketAddressEnumeratorClass parent_class;
822 } GNetworkAddressAddressEnumeratorClass;
824 static GType _g_network_address_address_enumerator_get_type (void);
825 G_DEFINE_TYPE (GNetworkAddressAddressEnumerator, _g_network_address_address_enumerator, G_TYPE_SOCKET_ADDRESS_ENUMERATOR)
828 g_network_address_address_enumerator_finalize (GObject *object)
830 GNetworkAddressAddressEnumerator *addr_enum =
831 G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (object);
833 g_object_unref (addr_enum->addr);
835 G_OBJECT_CLASS (_g_network_address_address_enumerator_parent_class)->finalize (object);
838 static GSocketAddress *
839 g_network_address_address_enumerator_next (GSocketAddressEnumerator *enumerator,
840 GCancellable *cancellable,
843 GNetworkAddressAddressEnumerator *addr_enum =
844 G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (enumerator);
845 GSocketAddress *sockaddr;
847 if (addr_enum->addresses == NULL)
849 if (!addr_enum->addr->priv->sockaddrs)
850 g_network_address_parse_sockaddr (addr_enum->addr);
851 if (!addr_enum->addr->priv->sockaddrs)
853 GResolver *resolver = g_resolver_get_default ();
856 addresses = g_resolver_lookup_by_name (resolver,
857 addr_enum->addr->priv->hostname,
859 g_object_unref (resolver);
864 g_network_address_set_addresses (addr_enum->addr, addresses);
867 addr_enum->addresses = addr_enum->addr->priv->sockaddrs;
868 addr_enum->next = addr_enum->addresses;
871 if (addr_enum->next == NULL)
874 sockaddr = addr_enum->next->data;
875 addr_enum->next = addr_enum->next->next;
876 return g_object_ref (sockaddr);
880 have_addresses (GNetworkAddressAddressEnumerator *addr_enum,
881 GTask *task, GError *error)
883 GSocketAddress *sockaddr;
885 addr_enum->addresses = addr_enum->addr->priv->sockaddrs;
886 addr_enum->next = addr_enum->addresses;
890 sockaddr = g_object_ref (addr_enum->next->data);
891 addr_enum->next = addr_enum->next->next;
897 g_task_return_error (task, error);
899 g_task_return_pointer (task, sockaddr, g_object_unref);
900 g_object_unref (task);
904 got_addresses (GObject *source_object,
905 GAsyncResult *result,
908 GTask *task = user_data;
909 GNetworkAddressAddressEnumerator *addr_enum = g_task_get_source_object (task);
910 GResolver *resolver = G_RESOLVER (source_object);
912 GError *error = NULL;
914 if (!addr_enum->addr->priv->sockaddrs)
916 addresses = g_resolver_lookup_by_name_finish (resolver, result, &error);
919 g_network_address_set_addresses (addr_enum->addr, addresses);
921 have_addresses (addr_enum, task, error);
925 g_network_address_address_enumerator_next_async (GSocketAddressEnumerator *enumerator,
926 GCancellable *cancellable,
927 GAsyncReadyCallback callback,
930 GNetworkAddressAddressEnumerator *addr_enum =
931 G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (enumerator);
932 GSocketAddress *sockaddr;
935 task = g_task_new (addr_enum, cancellable, callback, user_data);
937 if (addr_enum->addresses == NULL)
939 if (!addr_enum->addr->priv->sockaddrs)
941 if (g_network_address_parse_sockaddr (addr_enum->addr))
942 have_addresses (addr_enum, task, NULL);
945 GResolver *resolver = g_resolver_get_default ();
947 g_resolver_lookup_by_name_async (resolver,
948 addr_enum->addr->priv->hostname,
950 got_addresses, task);
951 g_object_unref (resolver);
956 addr_enum->addresses = addr_enum->addr->priv->sockaddrs;
957 addr_enum->next = addr_enum->addresses;
962 sockaddr = g_object_ref (addr_enum->next->data);
963 addr_enum->next = addr_enum->next->next;
968 g_task_return_pointer (task, sockaddr, g_object_unref);
969 g_object_unref (task);
972 static GSocketAddress *
973 g_network_address_address_enumerator_next_finish (GSocketAddressEnumerator *enumerator,
974 GAsyncResult *result,
977 g_return_val_if_fail (g_task_is_valid (result, enumerator), NULL);
979 return g_task_propagate_pointer (G_TASK (result), error);
983 _g_network_address_address_enumerator_init (GNetworkAddressAddressEnumerator *enumerator)
988 _g_network_address_address_enumerator_class_init (GNetworkAddressAddressEnumeratorClass *addrenum_class)
990 GObjectClass *object_class = G_OBJECT_CLASS (addrenum_class);
991 GSocketAddressEnumeratorClass *enumerator_class =
992 G_SOCKET_ADDRESS_ENUMERATOR_CLASS (addrenum_class);
994 enumerator_class->next = g_network_address_address_enumerator_next;
995 enumerator_class->next_async = g_network_address_address_enumerator_next_async;
996 enumerator_class->next_finish = g_network_address_address_enumerator_next_finish;
997 object_class->finalize = g_network_address_address_enumerator_finalize;
1000 static GSocketAddressEnumerator *
1001 g_network_address_connectable_enumerate (GSocketConnectable *connectable)
1003 GNetworkAddressAddressEnumerator *addr_enum;
1005 addr_enum = g_object_new (G_TYPE_NETWORK_ADDRESS_ADDRESS_ENUMERATOR, NULL);
1006 addr_enum->addr = g_object_ref (connectable);
1008 return (GSocketAddressEnumerator *)addr_enum;
1011 static GSocketAddressEnumerator *
1012 g_network_address_connectable_proxy_enumerate (GSocketConnectable *connectable)
1014 GNetworkAddress *self = G_NETWORK_ADDRESS (connectable);
1015 GSocketAddressEnumerator *proxy_enum;
1018 uri = _g_uri_from_authority (self->priv->scheme ? self->priv->scheme : "none",
1019 self->priv->hostname,
1023 proxy_enum = g_object_new (G_TYPE_PROXY_ADDRESS_ENUMERATOR,
1024 "connectable", connectable,