1335d94632653bf1524f2af08958e62fa001b402
[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
255 #ifdef AI_NUMERICSERV
256     | AI_NUMERICSERV
257 #endif
258     ;
259   g_snprintf (port, sizeof (port), "%u", addr->priv->port);
260
261   if (getaddrinfo (addr->priv->hostname, port, &hints, &res) != 0)
262     return FALSE;
263
264   sockaddr = g_socket_address_new_from_native (res->ai_addr, res->ai_addrlen);
265   freeaddrinfo (res);
266   if (!sockaddr || !G_IS_INET_SOCKET_ADDRESS (sockaddr))
267     return FALSE;
268
269   addr->priv->sockaddrs = g_list_prepend (addr->priv->sockaddrs, sockaddr);
270   return TRUE;
271 }
272
273 /**
274  * g_network_address_new:
275  * @hostname: the hostname
276  * @port: the port
277  *
278  * Creates a new #GSocketConnectable for connecting to the given
279  * @hostname and @port.
280  *
281  * Return value: (transfer full) (type GNetworkAddress): the new #GNetworkAddress
282  *
283  * Since: 2.22
284  */
285 GSocketConnectable *
286 g_network_address_new (const gchar *hostname,
287                        guint16      port)
288 {
289   return g_object_new (G_TYPE_NETWORK_ADDRESS,
290                        "hostname", hostname,
291                        "port", port,
292                        NULL);
293 }
294
295 /**
296  * g_network_address_parse:
297  * @host_and_port: the hostname and optionally a port
298  * @default_port: the default port if not in @host_and_port
299  * @error: a pointer to a #GError, or %NULL
300  *
301  * Creates a new #GSocketConnectable for connecting to the given
302  * @hostname and @port. May fail and return %NULL in case
303  * parsing @host_and_port fails.
304  *
305  * @host_and_port may be in any of a number of recognised formats; an IPv6
306  * address, an IPv4 address, or a domain name (in which case a DNS
307  * lookup is performed). Quoting with [] is supported for all address
308  * types. A port override may be specified in the usual way with a
309  * colon.
310  *
311  * If no port is specified in @host_and_port then @default_port will be
312  * used as the port number to connect to.
313  *
314  * In general, @host_and_port is expected to be provided by the user
315  * (allowing them to give the hostname, and a port overide if necessary)
316  * and @default_port is expected to be provided by the application.
317  *
318  * (The port component of @host_and_port can also be specified as a
319  * service name rather than as a numeric port, but this functionality
320  * is deprecated, because it depends on the contents of /etc/services,
321  * which is generally quite sparse on platforms other than Linux.)
322  *
323  * Return value: (transfer full): the new #GNetworkAddress, or %NULL on error
324  *
325  * Since: 2.22
326  */
327 GSocketConnectable *
328 g_network_address_parse (const gchar  *host_and_port,
329                          guint16       default_port,
330                          GError      **error)
331 {
332   GSocketConnectable *connectable;
333   const gchar *port;
334   guint16 portnum;
335   gchar *name;
336
337   g_return_val_if_fail (host_and_port != NULL, NULL);
338
339   port = NULL;
340   if (host_and_port[0] == '[')
341     /* escaped host part (to allow, eg. "[2001:db8::1]:888") */
342     {
343       const gchar *end;
344
345       end = strchr (host_and_port, ']');
346       if (end == NULL)
347         {
348           g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
349                        _("Hostname '%s' contains '[' but not ']'"), host_and_port);
350           return NULL;
351         }
352
353       if (end[1] == '\0')
354         port = NULL;
355       else if (end[1] == ':')
356         port = &end[2];
357       else
358         {
359           g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
360                        "The ']' character (in hostname '%s') must come at the"
361                        " end or be immediately followed by ':' and a port",
362                        host_and_port);
363           return NULL;
364         }
365
366       name = g_strndup (host_and_port + 1, end - host_and_port - 1);
367     }
368
369   else if ((port = strchr (host_and_port, ':')))
370     /* string has a ':' in it */
371     {
372       /* skip ':' */
373       port++;
374
375       if (strchr (port, ':'))
376         /* more than one ':' in string */
377         {
378           /* this is actually an unescaped IPv6 address */
379           name = g_strdup (host_and_port);
380           port = NULL;
381         }
382       else
383         name = g_strndup (host_and_port, port - host_and_port - 1);
384     }
385
386   else
387     /* plain hostname, no port */
388     name = g_strdup (host_and_port);
389
390   if (port != NULL)
391     {
392       if (port[0] == '\0')
393         {
394           g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
395                        "If a ':' character is given, it must be followed by a "
396                        "port (in hostname '%s').", host_and_port);
397           g_free (name);
398           return NULL;
399         }
400
401       else if ('0' <= port[0] && port[0] <= '9')
402         {
403           char *end;
404           long value;
405
406           value = strtol (port, &end, 10);
407           if (*end != '\0' || value < 0 || value > G_MAXUINT16)
408             {
409               g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
410                            "Invalid numeric port '%s' specified in hostname '%s'",
411                            port, host_and_port);
412               g_free (name);
413               return NULL;
414             }
415
416           portnum = value;
417         }
418
419       else
420         {
421           struct servent *entry;
422
423           entry = getservbyname (port, "tcp");
424           if (entry == NULL)
425             {
426               g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
427                            "Unknown service '%s' specified in hostname '%s'",
428                            port, host_and_port);
429 #ifdef HAVE_ENDSERVENT
430               endservent ();
431 #endif
432               g_free (name);
433               return NULL;
434             }
435
436           portnum = g_ntohs (entry->s_port);
437
438 #ifdef HAVE_ENDSERVENT
439           endservent ();
440 #endif
441         }
442     }
443   else
444     {
445       /* No port in host_and_port */
446       portnum = default_port;
447     }
448
449   connectable = g_network_address_new (name, portnum);
450   g_free (name);
451
452   return connectable;
453 }
454
455 /* Allowed characters outside alphanumeric for unreserved. */
456 #define G_URI_OTHER_UNRESERVED "-._~"
457
458 /* This or something equivalent will eventually go into glib/guri.h */
459 gboolean
460 _g_uri_parse_authority (const char  *uri,
461                         char       **host,
462                         guint16     *port,
463                         char       **userinfo)
464 {
465   char *tmp_str;
466   const char *start, *p;
467   char c;
468
469   g_return_val_if_fail (uri != NULL, FALSE);
470
471   if (host)
472     *host = NULL;
473
474   if (port)
475     *port = 0;
476
477   if (userinfo)
478     *userinfo = NULL;
479
480   /* From RFC 3986 Decodes:
481    * URI          = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
482    * hier-part    = "//" authority path-abempty
483    * path-abempty = *( "/" segment )
484    * authority    = [ userinfo "@" ] host [ ":" port ]
485    */
486
487   /* Check we have a valid scheme */
488   tmp_str = g_uri_parse_scheme (uri);
489
490   if (tmp_str == NULL)
491     return FALSE;
492
493   g_free (tmp_str);
494
495   /* Decode hier-part:
496    *  hier-part   = "//" authority path-abempty
497    */
498   p = uri;
499   start = strstr (p, "//");
500
501   if (start == NULL)
502     return FALSE;
503
504   start += 2;
505
506   if (strchr (start, '@') != NULL)
507     {
508       /* Decode userinfo:
509        * userinfo      = *( unreserved / pct-encoded / sub-delims / ":" )
510        * unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
511        * pct-encoded   = "%" HEXDIG HEXDIG
512        */
513       p = start;
514       while (1)
515         {
516           c = *p++;
517
518           if (c == '@')
519             break;
520
521           /* pct-encoded */
522           if (c == '%')
523             {
524               if (!(g_ascii_isxdigit (p[0]) ||
525                     g_ascii_isxdigit (p[1])))
526                 return FALSE;
527
528               p++;
529
530               continue;
531             }
532
533           /* unreserved /  sub-delims / : */
534           if (!(g_ascii_isalnum (c) ||
535                 strchr (G_URI_OTHER_UNRESERVED, c) ||
536                 strchr (G_URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS, c) ||
537                 c == ':'))
538             return FALSE;
539         }
540
541       if (userinfo)
542         *userinfo = g_strndup (start, p - start - 1);
543
544       start = p;
545     }
546   else
547     {
548       p = start;
549     }
550
551
552   /* decode host:
553    * host          = IP-literal / IPv4address / reg-name
554    * reg-name      = *( unreserved / pct-encoded / sub-delims )
555    */
556
557   /* If IPv6 or IPvFuture */
558   if (*p == '[')
559     {
560       start++;
561       p++;
562       while (1)
563         {
564           c = *p++;
565
566           if (c == ']')
567             break;
568
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) ||
573                 c == ':' ||
574                 c == '.'))
575             goto error;
576         }
577     }
578   else
579     {
580       while (1)
581         {
582           c = *p++;
583
584           if (c == ':' ||
585               c == '/' ||
586               c == '?' ||
587               c == '#' ||
588               c == '\0')
589             break;
590
591           /* pct-encoded */
592           if (c == '%')
593             {
594               if (!(g_ascii_isxdigit (p[0]) ||
595                     g_ascii_isxdigit (p[1])))
596                 goto error;
597
598               p++;
599
600               continue;
601             }
602
603           /* unreserved /  sub-delims */
604           if (!(g_ascii_isalnum (c) ||
605                 strchr (G_URI_OTHER_UNRESERVED, c) ||
606                 strchr (G_URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS, c)))
607             goto error;
608         }
609     }
610
611   if (host)
612     *host = g_uri_unescape_segment (start, p - 1, NULL);
613
614   if (c == ':')
615     {
616       /* Decode pot:
617        *  port          = *DIGIT
618        */
619       guint tmp = 0;
620
621       while (1)
622         {
623           c = *p++;
624
625           if (c == '/' ||
626               c == '?' ||
627               c == '#' ||
628               c == '\0')
629             break;
630
631           if (!g_ascii_isdigit (c))
632             goto error;
633
634           tmp = (tmp * 10) + (c - '0');
635
636           if (tmp > 65535)
637             goto error;
638         }
639       if (port)
640         *port = (guint16) tmp;
641     }
642
643   return TRUE;
644
645 error:
646   if (host && *host)
647     {
648       g_free (*host);
649       *host = NULL;
650     }
651
652   if (userinfo && *userinfo)
653     {
654       g_free (*userinfo);
655       *userinfo = NULL;
656     }
657
658   return FALSE;
659 }
660
661 gchar *
662 _g_uri_from_authority (const gchar *protocol,
663                        const gchar *host,
664                        guint        port,
665                        const gchar *userinfo)
666 {
667   GString *uri;
668
669   uri = g_string_new (protocol);
670   g_string_append (uri, "://");
671
672   if (userinfo)
673     {
674       g_string_append_uri_escaped (uri, userinfo, G_URI_RESERVED_CHARS_ALLOWED_IN_USERINFO, FALSE);
675       g_string_append_c (uri, '@');
676     }
677
678   if (g_hostname_is_non_ascii (host))
679     {
680       gchar *ace_encoded = g_hostname_to_ascii (host);
681
682       if (!ace_encoded)
683         {
684           g_string_free (uri, TRUE);
685           return NULL;
686         }
687       g_string_append (uri, ace_encoded);
688       g_free (ace_encoded);
689     }
690   else if (strchr (host, ':'))
691     g_string_append_printf (uri, "[%s]", host);
692   else
693     g_string_append (uri, host);
694
695   if (port != 0)
696     g_string_append_printf (uri, ":%u", port);
697
698   return g_string_free (uri, FALSE);
699 }
700
701 /**
702  * g_network_address_parse_uri:
703  * @uri: the hostname and optionally a port
704  * @default_port: The default port if none is found in the URI
705  * @error: a pointer to a #GError, or %NULL
706  *
707  * Creates a new #GSocketConnectable for connecting to the given
708  * @uri. May fail and return %NULL in case parsing @uri fails.
709  *
710  * Using this rather than g_network_address_new() or
711  * g_network_address_parse() allows #GSocketClient to determine
712  * when to use application-specific proxy protocols.
713  *
714  * Return value: (transfer full): the new #GNetworkAddress, or %NULL on error
715  *
716  * Since: 2.26
717  */
718 GSocketConnectable *
719 g_network_address_parse_uri (const gchar  *uri,
720                              guint16       default_port,
721                              GError      **error)
722 {
723   GSocketConnectable *conn;
724   gchar *scheme;
725   gchar *hostname;
726   guint16 port;
727
728   if (!_g_uri_parse_authority (uri, &hostname, &port, NULL))
729     {
730       g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
731                    "Invalid URI '%s'",
732                    uri);
733       return NULL;
734     }
735
736   if (port == 0)
737     port = default_port;
738
739   scheme = g_uri_parse_scheme (uri);
740
741   conn = g_object_new (G_TYPE_NETWORK_ADDRESS,
742                        "hostname", hostname,
743                        "port", port,
744                        "scheme", scheme,
745                        NULL);
746
747   g_free (scheme);
748   g_free (hostname);
749
750   return conn;
751 }
752
753 /**
754  * g_network_address_get_hostname:
755  * @addr: a #GNetworkAddress
756  *
757  * Gets @addr's hostname. This might be either UTF-8 or ASCII-encoded,
758  * depending on what @addr was created with.
759  *
760  * Return value: @addr's hostname
761  *
762  * Since: 2.22
763  */
764 const gchar *
765 g_network_address_get_hostname (GNetworkAddress *addr)
766 {
767   g_return_val_if_fail (G_IS_NETWORK_ADDRESS (addr), NULL);
768
769   return addr->priv->hostname;
770 }
771
772 /**
773  * g_network_address_get_port:
774  * @addr: a #GNetworkAddress
775  *
776  * Gets @addr's port number
777  *
778  * Return value: @addr's port (which may be 0)
779  *
780  * Since: 2.22
781  */
782 guint16
783 g_network_address_get_port (GNetworkAddress *addr)
784 {
785   g_return_val_if_fail (G_IS_NETWORK_ADDRESS (addr), 0);
786
787   return addr->priv->port;
788 }
789
790 /**
791  * g_network_address_get_scheme:
792  * @addr: a #GNetworkAddress
793  *
794  * Gets @addr's scheme
795  *
796  * Return value: @addr's scheme (%NULL if not built from URI)
797  *
798  * Since: 2.26
799  */
800 const gchar *
801 g_network_address_get_scheme (GNetworkAddress *addr)
802 {
803   g_return_val_if_fail (G_IS_NETWORK_ADDRESS (addr), NULL);
804
805   return addr->priv->scheme;
806 }
807
808 #define G_TYPE_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (_g_network_address_address_enumerator_get_type ())
809 #define G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), G_TYPE_NETWORK_ADDRESS_ADDRESS_ENUMERATOR, GNetworkAddressAddressEnumerator))
810
811 typedef struct {
812   GSocketAddressEnumerator parent_instance;
813
814   GNetworkAddress *addr;
815   GList *addresses;
816   GList *next;
817 } GNetworkAddressAddressEnumerator;
818
819 typedef struct {
820   GSocketAddressEnumeratorClass parent_class;
821
822 } GNetworkAddressAddressEnumeratorClass;
823
824 static GType _g_network_address_address_enumerator_get_type (void);
825 G_DEFINE_TYPE (GNetworkAddressAddressEnumerator, _g_network_address_address_enumerator, G_TYPE_SOCKET_ADDRESS_ENUMERATOR)
826
827 static void
828 g_network_address_address_enumerator_finalize (GObject *object)
829 {
830   GNetworkAddressAddressEnumerator *addr_enum =
831     G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (object);
832
833   g_object_unref (addr_enum->addr);
834
835   G_OBJECT_CLASS (_g_network_address_address_enumerator_parent_class)->finalize (object);
836 }
837
838 static GSocketAddress *
839 g_network_address_address_enumerator_next (GSocketAddressEnumerator  *enumerator,
840                                            GCancellable              *cancellable,
841                                            GError                   **error)
842 {
843   GNetworkAddressAddressEnumerator *addr_enum =
844     G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (enumerator);
845   GSocketAddress *sockaddr;
846
847   if (addr_enum->addresses == NULL)
848     {
849       if (!addr_enum->addr->priv->sockaddrs)
850         g_network_address_parse_sockaddr (addr_enum->addr);
851       if (!addr_enum->addr->priv->sockaddrs)
852         {
853           GResolver *resolver = g_resolver_get_default ();
854           GList *addresses;
855
856           addresses = g_resolver_lookup_by_name (resolver,
857                                                  addr_enum->addr->priv->hostname,
858                                                  cancellable, error);
859           g_object_unref (resolver);
860
861           if (!addresses)
862             return NULL;
863
864           g_network_address_set_addresses (addr_enum->addr, addresses);
865         }
866           
867       addr_enum->addresses = addr_enum->addr->priv->sockaddrs;
868       addr_enum->next = addr_enum->addresses;
869     }
870
871   if (addr_enum->next == NULL)
872     return NULL;
873
874   sockaddr = addr_enum->next->data;
875   addr_enum->next = addr_enum->next->next;
876   return g_object_ref (sockaddr);
877 }
878
879 static void
880 have_addresses (GNetworkAddressAddressEnumerator *addr_enum,
881                 GTask *task, GError *error)
882 {
883   GSocketAddress *sockaddr;
884
885   addr_enum->addresses = addr_enum->addr->priv->sockaddrs;
886   addr_enum->next = addr_enum->addresses;
887
888   if (addr_enum->next)
889     {
890       sockaddr = g_object_ref (addr_enum->next->data);
891       addr_enum->next = addr_enum->next->next;
892     }
893   else
894     sockaddr = NULL;
895
896   if (error)
897     g_task_return_error (task, error);
898   else
899     g_task_return_pointer (task, sockaddr, g_object_unref);
900   g_object_unref (task);
901 }
902
903 static void
904 got_addresses (GObject      *source_object,
905                GAsyncResult *result,
906                gpointer      user_data)
907 {
908   GTask *task = user_data;
909   GNetworkAddressAddressEnumerator *addr_enum = g_task_get_source_object (task);
910   GResolver *resolver = G_RESOLVER (source_object);
911   GList *addresses;
912   GError *error = NULL;
913
914   if (!addr_enum->addr->priv->sockaddrs)
915     {
916       addresses = g_resolver_lookup_by_name_finish (resolver, result, &error);
917
918       if (!error)
919         g_network_address_set_addresses (addr_enum->addr, addresses);
920     }
921   have_addresses (addr_enum, task, error);
922 }
923
924 static void
925 g_network_address_address_enumerator_next_async (GSocketAddressEnumerator  *enumerator,
926                                                  GCancellable              *cancellable,
927                                                  GAsyncReadyCallback        callback,
928                                                  gpointer                   user_data)
929 {
930   GNetworkAddressAddressEnumerator *addr_enum =
931     G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (enumerator);
932   GSocketAddress *sockaddr;
933   GTask *task;
934
935   task = g_task_new (addr_enum, cancellable, callback, user_data);
936
937   if (addr_enum->addresses == NULL)
938     {
939       if (!addr_enum->addr->priv->sockaddrs)
940         {
941           if (g_network_address_parse_sockaddr (addr_enum->addr))
942             have_addresses (addr_enum, task, NULL);
943           else
944             {
945               GResolver *resolver = g_resolver_get_default ();
946
947               g_resolver_lookup_by_name_async (resolver,
948                                                addr_enum->addr->priv->hostname,
949                                                cancellable,
950                                                got_addresses, task);
951               g_object_unref (resolver);
952             }
953           return;
954         }
955
956       addr_enum->addresses = addr_enum->addr->priv->sockaddrs;
957       addr_enum->next = addr_enum->addresses;
958     }
959
960   if (addr_enum->next)
961     {
962       sockaddr = g_object_ref (addr_enum->next->data);
963       addr_enum->next = addr_enum->next->next;
964     }
965   else
966     sockaddr = NULL;
967
968   g_task_return_pointer (task, sockaddr, g_object_unref);
969   g_object_unref (task);
970 }
971
972 static GSocketAddress *
973 g_network_address_address_enumerator_next_finish (GSocketAddressEnumerator  *enumerator,
974                                                   GAsyncResult              *result,
975                                                   GError                   **error)
976 {
977   g_return_val_if_fail (g_task_is_valid (result, enumerator), NULL);
978
979   return g_task_propagate_pointer (G_TASK (result), error);
980 }
981
982 static void
983 _g_network_address_address_enumerator_init (GNetworkAddressAddressEnumerator *enumerator)
984 {
985 }
986
987 static void
988 _g_network_address_address_enumerator_class_init (GNetworkAddressAddressEnumeratorClass *addrenum_class)
989 {
990   GObjectClass *object_class = G_OBJECT_CLASS (addrenum_class);
991   GSocketAddressEnumeratorClass *enumerator_class =
992     G_SOCKET_ADDRESS_ENUMERATOR_CLASS (addrenum_class);
993
994   enumerator_class->next = g_network_address_address_enumerator_next;
995   enumerator_class->next_async = g_network_address_address_enumerator_next_async;
996   enumerator_class->next_finish = g_network_address_address_enumerator_next_finish;
997   object_class->finalize = g_network_address_address_enumerator_finalize;
998 }
999
1000 static GSocketAddressEnumerator *
1001 g_network_address_connectable_enumerate (GSocketConnectable *connectable)
1002 {
1003   GNetworkAddressAddressEnumerator *addr_enum;
1004
1005   addr_enum = g_object_new (G_TYPE_NETWORK_ADDRESS_ADDRESS_ENUMERATOR, NULL);
1006   addr_enum->addr = g_object_ref (connectable);
1007
1008   return (GSocketAddressEnumerator *)addr_enum;
1009 }
1010
1011 static GSocketAddressEnumerator *
1012 g_network_address_connectable_proxy_enumerate (GSocketConnectable *connectable)
1013 {
1014   GNetworkAddress *self = G_NETWORK_ADDRESS (connectable);
1015   GSocketAddressEnumerator *proxy_enum;
1016   gchar *uri;
1017
1018   uri = _g_uri_from_authority (self->priv->scheme ? self->priv->scheme : "none",
1019                                self->priv->hostname,
1020                                self->priv->port,
1021                                NULL);
1022
1023   proxy_enum = g_object_new (G_TYPE_PROXY_ADDRESS_ENUMERATOR,
1024                              "connectable", connectable,
1025                              "uri", uri,
1026                              NULL);
1027
1028   g_free (uri);
1029
1030   return proxy_enum;
1031 }