Drop an unneeded if
[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       g_free (addr->priv->hostname);
163       addr->priv->hostname = g_value_dup_string (value);
164       break;
165
166     case PROP_PORT:
167       addr->priv->port = g_value_get_uint (value);
168       break;
169
170     default:
171       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
172       break;
173     }
174
175 }
176
177 static void
178 g_network_address_get_property (GObject    *object,
179                                 guint       prop_id,
180                                 GValue     *value,
181                                 GParamSpec *pspec)
182 {
183   GNetworkAddress *addr = G_NETWORK_ADDRESS (object);
184
185   switch (prop_id)
186     {
187     case PROP_HOSTNAME:
188       g_value_set_string (value, addr->priv->hostname);
189       break;
190
191     case PROP_PORT:
192       g_value_set_uint (value, addr->priv->port);
193       break;
194
195     default:
196       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
197       break;
198     }
199
200 }
201
202 static void
203 g_network_address_set_addresses (GNetworkAddress *addr,
204                                  GList           *addresses)
205 {
206   GList *a;
207   GSocketAddress *sockaddr;
208
209   g_return_if_fail (addresses != NULL && addr->priv->sockaddrs == NULL);
210
211   for (a = addresses; a; a = a->next)
212     {
213       sockaddr = g_inet_socket_address_new (a->data, addr->priv->port);
214       addr->priv->sockaddrs = g_list_prepend (addr->priv->sockaddrs, sockaddr);
215       g_object_unref (a->data);
216     }
217   g_list_free (addresses);
218   addr->priv->sockaddrs = g_list_reverse (addr->priv->sockaddrs);
219 }
220
221 /**
222  * g_network_address_new:
223  * @hostname: the hostname
224  * @port: the port
225  *
226  * Creates a new #GSocketConnectable for connecting to the given
227  * @hostname and @port.
228  *
229  * Return value: the new #GNetworkAddress
230  *
231  * Since: 2.22
232  */
233 GSocketConnectable *
234 g_network_address_new (const gchar *hostname,
235                        guint16      port)
236 {
237   return g_object_new (G_TYPE_NETWORK_ADDRESS,
238                        "hostname", hostname,
239                        "port", port,
240                        NULL);
241 }
242
243 /**
244  * g_network_address_parse:
245  * @host_and_port: the hostname and optionally a port
246  * @default_port: the default port if not in @host_and_port
247  * @error: a pointer to a #GError, or %NULL
248  *
249  * Creates a new #GSocketConnectable for connecting to the given
250  * @hostname and @port. May fail and return %NULL in case
251  * parsing @host_and_port fails.
252  *
253  * @host_and_port may be in any of a number of recognised formats: an IPv6
254  * address, an IPv4 address, or a domain name (in which case a DNS
255  * lookup is performed). Quoting with [] is supported for all address
256  * types. A port override may be specified in the usual way with a
257  * colon. Ports may be given as decimal numbers or symbolic names (in
258  * which case an /etc/services lookup is performed).
259  *
260  * If no port is specified in @host_and_port then @default_port will be
261  * used as the port number to connect to.
262  *
263  * In general, @host_and_port is expected to be provided by the user
264  * (allowing them to give the hostname, and a port overide if necessary)
265  * and @default_port is expected to be provided by the application.
266  *
267  * Return value: the new #GNetworkAddress, or %NULL on error
268  *
269  * Since: 2.22
270  */
271 GSocketConnectable *
272 g_network_address_parse (const gchar  *host_and_port,
273                          guint16       default_port,
274                          GError      **error)
275 {
276   GSocketConnectable *connectable;
277   const gchar *port;
278   guint16 portnum;
279   gchar *name;
280
281   g_return_val_if_fail (host_and_port != NULL, NULL);
282
283   port = NULL;
284   if (host_and_port[0] == '[')
285     /* escaped host part (to allow, eg. "[2001:db8::1]:888") */
286     {
287       const gchar *end;
288
289       end = strchr (host_and_port, ']');
290       if (end == NULL)
291         {
292           g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
293                        _("Hostname '%s' contains '[' but not ']'"), host_and_port);
294           return NULL;
295         }
296
297       if (end[1] == '\0')
298         port = NULL;
299       else if (end[1] == ':')
300         port = &end[2];
301       else
302         {
303           g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
304                        "The ']' character (in hostname '%s') must come at the"
305                        " end or be immediately followed by ':' and a port",
306                        host_and_port);
307           return NULL;
308         }
309
310       name = g_strndup (host_and_port + 1, end - host_and_port - 1);
311     }
312
313   else if ((port = strchr (host_and_port, ':')))
314     /* string has a ':' in it */
315     {
316       /* skip ':' */
317       port++;
318
319       if (strchr (port, ':'))
320         /* more than one ':' in string */
321         {
322           /* this is actually an unescaped IPv6 address */
323           name = g_strdup (host_and_port);
324           port = NULL;
325         }
326       else
327         name = g_strndup (host_and_port, port - host_and_port - 1);
328     }
329
330   else
331     /* plain hostname, no port */
332     name = g_strdup (host_and_port);
333
334   if (port != NULL)
335     {
336       if (port[0] == '\0')
337         {
338           g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
339                        "If a ':' character is given, it must be followed by a "
340                        "port (in hostname '%s').", host_and_port);
341           g_free (name);
342           return NULL;
343         }
344
345       else if ('0' <= port[0] && port[0] <= '9')
346         {
347           char *end;
348           long value;
349
350           value = strtol (port, &end, 10);
351           if (*end != '\0' || value < 0 || value > G_MAXUINT16)
352             {
353               g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
354                            "Invalid numeric port '%s' specified in hostname '%s'",
355                            port, host_and_port);
356               g_free (name);
357               return NULL;
358             }
359
360           portnum = value;
361         }
362
363       else
364         {
365           struct servent *entry;
366
367           entry = getservbyname (port, "tcp");
368           if (entry == NULL)
369             {
370               g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
371                            "Unknown service '%s' specified in hostname '%s'",
372                            port, host_and_port);
373 #ifdef HAVE_ENDSERVENT
374               endservent ();
375 #endif
376               g_free (name);
377               return NULL;
378             }
379
380           portnum = g_ntohs (entry->s_port);
381
382 #ifdef HAVE_ENDSERVENT
383           endservent ();
384 #endif
385         }
386     }
387   else
388     {
389       /* No port in host_and_port */
390       portnum = default_port;
391     }
392
393   connectable = g_network_address_new (name, portnum);
394   g_free (name);
395
396   return connectable;
397 }
398
399 /**
400  * g_network_address_get_hostname:
401  * @addr: a #GNetworkAddress
402  *
403  * Gets @addr's hostname. This might be either UTF-8 or ASCII-encoded,
404  * depending on what @addr was created with.
405  *
406  * Return value: @addr's hostname
407  *
408  * Since: 2.22
409  */
410 const gchar *
411 g_network_address_get_hostname (GNetworkAddress *addr)
412 {
413   g_return_val_if_fail (G_IS_NETWORK_ADDRESS (addr), NULL);
414
415   return addr->priv->hostname;
416 }
417
418 /**
419  * g_network_address_get_port:
420  * @addr: a #GNetworkAddress
421  *
422  * Gets @addr's port number
423  *
424  * Return value: @addr's port (which may be 0)
425  *
426  * Since: 2.22
427  */
428 guint16
429 g_network_address_get_port (GNetworkAddress *addr)
430 {
431   g_return_val_if_fail (G_IS_NETWORK_ADDRESS (addr), 0);
432
433   return addr->priv->port;
434 }
435
436 #define G_TYPE_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (_g_network_address_address_enumerator_get_type ())
437 #define G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), G_TYPE_NETWORK_ADDRESS_ADDRESS_ENUMERATOR, GNetworkAddressAddressEnumerator))
438
439 typedef struct {
440   GSocketAddressEnumerator parent_instance;
441
442   GNetworkAddress *addr;
443   GList *a;
444 } GNetworkAddressAddressEnumerator;
445
446 typedef struct {
447   GSocketAddressEnumeratorClass parent_class;
448
449 } GNetworkAddressAddressEnumeratorClass;
450
451 G_DEFINE_TYPE (GNetworkAddressAddressEnumerator, _g_network_address_address_enumerator, G_TYPE_SOCKET_ADDRESS_ENUMERATOR)
452
453 static void
454 g_network_address_address_enumerator_finalize (GObject *object)
455 {
456   GNetworkAddressAddressEnumerator *addr_enum =
457     G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (object);
458
459   g_object_unref (addr_enum->addr);
460
461   G_OBJECT_CLASS (_g_network_address_address_enumerator_parent_class)->finalize (object);
462 }
463
464 static GSocketAddress *
465 g_network_address_address_enumerator_next (GSocketAddressEnumerator  *enumerator,
466                                            GCancellable              *cancellable,
467                                            GError                   **error)
468 {
469   GNetworkAddressAddressEnumerator *addr_enum =
470     G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (enumerator);
471   GSocketAddress *sockaddr;
472
473   if (!addr_enum->addr->priv->sockaddrs)
474     {
475       GResolver *resolver = g_resolver_get_default ();
476       GList *addresses;
477
478       addresses = g_resolver_lookup_by_name (resolver,
479                                              addr_enum->addr->priv->hostname,
480                                              cancellable, error);
481       g_object_unref (resolver);
482
483       if (!addresses)
484         return NULL;
485
486       g_network_address_set_addresses (addr_enum->addr, addresses);
487       addr_enum->a = addr_enum->addr->priv->sockaddrs;
488     }
489
490   if (!addr_enum->a)
491     return NULL;
492   else
493     {
494       sockaddr = addr_enum->a->data;
495       addr_enum->a = addr_enum->a->next;
496       return g_object_ref (sockaddr);
497     }
498 }
499
500 static void
501 got_addresses (GObject      *source_object,
502                GAsyncResult *result,
503                gpointer      user_data)
504 {
505   GSimpleAsyncResult *simple = user_data;
506   GNetworkAddressAddressEnumerator *addr_enum =
507     g_simple_async_result_get_op_res_gpointer (simple);
508   GResolver *resolver = G_RESOLVER (source_object);
509   GList *addresses;
510   GError *error = NULL;
511
512   addresses = g_resolver_lookup_by_name_finish (resolver, result, &error);
513   if (!addr_enum->addr->priv->sockaddrs)
514     {
515       if (error)
516         {
517           g_simple_async_result_set_from_error (simple, error);
518           g_error_free (error);
519         }
520       else
521         {
522           g_network_address_set_addresses (addr_enum->addr, addresses);
523           addr_enum->a = addr_enum->addr->priv->sockaddrs;
524         }
525     }
526   else if (error)
527     g_error_free (error);
528
529   g_object_unref (resolver);
530
531   g_simple_async_result_complete (simple);
532   g_object_unref (simple);
533 }
534
535 static void
536 g_network_address_address_enumerator_next_async (GSocketAddressEnumerator  *enumerator,
537                                                  GCancellable              *cancellable,
538                                                  GAsyncReadyCallback        callback,
539                                                  gpointer                   user_data)
540 {
541   GNetworkAddressAddressEnumerator *addr_enum =
542     G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (enumerator);
543   GSimpleAsyncResult *simple;
544
545   simple = g_simple_async_result_new (G_OBJECT (enumerator),
546                                       callback, user_data,
547                                       g_network_address_address_enumerator_next_async);
548
549   if (!addr_enum->addr->priv->sockaddrs)
550     {
551       GResolver *resolver = g_resolver_get_default ();
552
553       g_simple_async_result_set_op_res_gpointer (simple, g_object_ref (addr_enum), g_object_unref);
554       g_resolver_lookup_by_name_async (resolver,
555                                        addr_enum->addr->priv->hostname,
556                                        cancellable,
557                                        got_addresses, simple);
558     }
559   else
560     {
561       g_simple_async_result_complete_in_idle (simple);
562       g_object_unref (simple);
563     }
564 }
565
566 static GSocketAddress *
567 g_network_address_address_enumerator_next_finish (GSocketAddressEnumerator  *enumerator,
568                                                   GAsyncResult              *result,
569                                                   GError                   **error)
570 {
571   GNetworkAddressAddressEnumerator *addr_enum =
572     G_NETWORK_ADDRESS_ADDRESS_ENUMERATOR (enumerator);
573   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
574   GSocketAddress *sockaddr;
575
576   if (g_simple_async_result_propagate_error (simple, error))
577     return NULL;
578   else if (!addr_enum->a)
579     return NULL;
580   else
581     {
582       sockaddr = addr_enum->a->data;
583       addr_enum->a = addr_enum->a->next;
584       return g_object_ref (sockaddr);
585     }
586 }
587
588 static void
589 _g_network_address_address_enumerator_init (GNetworkAddressAddressEnumerator *enumerator)
590 {
591 }
592
593 static void
594 _g_network_address_address_enumerator_class_init (GNetworkAddressAddressEnumeratorClass *addrenum_class)
595 {
596   GObjectClass *object_class = G_OBJECT_CLASS (addrenum_class);
597   GSocketAddressEnumeratorClass *enumerator_class =
598     G_SOCKET_ADDRESS_ENUMERATOR_CLASS (addrenum_class);
599
600   enumerator_class->next = g_network_address_address_enumerator_next;
601   enumerator_class->next_async = g_network_address_address_enumerator_next_async;
602   enumerator_class->next_finish = g_network_address_address_enumerator_next_finish;
603   object_class->finalize = g_network_address_address_enumerator_finalize;
604 }
605
606 static GSocketAddressEnumerator *
607 g_network_address_connectable_enumerate (GSocketConnectable *connectable)
608 {
609   GNetworkAddressAddressEnumerator *addr_enum;
610
611   addr_enum = g_object_new (G_TYPE_NETWORK_ADDRESS_ADDRESS_ENUMERATOR, NULL);
612   addr_enum->addr = g_object_ref (connectable);
613
614   return (GSocketAddressEnumerator *)addr_enum;
615 }