Merge branch 'g-clear-pointer-no-side-effects' into 'master'
[glib.git] / gio / gnetworkaddress.c
blob8d5a996e1e03c4f16d6d04ee0ae8bec6f6f9299a
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.1 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/>.
21 #include "config.h"
22 #include <glib.h>
23 #include "glibintl.h"
25 #include <stdlib.h>
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"
33 #include "gtask.h"
34 #include "gsocketaddressenumerator.h"
35 #include "gioerror.h"
36 #include "gsocketconnectable.h"
38 #include <string.h>
41 /**
42 * SECTION:gnetworkaddress
43 * @short_description: A GSocketConnectable for resolving hostnames
44 * @include: gio/gio.h
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
51 * interface.
54 /**
55 * GNetworkAddress:
57 * A #GSocketConnectable for resolving a hostname and connecting to
58 * that host.
61 struct _GNetworkAddressPrivate {
62 gchar *hostname;
63 guint16 port;
64 GList *sockaddrs;
65 gchar *scheme;
67 gint64 resolver_serial;
70 enum {
71 PROP_0,
72 PROP_HOSTNAME,
73 PROP_PORT,
74 PROP_SCHEME,
77 static void g_network_address_set_property (GObject *object,
78 guint prop_id,
79 const GValue *value,
80 GParamSpec *pspec);
81 static void g_network_address_get_property (GObject *object,
82 guint prop_id,
83 GValue *value,
84 GParamSpec *pspec);
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);
89 static gchar *g_network_address_connectable_to_string (GSocketConnectable *connectable);
91 G_DEFINE_TYPE_WITH_CODE (GNetworkAddress, g_network_address, G_TYPE_OBJECT,
92 G_ADD_PRIVATE (GNetworkAddress)
93 G_IMPLEMENT_INTERFACE (G_TYPE_SOCKET_CONNECTABLE,
94 g_network_address_connectable_iface_init))
96 static void
97 g_network_address_finalize (GObject *object)
99 GNetworkAddress *addr = G_NETWORK_ADDRESS (object);
101 g_free (addr->priv->hostname);
102 g_free (addr->priv->scheme);
103 g_list_free_full (addr->priv->sockaddrs, g_object_unref);
105 G_OBJECT_CLASS (g_network_address_parent_class)->finalize (object);
108 static void
109 g_network_address_class_init (GNetworkAddressClass *klass)
111 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
113 gobject_class->set_property = g_network_address_set_property;
114 gobject_class->get_property = g_network_address_get_property;
115 gobject_class->finalize = g_network_address_finalize;
117 g_object_class_install_property (gobject_class, PROP_HOSTNAME,
118 g_param_spec_string ("hostname",
119 P_("Hostname"),
120 P_("Hostname to resolve"),
121 NULL,
122 G_PARAM_READWRITE |
123 G_PARAM_CONSTRUCT_ONLY |
124 G_PARAM_STATIC_STRINGS));
125 g_object_class_install_property (gobject_class, PROP_PORT,
126 g_param_spec_uint ("port",
127 P_("Port"),
128 P_("Network port"),
129 0, 65535, 0,
130 G_PARAM_READWRITE |
131 G_PARAM_CONSTRUCT_ONLY |
132 G_PARAM_STATIC_STRINGS));
134 g_object_class_install_property (gobject_class, PROP_SCHEME,
135 g_param_spec_string ("scheme",
136 P_("Scheme"),
137 P_("URI Scheme"),
138 NULL,
139 G_PARAM_READWRITE |
140 G_PARAM_CONSTRUCT_ONLY |
141 G_PARAM_STATIC_STRINGS));
144 static void
145 g_network_address_connectable_iface_init (GSocketConnectableIface *connectable_iface)
147 connectable_iface->enumerate = g_network_address_connectable_enumerate;
148 connectable_iface->proxy_enumerate = g_network_address_connectable_proxy_enumerate;
149 connectable_iface->to_string = g_network_address_connectable_to_string;
152 static void
153 g_network_address_init (GNetworkAddress *addr)
155 addr->priv = g_network_address_get_instance_private (addr);
158 static void
159 g_network_address_set_property (GObject *object,
160 guint prop_id,
161 const GValue *value,
162 GParamSpec *pspec)
164 GNetworkAddress *addr = G_NETWORK_ADDRESS (object);
166 switch (prop_id)
168 case PROP_HOSTNAME:
169 g_free (addr->priv->hostname);
170 addr->priv->hostname = g_value_dup_string (value);
171 break;
173 case PROP_PORT:
174 addr->priv->port = g_value_get_uint (value);
175 break;
177 case PROP_SCHEME:
178 g_free (addr->priv->scheme);
179 addr->priv->scheme = g_value_dup_string (value);
180 break;
182 default:
183 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
184 break;
189 static void
190 g_network_address_get_property (GObject *object,
191 guint prop_id,
192 GValue *value,
193 GParamSpec *pspec)
195 GNetworkAddress *addr = G_NETWORK_ADDRESS (object);
197 switch (prop_id)
199 case PROP_HOSTNAME:
200 g_value_set_string (value, addr->priv->hostname);
201 break;
203 case PROP_PORT:
204 g_value_set_uint (value, addr->priv->port);
205 break;
207 case PROP_SCHEME:
208 g_value_set_string (value, addr->priv->scheme);
209 break;
211 default:
212 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
213 break;
218 static void
219 g_network_address_set_addresses (GNetworkAddress *addr,
220 GList *addresses,
221 guint64 resolver_serial)
223 GList *a;
224 GSocketAddress *sockaddr;
226 g_return_if_fail (addresses != NULL && addr->priv->sockaddrs == NULL);
228 for (a = addresses; a; a = a->next)
230 sockaddr = g_inet_socket_address_new (a->data, addr->priv->port);
231 addr->priv->sockaddrs = g_list_prepend (addr->priv->sockaddrs, sockaddr);
232 g_object_unref (a->data);
234 g_list_free (addresses);
235 addr->priv->sockaddrs = g_list_reverse (addr->priv->sockaddrs);
237 addr->priv->resolver_serial = resolver_serial;
240 static gboolean
241 g_network_address_parse_sockaddr (GNetworkAddress *addr)
243 GSocketAddress *sockaddr;
245 sockaddr = g_inet_socket_address_new_from_string (addr->priv->hostname,
246 addr->priv->port);
247 if (sockaddr)
249 addr->priv->sockaddrs = g_list_prepend (addr->priv->sockaddrs, sockaddr);
250 return TRUE;
252 else
253 return FALSE;
257 * g_network_address_new:
258 * @hostname: the hostname
259 * @port: the port
261 * Creates a new #GSocketConnectable for connecting to the given
262 * @hostname and @port.
264 * Note that depending on the configuration of the machine, a
265 * @hostname of `localhost` may refer to the IPv4 loopback address
266 * only, or to both IPv4 and IPv6; use
267 * g_network_address_new_loopback() to create a #GNetworkAddress that
268 * is guaranteed to resolve to both addresses.
270 * Returns: (transfer full) (type GNetworkAddress): the new #GNetworkAddress
272 * Since: 2.22
274 GSocketConnectable *
275 g_network_address_new (const gchar *hostname,
276 guint16 port)
278 return g_object_new (G_TYPE_NETWORK_ADDRESS,
279 "hostname", hostname,
280 "port", port,
281 NULL);
285 * g_network_address_new_loopback:
286 * @port: the port
288 * Creates a new #GSocketConnectable for connecting to the local host
289 * over a loopback connection to the given @port. This is intended for
290 * use in connecting to local services which may be running on IPv4 or
291 * IPv6.
293 * The connectable will return IPv4 and IPv6 loopback addresses,
294 * regardless of how the host resolves `localhost`. By contrast,
295 * g_network_address_new() will often only return an IPv4 address when
296 * resolving `localhost`, and an IPv6 address for `localhost6`.
298 * g_network_address_get_hostname() will always return `localhost` for
299 * #GNetworkAddresses created with this constructor.
301 * Returns: (transfer full) (type GNetworkAddress): the new #GNetworkAddress
303 * Since: 2.44
305 GSocketConnectable *
306 g_network_address_new_loopback (guint16 port)
308 GNetworkAddress *addr;
309 GList *addrs = NULL;
311 addr = g_object_new (G_TYPE_NETWORK_ADDRESS,
312 "hostname", "localhost",
313 "port", port,
314 NULL);
316 addrs = g_list_append (addrs, g_inet_address_new_loopback (AF_INET6));
317 addrs = g_list_append (addrs, g_inet_address_new_loopback (AF_INET));
318 g_network_address_set_addresses (addr, addrs, 0);
320 return G_SOCKET_CONNECTABLE (addr);
324 * g_network_address_parse:
325 * @host_and_port: the hostname and optionally a port
326 * @default_port: the default port if not in @host_and_port
327 * @error: a pointer to a #GError, or %NULL
329 * Creates a new #GSocketConnectable for connecting to the given
330 * @hostname and @port. May fail and return %NULL in case
331 * parsing @host_and_port fails.
333 * @host_and_port may be in any of a number of recognised formats; an IPv6
334 * address, an IPv4 address, or a domain name (in which case a DNS
335 * lookup is performed). Quoting with [] is supported for all address
336 * types. A port override may be specified in the usual way with a
337 * colon.
339 * If no port is specified in @host_and_port then @default_port will be
340 * used as the port number to connect to.
342 * In general, @host_and_port is expected to be provided by the user
343 * (allowing them to give the hostname, and a port override if necessary)
344 * and @default_port is expected to be provided by the application.
346 * (The port component of @host_and_port can also be specified as a
347 * service name rather than as a numeric port, but this functionality
348 * is deprecated, because it depends on the contents of /etc/services,
349 * which is generally quite sparse on platforms other than Linux.)
351 * Returns: (transfer full) (type GNetworkAddress): the new
352 * #GNetworkAddress, or %NULL on error
354 * Since: 2.22
356 GSocketConnectable *
357 g_network_address_parse (const gchar *host_and_port,
358 guint16 default_port,
359 GError **error)
361 GSocketConnectable *connectable;
362 const gchar *port;
363 guint16 portnum;
364 gchar *name;
366 g_return_val_if_fail (host_and_port != NULL, NULL);
368 port = NULL;
369 if (host_and_port[0] == '[')
370 /* escaped host part (to allow, eg. "[2001:db8::1]:888") */
372 const gchar *end;
374 end = strchr (host_and_port, ']');
375 if (end == NULL)
377 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
378 _("Hostname “%s” contains “[” but not “]”"), host_and_port);
379 return NULL;
382 if (end[1] == '\0')
383 port = NULL;
384 else if (end[1] == ':')
385 port = &end[2];
386 else
388 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
389 "The ']' character (in hostname '%s') must come at the"
390 " end or be immediately followed by ':' and a port",
391 host_and_port);
392 return NULL;
395 name = g_strndup (host_and_port + 1, end - host_and_port - 1);
398 else if ((port = strchr (host_and_port, ':')))
399 /* string has a ':' in it */
401 /* skip ':' */
402 port++;
404 if (strchr (port, ':'))
405 /* more than one ':' in string */
407 /* this is actually an unescaped IPv6 address */
408 name = g_strdup (host_and_port);
409 port = NULL;
411 else
412 name = g_strndup (host_and_port, port - host_and_port - 1);
415 else
416 /* plain hostname, no port */
417 name = g_strdup (host_and_port);
419 if (port != NULL)
421 if (port[0] == '\0')
423 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
424 "If a ':' character is given, it must be followed by a "
425 "port (in hostname '%s').", host_and_port);
426 g_free (name);
427 return NULL;
430 else if ('0' <= port[0] && port[0] <= '9')
432 char *end;
433 long value;
435 value = strtol (port, &end, 10);
436 if (*end != '\0' || value < 0 || value > G_MAXUINT16)
438 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
439 "Invalid numeric port '%s' specified in hostname '%s'",
440 port, host_and_port);
441 g_free (name);
442 return NULL;
445 portnum = value;
448 else
450 struct servent *entry;
452 entry = getservbyname (port, "tcp");
453 if (entry == NULL)
455 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
456 "Unknown service '%s' specified in hostname '%s'",
457 port, host_and_port);
458 #ifdef HAVE_ENDSERVENT
459 endservent ();
460 #endif
461 g_free (name);
462 return NULL;
465 portnum = g_ntohs (entry->s_port);
467 #ifdef HAVE_ENDSERVENT
468 endservent ();
469 #endif
472 else
474 /* No port in host_and_port */
475 portnum = default_port;
478 connectable = g_network_address_new (name, portnum);
479 g_free (name);
481 return connectable;
484 /* Allowed characters outside alphanumeric for unreserved. */
485 #define G_URI_OTHER_UNRESERVED "-._~"
487 /* This or something equivalent will eventually go into glib/guri.h */
488 gboolean
489 _g_uri_parse_authority (const char *uri,
490 char **host,
491 guint16 *port,
492 char **userinfo,
493 GError **error)
495 char *ascii_uri, *tmp_str;
496 const char *start, *p, *at, *delim;
497 char c;
499 g_return_val_if_fail (uri != NULL, FALSE);
501 if (host)
502 *host = NULL;
504 if (port)
505 *port = 0;
507 if (userinfo)
508 *userinfo = NULL;
510 /* Catch broken URIs early by trying to convert to ASCII. */
511 ascii_uri = g_hostname_to_ascii (uri);
512 if (!ascii_uri)
513 goto error;
515 /* From RFC 3986 Decodes:
516 * URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
517 * hier-part = "//" authority path-abempty
518 * path-abempty = *( "/" segment )
519 * authority = [ userinfo "@" ] host [ ":" port ]
522 /* Check we have a valid scheme */
523 tmp_str = g_uri_parse_scheme (ascii_uri);
525 if (tmp_str == NULL)
526 goto error;
528 g_free (tmp_str);
530 /* Decode hier-part:
531 * hier-part = "//" authority path-abempty
533 p = ascii_uri;
534 start = strstr (p, "//");
536 if (start == NULL)
537 goto error;
539 start += 2;
541 /* check if the @ sign is part of the authority before attempting to
542 * decode the userinfo */
543 delim = strpbrk (start, "/?#[]");
544 at = strchr (start, '@');
545 if (at && delim && at > delim)
546 at = NULL;
548 if (at != NULL)
550 /* Decode userinfo:
551 * userinfo = *( unreserved / pct-encoded / sub-delims / ":" )
552 * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
553 * pct-encoded = "%" HEXDIG HEXDIG
555 p = start;
556 while (1)
558 c = *p++;
560 if (c == '@')
561 break;
563 /* pct-encoded */
564 if (c == '%')
566 if (!(g_ascii_isxdigit (p[0]) ||
567 g_ascii_isxdigit (p[1])))
568 goto error;
570 p++;
572 continue;
575 /* unreserved / sub-delims / : */
576 if (!(g_ascii_isalnum (c) ||
577 strchr (G_URI_OTHER_UNRESERVED, c) ||
578 strchr (G_URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS, c) ||
579 c == ':'))
580 goto error;
583 if (userinfo)
584 *userinfo = g_strndup (start, p - start - 1);
586 start = p;
588 else
590 p = start;
594 /* decode host:
595 * host = IP-literal / IPv4address / reg-name
596 * reg-name = *( unreserved / pct-encoded / sub-delims )
599 /* If IPv6 or IPvFuture */
600 if (*p == '[')
602 gboolean has_scope_id = FALSE, has_bad_scope_id = FALSE;
604 start++;
605 p++;
606 while (1)
608 c = *p++;
610 if (c == ']')
611 break;
613 if (c == '%' && !has_scope_id)
615 has_scope_id = TRUE;
616 if (p[0] != '2' || p[1] != '5')
617 has_bad_scope_id = TRUE;
618 continue;
621 /* unreserved / sub-delims */
622 if (!(g_ascii_isalnum (c) ||
623 strchr (G_URI_OTHER_UNRESERVED, c) ||
624 strchr (G_URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS, c) ||
625 c == ':' ||
626 c == '.'))
627 goto error;
630 if (host)
632 if (has_bad_scope_id)
633 *host = g_strndup (start, p - start - 1);
634 else
635 *host = g_uri_unescape_segment (start, p - 1, NULL);
638 c = *p++;
640 else
642 while (1)
644 c = *p++;
646 if (c == ':' ||
647 c == '/' ||
648 c == '?' ||
649 c == '#' ||
650 c == '\0')
651 break;
653 /* pct-encoded */
654 if (c == '%')
656 if (!(g_ascii_isxdigit (p[0]) ||
657 g_ascii_isxdigit (p[1])))
658 goto error;
660 p++;
662 continue;
665 /* unreserved / sub-delims */
666 if (!(g_ascii_isalnum (c) ||
667 strchr (G_URI_OTHER_UNRESERVED, c) ||
668 strchr (G_URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS, c)))
669 goto error;
672 if (host)
673 *host = g_uri_unescape_segment (start, p - 1, NULL);
676 if (c == ':')
678 /* Decode port:
679 * port = *DIGIT
681 guint tmp = 0;
683 while (1)
685 c = *p++;
687 if (c == '/' ||
688 c == '?' ||
689 c == '#' ||
690 c == '\0')
691 break;
693 if (!g_ascii_isdigit (c))
694 goto error;
696 tmp = (tmp * 10) + (c - '0');
698 if (tmp > 65535)
699 goto error;
701 if (port)
702 *port = (guint16) tmp;
705 g_free (ascii_uri);
707 return TRUE;
709 error:
710 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
711 "Invalid URI ‘%s’", uri);
713 if (host && *host)
715 g_free (*host);
716 *host = NULL;
719 if (userinfo && *userinfo)
721 g_free (*userinfo);
722 *userinfo = NULL;
725 g_free (ascii_uri);
727 return FALSE;
730 gchar *
731 _g_uri_from_authority (const gchar *protocol,
732 const gchar *host,
733 guint port,
734 const gchar *userinfo)
736 GString *uri;
738 uri = g_string_new (protocol);
739 g_string_append (uri, "://");
741 if (userinfo)
743 g_string_append_uri_escaped (uri, userinfo, G_URI_RESERVED_CHARS_ALLOWED_IN_USERINFO, FALSE);
744 g_string_append_c (uri, '@');
747 if (g_hostname_is_non_ascii (host))
749 gchar *ace_encoded = g_hostname_to_ascii (host);
751 if (!ace_encoded)
753 g_string_free (uri, TRUE);
754 return NULL;
756 g_string_append (uri, ace_encoded);
757 g_free (ace_encoded);
759 else if (strchr (host, ':'))
760 g_string_append_printf (uri, "[%s]", host);
761 else
762 g_string_append (uri, host);
764 if (port != 0)
765 g_string_append_printf (uri, ":%u", port);
767 return g_string_free (uri, FALSE);
771 * g_network_address_parse_uri:
772 * @uri: the hostname and optionally a port
773 * @default_port: The default port if none is found in the URI
774 * @error: a pointer to a #GError, or %NULL
776 * Creates a new #GSocketConnectable for connecting to the given
777 * @uri. May fail and return %NULL in case parsing @uri fails.
779 * Using this rather than g_network_address_new() or
780 * g_network_address_parse() allows #GSocketClient to determine
781 * when to use application-specific proxy protocols.
783 * Returns: (transfer full) (type GNetworkAddress): the new
784 * #GNetworkAddress, or %NULL on error
786 * Since: 2.26
788 GSocketConnectable *
789 g_network_address_parse_uri (const gchar *uri,
790 guint16 default_port,
791 GError **error)
793 GSocketConnectable *conn;
794 gchar *scheme;
795 gchar *hostname;
796 guint16 port;
798 if (!_g_uri_parse_authority (uri, &hostname, &port, NULL, error))
799 return NULL;
801 if (port == 0)
802 port = default_port;
804 scheme = g_uri_parse_scheme (uri);
806 conn = g_object_new (G_TYPE_NETWORK_ADDRESS,
807 "hostname", hostname,
808 "port", port,
809 "scheme", scheme,
810 NULL);
812 g_free (scheme);
813 g_free (hostname);
815 return conn;
819 * g_network_address_get_hostname:
820 * @addr: a #GNetworkAddress
822 * Gets @addr's hostname. This might be either UTF-8 or ASCII-encoded,
823 * depending on what @addr was created with.
825 * Returns: @addr's hostname
827 * Since: 2.22
829 const gchar *
830 g_network_address_get_hostname (GNetworkAddress *addr)
832 g_return_val_if_fail (G_IS_NETWORK_ADDRESS (addr), NULL);
834 return addr->priv->hostname;
838 * g_network_address_get_port:
839 * @addr: a #GNetworkAddress
841 * Gets @addr's port number
843 * Returns: @addr's port (which may be 0)
845 * Since: 2.22
847 guint16
848 g_network_address_get_port (GNetworkAddress *addr)
850 g_return_val_if_fail (G_IS_NETWORK_ADDRESS (addr), 0);
852 return addr->priv->port;
856 * g_network_address_get_scheme:
857 * @addr: a #GNetworkAddress
859 * Gets @addr's scheme
861 * Returns: @addr's scheme (%NULL if not built from URI)
863 * Since: 2.26
865 const gchar *
866 g_network_address_get_scheme (GNetworkAddress *addr)
868 g_return_val_if_fail (G_IS_NETWORK_ADDRESS (addr), NULL);
870 return addr->priv->scheme;
873 #define G_TYPE_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (_g_network_address_address_enumerator_get_type ())
874 #define G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), G_TYPE_NETWORK_ADDRESS_ADDRESS_ENUMERATOR, GNetworkAddressAddressEnumerator))
876 typedef struct {
877 GSocketAddressEnumerator parent_instance;
879 GNetworkAddress *addr;
880 GList *addresses;
881 GList *next;
882 } GNetworkAddressAddressEnumerator;
884 typedef struct {
885 GSocketAddressEnumeratorClass parent_class;
887 } GNetworkAddressAddressEnumeratorClass;
889 static GType _g_network_address_address_enumerator_get_type (void);
890 G_DEFINE_TYPE (GNetworkAddressAddressEnumerator, _g_network_address_address_enumerator, G_TYPE_SOCKET_ADDRESS_ENUMERATOR)
892 static void
893 g_network_address_address_enumerator_finalize (GObject *object)
895 GNetworkAddressAddressEnumerator *addr_enum =
896 G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (object);
898 g_object_unref (addr_enum->addr);
900 G_OBJECT_CLASS (_g_network_address_address_enumerator_parent_class)->finalize (object);
903 static GSocketAddress *
904 g_network_address_address_enumerator_next (GSocketAddressEnumerator *enumerator,
905 GCancellable *cancellable,
906 GError **error)
908 GNetworkAddressAddressEnumerator *addr_enum =
909 G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (enumerator);
910 GSocketAddress *sockaddr;
912 if (addr_enum->addresses == NULL)
914 GNetworkAddress *addr = addr_enum->addr;
915 GResolver *resolver = g_resolver_get_default ();
916 gint64 serial = g_resolver_get_serial (resolver);
918 if (addr->priv->resolver_serial != 0 &&
919 addr->priv->resolver_serial != serial)
921 /* Resolver has reloaded, discard cached addresses */
922 g_list_free_full (addr->priv->sockaddrs, g_object_unref);
923 addr->priv->sockaddrs = NULL;
926 if (!addr->priv->sockaddrs)
927 g_network_address_parse_sockaddr (addr);
928 if (!addr->priv->sockaddrs)
930 GList *addresses;
932 addresses = g_resolver_lookup_by_name (resolver,
933 addr->priv->hostname,
934 cancellable, error);
935 if (!addresses)
937 g_object_unref (resolver);
938 return NULL;
941 g_network_address_set_addresses (addr, addresses, serial);
944 addr_enum->addresses = addr->priv->sockaddrs;
945 addr_enum->next = addr_enum->addresses;
946 g_object_unref (resolver);
949 if (addr_enum->next == NULL)
950 return NULL;
952 sockaddr = addr_enum->next->data;
953 addr_enum->next = addr_enum->next->next;
954 return g_object_ref (sockaddr);
957 static void
958 have_addresses (GNetworkAddressAddressEnumerator *addr_enum,
959 GTask *task, GError *error)
961 GSocketAddress *sockaddr;
963 addr_enum->addresses = addr_enum->addr->priv->sockaddrs;
964 addr_enum->next = addr_enum->addresses;
966 if (addr_enum->next)
968 sockaddr = g_object_ref (addr_enum->next->data);
969 addr_enum->next = addr_enum->next->next;
971 else
972 sockaddr = NULL;
974 if (error)
975 g_task_return_error (task, error);
976 else
977 g_task_return_pointer (task, sockaddr, g_object_unref);
978 g_object_unref (task);
981 static void
982 got_addresses (GObject *source_object,
983 GAsyncResult *result,
984 gpointer user_data)
986 GTask *task = user_data;
987 GNetworkAddressAddressEnumerator *addr_enum = g_task_get_source_object (task);
988 GResolver *resolver = G_RESOLVER (source_object);
989 GList *addresses;
990 GError *error = NULL;
992 if (!addr_enum->addr->priv->sockaddrs)
994 addresses = g_resolver_lookup_by_name_finish (resolver, result, &error);
996 if (!error)
998 g_network_address_set_addresses (addr_enum->addr, addresses,
999 g_resolver_get_serial (resolver));
1002 have_addresses (addr_enum, task, error);
1005 static void
1006 g_network_address_address_enumerator_next_async (GSocketAddressEnumerator *enumerator,
1007 GCancellable *cancellable,
1008 GAsyncReadyCallback callback,
1009 gpointer user_data)
1011 GNetworkAddressAddressEnumerator *addr_enum =
1012 G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (enumerator);
1013 GSocketAddress *sockaddr;
1014 GTask *task;
1016 task = g_task_new (addr_enum, cancellable, callback, user_data);
1017 g_task_set_source_tag (task, g_network_address_address_enumerator_next_async);
1019 if (addr_enum->addresses == NULL)
1021 GNetworkAddress *addr = addr_enum->addr;
1022 GResolver *resolver = g_resolver_get_default ();
1023 gint64 serial = g_resolver_get_serial (resolver);
1025 if (addr->priv->resolver_serial != 0 &&
1026 addr->priv->resolver_serial != serial)
1028 /* Resolver has reloaded, discard cached addresses */
1029 g_list_free_full (addr->priv->sockaddrs, g_object_unref);
1030 addr->priv->sockaddrs = NULL;
1033 if (!addr->priv->sockaddrs)
1035 if (g_network_address_parse_sockaddr (addr))
1036 have_addresses (addr_enum, task, NULL);
1037 else
1039 g_resolver_lookup_by_name_async (resolver,
1040 addr->priv->hostname,
1041 cancellable,
1042 got_addresses, task);
1044 g_object_unref (resolver);
1045 return;
1048 addr_enum->addresses = addr->priv->sockaddrs;
1049 addr_enum->next = addr_enum->addresses;
1050 g_object_unref (resolver);
1053 if (addr_enum->next)
1055 sockaddr = g_object_ref (addr_enum->next->data);
1056 addr_enum->next = addr_enum->next->next;
1058 else
1059 sockaddr = NULL;
1061 g_task_return_pointer (task, sockaddr, g_object_unref);
1062 g_object_unref (task);
1065 static GSocketAddress *
1066 g_network_address_address_enumerator_next_finish (GSocketAddressEnumerator *enumerator,
1067 GAsyncResult *result,
1068 GError **error)
1070 g_return_val_if_fail (g_task_is_valid (result, enumerator), NULL);
1072 return g_task_propagate_pointer (G_TASK (result), error);
1075 static void
1076 _g_network_address_address_enumerator_init (GNetworkAddressAddressEnumerator *enumerator)
1080 static void
1081 _g_network_address_address_enumerator_class_init (GNetworkAddressAddressEnumeratorClass *addrenum_class)
1083 GObjectClass *object_class = G_OBJECT_CLASS (addrenum_class);
1084 GSocketAddressEnumeratorClass *enumerator_class =
1085 G_SOCKET_ADDRESS_ENUMERATOR_CLASS (addrenum_class);
1087 enumerator_class->next = g_network_address_address_enumerator_next;
1088 enumerator_class->next_async = g_network_address_address_enumerator_next_async;
1089 enumerator_class->next_finish = g_network_address_address_enumerator_next_finish;
1090 object_class->finalize = g_network_address_address_enumerator_finalize;
1093 static GSocketAddressEnumerator *
1094 g_network_address_connectable_enumerate (GSocketConnectable *connectable)
1096 GNetworkAddressAddressEnumerator *addr_enum;
1098 addr_enum = g_object_new (G_TYPE_NETWORK_ADDRESS_ADDRESS_ENUMERATOR, NULL);
1099 addr_enum->addr = g_object_ref (G_NETWORK_ADDRESS (connectable));
1101 return (GSocketAddressEnumerator *)addr_enum;
1104 static GSocketAddressEnumerator *
1105 g_network_address_connectable_proxy_enumerate (GSocketConnectable *connectable)
1107 GNetworkAddress *self = G_NETWORK_ADDRESS (connectable);
1108 GSocketAddressEnumerator *proxy_enum;
1109 gchar *uri;
1111 uri = _g_uri_from_authority (self->priv->scheme ? self->priv->scheme : "none",
1112 self->priv->hostname,
1113 self->priv->port,
1114 NULL);
1116 proxy_enum = g_object_new (G_TYPE_PROXY_ADDRESS_ENUMERATOR,
1117 "connectable", connectable,
1118 "uri", uri,
1119 NULL);
1121 g_free (uri);
1123 return proxy_enum;
1126 static gchar *
1127 g_network_address_connectable_to_string (GSocketConnectable *connectable)
1129 GNetworkAddress *addr;
1130 const gchar *scheme;
1131 guint16 port;
1132 GString *out; /* owned */
1134 addr = G_NETWORK_ADDRESS (connectable);
1135 out = g_string_new ("");
1137 scheme = g_network_address_get_scheme (addr);
1138 if (scheme != NULL)
1139 g_string_append_printf (out, "%s:", scheme);
1141 g_string_append (out, g_network_address_get_hostname (addr));
1143 port = g_network_address_get_port (addr);
1144 if (port != 0)
1145 g_string_append_printf (out, ":%u", port);
1147 return g_string_free (out, FALSE);