gio/: fully remove gioalias hacks
[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 "gresolver.h"
34 #include "gsimpleasyncresult.h"
35 #include "gsocketaddressenumerator.h"
36 #include "gioerror.h"
37 #include "gsocketconnectable.h"
38
39 #include <string.h>
40
41
42 /**
43  * SECTION:gnetworkaddress
44  * @short_description: A GSocketConnectable for resolving hostnames
45  * @include: gio/gio.h
46  *
47  * #GNetworkAddress provides an easy way to resolve a hostname and
48  * then attempt to connect to that host, handling the possibility of
49  * multiple IP addresses and multiple address families.
50  *
51  * See #GSocketConnectable for and example of using the connectable
52  * interface.
53  */
54
55 /**
56  * GNetworkAddress:
57  *
58  * A #GSocketConnectable for resolving a hostname and connecting to
59  * that host.
60  */
61
62 struct _GNetworkAddressPrivate {
63   gchar *hostname;
64   guint16 port;
65   GList *sockaddrs;
66 };
67
68 enum {
69   PROP_0,
70   PROP_HOSTNAME,
71   PROP_PORT,
72 };
73
74 static void g_network_address_set_property (GObject      *object,
75                                             guint         prop_id,
76                                             const GValue *value,
77                                             GParamSpec   *pspec);
78 static void g_network_address_get_property (GObject      *object,
79                                             guint         prop_id,
80                                             GValue       *value,
81                                             GParamSpec   *pspec);
82
83 static void                      g_network_address_connectable_iface_init (GSocketConnectableIface *iface);
84 static GSocketAddressEnumerator *g_network_address_connectable_enumerate  (GSocketConnectable      *connectable);
85
86 G_DEFINE_TYPE_WITH_CODE (GNetworkAddress, g_network_address, G_TYPE_OBJECT,
87                          G_IMPLEMENT_INTERFACE (G_TYPE_SOCKET_CONNECTABLE,
88                                                 g_network_address_connectable_iface_init))
89
90 static void
91 g_network_address_finalize (GObject *object)
92 {
93   GNetworkAddress *addr = G_NETWORK_ADDRESS (object);
94
95   g_free (addr->priv->hostname);
96
97   if (addr->priv->sockaddrs)
98     {
99       GList *a;
100
101       for (a = addr->priv->sockaddrs; a; a = a->next)
102         g_object_unref (a->data);
103       g_list_free (addr->priv->sockaddrs);
104     }
105
106   G_OBJECT_CLASS (g_network_address_parent_class)->finalize (object);
107 }
108
109 static void
110 g_network_address_class_init (GNetworkAddressClass *klass)
111 {
112   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
113
114   g_type_class_add_private (klass, sizeof (GNetworkAddressPrivate));
115
116   gobject_class->set_property = g_network_address_set_property;
117   gobject_class->get_property = g_network_address_get_property;
118   gobject_class->finalize = g_network_address_finalize;
119
120   g_object_class_install_property (gobject_class, PROP_HOSTNAME,
121                                    g_param_spec_string ("hostname",
122                                                         P_("Hostname"),
123                                                         P_("Hostname to resolve"),
124                                                         NULL,
125                                                         G_PARAM_READWRITE |
126                                                         G_PARAM_CONSTRUCT_ONLY |
127                                                         G_PARAM_STATIC_STRINGS));
128   g_object_class_install_property (gobject_class, PROP_PORT,
129                                    g_param_spec_uint ("port",
130                                                       P_("Port"),
131                                                       P_("Network port"),
132                                                       0, 65535, 0,
133                                                       G_PARAM_READWRITE |
134                                                       G_PARAM_CONSTRUCT_ONLY |
135                                                       G_PARAM_STATIC_STRINGS));
136 }
137
138 static void
139 g_network_address_connectable_iface_init (GSocketConnectableIface *connectable_iface)
140 {
141   connectable_iface->enumerate  = g_network_address_connectable_enumerate;
142 }
143
144 static void
145 g_network_address_init (GNetworkAddress *addr)
146 {
147   addr->priv = G_TYPE_INSTANCE_GET_PRIVATE (addr, G_TYPE_NETWORK_ADDRESS,
148                                             GNetworkAddressPrivate);
149 }
150
151 static void
152 g_network_address_set_property (GObject      *object,
153                                 guint         prop_id,
154                                 const GValue *value,
155                                 GParamSpec   *pspec)
156 {
157   GNetworkAddress *addr = G_NETWORK_ADDRESS (object);
158
159   switch (prop_id)
160     {
161     case PROP_HOSTNAME:
162       if (addr->priv->hostname)
163         g_free (addr->priv->hostname);
164       addr->priv->hostname = g_value_dup_string (value);
165       break;
166
167     case PROP_PORT:
168       addr->priv->port = g_value_get_uint (value);
169       break;
170
171     default:
172       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
173       break;
174     }
175
176 }
177
178 static void
179 g_network_address_get_property (GObject    *object,
180                                 guint       prop_id,
181                                 GValue     *value,
182                                 GParamSpec *pspec)
183 {
184   GNetworkAddress *addr = G_NETWORK_ADDRESS (object);
185
186   switch (prop_id)
187     {
188     case PROP_HOSTNAME:
189       g_value_set_string (value, addr->priv->hostname);
190       break;
191
192     case PROP_PORT:
193       g_value_set_uint (value, addr->priv->port);
194       break;
195
196     default:
197       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
198       break;
199     }
200
201 }
202
203 static void
204 g_network_address_set_addresses (GNetworkAddress *addr,
205                                  GList           *addresses)
206 {
207   GList *a;
208   GSocketAddress *sockaddr;
209
210   g_return_if_fail (addresses != NULL && addr->priv->sockaddrs == NULL);
211
212   for (a = addresses; a; a = a->next)
213     {
214       sockaddr = g_inet_socket_address_new (a->data, addr->priv->port);
215       addr->priv->sockaddrs = g_list_prepend (addr->priv->sockaddrs, sockaddr);
216       g_object_unref (a->data);
217     }
218   g_list_free (addresses);
219   addr->priv->sockaddrs = g_list_reverse (addr->priv->sockaddrs);
220 }
221
222 /**
223  * g_network_address_new:
224  * @hostname: the hostname
225  * @port: the port
226  *
227  * Creates a new #GSocketConnectable for connecting to the given
228  * @hostname and @port.
229  *
230  * Return value: the new #GNetworkAddress
231  *
232  * Since: 2.22
233  */
234 GSocketConnectable *
235 g_network_address_new (const gchar *hostname,
236                        guint16      port)
237 {
238   return g_object_new (G_TYPE_NETWORK_ADDRESS,
239                        "hostname", hostname,
240                        "port", port,
241                        NULL);
242 }
243
244 /**
245  * g_network_address_parse:
246  * @host_and_port: the hostname and optionally a port
247  * @default_port: the default port if not in @host_and_port
248  * @error: a pointer to a #GError, or %NULL
249  *
250  * Creates a new #GSocketConnectable for connecting to the given
251  * @hostname and @port. May fail and return %NULL in case
252  * parsing @host_and_port fails.
253  *
254  * @host_and_port may be in any of a number of recognised formats: an IPv6
255  * address, an IPv4 address, or a domain name (in which case a DNS
256  * lookup is performed). Quoting with [] is supported for all address
257  * types. A port override may be specified in the usual way with a
258  * colon. Ports may be given as decimal numbers or symbolic names (in
259  * which case an /etc/services lookup is performed).
260  *
261  * If no port is specified in @host_and_port then @default_port will be
262  * used as the port number to connect to.
263  *
264  * In general, @host_and_port is expected to be provided by the user
265  * (allowing them to give the hostname, and a port overide if necessary)
266  * and @default_port is expected to be provided by the application.
267  *
268  * Return value: the new #GNetworkAddress, or %NULL on error
269  *
270  * Since: 2.22
271  */
272 GSocketConnectable *
273 g_network_address_parse (const gchar  *host_and_port,
274                          guint16       default_port,
275                          GError      **error)
276 {
277   GSocketConnectable *connectable;
278   const gchar *port;
279   guint16 portnum;
280   gchar *name;
281
282   g_return_val_if_fail (host_and_port != NULL, NULL);
283
284   port = NULL;
285   if (host_and_port[0] == '[')
286     /* escaped host part (to allow, eg. "[2001:db8::1]:888") */
287     {
288       const gchar *end;
289
290       end = strchr (host_and_port, ']');
291       if (end == NULL)
292         {
293           g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
294                        _("Hostname '%s' contains '[' but not ']'"), host_and_port);
295           return NULL;
296         }
297
298       if (end[1] == '\0')
299         port = NULL;
300       else if (end[1] == ':')
301         port = &end[2];
302       else
303         {
304           g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
305                        "The ']' character (in hostname '%s') must come at the"
306                        " end or be immediately followed by ':' and a port",
307                        host_and_port);
308           return NULL;
309         }
310
311       name = g_strndup (host_and_port + 1, end - host_and_port - 1);
312     }
313
314   else if ((port = strchr (host_and_port, ':')))
315     /* string has a ':' in it */
316     {
317       /* skip ':' */
318       port++;
319
320       if (strchr (port, ':'))
321         /* more than one ':' in string */
322         {
323           /* this is actually an unescaped IPv6 address */
324           name = g_strdup (host_and_port);
325           port = NULL;
326         }
327       else
328         name = g_strndup (host_and_port, port - host_and_port - 1);
329     }
330
331   else
332     /* plain hostname, no port */
333     name = g_strdup (host_and_port);
334
335   if (port != NULL)
336     {
337       if (port[0] == '\0')
338         {
339           g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
340                        "If a ':' character is given, it must be followed by a "
341                        "port (in hostname '%s').", host_and_port);
342           g_free (name);
343           return NULL;
344         }
345
346       else if ('0' <= port[0] && port[0] <= '9')
347         {
348           char *end;
349           long value;
350
351           value = strtol (port, &end, 10);
352           if (*end != '\0' || value < 0 || value > G_MAXUINT16)
353             {
354               g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
355                            "Invalid numeric port '%s' specified in hostname '%s'",
356                            port, host_and_port);
357               g_free (name);
358               return NULL;
359             }
360
361           portnum = value;
362         }
363
364       else
365         {
366           struct servent *entry;
367
368           entry = getservbyname (port, "tcp");
369           if (entry == NULL)
370             {
371               g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
372                            "Unknown service '%s' specified in hostname '%s'",
373                            port, host_and_port);
374 #ifdef HAVE_ENDSERVENT
375               endservent ();
376 #endif
377               g_free (name);
378               return NULL;
379             }
380
381           portnum = g_ntohs (entry->s_port);
382
383 #ifdef HAVE_ENDSERVENT
384           endservent ();
385 #endif
386         }
387     }
388   else
389     {
390       /* No port in host_and_port */
391       portnum = default_port;
392     }
393
394   connectable = g_network_address_new (name, portnum);
395   g_free (name);
396
397   return connectable;
398 }
399
400 /**
401  * g_network_address_get_hostname:
402  * @addr: a #GNetworkAddress
403  *
404  * Gets @addr's hostname. This might be either UTF-8 or ASCII-encoded,
405  * depending on what @addr was created with.
406  *
407  * Return value: @addr's hostname
408  *
409  * Since: 2.22
410  */
411 const gchar *
412 g_network_address_get_hostname (GNetworkAddress *addr)
413 {
414   g_return_val_if_fail (G_IS_NETWORK_ADDRESS (addr), NULL);
415
416   return addr->priv->hostname;
417 }
418
419 /**
420  * g_network_address_get_port:
421  * @addr: a #GNetworkAddress
422  *
423  * Gets @addr's port number
424  *
425  * Return value: @addr's port (which may be 0)
426  *
427  * Since: 2.22
428  */
429 guint16
430 g_network_address_get_port (GNetworkAddress *addr)
431 {
432   g_return_val_if_fail (G_IS_NETWORK_ADDRESS (addr), 0);
433
434   return addr->priv->port;
435 }
436
437 #define G_TYPE_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (_g_network_address_address_enumerator_get_type ())
438 #define G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), G_TYPE_NETWORK_ADDRESS_ADDRESS_ENUMERATOR, GNetworkAddressAddressEnumerator))
439
440 typedef struct {
441   GSocketAddressEnumerator parent_instance;
442
443   GNetworkAddress *addr;
444   GList *a;
445 } GNetworkAddressAddressEnumerator;
446
447 typedef struct {
448   GSocketAddressEnumeratorClass parent_class;
449
450 } GNetworkAddressAddressEnumeratorClass;
451
452 G_DEFINE_TYPE (GNetworkAddressAddressEnumerator, _g_network_address_address_enumerator, G_TYPE_SOCKET_ADDRESS_ENUMERATOR)
453
454 static void
455 g_network_address_address_enumerator_finalize (GObject *object)
456 {
457   GNetworkAddressAddressEnumerator *addr_enum =
458     G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (object);
459
460   g_object_unref (addr_enum->addr);
461
462   G_OBJECT_CLASS (_g_network_address_address_enumerator_parent_class)->finalize (object);
463 }
464
465 static GSocketAddress *
466 g_network_address_address_enumerator_next (GSocketAddressEnumerator  *enumerator,
467                                            GCancellable              *cancellable,
468                                            GError                   **error)
469 {
470   GNetworkAddressAddressEnumerator *addr_enum =
471     G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (enumerator);
472   GSocketAddress *sockaddr;
473
474   if (!addr_enum->addr->priv->sockaddrs)
475     {
476       GResolver *resolver = g_resolver_get_default ();
477       GList *addresses;
478
479       addresses = g_resolver_lookup_by_name (resolver,
480                                              addr_enum->addr->priv->hostname,
481                                              cancellable, error);
482       g_object_unref (resolver);
483
484       if (!addresses)
485         return NULL;
486
487       g_network_address_set_addresses (addr_enum->addr, addresses);
488       addr_enum->a = addr_enum->addr->priv->sockaddrs;
489     }
490
491   if (!addr_enum->a)
492     return NULL;
493   else
494     {
495       sockaddr = addr_enum->a->data;
496       addr_enum->a = addr_enum->a->next;
497       return g_object_ref (sockaddr);
498     }
499 }
500
501 static void
502 got_addresses (GObject      *source_object,
503                GAsyncResult *result,
504                gpointer      user_data)
505 {
506   GSimpleAsyncResult *simple = user_data;
507   GNetworkAddressAddressEnumerator *addr_enum =
508     g_simple_async_result_get_op_res_gpointer (simple);
509   GResolver *resolver = G_RESOLVER (source_object);
510   GList *addresses;
511   GError *error = NULL;
512
513   addresses = g_resolver_lookup_by_name_finish (resolver, result, &error);
514   if (!addr_enum->addr->priv->sockaddrs)
515     {
516       if (error)
517         {
518           g_simple_async_result_set_from_error (simple, error);
519           g_error_free (error);
520         }
521       else
522         {
523           g_network_address_set_addresses (addr_enum->addr, addresses);
524           addr_enum->a = addr_enum->addr->priv->sockaddrs;
525         }
526     }
527   else if (error)
528     g_error_free (error);
529
530   g_object_unref (resolver);
531
532   g_simple_async_result_complete (simple);
533   g_object_unref (simple);
534 }
535
536 static void
537 g_network_address_address_enumerator_next_async (GSocketAddressEnumerator  *enumerator,
538                                                  GCancellable              *cancellable,
539                                                  GAsyncReadyCallback        callback,
540                                                  gpointer                   user_data)
541 {
542   GNetworkAddressAddressEnumerator *addr_enum =
543     G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (enumerator);
544   GSimpleAsyncResult *simple;
545
546   simple = g_simple_async_result_new (G_OBJECT (enumerator),
547                                       callback, user_data,
548                                       g_network_address_address_enumerator_next_async);
549
550   if (!addr_enum->addr->priv->sockaddrs)
551     {
552       GResolver *resolver = g_resolver_get_default ();
553
554       g_simple_async_result_set_op_res_gpointer (simple, g_object_ref (addr_enum), g_object_unref);
555       g_resolver_lookup_by_name_async (resolver,
556                                        addr_enum->addr->priv->hostname,
557                                        cancellable,
558                                        got_addresses, simple);
559     }
560   else
561     {
562       g_simple_async_result_complete_in_idle (simple);
563       g_object_unref (simple);
564     }
565 }
566
567 static GSocketAddress *
568 g_network_address_address_enumerator_next_finish (GSocketAddressEnumerator  *enumerator,
569                                                   GAsyncResult              *result,
570                                                   GError                   **error)
571 {
572   GNetworkAddressAddressEnumerator *addr_enum =
573     G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (enumerator);
574   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
575   GSocketAddress *sockaddr;
576
577   if (g_simple_async_result_propagate_error (simple, error))
578     return NULL;
579   else if (!addr_enum->a)
580     return NULL;
581   else
582     {
583       sockaddr = addr_enum->a->data;
584       addr_enum->a = addr_enum->a->next;
585       return g_object_ref (sockaddr);
586     }
587 }
588
589 static void
590 _g_network_address_address_enumerator_init (GNetworkAddressAddressEnumerator *enumerator)
591 {
592 }
593
594 static void
595 _g_network_address_address_enumerator_class_init (GNetworkAddressAddressEnumeratorClass *addrenum_class)
596 {
597   GObjectClass *object_class = G_OBJECT_CLASS (addrenum_class);
598   GSocketAddressEnumeratorClass *enumerator_class =
599     G_SOCKET_ADDRESS_ENUMERATOR_CLASS (addrenum_class);
600
601   enumerator_class->next = g_network_address_address_enumerator_next;
602   enumerator_class->next_async = g_network_address_address_enumerator_next_async;
603   enumerator_class->next_finish = g_network_address_address_enumerator_next_finish;
604   object_class->finalize = g_network_address_address_enumerator_finalize;
605 }
606
607 static GSocketAddressEnumerator *
608 g_network_address_connectable_enumerate (GSocketConnectable *connectable)
609 {
610   GNetworkAddressAddressEnumerator *addr_enum;
611
612   addr_enum = g_object_new (G_TYPE_NETWORK_ADDRESS_ADDRESS_ENUMERATOR, NULL);
613   addr_enum->addr = g_object_ref (connectable);
614
615   return (GSocketAddressEnumerator *)addr_enum;
616 }