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