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, see <http://www.gnu.org/licenses/>.
26 #include "gnetworkaddress.h"
27 #include "gasyncresult.h"
28 #include "ginetaddress.h"
29 #include "ginetsocketaddress.h"
30 #include "gnetworkingprivate.h"
31 #include "gproxyaddressenumerator.h"
32 #include "gresolver.h"
34 #include "gsocketaddressenumerator.h"
36 #include "gsocketconnectable.h"
42 * SECTION:gnetworkaddress
43 * @short_description: A GSocketConnectable for resolving hostnames
46 * #GNetworkAddress provides an easy way to resolve a hostname and
47 * then attempt to connect to that host, handling the possibility of
48 * multiple IP addresses and multiple address families.
50 * See #GSocketConnectable for and example of using the connectable
57 * A #GSocketConnectable for resolving a hostname and connecting to
61 struct _GNetworkAddressPrivate {
67 gint64 resolver_serial;
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_ADD_PRIVATE (GNetworkAddress)
92 G_IMPLEMENT_INTERFACE (G_TYPE_SOCKET_CONNECTABLE,
93 g_network_address_connectable_iface_init))
96 g_network_address_finalize (GObject *object)
98 GNetworkAddress *addr = G_NETWORK_ADDRESS (object);
100 g_free (addr->priv->hostname);
101 g_free (addr->priv->scheme);
103 if (addr->priv->sockaddrs)
107 for (a = addr->priv->sockaddrs; a; a = a->next)
108 g_object_unref (a->data);
109 g_list_free (addr->priv->sockaddrs);
112 G_OBJECT_CLASS (g_network_address_parent_class)->finalize (object);
116 g_network_address_class_init (GNetworkAddressClass *klass)
118 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
120 gobject_class->set_property = g_network_address_set_property;
121 gobject_class->get_property = g_network_address_get_property;
122 gobject_class->finalize = g_network_address_finalize;
124 g_object_class_install_property (gobject_class, PROP_HOSTNAME,
125 g_param_spec_string ("hostname",
127 P_("Hostname to resolve"),
130 G_PARAM_CONSTRUCT_ONLY |
131 G_PARAM_STATIC_STRINGS));
132 g_object_class_install_property (gobject_class, PROP_PORT,
133 g_param_spec_uint ("port",
138 G_PARAM_CONSTRUCT_ONLY |
139 G_PARAM_STATIC_STRINGS));
141 g_object_class_install_property (gobject_class, PROP_SCHEME,
142 g_param_spec_string ("scheme",
147 G_PARAM_CONSTRUCT_ONLY |
148 G_PARAM_STATIC_STRINGS));
152 g_network_address_connectable_iface_init (GSocketConnectableIface *connectable_iface)
154 connectable_iface->enumerate = g_network_address_connectable_enumerate;
155 connectable_iface->proxy_enumerate = g_network_address_connectable_proxy_enumerate;
159 g_network_address_init (GNetworkAddress *addr)
161 addr->priv = g_network_address_get_instance_private (addr);
165 g_network_address_set_property (GObject *object,
170 GNetworkAddress *addr = G_NETWORK_ADDRESS (object);
175 g_free (addr->priv->hostname);
176 addr->priv->hostname = g_value_dup_string (value);
180 addr->priv->port = g_value_get_uint (value);
184 if (addr->priv->scheme)
185 g_free (addr->priv->scheme);
186 addr->priv->scheme = g_value_dup_string (value);
190 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
197 g_network_address_get_property (GObject *object,
202 GNetworkAddress *addr = G_NETWORK_ADDRESS (object);
207 g_value_set_string (value, addr->priv->hostname);
211 g_value_set_uint (value, addr->priv->port);
215 g_value_set_string (value, addr->priv->scheme);
219 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
226 g_network_address_set_addresses (GNetworkAddress *addr,
228 guint64 resolver_serial)
231 GSocketAddress *sockaddr;
233 g_return_if_fail (addresses != NULL && addr->priv->sockaddrs == NULL);
235 for (a = addresses; a; a = a->next)
237 sockaddr = g_inet_socket_address_new (a->data, addr->priv->port);
238 addr->priv->sockaddrs = g_list_prepend (addr->priv->sockaddrs, sockaddr);
239 g_object_unref (a->data);
241 g_list_free (addresses);
242 addr->priv->sockaddrs = g_list_reverse (addr->priv->sockaddrs);
244 addr->priv->resolver_serial = resolver_serial;
248 g_network_address_parse_sockaddr (GNetworkAddress *addr)
250 GSocketAddress *sockaddr;
252 sockaddr = g_inet_socket_address_new_from_string (addr->priv->hostname,
256 addr->priv->sockaddrs = g_list_prepend (addr->priv->sockaddrs, sockaddr);
264 * g_network_address_new:
265 * @hostname: the hostname
268 * Creates a new #GSocketConnectable for connecting to the given
269 * @hostname and @port.
271 * Returns: (transfer full) (type GNetworkAddress): the new #GNetworkAddress
276 g_network_address_new (const gchar *hostname,
279 return g_object_new (G_TYPE_NETWORK_ADDRESS,
280 "hostname", hostname,
286 * g_network_address_parse:
287 * @host_and_port: the hostname and optionally a port
288 * @default_port: the default port if not in @host_and_port
289 * @error: a pointer to a #GError, or %NULL
291 * Creates a new #GSocketConnectable for connecting to the given
292 * @hostname and @port. May fail and return %NULL in case
293 * parsing @host_and_port fails.
295 * @host_and_port may be in any of a number of recognised formats; an IPv6
296 * address, an IPv4 address, or a domain name (in which case a DNS
297 * lookup is performed). Quoting with [] is supported for all address
298 * types. A port override may be specified in the usual way with a
301 * If no port is specified in @host_and_port then @default_port will be
302 * used as the port number to connect to.
304 * In general, @host_and_port is expected to be provided by the user
305 * (allowing them to give the hostname, and a port overide if necessary)
306 * and @default_port is expected to be provided by the application.
308 * (The port component of @host_and_port can also be specified as a
309 * service name rather than as a numeric port, but this functionality
310 * is deprecated, because it depends on the contents of /etc/services,
311 * which is generally quite sparse on platforms other than Linux.)
313 * Returns: (transfer full): the new #GNetworkAddress, or %NULL on error
318 g_network_address_parse (const gchar *host_and_port,
319 guint16 default_port,
322 GSocketConnectable *connectable;
327 g_return_val_if_fail (host_and_port != NULL, NULL);
330 if (host_and_port[0] == '[')
331 /* escaped host part (to allow, eg. "[2001:db8::1]:888") */
335 end = strchr (host_and_port, ']');
338 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
339 _("Hostname '%s' contains '[' but not ']'"), host_and_port);
345 else if (end[1] == ':')
349 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
350 "The ']' character (in hostname '%s') must come at the"
351 " end or be immediately followed by ':' and a port",
356 name = g_strndup (host_and_port + 1, end - host_and_port - 1);
359 else if ((port = strchr (host_and_port, ':')))
360 /* string has a ':' in it */
365 if (strchr (port, ':'))
366 /* more than one ':' in string */
368 /* this is actually an unescaped IPv6 address */
369 name = g_strdup (host_and_port);
373 name = g_strndup (host_and_port, port - host_and_port - 1);
377 /* plain hostname, no port */
378 name = g_strdup (host_and_port);
384 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
385 "If a ':' character is given, it must be followed by a "
386 "port (in hostname '%s').", host_and_port);
391 else if ('0' <= port[0] && port[0] <= '9')
396 value = strtol (port, &end, 10);
397 if (*end != '\0' || value < 0 || value > G_MAXUINT16)
399 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
400 "Invalid numeric port '%s' specified in hostname '%s'",
401 port, host_and_port);
411 struct servent *entry;
413 entry = getservbyname (port, "tcp");
416 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
417 "Unknown service '%s' specified in hostname '%s'",
418 port, host_and_port);
419 #ifdef HAVE_ENDSERVENT
426 portnum = g_ntohs (entry->s_port);
428 #ifdef HAVE_ENDSERVENT
435 /* No port in host_and_port */
436 portnum = default_port;
439 connectable = g_network_address_new (name, portnum);
445 /* Allowed characters outside alphanumeric for unreserved. */
446 #define G_URI_OTHER_UNRESERVED "-._~"
448 /* This or something equivalent will eventually go into glib/guri.h */
450 _g_uri_parse_authority (const char *uri,
456 const char *start, *p;
459 g_return_val_if_fail (uri != NULL, FALSE);
470 /* From RFC 3986 Decodes:
471 * URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
472 * hier-part = "//" authority path-abempty
473 * path-abempty = *( "/" segment )
474 * authority = [ userinfo "@" ] host [ ":" port ]
477 /* Check we have a valid scheme */
478 tmp_str = g_uri_parse_scheme (uri);
486 * hier-part = "//" authority path-abempty
489 start = strstr (p, "//");
496 if (strchr (start, '@') != NULL)
499 * userinfo = *( unreserved / pct-encoded / sub-delims / ":" )
500 * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
501 * pct-encoded = "%" HEXDIG HEXDIG
514 if (!(g_ascii_isxdigit (p[0]) ||
515 g_ascii_isxdigit (p[1])))
523 /* unreserved / sub-delims / : */
524 if (!(g_ascii_isalnum (c) ||
525 strchr (G_URI_OTHER_UNRESERVED, c) ||
526 strchr (G_URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS, c) ||
532 *userinfo = g_strndup (start, p - start - 1);
543 * host = IP-literal / IPv4address / reg-name
544 * reg-name = *( unreserved / pct-encoded / sub-delims )
547 /* If IPv6 or IPvFuture */
550 gboolean has_scope_id = FALSE, has_bad_scope_id = FALSE;
561 if (c == '%' && !has_scope_id)
564 if (p[0] != '2' || p[1] != '5')
565 has_bad_scope_id = TRUE;
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) ||
580 if (has_bad_scope_id)
581 *host = g_strndup (start, p - start - 1);
583 *host = g_uri_unescape_segment (start, p - 1, NULL);
604 if (!(g_ascii_isxdigit (p[0]) ||
605 g_ascii_isxdigit (p[1])))
613 /* unreserved / sub-delims */
614 if (!(g_ascii_isalnum (c) ||
615 strchr (G_URI_OTHER_UNRESERVED, c) ||
616 strchr (G_URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS, c)))
621 *host = g_uri_unescape_segment (start, p - 1, NULL);
641 if (!g_ascii_isdigit (c))
644 tmp = (tmp * 10) + (c - '0');
650 *port = (guint16) tmp;
662 if (userinfo && *userinfo)
672 _g_uri_from_authority (const gchar *protocol,
675 const gchar *userinfo)
679 uri = g_string_new (protocol);
680 g_string_append (uri, "://");
684 g_string_append_uri_escaped (uri, userinfo, G_URI_RESERVED_CHARS_ALLOWED_IN_USERINFO, FALSE);
685 g_string_append_c (uri, '@');
688 if (g_hostname_is_non_ascii (host))
690 gchar *ace_encoded = g_hostname_to_ascii (host);
694 g_string_free (uri, TRUE);
697 g_string_append (uri, ace_encoded);
698 g_free (ace_encoded);
700 else if (strchr (host, ':'))
701 g_string_append_printf (uri, "[%s]", host);
703 g_string_append (uri, host);
706 g_string_append_printf (uri, ":%u", port);
708 return g_string_free (uri, FALSE);
712 * g_network_address_parse_uri:
713 * @uri: the hostname and optionally a port
714 * @default_port: The default port if none is found in the URI
715 * @error: a pointer to a #GError, or %NULL
717 * Creates a new #GSocketConnectable for connecting to the given
718 * @uri. May fail and return %NULL in case parsing @uri fails.
720 * Using this rather than g_network_address_new() or
721 * g_network_address_parse() allows #GSocketClient to determine
722 * when to use application-specific proxy protocols.
724 * Returns: (transfer full): the new #GNetworkAddress, or %NULL on error
729 g_network_address_parse_uri (const gchar *uri,
730 guint16 default_port,
733 GSocketConnectable *conn;
738 if (!_g_uri_parse_authority (uri, &hostname, &port, NULL))
740 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
749 scheme = g_uri_parse_scheme (uri);
751 conn = g_object_new (G_TYPE_NETWORK_ADDRESS,
752 "hostname", hostname,
764 * g_network_address_get_hostname:
765 * @addr: a #GNetworkAddress
767 * Gets @addr's hostname. This might be either UTF-8 or ASCII-encoded,
768 * depending on what @addr was created with.
770 * Returns: @addr's hostname
775 g_network_address_get_hostname (GNetworkAddress *addr)
777 g_return_val_if_fail (G_IS_NETWORK_ADDRESS (addr), NULL);
779 return addr->priv->hostname;
783 * g_network_address_get_port:
784 * @addr: a #GNetworkAddress
786 * Gets @addr's port number
788 * Returns: @addr's port (which may be 0)
793 g_network_address_get_port (GNetworkAddress *addr)
795 g_return_val_if_fail (G_IS_NETWORK_ADDRESS (addr), 0);
797 return addr->priv->port;
801 * g_network_address_get_scheme:
802 * @addr: a #GNetworkAddress
804 * Gets @addr's scheme
806 * Returns: @addr's scheme (%NULL if not built from URI)
811 g_network_address_get_scheme (GNetworkAddress *addr)
813 g_return_val_if_fail (G_IS_NETWORK_ADDRESS (addr), NULL);
815 return addr->priv->scheme;
818 #define G_TYPE_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (_g_network_address_address_enumerator_get_type ())
819 #define G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), G_TYPE_NETWORK_ADDRESS_ADDRESS_ENUMERATOR, GNetworkAddressAddressEnumerator))
822 GSocketAddressEnumerator parent_instance;
824 GNetworkAddress *addr;
827 } GNetworkAddressAddressEnumerator;
830 GSocketAddressEnumeratorClass parent_class;
832 } GNetworkAddressAddressEnumeratorClass;
834 static GType _g_network_address_address_enumerator_get_type (void);
835 G_DEFINE_TYPE (GNetworkAddressAddressEnumerator, _g_network_address_address_enumerator, G_TYPE_SOCKET_ADDRESS_ENUMERATOR)
838 g_network_address_address_enumerator_finalize (GObject *object)
840 GNetworkAddressAddressEnumerator *addr_enum =
841 G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (object);
843 g_object_unref (addr_enum->addr);
845 G_OBJECT_CLASS (_g_network_address_address_enumerator_parent_class)->finalize (object);
848 static GSocketAddress *
849 g_network_address_address_enumerator_next (GSocketAddressEnumerator *enumerator,
850 GCancellable *cancellable,
853 GNetworkAddressAddressEnumerator *addr_enum =
854 G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (enumerator);
855 GSocketAddress *sockaddr;
857 if (addr_enum->addresses == NULL)
859 GNetworkAddress *addr = addr_enum->addr;
860 GResolver *resolver = g_resolver_get_default ();
861 gint64 serial = g_resolver_get_serial (resolver);
863 if (addr->priv->resolver_serial != 0 &&
864 addr->priv->resolver_serial != serial)
866 /* Resolver has reloaded, discard cached addresses */
867 g_list_free_full (addr->priv->sockaddrs, g_object_unref);
868 addr->priv->sockaddrs = NULL;
871 if (!addr->priv->sockaddrs)
872 g_network_address_parse_sockaddr (addr);
873 if (!addr->priv->sockaddrs)
877 addresses = g_resolver_lookup_by_name (resolver,
878 addr->priv->hostname,
882 g_object_unref (resolver);
886 g_network_address_set_addresses (addr, addresses, serial);
889 addr_enum->addresses = addr->priv->sockaddrs;
890 addr_enum->next = addr_enum->addresses;
891 g_object_unref (resolver);
894 if (addr_enum->next == NULL)
897 sockaddr = addr_enum->next->data;
898 addr_enum->next = addr_enum->next->next;
899 return g_object_ref (sockaddr);
903 have_addresses (GNetworkAddressAddressEnumerator *addr_enum,
904 GTask *task, GError *error)
906 GSocketAddress *sockaddr;
908 addr_enum->addresses = addr_enum->addr->priv->sockaddrs;
909 addr_enum->next = addr_enum->addresses;
913 sockaddr = g_object_ref (addr_enum->next->data);
914 addr_enum->next = addr_enum->next->next;
920 g_task_return_error (task, error);
922 g_task_return_pointer (task, sockaddr, g_object_unref);
923 g_object_unref (task);
927 got_addresses (GObject *source_object,
928 GAsyncResult *result,
931 GTask *task = user_data;
932 GNetworkAddressAddressEnumerator *addr_enum = g_task_get_source_object (task);
933 GResolver *resolver = G_RESOLVER (source_object);
935 GError *error = NULL;
937 if (!addr_enum->addr->priv->sockaddrs)
939 addresses = g_resolver_lookup_by_name_finish (resolver, result, &error);
943 g_network_address_set_addresses (addr_enum->addr, addresses,
944 g_resolver_get_serial (resolver));
947 have_addresses (addr_enum, task, error);
951 g_network_address_address_enumerator_next_async (GSocketAddressEnumerator *enumerator,
952 GCancellable *cancellable,
953 GAsyncReadyCallback callback,
956 GNetworkAddressAddressEnumerator *addr_enum =
957 G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (enumerator);
958 GSocketAddress *sockaddr;
961 task = g_task_new (addr_enum, cancellable, callback, user_data);
963 if (addr_enum->addresses == NULL)
965 GNetworkAddress *addr = addr_enum->addr;
966 GResolver *resolver = g_resolver_get_default ();
967 gint64 serial = g_resolver_get_serial (resolver);
969 if (addr->priv->resolver_serial != 0 &&
970 addr->priv->resolver_serial != serial)
972 /* Resolver has reloaded, discard cached addresses */
973 g_list_free_full (addr->priv->sockaddrs, g_object_unref);
974 addr->priv->sockaddrs = NULL;
977 if (!addr->priv->sockaddrs)
979 if (g_network_address_parse_sockaddr (addr))
980 have_addresses (addr_enum, task, NULL);
983 g_resolver_lookup_by_name_async (resolver,
984 addr->priv->hostname,
986 got_addresses, task);
988 g_object_unref (resolver);
992 addr_enum->addresses = addr->priv->sockaddrs;
993 addr_enum->next = addr_enum->addresses;
994 g_object_unref (resolver);
999 sockaddr = g_object_ref (addr_enum->next->data);
1000 addr_enum->next = addr_enum->next->next;
1005 g_task_return_pointer (task, sockaddr, g_object_unref);
1006 g_object_unref (task);
1009 static GSocketAddress *
1010 g_network_address_address_enumerator_next_finish (GSocketAddressEnumerator *enumerator,
1011 GAsyncResult *result,
1014 g_return_val_if_fail (g_task_is_valid (result, enumerator), NULL);
1016 return g_task_propagate_pointer (G_TASK (result), error);
1020 _g_network_address_address_enumerator_init (GNetworkAddressAddressEnumerator *enumerator)
1025 _g_network_address_address_enumerator_class_init (GNetworkAddressAddressEnumeratorClass *addrenum_class)
1027 GObjectClass *object_class = G_OBJECT_CLASS (addrenum_class);
1028 GSocketAddressEnumeratorClass *enumerator_class =
1029 G_SOCKET_ADDRESS_ENUMERATOR_CLASS (addrenum_class);
1031 enumerator_class->next = g_network_address_address_enumerator_next;
1032 enumerator_class->next_async = g_network_address_address_enumerator_next_async;
1033 enumerator_class->next_finish = g_network_address_address_enumerator_next_finish;
1034 object_class->finalize = g_network_address_address_enumerator_finalize;
1037 static GSocketAddressEnumerator *
1038 g_network_address_connectable_enumerate (GSocketConnectable *connectable)
1040 GNetworkAddressAddressEnumerator *addr_enum;
1042 addr_enum = g_object_new (G_TYPE_NETWORK_ADDRESS_ADDRESS_ENUMERATOR, NULL);
1043 addr_enum->addr = g_object_ref (connectable);
1045 return (GSocketAddressEnumerator *)addr_enum;
1048 static GSocketAddressEnumerator *
1049 g_network_address_connectable_proxy_enumerate (GSocketConnectable *connectable)
1051 GNetworkAddress *self = G_NETWORK_ADDRESS (connectable);
1052 GSocketAddressEnumerator *proxy_enum;
1055 uri = _g_uri_from_authority (self->priv->scheme ? self->priv->scheme : "none",
1056 self->priv->hostname,
1060 proxy_enum = g_object_new (G_TYPE_PROXY_ADDRESS_ENUMERATOR,
1061 "connectable", connectable,