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 {
69 gint64 resolver_serial;
79 static void g_network_address_set_property (GObject *object,
83 static void g_network_address_get_property (GObject *object,
88 static void g_network_address_connectable_iface_init (GSocketConnectableIface *iface);
89 static GSocketAddressEnumerator *g_network_address_connectable_enumerate (GSocketConnectable *connectable);
90 static GSocketAddressEnumerator *g_network_address_connectable_proxy_enumerate (GSocketConnectable *connectable);
92 G_DEFINE_TYPE_WITH_CODE (GNetworkAddress, g_network_address, G_TYPE_OBJECT,
93 G_ADD_PRIVATE (GNetworkAddress)
94 G_IMPLEMENT_INTERFACE (G_TYPE_SOCKET_CONNECTABLE,
95 g_network_address_connectable_iface_init))
98 g_network_address_finalize (GObject *object)
100 GNetworkAddress *addr = G_NETWORK_ADDRESS (object);
102 g_free (addr->priv->hostname);
103 g_free (addr->priv->scheme);
105 if (addr->priv->sockaddrs)
109 for (a = addr->priv->sockaddrs; a; a = a->next)
110 g_object_unref (a->data);
111 g_list_free (addr->priv->sockaddrs);
114 G_OBJECT_CLASS (g_network_address_parent_class)->finalize (object);
118 g_network_address_class_init (GNetworkAddressClass *klass)
120 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
122 gobject_class->set_property = g_network_address_set_property;
123 gobject_class->get_property = g_network_address_get_property;
124 gobject_class->finalize = g_network_address_finalize;
126 g_object_class_install_property (gobject_class, PROP_HOSTNAME,
127 g_param_spec_string ("hostname",
129 P_("Hostname to resolve"),
132 G_PARAM_CONSTRUCT_ONLY |
133 G_PARAM_STATIC_STRINGS));
134 g_object_class_install_property (gobject_class, PROP_PORT,
135 g_param_spec_uint ("port",
140 G_PARAM_CONSTRUCT_ONLY |
141 G_PARAM_STATIC_STRINGS));
143 g_object_class_install_property (gobject_class, PROP_SCHEME,
144 g_param_spec_string ("scheme",
149 G_PARAM_CONSTRUCT_ONLY |
150 G_PARAM_STATIC_STRINGS));
154 g_network_address_connectable_iface_init (GSocketConnectableIface *connectable_iface)
156 connectable_iface->enumerate = g_network_address_connectable_enumerate;
157 connectable_iface->proxy_enumerate = g_network_address_connectable_proxy_enumerate;
161 g_network_address_init (GNetworkAddress *addr)
163 addr->priv = g_network_address_get_private (addr);
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,
230 guint64 resolver_serial)
233 GSocketAddress *sockaddr;
235 g_return_if_fail (addresses != NULL && addr->priv->sockaddrs == NULL);
237 for (a = addresses; a; a = a->next)
239 sockaddr = g_inet_socket_address_new (a->data, addr->priv->port);
240 addr->priv->sockaddrs = g_list_prepend (addr->priv->sockaddrs, sockaddr);
241 g_object_unref (a->data);
243 g_list_free (addresses);
244 addr->priv->sockaddrs = g_list_reverse (addr->priv->sockaddrs);
246 addr->priv->resolver_serial = resolver_serial;
250 g_network_address_parse_sockaddr (GNetworkAddress *addr)
252 struct addrinfo hints, *res = NULL;
253 GSocketAddress *sockaddr;
256 memset (&hints, 0, sizeof (hints));
257 hints.ai_flags = AI_NUMERICHOST
258 #ifdef AI_NUMERICSERV
262 g_snprintf (port, sizeof (port), "%u", addr->priv->port);
264 if (getaddrinfo (addr->priv->hostname, port, &hints, &res) != 0)
267 sockaddr = g_socket_address_new_from_native (res->ai_addr, res->ai_addrlen);
269 if (!sockaddr || !G_IS_INET_SOCKET_ADDRESS (sockaddr))
272 addr->priv->sockaddrs = g_list_prepend (addr->priv->sockaddrs, sockaddr);
277 * g_network_address_new:
278 * @hostname: the hostname
281 * Creates a new #GSocketConnectable for connecting to the given
282 * @hostname and @port.
284 * Return value: (transfer full) (type GNetworkAddress): the new #GNetworkAddress
289 g_network_address_new (const gchar *hostname,
292 return g_object_new (G_TYPE_NETWORK_ADDRESS,
293 "hostname", hostname,
299 * g_network_address_parse:
300 * @host_and_port: the hostname and optionally a port
301 * @default_port: the default port if not in @host_and_port
302 * @error: a pointer to a #GError, or %NULL
304 * Creates a new #GSocketConnectable for connecting to the given
305 * @hostname and @port. May fail and return %NULL in case
306 * parsing @host_and_port fails.
308 * @host_and_port may be in any of a number of recognised formats; an IPv6
309 * address, an IPv4 address, or a domain name (in which case a DNS
310 * lookup is performed). Quoting with [] is supported for all address
311 * types. A port override may be specified in the usual way with a
314 * If no port is specified in @host_and_port then @default_port will be
315 * used as the port number to connect to.
317 * In general, @host_and_port is expected to be provided by the user
318 * (allowing them to give the hostname, and a port overide if necessary)
319 * and @default_port is expected to be provided by the application.
321 * (The port component of @host_and_port can also be specified as a
322 * service name rather than as a numeric port, but this functionality
323 * is deprecated, because it depends on the contents of /etc/services,
324 * which is generally quite sparse on platforms other than Linux.)
326 * Return value: (transfer full): the new #GNetworkAddress, or %NULL on error
331 g_network_address_parse (const gchar *host_and_port,
332 guint16 default_port,
335 GSocketConnectable *connectable;
340 g_return_val_if_fail (host_and_port != NULL, NULL);
343 if (host_and_port[0] == '[')
344 /* escaped host part (to allow, eg. "[2001:db8::1]:888") */
348 end = strchr (host_and_port, ']');
351 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
352 _("Hostname '%s' contains '[' but not ']'"), host_and_port);
358 else if (end[1] == ':')
362 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
363 "The ']' character (in hostname '%s') must come at the"
364 " end or be immediately followed by ':' and a port",
369 name = g_strndup (host_and_port + 1, end - host_and_port - 1);
372 else if ((port = strchr (host_and_port, ':')))
373 /* string has a ':' in it */
378 if (strchr (port, ':'))
379 /* more than one ':' in string */
381 /* this is actually an unescaped IPv6 address */
382 name = g_strdup (host_and_port);
386 name = g_strndup (host_and_port, port - host_and_port - 1);
390 /* plain hostname, no port */
391 name = g_strdup (host_and_port);
397 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
398 "If a ':' character is given, it must be followed by a "
399 "port (in hostname '%s').", host_and_port);
404 else if ('0' <= port[0] && port[0] <= '9')
409 value = strtol (port, &end, 10);
410 if (*end != '\0' || value < 0 || value > G_MAXUINT16)
412 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
413 "Invalid numeric port '%s' specified in hostname '%s'",
414 port, host_and_port);
424 struct servent *entry;
426 entry = getservbyname (port, "tcp");
429 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
430 "Unknown service '%s' specified in hostname '%s'",
431 port, host_and_port);
432 #ifdef HAVE_ENDSERVENT
439 portnum = g_ntohs (entry->s_port);
441 #ifdef HAVE_ENDSERVENT
448 /* No port in host_and_port */
449 portnum = default_port;
452 connectable = g_network_address_new (name, portnum);
458 /* Allowed characters outside alphanumeric for unreserved. */
459 #define G_URI_OTHER_UNRESERVED "-._~"
461 /* This or something equivalent will eventually go into glib/guri.h */
463 _g_uri_parse_authority (const char *uri,
469 const char *start, *p;
472 g_return_val_if_fail (uri != NULL, FALSE);
483 /* From RFC 3986 Decodes:
484 * URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
485 * hier-part = "//" authority path-abempty
486 * path-abempty = *( "/" segment )
487 * authority = [ userinfo "@" ] host [ ":" port ]
490 /* Check we have a valid scheme */
491 tmp_str = g_uri_parse_scheme (uri);
499 * hier-part = "//" authority path-abempty
502 start = strstr (p, "//");
509 if (strchr (start, '@') != NULL)
512 * userinfo = *( unreserved / pct-encoded / sub-delims / ":" )
513 * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
514 * pct-encoded = "%" HEXDIG HEXDIG
527 if (!(g_ascii_isxdigit (p[0]) ||
528 g_ascii_isxdigit (p[1])))
536 /* unreserved / sub-delims / : */
537 if (!(g_ascii_isalnum (c) ||
538 strchr (G_URI_OTHER_UNRESERVED, c) ||
539 strchr (G_URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS, c) ||
545 *userinfo = g_strndup (start, p - start - 1);
556 * host = IP-literal / IPv4address / reg-name
557 * reg-name = *( unreserved / pct-encoded / sub-delims )
560 /* If IPv6 or IPvFuture */
572 /* unreserved / sub-delims */
573 if (!(g_ascii_isalnum (c) ||
574 strchr (G_URI_OTHER_UNRESERVED, c) ||
575 strchr (G_URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS, c) ||
597 if (!(g_ascii_isxdigit (p[0]) ||
598 g_ascii_isxdigit (p[1])))
606 /* unreserved / sub-delims */
607 if (!(g_ascii_isalnum (c) ||
608 strchr (G_URI_OTHER_UNRESERVED, c) ||
609 strchr (G_URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS, c)))
615 *host = g_uri_unescape_segment (start, p - 1, NULL);
634 if (!g_ascii_isdigit (c))
637 tmp = (tmp * 10) + (c - '0');
643 *port = (guint16) tmp;
655 if (userinfo && *userinfo)
665 _g_uri_from_authority (const gchar *protocol,
668 const gchar *userinfo)
672 uri = g_string_new (protocol);
673 g_string_append (uri, "://");
677 g_string_append_uri_escaped (uri, userinfo, G_URI_RESERVED_CHARS_ALLOWED_IN_USERINFO, FALSE);
678 g_string_append_c (uri, '@');
681 if (g_hostname_is_non_ascii (host))
683 gchar *ace_encoded = g_hostname_to_ascii (host);
687 g_string_free (uri, TRUE);
690 g_string_append (uri, ace_encoded);
691 g_free (ace_encoded);
693 else if (strchr (host, ':'))
694 g_string_append_printf (uri, "[%s]", host);
696 g_string_append (uri, host);
699 g_string_append_printf (uri, ":%u", port);
701 return g_string_free (uri, FALSE);
705 * g_network_address_parse_uri:
706 * @uri: the hostname and optionally a port
707 * @default_port: The default port if none is found in the URI
708 * @error: a pointer to a #GError, or %NULL
710 * Creates a new #GSocketConnectable for connecting to the given
711 * @uri. May fail and return %NULL in case parsing @uri fails.
713 * Using this rather than g_network_address_new() or
714 * g_network_address_parse() allows #GSocketClient to determine
715 * when to use application-specific proxy protocols.
717 * Return value: (transfer full): the new #GNetworkAddress, or %NULL on error
722 g_network_address_parse_uri (const gchar *uri,
723 guint16 default_port,
726 GSocketConnectable *conn;
731 if (!_g_uri_parse_authority (uri, &hostname, &port, NULL))
733 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
742 scheme = g_uri_parse_scheme (uri);
744 conn = g_object_new (G_TYPE_NETWORK_ADDRESS,
745 "hostname", hostname,
757 * g_network_address_get_hostname:
758 * @addr: a #GNetworkAddress
760 * Gets @addr's hostname. This might be either UTF-8 or ASCII-encoded,
761 * depending on what @addr was created with.
763 * Return value: @addr's hostname
768 g_network_address_get_hostname (GNetworkAddress *addr)
770 g_return_val_if_fail (G_IS_NETWORK_ADDRESS (addr), NULL);
772 return addr->priv->hostname;
776 * g_network_address_get_port:
777 * @addr: a #GNetworkAddress
779 * Gets @addr's port number
781 * Return value: @addr's port (which may be 0)
786 g_network_address_get_port (GNetworkAddress *addr)
788 g_return_val_if_fail (G_IS_NETWORK_ADDRESS (addr), 0);
790 return addr->priv->port;
794 * g_network_address_get_scheme:
795 * @addr: a #GNetworkAddress
797 * Gets @addr's scheme
799 * Return value: @addr's scheme (%NULL if not built from URI)
804 g_network_address_get_scheme (GNetworkAddress *addr)
806 g_return_val_if_fail (G_IS_NETWORK_ADDRESS (addr), NULL);
808 return addr->priv->scheme;
811 #define G_TYPE_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (_g_network_address_address_enumerator_get_type ())
812 #define G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), G_TYPE_NETWORK_ADDRESS_ADDRESS_ENUMERATOR, GNetworkAddressAddressEnumerator))
815 GSocketAddressEnumerator parent_instance;
817 GNetworkAddress *addr;
820 } GNetworkAddressAddressEnumerator;
823 GSocketAddressEnumeratorClass parent_class;
825 } GNetworkAddressAddressEnumeratorClass;
827 static GType _g_network_address_address_enumerator_get_type (void);
828 G_DEFINE_TYPE (GNetworkAddressAddressEnumerator, _g_network_address_address_enumerator, G_TYPE_SOCKET_ADDRESS_ENUMERATOR)
831 g_network_address_address_enumerator_finalize (GObject *object)
833 GNetworkAddressAddressEnumerator *addr_enum =
834 G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (object);
836 g_object_unref (addr_enum->addr);
838 G_OBJECT_CLASS (_g_network_address_address_enumerator_parent_class)->finalize (object);
841 static GSocketAddress *
842 g_network_address_address_enumerator_next (GSocketAddressEnumerator *enumerator,
843 GCancellable *cancellable,
846 GNetworkAddressAddressEnumerator *addr_enum =
847 G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (enumerator);
848 GSocketAddress *sockaddr;
850 if (addr_enum->addresses == NULL)
852 GNetworkAddress *addr = addr_enum->addr;
853 GResolver *resolver = g_resolver_get_default ();
854 gint64 serial = g_resolver_get_serial (resolver);
856 if (addr->priv->resolver_serial != 0 &&
857 addr->priv->resolver_serial != serial)
859 /* Resolver has reloaded, discard cached addresses */
860 g_list_free_full (addr->priv->sockaddrs, g_object_unref);
861 addr->priv->sockaddrs = NULL;
864 if (!addr->priv->sockaddrs)
865 g_network_address_parse_sockaddr (addr);
866 if (!addr->priv->sockaddrs)
870 addresses = g_resolver_lookup_by_name (resolver,
871 addr->priv->hostname,
875 g_object_unref (resolver);
879 g_network_address_set_addresses (addr, addresses, serial);
882 addr_enum->addresses = addr->priv->sockaddrs;
883 addr_enum->next = addr_enum->addresses;
884 g_object_unref (resolver);
887 if (addr_enum->next == NULL)
890 sockaddr = addr_enum->next->data;
891 addr_enum->next = addr_enum->next->next;
892 return g_object_ref (sockaddr);
896 have_addresses (GNetworkAddressAddressEnumerator *addr_enum,
897 GTask *task, GError *error)
899 GSocketAddress *sockaddr;
901 addr_enum->addresses = addr_enum->addr->priv->sockaddrs;
902 addr_enum->next = addr_enum->addresses;
906 sockaddr = g_object_ref (addr_enum->next->data);
907 addr_enum->next = addr_enum->next->next;
913 g_task_return_error (task, error);
915 g_task_return_pointer (task, sockaddr, g_object_unref);
916 g_object_unref (task);
920 got_addresses (GObject *source_object,
921 GAsyncResult *result,
924 GTask *task = user_data;
925 GNetworkAddressAddressEnumerator *addr_enum = g_task_get_source_object (task);
926 GResolver *resolver = G_RESOLVER (source_object);
928 GError *error = NULL;
930 if (!addr_enum->addr->priv->sockaddrs)
932 addresses = g_resolver_lookup_by_name_finish (resolver, result, &error);
936 g_network_address_set_addresses (addr_enum->addr, addresses,
937 g_resolver_get_serial (resolver));
940 have_addresses (addr_enum, task, error);
944 g_network_address_address_enumerator_next_async (GSocketAddressEnumerator *enumerator,
945 GCancellable *cancellable,
946 GAsyncReadyCallback callback,
949 GNetworkAddressAddressEnumerator *addr_enum =
950 G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (enumerator);
951 GSocketAddress *sockaddr;
954 task = g_task_new (addr_enum, cancellable, callback, user_data);
956 if (addr_enum->addresses == NULL)
958 GNetworkAddress *addr = addr_enum->addr;
959 GResolver *resolver = g_resolver_get_default ();
960 gint64 serial = g_resolver_get_serial (resolver);
962 if (addr->priv->resolver_serial != 0 &&
963 addr->priv->resolver_serial != serial)
965 /* Resolver has reloaded, discard cached addresses */
966 g_list_free_full (addr->priv->sockaddrs, g_object_unref);
967 addr->priv->sockaddrs = NULL;
970 if (!addr->priv->sockaddrs)
972 if (g_network_address_parse_sockaddr (addr))
973 have_addresses (addr_enum, task, NULL);
976 g_resolver_lookup_by_name_async (resolver,
977 addr->priv->hostname,
979 got_addresses, task);
981 g_object_unref (resolver);
985 addr_enum->addresses = addr->priv->sockaddrs;
986 addr_enum->next = addr_enum->addresses;
987 g_object_unref (resolver);
992 sockaddr = g_object_ref (addr_enum->next->data);
993 addr_enum->next = addr_enum->next->next;
998 g_task_return_pointer (task, sockaddr, g_object_unref);
999 g_object_unref (task);
1002 static GSocketAddress *
1003 g_network_address_address_enumerator_next_finish (GSocketAddressEnumerator *enumerator,
1004 GAsyncResult *result,
1007 g_return_val_if_fail (g_task_is_valid (result, enumerator), NULL);
1009 return g_task_propagate_pointer (G_TASK (result), error);
1013 _g_network_address_address_enumerator_init (GNetworkAddressAddressEnumerator *enumerator)
1018 _g_network_address_address_enumerator_class_init (GNetworkAddressAddressEnumeratorClass *addrenum_class)
1020 GObjectClass *object_class = G_OBJECT_CLASS (addrenum_class);
1021 GSocketAddressEnumeratorClass *enumerator_class =
1022 G_SOCKET_ADDRESS_ENUMERATOR_CLASS (addrenum_class);
1024 enumerator_class->next = g_network_address_address_enumerator_next;
1025 enumerator_class->next_async = g_network_address_address_enumerator_next_async;
1026 enumerator_class->next_finish = g_network_address_address_enumerator_next_finish;
1027 object_class->finalize = g_network_address_address_enumerator_finalize;
1030 static GSocketAddressEnumerator *
1031 g_network_address_connectable_enumerate (GSocketConnectable *connectable)
1033 GNetworkAddressAddressEnumerator *addr_enum;
1035 addr_enum = g_object_new (G_TYPE_NETWORK_ADDRESS_ADDRESS_ENUMERATOR, NULL);
1036 addr_enum->addr = g_object_ref (connectable);
1038 return (GSocketAddressEnumerator *)addr_enum;
1041 static GSocketAddressEnumerator *
1042 g_network_address_connectable_proxy_enumerate (GSocketConnectable *connectable)
1044 GNetworkAddress *self = G_NETWORK_ADDRESS (connectable);
1045 GSocketAddressEnumerator *proxy_enum;
1048 uri = _g_uri_from_authority (self->priv->scheme ? self->priv->scheme : "none",
1049 self->priv->hostname,
1053 proxy_enum = g_object_new (G_TYPE_PROXY_ADDRESS_ENUMERATOR,
1054 "connectable", connectable,