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