gnetworkaddress: preserve IPv6 scope ID in IP literals
[platform/upstream/glib.git] / gio / gnetworkaddress.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2
3 /* GIO - GLib Input, Output and Streaming Library
4  *
5  * Copyright (C) 2008 Red Hat, Inc.
6  *
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.
11  *
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.
16  *
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.
21  */
22
23 #include "config.h"
24 #include <glib.h>
25 #include "glibintl.h"
26
27 #include <stdlib.h>
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"
35 #include "gtask.h"
36 #include "gsocketaddressenumerator.h"
37 #include "gioerror.h"
38 #include "gsocketconnectable.h"
39
40 #include <string.h>
41
42
43 /**
44  * SECTION:gnetworkaddress
45  * @short_description: A GSocketConnectable for resolving hostnames
46  * @include: gio/gio.h
47  *
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.
51  *
52  * See #GSocketConnectable for and example of using the connectable
53  * interface.
54  */
55
56 /**
57  * GNetworkAddress:
58  *
59  * A #GSocketConnectable for resolving a hostname and connecting to
60  * that host.
61  */
62
63 struct _GNetworkAddressPrivate {
64   gchar *hostname;
65   guint16 port;
66   GList *sockaddrs;
67   gchar *scheme;
68 };
69
70 enum {
71   PROP_0,
72   PROP_HOSTNAME,
73   PROP_PORT,
74   PROP_SCHEME,
75 };
76
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);
85
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
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))
93
94 static void
95 g_network_address_finalize (GObject *object)
96 {
97   GNetworkAddress *addr = G_NETWORK_ADDRESS (object);
98
99   g_free (addr->priv->hostname);
100   g_free (addr->priv->scheme);
101
102   if (addr->priv->sockaddrs)
103     {
104       GList *a;
105
106       for (a = addr->priv->sockaddrs; a; a = a->next)
107         g_object_unref (a->data);
108       g_list_free (addr->priv->sockaddrs);
109     }
110
111   G_OBJECT_CLASS (g_network_address_parent_class)->finalize (object);
112 }
113
114 static void
115 g_network_address_class_init (GNetworkAddressClass *klass)
116 {
117   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
118
119   g_type_class_add_private (klass, sizeof (GNetworkAddressPrivate));
120
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;
124
125   g_object_class_install_property (gobject_class, PROP_HOSTNAME,
126                                    g_param_spec_string ("hostname",
127                                                         P_("Hostname"),
128                                                         P_("Hostname to resolve"),
129                                                         NULL,
130                                                         G_PARAM_READWRITE |
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",
135                                                       P_("Port"),
136                                                       P_("Network port"),
137                                                       0, 65535, 0,
138                                                       G_PARAM_READWRITE |
139                                                       G_PARAM_CONSTRUCT_ONLY |
140                                                       G_PARAM_STATIC_STRINGS));
141
142   g_object_class_install_property (gobject_class, PROP_SCHEME,
143                                    g_param_spec_string ("scheme",
144                                                         P_("Scheme"),
145                                                         P_("URI Scheme"),
146                                                         NULL,
147                                                         G_PARAM_READWRITE |
148                                                         G_PARAM_CONSTRUCT_ONLY |
149                                                         G_PARAM_STATIC_STRINGS));
150 }
151
152 static void
153 g_network_address_connectable_iface_init (GSocketConnectableIface *connectable_iface)
154 {
155   connectable_iface->enumerate  = g_network_address_connectable_enumerate;
156   connectable_iface->proxy_enumerate = g_network_address_connectable_proxy_enumerate;
157 }
158
159 static void
160 g_network_address_init (GNetworkAddress *addr)
161 {
162   addr->priv = G_TYPE_INSTANCE_GET_PRIVATE (addr, G_TYPE_NETWORK_ADDRESS,
163                                             GNetworkAddressPrivate);
164 }
165
166 static void
167 g_network_address_set_property (GObject      *object,
168                                 guint         prop_id,
169                                 const GValue *value,
170                                 GParamSpec   *pspec)
171 {
172   GNetworkAddress *addr = G_NETWORK_ADDRESS (object);
173
174   switch (prop_id)
175     {
176     case PROP_HOSTNAME:
177       g_free (addr->priv->hostname);
178       addr->priv->hostname = g_value_dup_string (value);
179       break;
180
181     case PROP_PORT:
182       addr->priv->port = g_value_get_uint (value);
183       break;
184
185     case PROP_SCHEME:
186       if (addr->priv->scheme)
187         g_free (addr->priv->scheme);
188       addr->priv->scheme = g_value_dup_string (value);
189       break;
190
191     default:
192       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
193       break;
194     }
195
196 }
197
198 static void
199 g_network_address_get_property (GObject    *object,
200                                 guint       prop_id,
201                                 GValue     *value,
202                                 GParamSpec *pspec)
203 {
204   GNetworkAddress *addr = G_NETWORK_ADDRESS (object);
205
206   switch (prop_id)
207     {
208     case PROP_HOSTNAME:
209       g_value_set_string (value, addr->priv->hostname);
210       break;
211
212     case PROP_PORT:
213       g_value_set_uint (value, addr->priv->port);
214       break;
215
216     case PROP_SCHEME:
217       g_value_set_string (value, addr->priv->scheme);
218       break;
219
220     default:
221       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
222       break;
223     }
224
225 }
226
227 static void
228 g_network_address_set_addresses (GNetworkAddress *addr,
229                                  GList           *addresses)
230 {
231   GList *a;
232   GSocketAddress *sockaddr;
233
234   g_return_if_fail (addresses != NULL && addr->priv->sockaddrs == NULL);
235
236   for (a = addresses; a; a = a->next)
237     {
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);
241     }
242   g_list_free (addresses);
243   addr->priv->sockaddrs = g_list_reverse (addr->priv->sockaddrs);
244 }
245
246 static gboolean
247 g_network_address_parse_sockaddr (GNetworkAddress *addr)
248 {
249   struct addrinfo hints, *res = NULL;
250   GSocketAddress *sockaddr;
251   gchar port[32];
252
253   memset (&hints, 0, sizeof (hints));
254   hints.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV;
255   g_snprintf (port, sizeof (port), "%u", addr->priv->port);
256
257   if (getaddrinfo (addr->priv->hostname, port, &hints, &res) != 0)
258     return FALSE;
259
260   sockaddr = g_socket_address_new_from_native (res->ai_addr, res->ai_addrlen);
261   freeaddrinfo (res);
262   if (!sockaddr || !G_IS_INET_SOCKET_ADDRESS (sockaddr))
263     return FALSE;
264
265   addr->priv->sockaddrs = g_list_prepend (addr->priv->sockaddrs, sockaddr);
266   return TRUE;
267 }
268
269 /**
270  * g_network_address_new:
271  * @hostname: the hostname
272  * @port: the port
273  *
274  * Creates a new #GSocketConnectable for connecting to the given
275  * @hostname and @port.
276  *
277  * Return value: (transfer full) (type GNetworkAddress): the new #GNetworkAddress
278  *
279  * Since: 2.22
280  */
281 GSocketConnectable *
282 g_network_address_new (const gchar *hostname,
283                        guint16      port)
284 {
285   return g_object_new (G_TYPE_NETWORK_ADDRESS,
286                        "hostname", hostname,
287                        "port", port,
288                        NULL);
289 }
290
291 /**
292  * g_network_address_parse:
293  * @host_and_port: the hostname and optionally a port
294  * @default_port: the default port if not in @host_and_port
295  * @error: a pointer to a #GError, or %NULL
296  *
297  * Creates a new #GSocketConnectable for connecting to the given
298  * @hostname and @port. May fail and return %NULL in case
299  * parsing @host_and_port fails.
300  *
301  * @host_and_port may be in any of a number of recognised formats; an IPv6
302  * address, an IPv4 address, or a domain name (in which case a DNS
303  * lookup is performed). Quoting with [] is supported for all address
304  * types. A port override may be specified in the usual way with a
305  * colon.
306  *
307  * If no port is specified in @host_and_port then @default_port will be
308  * used as the port number to connect to.
309  *
310  * In general, @host_and_port is expected to be provided by the user
311  * (allowing them to give the hostname, and a port overide if necessary)
312  * and @default_port is expected to be provided by the application.
313  *
314  * (The port component of @host_and_port can also be specified as a
315  * service name rather than as a numeric port, but this functionality
316  * is deprecated, because it depends on the contents of /etc/services,
317  * which is generally quite sparse on platforms other than Linux.)
318  *
319  * Return value: (transfer full): the new #GNetworkAddress, or %NULL on error
320  *
321  * Since: 2.22
322  */
323 GSocketConnectable *
324 g_network_address_parse (const gchar  *host_and_port,
325                          guint16       default_port,
326                          GError      **error)
327 {
328   GSocketConnectable *connectable;
329   const gchar *port;
330   guint16 portnum;
331   gchar *name;
332
333   g_return_val_if_fail (host_and_port != NULL, NULL);
334
335   port = NULL;
336   if (host_and_port[0] == '[')
337     /* escaped host part (to allow, eg. "[2001:db8::1]:888") */
338     {
339       const gchar *end;
340
341       end = strchr (host_and_port, ']');
342       if (end == NULL)
343         {
344           g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
345                        _("Hostname '%s' contains '[' but not ']'"), host_and_port);
346           return NULL;
347         }
348
349       if (end[1] == '\0')
350         port = NULL;
351       else if (end[1] == ':')
352         port = &end[2];
353       else
354         {
355           g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
356                        "The ']' character (in hostname '%s') must come at the"
357                        " end or be immediately followed by ':' and a port",
358                        host_and_port);
359           return NULL;
360         }
361
362       name = g_strndup (host_and_port + 1, end - host_and_port - 1);
363     }
364
365   else if ((port = strchr (host_and_port, ':')))
366     /* string has a ':' in it */
367     {
368       /* skip ':' */
369       port++;
370
371       if (strchr (port, ':'))
372         /* more than one ':' in string */
373         {
374           /* this is actually an unescaped IPv6 address */
375           name = g_strdup (host_and_port);
376           port = NULL;
377         }
378       else
379         name = g_strndup (host_and_port, port - host_and_port - 1);
380     }
381
382   else
383     /* plain hostname, no port */
384     name = g_strdup (host_and_port);
385
386   if (port != NULL)
387     {
388       if (port[0] == '\0')
389         {
390           g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
391                        "If a ':' character is given, it must be followed by a "
392                        "port (in hostname '%s').", host_and_port);
393           g_free (name);
394           return NULL;
395         }
396
397       else if ('0' <= port[0] && port[0] <= '9')
398         {
399           char *end;
400           long value;
401
402           value = strtol (port, &end, 10);
403           if (*end != '\0' || value < 0 || value > G_MAXUINT16)
404             {
405               g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
406                            "Invalid numeric port '%s' specified in hostname '%s'",
407                            port, host_and_port);
408               g_free (name);
409               return NULL;
410             }
411
412           portnum = value;
413         }
414
415       else
416         {
417           struct servent *entry;
418
419           entry = getservbyname (port, "tcp");
420           if (entry == NULL)
421             {
422               g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
423                            "Unknown service '%s' specified in hostname '%s'",
424                            port, host_and_port);
425 #ifdef HAVE_ENDSERVENT
426               endservent ();
427 #endif
428               g_free (name);
429               return NULL;
430             }
431
432           portnum = g_ntohs (entry->s_port);
433
434 #ifdef HAVE_ENDSERVENT
435           endservent ();
436 #endif
437         }
438     }
439   else
440     {
441       /* No port in host_and_port */
442       portnum = default_port;
443     }
444
445   connectable = g_network_address_new (name, portnum);
446   g_free (name);
447
448   return connectable;
449 }
450
451 /* Allowed characters outside alphanumeric for unreserved. */
452 #define G_URI_OTHER_UNRESERVED "-._~"
453
454 /* This or something equivalent will eventually go into glib/guri.h */
455 gboolean
456 _g_uri_parse_authority (const char  *uri,
457                         char       **host,
458                         guint16     *port,
459                         char       **userinfo)
460 {
461   char *tmp_str;
462   const char *start, *p;
463   char c;
464
465   g_return_val_if_fail (uri != NULL, FALSE);
466
467   if (host)
468     *host = NULL;
469
470   if (port)
471     *port = 0;
472
473   if (userinfo)
474     *userinfo = NULL;
475
476   /* From RFC 3986 Decodes:
477    * URI          = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
478    * hier-part    = "//" authority path-abempty
479    * path-abempty = *( "/" segment )
480    * authority    = [ userinfo "@" ] host [ ":" port ]
481    */
482
483   /* Check we have a valid scheme */
484   tmp_str = g_uri_parse_scheme (uri);
485
486   if (tmp_str == NULL)
487     return FALSE;
488
489   g_free (tmp_str);
490
491   /* Decode hier-part:
492    *  hier-part   = "//" authority path-abempty
493    */
494   p = uri;
495   start = strstr (p, "//");
496
497   if (start == NULL)
498     return FALSE;
499
500   start += 2;
501
502   if (strchr (start, '@') != NULL)
503     {
504       /* Decode userinfo:
505        * userinfo      = *( unreserved / pct-encoded / sub-delims / ":" )
506        * unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
507        * pct-encoded   = "%" HEXDIG HEXDIG
508        */
509       p = start;
510       while (1)
511         {
512           c = *p++;
513
514           if (c == '@')
515             break;
516
517           /* pct-encoded */
518           if (c == '%')
519             {
520               if (!(g_ascii_isxdigit (p[0]) ||
521                     g_ascii_isxdigit (p[1])))
522                 return FALSE;
523
524               p++;
525
526               continue;
527             }
528
529           /* unreserved /  sub-delims / : */
530           if (!(g_ascii_isalnum (c) ||
531                 strchr (G_URI_OTHER_UNRESERVED, c) ||
532                 strchr (G_URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS, c) ||
533                 c == ':'))
534             return FALSE;
535         }
536
537       if (userinfo)
538         *userinfo = g_strndup (start, p - start - 1);
539
540       start = p;
541     }
542   else
543     {
544       p = start;
545     }
546
547
548   /* decode host:
549    * host          = IP-literal / IPv4address / reg-name
550    * reg-name      = *( unreserved / pct-encoded / sub-delims )
551    */
552
553   /* If IPv6 or IPvFuture */
554   if (*p == '[')
555     {
556       start++;
557       p++;
558       while (1)
559         {
560           c = *p++;
561
562           if (c == ']')
563             break;
564
565           /* unreserved /  sub-delims */
566           if (!(g_ascii_isalnum (c) ||
567                 strchr (G_URI_OTHER_UNRESERVED, c) ||
568                 strchr (G_URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS, c) ||
569                 c == ':' ||
570                 c == '.'))
571             goto error;
572         }
573     }
574   else
575     {
576       while (1)
577         {
578           c = *p++;
579
580           if (c == ':' ||
581               c == '/' ||
582               c == '?' ||
583               c == '#' ||
584               c == '\0')
585             break;
586
587           /* pct-encoded */
588           if (c == '%')
589             {
590               if (!(g_ascii_isxdigit (p[0]) ||
591                     g_ascii_isxdigit (p[1])))
592                 goto error;
593
594               p++;
595
596               continue;
597             }
598
599           /* unreserved /  sub-delims */
600           if (!(g_ascii_isalnum (c) ||
601                 strchr (G_URI_OTHER_UNRESERVED, c) ||
602                 strchr (G_URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS, c)))
603             goto error;
604         }
605     }
606
607   if (host)
608     *host = g_uri_unescape_segment (start, p - 1, NULL);
609
610   if (c == ':')
611     {
612       /* Decode pot:
613        *  port          = *DIGIT
614        */
615       guint tmp = 0;
616
617       while (1)
618         {
619           c = *p++;
620
621           if (c == '/' ||
622               c == '?' ||
623               c == '#' ||
624               c == '\0')
625             break;
626
627           if (!g_ascii_isdigit (c))
628             goto error;
629
630           tmp = (tmp * 10) + (c - '0');
631
632           if (tmp > 65535)
633             goto error;
634         }
635       if (port)
636         *port = (guint16) tmp;
637     }
638
639   return TRUE;
640
641 error:
642   if (host && *host)
643     {
644       g_free (*host);
645       *host = NULL;
646     }
647
648   if (userinfo && *userinfo)
649     {
650       g_free (*userinfo);
651       *userinfo = NULL;
652     }
653
654   return FALSE;
655 }
656
657 gchar *
658 _g_uri_from_authority (const gchar *protocol,
659                        const gchar *host,
660                        guint        port,
661                        const gchar *userinfo)
662 {
663   GString *uri;
664
665   uri = g_string_new (protocol);
666   g_string_append (uri, "://");
667
668   if (userinfo)
669     {
670       g_string_append_uri_escaped (uri, userinfo, G_URI_RESERVED_CHARS_ALLOWED_IN_USERINFO, FALSE);
671       g_string_append_c (uri, '@');
672     }
673
674   if (g_hostname_is_non_ascii (host))
675     {
676       gchar *ace_encoded = g_hostname_to_ascii (host);
677
678       if (!ace_encoded)
679         {
680           g_string_free (uri, TRUE);
681           return NULL;
682         }
683       g_string_append (uri, ace_encoded);
684       g_free (ace_encoded);
685     }
686   else if (strchr (host, ':'))
687     g_string_append_printf (uri, "[%s]", host);
688   else
689     g_string_append (uri, host);
690
691   if (port != 0)
692     g_string_append_printf (uri, ":%u", port);
693
694   return g_string_free (uri, FALSE);
695 }
696
697 /**
698  * g_network_address_parse_uri:
699  * @uri: the hostname and optionally a port
700  * @default_port: The default port if none is found in the URI
701  * @error: a pointer to a #GError, or %NULL
702  *
703  * Creates a new #GSocketConnectable for connecting to the given
704  * @uri. May fail and return %NULL in case parsing @uri fails.
705  *
706  * Using this rather than g_network_address_new() or
707  * g_network_address_parse() allows #GSocketClient to determine
708  * when to use application-specific proxy protocols.
709  *
710  * Return value: (transfer full): the new #GNetworkAddress, or %NULL on error
711  *
712  * Since: 2.26
713  */
714 GSocketConnectable *
715 g_network_address_parse_uri (const gchar  *uri,
716                              guint16       default_port,
717                              GError      **error)
718 {
719   GSocketConnectable *conn;
720   gchar *scheme;
721   gchar *hostname;
722   guint16 port;
723
724   if (!_g_uri_parse_authority (uri, &hostname, &port, NULL))
725     {
726       g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
727                    "Invalid URI '%s'",
728                    uri);
729       return NULL;
730     }
731
732   if (port == 0)
733     port = default_port;
734
735   scheme = g_uri_parse_scheme (uri);
736
737   conn = g_object_new (G_TYPE_NETWORK_ADDRESS,
738                        "hostname", hostname,
739                        "port", port,
740                        "scheme", scheme,
741                        NULL);
742
743   g_free (scheme);
744   g_free (hostname);
745
746   return conn;
747 }
748
749 /**
750  * g_network_address_get_hostname:
751  * @addr: a #GNetworkAddress
752  *
753  * Gets @addr's hostname. This might be either UTF-8 or ASCII-encoded,
754  * depending on what @addr was created with.
755  *
756  * Return value: @addr's hostname
757  *
758  * Since: 2.22
759  */
760 const gchar *
761 g_network_address_get_hostname (GNetworkAddress *addr)
762 {
763   g_return_val_if_fail (G_IS_NETWORK_ADDRESS (addr), NULL);
764
765   return addr->priv->hostname;
766 }
767
768 /**
769  * g_network_address_get_port:
770  * @addr: a #GNetworkAddress
771  *
772  * Gets @addr's port number
773  *
774  * Return value: @addr's port (which may be 0)
775  *
776  * Since: 2.22
777  */
778 guint16
779 g_network_address_get_port (GNetworkAddress *addr)
780 {
781   g_return_val_if_fail (G_IS_NETWORK_ADDRESS (addr), 0);
782
783   return addr->priv->port;
784 }
785
786 /**
787  * g_network_address_get_scheme:
788  * @addr: a #GNetworkAddress
789  *
790  * Gets @addr's scheme
791  *
792  * Return value: @addr's scheme (%NULL if not built from URI)
793  *
794  * Since: 2.26
795  */
796 const gchar *
797 g_network_address_get_scheme (GNetworkAddress *addr)
798 {
799   g_return_val_if_fail (G_IS_NETWORK_ADDRESS (addr), NULL);
800
801   return addr->priv->scheme;
802 }
803
804 #define G_TYPE_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (_g_network_address_address_enumerator_get_type ())
805 #define G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), G_TYPE_NETWORK_ADDRESS_ADDRESS_ENUMERATOR, GNetworkAddressAddressEnumerator))
806
807 typedef struct {
808   GSocketAddressEnumerator parent_instance;
809
810   GNetworkAddress *addr;
811   GList *addresses;
812   GList *next;
813 } GNetworkAddressAddressEnumerator;
814
815 typedef struct {
816   GSocketAddressEnumeratorClass parent_class;
817
818 } GNetworkAddressAddressEnumeratorClass;
819
820 static GType _g_network_address_address_enumerator_get_type (void);
821 G_DEFINE_TYPE (GNetworkAddressAddressEnumerator, _g_network_address_address_enumerator, G_TYPE_SOCKET_ADDRESS_ENUMERATOR)
822
823 static void
824 g_network_address_address_enumerator_finalize (GObject *object)
825 {
826   GNetworkAddressAddressEnumerator *addr_enum =
827     G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (object);
828
829   g_object_unref (addr_enum->addr);
830
831   G_OBJECT_CLASS (_g_network_address_address_enumerator_parent_class)->finalize (object);
832 }
833
834 static GSocketAddress *
835 g_network_address_address_enumerator_next (GSocketAddressEnumerator  *enumerator,
836                                            GCancellable              *cancellable,
837                                            GError                   **error)
838 {
839   GNetworkAddressAddressEnumerator *addr_enum =
840     G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (enumerator);
841   GSocketAddress *sockaddr;
842
843   if (addr_enum->addresses == NULL)
844     {
845       if (!addr_enum->addr->priv->sockaddrs)
846         g_network_address_parse_sockaddr (addr_enum->addr);
847       if (!addr_enum->addr->priv->sockaddrs)
848         {
849           GResolver *resolver = g_resolver_get_default ();
850           GList *addresses;
851
852           addresses = g_resolver_lookup_by_name (resolver,
853                                                  addr_enum->addr->priv->hostname,
854                                                  cancellable, error);
855           g_object_unref (resolver);
856
857           if (!addresses)
858             return NULL;
859
860           g_network_address_set_addresses (addr_enum->addr, addresses);
861         }
862           
863       addr_enum->addresses = addr_enum->addr->priv->sockaddrs;
864       addr_enum->next = addr_enum->addresses;
865     }
866
867   if (addr_enum->next == NULL)
868     return NULL;
869
870   sockaddr = addr_enum->next->data;
871   addr_enum->next = addr_enum->next->next;
872   return g_object_ref (sockaddr);
873 }
874
875 static void
876 have_addresses (GNetworkAddressAddressEnumerator *addr_enum,
877                 GTask *task, GError *error)
878 {
879   GSocketAddress *sockaddr;
880
881   addr_enum->addresses = addr_enum->addr->priv->sockaddrs;
882   addr_enum->next = addr_enum->addresses;
883
884   if (addr_enum->next)
885     {
886       sockaddr = g_object_ref (addr_enum->next->data);
887       addr_enum->next = addr_enum->next->next;
888     }
889   else
890     sockaddr = NULL;
891
892   if (error)
893     g_task_return_error (task, error);
894   else
895     g_task_return_pointer (task, sockaddr, g_object_unref);
896   g_object_unref (task);
897 }
898
899 static void
900 got_addresses (GObject      *source_object,
901                GAsyncResult *result,
902                gpointer      user_data)
903 {
904   GTask *task = user_data;
905   GNetworkAddressAddressEnumerator *addr_enum = g_task_get_source_object (task);
906   GResolver *resolver = G_RESOLVER (source_object);
907   GList *addresses;
908   GError *error = NULL;
909
910   if (!addr_enum->addr->priv->sockaddrs)
911     {
912       addresses = g_resolver_lookup_by_name_finish (resolver, result, &error);
913
914       if (!error)
915         g_network_address_set_addresses (addr_enum->addr, addresses);
916     }
917   have_addresses (addr_enum, task, error);
918 }
919
920 static void
921 g_network_address_address_enumerator_next_async (GSocketAddressEnumerator  *enumerator,
922                                                  GCancellable              *cancellable,
923                                                  GAsyncReadyCallback        callback,
924                                                  gpointer                   user_data)
925 {
926   GNetworkAddressAddressEnumerator *addr_enum =
927     G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (enumerator);
928   GSocketAddress *sockaddr;
929   GTask *task;
930
931   task = g_task_new (addr_enum, cancellable, callback, user_data);
932
933   if (addr_enum->addresses == NULL)
934     {
935       if (!addr_enum->addr->priv->sockaddrs)
936         {
937           if (g_network_address_parse_sockaddr (addr_enum->addr))
938             have_addresses (addr_enum, task, NULL);
939           else
940             {
941               GResolver *resolver = g_resolver_get_default ();
942
943               g_resolver_lookup_by_name_async (resolver,
944                                                addr_enum->addr->priv->hostname,
945                                                cancellable,
946                                                got_addresses, task);
947               g_object_unref (resolver);
948             }
949           return;
950         }
951
952       addr_enum->addresses = addr_enum->addr->priv->sockaddrs;
953       addr_enum->next = addr_enum->addresses;
954     }
955
956   if (addr_enum->next)
957     {
958       sockaddr = g_object_ref (addr_enum->next->data);
959       addr_enum->next = addr_enum->next->next;
960     }
961   else
962     sockaddr = NULL;
963
964   g_task_return_pointer (task, sockaddr, g_object_unref);
965   g_object_unref (task);
966 }
967
968 static GSocketAddress *
969 g_network_address_address_enumerator_next_finish (GSocketAddressEnumerator  *enumerator,
970                                                   GAsyncResult              *result,
971                                                   GError                   **error)
972 {
973   g_return_val_if_fail (g_task_is_valid (result, enumerator), NULL);
974
975   return g_task_propagate_pointer (G_TASK (result), error);
976 }
977
978 static void
979 _g_network_address_address_enumerator_init (GNetworkAddressAddressEnumerator *enumerator)
980 {
981 }
982
983 static void
984 _g_network_address_address_enumerator_class_init (GNetworkAddressAddressEnumeratorClass *addrenum_class)
985 {
986   GObjectClass *object_class = G_OBJECT_CLASS (addrenum_class);
987   GSocketAddressEnumeratorClass *enumerator_class =
988     G_SOCKET_ADDRESS_ENUMERATOR_CLASS (addrenum_class);
989
990   enumerator_class->next = g_network_address_address_enumerator_next;
991   enumerator_class->next_async = g_network_address_address_enumerator_next_async;
992   enumerator_class->next_finish = g_network_address_address_enumerator_next_finish;
993   object_class->finalize = g_network_address_address_enumerator_finalize;
994 }
995
996 static GSocketAddressEnumerator *
997 g_network_address_connectable_enumerate (GSocketConnectable *connectable)
998 {
999   GNetworkAddressAddressEnumerator *addr_enum;
1000
1001   addr_enum = g_object_new (G_TYPE_NETWORK_ADDRESS_ADDRESS_ENUMERATOR, NULL);
1002   addr_enum->addr = g_object_ref (connectable);
1003
1004   return (GSocketAddressEnumerator *)addr_enum;
1005 }
1006
1007 static GSocketAddressEnumerator *
1008 g_network_address_connectable_proxy_enumerate (GSocketConnectable *connectable)
1009 {
1010   GNetworkAddress *self = G_NETWORK_ADDRESS (connectable);
1011   GSocketAddressEnumerator *proxy_enum;
1012   gchar *uri;
1013
1014   uri = _g_uri_from_authority (self->priv->scheme ? self->priv->scheme : "none",
1015                                self->priv->hostname,
1016                                self->priv->port,
1017                                NULL);
1018
1019   proxy_enum = g_object_new (G_TYPE_PROXY_ADDRESS_ENUMERATOR,
1020                              "connectable", connectable,
1021                              "uri", uri,
1022                              NULL);
1023
1024   g_free (uri);
1025
1026   return proxy_enum;
1027 }