GResolver: Don't return duplicate addresses
[platform/upstream/glib.git] / gio / gresolver.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 "gresolver.h"
28 #include "gnetworkingprivate.h"
29 #include "gasyncresult.h"
30 #include "ginetaddress.h"
31 #include "ginetsocketaddress.h"
32 #include "gsimpleasyncresult.h"
33 #include "gsrvtarget.h"
34
35 #ifdef G_OS_UNIX
36 #include "gunixresolver.h"
37 #include <sys/stat.h>
38 #endif
39 #ifdef G_OS_WIN32
40 #include "gwin32resolver.h"
41 #endif
42
43 #include <stdlib.h>
44
45
46 /**
47  * SECTION:gresolver
48  * @short_description: Asynchronous and cancellable DNS resolver
49  * @include: gio/gio.h
50  *
51  * #GResolver provides cancellable synchronous and asynchronous DNS
52  * resolution, for hostnames (g_resolver_lookup_by_address(),
53  * g_resolver_lookup_by_name() and their async variants) and SRV
54  * (service) records (g_resolver_lookup_service()).
55  *
56  * #GNetworkAddress and #GNetworkService provide wrappers around
57  * #GResolver functionality that also implement #GSocketConnectable,
58  * making it easy to connect to a remote host/service.
59  */
60
61 enum {
62   RELOAD,
63   LAST_SIGNAL
64 };
65
66 static guint signals[LAST_SIGNAL] = { 0 };
67
68 struct _GResolverPrivate {
69 #ifdef G_OS_UNIX
70   time_t resolv_conf_timestamp;
71 #else
72   int dummy;
73 #endif
74 };
75
76 /**
77  * GResolver:
78  *
79  * The object that handles DNS resolution. Use g_resolver_get_default()
80  * to get the default resolver.
81  */
82 G_DEFINE_TYPE (GResolver, g_resolver, G_TYPE_OBJECT)
83
84 static void
85 g_resolver_class_init (GResolverClass *resolver_class)
86 {
87   volatile GType type;
88
89   g_type_class_add_private (resolver_class, sizeof (GResolverPrivate));
90
91   /* Make sure _g_networking_init() has been called */
92   type = g_inet_address_get_type ();
93   (type); /* To avoid -Wunused-but-set-variable */
94
95   /* Initialize _g_resolver_addrinfo_hints */
96 #ifdef AI_ADDRCONFIG
97   _g_resolver_addrinfo_hints.ai_flags |= AI_ADDRCONFIG;
98 #endif
99   /* These two don't actually matter, they just get copied into the
100    * returned addrinfo structures (and then we ignore them). But if
101    * we leave them unset, we'll get back duplicate answers.
102    */
103   _g_resolver_addrinfo_hints.ai_socktype = SOCK_STREAM;
104   _g_resolver_addrinfo_hints.ai_protocol = IPPROTO_TCP;
105
106   /**
107    * GResolver::reload:
108    * @resolver: a #GResolver
109    *
110    * Emitted when the resolver notices that the system resolver
111    * configuration has changed.
112    **/
113   signals[RELOAD] =
114     g_signal_new (I_("reload"),
115                   G_TYPE_RESOLVER,
116                   G_SIGNAL_RUN_LAST,
117                   G_STRUCT_OFFSET (GResolverClass, reload),
118                   NULL, NULL,
119                   g_cclosure_marshal_VOID__VOID,
120                   G_TYPE_NONE, 0);
121 }
122
123 static void
124 g_resolver_init (GResolver *resolver)
125 {
126 #ifdef G_OS_UNIX
127   struct stat st;
128 #endif
129
130   resolver->priv = G_TYPE_INSTANCE_GET_PRIVATE (resolver, G_TYPE_RESOLVER, GResolverPrivate);
131
132 #ifdef G_OS_UNIX
133   if (stat (_PATH_RESCONF, &st) == 0)
134     resolver->priv->resolv_conf_timestamp = st.st_mtime;
135 #endif
136 }
137
138 static GResolver *default_resolver;
139
140 /**
141  * g_resolver_get_default:
142  *
143  * Gets the default #GResolver. You should unref it when you are done
144  * with it. #GResolver may use its reference count as a hint about how
145  * many threads/processes, etc it should allocate for concurrent DNS
146  * resolutions.
147  *
148  * Return value: (transfer full): the default #GResolver.
149  *
150  * Since: 2.22
151  */
152 GResolver *
153 g_resolver_get_default (void)
154 {
155   if (!default_resolver)
156     {
157       if (g_thread_supported ())
158         default_resolver = g_object_new (G_TYPE_THREADED_RESOLVER, NULL);
159       else
160         {
161 #if defined(G_OS_UNIX)
162           default_resolver = g_object_new (G_TYPE_UNIX_RESOLVER, NULL);
163 #elif defined(G_OS_WIN32)
164           default_resolver = g_object_new (G_TYPE_WIN32_RESOLVER, NULL);
165 #endif
166         }
167     }
168
169   return g_object_ref (default_resolver);
170 }
171
172 /**
173  * g_resolver_set_default:
174  * @resolver: the new default #GResolver
175  *
176  * Sets @resolver to be the application's default resolver (reffing
177  * @resolver, and unreffing the previous default resolver, if any).
178  * Future calls to g_resolver_get_default() will return this resolver.
179  *
180  * This can be used if an application wants to perform any sort of DNS
181  * caching or "pinning"; it can implement its own #GResolver that
182  * calls the original default resolver for DNS operations, and
183  * implements its own cache policies on top of that, and then set
184  * itself as the default resolver for all later code to use.
185  *
186  * Since: 2.22
187  */
188 void
189 g_resolver_set_default (GResolver *resolver)
190 {
191   if (default_resolver)
192     g_object_unref (default_resolver);
193   default_resolver = g_object_ref (resolver);
194 }
195
196
197 static void
198 g_resolver_maybe_reload (GResolver *resolver)
199 {
200 #ifdef G_OS_UNIX
201   struct stat st;
202
203   if (stat (_PATH_RESCONF, &st) == 0)
204     {
205       if (st.st_mtime != resolver->priv->resolv_conf_timestamp)
206         {
207           resolver->priv->resolv_conf_timestamp = st.st_mtime;
208           res_init ();
209           g_signal_emit (resolver, signals[RELOAD], 0);
210         }
211     }
212 #endif
213 }
214
215 /* filter out duplicates, cf. https://bugzilla.gnome.org/show_bug.cgi?id=631379 */
216 static void
217 remove_duplicates (GList *addrs)
218 {
219   GList *l;
220   GList *ll;
221   GList *lll;
222
223   /* TODO: if this is too slow (it's O(n^2) but n is typically really
224    * small), we can do something more clever but note that we must not
225    * change the order of elements...
226    */
227   for (l = addrs; l != NULL; l = l->next)
228     {
229       GInetAddress *address = G_INET_ADDRESS (l->data);
230       for (ll = l->next; ll != NULL; ll = lll)
231         {
232           GInetAddress *other_address = G_INET_ADDRESS (ll->data);
233           lll = ll->next;
234           if (g_inet_address_equal (address, other_address))
235             {
236               g_object_unref (other_address);
237               /* we never return the first element */
238               g_warn_if_fail (g_list_delete_link (addrs, ll) == addrs);
239             }
240         }
241     }
242 }
243
244
245 /**
246  * g_resolver_lookup_by_name:
247  * @resolver: a #GResolver
248  * @hostname: the hostname to look up
249  * @cancellable: (allow-none): a #GCancellable, or %NULL
250  * @error: return location for a #GError, or %NULL
251  *
252  * Synchronously resolves @hostname to determine its associated IP
253  * address(es). @hostname may be an ASCII-only or UTF-8 hostname, or
254  * the textual form of an IP address (in which case this just becomes
255  * a wrapper around g_inet_address_new_from_string()).
256  *
257  * On success, g_resolver_lookup_by_name() will return a #GList of
258  * #GInetAddress, sorted in order of preference and guaranteed to not
259  * contain duplicates. That is, if using the result to connect to
260  * @hostname, you should attempt to connect to the first address
261  * first, then the second if the first fails, etc. If you are using
262  * the result to listen on a socket, it is appropriate to add each
263  * result using e.g. g_socket_listener_add_address().
264  *
265  * If the DNS resolution fails, @error (if non-%NULL) will be set to a
266  * value from #GResolverError.
267  *
268  * If @cancellable is non-%NULL, it can be used to cancel the
269  * operation, in which case @error (if non-%NULL) will be set to
270  * %G_IO_ERROR_CANCELLED.
271  *
272  * If you are planning to connect to a socket on the resolved IP
273  * address, it may be easier to create a #GNetworkAddress and use its
274  * #GSocketConnectable interface.
275  *
276  * Return value: (element-type GInetAddress) (transfer full): a #GList
277  * of #GInetAddress, or %NULL on error. You
278  * must unref each of the addresses and free the list when you are
279  * done with it. (You can use g_resolver_free_addresses() to do this.)
280  *
281  * Since: 2.22
282  */
283 GList *
284 g_resolver_lookup_by_name (GResolver     *resolver,
285                            const gchar   *hostname,
286                            GCancellable  *cancellable,
287                            GError       **error)
288 {
289   GInetAddress *addr;
290   GList *addrs;
291   gchar *ascii_hostname = NULL;
292
293   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
294   g_return_val_if_fail (hostname != NULL, NULL);
295
296   /* Check if @hostname is just an IP address */
297   addr = g_inet_address_new_from_string (hostname);
298   if (addr)
299     return g_list_append (NULL, addr);
300
301   if (g_hostname_is_non_ascii (hostname))
302     hostname = ascii_hostname = g_hostname_to_ascii (hostname);
303
304   g_resolver_maybe_reload (resolver);
305   addrs = G_RESOLVER_GET_CLASS (resolver)->
306     lookup_by_name (resolver, hostname, cancellable, error);
307
308   remove_duplicates (addrs);
309
310   g_free (ascii_hostname);
311   return addrs;
312 }
313
314 /**
315  * g_resolver_lookup_by_name_async:
316  * @resolver: a #GResolver
317  * @hostname: the hostname to look up the address of
318  * @cancellable: (allow-none): a #GCancellable, or %NULL
319  * @callback: (scope async): callback to call after resolution completes
320  * @user_data: (closure): data for @callback
321  *
322  * Begins asynchronously resolving @hostname to determine its
323  * associated IP address(es), and eventually calls @callback, which
324  * must call g_resolver_lookup_by_name_finish() to get the result.
325  * See g_resolver_lookup_by_name() for more details.
326  *
327  * Since: 2.22
328  */
329 void
330 g_resolver_lookup_by_name_async (GResolver           *resolver,
331                                  const gchar         *hostname,
332                                  GCancellable        *cancellable,
333                                  GAsyncReadyCallback  callback,
334                                  gpointer             user_data)
335 {
336   GInetAddress *addr;
337   gchar *ascii_hostname = NULL;
338
339   g_return_if_fail (G_IS_RESOLVER (resolver));
340   g_return_if_fail (hostname != NULL);
341
342   /* Check if @hostname is just an IP address */
343   addr = g_inet_address_new_from_string (hostname);
344   if (addr)
345     {
346       GSimpleAsyncResult *simple;
347
348       simple = g_simple_async_result_new (G_OBJECT (resolver),
349                                           callback, user_data,
350                                           g_resolver_lookup_by_name_async);
351
352       g_simple_async_result_set_op_res_gpointer (simple, addr, g_object_unref);
353       g_simple_async_result_complete_in_idle (simple);
354       g_object_unref (simple);
355       return;
356     }
357
358   if (g_hostname_is_non_ascii (hostname))
359     hostname = ascii_hostname = g_hostname_to_ascii (hostname);
360
361   g_resolver_maybe_reload (resolver);
362   G_RESOLVER_GET_CLASS (resolver)->
363     lookup_by_name_async (resolver, hostname, cancellable, callback, user_data);
364
365   g_free (ascii_hostname);
366 }
367
368 /**
369  * g_resolver_lookup_by_name_finish:
370  * @resolver: a #GResolver
371  * @result: the result passed to your #GAsyncReadyCallback
372  * @error: return location for a #GError, or %NULL
373  *
374  * Retrieves the result of a call to
375  * g_resolver_lookup_by_name_async().
376  *
377  * If the DNS resolution failed, @error (if non-%NULL) will be set to
378  * a value from #GResolverError. If the operation was cancelled,
379  * @error will be set to %G_IO_ERROR_CANCELLED.
380  *
381  * Return value: (element-type GInetAddress) (transfer full): a #GList
382  * of #GInetAddress, or %NULL on error. See g_resolver_lookup_by_name()
383  * for more details.
384  *
385  * Since: 2.22
386  */
387 GList *
388 g_resolver_lookup_by_name_finish (GResolver     *resolver,
389                                   GAsyncResult  *result,
390                                   GError       **error)
391 {
392   GList *addrs;
393
394   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
395
396   if (G_IS_SIMPLE_ASYNC_RESULT (result))
397     {
398       GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
399
400       if (g_simple_async_result_propagate_error (simple, error))
401         return NULL;
402
403       /* Handle the stringified-IP-addr case */
404       if (g_simple_async_result_get_source_tag (simple) == g_resolver_lookup_by_name_async)
405         {
406           GInetAddress *addr;
407
408           addr = g_simple_async_result_get_op_res_gpointer (simple);
409           return g_list_append (NULL, g_object_ref (addr));
410         }
411     }
412
413   addrs = G_RESOLVER_GET_CLASS (resolver)->
414     lookup_by_name_finish (resolver, result, error);
415
416   remove_duplicates (addrs);
417
418   return addrs;
419 }
420
421 /**
422  * g_resolver_free_addresses: (skip)
423  * @addresses: a #GList of #GInetAddress
424  *
425  * Frees @addresses (which should be the return value from
426  * g_resolver_lookup_by_name() or g_resolver_lookup_by_name_finish()).
427  * (This is a convenience method; you can also simply free the results
428  * by hand.)
429  *
430  * Since: 2.22
431  */
432 void
433 g_resolver_free_addresses (GList *addresses)
434 {
435   GList *a;
436
437   for (a = addresses; a; a = a->next)
438     g_object_unref (a->data);
439   g_list_free (addresses);
440 }
441
442 /**
443  * g_resolver_lookup_by_address:
444  * @resolver: a #GResolver
445  * @address: the address to reverse-resolve
446  * @cancellable: (allow-none): a #GCancellable, or %NULL
447  * @error: return location for a #GError, or %NULL
448  *
449  * Synchronously reverse-resolves @address to determine its
450  * associated hostname.
451  *
452  * If the DNS resolution fails, @error (if non-%NULL) will be set to
453  * a value from #GResolverError.
454  *
455  * If @cancellable is non-%NULL, it can be used to cancel the
456  * operation, in which case @error (if non-%NULL) will be set to
457  * %G_IO_ERROR_CANCELLED.
458  *
459  * Return value: a hostname (either ASCII-only, or in ASCII-encoded
460  *     form), or %NULL on error.
461  *
462  * Since: 2.22
463  */
464 gchar *
465 g_resolver_lookup_by_address (GResolver     *resolver,
466                               GInetAddress  *address,
467                               GCancellable  *cancellable,
468                               GError       **error)
469 {
470   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
471   g_return_val_if_fail (G_IS_INET_ADDRESS (address), NULL);
472
473   g_resolver_maybe_reload (resolver);
474   return G_RESOLVER_GET_CLASS (resolver)->
475     lookup_by_address (resolver, address, cancellable, error);
476 }
477
478 /**
479  * g_resolver_lookup_by_address_async:
480  * @resolver: a #GResolver
481  * @address: the address to reverse-resolve
482  * @cancellable: (allow-none): a #GCancellable, or %NULL
483  * @callback: (scope async): callback to call after resolution completes
484  * @user_data: (closure): data for @callback
485  *
486  * Begins asynchronously reverse-resolving @address to determine its
487  * associated hostname, and eventually calls @callback, which must
488  * call g_resolver_lookup_by_address_finish() to get the final result.
489  *
490  * Since: 2.22
491  */
492 void
493 g_resolver_lookup_by_address_async (GResolver           *resolver,
494                                     GInetAddress        *address,
495                                     GCancellable        *cancellable,
496                                     GAsyncReadyCallback  callback,
497                                     gpointer             user_data)
498 {
499   g_return_if_fail (G_IS_RESOLVER (resolver));
500   g_return_if_fail (G_IS_INET_ADDRESS (address));
501
502   g_resolver_maybe_reload (resolver);
503   G_RESOLVER_GET_CLASS (resolver)->
504     lookup_by_address_async (resolver, address, cancellable, callback, user_data);
505 }
506
507 /**
508  * g_resolver_lookup_by_address_finish:
509  * @resolver: a #GResolver
510  * @result: the result passed to your #GAsyncReadyCallback
511  * @error: return location for a #GError, or %NULL
512  *
513  * Retrieves the result of a previous call to
514  * g_resolver_lookup_by_address_async().
515  *
516  * If the DNS resolution failed, @error (if non-%NULL) will be set to
517  * a value from #GResolverError. If the operation was cancelled,
518  * @error will be set to %G_IO_ERROR_CANCELLED.
519  *
520  * Return value: a hostname (either ASCII-only, or in ASCII-encoded
521  * form), or %NULL on error.
522  *
523  * Since: 2.22
524  */
525 gchar *
526 g_resolver_lookup_by_address_finish (GResolver     *resolver,
527                                      GAsyncResult  *result,
528                                      GError       **error)
529 {
530   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
531
532   if (G_IS_SIMPLE_ASYNC_RESULT (result))
533     {
534       GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
535
536       if (g_simple_async_result_propagate_error (simple, error))
537         return NULL;
538     }
539
540   return G_RESOLVER_GET_CLASS (resolver)->
541     lookup_by_address_finish (resolver, result, error);
542 }
543
544 static gchar *
545 g_resolver_get_service_rrname (const char *service,
546                                const char *protocol,
547                                const char *domain)
548 {
549   gchar *rrname, *ascii_domain = NULL;
550
551   if (g_hostname_is_non_ascii (domain))
552     domain = ascii_domain = g_hostname_to_ascii (domain);
553
554   rrname = g_strdup_printf ("_%s._%s.%s", service, protocol, domain);
555
556   g_free (ascii_domain);
557   return rrname;
558 }
559
560 /**
561  * g_resolver_lookup_service:
562  * @resolver: a #GResolver
563  * @service: the service type to look up (eg, "ldap")
564  * @protocol: the networking protocol to use for @service (eg, "tcp")
565  * @domain: the DNS domain to look up the service in
566  * @cancellable: (allow-none): a #GCancellable, or %NULL
567  * @error: return location for a #GError, or %NULL
568  *
569  * Synchronously performs a DNS SRV lookup for the given @service and
570  * @protocol in the given @domain and returns an array of #GSrvTarget.
571  * @domain may be an ASCII-only or UTF-8 hostname. Note also that the
572  * @service and @protocol arguments <emphasis>do not</emphasis>
573  * include the leading underscore that appears in the actual DNS
574  * entry.
575  *
576  * On success, g_resolver_lookup_service() will return a #GList of
577  * #GSrvTarget, sorted in order of preference. (That is, you should
578  * attempt to connect to the first target first, then the second if
579  * the first fails, etc.)
580  *
581  * If the DNS resolution fails, @error (if non-%NULL) will be set to
582  * a value from #GResolverError.
583  *
584  * If @cancellable is non-%NULL, it can be used to cancel the
585  * operation, in which case @error (if non-%NULL) will be set to
586  * %G_IO_ERROR_CANCELLED.
587  *
588  * If you are planning to connect to the service, it is usually easier
589  * to create a #GNetworkService and use its #GSocketConnectable
590  * interface.
591  *
592  * Return value: (element-type GSrvTarget) (transfer full): a #GList of #GSrvTarget,
593  * or %NULL on error. You must free each of the targets and the list when you are
594  * done with it. (You can use g_resolver_free_targets() to do this.)
595  *
596  * Since: 2.22
597  */
598 GList *
599 g_resolver_lookup_service (GResolver     *resolver,
600                            const gchar   *service,
601                            const gchar   *protocol,
602                            const gchar   *domain,
603                            GCancellable  *cancellable,
604                            GError       **error)
605 {
606   GList *targets;
607   gchar *rrname;
608
609   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
610   g_return_val_if_fail (service != NULL, NULL);
611   g_return_val_if_fail (protocol != NULL, NULL);
612   g_return_val_if_fail (domain != NULL, NULL);
613
614   rrname = g_resolver_get_service_rrname (service, protocol, domain);
615
616   g_resolver_maybe_reload (resolver);
617   targets = G_RESOLVER_GET_CLASS (resolver)->
618     lookup_service (resolver, rrname, cancellable, error);
619
620   g_free (rrname);
621   return targets;
622 }
623
624 /**
625  * g_resolver_lookup_service_async:
626  * @resolver: a #GResolver
627  * @service: the service type to look up (eg, "ldap")
628  * @protocol: the networking protocol to use for @service (eg, "tcp")
629  * @domain: the DNS domain to look up the service in
630  * @cancellable: (allow-none): a #GCancellable, or %NULL
631  * @callback: (scope async): callback to call after resolution completes
632  * @user_data: (closure): data for @callback
633  *
634  * Begins asynchronously performing a DNS SRV lookup for the given
635  * @service and @protocol in the given @domain, and eventually calls
636  * @callback, which must call g_resolver_lookup_service_finish() to
637  * get the final result. See g_resolver_lookup_service() for more
638  * details.
639  *
640  * Since: 2.22
641  */
642 void
643 g_resolver_lookup_service_async (GResolver           *resolver,
644                                  const gchar         *service,
645                                  const gchar         *protocol,
646                                  const gchar         *domain,
647                                  GCancellable        *cancellable,
648                                  GAsyncReadyCallback  callback,
649                                  gpointer             user_data)
650 {
651   gchar *rrname;
652
653   g_return_if_fail (G_IS_RESOLVER (resolver));
654   g_return_if_fail (service != NULL);
655   g_return_if_fail (protocol != NULL);
656   g_return_if_fail (domain != NULL);
657
658   rrname = g_resolver_get_service_rrname (service, protocol, domain);
659
660   g_resolver_maybe_reload (resolver);
661   G_RESOLVER_GET_CLASS (resolver)->
662     lookup_service_async (resolver, rrname, cancellable, callback, user_data);
663
664   g_free (rrname);
665 }
666
667 /**
668  * g_resolver_lookup_service_finish:
669  * @resolver: a #GResolver
670  * @result: the result passed to your #GAsyncReadyCallback
671  * @error: return location for a #GError, or %NULL
672  *
673  * Retrieves the result of a previous call to
674  * g_resolver_lookup_service_async().
675  *
676  * If the DNS resolution failed, @error (if non-%NULL) will be set to
677  * a value from #GResolverError. If the operation was cancelled,
678  * @error will be set to %G_IO_ERROR_CANCELLED.
679  *
680  * Return value: (element-type GSrvTarget) (transfer full): a #GList of #GSrvTarget,
681  * or %NULL on error. See g_resolver_lookup_service() for more details.
682  *
683  * Since: 2.22
684  */
685 GList *
686 g_resolver_lookup_service_finish (GResolver     *resolver,
687                                   GAsyncResult  *result,
688                                   GError       **error)
689 {
690   g_return_val_if_fail (G_IS_RESOLVER (resolver), NULL);
691
692   if (G_IS_SIMPLE_ASYNC_RESULT (result))
693     {
694       GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (result);
695
696       if (g_simple_async_result_propagate_error (simple, error))
697         return NULL;
698     }
699
700   return G_RESOLVER_GET_CLASS (resolver)->
701     lookup_service_finish (resolver, result, error);
702 }
703
704 /**
705  * g_resolver_free_targets: (skip)
706  * @targets: a #GList of #GSrvTarget
707  *
708  * Frees @targets (which should be the return value from
709  * g_resolver_lookup_service() or g_resolver_lookup_service_finish()).
710  * (This is a convenience method; you can also simply free the
711  * results by hand.)
712  *
713  * Since: 2.22
714  */
715 void
716 g_resolver_free_targets (GList *targets)
717 {
718   GList *t;
719
720   for (t = targets; t; t = t->next)
721     g_srv_target_free (t->data);
722   g_list_free (targets);
723 }
724
725 /**
726  * g_resolver_error_quark:
727  *
728  * Gets the #GResolver Error Quark.
729  *
730  * Return value: a #GQuark.
731  *
732  * Since: 2.22
733  */
734 GQuark
735 g_resolver_error_quark (void)
736 {
737   return g_quark_from_static_string ("g-resolver-error-quark");
738 }
739
740
741 static GResolverError
742 g_resolver_error_from_addrinfo_error (gint err)
743 {
744   switch (err)
745     {
746     case EAI_FAIL:
747 #if defined(EAI_NODATA) && (EAI_NODATA != EAI_NONAME)
748     case EAI_NODATA:
749 #endif
750     case EAI_NONAME:
751       return G_RESOLVER_ERROR_NOT_FOUND;
752
753     case EAI_AGAIN:
754       return G_RESOLVER_ERROR_TEMPORARY_FAILURE;
755
756     default:
757       return G_RESOLVER_ERROR_INTERNAL;
758     }
759 }
760
761 struct addrinfo _g_resolver_addrinfo_hints;
762
763 /* Private method to process a getaddrinfo() response. */
764 GList *
765 _g_resolver_addresses_from_addrinfo (const char       *hostname,
766                                      struct addrinfo  *res,
767                                      gint              gai_retval,
768                                      GError          **error)
769 {
770   struct addrinfo *ai;
771   GSocketAddress *sockaddr;
772   GInetAddress *addr;
773   GList *addrs;
774
775   if (gai_retval != 0)
776     {
777       g_set_error (error, G_RESOLVER_ERROR,
778                    g_resolver_error_from_addrinfo_error (gai_retval),
779                    _("Error resolving '%s': %s"),
780                    hostname, gai_strerror (gai_retval));
781       return NULL;
782     }
783
784   g_return_val_if_fail (res != NULL, NULL);
785
786   addrs = NULL;
787   for (ai = res; ai; ai = ai->ai_next)
788     {
789       sockaddr = g_socket_address_new_from_native (ai->ai_addr, ai->ai_addrlen);
790       if (!sockaddr || !G_IS_INET_SOCKET_ADDRESS (sockaddr))
791         continue;
792
793       addr = g_object_ref (g_inet_socket_address_get_address ((GInetSocketAddress *)sockaddr));
794       addrs = g_list_prepend (addrs, addr);
795       g_object_unref (sockaddr);
796     }
797
798   return g_list_reverse (addrs);
799 }
800
801 /* Private method to set up a getnameinfo() request */
802 void
803 _g_resolver_address_to_sockaddr (GInetAddress            *address,
804                                  struct sockaddr_storage *sa,
805                                  gsize                   *len)
806 {
807   GSocketAddress *sockaddr;
808
809   sockaddr = g_inet_socket_address_new (address, 0);
810   g_socket_address_to_native (sockaddr, (struct sockaddr *)sa, sizeof (*sa), NULL);
811   *len = g_socket_address_get_native_size (sockaddr);
812   g_object_unref (sockaddr);
813 }
814
815 /* Private method to process a getnameinfo() response. */
816 char *
817 _g_resolver_name_from_nameinfo (GInetAddress  *address,
818                                 const gchar   *name,
819                                 gint           gni_retval,
820                                 GError       **error)
821 {
822   if (gni_retval != 0)
823     {
824       gchar *phys;
825
826       phys = g_inet_address_to_string (address);
827       g_set_error (error, G_RESOLVER_ERROR,
828                    g_resolver_error_from_addrinfo_error (gni_retval),
829                    _("Error reverse-resolving '%s': %s"),
830                    phys ? phys : "(unknown)", gai_strerror (gni_retval));
831       g_free (phys);
832       return NULL;
833     }
834
835   return g_strdup (name);
836 }
837
838 #if defined(G_OS_UNIX)
839 /* Private method to process a res_query response into GSrvTargets */
840 GList *
841 _g_resolver_targets_from_res_query (const gchar      *rrname,
842                                     guchar           *answer,
843                                     gint              len,
844                                     gint              herr,
845                                     GError          **error)
846 {
847   gint count;
848   gchar namebuf[1024];
849   guchar *end, *p;
850   guint16 type, qclass, rdlength, priority, weight, port;
851   guint32 ttl;
852   HEADER *header;
853   GSrvTarget *target;
854   GList *targets;
855
856   if (len <= 0)
857     {
858       GResolverError errnum;
859       const gchar *format;
860
861       if (len == 0 || herr == HOST_NOT_FOUND || herr == NO_DATA)
862         {
863           errnum = G_RESOLVER_ERROR_NOT_FOUND;
864           format = _("No service record for '%s'");
865         }
866       else if (herr == TRY_AGAIN)
867         {
868           errnum = G_RESOLVER_ERROR_TEMPORARY_FAILURE;
869           format = _("Temporarily unable to resolve '%s'");
870         }
871       else
872         {
873           errnum = G_RESOLVER_ERROR_INTERNAL;
874           format = _("Error resolving '%s'");
875         }
876
877       g_set_error (error, G_RESOLVER_ERROR, errnum, format, rrname);
878       return NULL;
879     }
880
881   targets = NULL;
882
883   header = (HEADER *)answer;
884   p = answer + sizeof (HEADER);
885   end = answer + len;
886
887   /* Skip query */
888   count = ntohs (header->qdcount);
889   while (count-- && p < end)
890     {
891       p += dn_expand (answer, end, p, namebuf, sizeof (namebuf));
892       p += 4;
893     }
894
895   /* Read answers */
896   count = ntohs (header->ancount);
897   while (count-- && p < end)
898     {
899       p += dn_expand (answer, end, p, namebuf, sizeof (namebuf));
900       GETSHORT (type, p);
901       GETSHORT (qclass, p);
902       GETLONG  (ttl, p);
903       ttl = ttl; /* To avoid -Wunused-but-set-variable */
904       GETSHORT (rdlength, p);
905
906       if (type != T_SRV || qclass != C_IN)
907         {
908           p += rdlength;
909           continue;
910         }
911
912       GETSHORT (priority, p);
913       GETSHORT (weight, p);
914       GETSHORT (port, p);
915       p += dn_expand (answer, end, p, namebuf, sizeof (namebuf));
916
917       target = g_srv_target_new (namebuf, port, priority, weight);
918       targets = g_list_prepend (targets, target);
919     }
920
921   return g_srv_target_list_sort (targets);
922 }
923 #elif defined(G_OS_WIN32)
924 /* Private method to process a DnsQuery response into GSrvTargets */
925 GList *
926 _g_resolver_targets_from_DnsQuery (const gchar  *rrname,
927                                    DNS_STATUS    status,
928                                    DNS_RECORD   *results,
929                                    GError      **error)
930 {
931   DNS_RECORD *rec;
932   GSrvTarget *target;
933   GList *targets;
934
935   if (status != ERROR_SUCCESS)
936     {
937       GResolverError errnum;
938       const gchar *format;
939
940       if (status == DNS_ERROR_RCODE_NAME_ERROR)
941         {
942           errnum = G_RESOLVER_ERROR_NOT_FOUND;
943           format = _("No service record for '%s'");
944         }
945       else if (status == DNS_ERROR_RCODE_SERVER_FAILURE)
946         {
947           errnum = G_RESOLVER_ERROR_TEMPORARY_FAILURE;
948           format = _("Temporarily unable to resolve '%s'");
949         }
950       else
951         {
952           errnum = G_RESOLVER_ERROR_INTERNAL;
953           format = _("Error resolving '%s'");
954         }
955
956       g_set_error (error, G_RESOLVER_ERROR, errnum, format, rrname);
957       return NULL;
958     }
959
960   targets = NULL;
961   for (rec = results; rec; rec = rec->pNext)
962     {
963       if (rec->wType != DNS_TYPE_SRV)
964         continue;
965
966       target = g_srv_target_new (rec->Data.SRV.pNameTarget,
967                                  rec->Data.SRV.wPort,
968                                  rec->Data.SRV.wPriority,
969                                  rec->Data.SRV.wWeight);
970       targets = g_list_prepend (targets, target);
971     }
972
973   return g_srv_target_list_sort (targets);
974 }
975
976 #endif