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